Audio plugin host https://kx.studio/carla
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.

1768 lines
64KB

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