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.

2971 lines
96KB

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