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.

3030 lines
99KB

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