Slider.cs 47 KB

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