OptionSelector.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. #nullable enable
  2. using System.Diagnostics;
  3. namespace Terminal.Gui.Views;
  4. /// <summary>
  5. /// Provides a user interface for displaying and selecting a single item from a list of options.
  6. /// Each option is represented by a checkbox, but only one can be selected at a time.
  7. /// </summary>
  8. public class OptionSelector : View, IOrientation, IDesignable
  9. {
  10. /// <summary>
  11. /// Initializes a new instance of the <see cref="OptionSelector"/> class.
  12. /// </summary>
  13. public OptionSelector ()
  14. {
  15. CanFocus = true;
  16. Width = Dim.Auto (DimAutoStyle.Content);
  17. Height = Dim.Auto (DimAutoStyle.Content);
  18. _orientationHelper = new (this);
  19. _orientationHelper.Orientation = Orientation.Vertical;
  20. // Accept (Enter key or DoubleClick) - Raise Accept event - DO NOT advance state
  21. AddCommand (Command.Accept, HandleAcceptCommand);
  22. CreateCheckBoxes ();
  23. }
  24. private bool? HandleAcceptCommand (ICommandContext? ctx) { return RaiseAccepting (ctx); }
  25. private int? _selectedItem;
  26. /// <summary>
  27. /// Gets or sets the index of the selected item. Will be <see langword="null"/> if no item is selected.
  28. /// </summary>
  29. public int? SelectedItem
  30. {
  31. get => _selectedItem;
  32. set
  33. {
  34. if (value < 0 || value >= SubViews.OfType<CheckBox> ().Count ())
  35. {
  36. throw new ArgumentOutOfRangeException (nameof (value), @$"SelectedItem must be between 0 and {SubViews.OfType<CheckBox> ().Count ()-1}");
  37. }
  38. if (_selectedItem == value)
  39. {
  40. return;
  41. }
  42. int? previousSelectedItem = _selectedItem;
  43. _selectedItem = value;
  44. UpdateChecked ();
  45. RaiseSelectedItemChanged (previousSelectedItem);
  46. }
  47. }
  48. private void RaiseSelectedItemChanged (int? previousSelectedItem)
  49. {
  50. OnSelectedItemChanged (SelectedItem, previousSelectedItem);
  51. if (SelectedItem.HasValue)
  52. {
  53. SelectedItemChanged?.Invoke (this, new (SelectedItem, previousSelectedItem));
  54. }
  55. }
  56. /// <summary>
  57. /// Called when <see cref="SelectedItem"/> has changed.
  58. /// </summary>
  59. protected virtual void OnSelectedItemChanged (int? selectedItem, int? previousSelectedItem) { }
  60. /// <summary>
  61. /// Raised when <see cref="SelectedItem"/> has changed.
  62. /// </summary>
  63. public event EventHandler<SelectedItemChangedArgs>? SelectedItemChanged;
  64. private IReadOnlyList<string>? _options;
  65. /// <summary>
  66. /// Gets or sets the list of options.
  67. /// </summary>
  68. public IReadOnlyList<string>? Options
  69. {
  70. get => _options;
  71. set
  72. {
  73. _options = value;
  74. CreateCheckBoxes ();
  75. }
  76. }
  77. private bool _assignHotKeysToCheckBoxes;
  78. /// <summary>
  79. /// If <see langword="true"/> the CheckBoxes will each be automatically assigned a hotkey.
  80. /// <see cref="UsedHotKeys"/> will be used to ensure unique keys are assigned. Set <see cref="UsedHotKeys"/>
  81. /// before setting <see cref="Options"/> with any hotkeys that may conflict with other Views.
  82. /// </summary>
  83. public bool AssignHotKeysToCheckBoxes
  84. {
  85. get => _assignHotKeysToCheckBoxes;
  86. set
  87. {
  88. if (_assignHotKeysToCheckBoxes == value)
  89. {
  90. return;
  91. }
  92. _assignHotKeysToCheckBoxes = value;
  93. CreateCheckBoxes ();
  94. UpdateChecked ();
  95. }
  96. }
  97. /// <summary>
  98. /// Gets the list of hotkeys already used by the CheckBoxes or that should not be used if
  99. /// <see cref="AssignHotKeysToCheckBoxes"/>
  100. /// is enabled.
  101. /// </summary>
  102. public List<Key> UsedHotKeys { get; } = new ();
  103. private void CreateCheckBoxes ()
  104. {
  105. if (Options is null)
  106. {
  107. return;
  108. }
  109. foreach (CheckBox cb in RemoveAll<CheckBox> ())
  110. {
  111. cb.Dispose ();
  112. }
  113. for (var index = 0; index < Options.Count; index++)
  114. {
  115. Add (CreateCheckBox (Options [index], index));
  116. }
  117. SetLayout ();
  118. }
  119. /// <summary>
  120. ///
  121. /// </summary>
  122. /// <param name="name"></param>
  123. /// <param name="index"></param>
  124. /// <returns></returns>
  125. protected virtual CheckBox CreateCheckBox (string name, int index)
  126. {
  127. string nameWithHotKey = name;
  128. if (AssignHotKeysToCheckBoxes)
  129. {
  130. // Find the first char in label that is [a-z], [A-Z], or [0-9]
  131. for (var i = 0; i < name.Length; i++)
  132. {
  133. char c = char.ToLowerInvariant (name [i]);
  134. if (UsedHotKeys.Contains (new (c)) || !char.IsAsciiLetterOrDigit (c))
  135. {
  136. continue;
  137. }
  138. if (char.IsAsciiLetterOrDigit (c))
  139. {
  140. char? hotChar = c;
  141. nameWithHotKey = name.Insert (i, HotKeySpecifier.ToString ());
  142. UsedHotKeys.Add (new (hotChar));
  143. break;
  144. }
  145. }
  146. }
  147. var checkbox = new CheckBox
  148. {
  149. CanFocus = true,
  150. Title = nameWithHotKey,
  151. Id = name,
  152. Data = index,
  153. //HighlightStates = HighlightStates.Hover,
  154. RadioStyle = true
  155. };
  156. checkbox.GettingAttributeForRole += (_, e) =>
  157. {
  158. if (SuperView is { HasFocus: false })
  159. {
  160. return;
  161. }
  162. switch (e.Role)
  163. {
  164. case VisualRole.Normal:
  165. e.Handled = true;
  166. if (!HasFocus)
  167. {
  168. e.Result = GetAttributeForRole (VisualRole.Focus);
  169. }
  170. else
  171. {
  172. // If _scheme was set, it's because of Hover
  173. if (checkbox.HasScheme)
  174. {
  175. e.Result = checkbox.GetAttributeForRole(VisualRole.Normal);
  176. }
  177. else
  178. {
  179. e.Result = GetAttributeForRole (VisualRole.Normal);
  180. }
  181. }
  182. break;
  183. case VisualRole.HotNormal:
  184. e.Handled = true;
  185. if (!HasFocus)
  186. {
  187. e.Result = GetAttributeForRole (VisualRole.HotFocus);
  188. }
  189. else
  190. {
  191. e.Result = GetAttributeForRole (VisualRole.HotNormal);
  192. }
  193. break;
  194. }
  195. };
  196. checkbox.Selecting += (sender, args) =>
  197. {
  198. if (RaiseSelecting (args.Context) is true)
  199. {
  200. args.Handled = true;
  201. return;
  202. }
  203. ;
  204. if (RaiseAccepting (args.Context) is true)
  205. {
  206. args.Handled = true;
  207. }
  208. };
  209. checkbox.CheckedStateChanged += (sender, args) =>
  210. {
  211. if (checkbox.CheckedState == CheckState.Checked)
  212. {
  213. SelectedItem = index;
  214. }
  215. };
  216. return checkbox;
  217. }
  218. private void SetLayout ()
  219. {
  220. foreach (View sv in SubViews)
  221. {
  222. if (Orientation == Orientation.Vertical)
  223. {
  224. sv.X = 0;
  225. sv.Y = Pos.Align (Alignment.Start);
  226. }
  227. else
  228. {
  229. sv.X = Pos.Align (Alignment.Start);
  230. sv.Y = 0;
  231. sv.Margin!.Thickness = new (0, 0, 1, 0);
  232. }
  233. }
  234. }
  235. private void UpdateChecked ()
  236. {
  237. foreach (CheckBox cb in SubViews.OfType<CheckBox> ())
  238. {
  239. var index = (int)(cb.Data ?? throw new InvalidOperationException ("CheckBox.Data must be set"));
  240. cb.CheckedState = index == SelectedItem ? CheckState.Checked : CheckState.UnChecked;
  241. }
  242. }
  243. #region IOrientation
  244. /// <summary>
  245. /// Gets or sets the <see cref="Orientation"/> for this <see cref="OptionSelector"/>. The default is
  246. /// <see cref="Orientation.Vertical"/>.
  247. /// </summary>
  248. public Orientation Orientation
  249. {
  250. get => _orientationHelper.Orientation;
  251. set => _orientationHelper.Orientation = value;
  252. }
  253. private readonly OrientationHelper _orientationHelper;
  254. #pragma warning disable CS0067 // The event is never used
  255. /// <inheritdoc/>
  256. public event EventHandler<CancelEventArgs<Orientation>>? OrientationChanging;
  257. /// <inheritdoc/>
  258. public event EventHandler<EventArgs<Orientation>>? OrientationChanged;
  259. #pragma warning restore CS0067 // The event is never used
  260. /// <summary>Called when <see cref="Orientation"/> has changed.</summary>
  261. /// <param name="newOrientation"></param>
  262. public void OnOrientationChanged (Orientation newOrientation) { SetLayout (); }
  263. #endregion IOrientation
  264. /// <inheritdoc/>
  265. public bool EnableForDesign ()
  266. {
  267. AssignHotKeysToCheckBoxes = true;
  268. Options = ["Option 1", "Option 2", "Third Option", "Option Quattro"];
  269. return true;
  270. }
  271. }