Slider.cs 64 KB

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