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.

1424 lines
44KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. BEGIN_JUCE_NAMESPACE
  19. //==============================================================================
  20. class Slider::PopupDisplayComponent : public BubbleComponent,
  21. public Timer
  22. {
  23. public:
  24. PopupDisplayComponent (Slider& owner_)
  25. : owner (owner_),
  26. font (15.0f, Font::bold)
  27. {
  28. setAlwaysOnTop (true);
  29. }
  30. void paintContent (Graphics& g, int w, int h)
  31. {
  32. g.setFont (font);
  33. g.setColour (findColour (TooltipWindow::textColourId, true));
  34. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  35. }
  36. void getContentSize (int& w, int& h)
  37. {
  38. w = font.getStringWidth (text) + 18;
  39. h = (int) (font.getHeight() * 1.6f);
  40. }
  41. void updatePosition (const String& newText)
  42. {
  43. text = newText;
  44. BubbleComponent::setPosition (&owner);
  45. repaint();
  46. }
  47. void timerCallback()
  48. {
  49. owner.popupDisplay = nullptr;
  50. }
  51. private:
  52. Slider& owner;
  53. Font font;
  54. String text;
  55. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PopupDisplayComponent);
  56. };
  57. //==============================================================================
  58. Slider::Slider (const String& name)
  59. : Component (name),
  60. lastCurrentValue (0),
  61. lastValueMin (0),
  62. lastValueMax (0),
  63. minimum (0),
  64. maximum (10),
  65. interval (0),
  66. skewFactor (1.0),
  67. velocityModeSensitivity (1.0),
  68. velocityModeOffset (0.0),
  69. velocityModeThreshold (1),
  70. rotaryStart (float_Pi * 1.2f),
  71. rotaryEnd (float_Pi * 2.8f),
  72. numDecimalPlaces (7),
  73. sliderRegionStart (0),
  74. sliderRegionSize (1),
  75. sliderBeingDragged (-1),
  76. pixelsForFullDragExtent (250),
  77. style (LinearHorizontal),
  78. textBoxPos (TextBoxLeft),
  79. textBoxWidth (80),
  80. textBoxHeight (20),
  81. incDecButtonMode (incDecButtonsNotDraggable),
  82. editableText (true),
  83. doubleClickToValue (false),
  84. isVelocityBased (false),
  85. userKeyOverridesVelocity (true),
  86. rotaryStop (true),
  87. incDecButtonsSideBySide (false),
  88. sendChangeOnlyOnRelease (false),
  89. popupDisplayEnabled (false),
  90. menuEnabled (false),
  91. menuShown (false),
  92. scrollWheelEnabled (true),
  93. snapsToMousePos (true),
  94. parentForPopupDisplay (nullptr)
  95. {
  96. setWantsKeyboardFocus (false);
  97. setRepaintsOnMouseActivity (true);
  98. Slider::lookAndFeelChanged();
  99. updateText();
  100. currentValue.addListener (this);
  101. valueMin.addListener (this);
  102. valueMax.addListener (this);
  103. }
  104. Slider::~Slider()
  105. {
  106. currentValue.removeListener (this);
  107. valueMin.removeListener (this);
  108. valueMax.removeListener (this);
  109. popupDisplay = nullptr;
  110. }
  111. //==============================================================================
  112. void Slider::handleAsyncUpdate()
  113. {
  114. cancelPendingUpdate();
  115. Component::BailOutChecker checker (this);
  116. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  117. }
  118. void Slider::sendDragStart()
  119. {
  120. startedDragging();
  121. Component::BailOutChecker checker (this);
  122. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  123. }
  124. void Slider::sendDragEnd()
  125. {
  126. stoppedDragging();
  127. sliderBeingDragged = -1;
  128. Component::BailOutChecker checker (this);
  129. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  130. }
  131. void Slider::addListener (SliderListener* const listener)
  132. {
  133. listeners.add (listener);
  134. }
  135. void Slider::removeListener (SliderListener* const listener)
  136. {
  137. listeners.remove (listener);
  138. }
  139. //==============================================================================
  140. void Slider::setSliderStyle (const SliderStyle newStyle)
  141. {
  142. if (style != newStyle)
  143. {
  144. style = newStyle;
  145. repaint();
  146. lookAndFeelChanged();
  147. }
  148. }
  149. void Slider::setRotaryParameters (const float startAngleRadians,
  150. const float endAngleRadians,
  151. const bool stopAtEnd)
  152. {
  153. // make sure the values are sensible..
  154. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  155. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  156. jassert (rotaryStart < rotaryEnd);
  157. rotaryStart = startAngleRadians;
  158. rotaryEnd = endAngleRadians;
  159. rotaryStop = stopAtEnd;
  160. }
  161. void Slider::setVelocityBasedMode (const bool velBased)
  162. {
  163. isVelocityBased = velBased;
  164. }
  165. void Slider::setVelocityModeParameters (const double sensitivity,
  166. const int threshold,
  167. const double offset,
  168. const bool userCanPressKeyToSwapMode)
  169. {
  170. jassert (threshold >= 0);
  171. jassert (sensitivity > 0);
  172. jassert (offset >= 0);
  173. velocityModeSensitivity = sensitivity;
  174. velocityModeOffset = offset;
  175. velocityModeThreshold = threshold;
  176. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  177. }
  178. void Slider::setSkewFactor (const double factor)
  179. {
  180. skewFactor = factor;
  181. }
  182. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  183. {
  184. if (maximum > minimum)
  185. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  186. / (maximum - minimum));
  187. }
  188. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  189. {
  190. jassert (distanceForFullScaleDrag > 0);
  191. pixelsForFullDragExtent = distanceForFullScaleDrag;
  192. }
  193. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  194. {
  195. if (incDecButtonMode != mode)
  196. {
  197. incDecButtonMode = mode;
  198. lookAndFeelChanged();
  199. }
  200. }
  201. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  202. const bool isReadOnly,
  203. const int textEntryBoxWidth,
  204. const int textEntryBoxHeight)
  205. {
  206. if (textBoxPos != newPosition
  207. || editableText != (! isReadOnly)
  208. || textBoxWidth != textEntryBoxWidth
  209. || textBoxHeight != textEntryBoxHeight)
  210. {
  211. textBoxPos = newPosition;
  212. editableText = ! isReadOnly;
  213. textBoxWidth = textEntryBoxWidth;
  214. textBoxHeight = textEntryBoxHeight;
  215. repaint();
  216. lookAndFeelChanged();
  217. }
  218. }
  219. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  220. {
  221. editableText = shouldBeEditable;
  222. if (valueBox != nullptr)
  223. valueBox->setEditable (shouldBeEditable && isEnabled());
  224. }
  225. void Slider::showTextBox()
  226. {
  227. jassert (editableText); // this should probably be avoided in read-only sliders.
  228. if (valueBox != nullptr)
  229. valueBox->showEditor();
  230. }
  231. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  232. {
  233. if (valueBox != nullptr)
  234. {
  235. valueBox->hideEditor (discardCurrentEditorContents);
  236. if (discardCurrentEditorContents)
  237. updateText();
  238. }
  239. }
  240. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  241. {
  242. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  243. }
  244. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  245. {
  246. snapsToMousePos = shouldSnapToMouse;
  247. }
  248. void Slider::setPopupDisplayEnabled (const bool enabled, Component* const parentComponentToUse)
  249. {
  250. popupDisplayEnabled = enabled;
  251. parentForPopupDisplay = parentComponentToUse;
  252. }
  253. Component* Slider::getCurrentPopupDisplay() const noexcept
  254. {
  255. return popupDisplay.get();
  256. }
  257. //==============================================================================
  258. void Slider::colourChanged()
  259. {
  260. lookAndFeelChanged();
  261. }
  262. void Slider::lookAndFeelChanged()
  263. {
  264. LookAndFeel& lf = getLookAndFeel();
  265. if (textBoxPos != NoTextBox)
  266. {
  267. const String previousTextBoxContent (valueBox != nullptr ? valueBox->getText()
  268. : getTextFromValue (currentValue.getValue()));
  269. valueBox = nullptr;
  270. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  271. valueBox->setWantsKeyboardFocus (false);
  272. valueBox->setText (previousTextBoxContent, false);
  273. if (valueBox->isEditable() != editableText) // (avoid overriding the single/double click flags unless we have to)
  274. valueBox->setEditable (editableText && isEnabled());
  275. valueBox->addListener (this);
  276. if (style == LinearBar)
  277. valueBox->addMouseListener (this, false);
  278. valueBox->setTooltip (getTooltip());
  279. }
  280. else
  281. {
  282. valueBox = nullptr;
  283. }
  284. if (style == IncDecButtons)
  285. {
  286. addAndMakeVisible (incButton = lf.createSliderButton (true));
  287. incButton->addListener (this);
  288. addAndMakeVisible (decButton = lf.createSliderButton (false));
  289. decButton->addListener (this);
  290. if (incDecButtonMode != incDecButtonsNotDraggable)
  291. {
  292. incButton->addMouseListener (this, false);
  293. decButton->addMouseListener (this, false);
  294. }
  295. else
  296. {
  297. incButton->setRepeatSpeed (300, 100, 20);
  298. incButton->addMouseListener (decButton, false);
  299. decButton->setRepeatSpeed (300, 100, 20);
  300. decButton->addMouseListener (incButton, false);
  301. }
  302. incButton->setTooltip (getTooltip());
  303. decButton->setTooltip (getTooltip());
  304. }
  305. else
  306. {
  307. incButton = nullptr;
  308. decButton = nullptr;
  309. }
  310. setComponentEffect (lf.getSliderEffect());
  311. resized();
  312. repaint();
  313. }
  314. //==============================================================================
  315. void Slider::setRange (const double newMin,
  316. const double newMax,
  317. const double newInt)
  318. {
  319. if (minimum != newMin
  320. || maximum != newMax
  321. || interval != newInt)
  322. {
  323. minimum = newMin;
  324. maximum = newMax;
  325. interval = newInt;
  326. // figure out the number of DPs needed to display all values at this
  327. // interval setting.
  328. numDecimalPlaces = 7;
  329. if (newInt != 0)
  330. {
  331. int v = abs ((int) (newInt * 10000000));
  332. while ((v % 10) == 0)
  333. {
  334. --numDecimalPlaces;
  335. v /= 10;
  336. }
  337. }
  338. // keep the current values inside the new range..
  339. if (style != TwoValueHorizontal && style != TwoValueVertical)
  340. {
  341. setValue (getValue(), false, false);
  342. }
  343. else
  344. {
  345. setMinValue (getMinValue(), false, false);
  346. setMaxValue (getMaxValue(), false, false);
  347. }
  348. updateText();
  349. }
  350. }
  351. void Slider::triggerChangeMessage (const bool synchronous)
  352. {
  353. if (synchronous)
  354. handleAsyncUpdate();
  355. else
  356. triggerAsyncUpdate();
  357. valueChanged();
  358. }
  359. void Slider::valueChanged (Value& value)
  360. {
  361. if (value.refersToSameSourceAs (currentValue))
  362. {
  363. if (style != TwoValueHorizontal && style != TwoValueVertical)
  364. setValue (currentValue.getValue(), false, false);
  365. }
  366. else if (value.refersToSameSourceAs (valueMin))
  367. setMinValue (valueMin.getValue(), false, false, true);
  368. else if (value.refersToSameSourceAs (valueMax))
  369. setMaxValue (valueMax.getValue(), false, false, true);
  370. }
  371. double Slider::getValue() const
  372. {
  373. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  374. // methods to get the two values.
  375. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  376. return currentValue.getValue();
  377. }
  378. void Slider::setValue (double newValue,
  379. const bool sendUpdateMessage,
  380. const bool sendMessageSynchronously)
  381. {
  382. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  383. // methods to set the two values.
  384. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  385. newValue = constrainedValue (newValue);
  386. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  387. {
  388. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  389. newValue = jlimit ((double) valueMin.getValue(),
  390. (double) valueMax.getValue(),
  391. newValue);
  392. }
  393. if (newValue != lastCurrentValue)
  394. {
  395. if (valueBox != nullptr)
  396. valueBox->hideEditor (true);
  397. lastCurrentValue = newValue;
  398. // (need to do this comparison because the Value will use equalsWithSameType to compare
  399. // the new and old values, so will generate unwanted change events if the type changes)
  400. if (currentValue != newValue)
  401. currentValue = newValue;
  402. updateText();
  403. repaint();
  404. if (popupDisplay != nullptr)
  405. popupDisplay->updatePosition (getTextFromValue (newValue));
  406. if (sendUpdateMessage)
  407. triggerChangeMessage (sendMessageSynchronously);
  408. }
  409. }
  410. double Slider::getMinValue() const
  411. {
  412. // The minimum value only applies to sliders that are in two- or three-value mode.
  413. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  414. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  415. return valueMin.getValue();
  416. }
  417. double Slider::getMaxValue() const
  418. {
  419. // The maximum value only applies to sliders that are in two- or three-value mode.
  420. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  421. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  422. return valueMax.getValue();
  423. }
  424. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  425. {
  426. // The minimum value only applies to sliders that are in two- or three-value mode.
  427. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  428. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  429. newValue = constrainedValue (newValue);
  430. if (style == TwoValueHorizontal || style == TwoValueVertical)
  431. {
  432. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  433. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  434. newValue = jmin ((double) valueMax.getValue(), newValue);
  435. }
  436. else
  437. {
  438. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  439. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  440. newValue = jmin (lastCurrentValue, newValue);
  441. }
  442. if (lastValueMin != newValue)
  443. {
  444. lastValueMin = newValue;
  445. valueMin = newValue;
  446. repaint();
  447. if (popupDisplay != nullptr)
  448. popupDisplay->updatePosition (getTextFromValue (newValue));
  449. if (sendUpdateMessage)
  450. triggerChangeMessage (sendMessageSynchronously);
  451. }
  452. }
  453. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  454. {
  455. // The maximum value only applies to sliders that are in two- or three-value mode.
  456. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  457. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  458. newValue = constrainedValue (newValue);
  459. if (style == TwoValueHorizontal || style == TwoValueVertical)
  460. {
  461. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  462. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  463. newValue = jmax ((double) valueMin.getValue(), newValue);
  464. }
  465. else
  466. {
  467. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  468. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  469. newValue = jmax (lastCurrentValue, newValue);
  470. }
  471. if (lastValueMax != newValue)
  472. {
  473. lastValueMax = newValue;
  474. valueMax = newValue;
  475. repaint();
  476. if (popupDisplay != nullptr)
  477. popupDisplay->updatePosition (getTextFromValue (valueMax.getValue()));
  478. if (sendUpdateMessage)
  479. triggerChangeMessage (sendMessageSynchronously);
  480. }
  481. }
  482. void Slider::setMinAndMaxValues (double newMinValue, double newMaxValue, bool sendUpdateMessage, bool sendMessageSynchronously)
  483. {
  484. // The maximum value only applies to sliders that are in two- or three-value mode.
  485. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  486. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  487. if (newMaxValue < newMinValue)
  488. std::swap (newMaxValue, newMinValue);
  489. newMinValue = constrainedValue (newMinValue);
  490. newMaxValue = constrainedValue (newMaxValue);
  491. if (lastValueMax != newMaxValue || lastValueMin != newMinValue)
  492. {
  493. lastValueMax = newMaxValue;
  494. lastValueMin = newMinValue;
  495. valueMin = newMinValue;
  496. valueMax = newMaxValue;
  497. repaint();
  498. if (sendUpdateMessage)
  499. triggerChangeMessage (sendMessageSynchronously);
  500. }
  501. }
  502. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  503. const double valueToSetOnDoubleClick)
  504. {
  505. doubleClickToValue = isDoubleClickEnabled;
  506. doubleClickReturnValue = valueToSetOnDoubleClick;
  507. }
  508. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  509. {
  510. isEnabled_ = doubleClickToValue;
  511. return doubleClickReturnValue;
  512. }
  513. void Slider::updateText()
  514. {
  515. if (valueBox != nullptr)
  516. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  517. }
  518. void Slider::setTextValueSuffix (const String& suffix)
  519. {
  520. if (textSuffix != suffix)
  521. {
  522. textSuffix = suffix;
  523. updateText();
  524. }
  525. }
  526. String Slider::getTextValueSuffix() const
  527. {
  528. return textSuffix;
  529. }
  530. String Slider::getTextFromValue (double v)
  531. {
  532. if (getNumDecimalPlacesToDisplay() > 0)
  533. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  534. else
  535. return String (roundToInt (v)) + getTextValueSuffix();
  536. }
  537. double Slider::getValueFromText (const String& text)
  538. {
  539. String t (text.trimStart());
  540. if (t.endsWith (textSuffix))
  541. t = t.substring (0, t.length() - textSuffix.length());
  542. while (t.startsWithChar ('+'))
  543. t = t.substring (1).trimStart();
  544. return t.initialSectionContainingOnly ("0123456789.,-")
  545. .getDoubleValue();
  546. }
  547. double Slider::proportionOfLengthToValue (double proportion)
  548. {
  549. if (skewFactor != 1.0 && proportion > 0.0)
  550. proportion = exp (log (proportion) / skewFactor);
  551. return minimum + (maximum - minimum) * proportion;
  552. }
  553. double Slider::valueToProportionOfLength (double value)
  554. {
  555. const double n = (value - minimum) / (maximum - minimum);
  556. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  557. }
  558. double Slider::snapValue (double attemptedValue, const bool)
  559. {
  560. return attemptedValue;
  561. }
  562. //==============================================================================
  563. void Slider::startedDragging()
  564. {
  565. }
  566. void Slider::stoppedDragging()
  567. {
  568. }
  569. void Slider::valueChanged()
  570. {
  571. }
  572. //==============================================================================
  573. void Slider::enablementChanged()
  574. {
  575. repaint();
  576. }
  577. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  578. {
  579. menuEnabled = menuEnabled_;
  580. }
  581. void Slider::setScrollWheelEnabled (const bool enabled)
  582. {
  583. scrollWheelEnabled = enabled;
  584. }
  585. //==============================================================================
  586. void Slider::labelTextChanged (Label* label)
  587. {
  588. const double newValue = snapValue (getValueFromText (label->getText()), false);
  589. if (newValue != (double) currentValue.getValue())
  590. {
  591. sendDragStart();
  592. setValue (newValue, true, true);
  593. sendDragEnd();
  594. }
  595. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  596. }
  597. void Slider::buttonClicked (Button* button)
  598. {
  599. if (style == IncDecButtons)
  600. {
  601. sendDragStart();
  602. if (button == incButton)
  603. setValue (snapValue (getValue() + interval, false), true, true);
  604. else if (button == decButton)
  605. setValue (snapValue (getValue() - interval, false), true, true);
  606. sendDragEnd();
  607. }
  608. }
  609. //==============================================================================
  610. double Slider::constrainedValue (double value) const
  611. {
  612. if (interval > 0)
  613. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  614. if (value <= minimum || maximum <= minimum)
  615. value = minimum;
  616. else if (value >= maximum)
  617. value = maximum;
  618. return value;
  619. }
  620. float Slider::getLinearSliderPos (const double value)
  621. {
  622. double sliderPosProportional;
  623. if (maximum > minimum)
  624. {
  625. if (value < minimum)
  626. {
  627. sliderPosProportional = 0.0;
  628. }
  629. else if (value > maximum)
  630. {
  631. sliderPosProportional = 1.0;
  632. }
  633. else
  634. {
  635. sliderPosProportional = valueToProportionOfLength (value);
  636. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  637. }
  638. }
  639. else
  640. {
  641. sliderPosProportional = 0.5;
  642. }
  643. if (isVertical() || style == IncDecButtons)
  644. sliderPosProportional = 1.0 - sliderPosProportional;
  645. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  646. }
  647. bool Slider::isHorizontal() const
  648. {
  649. return style == LinearHorizontal
  650. || style == LinearBar
  651. || style == TwoValueHorizontal
  652. || style == ThreeValueHorizontal;
  653. }
  654. bool Slider::isVertical() const
  655. {
  656. return style == LinearVertical
  657. || style == TwoValueVertical
  658. || style == ThreeValueVertical;
  659. }
  660. bool Slider::incDecDragDirectionIsHorizontal() const
  661. {
  662. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  663. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  664. }
  665. float Slider::getPositionOfValue (const double value)
  666. {
  667. if (isHorizontal() || isVertical())
  668. {
  669. return getLinearSliderPos (value);
  670. }
  671. else
  672. {
  673. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  674. return 0.0f;
  675. }
  676. }
  677. //==============================================================================
  678. void Slider::paint (Graphics& g)
  679. {
  680. if (style != IncDecButtons)
  681. {
  682. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  683. {
  684. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  685. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  686. getLookAndFeel().drawRotarySlider (g,
  687. sliderRect.getX(),
  688. sliderRect.getY(),
  689. sliderRect.getWidth(),
  690. sliderRect.getHeight(),
  691. sliderPos,
  692. rotaryStart, rotaryEnd,
  693. *this);
  694. }
  695. else
  696. {
  697. getLookAndFeel().drawLinearSlider (g,
  698. sliderRect.getX(),
  699. sliderRect.getY(),
  700. sliderRect.getWidth(),
  701. sliderRect.getHeight(),
  702. getLinearSliderPos (lastCurrentValue),
  703. getLinearSliderPos (lastValueMin),
  704. getLinearSliderPos (lastValueMax),
  705. style,
  706. *this);
  707. }
  708. if (style == LinearBar && valueBox == nullptr)
  709. {
  710. g.setColour (findColour (Slider::textBoxOutlineColourId));
  711. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  712. }
  713. }
  714. }
  715. void Slider::resized()
  716. {
  717. int minXSpace = 0;
  718. int minYSpace = 0;
  719. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  720. minXSpace = 30;
  721. else
  722. minYSpace = 15;
  723. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  724. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  725. if (style == LinearBar)
  726. {
  727. if (valueBox != nullptr)
  728. valueBox->setBounds (getLocalBounds());
  729. }
  730. else
  731. {
  732. if (textBoxPos == NoTextBox)
  733. {
  734. sliderRect = getLocalBounds();
  735. }
  736. else if (textBoxPos == TextBoxLeft)
  737. {
  738. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  739. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  740. }
  741. else if (textBoxPos == TextBoxRight)
  742. {
  743. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  744. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  745. }
  746. else if (textBoxPos == TextBoxAbove)
  747. {
  748. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  749. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  750. }
  751. else if (textBoxPos == TextBoxBelow)
  752. {
  753. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  754. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  755. }
  756. }
  757. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  758. if (style == LinearBar)
  759. {
  760. const int barIndent = 1;
  761. sliderRegionStart = barIndent;
  762. sliderRegionSize = getWidth() - barIndent * 2;
  763. sliderRect.setBounds (sliderRegionStart, barIndent,
  764. sliderRegionSize, getHeight() - barIndent * 2);
  765. }
  766. else if (isHorizontal())
  767. {
  768. sliderRegionStart = sliderRect.getX() + indent;
  769. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  770. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  771. sliderRegionSize, sliderRect.getHeight());
  772. }
  773. else if (isVertical())
  774. {
  775. sliderRegionStart = sliderRect.getY() + indent;
  776. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  777. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  778. sliderRect.getWidth(), sliderRegionSize);
  779. }
  780. else
  781. {
  782. sliderRegionStart = 0;
  783. sliderRegionSize = 100;
  784. }
  785. if (style == IncDecButtons)
  786. {
  787. Rectangle<int> buttonRect (sliderRect);
  788. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  789. buttonRect.expand (-2, 0);
  790. else
  791. buttonRect.expand (0, -2);
  792. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  793. if (incDecButtonsSideBySide)
  794. {
  795. decButton->setBounds (buttonRect.removeFromLeft (buttonRect.getWidth() / 2));
  796. decButton->setConnectedEdges (Button::ConnectedOnRight);
  797. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  798. }
  799. else
  800. {
  801. decButton->setBounds (buttonRect.removeFromBottom (buttonRect.getHeight() / 2));
  802. decButton->setConnectedEdges (Button::ConnectedOnTop);
  803. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  804. }
  805. incButton->setBounds (buttonRect);
  806. }
  807. }
  808. void Slider::focusOfChildComponentChanged (FocusChangeType)
  809. {
  810. repaint();
  811. }
  812. namespace SliderHelpers
  813. {
  814. double smallestAngleBetween (double a1, double a2) noexcept
  815. {
  816. return jmin (std::abs (a1 - a2),
  817. std::abs (a1 + double_Pi * 2.0 - a2),
  818. std::abs (a2 + double_Pi * 2.0 - a1));
  819. }
  820. void sliderMenuCallback (int result, Slider* slider)
  821. {
  822. if (slider != nullptr)
  823. {
  824. switch (result)
  825. {
  826. case 1: slider->setVelocityBasedMode (! slider->getVelocityBasedMode()); break;
  827. case 2: slider->setSliderStyle (Slider::Rotary); break;
  828. case 3: slider->setSliderStyle (Slider::RotaryHorizontalDrag); break;
  829. case 4: slider->setSliderStyle (Slider::RotaryVerticalDrag); break;
  830. default: break;
  831. }
  832. }
  833. }
  834. }
  835. void Slider::showPopupMenu()
  836. {
  837. menuShown = true;
  838. PopupMenu m;
  839. m.setLookAndFeel (&getLookAndFeel());
  840. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  841. m.addSeparator();
  842. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  843. {
  844. PopupMenu rotaryMenu;
  845. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  846. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  847. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  848. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  849. }
  850. m.showMenuAsync (PopupMenu::Options(),
  851. ModalCallbackFunction::forComponent (SliderHelpers::sliderMenuCallback, this));
  852. }
  853. int Slider::getThumbIndexAt (const MouseEvent& e)
  854. {
  855. const bool isTwoValue = (style == TwoValueHorizontal || style == TwoValueVertical);
  856. const bool isThreeValue = (style == ThreeValueHorizontal || style == ThreeValueVertical);
  857. if (isTwoValue || isThreeValue)
  858. {
  859. const float mousePos = (float) (isVertical() ? e.y : e.x);
  860. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  861. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  862. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  863. if (isTwoValue)
  864. return maxPosDistance <= minPosDistance ? 2 : 1;
  865. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  866. return 1;
  867. else if (normalPosDistance >= maxPosDistance)
  868. return 2;
  869. }
  870. return 0;
  871. }
  872. void Slider::mouseDown (const MouseEvent& e)
  873. {
  874. mouseWasHidden = false;
  875. incDecDragged = false;
  876. mouseDragStartPos = mousePosWhenLastDragged = e.getPosition();
  877. if (isEnabled())
  878. {
  879. if (e.mods.isPopupMenu() && menuEnabled)
  880. {
  881. showPopupMenu();
  882. }
  883. else if (maximum > minimum)
  884. {
  885. menuShown = false;
  886. if (valueBox != nullptr)
  887. valueBox->hideEditor (true);
  888. sliderBeingDragged = getThumbIndexAt (e);
  889. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  890. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  891. * valueToProportionOfLength (currentValue.getValue());
  892. valueWhenLastDragged = (sliderBeingDragged == 2 ? valueMax
  893. : (sliderBeingDragged == 1 ? valueMin
  894. : currentValue)).getValue();
  895. valueOnMouseDown = valueWhenLastDragged;
  896. if (popupDisplayEnabled)
  897. {
  898. PopupDisplayComponent* const popup = new PopupDisplayComponent (*this);
  899. popupDisplay = popup;
  900. if (parentForPopupDisplay != nullptr)
  901. parentForPopupDisplay->addChildComponent (popup);
  902. else
  903. popup->addToDesktop (0);
  904. popup->setVisible (true);
  905. }
  906. sendDragStart();
  907. mouseDrag (e);
  908. }
  909. }
  910. }
  911. void Slider::mouseUp (const MouseEvent&)
  912. {
  913. if (isEnabled()
  914. && (! menuShown)
  915. && (maximum > minimum)
  916. && (style != IncDecButtons || incDecDragged))
  917. {
  918. restoreMouseIfHidden();
  919. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  920. triggerChangeMessage (false);
  921. sendDragEnd();
  922. popupDisplay = nullptr;
  923. if (style == IncDecButtons)
  924. {
  925. incButton->setState (Button::buttonNormal);
  926. decButton->setState (Button::buttonNormal);
  927. }
  928. }
  929. else if (popupDisplay != nullptr)
  930. {
  931. popupDisplay->startTimer (2000);
  932. }
  933. }
  934. void Slider::restoreMouseIfHidden()
  935. {
  936. if (mouseWasHidden)
  937. {
  938. mouseWasHidden = false;
  939. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  940. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  941. const double pos = sliderBeingDragged == 2 ? getMaxValue()
  942. : (sliderBeingDragged == 1 ? getMinValue()
  943. : (double) currentValue.getValue());
  944. Point<int> mousePos;
  945. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  946. {
  947. mousePos = Desktop::getLastMouseDownPosition();
  948. if (style == RotaryHorizontalDrag)
  949. {
  950. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  951. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  952. }
  953. else
  954. {
  955. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  956. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  957. }
  958. }
  959. else
  960. {
  961. const int pixelPos = (int) getLinearSliderPos (pos);
  962. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  963. isVertical() ? pixelPos : (getHeight() / 2)));
  964. }
  965. Desktop::setMousePosition (mousePos);
  966. }
  967. }
  968. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  969. {
  970. if (isEnabled()
  971. && style != IncDecButtons
  972. && style != Rotary
  973. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  974. {
  975. restoreMouseIfHidden();
  976. }
  977. }
  978. void Slider::handleRotaryDrag (const MouseEvent& e)
  979. {
  980. const int dx = e.x - sliderRect.getCentreX();
  981. const int dy = e.y - sliderRect.getCentreY();
  982. if (dx * dx + dy * dy > 25)
  983. {
  984. double angle = std::atan2 ((double) dx, (double) -dy);
  985. while (angle < 0.0)
  986. angle += double_Pi * 2.0;
  987. if (rotaryStop && ! e.mouseWasClicked())
  988. {
  989. if (std::abs (angle - lastAngle) > double_Pi)
  990. {
  991. if (angle >= lastAngle)
  992. angle -= double_Pi * 2.0;
  993. else
  994. angle += double_Pi * 2.0;
  995. }
  996. if (angle >= lastAngle)
  997. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  998. else
  999. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  1000. }
  1001. else
  1002. {
  1003. while (angle < rotaryStart)
  1004. angle += double_Pi * 2.0;
  1005. if (angle > rotaryEnd)
  1006. {
  1007. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  1008. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  1009. angle = rotaryStart;
  1010. else
  1011. angle = rotaryEnd;
  1012. }
  1013. }
  1014. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  1015. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  1016. lastAngle = angle;
  1017. }
  1018. }
  1019. void Slider::handleAbsoluteDrag (const MouseEvent& e)
  1020. {
  1021. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  1022. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  1023. if (style == RotaryHorizontalDrag
  1024. || style == RotaryVerticalDrag
  1025. || style == IncDecButtons
  1026. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  1027. && ! snapsToMousePos))
  1028. {
  1029. const int mouseDiff = (style == RotaryHorizontalDrag
  1030. || style == LinearHorizontal
  1031. || style == LinearBar
  1032. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  1033. ? e.x - mouseDragStartPos.x
  1034. : mouseDragStartPos.y - e.y;
  1035. double newPos = valueToProportionOfLength (valueOnMouseDown)
  1036. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  1037. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  1038. if (style == IncDecButtons)
  1039. {
  1040. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  1041. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  1042. }
  1043. }
  1044. else
  1045. {
  1046. if (isVertical())
  1047. scaledMousePos = 1.0 - scaledMousePos;
  1048. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  1049. }
  1050. }
  1051. void Slider::handleVelocityDrag (const MouseEvent& e)
  1052. {
  1053. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  1054. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  1055. ? e.x - mousePosWhenLastDragged.x
  1056. : e.y - mousePosWhenLastDragged.y;
  1057. const double maxSpeed = jmax (200, sliderRegionSize);
  1058. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  1059. if (speed != 0)
  1060. {
  1061. speed = 0.2 * velocityModeSensitivity
  1062. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  1063. + jmax (0.0, (double) (speed - velocityModeThreshold))
  1064. / maxSpeed))));
  1065. if (mouseDiff < 0)
  1066. speed = -speed;
  1067. if (isVertical() || style == RotaryVerticalDrag
  1068. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  1069. speed = -speed;
  1070. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  1071. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  1072. e.source.enableUnboundedMouseMovement (true, false);
  1073. mouseWasHidden = true;
  1074. }
  1075. }
  1076. void Slider::mouseDrag (const MouseEvent& e)
  1077. {
  1078. if (isEnabled()
  1079. && (! menuShown)
  1080. && (maximum > minimum)
  1081. && ! (style == LinearBar && e.mouseWasClicked() && valueBox != nullptr && valueBox->isEditable()))
  1082. {
  1083. if (style == Rotary)
  1084. {
  1085. handleRotaryDrag (e);
  1086. }
  1087. else
  1088. {
  1089. if (style == IncDecButtons && ! incDecDragged)
  1090. {
  1091. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  1092. return;
  1093. incDecDragged = true;
  1094. mouseDragStartPos = e.getPosition();
  1095. }
  1096. if (isVelocityBased == (userKeyOverridesVelocity && e.mods.testFlags (ModifierKeys::ctrlModifier
  1097. | ModifierKeys::commandModifier
  1098. | ModifierKeys::altModifier))
  1099. || (maximum - minimum) / sliderRegionSize < interval)
  1100. handleAbsoluteDrag (e);
  1101. else
  1102. handleVelocityDrag (e);
  1103. }
  1104. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  1105. if (sliderBeingDragged == 0)
  1106. {
  1107. setValue (snapValue (valueWhenLastDragged, true),
  1108. ! sendChangeOnlyOnRelease, true);
  1109. }
  1110. else if (sliderBeingDragged == 1)
  1111. {
  1112. setMinValue (snapValue (valueWhenLastDragged, true),
  1113. ! sendChangeOnlyOnRelease, false, true);
  1114. if (e.mods.isShiftDown())
  1115. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  1116. else
  1117. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  1118. }
  1119. else if (sliderBeingDragged == 2)
  1120. {
  1121. setMaxValue (snapValue (valueWhenLastDragged, true),
  1122. ! sendChangeOnlyOnRelease, false, true);
  1123. if (e.mods.isShiftDown())
  1124. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  1125. else
  1126. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  1127. }
  1128. mousePosWhenLastDragged = e.getPosition();
  1129. }
  1130. }
  1131. void Slider::mouseDoubleClick (const MouseEvent&)
  1132. {
  1133. if (doubleClickToValue
  1134. && isEnabled()
  1135. && style != IncDecButtons
  1136. && minimum <= doubleClickReturnValue
  1137. && maximum >= doubleClickReturnValue)
  1138. {
  1139. sendDragStart();
  1140. setValue (doubleClickReturnValue, true, true);
  1141. sendDragEnd();
  1142. }
  1143. }
  1144. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  1145. {
  1146. if (scrollWheelEnabled && isEnabled()
  1147. && style != TwoValueHorizontal
  1148. && style != TwoValueVertical)
  1149. {
  1150. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  1151. {
  1152. if (valueBox != nullptr)
  1153. valueBox->hideEditor (false);
  1154. const double value = (double) currentValue.getValue();
  1155. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  1156. const double currentPos = valueToProportionOfLength (value);
  1157. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  1158. double delta = (newValue != value)
  1159. ? jmax (std::abs (newValue - value), interval) : 0;
  1160. if (value > newValue)
  1161. delta = -delta;
  1162. sendDragStart();
  1163. setValue (snapValue (value + delta, false), true, true);
  1164. sendDragEnd();
  1165. }
  1166. }
  1167. else
  1168. {
  1169. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  1170. }
  1171. }
  1172. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  1173. {
  1174. }
  1175. void SliderListener::sliderDragEnded (Slider*)
  1176. {
  1177. }
  1178. END_JUCE_NAMESPACE