Slider.cs 47 KB

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