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.

3154 lines
103KB

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