Slider.cs 63 KB

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