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.

1824 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 (checker.shouldBailOut())
  295. return;
  296. if (auto* handler = owner.getAccessibilityHandler())
  297. handler->notifyAccessibilityEvent (AccessibilityEvent::valueChanged);
  298. }
  299. void sendDragStart()
  300. {
  301. owner.startedDragging();
  302. Component::BailOutChecker checker (&owner);
  303. listeners.callChecked (checker, [&] (Slider::Listener& l) { l.sliderDragStarted (&owner); });
  304. if (checker.shouldBailOut())
  305. return;
  306. if (owner.onDragStart != nullptr)
  307. owner.onDragStart();
  308. }
  309. void sendDragEnd()
  310. {
  311. owner.stoppedDragging();
  312. sliderBeingDragged = -1;
  313. Component::BailOutChecker checker (&owner);
  314. listeners.callChecked (checker, [&] (Slider::Listener& l) { l.sliderDragEnded (&owner); });
  315. if (checker.shouldBailOut())
  316. return;
  317. if (owner.onDragEnd != nullptr)
  318. owner.onDragEnd();
  319. }
  320. void incrementOrDecrement (double delta)
  321. {
  322. if (style == IncDecButtons)
  323. {
  324. auto newValue = owner.snapValue (getValue() + delta, notDragging);
  325. if (currentDrag != nullptr)
  326. {
  327. setValue (newValue, sendNotificationSync);
  328. }
  329. else
  330. {
  331. ScopedDragNotification drag (owner);
  332. setValue (newValue, sendNotificationSync);
  333. }
  334. }
  335. }
  336. void valueChanged (Value& value) override
  337. {
  338. if (value.refersToSameSourceAs (currentValue))
  339. {
  340. if (style != TwoValueHorizontal && style != TwoValueVertical)
  341. setValue (currentValue.getValue(), dontSendNotification);
  342. }
  343. else if (value.refersToSameSourceAs (valueMin))
  344. {
  345. setMinValue (valueMin.getValue(), dontSendNotification, true);
  346. }
  347. else if (value.refersToSameSourceAs (valueMax))
  348. {
  349. setMaxValue (valueMax.getValue(), dontSendNotification, true);
  350. }
  351. }
  352. void textChanged()
  353. {
  354. auto newValue = owner.snapValue (owner.getValueFromText (valueBox->getText()), notDragging);
  355. if (newValue != static_cast<double> (currentValue.getValue()))
  356. {
  357. ScopedDragNotification drag (owner);
  358. setValue (newValue, sendNotificationSync);
  359. }
  360. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  361. }
  362. void updateText()
  363. {
  364. if (valueBox != nullptr)
  365. {
  366. auto newValue = owner.getTextFromValue (currentValue.getValue());
  367. if (newValue != valueBox->getText())
  368. valueBox->setText (newValue, dontSendNotification);
  369. }
  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. if (style == SliderStyle::TwoValueHorizontal
  875. || style == SliderStyle::TwoValueVertical)
  876. {
  877. updatePopupDisplay (sliderBeingDragged == 2 ? getMaxValue()
  878. : getMinValue());
  879. }
  880. else
  881. {
  882. updatePopupDisplay (getValue());
  883. }
  884. popupDisplay->setVisible (true);
  885. }
  886. }
  887. void updatePopupDisplay (double valueToShow)
  888. {
  889. if (popupDisplay != nullptr)
  890. popupDisplay->updatePosition (owner.getTextFromValue (valueToShow));
  891. }
  892. bool canDoubleClickToValue() const
  893. {
  894. return doubleClickToValue
  895. && style != IncDecButtons
  896. && normRange.start <= doubleClickReturnValue
  897. && normRange.end >= doubleClickReturnValue;
  898. }
  899. void mouseDoubleClick()
  900. {
  901. if (canDoubleClickToValue())
  902. {
  903. ScopedDragNotification drag (owner);
  904. setValue (doubleClickReturnValue, sendNotificationSync);
  905. }
  906. }
  907. double getMouseWheelDelta (double value, double wheelAmount)
  908. {
  909. if (style == IncDecButtons)
  910. return normRange.interval * wheelAmount;
  911. auto proportionDelta = wheelAmount * 0.15;
  912. auto currentPos = owner.valueToProportionOfLength (value);
  913. auto newPos = currentPos + proportionDelta;
  914. newPos = (isRotary() && ! rotaryParams.stopAtEnd) ? newPos - std::floor (newPos)
  915. : jlimit (0.0, 1.0, newPos);
  916. return owner.proportionOfLengthToValue (newPos) - value;
  917. }
  918. bool mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  919. {
  920. if (scrollWheelEnabled
  921. && style != TwoValueHorizontal
  922. && style != TwoValueVertical)
  923. {
  924. // sometimes duplicate wheel events seem to be sent, so since we're going to
  925. // bump the value by a minimum of the interval, avoid doing this twice..
  926. if (e.eventTime != lastMouseWheelTime)
  927. {
  928. lastMouseWheelTime = e.eventTime;
  929. if (normRange.end > normRange.start && ! e.mods.isAnyMouseButtonDown())
  930. {
  931. if (valueBox != nullptr)
  932. valueBox->hideEditor (false);
  933. auto value = static_cast<double> (currentValue.getValue());
  934. auto delta = getMouseWheelDelta (value, (std::abs (wheel.deltaX) > std::abs (wheel.deltaY)
  935. ? -wheel.deltaX : wheel.deltaY)
  936. * (wheel.isReversed ? -1.0f : 1.0f));
  937. if (delta != 0.0)
  938. {
  939. auto newValue = value + jmax (normRange.interval, std::abs (delta)) * (delta < 0 ? -1.0 : 1.0);
  940. ScopedDragNotification drag (owner);
  941. setValue (owner.snapValue (newValue, notDragging), sendNotificationSync);
  942. }
  943. }
  944. }
  945. return true;
  946. }
  947. return false;
  948. }
  949. void modifierKeysChanged (const ModifierKeys& modifiers)
  950. {
  951. if (style != IncDecButtons && style != Rotary && isAbsoluteDragMode (modifiers))
  952. restoreMouseIfHidden();
  953. }
  954. bool isAbsoluteDragMode (ModifierKeys mods) const
  955. {
  956. return isVelocityBased == (userKeyOverridesVelocity && mods.testFlags (modifierToSwapModes));
  957. }
  958. void restoreMouseIfHidden()
  959. {
  960. for (auto& ms : Desktop::getInstance().getMouseSources())
  961. {
  962. if (ms.isUnboundedMouseMovementEnabled())
  963. {
  964. ms.enableUnboundedMouseMovement (false);
  965. auto pos = sliderBeingDragged == 2 ? getMaxValue()
  966. : (sliderBeingDragged == 1 ? getMinValue()
  967. : static_cast<double> (currentValue.getValue()));
  968. Point<float> mousePos;
  969. if (isRotary())
  970. {
  971. mousePos = ms.getLastMouseDownPosition();
  972. auto delta = (float) (pixelsForFullDragExtent * (owner.valueToProportionOfLength (valueOnMouseDown)
  973. - owner.valueToProportionOfLength (pos)));
  974. if (style == RotaryHorizontalDrag) mousePos += Point<float> (-delta, 0.0f);
  975. else if (style == RotaryVerticalDrag) mousePos += Point<float> (0.0f, delta);
  976. else mousePos += Point<float> (delta / -2.0f, delta / 2.0f);
  977. mousePos = owner.getScreenBounds().reduced (4).toFloat().getConstrainedPoint (mousePos);
  978. mouseDragStartPos = mousePosWhenLastDragged = owner.getLocalPoint (nullptr, mousePos);
  979. valueOnMouseDown = valueWhenLastDragged;
  980. }
  981. else
  982. {
  983. auto pixelPos = (float) getLinearSliderPos (pos);
  984. mousePos = owner.localPointToGlobal (Point<float> (isHorizontal() ? pixelPos : ((float) owner.getWidth() / 2.0f),
  985. isVertical() ? pixelPos : ((float) owner.getHeight() / 2.0f)));
  986. }
  987. const_cast <MouseInputSource&> (ms).setScreenPosition (mousePos);
  988. }
  989. }
  990. }
  991. //==============================================================================
  992. void paint (Graphics& g, LookAndFeel& lf)
  993. {
  994. if (style != IncDecButtons)
  995. {
  996. if (isRotary())
  997. {
  998. auto sliderPos = (float) owner.valueToProportionOfLength (lastCurrentValue);
  999. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  1000. lf.drawRotarySlider (g,
  1001. sliderRect.getX(), sliderRect.getY(),
  1002. sliderRect.getWidth(), sliderRect.getHeight(),
  1003. sliderPos, rotaryParams.startAngleRadians,
  1004. rotaryParams.endAngleRadians, owner);
  1005. }
  1006. else
  1007. {
  1008. lf.drawLinearSlider (g,
  1009. sliderRect.getX(), sliderRect.getY(),
  1010. sliderRect.getWidth(), sliderRect.getHeight(),
  1011. getLinearSliderPos (lastCurrentValue),
  1012. getLinearSliderPos (lastValueMin),
  1013. getLinearSliderPos (lastValueMax),
  1014. style, owner);
  1015. }
  1016. if ((style == LinearBar || style == LinearBarVertical) && valueBox == nullptr)
  1017. {
  1018. g.setColour (owner.findColour (Slider::textBoxOutlineColourId));
  1019. g.drawRect (0, 0, owner.getWidth(), owner.getHeight(), 1);
  1020. }
  1021. }
  1022. }
  1023. //==============================================================================
  1024. void resized (LookAndFeel& lf)
  1025. {
  1026. auto layout = lf.getSliderLayout (owner);
  1027. sliderRect = layout.sliderBounds;
  1028. if (valueBox != nullptr)
  1029. valueBox->setBounds (layout.textBoxBounds);
  1030. if (isHorizontal())
  1031. {
  1032. sliderRegionStart = layout.sliderBounds.getX();
  1033. sliderRegionSize = layout.sliderBounds.getWidth();
  1034. }
  1035. else if (isVertical())
  1036. {
  1037. sliderRegionStart = layout.sliderBounds.getY();
  1038. sliderRegionSize = layout.sliderBounds.getHeight();
  1039. }
  1040. else if (style == IncDecButtons)
  1041. {
  1042. resizeIncDecButtons();
  1043. }
  1044. }
  1045. //==============================================================================
  1046. void resizeIncDecButtons()
  1047. {
  1048. auto buttonRect = sliderRect;
  1049. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  1050. buttonRect.expand (-2, 0);
  1051. else
  1052. buttonRect.expand (0, -2);
  1053. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  1054. if (incDecButtonsSideBySide)
  1055. {
  1056. decButton->setBounds (buttonRect.removeFromLeft (buttonRect.getWidth() / 2));
  1057. decButton->setConnectedEdges (Button::ConnectedOnRight);
  1058. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  1059. }
  1060. else
  1061. {
  1062. decButton->setBounds (buttonRect.removeFromBottom (buttonRect.getHeight() / 2));
  1063. decButton->setConnectedEdges (Button::ConnectedOnTop);
  1064. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  1065. }
  1066. incButton->setBounds (buttonRect);
  1067. }
  1068. //==============================================================================
  1069. Slider& owner;
  1070. SliderStyle style;
  1071. ListenerList<Slider::Listener> listeners;
  1072. Value currentValue, valueMin, valueMax;
  1073. double lastCurrentValue = 0, lastValueMin = 0, lastValueMax = 0;
  1074. NormalisableRange<double> normRange { 0.0, 10.0 };
  1075. double doubleClickReturnValue = 0;
  1076. double valueWhenLastDragged = 0, valueOnMouseDown = 0, lastAngle = 0;
  1077. double velocityModeSensitivity = 1.0, velocityModeOffset = 0, minMaxDiff = 0;
  1078. int velocityModeThreshold = 1;
  1079. RotaryParameters rotaryParams;
  1080. Point<float> mouseDragStartPos, mousePosWhenLastDragged;
  1081. int sliderRegionStart = 0, sliderRegionSize = 1;
  1082. int sliderBeingDragged = -1;
  1083. int pixelsForFullDragExtent = 250;
  1084. Time lastMouseWheelTime;
  1085. Rectangle<int> sliderRect;
  1086. std::unique_ptr<ScopedDragNotification> currentDrag;
  1087. TextEntryBoxPosition textBoxPos;
  1088. String textSuffix;
  1089. int numDecimalPlaces = 7;
  1090. int fixedNumDecimalPlaces = -1;
  1091. int textBoxWidth = 80, textBoxHeight = 20;
  1092. IncDecButtonMode incDecButtonMode = incDecButtonsNotDraggable;
  1093. ModifierKeys::Flags modifierToSwapModes = ModifierKeys::ctrlAltCommandModifiers;
  1094. bool editableText = true;
  1095. bool doubleClickToValue = false;
  1096. bool isVelocityBased = false;
  1097. bool userKeyOverridesVelocity = true;
  1098. bool incDecButtonsSideBySide = false;
  1099. bool sendChangeOnlyOnRelease = false;
  1100. bool showPopupOnDrag = false;
  1101. bool showPopupOnHover = false;
  1102. bool menuEnabled = false;
  1103. bool useDragEvents = false;
  1104. bool incDecDragged = false;
  1105. bool scrollWheelEnabled = true;
  1106. bool snapsToMousePos = true;
  1107. int popupHoverTimeout = 2000;
  1108. double lastPopupDismissal = 0.0;
  1109. ModifierKeys singleClickModifiers;
  1110. std::unique_ptr<Label> valueBox;
  1111. std::unique_ptr<Button> incButton, decButton;
  1112. //==============================================================================
  1113. struct PopupDisplayComponent : public BubbleComponent,
  1114. public Timer
  1115. {
  1116. PopupDisplayComponent (Slider& s, bool isOnDesktop)
  1117. : owner (s),
  1118. font (s.getLookAndFeel().getSliderPopupFont (s))
  1119. {
  1120. if (isOnDesktop)
  1121. setTransform (AffineTransform::scale (Component::getApproximateScaleFactorForComponent (&s)));
  1122. setAlwaysOnTop (true);
  1123. setAllowedPlacement (owner.getLookAndFeel().getSliderPopupPlacement (s));
  1124. setLookAndFeel (&s.getLookAndFeel());
  1125. }
  1126. ~PopupDisplayComponent() override
  1127. {
  1128. if (owner.pimpl != nullptr)
  1129. owner.pimpl->lastPopupDismissal = Time::getMillisecondCounterHiRes();
  1130. }
  1131. void paintContent (Graphics& g, int w, int h) override
  1132. {
  1133. g.setFont (font);
  1134. g.setColour (owner.findColour (TooltipWindow::textColourId, true));
  1135. g.drawFittedText (text, Rectangle<int> (w, h), Justification::centred, 1);
  1136. }
  1137. void getContentSize (int& w, int& h) override
  1138. {
  1139. w = font.getStringWidth (text) + 18;
  1140. h = (int) (font.getHeight() * 1.6f);
  1141. }
  1142. void updatePosition (const String& newText)
  1143. {
  1144. text = newText;
  1145. BubbleComponent::setPosition (&owner);
  1146. repaint();
  1147. }
  1148. void timerCallback() override
  1149. {
  1150. stopTimer();
  1151. owner.pimpl->popupDisplay.reset();
  1152. }
  1153. private:
  1154. //==============================================================================
  1155. Slider& owner;
  1156. Font font;
  1157. String text;
  1158. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PopupDisplayComponent)
  1159. };
  1160. std::unique_ptr<PopupDisplayComponent> popupDisplay;
  1161. Component* parentForPopupDisplay = nullptr;
  1162. //==============================================================================
  1163. static double smallestAngleBetween (double a1, double a2) noexcept
  1164. {
  1165. return jmin (std::abs (a1 - a2),
  1166. std::abs (a1 + MathConstants<double>::twoPi - a2),
  1167. std::abs (a2 + MathConstants<double>::twoPi - a1));
  1168. }
  1169. };
  1170. //==============================================================================
  1171. Slider::ScopedDragNotification::ScopedDragNotification (Slider& s)
  1172. : sliderBeingDragged (s)
  1173. {
  1174. sliderBeingDragged.pimpl->sendDragStart();
  1175. }
  1176. Slider::ScopedDragNotification::~ScopedDragNotification()
  1177. {
  1178. if (sliderBeingDragged.pimpl != nullptr)
  1179. sliderBeingDragged.pimpl->sendDragEnd();
  1180. }
  1181. //==============================================================================
  1182. Slider::Slider()
  1183. {
  1184. init (LinearHorizontal, TextBoxLeft);
  1185. }
  1186. Slider::Slider (const String& name) : Component (name)
  1187. {
  1188. init (LinearHorizontal, TextBoxLeft);
  1189. }
  1190. Slider::Slider (SliderStyle style, TextEntryBoxPosition textBoxPos)
  1191. {
  1192. init (style, textBoxPos);
  1193. }
  1194. void Slider::init (SliderStyle style, TextEntryBoxPosition textBoxPos)
  1195. {
  1196. setWantsKeyboardFocus (false);
  1197. setRepaintsOnMouseActivity (true);
  1198. pimpl.reset (new Pimpl (*this, style, textBoxPos));
  1199. Slider::lookAndFeelChanged();
  1200. updateText();
  1201. pimpl->registerListeners();
  1202. }
  1203. Slider::~Slider() {}
  1204. //==============================================================================
  1205. void Slider::addListener (Listener* l) { pimpl->listeners.add (l); }
  1206. void Slider::removeListener (Listener* l) { pimpl->listeners.remove (l); }
  1207. //==============================================================================
  1208. Slider::SliderStyle Slider::getSliderStyle() const noexcept { return pimpl->style; }
  1209. void Slider::setSliderStyle (SliderStyle newStyle) { pimpl->setSliderStyle (newStyle); }
  1210. void Slider::setRotaryParameters (RotaryParameters p) noexcept
  1211. {
  1212. // make sure the values are sensible..
  1213. jassert (p.startAngleRadians >= 0 && p.endAngleRadians >= 0);
  1214. jassert (p.startAngleRadians < MathConstants<float>::pi * 4.0f
  1215. && p.endAngleRadians < MathConstants<float>::pi * 4.0f);
  1216. pimpl->rotaryParams = p;
  1217. }
  1218. void Slider::setRotaryParameters (float startAngleRadians, float endAngleRadians, bool stopAtEnd) noexcept
  1219. {
  1220. setRotaryParameters ({ startAngleRadians, endAngleRadians, stopAtEnd });
  1221. }
  1222. Slider::RotaryParameters Slider::getRotaryParameters() const noexcept
  1223. {
  1224. return pimpl->rotaryParams;
  1225. }
  1226. void Slider::setVelocityBasedMode (bool vb) { pimpl->isVelocityBased = vb; }
  1227. bool Slider::getVelocityBasedMode() const noexcept { return pimpl->isVelocityBased; }
  1228. bool Slider::getVelocityModeIsSwappable() const noexcept { return pimpl->userKeyOverridesVelocity; }
  1229. int Slider::getVelocityThreshold() const noexcept { return pimpl->velocityModeThreshold; }
  1230. double Slider::getVelocitySensitivity() const noexcept { return pimpl->velocityModeSensitivity; }
  1231. double Slider::getVelocityOffset() const noexcept { return pimpl->velocityModeOffset; }
  1232. void Slider::setVelocityModeParameters (double sensitivity, int threshold,
  1233. double offset, bool userCanPressKeyToSwapMode,
  1234. ModifierKeys::Flags modifierToSwapModes)
  1235. {
  1236. jassert (threshold >= 0);
  1237. jassert (sensitivity > 0);
  1238. jassert (offset >= 0);
  1239. pimpl->setVelocityModeParameters (sensitivity, threshold, offset,
  1240. userCanPressKeyToSwapMode, modifierToSwapModes);
  1241. }
  1242. double Slider::getSkewFactor() const noexcept { return pimpl->normRange.skew; }
  1243. bool Slider::isSymmetricSkew() const noexcept { return pimpl->normRange.symmetricSkew; }
  1244. void Slider::setSkewFactor (double factor, bool symmetricSkew)
  1245. {
  1246. pimpl->normRange.skew = factor;
  1247. pimpl->normRange.symmetricSkew = symmetricSkew;
  1248. }
  1249. void Slider::setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint)
  1250. {
  1251. pimpl->normRange.setSkewForCentre (sliderValueToShowAtMidPoint);
  1252. }
  1253. int Slider::getMouseDragSensitivity() const noexcept { return pimpl->pixelsForFullDragExtent; }
  1254. void Slider::setMouseDragSensitivity (int distanceForFullScaleDrag)
  1255. {
  1256. jassert (distanceForFullScaleDrag > 0);
  1257. pimpl->pixelsForFullDragExtent = distanceForFullScaleDrag;
  1258. }
  1259. void Slider::setIncDecButtonsMode (IncDecButtonMode mode) { pimpl->setIncDecButtonsMode (mode); }
  1260. Slider::TextEntryBoxPosition Slider::getTextBoxPosition() const noexcept { return pimpl->textBoxPos; }
  1261. int Slider::getTextBoxWidth() const noexcept { return pimpl->textBoxWidth; }
  1262. int Slider::getTextBoxHeight() const noexcept { return pimpl->textBoxHeight; }
  1263. void Slider::setTextBoxStyle (TextEntryBoxPosition newPosition, bool isReadOnly, int textEntryBoxWidth, int textEntryBoxHeight)
  1264. {
  1265. pimpl->setTextBoxStyle (newPosition, isReadOnly, textEntryBoxWidth, textEntryBoxHeight);
  1266. }
  1267. bool Slider::isTextBoxEditable() const noexcept { return pimpl->editableText; }
  1268. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) { pimpl->setTextBoxIsEditable (shouldBeEditable); }
  1269. void Slider::showTextBox() { pimpl->showTextBox(); }
  1270. void Slider::hideTextBox (bool discardCurrentEditorContents) { pimpl->hideTextBox (discardCurrentEditorContents); }
  1271. void Slider::setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease)
  1272. {
  1273. pimpl->sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  1274. }
  1275. bool Slider::getSliderSnapsToMousePosition() const noexcept { return pimpl->snapsToMousePos; }
  1276. void Slider::setSliderSnapsToMousePosition (bool shouldSnapToMouse) { pimpl->snapsToMousePos = shouldSnapToMouse; }
  1277. void Slider::setPopupDisplayEnabled (bool showOnDrag, bool showOnHover, Component* parent, int hoverTimeout)
  1278. {
  1279. pimpl->showPopupOnDrag = showOnDrag;
  1280. pimpl->showPopupOnHover = showOnHover;
  1281. pimpl->parentForPopupDisplay = parent;
  1282. pimpl->popupHoverTimeout = hoverTimeout;
  1283. }
  1284. Component* Slider::getCurrentPopupDisplay() const noexcept { return pimpl->popupDisplay.get(); }
  1285. //==============================================================================
  1286. void Slider::colourChanged() { lookAndFeelChanged(); }
  1287. void Slider::lookAndFeelChanged() { pimpl->lookAndFeelChanged (getLookAndFeel()); }
  1288. void Slider::enablementChanged() { repaint(); pimpl->updateTextBoxEnablement(); }
  1289. //==============================================================================
  1290. Range<double> Slider::getRange() const noexcept { return { pimpl->normRange.start, pimpl->normRange.end }; }
  1291. double Slider::getMaximum() const noexcept { return pimpl->normRange.end; }
  1292. double Slider::getMinimum() const noexcept { return pimpl->normRange.start; }
  1293. double Slider::getInterval() const noexcept { return pimpl->normRange.interval; }
  1294. void Slider::setRange (double newMin, double newMax, double newInt) { pimpl->setRange (newMin, newMax, newInt); }
  1295. void Slider::setRange (Range<double> newRange, double newInt) { pimpl->setRange (newRange.getStart(), newRange.getEnd(), newInt); }
  1296. void Slider::setNormalisableRange (NormalisableRange<double> newRange) { pimpl->setNormalisableRange (newRange); }
  1297. double Slider::getValue() const { return pimpl->getValue(); }
  1298. Value& Slider::getValueObject() noexcept { return pimpl->currentValue; }
  1299. Value& Slider::getMinValueObject() noexcept { return pimpl->valueMin; }
  1300. Value& Slider::getMaxValueObject() noexcept { return pimpl->valueMax; }
  1301. void Slider::setValue (double newValue, NotificationType notification)
  1302. {
  1303. pimpl->setValue (newValue, notification);
  1304. }
  1305. double Slider::getMinValue() const { return pimpl->getMinValue(); }
  1306. double Slider::getMaxValue() const { return pimpl->getMaxValue(); }
  1307. void Slider::setMinValue (double newValue, NotificationType notification, bool allowNudgingOfOtherValues)
  1308. {
  1309. pimpl->setMinValue (newValue, notification, allowNudgingOfOtherValues);
  1310. }
  1311. void Slider::setMaxValue (double newValue, NotificationType notification, bool allowNudgingOfOtherValues)
  1312. {
  1313. pimpl->setMaxValue (newValue, notification, allowNudgingOfOtherValues);
  1314. }
  1315. void Slider::setMinAndMaxValues (double newMinValue, double newMaxValue, NotificationType notification)
  1316. {
  1317. pimpl->setMinAndMaxValues (newMinValue, newMaxValue, notification);
  1318. }
  1319. void Slider::setDoubleClickReturnValue (bool isDoubleClickEnabled, double valueToSetOnDoubleClick, ModifierKeys mods)
  1320. {
  1321. pimpl->doubleClickToValue = isDoubleClickEnabled;
  1322. pimpl->doubleClickReturnValue = valueToSetOnDoubleClick;
  1323. pimpl->singleClickModifiers = mods;
  1324. }
  1325. double Slider::getDoubleClickReturnValue() const noexcept { return pimpl->doubleClickReturnValue; }
  1326. bool Slider::isDoubleClickReturnEnabled() const noexcept { return pimpl->doubleClickToValue; }
  1327. void Slider::updateText()
  1328. {
  1329. pimpl->updateText();
  1330. }
  1331. void Slider::setTextValueSuffix (const String& suffix)
  1332. {
  1333. pimpl->setTextValueSuffix (suffix);
  1334. }
  1335. String Slider::getTextValueSuffix() const
  1336. {
  1337. return pimpl->textSuffix;
  1338. }
  1339. String Slider::getTextFromValue (double v)
  1340. {
  1341. auto getText = [this] (double val)
  1342. {
  1343. if (textFromValueFunction != nullptr)
  1344. return textFromValueFunction (val);
  1345. if (getNumDecimalPlacesToDisplay() > 0)
  1346. return String (val, getNumDecimalPlacesToDisplay());
  1347. return String (roundToInt (val));
  1348. };
  1349. return getText (v) + getTextValueSuffix();
  1350. }
  1351. double Slider::getValueFromText (const String& text)
  1352. {
  1353. auto t = text.trimStart();
  1354. if (t.endsWith (getTextValueSuffix()))
  1355. t = t.substring (0, t.length() - getTextValueSuffix().length());
  1356. if (valueFromTextFunction != nullptr)
  1357. return valueFromTextFunction (t);
  1358. while (t.startsWithChar ('+'))
  1359. t = t.substring (1).trimStart();
  1360. return t.initialSectionContainingOnly ("0123456789.,-")
  1361. .getDoubleValue();
  1362. }
  1363. double Slider::proportionOfLengthToValue (double proportion)
  1364. {
  1365. return pimpl->normRange.convertFrom0to1 (proportion);
  1366. }
  1367. double Slider::valueToProportionOfLength (double value)
  1368. {
  1369. return pimpl->normRange.convertTo0to1 (value);
  1370. }
  1371. double Slider::snapValue (double attemptedValue, DragMode)
  1372. {
  1373. return attemptedValue;
  1374. }
  1375. int Slider::getNumDecimalPlacesToDisplay() const noexcept
  1376. {
  1377. return pimpl->getNumDecimalPlacesToDisplay();
  1378. }
  1379. void Slider::setNumDecimalPlacesToDisplay (int decimalPlacesToDisplay)
  1380. {
  1381. pimpl->setNumDecimalPlacesToDisplay (decimalPlacesToDisplay);
  1382. updateText();
  1383. }
  1384. //==============================================================================
  1385. int Slider::getThumbBeingDragged() const noexcept { return pimpl->sliderBeingDragged; }
  1386. void Slider::startedDragging() {}
  1387. void Slider::stoppedDragging() {}
  1388. void Slider::valueChanged() {}
  1389. //==============================================================================
  1390. void Slider::setPopupMenuEnabled (bool menuEnabled) { pimpl->menuEnabled = menuEnabled; }
  1391. void Slider::setScrollWheelEnabled (bool enabled) { pimpl->scrollWheelEnabled = enabled; }
  1392. bool Slider::isScrollWheelEnabled() const noexcept { return pimpl->scrollWheelEnabled; }
  1393. bool Slider::isHorizontal() const noexcept { return pimpl->isHorizontal(); }
  1394. bool Slider::isVertical() const noexcept { return pimpl->isVertical(); }
  1395. bool Slider::isRotary() const noexcept { return pimpl->isRotary(); }
  1396. bool Slider::isBar() const noexcept { return pimpl->isBar(); }
  1397. bool Slider::isTwoValue() const noexcept { return pimpl->isTwoValue(); }
  1398. bool Slider::isThreeValue() const noexcept { return pimpl->isThreeValue(); }
  1399. float Slider::getPositionOfValue (double value) const { return pimpl->getPositionOfValue (value); }
  1400. //==============================================================================
  1401. void Slider::paint (Graphics& g) { pimpl->paint (g, getLookAndFeel()); }
  1402. void Slider::resized() { pimpl->resized (getLookAndFeel()); }
  1403. void Slider::focusOfChildComponentChanged (FocusChangeType) { repaint(); }
  1404. void Slider::mouseDown (const MouseEvent& e) { pimpl->mouseDown (e); }
  1405. void Slider::mouseUp (const MouseEvent&) { pimpl->mouseUp(); }
  1406. void Slider::mouseMove (const MouseEvent&) { pimpl->mouseMove(); }
  1407. void Slider::mouseExit (const MouseEvent&) { pimpl->mouseExit(); }
  1408. // If popup display is enabled and set to show on mouse hover, this makes sure
  1409. // it is shown when dragging the mouse over a slider and releasing
  1410. void Slider::mouseEnter (const MouseEvent&) { pimpl->mouseMove(); }
  1411. /** @internal */
  1412. bool Slider::keyPressed (const KeyPress& k) { return pimpl->keyPressed (k); }
  1413. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  1414. {
  1415. if (isEnabled())
  1416. pimpl->modifierKeysChanged (modifiers);
  1417. }
  1418. void Slider::mouseDrag (const MouseEvent& e)
  1419. {
  1420. if (isEnabled())
  1421. pimpl->mouseDrag (e);
  1422. }
  1423. void Slider::mouseDoubleClick (const MouseEvent&)
  1424. {
  1425. if (isEnabled())
  1426. pimpl->mouseDoubleClick();
  1427. }
  1428. void Slider::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  1429. {
  1430. if (! (isEnabled() && pimpl->mouseWheelMove (e, wheel)))
  1431. Component::mouseWheelMove (e, wheel);
  1432. }
  1433. //==============================================================================
  1434. class SliderAccessibilityHandler : public AccessibilityHandler
  1435. {
  1436. public:
  1437. explicit SliderAccessibilityHandler (Slider& sliderToWrap)
  1438. : AccessibilityHandler (sliderToWrap,
  1439. AccessibilityRole::slider,
  1440. AccessibilityActions{},
  1441. AccessibilityHandler::Interfaces { std::make_unique<ValueInterface> (sliderToWrap) }),
  1442. slider (sliderToWrap)
  1443. {
  1444. }
  1445. String getHelp() const override { return slider.getTooltip(); }
  1446. private:
  1447. class ValueInterface : public AccessibilityValueInterface
  1448. {
  1449. public:
  1450. explicit ValueInterface (Slider& sliderToWrap)
  1451. : slider (sliderToWrap),
  1452. useMaxValue (slider.isTwoValue())
  1453. {
  1454. }
  1455. bool isReadOnly() const override { return false; }
  1456. double getCurrentValue() const override
  1457. {
  1458. return useMaxValue ? slider.getMaximum()
  1459. : slider.getValue();
  1460. }
  1461. void setValue (double newValue) override
  1462. {
  1463. Slider::ScopedDragNotification drag (slider);
  1464. if (useMaxValue)
  1465. slider.setMaxValue (newValue, sendNotificationSync);
  1466. else
  1467. slider.setValue (newValue, sendNotificationSync);
  1468. }
  1469. String getCurrentValueAsString() const override { return slider.getTextFromValue (getCurrentValue()); }
  1470. void setValueAsString (const String& newValue) override { setValue (slider.getValueFromText (newValue)); }
  1471. AccessibleValueRange getRange() const override
  1472. {
  1473. return { { slider.getMinimum(), slider.getMaximum() },
  1474. getStepSize (slider) };
  1475. }
  1476. private:
  1477. Slider& slider;
  1478. const bool useMaxValue;
  1479. //==============================================================================
  1480. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueInterface)
  1481. };
  1482. Slider& slider;
  1483. //==============================================================================
  1484. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderAccessibilityHandler)
  1485. };
  1486. std::unique_ptr<AccessibilityHandler> Slider::createAccessibilityHandler()
  1487. {
  1488. return std::make_unique<SliderAccessibilityHandler> (*this);
  1489. }
  1490. } // namespace juce