Slider.cs 65 KB

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