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

3089 lines
98KB

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