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.

2991 lines
97KB

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