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.

3184 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. WeakReference<Component> target (this);
  1398. MessageManager::callAsync ([=]
  1399. {
  1400. if (auto* c = target.get())
  1401. c->exitModalState (returnValue);
  1402. });
  1403. }
  1404. }
  1405. }
  1406. bool Component::isCurrentlyModal (bool onlyConsiderForemostModalComponent) const noexcept
  1407. {
  1408. auto& mcm = *ModalComponentManager::getInstance();
  1409. return onlyConsiderForemostModalComponent ? mcm.isFrontModalComponent (this)
  1410. : mcm.isModal (this);
  1411. }
  1412. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  1413. {
  1414. auto* mc = getCurrentlyModalComponent();
  1415. return ! (mc == nullptr || mc == this || mc->isParentOf (this)
  1416. || mc->canModalEventBeSentToComponent (this));
  1417. }
  1418. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() noexcept
  1419. {
  1420. return ModalComponentManager::getInstance()->getNumModalComponents();
  1421. }
  1422. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) noexcept
  1423. {
  1424. return ModalComponentManager::getInstance()->getModalComponent (index);
  1425. }
  1426. //==============================================================================
  1427. void Component::setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) noexcept
  1428. {
  1429. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  1430. }
  1431. bool Component::isBroughtToFrontOnMouseClick() const noexcept
  1432. {
  1433. return flags.bringToFrontOnClickFlag;
  1434. }
  1435. //==============================================================================
  1436. void Component::setMouseCursor (const MouseCursor& newCursor)
  1437. {
  1438. if (cursor != newCursor)
  1439. {
  1440. cursor = newCursor;
  1441. if (flags.visibleFlag)
  1442. updateMouseCursor();
  1443. }
  1444. }
  1445. MouseCursor Component::getMouseCursor()
  1446. {
  1447. return cursor;
  1448. }
  1449. void Component::updateMouseCursor() const
  1450. {
  1451. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1452. }
  1453. //==============================================================================
  1454. void Component::setRepaintsOnMouseActivity (bool shouldRepaint) noexcept
  1455. {
  1456. flags.repaintOnMouseActivityFlag = shouldRepaint;
  1457. }
  1458. //==============================================================================
  1459. float Component::getAlpha() const noexcept
  1460. {
  1461. return (255 - componentTransparency) / 255.0f;
  1462. }
  1463. void Component::setAlpha (float newAlpha)
  1464. {
  1465. auto newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  1466. if (componentTransparency != newIntAlpha)
  1467. {
  1468. componentTransparency = newIntAlpha;
  1469. alphaChanged();
  1470. }
  1471. }
  1472. void Component::alphaChanged()
  1473. {
  1474. if (flags.hasHeavyweightPeerFlag)
  1475. {
  1476. if (auto* peer = getPeer())
  1477. peer->setAlpha (getAlpha());
  1478. }
  1479. else
  1480. {
  1481. repaint();
  1482. }
  1483. }
  1484. //==============================================================================
  1485. void Component::repaint()
  1486. {
  1487. internalRepaintUnchecked (getLocalBounds(), true);
  1488. }
  1489. void Component::repaint (int x, int y, int w, int h)
  1490. {
  1491. internalRepaint ({ x, y, w, h });
  1492. }
  1493. void Component::repaint (Rectangle<int> area)
  1494. {
  1495. internalRepaint (area);
  1496. }
  1497. void Component::repaintParent()
  1498. {
  1499. if (parentComponent != nullptr)
  1500. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, getLocalBounds()));
  1501. }
  1502. void Component::internalRepaint (Rectangle<int> area)
  1503. {
  1504. area = area.getIntersection (getLocalBounds());
  1505. if (! area.isEmpty())
  1506. internalRepaintUnchecked (area, false);
  1507. }
  1508. void Component::internalRepaintUnchecked (Rectangle<int> area, bool isEntireComponent)
  1509. {
  1510. // if component methods are being called from threads other than the message
  1511. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1512. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  1513. if (flags.visibleFlag)
  1514. {
  1515. if (cachedImage != nullptr)
  1516. if (! (isEntireComponent ? cachedImage->invalidateAll()
  1517. : cachedImage->invalidate (area)))
  1518. return;
  1519. if (area.isEmpty())
  1520. return;
  1521. if (flags.hasHeavyweightPeerFlag)
  1522. {
  1523. if (auto* peer = getPeer())
  1524. {
  1525. // Tweak the scaling so that the component's integer size exactly aligns with the peer's scaled size
  1526. auto peerBounds = peer->getBounds();
  1527. auto scaled = area * Point<float> ((float) peerBounds.getWidth() / (float) getWidth(),
  1528. (float) peerBounds.getHeight() / (float) getHeight());
  1529. peer->repaint (affineTransform != nullptr ? scaled.transformedBy (*affineTransform) : scaled);
  1530. }
  1531. }
  1532. else
  1533. {
  1534. if (parentComponent != nullptr)
  1535. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, area));
  1536. }
  1537. }
  1538. }
  1539. //==============================================================================
  1540. void Component::paint (Graphics&)
  1541. {
  1542. // if your component is marked as opaque, you must implement a paint
  1543. // method and ensure that its entire area is completely painted.
  1544. jassert (getBounds().isEmpty() || ! isOpaque());
  1545. }
  1546. void Component::paintOverChildren (Graphics&)
  1547. {
  1548. // all painting is done in the subclasses
  1549. }
  1550. //==============================================================================
  1551. void Component::paintWithinParentContext (Graphics& g)
  1552. {
  1553. g.setOrigin (getPosition());
  1554. if (cachedImage != nullptr)
  1555. cachedImage->paint (g);
  1556. else
  1557. paintEntireComponent (g, false);
  1558. }
  1559. void Component::paintComponentAndChildren (Graphics& g)
  1560. {
  1561. auto clipBounds = g.getClipBounds();
  1562. if (flags.dontClipGraphicsFlag)
  1563. {
  1564. paint (g);
  1565. }
  1566. else
  1567. {
  1568. Graphics::ScopedSaveState ss (g);
  1569. if (! (ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, {}) && g.isClipEmpty()))
  1570. paint (g);
  1571. }
  1572. for (int i = 0; i < childComponentList.size(); ++i)
  1573. {
  1574. auto& child = *childComponentList.getUnchecked (i);
  1575. if (child.isVisible())
  1576. {
  1577. if (child.affineTransform != nullptr)
  1578. {
  1579. Graphics::ScopedSaveState ss (g);
  1580. g.addTransform (*child.affineTransform);
  1581. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  1582. child.paintWithinParentContext (g);
  1583. }
  1584. else if (clipBounds.intersects (child.getBounds()))
  1585. {
  1586. Graphics::ScopedSaveState ss (g);
  1587. if (child.flags.dontClipGraphicsFlag)
  1588. {
  1589. child.paintWithinParentContext (g);
  1590. }
  1591. else if (g.reduceClipRegion (child.getBounds()))
  1592. {
  1593. bool nothingClipped = true;
  1594. for (int j = i + 1; j < childComponentList.size(); ++j)
  1595. {
  1596. auto& sibling = *childComponentList.getUnchecked (j);
  1597. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == nullptr)
  1598. {
  1599. nothingClipped = false;
  1600. g.excludeClipRegion (sibling.getBounds());
  1601. }
  1602. }
  1603. if (nothingClipped || ! g.isClipEmpty())
  1604. child.paintWithinParentContext (g);
  1605. }
  1606. }
  1607. }
  1608. }
  1609. Graphics::ScopedSaveState ss (g);
  1610. paintOverChildren (g);
  1611. }
  1612. void Component::paintEntireComponent (Graphics& g, bool ignoreAlphaLevel)
  1613. {
  1614. // If sizing a top-level-window and the OS paint message is delivered synchronously
  1615. // before resized() is called, then we'll invoke the callback here, to make sure
  1616. // the components inside have had a chance to sort their sizes out..
  1617. #if JUCE_DEBUG
  1618. if (! flags.isInsidePaintCall) // (avoids an assertion in plugins hosted in WaveLab)
  1619. #endif
  1620. sendMovedResizedMessagesIfPending();
  1621. #if JUCE_DEBUG
  1622. flags.isInsidePaintCall = true;
  1623. #endif
  1624. if (effect != nullptr)
  1625. {
  1626. auto scale = g.getInternalContext().getPhysicalPixelScaleFactor();
  1627. auto scaledBounds = getLocalBounds() * scale;
  1628. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  1629. scaledBounds.getWidth(), scaledBounds.getHeight(), ! flags.opaqueFlag);
  1630. {
  1631. Graphics g2 (effectImage);
  1632. g2.addTransform (AffineTransform::scale ((float) scaledBounds.getWidth() / (float) getWidth(),
  1633. (float) scaledBounds.getHeight() / (float) getHeight()));
  1634. paintComponentAndChildren (g2);
  1635. }
  1636. Graphics::ScopedSaveState ss (g);
  1637. g.addTransform (AffineTransform::scale (1.0f / scale));
  1638. effect->applyEffect (effectImage, g, scale, ignoreAlphaLevel ? 1.0f : getAlpha());
  1639. }
  1640. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  1641. {
  1642. if (componentTransparency < 255)
  1643. {
  1644. g.beginTransparencyLayer (getAlpha());
  1645. paintComponentAndChildren (g);
  1646. g.endTransparencyLayer();
  1647. }
  1648. }
  1649. else
  1650. {
  1651. paintComponentAndChildren (g);
  1652. }
  1653. #if JUCE_DEBUG
  1654. flags.isInsidePaintCall = false;
  1655. #endif
  1656. }
  1657. void Component::setPaintingIsUnclipped (bool shouldPaintWithoutClipping) noexcept
  1658. {
  1659. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  1660. }
  1661. bool Component::isPaintingUnclipped() const noexcept
  1662. {
  1663. return flags.dontClipGraphicsFlag;
  1664. }
  1665. //==============================================================================
  1666. Image Component::createComponentSnapshot (Rectangle<int> areaToGrab,
  1667. bool clipImageToComponentBounds, float scaleFactor)
  1668. {
  1669. auto r = areaToGrab;
  1670. if (clipImageToComponentBounds)
  1671. r = r.getIntersection (getLocalBounds());
  1672. if (r.isEmpty())
  1673. return {};
  1674. auto w = roundToInt (scaleFactor * (float) r.getWidth());
  1675. auto h = roundToInt (scaleFactor * (float) r.getHeight());
  1676. Image image (flags.opaqueFlag ? Image::RGB : Image::ARGB, w, h, true);
  1677. Graphics g (image);
  1678. if (w != getWidth() || h != getHeight())
  1679. g.addTransform (AffineTransform::scale ((float) w / (float) r.getWidth(),
  1680. (float) h / (float) r.getHeight()));
  1681. g.setOrigin (-r.getPosition());
  1682. paintEntireComponent (g, true);
  1683. return image;
  1684. }
  1685. void Component::setComponentEffect (ImageEffectFilter* newEffect)
  1686. {
  1687. if (effect != newEffect)
  1688. {
  1689. effect = newEffect;
  1690. repaint();
  1691. }
  1692. }
  1693. //==============================================================================
  1694. LookAndFeel& Component::getLookAndFeel() const noexcept
  1695. {
  1696. for (auto* c = this; c != nullptr; c = c->parentComponent)
  1697. if (auto lf = c->lookAndFeel.get())
  1698. return *lf;
  1699. return LookAndFeel::getDefaultLookAndFeel();
  1700. }
  1701. void Component::setLookAndFeel (LookAndFeel* newLookAndFeel)
  1702. {
  1703. if (lookAndFeel != newLookAndFeel)
  1704. {
  1705. lookAndFeel = newLookAndFeel;
  1706. sendLookAndFeelChange();
  1707. }
  1708. }
  1709. void Component::lookAndFeelChanged() {}
  1710. void Component::colourChanged() {}
  1711. void Component::sendLookAndFeelChange()
  1712. {
  1713. const WeakReference<Component> safePointer (this);
  1714. repaint();
  1715. lookAndFeelChanged();
  1716. if (safePointer != nullptr)
  1717. {
  1718. colourChanged();
  1719. if (safePointer != nullptr)
  1720. {
  1721. for (int i = childComponentList.size(); --i >= 0;)
  1722. {
  1723. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  1724. if (safePointer == nullptr)
  1725. return;
  1726. i = jmin (i, childComponentList.size());
  1727. }
  1728. }
  1729. }
  1730. }
  1731. Colour Component::findColour (int colourID, bool inheritFromParent) const
  1732. {
  1733. if (auto* v = properties.getVarPointer (ComponentHelpers::getColourPropertyID (colourID)))
  1734. return Colour ((uint32) static_cast<int> (*v));
  1735. if (inheritFromParent && parentComponent != nullptr
  1736. && (lookAndFeel == nullptr || ! lookAndFeel->isColourSpecified (colourID)))
  1737. return parentComponent->findColour (colourID, true);
  1738. return getLookAndFeel().findColour (colourID);
  1739. }
  1740. bool Component::isColourSpecified (int colourID) const
  1741. {
  1742. return properties.contains (ComponentHelpers::getColourPropertyID (colourID));
  1743. }
  1744. void Component::removeColour (int colourID)
  1745. {
  1746. if (properties.remove (ComponentHelpers::getColourPropertyID (colourID)))
  1747. colourChanged();
  1748. }
  1749. void Component::setColour (int colourID, Colour colour)
  1750. {
  1751. if (properties.set (ComponentHelpers::getColourPropertyID (colourID), (int) colour.getARGB()))
  1752. colourChanged();
  1753. }
  1754. void Component::copyAllExplicitColoursTo (Component& target) const
  1755. {
  1756. bool changed = false;
  1757. for (int i = properties.size(); --i >= 0;)
  1758. {
  1759. auto name = properties.getName(i);
  1760. if (name.toString().startsWith (colourPropertyPrefix))
  1761. if (target.properties.set (name, properties [name]))
  1762. changed = true;
  1763. }
  1764. if (changed)
  1765. target.colourChanged();
  1766. }
  1767. //==============================================================================
  1768. Component::Positioner::Positioner (Component& c) noexcept : component (c)
  1769. {
  1770. }
  1771. Component::Positioner* Component::getPositioner() const noexcept
  1772. {
  1773. return positioner.get();
  1774. }
  1775. void Component::setPositioner (Positioner* newPositioner)
  1776. {
  1777. // You can only assign a positioner to the component that it was created for!
  1778. jassert (newPositioner == nullptr || this == &(newPositioner->getComponent()));
  1779. positioner.reset (newPositioner);
  1780. }
  1781. //==============================================================================
  1782. Rectangle<int> Component::getLocalBounds() const noexcept
  1783. {
  1784. return boundsRelativeToParent.withZeroOrigin();
  1785. }
  1786. Rectangle<int> Component::getBoundsInParent() const noexcept
  1787. {
  1788. return affineTransform == nullptr ? boundsRelativeToParent
  1789. : boundsRelativeToParent.transformedBy (*affineTransform);
  1790. }
  1791. //==============================================================================
  1792. void Component::mouseEnter (const MouseEvent&) {}
  1793. void Component::mouseExit (const MouseEvent&) {}
  1794. void Component::mouseDown (const MouseEvent&) {}
  1795. void Component::mouseUp (const MouseEvent&) {}
  1796. void Component::mouseDrag (const MouseEvent&) {}
  1797. void Component::mouseMove (const MouseEvent&) {}
  1798. void Component::mouseDoubleClick (const MouseEvent&) {}
  1799. void Component::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  1800. {
  1801. // the base class just passes this event up to its parent..
  1802. if (parentComponent != nullptr)
  1803. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent), wheel);
  1804. }
  1805. void Component::mouseMagnify (const MouseEvent& e, float magnifyAmount)
  1806. {
  1807. // the base class just passes this event up to its parent..
  1808. if (parentComponent != nullptr)
  1809. parentComponent->mouseMagnify (e.getEventRelativeTo (parentComponent), magnifyAmount);
  1810. }
  1811. //==============================================================================
  1812. void Component::resized() {}
  1813. void Component::moved() {}
  1814. void Component::childBoundsChanged (Component*) {}
  1815. void Component::parentSizeChanged() {}
  1816. void Component::addComponentListener (ComponentListener* newListener)
  1817. {
  1818. // if component methods are being called from threads other than the message
  1819. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1820. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  1821. if (getParentComponent() != nullptr)
  1822. {
  1823. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  1824. }
  1825. #endif
  1826. componentListeners.add (newListener);
  1827. }
  1828. void Component::removeComponentListener (ComponentListener* listenerToRemove)
  1829. {
  1830. componentListeners.remove (listenerToRemove);
  1831. }
  1832. //==============================================================================
  1833. void Component::inputAttemptWhenModal()
  1834. {
  1835. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1836. getLookAndFeel().playAlertSound();
  1837. }
  1838. bool Component::canModalEventBeSentToComponent (const Component*)
  1839. {
  1840. return false;
  1841. }
  1842. void Component::internalModalInputAttempt()
  1843. {
  1844. if (auto* current = getCurrentlyModalComponent())
  1845. current->inputAttemptWhenModal();
  1846. }
  1847. //==============================================================================
  1848. void Component::postCommandMessage (int commandID)
  1849. {
  1850. WeakReference<Component> target (this);
  1851. MessageManager::callAsync ([=]
  1852. {
  1853. if (auto* c = target.get())
  1854. c->handleCommandMessage (commandID);
  1855. });
  1856. }
  1857. void Component::handleCommandMessage (int)
  1858. {
  1859. // used by subclasses
  1860. }
  1861. //==============================================================================
  1862. void Component::addMouseListener (MouseListener* newListener,
  1863. bool wantsEventsForAllNestedChildComponents)
  1864. {
  1865. // if component methods are being called from threads other than the message
  1866. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1867. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  1868. // If you register a component as a mouselistener for itself, it'll receive all the events
  1869. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  1870. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  1871. if (mouseListeners == nullptr)
  1872. mouseListeners.reset (new MouseListenerList());
  1873. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  1874. }
  1875. void Component::removeMouseListener (MouseListener* listenerToRemove)
  1876. {
  1877. // if component methods are being called from threads other than the message
  1878. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1879. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  1880. if (mouseListeners != nullptr)
  1881. mouseListeners->removeListener (listenerToRemove);
  1882. }
  1883. //==============================================================================
  1884. void Component::internalMouseEnter (MouseInputSource source, Point<float> relativePos, Time time)
  1885. {
  1886. if (isCurrentlyBlockedByAnotherModalComponent())
  1887. {
  1888. // if something else is modal, always just show a normal mouse cursor
  1889. source.showMouseCursor (MouseCursor::NormalCursor);
  1890. return;
  1891. }
  1892. if (flags.repaintOnMouseActivityFlag)
  1893. repaint();
  1894. BailOutChecker checker (this);
  1895. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), MouseInputSource::invalidPressure,
  1896. MouseInputSource::invalidOrientation, MouseInputSource::invalidRotation,
  1897. MouseInputSource::invalidTiltX, MouseInputSource::invalidTiltY,
  1898. this, this, time, relativePos, time, 0, false);
  1899. mouseEnter (me);
  1900. flags.cachedMouseInsideComponent = true;
  1901. if (checker.shouldBailOut())
  1902. return;
  1903. Desktop::getInstance().getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseEnter (me); });
  1904. MouseListenerList::template sendMouseEvent<const MouseEvent&> (*this, checker, &MouseListener::mouseEnter, me);
  1905. }
  1906. void Component::internalMouseExit (MouseInputSource source, Point<float> relativePos, Time time)
  1907. {
  1908. if (isCurrentlyBlockedByAnotherModalComponent())
  1909. {
  1910. // if something else is modal, always just show a normal mouse cursor
  1911. source.showMouseCursor (MouseCursor::NormalCursor);
  1912. return;
  1913. }
  1914. if (flags.repaintOnMouseActivityFlag)
  1915. repaint();
  1916. flags.cachedMouseInsideComponent = false;
  1917. BailOutChecker checker (this);
  1918. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), MouseInputSource::invalidPressure,
  1919. MouseInputSource::invalidOrientation, MouseInputSource::invalidRotation,
  1920. MouseInputSource::invalidTiltX, MouseInputSource::invalidTiltY,
  1921. this, this, time, relativePos, time, 0, false);
  1922. mouseExit (me);
  1923. if (checker.shouldBailOut())
  1924. return;
  1925. Desktop::getInstance().getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseExit (me); });
  1926. MouseListenerList::template sendMouseEvent<const MouseEvent&> (*this, checker, &MouseListener::mouseExit, me);
  1927. }
  1928. void Component::internalMouseDown (MouseInputSource source, Point<float> relativePos, Time time,
  1929. float pressure, float orientation, float rotation, float tiltX, float tiltY)
  1930. {
  1931. auto& desktop = Desktop::getInstance();
  1932. BailOutChecker checker (this);
  1933. if (isCurrentlyBlockedByAnotherModalComponent())
  1934. {
  1935. flags.mouseDownWasBlocked = true;
  1936. internalModalInputAttempt();
  1937. if (checker.shouldBailOut())
  1938. return;
  1939. // If processing the input attempt has exited the modal loop, we'll allow the event
  1940. // to be delivered..
  1941. if (isCurrentlyBlockedByAnotherModalComponent())
  1942. {
  1943. // allow blocked mouse-events to go to global listeners..
  1944. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), pressure,
  1945. orientation, rotation, tiltX, tiltY, this, this, time, relativePos,
  1946. time, source.getNumberOfMultipleClicks(), false);
  1947. desktop.getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseDown (me); });
  1948. return;
  1949. }
  1950. }
  1951. flags.mouseDownWasBlocked = false;
  1952. for (auto* c = this; c != nullptr; c = c->parentComponent)
  1953. {
  1954. if (c->isBroughtToFrontOnMouseClick())
  1955. {
  1956. c->toFront (true);
  1957. if (checker.shouldBailOut())
  1958. return;
  1959. }
  1960. }
  1961. if (! flags.dontFocusOnMouseClickFlag)
  1962. {
  1963. grabKeyboardFocusInternal (focusChangedByMouseClick, true);
  1964. if (checker.shouldBailOut())
  1965. return;
  1966. }
  1967. if (flags.repaintOnMouseActivityFlag)
  1968. repaint();
  1969. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), pressure,
  1970. orientation, rotation, tiltX, tiltY, this, this, time, relativePos,
  1971. time, source.getNumberOfMultipleClicks(), false);
  1972. mouseDown (me);
  1973. if (checker.shouldBailOut())
  1974. return;
  1975. desktop.getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseDown (me); });
  1976. MouseListenerList::template sendMouseEvent<const MouseEvent&> (*this, checker, &MouseListener::mouseDown, me);
  1977. }
  1978. void Component::internalMouseUp (MouseInputSource source, Point<float> relativePos, Time time,
  1979. const ModifierKeys oldModifiers, float pressure, float orientation, float rotation, float tiltX, float tiltY)
  1980. {
  1981. if (flags.mouseDownWasBlocked && isCurrentlyBlockedByAnotherModalComponent())
  1982. return;
  1983. BailOutChecker checker (this);
  1984. if (flags.repaintOnMouseActivityFlag)
  1985. repaint();
  1986. const MouseEvent me (source, relativePos, oldModifiers, pressure, orientation,
  1987. rotation, tiltX, tiltY, this, this, time,
  1988. getLocalPoint (nullptr, source.getLastMouseDownPosition()),
  1989. source.getLastMouseDownTime(),
  1990. source.getNumberOfMultipleClicks(),
  1991. source.isLongPressOrDrag());
  1992. mouseUp (me);
  1993. if (checker.shouldBailOut())
  1994. return;
  1995. auto& desktop = Desktop::getInstance();
  1996. desktop.getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseUp (me); });
  1997. MouseListenerList::template sendMouseEvent<const MouseEvent&> (*this, checker, &MouseListener::mouseUp, me);
  1998. if (checker.shouldBailOut())
  1999. return;
  2000. // check for double-click
  2001. if (me.getNumberOfClicks() >= 2)
  2002. {
  2003. mouseDoubleClick (me);
  2004. if (checker.shouldBailOut())
  2005. return;
  2006. desktop.mouseListeners.callChecked (checker, [&] (MouseListener& l) { l.mouseDoubleClick (me); });
  2007. MouseListenerList::template sendMouseEvent<const MouseEvent&> (*this, checker, &MouseListener::mouseDoubleClick, me);
  2008. }
  2009. }
  2010. void Component::internalMouseDrag (MouseInputSource source, Point<float> relativePos, Time time,
  2011. float pressure, float orientation, float rotation, float tiltX, float tiltY)
  2012. {
  2013. if (! isCurrentlyBlockedByAnotherModalComponent())
  2014. {
  2015. BailOutChecker checker (this);
  2016. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  2017. pressure, orientation, rotation, tiltX, tiltY, this, this, time,
  2018. getLocalPoint (nullptr, source.getLastMouseDownPosition()),
  2019. source.getLastMouseDownTime(),
  2020. source.getNumberOfMultipleClicks(),
  2021. source.isLongPressOrDrag());
  2022. mouseDrag (me);
  2023. if (checker.shouldBailOut())
  2024. return;
  2025. Desktop::getInstance().getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseDrag (me); });
  2026. MouseListenerList::template sendMouseEvent<const MouseEvent&> (*this, checker, &MouseListener::mouseDrag, me);
  2027. }
  2028. }
  2029. void Component::internalMouseMove (MouseInputSource source, Point<float> relativePos, Time time)
  2030. {
  2031. auto& desktop = Desktop::getInstance();
  2032. if (isCurrentlyBlockedByAnotherModalComponent())
  2033. {
  2034. // allow blocked mouse-events to go to global listeners..
  2035. desktop.sendMouseMove();
  2036. }
  2037. else
  2038. {
  2039. BailOutChecker checker (this);
  2040. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), MouseInputSource::invalidPressure,
  2041. MouseInputSource::invalidOrientation, MouseInputSource::invalidRotation,
  2042. MouseInputSource::invalidTiltX, MouseInputSource::invalidTiltY,
  2043. this, this, time, relativePos, time, 0, false);
  2044. mouseMove (me);
  2045. if (checker.shouldBailOut())
  2046. return;
  2047. desktop.getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseMove (me); });
  2048. MouseListenerList::template sendMouseEvent<const MouseEvent&> (*this, checker, &MouseListener::mouseMove, me);
  2049. }
  2050. }
  2051. void Component::internalMouseWheel (MouseInputSource source, Point<float> relativePos,
  2052. Time time, const MouseWheelDetails& wheel)
  2053. {
  2054. auto& desktop = Desktop::getInstance();
  2055. BailOutChecker checker (this);
  2056. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), MouseInputSource::invalidPressure,
  2057. MouseInputSource::invalidOrientation, MouseInputSource::invalidRotation,
  2058. MouseInputSource::invalidTiltX, MouseInputSource::invalidTiltY,
  2059. this, this, time, relativePos, time, 0, false);
  2060. if (isCurrentlyBlockedByAnotherModalComponent())
  2061. {
  2062. // allow blocked mouse-events to go to global listeners..
  2063. desktop.mouseListeners.callChecked (checker, [&] (MouseListener& l) { l.mouseWheelMove (me, wheel); });
  2064. }
  2065. else
  2066. {
  2067. mouseWheelMove (me, wheel);
  2068. if (checker.shouldBailOut())
  2069. return;
  2070. desktop.mouseListeners.callChecked (checker, [&] (MouseListener& l) { l.mouseWheelMove (me, wheel); });
  2071. if (! checker.shouldBailOut())
  2072. MouseListenerList::template sendMouseEvent<const MouseEvent&, const MouseWheelDetails&> (*this, checker, &MouseListener::mouseWheelMove, me, wheel);
  2073. }
  2074. }
  2075. void Component::internalMagnifyGesture (MouseInputSource source, Point<float> relativePos,
  2076. Time time, float amount)
  2077. {
  2078. auto& desktop = Desktop::getInstance();
  2079. BailOutChecker checker (this);
  2080. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), MouseInputSource::invalidPressure,
  2081. MouseInputSource::invalidOrientation, MouseInputSource::invalidRotation,
  2082. MouseInputSource::invalidTiltX, MouseInputSource::invalidTiltY,
  2083. this, this, time, relativePos, time, 0, false);
  2084. if (isCurrentlyBlockedByAnotherModalComponent())
  2085. {
  2086. // allow blocked mouse-events to go to global listeners..
  2087. desktop.mouseListeners.callChecked (checker, [&] (MouseListener& l) { l.mouseMagnify (me, amount); });
  2088. }
  2089. else
  2090. {
  2091. mouseMagnify (me, amount);
  2092. if (checker.shouldBailOut())
  2093. return;
  2094. desktop.mouseListeners.callChecked (checker, [&] (MouseListener& l) { l.mouseMagnify (me, amount); });
  2095. if (! checker.shouldBailOut())
  2096. MouseListenerList::template sendMouseEvent<const MouseEvent&, float> (*this, checker, &MouseListener::mouseMagnify, me, amount);
  2097. }
  2098. }
  2099. void Component::sendFakeMouseMove() const
  2100. {
  2101. if (flags.ignoresMouseClicksFlag && ! flags.allowChildMouseClicksFlag)
  2102. return;
  2103. auto mainMouse = Desktop::getInstance().getMainMouseSource();
  2104. if (! mainMouse.isDragging())
  2105. mainMouse.triggerFakeMove();
  2106. }
  2107. void JUCE_CALLTYPE Component::beginDragAutoRepeat (int interval)
  2108. {
  2109. Desktop::getInstance().beginDragAutoRepeat (interval);
  2110. }
  2111. //==============================================================================
  2112. void Component::broughtToFront()
  2113. {
  2114. }
  2115. void Component::internalBroughtToFront()
  2116. {
  2117. if (flags.hasHeavyweightPeerFlag)
  2118. Desktop::getInstance().componentBroughtToFront (this);
  2119. BailOutChecker checker (this);
  2120. broughtToFront();
  2121. if (checker.shouldBailOut())
  2122. return;
  2123. componentListeners.callChecked (checker, [this] (ComponentListener& l) { l.componentBroughtToFront (*this); });
  2124. if (checker.shouldBailOut())
  2125. return;
  2126. // When brought to the front and there's a modal component blocking this one,
  2127. // we need to bring the modal one to the front instead..
  2128. if (auto* cm = getCurrentlyModalComponent())
  2129. if (cm->getTopLevelComponent() != getTopLevelComponent())
  2130. ModalComponentManager::getInstance()->bringModalComponentsToFront (false); // very important that this is false, otherwise in Windows,
  2131. // non-front components can't get focus when another modal comp is
  2132. // active, and therefore can't receive mouse-clicks
  2133. }
  2134. //==============================================================================
  2135. void Component::focusGained (FocusChangeType) {}
  2136. void Component::focusLost (FocusChangeType) {}
  2137. void Component::focusOfChildComponentChanged (FocusChangeType) {}
  2138. void Component::internalKeyboardFocusGain (FocusChangeType cause)
  2139. {
  2140. internalKeyboardFocusGain (cause, WeakReference<Component> (this));
  2141. }
  2142. void Component::internalKeyboardFocusGain (FocusChangeType cause,
  2143. const WeakReference<Component>& safePointer)
  2144. {
  2145. focusGained (cause);
  2146. if (safePointer != nullptr)
  2147. {
  2148. if (auto* handler = getAccessibilityHandler())
  2149. handler->grabFocus();
  2150. internalChildKeyboardFocusChange (cause, safePointer);
  2151. }
  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. std::unique_ptr<AccessibilityHandler> Component::createAccessibilityHandler()
  2514. {
  2515. return std::make_unique<AccessibilityHandler> (*this, AccessibilityRole::unspecified);
  2516. }
  2517. void Component::invalidateAccessibilityHandler()
  2518. {
  2519. accessibilityHandler = nullptr;
  2520. }
  2521. AccessibilityHandler* Component::getAccessibilityHandler()
  2522. {
  2523. if (flags.accessibilityIgnoredFlag)
  2524. return nullptr;
  2525. if (accessibilityHandler == nullptr
  2526. || accessibilityHandler->getTypeIndex() != std::type_index (typeid (*this)))
  2527. {
  2528. accessibilityHandler = createAccessibilityHandler();
  2529. }
  2530. return accessibilityHandler.get();
  2531. }
  2532. } // namespace juce