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.

3299 lines
109KB

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