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.

3044 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, 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, 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 (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. 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 (isAlwaysOnTop())
  545. peer->setAlwaysOnTop (true);
  546. peer->setConstrainer (currentConstainer);
  547. repaint();
  548. }
  549. internalHierarchyChanged();
  550. }
  551. }
  552. void Component::removeFromDesktop()
  553. {
  554. // if component methods are being called from threads other than the message
  555. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  556. CHECK_MESSAGE_MANAGER_IS_LOCKED
  557. if (flags.hasHeavyweightPeerFlag)
  558. {
  559. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  560. flags.hasHeavyweightPeerFlag = false;
  561. jassert (peer != nullptr);
  562. delete peer;
  563. Desktop::getInstance().removeDesktopComponent (this);
  564. }
  565. }
  566. bool Component::isOnDesktop() const noexcept
  567. {
  568. return flags.hasHeavyweightPeerFlag;
  569. }
  570. void Component::userTriedToCloseWindow()
  571. {
  572. /* This means that the user's trying to get rid of your window with the 'close window' system
  573. menu option (on windows) or possibly the task manager - you should really handle this
  574. and delete or hide your component in an appropriate way.
  575. If you want to ignore the event and don't want to trigger this assertion, just override
  576. this method and do nothing.
  577. */
  578. jassertfalse;
  579. }
  580. void Component::minimisationStateChanged (bool)
  581. {
  582. }
  583. //==============================================================================
  584. void Component::setOpaque (const bool shouldBeOpaque)
  585. {
  586. if (shouldBeOpaque != flags.opaqueFlag)
  587. {
  588. flags.opaqueFlag = shouldBeOpaque;
  589. if (flags.hasHeavyweightPeerFlag)
  590. {
  591. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  592. if (peer != nullptr)
  593. {
  594. // to make it recreate the heavyweight window
  595. addToDesktop (peer->getStyleFlags());
  596. }
  597. }
  598. repaint();
  599. }
  600. }
  601. bool Component::isOpaque() const noexcept
  602. {
  603. return flags.opaqueFlag;
  604. }
  605. //==============================================================================
  606. void Component::setCachedComponentImage (CachedComponentImage* newCachedImage)
  607. {
  608. cachedImage = newCachedImage;
  609. }
  610. void Component::setBufferedToImage (const bool shouldBeBuffered)
  611. {
  612. // This assertion means that this component is already using a custom CachedComponentImage,
  613. // so by calling setBufferedToImage, you'll be deleting the custom one - this is almost certainly
  614. // not what you wanted to happen... If you really do know what you're doing here, and want to
  615. // avoid this assertion, just call setCachedComponentImage (nullptr) before setBufferedToImage().
  616. jassert (cachedImage == nullptr || dynamic_cast <StandardCachedComponentImage*> (cachedImage.get()) != nullptr);
  617. if (shouldBeBuffered)
  618. {
  619. if (cachedImage == nullptr)
  620. cachedImage = new StandardCachedComponentImage (*this);
  621. }
  622. else
  623. {
  624. cachedImage = nullptr;
  625. }
  626. }
  627. //==============================================================================
  628. void Component::moveChildInternal (const int sourceIndex, const int destIndex)
  629. {
  630. if (sourceIndex != destIndex)
  631. {
  632. Component* const c = childComponentList.getUnchecked (sourceIndex);
  633. jassert (c != nullptr);
  634. c->repaintParent();
  635. childComponentList.move (sourceIndex, destIndex);
  636. sendFakeMouseMove();
  637. internalChildrenChanged();
  638. }
  639. }
  640. void Component::toFront (const bool setAsForeground)
  641. {
  642. // if component methods are being called from threads other than the message
  643. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  644. CHECK_MESSAGE_MANAGER_IS_LOCKED
  645. if (flags.hasHeavyweightPeerFlag)
  646. {
  647. ComponentPeer* const peer = getPeer();
  648. if (peer != nullptr)
  649. {
  650. peer->toFront (setAsForeground);
  651. if (setAsForeground && ! hasKeyboardFocus (true))
  652. grabKeyboardFocus();
  653. }
  654. }
  655. else if (parentComponent != nullptr)
  656. {
  657. const Array<Component*>& childList = parentComponent->childComponentList;
  658. if (childList.getLast() != this)
  659. {
  660. const int index = childList.indexOf (this);
  661. if (index >= 0)
  662. {
  663. int insertIndex = -1;
  664. if (! flags.alwaysOnTopFlag)
  665. {
  666. insertIndex = childList.size() - 1;
  667. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  668. --insertIndex;
  669. }
  670. parentComponent->moveChildInternal (index, insertIndex);
  671. }
  672. }
  673. if (setAsForeground)
  674. {
  675. internalBroughtToFront();
  676. grabKeyboardFocus();
  677. }
  678. }
  679. }
  680. void Component::toBehind (Component* const other)
  681. {
  682. if (other != nullptr && other != this)
  683. {
  684. // the two components must belong to the same parent..
  685. jassert (parentComponent == other->parentComponent);
  686. if (parentComponent != nullptr)
  687. {
  688. const Array<Component*>& childList = parentComponent->childComponentList;
  689. const int index = childList.indexOf (this);
  690. if (index >= 0 && childList [index + 1] != other)
  691. {
  692. int otherIndex = childList.indexOf (other);
  693. if (otherIndex >= 0)
  694. {
  695. if (index < otherIndex)
  696. --otherIndex;
  697. parentComponent->moveChildInternal (index, otherIndex);
  698. }
  699. }
  700. }
  701. else if (isOnDesktop())
  702. {
  703. jassert (other->isOnDesktop());
  704. if (other->isOnDesktop())
  705. {
  706. ComponentPeer* const us = getPeer();
  707. ComponentPeer* const them = other->getPeer();
  708. jassert (us != nullptr && them != nullptr);
  709. if (us != nullptr && them != nullptr)
  710. us->toBehind (them);
  711. }
  712. }
  713. }
  714. }
  715. void Component::toBack()
  716. {
  717. if (isOnDesktop())
  718. {
  719. jassertfalse; //xxx need to add this to native window
  720. }
  721. else if (parentComponent != nullptr)
  722. {
  723. const Array<Component*>& childList = parentComponent->childComponentList;
  724. if (childList.getFirst() != this)
  725. {
  726. const int index = childList.indexOf (this);
  727. if (index > 0)
  728. {
  729. int insertIndex = 0;
  730. if (flags.alwaysOnTopFlag)
  731. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  732. ++insertIndex;
  733. parentComponent->moveChildInternal (index, insertIndex);
  734. }
  735. }
  736. }
  737. }
  738. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  739. {
  740. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  741. {
  742. BailOutChecker checker (this);
  743. flags.alwaysOnTopFlag = shouldStayOnTop;
  744. if (isOnDesktop())
  745. {
  746. ComponentPeer* const peer = getPeer();
  747. jassert (peer != nullptr);
  748. if (peer != nullptr)
  749. {
  750. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  751. {
  752. // some kinds of peer can't change their always-on-top status, so
  753. // for these, we'll need to create a new window
  754. const int oldFlags = peer->getStyleFlags();
  755. removeFromDesktop();
  756. addToDesktop (oldFlags);
  757. }
  758. }
  759. }
  760. if (shouldStayOnTop && ! checker.shouldBailOut())
  761. toFront (false);
  762. if (! checker.shouldBailOut())
  763. internalHierarchyChanged();
  764. }
  765. }
  766. bool Component::isAlwaysOnTop() const noexcept
  767. {
  768. return flags.alwaysOnTopFlag;
  769. }
  770. //==============================================================================
  771. int Component::proportionOfWidth (const float proportion) const noexcept
  772. {
  773. return roundToInt (proportion * bounds.getWidth());
  774. }
  775. int Component::proportionOfHeight (const float proportion) const noexcept
  776. {
  777. return roundToInt (proportion * bounds.getHeight());
  778. }
  779. int Component::getParentWidth() const noexcept
  780. {
  781. return parentComponent != nullptr ? parentComponent->getWidth()
  782. : getParentMonitorArea().getWidth();
  783. }
  784. int Component::getParentHeight() const noexcept
  785. {
  786. return parentComponent != nullptr ? parentComponent->getHeight()
  787. : getParentMonitorArea().getHeight();
  788. }
  789. int Component::getScreenX() const { return getScreenPosition().x; }
  790. int Component::getScreenY() const { return getScreenPosition().y; }
  791. Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  792. Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  793. Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  794. {
  795. return ComponentHelpers::convertCoordinate (this, source, point);
  796. }
  797. Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  798. {
  799. return ComponentHelpers::convertCoordinate (this, source, area);
  800. }
  801. Point<int> Component::localPointToGlobal (const Point<int>& point) const
  802. {
  803. return ComponentHelpers::convertCoordinate (nullptr, this, point);
  804. }
  805. Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  806. {
  807. return ComponentHelpers::convertCoordinate (nullptr, this, area);
  808. }
  809. /* Deprecated methods... */
  810. Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  811. {
  812. return localPointToGlobal (relativePosition);
  813. }
  814. Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  815. {
  816. return getLocalPoint (nullptr, screenPosition);
  817. }
  818. Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  819. {
  820. return targetComponent == nullptr ? localPointToGlobal (positionRelativeToThis)
  821. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  822. }
  823. //==============================================================================
  824. void Component::setBounds (const int x, const int y, int w, int h)
  825. {
  826. // if component methods are being called from threads other than the message
  827. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  828. CHECK_MESSAGE_MANAGER_IS_LOCKED
  829. if (w < 0) w = 0;
  830. if (h < 0) h = 0;
  831. const bool wasResized = (getWidth() != w || getHeight() != h);
  832. const bool wasMoved = (getX() != x || getY() != y);
  833. #if JUCE_DEBUG
  834. // It's a very bad idea to try to resize a window during its paint() method!
  835. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  836. #endif
  837. if (wasMoved || wasResized)
  838. {
  839. const bool showing = isShowing();
  840. if (showing)
  841. {
  842. // send a fake mouse move to trigger enter/exit messages if needed..
  843. sendFakeMouseMove();
  844. if (! flags.hasHeavyweightPeerFlag)
  845. repaintParent();
  846. }
  847. bounds.setBounds (x, y, w, h);
  848. if (showing)
  849. {
  850. if (wasResized)
  851. repaint();
  852. else if (! flags.hasHeavyweightPeerFlag)
  853. repaintParent();
  854. }
  855. else if (cachedImage != nullptr)
  856. {
  857. cachedImage->invalidateAll();
  858. }
  859. if (flags.hasHeavyweightPeerFlag)
  860. {
  861. ComponentPeer* const peer = getPeer();
  862. if (peer != nullptr)
  863. {
  864. if (wasMoved && wasResized)
  865. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  866. else if (wasMoved)
  867. peer->setPosition (getX(), getY());
  868. else if (wasResized)
  869. peer->setSize (getWidth(), getHeight());
  870. }
  871. }
  872. sendMovedResizedMessages (wasMoved, wasResized);
  873. }
  874. }
  875. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  876. {
  877. BailOutChecker checker (this);
  878. if (wasMoved)
  879. {
  880. moved();
  881. if (checker.shouldBailOut())
  882. return;
  883. }
  884. if (wasResized)
  885. {
  886. resized();
  887. if (checker.shouldBailOut())
  888. return;
  889. for (int i = childComponentList.size(); --i >= 0;)
  890. {
  891. childComponentList.getUnchecked(i)->parentSizeChanged();
  892. if (checker.shouldBailOut())
  893. return;
  894. i = jmin (i, childComponentList.size());
  895. }
  896. }
  897. if (parentComponent != nullptr)
  898. parentComponent->childBoundsChanged (this);
  899. if (! checker.shouldBailOut())
  900. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  901. *this, wasMoved, wasResized);
  902. }
  903. void Component::setSize (const int w, const int h)
  904. {
  905. setBounds (getX(), getY(), w, h);
  906. }
  907. void Component::setTopLeftPosition (const int x, const int y)
  908. {
  909. setBounds (x, y, getWidth(), getHeight());
  910. }
  911. void Component::setTopLeftPosition (const Point<int>& pos)
  912. {
  913. setBounds (pos.x, pos.y, getWidth(), getHeight());
  914. }
  915. void Component::setTopRightPosition (const int x, const int y)
  916. {
  917. setTopLeftPosition (x - getWidth(), y);
  918. }
  919. void Component::setBounds (const Rectangle<int>& r)
  920. {
  921. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  922. }
  923. void Component::setBounds (const RelativeRectangle& newBounds)
  924. {
  925. newBounds.applyToComponent (*this);
  926. }
  927. void Component::setBounds (const String& newBoundsExpression)
  928. {
  929. setBounds (RelativeRectangle (newBoundsExpression));
  930. }
  931. void Component::setBoundsRelative (const float x, const float y,
  932. const float w, const float h)
  933. {
  934. const int pw = getParentWidth();
  935. const int ph = getParentHeight();
  936. setBounds (roundToInt (x * pw),
  937. roundToInt (y * ph),
  938. roundToInt (w * pw),
  939. roundToInt (h * ph));
  940. }
  941. void Component::setCentrePosition (const int x, const int y)
  942. {
  943. setTopLeftPosition (x - getWidth() / 2,
  944. y - getHeight() / 2);
  945. }
  946. void Component::setCentreRelative (const float x, const float y)
  947. {
  948. setCentrePosition (roundToInt (getParentWidth() * x),
  949. roundToInt (getParentHeight() * y));
  950. }
  951. void Component::centreWithSize (const int width, const int height)
  952. {
  953. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  954. setBounds (parentArea.getCentreX() - width / 2,
  955. parentArea.getCentreY() - height / 2,
  956. width, height);
  957. }
  958. void Component::setBoundsInset (const BorderSize<int>& borders)
  959. {
  960. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  961. }
  962. void Component::setBoundsToFit (int x, int y, int width, int height,
  963. const Justification& justification,
  964. const bool onlyReduceInSize)
  965. {
  966. // it's no good calling this method unless both the component and
  967. // target rectangle have a finite size.
  968. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  969. if (getWidth() > 0 && getHeight() > 0
  970. && width > 0 && height > 0)
  971. {
  972. int newW, newH;
  973. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  974. {
  975. newW = getWidth();
  976. newH = getHeight();
  977. }
  978. else
  979. {
  980. const double imageRatio = getHeight() / (double) getWidth();
  981. const double targetRatio = height / (double) width;
  982. if (imageRatio <= targetRatio)
  983. {
  984. newW = width;
  985. newH = jmin (height, roundToInt (newW * imageRatio));
  986. }
  987. else
  988. {
  989. newH = height;
  990. newW = jmin (width, roundToInt (newH / imageRatio));
  991. }
  992. }
  993. if (newW > 0 && newH > 0)
  994. setBounds (justification.appliedToRectangle (Rectangle<int> (newW, newH),
  995. Rectangle<int> (x, y, width, height)));
  996. }
  997. }
  998. //==============================================================================
  999. bool Component::isTransformed() const noexcept
  1000. {
  1001. return affineTransform != nullptr;
  1002. }
  1003. void Component::setTransform (const AffineTransform& newTransform)
  1004. {
  1005. // If you pass in a transform with no inverse, the component will have no dimensions,
  1006. // and there will be all sorts of maths errors when converting coordinates.
  1007. jassert (! newTransform.isSingularity());
  1008. if (newTransform.isIdentity())
  1009. {
  1010. if (affineTransform != nullptr)
  1011. {
  1012. repaint();
  1013. affineTransform = nullptr;
  1014. repaint();
  1015. sendMovedResizedMessages (false, false);
  1016. }
  1017. }
  1018. else if (affineTransform == nullptr)
  1019. {
  1020. repaint();
  1021. affineTransform = new AffineTransform (newTransform);
  1022. repaint();
  1023. sendMovedResizedMessages (false, false);
  1024. }
  1025. else if (*affineTransform != newTransform)
  1026. {
  1027. repaint();
  1028. *affineTransform = newTransform;
  1029. repaint();
  1030. sendMovedResizedMessages (false, false);
  1031. }
  1032. }
  1033. AffineTransform Component::getTransform() const
  1034. {
  1035. return affineTransform != nullptr ? *affineTransform : AffineTransform::identity;
  1036. }
  1037. //==============================================================================
  1038. bool Component::hitTest (int x, int y)
  1039. {
  1040. if (! flags.ignoresMouseClicksFlag)
  1041. return true;
  1042. if (flags.allowChildMouseClicksFlag)
  1043. {
  1044. for (int i = childComponentList.size(); --i >= 0;)
  1045. {
  1046. Component& child = *childComponentList.getUnchecked (i);
  1047. if (child.isVisible()
  1048. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  1049. return true;
  1050. }
  1051. }
  1052. return false;
  1053. }
  1054. void Component::setInterceptsMouseClicks (const bool allowClicks,
  1055. const bool allowClicksOnChildComponents) noexcept
  1056. {
  1057. flags.ignoresMouseClicksFlag = ! allowClicks;
  1058. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  1059. }
  1060. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  1061. bool& allowsClicksOnChildComponents) const noexcept
  1062. {
  1063. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  1064. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  1065. }
  1066. bool Component::contains (const Point<int>& point)
  1067. {
  1068. if (ComponentHelpers::hitTest (*this, point))
  1069. {
  1070. if (parentComponent != nullptr)
  1071. {
  1072. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  1073. }
  1074. else if (flags.hasHeavyweightPeerFlag)
  1075. {
  1076. const ComponentPeer* const peer = getPeer();
  1077. if (peer != nullptr)
  1078. return peer->contains (point, true);
  1079. }
  1080. }
  1081. return false;
  1082. }
  1083. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  1084. {
  1085. if (! contains (point))
  1086. return false;
  1087. Component* const top = getTopLevelComponent();
  1088. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  1089. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  1090. }
  1091. Component* Component::getComponentAt (const Point<int>& position)
  1092. {
  1093. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  1094. {
  1095. for (int i = childComponentList.size(); --i >= 0;)
  1096. {
  1097. Component* child = childComponentList.getUnchecked(i);
  1098. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  1099. if (child != nullptr)
  1100. return child;
  1101. }
  1102. return this;
  1103. }
  1104. return nullptr;
  1105. }
  1106. Component* Component::getComponentAt (const int x, const int y)
  1107. {
  1108. return getComponentAt (Point<int> (x, y));
  1109. }
  1110. //==============================================================================
  1111. void Component::addChildComponent (Component* const child, int zOrder)
  1112. {
  1113. // if component methods are being called from threads other than the message
  1114. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1115. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1116. if (child != nullptr && child->parentComponent != this)
  1117. {
  1118. if (child->parentComponent != nullptr)
  1119. child->parentComponent->removeChildComponent (child);
  1120. else
  1121. child->removeFromDesktop();
  1122. child->parentComponent = this;
  1123. if (child->isVisible())
  1124. child->repaintParent();
  1125. if (! child->isAlwaysOnTop())
  1126. {
  1127. if (zOrder < 0 || zOrder > childComponentList.size())
  1128. zOrder = childComponentList.size();
  1129. while (zOrder > 0)
  1130. {
  1131. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  1132. break;
  1133. --zOrder;
  1134. }
  1135. }
  1136. childComponentList.insert (zOrder, child);
  1137. child->internalHierarchyChanged();
  1138. internalChildrenChanged();
  1139. }
  1140. }
  1141. void Component::addAndMakeVisible (Component* const child, int zOrder)
  1142. {
  1143. if (child != nullptr)
  1144. {
  1145. child->setVisible (true);
  1146. addChildComponent (child, zOrder);
  1147. }
  1148. }
  1149. void Component::removeChildComponent (Component* const child)
  1150. {
  1151. removeChildComponent (childComponentList.indexOf (child), true, true);
  1152. }
  1153. Component* Component::removeChildComponent (const int index)
  1154. {
  1155. return removeChildComponent (index, true, true);
  1156. }
  1157. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  1158. {
  1159. // if component methods are being called from threads other than the message
  1160. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1161. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1162. Component* const child = childComponentList [index];
  1163. if (child != nullptr)
  1164. {
  1165. sendParentEvents = sendParentEvents && child->isShowing();
  1166. if (sendParentEvents)
  1167. {
  1168. sendFakeMouseMove();
  1169. if (child->isVisible())
  1170. child->repaintParent();
  1171. }
  1172. childComponentList.remove (index);
  1173. child->parentComponent = nullptr;
  1174. if (child->cachedImage != nullptr)
  1175. child->cachedImage->releaseResources();
  1176. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  1177. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  1178. {
  1179. if (sendParentEvents)
  1180. {
  1181. const WeakReference<Component> thisPointer (this);
  1182. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  1183. if (thisPointer == nullptr)
  1184. return child;
  1185. grabKeyboardFocus();
  1186. }
  1187. else
  1188. {
  1189. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  1190. }
  1191. }
  1192. if (sendChildEvents)
  1193. child->internalHierarchyChanged();
  1194. if (sendParentEvents)
  1195. internalChildrenChanged();
  1196. }
  1197. return child;
  1198. }
  1199. //==============================================================================
  1200. void Component::removeAllChildren()
  1201. {
  1202. while (childComponentList.size() > 0)
  1203. removeChildComponent (childComponentList.size() - 1);
  1204. }
  1205. void Component::deleteAllChildren()
  1206. {
  1207. while (childComponentList.size() > 0)
  1208. delete (removeChildComponent (childComponentList.size() - 1));
  1209. }
  1210. //==============================================================================
  1211. int Component::getNumChildComponents() const noexcept
  1212. {
  1213. return childComponentList.size();
  1214. }
  1215. Component* Component::getChildComponent (const int index) const noexcept
  1216. {
  1217. return childComponentList [index];
  1218. }
  1219. int Component::getIndexOfChildComponent (const Component* const child) const noexcept
  1220. {
  1221. return childComponentList.indexOf (const_cast <Component*> (child));
  1222. }
  1223. Component* Component::findChildWithID (const String& targetID) const noexcept
  1224. {
  1225. for (int i = childComponentList.size(); --i >= 0;)
  1226. {
  1227. Component* const c = childComponentList.getUnchecked(i);
  1228. if (c->componentID == targetID)
  1229. return c;
  1230. }
  1231. return nullptr;
  1232. }
  1233. Component* Component::getTopLevelComponent() const noexcept
  1234. {
  1235. const Component* comp = this;
  1236. while (comp->parentComponent != nullptr)
  1237. comp = comp->parentComponent;
  1238. return const_cast <Component*> (comp);
  1239. }
  1240. bool Component::isParentOf (const Component* possibleChild) const noexcept
  1241. {
  1242. while (possibleChild != nullptr)
  1243. {
  1244. possibleChild = possibleChild->parentComponent;
  1245. if (possibleChild == this)
  1246. return true;
  1247. }
  1248. return false;
  1249. }
  1250. //==============================================================================
  1251. void Component::parentHierarchyChanged()
  1252. {
  1253. }
  1254. void Component::childrenChanged()
  1255. {
  1256. }
  1257. void Component::internalChildrenChanged()
  1258. {
  1259. if (componentListeners.isEmpty())
  1260. {
  1261. childrenChanged();
  1262. }
  1263. else
  1264. {
  1265. BailOutChecker checker (this);
  1266. childrenChanged();
  1267. if (! checker.shouldBailOut())
  1268. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  1269. }
  1270. }
  1271. void Component::internalHierarchyChanged()
  1272. {
  1273. BailOutChecker checker (this);
  1274. parentHierarchyChanged();
  1275. if (checker.shouldBailOut())
  1276. return;
  1277. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  1278. if (checker.shouldBailOut())
  1279. return;
  1280. for (int i = childComponentList.size(); --i >= 0;)
  1281. {
  1282. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  1283. if (checker.shouldBailOut())
  1284. {
  1285. // you really shouldn't delete the parent component during a callback telling you
  1286. // that it's changed..
  1287. jassertfalse;
  1288. return;
  1289. }
  1290. i = jmin (i, childComponentList.size());
  1291. }
  1292. }
  1293. //==============================================================================
  1294. #if JUCE_MODAL_LOOPS_PERMITTED
  1295. int Component::runModalLoop()
  1296. {
  1297. if (! MessageManager::getInstance()->isThisTheMessageThread())
  1298. {
  1299. // use a callback so this can be called from non-gui threads
  1300. return (int) (pointer_sized_int) MessageManager::getInstance()
  1301. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  1302. }
  1303. if (! isCurrentlyModal())
  1304. enterModalState (true);
  1305. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  1306. }
  1307. #endif
  1308. //==============================================================================
  1309. void Component::enterModalState (const bool shouldTakeKeyboardFocus,
  1310. ModalComponentManager::Callback* callback,
  1311. const bool deleteWhenDismissed)
  1312. {
  1313. // if component methods are being called from threads other than the message
  1314. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1315. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1316. // Check for an attempt to make a component modal when it already is!
  1317. // This can cause nasty problems..
  1318. jassert (! flags.currentlyModalFlag);
  1319. if (! isCurrentlyModal())
  1320. {
  1321. ModalComponentManager* const mcm = ModalComponentManager::getInstance();
  1322. mcm->startModal (this, deleteWhenDismissed);
  1323. mcm->attachCallback (this, callback);
  1324. flags.currentlyModalFlag = true;
  1325. setVisible (true);
  1326. if (shouldTakeKeyboardFocus)
  1327. grabKeyboardFocus();
  1328. }
  1329. }
  1330. void Component::exitModalState (const int returnValue)
  1331. {
  1332. if (flags.currentlyModalFlag)
  1333. {
  1334. if (MessageManager::getInstance()->isThisTheMessageThread())
  1335. {
  1336. ModalComponentManager::getInstance()->endModal (this, returnValue);
  1337. flags.currentlyModalFlag = false;
  1338. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1339. }
  1340. else
  1341. {
  1342. class ExitModalStateMessage : public CallbackMessage
  1343. {
  1344. public:
  1345. ExitModalStateMessage (Component* const target_, const int result_)
  1346. : target (target_), result (result_) {}
  1347. void messageCallback()
  1348. {
  1349. if (target.get() != nullptr) // (get() required for VS2003 bug)
  1350. target->exitModalState (result);
  1351. }
  1352. private:
  1353. WeakReference<Component> target;
  1354. int result;
  1355. };
  1356. (new ExitModalStateMessage (this, returnValue))->post();
  1357. }
  1358. }
  1359. }
  1360. bool Component::isCurrentlyModal() const noexcept
  1361. {
  1362. return flags.currentlyModalFlag
  1363. && getCurrentlyModalComponent() == this;
  1364. }
  1365. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  1366. {
  1367. Component* const mc = getCurrentlyModalComponent();
  1368. return ! (mc == nullptr || mc == this || mc->isParentOf (this)
  1369. || mc->canModalEventBeSentToComponent (this));
  1370. }
  1371. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() noexcept
  1372. {
  1373. return ModalComponentManager::getInstance()->getNumModalComponents();
  1374. }
  1375. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) noexcept
  1376. {
  1377. return ModalComponentManager::getInstance()->getModalComponent (index);
  1378. }
  1379. //==============================================================================
  1380. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) noexcept
  1381. {
  1382. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  1383. }
  1384. bool Component::isBroughtToFrontOnMouseClick() const noexcept
  1385. {
  1386. return flags.bringToFrontOnClickFlag;
  1387. }
  1388. //==============================================================================
  1389. void Component::setMouseCursor (const MouseCursor& newCursor)
  1390. {
  1391. if (cursor != newCursor)
  1392. {
  1393. cursor = newCursor;
  1394. if (flags.visibleFlag)
  1395. updateMouseCursor();
  1396. }
  1397. }
  1398. MouseCursor Component::getMouseCursor()
  1399. {
  1400. return cursor;
  1401. }
  1402. void Component::updateMouseCursor() const
  1403. {
  1404. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1405. }
  1406. //==============================================================================
  1407. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) noexcept
  1408. {
  1409. flags.repaintOnMouseActivityFlag = shouldRepaint;
  1410. }
  1411. //==============================================================================
  1412. void Component::setAlpha (const float newAlpha)
  1413. {
  1414. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  1415. if (componentTransparency != newIntAlpha)
  1416. {
  1417. componentTransparency = newIntAlpha;
  1418. if (flags.hasHeavyweightPeerFlag)
  1419. {
  1420. ComponentPeer* const peer = getPeer();
  1421. if (peer != nullptr)
  1422. peer->setAlpha (newAlpha);
  1423. }
  1424. else
  1425. {
  1426. repaint();
  1427. }
  1428. }
  1429. }
  1430. float Component::getAlpha() const
  1431. {
  1432. return (255 - componentTransparency) / 255.0f;
  1433. }
  1434. //==============================================================================
  1435. void Component::repaint()
  1436. {
  1437. internalRepaintUnchecked (getLocalBounds(), true);
  1438. }
  1439. void Component::repaint (const int x, const int y, const int w, const int h)
  1440. {
  1441. internalRepaint (Rectangle<int> (x, y, w, h));
  1442. }
  1443. void Component::repaint (const Rectangle<int>& area)
  1444. {
  1445. internalRepaint (area);
  1446. }
  1447. void Component::repaintParent()
  1448. {
  1449. if (parentComponent != nullptr)
  1450. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, getLocalBounds()));
  1451. }
  1452. void Component::internalRepaint (const Rectangle<int>& area)
  1453. {
  1454. const Rectangle<int> r (area.getIntersection (getLocalBounds()));
  1455. if (! r.isEmpty())
  1456. internalRepaintUnchecked (r, false);
  1457. }
  1458. void Component::internalRepaintUnchecked (const Rectangle<int>& area, const bool isEntireComponent)
  1459. {
  1460. // if component methods are being called from threads other than the message
  1461. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1462. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1463. if (flags.visibleFlag)
  1464. {
  1465. if (flags.hasHeavyweightPeerFlag)
  1466. {
  1467. ComponentPeer* const peer = getPeer();
  1468. if (peer != nullptr)
  1469. peer->repaint (area);
  1470. }
  1471. else
  1472. {
  1473. if (cachedImage != nullptr)
  1474. {
  1475. if (isEntireComponent)
  1476. cachedImage->invalidateAll();
  1477. else
  1478. cachedImage->invalidate (area);
  1479. }
  1480. if (parentComponent != nullptr)
  1481. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, area));
  1482. }
  1483. }
  1484. }
  1485. //==============================================================================
  1486. void Component::paintWithinParentContext (Graphics& g)
  1487. {
  1488. g.setOrigin (getX(), getY());
  1489. if (cachedImage != nullptr)
  1490. cachedImage->paint (g);
  1491. else
  1492. paintEntireComponent (g, false);
  1493. }
  1494. void Component::paintComponentAndChildren (Graphics& g)
  1495. {
  1496. const Rectangle<int> clipBounds (g.getClipBounds());
  1497. if (flags.dontClipGraphicsFlag)
  1498. {
  1499. paint (g);
  1500. }
  1501. else
  1502. {
  1503. g.saveState();
  1504. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  1505. if (! g.isClipEmpty())
  1506. paint (g);
  1507. g.restoreState();
  1508. }
  1509. for (int i = 0; i < childComponentList.size(); ++i)
  1510. {
  1511. Component& child = *childComponentList.getUnchecked (i);
  1512. if (child.isVisible())
  1513. {
  1514. if (child.affineTransform != nullptr)
  1515. {
  1516. g.saveState();
  1517. g.addTransform (*child.affineTransform);
  1518. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  1519. child.paintWithinParentContext (g);
  1520. g.restoreState();
  1521. }
  1522. else if (clipBounds.intersects (child.getBounds()))
  1523. {
  1524. g.saveState();
  1525. if (child.flags.dontClipGraphicsFlag)
  1526. {
  1527. child.paintWithinParentContext (g);
  1528. }
  1529. else if (g.reduceClipRegion (child.getBounds()))
  1530. {
  1531. bool nothingClipped = true;
  1532. for (int j = i + 1; j < childComponentList.size(); ++j)
  1533. {
  1534. const Component& sibling = *childComponentList.getUnchecked (j);
  1535. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == nullptr)
  1536. {
  1537. nothingClipped = false;
  1538. g.excludeClipRegion (sibling.getBounds());
  1539. }
  1540. }
  1541. if (nothingClipped || ! g.isClipEmpty())
  1542. child.paintWithinParentContext (g);
  1543. }
  1544. g.restoreState();
  1545. }
  1546. }
  1547. }
  1548. g.saveState();
  1549. paintOverChildren (g);
  1550. g.restoreState();
  1551. }
  1552. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  1553. {
  1554. #if JUCE_DEBUG
  1555. flags.isInsidePaintCall = true;
  1556. #endif
  1557. if (effect != nullptr)
  1558. {
  1559. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  1560. getWidth(), getHeight(), ! flags.opaqueFlag);
  1561. {
  1562. Graphics g2 (effectImage);
  1563. paintComponentAndChildren (g2);
  1564. }
  1565. effect->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  1566. }
  1567. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  1568. {
  1569. if (componentTransparency < 255)
  1570. {
  1571. g.beginTransparencyLayer (getAlpha());
  1572. paintComponentAndChildren (g);
  1573. g.endTransparencyLayer();
  1574. }
  1575. }
  1576. else
  1577. {
  1578. paintComponentAndChildren (g);
  1579. }
  1580. #if JUCE_DEBUG
  1581. flags.isInsidePaintCall = false;
  1582. #endif
  1583. }
  1584. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) noexcept
  1585. {
  1586. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  1587. }
  1588. //==============================================================================
  1589. Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  1590. const bool clipImageToComponentBounds)
  1591. {
  1592. Rectangle<int> r (areaToGrab);
  1593. if (clipImageToComponentBounds)
  1594. r = r.getIntersection (getLocalBounds());
  1595. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  1596. jmax (1, r.getWidth()),
  1597. jmax (1, r.getHeight()),
  1598. true);
  1599. Graphics imageContext (componentImage);
  1600. imageContext.setOrigin (-r.getX(), -r.getY());
  1601. paintEntireComponent (imageContext, true);
  1602. return componentImage;
  1603. }
  1604. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  1605. {
  1606. if (effect != newEffect)
  1607. {
  1608. effect = newEffect;
  1609. repaint();
  1610. }
  1611. }
  1612. //==============================================================================
  1613. LookAndFeel& Component::getLookAndFeel() const noexcept
  1614. {
  1615. const Component* c = this;
  1616. do
  1617. {
  1618. if (c->lookAndFeel != nullptr)
  1619. return *(c->lookAndFeel);
  1620. c = c->parentComponent;
  1621. }
  1622. while (c != nullptr);
  1623. return LookAndFeel::getDefaultLookAndFeel();
  1624. }
  1625. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  1626. {
  1627. if (lookAndFeel != newLookAndFeel)
  1628. {
  1629. lookAndFeel = newLookAndFeel;
  1630. sendLookAndFeelChange();
  1631. }
  1632. }
  1633. void Component::lookAndFeelChanged()
  1634. {
  1635. }
  1636. void Component::sendLookAndFeelChange()
  1637. {
  1638. repaint();
  1639. const WeakReference<Component> safePointer (this);
  1640. lookAndFeelChanged();
  1641. if (safePointer != nullptr)
  1642. {
  1643. for (int i = childComponentList.size(); --i >= 0;)
  1644. {
  1645. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  1646. if (safePointer == nullptr)
  1647. return;
  1648. i = jmin (i, childComponentList.size());
  1649. }
  1650. }
  1651. }
  1652. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  1653. {
  1654. const var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  1655. if (v != nullptr)
  1656. return Colour ((uint32) static_cast <int> (*v));
  1657. if (inheritFromParent && parentComponent != nullptr
  1658. && (lookAndFeel == nullptr || ! lookAndFeel->isColourSpecified (colourId)))
  1659. return parentComponent->findColour (colourId, true);
  1660. return getLookAndFeel().findColour (colourId);
  1661. }
  1662. bool Component::isColourSpecified (const int colourId) const
  1663. {
  1664. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  1665. }
  1666. void Component::removeColour (const int colourId)
  1667. {
  1668. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  1669. colourChanged();
  1670. }
  1671. void Component::setColour (const int colourId, const Colour& colour)
  1672. {
  1673. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  1674. colourChanged();
  1675. }
  1676. void Component::copyAllExplicitColoursTo (Component& target) const
  1677. {
  1678. bool changed = false;
  1679. for (int i = properties.size(); --i >= 0;)
  1680. {
  1681. const Identifier name (properties.getName(i));
  1682. if (name.toString().startsWith ("jcclr_"))
  1683. if (target.properties.set (name, properties [name]))
  1684. changed = true;
  1685. }
  1686. if (changed)
  1687. target.colourChanged();
  1688. }
  1689. void Component::colourChanged()
  1690. {
  1691. }
  1692. //==============================================================================
  1693. MarkerList* Component::getMarkers (bool /*xAxis*/)
  1694. {
  1695. return nullptr;
  1696. }
  1697. //==============================================================================
  1698. Component::Positioner::Positioner (Component& component_) noexcept
  1699. : component (component_)
  1700. {
  1701. }
  1702. Component::Positioner* Component::getPositioner() const noexcept
  1703. {
  1704. return positioner;
  1705. }
  1706. void Component::setPositioner (Positioner* newPositioner)
  1707. {
  1708. // You can only assign a positioner to the component that it was created for!
  1709. jassert (newPositioner == nullptr || this == &(newPositioner->getComponent()));
  1710. positioner = newPositioner;
  1711. }
  1712. //==============================================================================
  1713. Rectangle<int> Component::getLocalBounds() const noexcept
  1714. {
  1715. return Rectangle<int> (getWidth(), getHeight());
  1716. }
  1717. Rectangle<int> Component::getBoundsInParent() const noexcept
  1718. {
  1719. return affineTransform == nullptr ? bounds
  1720. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  1721. }
  1722. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  1723. {
  1724. result.clear();
  1725. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  1726. if (! unclipped.isEmpty())
  1727. {
  1728. result.add (unclipped);
  1729. if (includeSiblings)
  1730. {
  1731. const Component* const c = getTopLevelComponent();
  1732. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  1733. c->getLocalBounds(), this);
  1734. }
  1735. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, nullptr);
  1736. result.consolidate();
  1737. }
  1738. }
  1739. //==============================================================================
  1740. void Component::mouseEnter (const MouseEvent&)
  1741. {
  1742. // base class does nothing
  1743. }
  1744. void Component::mouseExit (const MouseEvent&)
  1745. {
  1746. // base class does nothing
  1747. }
  1748. void Component::mouseDown (const MouseEvent&)
  1749. {
  1750. // base class does nothing
  1751. }
  1752. void Component::mouseUp (const MouseEvent&)
  1753. {
  1754. // base class does nothing
  1755. }
  1756. void Component::mouseDrag (const MouseEvent&)
  1757. {
  1758. // base class does nothing
  1759. }
  1760. void Component::mouseMove (const MouseEvent&)
  1761. {
  1762. // base class does nothing
  1763. }
  1764. void Component::mouseDoubleClick (const MouseEvent&)
  1765. {
  1766. // base class does nothing
  1767. }
  1768. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  1769. {
  1770. // the base class just passes this event up to its parent..
  1771. if (parentComponent != nullptr)
  1772. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent),
  1773. wheelIncrementX, wheelIncrementY);
  1774. }
  1775. //==============================================================================
  1776. void Component::resized()
  1777. {
  1778. // base class does nothing
  1779. }
  1780. void Component::moved()
  1781. {
  1782. // base class does nothing
  1783. }
  1784. void Component::childBoundsChanged (Component*)
  1785. {
  1786. // base class does nothing
  1787. }
  1788. void Component::parentSizeChanged()
  1789. {
  1790. // base class does nothing
  1791. }
  1792. void Component::addComponentListener (ComponentListener* const newListener)
  1793. {
  1794. // if component methods are being called from threads other than the message
  1795. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1796. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1797. componentListeners.add (newListener);
  1798. }
  1799. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  1800. {
  1801. componentListeners.remove (listenerToRemove);
  1802. }
  1803. //==============================================================================
  1804. void Component::inputAttemptWhenModal()
  1805. {
  1806. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1807. getLookAndFeel().playAlertSound();
  1808. }
  1809. bool Component::canModalEventBeSentToComponent (const Component*)
  1810. {
  1811. return false;
  1812. }
  1813. void Component::internalModalInputAttempt()
  1814. {
  1815. Component* const current = getCurrentlyModalComponent();
  1816. if (current != nullptr)
  1817. current->inputAttemptWhenModal();
  1818. }
  1819. //==============================================================================
  1820. void Component::paint (Graphics&)
  1821. {
  1822. // all painting is done in the subclasses
  1823. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  1824. }
  1825. void Component::paintOverChildren (Graphics&)
  1826. {
  1827. // all painting is done in the subclasses
  1828. }
  1829. //==============================================================================
  1830. void Component::postCommandMessage (const int commandId)
  1831. {
  1832. class CustomCommandMessage : public CallbackMessage
  1833. {
  1834. public:
  1835. CustomCommandMessage (Component* const target_, const int commandId_)
  1836. : target (target_), commandId (commandId_) {}
  1837. void messageCallback()
  1838. {
  1839. if (target.get() != nullptr) // (get() required for VS2003 bug)
  1840. target->handleCommandMessage (commandId);
  1841. }
  1842. private:
  1843. WeakReference<Component> target;
  1844. int commandId;
  1845. };
  1846. (new CustomCommandMessage (this, commandId))->post();
  1847. }
  1848. void Component::handleCommandMessage (int)
  1849. {
  1850. // used by subclasses
  1851. }
  1852. //==============================================================================
  1853. void Component::addMouseListener (MouseListener* const newListener,
  1854. const bool wantsEventsForAllNestedChildComponents)
  1855. {
  1856. // if component methods are being called from threads other than the message
  1857. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1858. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1859. // If you register a component as a mouselistener for itself, it'll receive all the events
  1860. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  1861. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  1862. if (mouseListeners == nullptr)
  1863. mouseListeners = new MouseListenerList();
  1864. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  1865. }
  1866. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  1867. {
  1868. // if component methods are being called from threads other than the message
  1869. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1870. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1871. if (mouseListeners != nullptr)
  1872. mouseListeners->removeListener (listenerToRemove);
  1873. }
  1874. //==============================================================================
  1875. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1876. {
  1877. if (isCurrentlyBlockedByAnotherModalComponent())
  1878. {
  1879. // if something else is modal, always just show a normal mouse cursor
  1880. source.showMouseCursor (MouseCursor::NormalCursor);
  1881. return;
  1882. }
  1883. if (flags.repaintOnMouseActivityFlag)
  1884. repaint();
  1885. BailOutChecker checker (this);
  1886. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1887. this, this, time, relativePos, time, 0, false);
  1888. mouseEnter (me);
  1889. if (checker.shouldBailOut())
  1890. return;
  1891. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseEnter, me);
  1892. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  1893. }
  1894. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1895. {
  1896. if (flags.repaintOnMouseActivityFlag)
  1897. repaint();
  1898. BailOutChecker checker (this);
  1899. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1900. this, this, time, relativePos, time, 0, false);
  1901. mouseExit (me);
  1902. if (checker.shouldBailOut())
  1903. return;
  1904. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseExit, me);
  1905. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  1906. }
  1907. //==============================================================================
  1908. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1909. {
  1910. Desktop& desktop = Desktop::getInstance();
  1911. BailOutChecker checker (this);
  1912. if (isCurrentlyBlockedByAnotherModalComponent())
  1913. {
  1914. internalModalInputAttempt();
  1915. if (checker.shouldBailOut())
  1916. return;
  1917. // If processing the input attempt has exited the modal loop, we'll allow the event
  1918. // to be delivered..
  1919. if (isCurrentlyBlockedByAnotherModalComponent())
  1920. {
  1921. // allow blocked mouse-events to go to global listeners..
  1922. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1923. this, this, time, relativePos, time,
  1924. source.getNumberOfMultipleClicks(), false);
  1925. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseDown, me);
  1926. return;
  1927. }
  1928. }
  1929. {
  1930. Component* c = this;
  1931. while (c != nullptr)
  1932. {
  1933. if (c->isBroughtToFrontOnMouseClick())
  1934. {
  1935. c->toFront (true);
  1936. if (checker.shouldBailOut())
  1937. return;
  1938. }
  1939. c = c->parentComponent;
  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. }
  2412. END_JUCE_NAMESPACE