Slider.cs 49 KB

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