The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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