The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3311 lines
109KB

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