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.

3173 lines
104KB

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