Slider.cs 47 KB

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