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