Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3030 lines
96KB

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