2
0

Slider.cs 63 KB

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