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.

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