Slider.cs 65 KB

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