Slider.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699
  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 () { Rune = CM.Glyphs.HLine }; // '─'
  578. _style.OptionChar = new Cell () { Rune = CM.Glyphs.BlackCircle }; // '┼●🗹□⏹'
  579. break;
  580. case Orientation.Vertical:
  581. _style.SpaceChar = new Cell () { Rune = CM.Glyphs.VLine };
  582. _style.OptionChar = new Cell () { Rune = 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 () { Rune = new Rune (' ') };
  599. _style.SetChar = new Cell () { Rune = CM.Glyphs.ContinuousMeterSegment }; // ■
  600. _style.RangeChar = new Cell () { Rune = CM.Glyphs.Stipple }; // ░ ▒ ▓ // Medium shade not blinking on curses.
  601. _style.StartRangeChar = new Cell () { Rune = CM.Glyphs.ContinuousMeterSegment };
  602. _style.EndRangeChar = new Cell () { Rune = CM.Glyphs.ContinuousMeterSegment };
  603. _style.DragChar = new Cell () { Rune = 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.Rune);
  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.Rune : _style.SpaceChar.Rune;
  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.Rune);
  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.Rune : _style.OptionChar.Rune;
  927. if (isSet) {
  928. if (_setOptions [0] == i) {
  929. rune = _style.StartRangeChar.Rune;
  930. } else if (_setOptions.Count > 1 && _setOptions [1] == i) {
  931. rune = _style.EndRangeChar.Rune;
  932. } else if (_setOptions.Contains (i)) {
  933. rune = _style.SetChar.Rune;
  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.Rune : _style.SpaceChar.Rune);
  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.Rune : _style.SpaceChar.Rune;
  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.Rune);
  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. KeyBindings.Add (KeyCode.CursorRight, Command.Right);
  1201. KeyBindings.Remove (KeyCode.CursorDown);
  1202. KeyBindings.Add (KeyCode.CursorLeft, Command.Left);
  1203. KeyBindings.Remove (KeyCode.CursorUp);
  1204. KeyBindings.Add (KeyCode.CursorRight | KeyCode.CtrlMask, Command.RightExtend);
  1205. KeyBindings.Remove (KeyCode.CursorDown | KeyCode.CtrlMask);
  1206. KeyBindings.Add (KeyCode.CursorLeft | KeyCode.CtrlMask, Command.LeftExtend);
  1207. KeyBindings.Remove (KeyCode.CursorUp | KeyCode.CtrlMask);
  1208. } else {
  1209. KeyBindings.Remove (KeyCode.CursorRight);
  1210. KeyBindings.Add (KeyCode.CursorDown, Command.LineDown);
  1211. KeyBindings.Remove (KeyCode.CursorLeft);
  1212. KeyBindings.Add (KeyCode.CursorUp, Command.LineUp);
  1213. KeyBindings.Remove (KeyCode.CursorRight | KeyCode.CtrlMask);
  1214. KeyBindings.Add (KeyCode.CursorDown | KeyCode.CtrlMask, Command.RightExtend);
  1215. KeyBindings.Remove (KeyCode.CursorLeft | KeyCode.CtrlMask);
  1216. KeyBindings.Add (KeyCode.CursorUp | KeyCode.CtrlMask, Command.LeftExtend);
  1217. }
  1218. KeyBindings.Add (KeyCode.Home, Command.LeftHome);
  1219. KeyBindings.Add (KeyCode.End, Command.RightEnd);
  1220. KeyBindings.Add (KeyCode.Enter, Command.Accept);
  1221. KeyBindings.Add (KeyCode.Space, Command.Accept);
  1222. }
  1223. Dictionary<int, SliderOption<T>> GetSetOptionDictionary () => _setOptions.ToDictionary (e => e, e => _options [e]);
  1224. void SetFocusedOption ()
  1225. {
  1226. switch (_config._type) {
  1227. case SliderType.Single:
  1228. case SliderType.LeftRange:
  1229. case SliderType.RightRange:
  1230. if (_setOptions.Count == 1) {
  1231. var prev = _setOptions [0];
  1232. if (!_config._allowEmpty && prev == FocusedOption) {
  1233. break;
  1234. }
  1235. _setOptions.Clear ();
  1236. _options [FocusedOption].OnUnSet ();
  1237. if (FocusedOption != prev) {
  1238. _setOptions.Add (FocusedOption);
  1239. _options [FocusedOption].OnSet ();
  1240. }
  1241. } else {
  1242. _setOptions.Add (FocusedOption);
  1243. _options [FocusedOption].OnSet ();
  1244. }
  1245. // Raise slider changed event.
  1246. OnOptionsChanged ();
  1247. break;
  1248. case SliderType.Multiple:
  1249. if (_setOptions.Contains (FocusedOption)) {
  1250. if (!_config._allowEmpty && _setOptions.Count () == 1) {
  1251. break;
  1252. }
  1253. _setOptions.Remove (FocusedOption);
  1254. _options [FocusedOption].OnUnSet ();
  1255. } else {
  1256. _setOptions.Add (FocusedOption);
  1257. _options [FocusedOption].OnSet ();
  1258. }
  1259. OnOptionsChanged ();
  1260. break;
  1261. case SliderType.Range:
  1262. if (_config._rangeAllowSingle) {
  1263. if (_setOptions.Count == 1) {
  1264. var prev = _setOptions [0];
  1265. if (!_config._allowEmpty && prev == FocusedOption) {
  1266. break;
  1267. }
  1268. if (FocusedOption == prev) {
  1269. // un-set
  1270. _setOptions.Clear ();
  1271. _options [FocusedOption].OnUnSet ();
  1272. } else {
  1273. _setOptions [0] = FocusedOption;
  1274. _setOptions.Add (prev);
  1275. _setOptions.Sort ();
  1276. _options [FocusedOption].OnSet ();
  1277. }
  1278. } else if (_setOptions.Count == 0) {
  1279. _setOptions.Add (FocusedOption);
  1280. _options [FocusedOption].OnSet ();
  1281. } else {
  1282. // Extend/Shrink
  1283. if (FocusedOption < _setOptions [0]) {
  1284. // extend left
  1285. _options [_setOptions [0]].OnUnSet ();
  1286. _setOptions [0] = FocusedOption;
  1287. } else if (FocusedOption > _setOptions [1]) {
  1288. // extend right
  1289. _options [_setOptions [1]].OnUnSet ();
  1290. _setOptions [1] = FocusedOption;
  1291. } else if (FocusedOption >= _setOptions [0] && FocusedOption <= _setOptions [1]) {
  1292. if (FocusedOption < _lastFocusedOption) {
  1293. // shrink to the left
  1294. _options [_setOptions [1]].OnUnSet ();
  1295. _setOptions [1] = FocusedOption;
  1296. } else if (FocusedOption > _lastFocusedOption) {
  1297. // shrink to the right
  1298. _options [_setOptions [0]].OnUnSet ();
  1299. _setOptions [0] = FocusedOption;
  1300. }
  1301. if (_setOptions.Count > 1 && _setOptions [0] == _setOptions [1]) {
  1302. _setOptions.Clear ();
  1303. _setOptions.Add (FocusedOption);
  1304. }
  1305. }
  1306. }
  1307. } else {
  1308. if (_setOptions.Count == 1) {
  1309. var prev = _setOptions [0];
  1310. if (!_config._allowEmpty && prev == FocusedOption) {
  1311. break;
  1312. }
  1313. _setOptions [0] = FocusedOption;
  1314. _setOptions.Add (prev);
  1315. _setOptions.Sort ();
  1316. _options [FocusedOption].OnSet ();
  1317. } else if (_setOptions.Count == 0) {
  1318. _setOptions.Add (FocusedOption);
  1319. _options [FocusedOption].OnSet ();
  1320. var next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption - 1;
  1321. _setOptions.Add (next);
  1322. _options [next].OnSet ();
  1323. } else {
  1324. // Extend/Shrink
  1325. if (FocusedOption < _setOptions [0]) {
  1326. // extend left
  1327. _options [_setOptions [0]].OnUnSet ();
  1328. _setOptions [0] = FocusedOption;
  1329. } else if (FocusedOption > _setOptions [1]) {
  1330. // extend right
  1331. _options [_setOptions [1]].OnUnSet ();
  1332. _setOptions [1] = FocusedOption;
  1333. } else if (FocusedOption >= _setOptions [0] && FocusedOption <= _setOptions [1] && (_setOptions [1] - _setOptions [0] > 1)) {
  1334. if (FocusedOption < _lastFocusedOption) {
  1335. // shrink to the left
  1336. _options [_setOptions [1]].OnUnSet ();
  1337. _setOptions [1] = FocusedOption;
  1338. } else if (FocusedOption > _lastFocusedOption) {
  1339. // shrink to the right
  1340. _options [_setOptions [0]].OnUnSet ();
  1341. _setOptions [0] = FocusedOption;
  1342. }
  1343. }
  1344. //if (_setOptions.Count > 1 && _setOptions [0] == _setOptions [1]) {
  1345. // SetFocusedOption ();
  1346. //}
  1347. }
  1348. }
  1349. // Raise Slider Option Changed Event.
  1350. OnOptionsChanged ();
  1351. break;
  1352. default:
  1353. throw new ArgumentOutOfRangeException (_config._type.ToString ());
  1354. }
  1355. }
  1356. internal bool ExtendPlus ()
  1357. {
  1358. var next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption;
  1359. if (next != FocusedOption && !OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1360. SetFocusedOption ();
  1361. }
  1362. return true;
  1363. //// TODO: Support RangeMultiple
  1364. //if (_setOptions.Contains (FocusedOption)) {
  1365. // var next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption;
  1366. // if (!_setOptions.Contains (next)) {
  1367. // if (_config._type == SliderType.Range) {
  1368. // if (_setOptions.Count == 1) {
  1369. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1370. // _setOptions.Add (FocusedOption);
  1371. // _setOptions.Sort (); // Range Type
  1372. // OnOptionsChanged ();
  1373. // }
  1374. // } else if (_setOptions.Count == 2) {
  1375. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1376. // _setOptions [1] = FocusedOption;
  1377. // _setOptions.Sort (); // Range Type
  1378. // OnOptionsChanged ();
  1379. // }
  1380. // }
  1381. // } else {
  1382. // _setOptions.Remove (FocusedOption);
  1383. // // Note(jmperricone): We are setting the option here, do we send the OptionFocused Event too ?
  1384. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1385. // _setOptions.Add (FocusedOption);
  1386. // _setOptions.Sort (); // Range Type
  1387. // OnOptionsChanged ();
  1388. // }
  1389. // }
  1390. // } else {
  1391. // if (_config._type == SliderType.Range) {
  1392. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1393. // _setOptions.Clear();
  1394. // _setOptions.Add (FocusedOption);
  1395. // OnOptionsChanged ();
  1396. // }
  1397. // } else if (/*_settingRange == true ||*/ !AllowEmpty) {
  1398. // SetFocusedOption ();
  1399. // }
  1400. // }
  1401. //}
  1402. //return true;
  1403. }
  1404. internal bool ExtendMinus ()
  1405. {
  1406. var prev = FocusedOption > 0 ? FocusedOption - 1 : FocusedOption;
  1407. if (prev != FocusedOption && !OnOptionFocused (prev, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1408. SetFocusedOption ();
  1409. }
  1410. return true;
  1411. }
  1412. internal bool Set ()
  1413. {
  1414. SetFocusedOption ();
  1415. return true;
  1416. }
  1417. internal bool MovePlus ()
  1418. {
  1419. var cancelled = OnOptionFocused (FocusedOption + 1, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption));
  1420. if (cancelled) {
  1421. return false;
  1422. }
  1423. if (!AllowEmpty) {
  1424. SetFocusedOption ();
  1425. }
  1426. return true;
  1427. }
  1428. internal bool MoveMinus ()
  1429. {
  1430. var cancelled = OnOptionFocused (FocusedOption - 1, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption));
  1431. if (cancelled) {
  1432. return false;
  1433. }
  1434. if (!AllowEmpty) {
  1435. SetFocusedOption ();
  1436. }
  1437. return true;
  1438. }
  1439. internal bool MoveStart ()
  1440. {
  1441. if (OnOptionFocused (0, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1442. return false;
  1443. }
  1444. if (!AllowEmpty) {
  1445. SetFocusedOption ();
  1446. }
  1447. return true;
  1448. }
  1449. internal bool MoveEnd ()
  1450. {
  1451. if (OnOptionFocused (_options.Count - 1, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1452. return false;
  1453. }
  1454. if (!AllowEmpty) {
  1455. SetFocusedOption ();
  1456. }
  1457. return true;
  1458. }
  1459. #endregion
  1460. }