RadioGroup.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. // TOOD: Hack - using Text when we should use SubViews
  69. Add (_dummyView);
  70. Width = Dim.Auto (Dim.DimAutoStyle.Content);
  71. Height = Dim.Auto (Dim.DimAutoStyle.Content);
  72. }
  73. // TODO: Fix InvertColorsOnPress - only highlight the selected item
  74. private void RadioGroup_MouseClick (object sender, MouseEventEventArgs e)
  75. {
  76. SetFocus ();
  77. int boundsX = e.MouseEvent.X;
  78. int boundsY = e.MouseEvent.Y;
  79. int pos = _orientation == Orientation.Horizontal ? boundsX : boundsY;
  80. int rCount = _orientation == Orientation.Horizontal
  81. ? _horizontal.Last ().pos + _horizontal.Last ().length
  82. : _radioLabels.Count;
  83. if (pos < rCount)
  84. {
  85. int c = _orientation == Orientation.Horizontal
  86. ? _horizontal.FindIndex (x => x.pos <= boundsX && x.pos + x.length - 2 >= boundsX)
  87. : boundsY;
  88. if (c > -1)
  89. {
  90. _cursor = SelectedItem = c;
  91. SetNeedsDisplay ();
  92. }
  93. }
  94. e.Handled = true;
  95. }
  96. /// <summary>
  97. /// Gets or sets the horizontal space for this <see cref="RadioGroup"/> if the <see cref="Orientation"/> is
  98. /// <see cref="Orientation.Horizontal"/>
  99. /// </summary>
  100. public int HorizontalSpace
  101. {
  102. get => _horizontalSpace;
  103. set
  104. {
  105. if (_horizontalSpace != value && _orientation == Orientation.Horizontal)
  106. {
  107. _horizontalSpace = value;
  108. SetWidthHeight (_radioLabels);
  109. UpdateTextFormatterText ();
  110. SetNeedsDisplay ();
  111. }
  112. }
  113. }
  114. /// <summary>
  115. /// Gets or sets the <see cref="Orientation"/> for this <see cref="RadioGroup"/>. The default is
  116. /// <see cref="Orientation.Vertical"/>.
  117. /// </summary>
  118. public Orientation Orientation
  119. {
  120. get => _orientation;
  121. set => OnOrientationChanged (value);
  122. }
  123. /// <summary>
  124. /// The radio labels to display. A key binding will be added for each radio radio enabling the user to select
  125. /// and/or focus the radio label using the keyboard. See <see cref="View.HotKey"/> for details on how HotKeys work.
  126. /// </summary>
  127. /// <value>The radio labels.</value>
  128. public string [] RadioLabels
  129. {
  130. get => _radioLabels.ToArray ();
  131. set
  132. {
  133. // Remove old hot key bindings
  134. foreach (string label in _radioLabels)
  135. {
  136. if (TextFormatter.FindHotKey (label, HotKeySpecifier, out _, out Key hotKey))
  137. {
  138. AddKeyBindingsForHotKey (hotKey, Key.Empty);
  139. }
  140. }
  141. int prevCount = _radioLabels.Count;
  142. _radioLabels = value.ToList ();
  143. foreach (string label in _radioLabels)
  144. {
  145. if (TextFormatter.FindHotKey (label, HotKeySpecifier, out _, out Key hotKey))
  146. {
  147. AddKeyBindingsForHotKey (Key.Empty, hotKey);
  148. }
  149. }
  150. if (prevCount != _radioLabels.Count)
  151. {
  152. SetWidthHeight (_radioLabels);
  153. }
  154. SelectedItem = 0;
  155. SetNeedsDisplay ();
  156. }
  157. }
  158. /// <summary>The currently selected item from the list of radio labels</summary>
  159. /// <value>The selected.</value>
  160. public int SelectedItem
  161. {
  162. get => _selected;
  163. set
  164. {
  165. OnSelectedItemChanged (value, SelectedItem);
  166. _cursor = Math.Max (_selected, 0);
  167. SetNeedsDisplay ();
  168. }
  169. }
  170. /// <inheritdoc/>
  171. public override void OnDrawContent (Rectangle viewport)
  172. {
  173. base.OnDrawContent (viewport);
  174. Driver.SetAttribute (GetNormalColor ());
  175. for (var i = 0; i < _radioLabels.Count; i++)
  176. {
  177. switch (Orientation)
  178. {
  179. case Orientation.Vertical:
  180. Move (0, i);
  181. break;
  182. case Orientation.Horizontal:
  183. Move (_horizontal [i].pos, 0);
  184. break;
  185. }
  186. string rl = _radioLabels [i];
  187. Driver.SetAttribute (GetNormalColor ());
  188. Driver.AddStr ($"{(i == _selected ? Glyphs.Selected : Glyphs.UnSelected)} ");
  189. TextFormatter.FindHotKey (rl, HotKeySpecifier, out int hotPos, out Key hotKey);
  190. if (hotPos != -1 && hotKey != Key.Empty)
  191. {
  192. Rune [] rlRunes = rl.ToRunes ();
  193. for (var j = 0; j < rlRunes.Length; j++)
  194. {
  195. Rune rune = rlRunes [j];
  196. if (j == hotPos && i == _cursor)
  197. {
  198. Application.Driver.SetAttribute (
  199. HasFocus
  200. ? ColorScheme.HotFocus
  201. : GetHotNormalColor ()
  202. );
  203. }
  204. else if (j == hotPos && i != _cursor)
  205. {
  206. Application.Driver.SetAttribute (GetHotNormalColor ());
  207. }
  208. else if (HasFocus && i == _cursor)
  209. {
  210. Application.Driver.SetAttribute (ColorScheme.Focus);
  211. }
  212. if (rune == HotKeySpecifier && j + 1 < rlRunes.Length)
  213. {
  214. j++;
  215. rune = rlRunes [j];
  216. if (i == _cursor)
  217. {
  218. Application.Driver.SetAttribute (
  219. HasFocus
  220. ? ColorScheme.HotFocus
  221. : GetHotNormalColor ()
  222. );
  223. }
  224. else if (i != _cursor)
  225. {
  226. Application.Driver.SetAttribute (GetHotNormalColor ());
  227. }
  228. }
  229. Application.Driver.AddRune (rune);
  230. Driver.SetAttribute (GetNormalColor ());
  231. }
  232. }
  233. else
  234. {
  235. DrawHotString (rl, HasFocus && i == _cursor, ColorScheme);
  236. }
  237. }
  238. }
  239. /// <inheritdoc/>
  240. public override bool? OnInvokingKeyBindings (Key keyEvent)
  241. {
  242. // This is a bit of a hack. We want to handle the key bindings for the radio group but
  243. // InvokeKeyBindings doesn't pass any context so we can't tell if the key binding is for
  244. // the radio group or for one of the radio buttons. So before we call the base class
  245. // we set SelectedItem appropriately.
  246. Key key = keyEvent;
  247. if (KeyBindings.TryGet (key, out _))
  248. {
  249. // Search RadioLabels
  250. for (var i = 0; i < _radioLabels.Count; i++)
  251. {
  252. if (TextFormatter.FindHotKey (
  253. _radioLabels [i],
  254. HotKeySpecifier,
  255. out _,
  256. out Key hotKey,
  257. true
  258. )
  259. && key.NoAlt.NoCtrl.NoShift == hotKey)
  260. {
  261. SelectedItem = i;
  262. break;
  263. }
  264. }
  265. }
  266. return base.OnInvokingKeyBindings (keyEvent);
  267. }
  268. /// <summary>Called when the view orientation has changed. Invokes the <see cref="OrientationChanged"/> event.</summary>
  269. /// <param name="newOrientation"></param>
  270. /// <returns>True of the event was cancelled.</returns>
  271. public virtual bool OnOrientationChanged (Orientation newOrientation)
  272. {
  273. var args = new OrientationEventArgs (newOrientation);
  274. OrientationChanged?.Invoke (this, args);
  275. if (!args.Cancel)
  276. {
  277. _orientation = newOrientation;
  278. SetNeedsLayout ();
  279. }
  280. return args.Cancel;
  281. }
  282. // TODO: This should be cancelable
  283. /// <summary>Called whenever the current selected item changes. Invokes the <see cref="SelectedItemChanged"/> event.</summary>
  284. /// <param name="selectedItem"></param>
  285. /// <param name="previousSelectedItem"></param>
  286. public virtual void OnSelectedItemChanged (int selectedItem, int previousSelectedItem)
  287. {
  288. _selected = selectedItem;
  289. SelectedItemChanged?.Invoke (this, new SelectedItemChangedArgs (selectedItem, previousSelectedItem));
  290. }
  291. /// <summary>
  292. /// Fired when the view orientation has changed. Can be cancelled by setting
  293. /// <see cref="OrientationEventArgs.Cancel"/> to true.
  294. /// </summary>
  295. public event EventHandler<OrientationEventArgs> OrientationChanged;
  296. /// <inheritdoc/>
  297. public override Point? PositionCursor ()
  298. {
  299. int x = 0;
  300. int y = 0;
  301. switch (Orientation)
  302. {
  303. case Orientation.Vertical:
  304. y = _cursor;
  305. break;
  306. case Orientation.Horizontal:
  307. x = _horizontal [_cursor].pos;
  308. break;
  309. default:
  310. return null;
  311. }
  312. Move (x, y);
  313. return null; // Don't show the cursor
  314. }
  315. /// <summary>Allow to invoke the <see cref="SelectedItemChanged"/> after their creation.</summary>
  316. public void Refresh () { OnSelectedItemChanged (_selected, -1); }
  317. // TODO: This should use StateEventArgs<int> and should be cancelable.
  318. /// <summary>Invoked when the selected radio label has changed.</summary>
  319. public event EventHandler<SelectedItemChangedArgs> SelectedItemChanged;
  320. private void CalculateHorizontalPositions ()
  321. {
  322. if (_orientation == Orientation.Horizontal)
  323. {
  324. _horizontal = new List<(int pos, int length)> ();
  325. var start = 0;
  326. var length = 0;
  327. for (var i = 0; i < _radioLabels.Count; i++)
  328. {
  329. start += length;
  330. length = _radioLabels [i].GetColumns () + 2 + (i < _radioLabels.Count - 1 ? _horizontalSpace : 0);
  331. _horizontal.Add ((start, length));
  332. }
  333. }
  334. }
  335. private static Rectangle MakeRect (int x, int y, List<string> radioLabels)
  336. {
  337. if (radioLabels is null)
  338. {
  339. return new (x, y, 0, 0);
  340. }
  341. var width = 0;
  342. foreach (string s in radioLabels)
  343. {
  344. width = Math.Max (s.GetColumns () + 2, width);
  345. }
  346. return new (x, y, width, radioLabels.Count);
  347. }
  348. private void MoveDown ()
  349. {
  350. if (_cursor + 1 < _radioLabels.Count)
  351. {
  352. _cursor++;
  353. SetNeedsDisplay ();
  354. }
  355. else if (_cursor > 0)
  356. {
  357. _cursor = 0;
  358. SetNeedsDisplay ();
  359. }
  360. }
  361. private void MoveEnd () { _cursor = Math.Max (_radioLabels.Count - 1, 0); }
  362. private void MoveHome () { _cursor = 0; }
  363. private void MoveUp ()
  364. {
  365. if (_cursor > 0)
  366. {
  367. _cursor--;
  368. SetNeedsDisplay ();
  369. }
  370. else if (_radioLabels.Count - 1 > 0)
  371. {
  372. _cursor = _radioLabels.Count - 1;
  373. SetNeedsDisplay ();
  374. }
  375. }
  376. private void RadioGroup_LayoutStarted (object sender, EventArgs e) { /*SetWidthHeight (_radioLabels);*/ }
  377. private void SelectItem () { SelectedItem = _cursor; }
  378. private View _dummyView = new View () {};
  379. private void SetWidthHeight (List<string> radioLabels)
  380. {
  381. switch (_orientation)
  382. {
  383. case Orientation.Vertical:
  384. Rectangle r = MakeRect (0, 0, radioLabels);
  385. // TODO: Hack
  386. _dummyView.X = r.Width + +GetAdornmentsThickness ().Horizontal;
  387. _dummyView.Y = radioLabels.Count + GetAdornmentsThickness ().Vertical;
  388. //if (IsInitialized)
  389. //{
  390. // Width = r.Width + GetAdornmentsThickness ().Horizontal;
  391. // Height = radioLabels.Count + GetAdornmentsThickness ().Vertical;
  392. //}
  393. break;
  394. case Orientation.Horizontal:
  395. CalculateHorizontalPositions ();
  396. var length = 0;
  397. foreach ((int pos, int length) item in _horizontal)
  398. {
  399. length += item.length;
  400. }
  401. // TODO: Hack
  402. _dummyView.X = length + GetAdornmentsThickness ().Horizontal;
  403. _dummyView.Y = 1 + GetAdornmentsThickness ().Vertical;
  404. //if (IsInitialized)
  405. //{
  406. // Width = length + GetAdornmentsThickness ().Vertical;
  407. // Height = 1 + GetAdornmentsThickness ().Horizontal;
  408. //}
  409. break;
  410. }
  411. }
  412. }