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.

3050 lines
97KB

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