Slider.cs 47 KB

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