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.

1767 lines
64KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. class Slider::Pimpl : public AsyncUpdater, // this needs to be public otherwise it will cause an
  21. // error when JUCE_DLL_BUILD=1
  22. private Value::Listener
  23. {
  24. public:
  25. Pimpl (Slider& s, SliderStyle sliderStyle, TextEntryBoxPosition textBoxPosition)
  26. : owner (s),
  27. style (sliderStyle),
  28. textBoxPos (textBoxPosition)
  29. {
  30. rotaryParams.startAngleRadians = MathConstants<float>::pi * 1.2f;
  31. rotaryParams.endAngleRadians = MathConstants<float>::pi * 2.8f;
  32. rotaryParams.stopAtEnd = true;
  33. }
  34. ~Pimpl() override
  35. {
  36. currentValue.removeListener (this);
  37. valueMin.removeListener (this);
  38. valueMax.removeListener (this);
  39. popupDisplay.reset();
  40. }
  41. //==============================================================================
  42. void registerListeners()
  43. {
  44. currentValue.addListener (this);
  45. valueMin.addListener (this);
  46. valueMax.addListener (this);
  47. }
  48. bool isHorizontal() const noexcept
  49. {
  50. return style == LinearHorizontal
  51. || style == LinearBar
  52. || style == TwoValueHorizontal
  53. || style == ThreeValueHorizontal;
  54. }
  55. bool isVertical() const noexcept
  56. {
  57. return style == LinearVertical
  58. || style == LinearBarVertical
  59. || style == TwoValueVertical
  60. || style == ThreeValueVertical;
  61. }
  62. bool isRotary() const noexcept
  63. {
  64. return style == Rotary
  65. || style == RotaryHorizontalDrag
  66. || style == RotaryVerticalDrag
  67. || style == RotaryHorizontalVerticalDrag;
  68. }
  69. bool isBar() const noexcept
  70. {
  71. return style == LinearBar
  72. || style == LinearBarVertical;
  73. }
  74. bool isTwoValue() const noexcept
  75. {
  76. return style == TwoValueHorizontal
  77. || style == TwoValueVertical;
  78. }
  79. bool isThreeValue() const noexcept
  80. {
  81. return style == ThreeValueHorizontal
  82. || style == ThreeValueVertical;
  83. }
  84. bool incDecDragDirectionIsHorizontal() const noexcept
  85. {
  86. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  87. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  88. }
  89. float getPositionOfValue (double value) const
  90. {
  91. if (isHorizontal() || isVertical())
  92. return getLinearSliderPos (value);
  93. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  94. return 0.0f;
  95. }
  96. void updateRange()
  97. {
  98. // figure out the number of DPs needed to display all values at this
  99. // interval setting.
  100. numDecimalPlaces = 7;
  101. if (normRange.interval != 0.0)
  102. {
  103. int v = std::abs (roundToInt (normRange.interval * 10000000));
  104. while ((v % 10) == 0 && numDecimalPlaces > 0)
  105. {
  106. --numDecimalPlaces;
  107. v /= 10;
  108. }
  109. }
  110. // keep the current values inside the new range..
  111. if (style != TwoValueHorizontal && style != TwoValueVertical)
  112. {
  113. setValue (getValue(), dontSendNotification);
  114. }
  115. else
  116. {
  117. setMinValue (getMinValue(), dontSendNotification, false);
  118. setMaxValue (getMaxValue(), dontSendNotification, false);
  119. }
  120. updateText();
  121. }
  122. void setRange (double newMin, double newMax, double newInt)
  123. {
  124. normRange = NormalisableRange<double> (newMin, newMax, newInt,
  125. normRange.skew, normRange.symmetricSkew);
  126. updateRange();
  127. }
  128. void setNormalisableRange (NormalisableRange<double> newRange)
  129. {
  130. normRange = newRange;
  131. updateRange();
  132. }
  133. double getValue() const
  134. {
  135. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  136. // methods to get the two values.
  137. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  138. return currentValue.getValue();
  139. }
  140. void setValue (double newValue, NotificationType notification)
  141. {
  142. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  143. // methods to set the two values.
  144. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  145. newValue = constrainedValue (newValue);
  146. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  147. {
  148. jassert (static_cast<double> (valueMin.getValue()) <= static_cast<double> (valueMax.getValue()));
  149. newValue = jlimit (static_cast<double> (valueMin.getValue()),
  150. static_cast<double> (valueMax.getValue()),
  151. newValue);
  152. }
  153. if (newValue != lastCurrentValue)
  154. {
  155. if (valueBox != nullptr)
  156. valueBox->hideEditor (true);
  157. lastCurrentValue = newValue;
  158. // (need to do this comparison because the Value will use equalsWithSameType to compare
  159. // the new and old values, so will generate unwanted change events if the type changes)
  160. if (currentValue != newValue)
  161. currentValue = newValue;
  162. updateText();
  163. owner.repaint();
  164. updatePopupDisplay (newValue);
  165. triggerChangeMessage (notification);
  166. }
  167. }
  168. void setMinValue (double newValue, NotificationType notification, bool allowNudgingOfOtherValues)
  169. {
  170. // The minimum value only applies to sliders that are in two- or three-value mode.
  171. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  172. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  173. newValue = constrainedValue (newValue);
  174. if (style == TwoValueHorizontal || style == TwoValueVertical)
  175. {
  176. if (allowNudgingOfOtherValues && newValue > static_cast<double> (valueMax.getValue()))
  177. setMaxValue (newValue, notification, false);
  178. newValue = jmin (static_cast<double> (valueMax.getValue()), newValue);
  179. }
  180. else
  181. {
  182. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  183. setValue (newValue, notification);
  184. newValue = jmin (lastCurrentValue, newValue);
  185. }
  186. if (lastValueMin != newValue)
  187. {
  188. lastValueMin = newValue;
  189. valueMin = newValue;
  190. owner.repaint();
  191. updatePopupDisplay (newValue);
  192. triggerChangeMessage (notification);
  193. }
  194. }
  195. void setMaxValue (double newValue, NotificationType notification, bool allowNudgingOfOtherValues)
  196. {
  197. // The maximum value only applies to sliders that are in two- or three-value mode.
  198. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  199. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  200. newValue = constrainedValue (newValue);
  201. if (style == TwoValueHorizontal || style == TwoValueVertical)
  202. {
  203. if (allowNudgingOfOtherValues && newValue < static_cast<double> (valueMin.getValue()))
  204. setMinValue (newValue, notification, false);
  205. newValue = jmax (static_cast<double> (valueMin.getValue()), newValue);
  206. }
  207. else
  208. {
  209. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  210. setValue (newValue, notification);
  211. newValue = jmax (lastCurrentValue, newValue);
  212. }
  213. if (lastValueMax != newValue)
  214. {
  215. lastValueMax = newValue;
  216. valueMax = newValue;
  217. owner.repaint();
  218. updatePopupDisplay (valueMax.getValue());
  219. triggerChangeMessage (notification);
  220. }
  221. }
  222. void setMinAndMaxValues (double newMinValue, double newMaxValue, NotificationType notification)
  223. {
  224. // The maximum value only applies to sliders that are in two- or three-value mode.
  225. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  226. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  227. if (newMaxValue < newMinValue)
  228. std::swap (newMaxValue, newMinValue);
  229. newMinValue = constrainedValue (newMinValue);
  230. newMaxValue = constrainedValue (newMaxValue);
  231. if (lastValueMax != newMaxValue || lastValueMin != newMinValue)
  232. {
  233. lastValueMax = newMaxValue;
  234. lastValueMin = newMinValue;
  235. valueMin = newMinValue;
  236. valueMax = newMaxValue;
  237. owner.repaint();
  238. triggerChangeMessage (notification);
  239. }
  240. }
  241. double getMinValue() const
  242. {
  243. // The minimum value only applies to sliders that are in two- or three-value mode.
  244. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  245. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  246. return valueMin.getValue();
  247. }
  248. double getMaxValue() const
  249. {
  250. // The maximum value only applies to sliders that are in two- or three-value mode.
  251. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  252. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  253. return valueMax.getValue();
  254. }
  255. void triggerChangeMessage (NotificationType notification)
  256. {
  257. if (notification != dontSendNotification)
  258. {
  259. owner.valueChanged();
  260. if (notification == sendNotificationSync)
  261. handleAsyncUpdate();
  262. else
  263. triggerAsyncUpdate();
  264. }
  265. }
  266. void handleAsyncUpdate() override
  267. {
  268. cancelPendingUpdate();
  269. Component::BailOutChecker checker (&owner);
  270. listeners.callChecked (checker, [&] (Slider::Listener& l) { l.sliderValueChanged (&owner); });
  271. if (checker.shouldBailOut())
  272. return;
  273. if (owner.onValueChange != nullptr)
  274. owner.onValueChange();
  275. if (auto* handler = owner.getAccessibilityHandler())
  276. handler->notifyAccessibilityEvent (AccessibilityEvent::valueChanged);
  277. }
  278. void sendDragStart()
  279. {
  280. owner.startedDragging();
  281. Component::BailOutChecker checker (&owner);
  282. listeners.callChecked (checker, [&] (Slider::Listener& l) { l.sliderDragStarted (&owner); });
  283. if (checker.shouldBailOut())
  284. return;
  285. if (owner.onDragStart != nullptr)
  286. owner.onDragStart();
  287. }
  288. void sendDragEnd()
  289. {
  290. owner.stoppedDragging();
  291. sliderBeingDragged = -1;
  292. Component::BailOutChecker checker (&owner);
  293. listeners.callChecked (checker, [&] (Slider::Listener& l) { l.sliderDragEnded (&owner); });
  294. if (checker.shouldBailOut())
  295. return;
  296. if (owner.onDragEnd != nullptr)
  297. owner.onDragEnd();
  298. }
  299. void incrementOrDecrement (double delta)
  300. {
  301. if (style == IncDecButtons)
  302. {
  303. auto newValue = owner.snapValue (getValue() + delta, notDragging);
  304. if (currentDrag != nullptr)
  305. {
  306. setValue (newValue, sendNotificationSync);
  307. }
  308. else
  309. {
  310. ScopedDragNotification drag (owner);
  311. setValue (newValue, sendNotificationSync);
  312. }
  313. }
  314. }
  315. void valueChanged (Value& value) override
  316. {
  317. if (value.refersToSameSourceAs (currentValue))
  318. {
  319. if (style != TwoValueHorizontal && style != TwoValueVertical)
  320. setValue (currentValue.getValue(), dontSendNotification);
  321. }
  322. else if (value.refersToSameSourceAs (valueMin))
  323. {
  324. setMinValue (valueMin.getValue(), dontSendNotification, true);
  325. }
  326. else if (value.refersToSameSourceAs (valueMax))
  327. {
  328. setMaxValue (valueMax.getValue(), dontSendNotification, true);
  329. }
  330. }
  331. void textChanged()
  332. {
  333. auto newValue = owner.snapValue (owner.getValueFromText (valueBox->getText()), notDragging);
  334. if (newValue != static_cast<double> (currentValue.getValue()))
  335. {
  336. ScopedDragNotification drag (owner);
  337. setValue (newValue, sendNotificationSync);
  338. }
  339. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  340. }
  341. void updateText()
  342. {
  343. if (valueBox != nullptr)
  344. {
  345. auto newValue = owner.getTextFromValue (currentValue.getValue());
  346. if (newValue != valueBox->getText())
  347. valueBox->setText (newValue, dontSendNotification);
  348. }
  349. }
  350. double constrainedValue (double value) const
  351. {
  352. return normRange.snapToLegalValue (value);
  353. }
  354. float getLinearSliderPos (double value) const
  355. {
  356. double pos;
  357. if (normRange.end <= normRange.start)
  358. pos = 0.5;
  359. else if (value < normRange.start)
  360. pos = 0.0;
  361. else if (value > normRange.end)
  362. pos = 1.0;
  363. else
  364. pos = owner.valueToProportionOfLength (value);
  365. if (isVertical() || style == IncDecButtons)
  366. pos = 1.0 - pos;
  367. jassert (pos >= 0 && pos <= 1.0);
  368. return (float) (sliderRegionStart + pos * sliderRegionSize);
  369. }
  370. void setSliderStyle (SliderStyle newStyle)
  371. {
  372. if (style != newStyle)
  373. {
  374. style = newStyle;
  375. owner.repaint();
  376. owner.lookAndFeelChanged();
  377. owner.invalidateAccessibilityHandler();
  378. }
  379. }
  380. void setVelocityModeParameters (double sensitivity, int threshold,
  381. double offset, bool userCanPressKeyToSwapMode,
  382. ModifierKeys::Flags newModifierToSwapModes)
  383. {
  384. velocityModeSensitivity = sensitivity;
  385. velocityModeOffset = offset;
  386. velocityModeThreshold = threshold;
  387. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  388. modifierToSwapModes = newModifierToSwapModes;
  389. }
  390. void setIncDecButtonsMode (IncDecButtonMode mode)
  391. {
  392. if (incDecButtonMode != mode)
  393. {
  394. incDecButtonMode = mode;
  395. owner.lookAndFeelChanged();
  396. }
  397. }
  398. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  399. bool isReadOnly,
  400. int textEntryBoxWidth,
  401. int textEntryBoxHeight)
  402. {
  403. if (textBoxPos != newPosition
  404. || editableText != (! isReadOnly)
  405. || textBoxWidth != textEntryBoxWidth
  406. || textBoxHeight != textEntryBoxHeight)
  407. {
  408. textBoxPos = newPosition;
  409. editableText = ! isReadOnly;
  410. textBoxWidth = textEntryBoxWidth;
  411. textBoxHeight = textEntryBoxHeight;
  412. owner.repaint();
  413. owner.lookAndFeelChanged();
  414. }
  415. }
  416. void setTextBoxIsEditable (bool shouldBeEditable)
  417. {
  418. editableText = shouldBeEditable;
  419. updateTextBoxEnablement();
  420. }
  421. void showTextBox()
  422. {
  423. jassert (editableText); // this should probably be avoided in read-only sliders.
  424. if (valueBox != nullptr)
  425. valueBox->showEditor();
  426. }
  427. void hideTextBox (bool discardCurrentEditorContents)
  428. {
  429. if (valueBox != nullptr)
  430. {
  431. valueBox->hideEditor (discardCurrentEditorContents);
  432. if (discardCurrentEditorContents)
  433. updateText();
  434. }
  435. }
  436. void setTextValueSuffix (const String& suffix)
  437. {
  438. if (textSuffix != suffix)
  439. {
  440. textSuffix = suffix;
  441. updateText();
  442. }
  443. }
  444. void updateTextBoxEnablement()
  445. {
  446. if (valueBox != nullptr)
  447. {
  448. bool shouldBeEditable = editableText && owner.isEnabled();
  449. if (valueBox->isEditable() != shouldBeEditable) // (to avoid changing the single/double click flags unless we need to)
  450. valueBox->setEditable (shouldBeEditable);
  451. }
  452. }
  453. void lookAndFeelChanged (LookAndFeel& lf)
  454. {
  455. if (textBoxPos != NoTextBox)
  456. {
  457. auto previousTextBoxContent = (valueBox != nullptr ? valueBox->getText()
  458. : owner.getTextFromValue (currentValue.getValue()));
  459. valueBox.reset();
  460. valueBox.reset (lf.createSliderTextBox (owner));
  461. owner.addAndMakeVisible (valueBox.get());
  462. valueBox->setWantsKeyboardFocus (false);
  463. valueBox->setAccessible (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. sliderBeingDragged.pimpl->sendDragEnd();
  1134. }
  1135. //==============================================================================
  1136. Slider::Slider()
  1137. {
  1138. init (LinearHorizontal, TextBoxLeft);
  1139. }
  1140. Slider::Slider (const String& name) : Component (name)
  1141. {
  1142. init (LinearHorizontal, TextBoxLeft);
  1143. }
  1144. Slider::Slider (SliderStyle style, TextEntryBoxPosition textBoxPos)
  1145. {
  1146. init (style, textBoxPos);
  1147. }
  1148. void Slider::init (SliderStyle style, TextEntryBoxPosition textBoxPos)
  1149. {
  1150. setWantsKeyboardFocus (false);
  1151. setRepaintsOnMouseActivity (true);
  1152. pimpl.reset (new Pimpl (*this, style, textBoxPos));
  1153. Slider::lookAndFeelChanged();
  1154. updateText();
  1155. pimpl->registerListeners();
  1156. }
  1157. Slider::~Slider() {}
  1158. //==============================================================================
  1159. void Slider::addListener (Listener* l) { pimpl->listeners.add (l); }
  1160. void Slider::removeListener (Listener* l) { pimpl->listeners.remove (l); }
  1161. //==============================================================================
  1162. Slider::SliderStyle Slider::getSliderStyle() const noexcept { return pimpl->style; }
  1163. void Slider::setSliderStyle (SliderStyle newStyle) { pimpl->setSliderStyle (newStyle); }
  1164. void Slider::setRotaryParameters (RotaryParameters p) noexcept
  1165. {
  1166. // make sure the values are sensible..
  1167. jassert (p.startAngleRadians >= 0 && p.endAngleRadians >= 0);
  1168. jassert (p.startAngleRadians < MathConstants<float>::pi * 4.0f
  1169. && p.endAngleRadians < MathConstants<float>::pi * 4.0f);
  1170. pimpl->rotaryParams = p;
  1171. }
  1172. void Slider::setRotaryParameters (float startAngleRadians, float endAngleRadians, bool stopAtEnd) noexcept
  1173. {
  1174. setRotaryParameters ({ startAngleRadians, endAngleRadians, stopAtEnd });
  1175. }
  1176. Slider::RotaryParameters Slider::getRotaryParameters() const noexcept
  1177. {
  1178. return pimpl->rotaryParams;
  1179. }
  1180. void Slider::setVelocityBasedMode (bool vb) { pimpl->isVelocityBased = vb; }
  1181. bool Slider::getVelocityBasedMode() const noexcept { return pimpl->isVelocityBased; }
  1182. bool Slider::getVelocityModeIsSwappable() const noexcept { return pimpl->userKeyOverridesVelocity; }
  1183. int Slider::getVelocityThreshold() const noexcept { return pimpl->velocityModeThreshold; }
  1184. double Slider::getVelocitySensitivity() const noexcept { return pimpl->velocityModeSensitivity; }
  1185. double Slider::getVelocityOffset() const noexcept { return pimpl->velocityModeOffset; }
  1186. void Slider::setVelocityModeParameters (double sensitivity, int threshold,
  1187. double offset, bool userCanPressKeyToSwapMode,
  1188. ModifierKeys::Flags modifierToSwapModes)
  1189. {
  1190. jassert (threshold >= 0);
  1191. jassert (sensitivity > 0);
  1192. jassert (offset >= 0);
  1193. pimpl->setVelocityModeParameters (sensitivity, threshold, offset,
  1194. userCanPressKeyToSwapMode, modifierToSwapModes);
  1195. }
  1196. double Slider::getSkewFactor() const noexcept { return pimpl->normRange.skew; }
  1197. bool Slider::isSymmetricSkew() const noexcept { return pimpl->normRange.symmetricSkew; }
  1198. void Slider::setSkewFactor (double factor, bool symmetricSkew)
  1199. {
  1200. pimpl->normRange.skew = factor;
  1201. pimpl->normRange.symmetricSkew = symmetricSkew;
  1202. }
  1203. void Slider::setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint)
  1204. {
  1205. pimpl->normRange.setSkewForCentre (sliderValueToShowAtMidPoint);
  1206. }
  1207. int Slider::getMouseDragSensitivity() const noexcept { return pimpl->pixelsForFullDragExtent; }
  1208. void Slider::setMouseDragSensitivity (int distanceForFullScaleDrag)
  1209. {
  1210. jassert (distanceForFullScaleDrag > 0);
  1211. pimpl->pixelsForFullDragExtent = distanceForFullScaleDrag;
  1212. }
  1213. void Slider::setIncDecButtonsMode (IncDecButtonMode mode) { pimpl->setIncDecButtonsMode (mode); }
  1214. Slider::TextEntryBoxPosition Slider::getTextBoxPosition() const noexcept { return pimpl->textBoxPos; }
  1215. int Slider::getTextBoxWidth() const noexcept { return pimpl->textBoxWidth; }
  1216. int Slider::getTextBoxHeight() const noexcept { return pimpl->textBoxHeight; }
  1217. void Slider::setTextBoxStyle (TextEntryBoxPosition newPosition, bool isReadOnly, int textEntryBoxWidth, int textEntryBoxHeight)
  1218. {
  1219. pimpl->setTextBoxStyle (newPosition, isReadOnly, textEntryBoxWidth, textEntryBoxHeight);
  1220. }
  1221. bool Slider::isTextBoxEditable() const noexcept { return pimpl->editableText; }
  1222. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) { pimpl->setTextBoxIsEditable (shouldBeEditable); }
  1223. void Slider::showTextBox() { pimpl->showTextBox(); }
  1224. void Slider::hideTextBox (bool discardCurrentEditorContents) { pimpl->hideTextBox (discardCurrentEditorContents); }
  1225. void Slider::setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease)
  1226. {
  1227. pimpl->sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  1228. }
  1229. bool Slider::getSliderSnapsToMousePosition() const noexcept { return pimpl->snapsToMousePos; }
  1230. void Slider::setSliderSnapsToMousePosition (bool shouldSnapToMouse) { pimpl->snapsToMousePos = shouldSnapToMouse; }
  1231. void Slider::setPopupDisplayEnabled (bool showOnDrag, bool showOnHover, Component* parent, int hoverTimeout)
  1232. {
  1233. pimpl->showPopupOnDrag = showOnDrag;
  1234. pimpl->showPopupOnHover = showOnHover;
  1235. pimpl->parentForPopupDisplay = parent;
  1236. pimpl->popupHoverTimeout = hoverTimeout;
  1237. }
  1238. Component* Slider::getCurrentPopupDisplay() const noexcept { return pimpl->popupDisplay.get(); }
  1239. //==============================================================================
  1240. void Slider::colourChanged() { lookAndFeelChanged(); }
  1241. void Slider::lookAndFeelChanged() { pimpl->lookAndFeelChanged (getLookAndFeel()); }
  1242. void Slider::enablementChanged() { repaint(); pimpl->updateTextBoxEnablement(); }
  1243. //==============================================================================
  1244. Range<double> Slider::getRange() const noexcept { return { pimpl->normRange.start, pimpl->normRange.end }; }
  1245. double Slider::getMaximum() const noexcept { return pimpl->normRange.end; }
  1246. double Slider::getMinimum() const noexcept { return pimpl->normRange.start; }
  1247. double Slider::getInterval() const noexcept { return pimpl->normRange.interval; }
  1248. void Slider::setRange (double newMin, double newMax, double newInt) { pimpl->setRange (newMin, newMax, newInt); }
  1249. void Slider::setRange (Range<double> newRange, double newInt) { pimpl->setRange (newRange.getStart(), newRange.getEnd(), newInt); }
  1250. void Slider::setNormalisableRange (NormalisableRange<double> newRange) { pimpl->setNormalisableRange (newRange); }
  1251. double Slider::getValue() const { return pimpl->getValue(); }
  1252. Value& Slider::getValueObject() noexcept { return pimpl->currentValue; }
  1253. Value& Slider::getMinValueObject() noexcept { return pimpl->valueMin; }
  1254. Value& Slider::getMaxValueObject() noexcept { return pimpl->valueMax; }
  1255. void Slider::setValue (double newValue, NotificationType notification)
  1256. {
  1257. pimpl->setValue (newValue, notification);
  1258. }
  1259. double Slider::getMinValue() const { return pimpl->getMinValue(); }
  1260. double Slider::getMaxValue() const { return pimpl->getMaxValue(); }
  1261. void Slider::setMinValue (double newValue, NotificationType notification, bool allowNudgingOfOtherValues)
  1262. {
  1263. pimpl->setMinValue (newValue, notification, allowNudgingOfOtherValues);
  1264. }
  1265. void Slider::setMaxValue (double newValue, NotificationType notification, bool allowNudgingOfOtherValues)
  1266. {
  1267. pimpl->setMaxValue (newValue, notification, allowNudgingOfOtherValues);
  1268. }
  1269. void Slider::setMinAndMaxValues (double newMinValue, double newMaxValue, NotificationType notification)
  1270. {
  1271. pimpl->setMinAndMaxValues (newMinValue, newMaxValue, notification);
  1272. }
  1273. void Slider::setDoubleClickReturnValue (bool isDoubleClickEnabled, double valueToSetOnDoubleClick, ModifierKeys mods)
  1274. {
  1275. pimpl->doubleClickToValue = isDoubleClickEnabled;
  1276. pimpl->doubleClickReturnValue = valueToSetOnDoubleClick;
  1277. pimpl->singleClickModifiers = mods;
  1278. }
  1279. double Slider::getDoubleClickReturnValue() const noexcept { return pimpl->doubleClickReturnValue; }
  1280. bool Slider::isDoubleClickReturnEnabled() const noexcept { return pimpl->doubleClickToValue; }
  1281. void Slider::updateText()
  1282. {
  1283. pimpl->updateText();
  1284. }
  1285. void Slider::setTextValueSuffix (const String& suffix)
  1286. {
  1287. pimpl->setTextValueSuffix (suffix);
  1288. }
  1289. String Slider::getTextValueSuffix() const
  1290. {
  1291. return pimpl->textSuffix;
  1292. }
  1293. String Slider::getTextFromValue (double v)
  1294. {
  1295. auto getText = [this] (double val)
  1296. {
  1297. if (textFromValueFunction != nullptr)
  1298. return textFromValueFunction (val);
  1299. if (getNumDecimalPlacesToDisplay() > 0)
  1300. return String (val, getNumDecimalPlacesToDisplay());
  1301. return String (roundToInt (val));
  1302. };
  1303. return getText (v) + getTextValueSuffix();
  1304. }
  1305. double Slider::getValueFromText (const String& text)
  1306. {
  1307. auto t = text.trimStart();
  1308. if (t.endsWith (getTextValueSuffix()))
  1309. t = t.substring (0, t.length() - getTextValueSuffix().length());
  1310. if (valueFromTextFunction != nullptr)
  1311. return valueFromTextFunction (t);
  1312. while (t.startsWithChar ('+'))
  1313. t = t.substring (1).trimStart();
  1314. return t.initialSectionContainingOnly ("0123456789.,-")
  1315. .getDoubleValue();
  1316. }
  1317. double Slider::proportionOfLengthToValue (double proportion)
  1318. {
  1319. return pimpl->normRange.convertFrom0to1 (proportion);
  1320. }
  1321. double Slider::valueToProportionOfLength (double value)
  1322. {
  1323. return pimpl->normRange.convertTo0to1 (value);
  1324. }
  1325. double Slider::snapValue (double attemptedValue, DragMode)
  1326. {
  1327. return attemptedValue;
  1328. }
  1329. int Slider::getNumDecimalPlacesToDisplay() const noexcept { return pimpl->numDecimalPlaces; }
  1330. void Slider::setNumDecimalPlacesToDisplay (int decimalPlacesToDisplay)
  1331. {
  1332. pimpl->numDecimalPlaces = decimalPlacesToDisplay;
  1333. updateText();
  1334. }
  1335. //==============================================================================
  1336. int Slider::getThumbBeingDragged() const noexcept { return pimpl->sliderBeingDragged; }
  1337. void Slider::startedDragging() {}
  1338. void Slider::stoppedDragging() {}
  1339. void Slider::valueChanged() {}
  1340. //==============================================================================
  1341. void Slider::setPopupMenuEnabled (bool menuEnabled) { pimpl->menuEnabled = menuEnabled; }
  1342. void Slider::setScrollWheelEnabled (bool enabled) { pimpl->scrollWheelEnabled = enabled; }
  1343. bool Slider::isScrollWheelEnabled() const noexcept { return pimpl->scrollWheelEnabled; }
  1344. bool Slider::isHorizontal() const noexcept { return pimpl->isHorizontal(); }
  1345. bool Slider::isVertical() const noexcept { return pimpl->isVertical(); }
  1346. bool Slider::isRotary() const noexcept { return pimpl->isRotary(); }
  1347. bool Slider::isBar() const noexcept { return pimpl->isBar(); }
  1348. bool Slider::isTwoValue() const noexcept { return pimpl->isTwoValue(); }
  1349. bool Slider::isThreeValue() const noexcept { return pimpl->isThreeValue(); }
  1350. float Slider::getPositionOfValue (double value) const { return pimpl->getPositionOfValue (value); }
  1351. //==============================================================================
  1352. void Slider::paint (Graphics& g) { pimpl->paint (g, getLookAndFeel()); }
  1353. void Slider::resized() { pimpl->resized (getLookAndFeel()); }
  1354. void Slider::focusOfChildComponentChanged (FocusChangeType) { repaint(); }
  1355. void Slider::mouseDown (const MouseEvent& e) { pimpl->mouseDown (e); }
  1356. void Slider::mouseUp (const MouseEvent&) { pimpl->mouseUp(); }
  1357. void Slider::mouseMove (const MouseEvent&) { pimpl->mouseMove(); }
  1358. void Slider::mouseExit (const MouseEvent&) { pimpl->mouseExit(); }
  1359. // If popup display is enabled and set to show on mouse hover, this makes sure
  1360. // it is shown when dragging the mouse over a slider and releasing
  1361. void Slider::mouseEnter (const MouseEvent&) { pimpl->mouseMove(); }
  1362. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  1363. {
  1364. if (isEnabled())
  1365. pimpl->modifierKeysChanged (modifiers);
  1366. }
  1367. void Slider::mouseDrag (const MouseEvent& e)
  1368. {
  1369. if (isEnabled())
  1370. pimpl->mouseDrag (e);
  1371. }
  1372. void Slider::mouseDoubleClick (const MouseEvent&)
  1373. {
  1374. if (isEnabled())
  1375. pimpl->mouseDoubleClick();
  1376. }
  1377. void Slider::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  1378. {
  1379. if (! (isEnabled() && pimpl->mouseWheelMove (e, wheel)))
  1380. Component::mouseWheelMove (e, wheel);
  1381. }
  1382. //==============================================================================
  1383. class SliderAccessibilityHandler : public AccessibilityHandler
  1384. {
  1385. public:
  1386. explicit SliderAccessibilityHandler (Slider& sliderToWrap)
  1387. : AccessibilityHandler (sliderToWrap,
  1388. AccessibilityRole::slider,
  1389. AccessibilityActions{},
  1390. AccessibilityHandler::Interfaces { std::make_unique<ValueInterface> (sliderToWrap) }),
  1391. slider (sliderToWrap)
  1392. {
  1393. }
  1394. String getHelp() const override { return slider.getTooltip(); }
  1395. private:
  1396. class ValueInterface : public AccessibilityValueInterface
  1397. {
  1398. public:
  1399. explicit ValueInterface (Slider& sliderToWrap)
  1400. : slider (sliderToWrap),
  1401. useMaxValue (slider.isTwoValue())
  1402. {
  1403. }
  1404. bool isReadOnly() const override { return false; }
  1405. double getCurrentValue() const override
  1406. {
  1407. return useMaxValue ? slider.getMaximum()
  1408. : slider.getValue();
  1409. }
  1410. void setValue (double newValue) override
  1411. {
  1412. Slider::ScopedDragNotification drag (slider);
  1413. if (useMaxValue)
  1414. slider.setMaxValue (newValue, sendNotificationSync);
  1415. else
  1416. slider.setValue (newValue, sendNotificationSync);
  1417. }
  1418. String getCurrentValueAsString() const override { return slider.getTextFromValue (getCurrentValue()); }
  1419. void setValueAsString (const String& newValue) override { setValue (slider.getValueFromText (newValue)); }
  1420. AccessibleValueRange getRange() const override
  1421. {
  1422. return { { slider.getMinimum(), slider.getMaximum() },
  1423. getStepSize() };
  1424. }
  1425. private:
  1426. double getStepSize() const
  1427. {
  1428. auto interval = slider.getInterval();
  1429. return interval != 0.0 ? interval
  1430. : slider.getRange().getLength() * 0.01;
  1431. }
  1432. Slider& slider;
  1433. const bool useMaxValue;
  1434. //==============================================================================
  1435. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueInterface)
  1436. };
  1437. Slider& slider;
  1438. //==============================================================================
  1439. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderAccessibilityHandler)
  1440. };
  1441. std::unique_ptr<AccessibilityHandler> Slider::createAccessibilityHandler()
  1442. {
  1443. return std::make_unique<SliderAccessibilityHandler> (*this);
  1444. }
  1445. } // namespace juce