RadioGroup.cs 18 KB

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