RadioGroup.cs 15 KB

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