RadioGroup.cs 14 KB

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