Slider.cs 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  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.Subviews);
  321. Height = Dim.Auto (Dim.DimAutoStyle.Subviews);
  322. }
  323. else
  324. {
  325. Width = ContentSize.Width;
  326. Height = ContentSize.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.Width - adornmentsThickness.Horizontal,
  653. CalcBestLength ()
  654. ),
  655. int.Min (
  656. SuperView.ContentSize.Height - adornmentsThickness.Vertical,
  657. CalcThickness ()
  658. )
  659. )
  660. );
  661. }
  662. else
  663. {
  664. IdealContentSize = new (
  665. new (
  666. int.Min (
  667. SuperView.ContentSize.Width - adornmentsThickness.Horizontal,
  668. CalcThickness ()
  669. ),
  670. int.Min (
  671. SuperView.ContentSize.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 void 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. }
  827. }
  828. }
  829. /// <inheritdoc/>
  830. public override void OnDrawContent (Rectangle viewport)
  831. {
  832. // TODO: make this more surgical to reduce repaint
  833. if (_options is null && _options.Count > 0)
  834. {
  835. return;
  836. }
  837. // Debug
  838. #if (DEBUG)
  839. Driver?.SetAttribute (new Attribute (Color.White, Color.Red));
  840. for (var y = 0; y < viewport.Height; y++)
  841. {
  842. for (var x = 0; x < viewport.Width; x++)
  843. {
  844. // MoveAndAdd (x, y, '·');
  845. }
  846. }
  847. #endif
  848. // Draw Slider
  849. DrawSlider ();
  850. // Draw Legends.
  851. if (_config._showLegends)
  852. {
  853. DrawLegends ();
  854. }
  855. if (_dragPosition.HasValue && _moveRenderPosition.HasValue)
  856. {
  857. AddRune (_moveRenderPosition.Value.X, _moveRenderPosition.Value.Y, Style.DragChar.Rune);
  858. }
  859. }
  860. private string AlignText (string text, int width, TextAlignment textAlignment)
  861. {
  862. if (text is null)
  863. {
  864. return "";
  865. }
  866. if (text.Length > width)
  867. {
  868. text = text [..width];
  869. }
  870. int w = width - text.Length;
  871. string s1 = new (' ', w / 2);
  872. string s2 = new (' ', w % 2);
  873. // Note: The formatter doesn't handle all of this ???
  874. switch (textAlignment)
  875. {
  876. case TextAlignment.Justified:
  877. return TextFormatter.Justify (text, width);
  878. case TextAlignment.Left:
  879. return text + s1 + s1 + s2;
  880. case TextAlignment.Centered:
  881. if (text.Length % 2 != 0)
  882. {
  883. return s1 + text + s1 + s2;
  884. }
  885. return s1 + s2 + text + s1;
  886. case TextAlignment.Right:
  887. return s1 + s1 + s2 + text;
  888. default:
  889. return text;
  890. }
  891. }
  892. private void DrawSlider ()
  893. {
  894. // TODO: be more surgical on clear
  895. Clear ();
  896. // Attributes
  897. var normalAttr = new Attribute (Color.White, Color.Black);
  898. var setAtrr = new Attribute (Color.Black, Color.White);
  899. if (IsInitialized)
  900. {
  901. normalAttr = ColorScheme?.Normal ?? Application.Current.ColorScheme.Normal;
  902. setAtrr = Style.SetChar.Attribute ?? ColorScheme.HotNormal;
  903. }
  904. bool isVertical = _config._sliderOrientation == Orientation.Vertical;
  905. bool isLegendsVertical = _config._legendsOrientation == Orientation.Vertical;
  906. bool isReverse = _config._sliderOrientation != _config._legendsOrientation;
  907. var x = 0;
  908. var y = 0;
  909. bool isSet = _setOptions.Count > 0;
  910. // Left Spacing
  911. if (_config._showEndSpacing && _config._startSpacing > 0)
  912. {
  913. Driver?.SetAttribute (
  914. isSet && _config._type == SliderType.LeftRange
  915. ? Style.RangeChar.Attribute ?? normalAttr
  916. : Style.SpaceChar.Attribute ?? normalAttr
  917. );
  918. Rune rune = isSet && _config._type == SliderType.LeftRange ? Style.RangeChar.Rune : Style.SpaceChar.Rune;
  919. for (var i = 0; i < _config._startSpacing; i++)
  920. {
  921. MoveAndAdd (x, y, rune);
  922. if (isVertical)
  923. {
  924. y++;
  925. }
  926. else
  927. {
  928. x++;
  929. }
  930. }
  931. }
  932. else
  933. {
  934. Driver?.SetAttribute (Style.EmptyChar.Attribute ?? normalAttr);
  935. for (var i = 0; i < _config._startSpacing; i++)
  936. {
  937. MoveAndAdd (x, y, Style.EmptyChar.Rune);
  938. if (isVertical)
  939. {
  940. y++;
  941. }
  942. else
  943. {
  944. x++;
  945. }
  946. }
  947. }
  948. // Slider
  949. if (_options.Count > 0)
  950. {
  951. for (var i = 0; i < _options.Count; i++)
  952. {
  953. var drawRange = false;
  954. if (isSet)
  955. {
  956. switch (_config._type)
  957. {
  958. case SliderType.LeftRange when i <= _setOptions [0]:
  959. drawRange = i < _setOptions [0];
  960. break;
  961. case SliderType.RightRange when i >= _setOptions [0]:
  962. drawRange = i >= _setOptions [0];
  963. break;
  964. case SliderType.Range when _setOptions.Count == 1:
  965. drawRange = false;
  966. break;
  967. case SliderType.Range when _setOptions.Count == 2:
  968. if ((i >= _setOptions [0] && i <= _setOptions [1])
  969. || (i >= _setOptions [1] && i <= _setOptions [0]))
  970. {
  971. drawRange = (i >= _setOptions [0] && i < _setOptions [1])
  972. || (i >= _setOptions [1] && i < _setOptions [0]);
  973. }
  974. break;
  975. }
  976. }
  977. // Draw Option
  978. Driver?.SetAttribute (
  979. isSet && _setOptions.Contains (i) ? Style.SetChar.Attribute ?? setAtrr :
  980. drawRange ? Style.RangeChar.Attribute ?? setAtrr : Style.OptionChar.Attribute ?? normalAttr
  981. );
  982. // Note(jmperricone): Maybe only for curses, windows inverts actual colors, while curses inverts bg with fg.
  983. //if (Application.Driver is CursesDriver) {
  984. // if (FocusedOption == i && HasFocus) {
  985. // Driver.SetAttribute (ColorScheme.Focus);
  986. // }
  987. //}
  988. Rune rune = drawRange ? Style.RangeChar.Rune : Style.OptionChar.Rune;
  989. if (isSet)
  990. {
  991. if (_setOptions [0] == i)
  992. {
  993. rune = Style.StartRangeChar.Rune;
  994. }
  995. else if (_setOptions.Count > 1 && _setOptions [1] == i)
  996. {
  997. rune = Style.EndRangeChar.Rune;
  998. }
  999. else if (_setOptions.Contains (i))
  1000. {
  1001. rune = Style.SetChar.Rune;
  1002. }
  1003. }
  1004. MoveAndAdd (x, y, rune);
  1005. if (isVertical)
  1006. {
  1007. y++;
  1008. }
  1009. else
  1010. {
  1011. x++;
  1012. }
  1013. // Draw Spacing
  1014. if (_config._showEndSpacing || i < _options.Count - 1)
  1015. {
  1016. // Skip if is the Last Spacing.
  1017. Driver?.SetAttribute (
  1018. drawRange && isSet
  1019. ? Style.RangeChar.Attribute ?? setAtrr
  1020. : Style.SpaceChar.Attribute ?? normalAttr
  1021. );
  1022. for (var s = 0; s < _config._innerSpacing; s++)
  1023. {
  1024. MoveAndAdd (x, y, drawRange && isSet ? Style.RangeChar.Rune : Style.SpaceChar.Rune);
  1025. if (isVertical)
  1026. {
  1027. y++;
  1028. }
  1029. else
  1030. {
  1031. x++;
  1032. }
  1033. }
  1034. }
  1035. }
  1036. }
  1037. int remaining = isVertical ? Viewport.Height - y : Viewport.Width - x;
  1038. // Right Spacing
  1039. if (_config._showEndSpacing)
  1040. {
  1041. Driver?.SetAttribute (
  1042. isSet && _config._type == SliderType.RightRange
  1043. ? Style.RangeChar.Attribute ?? normalAttr
  1044. : Style.SpaceChar.Attribute ?? normalAttr
  1045. );
  1046. Rune rune = isSet && _config._type == SliderType.RightRange ? Style.RangeChar.Rune : Style.SpaceChar.Rune;
  1047. for (var i = 0; i < remaining; i++)
  1048. {
  1049. MoveAndAdd (x, y, rune);
  1050. if (isVertical)
  1051. {
  1052. y++;
  1053. }
  1054. else
  1055. {
  1056. x++;
  1057. }
  1058. }
  1059. }
  1060. else
  1061. {
  1062. Driver?.SetAttribute (Style.EmptyChar.Attribute ?? normalAttr);
  1063. for (var i = 0; i < remaining; i++)
  1064. {
  1065. MoveAndAdd (x, y, Style.EmptyChar.Rune);
  1066. if (isVertical)
  1067. {
  1068. y++;
  1069. }
  1070. else
  1071. {
  1072. x++;
  1073. }
  1074. }
  1075. }
  1076. }
  1077. private void DrawLegends ()
  1078. {
  1079. // Attributes
  1080. var normalAttr = new Attribute (Color.White, Color.Black);
  1081. var setAttr = new Attribute (Color.Black, Color.White);
  1082. Attribute spaceAttr = normalAttr;
  1083. if (IsInitialized)
  1084. {
  1085. normalAttr = Style.LegendAttributes.NormalAttribute ?? ColorScheme?.Normal ?? ColorScheme.Disabled;
  1086. setAttr = Style.LegendAttributes.SetAttribute ?? ColorScheme?.HotNormal ?? ColorScheme.Normal;
  1087. spaceAttr = Style.LegendAttributes.EmptyAttribute ?? normalAttr;
  1088. }
  1089. bool isTextVertical = _config._legendsOrientation == Orientation.Vertical;
  1090. bool isSet = _setOptions.Count > 0;
  1091. var x = 0;
  1092. var y = 0;
  1093. Move (x, y);
  1094. if (_config._sliderOrientation == Orientation.Horizontal
  1095. && _config._legendsOrientation == Orientation.Vertical)
  1096. {
  1097. x += _config._startSpacing;
  1098. }
  1099. if (_config._sliderOrientation == Orientation.Vertical
  1100. && _config._legendsOrientation == Orientation.Horizontal)
  1101. {
  1102. y += _config._startSpacing;
  1103. }
  1104. if (_config._sliderOrientation == Orientation.Horizontal)
  1105. {
  1106. y += 1;
  1107. }
  1108. else
  1109. {
  1110. // Vertical
  1111. x += 1;
  1112. }
  1113. for (var i = 0; i < _options.Count; i++)
  1114. {
  1115. var isOptionSet = false;
  1116. // Check if the Option is Set.
  1117. switch (_config._type)
  1118. {
  1119. case SliderType.Single:
  1120. case SliderType.Multiple:
  1121. if (isSet && _setOptions.Contains (i))
  1122. {
  1123. isOptionSet = true;
  1124. }
  1125. break;
  1126. case SliderType.LeftRange:
  1127. if (isSet && i <= _setOptions [0])
  1128. {
  1129. isOptionSet = true;
  1130. }
  1131. break;
  1132. case SliderType.RightRange:
  1133. if (isSet && i >= _setOptions [0])
  1134. {
  1135. isOptionSet = true;
  1136. }
  1137. break;
  1138. case SliderType.Range when _setOptions.Count == 1:
  1139. if (isSet && i == _setOptions [0])
  1140. {
  1141. isOptionSet = true;
  1142. }
  1143. break;
  1144. case SliderType.Range:
  1145. if (isSet
  1146. && ((i >= _setOptions [0] && i <= _setOptions [1])
  1147. || (i >= _setOptions [1] && i <= _setOptions [0])))
  1148. {
  1149. isOptionSet = true;
  1150. }
  1151. break;
  1152. }
  1153. // Text || Abbreviation
  1154. var text = string.Empty;
  1155. if (_config._showLegendsAbbr)
  1156. {
  1157. text = _options [i].LegendAbbr.ToString () ?? new Rune (_options [i].Legend.First ()).ToString ();
  1158. }
  1159. else
  1160. {
  1161. text = _options [i].Legend;
  1162. }
  1163. switch (_config._sliderOrientation)
  1164. {
  1165. case Orientation.Horizontal:
  1166. switch (_config._legendsOrientation)
  1167. {
  1168. case Orientation.Horizontal:
  1169. text = AlignText (text, _config._innerSpacing + 1, TextAlignment.Centered);
  1170. break;
  1171. case Orientation.Vertical:
  1172. y = 1;
  1173. break;
  1174. }
  1175. break;
  1176. case Orientation.Vertical:
  1177. switch (_config._legendsOrientation)
  1178. {
  1179. case Orientation.Horizontal:
  1180. x = 1;
  1181. break;
  1182. case Orientation.Vertical:
  1183. text = AlignText (text, _config._innerSpacing + 1, TextAlignment.Centered);
  1184. break;
  1185. }
  1186. break;
  1187. }
  1188. // Text
  1189. int legend_left_spaces_count = text.TakeWhile (e => e == ' ').Count ();
  1190. int legend_right_spaces_count = text.Reverse ().TakeWhile (e => e == ' ').Count ();
  1191. text = text.Trim ();
  1192. // TODO(jmperricone): Improve the Orientation check.
  1193. // Calculate Start Spacing
  1194. if (_config._sliderOrientation == _config._legendsOrientation)
  1195. {
  1196. if (i == 0)
  1197. {
  1198. // The spacing for the slider use the StartSpacing but...
  1199. // The spacing for the legends is the StartSpacing MINUS the total chars to the left of the first options.
  1200. // ●────●────●
  1201. // Hello Bye World
  1202. //
  1203. // chars_left is 2 for Hello => (5 - 1) / 2
  1204. //
  1205. // then the spacing is 2 for the slider but 0 for the legends.
  1206. int chars_left = (text.Length - 1) / 2;
  1207. legend_left_spaces_count = _config._startSpacing - chars_left;
  1208. }
  1209. // Option Left Spacing
  1210. if (isTextVertical)
  1211. {
  1212. y += legend_left_spaces_count;
  1213. }
  1214. else
  1215. {
  1216. x += legend_left_spaces_count;
  1217. }
  1218. //Move (x, y);
  1219. }
  1220. // Legend
  1221. Driver?.SetAttribute (isOptionSet ? setAttr : normalAttr);
  1222. foreach (Rune c in text.EnumerateRunes ())
  1223. {
  1224. MoveAndAdd (x, y, c);
  1225. //Driver.AddRune (c);
  1226. if (isTextVertical)
  1227. {
  1228. y += 1;
  1229. }
  1230. else
  1231. {
  1232. x += 1;
  1233. }
  1234. }
  1235. // Calculate End Spacing
  1236. if (i == _options.Count () - 1)
  1237. {
  1238. // See Start Spacing explanation.
  1239. int chars_right = text.Length / 2;
  1240. legend_right_spaces_count = _config._endSpacing - chars_right;
  1241. }
  1242. // Option Right Spacing of Option
  1243. Driver?.SetAttribute (spaceAttr);
  1244. if (isTextVertical)
  1245. {
  1246. y += legend_right_spaces_count;
  1247. }
  1248. else
  1249. {
  1250. x += legend_right_spaces_count;
  1251. }
  1252. if (_config._sliderOrientation == Orientation.Horizontal
  1253. && _config._legendsOrientation == Orientation.Vertical)
  1254. {
  1255. x += _config._innerSpacing + 1;
  1256. }
  1257. else if (_config._sliderOrientation == Orientation.Vertical
  1258. && _config._legendsOrientation == Orientation.Horizontal)
  1259. {
  1260. y += _config._innerSpacing + 1;
  1261. }
  1262. }
  1263. }
  1264. #endregion
  1265. #region Keys and Mouse
  1266. // Mouse coordinates of current drag
  1267. private Point? _dragPosition;
  1268. // Coordinates of where the "move cursor" is drawn (in OnDrawContent)
  1269. private Point? _moveRenderPosition;
  1270. /// <inheritdoc/>
  1271. protected internal override bool OnMouseEvent (MouseEvent mouseEvent)
  1272. {
  1273. // Note(jmperricone): Maybe we click to focus the cursor, and on next click we set the option.
  1274. // That will makes OptionFocused Event more relevant.
  1275. // (tig: I don't think so. Maybe an option if someone really wants it, but for now that
  1276. // adss to much friction to UI.
  1277. // TODO(jmperricone): Make Range Type work with mouse.
  1278. if (!(mouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked)
  1279. || mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed)
  1280. || mouseEvent.Flags.HasFlag (MouseFlags.ReportMousePosition)
  1281. || mouseEvent.Flags.HasFlag (MouseFlags.Button1Released)))
  1282. {
  1283. return false;
  1284. }
  1285. Point ClampMovePosition (Point position)
  1286. {
  1287. int Clamp (int value, int min, int max) { return Math.Max (min, Math.Min (max, value)); }
  1288. if (Orientation == Orientation.Horizontal)
  1289. {
  1290. int left = _config._startSpacing;
  1291. int width = _options.Count + (_options.Count - 1) * _config._innerSpacing;
  1292. int right = left + width - 1;
  1293. int clampedX = Clamp (position.X, left, right);
  1294. position = new Point (clampedX, 0);
  1295. }
  1296. else
  1297. {
  1298. int top = _config._startSpacing;
  1299. int height = _options.Count + (_options.Count - 1) * _config._innerSpacing;
  1300. int bottom = top + height - 1;
  1301. int clampedY = Clamp (position.Y, top, bottom);
  1302. position = new Point (0, clampedY);
  1303. }
  1304. return position;
  1305. }
  1306. SetFocus ();
  1307. if (!_dragPosition.HasValue && mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed))
  1308. {
  1309. if (mouseEvent.Flags.HasFlag (MouseFlags.ReportMousePosition))
  1310. {
  1311. _dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  1312. _moveRenderPosition = ClampMovePosition ((Point)_dragPosition);
  1313. Application.GrabMouse (this);
  1314. }
  1315. SetNeedsDisplay ();
  1316. return true;
  1317. }
  1318. if (_dragPosition.HasValue
  1319. && mouseEvent.Flags.HasFlag (MouseFlags.ReportMousePosition)
  1320. && mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed))
  1321. {
  1322. // Continue Drag
  1323. _dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  1324. _moveRenderPosition = ClampMovePosition ((Point)_dragPosition);
  1325. var success = false;
  1326. var option = 0;
  1327. // how far has user dragged from original location?
  1328. if (Orientation == Orientation.Horizontal)
  1329. {
  1330. success = TryGetOptionByPosition (mouseEvent.X, 0, Math.Max (0, _config._innerSpacing / 2), out option);
  1331. }
  1332. else
  1333. {
  1334. success = TryGetOptionByPosition (0, mouseEvent.Y, Math.Max (0, _config._innerSpacing / 2), out option);
  1335. }
  1336. if (!_config._allowEmpty && success)
  1337. {
  1338. if (!OnOptionFocused (option, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption)))
  1339. {
  1340. SetFocusedOption ();
  1341. }
  1342. }
  1343. SetNeedsDisplay ();
  1344. return true;
  1345. }
  1346. if ((_dragPosition.HasValue && mouseEvent.Flags.HasFlag (MouseFlags.Button1Released))
  1347. || mouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked))
  1348. {
  1349. // End Drag
  1350. Application.UngrabMouse ();
  1351. _dragPosition = null;
  1352. _moveRenderPosition = null;
  1353. // TODO: Add func to calc distance between options to use as the MouseClickXOptionThreshold
  1354. var success = false;
  1355. var option = 0;
  1356. if (Orientation == Orientation.Horizontal)
  1357. {
  1358. success = TryGetOptionByPosition (mouseEvent.X, 0, Math.Max (0, _config._innerSpacing / 2), out option);
  1359. }
  1360. else
  1361. {
  1362. success = TryGetOptionByPosition (0, mouseEvent.Y, Math.Max (0, _config._innerSpacing / 2), out option);
  1363. }
  1364. if (success)
  1365. {
  1366. if (!OnOptionFocused (option, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption)))
  1367. {
  1368. SetFocusedOption ();
  1369. }
  1370. }
  1371. SetNeedsDisplay ();
  1372. return true;
  1373. }
  1374. return false;
  1375. }
  1376. private void SetCommands ()
  1377. {
  1378. AddCommand (Command.Right, () => MovePlus ());
  1379. AddCommand (Command.LineDown, () => MovePlus ());
  1380. AddCommand (Command.Left, () => MoveMinus ());
  1381. AddCommand (Command.LineUp, () => MoveMinus ());
  1382. AddCommand (Command.LeftHome, () => MoveStart ());
  1383. AddCommand (Command.RightEnd, () => MoveEnd ());
  1384. AddCommand (Command.RightExtend, () => ExtendPlus ());
  1385. AddCommand (Command.LeftExtend, () => ExtendMinus ());
  1386. AddCommand (Command.Accept, () => Set ());
  1387. SetKeyBindings ();
  1388. }
  1389. // This is called during initialization and anytime orientation changes
  1390. private void SetKeyBindings ()
  1391. {
  1392. if (_config._sliderOrientation == Orientation.Horizontal)
  1393. {
  1394. KeyBindings.Add (Key.CursorRight, Command.Right);
  1395. KeyBindings.Remove (Key.CursorDown);
  1396. KeyBindings.Add (Key.CursorLeft, Command.Left);
  1397. KeyBindings.Remove (Key.CursorUp);
  1398. KeyBindings.Add (Key.CursorRight.WithCtrl, Command.RightExtend);
  1399. KeyBindings.Remove (Key.CursorDown.WithCtrl);
  1400. KeyBindings.Add (Key.CursorLeft.WithCtrl, Command.LeftExtend);
  1401. KeyBindings.Remove (Key.CursorUp.WithCtrl);
  1402. }
  1403. else
  1404. {
  1405. KeyBindings.Remove (Key.CursorRight);
  1406. KeyBindings.Add (Key.CursorDown, Command.LineDown);
  1407. KeyBindings.Remove (Key.CursorLeft);
  1408. KeyBindings.Add (Key.CursorUp, Command.LineUp);
  1409. KeyBindings.Remove (Key.CursorRight.WithCtrl);
  1410. KeyBindings.Add (Key.CursorDown.WithCtrl, Command.RightExtend);
  1411. KeyBindings.Remove (Key.CursorLeft.WithCtrl);
  1412. KeyBindings.Add (Key.CursorUp.WithCtrl, Command.LeftExtend);
  1413. }
  1414. KeyBindings.Add (Key.Home, Command.LeftHome);
  1415. KeyBindings.Add (Key.End, Command.RightEnd);
  1416. KeyBindings.Add (Key.Enter, Command.Accept);
  1417. KeyBindings.Add (Key.Space, Command.Accept);
  1418. }
  1419. private Dictionary<int, SliderOption<T>> GetSetOptionDictionary () { return _setOptions.ToDictionary (e => e, e => _options [e]); }
  1420. private void SetFocusedOption ()
  1421. {
  1422. switch (_config._type)
  1423. {
  1424. case SliderType.Single:
  1425. case SliderType.LeftRange:
  1426. case SliderType.RightRange:
  1427. if (_setOptions.Count == 1)
  1428. {
  1429. int prev = _setOptions [0];
  1430. if (!_config._allowEmpty && prev == FocusedOption)
  1431. {
  1432. break;
  1433. }
  1434. _setOptions.Clear ();
  1435. _options [FocusedOption].OnUnSet ();
  1436. if (FocusedOption != prev)
  1437. {
  1438. _setOptions.Add (FocusedOption);
  1439. _options [FocusedOption].OnSet ();
  1440. }
  1441. }
  1442. else
  1443. {
  1444. _setOptions.Add (FocusedOption);
  1445. _options [FocusedOption].OnSet ();
  1446. }
  1447. // Raise slider changed event.
  1448. OnOptionsChanged ();
  1449. break;
  1450. case SliderType.Multiple:
  1451. if (_setOptions.Contains (FocusedOption))
  1452. {
  1453. if (!_config._allowEmpty && _setOptions.Count () == 1)
  1454. {
  1455. break;
  1456. }
  1457. _setOptions.Remove (FocusedOption);
  1458. _options [FocusedOption].OnUnSet ();
  1459. }
  1460. else
  1461. {
  1462. _setOptions.Add (FocusedOption);
  1463. _options [FocusedOption].OnSet ();
  1464. }
  1465. OnOptionsChanged ();
  1466. break;
  1467. case SliderType.Range:
  1468. if (_config._rangeAllowSingle)
  1469. {
  1470. if (_setOptions.Count == 1)
  1471. {
  1472. int prev = _setOptions [0];
  1473. if (!_config._allowEmpty && prev == FocusedOption)
  1474. {
  1475. break;
  1476. }
  1477. if (FocusedOption == prev)
  1478. {
  1479. // un-set
  1480. _setOptions.Clear ();
  1481. _options [FocusedOption].OnUnSet ();
  1482. }
  1483. else
  1484. {
  1485. _setOptions [0] = FocusedOption;
  1486. _setOptions.Add (prev);
  1487. _setOptions.Sort ();
  1488. _options [FocusedOption].OnSet ();
  1489. }
  1490. }
  1491. else if (_setOptions.Count == 0)
  1492. {
  1493. _setOptions.Add (FocusedOption);
  1494. _options [FocusedOption].OnSet ();
  1495. }
  1496. else
  1497. {
  1498. // Extend/Shrink
  1499. if (FocusedOption < _setOptions [0])
  1500. {
  1501. // extend left
  1502. _options [_setOptions [0]].OnUnSet ();
  1503. _setOptions [0] = FocusedOption;
  1504. }
  1505. else if (FocusedOption > _setOptions [1])
  1506. {
  1507. // extend right
  1508. _options [_setOptions [1]].OnUnSet ();
  1509. _setOptions [1] = FocusedOption;
  1510. }
  1511. else if (FocusedOption >= _setOptions [0] && FocusedOption <= _setOptions [1])
  1512. {
  1513. if (FocusedOption < _lastFocusedOption)
  1514. {
  1515. // shrink to the left
  1516. _options [_setOptions [1]].OnUnSet ();
  1517. _setOptions [1] = FocusedOption;
  1518. }
  1519. else if (FocusedOption > _lastFocusedOption)
  1520. {
  1521. // shrink to the right
  1522. _options [_setOptions [0]].OnUnSet ();
  1523. _setOptions [0] = FocusedOption;
  1524. }
  1525. if (_setOptions.Count > 1 && _setOptions [0] == _setOptions [1])
  1526. {
  1527. _setOptions.Clear ();
  1528. _setOptions.Add (FocusedOption);
  1529. }
  1530. }
  1531. }
  1532. }
  1533. else
  1534. {
  1535. if (_setOptions.Count == 1)
  1536. {
  1537. int prev = _setOptions [0];
  1538. if (!_config._allowEmpty && prev == FocusedOption)
  1539. {
  1540. break;
  1541. }
  1542. _setOptions [0] = FocusedOption;
  1543. _setOptions.Add (prev);
  1544. _setOptions.Sort ();
  1545. _options [FocusedOption].OnSet ();
  1546. }
  1547. else if (_setOptions.Count == 0)
  1548. {
  1549. _setOptions.Add (FocusedOption);
  1550. _options [FocusedOption].OnSet ();
  1551. int next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption - 1;
  1552. _setOptions.Add (next);
  1553. _options [next].OnSet ();
  1554. }
  1555. else
  1556. {
  1557. // Extend/Shrink
  1558. if (FocusedOption < _setOptions [0])
  1559. {
  1560. // extend left
  1561. _options [_setOptions [0]].OnUnSet ();
  1562. _setOptions [0] = FocusedOption;
  1563. }
  1564. else if (FocusedOption > _setOptions [1])
  1565. {
  1566. // extend right
  1567. _options [_setOptions [1]].OnUnSet ();
  1568. _setOptions [1] = FocusedOption;
  1569. }
  1570. else if (FocusedOption >= _setOptions [0]
  1571. && FocusedOption <= _setOptions [1]
  1572. && _setOptions [1] - _setOptions [0] > 1)
  1573. {
  1574. if (FocusedOption < _lastFocusedOption)
  1575. {
  1576. // shrink to the left
  1577. _options [_setOptions [1]].OnUnSet ();
  1578. _setOptions [1] = FocusedOption;
  1579. }
  1580. else if (FocusedOption > _lastFocusedOption)
  1581. {
  1582. // shrink to the right
  1583. _options [_setOptions [0]].OnUnSet ();
  1584. _setOptions [0] = FocusedOption;
  1585. }
  1586. }
  1587. //if (_setOptions.Count > 1 && _setOptions [0] == _setOptions [1]) {
  1588. // SetFocusedOption ();
  1589. //}
  1590. }
  1591. }
  1592. // Raise Slider Option Changed Event.
  1593. OnOptionsChanged ();
  1594. break;
  1595. default:
  1596. throw new ArgumentOutOfRangeException (_config._type.ToString ());
  1597. }
  1598. }
  1599. internal bool ExtendPlus ()
  1600. {
  1601. int next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption;
  1602. if (next != FocusedOption
  1603. && !OnOptionFocused (
  1604. next,
  1605. new SliderEventArgs<T> (
  1606. GetSetOptionDictionary (),
  1607. FocusedOption
  1608. )
  1609. ))
  1610. {
  1611. SetFocusedOption ();
  1612. }
  1613. return true;
  1614. //// TODO: Support RangeMultiple
  1615. //if (_setOptions.Contains (FocusedOption)) {
  1616. // var next = FocusedOption < _options.Count - 1 ? FocusedOption + 1 : FocusedOption;
  1617. // if (!_setOptions.Contains (next)) {
  1618. // if (_config._type == SliderType.Range) {
  1619. // if (_setOptions.Count == 1) {
  1620. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1621. // _setOptions.Add (FocusedOption);
  1622. // _setOptions.Sort (); // Range Type
  1623. // OnOptionsChanged ();
  1624. // }
  1625. // } else if (_setOptions.Count == 2) {
  1626. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1627. // _setOptions [1] = FocusedOption;
  1628. // _setOptions.Sort (); // Range Type
  1629. // OnOptionsChanged ();
  1630. // }
  1631. // }
  1632. // } else {
  1633. // _setOptions.Remove (FocusedOption);
  1634. // // Note(jmperricone): We are setting the option here, do we send the OptionFocused Event too ?
  1635. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1636. // _setOptions.Add (FocusedOption);
  1637. // _setOptions.Sort (); // Range Type
  1638. // OnOptionsChanged ();
  1639. // }
  1640. // }
  1641. // } else {
  1642. // if (_config._type == SliderType.Range) {
  1643. // if (!OnOptionFocused (next, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption))) {
  1644. // _setOptions.Clear();
  1645. // _setOptions.Add (FocusedOption);
  1646. // OnOptionsChanged ();
  1647. // }
  1648. // } else if (/*_settingRange == true ||*/ !AllowEmpty) {
  1649. // SetFocusedOption ();
  1650. // }
  1651. // }
  1652. //}
  1653. //return true;
  1654. }
  1655. internal bool ExtendMinus ()
  1656. {
  1657. int prev = FocusedOption > 0 ? FocusedOption - 1 : FocusedOption;
  1658. if (prev != FocusedOption
  1659. && !OnOptionFocused (
  1660. prev,
  1661. new SliderEventArgs<T> (
  1662. GetSetOptionDictionary (),
  1663. FocusedOption
  1664. )
  1665. ))
  1666. {
  1667. SetFocusedOption ();
  1668. }
  1669. return true;
  1670. }
  1671. internal bool Set ()
  1672. {
  1673. SetFocusedOption ();
  1674. return true;
  1675. }
  1676. internal bool MovePlus ()
  1677. {
  1678. bool cancelled = OnOptionFocused (
  1679. FocusedOption + 1,
  1680. new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption)
  1681. );
  1682. if (cancelled)
  1683. {
  1684. return false;
  1685. }
  1686. if (!AllowEmpty)
  1687. {
  1688. SetFocusedOption ();
  1689. }
  1690. return true;
  1691. }
  1692. internal bool MoveMinus ()
  1693. {
  1694. bool cancelled = OnOptionFocused (
  1695. FocusedOption - 1,
  1696. new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption)
  1697. );
  1698. if (cancelled)
  1699. {
  1700. return false;
  1701. }
  1702. if (!AllowEmpty)
  1703. {
  1704. SetFocusedOption ();
  1705. }
  1706. return true;
  1707. }
  1708. internal bool MoveStart ()
  1709. {
  1710. if (OnOptionFocused (0, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption)))
  1711. {
  1712. return false;
  1713. }
  1714. if (!AllowEmpty)
  1715. {
  1716. SetFocusedOption ();
  1717. }
  1718. return true;
  1719. }
  1720. internal bool MoveEnd ()
  1721. {
  1722. if (OnOptionFocused (_options.Count - 1, new SliderEventArgs<T> (GetSetOptionDictionary (), FocusedOption)))
  1723. {
  1724. return false;
  1725. }
  1726. if (!AllowEmpty)
  1727. {
  1728. SetFocusedOption ();
  1729. }
  1730. return true;
  1731. }
  1732. #endregion
  1733. }