RadioGroup.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. #nullable enable
  2. namespace Terminal.Gui;
  3. /// <summary>Displays a group of labels each with a selected indicator. Only one of those can be selected at a given time.</summary>
  4. public class RadioGroup : View, IDesignable, IOrientation
  5. {
  6. /// <summary>
  7. /// Initializes a new instance of the <see cref="RadioGroup"/> class.
  8. /// </summary>
  9. public RadioGroup ()
  10. {
  11. CanFocus = true;
  12. Width = Dim.Auto (DimAutoStyle.Content);
  13. Height = Dim.Auto (DimAutoStyle.Content);
  14. // Things this view knows how to do
  15. AddCommand (
  16. Command.Up,
  17. () =>
  18. {
  19. if (!HasFocus)
  20. {
  21. return false;
  22. }
  23. return MoveUpLeft ();
  24. }
  25. );
  26. AddCommand (
  27. Command.Down,
  28. () =>
  29. {
  30. if (!HasFocus)
  31. {
  32. return false;
  33. }
  34. return MoveDownRight ();
  35. }
  36. );
  37. AddCommand (
  38. Command.Start,
  39. () =>
  40. {
  41. if (!HasFocus)
  42. {
  43. return false;
  44. }
  45. MoveHome ();
  46. return true;
  47. }
  48. );
  49. AddCommand (
  50. Command.End,
  51. () =>
  52. {
  53. if (!HasFocus)
  54. {
  55. return false;
  56. }
  57. MoveEnd ();
  58. return true;
  59. }
  60. );
  61. AddCommand (
  62. Command.Select,
  63. () =>
  64. {
  65. if (SelectedItem == Cursor)
  66. {
  67. if (!MoveDownRight ())
  68. {
  69. MoveHome ();
  70. }
  71. }
  72. return ChangeSelectedItem (Cursor) is false or null;
  73. });
  74. // Accept (Enter key) - Raise Accept event - DO NOT advance state
  75. AddCommand (Command.Accept, RaiseAcceptEvent);
  76. AddCommand (
  77. Command.HotKey,
  78. ctx =>
  79. {
  80. var item = ctx.KeyBinding?.Context as int?;
  81. if (HasFocus)
  82. {
  83. if (ctx is { KeyBinding: { } } && (ctx.KeyBinding.Value.BoundView != this || HotKey == ctx.Key?.NoAlt.NoCtrl.NoShift))
  84. {
  85. // It's this.HotKey OR Another View (Label?) forwarded the hotkey command to us - Act just like `Space` (Select)
  86. return InvokeCommand (Command.Select, ctx.Key, ctx.KeyBinding);
  87. }
  88. }
  89. if (item is { } && item < _radioLabels.Count)
  90. {
  91. if (item.Value == SelectedItem)
  92. {
  93. return true;
  94. }
  95. // If a RadioItem.HotKey is pressed we always set the selected item - never SetFocus
  96. if (ChangeSelectedItem (item.Value) is null or false)
  97. {
  98. return true;
  99. }
  100. return false;
  101. }
  102. if (SelectedItem == -1 && ChangeSelectedItem (0) == true)
  103. {
  104. return true;
  105. }
  106. SetFocus ();
  107. return true;
  108. });
  109. _orientationHelper = new (this);
  110. _orientationHelper.Orientation = Orientation.Vertical;
  111. _orientationHelper.OrientationChanging += (sender, e) => OrientationChanging?.Invoke (this, e);
  112. _orientationHelper.OrientationChanged += (sender, e) => OrientationChanged?.Invoke (this, e);
  113. SetupKeyBindings ();
  114. LayoutStarted += RadioGroup_LayoutStarted;
  115. HighlightStyle = HighlightStyle.PressedOutside | HighlightStyle.Pressed;
  116. MouseClick += RadioGroup_MouseClick;
  117. }
  118. // TODO: Fix InvertColorsOnPress - only highlight the selected item
  119. private void SetupKeyBindings ()
  120. {
  121. // Default keybindings for this view
  122. if (Orientation == Orientation.Vertical)
  123. {
  124. KeyBindings.Remove (Key.CursorUp);
  125. KeyBindings.Add (Key.CursorUp, Command.Up);
  126. KeyBindings.Remove (Key.CursorDown);
  127. KeyBindings.Add (Key.CursorDown, Command.Down);
  128. }
  129. else
  130. {
  131. KeyBindings.Remove (Key.CursorLeft);
  132. KeyBindings.Add (Key.CursorLeft, Command.Up);
  133. KeyBindings.Remove (Key.CursorRight);
  134. KeyBindings.Add (Key.CursorRight, Command.Down);
  135. }
  136. KeyBindings.Remove (Key.Home);
  137. KeyBindings.Add (Key.Home, Command.Start);
  138. KeyBindings.Remove (Key.End);
  139. KeyBindings.Add (Key.End, Command.End);
  140. }
  141. /// <summary>
  142. /// Gets or sets whether double clicking on a Radio Item will cause the <see cref="View.Accept"/> event to be raised.
  143. /// </summary>
  144. /// <remarks>
  145. /// <para>
  146. /// If <see langword="false"/> and Accept is not handled, the Accept event on the <see cref="View.SuperView"/> will be raised. The default is
  147. /// <see langword="true"/>.
  148. /// </para>
  149. /// </remarks>
  150. public bool DoubleClickAccepts { get; set; } = true;
  151. private void RadioGroup_MouseClick (object sender, MouseEventEventArgs e)
  152. {
  153. if (e.MouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked))
  154. {
  155. int viewportX = e.MouseEvent.Position.X;
  156. int viewportY = e.MouseEvent.Position.Y;
  157. int pos = Orientation == Orientation.Horizontal ? viewportX : viewportY;
  158. int rCount = Orientation == Orientation.Horizontal
  159. ? _horizontal.Last ().pos + _horizontal.Last ().length
  160. : _radioLabels.Count;
  161. if (pos < rCount)
  162. {
  163. int c = Orientation == Orientation.Horizontal
  164. ? _horizontal.FindIndex (x => x.pos <= viewportX && x.pos + x.length - 2 >= viewportX)
  165. : viewportY;
  166. if (c > -1)
  167. {
  168. if (ChangeSelectedItem (c) == false)
  169. {
  170. Cursor = c;
  171. e.Handled = true;
  172. }
  173. }
  174. }
  175. }
  176. if (DoubleClickAccepts && e.MouseEvent.Flags.HasFlag (MouseFlags.Button1DoubleClicked))
  177. {
  178. int savedSelectedItem = SelectedItem;
  179. if (RaiseAcceptEvent () == true)
  180. {
  181. e.Handled = false;
  182. _selected = savedSelectedItem;
  183. }
  184. if (SuperView?.InvokeCommand (Command.Accept) is false or null)
  185. {
  186. e.Handled = true;
  187. }
  188. }
  189. }
  190. private List<(int pos, int length)> _horizontal;
  191. private int _horizontalSpace = 2;
  192. /// <summary>
  193. /// Gets or sets the horizontal space for this <see cref="RadioGroup"/> if the <see cref="Orientation"/> is
  194. /// <see cref="Orientation.Horizontal"/>
  195. /// </summary>
  196. public int HorizontalSpace
  197. {
  198. get => _horizontalSpace;
  199. set
  200. {
  201. if (_horizontalSpace != value && Orientation == Orientation.Horizontal)
  202. {
  203. _horizontalSpace = value;
  204. UpdateTextFormatterText ();
  205. SetContentSize ();
  206. }
  207. }
  208. }
  209. private List<string> _radioLabels = [];
  210. /// <summary>
  211. /// The radio labels to display. A key binding will be added for each radio enabling the user to select
  212. /// and/or focus the radio label using the keyboard. See <see cref="View.HotKey"/> for details on how HotKeys work.
  213. /// </summary>
  214. /// <value>The radio labels.</value>
  215. public string [] RadioLabels
  216. {
  217. get => _radioLabels.ToArray ();
  218. set
  219. {
  220. // Remove old hot key bindings
  221. foreach (string label in _radioLabels)
  222. {
  223. if (TextFormatter.FindHotKey (label, HotKeySpecifier, out _, out Key hotKey))
  224. {
  225. AddKeyBindingsForHotKey (hotKey, Key.Empty);
  226. }
  227. }
  228. int prevCount = _radioLabels.Count;
  229. _radioLabels = value.ToList ();
  230. for (var index = 0; index < _radioLabels.Count; index++)
  231. {
  232. string label = _radioLabels [index];
  233. if (TextFormatter.FindHotKey (label, HotKeySpecifier, out _, out Key hotKey))
  234. {
  235. AddKeyBindingsForHotKey (Key.Empty, hotKey, index);
  236. }
  237. }
  238. SelectedItem = 0;
  239. SetContentSize ();
  240. }
  241. }
  242. private int _selected;
  243. /// <summary>The currently selected item from the list of radio labels</summary>
  244. /// <value>The selected.</value>
  245. public int SelectedItem
  246. {
  247. get => _selected;
  248. set => ChangeSelectedItem (value);
  249. }
  250. /// <summary>
  251. /// INTERNAL Sets the selected item.
  252. /// </summary>
  253. /// <param name="value"></param>
  254. /// <returns><see langword="true"/> if state change was canceled, <see langword="false"/> if the state changed, and <see langword="null"/> if the state was not changed for some other reason.</returns>
  255. private bool? ChangeSelectedItem (int value)
  256. {
  257. if (_selected == value || value > _radioLabels.Count - 1)
  258. {
  259. return null;
  260. }
  261. if (RaiseSelectEvent () == true)
  262. {
  263. return true;
  264. }
  265. int savedSelected = _selected;
  266. _selected = value;
  267. Cursor = Math.Max (_selected, 0);
  268. OnSelectedItemChanged (value, SelectedItem);
  269. SelectedItemChanged?.Invoke (this, new (SelectedItem, savedSelected));
  270. SetNeedsDisplay ();
  271. return false;
  272. }
  273. /// <inheritdoc/>
  274. public override void OnDrawContent (Rectangle viewport)
  275. {
  276. base.OnDrawContent (viewport);
  277. Driver.SetAttribute (GetNormalColor ());
  278. for (var i = 0; i < _radioLabels.Count; i++)
  279. {
  280. switch (Orientation)
  281. {
  282. case Orientation.Vertical:
  283. Move (0, i);
  284. break;
  285. case Orientation.Horizontal:
  286. Move (_horizontal [i].pos, 0);
  287. break;
  288. }
  289. string rl = _radioLabels [i];
  290. Driver.SetAttribute (GetNormalColor ());
  291. Driver.AddStr ($"{(i == _selected ? Glyphs.Selected : Glyphs.UnSelected)} ");
  292. TextFormatter.FindHotKey (rl, HotKeySpecifier, out int hotPos, out Key hotKey);
  293. if (hotPos != -1 && hotKey != Key.Empty)
  294. {
  295. Rune [] rlRunes = rl.ToRunes ();
  296. for (var j = 0; j < rlRunes.Length; j++)
  297. {
  298. Rune rune = rlRunes [j];
  299. if (j == hotPos && i == Cursor)
  300. {
  301. Application.Driver?.SetAttribute (
  302. HasFocus
  303. ? ColorScheme.HotFocus
  304. : GetHotNormalColor ()
  305. );
  306. }
  307. else if (j == hotPos && i != Cursor)
  308. {
  309. Application.Driver?.SetAttribute (GetHotNormalColor ());
  310. }
  311. else if (HasFocus && i == Cursor)
  312. {
  313. Application.Driver?.SetAttribute (GetFocusColor ());
  314. }
  315. if (rune == HotKeySpecifier && j + 1 < rlRunes.Length)
  316. {
  317. j++;
  318. rune = rlRunes [j];
  319. if (i == Cursor)
  320. {
  321. Application.Driver?.SetAttribute (
  322. HasFocus
  323. ? ColorScheme.HotFocus
  324. : GetHotNormalColor ()
  325. );
  326. }
  327. else if (i != Cursor)
  328. {
  329. Application.Driver?.SetAttribute (GetHotNormalColor ());
  330. }
  331. }
  332. Application.Driver?.AddRune (rune);
  333. Driver.SetAttribute (GetNormalColor ());
  334. }
  335. }
  336. else
  337. {
  338. DrawHotString (rl, HasFocus && i == Cursor);
  339. }
  340. }
  341. }
  342. #region IOrientation
  343. /// <summary>
  344. /// Gets or sets the <see cref="Orientation"/> for this <see cref="RadioGroup"/>. The default is
  345. /// <see cref="Orientation.Vertical"/>.
  346. /// </summary>
  347. public Orientation Orientation
  348. {
  349. get => _orientationHelper.Orientation;
  350. set => _orientationHelper.Orientation = value;
  351. }
  352. private readonly OrientationHelper _orientationHelper;
  353. /// <inheritdoc/>
  354. public event EventHandler<CancelEventArgs<Orientation>> OrientationChanging;
  355. /// <inheritdoc/>
  356. public event EventHandler<EventArgs<Orientation>> OrientationChanged;
  357. /// <summary>Called when <see cref="Orientation"/> has changed.</summary>
  358. /// <param name="newOrientation"></param>
  359. public void OnOrientationChanged (Orientation newOrientation)
  360. {
  361. SetupKeyBindings ();
  362. SetContentSize ();
  363. }
  364. #endregion IOrientation
  365. // TODO: This should be cancelable
  366. /// <summary>Called whenever the current selected item changes. Invokes the <see cref="SelectedItemChanged"/> event.</summary>
  367. /// <param name="selectedItem"></param>
  368. /// <param name="previousSelectedItem"></param>
  369. protected virtual void OnSelectedItemChanged (int selectedItem, int previousSelectedItem) { }
  370. /// <summary>
  371. /// Gets or sets the <see cref="RadioLabels"/> index for the cursor. The cursor may or may not be the selected
  372. /// RadioItem.
  373. /// </summary>
  374. /// <remarks>
  375. /// <para>
  376. /// Maps to either the X or Y position within <see cref="View.Viewport"/> depending on <see cref="Orientation"/>.
  377. /// </para>
  378. /// </remarks>
  379. public int Cursor { get; set; }
  380. /// <inheritdoc/>
  381. public override Point? PositionCursor ()
  382. {
  383. var x = 0;
  384. var y = 0;
  385. switch (Orientation)
  386. {
  387. case Orientation.Vertical:
  388. y = Cursor;
  389. break;
  390. case Orientation.Horizontal:
  391. if (_horizontal.Count > 0)
  392. {
  393. x = _horizontal [Cursor].pos;
  394. }
  395. break;
  396. default:
  397. return null;
  398. }
  399. Move (x, y);
  400. return null; // Don't show the cursor
  401. }
  402. /// <summary>Allow to invoke the <see cref="SelectedItemChanged"/> after their creation.</summary>
  403. public void Refresh () { OnSelectedItemChanged (_selected, -1); }
  404. // TODO: This should use StateEventArgs<int> and should be cancelable.
  405. /// <summary>Invoked when the selected radio label has changed.</summary>
  406. public event EventHandler<SelectedItemChangedArgs> SelectedItemChanged;
  407. private bool MoveDownRight ()
  408. {
  409. if (Cursor + 1 < _radioLabels.Count)
  410. {
  411. Cursor++;
  412. SetNeedsDisplay ();
  413. return true;
  414. }
  415. // Moving past should move focus to next view, not wrap
  416. return false;
  417. }
  418. private void MoveEnd () { Cursor = Math.Max (_radioLabels.Count - 1, 0); }
  419. private void MoveHome () { Cursor = 0; }
  420. private bool MoveUpLeft ()
  421. {
  422. if (Cursor > 0)
  423. {
  424. Cursor--;
  425. SetNeedsDisplay ();
  426. return true;
  427. }
  428. // Moving past should move focus to next view, not wrap
  429. return false;
  430. }
  431. private void RadioGroup_LayoutStarted (object sender, EventArgs e) { SetContentSize (); }
  432. private void SetContentSize ()
  433. {
  434. switch (Orientation)
  435. {
  436. case Orientation.Vertical:
  437. var width = 0;
  438. foreach (string s in _radioLabels)
  439. {
  440. width = Math.Max (s.GetColumns () + 2, width);
  441. }
  442. SetContentSize (new (width, _radioLabels.Count));
  443. break;
  444. case Orientation.Horizontal:
  445. _horizontal = new ();
  446. var start = 0;
  447. var length = 0;
  448. for (var i = 0; i < _radioLabels.Count; i++)
  449. {
  450. start += length;
  451. length = _radioLabels [i].GetColumns () + 2 + (i < _radioLabels.Count - 1 ? _horizontalSpace : 0);
  452. _horizontal.Add ((start, length));
  453. }
  454. SetContentSize (new (_horizontal.Sum (item => item.length), 1));
  455. break;
  456. }
  457. }
  458. /// <inheritdoc/>
  459. public bool EnableForDesign ()
  460. {
  461. RadioLabels = new [] { "Option _1", "Option _2", "Option _3" };
  462. return true;
  463. }
  464. }