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.

3227 lines
107KB

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