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.

3038 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::removeChildComponent (Component* const child)
  1152. {
  1153. removeChildComponent (childComponentList.indexOf (child), true, true);
  1154. }
  1155. Component* Component::removeChildComponent (const int index)
  1156. {
  1157. return removeChildComponent (index, true, true);
  1158. }
  1159. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  1160. {
  1161. // if component methods are being called from threads other than the message
  1162. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1163. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1164. Component* const child = childComponentList [index];
  1165. if (child != nullptr)
  1166. {
  1167. sendParentEvents = sendParentEvents && child->isShowing();
  1168. if (sendParentEvents)
  1169. {
  1170. sendFakeMouseMove();
  1171. if (child->isVisible())
  1172. child->repaintParent();
  1173. }
  1174. childComponentList.remove (index);
  1175. child->parentComponent = nullptr;
  1176. if (child->cachedImage != nullptr)
  1177. child->cachedImage->releaseResources();
  1178. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  1179. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  1180. {
  1181. if (sendParentEvents)
  1182. {
  1183. const WeakReference<Component> thisPointer (this);
  1184. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  1185. if (thisPointer == nullptr)
  1186. return child;
  1187. grabKeyboardFocus();
  1188. }
  1189. else
  1190. {
  1191. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  1192. }
  1193. }
  1194. if (sendChildEvents)
  1195. child->internalHierarchyChanged();
  1196. if (sendParentEvents)
  1197. internalChildrenChanged();
  1198. }
  1199. return child;
  1200. }
  1201. //==============================================================================
  1202. void Component::removeAllChildren()
  1203. {
  1204. while (childComponentList.size() > 0)
  1205. removeChildComponent (childComponentList.size() - 1);
  1206. }
  1207. void Component::deleteAllChildren()
  1208. {
  1209. while (childComponentList.size() > 0)
  1210. delete (removeChildComponent (childComponentList.size() - 1));
  1211. }
  1212. //==============================================================================
  1213. int Component::getNumChildComponents() const noexcept
  1214. {
  1215. return childComponentList.size();
  1216. }
  1217. Component* Component::getChildComponent (const int index) const noexcept
  1218. {
  1219. return childComponentList [index];
  1220. }
  1221. int Component::getIndexOfChildComponent (const Component* const child) const noexcept
  1222. {
  1223. return childComponentList.indexOf (const_cast <Component*> (child));
  1224. }
  1225. Component* Component::findChildWithID (const String& targetID) const noexcept
  1226. {
  1227. for (int i = childComponentList.size(); --i >= 0;)
  1228. {
  1229. Component* const c = childComponentList.getUnchecked(i);
  1230. if (c->componentID == targetID)
  1231. return c;
  1232. }
  1233. return nullptr;
  1234. }
  1235. Component* Component::getTopLevelComponent() const noexcept
  1236. {
  1237. const Component* comp = this;
  1238. while (comp->parentComponent != nullptr)
  1239. comp = comp->parentComponent;
  1240. return const_cast <Component*> (comp);
  1241. }
  1242. bool Component::isParentOf (const Component* possibleChild) const noexcept
  1243. {
  1244. while (possibleChild != nullptr)
  1245. {
  1246. possibleChild = possibleChild->parentComponent;
  1247. if (possibleChild == this)
  1248. return true;
  1249. }
  1250. return false;
  1251. }
  1252. //==============================================================================
  1253. void Component::parentHierarchyChanged()
  1254. {
  1255. }
  1256. void Component::childrenChanged()
  1257. {
  1258. }
  1259. void Component::internalChildrenChanged()
  1260. {
  1261. if (componentListeners.isEmpty())
  1262. {
  1263. childrenChanged();
  1264. }
  1265. else
  1266. {
  1267. BailOutChecker checker (this);
  1268. childrenChanged();
  1269. if (! checker.shouldBailOut())
  1270. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  1271. }
  1272. }
  1273. void Component::internalHierarchyChanged()
  1274. {
  1275. BailOutChecker checker (this);
  1276. parentHierarchyChanged();
  1277. if (checker.shouldBailOut())
  1278. return;
  1279. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  1280. if (checker.shouldBailOut())
  1281. return;
  1282. for (int i = childComponentList.size(); --i >= 0;)
  1283. {
  1284. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  1285. if (checker.shouldBailOut())
  1286. {
  1287. // you really shouldn't delete the parent component during a callback telling you
  1288. // that it's changed..
  1289. jassertfalse;
  1290. return;
  1291. }
  1292. i = jmin (i, childComponentList.size());
  1293. }
  1294. }
  1295. //==============================================================================
  1296. #if JUCE_MODAL_LOOPS_PERMITTED
  1297. int Component::runModalLoop()
  1298. {
  1299. if (! MessageManager::getInstance()->isThisTheMessageThread())
  1300. {
  1301. // use a callback so this can be called from non-gui threads
  1302. return (int) (pointer_sized_int) MessageManager::getInstance()
  1303. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  1304. }
  1305. if (! isCurrentlyModal())
  1306. enterModalState (true);
  1307. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  1308. }
  1309. #endif
  1310. //==============================================================================
  1311. void Component::enterModalState (const bool shouldTakeKeyboardFocus,
  1312. ModalComponentManager::Callback* callback,
  1313. const bool deleteWhenDismissed)
  1314. {
  1315. // if component methods are being called from threads other than the message
  1316. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1317. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1318. // Check for an attempt to make a component modal when it already is!
  1319. // This can cause nasty problems..
  1320. jassert (! flags.currentlyModalFlag);
  1321. if (! isCurrentlyModal())
  1322. {
  1323. ModalComponentManager* const mcm = ModalComponentManager::getInstance();
  1324. mcm->startModal (this, deleteWhenDismissed);
  1325. mcm->attachCallback (this, callback);
  1326. flags.currentlyModalFlag = true;
  1327. setVisible (true);
  1328. if (shouldTakeKeyboardFocus)
  1329. grabKeyboardFocus();
  1330. }
  1331. }
  1332. void Component::exitModalState (const int returnValue)
  1333. {
  1334. if (flags.currentlyModalFlag)
  1335. {
  1336. if (MessageManager::getInstance()->isThisTheMessageThread())
  1337. {
  1338. ModalComponentManager::getInstance()->endModal (this, returnValue);
  1339. flags.currentlyModalFlag = false;
  1340. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1341. }
  1342. else
  1343. {
  1344. class ExitModalStateMessage : public CallbackMessage
  1345. {
  1346. public:
  1347. ExitModalStateMessage (Component* const target_, const int result_)
  1348. : target (target_), result (result_) {}
  1349. void messageCallback()
  1350. {
  1351. if (target.get() != nullptr) // (get() required for VS2003 bug)
  1352. target->exitModalState (result);
  1353. }
  1354. private:
  1355. WeakReference<Component> target;
  1356. int result;
  1357. };
  1358. (new ExitModalStateMessage (this, returnValue))->post();
  1359. }
  1360. }
  1361. }
  1362. bool Component::isCurrentlyModal() const noexcept
  1363. {
  1364. return flags.currentlyModalFlag
  1365. && getCurrentlyModalComponent() == this;
  1366. }
  1367. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  1368. {
  1369. Component* const mc = getCurrentlyModalComponent();
  1370. return ! (mc == nullptr || mc == this || mc->isParentOf (this)
  1371. || mc->canModalEventBeSentToComponent (this));
  1372. }
  1373. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() noexcept
  1374. {
  1375. return ModalComponentManager::getInstance()->getNumModalComponents();
  1376. }
  1377. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) noexcept
  1378. {
  1379. return ModalComponentManager::getInstance()->getModalComponent (index);
  1380. }
  1381. //==============================================================================
  1382. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) noexcept
  1383. {
  1384. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  1385. }
  1386. bool Component::isBroughtToFrontOnMouseClick() const noexcept
  1387. {
  1388. return flags.bringToFrontOnClickFlag;
  1389. }
  1390. //==============================================================================
  1391. void Component::setMouseCursor (const MouseCursor& newCursor)
  1392. {
  1393. if (cursor != newCursor)
  1394. {
  1395. cursor = newCursor;
  1396. if (flags.visibleFlag)
  1397. updateMouseCursor();
  1398. }
  1399. }
  1400. MouseCursor Component::getMouseCursor()
  1401. {
  1402. return cursor;
  1403. }
  1404. void Component::updateMouseCursor() const
  1405. {
  1406. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1407. }
  1408. //==============================================================================
  1409. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) noexcept
  1410. {
  1411. flags.repaintOnMouseActivityFlag = shouldRepaint;
  1412. }
  1413. //==============================================================================
  1414. void Component::setAlpha (const float newAlpha)
  1415. {
  1416. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  1417. if (componentTransparency != newIntAlpha)
  1418. {
  1419. componentTransparency = newIntAlpha;
  1420. if (flags.hasHeavyweightPeerFlag)
  1421. {
  1422. ComponentPeer* const peer = getPeer();
  1423. if (peer != nullptr)
  1424. peer->setAlpha (newAlpha);
  1425. }
  1426. else
  1427. {
  1428. repaint();
  1429. }
  1430. }
  1431. }
  1432. float Component::getAlpha() const
  1433. {
  1434. return (255 - componentTransparency) / 255.0f;
  1435. }
  1436. //==============================================================================
  1437. void Component::repaint()
  1438. {
  1439. internalRepaintUnchecked (getLocalBounds(), true);
  1440. }
  1441. void Component::repaint (const int x, const int y, const int w, const int h)
  1442. {
  1443. internalRepaint (Rectangle<int> (x, y, w, h));
  1444. }
  1445. void Component::repaint (const Rectangle<int>& area)
  1446. {
  1447. internalRepaint (area);
  1448. }
  1449. void Component::repaintParent()
  1450. {
  1451. if (parentComponent != nullptr)
  1452. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, getLocalBounds()));
  1453. }
  1454. void Component::internalRepaint (const Rectangle<int>& area)
  1455. {
  1456. const Rectangle<int> r (area.getIntersection (getLocalBounds()));
  1457. if (! r.isEmpty())
  1458. internalRepaintUnchecked (r, false);
  1459. }
  1460. void Component::internalRepaintUnchecked (const Rectangle<int>& area, const bool isEntireComponent)
  1461. {
  1462. // if component methods are being called from threads other than the message
  1463. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1464. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1465. if (flags.visibleFlag)
  1466. {
  1467. if (flags.hasHeavyweightPeerFlag)
  1468. {
  1469. ComponentPeer* const peer = getPeer();
  1470. if (peer != nullptr)
  1471. peer->repaint (area);
  1472. }
  1473. else
  1474. {
  1475. if (cachedImage != nullptr)
  1476. {
  1477. if (isEntireComponent)
  1478. cachedImage->invalidateAll();
  1479. else
  1480. cachedImage->invalidate (area);
  1481. }
  1482. if (parentComponent != nullptr)
  1483. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, area));
  1484. }
  1485. }
  1486. }
  1487. //==============================================================================
  1488. void Component::paintWithinParentContext (Graphics& g)
  1489. {
  1490. g.setOrigin (getX(), getY());
  1491. if (cachedImage != nullptr)
  1492. cachedImage->paint (g);
  1493. else
  1494. paintEntireComponent (g, false);
  1495. }
  1496. void Component::paintComponentAndChildren (Graphics& g)
  1497. {
  1498. const Rectangle<int> clipBounds (g.getClipBounds());
  1499. if (flags.dontClipGraphicsFlag)
  1500. {
  1501. paint (g);
  1502. }
  1503. else
  1504. {
  1505. g.saveState();
  1506. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  1507. if (! g.isClipEmpty())
  1508. paint (g);
  1509. g.restoreState();
  1510. }
  1511. for (int i = 0; i < childComponentList.size(); ++i)
  1512. {
  1513. Component& child = *childComponentList.getUnchecked (i);
  1514. if (child.isVisible())
  1515. {
  1516. if (child.affineTransform != nullptr)
  1517. {
  1518. g.saveState();
  1519. g.addTransform (*child.affineTransform);
  1520. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  1521. child.paintWithinParentContext (g);
  1522. g.restoreState();
  1523. }
  1524. else if (clipBounds.intersects (child.getBounds()))
  1525. {
  1526. g.saveState();
  1527. if (child.flags.dontClipGraphicsFlag)
  1528. {
  1529. child.paintWithinParentContext (g);
  1530. }
  1531. else if (g.reduceClipRegion (child.getBounds()))
  1532. {
  1533. bool nothingClipped = true;
  1534. for (int j = i + 1; j < childComponentList.size(); ++j)
  1535. {
  1536. const Component& sibling = *childComponentList.getUnchecked (j);
  1537. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == nullptr)
  1538. {
  1539. nothingClipped = false;
  1540. g.excludeClipRegion (sibling.getBounds());
  1541. }
  1542. }
  1543. if (nothingClipped || ! g.isClipEmpty())
  1544. child.paintWithinParentContext (g);
  1545. }
  1546. g.restoreState();
  1547. }
  1548. }
  1549. }
  1550. g.saveState();
  1551. paintOverChildren (g);
  1552. g.restoreState();
  1553. }
  1554. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  1555. {
  1556. #if JUCE_DEBUG
  1557. flags.isInsidePaintCall = true;
  1558. #endif
  1559. if (effect != nullptr)
  1560. {
  1561. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  1562. getWidth(), getHeight(), ! flags.opaqueFlag);
  1563. {
  1564. Graphics g2 (effectImage);
  1565. paintComponentAndChildren (g2);
  1566. }
  1567. effect->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  1568. }
  1569. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  1570. {
  1571. if (componentTransparency < 255)
  1572. {
  1573. g.beginTransparencyLayer (getAlpha());
  1574. paintComponentAndChildren (g);
  1575. g.endTransparencyLayer();
  1576. }
  1577. }
  1578. else
  1579. {
  1580. paintComponentAndChildren (g);
  1581. }
  1582. #if JUCE_DEBUG
  1583. flags.isInsidePaintCall = false;
  1584. #endif
  1585. }
  1586. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) noexcept
  1587. {
  1588. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  1589. }
  1590. //==============================================================================
  1591. Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  1592. const bool clipImageToComponentBounds)
  1593. {
  1594. Rectangle<int> r (areaToGrab);
  1595. if (clipImageToComponentBounds)
  1596. r = r.getIntersection (getLocalBounds());
  1597. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  1598. jmax (1, r.getWidth()),
  1599. jmax (1, r.getHeight()),
  1600. true);
  1601. Graphics imageContext (componentImage);
  1602. imageContext.setOrigin (-r.getX(), -r.getY());
  1603. paintEntireComponent (imageContext, true);
  1604. return componentImage;
  1605. }
  1606. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  1607. {
  1608. if (effect != newEffect)
  1609. {
  1610. effect = newEffect;
  1611. repaint();
  1612. }
  1613. }
  1614. //==============================================================================
  1615. LookAndFeel& Component::getLookAndFeel() const noexcept
  1616. {
  1617. const Component* c = this;
  1618. do
  1619. {
  1620. if (c->lookAndFeel != nullptr)
  1621. return *(c->lookAndFeel);
  1622. c = c->parentComponent;
  1623. }
  1624. while (c != nullptr);
  1625. return LookAndFeel::getDefaultLookAndFeel();
  1626. }
  1627. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  1628. {
  1629. if (lookAndFeel != newLookAndFeel)
  1630. {
  1631. lookAndFeel = newLookAndFeel;
  1632. sendLookAndFeelChange();
  1633. }
  1634. }
  1635. void Component::lookAndFeelChanged()
  1636. {
  1637. }
  1638. void Component::sendLookAndFeelChange()
  1639. {
  1640. repaint();
  1641. const WeakReference<Component> safePointer (this);
  1642. lookAndFeelChanged();
  1643. if (safePointer != nullptr)
  1644. {
  1645. for (int i = childComponentList.size(); --i >= 0;)
  1646. {
  1647. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  1648. if (safePointer == nullptr)
  1649. return;
  1650. i = jmin (i, childComponentList.size());
  1651. }
  1652. }
  1653. }
  1654. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  1655. {
  1656. const var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  1657. if (v != nullptr)
  1658. return Colour ((uint32) static_cast <int> (*v));
  1659. if (inheritFromParent && parentComponent != nullptr
  1660. && (lookAndFeel == nullptr || ! lookAndFeel->isColourSpecified (colourId)))
  1661. return parentComponent->findColour (colourId, true);
  1662. return getLookAndFeel().findColour (colourId);
  1663. }
  1664. bool Component::isColourSpecified (const int colourId) const
  1665. {
  1666. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  1667. }
  1668. void Component::removeColour (const int colourId)
  1669. {
  1670. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  1671. colourChanged();
  1672. }
  1673. void Component::setColour (const int colourId, const Colour& colour)
  1674. {
  1675. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  1676. colourChanged();
  1677. }
  1678. void Component::copyAllExplicitColoursTo (Component& target) const
  1679. {
  1680. bool changed = false;
  1681. for (int i = properties.size(); --i >= 0;)
  1682. {
  1683. const Identifier name (properties.getName(i));
  1684. if (name.toString().startsWith ("jcclr_"))
  1685. if (target.properties.set (name, properties [name]))
  1686. changed = true;
  1687. }
  1688. if (changed)
  1689. target.colourChanged();
  1690. }
  1691. void Component::colourChanged()
  1692. {
  1693. }
  1694. //==============================================================================
  1695. MarkerList* Component::getMarkers (bool /*xAxis*/)
  1696. {
  1697. return nullptr;
  1698. }
  1699. //==============================================================================
  1700. Component::Positioner::Positioner (Component& component_) noexcept
  1701. : component (component_)
  1702. {
  1703. }
  1704. Component::Positioner* Component::getPositioner() const noexcept
  1705. {
  1706. return positioner;
  1707. }
  1708. void Component::setPositioner (Positioner* newPositioner)
  1709. {
  1710. // You can only assign a positioner to the component that it was created for!
  1711. jassert (newPositioner == nullptr || this == &(newPositioner->getComponent()));
  1712. positioner = newPositioner;
  1713. }
  1714. //==============================================================================
  1715. Rectangle<int> Component::getLocalBounds() const noexcept
  1716. {
  1717. return Rectangle<int> (getWidth(), getHeight());
  1718. }
  1719. Rectangle<int> Component::getBoundsInParent() const noexcept
  1720. {
  1721. return affineTransform == nullptr ? bounds
  1722. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  1723. }
  1724. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  1725. {
  1726. result.clear();
  1727. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  1728. if (! unclipped.isEmpty())
  1729. {
  1730. result.add (unclipped);
  1731. if (includeSiblings)
  1732. {
  1733. const Component* const c = getTopLevelComponent();
  1734. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  1735. c->getLocalBounds(), this);
  1736. }
  1737. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, nullptr);
  1738. result.consolidate();
  1739. }
  1740. }
  1741. //==============================================================================
  1742. void Component::mouseEnter (const MouseEvent&)
  1743. {
  1744. // base class does nothing
  1745. }
  1746. void Component::mouseExit (const MouseEvent&)
  1747. {
  1748. // base class does nothing
  1749. }
  1750. void Component::mouseDown (const MouseEvent&)
  1751. {
  1752. // base class does nothing
  1753. }
  1754. void Component::mouseUp (const MouseEvent&)
  1755. {
  1756. // base class does nothing
  1757. }
  1758. void Component::mouseDrag (const MouseEvent&)
  1759. {
  1760. // base class does nothing
  1761. }
  1762. void Component::mouseMove (const MouseEvent&)
  1763. {
  1764. // base class does nothing
  1765. }
  1766. void Component::mouseDoubleClick (const MouseEvent&)
  1767. {
  1768. // base class does nothing
  1769. }
  1770. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  1771. {
  1772. // the base class just passes this event up to its parent..
  1773. if (parentComponent != nullptr)
  1774. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent),
  1775. wheelIncrementX, wheelIncrementY);
  1776. }
  1777. //==============================================================================
  1778. void Component::resized()
  1779. {
  1780. // base class does nothing
  1781. }
  1782. void Component::moved()
  1783. {
  1784. // base class does nothing
  1785. }
  1786. void Component::childBoundsChanged (Component*)
  1787. {
  1788. // base class does nothing
  1789. }
  1790. void Component::parentSizeChanged()
  1791. {
  1792. // base class does nothing
  1793. }
  1794. void Component::addComponentListener (ComponentListener* const newListener)
  1795. {
  1796. // if component methods are being called from threads other than the message
  1797. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1798. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1799. componentListeners.add (newListener);
  1800. }
  1801. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  1802. {
  1803. componentListeners.remove (listenerToRemove);
  1804. }
  1805. //==============================================================================
  1806. void Component::inputAttemptWhenModal()
  1807. {
  1808. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1809. getLookAndFeel().playAlertSound();
  1810. }
  1811. bool Component::canModalEventBeSentToComponent (const Component*)
  1812. {
  1813. return false;
  1814. }
  1815. void Component::internalModalInputAttempt()
  1816. {
  1817. Component* const current = getCurrentlyModalComponent();
  1818. if (current != nullptr)
  1819. current->inputAttemptWhenModal();
  1820. }
  1821. //==============================================================================
  1822. void Component::paint (Graphics&)
  1823. {
  1824. // all painting is done in the subclasses
  1825. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  1826. }
  1827. void Component::paintOverChildren (Graphics&)
  1828. {
  1829. // all painting is done in the subclasses
  1830. }
  1831. //==============================================================================
  1832. void Component::postCommandMessage (const int commandId)
  1833. {
  1834. class CustomCommandMessage : public CallbackMessage
  1835. {
  1836. public:
  1837. CustomCommandMessage (Component* const target_, const int commandId_)
  1838. : target (target_), commandId (commandId_) {}
  1839. void messageCallback()
  1840. {
  1841. if (target.get() != nullptr) // (get() required for VS2003 bug)
  1842. target->handleCommandMessage (commandId);
  1843. }
  1844. private:
  1845. WeakReference<Component> target;
  1846. int commandId;
  1847. };
  1848. (new CustomCommandMessage (this, commandId))->post();
  1849. }
  1850. void Component::handleCommandMessage (int)
  1851. {
  1852. // used by subclasses
  1853. }
  1854. //==============================================================================
  1855. void Component::addMouseListener (MouseListener* const newListener,
  1856. const bool wantsEventsForAllNestedChildComponents)
  1857. {
  1858. // if component methods are being called from threads other than the message
  1859. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1860. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1861. // If you register a component as a mouselistener for itself, it'll receive all the events
  1862. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  1863. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  1864. if (mouseListeners == nullptr)
  1865. mouseListeners = new MouseListenerList();
  1866. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  1867. }
  1868. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  1869. {
  1870. // if component methods are being called from threads other than the message
  1871. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1872. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1873. if (mouseListeners != nullptr)
  1874. mouseListeners->removeListener (listenerToRemove);
  1875. }
  1876. //==============================================================================
  1877. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1878. {
  1879. if (isCurrentlyBlockedByAnotherModalComponent())
  1880. {
  1881. // if something else is modal, always just show a normal mouse cursor
  1882. source.showMouseCursor (MouseCursor::NormalCursor);
  1883. return;
  1884. }
  1885. if (flags.repaintOnMouseActivityFlag)
  1886. repaint();
  1887. BailOutChecker checker (this);
  1888. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1889. this, this, time, relativePos, time, 0, false);
  1890. mouseEnter (me);
  1891. if (checker.shouldBailOut())
  1892. return;
  1893. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseEnter, me);
  1894. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  1895. }
  1896. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1897. {
  1898. if (flags.repaintOnMouseActivityFlag)
  1899. repaint();
  1900. BailOutChecker checker (this);
  1901. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1902. this, this, time, relativePos, time, 0, false);
  1903. mouseExit (me);
  1904. if (checker.shouldBailOut())
  1905. return;
  1906. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseExit, me);
  1907. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  1908. }
  1909. //==============================================================================
  1910. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1911. {
  1912. Desktop& desktop = Desktop::getInstance();
  1913. BailOutChecker checker (this);
  1914. if (isCurrentlyBlockedByAnotherModalComponent())
  1915. {
  1916. internalModalInputAttempt();
  1917. if (checker.shouldBailOut())
  1918. return;
  1919. // If processing the input attempt has exited the modal loop, we'll allow the event
  1920. // to be delivered..
  1921. if (isCurrentlyBlockedByAnotherModalComponent())
  1922. {
  1923. // allow blocked mouse-events to go to global listeners..
  1924. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1925. this, this, time, relativePos, time,
  1926. source.getNumberOfMultipleClicks(), false);
  1927. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseDown, me);
  1928. return;
  1929. }
  1930. }
  1931. for (Component* c = this; c != nullptr; c = c->parentComponent)
  1932. {
  1933. if (c->isBroughtToFrontOnMouseClick())
  1934. {
  1935. c->toFront (true);
  1936. if (checker.shouldBailOut())
  1937. return;
  1938. }
  1939. }
  1940. if (! flags.dontFocusOnMouseClickFlag)
  1941. {
  1942. grabFocusInternal (focusChangedByMouseClick, true);
  1943. if (checker.shouldBailOut())
  1944. return;
  1945. }
  1946. if (flags.repaintOnMouseActivityFlag)
  1947. repaint();
  1948. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1949. this, this, time, relativePos, time,
  1950. source.getNumberOfMultipleClicks(), false);
  1951. mouseDown (me);
  1952. if (checker.shouldBailOut())
  1953. return;
  1954. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseDown, me);
  1955. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  1956. }
  1957. //==============================================================================
  1958. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  1959. {
  1960. BailOutChecker checker (this);
  1961. if (flags.repaintOnMouseActivityFlag)
  1962. repaint();
  1963. const MouseEvent me (source, relativePos,
  1964. oldModifiers, this, this, time,
  1965. getLocalPoint (nullptr, source.getLastMouseDownPosition()),
  1966. source.getLastMouseDownTime(),
  1967. source.getNumberOfMultipleClicks(),
  1968. source.hasMouseMovedSignificantlySincePressed());
  1969. mouseUp (me);
  1970. if (checker.shouldBailOut())
  1971. return;
  1972. Desktop& desktop = Desktop::getInstance();
  1973. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseUp, me);
  1974. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  1975. if (checker.shouldBailOut())
  1976. return;
  1977. // check for double-click
  1978. if (me.getNumberOfClicks() >= 2)
  1979. {
  1980. mouseDoubleClick (me);
  1981. if (checker.shouldBailOut())
  1982. return;
  1983. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  1984. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  1985. }
  1986. }
  1987. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1988. {
  1989. BailOutChecker checker (this);
  1990. const MouseEvent me (source, relativePos,
  1991. source.getCurrentModifiers(), this, this, time,
  1992. getLocalPoint (nullptr, source.getLastMouseDownPosition()),
  1993. source.getLastMouseDownTime(),
  1994. source.getNumberOfMultipleClicks(),
  1995. source.hasMouseMovedSignificantlySincePressed());
  1996. mouseDrag (me);
  1997. if (checker.shouldBailOut())
  1998. return;
  1999. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseDrag, me);
  2000. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  2001. }
  2002. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  2003. {
  2004. Desktop& desktop = Desktop::getInstance();
  2005. BailOutChecker checker (this);
  2006. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  2007. this, this, time, relativePos, time, 0, false);
  2008. if (isCurrentlyBlockedByAnotherModalComponent())
  2009. {
  2010. // allow blocked mouse-events to go to global listeners..
  2011. desktop.sendMouseMove();
  2012. }
  2013. else
  2014. {
  2015. mouseMove (me);
  2016. if (checker.shouldBailOut())
  2017. return;
  2018. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseMove, me);
  2019. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  2020. }
  2021. }
  2022. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  2023. const Time& time, const float amountX, const float amountY)
  2024. {
  2025. Desktop& desktop = Desktop::getInstance();
  2026. BailOutChecker checker (this);
  2027. const float wheelIncrementX = amountX / 256.0f;
  2028. const float wheelIncrementY = amountY / 256.0f;
  2029. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  2030. this, this, time, relativePos, time, 0, false);
  2031. if (isCurrentlyBlockedByAnotherModalComponent())
  2032. {
  2033. // allow blocked mouse-events to go to global listeners..
  2034. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  2035. }
  2036. else
  2037. {
  2038. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  2039. if (checker.shouldBailOut())
  2040. return;
  2041. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  2042. if (! checker.shouldBailOut())
  2043. MouseListenerList::sendWheelEvent (*this, checker, me, wheelIncrementX, wheelIncrementY);
  2044. }
  2045. }
  2046. void Component::sendFakeMouseMove() const
  2047. {
  2048. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  2049. if (! mainMouse.isDragging())
  2050. mainMouse.triggerFakeMove();
  2051. }
  2052. void Component::beginDragAutoRepeat (const int interval)
  2053. {
  2054. Desktop::getInstance().beginDragAutoRepeat (interval);
  2055. }
  2056. void Component::broughtToFront()
  2057. {
  2058. }
  2059. void Component::internalBroughtToFront()
  2060. {
  2061. if (flags.hasHeavyweightPeerFlag)
  2062. Desktop::getInstance().componentBroughtToFront (this);
  2063. BailOutChecker checker (this);
  2064. broughtToFront();
  2065. if (checker.shouldBailOut())
  2066. return;
  2067. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  2068. if (checker.shouldBailOut())
  2069. return;
  2070. // When brought to the front and there's a modal component blocking this one,
  2071. // we need to bring the modal one to the front instead..
  2072. Component* const cm = getCurrentlyModalComponent();
  2073. if (cm != nullptr && cm->getTopLevelComponent() != getTopLevelComponent())
  2074. ModalComponentManager::getInstance()->bringModalComponentsToFront (false); // very important that this is false, otherwise in Windows,
  2075. // non-front components can't get focus when another modal comp is
  2076. // active, and therefore can't receive mouse-clicks
  2077. }
  2078. void Component::focusGained (FocusChangeType)
  2079. {
  2080. // base class does nothing
  2081. }
  2082. void Component::internalFocusGain (const FocusChangeType cause)
  2083. {
  2084. internalFocusGain (cause, WeakReference<Component> (this));
  2085. }
  2086. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  2087. {
  2088. focusGained (cause);
  2089. if (safePointer != nullptr)
  2090. internalChildFocusChange (cause, safePointer);
  2091. }
  2092. void Component::focusLost (FocusChangeType)
  2093. {
  2094. // base class does nothing
  2095. }
  2096. void Component::internalFocusLoss (const FocusChangeType cause)
  2097. {
  2098. const WeakReference<Component> safePointer (this);
  2099. focusLost (focusChangedDirectly);
  2100. if (safePointer != nullptr)
  2101. internalChildFocusChange (cause, safePointer);
  2102. }
  2103. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  2104. {
  2105. // base class does nothing
  2106. }
  2107. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  2108. {
  2109. const bool childIsNowFocused = hasKeyboardFocus (true);
  2110. if (flags.childCompFocusedFlag != childIsNowFocused)
  2111. {
  2112. flags.childCompFocusedFlag = childIsNowFocused;
  2113. focusOfChildComponentChanged (cause);
  2114. if (safePointer == nullptr)
  2115. return;
  2116. }
  2117. if (parentComponent != nullptr)
  2118. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  2119. }
  2120. //==============================================================================
  2121. bool Component::isEnabled() const noexcept
  2122. {
  2123. return (! flags.isDisabledFlag)
  2124. && (parentComponent == nullptr || parentComponent->isEnabled());
  2125. }
  2126. void Component::setEnabled (const bool shouldBeEnabled)
  2127. {
  2128. if (flags.isDisabledFlag == shouldBeEnabled)
  2129. {
  2130. flags.isDisabledFlag = ! shouldBeEnabled;
  2131. // if any parent components are disabled, setting our flag won't make a difference,
  2132. // so no need to send a change message
  2133. if (parentComponent == nullptr || parentComponent->isEnabled())
  2134. sendEnablementChangeMessage();
  2135. }
  2136. }
  2137. void Component::sendEnablementChangeMessage()
  2138. {
  2139. const WeakReference<Component> safePointer (this);
  2140. enablementChanged();
  2141. if (safePointer == nullptr)
  2142. return;
  2143. for (int i = getNumChildComponents(); --i >= 0;)
  2144. {
  2145. Component* const c = getChildComponent (i);
  2146. if (c != nullptr)
  2147. {
  2148. c->sendEnablementChangeMessage();
  2149. if (safePointer == nullptr)
  2150. return;
  2151. }
  2152. }
  2153. }
  2154. void Component::enablementChanged()
  2155. {
  2156. }
  2157. //==============================================================================
  2158. void Component::setWantsKeyboardFocus (const bool wantsFocus) noexcept
  2159. {
  2160. flags.wantsFocusFlag = wantsFocus;
  2161. }
  2162. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  2163. {
  2164. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  2165. }
  2166. bool Component::getMouseClickGrabsKeyboardFocus() const noexcept
  2167. {
  2168. return ! flags.dontFocusOnMouseClickFlag;
  2169. }
  2170. bool Component::getWantsKeyboardFocus() const noexcept
  2171. {
  2172. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  2173. }
  2174. void Component::setFocusContainer (const bool shouldBeFocusContainer) noexcept
  2175. {
  2176. flags.isFocusContainerFlag = shouldBeFocusContainer;
  2177. }
  2178. bool Component::isFocusContainer() const noexcept
  2179. {
  2180. return flags.isFocusContainerFlag;
  2181. }
  2182. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  2183. int Component::getExplicitFocusOrder() const
  2184. {
  2185. return properties [juce_explicitFocusOrderId];
  2186. }
  2187. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  2188. {
  2189. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  2190. }
  2191. KeyboardFocusTraverser* Component::createFocusTraverser()
  2192. {
  2193. if (flags.isFocusContainerFlag || parentComponent == nullptr)
  2194. return new KeyboardFocusTraverser();
  2195. return parentComponent->createFocusTraverser();
  2196. }
  2197. void Component::takeKeyboardFocus (const FocusChangeType cause)
  2198. {
  2199. // give the focus to this component
  2200. if (currentlyFocusedComponent != this)
  2201. {
  2202. // get the focus onto our desktop window
  2203. ComponentPeer* const peer = getPeer();
  2204. if (peer != nullptr)
  2205. {
  2206. const WeakReference<Component> safePointer (this);
  2207. peer->grabFocus();
  2208. if (peer->isFocused() && currentlyFocusedComponent != this)
  2209. {
  2210. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  2211. currentlyFocusedComponent = this;
  2212. Desktop::getInstance().triggerFocusCallback();
  2213. // call this after setting currentlyFocusedComponent so that the one that's
  2214. // losing it has a chance to see where focus is going
  2215. if (componentLosingFocus != nullptr)
  2216. componentLosingFocus->internalFocusLoss (cause);
  2217. if (currentlyFocusedComponent == this)
  2218. internalFocusGain (cause, safePointer);
  2219. }
  2220. }
  2221. }
  2222. }
  2223. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  2224. {
  2225. if (isShowing())
  2226. {
  2227. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == nullptr))
  2228. {
  2229. takeKeyboardFocus (cause);
  2230. }
  2231. else
  2232. {
  2233. if (isParentOf (currentlyFocusedComponent)
  2234. && currentlyFocusedComponent->isShowing())
  2235. {
  2236. // do nothing if the focused component is actually a child of ours..
  2237. }
  2238. else
  2239. {
  2240. // find the default child component..
  2241. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  2242. if (traverser != nullptr)
  2243. {
  2244. Component* const defaultComp = traverser->getDefaultComponent (this);
  2245. traverser = nullptr;
  2246. if (defaultComp != nullptr)
  2247. {
  2248. defaultComp->grabFocusInternal (cause, false);
  2249. return;
  2250. }
  2251. }
  2252. if (canTryParent && parentComponent != nullptr)
  2253. {
  2254. // if no children want it and we're allowed to try our parent comp,
  2255. // then pass up to parent, which will try our siblings.
  2256. parentComponent->grabFocusInternal (cause, true);
  2257. }
  2258. }
  2259. }
  2260. }
  2261. }
  2262. void Component::grabKeyboardFocus()
  2263. {
  2264. // if component methods are being called from threads other than the message
  2265. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  2266. CHECK_MESSAGE_MANAGER_IS_LOCKED
  2267. grabFocusInternal (focusChangedDirectly, true);
  2268. }
  2269. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  2270. {
  2271. // if component methods are being called from threads other than the message
  2272. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  2273. CHECK_MESSAGE_MANAGER_IS_LOCKED
  2274. if (parentComponent != nullptr)
  2275. {
  2276. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  2277. if (traverser != nullptr)
  2278. {
  2279. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  2280. : traverser->getPreviousComponent (this);
  2281. traverser = nullptr;
  2282. if (nextComp != nullptr)
  2283. {
  2284. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  2285. {
  2286. const WeakReference<Component> nextCompPointer (nextComp);
  2287. internalModalInputAttempt();
  2288. if (nextCompPointer == nullptr || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  2289. return;
  2290. }
  2291. nextComp->grabFocusInternal (focusChangedByTabKey, true);
  2292. return;
  2293. }
  2294. }
  2295. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  2296. }
  2297. }
  2298. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  2299. {
  2300. return (currentlyFocusedComponent == this)
  2301. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  2302. }
  2303. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() noexcept
  2304. {
  2305. return currentlyFocusedComponent;
  2306. }
  2307. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  2308. {
  2309. Component* const componentLosingFocus = currentlyFocusedComponent;
  2310. currentlyFocusedComponent = nullptr;
  2311. if (sendFocusLossEvent && componentLosingFocus != nullptr)
  2312. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  2313. Desktop::getInstance().triggerFocusCallback();
  2314. }
  2315. //==============================================================================
  2316. bool Component::isMouseOver (const bool includeChildren) const
  2317. {
  2318. const Desktop& desktop = Desktop::getInstance();
  2319. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  2320. {
  2321. const MouseInputSource* const mi = desktop.getMouseSource(i);
  2322. Component* const c = mi->getComponentUnderMouse();
  2323. if ((c == this || (includeChildren && isParentOf (c)))
  2324. && c->reallyContains (c->getLocalPoint (nullptr, mi->getScreenPosition()), false))
  2325. return true;
  2326. }
  2327. return false;
  2328. }
  2329. bool Component::isMouseButtonDown() const
  2330. {
  2331. const Desktop& desktop = Desktop::getInstance();
  2332. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  2333. {
  2334. const MouseInputSource* const mi = desktop.getMouseSource(i);
  2335. if (mi->isDragging() && mi->getComponentUnderMouse() == this)
  2336. return true;
  2337. }
  2338. return false;
  2339. }
  2340. bool Component::isMouseOverOrDragging() const
  2341. {
  2342. const Desktop& desktop = Desktop::getInstance();
  2343. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  2344. if (desktop.getMouseSource(i)->getComponentUnderMouse() == this)
  2345. return true;
  2346. return false;
  2347. }
  2348. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() noexcept
  2349. {
  2350. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  2351. }
  2352. Point<int> Component::getMouseXYRelative() const
  2353. {
  2354. return getLocalPoint (nullptr, Desktop::getMousePosition());
  2355. }
  2356. //==============================================================================
  2357. Rectangle<int> Component::getParentMonitorArea() const
  2358. {
  2359. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  2360. }
  2361. //==============================================================================
  2362. void Component::addKeyListener (KeyListener* const newListener)
  2363. {
  2364. if (keyListeners == nullptr)
  2365. keyListeners = new Array <KeyListener*>();
  2366. keyListeners->addIfNotAlreadyThere (newListener);
  2367. }
  2368. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  2369. {
  2370. if (keyListeners != nullptr)
  2371. keyListeners->removeValue (listenerToRemove);
  2372. }
  2373. bool Component::keyPressed (const KeyPress&)
  2374. {
  2375. return false;
  2376. }
  2377. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  2378. {
  2379. return false;
  2380. }
  2381. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  2382. {
  2383. if (parentComponent != nullptr)
  2384. parentComponent->modifierKeysChanged (modifiers);
  2385. }
  2386. void Component::internalModifierKeysChanged()
  2387. {
  2388. sendFakeMouseMove();
  2389. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  2390. }
  2391. //==============================================================================
  2392. ComponentPeer* Component::getPeer() const
  2393. {
  2394. if (flags.hasHeavyweightPeerFlag)
  2395. return ComponentPeer::getPeerFor (this);
  2396. else if (parentComponent == nullptr)
  2397. return nullptr;
  2398. return parentComponent->getPeer();
  2399. }
  2400. //==============================================================================
  2401. Component::BailOutChecker::BailOutChecker (Component* const component)
  2402. : safePointer (component)
  2403. {
  2404. jassert (component != nullptr);
  2405. }
  2406. bool Component::BailOutChecker::shouldBailOut() const noexcept
  2407. {
  2408. return safePointer == nullptr;
  2409. }
  2410. END_JUCE_NAMESPACE