RadioGroup.cs 15 KB

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