Slider.cs 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814
  1. namespace Terminal.Gui;
  2. /// <summary>Slider control.</summary>
  3. public class Slider : Slider<object>
  4. {
  5. /// <summary>Initializes a new instance of the <see cref="Slider"/> class.</summary>
  6. public Slider () { }
  7. /// <summary>Initializes a new instance of the <see cref="Slider"/> class.</summary>
  8. /// <param name="options">Initial slider options.</param>
  9. /// <param name="orientation">Initial slider options.</param>
  10. public Slider (List<object> options, Orientation orientation = Orientation.Horizontal) :
  11. base (options, orientation)
  12. { }
  13. }
  14. /// <summary>
  15. /// Provides a slider control letting the user navigate from a set of typed options in a linear manner using the
  16. /// keyboard or mouse.
  17. /// </summary>
  18. /// <typeparam name="T"></typeparam>
  19. public class Slider<T> : View
  20. {
  21. private readonly SliderConfiguration _config = new ();
  22. // List of the current set options.
  23. private readonly List<int> _setOptions = new ();
  24. // Options
  25. private List<SliderOption<T>> _options;
  26. #region Initialize
  27. private void SetInitialProperties (
  28. List<SliderOption<T>> options,
  29. Orientation orientation = Orientation.Horizontal
  30. )
  31. {
  32. Width = Dim.Auto (DimAutoStyle.Content);
  33. Height = Dim.Auto (DimAutoStyle.Content);
  34. CanFocus = true;
  35. CursorVisibility = CursorVisibility.Default;
  36. _options = options ?? new List<SliderOption<T>> ();
  37. _config._sliderOrientation = orientation;
  38. SetDefaultStyle ();
  39. SetCommands ();
  40. SetContentSize ();
  41. // BUGBUG: This should not be needed - Need to ensure SetRelativeLayout gets called during EndInit
  42. Initialized += (s, e) => { SetContentSize (); };
  43. LayoutStarted += (s, e) => { SetContentSize (); };
  44. }
  45. // TODO: Make configurable via ConfigurationManager
  46. private void SetDefaultStyle ()
  47. {
  48. _config._showLegends = true;
  49. switch (_config._sliderOrientation)
  50. {
  51. case Orientation.Horizontal:
  52. Style.SpaceChar = new () { Rune = Glyphs.HLine }; // '─'
  53. Style.OptionChar = new () { Rune = Glyphs.BlackCircle }; // '┼●🗹□⏹'
  54. break;
  55. case Orientation.Vertical:
  56. Style.SpaceChar = new () { Rune = Glyphs.VLine };
  57. Style.OptionChar = new () { Rune = Glyphs.BlackCircle };
  58. break;
  59. }
  60. // TODO(jmperricone) Wide Vertical ???
  61. /*
  62. ┼─ 40
  63. ███ 30
  64. ▒▒▒
  65. ▒▒▒
  66. ▒▒▒ 20
  67. ▒▒▒
  68. ▒▒▒
  69. ███ 10
  70. ─●─ 0
  71. */
  72. _config._legendsOrientation = _config._sliderOrientation;
  73. Style.EmptyChar = new () { Rune = new (' ') };
  74. Style.SetChar = new () { Rune = Glyphs.ContinuousMeterSegment }; // ■
  75. Style.RangeChar = new () { Rune = Glyphs.Stipple }; // ░ ▒ ▓ // Medium shade not blinking on curses.
  76. Style.StartRangeChar = new () { Rune = Glyphs.ContinuousMeterSegment };
  77. Style.EndRangeChar = new () { Rune = Glyphs.ContinuousMeterSegment };
  78. Style.DragChar = new () { Rune = Glyphs.Diamond };
  79. // TODO: Support left & right (top/bottom)
  80. // First = '├',
  81. // Last = '┤',
  82. }
  83. #endregion
  84. #region Constructors
  85. /// <summary>Initializes a new instance of the <see cref="Slider"/> class.</summary>
  86. public Slider () : this (new ()) { }
  87. /// <summary>Initializes a new instance of the <see cref="Slider"/> class.</summary>
  88. /// <param name="options">Initial slider options.</param>
  89. /// <param name="orientation">Initial slider orientation.</param>
  90. public Slider (List<T> options, Orientation orientation = Orientation.Horizontal)
  91. {
  92. if (options is null)
  93. {
  94. SetInitialProperties (null, orientation);
  95. }
  96. else
  97. {
  98. SetInitialProperties (
  99. options.Select (
  100. e =>
  101. {
  102. var legend = e.ToString ();
  103. return new SliderOption<T>
  104. {
  105. Data = e,
  106. Legend = legend,
  107. LegendAbbr =
  108. (Rune)(legend?.Length > 0 ? legend [0] : ' ')
  109. };
  110. }
  111. )
  112. .ToList (),
  113. orientation
  114. );
  115. }
  116. }
  117. #endregion
  118. #region Properties
  119. /// <summary>
  120. /// Setting the Text of a slider is a shortcut to setting options. The text is a CSV string of the options.
  121. /// </summary>
  122. public override string Text
  123. {
  124. get
  125. {
  126. if (_options.Count == 0)
  127. {
  128. return string.Empty;
  129. }
  130. // Return labels as a CSV string
  131. return string.Join (",", _options);
  132. }
  133. set
  134. {
  135. if (string.IsNullOrEmpty (value))
  136. {
  137. Options = [];
  138. }
  139. else
  140. {
  141. IEnumerable<string> list = value.Split (',').Select (x => x.Trim ());
  142. Options = list.Select (x => new SliderOption<T> { Legend = x }).ToList ();
  143. }
  144. }
  145. }
  146. /// <summary>Allow no selection.</summary>
  147. public bool AllowEmpty
  148. {
  149. get => _config._allowEmpty;
  150. set
  151. {
  152. _config._allowEmpty = value;
  153. if (!value && _options.Count > 0 && _setOptions.Count == 0)
  154. {
  155. SetOption (0);
  156. }
  157. }
  158. }
  159. /// <summary>Gets or sets the minimum number of rows/columns between <see cref="Options"/>. The default is 1.</summary>
  160. public int MinimumInnerSpacing
  161. {
  162. get => _config._minInnerSpacing;
  163. set
  164. {
  165. _config._minInnerSpacing = value;
  166. SetContentSize ();
  167. }
  168. }
  169. /// <summary>Slider Type. <see cref="SliderType"></see></summary>
  170. public SliderType Type
  171. {
  172. get => _config._type;
  173. set
  174. {
  175. _config._type = value;
  176. // Todo: Custom logic to preserve options.
  177. _setOptions.Clear ();
  178. SetNeedsDisplay ();
  179. }
  180. }
  181. /// <summary>Slider Orientation. <see cref="Gui.Orientation"></see></summary>
  182. public Orientation Orientation
  183. {
  184. get => _config._sliderOrientation;
  185. set => OnOrientationChanged (value);
  186. }
  187. /// <summary>Legends Orientation. <see cref="Gui.Orientation"></see></summary>
  188. public Orientation LegendsOrientation
  189. {
  190. get => _config._legendsOrientation;
  191. set
  192. {
  193. _config._legendsOrientation = value;
  194. SetContentSize ();
  195. }
  196. }
  197. /// <summary>Slider styles. <see cref="SliderStyle"></see></summary>
  198. public SliderStyle Style { get; set; } = new ();
  199. /// <summary>Set the slider options.</summary>
  200. public List<SliderOption<T>> Options
  201. {
  202. get =>
  203. _options;
  204. set
  205. {
  206. // _options should never be null
  207. _options = value ?? throw new ArgumentNullException (nameof (value));
  208. if (_options.Count == 0)
  209. {
  210. return;
  211. }
  212. SetContentSize ();
  213. }
  214. }
  215. /// <summary>Allow range start and end be in the same option, as a single option.</summary>
  216. public bool RangeAllowSingle
  217. {
  218. get => _config._rangeAllowSingle;
  219. set => _config._rangeAllowSingle = value;
  220. }
  221. /// <summary>Show/Hide spacing before and after the first and last option.</summary>
  222. public bool ShowEndSpacing
  223. {
  224. get => _config._showEndSpacing;
  225. set
  226. {
  227. _config._showEndSpacing = value;
  228. SetContentSize ();
  229. }
  230. }
  231. /// <summary>Show/Hide the options legends.</summary>
  232. public bool ShowLegends
  233. {
  234. get => _config._showLegends;
  235. set
  236. {
  237. _config._showLegends = value;
  238. SetContentSize ();
  239. }
  240. }
  241. /// <summary>
  242. /// Gets or sets whether the minimum or ideal size will be used when calculating the size of the slider.
  243. /// </summary>
  244. public bool UseMinimumSize
  245. {
  246. get => _config._useMinimumSize;
  247. set
  248. {
  249. _config._useMinimumSize = value;
  250. SetContentSize ();
  251. }
  252. }
  253. #endregion
  254. #region Events
  255. /// <summary>
  256. /// Fired when the slider orientation has changed. Can be cancelled by setting
  257. /// <see cref="OrientationEventArgs.Cancel"/> to true.
  258. /// </summary>
  259. public event EventHandler<OrientationEventArgs> OrientationChanged;
  260. /// <summary>Called when the slider orientation has changed. Invokes the <see cref="OrientationChanged"/> event.</summary>
  261. /// <param name="newOrientation"></param>
  262. /// <returns>True of the event was cancelled.</returns>
  263. public virtual bool OnOrientationChanged (Orientation newOrientation)
  264. {
  265. var args = new OrientationEventArgs (newOrientation);
  266. OrientationChanged?.Invoke (this, args);
  267. if (!args.Cancel)
  268. {
  269. _config._sliderOrientation = newOrientation;
  270. switch (_config._sliderOrientation)
  271. {
  272. case Orientation.Horizontal:
  273. Style.SpaceChar = new () { Rune = Glyphs.HLine }; // '─'
  274. break;
  275. case Orientation.Vertical:
  276. Style.SpaceChar = new () { Rune = Glyphs.VLine };
  277. break;
  278. }
  279. SetKeyBindings ();
  280. SetContentSize ();
  281. }
  282. return args.Cancel;
  283. }
  284. /// <summary>Event raised when the slider option/s changed. The dictionary contains: key = option index, value = T</summary>
  285. public event EventHandler<SliderEventArgs<T>> OptionsChanged;
  286. /// <summary>Overridable method called when the slider options have changed. Raises the <see cref="OptionsChanged"/> event.</summary>
  287. public virtual void OnOptionsChanged ()
  288. {
  289. OptionsChanged?.Invoke (this, new (GetSetOptionDictionary ()));
  290. SetNeedsDisplay ();
  291. }
  292. /// <summary>Event raised When the option is hovered with the keys or the mouse.</summary>
  293. public event EventHandler<SliderEventArgs<T>> OptionFocused;
  294. private int
  295. _lastFocusedOption; // for Range type; the most recently focused option. Used to determine shrink direction
  296. /// <summary>Overridable function that fires the <see cref="OptionFocused"/> event.</summary>
  297. /// <param name="args"></param>
  298. /// <returns><see langword="true"/> if the focus change was cancelled.</returns>
  299. /// <param name="newFocusedOption"></param>
  300. public virtual bool OnOptionFocused (int newFocusedOption, SliderEventArgs<T> args)
  301. {
  302. if (newFocusedOption > _options.Count - 1 || newFocusedOption < 0)
  303. {
  304. return true;
  305. }
  306. OptionFocused?.Invoke (this, args);
  307. if (!args.Cancel)
  308. {
  309. _lastFocusedOption = FocusedOption;
  310. FocusedOption = newFocusedOption;
  311. //PositionCursor ();
  312. }
  313. return args.Cancel;
  314. }
  315. #endregion Events
  316. #region Public Methods
  317. /// <summary>The focused option (has the cursor).</summary>
  318. public int FocusedOption { get; set; }
  319. /// <summary>Causes the specified option to be set and be focused.</summary>
  320. public bool SetOption (int optionIndex)
  321. {
  322. // TODO: Handle range type.
  323. // Note: Maybe return false only when optionIndex doesn't exist, otherwise true.
  324. if (!_setOptions.Contains (optionIndex) && optionIndex >= 0 && optionIndex < _options.Count)
  325. {
  326. FocusedOption = optionIndex;
  327. SetFocusedOption ();
  328. return true;
  329. }
  330. return false;
  331. }
  332. /// <summary>Causes the specified option to be un-set and be focused.</summary>
  333. public bool UnSetOption (int optionIndex)
  334. {
  335. if (!AllowEmpty && _setOptions.Count > 2 && _setOptions.Contains (optionIndex))
  336. {
  337. FocusedOption = optionIndex;
  338. SetFocusedOption ();
  339. return true;
  340. }
  341. return false;
  342. }
  343. /// <summary>Get the indexes of the set options.</summary>
  344. public List<int> GetSetOptions ()
  345. {
  346. // Copy
  347. return _setOptions.OrderBy (e => e).ToList ();
  348. }
  349. #endregion Public Methods
  350. #region Helpers
  351. private void MoveAndAdd (int x, int y, Rune rune)
  352. {
  353. Move (x, y);
  354. Driver?.AddRune (rune);
  355. }
  356. private void MoveAndAdd (int x, int y, string str)
  357. {
  358. Move (x, y);
  359. Driver?.AddStr (str);
  360. }
  361. /// <summary>Sets the dimensions of the Slider to the ideal values.</summary>
  362. private void SetContentSize ()
  363. {
  364. if (_options.Count == 0)
  365. {
  366. return;
  367. }
  368. bool horizontal = _config._sliderOrientation == Orientation.Horizontal;
  369. if (UseMinimumSize)
  370. {
  371. CalcSpacingConfig (CalcMinLength ());
  372. }
  373. else
  374. {
  375. CalcSpacingConfig (horizontal ? Viewport.Width : Viewport.Height);
  376. }
  377. SetContentSize (new (GetIdealWidth (), GetIdealHeight ()));
  378. return;
  379. void CalcSpacingConfig (int size)
  380. {
  381. _config._cachedInnerSpacing = 0;
  382. _config._startSpacing = 0;
  383. _config._endSpacing = 0;
  384. int maxLegend; // Because the legends are centered, the longest one determines inner spacing
  385. if (_config._sliderOrientation == _config._legendsOrientation)
  386. {
  387. maxLegend = int.Max (_options.Max (s => s.Legend?.GetColumns () ?? 1), 1);
  388. }
  389. else
  390. {
  391. maxLegend = 1;
  392. }
  393. int minSizeThatFitsLegends = _options.Count == 1 ? maxLegend : _options.Sum (o => o.Legend.GetColumns ());
  394. string first;
  395. string last;
  396. if (minSizeThatFitsLegends > size)
  397. {
  398. _config._showLegendsAbbr = false;
  399. if (_config._sliderOrientation == _config._legendsOrientation)
  400. {
  401. _config._showLegendsAbbr = true;
  402. foreach (SliderOption<T> o in _options.Where (op => op.LegendAbbr == default (Rune)))
  403. {
  404. o.LegendAbbr = (Rune)(o.Legend?.GetColumns () > 0 ? o.Legend [0] : ' ');
  405. }
  406. }
  407. first = "x";
  408. last = "x";
  409. }
  410. else
  411. {
  412. _config._showLegendsAbbr = false;
  413. first = _options.First ().Legend;
  414. last = _options.Last ().Legend;
  415. }
  416. // --o--
  417. // Hello
  418. // Left = He
  419. // Right = lo
  420. int firstLeft = (first.Length - 1) / 2; // Chars count of the first option to the left.
  421. int lastRight = last.Length / 2; // Chars count of the last option to the right.
  422. if (_config._sliderOrientation != _config._legendsOrientation)
  423. {
  424. firstLeft = 0;
  425. lastRight = 0;
  426. }
  427. // -1 because it's better to have an extra space at right than to clip
  428. int width = size - firstLeft - lastRight - 1;
  429. _config._startSpacing = firstLeft;
  430. if (_options.Count == 1)
  431. {
  432. _config._cachedInnerSpacing = maxLegend;
  433. }
  434. else
  435. {
  436. _config._cachedInnerSpacing = Math.Max (0, (int)Math.Floor ((double)width / (_options.Count - 1)) - 1);
  437. }
  438. _config._cachedInnerSpacing = Math.Max (_config._minInnerSpacing, _config._cachedInnerSpacing);
  439. _config._endSpacing = lastRight;
  440. }
  441. }
  442. /// <summary>Calculates the min dimension required for all options and inner spacing with abbreviated legends</summary>
  443. /// <returns></returns>
  444. private int CalcMinLength ()
  445. {
  446. if (_options.Count == 0)
  447. {
  448. return 0;
  449. }
  450. var length = 0;
  451. length += _config._startSpacing + _config._endSpacing;
  452. length += _options.Count;
  453. length += (_options.Count - 1) * _config._minInnerSpacing;
  454. return length;
  455. }
  456. /// <summary>
  457. /// Gets the ideal width of the slider. The ideal width is the minimum width required to display all options and inner
  458. /// spacing.
  459. /// </summary>
  460. /// <returns></returns>
  461. public int GetIdealWidth ()
  462. {
  463. if (UseMinimumSize)
  464. {
  465. return Orientation == Orientation.Horizontal ? CalcMinLength () : CalcIdealThickness ();
  466. }
  467. return Orientation == Orientation.Horizontal ? CalcIdealLength () : CalcIdealThickness ();
  468. }
  469. /// <summary>
  470. /// Gets the ideal height of the slider. The ideal height is the minimum height required to display all options and
  471. /// inner spacing.
  472. /// </summary>
  473. /// <returns></returns>
  474. public int GetIdealHeight ()
  475. {
  476. if (UseMinimumSize)
  477. {
  478. return Orientation == Orientation.Horizontal ? CalcIdealThickness () : CalcMinLength ();
  479. }
  480. return Orientation == Orientation.Horizontal ? CalcIdealThickness () : CalcIdealLength ();
  481. }
  482. /// <summary>
  483. /// Calculates the ideal dimension required for all options, inner spacing, and legends (non-abbreviated, with one
  484. /// space between).
  485. /// </summary>
  486. /// <returns></returns>
  487. private int CalcIdealLength ()
  488. {
  489. if (_options.Count == 0)
  490. {
  491. return 0;
  492. }
  493. bool isVertical = Orientation == Orientation.Vertical;
  494. var length = 0;
  495. if (_config._showLegends)
  496. {
  497. if (_config._legendsOrientation == _config._sliderOrientation && _options.Count > 0)
  498. {
  499. // Each legend should be centered in a space the width of the longest legend, with one space between.
  500. // Calculate the total length required for all legends.
  501. //if (!isVertical)
  502. {
  503. int maxLegend = int.Max (_options.Max (s => s.Legend?.GetColumns () ?? 1), 1);
  504. length = maxLegend * _options.Count + (_options.Count - 1);
  505. }
  506. //
  507. //{
  508. // length = CalcMinLength ();
  509. //}
  510. }
  511. else
  512. {
  513. length = CalcMinLength ();
  514. }
  515. }
  516. return Math.Max (length, CalcMinLength ());
  517. }
  518. /// <summary>
  519. /// Calculates the minimum dimension required for the slider and legends.
  520. /// </summary>
  521. /// <returns></returns>
  522. private int CalcIdealThickness ()
  523. {
  524. var thickness = 1; // Always show the slider.
  525. if (_config._showLegends)
  526. {
  527. if (_config._legendsOrientation != _config._sliderOrientation && _options.Count > 0)
  528. {
  529. thickness += _options.Max (s => s.Legend?.GetColumns () ?? 0);
  530. }
  531. else
  532. {
  533. thickness += 1;
  534. }
  535. }
  536. return thickness;
  537. }
  538. #endregion Helpers
  539. #region Cursor and Position
  540. internal bool TryGetPositionByOption (int option, out (int x, int y) position)
  541. {
  542. position = (-1, -1);
  543. if (option < 0 || option >= _options.Count ())
  544. {
  545. return false;
  546. }
  547. var offset = 0;
  548. offset += _config._startSpacing;
  549. offset += option * (_config._cachedInnerSpacing + 1);
  550. if (_config._sliderOrientation == Orientation.Vertical)
  551. {
  552. position = (0, offset);
  553. }
  554. else
  555. {
  556. position = (offset, 0);
  557. }
  558. return true;
  559. }
  560. /// <summary>Tries to get the option index by the position.</summary>
  561. /// <param name="x"></param>
  562. /// <param name="y"></param>
  563. /// <param name="threshold"></param>
  564. /// <param name="optionIdx"></param>
  565. /// <returns></returns>
  566. internal bool TryGetOptionByPosition (int x, int y, int threshold, out int optionIdx)
  567. {
  568. // Fix(jmperricone): Not working.
  569. optionIdx = -1;
  570. if (Orientation == Orientation.Horizontal)
  571. {
  572. if (y != 0)
  573. {
  574. return false;
  575. }
  576. for (int xx = x - threshold; xx < x + threshold + 1; xx++)
  577. {
  578. int cx = xx;
  579. cx -= _config._startSpacing;
  580. int option = cx / (_config._cachedInnerSpacing + 1);
  581. bool valid = cx % (_config._cachedInnerSpacing + 1) == 0;
  582. if (!valid || option < 0 || option > _options.Count - 1)
  583. {
  584. continue;
  585. }
  586. optionIdx = option;
  587. return true;
  588. }
  589. }
  590. else
  591. {
  592. if (x != 0)
  593. {
  594. return false;
  595. }
  596. for (int yy = y - threshold; yy < y + threshold + 1; yy++)
  597. {
  598. int cy = yy;
  599. cy -= _config._startSpacing;
  600. int option = cy / (_config._cachedInnerSpacing + 1);
  601. bool valid = cy % (_config._cachedInnerSpacing + 1) == 0;
  602. if (!valid || option < 0 || option > _options.Count - 1)
  603. {
  604. continue;
  605. }
  606. optionIdx = option;
  607. return true;
  608. }
  609. }
  610. return false;
  611. }
  612. /// <inheritdoc/>
  613. public override Point? PositionCursor ()
  614. {
  615. if (TryGetPositionByOption (FocusedOption, out (int x, int y) position))
  616. {
  617. if (IsInitialized && Viewport.Contains (position.x, position.y))
  618. {
  619. Move (position.x, position.y);
  620. return new (position.x, position.y);
  621. }
  622. }
  623. return base.PositionCursor ();
  624. }
  625. #endregion Cursor and Position
  626. #region Drawing
  627. /// <inheritdoc/>
  628. public override void OnDrawContent (Rectangle viewport)
  629. {
  630. // TODO: make this more surgical to reduce repaint
  631. if (_options is null || _options.Count == 0)
  632. {
  633. return;
  634. }
  635. // Draw Slider
  636. DrawSlider ();
  637. // Draw Legends.
  638. if (_config._showLegends)
  639. {
  640. DrawLegends ();
  641. }
  642. if (_dragPosition.HasValue && _moveRenderPosition.HasValue)
  643. {
  644. AddRune (_moveRenderPosition.Value.X, _moveRenderPosition.Value.Y, Style.DragChar.Rune);
  645. }
  646. }
  647. private string AlignText (string text, int width, Alignment alignment)
  648. {
  649. if (text is null)
  650. {
  651. return "";
  652. }
  653. if (text.Length > width)
  654. {
  655. text = text [..width];
  656. }
  657. int w = width - text.Length;
  658. string s1 = new (' ', w / 2);
  659. string s2 = new (' ', w % 2);
  660. // Note: The formatter doesn't handle all of this ???
  661. switch (alignment)
  662. {
  663. case Alignment.Fill:
  664. return TextFormatter.Justify (text, width);
  665. case Alignment.Start:
  666. return text + s1 + s1 + s2;
  667. case Alignment.Center:
  668. if (text.Length % 2 != 0)
  669. {
  670. return s1 + text + s1 + s2;
  671. }
  672. return s1 + s2 + text + s1;
  673. case Alignment.End:
  674. return s1 + s1 + s2 + text;
  675. default:
  676. return text;
  677. }
  678. }
  679. private void DrawSlider ()
  680. {
  681. // TODO: be more surgical on clear
  682. Clear ();
  683. // Attributes
  684. var normalAttr = new Attribute (Color.White, Color.Black);
  685. var setAttr = new Attribute (Color.Black, Color.White);
  686. if (IsInitialized)
  687. {
  688. normalAttr = ColorScheme?.Normal ?? Application.Current.ColorScheme.Normal;
  689. setAttr = Style.SetChar.Attribute ?? ColorScheme!.HotNormal;
  690. }
  691. bool isVertical = _config._sliderOrientation == Orientation.Vertical;
  692. bool isLegendsVertical = _config._legendsOrientation == Orientation.Vertical;
  693. bool isReverse = _config._sliderOrientation != _config._legendsOrientation;
  694. var x = 0;
  695. var y = 0;
  696. bool isSet = _setOptions.Count > 0;
  697. // Left Spacing
  698. if (_config._showEndSpacing && _config._startSpacing > 0)
  699. {
  700. Driver?.SetAttribute (
  701. isSet && _config._type == SliderType.LeftRange
  702. ? Style.RangeChar.Attribute ?? normalAttr
  703. : Style.SpaceChar.Attribute ?? normalAttr
  704. );
  705. Rune rune = isSet && _config._type == SliderType.LeftRange ? Style.RangeChar.Rune : Style.SpaceChar.Rune;
  706. for (var i = 0; i < _config._startSpacing; i++)
  707. {
  708. MoveAndAdd (x, y, rune);
  709. if (isVertical)
  710. {
  711. y++;
  712. }
  713. else
  714. {
  715. x++;
  716. }
  717. }
  718. }
  719. else
  720. {
  721. Driver?.SetAttribute (Style.EmptyChar.Attribute ?? normalAttr);
  722. for (var i = 0; i < _config._startSpacing; i++)
  723. {
  724. MoveAndAdd (x, y, Style.EmptyChar.Rune);
  725. if (isVertical)
  726. {
  727. y++;
  728. }
  729. else
  730. {
  731. x++;
  732. }
  733. }
  734. }
  735. // Slider
  736. if (_options.Count > 0)
  737. {
  738. for (var i = 0; i < _options.Count; i++)
  739. {
  740. var drawRange = false;
  741. if (isSet)
  742. {
  743. switch (_config._type)
  744. {
  745. case SliderType.LeftRange when i <= _setOptions [0]:
  746. drawRange = i < _setOptions [0];
  747. break;
  748. case SliderType.RightRange when i >= _setOptions [0]:
  749. drawRange = i >= _setOptions [0];
  750. break;
  751. case SliderType.Range when _setOptions.Count == 1:
  752. drawRange = false;
  753. break;
  754. case SliderType.Range when _setOptions.Count == 2:
  755. if ((i >= _setOptions [0] && i <= _setOptions [1])
  756. || (i >= _setOptions [1] && i <= _setOptions [0]))
  757. {
  758. drawRange = (i >= _setOptions [0] && i < _setOptions [1])
  759. || (i >= _setOptions [1] && i < _setOptions [0]);
  760. }
  761. break;
  762. }
  763. }
  764. // Draw Option
  765. Driver?.SetAttribute (
  766. isSet && _setOptions.Contains (i) ? Style.SetChar.Attribute ?? setAttr :
  767. drawRange ? Style.RangeChar.Attribute ?? setAttr : Style.OptionChar.Attribute ?? normalAttr
  768. );
  769. Rune rune = drawRange ? Style.RangeChar.Rune : Style.OptionChar.Rune;
  770. if (isSet)
  771. {
  772. if (_setOptions [0] == i)
  773. {
  774. rune = Style.StartRangeChar.Rune;
  775. }
  776. else if (_setOptions.Count > 1 && _setOptions [1] == i)
  777. {
  778. rune = Style.EndRangeChar.Rune;
  779. }
  780. else if (_setOptions.Contains (i))
  781. {
  782. rune = Style.SetChar.Rune;
  783. }
  784. }
  785. MoveAndAdd (x, y, rune);
  786. if (isVertical)
  787. {
  788. y++;
  789. }
  790. else
  791. {
  792. x++;
  793. }
  794. // Draw Spacing
  795. if (_config._showEndSpacing || i < _options.Count - 1)
  796. {
  797. // Skip if is the Last Spacing.
  798. Driver?.SetAttribute (
  799. drawRange && isSet
  800. ? Style.RangeChar.Attribute ?? setAttr
  801. : Style.SpaceChar.Attribute ?? normalAttr
  802. );
  803. for (var s = 0; s < _config._cachedInnerSpacing; s++)
  804. {
  805. MoveAndAdd (x, y, drawRange && isSet ? Style.RangeChar.Rune : Style.SpaceChar.Rune);
  806. if (isVertical)
  807. {
  808. y++;
  809. }
  810. else
  811. {
  812. x++;
  813. }
  814. }
  815. }
  816. }
  817. }
  818. int remaining = isVertical ? Viewport.Height - y : Viewport.Width - x;
  819. // Right Spacing
  820. if (_config._showEndSpacing)
  821. {
  822. Driver?.SetAttribute (
  823. isSet && _config._type == SliderType.RightRange
  824. ? Style.RangeChar.Attribute ?? normalAttr
  825. : Style.SpaceChar.Attribute ?? normalAttr
  826. );
  827. Rune rune = isSet && _config._type == SliderType.RightRange ? Style.RangeChar.Rune : Style.SpaceChar.Rune;
  828. for (var i = 0; i < remaining; i++)
  829. {
  830. MoveAndAdd (x, y, rune);
  831. if (isVertical)
  832. {
  833. y++;
  834. }
  835. else
  836. {
  837. x++;
  838. }
  839. }
  840. }
  841. else
  842. {
  843. Driver?.SetAttribute (Style.EmptyChar.Attribute ?? normalAttr);
  844. for (var i = 0; i < remaining; i++)
  845. {
  846. MoveAndAdd (x, y, Style.EmptyChar.Rune);
  847. if (isVertical)
  848. {
  849. y++;
  850. }
  851. else
  852. {
  853. x++;
  854. }
  855. }
  856. }
  857. }
  858. private void DrawLegends ()
  859. {
  860. // Attributes
  861. var normalAttr = new Attribute (Color.White, Color.Black);
  862. var setAttr = new Attribute (Color.Black, Color.White);
  863. Attribute spaceAttr = normalAttr;
  864. if (IsInitialized)
  865. {
  866. normalAttr = Style.LegendAttributes.NormalAttribute ?? ColorScheme?.Normal ?? ColorScheme.Disabled;
  867. setAttr = Style.LegendAttributes.SetAttribute ?? ColorScheme?.HotNormal ?? ColorScheme.Normal;
  868. spaceAttr = Style.LegendAttributes.EmptyAttribute ?? normalAttr;
  869. }
  870. bool isTextVertical = _config._legendsOrientation == Orientation.Vertical;
  871. bool isSet = _setOptions.Count > 0;
  872. var x = 0;
  873. var y = 0;
  874. Move (x, y);
  875. if (_config._sliderOrientation == Orientation.Horizontal
  876. && _config._legendsOrientation == Orientation.Vertical)
  877. {
  878. x += _config._startSpacing;
  879. }
  880. if (_config._sliderOrientation == Orientation.Vertical
  881. && _config._legendsOrientation == Orientation.Horizontal)
  882. {
  883. y += _config._startSpacing;
  884. }
  885. if (_config._sliderOrientation == Orientation.Horizontal)
  886. {
  887. y += 1;
  888. }
  889. else
  890. {
  891. // Vertical
  892. x += 1;
  893. }
  894. for (var i = 0; i < _options.Count; i++)
  895. {
  896. var isOptionSet = false;
  897. // Check if the Option is Set.
  898. switch (_config._type)
  899. {
  900. case SliderType.Single:
  901. case SliderType.Multiple:
  902. if (isSet && _setOptions.Contains (i))
  903. {
  904. isOptionSet = true;
  905. }
  906. break;
  907. case SliderType.LeftRange:
  908. if (isSet && i <= _setOptions [0])
  909. {
  910. isOptionSet = true;
  911. }
  912. break;
  913. case SliderType.RightRange:
  914. if (isSet && i >= _setOptions [0])
  915. {
  916. isOptionSet = true;
  917. }
  918. break;
  919. case SliderType.Range when _setOptions.Count == 1:
  920. if (isSet && i == _setOptions [0])
  921. {
  922. isOptionSet = true;
  923. }
  924. break;
  925. case SliderType.Range:
  926. if (isSet
  927. && ((i >= _setOptions [0] && i <= _setOptions [1])
  928. || (i >= _setOptions [1] && i <= _setOptions [0])))
  929. {
  930. isOptionSet = true;
  931. }
  932. break;
  933. }
  934. // Text || Abbreviation
  935. var text = string.Empty;
  936. if (_config._showLegendsAbbr)
  937. {
  938. text = _options [i].LegendAbbr.ToString () ?? new Rune (_options [i].Legend.First ()).ToString ();
  939. }
  940. else
  941. {
  942. text = _options [i].Legend;
  943. }
  944. switch (_config._sliderOrientation)
  945. {
  946. case Orientation.Horizontal:
  947. switch (_config._legendsOrientation)
  948. {
  949. case Orientation.Horizontal:
  950. text = AlignText (text, _config._cachedInnerSpacing + 1, Alignment.Center);
  951. break;
  952. case Orientation.Vertical:
  953. y = 1;
  954. break;
  955. }
  956. break;
  957. case Orientation.Vertical:
  958. switch (_config._legendsOrientation)
  959. {
  960. case Orientation.Horizontal:
  961. x = 1;
  962. break;
  963. case Orientation.Vertical:
  964. text = AlignText (text, _config._cachedInnerSpacing + 1, Alignment.Center);
  965. break;
  966. }
  967. break;
  968. }
  969. // Text
  970. int legendLeftSpacesCount = text.TakeWhile (e => e == ' ').Count ();
  971. int legendRightSpacesCount = text.Reverse ().TakeWhile (e => e == ' ').Count ();
  972. text = text.Trim ();
  973. // TODO(jmperricone): Improve the Orientation check.
  974. // Calculate Start Spacing
  975. if (_config._sliderOrientation == _config._legendsOrientation)
  976. {
  977. if (i == 0)
  978. {
  979. // The spacing for the slider use the StartSpacing but...
  980. // The spacing for the legends is the StartSpacing MINUS the total chars to the left of the first options.
  981. // ●────●────●
  982. // Hello Bye World
  983. //
  984. // chars_left is 2 for Hello => (5 - 1) / 2
  985. //
  986. // then the spacing is 2 for the slider but 0 for the legends.
  987. int charsLeft = (text.Length - 1) / 2;
  988. legendLeftSpacesCount = _config._startSpacing - charsLeft;
  989. }
  990. // Option Left Spacing
  991. if (isTextVertical)
  992. {
  993. y += legendLeftSpacesCount;
  994. }
  995. else
  996. {
  997. x += legendLeftSpacesCount;
  998. }
  999. //Move (x, y);
  1000. }
  1001. // Legend
  1002. Driver?.SetAttribute (isOptionSet ? setAttr : normalAttr);
  1003. foreach (Rune c in text.EnumerateRunes ())
  1004. {
  1005. MoveAndAdd (x, y, c);
  1006. //Driver.AddRune (c);
  1007. if (isTextVertical)
  1008. {
  1009. y += 1;
  1010. }
  1011. else
  1012. {
  1013. x += 1;
  1014. }
  1015. }
  1016. // Calculate End Spacing
  1017. if (i == _options.Count () - 1)
  1018. {
  1019. // See Start Spacing explanation.
  1020. int charsRight = text.Length / 2;
  1021. legendRightSpacesCount = _config._endSpacing - charsRight;
  1022. }
  1023. // Option Right Spacing of Option
  1024. Driver?.SetAttribute (spaceAttr);
  1025. if (isTextVertical)
  1026. {
  1027. y += legendRightSpacesCount;
  1028. }
  1029. else
  1030. {
  1031. x += legendRightSpacesCount;
  1032. }
  1033. if (_config._sliderOrientation == Orientation.Horizontal
  1034. && _config._legendsOrientation == Orientation.Vertical)
  1035. {
  1036. x += _config._cachedInnerSpacing + 1;
  1037. }
  1038. else if (_config._sliderOrientation == Orientation.Vertical
  1039. && _config._legendsOrientation == Orientation.Horizontal)
  1040. {
  1041. y += _config._cachedInnerSpacing + 1;
  1042. }
  1043. }
  1044. }
  1045. #endregion Drawing
  1046. #region Keys and Mouse
  1047. // Mouse coordinates of current drag
  1048. private Point? _dragPosition;
  1049. // Coordinates of where the "move cursor" is drawn (in OnDrawContent)
  1050. private Point? _moveRenderPosition;
  1051. /// <inheritdoc/>
  1052. protected internal override bool OnMouseEvent (MouseEvent mouseEvent)
  1053. {
  1054. // Note(jmperricone): Maybe we click to focus the cursor, and on next click we set the option.
  1055. // That will makes OptionFocused Event more relevant.
  1056. // (tig: I don't think so. Maybe an option if someone really wants it, but for now that
  1057. // adss to much friction to UI.
  1058. // TODO(jmperricone): Make Range Type work with mouse.
  1059. if (!(mouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked)
  1060. || mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed)
  1061. || mouseEvent.Flags.HasFlag (MouseFlags.ReportMousePosition)
  1062. || mouseEvent.Flags.HasFlag (MouseFlags.Button1Released)))
  1063. {
  1064. return false;
  1065. }
  1066. SetFocus ();
  1067. if (!_dragPosition.HasValue && mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed))
  1068. {
  1069. if (mouseEvent.Flags.HasFlag (MouseFlags.ReportMousePosition))
  1070. {
  1071. _dragPosition = mouseEvent.Position;
  1072. _moveRenderPosition = ClampMovePosition ((Point)_dragPosition);
  1073. Application.GrabMouse (this);
  1074. }
  1075. SetNeedsDisplay ();
  1076. return true;
  1077. }
  1078. if (_dragPosition.HasValue
  1079. && mouseEvent.Flags.HasFlag (MouseFlags.ReportMousePosition)
  1080. && mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed))
  1081. {
  1082. // Continue Drag
  1083. _dragPosition = mouseEvent.Position;
  1084. _moveRenderPosition = ClampMovePosition ((Point)_dragPosition);
  1085. var success = false;
  1086. var option = 0;
  1087. // how far has user dragged from original location?
  1088. if (Orientation == Orientation.Horizontal)
  1089. {
  1090. success = TryGetOptionByPosition (mouseEvent.Position.X, 0, Math.Max (0, _config._cachedInnerSpacing / 2), out option);
  1091. }
  1092. else
  1093. {
  1094. success = TryGetOptionByPosition (0, mouseEvent.Position.Y, Math.Max (0, _config._cachedInnerSpacing / 2), out option);
  1095. }
  1096. if (!_config._allowEmpty && success)
  1097. {
  1098. if (!OnOptionFocused (option, new (GetSetOptionDictionary (), FocusedOption)))
  1099. {
  1100. SetFocusedOption ();
  1101. }
  1102. }
  1103. SetNeedsDisplay ();
  1104. return true;
  1105. }
  1106. if ((_dragPosition.HasValue && mouseEvent.Flags.HasFlag (MouseFlags.Button1Released))
  1107. || mouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked))
  1108. {
  1109. // End Drag
  1110. Application.UngrabMouse ();
  1111. _dragPosition = null;
  1112. _moveRenderPosition = null;
  1113. // TODO: Add func to calc distance between options to use as the MouseClickXOptionThreshold
  1114. var success = false;
  1115. var option = 0;
  1116. if (Orientation == Orientation.Horizontal)
  1117. {
  1118. success = TryGetOptionByPosition (mouseEvent.Position.X, 0, Math.Max (0, _config._cachedInnerSpacing / 2), out option);
  1119. }
  1120. else
  1121. {
  1122. success = TryGetOptionByPosition (0, mouseEvent.Position.Y, Math.Max (0, _config._cachedInnerSpacing / 2), out option);
  1123. }
  1124. if (success)
  1125. {
  1126. if (!OnOptionFocused (option, new (GetSetOptionDictionary (), FocusedOption)))
  1127. {
  1128. SetFocusedOption ();
  1129. }
  1130. }
  1131. SetNeedsDisplay ();
  1132. return true;
  1133. }
  1134. return false;
  1135. Point ClampMovePosition (Point position)
  1136. {
  1137. int Clamp (int value, int min, int max) { return Math.Max (min, Math.Min (max, value)); }
  1138. if (Orientation == Orientation.Horizontal)
  1139. {
  1140. int left = _config._startSpacing;
  1141. int width = _options.Count + (_options.Count - 1) * _config._cachedInnerSpacing;
  1142. int right = left + width - 1;
  1143. int clampedX = Clamp (position.X, left, right);
  1144. position = new (clampedX, 0);
  1145. }
  1146. else
  1147. {
  1148. int top = _config._startSpacing;
  1149. int height = _options.Count + (_options.Count - 1) * _config._cachedInnerSpacing;
  1150. int bottom = top + height - 1;
  1151. int clampedY = Clamp (position.Y, top, bottom);
  1152. position = new (0, clampedY);
  1153. }
  1154. return position;
  1155. }
  1156. }
  1157. private void SetCommands ()
  1158. {
  1159. AddCommand (Command.Right, () => MovePlus ());
  1160. AddCommand (Command.LineDown, () => MovePlus ());
  1161. AddCommand (Command.Left, () => MoveMinus ());
  1162. AddCommand (Command.LineUp, () => MoveMinus ());
  1163. AddCommand (Command.LeftHome, () => MoveStart ());
  1164. AddCommand (Command.RightEnd, () => MoveEnd ());
  1165. AddCommand (Command.RightExtend, () => ExtendPlus ());
  1166. AddCommand (Command.LeftExtend, () => ExtendMinus ());
  1167. AddCommand (Command.Accept, () => Set ());
  1168. SetKeyBindings ();
  1169. }
  1170. // This is called during initialization and anytime orientation changes
  1171. private void SetKeyBindings ()
  1172. {
  1173. if (_config._sliderOrientation == Orientation.Horizontal)
  1174. {
  1175. KeyBindings.Add (Key.CursorRight, Command.Right);
  1176. KeyBindings.Remove (Key.CursorDown);
  1177. KeyBindings.Add (Key.CursorLeft, Command.Left);
  1178. KeyBindings.Remove (Key.CursorUp);
  1179. KeyBindings.Add (Key.CursorRight.WithCtrl, Command.RightExtend);
  1180. KeyBindings.Remove (Key.CursorDown.WithCtrl);
  1181. KeyBindings.Add (Key.CursorLeft.WithCtrl, Command.LeftExtend);
  1182. KeyBindings.Remove (Key.CursorUp.WithCtrl);
  1183. }
  1184. else
  1185. {
  1186. KeyBindings.Remove (Key.CursorRight);
  1187. KeyBindings.Add (Key.CursorDown, Command.LineDown);
  1188. KeyBindings.Remove (Key.CursorLeft);
  1189. KeyBindings.Add (Key.CursorUp, Command.LineUp);
  1190. KeyBindings.Remove (Key.CursorRight.WithCtrl);
  1191. KeyBindings.Add (Key.CursorDown.WithCtrl, Command.RightExtend);
  1192. KeyBindings.Remove (Key.CursorLeft.WithCtrl);
  1193. KeyBindings.Add (Key.CursorUp.WithCtrl, Command.LeftExtend);
  1194. }
  1195. KeyBindings.Add (Key.Home, Command.LeftHome);
  1196. KeyBindings.Add (Key.End, Command.RightEnd);
  1197. KeyBindings.Add (Key.Enter, Command.Accept);
  1198. KeyBindings.Add (Key.Space, Command.Accept);
  1199. }
  1200. private Dictionary<int, SliderOption<T>> GetSetOptionDictionary () { return _setOptions.ToDictionary (e => e, e => _options [e]); }
  1201. private void SetFocusedOption ()
  1202. {
  1203. switch (_config._type)
  1204. {
  1205. case SliderType.Single:
  1206. case SliderType.LeftRange:
  1207. case SliderType.RightRange:
  1208. if (_setOptions.Count == 1)
  1209. {
  1210. int prev = _setOptions [0];
  1211. if (!_config._allowEmpty && prev == FocusedOption)
  1212. {
  1213. break;
  1214. }
  1215. _setOptions.Clear ();
  1216. _options [FocusedOption].OnUnSet ();
  1217. if (FocusedOption != prev)
  1218. {
  1219. _setOptions.Add (FocusedOption);
  1220. _options [FocusedOption].OnSet ();
  1221. }
  1222. }
  1223. else
  1224. {
  1225. _setOptions.Add (FocusedOption);
  1226. _options [FocusedOption].OnSet ();
  1227. }
  1228. // Raise slider changed event.
  1229. OnOptionsChanged ();
  1230. break;
  1231. case SliderType.Multiple:
  1232. if (_setOptions.Contains (FocusedOption))
  1233. {
  1234. if (!_config._allowEmpty && _setOptions.Count () == 1)
  1235. {
  1236. break;
  1237. }
  1238. _setOptions.Remove (FocusedOption);
  1239. _options [FocusedOption].OnUnSet ();
  1240. }
  1241. else
  1242. {
  1243. _setOptions.Add (FocusedOption);
  1244. _options [FocusedOption].OnSet ();
  1245. }
  1246. OnOptionsChanged ();
  1247. break;
  1248. case SliderType.Range:
  1249. if (_config._rangeAllowSingle)
  1250. {
  1251. if (_setOptions.Count == 1)
  1252. {
  1253. int prev = _setOptions [0];
  1254. if (!_config._allowEmpty && prev == FocusedOption)
  1255. {
  1256. break;
  1257. }
  1258. if (FocusedOption == prev)
  1259. {
  1260. // un-set
  1261. _setOptions.Clear ();
  1262. _options [FocusedOption].OnUnSet ();
  1263. }
  1264. else
  1265. {
  1266. _setOptions [0] = FocusedOption;
  1267. _setOptions.Add (prev);
  1268. _setOptions.Sort ();
  1269. _options [FocusedOption].OnSet ();
  1270. }
  1271. }
  1272. else if (_setOptions.Count == 0)
  1273. {
  1274. _setOptions.Add (FocusedOption);
  1275. _options [FocusedOption].OnSet ();
  1276. }
  1277. else
  1278. {
  1279. // Extend/Shrink
  1280. if (FocusedOption < _setOptions [0])
  1281. {
  1282. // extend left
  1283. _options [_setOptions [0]].OnUnSet ();
  1284. _setOptions [0] = FocusedOption;
  1285. }
  1286. else if (FocusedOption > _setOptions [1])
  1287. {
  1288. // extend right
  1289. _options [_setOptions [1]].OnUnSet ();
  1290. _setOptions [1] = FocusedOption;
  1291. }
  1292. else if (FocusedOption >= _setOptions [0] && FocusedOption <= _setOptions [1])
  1293. {
  1294. if (FocusedOption < _lastFocusedOption)
  1295. {
  1296. // shrink to the left
  1297. _options [_setOptions [1]].OnUnSet ();
  1298. _setOptions [1] = FocusedOption;
  1299. }
  1300. else if (FocusedOption > _lastFocusedOption)
  1301. {
  1302. // shrink to the right
  1303. _options [_setOptions [0]].OnUnSet ();
  1304. _setOptions [0] = FocusedOption;
  1305. }
  1306. if (_setOptions.Count > 1 && _setOptions [0] == _setOptions [1])
  1307. {
  1308. _setOptions.Clear ();
  1309. _setOptions.Add (FocusedOption);
  1310. }
  1311. }
  1312. }
  1313. }
  1314. else
  1315. {
  1316. if (_setOptions.Count == 1)
  1317. {
  1318. int prev = _setOptions [0];
  1319. if (!_config._allowEmpty && prev == FocusedOption)
  1320. {
  1321. break;
  1322. }
  1323. _setOptions [0] = FocusedOption;
  1324. _setOptions.Add (prev);
  1325. _setOptions.Sort ();
  1326. _options [FocusedOption].OnSet ();
  1327. }
  1328. else if (_setOptions.Count == 0)
  1329. {
  1330. _setOptions.Add (FocusedOption);
  1331. _options [FocusedOption].OnSet ();
  1332. int next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption - 1;
  1333. _setOptions.Add (next);
  1334. _options [next].OnSet ();
  1335. }
  1336. else
  1337. {
  1338. // Extend/Shrink
  1339. if (FocusedOption < _setOptions [0])
  1340. {
  1341. // extend left
  1342. _options [_setOptions [0]].OnUnSet ();
  1343. _setOptions [0] = FocusedOption;
  1344. }
  1345. else if (FocusedOption > _setOptions [1])
  1346. {
  1347. // extend right
  1348. _options [_setOptions [1]].OnUnSet ();
  1349. _setOptions [1] = FocusedOption;
  1350. }
  1351. else if (FocusedOption >= _setOptions [0]
  1352. && FocusedOption <= _setOptions [1]
  1353. && _setOptions [1] - _setOptions [0] > 1)
  1354. {
  1355. if (FocusedOption < _lastFocusedOption)
  1356. {
  1357. // shrink to the left
  1358. _options [_setOptions [1]].OnUnSet ();
  1359. _setOptions [1] = FocusedOption;
  1360. }
  1361. else if (FocusedOption > _lastFocusedOption)
  1362. {
  1363. // shrink to the right
  1364. _options [_setOptions [0]].OnUnSet ();
  1365. _setOptions [0] = FocusedOption;
  1366. }
  1367. }
  1368. }
  1369. }
  1370. // Raise Slider Option Changed Event.
  1371. OnOptionsChanged ();
  1372. break;
  1373. default:
  1374. throw new ArgumentOutOfRangeException (_config._type.ToString ());
  1375. }
  1376. OnAccept ();
  1377. }
  1378. internal bool ExtendPlus ()
  1379. {
  1380. int next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption;
  1381. if (next != FocusedOption
  1382. && !OnOptionFocused (
  1383. next,
  1384. new (
  1385. GetSetOptionDictionary (),
  1386. FocusedOption
  1387. )
  1388. ))
  1389. {
  1390. SetFocusedOption ();
  1391. }
  1392. return true;
  1393. //// TODO: Support RangeMultiple
  1394. //if (_setOptions.Contains (FocusedOption)) {
  1395. // var next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption;
  1396. // if (!_setOptions.Contains (next)) {
  1397. // if (_config._type == SliderType.Range) {
  1398. // if (_setOptions.Count == 1) {
  1399. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1400. // _setOptions.Add (FocusedOption);
  1401. // _setOptions.Sort (); // Range Type
  1402. // OnOptionsChanged ();
  1403. // }
  1404. // } else if (_setOptions.Count == 2) {
  1405. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1406. // _setOptions [1] = FocusedOption;
  1407. // _setOptions.Sort (); // Range Type
  1408. // OnOptionsChanged ();
  1409. // }
  1410. // }
  1411. // } else {
  1412. // _setOptions.Remove (FocusedOption);
  1413. // // Note(jmperricone): We are setting the option here, do we send the OptionFocused Event too ?
  1414. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1415. // _setOptions.Add (FocusedOption);
  1416. // _setOptions.Sort (); // Range Type
  1417. // OnOptionsChanged ();
  1418. // }
  1419. // }
  1420. // } else {
  1421. // if (_config._type == SliderType.Range) {
  1422. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1423. // _setOptions.Clear();
  1424. // _setOptions.Add (FocusedOption);
  1425. // OnOptionsChanged ();
  1426. // }
  1427. // } else if (/*_settingRange == true ||*/ !AllowEmpty) {
  1428. // SetFocusedOption ();
  1429. // }
  1430. // }
  1431. //}
  1432. //return true;
  1433. }
  1434. internal bool ExtendMinus ()
  1435. {
  1436. int prev = FocusedOption > 0 ? FocusedOption - 1 : FocusedOption;
  1437. if (prev != FocusedOption
  1438. && !OnOptionFocused (
  1439. prev,
  1440. new (
  1441. GetSetOptionDictionary (),
  1442. FocusedOption
  1443. )
  1444. ))
  1445. {
  1446. SetFocusedOption ();
  1447. }
  1448. return true;
  1449. }
  1450. internal bool Set ()
  1451. {
  1452. SetFocusedOption ();
  1453. return true;
  1454. }
  1455. internal bool MovePlus ()
  1456. {
  1457. bool cancelled = OnOptionFocused (
  1458. FocusedOption + 1,
  1459. new (GetSetOptionDictionary (), FocusedOption)
  1460. );
  1461. if (cancelled)
  1462. {
  1463. return false;
  1464. }
  1465. if (!AllowEmpty)
  1466. {
  1467. SetFocusedOption ();
  1468. }
  1469. return true;
  1470. }
  1471. internal bool MoveMinus ()
  1472. {
  1473. bool cancelled = OnOptionFocused (
  1474. FocusedOption - 1,
  1475. new (GetSetOptionDictionary (), FocusedOption)
  1476. );
  1477. if (cancelled)
  1478. {
  1479. return false;
  1480. }
  1481. if (!AllowEmpty)
  1482. {
  1483. SetFocusedOption ();
  1484. }
  1485. return true;
  1486. }
  1487. internal bool MoveStart ()
  1488. {
  1489. if (OnOptionFocused (0, new (GetSetOptionDictionary (), FocusedOption)))
  1490. {
  1491. return false;
  1492. }
  1493. if (!AllowEmpty)
  1494. {
  1495. SetFocusedOption ();
  1496. }
  1497. return true;
  1498. }
  1499. internal bool MoveEnd ()
  1500. {
  1501. if (OnOptionFocused (_options.Count - 1, new (GetSetOptionDictionary (), FocusedOption)))
  1502. {
  1503. return false;
  1504. }
  1505. if (!AllowEmpty)
  1506. {
  1507. SetFocusedOption ();
  1508. }
  1509. return true;
  1510. }
  1511. #endregion
  1512. }