Slider.cs 58 KB

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