RadioGroup.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. Orientation _orientation = Orientation.Vertical;
  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. SetInitialProperties (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. SetInitialProperties (radioLabels, selected);
  37. }
  38. void SetInitialProperties (string [] radioLabels, int selected)
  39. {
  40. HotKeySpecifier = new Rune ('_');
  41. if (radioLabels != null) {
  42. RadioLabels = radioLabels;
  43. }
  44. _selected = selected;
  45. CanFocus = true;
  46. // Things this view knows how to do
  47. AddCommand (Command.LineUp, () => { MoveUp (); return true; });
  48. AddCommand (Command.LineDown, () => { MoveDown (); return true; });
  49. AddCommand (Command.TopHome, () => { MoveHome (); return true; });
  50. AddCommand (Command.BottomEnd, () => { MoveEnd (); return true; });
  51. AddCommand (Command.Accept, () => { SelectItem (); return true; });
  52. // Default keybindings for this view
  53. KeyBindings.Add (KeyCode.CursorUp, Command.LineUp);
  54. KeyBindings.Add (KeyCode.CursorDown, Command.LineDown);
  55. KeyBindings.Add (KeyCode.Home, Command.TopHome);
  56. KeyBindings.Add (KeyCode.End, Command.BottomEnd);
  57. KeyBindings.Add (KeyCode.Space, Command.Accept);
  58. LayoutStarted += RadioGroup_LayoutStarted;
  59. }
  60. void RadioGroup_LayoutStarted (object sender, EventArgs e)
  61. {
  62. SetWidthHeight (_radioLabels);
  63. }
  64. /// <summary>
  65. /// Gets or sets the <see cref="Orientation"/> for this <see cref="RadioGroup"/>. The default is <see cref="Orientation.Vertical"/>.
  66. /// </summary>
  67. public Orientation Orientation {
  68. get => _orientation;
  69. set => OnOrientationChanged (value);
  70. }
  71. /// <summary>
  72. /// Fired when the view orientation has changed. Can be cancelled by setting
  73. /// <see cref="OrientationEventArgs.Cancel"/> to true.
  74. /// </summary>
  75. public event EventHandler<OrientationEventArgs> OrientationChanged;
  76. /// <summary>
  77. /// Called when the view orientation has changed. Invokes the <see cref="OrientationChanged"/> event.
  78. /// </summary>
  79. /// <param name="newOrientation"></param>
  80. /// <returns>True of the event was cancelled.</returns>
  81. public virtual bool OnOrientationChanged (Orientation newOrientation)
  82. {
  83. var args = new OrientationEventArgs (newOrientation);
  84. OrientationChanged?.Invoke (this, args);
  85. if (!args.Cancel) {
  86. _orientation = newOrientation;
  87. SetNeedsLayout ();
  88. }
  89. return args.Cancel;
  90. }
  91. /// <summary>
  92. /// Gets or sets the horizontal space for this <see cref="RadioGroup"/> if the <see cref="Orientation"/> is <see cref="Orientation.Horizontal"/>
  93. /// </summary>
  94. public int HorizontalSpace {
  95. get { return _horizontalSpace; }
  96. set {
  97. if (_horizontalSpace != value && _orientation == Orientation.Horizontal) {
  98. _horizontalSpace = value;
  99. SetWidthHeight (_radioLabels);
  100. UpdateTextFormatterText ();
  101. SetNeedsDisplay ();
  102. }
  103. }
  104. }
  105. void SetWidthHeight (List<string> radioLabels)
  106. {
  107. switch (_orientation) {
  108. case Orientation.Vertical:
  109. var r = MakeRect (0, 0, radioLabels);
  110. if (IsInitialized) {
  111. Width = r.Width + GetFramesThickness ().Horizontal;
  112. Height = radioLabels.Count + GetFramesThickness ().Vertical;
  113. }
  114. break;
  115. case Orientation.Horizontal:
  116. CalculateHorizontalPositions ();
  117. var length = 0;
  118. foreach (var item in _horizontal) {
  119. length += item.length;
  120. }
  121. if (IsInitialized) {
  122. Width = length + GetFramesThickness ().Vertical;
  123. Height = 1 + GetFramesThickness ().Horizontal;
  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. A key binding will be added for each radio radio enabling the user
  142. /// to select and/or focus the radio label using the keyboard. See <see cref="View.HotKey"/> for details
  143. /// on how HotKeys work.
  144. /// </summary>
  145. /// <value>The radio labels.</value>
  146. public string [] RadioLabels {
  147. get => _radioLabels.ToArray ();
  148. set {
  149. // Remove old hot key bindings
  150. foreach (var label in _radioLabels) {
  151. if (TextFormatter.FindHotKey (label, HotKeySpecifier, true, out _, out var hotKey)) {
  152. AddKeyBindingsForHotKey (hotKey, KeyCode.Null);
  153. }
  154. }
  155. var prevCount = _radioLabels.Count;
  156. _radioLabels = value.ToList ();
  157. foreach (var label in _radioLabels) {
  158. if (TextFormatter.FindHotKey (label, HotKeySpecifier, true, out _, out var hotKey)) {
  159. AddKeyBindingsForHotKey (KeyCode.Null, hotKey);
  160. }
  161. }
  162. if (IsInitialized && prevCount != _radioLabels.Count) {
  163. SetWidthHeight (_radioLabels);
  164. }
  165. SelectedItem = 0;
  166. _cursor = 0;
  167. SetNeedsDisplay ();
  168. }
  169. }
  170. /// <inheritdoc/>
  171. public override bool? OnInvokingKeyBindings (Key keyEvent)
  172. {
  173. // This is a bit of a hack. We want to handle the key bindings for the radio group but
  174. // InvokeKeyBindings doesn't pass any context so we can't tell if the key binding is for
  175. // the radio group or for one of the radio buttons. So before we call the base class
  176. // we set SelectedItem appropriately.
  177. var key = keyEvent;
  178. if (KeyBindings.TryGet (key, out _)) {
  179. // Search RadioLabels
  180. for (int i = 0; i < _radioLabels.Count; i++) {
  181. if (TextFormatter.FindHotKey (_radioLabels [i], HotKeySpecifier, true, out _, out var hotKey)
  182. && (key.NoAlt.NoCtrl.NoShift) == hotKey) {
  183. SelectedItem = i;
  184. keyEvent.Scope = KeyBindingScope.HotKey;
  185. break;
  186. }
  187. }
  188. }
  189. return base.OnInvokingKeyBindings (keyEvent);
  190. }
  191. void CalculateHorizontalPositions ()
  192. {
  193. if (_orientation == Orientation.Horizontal) {
  194. _horizontal = new List<(int pos, int length)> ();
  195. int start = 0;
  196. int length = 0;
  197. for (int i = 0; i < _radioLabels.Count; i++) {
  198. start += length;
  199. length = _radioLabels [i].GetColumns () + 2 + (i < _radioLabels.Count - 1 ? _horizontalSpace : 0);
  200. _horizontal.Add ((start, length));
  201. }
  202. }
  203. }
  204. ///<inheritdoc/>
  205. public override void OnDrawContent (Rect contentArea)
  206. {
  207. base.OnDrawContent (contentArea);
  208. Driver.SetAttribute (GetNormalColor ());
  209. for (int i = 0; i < _radioLabels.Count; i++) {
  210. switch (Orientation) {
  211. case Orientation.Vertical:
  212. Move (0, i);
  213. break;
  214. case Orientation.Horizontal:
  215. Move (_horizontal [i].pos, 0);
  216. break;
  217. }
  218. var rl = _radioLabels [i];
  219. Driver.SetAttribute (GetNormalColor ());
  220. Driver.AddStr ($"{(i == _selected ? CM.Glyphs.Selected : CM.Glyphs.UnSelected)} ");
  221. TextFormatter.FindHotKey (rl, HotKeySpecifier, true, out int hotPos, out var hotKey);
  222. if (hotPos != -1 && (hotKey != KeyCode.Null)) {
  223. var rlRunes = rl.ToRunes ();
  224. for (int j = 0; j < rlRunes.Length; j++) {
  225. Rune rune = rlRunes [j];
  226. if (j == hotPos && i == _cursor) {
  227. Application.Driver.SetAttribute (HasFocus ? ColorScheme.HotFocus : GetHotNormalColor ());
  228. } else if (j == hotPos && i != _cursor) {
  229. Application.Driver.SetAttribute (GetHotNormalColor ());
  230. } else if (HasFocus && i == _cursor) {
  231. Application.Driver.SetAttribute (ColorScheme.Focus);
  232. }
  233. if (rune == HotKeySpecifier && j + 1 < rlRunes.Length) {
  234. j++;
  235. rune = rlRunes [j];
  236. if (i == _cursor) {
  237. Application.Driver.SetAttribute (HasFocus ? ColorScheme.HotFocus : GetHotNormalColor ());
  238. } else if (i != _cursor) {
  239. Application.Driver.SetAttribute (GetHotNormalColor ());
  240. }
  241. }
  242. Application.Driver.AddRune (rune);
  243. Driver.SetAttribute (GetNormalColor ());
  244. }
  245. } else {
  246. DrawHotString (rl, HasFocus && i == _cursor, ColorScheme);
  247. }
  248. }
  249. }
  250. ///<inheritdoc/>
  251. public override void PositionCursor ()
  252. {
  253. switch (Orientation) {
  254. case Orientation.Vertical:
  255. Move (0, _cursor);
  256. break;
  257. case Orientation.Horizontal:
  258. Move (_horizontal [_cursor].pos, 0);
  259. break;
  260. }
  261. }
  262. /// <summary>
  263. /// Invoked when the selected radio label has changed.
  264. /// </summary>
  265. public event EventHandler<SelectedItemChangedArgs> SelectedItemChanged;
  266. /// <summary>
  267. /// The currently selected item from the list of radio labels
  268. /// </summary>
  269. /// <value>The selected.</value>
  270. public int SelectedItem {
  271. get => _selected;
  272. set {
  273. OnSelectedItemChanged (value, SelectedItem);
  274. _cursor = _selected;
  275. SetNeedsDisplay ();
  276. }
  277. }
  278. /// <summary>
  279. /// Allow to invoke the <see cref="SelectedItemChanged"/> after their creation.
  280. /// </summary>
  281. public void Refresh ()
  282. {
  283. OnSelectedItemChanged (_selected, -1);
  284. }
  285. /// <summary>
  286. /// Called whenever the current selected item changes. Invokes the <see cref="SelectedItemChanged"/> event.
  287. /// </summary>
  288. /// <param name="selectedItem"></param>
  289. /// <param name="previousSelectedItem"></param>
  290. public virtual void OnSelectedItemChanged (int selectedItem, int previousSelectedItem)
  291. {
  292. _selected = selectedItem;
  293. SelectedItemChanged?.Invoke (this, new SelectedItemChangedArgs (selectedItem, previousSelectedItem));
  294. }
  295. void SelectItem ()
  296. {
  297. SelectedItem = _cursor;
  298. }
  299. void MoveEnd ()
  300. {
  301. _cursor = Math.Max (_radioLabels.Count - 1, 0);
  302. }
  303. void MoveHome ()
  304. {
  305. _cursor = 0;
  306. }
  307. void MoveDown ()
  308. {
  309. if (_cursor + 1 < _radioLabels.Count) {
  310. _cursor++;
  311. SetNeedsDisplay ();
  312. } else if (_cursor > 0) {
  313. _cursor = 0;
  314. SetNeedsDisplay ();
  315. }
  316. }
  317. void MoveUp ()
  318. {
  319. if (_cursor > 0) {
  320. _cursor--;
  321. SetNeedsDisplay ();
  322. } else if (_radioLabels.Count - 1 > 0) {
  323. _cursor = _radioLabels.Count - 1;
  324. SetNeedsDisplay ();
  325. }
  326. }
  327. ///<inheritdoc/>
  328. public override bool MouseEvent (MouseEvent me)
  329. {
  330. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  331. return false;
  332. }
  333. if (!CanFocus) {
  334. return false;
  335. }
  336. SetFocus ();
  337. int boundsX = me.X;
  338. int boundsY = me.Y;
  339. var pos = _orientation == Orientation.Horizontal ? boundsX : boundsY;
  340. var rCount = _orientation == Orientation.Horizontal ? _horizontal.Last ().pos + _horizontal.Last ().length : _radioLabels.Count;
  341. if (pos < rCount) {
  342. var c = _orientation == Orientation.Horizontal ? _horizontal.FindIndex ((x) => x.pos <= boundsX && x.pos + x.length - 2 >= boundsX) : boundsY;
  343. if (c > -1) {
  344. _cursor = SelectedItem = c;
  345. SetNeedsDisplay ();
  346. }
  347. }
  348. return true;
  349. }
  350. ///<inheritdoc/>
  351. public override bool OnEnter (View view)
  352. {
  353. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  354. return base.OnEnter (view);
  355. }
  356. }