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.

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