Slider.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772
  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. Width = 0;
  689. Height = 0;
  690. if (_config._sliderOrientation == Orientation.Horizontal) {
  691. Bounds = new Rect (Bounds.Location,
  692. new Size (int.Min (SuperView.Bounds.Width - GetAdornmentsThickness ().Horizontal, CalcBestLength ()),
  693. int.Min (SuperView.Bounds.Height - GetAdornmentsThickness ().Vertical, CalcThickness ())));
  694. } else {
  695. Bounds = new Rect (Bounds.Location,
  696. new Size (int.Min (SuperView.Bounds.Width - GetAdornmentsThickness ().Horizontal, CalcThickness ()),
  697. int.Min (SuperView.Bounds.Height - GetAdornmentsThickness ().Vertical, CalcBestLength ())));
  698. }
  699. }
  700. /// <summary>
  701. /// Calculates the min dimension required for all options and inner spacing with abbreviated legends
  702. /// </summary>
  703. /// <returns></returns>
  704. int CalcMinLength ()
  705. {
  706. if (_options.Count == 0) {
  707. return 0;
  708. }
  709. var length = 0;
  710. length += _config._startSpacing + _config._endSpacing;
  711. length += _options.Count;
  712. length += (_options.Count - 1) * _config._innerSpacing;
  713. return length;
  714. }
  715. /// <summary>
  716. /// Calculates the ideal dimension required for all options, inner spacing, and legends
  717. /// (non-abbreviated).
  718. /// </summary>
  719. /// <returns></returns>
  720. int CalcBestLength ()
  721. {
  722. if (_options.Count == 0) {
  723. return 0;
  724. }
  725. var length = 0;
  726. if (_config._showLegends) {
  727. var max_legend = 1;
  728. if (_config._legendsOrientation == _config._sliderOrientation && _options.Count > 0) {
  729. max_legend = int.Max (_options.Max (s => s.Legend?.Length + 1 ?? 1), 1);
  730. length += max_legend * _options.Count;
  731. //length += (max_legend / 2);
  732. } else {
  733. length += 1;
  734. }
  735. }
  736. return int.Max (length, CalcMinLength ());
  737. }
  738. /// <summary>
  739. /// Calculates the min dimension required for the slider and legends
  740. /// </summary>
  741. /// <returns></returns>
  742. int CalcThickness ()
  743. {
  744. var thickness = 1; // Always show the slider.
  745. if (_config._showLegends) {
  746. if (_config._legendsOrientation != _config._sliderOrientation && _options.Count > 0) {
  747. thickness += _options.Max (s => s.Legend?.Length ?? 0);
  748. } else {
  749. thickness += 1;
  750. }
  751. }
  752. return thickness;
  753. }
  754. internal bool TryGetPositionByOption (int option, out (int x, int y) position)
  755. {
  756. position = (-1, -1);
  757. if (option < 0 || option >= _options.Count ()) {
  758. return false;
  759. }
  760. var offset = 0;
  761. offset += _config._startSpacing;
  762. offset += option * (_config._innerSpacing + 1);
  763. if (_config._sliderOrientation == Orientation.Vertical) {
  764. position = (0, offset);
  765. } else {
  766. position = (offset, 0);
  767. }
  768. return true;
  769. }
  770. /// <summary>
  771. /// Tries to get the option index by the position.
  772. /// </summary>
  773. /// <param name="x"></param>
  774. /// <param name="y"></param>
  775. /// <param name="threshold"></param>
  776. /// <param name="option_idx"></param>
  777. /// <returns></returns>
  778. internal bool TryGetOptionByPosition (int x, int y, int threshold, out int option_idx)
  779. {
  780. // Fix(jmperricone): Not working.
  781. option_idx = -1;
  782. if (Orientation == Orientation.Horizontal) {
  783. if (y != 0) {
  784. return false;
  785. }
  786. for (var xx = x - threshold; xx < x + threshold + 1; xx++) {
  787. var cx = xx;
  788. cx -= _config._startSpacing;
  789. var option = cx / (_config._innerSpacing + 1);
  790. var valid = cx % (_config._innerSpacing + 1) == 0;
  791. if (!valid || option < 0 || option > _options.Count - 1) {
  792. continue;
  793. }
  794. option_idx = option;
  795. return true;
  796. }
  797. } else {
  798. if (x != 0) {
  799. return false;
  800. }
  801. for (var yy = y - threshold; yy < y + threshold + 1; yy++) {
  802. var cy = yy;
  803. cy -= _config._startSpacing;
  804. var option = cy / (_config._innerSpacing + 1);
  805. var valid = cy % (_config._innerSpacing + 1) == 0;
  806. if (!valid || option < 0 || option > _options.Count - 1) {
  807. continue;
  808. }
  809. option_idx = option;
  810. return true;
  811. }
  812. }
  813. return false;
  814. }
  815. #endregion
  816. #region Cursor and Drawing
  817. /// <inheritdoc/>
  818. public override void PositionCursor ()
  819. {
  820. //base.PositionCursor ();
  821. if (HasFocus) {
  822. Driver?.SetCursorVisibility (CursorVisibility.Default);
  823. } else {
  824. Driver?.SetCursorVisibility (CursorVisibility.Invisible);
  825. }
  826. if (TryGetPositionByOption (FocusedOption, out var position)) {
  827. if (IsInitialized && Bounds.Contains (position.x, position.y)) {
  828. Move (position.x, position.y);
  829. }
  830. }
  831. }
  832. /// <inheritdoc/>
  833. public override void OnDrawContent (Rect contentArea)
  834. {
  835. // TODO: make this more surgical to reduce repaint
  836. if (_options == null && _options.Count > 0) {
  837. return;
  838. }
  839. // Debug
  840. #if (DEBUG)
  841. Driver?.SetAttribute (new Attribute (Color.White, Color.Red));
  842. for (var y = 0; y < contentArea.Height; y++) {
  843. for (var x = 0; x < contentArea.Width; x++) {
  844. // MoveAndAdd (x, y, '·');
  845. }
  846. }
  847. #endif
  848. // Draw Slider
  849. DrawSlider ();
  850. // Draw Legends.
  851. if (_config._showLegends) {
  852. DrawLegends ();
  853. }
  854. if (_dragPosition.HasValue && _moveRenderPosition.HasValue) {
  855. AddRune (_moveRenderPosition.Value.X, _moveRenderPosition.Value.Y, Style.DragChar.Rune);
  856. }
  857. }
  858. string AlignText (string text, int width, TextAlignment textAlignment)
  859. {
  860. if (text == null) {
  861. return "";
  862. }
  863. if (text.Length > width) {
  864. text = text [..width];
  865. }
  866. var w = width - text.Length;
  867. string s1 = new (' ', w / 2);
  868. string s2 = new (' ', w % 2);
  869. // Note: The formatter doesn't handle all of this ???
  870. switch (textAlignment) {
  871. case TextAlignment.Justified:
  872. return TextFormatter.Justify (text, width);
  873. case TextAlignment.Left:
  874. return text + s1 + s1 + s2;
  875. case TextAlignment.Centered:
  876. if (text.Length % 2 != 0) {
  877. return s1 + text + s1 + s2;
  878. }
  879. return s1 + s2 + text + s1;
  880. case TextAlignment.Right:
  881. return s1 + s1 + s2 + text;
  882. default:
  883. return text;
  884. }
  885. }
  886. void DrawSlider ()
  887. {
  888. // TODO: be more surgical on clear
  889. Clear ();
  890. // Attributes
  891. var normalAttr = new Attribute (Color.White, Color.Black);
  892. var setAtrr = new Attribute (Color.Black, Color.White);
  893. if (IsInitialized) {
  894. normalAttr = ColorScheme?.Normal ?? Application.Current.ColorScheme.Normal;
  895. setAtrr = Style.SetChar.Attribute ?? ColorScheme.HotNormal;
  896. }
  897. var isVertical = _config._sliderOrientation == Orientation.Vertical;
  898. var isLegendsVertical = _config._legendsOrientation == Orientation.Vertical;
  899. var isReverse = _config._sliderOrientation != _config._legendsOrientation;
  900. var x = 0;
  901. var y = 0;
  902. var isSet = _setOptions.Count > 0;
  903. // Left Spacing
  904. if (_config._showEndSpacing && _config._startSpacing > 0) {
  905. Driver?.SetAttribute (isSet && _config._type == SliderType.LeftRange ? Style.RangeChar.Attribute ?? normalAttr : Style.SpaceChar.Attribute ?? normalAttr);
  906. var rune = isSet && _config._type == SliderType.LeftRange ? Style.RangeChar.Rune : Style.SpaceChar.Rune;
  907. for (var i = 0; i < _config._startSpacing; i++) {
  908. MoveAndAdd (x, y, rune);
  909. if (isVertical) {
  910. y++;
  911. } else {
  912. x++;
  913. }
  914. }
  915. } else {
  916. Driver?.SetAttribute (Style.EmptyChar.Attribute ?? normalAttr);
  917. for (var i = 0; i < _config._startSpacing; i++) {
  918. MoveAndAdd (x, y, Style.EmptyChar.Rune);
  919. if (isVertical) {
  920. y++;
  921. } else {
  922. x++;
  923. }
  924. }
  925. }
  926. // Slider
  927. if (_options.Count > 0) {
  928. for (var i = 0; i < _options.Count; i++) {
  929. var drawRange = false;
  930. if (isSet) {
  931. switch (_config._type) {
  932. case SliderType.LeftRange when i <= _setOptions [0]:
  933. drawRange = i < _setOptions [0];
  934. break;
  935. case SliderType.RightRange when i >= _setOptions [0]:
  936. drawRange = i >= _setOptions [0];
  937. break;
  938. case SliderType.Range when _setOptions.Count == 1:
  939. drawRange = false;
  940. break;
  941. case SliderType.Range when _setOptions.Count == 2:
  942. if (i >= _setOptions [0] && i <= _setOptions [1] || i >= _setOptions [1] && i <= _setOptions [0]) {
  943. drawRange = i >= _setOptions [0] && i < _setOptions [1] || i >= _setOptions [1] && i < _setOptions [0];
  944. }
  945. break;
  946. }
  947. }
  948. // Draw Option
  949. Driver?.SetAttribute (isSet && _setOptions.Contains (i) ? Style.SetChar.Attribute ?? setAtrr : drawRange
  950. ? Style.RangeChar.Attribute ?? setAtrr : Style.OptionChar.Attribute ?? normalAttr);
  951. // Note(jmperricone): Maybe only for curses, windows inverts actual colors, while curses inverts bg with fg.
  952. //if (Application.Driver is CursesDriver) {
  953. // if (FocusedOption == i && HasFocus) {
  954. // Driver.SetAttribute (ColorScheme.Focus);
  955. // }
  956. //}
  957. var rune = drawRange ? Style.RangeChar.Rune : Style.OptionChar.Rune;
  958. if (isSet) {
  959. if (_setOptions [0] == i) {
  960. rune = Style.StartRangeChar.Rune;
  961. } else if (_setOptions.Count > 1 && _setOptions [1] == i) {
  962. rune = Style.EndRangeChar.Rune;
  963. } else if (_setOptions.Contains (i)) {
  964. rune = Style.SetChar.Rune;
  965. }
  966. }
  967. MoveAndAdd (x, y, rune);
  968. if (isVertical) {
  969. y++;
  970. } else {
  971. x++;
  972. }
  973. // Draw Spacing
  974. if (_config._showEndSpacing || i < _options.Count - 1) {
  975. // Skip if is the Last Spacing.
  976. Driver?.SetAttribute (drawRange && isSet ? Style.RangeChar.Attribute ?? setAtrr : Style.SpaceChar.Attribute ?? normalAttr);
  977. for (var s = 0; s < _config._innerSpacing; s++) {
  978. MoveAndAdd (x, y, drawRange && isSet ? Style.RangeChar.Rune : Style.SpaceChar.Rune);
  979. if (isVertical) {
  980. y++;
  981. } else {
  982. x++;
  983. }
  984. }
  985. }
  986. }
  987. }
  988. var remaining = isVertical ? Bounds.Height - y : Bounds.Width - x;
  989. // Right Spacing
  990. if (_config._showEndSpacing) {
  991. Driver?.SetAttribute (isSet && _config._type == SliderType.RightRange ? Style.RangeChar.Attribute ?? normalAttr : Style.SpaceChar.Attribute ?? normalAttr);
  992. var rune = isSet && _config._type == SliderType.RightRange ? Style.RangeChar.Rune : Style.SpaceChar.Rune;
  993. for (var i = 0; i < remaining; i++) {
  994. MoveAndAdd (x, y, rune);
  995. if (isVertical) {
  996. y++;
  997. } else {
  998. x++;
  999. }
  1000. }
  1001. } else {
  1002. Driver?.SetAttribute (Style.EmptyChar.Attribute ?? normalAttr);
  1003. for (var i = 0; i < remaining; i++) {
  1004. MoveAndAdd (x, y, Style.EmptyChar.Rune);
  1005. if (isVertical) {
  1006. y++;
  1007. } else {
  1008. x++;
  1009. }
  1010. }
  1011. }
  1012. }
  1013. void DrawLegends ()
  1014. {
  1015. // Attributes
  1016. var normalAttr = new Attribute (Color.White, Color.Black);
  1017. var setAttr = new Attribute (Color.Black, Color.White);
  1018. var spaceAttr = normalAttr;
  1019. if (IsInitialized) {
  1020. normalAttr = Style.LegendAttributes.NormalAttribute ?? ColorScheme?.Normal ?? ColorScheme.Disabled;
  1021. setAttr = Style.LegendAttributes.SetAttribute ?? ColorScheme?.HotNormal ?? ColorScheme.Normal;
  1022. spaceAttr = Style.LegendAttributes.EmptyAttribute ?? normalAttr;
  1023. }
  1024. var isTextVertical = _config._legendsOrientation == Orientation.Vertical;
  1025. var isSet = _setOptions.Count > 0;
  1026. var x = 0;
  1027. var y = 0;
  1028. Move (x, y);
  1029. if (_config._sliderOrientation == Orientation.Horizontal && _config._legendsOrientation == Orientation.Vertical) {
  1030. x += _config._startSpacing;
  1031. }
  1032. if (_config._sliderOrientation == Orientation.Vertical && _config._legendsOrientation == Orientation.Horizontal) {
  1033. y += _config._startSpacing;
  1034. }
  1035. if (_config._sliderOrientation == Orientation.Horizontal) {
  1036. y += 1;
  1037. } else {
  1038. // Vertical
  1039. x += 1;
  1040. }
  1041. for (var i = 0; i < _options.Count; i++) {
  1042. var isOptionSet = false;
  1043. // Check if the Option is Set.
  1044. switch (_config._type) {
  1045. case SliderType.Single:
  1046. case SliderType.Multiple:
  1047. if (isSet && _setOptions.Contains (i)) {
  1048. isOptionSet = true;
  1049. }
  1050. break;
  1051. case SliderType.LeftRange:
  1052. if (isSet && i <= _setOptions [0]) {
  1053. isOptionSet = true;
  1054. }
  1055. break;
  1056. case SliderType.RightRange:
  1057. if (isSet && i >= _setOptions [0]) {
  1058. isOptionSet = true;
  1059. }
  1060. break;
  1061. case SliderType.Range when _setOptions.Count == 1:
  1062. if (isSet && i == _setOptions [0]) {
  1063. isOptionSet = true;
  1064. }
  1065. break;
  1066. case SliderType.Range:
  1067. if (isSet && (i >= _setOptions [0] && i <= _setOptions [1] || i >= _setOptions [1] && i <= _setOptions [0])) {
  1068. isOptionSet = true;
  1069. }
  1070. break;
  1071. }
  1072. // Text || Abbreviation
  1073. var text = string.Empty;
  1074. if (_config._showLegendsAbbr) {
  1075. text = _options [i].LegendAbbr.ToString () ?? new Rune (_options [i].Legend.First ()).ToString ();
  1076. } else {
  1077. text = _options [i].Legend;
  1078. }
  1079. switch (_config._sliderOrientation) {
  1080. case Orientation.Horizontal:
  1081. switch (_config._legendsOrientation) {
  1082. case Orientation.Horizontal:
  1083. text = AlignText (text, _config._innerSpacing + 1, TextAlignment.Centered);
  1084. break;
  1085. case Orientation.Vertical:
  1086. y = 1;
  1087. break;
  1088. }
  1089. break;
  1090. case Orientation.Vertical:
  1091. switch (_config._legendsOrientation) {
  1092. case Orientation.Horizontal:
  1093. x = 1;
  1094. break;
  1095. case Orientation.Vertical:
  1096. text = AlignText (text, _config._innerSpacing + 1, TextAlignment.Centered);
  1097. break;
  1098. }
  1099. break;
  1100. }
  1101. // Text
  1102. var legend_left_spaces_count = text.TakeWhile (e => e == ' ').Count ();
  1103. var legend_right_spaces_count = text.Reverse ().TakeWhile (e => e == ' ').Count ();
  1104. text = text.Trim ();
  1105. // TODO(jmperricone): Improve the Orientation check.
  1106. // Calculate Start Spacing
  1107. if (_config._sliderOrientation == _config._legendsOrientation) {
  1108. if (i == 0) {
  1109. // The spacing for the slider use the StartSpacing but...
  1110. // The spacing for the legends is the StartSpacing MINUS the total chars to the left of the first options.
  1111. // ●────●────●
  1112. // Hello Bye World
  1113. //
  1114. // chars_left is 2 for Hello => (5 - 1) / 2
  1115. //
  1116. // then the spacing is 2 for the slider but 0 for the legends.
  1117. var chars_left = (text.Length - 1) / 2;
  1118. legend_left_spaces_count = _config._startSpacing - chars_left;
  1119. }
  1120. // Option Left Spacing
  1121. if (isTextVertical) {
  1122. y += legend_left_spaces_count;
  1123. } else {
  1124. x += legend_left_spaces_count;
  1125. }
  1126. //Move (x, y);
  1127. }
  1128. // Legend
  1129. Driver?.SetAttribute (isOptionSet ? setAttr : normalAttr);
  1130. foreach (var c in text.EnumerateRunes ()) {
  1131. MoveAndAdd (x, y, c);
  1132. //Driver.AddRune (c);
  1133. if (isTextVertical) {
  1134. y += 1;
  1135. } else {
  1136. x += 1;
  1137. }
  1138. }
  1139. // Calculate End Spacing
  1140. if (i == _options.Count () - 1) {
  1141. // See Start Spacing explanation.
  1142. var chars_right = text.Length / 2;
  1143. legend_right_spaces_count = _config._endSpacing - chars_right;
  1144. }
  1145. // Option Right Spacing of Option
  1146. Driver?.SetAttribute (spaceAttr);
  1147. if (isTextVertical) {
  1148. y += legend_right_spaces_count;
  1149. } else {
  1150. x += legend_right_spaces_count;
  1151. }
  1152. if (_config._sliderOrientation == Orientation.Horizontal && _config._legendsOrientation == Orientation.Vertical) {
  1153. x += _config._innerSpacing + 1;
  1154. } else if (_config._sliderOrientation == Orientation.Vertical && _config._legendsOrientation == Orientation.Horizontal) {
  1155. y += _config._innerSpacing + 1;
  1156. }
  1157. }
  1158. }
  1159. #endregion
  1160. #region Keys and Mouse
  1161. // Mouse coordinates of current drag
  1162. Point? _dragPosition;
  1163. // Coordinates of where the "move cursor" is drawn (in OnDrawContent)
  1164. Point? _moveRenderPosition;
  1165. /// <inheritdoc/>
  1166. public override bool MouseEvent (MouseEvent mouseEvent)
  1167. {
  1168. // Note(jmperricone): Maybe we click to focus the cursor, and on next click we set the option.
  1169. // That will makes OptionFocused Event more relevant.
  1170. // (tig: I don't think so. Maybe an option if someone really wants it, but for now that
  1171. // adss to much friction to UI.
  1172. // TODO(jmperricone): Make Range Type work with mouse.
  1173. if (!(mouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked) ||
  1174. mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed) ||
  1175. mouseEvent.Flags.HasFlag (MouseFlags.ReportMousePosition) ||
  1176. mouseEvent.Flags.HasFlag (MouseFlags.Button1Released))) {
  1177. return false;
  1178. }
  1179. Point ClampMovePosition (Point position)
  1180. {
  1181. int Clamp (int value, int min, int max) => Math.Max (min, Math.Min (max, value));
  1182. if (Orientation == Orientation.Horizontal) {
  1183. var left = _config._startSpacing;
  1184. var width = _options.Count + (_options.Count - 1) * _config._innerSpacing;
  1185. var right = left + width - 1;
  1186. var clampedX = Clamp (position.X, left, right);
  1187. position = new Point (clampedX, 0);
  1188. } else {
  1189. var top = _config._startSpacing;
  1190. var height = _options.Count + (_options.Count - 1) * _config._innerSpacing;
  1191. var bottom = top + height - 1;
  1192. var clampedY = Clamp (position.Y, top, bottom);
  1193. position = new Point (0, clampedY);
  1194. }
  1195. return position;
  1196. }
  1197. SetFocus ();
  1198. if (!_dragPosition.HasValue && mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  1199. if (mouseEvent.Flags.HasFlag (MouseFlags.ReportMousePosition)) {
  1200. _dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  1201. _moveRenderPosition = ClampMovePosition ((Point)_dragPosition);
  1202. Application.GrabMouse (this);
  1203. }
  1204. SetNeedsDisplay ();
  1205. return true;
  1206. }
  1207. if (_dragPosition.HasValue && mouseEvent.Flags.HasFlag (MouseFlags.ReportMousePosition) && mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  1208. // Continue Drag
  1209. _dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  1210. _moveRenderPosition = ClampMovePosition ((Point)_dragPosition);
  1211. var success = false;
  1212. var option = 0;
  1213. // how far has user dragged from original location?
  1214. if (Orientation == Orientation.Horizontal) {
  1215. success = TryGetOptionByPosition (mouseEvent.X, 0, Math.Max (0, _config._innerSpacing / 2), out option);
  1216. } else {
  1217. success = TryGetOptionByPosition (0, mouseEvent.Y, Math.Max (0, _config._innerSpacing / 2), out option);
  1218. }
  1219. if (!_config._allowEmpty && success) {
  1220. if (!OnOptionFocused (option, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1221. SetFocusedOption ();
  1222. }
  1223. }
  1224. SetNeedsDisplay ();
  1225. return true;
  1226. }
  1227. if (_dragPosition.HasValue && mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) || mouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  1228. // End Drag
  1229. Application.UngrabMouse ();
  1230. _dragPosition = null;
  1231. _moveRenderPosition = null;
  1232. // TODO: Add func to calc distance between options to use as the MouseClickXOptionThreshold
  1233. var success = false;
  1234. var option = 0;
  1235. if (Orientation == Orientation.Horizontal) {
  1236. success = TryGetOptionByPosition (mouseEvent.X, 0, Math.Max (0, _config._innerSpacing / 2), out option);
  1237. } else {
  1238. success = TryGetOptionByPosition (0, mouseEvent.Y, Math.Max (0, _config._innerSpacing / 2), out option);
  1239. }
  1240. if (success) {
  1241. if (!OnOptionFocused (option, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1242. SetFocusedOption ();
  1243. }
  1244. }
  1245. SetNeedsDisplay ();
  1246. return true;
  1247. }
  1248. return false;
  1249. }
  1250. void SetCommands ()
  1251. {
  1252. AddCommand (Command.Right, () => MovePlus ());
  1253. AddCommand (Command.LineDown, () => MovePlus ());
  1254. AddCommand (Command.Left, () => MoveMinus ());
  1255. AddCommand (Command.LineUp, () => MoveMinus ());
  1256. AddCommand (Command.LeftHome, () => MoveStart ());
  1257. AddCommand (Command.RightEnd, () => MoveEnd ());
  1258. AddCommand (Command.RightExtend, () => ExtendPlus ());
  1259. AddCommand (Command.LeftExtend, () => ExtendMinus ());
  1260. AddCommand (Command.Accept, () => Set ());
  1261. SetKeyBindings ();
  1262. }
  1263. // This is called during initialization and anytime orientation changes
  1264. void SetKeyBindings ()
  1265. {
  1266. if (_config._sliderOrientation == Orientation.Horizontal) {
  1267. KeyBindings.Add (KeyCode.CursorRight, Command.Right);
  1268. KeyBindings.Remove (KeyCode.CursorDown);
  1269. KeyBindings.Add (KeyCode.CursorLeft, Command.Left);
  1270. KeyBindings.Remove (KeyCode.CursorUp);
  1271. KeyBindings.Add (KeyCode.CursorRight | KeyCode.CtrlMask, Command.RightExtend);
  1272. KeyBindings.Remove (KeyCode.CursorDown | KeyCode.CtrlMask);
  1273. KeyBindings.Add (KeyCode.CursorLeft | KeyCode.CtrlMask, Command.LeftExtend);
  1274. KeyBindings.Remove (KeyCode.CursorUp | KeyCode.CtrlMask);
  1275. } else {
  1276. KeyBindings.Remove (KeyCode.CursorRight);
  1277. KeyBindings.Add (KeyCode.CursorDown, Command.LineDown);
  1278. KeyBindings.Remove (KeyCode.CursorLeft);
  1279. KeyBindings.Add (KeyCode.CursorUp, Command.LineUp);
  1280. KeyBindings.Remove (KeyCode.CursorRight | KeyCode.CtrlMask);
  1281. KeyBindings.Add (KeyCode.CursorDown | KeyCode.CtrlMask, Command.RightExtend);
  1282. KeyBindings.Remove (KeyCode.CursorLeft | KeyCode.CtrlMask);
  1283. KeyBindings.Add (KeyCode.CursorUp | KeyCode.CtrlMask, Command.LeftExtend);
  1284. }
  1285. KeyBindings.Add (KeyCode.Home, Command.LeftHome);
  1286. KeyBindings.Add (KeyCode.End, Command.RightEnd);
  1287. KeyBindings.Add (KeyCode.Enter, Command.Accept);
  1288. KeyBindings.Add (KeyCode.Space, Command.Accept);
  1289. }
  1290. Dictionary<int, SliderOption<T>> GetSetOptionDictionary () => _setOptions.ToDictionary (e => e, e => _options [e]);
  1291. void SetFocusedOption ()
  1292. {
  1293. switch (_config._type) {
  1294. case SliderType.Single:
  1295. case SliderType.LeftRange:
  1296. case SliderType.RightRange:
  1297. if (_setOptions.Count == 1) {
  1298. var prev = _setOptions [0];
  1299. if (!_config._allowEmpty && prev == FocusedOption) {
  1300. break;
  1301. }
  1302. _setOptions.Clear ();
  1303. _options [FocusedOption].OnUnSet ();
  1304. if (FocusedOption != prev) {
  1305. _setOptions.Add (FocusedOption);
  1306. _options [FocusedOption].OnSet ();
  1307. }
  1308. } else {
  1309. _setOptions.Add (FocusedOption);
  1310. _options [FocusedOption].OnSet ();
  1311. }
  1312. // Raise slider changed event.
  1313. OnOptionsChanged ();
  1314. break;
  1315. case SliderType.Multiple:
  1316. if (_setOptions.Contains (FocusedOption)) {
  1317. if (!_config._allowEmpty && _setOptions.Count () == 1) {
  1318. break;
  1319. }
  1320. _setOptions.Remove (FocusedOption);
  1321. _options [FocusedOption].OnUnSet ();
  1322. } else {
  1323. _setOptions.Add (FocusedOption);
  1324. _options [FocusedOption].OnSet ();
  1325. }
  1326. OnOptionsChanged ();
  1327. break;
  1328. case SliderType.Range:
  1329. if (_config._rangeAllowSingle) {
  1330. if (_setOptions.Count == 1) {
  1331. var prev = _setOptions [0];
  1332. if (!_config._allowEmpty && prev == FocusedOption) {
  1333. break;
  1334. }
  1335. if (FocusedOption == prev) {
  1336. // un-set
  1337. _setOptions.Clear ();
  1338. _options [FocusedOption].OnUnSet ();
  1339. } else {
  1340. _setOptions [0] = FocusedOption;
  1341. _setOptions.Add (prev);
  1342. _setOptions.Sort ();
  1343. _options [FocusedOption].OnSet ();
  1344. }
  1345. } else if (_setOptions.Count == 0) {
  1346. _setOptions.Add (FocusedOption);
  1347. _options [FocusedOption].OnSet ();
  1348. } else {
  1349. // Extend/Shrink
  1350. if (FocusedOption < _setOptions [0]) {
  1351. // extend left
  1352. _options [_setOptions [0]].OnUnSet ();
  1353. _setOptions [0] = FocusedOption;
  1354. } else if (FocusedOption > _setOptions [1]) {
  1355. // extend right
  1356. _options [_setOptions [1]].OnUnSet ();
  1357. _setOptions [1] = FocusedOption;
  1358. } else if (FocusedOption >= _setOptions [0] && FocusedOption <= _setOptions [1]) {
  1359. if (FocusedOption < _lastFocusedOption) {
  1360. // shrink to the left
  1361. _options [_setOptions [1]].OnUnSet ();
  1362. _setOptions [1] = FocusedOption;
  1363. } else if (FocusedOption > _lastFocusedOption) {
  1364. // shrink to the right
  1365. _options [_setOptions [0]].OnUnSet ();
  1366. _setOptions [0] = FocusedOption;
  1367. }
  1368. if (_setOptions.Count > 1 && _setOptions [0] == _setOptions [1]) {
  1369. _setOptions.Clear ();
  1370. _setOptions.Add (FocusedOption);
  1371. }
  1372. }
  1373. }
  1374. } else {
  1375. if (_setOptions.Count == 1) {
  1376. var prev = _setOptions [0];
  1377. if (!_config._allowEmpty && prev == FocusedOption) {
  1378. break;
  1379. }
  1380. _setOptions [0] = FocusedOption;
  1381. _setOptions.Add (prev);
  1382. _setOptions.Sort ();
  1383. _options [FocusedOption].OnSet ();
  1384. } else if (_setOptions.Count == 0) {
  1385. _setOptions.Add (FocusedOption);
  1386. _options [FocusedOption].OnSet ();
  1387. var next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption - 1;
  1388. _setOptions.Add (next);
  1389. _options [next].OnSet ();
  1390. } else {
  1391. // Extend/Shrink
  1392. if (FocusedOption < _setOptions [0]) {
  1393. // extend left
  1394. _options [_setOptions [0]].OnUnSet ();
  1395. _setOptions [0] = FocusedOption;
  1396. } else if (FocusedOption > _setOptions [1]) {
  1397. // extend right
  1398. _options [_setOptions [1]].OnUnSet ();
  1399. _setOptions [1] = FocusedOption;
  1400. } else if (FocusedOption >= _setOptions [0] && FocusedOption <= _setOptions [1] && _setOptions [1] - _setOptions [0] > 1) {
  1401. if (FocusedOption < _lastFocusedOption) {
  1402. // shrink to the left
  1403. _options [_setOptions [1]].OnUnSet ();
  1404. _setOptions [1] = FocusedOption;
  1405. } else if (FocusedOption > _lastFocusedOption) {
  1406. // shrink to the right
  1407. _options [_setOptions [0]].OnUnSet ();
  1408. _setOptions [0] = FocusedOption;
  1409. }
  1410. }
  1411. //if (_setOptions.Count > 1 && _setOptions [0] == _setOptions [1]) {
  1412. // SetFocusedOption ();
  1413. //}
  1414. }
  1415. }
  1416. // Raise Slider Option Changed Event.
  1417. OnOptionsChanged ();
  1418. break;
  1419. default:
  1420. throw new ArgumentOutOfRangeException (_config._type.ToString ());
  1421. }
  1422. }
  1423. internal bool ExtendPlus ()
  1424. {
  1425. var next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption;
  1426. if (next != FocusedOption && !OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1427. SetFocusedOption ();
  1428. }
  1429. return true;
  1430. //// TODO: Support RangeMultiple
  1431. //if (_setOptions.Contains (FocusedOption)) {
  1432. // var next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption;
  1433. // if (!_setOptions.Contains (next)) {
  1434. // if (_config._type == SliderType.Range) {
  1435. // if (_setOptions.Count == 1) {
  1436. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1437. // _setOptions.Add (FocusedOption);
  1438. // _setOptions.Sort (); // Range Type
  1439. // OnOptionsChanged ();
  1440. // }
  1441. // } else if (_setOptions.Count == 2) {
  1442. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1443. // _setOptions [1] = FocusedOption;
  1444. // _setOptions.Sort (); // Range Type
  1445. // OnOptionsChanged ();
  1446. // }
  1447. // }
  1448. // } else {
  1449. // _setOptions.Remove (FocusedOption);
  1450. // // Note(jmperricone): We are setting the option here, do we send the OptionFocused Event too ?
  1451. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1452. // _setOptions.Add (FocusedOption);
  1453. // _setOptions.Sort (); // Range Type
  1454. // OnOptionsChanged ();
  1455. // }
  1456. // }
  1457. // } else {
  1458. // if (_config._type == SliderType.Range) {
  1459. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1460. // _setOptions.Clear();
  1461. // _setOptions.Add (FocusedOption);
  1462. // OnOptionsChanged ();
  1463. // }
  1464. // } else if (/*_settingRange == true ||*/ !AllowEmpty) {
  1465. // SetFocusedOption ();
  1466. // }
  1467. // }
  1468. //}
  1469. //return true;
  1470. }
  1471. internal bool ExtendMinus ()
  1472. {
  1473. var prev = FocusedOption > 0 ? FocusedOption - 1 : FocusedOption;
  1474. if (prev != FocusedOption && !OnOptionFocused (prev, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1475. SetFocusedOption ();
  1476. }
  1477. return true;
  1478. }
  1479. internal bool Set ()
  1480. {
  1481. SetFocusedOption ();
  1482. return true;
  1483. }
  1484. internal bool MovePlus ()
  1485. {
  1486. var cancelled = OnOptionFocused (FocusedOption + 1, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption));
  1487. if (cancelled) {
  1488. return false;
  1489. }
  1490. if (!AllowEmpty) {
  1491. SetFocusedOption ();
  1492. }
  1493. return true;
  1494. }
  1495. internal bool MoveMinus ()
  1496. {
  1497. var cancelled = OnOptionFocused (FocusedOption - 1, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption));
  1498. if (cancelled) {
  1499. return false;
  1500. }
  1501. if (!AllowEmpty) {
  1502. SetFocusedOption ();
  1503. }
  1504. return true;
  1505. }
  1506. internal bool MoveStart ()
  1507. {
  1508. if (OnOptionFocused (0, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1509. return false;
  1510. }
  1511. if (!AllowEmpty) {
  1512. SetFocusedOption ();
  1513. }
  1514. return true;
  1515. }
  1516. internal bool MoveEnd ()
  1517. {
  1518. if (OnOptionFocused (_options.Count - 1, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1519. return false;
  1520. }
  1521. if (!AllowEmpty) {
  1522. SetFocusedOption ();
  1523. }
  1524. return true;
  1525. }
  1526. #endregion
  1527. }