RadioGroup.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. namespace Terminal.Gui;
  2. /// <summary>Displays a group of labels each with a selected indicator. Only one of those can be selected at a given time.</summary>
  3. public class RadioGroup : View
  4. {
  5. private int _cursor;
  6. private List<(int pos, int length)> _horizontal;
  7. private int _horizontalSpace = 2;
  8. private Orientation _orientation = Orientation.Vertical;
  9. private List<string> _radioLabels = [];
  10. private int _selected;
  11. /// <summary>
  12. /// Initializes a new instance of the <see cref="RadioGroup"/> class using <see cref="LayoutStyle.Computed"/>
  13. /// layout.
  14. /// </summary>
  15. public RadioGroup ()
  16. {
  17. CanFocus = true;
  18. // Things this view knows how to do
  19. AddCommand (
  20. Command.LineUp,
  21. () =>
  22. {
  23. MoveUp ();
  24. return true;
  25. }
  26. );
  27. AddCommand (
  28. Command.LineDown,
  29. () =>
  30. {
  31. MoveDown ();
  32. return true;
  33. }
  34. );
  35. AddCommand (
  36. Command.TopHome,
  37. () =>
  38. {
  39. MoveHome ();
  40. return true;
  41. }
  42. );
  43. AddCommand (
  44. Command.BottomEnd,
  45. () =>
  46. {
  47. MoveEnd ();
  48. return true;
  49. }
  50. );
  51. AddCommand (
  52. Command.Accept,
  53. () =>
  54. {
  55. SelectItem ();
  56. return !OnAccept ();
  57. }
  58. );
  59. // Default keybindings for this view
  60. KeyBindings.Add (Key.CursorUp, Command.LineUp);
  61. KeyBindings.Add (Key.CursorDown, Command.LineDown);
  62. KeyBindings.Add (Key.Home, Command.TopHome);
  63. KeyBindings.Add (Key.End, Command.BottomEnd);
  64. KeyBindings.Add (Key.Space, Command.Accept);
  65. LayoutStarted += RadioGroup_LayoutStarted;
  66. HighlightStyle = Gui.HighlightStyle.PressedOutside | Gui.HighlightStyle.Pressed;
  67. MouseClick += RadioGroup_MouseClick;
  68. }
  69. // TODO: Fix InvertColorsOnPress - only highlight the selected item
  70. private void RadioGroup_MouseClick (object sender, MouseEventEventArgs e)
  71. {
  72. SetFocus ();
  73. int boundsX = e.MouseEvent.X;
  74. int boundsY = e.MouseEvent.Y;
  75. int pos = _orientation == Orientation.Horizontal ? boundsX : boundsY;
  76. int rCount = _orientation == Orientation.Horizontal
  77. ? _horizontal.Last ().pos + _horizontal.Last ().length
  78. : _radioLabels.Count;
  79. if (pos < rCount)
  80. {
  81. int c = _orientation == Orientation.Horizontal
  82. ? _horizontal.FindIndex (x => x.pos <= boundsX && x.pos + x.length - 2 >= boundsX)
  83. : boundsY;
  84. if (c > -1)
  85. {
  86. _cursor = SelectedItem = c;
  87. SetNeedsDisplay ();
  88. }
  89. }
  90. e.Handled = true;
  91. }
  92. /// <summary>
  93. /// Gets or sets the horizontal space for this <see cref="RadioGroup"/> if the <see cref="Orientation"/> is
  94. /// <see cref="Orientation.Horizontal"/>
  95. /// </summary>
  96. public int HorizontalSpace
  97. {
  98. get => _horizontalSpace;
  99. set
  100. {
  101. if (_horizontalSpace != value && _orientation == Orientation.Horizontal)
  102. {
  103. _horizontalSpace = value;
  104. SetWidthHeight (_radioLabels);
  105. UpdateTextFormatterText ();
  106. SetNeedsDisplay ();
  107. }
  108. }
  109. }
  110. /// <summary>
  111. /// Gets or sets the <see cref="Orientation"/> for this <see cref="RadioGroup"/>. The default is
  112. /// <see cref="Orientation.Vertical"/>.
  113. /// </summary>
  114. public Orientation Orientation
  115. {
  116. get => _orientation;
  117. set => OnOrientationChanged (value);
  118. }
  119. /// <summary>
  120. /// The radio labels to display. A key binding will be added for each radio radio enabling the user to select
  121. /// and/or focus the radio label using the keyboard. See <see cref="View.HotKey"/> for details on how HotKeys work.
  122. /// </summary>
  123. /// <value>The radio labels.</value>
  124. public string [] RadioLabels
  125. {
  126. get => _radioLabels.ToArray ();
  127. set
  128. {
  129. // Remove old hot key bindings
  130. foreach (string label in _radioLabels)
  131. {
  132. if (TextFormatter.FindHotKey (label, HotKeySpecifier, out _, out Key hotKey))
  133. {
  134. AddKeyBindingsForHotKey (hotKey, Key.Empty);
  135. }
  136. }
  137. int prevCount = _radioLabels.Count;
  138. _radioLabels = value.ToList ();
  139. foreach (string label in _radioLabels)
  140. {
  141. if (TextFormatter.FindHotKey (label, HotKeySpecifier, out _, out Key hotKey))
  142. {
  143. AddKeyBindingsForHotKey (Key.Empty, hotKey);
  144. }
  145. }
  146. if (IsInitialized && prevCount != _radioLabels.Count)
  147. {
  148. SetWidthHeight (_radioLabels);
  149. }
  150. SelectedItem = 0;
  151. SetNeedsDisplay ();
  152. }
  153. }
  154. /// <summary>The currently selected item from the list of radio labels</summary>
  155. /// <value>The selected.</value>
  156. public int SelectedItem
  157. {
  158. get => _selected;
  159. set
  160. {
  161. OnSelectedItemChanged (value, SelectedItem);
  162. _cursor = Math.Max (_selected, 0);
  163. SetNeedsDisplay ();
  164. }
  165. }
  166. /// <inheritdoc/>
  167. public override void OnDrawContent (Rectangle viewport)
  168. {
  169. base.OnDrawContent (viewport);
  170. Driver.SetAttribute (GetNormalColor ());
  171. for (var i = 0; i < _radioLabels.Count; i++)
  172. {
  173. switch (Orientation)
  174. {
  175. case Orientation.Vertical:
  176. Move (0, i);
  177. break;
  178. case Orientation.Horizontal:
  179. Move (_horizontal [i].pos, 0);
  180. break;
  181. }
  182. string rl = _radioLabels [i];
  183. Driver.SetAttribute (GetNormalColor ());
  184. Driver.AddStr ($"{(i == _selected ? Glyphs.Selected : Glyphs.UnSelected)} ");
  185. TextFormatter.FindHotKey (rl, HotKeySpecifier, out int hotPos, out Key hotKey);
  186. if (hotPos != -1 && hotKey != Key.Empty)
  187. {
  188. Rune [] rlRunes = rl.ToRunes ();
  189. for (var j = 0; j < rlRunes.Length; j++)
  190. {
  191. Rune rune = rlRunes [j];
  192. if (j == hotPos && i == _cursor)
  193. {
  194. Application.Driver.SetAttribute (
  195. HasFocus
  196. ? ColorScheme.HotFocus
  197. : GetHotNormalColor ()
  198. );
  199. }
  200. else if (j == hotPos && i != _cursor)
  201. {
  202. Application.Driver.SetAttribute (GetHotNormalColor ());
  203. }
  204. else if (HasFocus && i == _cursor)
  205. {
  206. Application.Driver.SetAttribute (ColorScheme.Focus);
  207. }
  208. if (rune == HotKeySpecifier && j + 1 < rlRunes.Length)
  209. {
  210. j++;
  211. rune = rlRunes [j];
  212. if (i == _cursor)
  213. {
  214. Application.Driver.SetAttribute (
  215. HasFocus
  216. ? ColorScheme.HotFocus
  217. : GetHotNormalColor ()
  218. );
  219. }
  220. else if (i != _cursor)
  221. {
  222. Application.Driver.SetAttribute (GetHotNormalColor ());
  223. }
  224. }
  225. Application.Driver.AddRune (rune);
  226. Driver.SetAttribute (GetNormalColor ());
  227. }
  228. }
  229. else
  230. {
  231. DrawHotString (rl, HasFocus && i == _cursor, ColorScheme);
  232. }
  233. }
  234. }
  235. /// <inheritdoc/>
  236. public override bool? OnInvokingKeyBindings (Key keyEvent)
  237. {
  238. // This is a bit of a hack. We want to handle the key bindings for the radio group but
  239. // InvokeKeyBindings doesn't pass any context so we can't tell if the key binding is for
  240. // the radio group or for one of the radio buttons. So before we call the base class
  241. // we set SelectedItem appropriately.
  242. Key key = keyEvent;
  243. if (KeyBindings.TryGet (key, out _))
  244. {
  245. // Search RadioLabels
  246. for (var i = 0; i < _radioLabels.Count; i++)
  247. {
  248. if (TextFormatter.FindHotKey (
  249. _radioLabels [i],
  250. HotKeySpecifier,
  251. out _,
  252. out Key hotKey,
  253. true
  254. )
  255. && key.NoAlt.NoCtrl.NoShift == hotKey)
  256. {
  257. SelectedItem = i;
  258. break;
  259. }
  260. }
  261. }
  262. return base.OnInvokingKeyBindings (keyEvent);
  263. }
  264. /// <summary>Called when the view orientation has changed. Invokes the <see cref="OrientationChanged"/> event.</summary>
  265. /// <param name="newOrientation"></param>
  266. /// <returns>True of the event was cancelled.</returns>
  267. public virtual bool OnOrientationChanged (Orientation newOrientation)
  268. {
  269. var args = new OrientationEventArgs (newOrientation);
  270. OrientationChanged?.Invoke (this, args);
  271. if (!args.Cancel)
  272. {
  273. _orientation = newOrientation;
  274. SetNeedsLayout ();
  275. }
  276. return args.Cancel;
  277. }
  278. // TODO: This should be cancelable
  279. /// <summary>Called whenever the current selected item changes. Invokes the <see cref="SelectedItemChanged"/> event.</summary>
  280. /// <param name="selectedItem"></param>
  281. /// <param name="previousSelectedItem"></param>
  282. public virtual void OnSelectedItemChanged (int selectedItem, int previousSelectedItem)
  283. {
  284. _selected = selectedItem;
  285. SelectedItemChanged?.Invoke (this, new SelectedItemChangedArgs (selectedItem, previousSelectedItem));
  286. }
  287. /// <summary>
  288. /// Fired when the view orientation has changed. Can be cancelled by setting
  289. /// <see cref="OrientationEventArgs.Cancel"/> to true.
  290. /// </summary>
  291. public event EventHandler<OrientationEventArgs> OrientationChanged;
  292. /// <inheritdoc/>
  293. public override Point? PositionCursor ()
  294. {
  295. int x = 0;
  296. int y = 0;
  297. switch (Orientation)
  298. {
  299. case Orientation.Vertical:
  300. y = _cursor;
  301. break;
  302. case Orientation.Horizontal:
  303. x = _horizontal [_cursor].pos;
  304. break;
  305. default:
  306. return null;
  307. }
  308. Move (x, y);
  309. return null; // Don't show the cursor
  310. }
  311. /// <summary>Allow to invoke the <see cref="SelectedItemChanged"/> after their creation.</summary>
  312. public void Refresh () { OnSelectedItemChanged (_selected, -1); }
  313. // TODO: This should use StateEventArgs<int> and should be cancelable.
  314. /// <summary>Invoked when the selected radio label has changed.</summary>
  315. public event EventHandler<SelectedItemChangedArgs> SelectedItemChanged;
  316. private void CalculateHorizontalPositions ()
  317. {
  318. if (_orientation == Orientation.Horizontal)
  319. {
  320. _horizontal = new List<(int pos, int length)> ();
  321. var start = 0;
  322. var length = 0;
  323. for (var i = 0; i < _radioLabels.Count; i++)
  324. {
  325. start += length;
  326. length = _radioLabels [i].GetColumns () + 2 + (i < _radioLabels.Count - 1 ? _horizontalSpace : 0);
  327. _horizontal.Add ((start, length));
  328. }
  329. }
  330. }
  331. private static Rectangle MakeRect (int x, int y, List<string> radioLabels)
  332. {
  333. if (radioLabels is null)
  334. {
  335. return new (x, y, 0, 0);
  336. }
  337. var width = 0;
  338. foreach (string s in radioLabels)
  339. {
  340. width = Math.Max (s.GetColumns () + 2, width);
  341. }
  342. return new (x, y, width, radioLabels.Count);
  343. }
  344. private void MoveDown ()
  345. {
  346. if (_cursor + 1 < _radioLabels.Count)
  347. {
  348. _cursor++;
  349. SetNeedsDisplay ();
  350. }
  351. else if (_cursor > 0)
  352. {
  353. _cursor = 0;
  354. SetNeedsDisplay ();
  355. }
  356. }
  357. private void MoveEnd () { _cursor = Math.Max (_radioLabels.Count - 1, 0); }
  358. private void MoveHome () { _cursor = 0; }
  359. private void MoveUp ()
  360. {
  361. if (_cursor > 0)
  362. {
  363. _cursor--;
  364. SetNeedsDisplay ();
  365. }
  366. else if (_radioLabels.Count - 1 > 0)
  367. {
  368. _cursor = _radioLabels.Count - 1;
  369. SetNeedsDisplay ();
  370. }
  371. }
  372. private void RadioGroup_LayoutStarted (object sender, EventArgs e) { SetWidthHeight (_radioLabels); }
  373. private void SelectItem () { SelectedItem = _cursor; }
  374. private void SetWidthHeight (List<string> radioLabels)
  375. {
  376. switch (_orientation)
  377. {
  378. case Orientation.Vertical:
  379. Rectangle r = MakeRect (0, 0, radioLabels);
  380. if (IsInitialized)
  381. {
  382. Width = r.Width + GetAdornmentsThickness ().Horizontal;
  383. Height = radioLabels.Count + GetAdornmentsThickness ().Vertical;
  384. }
  385. break;
  386. case Orientation.Horizontal:
  387. CalculateHorizontalPositions ();
  388. var length = 0;
  389. foreach ((int pos, int length) item in _horizontal)
  390. {
  391. length += item.length;
  392. }
  393. if (IsInitialized)
  394. {
  395. Width = length + GetAdornmentsThickness ().Vertical;
  396. Height = 1 + GetAdornmentsThickness ().Horizontal;
  397. }
  398. break;
  399. }
  400. }
  401. }