RadioGroup.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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
  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. if (!HasFocus)
  25. {
  26. return false;
  27. }
  28. return MoveUpLeft ();
  29. }
  30. );
  31. AddCommand (
  32. Command.LineDown,
  33. () =>
  34. {
  35. if (!HasFocus)
  36. {
  37. return false;
  38. }
  39. return MoveDownRight ();
  40. }
  41. );
  42. AddCommand (
  43. Command.TopHome,
  44. () =>
  45. {
  46. if (!HasFocus)
  47. {
  48. return false;
  49. }
  50. MoveHome ();
  51. return true;
  52. }
  53. );
  54. AddCommand (
  55. Command.BottomEnd,
  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. SetupKeyBindings ();
  87. LayoutStarted += RadioGroup_LayoutStarted;
  88. HighlightStyle = HighlightStyle.PressedOutside | HighlightStyle.Pressed;
  89. MouseClick += RadioGroup_MouseClick;
  90. }
  91. // TODO: Fix InvertColorsOnPress - only highlight the selected item
  92. private void SetupKeyBindings ()
  93. {
  94. KeyBindings.Clear ();
  95. // Default keybindings for this view
  96. if (Orientation == Orientation.Vertical)
  97. {
  98. KeyBindings.Add (Key.CursorUp, Command.LineUp);
  99. KeyBindings.Add (Key.CursorDown, Command.LineDown);
  100. }
  101. else
  102. {
  103. KeyBindings.Add (Key.CursorLeft, Command.LineUp);
  104. KeyBindings.Add (Key.CursorRight, Command.LineDown);
  105. }
  106. KeyBindings.Add (Key.Home, Command.TopHome);
  107. KeyBindings.Add (Key.End, Command.BottomEnd);
  108. KeyBindings.Add (Key.Space, Command.Accept);
  109. }
  110. private void RadioGroup_MouseClick (object sender, MouseEventEventArgs e)
  111. {
  112. SetFocus ();
  113. int viewportX = e.MouseEvent.Position.X;
  114. int viewportY = e.MouseEvent.Position.Y;
  115. int pos = _orientation == Orientation.Horizontal ? viewportX : viewportY;
  116. int rCount = _orientation == Orientation.Horizontal
  117. ? _horizontal.Last ().pos + _horizontal.Last ().length
  118. : _radioLabels.Count;
  119. if (pos < rCount)
  120. {
  121. int c = _orientation == Orientation.Horizontal
  122. ? _horizontal.FindIndex (x => x.pos <= viewportX && x.pos + x.length - 2 >= viewportX)
  123. : viewportY;
  124. if (c > -1)
  125. {
  126. _cursor = SelectedItem = c;
  127. SetNeedsDisplay ();
  128. }
  129. }
  130. e.Handled = true;
  131. }
  132. /// <summary>
  133. /// Gets or sets the horizontal space for this <see cref="RadioGroup"/> if the <see cref="Orientation"/> is
  134. /// <see cref="Orientation.Horizontal"/>
  135. /// </summary>
  136. public int HorizontalSpace
  137. {
  138. get => _horizontalSpace;
  139. set
  140. {
  141. if (_horizontalSpace != value && _orientation == Orientation.Horizontal)
  142. {
  143. _horizontalSpace = value;
  144. UpdateTextFormatterText ();
  145. SetContentSize ();
  146. }
  147. }
  148. }
  149. /// <summary>
  150. /// Gets or sets the <see cref="Orientation"/> for this <see cref="RadioGroup"/>. The default is
  151. /// <see cref="Orientation.Vertical"/>.
  152. /// </summary>
  153. public Orientation Orientation
  154. {
  155. get => _orientation;
  156. set => OnOrientationChanged (value);
  157. }
  158. /// <summary>
  159. /// The radio labels to display. A key binding will be added for each radio enabling the user to select
  160. /// and/or focus the radio label using the keyboard. See <see cref="View.HotKey"/> for details on how HotKeys work.
  161. /// </summary>
  162. /// <value>The radio labels.</value>
  163. public string [] RadioLabels
  164. {
  165. get => _radioLabels.ToArray ();
  166. set
  167. {
  168. // Remove old hot key bindings
  169. foreach (string label in _radioLabels)
  170. {
  171. if (TextFormatter.FindHotKey (label, HotKeySpecifier, out _, out Key hotKey))
  172. {
  173. AddKeyBindingsForHotKey (hotKey, Key.Empty);
  174. }
  175. }
  176. int prevCount = _radioLabels.Count;
  177. _radioLabels = value.ToList ();
  178. for (var index = 0; index < _radioLabels.Count; index++)
  179. {
  180. string label = _radioLabels [index];
  181. if (TextFormatter.FindHotKey (label, HotKeySpecifier, out _, out Key hotKey))
  182. {
  183. AddKeyBindingsForHotKey (Key.Empty, hotKey, index);
  184. }
  185. }
  186. SelectedItem = 0;
  187. SetContentSize ();
  188. }
  189. }
  190. /// <summary>The currently selected item from the list of radio labels</summary>
  191. /// <value>The selected.</value>
  192. public int SelectedItem
  193. {
  194. get => _selected;
  195. set
  196. {
  197. OnSelectedItemChanged (value, SelectedItem);
  198. _cursor = Math.Max (_selected, 0);
  199. SetNeedsDisplay ();
  200. }
  201. }
  202. /// <inheritdoc/>
  203. public override void OnDrawContent (Rectangle viewport)
  204. {
  205. base.OnDrawContent (viewport);
  206. Driver.SetAttribute (GetNormalColor ());
  207. for (var i = 0; i < _radioLabels.Count; i++)
  208. {
  209. switch (Orientation)
  210. {
  211. case Orientation.Vertical:
  212. Move (0, i);
  213. break;
  214. case Orientation.Horizontal:
  215. Move (_horizontal [i].pos, 0);
  216. break;
  217. }
  218. string rl = _radioLabels [i];
  219. Driver.SetAttribute (GetNormalColor ());
  220. Driver.AddStr ($"{(i == _selected ? Glyphs.Selected : Glyphs.UnSelected)} ");
  221. TextFormatter.FindHotKey (rl, HotKeySpecifier, out int hotPos, out Key hotKey);
  222. if (hotPos != -1 && hotKey != Key.Empty)
  223. {
  224. Rune [] rlRunes = rl.ToRunes ();
  225. for (var j = 0; j < rlRunes.Length; j++)
  226. {
  227. Rune rune = rlRunes [j];
  228. if (j == hotPos && i == _cursor)
  229. {
  230. Application.Driver?.SetAttribute (
  231. HasFocus
  232. ? ColorScheme.HotFocus
  233. : GetHotNormalColor ()
  234. );
  235. }
  236. else if (j == hotPos && i != _cursor)
  237. {
  238. Application.Driver?.SetAttribute (GetHotNormalColor ());
  239. }
  240. else if (HasFocus && i == _cursor)
  241. {
  242. Application.Driver?.SetAttribute (ColorScheme.Focus);
  243. }
  244. if (rune == HotKeySpecifier && j + 1 < rlRunes.Length)
  245. {
  246. j++;
  247. rune = rlRunes [j];
  248. if (i == _cursor)
  249. {
  250. Application.Driver?.SetAttribute (
  251. HasFocus
  252. ? ColorScheme.HotFocus
  253. : GetHotNormalColor ()
  254. );
  255. }
  256. else if (i != _cursor)
  257. {
  258. Application.Driver?.SetAttribute (GetHotNormalColor ());
  259. }
  260. }
  261. Application.Driver?.AddRune (rune);
  262. Driver.SetAttribute (GetNormalColor ());
  263. }
  264. }
  265. else
  266. {
  267. DrawHotString (rl, HasFocus && i == _cursor, ColorScheme);
  268. }
  269. }
  270. }
  271. /// <summary>Called when the view orientation has changed. Invokes the <see cref="OrientationChanged"/> event.</summary>
  272. /// <param name="newOrientation"></param>
  273. /// <returns>True of the event was cancelled.</returns>
  274. public virtual bool OnOrientationChanged (Orientation newOrientation)
  275. {
  276. var args = new OrientationEventArgs (newOrientation);
  277. OrientationChanged?.Invoke (this, args);
  278. if (!args.Cancel)
  279. {
  280. _orientation = newOrientation;
  281. SetupKeyBindings ();
  282. SetContentSize ();
  283. }
  284. return args.Cancel;
  285. }
  286. // TODO: This should be cancelable
  287. /// <summary>Called whenever the current selected item changes. Invokes the <see cref="SelectedItemChanged"/> event.</summary>
  288. /// <param name="selectedItem"></param>
  289. /// <param name="previousSelectedItem"></param>
  290. public virtual void OnSelectedItemChanged (int selectedItem, int previousSelectedItem)
  291. {
  292. if (_selected == selectedItem)
  293. {
  294. return;
  295. }
  296. _selected = selectedItem;
  297. SelectedItemChanged?.Invoke (this, new (selectedItem, previousSelectedItem));
  298. }
  299. /// <summary>
  300. /// Fired when the view orientation has changed. Can be cancelled by setting
  301. /// <see cref="OrientationEventArgs.Cancel"/> to true.
  302. /// </summary>
  303. public event EventHandler<OrientationEventArgs> OrientationChanged;
  304. /// <inheritdoc/>
  305. public override Point? PositionCursor ()
  306. {
  307. var x = 0;
  308. var y = 0;
  309. switch (Orientation)
  310. {
  311. case Orientation.Vertical:
  312. y = _cursor;
  313. break;
  314. case Orientation.Horizontal:
  315. x = _horizontal [_cursor].pos;
  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. }