Audio plugin host https://kx.studio/carla
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.

2999 lines
98KB

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