2
0

RadioGroup.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. HighlightStyle = Gui.HighlightStyle.PressedOutside | Gui.HighlightStyle.Pressed;
  67. MouseClick += RadioGroup_MouseClick;
  68. }
  69. // TODO: Fix InvertColorsOnPress - only highlight the selected item
  70. private void RadioGroup_MouseClick (object sender, MouseEventEventArgs e)
  71. {
  72. SetFocus ();
  73. int boundsX = e.MouseEvent.X;
  74. int boundsY = e.MouseEvent.Y;
  75. int pos = _orientation == Orientation.Horizontal ? boundsX : boundsY;
  76. int rCount = _orientation == Orientation.Horizontal
  77. ? _horizontal.Last ().pos + _horizontal.Last ().length
  78. : _radioLabels.Count;
  79. if (pos < rCount)
  80. {
  81. int c = _orientation == Orientation.Horizontal
  82. ? _horizontal.FindIndex (x => x.pos <= boundsX && x.pos + x.length - 2 >= boundsX)
  83. : boundsY;
  84. if (c > -1)
  85. {
  86. _cursor = SelectedItem = c;
  87. SetNeedsDisplay ();
  88. }
  89. }
  90. e.Handled = true;
  91. }
  92. /// <summary>
  93. /// Gets or sets the horizontal space for this <see cref="RadioGroup"/> if the <see cref="Orientation"/> is
  94. /// <see cref="Orientation.Horizontal"/>
  95. /// </summary>
  96. public int HorizontalSpace
  97. {
  98. get => _horizontalSpace;
  99. set
  100. {
  101. if (_horizontalSpace != value && _orientation == Orientation.Horizontal)
  102. {
  103. _horizontalSpace = value;
  104. SetWidthHeight (_radioLabels);
  105. UpdateTextFormatterText ();
  106. SetNeedsDisplay ();
  107. }
  108. }
  109. }
  110. /// <summary>
  111. /// Gets or sets the <see cref="Orientation"/> for this <see cref="RadioGroup"/>. The default is
  112. /// <see cref="Orientation.Vertical"/>.
  113. /// </summary>
  114. public Orientation Orientation
  115. {
  116. get => _orientation;
  117. set => OnOrientationChanged (value);
  118. }
  119. /// <summary>
  120. /// The radio labels to display. A key binding will be added for each radio radio enabling the user to select
  121. /// and/or focus the radio label using the keyboard. See <see cref="View.HotKey"/> for details on how HotKeys work.
  122. /// </summary>
  123. /// <value>The radio labels.</value>
  124. public string [] RadioLabels
  125. {
  126. get => _radioLabels.ToArray ();
  127. set
  128. {
  129. // Remove old hot key bindings
  130. foreach (string label in _radioLabels)
  131. {
  132. if (TextFormatter.FindHotKey (label, HotKeySpecifier, out _, out Key hotKey))
  133. {
  134. AddKeyBindingsForHotKey (hotKey, Key.Empty);
  135. }
  136. }
  137. int prevCount = _radioLabels.Count;
  138. _radioLabels = value.ToList ();
  139. foreach (string label in _radioLabels)
  140. {
  141. if (TextFormatter.FindHotKey (label, HotKeySpecifier, out _, out Key hotKey))
  142. {
  143. AddKeyBindingsForHotKey (Key.Empty, hotKey);
  144. }
  145. }
  146. if (IsInitialized && prevCount != _radioLabels.Count)
  147. {
  148. SetWidthHeight (_radioLabels);
  149. }
  150. SelectedItem = 0;
  151. SetNeedsDisplay ();
  152. }
  153. }
  154. /// <summary>The currently selected item from the list of radio labels</summary>
  155. /// <value>The selected.</value>
  156. public int SelectedItem
  157. {
  158. get => _selected;
  159. set
  160. {
  161. OnSelectedItemChanged (value, SelectedItem);
  162. _cursor = Math.Max (_selected, 0);
  163. SetNeedsDisplay ();
  164. }
  165. }
  166. /// <inheritdoc/>
  167. public override void OnDrawContent (Rectangle viewport)
  168. {
  169. base.OnDrawContent (viewport);
  170. Driver.SetAttribute (GetNormalColor ());
  171. for (var i = 0; i < _radioLabels.Count; i++)
  172. {
  173. switch (Orientation)
  174. {
  175. case Orientation.Vertical:
  176. Move (0, i);
  177. break;
  178. case Orientation.Horizontal:
  179. Move (_horizontal [i].pos, 0);
  180. break;
  181. }
  182. string rl = _radioLabels [i];
  183. Driver.SetAttribute (GetNormalColor ());
  184. Driver.AddStr ($"{(i == _selected ? Glyphs.Selected : Glyphs.UnSelected)} ");
  185. TextFormatter.FindHotKey (rl, HotKeySpecifier, out int hotPos, out Key hotKey);
  186. if (hotPos != -1 && hotKey != Key.Empty)
  187. {
  188. Rune [] rlRunes = rl.ToRunes ();
  189. for (var j = 0; j < rlRunes.Length; j++)
  190. {
  191. Rune rune = rlRunes [j];
  192. if (j == hotPos && i == _cursor)
  193. {
  194. Application.Driver.SetAttribute (
  195. HasFocus
  196. ? ColorScheme.HotFocus
  197. : GetHotNormalColor ()
  198. );
  199. }
  200. else if (j == hotPos && i != _cursor)
  201. {
  202. Application.Driver.SetAttribute (GetHotNormalColor ());
  203. }
  204. else if (HasFocus && i == _cursor)
  205. {
  206. Application.Driver.SetAttribute (ColorScheme.Focus);
  207. }
  208. if (rune == HotKeySpecifier && j + 1 < rlRunes.Length)
  209. {
  210. j++;
  211. rune = rlRunes [j];
  212. if (i == _cursor)
  213. {
  214. Application.Driver.SetAttribute (
  215. HasFocus
  216. ? ColorScheme.HotFocus
  217. : GetHotNormalColor ()
  218. );
  219. }
  220. else if (i != _cursor)
  221. {
  222. Application.Driver.SetAttribute (GetHotNormalColor ());
  223. }
  224. }
  225. Application.Driver.AddRune (rune);
  226. Driver.SetAttribute (GetNormalColor ());
  227. }
  228. }
  229. else
  230. {
  231. DrawHotString (rl, HasFocus && i == _cursor, ColorScheme);
  232. }
  233. }
  234. }
  235. /// <inheritdoc/>
  236. public override bool OnEnter (View view)
  237. {
  238. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  239. return base.OnEnter (view);
  240. }
  241. /// <inheritdoc/>
  242. public override bool? OnInvokingKeyBindings (Key keyEvent)
  243. {
  244. // This is a bit of a hack. We want to handle the key bindings for the radio group but
  245. // InvokeKeyBindings doesn't pass any context so we can't tell if the key binding is for
  246. // the radio group or for one of the radio buttons. So before we call the base class
  247. // we set SelectedItem appropriately.
  248. Key key = keyEvent;
  249. if (KeyBindings.TryGet (key, out _))
  250. {
  251. // Search RadioLabels
  252. for (var i = 0; i < _radioLabels.Count; i++)
  253. {
  254. if (TextFormatter.FindHotKey (
  255. _radioLabels [i],
  256. HotKeySpecifier,
  257. out _,
  258. out Key hotKey,
  259. true
  260. )
  261. && key.NoAlt.NoCtrl.NoShift == hotKey)
  262. {
  263. SelectedItem = i;
  264. break;
  265. }
  266. }
  267. }
  268. return base.OnInvokingKeyBindings (keyEvent);
  269. }
  270. /// <summary>Called when the view orientation has changed. Invokes the <see cref="OrientationChanged"/> event.</summary>
  271. /// <param name="newOrientation"></param>
  272. /// <returns>True of the event was cancelled.</returns>
  273. public virtual bool OnOrientationChanged (Orientation newOrientation)
  274. {
  275. var args = new OrientationEventArgs (newOrientation);
  276. OrientationChanged?.Invoke (this, args);
  277. if (!args.Cancel)
  278. {
  279. _orientation = newOrientation;
  280. SetNeedsLayout ();
  281. }
  282. return args.Cancel;
  283. }
  284. // TODO: This should be cancelable
  285. /// <summary>Called whenever the current selected item changes. Invokes the <see cref="SelectedItemChanged"/> event.</summary>
  286. /// <param name="selectedItem"></param>
  287. /// <param name="previousSelectedItem"></param>
  288. public virtual void OnSelectedItemChanged (int selectedItem, int previousSelectedItem)
  289. {
  290. _selected = selectedItem;
  291. SelectedItemChanged?.Invoke (this, new SelectedItemChangedArgs (selectedItem, previousSelectedItem));
  292. }
  293. /// <summary>
  294. /// Fired when the view orientation has changed. Can be cancelled by setting
  295. /// <see cref="OrientationEventArgs.Cancel"/> to true.
  296. /// </summary>
  297. public event EventHandler<OrientationEventArgs> OrientationChanged;
  298. /// <inheritdoc/>
  299. public override Point? PositionCursor ()
  300. {
  301. int x = 0;
  302. int y = 0;
  303. switch (Orientation)
  304. {
  305. case Orientation.Vertical:
  306. y = _cursor;
  307. break;
  308. case Orientation.Horizontal:
  309. x = _horizontal [_cursor].pos;
  310. break;
  311. default:
  312. return null;
  313. }
  314. Move (x, y);
  315. return new Point (x, y);
  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. }