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.

1420 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,
  249. Component* const parentComponentToUse)
  250. {
  251. popupDisplayEnabled = enabled;
  252. parentForPopupDisplay = parentComponentToUse;
  253. }
  254. //==============================================================================
  255. void Slider::colourChanged()
  256. {
  257. lookAndFeelChanged();
  258. }
  259. void Slider::lookAndFeelChanged()
  260. {
  261. LookAndFeel& lf = getLookAndFeel();
  262. if (textBoxPos != NoTextBox)
  263. {
  264. const String previousTextBoxContent (valueBox != nullptr ? valueBox->getText()
  265. : getTextFromValue (currentValue.getValue()));
  266. valueBox = nullptr;
  267. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  268. valueBox->setWantsKeyboardFocus (false);
  269. valueBox->setText (previousTextBoxContent, false);
  270. if (valueBox->isEditable() != editableText) // (avoid overriding the single/double click flags unless we have to)
  271. valueBox->setEditable (editableText && isEnabled());
  272. valueBox->addListener (this);
  273. if (style == LinearBar)
  274. valueBox->addMouseListener (this, false);
  275. valueBox->setTooltip (getTooltip());
  276. }
  277. else
  278. {
  279. valueBox = nullptr;
  280. }
  281. if (style == IncDecButtons)
  282. {
  283. addAndMakeVisible (incButton = lf.createSliderButton (true));
  284. incButton->addListener (this);
  285. addAndMakeVisible (decButton = lf.createSliderButton (false));
  286. decButton->addListener (this);
  287. if (incDecButtonMode != incDecButtonsNotDraggable)
  288. {
  289. incButton->addMouseListener (this, false);
  290. decButton->addMouseListener (this, false);
  291. }
  292. else
  293. {
  294. incButton->setRepeatSpeed (300, 100, 20);
  295. incButton->addMouseListener (decButton, false);
  296. decButton->setRepeatSpeed (300, 100, 20);
  297. decButton->addMouseListener (incButton, false);
  298. }
  299. incButton->setTooltip (getTooltip());
  300. decButton->setTooltip (getTooltip());
  301. }
  302. else
  303. {
  304. incButton = nullptr;
  305. decButton = nullptr;
  306. }
  307. setComponentEffect (lf.getSliderEffect());
  308. resized();
  309. repaint();
  310. }
  311. //==============================================================================
  312. void Slider::setRange (const double newMin,
  313. const double newMax,
  314. const double newInt)
  315. {
  316. if (minimum != newMin
  317. || maximum != newMax
  318. || interval != newInt)
  319. {
  320. minimum = newMin;
  321. maximum = newMax;
  322. interval = newInt;
  323. // figure out the number of DPs needed to display all values at this
  324. // interval setting.
  325. numDecimalPlaces = 7;
  326. if (newInt != 0)
  327. {
  328. int v = abs ((int) (newInt * 10000000));
  329. while ((v % 10) == 0)
  330. {
  331. --numDecimalPlaces;
  332. v /= 10;
  333. }
  334. }
  335. // keep the current values inside the new range..
  336. if (style != TwoValueHorizontal && style != TwoValueVertical)
  337. {
  338. setValue (getValue(), false, false);
  339. }
  340. else
  341. {
  342. setMinValue (getMinValue(), false, false);
  343. setMaxValue (getMaxValue(), false, false);
  344. }
  345. updateText();
  346. }
  347. }
  348. void Slider::triggerChangeMessage (const bool synchronous)
  349. {
  350. if (synchronous)
  351. handleAsyncUpdate();
  352. else
  353. triggerAsyncUpdate();
  354. valueChanged();
  355. }
  356. void Slider::valueChanged (Value& value)
  357. {
  358. if (value.refersToSameSourceAs (currentValue))
  359. {
  360. if (style != TwoValueHorizontal && style != TwoValueVertical)
  361. setValue (currentValue.getValue(), false, false);
  362. }
  363. else if (value.refersToSameSourceAs (valueMin))
  364. setMinValue (valueMin.getValue(), false, false, true);
  365. else if (value.refersToSameSourceAs (valueMax))
  366. setMaxValue (valueMax.getValue(), false, false, true);
  367. }
  368. double Slider::getValue() const
  369. {
  370. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  371. // methods to get the two values.
  372. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  373. return currentValue.getValue();
  374. }
  375. void Slider::setValue (double newValue,
  376. const bool sendUpdateMessage,
  377. const bool sendMessageSynchronously)
  378. {
  379. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  380. // methods to set the two values.
  381. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  382. newValue = constrainedValue (newValue);
  383. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  384. {
  385. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  386. newValue = jlimit ((double) valueMin.getValue(),
  387. (double) valueMax.getValue(),
  388. newValue);
  389. }
  390. if (newValue != lastCurrentValue)
  391. {
  392. if (valueBox != nullptr)
  393. valueBox->hideEditor (true);
  394. lastCurrentValue = newValue;
  395. // (need to do this comparison because the Value will use equalsWithSameType to compare
  396. // the new and old values, so will generate unwanted change events if the type changes)
  397. if (currentValue != newValue)
  398. currentValue = newValue;
  399. updateText();
  400. repaint();
  401. if (popupDisplay != nullptr)
  402. popupDisplay->updatePosition (getTextFromValue (newValue));
  403. if (sendUpdateMessage)
  404. triggerChangeMessage (sendMessageSynchronously);
  405. }
  406. }
  407. double Slider::getMinValue() const
  408. {
  409. // The minimum value only applies to sliders that are in two- or three-value mode.
  410. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  411. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  412. return valueMin.getValue();
  413. }
  414. double Slider::getMaxValue() const
  415. {
  416. // The maximum value only applies to sliders that are in two- or three-value mode.
  417. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  418. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  419. return valueMax.getValue();
  420. }
  421. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  422. {
  423. // The minimum value only applies to sliders that are in two- or three-value mode.
  424. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  425. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  426. newValue = constrainedValue (newValue);
  427. if (style == TwoValueHorizontal || style == TwoValueVertical)
  428. {
  429. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  430. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  431. newValue = jmin ((double) valueMax.getValue(), newValue);
  432. }
  433. else
  434. {
  435. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  436. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  437. newValue = jmin (lastCurrentValue, newValue);
  438. }
  439. if (lastValueMin != newValue)
  440. {
  441. lastValueMin = newValue;
  442. valueMin = newValue;
  443. repaint();
  444. if (popupDisplay != nullptr)
  445. popupDisplay->updatePosition (getTextFromValue (newValue));
  446. if (sendUpdateMessage)
  447. triggerChangeMessage (sendMessageSynchronously);
  448. }
  449. }
  450. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  451. {
  452. // The maximum value only applies to sliders that are in two- or three-value mode.
  453. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  454. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  455. newValue = constrainedValue (newValue);
  456. if (style == TwoValueHorizontal || style == TwoValueVertical)
  457. {
  458. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  459. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  460. newValue = jmax ((double) valueMin.getValue(), newValue);
  461. }
  462. else
  463. {
  464. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  465. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  466. newValue = jmax (lastCurrentValue, newValue);
  467. }
  468. if (lastValueMax != newValue)
  469. {
  470. lastValueMax = newValue;
  471. valueMax = newValue;
  472. repaint();
  473. if (popupDisplay != nullptr)
  474. popupDisplay->updatePosition (getTextFromValue (valueMax.getValue()));
  475. if (sendUpdateMessage)
  476. triggerChangeMessage (sendMessageSynchronously);
  477. }
  478. }
  479. void Slider::setMinAndMaxValues (double newMinValue, double newMaxValue, bool sendUpdateMessage, bool sendMessageSynchronously)
  480. {
  481. // The maximum value only applies to sliders that are in two- or three-value mode.
  482. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  483. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  484. if (newMaxValue < newMinValue)
  485. std::swap (newMaxValue, newMinValue);
  486. newMinValue = constrainedValue (newMinValue);
  487. newMaxValue = constrainedValue (newMaxValue);
  488. if (lastValueMax != newMaxValue || lastValueMin != newMinValue)
  489. {
  490. lastValueMax = newMaxValue;
  491. lastValueMin = newMinValue;
  492. valueMin = newMinValue;
  493. valueMax = newMaxValue;
  494. repaint();
  495. if (sendUpdateMessage)
  496. triggerChangeMessage (sendMessageSynchronously);
  497. }
  498. }
  499. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  500. const double valueToSetOnDoubleClick)
  501. {
  502. doubleClickToValue = isDoubleClickEnabled;
  503. doubleClickReturnValue = valueToSetOnDoubleClick;
  504. }
  505. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  506. {
  507. isEnabled_ = doubleClickToValue;
  508. return doubleClickReturnValue;
  509. }
  510. void Slider::updateText()
  511. {
  512. if (valueBox != nullptr)
  513. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  514. }
  515. void Slider::setTextValueSuffix (const String& suffix)
  516. {
  517. if (textSuffix != suffix)
  518. {
  519. textSuffix = suffix;
  520. updateText();
  521. }
  522. }
  523. String Slider::getTextValueSuffix() const
  524. {
  525. return textSuffix;
  526. }
  527. const String Slider::getTextFromValue (double v)
  528. {
  529. if (getNumDecimalPlacesToDisplay() > 0)
  530. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  531. else
  532. return String (roundToInt (v)) + getTextValueSuffix();
  533. }
  534. double Slider::getValueFromText (const String& text)
  535. {
  536. String t (text.trimStart());
  537. if (t.endsWith (textSuffix))
  538. t = t.substring (0, t.length() - textSuffix.length());
  539. while (t.startsWithChar ('+'))
  540. t = t.substring (1).trimStart();
  541. return t.initialSectionContainingOnly ("0123456789.,-")
  542. .getDoubleValue();
  543. }
  544. double Slider::proportionOfLengthToValue (double proportion)
  545. {
  546. if (skewFactor != 1.0 && proportion > 0.0)
  547. proportion = exp (log (proportion) / skewFactor);
  548. return minimum + (maximum - minimum) * proportion;
  549. }
  550. double Slider::valueToProportionOfLength (double value)
  551. {
  552. const double n = (value - minimum) / (maximum - minimum);
  553. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  554. }
  555. double Slider::snapValue (double attemptedValue, const bool)
  556. {
  557. return attemptedValue;
  558. }
  559. //==============================================================================
  560. void Slider::startedDragging()
  561. {
  562. }
  563. void Slider::stoppedDragging()
  564. {
  565. }
  566. void Slider::valueChanged()
  567. {
  568. }
  569. //==============================================================================
  570. void Slider::enablementChanged()
  571. {
  572. repaint();
  573. }
  574. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  575. {
  576. menuEnabled = menuEnabled_;
  577. }
  578. void Slider::setScrollWheelEnabled (const bool enabled)
  579. {
  580. scrollWheelEnabled = enabled;
  581. }
  582. //==============================================================================
  583. void Slider::labelTextChanged (Label* label)
  584. {
  585. const double newValue = snapValue (getValueFromText (label->getText()), false);
  586. if (newValue != (double) currentValue.getValue())
  587. {
  588. sendDragStart();
  589. setValue (newValue, true, true);
  590. sendDragEnd();
  591. }
  592. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  593. }
  594. void Slider::buttonClicked (Button* button)
  595. {
  596. if (style == IncDecButtons)
  597. {
  598. sendDragStart();
  599. if (button == incButton)
  600. setValue (snapValue (getValue() + interval, false), true, true);
  601. else if (button == decButton)
  602. setValue (snapValue (getValue() - interval, false), true, true);
  603. sendDragEnd();
  604. }
  605. }
  606. //==============================================================================
  607. double Slider::constrainedValue (double value) const
  608. {
  609. if (interval > 0)
  610. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  611. if (value <= minimum || maximum <= minimum)
  612. value = minimum;
  613. else if (value >= maximum)
  614. value = maximum;
  615. return value;
  616. }
  617. float Slider::getLinearSliderPos (const double value)
  618. {
  619. double sliderPosProportional;
  620. if (maximum > minimum)
  621. {
  622. if (value < minimum)
  623. {
  624. sliderPosProportional = 0.0;
  625. }
  626. else if (value > maximum)
  627. {
  628. sliderPosProportional = 1.0;
  629. }
  630. else
  631. {
  632. sliderPosProportional = valueToProportionOfLength (value);
  633. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  634. }
  635. }
  636. else
  637. {
  638. sliderPosProportional = 0.5;
  639. }
  640. if (isVertical() || style == IncDecButtons)
  641. sliderPosProportional = 1.0 - sliderPosProportional;
  642. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  643. }
  644. bool Slider::isHorizontal() const
  645. {
  646. return style == LinearHorizontal
  647. || style == LinearBar
  648. || style == TwoValueHorizontal
  649. || style == ThreeValueHorizontal;
  650. }
  651. bool Slider::isVertical() const
  652. {
  653. return style == LinearVertical
  654. || style == TwoValueVertical
  655. || style == ThreeValueVertical;
  656. }
  657. bool Slider::incDecDragDirectionIsHorizontal() const
  658. {
  659. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  660. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  661. }
  662. float Slider::getPositionOfValue (const double value)
  663. {
  664. if (isHorizontal() || isVertical())
  665. {
  666. return getLinearSliderPos (value);
  667. }
  668. else
  669. {
  670. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  671. return 0.0f;
  672. }
  673. }
  674. //==============================================================================
  675. void Slider::paint (Graphics& g)
  676. {
  677. if (style != IncDecButtons)
  678. {
  679. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  680. {
  681. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  682. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  683. getLookAndFeel().drawRotarySlider (g,
  684. sliderRect.getX(),
  685. sliderRect.getY(),
  686. sliderRect.getWidth(),
  687. sliderRect.getHeight(),
  688. sliderPos,
  689. rotaryStart, rotaryEnd,
  690. *this);
  691. }
  692. else
  693. {
  694. getLookAndFeel().drawLinearSlider (g,
  695. sliderRect.getX(),
  696. sliderRect.getY(),
  697. sliderRect.getWidth(),
  698. sliderRect.getHeight(),
  699. getLinearSliderPos (lastCurrentValue),
  700. getLinearSliderPos (lastValueMin),
  701. getLinearSliderPos (lastValueMax),
  702. style,
  703. *this);
  704. }
  705. if (style == LinearBar && valueBox == nullptr)
  706. {
  707. g.setColour (findColour (Slider::textBoxOutlineColourId));
  708. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  709. }
  710. }
  711. }
  712. void Slider::resized()
  713. {
  714. int minXSpace = 0;
  715. int minYSpace = 0;
  716. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  717. minXSpace = 30;
  718. else
  719. minYSpace = 15;
  720. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  721. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  722. if (style == LinearBar)
  723. {
  724. if (valueBox != nullptr)
  725. valueBox->setBounds (getLocalBounds());
  726. }
  727. else
  728. {
  729. if (textBoxPos == NoTextBox)
  730. {
  731. sliderRect = getLocalBounds();
  732. }
  733. else if (textBoxPos == TextBoxLeft)
  734. {
  735. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  736. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  737. }
  738. else if (textBoxPos == TextBoxRight)
  739. {
  740. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  741. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  742. }
  743. else if (textBoxPos == TextBoxAbove)
  744. {
  745. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  746. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  747. }
  748. else if (textBoxPos == TextBoxBelow)
  749. {
  750. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  751. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  752. }
  753. }
  754. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  755. if (style == LinearBar)
  756. {
  757. const int barIndent = 1;
  758. sliderRegionStart = barIndent;
  759. sliderRegionSize = getWidth() - barIndent * 2;
  760. sliderRect.setBounds (sliderRegionStart, barIndent,
  761. sliderRegionSize, getHeight() - barIndent * 2);
  762. }
  763. else if (isHorizontal())
  764. {
  765. sliderRegionStart = sliderRect.getX() + indent;
  766. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  767. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  768. sliderRegionSize, sliderRect.getHeight());
  769. }
  770. else if (isVertical())
  771. {
  772. sliderRegionStart = sliderRect.getY() + indent;
  773. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  774. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  775. sliderRect.getWidth(), sliderRegionSize);
  776. }
  777. else
  778. {
  779. sliderRegionStart = 0;
  780. sliderRegionSize = 100;
  781. }
  782. if (style == IncDecButtons)
  783. {
  784. Rectangle<int> buttonRect (sliderRect);
  785. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  786. buttonRect.expand (-2, 0);
  787. else
  788. buttonRect.expand (0, -2);
  789. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  790. if (incDecButtonsSideBySide)
  791. {
  792. decButton->setBounds (buttonRect.removeFromLeft (buttonRect.getWidth() / 2));
  793. decButton->setConnectedEdges (Button::ConnectedOnRight);
  794. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  795. }
  796. else
  797. {
  798. decButton->setBounds (buttonRect.removeFromBottom (buttonRect.getHeight() / 2));
  799. decButton->setConnectedEdges (Button::ConnectedOnTop);
  800. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  801. }
  802. incButton->setBounds (buttonRect);
  803. }
  804. }
  805. void Slider::focusOfChildComponentChanged (FocusChangeType)
  806. {
  807. repaint();
  808. }
  809. namespace SliderHelpers
  810. {
  811. double smallestAngleBetween (double a1, double a2) noexcept
  812. {
  813. return jmin (std::abs (a1 - a2),
  814. std::abs (a1 + double_Pi * 2.0 - a2),
  815. std::abs (a2 + double_Pi * 2.0 - a1));
  816. }
  817. void sliderMenuCallback (int result, Slider* slider)
  818. {
  819. if (slider != nullptr)
  820. {
  821. switch (result)
  822. {
  823. case 1: slider->setVelocityBasedMode (! slider->getVelocityBasedMode()); break;
  824. case 2: slider->setSliderStyle (Slider::Rotary); break;
  825. case 3: slider->setSliderStyle (Slider::RotaryHorizontalDrag); break;
  826. case 4: slider->setSliderStyle (Slider::RotaryVerticalDrag); break;
  827. default: break;
  828. }
  829. }
  830. }
  831. }
  832. void Slider::showPopupMenu()
  833. {
  834. menuShown = true;
  835. PopupMenu m;
  836. m.setLookAndFeel (&getLookAndFeel());
  837. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  838. m.addSeparator();
  839. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  840. {
  841. PopupMenu rotaryMenu;
  842. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  843. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  844. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  845. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  846. }
  847. m.showMenuAsync (PopupMenu::Options(),
  848. ModalCallbackFunction::forComponent (SliderHelpers::sliderMenuCallback, this));
  849. }
  850. int Slider::getThumbIndexAt (const MouseEvent& e)
  851. {
  852. const bool isTwoValue = (style == TwoValueHorizontal || style == TwoValueVertical);
  853. const bool isThreeValue = (style == ThreeValueHorizontal || style == ThreeValueVertical);
  854. if (isTwoValue || isThreeValue)
  855. {
  856. const float mousePos = (float) (isVertical() ? e.y : e.x);
  857. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  858. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  859. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  860. if (isTwoValue)
  861. return maxPosDistance <= minPosDistance ? 2 : 1;
  862. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  863. return 1;
  864. else if (normalPosDistance >= maxPosDistance)
  865. return 2;
  866. }
  867. return 0;
  868. }
  869. void Slider::mouseDown (const MouseEvent& e)
  870. {
  871. mouseWasHidden = false;
  872. incDecDragged = false;
  873. mouseDragStartPos = mousePosWhenLastDragged = e.getPosition();
  874. if (isEnabled())
  875. {
  876. if (e.mods.isPopupMenu() && menuEnabled)
  877. {
  878. showPopupMenu();
  879. }
  880. else if (maximum > minimum)
  881. {
  882. menuShown = false;
  883. if (valueBox != nullptr)
  884. valueBox->hideEditor (true);
  885. sliderBeingDragged = getThumbIndexAt (e);
  886. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  887. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  888. * valueToProportionOfLength (currentValue.getValue());
  889. valueWhenLastDragged = (sliderBeingDragged == 2 ? valueMax
  890. : (sliderBeingDragged == 1 ? valueMin
  891. : currentValue)).getValue();
  892. valueOnMouseDown = valueWhenLastDragged;
  893. if (popupDisplayEnabled)
  894. {
  895. PopupDisplayComponent* const popup = new PopupDisplayComponent (*this);
  896. popupDisplay = popup;
  897. if (parentForPopupDisplay != nullptr)
  898. parentForPopupDisplay->addChildComponent (popup);
  899. else
  900. popup->addToDesktop (0);
  901. popup->setVisible (true);
  902. }
  903. sendDragStart();
  904. mouseDrag (e);
  905. }
  906. }
  907. }
  908. void Slider::mouseUp (const MouseEvent&)
  909. {
  910. if (isEnabled()
  911. && (! menuShown)
  912. && (maximum > minimum)
  913. && (style != IncDecButtons || incDecDragged))
  914. {
  915. restoreMouseIfHidden();
  916. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  917. triggerChangeMessage (false);
  918. sendDragEnd();
  919. popupDisplay = nullptr;
  920. if (style == IncDecButtons)
  921. {
  922. incButton->setState (Button::buttonNormal);
  923. decButton->setState (Button::buttonNormal);
  924. }
  925. }
  926. else if (popupDisplay != nullptr)
  927. {
  928. popupDisplay->startTimer (2000);
  929. }
  930. }
  931. void Slider::restoreMouseIfHidden()
  932. {
  933. if (mouseWasHidden)
  934. {
  935. mouseWasHidden = false;
  936. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  937. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  938. const double pos = sliderBeingDragged == 2 ? getMaxValue()
  939. : (sliderBeingDragged == 1 ? getMinValue()
  940. : (double) currentValue.getValue());
  941. Point<int> mousePos;
  942. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  943. {
  944. mousePos = Desktop::getLastMouseDownPosition();
  945. if (style == RotaryHorizontalDrag)
  946. {
  947. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  948. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  949. }
  950. else
  951. {
  952. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  953. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  954. }
  955. }
  956. else
  957. {
  958. const int pixelPos = (int) getLinearSliderPos (pos);
  959. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  960. isVertical() ? pixelPos : (getHeight() / 2)));
  961. }
  962. Desktop::setMousePosition (mousePos);
  963. }
  964. }
  965. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  966. {
  967. if (isEnabled()
  968. && style != IncDecButtons
  969. && style != Rotary
  970. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  971. {
  972. restoreMouseIfHidden();
  973. }
  974. }
  975. void Slider::handleRotaryDrag (const MouseEvent& e)
  976. {
  977. const int dx = e.x - sliderRect.getCentreX();
  978. const int dy = e.y - sliderRect.getCentreY();
  979. if (dx * dx + dy * dy > 25)
  980. {
  981. double angle = std::atan2 ((double) dx, (double) -dy);
  982. while (angle < 0.0)
  983. angle += double_Pi * 2.0;
  984. if (rotaryStop && ! e.mouseWasClicked())
  985. {
  986. if (std::abs (angle - lastAngle) > double_Pi)
  987. {
  988. if (angle >= lastAngle)
  989. angle -= double_Pi * 2.0;
  990. else
  991. angle += double_Pi * 2.0;
  992. }
  993. if (angle >= lastAngle)
  994. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  995. else
  996. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  997. }
  998. else
  999. {
  1000. while (angle < rotaryStart)
  1001. angle += double_Pi * 2.0;
  1002. if (angle > rotaryEnd)
  1003. {
  1004. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  1005. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  1006. angle = rotaryStart;
  1007. else
  1008. angle = rotaryEnd;
  1009. }
  1010. }
  1011. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  1012. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  1013. lastAngle = angle;
  1014. }
  1015. }
  1016. void Slider::handleAbsoluteDrag (const MouseEvent& e)
  1017. {
  1018. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  1019. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  1020. if (style == RotaryHorizontalDrag
  1021. || style == RotaryVerticalDrag
  1022. || style == IncDecButtons
  1023. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  1024. && ! snapsToMousePos))
  1025. {
  1026. const int mouseDiff = (style == RotaryHorizontalDrag
  1027. || style == LinearHorizontal
  1028. || style == LinearBar
  1029. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  1030. ? e.x - mouseDragStartPos.getX()
  1031. : mouseDragStartPos.getY() - e.y;
  1032. double newPos = valueToProportionOfLength (valueOnMouseDown)
  1033. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  1034. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  1035. if (style == IncDecButtons)
  1036. {
  1037. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  1038. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  1039. }
  1040. }
  1041. else
  1042. {
  1043. if (isVertical())
  1044. scaledMousePos = 1.0 - scaledMousePos;
  1045. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  1046. }
  1047. }
  1048. void Slider::handleVelocityDrag (const MouseEvent& e)
  1049. {
  1050. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  1051. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  1052. ? e.x - mousePosWhenLastDragged.getX()
  1053. : e.y - mousePosWhenLastDragged.getY();
  1054. const double maxSpeed = jmax (200, sliderRegionSize);
  1055. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  1056. if (speed != 0)
  1057. {
  1058. speed = 0.2 * velocityModeSensitivity
  1059. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  1060. + jmax (0.0, (double) (speed - velocityModeThreshold))
  1061. / maxSpeed))));
  1062. if (mouseDiff < 0)
  1063. speed = -speed;
  1064. if (isVertical() || style == RotaryVerticalDrag
  1065. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  1066. speed = -speed;
  1067. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  1068. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  1069. e.source.enableUnboundedMouseMovement (true, false);
  1070. mouseWasHidden = true;
  1071. }
  1072. }
  1073. void Slider::mouseDrag (const MouseEvent& e)
  1074. {
  1075. if (isEnabled()
  1076. && (! menuShown)
  1077. && (maximum > minimum)
  1078. && ! (style == LinearBar && e.mouseWasClicked() && valueBox != nullptr && valueBox->isEditable()))
  1079. {
  1080. if (style == Rotary)
  1081. {
  1082. handleRotaryDrag (e);
  1083. }
  1084. else
  1085. {
  1086. if (style == IncDecButtons && ! incDecDragged)
  1087. {
  1088. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  1089. return;
  1090. incDecDragged = true;
  1091. mouseDragStartPos = e.getPosition();
  1092. }
  1093. if (isVelocityBased == (userKeyOverridesVelocity && e.mods.testFlags (ModifierKeys::ctrlModifier
  1094. | ModifierKeys::commandModifier
  1095. | ModifierKeys::altModifier))
  1096. || (maximum - minimum) / sliderRegionSize < interval)
  1097. handleAbsoluteDrag (e);
  1098. else
  1099. handleVelocityDrag (e);
  1100. }
  1101. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  1102. if (sliderBeingDragged == 0)
  1103. {
  1104. setValue (snapValue (valueWhenLastDragged, true),
  1105. ! sendChangeOnlyOnRelease, true);
  1106. }
  1107. else if (sliderBeingDragged == 1)
  1108. {
  1109. setMinValue (snapValue (valueWhenLastDragged, true),
  1110. ! sendChangeOnlyOnRelease, false, true);
  1111. if (e.mods.isShiftDown())
  1112. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  1113. else
  1114. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  1115. }
  1116. else if (sliderBeingDragged == 2)
  1117. {
  1118. setMaxValue (snapValue (valueWhenLastDragged, true),
  1119. ! sendChangeOnlyOnRelease, false, true);
  1120. if (e.mods.isShiftDown())
  1121. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  1122. else
  1123. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  1124. }
  1125. mousePosWhenLastDragged = e.getPosition();
  1126. }
  1127. }
  1128. void Slider::mouseDoubleClick (const MouseEvent&)
  1129. {
  1130. if (doubleClickToValue
  1131. && isEnabled()
  1132. && style != IncDecButtons
  1133. && minimum <= doubleClickReturnValue
  1134. && maximum >= doubleClickReturnValue)
  1135. {
  1136. sendDragStart();
  1137. setValue (doubleClickReturnValue, true, true);
  1138. sendDragEnd();
  1139. }
  1140. }
  1141. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  1142. {
  1143. if (scrollWheelEnabled && isEnabled()
  1144. && style != TwoValueHorizontal
  1145. && style != TwoValueVertical)
  1146. {
  1147. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  1148. {
  1149. if (valueBox != nullptr)
  1150. valueBox->hideEditor (false);
  1151. const double value = (double) currentValue.getValue();
  1152. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  1153. const double currentPos = valueToProportionOfLength (value);
  1154. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  1155. double delta = (newValue != value)
  1156. ? jmax (std::abs (newValue - value), interval) : 0;
  1157. if (value > newValue)
  1158. delta = -delta;
  1159. sendDragStart();
  1160. setValue (snapValue (value + delta, false), true, true);
  1161. sendDragEnd();
  1162. }
  1163. }
  1164. else
  1165. {
  1166. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  1167. }
  1168. }
  1169. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  1170. {
  1171. }
  1172. void SliderListener::sliderDragEnded (Slider*)
  1173. {
  1174. }
  1175. END_JUCE_NAMESPACE