RadioGroup.cs 17 KB

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