Slider.cs 64 KB

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