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.

2973 lines
93KB

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