Audio plugin host https://kx.studio/carla
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.

3046 lines
97KB

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