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.

2925 lines
90KB

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