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.

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