Slider.cs 66 KB

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