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