RadioGroup.cs 15 KB

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