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.

3150 lines
103KB

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