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.

1748 lines
63KB

  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. class Slider::Pimpl : public AsyncUpdater, // this needs to be public otherwise it will cause an
  21. // error when JUCE_DLL_BUILD=1
  22. private Value::Listener
  23. {
  24. public:
  25. Pimpl (Slider& s, SliderStyle sliderStyle, TextEntryBoxPosition textBoxPosition)
  26. : owner (s),
  27. style (sliderStyle),
  28. textBoxPos (textBoxPosition)
  29. {
  30. rotaryParams.startAngleRadians = MathConstants<float>::pi * 1.2f;
  31. rotaryParams.endAngleRadians = MathConstants<float>::pi * 2.8f;
  32. rotaryParams.stopAtEnd = true;
  33. }
  34. ~Pimpl() override
  35. {
  36. currentValue.removeListener (this);
  37. valueMin.removeListener (this);
  38. valueMax.removeListener (this);
  39. popupDisplay.reset();
  40. }
  41. //==============================================================================
  42. void registerListeners()
  43. {
  44. currentValue.addListener (this);
  45. valueMin.addListener (this);
  46. valueMax.addListener (this);
  47. }
  48. bool isHorizontal() const noexcept
  49. {
  50. return style == LinearHorizontal
  51. || style == LinearBar
  52. || style == TwoValueHorizontal
  53. || style == ThreeValueHorizontal;
  54. }
  55. bool isVertical() const noexcept
  56. {
  57. return style == LinearVertical
  58. || style == LinearBarVertical
  59. || style == TwoValueVertical
  60. || style == ThreeValueVertical;
  61. }
  62. bool isRotary() const noexcept
  63. {
  64. return style == Rotary
  65. || style == RotaryHorizontalDrag
  66. || style == RotaryVerticalDrag
  67. || style == RotaryHorizontalVerticalDrag;
  68. }
  69. bool isBar() const noexcept
  70. {
  71. return style == LinearBar
  72. || style == LinearBarVertical;
  73. }
  74. bool isTwoValue() const noexcept
  75. {
  76. return style == TwoValueHorizontal
  77. || style == TwoValueVertical;
  78. }
  79. bool isThreeValue() const noexcept
  80. {
  81. return style == ThreeValueHorizontal
  82. || style == ThreeValueVertical;
  83. }
  84. bool incDecDragDirectionIsHorizontal() const noexcept
  85. {
  86. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  87. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  88. }
  89. float getPositionOfValue (double value) const
  90. {
  91. if (isHorizontal() || isVertical())
  92. return getLinearSliderPos (value);
  93. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  94. return 0.0f;
  95. }
  96. void updateRange()
  97. {
  98. // figure out the number of DPs needed to display all values at this
  99. // interval setting.
  100. numDecimalPlaces = 7;
  101. if (normRange.interval != 0.0)
  102. {
  103. int v = std::abs (roundToInt (normRange.interval * 10000000));
  104. while ((v % 10) == 0 && numDecimalPlaces > 0)
  105. {
  106. --numDecimalPlaces;
  107. v /= 10;
  108. }
  109. }
  110. // keep the current values inside the new range..
  111. if (style != TwoValueHorizontal && style != TwoValueVertical)
  112. {
  113. setValue (getValue(), dontSendNotification);
  114. }
  115. else
  116. {
  117. setMinValue (getMinValue(), dontSendNotification, false);
  118. setMaxValue (getMaxValue(), dontSendNotification, false);
  119. }
  120. updateText();
  121. }
  122. void setRange (double newMin, double newMax, double newInt)
  123. {
  124. normRange = NormalisableRange<double> (newMin, newMax, newInt,
  125. normRange.skew, normRange.symmetricSkew);
  126. updateRange();
  127. }
  128. void setNormalisableRange (NormalisableRange<double> newRange)
  129. {
  130. normRange = newRange;
  131. updateRange();
  132. }
  133. double getValue() const
  134. {
  135. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  136. // methods to get the two values.
  137. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  138. return currentValue.getValue();
  139. }
  140. void setValue (double newValue, NotificationType notification)
  141. {
  142. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  143. // methods to set the two values.
  144. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  145. newValue = constrainedValue (newValue);
  146. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  147. {
  148. jassert (static_cast<double> (valueMin.getValue()) <= static_cast<double> (valueMax.getValue()));
  149. newValue = jlimit (static_cast<double> (valueMin.getValue()),
  150. static_cast<double> (valueMax.getValue()),
  151. newValue);
  152. }
  153. if (newValue != lastCurrentValue)
  154. {
  155. if (valueBox != nullptr)
  156. valueBox->hideEditor (true);
  157. lastCurrentValue = newValue;
  158. // (need to do this comparison because the Value will use equalsWithSameType to compare
  159. // the new and old values, so will generate unwanted change events if the type changes)
  160. if (currentValue != newValue)
  161. currentValue = newValue;
  162. updateText();
  163. owner.repaint();
  164. updatePopupDisplay (newValue);
  165. triggerChangeMessage (notification);
  166. }
  167. }
  168. void setMinValue (double newValue, NotificationType notification, bool allowNudgingOfOtherValues)
  169. {
  170. // The minimum value only applies to sliders that are in two- or three-value mode.
  171. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  172. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  173. newValue = constrainedValue (newValue);
  174. if (style == TwoValueHorizontal || style == TwoValueVertical)
  175. {
  176. if (allowNudgingOfOtherValues && newValue > static_cast<double> (valueMax.getValue()))
  177. setMaxValue (newValue, notification, false);
  178. newValue = jmin (static_cast<double> (valueMax.getValue()), newValue);
  179. }
  180. else
  181. {
  182. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  183. setValue (newValue, notification);
  184. newValue = jmin (lastCurrentValue, newValue);
  185. }
  186. if (lastValueMin != newValue)
  187. {
  188. lastValueMin = newValue;
  189. valueMin = newValue;
  190. owner.repaint();
  191. updatePopupDisplay (newValue);
  192. triggerChangeMessage (notification);
  193. }
  194. }
  195. void setMaxValue (double newValue, NotificationType notification, bool allowNudgingOfOtherValues)
  196. {
  197. // The maximum value only applies to sliders that are in two- or three-value mode.
  198. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  199. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  200. newValue = constrainedValue (newValue);
  201. if (style == TwoValueHorizontal || style == TwoValueVertical)
  202. {
  203. if (allowNudgingOfOtherValues && newValue < static_cast<double> (valueMin.getValue()))
  204. setMinValue (newValue, notification, false);
  205. newValue = jmax (static_cast<double> (valueMin.getValue()), newValue);
  206. }
  207. else
  208. {
  209. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  210. setValue (newValue, notification);
  211. newValue = jmax (lastCurrentValue, newValue);
  212. }
  213. if (lastValueMax != newValue)
  214. {
  215. lastValueMax = newValue;
  216. valueMax = newValue;
  217. owner.repaint();
  218. updatePopupDisplay (valueMax.getValue());
  219. triggerChangeMessage (notification);
  220. }
  221. }
  222. void setMinAndMaxValues (double newMinValue, double newMaxValue, NotificationType notification)
  223. {
  224. // The maximum value only applies to sliders that are in two- or three-value mode.
  225. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  226. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  227. if (newMaxValue < newMinValue)
  228. std::swap (newMaxValue, newMinValue);
  229. newMinValue = constrainedValue (newMinValue);
  230. newMaxValue = constrainedValue (newMaxValue);
  231. if (lastValueMax != newMaxValue || lastValueMin != newMinValue)
  232. {
  233. lastValueMax = newMaxValue;
  234. lastValueMin = newMinValue;
  235. valueMin = newMinValue;
  236. valueMax = newMaxValue;
  237. owner.repaint();
  238. triggerChangeMessage (notification);
  239. }
  240. }
  241. double getMinValue() const
  242. {
  243. // The minimum value only applies to sliders that are in two- or three-value mode.
  244. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  245. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  246. return valueMin.getValue();
  247. }
  248. double getMaxValue() const
  249. {
  250. // The maximum value only applies to sliders that are in two- or three-value mode.
  251. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  252. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  253. return valueMax.getValue();
  254. }
  255. void triggerChangeMessage (NotificationType notification)
  256. {
  257. if (notification != dontSendNotification)
  258. {
  259. owner.valueChanged();
  260. if (notification == sendNotificationSync)
  261. handleAsyncUpdate();
  262. else
  263. triggerAsyncUpdate();
  264. }
  265. }
  266. void handleAsyncUpdate() override
  267. {
  268. cancelPendingUpdate();
  269. Component::BailOutChecker checker (&owner);
  270. listeners.callChecked (checker, [&] (Slider::Listener& l) { l.sliderValueChanged (&owner); });
  271. if (checker.shouldBailOut())
  272. return;
  273. if (owner.onValueChange != nullptr)
  274. owner.onValueChange();
  275. if (auto* handler = owner.getAccessibilityHandler())
  276. handler->notifyAccessibilityEvent (AccessibilityEvent::valueChanged);
  277. }
  278. void sendDragStart()
  279. {
  280. owner.startedDragging();
  281. Component::BailOutChecker checker (&owner);
  282. listeners.callChecked (checker, [&] (Slider::Listener& l) { l.sliderDragStarted (&owner); });
  283. if (checker.shouldBailOut())
  284. return;
  285. if (owner.onDragStart != nullptr)
  286. owner.onDragStart();
  287. }
  288. void sendDragEnd()
  289. {
  290. owner.stoppedDragging();
  291. sliderBeingDragged = -1;
  292. Component::BailOutChecker checker (&owner);
  293. listeners.callChecked (checker, [&] (Slider::Listener& l) { l.sliderDragEnded (&owner); });
  294. if (checker.shouldBailOut())
  295. return;
  296. if (owner.onDragEnd != nullptr)
  297. owner.onDragEnd();
  298. }
  299. struct DragInProgress
  300. {
  301. DragInProgress (Pimpl& p) : owner (p) { owner.sendDragStart(); }
  302. ~DragInProgress() { owner.sendDragEnd(); }
  303. Pimpl& owner;
  304. JUCE_DECLARE_NON_COPYABLE (DragInProgress)
  305. };
  306. void incrementOrDecrement (double delta)
  307. {
  308. if (style == IncDecButtons)
  309. {
  310. auto newValue = owner.snapValue (getValue() + delta, notDragging);
  311. if (currentDrag != nullptr)
  312. {
  313. setValue (newValue, sendNotificationSync);
  314. }
  315. else
  316. {
  317. DragInProgress drag (*this);
  318. setValue (newValue, sendNotificationSync);
  319. }
  320. }
  321. }
  322. void valueChanged (Value& value) override
  323. {
  324. if (value.refersToSameSourceAs (currentValue))
  325. {
  326. if (style != TwoValueHorizontal && style != TwoValueVertical)
  327. setValue (currentValue.getValue(), dontSendNotification);
  328. }
  329. else if (value.refersToSameSourceAs (valueMin))
  330. setMinValue (valueMin.getValue(), dontSendNotification, true);
  331. else if (value.refersToSameSourceAs (valueMax))
  332. setMaxValue (valueMax.getValue(), dontSendNotification, true);
  333. }
  334. void textChanged()
  335. {
  336. auto newValue = owner.snapValue (owner.getValueFromText (valueBox->getText()), notDragging);
  337. if (newValue != static_cast<double> (currentValue.getValue()))
  338. {
  339. DragInProgress drag (*this);
  340. setValue (newValue, sendNotificationSync);
  341. }
  342. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  343. }
  344. void updateText()
  345. {
  346. if (valueBox != nullptr)
  347. {
  348. auto newValue = owner.getTextFromValue (currentValue.getValue());
  349. if (newValue != valueBox->getText())
  350. valueBox->setText (newValue, dontSendNotification);
  351. }
  352. }
  353. double constrainedValue (double value) const
  354. {
  355. return normRange.snapToLegalValue (value);
  356. }
  357. float getLinearSliderPos (double value) const
  358. {
  359. double pos;
  360. if (normRange.end <= normRange.start)
  361. pos = 0.5;
  362. else if (value < normRange.start)
  363. pos = 0.0;
  364. else if (value > normRange.end)
  365. pos = 1.0;
  366. else
  367. pos = owner.valueToProportionOfLength (value);
  368. if (isVertical() || style == IncDecButtons)
  369. pos = 1.0 - pos;
  370. jassert (pos >= 0 && pos <= 1.0);
  371. return (float) (sliderRegionStart + pos * sliderRegionSize);
  372. }
  373. void setSliderStyle (SliderStyle newStyle)
  374. {
  375. if (style != newStyle)
  376. {
  377. style = newStyle;
  378. owner.repaint();
  379. owner.lookAndFeelChanged();
  380. owner.invalidateAccessibilityHandler();
  381. }
  382. }
  383. void setVelocityModeParameters (double sensitivity, int threshold,
  384. double offset, bool userCanPressKeyToSwapMode,
  385. ModifierKeys::Flags newModifierToSwapModes)
  386. {
  387. velocityModeSensitivity = sensitivity;
  388. velocityModeOffset = offset;
  389. velocityModeThreshold = threshold;
  390. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  391. modifierToSwapModes = newModifierToSwapModes;
  392. }
  393. void setIncDecButtonsMode (IncDecButtonMode mode)
  394. {
  395. if (incDecButtonMode != mode)
  396. {
  397. incDecButtonMode = mode;
  398. owner.lookAndFeelChanged();
  399. }
  400. }
  401. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  402. bool isReadOnly,
  403. int textEntryBoxWidth,
  404. int textEntryBoxHeight)
  405. {
  406. if (textBoxPos != newPosition
  407. || editableText != (! isReadOnly)
  408. || textBoxWidth != textEntryBoxWidth
  409. || textBoxHeight != textEntryBoxHeight)
  410. {
  411. textBoxPos = newPosition;
  412. editableText = ! isReadOnly;
  413. textBoxWidth = textEntryBoxWidth;
  414. textBoxHeight = textEntryBoxHeight;
  415. owner.repaint();
  416. owner.lookAndFeelChanged();
  417. }
  418. }
  419. void setTextBoxIsEditable (bool shouldBeEditable)
  420. {
  421. editableText = shouldBeEditable;
  422. updateTextBoxEnablement();
  423. }
  424. void showTextBox()
  425. {
  426. jassert (editableText); // this should probably be avoided in read-only sliders.
  427. if (valueBox != nullptr)
  428. valueBox->showEditor();
  429. }
  430. void hideTextBox (bool discardCurrentEditorContents)
  431. {
  432. if (valueBox != nullptr)
  433. {
  434. valueBox->hideEditor (discardCurrentEditorContents);
  435. if (discardCurrentEditorContents)
  436. updateText();
  437. }
  438. }
  439. void setTextValueSuffix (const String& suffix)
  440. {
  441. if (textSuffix != suffix)
  442. {
  443. textSuffix = suffix;
  444. updateText();
  445. }
  446. }
  447. void updateTextBoxEnablement()
  448. {
  449. if (valueBox != nullptr)
  450. {
  451. bool shouldBeEditable = editableText && owner.isEnabled();
  452. if (valueBox->isEditable() != shouldBeEditable) // (to avoid changing the single/double click flags unless we need to)
  453. valueBox->setEditable (shouldBeEditable);
  454. }
  455. }
  456. void lookAndFeelChanged (LookAndFeel& lf)
  457. {
  458. if (textBoxPos != NoTextBox)
  459. {
  460. auto previousTextBoxContent = (valueBox != nullptr ? valueBox->getText()
  461. : owner.getTextFromValue (currentValue.getValue()));
  462. valueBox.reset();
  463. valueBox.reset (lf.createSliderTextBox (owner));
  464. owner.addAndMakeVisible (valueBox.get());
  465. valueBox->setWantsKeyboardFocus (false);
  466. valueBox->setAccessible (false);
  467. valueBox->setText (previousTextBoxContent, dontSendNotification);
  468. valueBox->setTooltip (owner.getTooltip());
  469. updateTextBoxEnablement();
  470. valueBox->onTextChange = [this] { textChanged(); };
  471. if (style == LinearBar || style == LinearBarVertical)
  472. {
  473. valueBox->addMouseListener (&owner, false);
  474. valueBox->setMouseCursor (MouseCursor::ParentCursor);
  475. }
  476. }
  477. else
  478. {
  479. valueBox.reset();
  480. }
  481. if (style == IncDecButtons)
  482. {
  483. incButton.reset (lf.createSliderButton (owner, true));
  484. decButton.reset (lf.createSliderButton (owner, false));
  485. auto tooltip = owner.getTooltip();
  486. auto setupButton = [&] (Button& b, bool isIncrement)
  487. {
  488. owner.addAndMakeVisible (b);
  489. b.onClick = [this, isIncrement] { incrementOrDecrement (isIncrement ? normRange.interval : -normRange.interval); };
  490. if (incDecButtonMode != incDecButtonsNotDraggable)
  491. b.addMouseListener (&owner, false);
  492. else
  493. b.setRepeatSpeed (300, 100, 20);
  494. b.setTooltip (tooltip);
  495. b.setAccessible (false);
  496. };
  497. setupButton (*incButton, true);
  498. setupButton (*decButton, false);
  499. }
  500. else
  501. {
  502. incButton.reset();
  503. decButton.reset();
  504. }
  505. owner.setComponentEffect (lf.getSliderEffect (owner));
  506. owner.resized();
  507. owner.repaint();
  508. }
  509. void showPopupMenu()
  510. {
  511. PopupMenu m;
  512. m.setLookAndFeel (&owner.getLookAndFeel());
  513. m.addItem (1, TRANS ("Velocity-sensitive mode"), true, isVelocityBased);
  514. m.addSeparator();
  515. if (isRotary())
  516. {
  517. PopupMenu rotaryMenu;
  518. rotaryMenu.addItem (2, TRANS ("Use circular dragging"), true, style == Rotary);
  519. rotaryMenu.addItem (3, TRANS ("Use left-right dragging"), true, style == RotaryHorizontalDrag);
  520. rotaryMenu.addItem (4, TRANS ("Use up-down dragging"), true, style == RotaryVerticalDrag);
  521. rotaryMenu.addItem (5, TRANS ("Use left-right/up-down dragging"), true, style == RotaryHorizontalVerticalDrag);
  522. m.addSubMenu (TRANS ("Rotary mode"), rotaryMenu);
  523. }
  524. m.showMenuAsync (PopupMenu::Options(),
  525. ModalCallbackFunction::forComponent (sliderMenuCallback, &owner));
  526. }
  527. static void sliderMenuCallback (int result, Slider* slider)
  528. {
  529. if (slider != nullptr)
  530. {
  531. switch (result)
  532. {
  533. case 1: slider->setVelocityBasedMode (! slider->getVelocityBasedMode()); break;
  534. case 2: slider->setSliderStyle (Rotary); break;
  535. case 3: slider->setSliderStyle (RotaryHorizontalDrag); break;
  536. case 4: slider->setSliderStyle (RotaryVerticalDrag); break;
  537. case 5: slider->setSliderStyle (RotaryHorizontalVerticalDrag); break;
  538. default: break;
  539. }
  540. }
  541. }
  542. int getThumbIndexAt (const MouseEvent& e)
  543. {
  544. if (isTwoValue() || isThreeValue())
  545. {
  546. auto mousePos = isVertical() ? e.position.y : e.position.x;
  547. auto normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  548. auto minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) + (isVertical() ? 0.1f : -0.1f) - mousePos);
  549. auto maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + (isVertical() ? -0.1f : 0.1f) - mousePos);
  550. if (isTwoValue())
  551. return maxPosDistance <= minPosDistance ? 2 : 1;
  552. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  553. return 1;
  554. if (normalPosDistance >= maxPosDistance)
  555. return 2;
  556. }
  557. return 0;
  558. }
  559. //==============================================================================
  560. void handleRotaryDrag (const MouseEvent& e)
  561. {
  562. auto dx = e.position.x - (float) sliderRect.getCentreX();
  563. auto dy = e.position.y - (float) sliderRect.getCentreY();
  564. if (dx * dx + dy * dy > 25.0f)
  565. {
  566. auto angle = std::atan2 ((double) dx, (double) -dy);
  567. while (angle < 0.0)
  568. angle += MathConstants<double>::twoPi;
  569. if (rotaryParams.stopAtEnd && e.mouseWasDraggedSinceMouseDown())
  570. {
  571. if (std::abs (angle - lastAngle) > MathConstants<double>::pi)
  572. {
  573. if (angle >= lastAngle)
  574. angle -= MathConstants<double>::twoPi;
  575. else
  576. angle += MathConstants<double>::twoPi;
  577. }
  578. if (angle >= lastAngle)
  579. angle = jmin (angle, (double) jmax (rotaryParams.startAngleRadians, rotaryParams.endAngleRadians));
  580. else
  581. angle = jmax (angle, (double) jmin (rotaryParams.startAngleRadians, rotaryParams.endAngleRadians));
  582. }
  583. else
  584. {
  585. while (angle < rotaryParams.startAngleRadians)
  586. angle += MathConstants<double>::twoPi;
  587. if (angle > rotaryParams.endAngleRadians)
  588. {
  589. if (smallestAngleBetween (angle, rotaryParams.startAngleRadians)
  590. <= smallestAngleBetween (angle, rotaryParams.endAngleRadians))
  591. angle = rotaryParams.startAngleRadians;
  592. else
  593. angle = rotaryParams.endAngleRadians;
  594. }
  595. }
  596. auto proportion = (angle - rotaryParams.startAngleRadians) / (rotaryParams.endAngleRadians - rotaryParams.startAngleRadians);
  597. valueWhenLastDragged = owner.proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  598. lastAngle = angle;
  599. }
  600. }
  601. void handleAbsoluteDrag (const MouseEvent& e)
  602. {
  603. auto mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.position.x : e.position.y;
  604. double newPos = 0;
  605. if (style == RotaryHorizontalDrag
  606. || style == RotaryVerticalDrag
  607. || style == IncDecButtons
  608. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar || style == LinearBarVertical)
  609. && ! snapsToMousePos))
  610. {
  611. auto mouseDiff = (style == RotaryHorizontalDrag
  612. || style == LinearHorizontal
  613. || style == LinearBar
  614. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  615. ? e.position.x - mouseDragStartPos.x
  616. : mouseDragStartPos.y - e.position.y;
  617. newPos = owner.valueToProportionOfLength (valueOnMouseDown)
  618. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  619. if (style == IncDecButtons)
  620. {
  621. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  622. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  623. }
  624. }
  625. else if (style == RotaryHorizontalVerticalDrag)
  626. {
  627. auto mouseDiff = (e.position.x - mouseDragStartPos.x)
  628. + (mouseDragStartPos.y - e.position.y);
  629. newPos = owner.valueToProportionOfLength (valueOnMouseDown)
  630. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  631. }
  632. else
  633. {
  634. newPos = (mousePos - (float) sliderRegionStart) / (double) sliderRegionSize;
  635. if (isVertical())
  636. newPos = 1.0 - newPos;
  637. }
  638. newPos = (isRotary() && ! rotaryParams.stopAtEnd) ? newPos - std::floor (newPos)
  639. : jlimit (0.0, 1.0, newPos);
  640. valueWhenLastDragged = owner.proportionOfLengthToValue (newPos);
  641. }
  642. void handleVelocityDrag (const MouseEvent& e)
  643. {
  644. bool hasHorizontalStyle =
  645. (isHorizontal() || style == RotaryHorizontalDrag
  646. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()));
  647. auto mouseDiff = style == RotaryHorizontalVerticalDrag
  648. ? (e.position.x - mousePosWhenLastDragged.x) + (mousePosWhenLastDragged.y - e.position.y)
  649. : (hasHorizontalStyle ? e.position.x - mousePosWhenLastDragged.x
  650. : e.position.y - mousePosWhenLastDragged.y);
  651. auto maxSpeed = jmax (200.0, (double) sliderRegionSize);
  652. auto speed = jlimit (0.0, maxSpeed, (double) std::abs (mouseDiff));
  653. if (speed != 0.0)
  654. {
  655. speed = 0.2 * velocityModeSensitivity
  656. * (1.0 + std::sin (MathConstants<double>::pi * (1.5 + jmin (0.5, velocityModeOffset
  657. + jmax (0.0, (double) (speed - velocityModeThreshold))
  658. / maxSpeed))));
  659. if (mouseDiff < 0)
  660. speed = -speed;
  661. if (isVertical() || style == RotaryVerticalDrag
  662. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  663. speed = -speed;
  664. auto newPos = owner.valueToProportionOfLength (valueWhenLastDragged) + speed;
  665. newPos = (isRotary() && ! rotaryParams.stopAtEnd) ? newPos - std::floor (newPos)
  666. : jlimit (0.0, 1.0, newPos);
  667. valueWhenLastDragged = owner.proportionOfLengthToValue (newPos);
  668. e.source.enableUnboundedMouseMovement (true, false);
  669. }
  670. }
  671. void mouseDown (const MouseEvent& e)
  672. {
  673. incDecDragged = false;
  674. useDragEvents = false;
  675. mouseDragStartPos = mousePosWhenLastDragged = e.position;
  676. currentDrag.reset();
  677. popupDisplay.reset();
  678. if (owner.isEnabled())
  679. {
  680. if (e.mods.isPopupMenu() && menuEnabled)
  681. {
  682. showPopupMenu();
  683. }
  684. else if (canDoubleClickToValue()
  685. && (singleClickModifiers != ModifierKeys() && e.mods.withoutMouseButtons() == singleClickModifiers))
  686. {
  687. mouseDoubleClick();
  688. }
  689. else if (normRange.end > normRange.start)
  690. {
  691. useDragEvents = true;
  692. if (valueBox != nullptr)
  693. valueBox->hideEditor (true);
  694. sliderBeingDragged = getThumbIndexAt (e);
  695. minMaxDiff = static_cast<double> (valueMax.getValue()) - static_cast<double> (valueMin.getValue());
  696. if (! isTwoValue())
  697. lastAngle = rotaryParams.startAngleRadians
  698. + (rotaryParams.endAngleRadians - rotaryParams.startAngleRadians)
  699. * owner.valueToProportionOfLength (currentValue.getValue());
  700. valueWhenLastDragged = (sliderBeingDragged == 2 ? valueMax
  701. : (sliderBeingDragged == 1 ? valueMin
  702. : currentValue)).getValue();
  703. valueOnMouseDown = valueWhenLastDragged;
  704. if (showPopupOnDrag || showPopupOnHover)
  705. {
  706. showPopupDisplay();
  707. if (popupDisplay != nullptr)
  708. popupDisplay->stopTimer();
  709. }
  710. currentDrag.reset (new DragInProgress (*this));
  711. mouseDrag (e);
  712. }
  713. }
  714. }
  715. void mouseDrag (const MouseEvent& e)
  716. {
  717. if (useDragEvents && normRange.end > normRange.start
  718. && ! ((style == LinearBar || style == LinearBarVertical)
  719. && e.mouseWasClicked() && valueBox != nullptr && valueBox->isEditable()))
  720. {
  721. DragMode dragMode = notDragging;
  722. if (style == Rotary)
  723. {
  724. handleRotaryDrag (e);
  725. }
  726. else
  727. {
  728. if (style == IncDecButtons && ! incDecDragged)
  729. {
  730. if (e.getDistanceFromDragStart() < 10 || ! e.mouseWasDraggedSinceMouseDown())
  731. return;
  732. incDecDragged = true;
  733. mouseDragStartPos = e.position;
  734. }
  735. if (isAbsoluteDragMode (e.mods) || (normRange.end - normRange.start) / sliderRegionSize < normRange.interval)
  736. {
  737. dragMode = absoluteDrag;
  738. handleAbsoluteDrag (e);
  739. }
  740. else
  741. {
  742. dragMode = velocityDrag;
  743. handleVelocityDrag (e);
  744. }
  745. }
  746. valueWhenLastDragged = jlimit (normRange.start, normRange.end, valueWhenLastDragged);
  747. if (sliderBeingDragged == 0)
  748. {
  749. setValue (owner.snapValue (valueWhenLastDragged, dragMode),
  750. sendChangeOnlyOnRelease ? dontSendNotification : sendNotificationSync);
  751. }
  752. else if (sliderBeingDragged == 1)
  753. {
  754. setMinValue (owner.snapValue (valueWhenLastDragged, dragMode),
  755. sendChangeOnlyOnRelease ? dontSendNotification : sendNotificationAsync, true);
  756. if (e.mods.isShiftDown())
  757. setMaxValue (getMinValue() + minMaxDiff, dontSendNotification, true);
  758. else
  759. minMaxDiff = static_cast<double> (valueMax.getValue()) - static_cast<double> (valueMin.getValue());
  760. }
  761. else if (sliderBeingDragged == 2)
  762. {
  763. setMaxValue (owner.snapValue (valueWhenLastDragged, dragMode),
  764. sendChangeOnlyOnRelease ? dontSendNotification : sendNotificationAsync, true);
  765. if (e.mods.isShiftDown())
  766. setMinValue (getMaxValue() - minMaxDiff, dontSendNotification, true);
  767. else
  768. minMaxDiff = static_cast<double> (valueMax.getValue()) - static_cast<double> (valueMin.getValue());
  769. }
  770. mousePosWhenLastDragged = e.position;
  771. }
  772. }
  773. void mouseUp()
  774. {
  775. if (owner.isEnabled()
  776. && useDragEvents
  777. && (normRange.end > normRange.start)
  778. && (style != IncDecButtons || incDecDragged))
  779. {
  780. restoreMouseIfHidden();
  781. if (sendChangeOnlyOnRelease && valueOnMouseDown != static_cast<double> (currentValue.getValue()))
  782. triggerChangeMessage (sendNotificationAsync);
  783. currentDrag.reset();
  784. popupDisplay.reset();
  785. if (style == IncDecButtons)
  786. {
  787. incButton->setState (Button::buttonNormal);
  788. decButton->setState (Button::buttonNormal);
  789. }
  790. }
  791. else if (popupDisplay != nullptr)
  792. {
  793. popupDisplay->startTimer (200);
  794. }
  795. currentDrag.reset();
  796. }
  797. void mouseMove()
  798. {
  799. // this is a workaround for a bug where the popup display being dismissed triggers
  800. // a mouse move causing it to never be hidden
  801. auto shouldShowPopup = showPopupOnHover
  802. && (Time::getMillisecondCounterHiRes() - lastPopupDismissal) > 250;
  803. if (shouldShowPopup
  804. && ! isTwoValue()
  805. && ! isThreeValue())
  806. {
  807. if (owner.isMouseOver (true))
  808. {
  809. if (popupDisplay == nullptr)
  810. showPopupDisplay();
  811. if (popupDisplay != nullptr && popupHoverTimeout != -1)
  812. popupDisplay->startTimer (popupHoverTimeout);
  813. }
  814. }
  815. }
  816. void mouseExit()
  817. {
  818. popupDisplay.reset();
  819. }
  820. void showPopupDisplay()
  821. {
  822. if (style == IncDecButtons)
  823. return;
  824. if (popupDisplay == nullptr)
  825. {
  826. popupDisplay.reset (new PopupDisplayComponent (owner, parentForPopupDisplay == nullptr));
  827. if (parentForPopupDisplay != nullptr)
  828. parentForPopupDisplay->addChildComponent (popupDisplay.get());
  829. else
  830. popupDisplay->addToDesktop (ComponentPeer::windowIsTemporary
  831. | ComponentPeer::windowIgnoresKeyPresses
  832. | ComponentPeer::windowIgnoresMouseClicks);
  833. if (style == SliderStyle::TwoValueHorizontal
  834. || style == SliderStyle::TwoValueVertical)
  835. {
  836. updatePopupDisplay (sliderBeingDragged == 2 ? getMaxValue()
  837. : getMinValue());
  838. }
  839. else
  840. {
  841. updatePopupDisplay (getValue());
  842. }
  843. popupDisplay->setVisible (true);
  844. }
  845. }
  846. void updatePopupDisplay (double valueToShow)
  847. {
  848. if (popupDisplay != nullptr)
  849. popupDisplay->updatePosition (owner.getTextFromValue (valueToShow));
  850. }
  851. bool canDoubleClickToValue() const
  852. {
  853. return doubleClickToValue
  854. && style != IncDecButtons
  855. && normRange.start <= doubleClickReturnValue
  856. && normRange.end >= doubleClickReturnValue;
  857. }
  858. void mouseDoubleClick()
  859. {
  860. if (canDoubleClickToValue())
  861. {
  862. DragInProgress drag (*this);
  863. setValue (doubleClickReturnValue, sendNotificationSync);
  864. }
  865. }
  866. double getMouseWheelDelta (double value, double wheelAmount)
  867. {
  868. if (style == IncDecButtons)
  869. return normRange.interval * wheelAmount;
  870. auto proportionDelta = wheelAmount * 0.15;
  871. auto currentPos = owner.valueToProportionOfLength (value);
  872. auto newPos = currentPos + proportionDelta;
  873. newPos = (isRotary() && ! rotaryParams.stopAtEnd) ? newPos - std::floor (newPos)
  874. : jlimit (0.0, 1.0, newPos);
  875. return owner.proportionOfLengthToValue (newPos) - value;
  876. }
  877. bool mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  878. {
  879. if (scrollWheelEnabled
  880. && style != TwoValueHorizontal
  881. && style != TwoValueVertical)
  882. {
  883. // sometimes duplicate wheel events seem to be sent, so since we're going to
  884. // bump the value by a minimum of the interval, avoid doing this twice..
  885. if (e.eventTime != lastMouseWheelTime)
  886. {
  887. lastMouseWheelTime = e.eventTime;
  888. if (normRange.end > normRange.start && ! e.mods.isAnyMouseButtonDown())
  889. {
  890. if (valueBox != nullptr)
  891. valueBox->hideEditor (false);
  892. auto value = static_cast<double> (currentValue.getValue());
  893. auto delta = getMouseWheelDelta (value, (std::abs (wheel.deltaX) > std::abs (wheel.deltaY)
  894. ? -wheel.deltaX : wheel.deltaY)
  895. * (wheel.isReversed ? -1.0f : 1.0f));
  896. if (delta != 0.0)
  897. {
  898. auto newValue = value + jmax (normRange.interval, std::abs (delta)) * (delta < 0 ? -1.0 : 1.0);
  899. DragInProgress drag (*this);
  900. setValue (owner.snapValue (newValue, notDragging), sendNotificationSync);
  901. }
  902. }
  903. }
  904. return true;
  905. }
  906. return false;
  907. }
  908. void modifierKeysChanged (const ModifierKeys& modifiers)
  909. {
  910. if (style != IncDecButtons && style != Rotary && isAbsoluteDragMode (modifiers))
  911. restoreMouseIfHidden();
  912. }
  913. bool isAbsoluteDragMode (ModifierKeys mods) const
  914. {
  915. return isVelocityBased == (userKeyOverridesVelocity && mods.testFlags (modifierToSwapModes));
  916. }
  917. void restoreMouseIfHidden()
  918. {
  919. for (auto& ms : Desktop::getInstance().getMouseSources())
  920. {
  921. if (ms.isUnboundedMouseMovementEnabled())
  922. {
  923. ms.enableUnboundedMouseMovement (false);
  924. auto pos = sliderBeingDragged == 2 ? getMaxValue()
  925. : (sliderBeingDragged == 1 ? getMinValue()
  926. : static_cast<double> (currentValue.getValue()));
  927. Point<float> mousePos;
  928. if (isRotary())
  929. {
  930. mousePos = ms.getLastMouseDownPosition();
  931. auto delta = (float) (pixelsForFullDragExtent * (owner.valueToProportionOfLength (valueOnMouseDown)
  932. - owner.valueToProportionOfLength (pos)));
  933. if (style == RotaryHorizontalDrag) mousePos += Point<float> (-delta, 0.0f);
  934. else if (style == RotaryVerticalDrag) mousePos += Point<float> (0.0f, delta);
  935. else mousePos += Point<float> (delta / -2.0f, delta / 2.0f);
  936. mousePos = owner.getScreenBounds().reduced (4).toFloat().getConstrainedPoint (mousePos);
  937. mouseDragStartPos = mousePosWhenLastDragged = owner.getLocalPoint (nullptr, mousePos);
  938. valueOnMouseDown = valueWhenLastDragged;
  939. }
  940. else
  941. {
  942. auto pixelPos = (float) getLinearSliderPos (pos);
  943. mousePos = owner.localPointToGlobal (Point<float> (isHorizontal() ? pixelPos : ((float) owner.getWidth() / 2.0f),
  944. isVertical() ? pixelPos : ((float) owner.getHeight() / 2.0f)));
  945. }
  946. const_cast <MouseInputSource&> (ms).setScreenPosition (mousePos);
  947. }
  948. }
  949. }
  950. //==============================================================================
  951. void paint (Graphics& g, LookAndFeel& lf)
  952. {
  953. if (style != IncDecButtons)
  954. {
  955. if (isRotary())
  956. {
  957. auto sliderPos = (float) owner.valueToProportionOfLength (lastCurrentValue);
  958. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  959. lf.drawRotarySlider (g,
  960. sliderRect.getX(), sliderRect.getY(),
  961. sliderRect.getWidth(), sliderRect.getHeight(),
  962. sliderPos, rotaryParams.startAngleRadians,
  963. rotaryParams.endAngleRadians, owner);
  964. }
  965. else
  966. {
  967. lf.drawLinearSlider (g,
  968. sliderRect.getX(), sliderRect.getY(),
  969. sliderRect.getWidth(), sliderRect.getHeight(),
  970. getLinearSliderPos (lastCurrentValue),
  971. getLinearSliderPos (lastValueMin),
  972. getLinearSliderPos (lastValueMax),
  973. style, owner);
  974. }
  975. if ((style == LinearBar || style == LinearBarVertical) && valueBox == nullptr)
  976. {
  977. g.setColour (owner.findColour (Slider::textBoxOutlineColourId));
  978. g.drawRect (0, 0, owner.getWidth(), owner.getHeight(), 1);
  979. }
  980. }
  981. }
  982. //==============================================================================
  983. void resized (LookAndFeel& lf)
  984. {
  985. auto layout = lf.getSliderLayout (owner);
  986. sliderRect = layout.sliderBounds;
  987. if (valueBox != nullptr)
  988. valueBox->setBounds (layout.textBoxBounds);
  989. if (isHorizontal())
  990. {
  991. sliderRegionStart = layout.sliderBounds.getX();
  992. sliderRegionSize = layout.sliderBounds.getWidth();
  993. }
  994. else if (isVertical())
  995. {
  996. sliderRegionStart = layout.sliderBounds.getY();
  997. sliderRegionSize = layout.sliderBounds.getHeight();
  998. }
  999. else if (style == IncDecButtons)
  1000. {
  1001. resizeIncDecButtons();
  1002. }
  1003. }
  1004. //==============================================================================
  1005. void resizeIncDecButtons()
  1006. {
  1007. auto buttonRect = sliderRect;
  1008. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  1009. buttonRect.expand (-2, 0);
  1010. else
  1011. buttonRect.expand (0, -2);
  1012. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  1013. if (incDecButtonsSideBySide)
  1014. {
  1015. decButton->setBounds (buttonRect.removeFromLeft (buttonRect.getWidth() / 2));
  1016. decButton->setConnectedEdges (Button::ConnectedOnRight);
  1017. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  1018. }
  1019. else
  1020. {
  1021. decButton->setBounds (buttonRect.removeFromBottom (buttonRect.getHeight() / 2));
  1022. decButton->setConnectedEdges (Button::ConnectedOnTop);
  1023. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  1024. }
  1025. incButton->setBounds (buttonRect);
  1026. }
  1027. //==============================================================================
  1028. Slider& owner;
  1029. SliderStyle style;
  1030. ListenerList<Slider::Listener> listeners;
  1031. Value currentValue, valueMin, valueMax;
  1032. double lastCurrentValue = 0, lastValueMin = 0, lastValueMax = 0;
  1033. NormalisableRange<double> normRange { 0.0, 10.0 };
  1034. double doubleClickReturnValue = 0;
  1035. double valueWhenLastDragged = 0, valueOnMouseDown = 0, lastAngle = 0;
  1036. double velocityModeSensitivity = 1.0, velocityModeOffset = 0, minMaxDiff = 0;
  1037. int velocityModeThreshold = 1;
  1038. RotaryParameters rotaryParams;
  1039. Point<float> mouseDragStartPos, mousePosWhenLastDragged;
  1040. int sliderRegionStart = 0, sliderRegionSize = 1;
  1041. int sliderBeingDragged = -1;
  1042. int pixelsForFullDragExtent = 250;
  1043. Time lastMouseWheelTime;
  1044. Rectangle<int> sliderRect;
  1045. std::unique_ptr<DragInProgress> currentDrag;
  1046. TextEntryBoxPosition textBoxPos;
  1047. String textSuffix;
  1048. int numDecimalPlaces = 7;
  1049. int textBoxWidth = 80, textBoxHeight = 20;
  1050. IncDecButtonMode incDecButtonMode = incDecButtonsNotDraggable;
  1051. ModifierKeys::Flags modifierToSwapModes = ModifierKeys::ctrlAltCommandModifiers;
  1052. bool editableText = true;
  1053. bool doubleClickToValue = false;
  1054. bool isVelocityBased = false;
  1055. bool userKeyOverridesVelocity = true;
  1056. bool incDecButtonsSideBySide = false;
  1057. bool sendChangeOnlyOnRelease = false;
  1058. bool showPopupOnDrag = false;
  1059. bool showPopupOnHover = false;
  1060. bool menuEnabled = false;
  1061. bool useDragEvents = false;
  1062. bool incDecDragged = false;
  1063. bool scrollWheelEnabled = true;
  1064. bool snapsToMousePos = true;
  1065. int popupHoverTimeout = 2000;
  1066. double lastPopupDismissal = 0.0;
  1067. ModifierKeys singleClickModifiers;
  1068. std::unique_ptr<Label> valueBox;
  1069. std::unique_ptr<Button> incButton, decButton;
  1070. //==============================================================================
  1071. struct PopupDisplayComponent : public BubbleComponent,
  1072. public Timer
  1073. {
  1074. PopupDisplayComponent (Slider& s, bool isOnDesktop)
  1075. : owner (s),
  1076. font (s.getLookAndFeel().getSliderPopupFont (s))
  1077. {
  1078. if (isOnDesktop)
  1079. setTransform (AffineTransform::scale (Component::getApproximateScaleFactorForComponent (&s)));
  1080. setAlwaysOnTop (true);
  1081. setAllowedPlacement (owner.getLookAndFeel().getSliderPopupPlacement (s));
  1082. setLookAndFeel (&s.getLookAndFeel());
  1083. }
  1084. ~PopupDisplayComponent() override
  1085. {
  1086. if (owner.pimpl != nullptr)
  1087. owner.pimpl->lastPopupDismissal = Time::getMillisecondCounterHiRes();
  1088. }
  1089. void paintContent (Graphics& g, int w, int h) override
  1090. {
  1091. g.setFont (font);
  1092. g.setColour (owner.findColour (TooltipWindow::textColourId, true));
  1093. g.drawFittedText (text, Rectangle<int> (w, h), Justification::centred, 1);
  1094. }
  1095. void getContentSize (int& w, int& h) override
  1096. {
  1097. w = font.getStringWidth (text) + 18;
  1098. h = (int) (font.getHeight() * 1.6f);
  1099. }
  1100. void updatePosition (const String& newText)
  1101. {
  1102. text = newText;
  1103. BubbleComponent::setPosition (&owner);
  1104. repaint();
  1105. }
  1106. void timerCallback() override
  1107. {
  1108. stopTimer();
  1109. owner.pimpl->popupDisplay.reset();
  1110. }
  1111. private:
  1112. //==============================================================================
  1113. Slider& owner;
  1114. Font font;
  1115. String text;
  1116. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PopupDisplayComponent)
  1117. };
  1118. std::unique_ptr<PopupDisplayComponent> popupDisplay;
  1119. Component* parentForPopupDisplay = nullptr;
  1120. //==============================================================================
  1121. static double smallestAngleBetween (double a1, double a2) noexcept
  1122. {
  1123. return jmin (std::abs (a1 - a2),
  1124. std::abs (a1 + MathConstants<double>::twoPi - a2),
  1125. std::abs (a2 + MathConstants<double>::twoPi - a1));
  1126. }
  1127. };
  1128. //==============================================================================
  1129. Slider::Slider()
  1130. {
  1131. init (LinearHorizontal, TextBoxLeft);
  1132. }
  1133. Slider::Slider (const String& name) : Component (name)
  1134. {
  1135. init (LinearHorizontal, TextBoxLeft);
  1136. }
  1137. Slider::Slider (SliderStyle style, TextEntryBoxPosition textBoxPos)
  1138. {
  1139. init (style, textBoxPos);
  1140. }
  1141. void Slider::init (SliderStyle style, TextEntryBoxPosition textBoxPos)
  1142. {
  1143. setWantsKeyboardFocus (false);
  1144. setRepaintsOnMouseActivity (true);
  1145. pimpl.reset (new Pimpl (*this, style, textBoxPos));
  1146. Slider::lookAndFeelChanged();
  1147. updateText();
  1148. pimpl->registerListeners();
  1149. }
  1150. Slider::~Slider() {}
  1151. //==============================================================================
  1152. void Slider::addListener (Listener* l) { pimpl->listeners.add (l); }
  1153. void Slider::removeListener (Listener* l) { pimpl->listeners.remove (l); }
  1154. //==============================================================================
  1155. Slider::SliderStyle Slider::getSliderStyle() const noexcept { return pimpl->style; }
  1156. void Slider::setSliderStyle (SliderStyle newStyle) { pimpl->setSliderStyle (newStyle); }
  1157. void Slider::setRotaryParameters (RotaryParameters p) noexcept
  1158. {
  1159. // make sure the values are sensible..
  1160. jassert (p.startAngleRadians >= 0 && p.endAngleRadians >= 0);
  1161. jassert (p.startAngleRadians < MathConstants<float>::pi * 4.0f
  1162. && p.endAngleRadians < MathConstants<float>::pi * 4.0f);
  1163. pimpl->rotaryParams = p;
  1164. }
  1165. void Slider::setRotaryParameters (float startAngleRadians, float endAngleRadians, bool stopAtEnd) noexcept
  1166. {
  1167. setRotaryParameters ({ startAngleRadians, endAngleRadians, stopAtEnd });
  1168. }
  1169. Slider::RotaryParameters Slider::getRotaryParameters() const noexcept
  1170. {
  1171. return pimpl->rotaryParams;
  1172. }
  1173. void Slider::setVelocityBasedMode (bool vb) { pimpl->isVelocityBased = vb; }
  1174. bool Slider::getVelocityBasedMode() const noexcept { return pimpl->isVelocityBased; }
  1175. bool Slider::getVelocityModeIsSwappable() const noexcept { return pimpl->userKeyOverridesVelocity; }
  1176. int Slider::getVelocityThreshold() const noexcept { return pimpl->velocityModeThreshold; }
  1177. double Slider::getVelocitySensitivity() const noexcept { return pimpl->velocityModeSensitivity; }
  1178. double Slider::getVelocityOffset() const noexcept { return pimpl->velocityModeOffset; }
  1179. void Slider::setVelocityModeParameters (double sensitivity, int threshold,
  1180. double offset, bool userCanPressKeyToSwapMode,
  1181. ModifierKeys::Flags modifierToSwapModes)
  1182. {
  1183. jassert (threshold >= 0);
  1184. jassert (sensitivity > 0);
  1185. jassert (offset >= 0);
  1186. pimpl->setVelocityModeParameters (sensitivity, threshold, offset,
  1187. userCanPressKeyToSwapMode, modifierToSwapModes);
  1188. }
  1189. double Slider::getSkewFactor() const noexcept { return pimpl->normRange.skew; }
  1190. bool Slider::isSymmetricSkew() const noexcept { return pimpl->normRange.symmetricSkew; }
  1191. void Slider::setSkewFactor (double factor, bool symmetricSkew)
  1192. {
  1193. pimpl->normRange.skew = factor;
  1194. pimpl->normRange.symmetricSkew = symmetricSkew;
  1195. }
  1196. void Slider::setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint)
  1197. {
  1198. pimpl->normRange.setSkewForCentre (sliderValueToShowAtMidPoint);
  1199. }
  1200. int Slider::getMouseDragSensitivity() const noexcept { return pimpl->pixelsForFullDragExtent; }
  1201. void Slider::setMouseDragSensitivity (int distanceForFullScaleDrag)
  1202. {
  1203. jassert (distanceForFullScaleDrag > 0);
  1204. pimpl->pixelsForFullDragExtent = distanceForFullScaleDrag;
  1205. }
  1206. void Slider::setIncDecButtonsMode (IncDecButtonMode mode) { pimpl->setIncDecButtonsMode (mode); }
  1207. Slider::TextEntryBoxPosition Slider::getTextBoxPosition() const noexcept { return pimpl->textBoxPos; }
  1208. int Slider::getTextBoxWidth() const noexcept { return pimpl->textBoxWidth; }
  1209. int Slider::getTextBoxHeight() const noexcept { return pimpl->textBoxHeight; }
  1210. void Slider::setTextBoxStyle (TextEntryBoxPosition newPosition, bool isReadOnly, int textEntryBoxWidth, int textEntryBoxHeight)
  1211. {
  1212. pimpl->setTextBoxStyle (newPosition, isReadOnly, textEntryBoxWidth, textEntryBoxHeight);
  1213. }
  1214. bool Slider::isTextBoxEditable() const noexcept { return pimpl->editableText; }
  1215. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) { pimpl->setTextBoxIsEditable (shouldBeEditable); }
  1216. void Slider::showTextBox() { pimpl->showTextBox(); }
  1217. void Slider::hideTextBox (bool discardCurrentEditorContents) { pimpl->hideTextBox (discardCurrentEditorContents); }
  1218. void Slider::setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease)
  1219. {
  1220. pimpl->sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  1221. }
  1222. bool Slider::getSliderSnapsToMousePosition() const noexcept { return pimpl->snapsToMousePos; }
  1223. void Slider::setSliderSnapsToMousePosition (bool shouldSnapToMouse) { pimpl->snapsToMousePos = shouldSnapToMouse; }
  1224. void Slider::setPopupDisplayEnabled (bool showOnDrag, bool showOnHover, Component* parent, int hoverTimeout)
  1225. {
  1226. pimpl->showPopupOnDrag = showOnDrag;
  1227. pimpl->showPopupOnHover = showOnHover;
  1228. pimpl->parentForPopupDisplay = parent;
  1229. pimpl->popupHoverTimeout = hoverTimeout;
  1230. }
  1231. Component* Slider::getCurrentPopupDisplay() const noexcept { return pimpl->popupDisplay.get(); }
  1232. //==============================================================================
  1233. void Slider::colourChanged() { lookAndFeelChanged(); }
  1234. void Slider::lookAndFeelChanged() { pimpl->lookAndFeelChanged (getLookAndFeel()); }
  1235. void Slider::enablementChanged() { repaint(); pimpl->updateTextBoxEnablement(); }
  1236. //==============================================================================
  1237. Range<double> Slider::getRange() const noexcept { return { pimpl->normRange.start, pimpl->normRange.end }; }
  1238. double Slider::getMaximum() const noexcept { return pimpl->normRange.end; }
  1239. double Slider::getMinimum() const noexcept { return pimpl->normRange.start; }
  1240. double Slider::getInterval() const noexcept { return pimpl->normRange.interval; }
  1241. void Slider::setRange (double newMin, double newMax, double newInt) { pimpl->setRange (newMin, newMax, newInt); }
  1242. void Slider::setRange (Range<double> newRange, double newInt) { pimpl->setRange (newRange.getStart(), newRange.getEnd(), newInt); }
  1243. void Slider::setNormalisableRange (NormalisableRange<double> newRange) { pimpl->setNormalisableRange (newRange); }
  1244. double Slider::getValue() const { return pimpl->getValue(); }
  1245. Value& Slider::getValueObject() noexcept { return pimpl->currentValue; }
  1246. Value& Slider::getMinValueObject() noexcept { return pimpl->valueMin; }
  1247. Value& Slider::getMaxValueObject() noexcept { return pimpl->valueMax; }
  1248. void Slider::setValue (double newValue, NotificationType notification)
  1249. {
  1250. pimpl->setValue (newValue, notification);
  1251. }
  1252. double Slider::getMinValue() const { return pimpl->getMinValue(); }
  1253. double Slider::getMaxValue() const { return pimpl->getMaxValue(); }
  1254. void Slider::setMinValue (double newValue, NotificationType notification, bool allowNudgingOfOtherValues)
  1255. {
  1256. pimpl->setMinValue (newValue, notification, allowNudgingOfOtherValues);
  1257. }
  1258. void Slider::setMaxValue (double newValue, NotificationType notification, bool allowNudgingOfOtherValues)
  1259. {
  1260. pimpl->setMaxValue (newValue, notification, allowNudgingOfOtherValues);
  1261. }
  1262. void Slider::setMinAndMaxValues (double newMinValue, double newMaxValue, NotificationType notification)
  1263. {
  1264. pimpl->setMinAndMaxValues (newMinValue, newMaxValue, notification);
  1265. }
  1266. void Slider::setDoubleClickReturnValue (bool isDoubleClickEnabled, double valueToSetOnDoubleClick, ModifierKeys mods)
  1267. {
  1268. pimpl->doubleClickToValue = isDoubleClickEnabled;
  1269. pimpl->doubleClickReturnValue = valueToSetOnDoubleClick;
  1270. pimpl->singleClickModifiers = mods;
  1271. }
  1272. double Slider::getDoubleClickReturnValue() const noexcept { return pimpl->doubleClickReturnValue; }
  1273. bool Slider::isDoubleClickReturnEnabled() const noexcept { return pimpl->doubleClickToValue; }
  1274. void Slider::updateText()
  1275. {
  1276. pimpl->updateText();
  1277. }
  1278. void Slider::setTextValueSuffix (const String& suffix)
  1279. {
  1280. pimpl->setTextValueSuffix (suffix);
  1281. }
  1282. String Slider::getTextValueSuffix() const
  1283. {
  1284. return pimpl->textSuffix;
  1285. }
  1286. String Slider::getTextFromValue (double v)
  1287. {
  1288. auto getText = [this] (double val)
  1289. {
  1290. if (textFromValueFunction != nullptr)
  1291. return textFromValueFunction (val);
  1292. if (getNumDecimalPlacesToDisplay() > 0)
  1293. return String (val, getNumDecimalPlacesToDisplay());
  1294. return String (roundToInt (val));
  1295. };
  1296. return getText (v) + getTextValueSuffix();
  1297. }
  1298. double Slider::getValueFromText (const String& text)
  1299. {
  1300. auto t = text.trimStart();
  1301. if (t.endsWith (getTextValueSuffix()))
  1302. t = t.substring (0, t.length() - getTextValueSuffix().length());
  1303. if (valueFromTextFunction != nullptr)
  1304. return valueFromTextFunction (t);
  1305. while (t.startsWithChar ('+'))
  1306. t = t.substring (1).trimStart();
  1307. return t.initialSectionContainingOnly ("0123456789.,-")
  1308. .getDoubleValue();
  1309. }
  1310. double Slider::proportionOfLengthToValue (double proportion)
  1311. {
  1312. return pimpl->normRange.convertFrom0to1 (proportion);
  1313. }
  1314. double Slider::valueToProportionOfLength (double value)
  1315. {
  1316. return pimpl->normRange.convertTo0to1 (value);
  1317. }
  1318. double Slider::snapValue (double attemptedValue, DragMode)
  1319. {
  1320. return attemptedValue;
  1321. }
  1322. int Slider::getNumDecimalPlacesToDisplay() const noexcept { return pimpl->numDecimalPlaces; }
  1323. void Slider::setNumDecimalPlacesToDisplay (int decimalPlacesToDisplay)
  1324. {
  1325. pimpl->numDecimalPlaces = decimalPlacesToDisplay;
  1326. updateText();
  1327. }
  1328. //==============================================================================
  1329. int Slider::getThumbBeingDragged() const noexcept { return pimpl->sliderBeingDragged; }
  1330. void Slider::startedDragging() {}
  1331. void Slider::stoppedDragging() {}
  1332. void Slider::valueChanged() {}
  1333. //==============================================================================
  1334. void Slider::setPopupMenuEnabled (bool menuEnabled) { pimpl->menuEnabled = menuEnabled; }
  1335. void Slider::setScrollWheelEnabled (bool enabled) { pimpl->scrollWheelEnabled = enabled; }
  1336. bool Slider::isHorizontal() const noexcept { return pimpl->isHorizontal(); }
  1337. bool Slider::isVertical() const noexcept { return pimpl->isVertical(); }
  1338. bool Slider::isRotary() const noexcept { return pimpl->isRotary(); }
  1339. bool Slider::isBar() const noexcept { return pimpl->isBar(); }
  1340. bool Slider::isTwoValue() const noexcept { return pimpl->isTwoValue(); }
  1341. bool Slider::isThreeValue() const noexcept { return pimpl->isThreeValue(); }
  1342. float Slider::getPositionOfValue (double value) const { return pimpl->getPositionOfValue (value); }
  1343. //==============================================================================
  1344. void Slider::paint (Graphics& g) { pimpl->paint (g, getLookAndFeel()); }
  1345. void Slider::resized() { pimpl->resized (getLookAndFeel()); }
  1346. void Slider::focusOfChildComponentChanged (FocusChangeType) { repaint(); }
  1347. void Slider::mouseDown (const MouseEvent& e) { pimpl->mouseDown (e); }
  1348. void Slider::mouseUp (const MouseEvent&) { pimpl->mouseUp(); }
  1349. void Slider::mouseMove (const MouseEvent&) { pimpl->mouseMove(); }
  1350. void Slider::mouseExit (const MouseEvent&) { pimpl->mouseExit(); }
  1351. // If popup display is enabled and set to show on mouse hover, this makes sure
  1352. // it is shown when dragging the mouse over a slider and releasing
  1353. void Slider::mouseEnter (const MouseEvent&) { pimpl->mouseMove(); }
  1354. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  1355. {
  1356. if (isEnabled())
  1357. pimpl->modifierKeysChanged (modifiers);
  1358. }
  1359. void Slider::mouseDrag (const MouseEvent& e)
  1360. {
  1361. if (isEnabled())
  1362. pimpl->mouseDrag (e);
  1363. }
  1364. void Slider::mouseDoubleClick (const MouseEvent&)
  1365. {
  1366. if (isEnabled())
  1367. pimpl->mouseDoubleClick();
  1368. }
  1369. void Slider::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  1370. {
  1371. if (! (isEnabled() && pimpl->mouseWheelMove (e, wheel)))
  1372. Component::mouseWheelMove (e, wheel);
  1373. }
  1374. //==============================================================================
  1375. class SliderAccessibilityHandler : public AccessibilityHandler
  1376. {
  1377. public:
  1378. explicit SliderAccessibilityHandler (Slider& sliderToWrap)
  1379. : AccessibilityHandler (sliderToWrap,
  1380. AccessibilityRole::slider,
  1381. AccessibilityActions{},
  1382. AccessibilityHandler::Interfaces { std::make_unique<ValueInterface> (sliderToWrap) }),
  1383. slider (sliderToWrap)
  1384. {
  1385. }
  1386. String getHelp() const override { return slider.getTooltip(); }
  1387. private:
  1388. class ValueInterface : public AccessibilityValueInterface
  1389. {
  1390. public:
  1391. explicit ValueInterface (Slider& sliderToWrap)
  1392. : slider (sliderToWrap),
  1393. valueToControl (slider.isTwoValue() ? slider.getMaxValueObject() : slider.getValueObject())
  1394. {
  1395. }
  1396. bool isReadOnly() const override { return false; }
  1397. double getCurrentValue() const override { return valueToControl.getValue(); }
  1398. void setValue (double newValue) override { valueToControl = newValue; }
  1399. String getCurrentValueAsString() const override { return slider.getTextFromValue (getCurrentValue()); }
  1400. void setValueAsString (const String& newValue) override { setValue (slider.getValueFromText (newValue)); }
  1401. AccessibleValueRange getRange() const override
  1402. {
  1403. return { { slider.getMinimum(), slider.getMaximum() },
  1404. getStepSize() };
  1405. }
  1406. private:
  1407. double getStepSize() const
  1408. {
  1409. auto interval = slider.getInterval();
  1410. return interval != 0.0 ? interval
  1411. : slider.getRange().getLength() * 0.01;
  1412. }
  1413. Slider& slider;
  1414. Value valueToControl;
  1415. //==============================================================================
  1416. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueInterface)
  1417. };
  1418. Slider& slider;
  1419. //==============================================================================
  1420. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderAccessibilityHandler)
  1421. };
  1422. std::unique_ptr<AccessibilityHandler> Slider::createAccessibilityHandler()
  1423. {
  1424. return std::make_unique<SliderAccessibilityHandler> (*this);
  1425. }
  1426. } // namespace juce