RadioGroup.cs 15 KB

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