RadioGroup.cs 14 KB

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