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.

3065 lines
98KB

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