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.

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