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.

1836 lines
66KB

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