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

2917 lines
91KB

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