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.

634 lines
21KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. Viewport::Viewport (const String& name) : Component (name)
  21. {
  22. // content holder is used to clip the contents so they don't overlap the scrollbars
  23. addAndMakeVisible (contentHolder);
  24. contentHolder.setInterceptsMouseClicks (false, true);
  25. scrollBarThickness = getLookAndFeel().getDefaultScrollbarWidth();
  26. setInterceptsMouseClicks (false, true);
  27. setWantsKeyboardFocus (true);
  28. setScrollOnDragEnabled (Desktop::getInstance().getMainMouseSource().isTouch());
  29. recreateScrollbars();
  30. }
  31. Viewport::~Viewport()
  32. {
  33. setScrollOnDragEnabled (false);
  34. deleteOrRemoveContentComp();
  35. }
  36. //==============================================================================
  37. void Viewport::visibleAreaChanged (const Rectangle<int>&) {}
  38. void Viewport::viewedComponentChanged (Component*) {}
  39. //==============================================================================
  40. void Viewport::deleteOrRemoveContentComp()
  41. {
  42. if (contentComp != nullptr)
  43. {
  44. contentComp->removeComponentListener (this);
  45. if (deleteContent)
  46. {
  47. // This sets the content comp to a null pointer before deleting the old one, in case
  48. // anything tries to use the old one while it's in mid-deletion..
  49. std::unique_ptr<Component> oldCompDeleter (contentComp.get());
  50. contentComp = nullptr;
  51. }
  52. else
  53. {
  54. contentHolder.removeChildComponent (contentComp);
  55. contentComp = nullptr;
  56. }
  57. }
  58. }
  59. void Viewport::setViewedComponent (Component* const newViewedComponent, const bool deleteComponentWhenNoLongerNeeded)
  60. {
  61. if (contentComp.get() != newViewedComponent)
  62. {
  63. deleteOrRemoveContentComp();
  64. contentComp = newViewedComponent;
  65. deleteContent = deleteComponentWhenNoLongerNeeded;
  66. if (contentComp != nullptr)
  67. {
  68. contentHolder.addAndMakeVisible (contentComp);
  69. setViewPosition (Point<int>());
  70. contentComp->addComponentListener (this);
  71. }
  72. viewedComponentChanged (contentComp);
  73. updateVisibleArea();
  74. }
  75. }
  76. void Viewport::recreateScrollbars()
  77. {
  78. verticalScrollBar.reset();
  79. horizontalScrollBar.reset();
  80. verticalScrollBar .reset (createScrollBarComponent (true));
  81. horizontalScrollBar.reset (createScrollBarComponent (false));
  82. addChildComponent (verticalScrollBar.get());
  83. addChildComponent (horizontalScrollBar.get());
  84. getVerticalScrollBar().addListener (this);
  85. getHorizontalScrollBar().addListener (this);
  86. resized();
  87. }
  88. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  89. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  90. bool Viewport::canScrollVertically() const noexcept { return contentComp->getY() < 0 || contentComp->getBottom() > getHeight(); }
  91. bool Viewport::canScrollHorizontally() const noexcept { return contentComp->getX() < 0 || contentComp->getRight() > getWidth(); }
  92. Point<int> Viewport::viewportPosToCompPos (Point<int> pos) const
  93. {
  94. jassert (contentComp != nullptr);
  95. auto contentBounds = contentHolder.getLocalArea (contentComp.get(), contentComp->getLocalBounds());
  96. Point<int> p (jmax (jmin (0, contentHolder.getWidth() - contentBounds.getWidth()), jmin (0, -(pos.x))),
  97. jmax (jmin (0, contentHolder.getHeight() - contentBounds.getHeight()), jmin (0, -(pos.y))));
  98. return p.transformedBy (contentComp->getTransform().inverted());
  99. }
  100. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  101. {
  102. setViewPosition ({ xPixelsOffset, yPixelsOffset });
  103. }
  104. void Viewport::setViewPosition (Point<int> newPosition)
  105. {
  106. if (contentComp != nullptr)
  107. contentComp->setTopLeftPosition (viewportPosToCompPos (newPosition));
  108. }
  109. void Viewport::setViewPositionProportionately (const double x, const double y)
  110. {
  111. if (contentComp != nullptr)
  112. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  113. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  114. }
  115. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  116. {
  117. if (contentComp != nullptr)
  118. {
  119. int dx = 0, dy = 0;
  120. if (getHorizontalScrollBar().isVisible() || canScrollHorizontally())
  121. {
  122. if (mouseX < activeBorderThickness)
  123. dx = activeBorderThickness - mouseX;
  124. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  125. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  126. if (dx < 0)
  127. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  128. else
  129. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  130. }
  131. if (getVerticalScrollBar().isVisible() || canScrollVertically())
  132. {
  133. if (mouseY < activeBorderThickness)
  134. dy = activeBorderThickness - mouseY;
  135. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  136. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  137. if (dy < 0)
  138. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  139. else
  140. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  141. }
  142. if (dx != 0 || dy != 0)
  143. {
  144. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  145. contentComp->getY() + dy);
  146. return true;
  147. }
  148. }
  149. return false;
  150. }
  151. void Viewport::componentMovedOrResized (Component&, bool, bool)
  152. {
  153. updateVisibleArea();
  154. }
  155. //==============================================================================
  156. typedef AnimatedPosition<AnimatedPositionBehaviours::ContinuousWithMomentum> ViewportDragPosition;
  157. struct Viewport::DragToScrollListener : private MouseListener,
  158. private ViewportDragPosition::Listener
  159. {
  160. DragToScrollListener (Viewport& v) : viewport (v)
  161. {
  162. viewport.contentHolder.addMouseListener (this, true);
  163. offsetX.addListener (this);
  164. offsetY.addListener (this);
  165. offsetX.behaviour.setMinimumVelocity (60);
  166. offsetY.behaviour.setMinimumVelocity (60);
  167. }
  168. ~DragToScrollListener() override
  169. {
  170. viewport.contentHolder.removeMouseListener (this);
  171. Desktop::getInstance().removeGlobalMouseListener (this);
  172. }
  173. void positionChanged (ViewportDragPosition&, double) override
  174. {
  175. viewport.setViewPosition (originalViewPos - Point<int> ((int) offsetX.getPosition(),
  176. (int) offsetY.getPosition()));
  177. }
  178. void mouseDown (const MouseEvent& e) override
  179. {
  180. if (! isGlobalMouseListener)
  181. {
  182. offsetX.setPosition (offsetX.getPosition());
  183. offsetY.setPosition (offsetY.getPosition());
  184. // switch to a global mouse listener so we still receive mouseUp events
  185. // if the original event component is deleted
  186. viewport.contentHolder.removeMouseListener (this);
  187. Desktop::getInstance().addGlobalMouseListener (this);
  188. isGlobalMouseListener = true;
  189. scrollSource = e.source;
  190. }
  191. }
  192. void mouseDrag (const MouseEvent& e) override
  193. {
  194. if (e.source == scrollSource
  195. && ! doesMouseEventComponentBlockViewportDrag (e.eventComponent))
  196. {
  197. auto totalOffset = e.getOffsetFromDragStart().toFloat();
  198. if (! isDragging && totalOffset.getDistanceFromOrigin() > 8.0f)
  199. {
  200. isDragging = true;
  201. originalViewPos = viewport.getViewPosition();
  202. offsetX.setPosition (0.0);
  203. offsetX.beginDrag();
  204. offsetY.setPosition (0.0);
  205. offsetY.beginDrag();
  206. }
  207. if (isDragging)
  208. {
  209. offsetX.drag (totalOffset.x);
  210. offsetY.drag (totalOffset.y);
  211. }
  212. }
  213. }
  214. void mouseUp (const MouseEvent& e) override
  215. {
  216. if (isGlobalMouseListener && e.source == scrollSource)
  217. endDragAndClearGlobalMouseListener();
  218. }
  219. void endDragAndClearGlobalMouseListener()
  220. {
  221. offsetX.endDrag();
  222. offsetY.endDrag();
  223. isDragging = false;
  224. viewport.contentHolder.addMouseListener (this, true);
  225. Desktop::getInstance().removeGlobalMouseListener (this);
  226. isGlobalMouseListener = false;
  227. }
  228. bool doesMouseEventComponentBlockViewportDrag (const Component* eventComp)
  229. {
  230. for (auto c = eventComp; c != nullptr && c != &viewport; c = c->getParentComponent())
  231. if (c->getViewportIgnoreDragFlag())
  232. return true;
  233. return false;
  234. }
  235. Viewport& viewport;
  236. ViewportDragPosition offsetX, offsetY;
  237. Point<int> originalViewPos;
  238. MouseInputSource scrollSource = Desktop::getInstance().getMainMouseSource();
  239. bool isDragging = false;
  240. bool isGlobalMouseListener = false;
  241. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragToScrollListener)
  242. };
  243. void Viewport::setScrollOnDragEnabled (bool shouldScrollOnDrag)
  244. {
  245. if (isScrollOnDragEnabled() != shouldScrollOnDrag)
  246. {
  247. if (shouldScrollOnDrag)
  248. dragToScrollListener.reset (new DragToScrollListener (*this));
  249. else
  250. dragToScrollListener.reset();
  251. }
  252. }
  253. bool Viewport::isScrollOnDragEnabled() const noexcept
  254. {
  255. return dragToScrollListener != nullptr;
  256. }
  257. bool Viewport::isCurrentlyScrollingOnDrag() const noexcept
  258. {
  259. return dragToScrollListener != nullptr && dragToScrollListener->isDragging;
  260. }
  261. //==============================================================================
  262. void Viewport::lookAndFeelChanged()
  263. {
  264. if (! customScrollBarThickness)
  265. {
  266. scrollBarThickness = getLookAndFeel().getDefaultScrollbarWidth();
  267. resized();
  268. }
  269. }
  270. void Viewport::resized()
  271. {
  272. updateVisibleArea();
  273. }
  274. //==============================================================================
  275. void Viewport::updateVisibleArea()
  276. {
  277. auto scrollbarWidth = getScrollBarThickness();
  278. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  279. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  280. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  281. bool hBarVisible = false, vBarVisible = false;
  282. Rectangle<int> contentArea;
  283. for (int i = 3; --i >= 0;)
  284. {
  285. hBarVisible = canShowHBar && ! getHorizontalScrollBar().autoHides();
  286. vBarVisible = canShowVBar && ! getVerticalScrollBar().autoHides();
  287. contentArea = getLocalBounds();
  288. if (contentComp != nullptr && ! contentArea.contains (contentComp->getBounds()))
  289. {
  290. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  291. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  292. if (vBarVisible)
  293. contentArea.setWidth (getWidth() - scrollbarWidth);
  294. if (hBarVisible)
  295. contentArea.setHeight (getHeight() - scrollbarWidth);
  296. if (! contentArea.contains (contentComp->getBounds()))
  297. {
  298. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  299. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  300. }
  301. }
  302. if (vBarVisible) contentArea.setWidth (getWidth() - scrollbarWidth);
  303. if (hBarVisible) contentArea.setHeight (getHeight() - scrollbarWidth);
  304. if (! vScrollbarRight && vBarVisible)
  305. contentArea.setX (scrollbarWidth);
  306. if (! hScrollbarBottom && hBarVisible)
  307. contentArea.setY (scrollbarWidth);
  308. if (contentComp == nullptr)
  309. {
  310. contentHolder.setBounds (contentArea);
  311. break;
  312. }
  313. auto oldContentBounds = contentComp->getBounds();
  314. contentHolder.setBounds (contentArea);
  315. // If the content has changed its size, that might affect our scrollbars, so go round again and re-calculate..
  316. if (oldContentBounds == contentComp->getBounds())
  317. break;
  318. }
  319. Rectangle<int> contentBounds;
  320. if (auto cc = contentComp.get())
  321. contentBounds = contentHolder.getLocalArea (cc, cc->getLocalBounds());
  322. auto visibleOrigin = -contentBounds.getPosition();
  323. auto& hbar = getHorizontalScrollBar();
  324. auto& vbar = getVerticalScrollBar();
  325. hbar.setBounds (contentArea.getX(), hScrollbarBottom ? contentArea.getHeight() : 0, contentArea.getWidth(), scrollbarWidth);
  326. hbar.setRangeLimits (0.0, contentBounds.getWidth());
  327. hbar.setCurrentRange (visibleOrigin.x, contentArea.getWidth());
  328. hbar.setSingleStepSize (singleStepX);
  329. if (canShowHBar && ! hBarVisible)
  330. visibleOrigin.setX (0);
  331. vbar.setBounds (vScrollbarRight ? contentArea.getWidth() : 0, contentArea.getY(), scrollbarWidth, contentArea.getHeight());
  332. vbar.setRangeLimits (0.0, contentBounds.getHeight());
  333. vbar.setCurrentRange (visibleOrigin.y, contentArea.getHeight());
  334. vbar.setSingleStepSize (singleStepY);
  335. if (canShowVBar && ! vBarVisible)
  336. visibleOrigin.setY (0);
  337. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  338. hbar.setVisible (hBarVisible);
  339. vbar.setVisible (vBarVisible);
  340. if (contentComp != nullptr)
  341. {
  342. auto newContentCompPos = viewportPosToCompPos (visibleOrigin);
  343. if (contentComp->getBounds().getPosition() != newContentCompPos)
  344. {
  345. contentComp->setTopLeftPosition (newContentCompPos); // (this will re-entrantly call updateVisibleArea again)
  346. return;
  347. }
  348. }
  349. const Rectangle<int> visibleArea (visibleOrigin.x, visibleOrigin.y,
  350. jmin (contentBounds.getWidth() - visibleOrigin.x, contentArea.getWidth()),
  351. jmin (contentBounds.getHeight() - visibleOrigin.y, contentArea.getHeight()));
  352. if (lastVisibleArea != visibleArea)
  353. {
  354. lastVisibleArea = visibleArea;
  355. visibleAreaChanged (visibleArea);
  356. }
  357. hbar.handleUpdateNowIfNeeded();
  358. vbar.handleUpdateNowIfNeeded();
  359. }
  360. //==============================================================================
  361. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  362. {
  363. if (singleStepX != stepX || singleStepY != stepY)
  364. {
  365. singleStepX = stepX;
  366. singleStepY = stepY;
  367. updateVisibleArea();
  368. }
  369. }
  370. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  371. const bool showHorizontalScrollbarIfNeeded,
  372. const bool allowVerticalScrollingWithoutScrollbar,
  373. const bool allowHorizontalScrollingWithoutScrollbar)
  374. {
  375. allowScrollingWithoutScrollbarV = allowVerticalScrollingWithoutScrollbar;
  376. allowScrollingWithoutScrollbarH = allowHorizontalScrollingWithoutScrollbar;
  377. if (showVScrollbar != showVerticalScrollbarIfNeeded
  378. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  379. {
  380. showVScrollbar = showVerticalScrollbarIfNeeded;
  381. showHScrollbar = showHorizontalScrollbarIfNeeded;
  382. updateVisibleArea();
  383. }
  384. }
  385. void Viewport::setScrollBarThickness (const int thickness)
  386. {
  387. int newThickness;
  388. // To stay compatible with the previous code: use the
  389. // default thickness if thickness parameter is zero
  390. // or negative
  391. if (thickness <= 0)
  392. {
  393. customScrollBarThickness = false;
  394. newThickness = getLookAndFeel().getDefaultScrollbarWidth();
  395. }
  396. else
  397. {
  398. customScrollBarThickness = true;
  399. newThickness = thickness;
  400. }
  401. if (scrollBarThickness != newThickness)
  402. {
  403. scrollBarThickness = newThickness;
  404. updateVisibleArea();
  405. }
  406. }
  407. int Viewport::getScrollBarThickness() const
  408. {
  409. return scrollBarThickness;
  410. }
  411. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  412. {
  413. auto newRangeStartInt = roundToInt (newRangeStart);
  414. if (scrollBarThatHasMoved == horizontalScrollBar.get())
  415. {
  416. setViewPosition (newRangeStartInt, getViewPositionY());
  417. }
  418. else if (scrollBarThatHasMoved == verticalScrollBar.get())
  419. {
  420. setViewPosition (getViewPositionX(), newRangeStartInt);
  421. }
  422. }
  423. void Viewport::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  424. {
  425. if (! useMouseWheelMoveIfNeeded (e, wheel))
  426. Component::mouseWheelMove (e, wheel);
  427. }
  428. static int rescaleMouseWheelDistance (float distance, int singleStepSize) noexcept
  429. {
  430. if (distance == 0.0f)
  431. return 0;
  432. distance *= 14.0f * (float) singleStepSize;
  433. return roundToInt (distance < 0 ? jmin (distance, -1.0f)
  434. : jmax (distance, 1.0f));
  435. }
  436. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, const MouseWheelDetails& wheel)
  437. {
  438. if (! (e.mods.isAltDown() || e.mods.isCtrlDown() || e.mods.isCommandDown()))
  439. {
  440. const bool canScrollVert = (allowScrollingWithoutScrollbarV || getVerticalScrollBar().isVisible());
  441. const bool canScrollHorz = (allowScrollingWithoutScrollbarH || getHorizontalScrollBar().isVisible());
  442. if (canScrollHorz || canScrollVert)
  443. {
  444. auto deltaX = rescaleMouseWheelDistance (wheel.deltaX, singleStepX);
  445. auto deltaY = rescaleMouseWheelDistance (wheel.deltaY, singleStepY);
  446. auto pos = getViewPosition();
  447. if (deltaX != 0 && deltaY != 0 && canScrollHorz && canScrollVert)
  448. {
  449. pos.x -= deltaX;
  450. pos.y -= deltaY;
  451. }
  452. else if (canScrollHorz && (deltaX != 0 || e.mods.isShiftDown() || ! canScrollVert))
  453. {
  454. pos.x -= deltaX != 0 ? deltaX : deltaY;
  455. }
  456. else if (canScrollVert && deltaY != 0)
  457. {
  458. pos.y -= deltaY;
  459. }
  460. if (pos != getViewPosition())
  461. {
  462. setViewPosition (pos);
  463. return true;
  464. }
  465. }
  466. }
  467. return false;
  468. }
  469. static bool isUpDownKeyPress (const KeyPress& key)
  470. {
  471. return key == KeyPress::upKey
  472. || key == KeyPress::downKey
  473. || key == KeyPress::pageUpKey
  474. || key == KeyPress::pageDownKey
  475. || key == KeyPress::homeKey
  476. || key == KeyPress::endKey;
  477. }
  478. static bool isLeftRightKeyPress (const KeyPress& key)
  479. {
  480. return key == KeyPress::leftKey
  481. || key == KeyPress::rightKey;
  482. }
  483. bool Viewport::keyPressed (const KeyPress& key)
  484. {
  485. const bool isUpDownKey = isUpDownKeyPress (key);
  486. if (getVerticalScrollBar().isVisible() && isUpDownKey)
  487. return getVerticalScrollBar().keyPressed (key);
  488. const bool isLeftRightKey = isLeftRightKeyPress (key);
  489. if (getHorizontalScrollBar().isVisible() && (isUpDownKey || isLeftRightKey))
  490. return getHorizontalScrollBar().keyPressed (key);
  491. return false;
  492. }
  493. bool Viewport::respondsToKey (const KeyPress& key)
  494. {
  495. return isUpDownKeyPress (key) || isLeftRightKeyPress (key);
  496. }
  497. ScrollBar* Viewport::createScrollBarComponent (bool isVertical)
  498. {
  499. return new ScrollBar (isVertical);
  500. }
  501. void Viewport::setScrollBarPosition (bool verticalScrollbarOnRight,
  502. bool horizontalScrollbarAtBottom)
  503. {
  504. vScrollbarRight = verticalScrollbarOnRight;
  505. hScrollbarBottom = horizontalScrollbarAtBottom;
  506. resized();
  507. }
  508. } // namespace juce