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.

3195 lines
105KB

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