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.

3037 lines
91KB

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