Audio plugin host https://kx.studio/carla
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.

3329 lines
111KB

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