Slider.cs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870
  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, IOrientation
  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. private OrientationHelper _orientationHelper;
  28. #region Initialize
  29. private void SetInitialProperties (
  30. List<SliderOption<T>> options,
  31. Orientation orientation = Orientation.Horizontal
  32. )
  33. {
  34. Width = Dim.Auto (DimAutoStyle.Content);
  35. Height = Dim.Auto (DimAutoStyle.Content);
  36. CanFocus = true;
  37. CursorVisibility = CursorVisibility.Default;
  38. _options = options ?? new List<SliderOption<T>> ();
  39. _orientationHelper = new (this); // Do not use object initializer!
  40. _orientationHelper.Orientation = _config._sliderOrientation = orientation;
  41. _orientationHelper.OrientationChanging += (sender, e) => OrientationChanging?.Invoke (this, e);
  42. _orientationHelper.OrientationChanged += (sender, e) => OrientationChanged?.Invoke (this, e);
  43. SetDefaultStyle ();
  44. SetCommands ();
  45. SetContentSize ();
  46. // BUGBUG: This should not be needed - Need to ensure SetRelativeLayout gets called during EndInit
  47. Initialized += (s, e) => { SetContentSize (); };
  48. SubviewLayout += (s, e) => { SetContentSize (); };
  49. }
  50. // TODO: Make configurable via ConfigurationManager
  51. private void SetDefaultStyle ()
  52. {
  53. _config._showLegends = true;
  54. switch (_config._sliderOrientation)
  55. {
  56. case Orientation.Horizontal:
  57. Style.SpaceChar = new () { Rune = Glyphs.HLine }; // '─'
  58. Style.OptionChar = new () { Rune = Glyphs.BlackCircle }; // '┼●🗹□⏹'
  59. break;
  60. case Orientation.Vertical:
  61. Style.SpaceChar = new () { Rune = Glyphs.VLine };
  62. Style.OptionChar = new () { Rune = Glyphs.BlackCircle };
  63. break;
  64. }
  65. // TODO(jmperricone) Wide Vertical ???
  66. /*
  67. ┼─ 40
  68. ███ 30
  69. ▒▒▒
  70. ▒▒▒
  71. ▒▒▒ 20
  72. ▒▒▒
  73. ▒▒▒
  74. ███ 10
  75. ─●─ 0
  76. */
  77. _config._legendsOrientation = _config._sliderOrientation;
  78. Style.EmptyChar = new () { Rune = new (' ') };
  79. Style.SetChar = new () { Rune = Glyphs.ContinuousMeterSegment }; // ■
  80. Style.RangeChar = new () { Rune = Glyphs.Stipple }; // ░ ▒ ▓ // Medium shade not blinking on curses.
  81. Style.StartRangeChar = new () { Rune = Glyphs.ContinuousMeterSegment };
  82. Style.EndRangeChar = new () { Rune = Glyphs.ContinuousMeterSegment };
  83. Style.DragChar = new () { Rune = Glyphs.Diamond };
  84. // TODO: Support left & right (top/bottom)
  85. // First = '├',
  86. // Last = '┤',
  87. }
  88. #endregion
  89. #region Constructors
  90. /// <summary>Initializes a new instance of the <see cref="Slider"/> class.</summary>
  91. public Slider () : this (new ()) { }
  92. /// <summary>Initializes a new instance of the <see cref="Slider"/> class.</summary>
  93. /// <param name="options">Initial slider options.</param>
  94. /// <param name="orientation">Initial slider orientation.</param>
  95. public Slider (List<T> options, Orientation orientation = Orientation.Horizontal)
  96. {
  97. if (options is null)
  98. {
  99. SetInitialProperties (null, orientation);
  100. }
  101. else
  102. {
  103. SetInitialProperties (
  104. options.Select (
  105. e =>
  106. {
  107. var legend = e.ToString ();
  108. return new SliderOption<T>
  109. {
  110. Data = e,
  111. Legend = legend,
  112. LegendAbbr =
  113. (Rune)(legend?.Length > 0 ? legend [0] : ' ')
  114. };
  115. }
  116. )
  117. .ToList (),
  118. orientation
  119. );
  120. }
  121. }
  122. #endregion
  123. #region Properties
  124. /// <summary>
  125. /// Setting the Text of a slider is a shortcut to setting options. The text is a CSV string of the options.
  126. /// </summary>
  127. public override string Text
  128. {
  129. get
  130. {
  131. if (_options.Count == 0)
  132. {
  133. return string.Empty;
  134. }
  135. // Return labels as a CSV string
  136. return string.Join (",", _options);
  137. }
  138. set
  139. {
  140. if (string.IsNullOrEmpty (value))
  141. {
  142. Options = [];
  143. }
  144. else
  145. {
  146. IEnumerable<string> list = value.Split (',').Select (x => x.Trim ());
  147. Options = list.Select (x => new SliderOption<T> { Legend = x }).ToList ();
  148. }
  149. }
  150. }
  151. /// <summary>Allow no selection.</summary>
  152. public bool AllowEmpty
  153. {
  154. get => _config._allowEmpty;
  155. set
  156. {
  157. _config._allowEmpty = value;
  158. if (!value && _options.Count > 0 && _setOptions.Count == 0)
  159. {
  160. SetOption (0);
  161. }
  162. }
  163. }
  164. /// <summary>Gets or sets the minimum number of rows/columns between <see cref="Options"/>. The default is 1.</summary>
  165. public int MinimumInnerSpacing
  166. {
  167. get => _config._minInnerSpacing;
  168. set
  169. {
  170. _config._minInnerSpacing = value;
  171. SetContentSize ();
  172. }
  173. }
  174. /// <summary>Slider Type. <see cref="SliderType"></see></summary>
  175. public SliderType Type
  176. {
  177. get => _config._type;
  178. set
  179. {
  180. _config._type = value;
  181. // Todo: Custom logic to preserve options.
  182. _setOptions.Clear ();
  183. SetNeedsDraw ();
  184. }
  185. }
  186. /// <summary>
  187. /// Gets or sets the <see cref="Orientation"/>. The default is <see cref="Orientation.Horizontal"/>.
  188. /// </summary>
  189. public Orientation Orientation
  190. {
  191. get => _orientationHelper.Orientation;
  192. set => _orientationHelper.Orientation = value;
  193. }
  194. #region IOrientation members
  195. /// <inheritdoc />
  196. public event EventHandler<CancelEventArgs<Orientation>> OrientationChanging;
  197. /// <inheritdoc />
  198. public event EventHandler<EventArgs<Orientation>> OrientationChanged;
  199. /// <inheritdoc />
  200. public void OnOrientationChanged (Orientation newOrientation)
  201. {
  202. _config._sliderOrientation = newOrientation;
  203. switch (_config._sliderOrientation)
  204. {
  205. case Orientation.Horizontal:
  206. Style.SpaceChar = new () { Rune = Glyphs.HLine }; // '─'
  207. break;
  208. case Orientation.Vertical:
  209. Style.SpaceChar = new () { Rune = Glyphs.VLine };
  210. break;
  211. }
  212. SetKeyBindings ();
  213. SetContentSize ();
  214. }
  215. #endregion
  216. /// <summary>Legends Orientation. <see cref="Gui.Orientation"></see></summary>
  217. public Orientation LegendsOrientation
  218. {
  219. get => _config._legendsOrientation;
  220. set
  221. {
  222. _config._legendsOrientation = value;
  223. SetContentSize ();
  224. }
  225. }
  226. /// <summary>Slider styles. <see cref="SliderStyle"></see></summary>
  227. public SliderStyle Style { get; set; } = new ();
  228. /// <summary>Set the slider options.</summary>
  229. public List<SliderOption<T>> Options
  230. {
  231. get =>
  232. _options;
  233. set
  234. {
  235. // _options should never be null
  236. _options = value ?? throw new ArgumentNullException (nameof (value));
  237. if (_options.Count == 0)
  238. {
  239. return;
  240. }
  241. SetContentSize ();
  242. }
  243. }
  244. /// <summary>Allow range start and end be in the same option, as a single option.</summary>
  245. public bool RangeAllowSingle
  246. {
  247. get => _config._rangeAllowSingle;
  248. set => _config._rangeAllowSingle = value;
  249. }
  250. /// <summary>Show/Hide spacing before and after the first and last option.</summary>
  251. public bool ShowEndSpacing
  252. {
  253. get => _config._showEndSpacing;
  254. set
  255. {
  256. _config._showEndSpacing = value;
  257. SetContentSize ();
  258. }
  259. }
  260. /// <summary>Show/Hide the options legends.</summary>
  261. public bool ShowLegends
  262. {
  263. get => _config._showLegends;
  264. set
  265. {
  266. _config._showLegends = value;
  267. SetContentSize ();
  268. }
  269. }
  270. /// <summary>
  271. /// Gets or sets whether the minimum or ideal size will be used when calculating the size of the slider.
  272. /// </summary>
  273. public bool UseMinimumSize
  274. {
  275. get => _config._useMinimumSize;
  276. set
  277. {
  278. _config._useMinimumSize = value;
  279. SetContentSize ();
  280. }
  281. }
  282. #endregion
  283. #region Events
  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. SetNeedsDraw ();
  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. protected override bool OnDrawingContent ()
  629. {
  630. // TODO: make this more surgical to reduce repaint
  631. if (_options is null || _options.Count == 0)
  632. {
  633. return true;
  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. return true;
  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. ClearViewport ();
  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 = GetNormalColor();
  690. setAttr = Style.SetChar.Attribute ?? GetHotNormalColor ();
  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. 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. 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. 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. 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. 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. 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 ?? GetNormalColor ();
  868. setAttr = Style.LegendAttributes.SetAttribute ?? GetHotNormalColor ();
  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. 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. 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 override bool OnMouseEvent (MouseEventArgs mouseEvent)
  1054. {
  1055. // Note(jmperricone): Maybe we click to focus the cursor, and on next click we set the option.
  1056. // That will make OptionFocused Event more relevant.
  1057. // (tig: I don't think so. Maybe an option if someone really wants it, but for now that
  1058. // adds too 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. SetNeedsDraw ();
  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. SetNeedsDraw ();
  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. SetNeedsDraw ();
  1133. mouseEvent.Handled = true;
  1134. }
  1135. return mouseEvent.Handled;
  1136. Point ClampMovePosition (Point position)
  1137. {
  1138. int Clamp (int value, int min, int max) { return Math.Max (min, Math.Min (max, value)); }
  1139. if (Orientation == Orientation.Horizontal)
  1140. {
  1141. int left = _config._startSpacing;
  1142. int width = _options.Count + (_options.Count - 1) * _config._cachedInnerSpacing;
  1143. int right = left + width - 1;
  1144. int clampedX = Clamp (position.X, left, right);
  1145. position = new (clampedX, 0);
  1146. }
  1147. else
  1148. {
  1149. int top = _config._startSpacing;
  1150. int height = _options.Count + (_options.Count - 1) * _config._cachedInnerSpacing;
  1151. int bottom = top + height - 1;
  1152. int clampedY = Clamp (position.Y, top, bottom);
  1153. position = new (0, clampedY);
  1154. }
  1155. return position;
  1156. }
  1157. }
  1158. private void SetCommands ()
  1159. {
  1160. AddCommand (Command.Right, () => MovePlus ());
  1161. AddCommand (Command.Down, () => MovePlus ());
  1162. AddCommand (Command.Left, () => MoveMinus ());
  1163. AddCommand (Command.Up, () => MoveMinus ());
  1164. AddCommand (Command.LeftStart, () => MoveStart ());
  1165. AddCommand (Command.RightEnd, () => MoveEnd ());
  1166. AddCommand (Command.RightExtend, () => ExtendPlus ());
  1167. AddCommand (Command.LeftExtend, () => ExtendMinus ());
  1168. AddCommand (Command.Select, () => Select ());
  1169. AddCommand (Command.Accept, (ctx) => Accept (ctx));
  1170. SetKeyBindings ();
  1171. }
  1172. // This is called during initialization and anytime orientation changes
  1173. private void SetKeyBindings ()
  1174. {
  1175. if (_config._sliderOrientation == Orientation.Horizontal)
  1176. {
  1177. KeyBindings.Add (Key.CursorRight, Command.Right);
  1178. KeyBindings.Remove (Key.CursorDown);
  1179. KeyBindings.Add (Key.CursorLeft, Command.Left);
  1180. KeyBindings.Remove (Key.CursorUp);
  1181. KeyBindings.Add (Key.CursorRight.WithCtrl, Command.RightExtend);
  1182. KeyBindings.Remove (Key.CursorDown.WithCtrl);
  1183. KeyBindings.Add (Key.CursorLeft.WithCtrl, Command.LeftExtend);
  1184. KeyBindings.Remove (Key.CursorUp.WithCtrl);
  1185. }
  1186. else
  1187. {
  1188. KeyBindings.Remove (Key.CursorRight);
  1189. KeyBindings.Add (Key.CursorDown, Command.Down);
  1190. KeyBindings.Remove (Key.CursorLeft);
  1191. KeyBindings.Add (Key.CursorUp, Command.Up);
  1192. KeyBindings.Remove (Key.CursorRight.WithCtrl);
  1193. KeyBindings.Add (Key.CursorDown.WithCtrl, Command.RightExtend);
  1194. KeyBindings.Remove (Key.CursorLeft.WithCtrl);
  1195. KeyBindings.Add (Key.CursorUp.WithCtrl, Command.LeftExtend);
  1196. }
  1197. KeyBindings.Remove (Key.Home);
  1198. KeyBindings.Add (Key.Home, Command.LeftStart);
  1199. KeyBindings.Remove (Key.End);
  1200. KeyBindings.Add (Key.End, Command.RightEnd);
  1201. KeyBindings.Remove (Key.Enter);
  1202. KeyBindings.Add (Key.Enter, Command.Accept);
  1203. KeyBindings.Remove (Key.Space);
  1204. KeyBindings.Add (Key.Space, Command.Select);
  1205. }
  1206. private Dictionary<int, SliderOption<T>> GetSetOptionDictionary () { return _setOptions.ToDictionary (e => e, e => _options [e]); }
  1207. /// <summary>
  1208. /// Sets or unsets <paramref name="optionIndex"/> based on <paramref name="set"/>.
  1209. /// </summary>
  1210. /// <param name="optionIndex">The option to change.</param>
  1211. /// <param name="set">If <see langword="true"/>, sets the option. Unsets it otherwise.</param>
  1212. public void ChangeOption (int optionIndex, bool set)
  1213. {
  1214. if (set)
  1215. {
  1216. if (!_setOptions.Contains (optionIndex))
  1217. {
  1218. _setOptions.Add (optionIndex);
  1219. _options [optionIndex].OnSet ();
  1220. }
  1221. }
  1222. else
  1223. {
  1224. if (_setOptions.Contains (optionIndex))
  1225. {
  1226. _setOptions.Remove (optionIndex);
  1227. _options [optionIndex].OnUnSet ();
  1228. }
  1229. }
  1230. // Raise slider changed event.
  1231. OnOptionsChanged ();
  1232. }
  1233. private bool SetFocusedOption ()
  1234. {
  1235. if (_options.Count == 0)
  1236. {
  1237. return false;
  1238. }
  1239. bool changed = false;
  1240. switch (_config._type)
  1241. {
  1242. case SliderType.Single:
  1243. case SliderType.LeftRange:
  1244. case SliderType.RightRange:
  1245. if (_setOptions.Count == 1)
  1246. {
  1247. int prev = _setOptions [0];
  1248. if (!_config._allowEmpty && prev == FocusedOption)
  1249. {
  1250. break;
  1251. }
  1252. _setOptions.Clear ();
  1253. _options [FocusedOption].OnUnSet ();
  1254. if (FocusedOption != prev)
  1255. {
  1256. _setOptions.Add (FocusedOption);
  1257. _options [FocusedOption].OnSet ();
  1258. }
  1259. }
  1260. else
  1261. {
  1262. _setOptions.Add (FocusedOption);
  1263. _options [FocusedOption].OnSet ();
  1264. }
  1265. // Raise slider changed event.
  1266. OnOptionsChanged ();
  1267. changed = true;
  1268. break;
  1269. case SliderType.Multiple:
  1270. if (_setOptions.Contains (FocusedOption))
  1271. {
  1272. if (!_config._allowEmpty && _setOptions.Count () == 1)
  1273. {
  1274. break;
  1275. }
  1276. _setOptions.Remove (FocusedOption);
  1277. _options [FocusedOption].OnUnSet ();
  1278. }
  1279. else
  1280. {
  1281. _setOptions.Add (FocusedOption);
  1282. _options [FocusedOption].OnSet ();
  1283. }
  1284. OnOptionsChanged ();
  1285. changed = true;
  1286. break;
  1287. case SliderType.Range:
  1288. if (_config._rangeAllowSingle)
  1289. {
  1290. if (_setOptions.Count == 1)
  1291. {
  1292. int prev = _setOptions [0];
  1293. if (!_config._allowEmpty && prev == FocusedOption)
  1294. {
  1295. break;
  1296. }
  1297. if (FocusedOption == prev)
  1298. {
  1299. // un-set
  1300. _setOptions.Clear ();
  1301. _options [FocusedOption].OnUnSet ();
  1302. }
  1303. else
  1304. {
  1305. _setOptions [0] = FocusedOption;
  1306. _setOptions.Add (prev);
  1307. _setOptions.Sort ();
  1308. _options [FocusedOption].OnSet ();
  1309. }
  1310. }
  1311. else if (_setOptions.Count == 0)
  1312. {
  1313. _setOptions.Add (FocusedOption);
  1314. _options [FocusedOption].OnSet ();
  1315. }
  1316. else
  1317. {
  1318. // Extend/Shrink
  1319. if (FocusedOption < _setOptions [0])
  1320. {
  1321. // extend left
  1322. _options [_setOptions [0]].OnUnSet ();
  1323. _setOptions [0] = FocusedOption;
  1324. }
  1325. else if (FocusedOption > _setOptions [1])
  1326. {
  1327. // extend right
  1328. _options [_setOptions [1]].OnUnSet ();
  1329. _setOptions [1] = FocusedOption;
  1330. }
  1331. else if (FocusedOption >= _setOptions [0] && FocusedOption <= _setOptions [1])
  1332. {
  1333. if (FocusedOption < _lastFocusedOption)
  1334. {
  1335. // shrink to the left
  1336. _options [_setOptions [1]].OnUnSet ();
  1337. _setOptions [1] = FocusedOption;
  1338. }
  1339. else if (FocusedOption > _lastFocusedOption)
  1340. {
  1341. // shrink to the right
  1342. _options [_setOptions [0]].OnUnSet ();
  1343. _setOptions [0] = FocusedOption;
  1344. }
  1345. if (_setOptions.Count > 1 && _setOptions [0] == _setOptions [1])
  1346. {
  1347. _setOptions.Clear ();
  1348. _setOptions.Add (FocusedOption);
  1349. }
  1350. }
  1351. }
  1352. }
  1353. else
  1354. {
  1355. if (_setOptions.Count == 1)
  1356. {
  1357. int prev = _setOptions [0];
  1358. if (!_config._allowEmpty && prev == FocusedOption)
  1359. {
  1360. break;
  1361. }
  1362. _setOptions [0] = FocusedOption;
  1363. _setOptions.Add (prev);
  1364. _setOptions.Sort ();
  1365. _options [FocusedOption].OnSet ();
  1366. }
  1367. else if (_setOptions.Count == 0)
  1368. {
  1369. _setOptions.Add (FocusedOption);
  1370. _options [FocusedOption].OnSet ();
  1371. int next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption - 1;
  1372. _setOptions.Add (next);
  1373. _options [next].OnSet ();
  1374. }
  1375. else
  1376. {
  1377. // Extend/Shrink
  1378. if (FocusedOption < _setOptions [0])
  1379. {
  1380. // extend left
  1381. _options [_setOptions [0]].OnUnSet ();
  1382. _setOptions [0] = FocusedOption;
  1383. }
  1384. else if (FocusedOption > _setOptions [1])
  1385. {
  1386. // extend right
  1387. _options [_setOptions [1]].OnUnSet ();
  1388. _setOptions [1] = FocusedOption;
  1389. }
  1390. else if (FocusedOption >= _setOptions [0]
  1391. && FocusedOption <= _setOptions [1]
  1392. && _setOptions [1] - _setOptions [0] > 1)
  1393. {
  1394. if (FocusedOption < _lastFocusedOption)
  1395. {
  1396. // shrink to the left
  1397. _options [_setOptions [1]].OnUnSet ();
  1398. _setOptions [1] = FocusedOption;
  1399. }
  1400. else if (FocusedOption > _lastFocusedOption)
  1401. {
  1402. // shrink to the right
  1403. _options [_setOptions [0]].OnUnSet ();
  1404. _setOptions [0] = FocusedOption;
  1405. }
  1406. }
  1407. }
  1408. }
  1409. // Raise Slider Option Changed Event.
  1410. OnOptionsChanged ();
  1411. changed = true;
  1412. break;
  1413. default:
  1414. throw new ArgumentOutOfRangeException (_config._type.ToString ());
  1415. }
  1416. return changed;
  1417. }
  1418. internal bool ExtendPlus ()
  1419. {
  1420. int next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption;
  1421. if (next != FocusedOption
  1422. && !OnOptionFocused (
  1423. next,
  1424. new (
  1425. GetSetOptionDictionary (),
  1426. FocusedOption
  1427. )
  1428. ))
  1429. {
  1430. SetFocusedOption ();
  1431. }
  1432. return true;
  1433. //// TODO: Support RangeMultiple
  1434. //if (_setOptions.Contains (FocusedOption)) {
  1435. // var next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption;
  1436. // if (!_setOptions.Contains (next)) {
  1437. // if (_config._type == SliderType.Range) {
  1438. // if (_setOptions.Count == 1) {
  1439. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1440. // _setOptions.Add (FocusedOption);
  1441. // _setOptions.Sort (); // Range Type
  1442. // OnOptionsChanged ();
  1443. // }
  1444. // } else if (_setOptions.Count == 2) {
  1445. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1446. // _setOptions [1] = FocusedOption;
  1447. // _setOptions.Sort (); // Range Type
  1448. // OnOptionsChanged ();
  1449. // }
  1450. // }
  1451. // } else {
  1452. // _setOptions.Remove (FocusedOption);
  1453. // // Note(jmperricone): We are setting the option here, do we send the OptionFocused Event too ?
  1454. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1455. // _setOptions.Add (FocusedOption);
  1456. // _setOptions.Sort (); // Range Type
  1457. // OnOptionsChanged ();
  1458. // }
  1459. // }
  1460. // } else {
  1461. // if (_config._type == SliderType.Range) {
  1462. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1463. // _setOptions.Clear();
  1464. // _setOptions.Add (FocusedOption);
  1465. // OnOptionsChanged ();
  1466. // }
  1467. // } else if (/*_settingRange == true ||*/ !AllowEmpty) {
  1468. // SetFocusedOption ();
  1469. // }
  1470. // }
  1471. //}
  1472. //return true;
  1473. }
  1474. internal bool ExtendMinus ()
  1475. {
  1476. int prev = FocusedOption > 0 ? FocusedOption - 1 : FocusedOption;
  1477. if (prev != FocusedOption
  1478. && !OnOptionFocused (
  1479. prev,
  1480. new (
  1481. GetSetOptionDictionary (),
  1482. FocusedOption
  1483. )
  1484. ))
  1485. {
  1486. SetFocusedOption ();
  1487. }
  1488. return true;
  1489. }
  1490. internal bool Select ()
  1491. {
  1492. return SetFocusedOption ();
  1493. }
  1494. internal bool Accept (ICommandContext commandContext)
  1495. {
  1496. if (commandContext is not CommandContext<KeyBinding> ctx)
  1497. {
  1498. return false;
  1499. }
  1500. SetFocusedOption ();
  1501. return RaiseAccepting (ctx) == true;
  1502. }
  1503. internal bool MovePlus ()
  1504. {
  1505. bool cancelled = OnOptionFocused (
  1506. FocusedOption + 1,
  1507. new (GetSetOptionDictionary (), FocusedOption)
  1508. );
  1509. if (cancelled)
  1510. {
  1511. return false;
  1512. }
  1513. if (!AllowEmpty)
  1514. {
  1515. SetFocusedOption ();
  1516. }
  1517. return true;
  1518. }
  1519. internal bool MoveMinus ()
  1520. {
  1521. bool cancelled = OnOptionFocused (
  1522. FocusedOption - 1,
  1523. new (GetSetOptionDictionary (), FocusedOption)
  1524. );
  1525. if (cancelled)
  1526. {
  1527. return false;
  1528. }
  1529. if (!AllowEmpty)
  1530. {
  1531. SetFocusedOption ();
  1532. }
  1533. return true;
  1534. }
  1535. internal bool MoveStart ()
  1536. {
  1537. if (OnOptionFocused (0, new (GetSetOptionDictionary (), FocusedOption)))
  1538. {
  1539. return false;
  1540. }
  1541. if (!AllowEmpty)
  1542. {
  1543. SetFocusedOption ();
  1544. }
  1545. return true;
  1546. }
  1547. internal bool MoveEnd ()
  1548. {
  1549. if (OnOptionFocused (_options.Count - 1, new (GetSetOptionDictionary (), FocusedOption)))
  1550. {
  1551. return false;
  1552. }
  1553. if (!AllowEmpty)
  1554. {
  1555. SetFocusedOption ();
  1556. }
  1557. return true;
  1558. }
  1559. #endregion
  1560. }