Slider.cs 66 KB

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