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.

2908 lines
91KB

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