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.

2994 lines
98KB

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