Slider.cs 56 KB

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