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

3009 lines
98KB

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