The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2894 lines
90KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. #define CHECK_MESSAGE_MANAGER_IS_LOCKED \
  19. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  20. #define CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN \
  21. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager() || getPeer() == nullptr);
  22. Component* Component::currentlyFocusedComponent = nullptr;
  23. //==============================================================================
  24. class Component::MouseListenerList
  25. {
  26. public:
  27. MouseListenerList() noexcept
  28. : numDeepMouseListeners (0)
  29. {
  30. }
  31. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  32. {
  33. if (! listeners.contains (newListener))
  34. {
  35. if (wantsEventsForAllNestedChildComponents)
  36. {
  37. listeners.insert (0, newListener);
  38. ++numDeepMouseListeners;
  39. }
  40. else
  41. {
  42. listeners.add (newListener);
  43. }
  44. }
  45. }
  46. void removeListener (MouseListener* const listenerToRemove)
  47. {
  48. const int index = listeners.indexOf (listenerToRemove);
  49. if (index >= 0)
  50. {
  51. if (index < numDeepMouseListeners)
  52. --numDeepMouseListeners;
  53. listeners.remove (index);
  54. }
  55. }
  56. static void sendMouseEvent (Component& comp, Component::BailOutChecker& checker,
  57. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  58. {
  59. if (checker.shouldBailOut())
  60. return;
  61. if (MouseListenerList* const list = comp.mouseListeners)
  62. {
  63. for (int i = list->listeners.size(); --i >= 0;)
  64. {
  65. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  66. if (checker.shouldBailOut())
  67. return;
  68. i = jmin (i, list->listeners.size());
  69. }
  70. }
  71. for (Component* p = comp.parentComponent; p != nullptr; p = p->parentComponent)
  72. {
  73. MouseListenerList* const list = p->mouseListeners;
  74. if (list != nullptr && list->numDeepMouseListeners > 0)
  75. {
  76. BailOutChecker2 checker2 (checker, p);
  77. for (int i = list->numDeepMouseListeners; --i >= 0;)
  78. {
  79. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  80. if (checker2.shouldBailOut())
  81. return;
  82. i = jmin (i, list->numDeepMouseListeners);
  83. }
  84. }
  85. }
  86. }
  87. static void sendWheelEvent (Component& comp, Component::BailOutChecker& checker,
  88. const MouseEvent& e, const MouseWheelDetails& wheel)
  89. {
  90. if (MouseListenerList* const list = comp.mouseListeners)
  91. {
  92. for (int i = list->listeners.size(); --i >= 0;)
  93. {
  94. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheel);
  95. if (checker.shouldBailOut())
  96. return;
  97. i = jmin (i, list->listeners.size());
  98. }
  99. }
  100. for (Component* p = comp.parentComponent; p != nullptr; p = p->parentComponent)
  101. {
  102. MouseListenerList* const list = p->mouseListeners;
  103. if (list != nullptr && list->numDeepMouseListeners > 0)
  104. {
  105. BailOutChecker2 checker2 (checker, p);
  106. for (int i = list->numDeepMouseListeners; --i >= 0;)
  107. {
  108. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheel);
  109. if (checker2.shouldBailOut())
  110. return;
  111. i = jmin (i, list->numDeepMouseListeners);
  112. }
  113. }
  114. }
  115. }
  116. private:
  117. Array <MouseListener*> listeners;
  118. int numDeepMouseListeners;
  119. class BailOutChecker2
  120. {
  121. public:
  122. BailOutChecker2 (Component::BailOutChecker& boc, Component* const comp)
  123. : checker (boc), safePointer (comp)
  124. {
  125. }
  126. bool shouldBailOut() const noexcept
  127. {
  128. return checker.shouldBailOut() || safePointer == 0;
  129. }
  130. private:
  131. Component::BailOutChecker& checker;
  132. const WeakReference<Component> safePointer;
  133. JUCE_DECLARE_NON_COPYABLE (BailOutChecker2)
  134. };
  135. JUCE_DECLARE_NON_COPYABLE (MouseListenerList)
  136. };
  137. //==============================================================================
  138. struct Component::ComponentHelpers
  139. {
  140. #if JUCE_MODAL_LOOPS_PERMITTED
  141. static void* runModalLoopCallback (void* userData)
  142. {
  143. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  144. }
  145. #endif
  146. static Identifier getColourPropertyId (const int colourId)
  147. {
  148. String s;
  149. s.preallocateBytes (32);
  150. s << "jcclr_" << String::toHexString (colourId);
  151. return s;
  152. }
  153. //==============================================================================
  154. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  155. {
  156. return isPositiveAndBelow (localPoint.x, comp.getWidth())
  157. && isPositiveAndBelow (localPoint.y, comp.getHeight())
  158. && comp.hitTest (localPoint.x, localPoint.y);
  159. }
  160. static Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  161. {
  162. if (comp.affineTransform == nullptr)
  163. return pointInParentSpace - comp.getPosition();
  164. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform->inverted()).toInt() - comp.getPosition();
  165. }
  166. static Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  167. {
  168. if (comp.affineTransform == nullptr)
  169. return areaInParentSpace - comp.getPosition();
  170. return areaInParentSpace.toFloat().transformed (comp.affineTransform->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  171. }
  172. static Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  173. {
  174. if (comp.affineTransform == nullptr)
  175. return pointInLocalSpace + comp.getPosition();
  176. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform).toInt();
  177. }
  178. static Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  179. {
  180. if (comp.affineTransform == nullptr)
  181. return areaInLocalSpace + comp.getPosition();
  182. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform).getSmallestIntegerContainer();
  183. }
  184. template <typename Type>
  185. static Type convertFromDistantParentSpace (const Component* parent, const Component& target, const Type& coordInParent)
  186. {
  187. const Component* const directParent = target.getParentComponent();
  188. jassert (directParent != nullptr);
  189. if (directParent == parent)
  190. return convertFromParentSpace (target, coordInParent);
  191. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  192. }
  193. template <typename Type>
  194. static Type convertCoordinate (const Component* target, const Component* source, Type p)
  195. {
  196. while (source != nullptr)
  197. {
  198. if (source == target)
  199. return p;
  200. if (source->isParentOf (target))
  201. return convertFromDistantParentSpace (source, *target, p);
  202. if (source->isOnDesktop())
  203. {
  204. p = source->getPeer()->localToGlobal (p);
  205. source = nullptr;
  206. }
  207. else
  208. {
  209. p = convertToParentSpace (*source, p);
  210. source = source->getParentComponent();
  211. }
  212. }
  213. jassert (source == nullptr);
  214. if (target == nullptr)
  215. return p;
  216. const Component* const topLevelComp = target->getTopLevelComponent();
  217. if (topLevelComp->isOnDesktop())
  218. p = topLevelComp->getPeer()->globalToLocal (p);
  219. else
  220. p = convertFromParentSpace (*topLevelComp, p);
  221. if (topLevelComp == target)
  222. return p;
  223. return convertFromDistantParentSpace (topLevelComp, *target, p);
  224. }
  225. static Rectangle<int> getUnclippedArea (const Component& comp)
  226. {
  227. Rectangle<int> r (comp.getLocalBounds());
  228. if (Component* const p = comp.getParentComponent())
  229. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  230. return r;
  231. }
  232. static bool clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  233. {
  234. bool nothingChanged = true;
  235. for (int i = comp.childComponentList.size(); --i >= 0;)
  236. {
  237. const Component& child = *comp.childComponentList.getUnchecked(i);
  238. if (child.isVisible() && ! child.isTransformed())
  239. {
  240. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds));
  241. if (! newClip.isEmpty())
  242. {
  243. if (child.isOpaque() && child.componentTransparency == 0)
  244. {
  245. g.excludeClipRegion (newClip + delta);
  246. nothingChanged = false;
  247. }
  248. else
  249. {
  250. const Point<int> childPos (child.getPosition());
  251. if (clipObscuredRegions (child, g, newClip - childPos, childPos + delta))
  252. nothingChanged = false;
  253. }
  254. }
  255. }
  256. }
  257. return nothingChanged;
  258. }
  259. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  260. const Point<int>& delta, const Rectangle<int>& clipRect,
  261. const Component* const compToAvoid)
  262. {
  263. for (int i = comp.childComponentList.size(); --i >= 0;)
  264. {
  265. const Component* const c = comp.childComponentList.getUnchecked(i);
  266. if (c != compToAvoid && c->isVisible())
  267. {
  268. if (c->isOpaque() && c->componentTransparency == 0)
  269. {
  270. Rectangle<int> childBounds (c->bounds.getIntersection (clipRect));
  271. childBounds.translate (delta.x, delta.y);
  272. result.subtract (childBounds);
  273. }
  274. else
  275. {
  276. Rectangle<int> newClip (clipRect.getIntersection (c->bounds));
  277. newClip.translate (-c->getX(), -c->getY());
  278. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  279. newClip, compToAvoid);
  280. }
  281. }
  282. }
  283. }
  284. static Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  285. {
  286. return comp.getParentComponent() != nullptr ? comp.getParentComponent()->getLocalBounds()
  287. : Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  288. }
  289. };
  290. //==============================================================================
  291. Component::Component()
  292. : parentComponent (nullptr),
  293. lookAndFeel (nullptr),
  294. effect (nullptr),
  295. componentFlags (0),
  296. componentTransparency (0)
  297. {
  298. }
  299. Component::Component (const String& name)
  300. : componentName (name),
  301. parentComponent (nullptr),
  302. lookAndFeel (nullptr),
  303. effect (nullptr),
  304. componentFlags (0),
  305. componentTransparency (0)
  306. {
  307. }
  308. Component::~Component()
  309. {
  310. static_jassert (sizeof (flags) <= sizeof (componentFlags));
  311. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  312. masterReference.clear();
  313. while (childComponentList.size() > 0)
  314. removeChildComponent (childComponentList.size() - 1, false, true);
  315. if (parentComponent != nullptr)
  316. parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false);
  317. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  318. giveAwayFocus (currentlyFocusedComponent != this);
  319. if (flags.hasHeavyweightPeerFlag)
  320. removeFromDesktop();
  321. // Something has added some children to this component during its destructor! Not a smart idea!
  322. jassert (childComponentList.size() == 0);
  323. }
  324. //==============================================================================
  325. void Component::setName (const String& name)
  326. {
  327. // if component methods are being called from threads other than the message
  328. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  329. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  330. if (componentName != name)
  331. {
  332. componentName = name;
  333. if (flags.hasHeavyweightPeerFlag)
  334. if (ComponentPeer* const peer = getPeer())
  335. peer->setTitle (name);
  336. BailOutChecker checker (this);
  337. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  338. }
  339. }
  340. void Component::setComponentID (const String& newID)
  341. {
  342. componentID = newID;
  343. }
  344. void Component::setVisible (bool shouldBeVisible)
  345. {
  346. if (flags.visibleFlag != shouldBeVisible)
  347. {
  348. // if component methods are being called from threads other than the message
  349. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  350. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  351. const WeakReference<Component> safePointer (this);
  352. flags.visibleFlag = shouldBeVisible;
  353. if (shouldBeVisible)
  354. repaint();
  355. else
  356. repaintParent();
  357. sendFakeMouseMove();
  358. if (! shouldBeVisible)
  359. {
  360. if (cachedImage != nullptr)
  361. cachedImage->releaseResources();
  362. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  363. {
  364. if (parentComponent != nullptr)
  365. parentComponent->grabKeyboardFocus();
  366. else
  367. giveAwayFocus (true);
  368. }
  369. }
  370. if (safePointer != nullptr)
  371. {
  372. sendVisibilityChangeMessage();
  373. if (safePointer != nullptr && flags.hasHeavyweightPeerFlag)
  374. {
  375. if (ComponentPeer* const peer = getPeer())
  376. {
  377. peer->setVisible (shouldBeVisible);
  378. internalHierarchyChanged();
  379. }
  380. }
  381. }
  382. }
  383. }
  384. void Component::visibilityChanged() {}
  385. void Component::sendVisibilityChangeMessage()
  386. {
  387. BailOutChecker checker (this);
  388. visibilityChanged();
  389. if (! checker.shouldBailOut())
  390. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  391. }
  392. bool Component::isShowing() const
  393. {
  394. if (! flags.visibleFlag)
  395. return false;
  396. if (parentComponent != nullptr)
  397. return parentComponent->isShowing();
  398. const ComponentPeer* const peer = getPeer();
  399. return peer != nullptr && ! peer->isMinimised();
  400. }
  401. //==============================================================================
  402. void* Component::getWindowHandle() const
  403. {
  404. if (const ComponentPeer* const peer = getPeer())
  405. return peer->getNativeHandle();
  406. return nullptr;
  407. }
  408. //==============================================================================
  409. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  410. {
  411. // if component methods are being called from threads other than the message
  412. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  413. CHECK_MESSAGE_MANAGER_IS_LOCKED
  414. if (isOpaque())
  415. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  416. else
  417. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  418. // don't use getPeer(), so that we only get the peer that's specifically
  419. // for this comp, and not for one of its parents.
  420. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  421. if (peer == nullptr || styleWanted != peer->getStyleFlags())
  422. {
  423. const WeakReference<Component> safePointer (this);
  424. #if JUCE_LINUX
  425. // it's wise to give the component a non-zero size before
  426. // putting it on the desktop, as X windows get confused by this, and
  427. // a (1, 1) minimum size is enforced here.
  428. setSize (jmax (1, getWidth()),
  429. jmax (1, getHeight()));
  430. #endif
  431. const Point<int> topLeft (getScreenPosition());
  432. bool wasFullscreen = false;
  433. bool wasMinimised = false;
  434. ComponentBoundsConstrainer* currentConstainer = nullptr;
  435. Rectangle<int> oldNonFullScreenBounds;
  436. int oldRenderingEngine = -1;
  437. if (peer != nullptr)
  438. {
  439. ScopedPointer<ComponentPeer> oldPeerToDelete (peer);
  440. wasFullscreen = peer->isFullScreen();
  441. wasMinimised = peer->isMinimised();
  442. currentConstainer = peer->getConstrainer();
  443. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  444. oldRenderingEngine = peer->getCurrentRenderingEngine();
  445. flags.hasHeavyweightPeerFlag = false;
  446. Desktop::getInstance().removeDesktopComponent (this);
  447. internalHierarchyChanged(); // give comps a chance to react to the peer change before the old peer is deleted.
  448. if (safePointer == nullptr)
  449. return;
  450. setTopLeftPosition (topLeft);
  451. }
  452. if (parentComponent != nullptr)
  453. parentComponent->removeChildComponent (this);
  454. if (safePointer != nullptr)
  455. {
  456. flags.hasHeavyweightPeerFlag = true;
  457. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  458. Desktop::getInstance().addDesktopComponent (this);
  459. bounds.setPosition (topLeft);
  460. peer->setBounds (topLeft.x, topLeft.y, getWidth(), getHeight(), false);
  461. if (oldRenderingEngine >= 0)
  462. peer->setCurrentRenderingEngine (oldRenderingEngine);
  463. peer->setVisible (isVisible());
  464. peer = ComponentPeer::getPeerFor (this);
  465. if (peer == nullptr)
  466. return;
  467. if (wasFullscreen)
  468. {
  469. peer->setFullScreen (true);
  470. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  471. }
  472. if (wasMinimised)
  473. peer->setMinimised (true);
  474. #if JUCE_WINDOWS
  475. if (isAlwaysOnTop())
  476. peer->setAlwaysOnTop (true);
  477. #endif
  478. peer->setConstrainer (currentConstainer);
  479. repaint();
  480. internalHierarchyChanged();
  481. }
  482. }
  483. }
  484. void Component::removeFromDesktop()
  485. {
  486. // if component methods are being called from threads other than the message
  487. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  488. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  489. if (flags.hasHeavyweightPeerFlag)
  490. {
  491. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  492. jassert (peer != nullptr);
  493. flags.hasHeavyweightPeerFlag = false;
  494. delete peer;
  495. Desktop::getInstance().removeDesktopComponent (this);
  496. }
  497. }
  498. bool Component::isOnDesktop() const noexcept
  499. {
  500. return flags.hasHeavyweightPeerFlag;
  501. }
  502. ComponentPeer* Component::getPeer() const
  503. {
  504. if (flags.hasHeavyweightPeerFlag)
  505. return ComponentPeer::getPeerFor (this);
  506. else if (parentComponent == nullptr)
  507. return nullptr;
  508. return parentComponent->getPeer();
  509. }
  510. void Component::userTriedToCloseWindow()
  511. {
  512. /* This means that the user's trying to get rid of your window with the 'close window' system
  513. menu option (on windows) or possibly the task manager - you should really handle this
  514. and delete or hide your component in an appropriate way.
  515. If you want to ignore the event and don't want to trigger this assertion, just override
  516. this method and do nothing.
  517. */
  518. jassertfalse;
  519. }
  520. void Component::minimisationStateChanged (bool) {}
  521. //==============================================================================
  522. void Component::setOpaque (const bool shouldBeOpaque)
  523. {
  524. if (shouldBeOpaque != flags.opaqueFlag)
  525. {
  526. flags.opaqueFlag = shouldBeOpaque;
  527. if (flags.hasHeavyweightPeerFlag)
  528. if (const ComponentPeer* const peer = ComponentPeer::getPeerFor (this))
  529. addToDesktop (peer->getStyleFlags()); // recreates the heavyweight window
  530. repaint();
  531. }
  532. }
  533. bool Component::isOpaque() const noexcept
  534. {
  535. return flags.opaqueFlag;
  536. }
  537. //==============================================================================
  538. class StandardCachedComponentImage : public CachedComponentImage
  539. {
  540. public:
  541. StandardCachedComponentImage (Component& c) noexcept : owner (c) {}
  542. void paint (Graphics& g)
  543. {
  544. const Rectangle<int> bounds (owner.getLocalBounds());
  545. if (image.isNull() || image.getBounds() != bounds)
  546. {
  547. image = Image (owner.isOpaque() ? Image::RGB : Image::ARGB,
  548. jmax (1, bounds.getWidth()), jmax (1, bounds.getHeight()), ! owner.isOpaque());
  549. validArea.clear();
  550. }
  551. {
  552. Graphics imG (image);
  553. LowLevelGraphicsContext& lg = imG.getInternalContext();
  554. for (const Rectangle<int>* i = validArea.begin(), * const e = validArea.end(); i != e; ++i)
  555. lg.excludeClipRectangle (*i);
  556. if (! lg.isClipEmpty())
  557. {
  558. if (! owner.isOpaque())
  559. {
  560. lg.setFill (Colours::transparentBlack);
  561. lg.fillRect (bounds, true);
  562. lg.setFill (Colours::black);
  563. }
  564. owner.paintEntireComponent (imG, true);
  565. }
  566. }
  567. validArea = bounds;
  568. g.setColour (Colours::black.withAlpha (owner.getAlpha()));
  569. g.drawImageAt (image, 0, 0);
  570. }
  571. void invalidateAll() { validArea.clear(); }
  572. void invalidate (const Rectangle<int>& area) { validArea.subtract (area); }
  573. void releaseResources() { image = Image::null; }
  574. private:
  575. Image image;
  576. RectangleList validArea;
  577. Component& owner;
  578. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StandardCachedComponentImage)
  579. };
  580. void Component::setCachedComponentImage (CachedComponentImage* newCachedImage)
  581. {
  582. if (cachedImage != newCachedImage)
  583. {
  584. cachedImage = newCachedImage;
  585. repaint();
  586. }
  587. }
  588. void Component::setBufferedToImage (const bool shouldBeBuffered)
  589. {
  590. // This assertion means that this component is already using a custom CachedComponentImage,
  591. // so by calling setBufferedToImage, you'll be deleting the custom one - this is almost certainly
  592. // not what you wanted to happen... If you really do know what you're doing here, and want to
  593. // avoid this assertion, just call setCachedComponentImage (nullptr) before setBufferedToImage().
  594. jassert (cachedImage == nullptr || dynamic_cast <StandardCachedComponentImage*> (cachedImage.get()) != nullptr);
  595. if (shouldBeBuffered)
  596. {
  597. if (cachedImage == nullptr)
  598. cachedImage = new StandardCachedComponentImage (*this);
  599. }
  600. else
  601. {
  602. cachedImage = nullptr;
  603. }
  604. }
  605. //==============================================================================
  606. void Component::reorderChildInternal (const int sourceIndex, const int destIndex)
  607. {
  608. if (sourceIndex != destIndex)
  609. {
  610. Component* const c = childComponentList.getUnchecked (sourceIndex);
  611. jassert (c != nullptr);
  612. c->repaintParent();
  613. childComponentList.move (sourceIndex, destIndex);
  614. sendFakeMouseMove();
  615. internalChildrenChanged();
  616. }
  617. }
  618. void Component::toFront (const bool setAsForeground)
  619. {
  620. // if component methods are being called from threads other than the message
  621. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  622. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  623. if (flags.hasHeavyweightPeerFlag)
  624. {
  625. if (ComponentPeer* const peer = getPeer())
  626. {
  627. peer->toFront (setAsForeground);
  628. if (setAsForeground && ! hasKeyboardFocus (true))
  629. grabKeyboardFocus();
  630. }
  631. }
  632. else if (parentComponent != nullptr)
  633. {
  634. const Array<Component*>& childList = parentComponent->childComponentList;
  635. if (childList.getLast() != this)
  636. {
  637. const int index = childList.indexOf (this);
  638. if (index >= 0)
  639. {
  640. int insertIndex = -1;
  641. if (! flags.alwaysOnTopFlag)
  642. {
  643. insertIndex = childList.size() - 1;
  644. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  645. --insertIndex;
  646. }
  647. parentComponent->reorderChildInternal (index, insertIndex);
  648. }
  649. }
  650. if (setAsForeground)
  651. {
  652. internalBroughtToFront();
  653. grabKeyboardFocus();
  654. }
  655. }
  656. }
  657. void Component::toBehind (Component* const other)
  658. {
  659. if (other != nullptr && other != this)
  660. {
  661. // the two components must belong to the same parent..
  662. jassert (parentComponent == other->parentComponent);
  663. if (parentComponent != nullptr)
  664. {
  665. const Array<Component*>& childList = parentComponent->childComponentList;
  666. const int index = childList.indexOf (this);
  667. if (index >= 0 && childList [index + 1] != other)
  668. {
  669. int otherIndex = childList.indexOf (other);
  670. if (otherIndex >= 0)
  671. {
  672. if (index < otherIndex)
  673. --otherIndex;
  674. parentComponent->reorderChildInternal (index, otherIndex);
  675. }
  676. }
  677. }
  678. else if (isOnDesktop())
  679. {
  680. jassert (other->isOnDesktop());
  681. if (other->isOnDesktop())
  682. {
  683. ComponentPeer* const us = getPeer();
  684. ComponentPeer* const them = other->getPeer();
  685. jassert (us != nullptr && them != nullptr);
  686. if (us != nullptr && them != nullptr)
  687. us->toBehind (them);
  688. }
  689. }
  690. }
  691. }
  692. void Component::toBack()
  693. {
  694. if (isOnDesktop())
  695. {
  696. jassertfalse; //xxx need to add this to native window
  697. }
  698. else if (parentComponent != nullptr)
  699. {
  700. const Array<Component*>& childList = parentComponent->childComponentList;
  701. if (childList.getFirst() != this)
  702. {
  703. const int index = childList.indexOf (this);
  704. if (index > 0)
  705. {
  706. int insertIndex = 0;
  707. if (flags.alwaysOnTopFlag)
  708. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  709. ++insertIndex;
  710. parentComponent->reorderChildInternal (index, insertIndex);
  711. }
  712. }
  713. }
  714. }
  715. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  716. {
  717. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  718. {
  719. BailOutChecker checker (this);
  720. flags.alwaysOnTopFlag = shouldStayOnTop;
  721. if (isOnDesktop())
  722. {
  723. if (ComponentPeer* const peer = getPeer())
  724. {
  725. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  726. {
  727. // some kinds of peer can't change their always-on-top status, so
  728. // for these, we'll need to create a new window
  729. const int oldFlags = peer->getStyleFlags();
  730. removeFromDesktop();
  731. addToDesktop (oldFlags);
  732. }
  733. }
  734. }
  735. if (shouldStayOnTop && ! checker.shouldBailOut())
  736. toFront (false);
  737. if (! checker.shouldBailOut())
  738. internalHierarchyChanged();
  739. }
  740. }
  741. bool Component::isAlwaysOnTop() const noexcept
  742. {
  743. return flags.alwaysOnTopFlag;
  744. }
  745. //==============================================================================
  746. int Component::proportionOfWidth (const float proportion) const noexcept { return roundToInt (proportion * bounds.getWidth()); }
  747. int Component::proportionOfHeight (const float proportion) const noexcept { return roundToInt (proportion * bounds.getHeight()); }
  748. int Component::getParentWidth() const noexcept
  749. {
  750. return parentComponent != nullptr ? parentComponent->getWidth()
  751. : getParentMonitorArea().getWidth();
  752. }
  753. int Component::getParentHeight() const noexcept
  754. {
  755. return parentComponent != nullptr ? parentComponent->getHeight()
  756. : getParentMonitorArea().getHeight();
  757. }
  758. int Component::getScreenX() const { return getScreenPosition().x; }
  759. int Component::getScreenY() const { return getScreenPosition().y; }
  760. Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  761. Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  762. Rectangle<int> Component::getParentMonitorArea() const
  763. {
  764. return Desktop::getInstance().getDisplays().getDisplayContaining (getScreenBounds().getCentre()).userArea;
  765. }
  766. Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  767. {
  768. return ComponentHelpers::convertCoordinate (this, source, point);
  769. }
  770. Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  771. {
  772. return ComponentHelpers::convertCoordinate (this, source, area);
  773. }
  774. Point<int> Component::localPointToGlobal (const Point<int>& point) const
  775. {
  776. return ComponentHelpers::convertCoordinate (nullptr, this, point);
  777. }
  778. Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  779. {
  780. return ComponentHelpers::convertCoordinate (nullptr, this, area);
  781. }
  782. // Deprecated methods...
  783. Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  784. {
  785. return localPointToGlobal (relativePosition);
  786. }
  787. Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  788. {
  789. return getLocalPoint (nullptr, screenPosition);
  790. }
  791. Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  792. {
  793. return targetComponent == nullptr ? localPointToGlobal (positionRelativeToThis)
  794. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  795. }
  796. //==============================================================================
  797. void Component::setBounds (const int x, const int y, int w, int h)
  798. {
  799. // if component methods are being called from threads other than the message
  800. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  801. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  802. if (w < 0) w = 0;
  803. if (h < 0) h = 0;
  804. const bool wasResized = (getWidth() != w || getHeight() != h);
  805. const bool wasMoved = (getX() != x || getY() != y);
  806. #if JUCE_DEBUG
  807. // It's a very bad idea to try to resize a window during its paint() method!
  808. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  809. #endif
  810. if (wasMoved || wasResized)
  811. {
  812. const bool showing = isShowing();
  813. if (showing)
  814. {
  815. // send a fake mouse move to trigger enter/exit messages if needed..
  816. sendFakeMouseMove();
  817. if (! flags.hasHeavyweightPeerFlag)
  818. repaintParent();
  819. }
  820. bounds.setBounds (x, y, w, h);
  821. if (showing)
  822. {
  823. if (wasResized)
  824. repaint();
  825. else if (! flags.hasHeavyweightPeerFlag)
  826. repaintParent();
  827. }
  828. else if (cachedImage != nullptr)
  829. {
  830. cachedImage->invalidateAll();
  831. }
  832. if (flags.hasHeavyweightPeerFlag)
  833. {
  834. if (ComponentPeer* const peer = getPeer())
  835. {
  836. if (wasMoved && wasResized)
  837. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  838. else if (wasMoved)
  839. peer->setPosition (getX(), getY());
  840. else if (wasResized)
  841. peer->setSize (getWidth(), getHeight());
  842. }
  843. }
  844. sendMovedResizedMessages (wasMoved, wasResized);
  845. }
  846. }
  847. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  848. {
  849. BailOutChecker checker (this);
  850. if (wasMoved)
  851. {
  852. moved();
  853. if (checker.shouldBailOut())
  854. return;
  855. }
  856. if (wasResized)
  857. {
  858. resized();
  859. if (checker.shouldBailOut())
  860. return;
  861. for (int i = childComponentList.size(); --i >= 0;)
  862. {
  863. childComponentList.getUnchecked(i)->parentSizeChanged();
  864. if (checker.shouldBailOut())
  865. return;
  866. i = jmin (i, childComponentList.size());
  867. }
  868. }
  869. if (parentComponent != nullptr)
  870. parentComponent->childBoundsChanged (this);
  871. if (! checker.shouldBailOut())
  872. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  873. *this, wasMoved, wasResized);
  874. }
  875. void Component::setSize (const int w, const int h)
  876. {
  877. setBounds (getX(), getY(), w, h);
  878. }
  879. void Component::setTopLeftPosition (const int x, const int y)
  880. {
  881. setBounds (x, y, getWidth(), getHeight());
  882. }
  883. void Component::setTopLeftPosition (const Point<int>& pos)
  884. {
  885. setBounds (pos.x, pos.y, getWidth(), getHeight());
  886. }
  887. void Component::setTopRightPosition (const int x, const int y)
  888. {
  889. setTopLeftPosition (x - getWidth(), y);
  890. }
  891. void Component::setBounds (const Rectangle<int>& r)
  892. {
  893. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  894. }
  895. void Component::setBounds (const RelativeRectangle& newBounds)
  896. {
  897. newBounds.applyToComponent (*this);
  898. }
  899. void Component::setBounds (const String& newBoundsExpression)
  900. {
  901. setBounds (RelativeRectangle (newBoundsExpression));
  902. }
  903. void Component::setBoundsRelative (const float x, const float y,
  904. const float w, const float h)
  905. {
  906. const int pw = getParentWidth();
  907. const int ph = getParentHeight();
  908. setBounds (roundToInt (x * pw),
  909. roundToInt (y * ph),
  910. roundToInt (w * pw),
  911. roundToInt (h * ph));
  912. }
  913. void Component::setCentrePosition (const int x, const int y)
  914. {
  915. setTopLeftPosition (x - getWidth() / 2,
  916. y - getHeight() / 2);
  917. }
  918. void Component::setCentreRelative (const float x, const float y)
  919. {
  920. setCentrePosition (roundToInt (getParentWidth() * x),
  921. roundToInt (getParentHeight() * y));
  922. }
  923. void Component::centreWithSize (const int width, const int height)
  924. {
  925. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  926. setBounds (parentArea.getCentreX() - width / 2,
  927. parentArea.getCentreY() - height / 2,
  928. width, height);
  929. }
  930. void Component::setBoundsInset (const BorderSize<int>& borders)
  931. {
  932. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  933. }
  934. void Component::setBoundsToFit (int x, int y, int width, int height,
  935. const Justification& justification,
  936. const bool onlyReduceInSize)
  937. {
  938. // it's no good calling this method unless both the component and
  939. // target rectangle have a finite size.
  940. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  941. if (getWidth() > 0 && getHeight() > 0
  942. && width > 0 && height > 0)
  943. {
  944. int newW, newH;
  945. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  946. {
  947. newW = getWidth();
  948. newH = getHeight();
  949. }
  950. else
  951. {
  952. const double imageRatio = getHeight() / (double) getWidth();
  953. const double targetRatio = height / (double) width;
  954. if (imageRatio <= targetRatio)
  955. {
  956. newW = width;
  957. newH = jmin (height, roundToInt (newW * imageRatio));
  958. }
  959. else
  960. {
  961. newH = height;
  962. newW = jmin (width, roundToInt (newH / imageRatio));
  963. }
  964. }
  965. if (newW > 0 && newH > 0)
  966. setBounds (justification.appliedToRectangle (Rectangle<int> (newW, newH),
  967. Rectangle<int> (x, y, width, height)));
  968. }
  969. }
  970. //==============================================================================
  971. bool Component::isTransformed() const noexcept
  972. {
  973. return affineTransform != nullptr;
  974. }
  975. void Component::setTransform (const AffineTransform& newTransform)
  976. {
  977. // If you pass in a transform with no inverse, the component will have no dimensions,
  978. // and there will be all sorts of maths errors when converting coordinates.
  979. jassert (! newTransform.isSingularity());
  980. if (newTransform.isIdentity())
  981. {
  982. if (affineTransform != nullptr)
  983. {
  984. repaint();
  985. affineTransform = nullptr;
  986. repaint();
  987. sendMovedResizedMessages (false, false);
  988. }
  989. }
  990. else if (affineTransform == nullptr)
  991. {
  992. repaint();
  993. affineTransform = new AffineTransform (newTransform);
  994. repaint();
  995. sendMovedResizedMessages (false, false);
  996. }
  997. else if (*affineTransform != newTransform)
  998. {
  999. repaint();
  1000. *affineTransform = newTransform;
  1001. repaint();
  1002. sendMovedResizedMessages (false, false);
  1003. }
  1004. }
  1005. AffineTransform Component::getTransform() const
  1006. {
  1007. return affineTransform != nullptr ? *affineTransform : AffineTransform::identity;
  1008. }
  1009. //==============================================================================
  1010. bool Component::hitTest (int x, int y)
  1011. {
  1012. if (! flags.ignoresMouseClicksFlag)
  1013. return true;
  1014. if (flags.allowChildMouseClicksFlag)
  1015. {
  1016. for (int i = childComponentList.size(); --i >= 0;)
  1017. {
  1018. Component& child = *childComponentList.getUnchecked (i);
  1019. if (child.isVisible()
  1020. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  1021. return true;
  1022. }
  1023. }
  1024. return false;
  1025. }
  1026. void Component::setInterceptsMouseClicks (const bool allowClicks,
  1027. const bool allowClicksOnChildComponents) noexcept
  1028. {
  1029. flags.ignoresMouseClicksFlag = ! allowClicks;
  1030. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  1031. }
  1032. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  1033. bool& allowsClicksOnChildComponents) const noexcept
  1034. {
  1035. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  1036. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  1037. }
  1038. bool Component::contains (const Point<int>& point)
  1039. {
  1040. if (ComponentHelpers::hitTest (*this, point))
  1041. {
  1042. if (parentComponent != nullptr)
  1043. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  1044. if (flags.hasHeavyweightPeerFlag)
  1045. if (const ComponentPeer* const peer = getPeer())
  1046. return peer->contains (point, true);
  1047. }
  1048. return false;
  1049. }
  1050. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  1051. {
  1052. if (! contains (point))
  1053. return false;
  1054. Component* const top = getTopLevelComponent();
  1055. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  1056. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  1057. }
  1058. Component* Component::getComponentAt (const Point<int>& position)
  1059. {
  1060. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  1061. {
  1062. for (int i = childComponentList.size(); --i >= 0;)
  1063. {
  1064. Component* child = childComponentList.getUnchecked(i);
  1065. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  1066. if (child != nullptr)
  1067. return child;
  1068. }
  1069. return this;
  1070. }
  1071. return nullptr;
  1072. }
  1073. Component* Component::getComponentAt (const int x, const int y)
  1074. {
  1075. return getComponentAt (Point<int> (x, y));
  1076. }
  1077. //==============================================================================
  1078. void Component::addChildComponent (Component* const child, int zOrder)
  1079. {
  1080. // if component methods are being called from threads other than the message
  1081. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1082. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  1083. if (child != nullptr && child->parentComponent != this)
  1084. {
  1085. if (child->parentComponent != nullptr)
  1086. child->parentComponent->removeChildComponent (child);
  1087. else
  1088. child->removeFromDesktop();
  1089. child->parentComponent = this;
  1090. if (child->isVisible())
  1091. child->repaintParent();
  1092. if (! child->isAlwaysOnTop())
  1093. {
  1094. if (zOrder < 0 || zOrder > childComponentList.size())
  1095. zOrder = childComponentList.size();
  1096. while (zOrder > 0)
  1097. {
  1098. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  1099. break;
  1100. --zOrder;
  1101. }
  1102. }
  1103. childComponentList.insert (zOrder, child);
  1104. child->internalHierarchyChanged();
  1105. internalChildrenChanged();
  1106. }
  1107. }
  1108. void Component::addAndMakeVisible (Component* const child, int zOrder)
  1109. {
  1110. if (child != nullptr)
  1111. {
  1112. child->setVisible (true);
  1113. addChildComponent (child, zOrder);
  1114. }
  1115. }
  1116. void Component::addChildAndSetID (Component* const child, const String& childID)
  1117. {
  1118. if (child != nullptr)
  1119. {
  1120. child->setComponentID (childID);
  1121. addAndMakeVisible (child);
  1122. }
  1123. }
  1124. void Component::removeChildComponent (Component* const child)
  1125. {
  1126. removeChildComponent (childComponentList.indexOf (child), true, true);
  1127. }
  1128. Component* Component::removeChildComponent (const int index)
  1129. {
  1130. return removeChildComponent (index, true, true);
  1131. }
  1132. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  1133. {
  1134. // if component methods are being called from threads other than the message
  1135. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1136. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  1137. Component* const child = childComponentList [index];
  1138. if (child != nullptr)
  1139. {
  1140. sendParentEvents = sendParentEvents && child->isShowing();
  1141. if (sendParentEvents)
  1142. {
  1143. sendFakeMouseMove();
  1144. if (child->isVisible())
  1145. child->repaintParent();
  1146. }
  1147. childComponentList.remove (index);
  1148. child->parentComponent = nullptr;
  1149. if (child->cachedImage != nullptr)
  1150. child->cachedImage->releaseResources();
  1151. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  1152. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  1153. {
  1154. if (sendParentEvents)
  1155. {
  1156. const WeakReference<Component> thisPointer (this);
  1157. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  1158. if (thisPointer == nullptr)
  1159. return child;
  1160. grabKeyboardFocus();
  1161. }
  1162. else
  1163. {
  1164. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  1165. }
  1166. }
  1167. if (sendChildEvents)
  1168. child->internalHierarchyChanged();
  1169. if (sendParentEvents)
  1170. internalChildrenChanged();
  1171. }
  1172. return child;
  1173. }
  1174. //==============================================================================
  1175. void Component::removeAllChildren()
  1176. {
  1177. while (childComponentList.size() > 0)
  1178. removeChildComponent (childComponentList.size() - 1);
  1179. }
  1180. void Component::deleteAllChildren()
  1181. {
  1182. while (childComponentList.size() > 0)
  1183. delete (removeChildComponent (childComponentList.size() - 1));
  1184. }
  1185. int Component::getNumChildComponents() const noexcept
  1186. {
  1187. return childComponentList.size();
  1188. }
  1189. Component* Component::getChildComponent (const int index) const noexcept
  1190. {
  1191. return childComponentList [index];
  1192. }
  1193. int Component::getIndexOfChildComponent (const Component* const child) const noexcept
  1194. {
  1195. return childComponentList.indexOf (const_cast <Component*> (child));
  1196. }
  1197. Component* Component::findChildWithID (const String& targetID) const noexcept
  1198. {
  1199. for (int i = childComponentList.size(); --i >= 0;)
  1200. {
  1201. Component* const c = childComponentList.getUnchecked(i);
  1202. if (c->componentID == targetID)
  1203. return c;
  1204. }
  1205. return nullptr;
  1206. }
  1207. Component* Component::getTopLevelComponent() const noexcept
  1208. {
  1209. const Component* comp = this;
  1210. while (comp->parentComponent != nullptr)
  1211. comp = comp->parentComponent;
  1212. return const_cast <Component*> (comp);
  1213. }
  1214. bool Component::isParentOf (const Component* possibleChild) const noexcept
  1215. {
  1216. while (possibleChild != nullptr)
  1217. {
  1218. possibleChild = possibleChild->parentComponent;
  1219. if (possibleChild == this)
  1220. return true;
  1221. }
  1222. return false;
  1223. }
  1224. //==============================================================================
  1225. void Component::parentHierarchyChanged() {}
  1226. void Component::childrenChanged() {}
  1227. void Component::internalChildrenChanged()
  1228. {
  1229. if (componentListeners.isEmpty())
  1230. {
  1231. childrenChanged();
  1232. }
  1233. else
  1234. {
  1235. BailOutChecker checker (this);
  1236. childrenChanged();
  1237. if (! checker.shouldBailOut())
  1238. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  1239. }
  1240. }
  1241. void Component::internalHierarchyChanged()
  1242. {
  1243. BailOutChecker checker (this);
  1244. parentHierarchyChanged();
  1245. if (checker.shouldBailOut())
  1246. return;
  1247. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  1248. if (checker.shouldBailOut())
  1249. return;
  1250. for (int i = childComponentList.size(); --i >= 0;)
  1251. {
  1252. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  1253. if (checker.shouldBailOut())
  1254. {
  1255. // you really shouldn't delete the parent component during a callback telling you
  1256. // that it's changed..
  1257. jassertfalse;
  1258. return;
  1259. }
  1260. i = jmin (i, childComponentList.size());
  1261. }
  1262. }
  1263. //==============================================================================
  1264. #if JUCE_MODAL_LOOPS_PERMITTED
  1265. int Component::runModalLoop()
  1266. {
  1267. if (! MessageManager::getInstance()->isThisTheMessageThread())
  1268. {
  1269. // use a callback so this can be called from non-gui threads
  1270. return (int) (pointer_sized_int) MessageManager::getInstance()
  1271. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  1272. }
  1273. if (! isCurrentlyModal())
  1274. enterModalState (true);
  1275. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  1276. }
  1277. #endif
  1278. //==============================================================================
  1279. void Component::enterModalState (const bool shouldTakeKeyboardFocus,
  1280. ModalComponentManager::Callback* callback,
  1281. const bool deleteWhenDismissed)
  1282. {
  1283. // if component methods are being called from threads other than the message
  1284. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1285. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1286. // Check for an attempt to make a component modal when it already is!
  1287. // This can cause nasty problems..
  1288. jassert (! flags.currentlyModalFlag);
  1289. if (! isCurrentlyModal())
  1290. {
  1291. ModalComponentManager* const mcm = ModalComponentManager::getInstance();
  1292. mcm->startModal (this, deleteWhenDismissed);
  1293. mcm->attachCallback (this, callback);
  1294. flags.currentlyModalFlag = true;
  1295. setVisible (true);
  1296. if (shouldTakeKeyboardFocus)
  1297. grabKeyboardFocus();
  1298. }
  1299. }
  1300. void Component::exitModalState (const int returnValue)
  1301. {
  1302. if (flags.currentlyModalFlag)
  1303. {
  1304. if (MessageManager::getInstance()->isThisTheMessageThread())
  1305. {
  1306. ModalComponentManager::getInstance()->endModal (this, returnValue);
  1307. flags.currentlyModalFlag = false;
  1308. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1309. }
  1310. else
  1311. {
  1312. class ExitModalStateMessage : public CallbackMessage
  1313. {
  1314. public:
  1315. ExitModalStateMessage (Component* const c, const int res)
  1316. : target (c), result (res) {}
  1317. void messageCallback()
  1318. {
  1319. if (target.get() != nullptr) // (get() required for VS2003 bug)
  1320. target->exitModalState (result);
  1321. }
  1322. private:
  1323. WeakReference<Component> target;
  1324. int result;
  1325. };
  1326. (new ExitModalStateMessage (this, returnValue))->post();
  1327. }
  1328. }
  1329. }
  1330. bool Component::isCurrentlyModal() const noexcept
  1331. {
  1332. return flags.currentlyModalFlag
  1333. && getCurrentlyModalComponent() == this;
  1334. }
  1335. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  1336. {
  1337. Component* const mc = getCurrentlyModalComponent();
  1338. return ! (mc == nullptr || mc == this || mc->isParentOf (this)
  1339. || mc->canModalEventBeSentToComponent (this));
  1340. }
  1341. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() noexcept
  1342. {
  1343. return ModalComponentManager::getInstance()->getNumModalComponents();
  1344. }
  1345. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) noexcept
  1346. {
  1347. return ModalComponentManager::getInstance()->getModalComponent (index);
  1348. }
  1349. //==============================================================================
  1350. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) noexcept
  1351. {
  1352. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  1353. }
  1354. bool Component::isBroughtToFrontOnMouseClick() const noexcept
  1355. {
  1356. return flags.bringToFrontOnClickFlag;
  1357. }
  1358. //==============================================================================
  1359. void Component::setMouseCursor (const MouseCursor& newCursor)
  1360. {
  1361. if (cursor != newCursor)
  1362. {
  1363. cursor = newCursor;
  1364. if (flags.visibleFlag)
  1365. updateMouseCursor();
  1366. }
  1367. }
  1368. MouseCursor Component::getMouseCursor()
  1369. {
  1370. return cursor;
  1371. }
  1372. void Component::updateMouseCursor() const
  1373. {
  1374. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1375. }
  1376. //==============================================================================
  1377. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) noexcept
  1378. {
  1379. flags.repaintOnMouseActivityFlag = shouldRepaint;
  1380. }
  1381. //==============================================================================
  1382. void Component::setAlpha (const float newAlpha)
  1383. {
  1384. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  1385. if (componentTransparency != newIntAlpha)
  1386. {
  1387. componentTransparency = newIntAlpha;
  1388. if (flags.hasHeavyweightPeerFlag)
  1389. {
  1390. if (ComponentPeer* const peer = getPeer())
  1391. peer->setAlpha (newAlpha);
  1392. }
  1393. else
  1394. {
  1395. repaint();
  1396. }
  1397. }
  1398. }
  1399. float Component::getAlpha() const
  1400. {
  1401. return (255 - componentTransparency) / 255.0f;
  1402. }
  1403. //==============================================================================
  1404. void Component::repaint()
  1405. {
  1406. internalRepaintUnchecked (getLocalBounds(), true);
  1407. }
  1408. void Component::repaint (const int x, const int y, const int w, const int h)
  1409. {
  1410. internalRepaint (Rectangle<int> (x, y, w, h));
  1411. }
  1412. void Component::repaint (const Rectangle<int>& area)
  1413. {
  1414. internalRepaint (area);
  1415. }
  1416. void Component::repaintParent()
  1417. {
  1418. if (parentComponent != nullptr)
  1419. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, getLocalBounds()));
  1420. }
  1421. void Component::internalRepaint (const Rectangle<int>& area)
  1422. {
  1423. const Rectangle<int> r (area.getIntersection (getLocalBounds()));
  1424. if (! r.isEmpty())
  1425. internalRepaintUnchecked (r, false);
  1426. }
  1427. void Component::internalRepaintUnchecked (const Rectangle<int>& area, const bool isEntireComponent)
  1428. {
  1429. if (flags.visibleFlag)
  1430. {
  1431. if (cachedImage != nullptr)
  1432. {
  1433. if (isEntireComponent)
  1434. cachedImage->invalidateAll();
  1435. else
  1436. cachedImage->invalidate (area);
  1437. }
  1438. if (flags.hasHeavyweightPeerFlag)
  1439. {
  1440. // if component methods are being called from threads other than the message
  1441. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1442. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1443. if (ComponentPeer* const peer = getPeer())
  1444. peer->repaint (area);
  1445. }
  1446. else
  1447. {
  1448. if (parentComponent != nullptr)
  1449. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, area));
  1450. }
  1451. }
  1452. }
  1453. //==============================================================================
  1454. void Component::paint (Graphics&)
  1455. {
  1456. // all painting is done in the subclasses
  1457. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  1458. }
  1459. void Component::paintOverChildren (Graphics&)
  1460. {
  1461. // all painting is done in the subclasses
  1462. }
  1463. //==============================================================================
  1464. void Component::paintWithinParentContext (Graphics& g)
  1465. {
  1466. g.setOrigin (getX(), getY());
  1467. if (cachedImage != nullptr)
  1468. cachedImage->paint (g);
  1469. else
  1470. paintEntireComponent (g, false);
  1471. }
  1472. void Component::paintComponentAndChildren (Graphics& g)
  1473. {
  1474. const Rectangle<int> clipBounds (g.getClipBounds());
  1475. if (flags.dontClipGraphicsFlag)
  1476. {
  1477. paint (g);
  1478. }
  1479. else
  1480. {
  1481. g.saveState();
  1482. if (ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>()) || ! g.isClipEmpty())
  1483. paint (g);
  1484. g.restoreState();
  1485. }
  1486. for (int i = 0; i < childComponentList.size(); ++i)
  1487. {
  1488. Component& child = *childComponentList.getUnchecked (i);
  1489. if (child.isVisible())
  1490. {
  1491. if (child.affineTransform != nullptr)
  1492. {
  1493. g.saveState();
  1494. g.addTransform (*child.affineTransform);
  1495. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  1496. child.paintWithinParentContext (g);
  1497. g.restoreState();
  1498. }
  1499. else if (clipBounds.intersects (child.getBounds()))
  1500. {
  1501. g.saveState();
  1502. if (child.flags.dontClipGraphicsFlag)
  1503. {
  1504. child.paintWithinParentContext (g);
  1505. }
  1506. else if (g.reduceClipRegion (child.getBounds()))
  1507. {
  1508. bool nothingClipped = true;
  1509. for (int j = i + 1; j < childComponentList.size(); ++j)
  1510. {
  1511. const Component& sibling = *childComponentList.getUnchecked (j);
  1512. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == nullptr)
  1513. {
  1514. nothingClipped = false;
  1515. g.excludeClipRegion (sibling.getBounds());
  1516. }
  1517. }
  1518. if (nothingClipped || ! g.isClipEmpty())
  1519. child.paintWithinParentContext (g);
  1520. }
  1521. g.restoreState();
  1522. }
  1523. }
  1524. }
  1525. g.saveState();
  1526. paintOverChildren (g);
  1527. g.restoreState();
  1528. }
  1529. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  1530. {
  1531. #if JUCE_DEBUG
  1532. flags.isInsidePaintCall = true;
  1533. #endif
  1534. if (effect != nullptr)
  1535. {
  1536. const float scale = g.getInternalContext().getTargetDeviceScaleFactor();
  1537. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  1538. (int) (scale * getWidth()), (int) (scale * getHeight()), ! flags.opaqueFlag);
  1539. {
  1540. Graphics g2 (effectImage);
  1541. g2.addTransform (AffineTransform::scale (scale));
  1542. paintComponentAndChildren (g2);
  1543. }
  1544. g.saveState();
  1545. g.addTransform (AffineTransform::scale (1.0f / scale));
  1546. effect->applyEffect (effectImage, g, scale, ignoreAlphaLevel ? 1.0f : getAlpha());
  1547. g.restoreState();
  1548. }
  1549. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  1550. {
  1551. if (componentTransparency < 255)
  1552. {
  1553. g.beginTransparencyLayer (getAlpha());
  1554. paintComponentAndChildren (g);
  1555. g.endTransparencyLayer();
  1556. }
  1557. }
  1558. else
  1559. {
  1560. paintComponentAndChildren (g);
  1561. }
  1562. #if JUCE_DEBUG
  1563. flags.isInsidePaintCall = false;
  1564. #endif
  1565. }
  1566. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) noexcept
  1567. {
  1568. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  1569. }
  1570. //==============================================================================
  1571. Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  1572. const bool clipImageToComponentBounds)
  1573. {
  1574. Rectangle<int> r (areaToGrab);
  1575. if (clipImageToComponentBounds)
  1576. r = r.getIntersection (getLocalBounds());
  1577. if (r.isEmpty())
  1578. return Image();
  1579. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  1580. r.getWidth(), r.getHeight(), true);
  1581. Graphics imageContext (componentImage);
  1582. imageContext.setOrigin (-r.getX(), -r.getY());
  1583. paintEntireComponent (imageContext, true);
  1584. return componentImage;
  1585. }
  1586. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  1587. {
  1588. if (effect != newEffect)
  1589. {
  1590. effect = newEffect;
  1591. repaint();
  1592. }
  1593. }
  1594. //==============================================================================
  1595. LookAndFeel& Component::getLookAndFeel() const noexcept
  1596. {
  1597. for (const Component* c = this; c != nullptr; c = c->parentComponent)
  1598. if (c->lookAndFeel != nullptr)
  1599. return *(c->lookAndFeel);
  1600. return LookAndFeel::getDefaultLookAndFeel();
  1601. }
  1602. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  1603. {
  1604. if (lookAndFeel != newLookAndFeel)
  1605. {
  1606. lookAndFeel = newLookAndFeel;
  1607. sendLookAndFeelChange();
  1608. }
  1609. }
  1610. void Component::lookAndFeelChanged() {}
  1611. void Component::colourChanged() {}
  1612. void Component::sendLookAndFeelChange()
  1613. {
  1614. const WeakReference<Component> safePointer (this);
  1615. repaint();
  1616. lookAndFeelChanged();
  1617. if (safePointer != nullptr)
  1618. {
  1619. colourChanged();
  1620. if (safePointer != nullptr)
  1621. {
  1622. for (int i = childComponentList.size(); --i >= 0;)
  1623. {
  1624. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  1625. if (safePointer == nullptr)
  1626. return;
  1627. i = jmin (i, childComponentList.size());
  1628. }
  1629. }
  1630. }
  1631. }
  1632. Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  1633. {
  1634. if (const var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId)))
  1635. return Colour ((uint32) static_cast <int> (*v));
  1636. if (inheritFromParent && parentComponent != nullptr
  1637. && (lookAndFeel == nullptr || ! lookAndFeel->isColourSpecified (colourId)))
  1638. return parentComponent->findColour (colourId, true);
  1639. return getLookAndFeel().findColour (colourId);
  1640. }
  1641. bool Component::isColourSpecified (const int colourId) const
  1642. {
  1643. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  1644. }
  1645. void Component::removeColour (const int colourId)
  1646. {
  1647. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  1648. colourChanged();
  1649. }
  1650. void Component::setColour (const int colourId, const Colour& colour)
  1651. {
  1652. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  1653. colourChanged();
  1654. }
  1655. void Component::copyAllExplicitColoursTo (Component& target) const
  1656. {
  1657. bool changed = false;
  1658. for (int i = properties.size(); --i >= 0;)
  1659. {
  1660. const Identifier name (properties.getName(i));
  1661. if (name.toString().startsWith ("jcclr_"))
  1662. if (target.properties.set (name, properties [name]))
  1663. changed = true;
  1664. }
  1665. if (changed)
  1666. target.colourChanged();
  1667. }
  1668. //==============================================================================
  1669. MarkerList* Component::getMarkers (bool /*xAxis*/)
  1670. {
  1671. return nullptr;
  1672. }
  1673. //==============================================================================
  1674. Component::Positioner::Positioner (Component& c) noexcept
  1675. : component (c)
  1676. {
  1677. }
  1678. Component::Positioner* Component::getPositioner() const noexcept
  1679. {
  1680. return positioner;
  1681. }
  1682. void Component::setPositioner (Positioner* newPositioner)
  1683. {
  1684. // You can only assign a positioner to the component that it was created for!
  1685. jassert (newPositioner == nullptr || this == &(newPositioner->getComponent()));
  1686. positioner = newPositioner;
  1687. }
  1688. //==============================================================================
  1689. Rectangle<int> Component::getLocalBounds() const noexcept
  1690. {
  1691. return bounds.withZeroOrigin();
  1692. }
  1693. Rectangle<int> Component::getBoundsInParent() const noexcept
  1694. {
  1695. return affineTransform == nullptr ? bounds
  1696. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  1697. }
  1698. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  1699. {
  1700. result.clear();
  1701. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  1702. if (! unclipped.isEmpty())
  1703. {
  1704. result.add (unclipped);
  1705. if (includeSiblings)
  1706. {
  1707. const Component* const c = getTopLevelComponent();
  1708. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  1709. c->getLocalBounds(), this);
  1710. }
  1711. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, nullptr);
  1712. result.consolidate();
  1713. }
  1714. }
  1715. //==============================================================================
  1716. void Component::mouseEnter (const MouseEvent&) {}
  1717. void Component::mouseExit (const MouseEvent&) {}
  1718. void Component::mouseDown (const MouseEvent&) {}
  1719. void Component::mouseUp (const MouseEvent&) {}
  1720. void Component::mouseDrag (const MouseEvent&) {}
  1721. void Component::mouseMove (const MouseEvent&) {}
  1722. void Component::mouseDoubleClick (const MouseEvent&) {}
  1723. void Component::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  1724. {
  1725. // the base class just passes this event up to its parent..
  1726. if (parentComponent != nullptr)
  1727. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent), wheel);
  1728. }
  1729. //==============================================================================
  1730. void Component::resized() {}
  1731. void Component::moved() {}
  1732. void Component::childBoundsChanged (Component*) {}
  1733. void Component::parentSizeChanged() {}
  1734. void Component::addComponentListener (ComponentListener* const newListener)
  1735. {
  1736. // if component methods are being called from threads other than the message
  1737. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1738. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1739. componentListeners.add (newListener);
  1740. }
  1741. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  1742. {
  1743. componentListeners.remove (listenerToRemove);
  1744. }
  1745. //==============================================================================
  1746. void Component::inputAttemptWhenModal()
  1747. {
  1748. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1749. getLookAndFeel().playAlertSound();
  1750. }
  1751. bool Component::canModalEventBeSentToComponent (const Component*)
  1752. {
  1753. return false;
  1754. }
  1755. void Component::internalModalInputAttempt()
  1756. {
  1757. if (Component* const current = getCurrentlyModalComponent())
  1758. current->inputAttemptWhenModal();
  1759. }
  1760. //==============================================================================
  1761. void Component::postCommandMessage (const int commandId)
  1762. {
  1763. class CustomCommandMessage : public CallbackMessage
  1764. {
  1765. public:
  1766. CustomCommandMessage (Component* const c, const int command)
  1767. : target (c), commandId (command) {}
  1768. void messageCallback()
  1769. {
  1770. if (target.get() != nullptr) // (get() required for VS2003 bug)
  1771. target->handleCommandMessage (commandId);
  1772. }
  1773. private:
  1774. WeakReference<Component> target;
  1775. int commandId;
  1776. };
  1777. (new CustomCommandMessage (this, commandId))->post();
  1778. }
  1779. void Component::handleCommandMessage (int)
  1780. {
  1781. // used by subclasses
  1782. }
  1783. //==============================================================================
  1784. void Component::addMouseListener (MouseListener* const newListener,
  1785. const bool wantsEventsForAllNestedChildComponents)
  1786. {
  1787. // if component methods are being called from threads other than the message
  1788. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1789. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1790. // If you register a component as a mouselistener for itself, it'll receive all the events
  1791. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  1792. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  1793. if (mouseListeners == nullptr)
  1794. mouseListeners = new MouseListenerList();
  1795. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  1796. }
  1797. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  1798. {
  1799. // if component methods are being called from threads other than the message
  1800. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1801. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1802. if (mouseListeners != nullptr)
  1803. mouseListeners->removeListener (listenerToRemove);
  1804. }
  1805. //==============================================================================
  1806. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1807. {
  1808. if (isCurrentlyBlockedByAnotherModalComponent())
  1809. {
  1810. // if something else is modal, always just show a normal mouse cursor
  1811. source.showMouseCursor (MouseCursor::NormalCursor);
  1812. return;
  1813. }
  1814. if (flags.repaintOnMouseActivityFlag)
  1815. repaint();
  1816. BailOutChecker checker (this);
  1817. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1818. this, this, time, relativePos, time, 0, false);
  1819. mouseEnter (me);
  1820. if (checker.shouldBailOut())
  1821. return;
  1822. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseEnter, me);
  1823. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  1824. }
  1825. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1826. {
  1827. if (flags.repaintOnMouseActivityFlag)
  1828. repaint();
  1829. BailOutChecker checker (this);
  1830. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1831. this, this, time, relativePos, time, 0, false);
  1832. mouseExit (me);
  1833. if (checker.shouldBailOut())
  1834. return;
  1835. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseExit, me);
  1836. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  1837. }
  1838. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1839. {
  1840. Desktop& desktop = Desktop::getInstance();
  1841. BailOutChecker checker (this);
  1842. if (isCurrentlyBlockedByAnotherModalComponent())
  1843. {
  1844. flags.mouseDownWasBlocked = true;
  1845. internalModalInputAttempt();
  1846. if (checker.shouldBailOut())
  1847. return;
  1848. // If processing the input attempt has exited the modal loop, we'll allow the event
  1849. // to be delivered..
  1850. if (isCurrentlyBlockedByAnotherModalComponent())
  1851. {
  1852. // allow blocked mouse-events to go to global listeners..
  1853. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1854. this, this, time, relativePos, time,
  1855. source.getNumberOfMultipleClicks(), false);
  1856. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseDown, me);
  1857. return;
  1858. }
  1859. }
  1860. flags.mouseDownWasBlocked = false;
  1861. for (Component* c = this; c != nullptr; c = c->parentComponent)
  1862. {
  1863. if (c->isBroughtToFrontOnMouseClick())
  1864. {
  1865. c->toFront (true);
  1866. if (checker.shouldBailOut())
  1867. return;
  1868. }
  1869. }
  1870. if (! flags.dontFocusOnMouseClickFlag)
  1871. {
  1872. grabFocusInternal (focusChangedByMouseClick, true);
  1873. if (checker.shouldBailOut())
  1874. return;
  1875. }
  1876. if (flags.repaintOnMouseActivityFlag)
  1877. repaint();
  1878. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1879. this, this, time, relativePos, time,
  1880. source.getNumberOfMultipleClicks(), false);
  1881. mouseDown (me);
  1882. if (checker.shouldBailOut())
  1883. return;
  1884. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseDown, me);
  1885. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  1886. }
  1887. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos,
  1888. const Time& time, const ModifierKeys& oldModifiers)
  1889. {
  1890. if (flags.mouseDownWasBlocked && isCurrentlyBlockedByAnotherModalComponent())
  1891. return;
  1892. BailOutChecker checker (this);
  1893. if (flags.repaintOnMouseActivityFlag)
  1894. repaint();
  1895. const MouseEvent me (source, relativePos,
  1896. oldModifiers, this, this, time,
  1897. getLocalPoint (nullptr, source.getLastMouseDownPosition()),
  1898. source.getLastMouseDownTime(),
  1899. source.getNumberOfMultipleClicks(),
  1900. source.hasMouseMovedSignificantlySincePressed());
  1901. mouseUp (me);
  1902. if (checker.shouldBailOut())
  1903. return;
  1904. Desktop& desktop = Desktop::getInstance();
  1905. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseUp, me);
  1906. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  1907. if (checker.shouldBailOut())
  1908. return;
  1909. // check for double-click
  1910. if (me.getNumberOfClicks() >= 2)
  1911. {
  1912. mouseDoubleClick (me);
  1913. if (checker.shouldBailOut())
  1914. return;
  1915. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  1916. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  1917. }
  1918. }
  1919. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1920. {
  1921. if (! isCurrentlyBlockedByAnotherModalComponent())
  1922. {
  1923. BailOutChecker checker (this);
  1924. const MouseEvent me (source, relativePos,
  1925. source.getCurrentModifiers(), this, this, time,
  1926. getLocalPoint (nullptr, source.getLastMouseDownPosition()),
  1927. source.getLastMouseDownTime(),
  1928. source.getNumberOfMultipleClicks(),
  1929. source.hasMouseMovedSignificantlySincePressed());
  1930. mouseDrag (me);
  1931. if (checker.shouldBailOut())
  1932. return;
  1933. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseDrag, me);
  1934. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  1935. }
  1936. }
  1937. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1938. {
  1939. Desktop& desktop = Desktop::getInstance();
  1940. if (isCurrentlyBlockedByAnotherModalComponent())
  1941. {
  1942. // allow blocked mouse-events to go to global listeners..
  1943. desktop.sendMouseMove();
  1944. }
  1945. else
  1946. {
  1947. BailOutChecker checker (this);
  1948. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1949. this, this, time, relativePos, time, 0, false);
  1950. mouseMove (me);
  1951. if (checker.shouldBailOut())
  1952. return;
  1953. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseMove, me);
  1954. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  1955. }
  1956. }
  1957. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  1958. const Time& time, const MouseWheelDetails& wheel)
  1959. {
  1960. Desktop& desktop = Desktop::getInstance();
  1961. BailOutChecker checker (this);
  1962. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1963. this, this, time, relativePos, time, 0, false);
  1964. if (isCurrentlyBlockedByAnotherModalComponent())
  1965. {
  1966. // allow blocked mouse-events to go to global listeners..
  1967. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheel);
  1968. }
  1969. else
  1970. {
  1971. mouseWheelMove (me, wheel);
  1972. if (checker.shouldBailOut())
  1973. return;
  1974. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheel);
  1975. if (! checker.shouldBailOut())
  1976. MouseListenerList::sendWheelEvent (*this, checker, me, wheel);
  1977. }
  1978. }
  1979. void Component::sendFakeMouseMove() const
  1980. {
  1981. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  1982. if (! mainMouse.isDragging())
  1983. mainMouse.triggerFakeMove();
  1984. }
  1985. void JUCE_CALLTYPE Component::beginDragAutoRepeat (const int interval)
  1986. {
  1987. Desktop::getInstance().beginDragAutoRepeat (interval);
  1988. }
  1989. //==============================================================================
  1990. void Component::broughtToFront()
  1991. {
  1992. }
  1993. void Component::internalBroughtToFront()
  1994. {
  1995. if (flags.hasHeavyweightPeerFlag)
  1996. Desktop::getInstance().componentBroughtToFront (this);
  1997. BailOutChecker checker (this);
  1998. broughtToFront();
  1999. if (checker.shouldBailOut())
  2000. return;
  2001. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  2002. if (checker.shouldBailOut())
  2003. return;
  2004. // When brought to the front and there's a modal component blocking this one,
  2005. // we need to bring the modal one to the front instead..
  2006. if (Component* const cm = getCurrentlyModalComponent())
  2007. if (cm->getTopLevelComponent() != getTopLevelComponent())
  2008. ModalComponentManager::getInstance()->bringModalComponentsToFront (false); // very important that this is false, otherwise in Windows,
  2009. // non-front components can't get focus when another modal comp is
  2010. // active, and therefore can't receive mouse-clicks
  2011. }
  2012. //==============================================================================
  2013. void Component::focusGained (FocusChangeType) {}
  2014. void Component::focusLost (FocusChangeType) {}
  2015. void Component::focusOfChildComponentChanged (FocusChangeType) {}
  2016. void Component::internalFocusGain (const FocusChangeType cause)
  2017. {
  2018. internalFocusGain (cause, WeakReference<Component> (this));
  2019. }
  2020. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  2021. {
  2022. focusGained (cause);
  2023. if (safePointer != nullptr)
  2024. internalChildFocusChange (cause, safePointer);
  2025. }
  2026. void Component::internalFocusLoss (const FocusChangeType cause)
  2027. {
  2028. const WeakReference<Component> safePointer (this);
  2029. focusLost (focusChangedDirectly);
  2030. if (safePointer != nullptr)
  2031. internalChildFocusChange (cause, safePointer);
  2032. }
  2033. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  2034. {
  2035. const bool childIsNowFocused = hasKeyboardFocus (true);
  2036. if (flags.childCompFocusedFlag != childIsNowFocused)
  2037. {
  2038. flags.childCompFocusedFlag = childIsNowFocused;
  2039. focusOfChildComponentChanged (cause);
  2040. if (safePointer == nullptr)
  2041. return;
  2042. }
  2043. if (parentComponent != nullptr)
  2044. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  2045. }
  2046. void Component::setWantsKeyboardFocus (const bool wantsFocus) noexcept
  2047. {
  2048. flags.wantsFocusFlag = wantsFocus;
  2049. }
  2050. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  2051. {
  2052. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  2053. }
  2054. bool Component::getMouseClickGrabsKeyboardFocus() const noexcept
  2055. {
  2056. return ! flags.dontFocusOnMouseClickFlag;
  2057. }
  2058. bool Component::getWantsKeyboardFocus() const noexcept
  2059. {
  2060. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  2061. }
  2062. void Component::setFocusContainer (const bool shouldBeFocusContainer) noexcept
  2063. {
  2064. flags.isFocusContainerFlag = shouldBeFocusContainer;
  2065. }
  2066. bool Component::isFocusContainer() const noexcept
  2067. {
  2068. return flags.isFocusContainerFlag;
  2069. }
  2070. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  2071. int Component::getExplicitFocusOrder() const
  2072. {
  2073. return properties [juce_explicitFocusOrderId];
  2074. }
  2075. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  2076. {
  2077. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  2078. }
  2079. KeyboardFocusTraverser* Component::createFocusTraverser()
  2080. {
  2081. if (flags.isFocusContainerFlag || parentComponent == nullptr)
  2082. return new KeyboardFocusTraverser();
  2083. return parentComponent->createFocusTraverser();
  2084. }
  2085. void Component::takeKeyboardFocus (const FocusChangeType cause)
  2086. {
  2087. // give the focus to this component
  2088. if (currentlyFocusedComponent != this)
  2089. {
  2090. // get the focus onto our desktop window
  2091. if (ComponentPeer* const peer = getPeer())
  2092. {
  2093. const WeakReference<Component> safePointer (this);
  2094. peer->grabFocus();
  2095. if (peer->isFocused() && currentlyFocusedComponent != this)
  2096. {
  2097. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  2098. currentlyFocusedComponent = this;
  2099. Desktop::getInstance().triggerFocusCallback();
  2100. // call this after setting currentlyFocusedComponent so that the one that's
  2101. // losing it has a chance to see where focus is going
  2102. if (componentLosingFocus != nullptr)
  2103. componentLosingFocus->internalFocusLoss (cause);
  2104. if (currentlyFocusedComponent == this)
  2105. internalFocusGain (cause, safePointer);
  2106. }
  2107. }
  2108. }
  2109. }
  2110. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  2111. {
  2112. if (isShowing())
  2113. {
  2114. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == nullptr))
  2115. {
  2116. takeKeyboardFocus (cause);
  2117. }
  2118. else
  2119. {
  2120. if (isParentOf (currentlyFocusedComponent)
  2121. && currentlyFocusedComponent->isShowing())
  2122. {
  2123. // do nothing if the focused component is actually a child of ours..
  2124. }
  2125. else
  2126. {
  2127. // find the default child component..
  2128. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  2129. if (traverser != nullptr)
  2130. {
  2131. Component* const defaultComp = traverser->getDefaultComponent (this);
  2132. traverser = nullptr;
  2133. if (defaultComp != nullptr)
  2134. {
  2135. defaultComp->grabFocusInternal (cause, false);
  2136. return;
  2137. }
  2138. }
  2139. if (canTryParent && parentComponent != nullptr)
  2140. {
  2141. // if no children want it and we're allowed to try our parent comp,
  2142. // then pass up to parent, which will try our siblings.
  2143. parentComponent->grabFocusInternal (cause, true);
  2144. }
  2145. }
  2146. }
  2147. }
  2148. }
  2149. void Component::grabKeyboardFocus()
  2150. {
  2151. // if component methods are being called from threads other than the message
  2152. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  2153. CHECK_MESSAGE_MANAGER_IS_LOCKED
  2154. grabFocusInternal (focusChangedDirectly, true);
  2155. }
  2156. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  2157. {
  2158. // if component methods are being called from threads other than the message
  2159. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  2160. CHECK_MESSAGE_MANAGER_IS_LOCKED
  2161. if (parentComponent != nullptr)
  2162. {
  2163. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  2164. if (traverser != nullptr)
  2165. {
  2166. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  2167. : traverser->getPreviousComponent (this);
  2168. traverser = nullptr;
  2169. if (nextComp != nullptr)
  2170. {
  2171. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  2172. {
  2173. const WeakReference<Component> nextCompPointer (nextComp);
  2174. internalModalInputAttempt();
  2175. if (nextCompPointer == nullptr || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  2176. return;
  2177. }
  2178. nextComp->grabFocusInternal (focusChangedByTabKey, true);
  2179. return;
  2180. }
  2181. }
  2182. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  2183. }
  2184. }
  2185. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  2186. {
  2187. return (currentlyFocusedComponent == this)
  2188. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  2189. }
  2190. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() noexcept
  2191. {
  2192. return currentlyFocusedComponent;
  2193. }
  2194. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  2195. {
  2196. Component* const componentLosingFocus = currentlyFocusedComponent;
  2197. currentlyFocusedComponent = nullptr;
  2198. if (sendFocusLossEvent && componentLosingFocus != nullptr)
  2199. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  2200. Desktop::getInstance().triggerFocusCallback();
  2201. }
  2202. //==============================================================================
  2203. bool Component::isEnabled() const noexcept
  2204. {
  2205. return (! flags.isDisabledFlag)
  2206. && (parentComponent == nullptr || parentComponent->isEnabled());
  2207. }
  2208. void Component::setEnabled (const bool shouldBeEnabled)
  2209. {
  2210. if (flags.isDisabledFlag == shouldBeEnabled)
  2211. {
  2212. flags.isDisabledFlag = ! shouldBeEnabled;
  2213. // if any parent components are disabled, setting our flag won't make a difference,
  2214. // so no need to send a change message
  2215. if (parentComponent == nullptr || parentComponent->isEnabled())
  2216. sendEnablementChangeMessage();
  2217. }
  2218. }
  2219. void Component::enablementChanged() {}
  2220. void Component::sendEnablementChangeMessage()
  2221. {
  2222. const WeakReference<Component> safePointer (this);
  2223. enablementChanged();
  2224. if (safePointer == nullptr)
  2225. return;
  2226. for (int i = getNumChildComponents(); --i >= 0;)
  2227. {
  2228. if (Component* const c = getChildComponent (i))
  2229. {
  2230. c->sendEnablementChangeMessage();
  2231. if (safePointer == nullptr)
  2232. return;
  2233. }
  2234. }
  2235. }
  2236. //==============================================================================
  2237. bool Component::isMouseOver (const bool includeChildren) const
  2238. {
  2239. const Desktop& desktop = Desktop::getInstance();
  2240. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  2241. {
  2242. const MouseInputSource* const mi = desktop.getMouseSource(i);
  2243. Component* const c = mi->getComponentUnderMouse();
  2244. if ((c == this || (includeChildren && isParentOf (c)))
  2245. && c->reallyContains (c->getLocalPoint (nullptr, mi->getScreenPosition()), false))
  2246. return true;
  2247. }
  2248. return false;
  2249. }
  2250. bool Component::isMouseButtonDown() const
  2251. {
  2252. const Desktop& desktop = Desktop::getInstance();
  2253. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  2254. {
  2255. const MouseInputSource* const mi = desktop.getMouseSource(i);
  2256. if (mi->isDragging() && mi->getComponentUnderMouse() == this)
  2257. return true;
  2258. }
  2259. return false;
  2260. }
  2261. bool Component::isMouseOverOrDragging() const
  2262. {
  2263. const Desktop& desktop = Desktop::getInstance();
  2264. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  2265. if (desktop.getMouseSource(i)->getComponentUnderMouse() == this)
  2266. return true;
  2267. return false;
  2268. }
  2269. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() noexcept
  2270. {
  2271. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  2272. }
  2273. Point<int> Component::getMouseXYRelative() const
  2274. {
  2275. return getLocalPoint (nullptr, Desktop::getMousePosition());
  2276. }
  2277. //==============================================================================
  2278. void Component::addKeyListener (KeyListener* const newListener)
  2279. {
  2280. if (keyListeners == nullptr)
  2281. keyListeners = new Array <KeyListener*>();
  2282. keyListeners->addIfNotAlreadyThere (newListener);
  2283. }
  2284. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  2285. {
  2286. if (keyListeners != nullptr)
  2287. keyListeners->removeFirstMatchingValue (listenerToRemove);
  2288. }
  2289. bool Component::keyPressed (const KeyPress&) { return false; }
  2290. bool Component::keyStateChanged (const bool /*isKeyDown*/) { return false; }
  2291. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  2292. {
  2293. if (parentComponent != nullptr)
  2294. parentComponent->modifierKeysChanged (modifiers);
  2295. }
  2296. void Component::internalModifierKeysChanged()
  2297. {
  2298. sendFakeMouseMove();
  2299. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  2300. }
  2301. //==============================================================================
  2302. Component::BailOutChecker::BailOutChecker (Component* const component)
  2303. : safePointer (component)
  2304. {
  2305. jassert (component != nullptr);
  2306. }
  2307. bool Component::BailOutChecker::shouldBailOut() const noexcept
  2308. {
  2309. return safePointer == nullptr;
  2310. }