Slider.cs 66 KB

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