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.

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