RadioGroup.cs 14 KB

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