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.

2985 lines
88KB

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