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.

3287 lines
108KB

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