RadioGroup.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. using NStack;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. namespace Terminal.Gui {
  6. /// <summary>
  7. /// Displays a group of labels each with a selected indicator. Only one of those can be selected at a given time.
  8. /// </summary>
  9. public class RadioGroup : View {
  10. int selected = -1;
  11. int cursor;
  12. DisplayModeLayout displayMode;
  13. int horizontalSpace = 2;
  14. List<(int pos, int length)> horizontal;
  15. /// <summary>
  16. /// Initializes a new instance of the <see cref="RadioGroup"/> class using <see cref="LayoutStyle.Computed"/> layout.
  17. /// </summary>
  18. public RadioGroup () : this (radioLabels: new ustring [] { }) { }
  19. /// <summary>
  20. /// Initializes a new instance of the <see cref="RadioGroup"/> class using <see cref="LayoutStyle.Computed"/> layout.
  21. /// </summary>
  22. /// <param name="radioLabels">The radio labels; an array of strings that can contain hotkeys using an underscore before the letter.</param>
  23. /// <param name="selected">The index of the item to be selected, the value is clamped to the number of items.</param>
  24. public RadioGroup (ustring [] radioLabels, int selected = 0) : base ()
  25. {
  26. Initialize (Rect.Empty, radioLabels, selected);
  27. }
  28. /// <summary>
  29. /// Initializes a new instance of the <see cref="RadioGroup"/> class using <see cref="LayoutStyle.Absolute"/> layout.
  30. /// </summary>
  31. /// <param name="rect">Boundaries for the radio group.</param>
  32. /// <param name="radioLabels">The radio labels; an array of strings that can contain hotkeys using an underscore before the letter.</param>
  33. /// <param name="selected">The index of item to be selected, the value is clamped to the number of items.</param>
  34. public RadioGroup (Rect rect, ustring [] radioLabels, int selected = 0) : base (rect)
  35. {
  36. Initialize (rect, radioLabels, selected);
  37. }
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="RadioGroup"/> class using <see cref="LayoutStyle.Absolute"/> layout.
  40. /// The <see cref="View"/> frame is computed from the provided radio labels.
  41. /// </summary>
  42. /// <param name="x">The x coordinate.</param>
  43. /// <param name="y">The y coordinate.</param>
  44. /// <param name="radioLabels">The radio labels; an array of strings that can contain hotkeys using an underscore before the letter.</param>
  45. /// <param name="selected">The item to be selected, the value is clamped to the number of items.</param>
  46. public RadioGroup (int x, int y, ustring [] radioLabels, int selected = 0) :
  47. this (MakeRect (x, y, radioLabels != null ? radioLabels.ToList () : null), radioLabels, selected)
  48. { }
  49. void Initialize (Rect rect, ustring [] radioLabels, int selected)
  50. {
  51. if (radioLabels == null) {
  52. this.radioLabels = new List<ustring> ();
  53. } else {
  54. this.radioLabels = radioLabels.ToList ();
  55. }
  56. this.selected = selected;
  57. if (rect == Rect.Empty) {
  58. SetWidthHeight (this.radioLabels);
  59. } else {
  60. Frame = rect;
  61. }
  62. CanFocus = true;
  63. // Things this view knows how to do
  64. AddCommand (Command.LineUp, () => { MoveUp (); return true; });
  65. AddCommand (Command.LineDown, () => { MoveDown (); return true; });
  66. AddCommand (Command.TopHome, () => { MoveHome (); return true; });
  67. AddCommand (Command.BottomEnd, () => { MoveEnd (); return true; });
  68. AddCommand (Command.Accept, () => { SelectItem (); return true; });
  69. // Default keybindings for this view
  70. AddKeyBinding (Key.CursorUp, Command.LineUp);
  71. AddKeyBinding (Key.CursorDown, Command.LineDown);
  72. AddKeyBinding (Key.Home, Command.TopHome);
  73. AddKeyBinding (Key.End, Command.BottomEnd);
  74. AddKeyBinding (Key.Space, Command.Accept);
  75. }
  76. /// <summary>
  77. /// Gets or sets the <see cref="DisplayModeLayout"/> for this <see cref="RadioGroup"/>.
  78. /// </summary>
  79. public DisplayModeLayout DisplayMode {
  80. get { return displayMode; }
  81. set {
  82. if (displayMode != value) {
  83. displayMode = value;
  84. SetWidthHeight (radioLabels);
  85. SetNeedsDisplay ();
  86. }
  87. }
  88. }
  89. /// <summary>
  90. /// Gets or sets the horizontal space for this <see cref="RadioGroup"/> if the <see cref="DisplayMode"/> is <see cref="DisplayModeLayout.Horizontal"/>
  91. /// </summary>
  92. public int HorizontalSpace {
  93. get { return horizontalSpace; }
  94. set {
  95. if (horizontalSpace != value && displayMode == DisplayModeLayout.Horizontal) {
  96. horizontalSpace = value;
  97. SetWidthHeight (radioLabels);
  98. UpdateTextFormatterText ();
  99. SetNeedsDisplay ();
  100. }
  101. }
  102. }
  103. void SetWidthHeight (List<ustring> radioLabels)
  104. {
  105. switch (displayMode) {
  106. case DisplayModeLayout.Vertical:
  107. var r = MakeRect (0, 0, radioLabels);
  108. if (IsAdded && LayoutStyle == LayoutStyle.Computed) {
  109. Width = r.Width;
  110. Height = radioLabels.Count;
  111. } else {
  112. Frame = new Rect (Frame.Location, new Size (r.Width, radioLabels.Count));
  113. }
  114. break;
  115. case DisplayModeLayout.Horizontal:
  116. CalculateHorizontalPositions ();
  117. var length = 0;
  118. foreach (var item in horizontal) {
  119. length += item.length;
  120. }
  121. var hr = new Rect (0, 0, length, 1);
  122. if (IsAdded && LayoutStyle == LayoutStyle.Computed) {
  123. Width = hr.Width;
  124. Height = 1;
  125. } else {
  126. Frame = new Rect (Frame.Location, new Size (hr.Width, radioLabels.Count));
  127. }
  128. break;
  129. }
  130. }
  131. static Rect MakeRect (int x, int y, List<ustring> radioLabels)
  132. {
  133. if (radioLabels == null) {
  134. return new Rect (x, y, 0, 0);
  135. }
  136. int width = 0;
  137. foreach (var s in radioLabels)
  138. width = Math.Max (s.ConsoleWidth + 3, width);
  139. return new Rect (x, y, width, radioLabels.Count);
  140. }
  141. List<ustring> radioLabels = new List<ustring> ();
  142. /// <summary>
  143. /// The radio labels to display
  144. /// </summary>
  145. /// <value>The radio labels.</value>
  146. public ustring [] RadioLabels {
  147. get => radioLabels.ToArray ();
  148. set {
  149. var prevCount = radioLabels.Count;
  150. radioLabels = value.ToList ();
  151. if (prevCount != radioLabels.Count) {
  152. SetWidthHeight (radioLabels);
  153. }
  154. SelectedItem = 0;
  155. cursor = 0;
  156. SetNeedsDisplay ();
  157. }
  158. }
  159. private void CalculateHorizontalPositions ()
  160. {
  161. if (displayMode == DisplayModeLayout.Horizontal) {
  162. horizontal = new List<(int pos, int length)> ();
  163. int start = 0;
  164. int length = 0;
  165. for (int i = 0; i < radioLabels.Count; i++) {
  166. start += length;
  167. length = radioLabels [i].ConsoleWidth + 2 + (i < radioLabels.Count - 1 ? horizontalSpace : 0);
  168. horizontal.Add ((start, length));
  169. }
  170. }
  171. }
  172. //// Redraws the RadioGroup
  173. //void Update(List<ustring> newRadioLabels)
  174. //{
  175. // for (int i = 0; i < radioLabels.Count; i++) {
  176. // Move(0, i);
  177. // Driver.SetAttribute(ColorScheme.Normal);
  178. // Driver.AddStr(ustring.Make(new string (' ', radioLabels[i].ConsoleWidth + 4)));
  179. // }
  180. // if (newRadioLabels.Count != radioLabels.Count) {
  181. // SetWidthHeight(newRadioLabels);
  182. // }
  183. //}
  184. ///<inheritdoc/>
  185. public override void Redraw (Rect bounds)
  186. {
  187. Driver.SetAttribute (GetNormalColor ());
  188. Clear ();
  189. for (int i = 0; i < radioLabels.Count; i++) {
  190. switch (DisplayMode) {
  191. case DisplayModeLayout.Vertical:
  192. Move (0, i);
  193. break;
  194. case DisplayModeLayout.Horizontal:
  195. Move (horizontal [i].pos, 0);
  196. break;
  197. }
  198. Driver.SetAttribute (GetNormalColor ());
  199. Driver.AddStr (ustring.Make (new Rune [] { i == selected ? Driver.Selected : Driver.UnSelected, ' ' }));
  200. DrawHotString (radioLabels [i], HasFocus && i == cursor, ColorScheme);
  201. }
  202. }
  203. ///<inheritdoc/>
  204. public override void PositionCursor ()
  205. {
  206. switch (DisplayMode) {
  207. case DisplayModeLayout.Vertical:
  208. Move (0, cursor);
  209. break;
  210. case DisplayModeLayout.Horizontal:
  211. Move (horizontal [cursor].pos, 0);
  212. break;
  213. }
  214. }
  215. /// <summary>
  216. /// Invoked when the selected radio label has changed.
  217. /// </summary>
  218. public event Action<SelectedItemChangedArgs> SelectedItemChanged;
  219. /// <summary>
  220. /// The currently selected item from the list of radio labels
  221. /// </summary>
  222. /// <value>The selected.</value>
  223. public int SelectedItem {
  224. get => selected;
  225. set {
  226. OnSelectedItemChanged (value, SelectedItem);
  227. cursor = selected;
  228. SetNeedsDisplay ();
  229. }
  230. }
  231. /// <summary>
  232. /// Allow to invoke the <see cref="SelectedItemChanged"/> after their creation.
  233. /// </summary>
  234. public void Refresh ()
  235. {
  236. OnSelectedItemChanged (selected, -1);
  237. }
  238. /// <summary>
  239. /// Called whenever the current selected item changes. Invokes the <see cref="SelectedItemChanged"/> event.
  240. /// </summary>
  241. /// <param name="selectedItem"></param>
  242. /// <param name="previousSelectedItem"></param>
  243. public virtual void OnSelectedItemChanged (int selectedItem, int previousSelectedItem)
  244. {
  245. selected = selectedItem;
  246. SelectedItemChanged?.Invoke (new SelectedItemChangedArgs (selectedItem, previousSelectedItem));
  247. }
  248. ///<inheritdoc/>
  249. public override bool ProcessColdKey (KeyEvent kb)
  250. {
  251. var key = kb.KeyValue;
  252. if (key < Char.MaxValue && Char.IsLetterOrDigit ((char)key)) {
  253. int i = 0;
  254. key = Char.ToUpper ((char)key);
  255. foreach (var l in radioLabels) {
  256. bool nextIsHot = false;
  257. foreach (var c in l) {
  258. if (c == '_')
  259. nextIsHot = true;
  260. else {
  261. if (nextIsHot && c == key) {
  262. SelectedItem = i;
  263. cursor = i;
  264. if (!HasFocus)
  265. SetFocus ();
  266. return true;
  267. }
  268. nextIsHot = false;
  269. }
  270. }
  271. i++;
  272. }
  273. }
  274. return false;
  275. }
  276. ///<inheritdoc/>
  277. public override bool ProcessKey (KeyEvent kb)
  278. {
  279. var result = InvokeKeybindings (kb);
  280. if (result != null)
  281. return (bool)result;
  282. return base.ProcessKey (kb);
  283. }
  284. void SelectItem ()
  285. {
  286. SelectedItem = cursor;
  287. }
  288. void MoveEnd ()
  289. {
  290. cursor = Math.Max (radioLabels.Count - 1, 0);
  291. }
  292. void MoveHome ()
  293. {
  294. cursor = 0;
  295. }
  296. void MoveDown ()
  297. {
  298. if (cursor + 1 < radioLabels.Count) {
  299. cursor++;
  300. SetNeedsDisplay ();
  301. } else if (cursor > 0) {
  302. cursor = 0;
  303. SetNeedsDisplay ();
  304. }
  305. }
  306. void MoveUp ()
  307. {
  308. if (cursor > 0) {
  309. cursor--;
  310. SetNeedsDisplay ();
  311. } else if (radioLabels.Count - 1 > 0) {
  312. cursor = radioLabels.Count - 1;
  313. SetNeedsDisplay ();
  314. }
  315. }
  316. ///<inheritdoc/>
  317. public override bool MouseEvent (MouseEvent me)
  318. {
  319. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  320. return false;
  321. }
  322. if (!CanFocus) {
  323. return false;
  324. }
  325. SetFocus ();
  326. var pos = displayMode == DisplayModeLayout.Horizontal ? me.X : me.Y;
  327. var rCount = displayMode == DisplayModeLayout.Horizontal ? horizontal.Last ().pos + horizontal.Last ().length : radioLabels.Count;
  328. if (pos < rCount) {
  329. var c = displayMode == DisplayModeLayout.Horizontal ? horizontal.FindIndex ((x) => x.pos <= me.X && x.pos + x.length - 2 >= me.X) : me.Y;
  330. if (c > -1) {
  331. cursor = SelectedItem = c;
  332. SetNeedsDisplay ();
  333. }
  334. }
  335. return true;
  336. }
  337. ///<inheritdoc/>
  338. public override bool OnEnter (View view)
  339. {
  340. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  341. return base.OnEnter (view);
  342. }
  343. }
  344. /// <summary>
  345. /// Used for choose the display mode of this <see cref="RadioGroup"/>
  346. /// </summary>
  347. public enum DisplayModeLayout {
  348. /// <summary>
  349. /// Vertical mode display. It's the default.
  350. /// </summary>
  351. Vertical,
  352. /// <summary>
  353. /// Horizontal mode display.
  354. /// </summary>
  355. Horizontal
  356. }
  357. /// <summary>
  358. /// Event arguments for the SelectedItemChagned event.
  359. /// </summary>
  360. public class SelectedItemChangedArgs : EventArgs {
  361. /// <summary>
  362. /// Gets the index of the item that was previously selected. -1 if there was no previous selection.
  363. /// </summary>
  364. public int PreviousSelectedItem { get; }
  365. /// <summary>
  366. /// Gets the index of the item that is now selected. -1 if there is no selection.
  367. /// </summary>
  368. public int SelectedItem { get; }
  369. /// <summary>
  370. /// Initializes a new <see cref="SelectedItemChangedArgs"/> class.
  371. /// </summary>
  372. /// <param name="selectedItem"></param>
  373. /// <param name="previousSelectedItem"></param>
  374. public SelectedItemChangedArgs (int selectedItem, int previousSelectedItem)
  375. {
  376. PreviousSelectedItem = previousSelectedItem;
  377. SelectedItem = selectedItem;
  378. }
  379. }
  380. }