Slider.cs 58 KB

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