RadioGroup.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. using System.Text;
  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 string [] { }) { }
  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 (string [] radioLabels, int selected = 0) : base ()
  25. {
  26. SetInitalProperties (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, string [] radioLabels, int selected = 0) : base (rect)
  35. {
  36. SetInitalProperties (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, string [] radioLabels, int selected = 0) :
  47. this (MakeRect (x, y, radioLabels != null ? radioLabels.ToList () : null), radioLabels, selected)
  48. { }
  49. void SetInitalProperties (Rect rect, string [] radioLabels, int selected)
  50. {
  51. if (radioLabels == null) {
  52. this.radioLabels = new List<string> ();
  53. } else {
  54. this.radioLabels = radioLabels.ToList ();
  55. }
  56. this.selected = selected;
  57. Frame = rect;
  58. CanFocus = true;
  59. HotKeySpecifier = new Rune ('_');
  60. // Things this view knows how to do
  61. AddCommand (Command.LineUp, () => { MoveUp (); return true; });
  62. AddCommand (Command.LineDown, () => { MoveDown (); return true; });
  63. AddCommand (Command.TopHome, () => { MoveHome (); return true; });
  64. AddCommand (Command.BottomEnd, () => { MoveEnd (); return true; });
  65. AddCommand (Command.Accept, () => { SelectItem (); return true; });
  66. // Default keybindings for this view
  67. AddKeyBinding (Key.CursorUp, Command.LineUp);
  68. AddKeyBinding (Key.CursorDown, Command.LineDown);
  69. AddKeyBinding (Key.Home, Command.TopHome);
  70. AddKeyBinding (Key.End, Command.BottomEnd);
  71. AddKeyBinding (Key.Space, Command.Accept);
  72. LayoutStarted += RadioGroup_LayoutStarted;
  73. }
  74. private void RadioGroup_LayoutStarted (object sender, EventArgs e)
  75. {
  76. SetWidthHeight (radioLabels);
  77. }
  78. /// <summary>
  79. /// Gets or sets the <see cref="DisplayModeLayout"/> for this <see cref="RadioGroup"/>.
  80. /// </summary>
  81. public DisplayModeLayout DisplayMode {
  82. get { return displayMode; }
  83. set {
  84. if (displayMode != value) {
  85. displayMode = value;
  86. SetWidthHeight (radioLabels);
  87. SetNeedsDisplay ();
  88. }
  89. }
  90. }
  91. /// <summary>
  92. /// Gets or sets the horizontal space for this <see cref="RadioGroup"/> if the <see cref="DisplayMode"/> is <see cref="DisplayModeLayout.Horizontal"/>
  93. /// </summary>
  94. public int HorizontalSpace {
  95. get { return horizontalSpace; }
  96. set {
  97. if (horizontalSpace != value && displayMode == DisplayModeLayout.Horizontal) {
  98. horizontalSpace = value;
  99. SetWidthHeight (radioLabels);
  100. UpdateTextFormatterText ();
  101. SetNeedsDisplay ();
  102. }
  103. }
  104. }
  105. void SetWidthHeight (List<string> radioLabels)
  106. {
  107. switch (displayMode) {
  108. case DisplayModeLayout.Vertical:
  109. var r = MakeRect (0, 0, radioLabels);
  110. Bounds = new Rect (Bounds.Location, new Size (r.Width, radioLabels.Count));
  111. break;
  112. case DisplayModeLayout.Horizontal:
  113. CalculateHorizontalPositions ();
  114. var length = 0;
  115. foreach (var item in horizontal) {
  116. length += item.length;
  117. }
  118. var hr = new Rect (0, 0, length, 1);
  119. if (IsAdded && LayoutStyle == LayoutStyle.Computed) {
  120. Width = hr.Width;
  121. Height = 1;
  122. } else {
  123. Bounds = new Rect (Bounds.Location, new Size (hr.Width, radioLabels.Count));
  124. }
  125. break;
  126. }
  127. }
  128. static Rect MakeRect (int x, int y, List<string> radioLabels)
  129. {
  130. if (radioLabels == null) {
  131. return new Rect (x, y, 0, 0);
  132. }
  133. int width = 0;
  134. foreach (var s in radioLabels) {
  135. width = Math.Max (s.GetColumns () + 2, width);
  136. }
  137. return new Rect (x, y, width, radioLabels.Count);
  138. }
  139. List<string> radioLabels = new List<string> ();
  140. /// <summary>
  141. /// The radio labels to display
  142. /// </summary>
  143. /// <value>The radio labels.</value>
  144. public string [] RadioLabels {
  145. get => radioLabels.ToArray ();
  146. set {
  147. var prevCount = radioLabels.Count;
  148. radioLabels = value.ToList ();
  149. if (prevCount != radioLabels.Count) {
  150. SetWidthHeight (radioLabels);
  151. }
  152. SelectedItem = 0;
  153. cursor = 0;
  154. SetNeedsDisplay ();
  155. }
  156. }
  157. private void CalculateHorizontalPositions ()
  158. {
  159. if (displayMode == DisplayModeLayout.Horizontal) {
  160. horizontal = new List<(int pos, int length)> ();
  161. int start = 0;
  162. int length = 0;
  163. for (int i = 0; i < radioLabels.Count; i++) {
  164. start += length;
  165. length = radioLabels [i].GetColumns () + 2 + (i < radioLabels.Count - 1 ? horizontalSpace : 0);
  166. horizontal.Add ((start, length));
  167. }
  168. }
  169. }
  170. ///<inheritdoc/>
  171. public override void OnDrawContent (Rect contentArea)
  172. {
  173. base.OnDrawContent (contentArea);
  174. Driver.SetAttribute (GetNormalColor ());
  175. for (int i = 0; i < radioLabels.Count; i++) {
  176. switch (DisplayMode) {
  177. case DisplayModeLayout.Vertical:
  178. Move (0, i);
  179. break;
  180. case DisplayModeLayout.Horizontal:
  181. Move (horizontal [i].pos, 0);
  182. break;
  183. }
  184. var rl = radioLabels [i];
  185. Driver.SetAttribute (GetNormalColor ());
  186. Driver.AddStr ($"{(i == selected ? CM.Glyphs.Selected : CM.Glyphs.UnSelected)} ");
  187. TextFormatter.FindHotKey (rl, HotKeySpecifier, true, out int hotPos, out Key hotKey);
  188. if (hotPos != -1 && (hotKey != Key.Null || hotKey != Key.Unknown)) {
  189. var rlRunes = rl.ToRunes ();
  190. for (int j = 0; j < rlRunes.Length; j++) {
  191. Rune rune = rlRunes [j];
  192. if (j == hotPos && i == cursor) {
  193. Application.Driver.SetAttribute (HasFocus ? ColorScheme.HotFocus : GetHotNormalColor ());
  194. } else if (j == hotPos && i != cursor) {
  195. Application.Driver.SetAttribute (GetHotNormalColor ());
  196. } else if (HasFocus && i == cursor) {
  197. Application.Driver.SetAttribute (ColorScheme.Focus);
  198. }
  199. if (rune == HotKeySpecifier && j + 1 < rlRunes.Length) {
  200. j++;
  201. rune = rlRunes [j];
  202. if (i == cursor) {
  203. Application.Driver.SetAttribute (HasFocus ? ColorScheme.HotFocus : GetHotNormalColor ());
  204. } else if (i != cursor) {
  205. Application.Driver.SetAttribute (GetHotNormalColor ());
  206. }
  207. }
  208. Application.Driver.AddRune (rune);
  209. Driver.SetAttribute (GetNormalColor ());
  210. }
  211. } else {
  212. DrawHotString (rl, HasFocus && i == cursor, ColorScheme);
  213. }
  214. }
  215. }
  216. ///<inheritdoc/>
  217. public override void PositionCursor ()
  218. {
  219. switch (DisplayMode) {
  220. case DisplayModeLayout.Vertical:
  221. Move (0, cursor);
  222. break;
  223. case DisplayModeLayout.Horizontal:
  224. Move (horizontal [cursor].pos, 0);
  225. break;
  226. }
  227. }
  228. /// <summary>
  229. /// Invoked when the selected radio label has changed.
  230. /// </summary>
  231. public event EventHandler<SelectedItemChangedArgs> SelectedItemChanged;
  232. /// <summary>
  233. /// The currently selected item from the list of radio labels
  234. /// </summary>
  235. /// <value>The selected.</value>
  236. public int SelectedItem {
  237. get => selected;
  238. set {
  239. OnSelectedItemChanged (value, SelectedItem);
  240. cursor = selected;
  241. SetNeedsDisplay ();
  242. }
  243. }
  244. /// <summary>
  245. /// Allow to invoke the <see cref="SelectedItemChanged"/> after their creation.
  246. /// </summary>
  247. public void Refresh ()
  248. {
  249. OnSelectedItemChanged (selected, -1);
  250. }
  251. /// <summary>
  252. /// Called whenever the current selected item changes. Invokes the <see cref="SelectedItemChanged"/> event.
  253. /// </summary>
  254. /// <param name="selectedItem"></param>
  255. /// <param name="previousSelectedItem"></param>
  256. public virtual void OnSelectedItemChanged (int selectedItem, int previousSelectedItem)
  257. {
  258. selected = selectedItem;
  259. SelectedItemChanged?.Invoke (this, new SelectedItemChangedArgs (selectedItem, previousSelectedItem));
  260. }
  261. ///<inheritdoc/>
  262. public override bool ProcessColdKey (KeyEvent kb)
  263. {
  264. var key = kb.KeyValue;
  265. if (key < Char.MaxValue && Char.IsLetterOrDigit ((char)key)) {
  266. int i = 0;
  267. key = Char.ToUpper ((char)key);
  268. foreach (var l in radioLabels) {
  269. bool nextIsHot = false;
  270. TextFormatter.FindHotKey (l, HotKeySpecifier, true, out _, out Key hotKey);
  271. foreach (Rune c in l) {
  272. if (c == HotKeySpecifier) {
  273. nextIsHot = true;
  274. } else {
  275. if ((nextIsHot && Rune.ToUpperInvariant (c).Value == key) || (key == (uint)hotKey)) {
  276. SelectedItem = i;
  277. cursor = i;
  278. if (!HasFocus)
  279. SetFocus ();
  280. return true;
  281. }
  282. nextIsHot = false;
  283. }
  284. }
  285. i++;
  286. }
  287. }
  288. return false;
  289. }
  290. ///<inheritdoc/>
  291. public override bool ProcessKey (KeyEvent kb)
  292. {
  293. var result = InvokeKeybindings (kb);
  294. if (result != null)
  295. return (bool)result;
  296. return base.ProcessKey (kb);
  297. }
  298. void SelectItem ()
  299. {
  300. SelectedItem = cursor;
  301. }
  302. void MoveEnd ()
  303. {
  304. cursor = Math.Max (radioLabels.Count - 1, 0);
  305. }
  306. void MoveHome ()
  307. {
  308. cursor = 0;
  309. }
  310. void MoveDown ()
  311. {
  312. if (cursor + 1 < radioLabels.Count) {
  313. cursor++;
  314. SetNeedsDisplay ();
  315. } else if (cursor > 0) {
  316. cursor = 0;
  317. SetNeedsDisplay ();
  318. }
  319. }
  320. void MoveUp ()
  321. {
  322. if (cursor > 0) {
  323. cursor--;
  324. SetNeedsDisplay ();
  325. } else if (radioLabels.Count - 1 > 0) {
  326. cursor = radioLabels.Count - 1;
  327. SetNeedsDisplay ();
  328. }
  329. }
  330. ///<inheritdoc/>
  331. public override bool MouseEvent (MouseEvent me)
  332. {
  333. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  334. return false;
  335. }
  336. if (!CanFocus) {
  337. return false;
  338. }
  339. SetFocus ();
  340. int boundsX = me.X - GetFramesThickness ().Left;
  341. int boundsY = me.Y - GetFramesThickness ().Top;
  342. var pos = displayMode == DisplayModeLayout.Horizontal ? boundsX : boundsY;
  343. var rCount = displayMode == DisplayModeLayout.Horizontal ? horizontal.Last ().pos + horizontal.Last ().length : radioLabels.Count;
  344. if (pos < rCount) {
  345. var c = displayMode == DisplayModeLayout.Horizontal ? horizontal.FindIndex ((x) => x.pos <= boundsX && x.pos + x.length - 2 >= boundsX) : boundsY;
  346. if (c > -1) {
  347. cursor = SelectedItem = c;
  348. SetNeedsDisplay ();
  349. }
  350. }
  351. return true;
  352. }
  353. ///<inheritdoc/>
  354. public override bool OnEnter (View view)
  355. {
  356. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  357. return base.OnEnter (view);
  358. }
  359. }
  360. /// <summary>
  361. /// Used for choose the display mode of this <see cref="RadioGroup"/>
  362. /// </summary>
  363. public enum DisplayModeLayout {
  364. /// <summary>
  365. /// Vertical mode display. It's the default.
  366. /// </summary>
  367. Vertical,
  368. /// <summary>
  369. /// Horizontal mode display.
  370. /// </summary>
  371. Horizontal
  372. }
  373. }