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.

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