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

3056 lines
98KB

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