Slider.cs 58 KB

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