CheckBox.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. namespace Terminal.Gui.Views;
  2. /// <summary>Shows a checkbox that can be cycled between two or three states.</summary>
  3. /// <remarks>
  4. /// <para>
  5. /// <see cref="RadioStyle"/> is used to display radio button style glyphs (●) instead of checkbox style glyphs (☑).
  6. /// </para>
  7. /// </remarks>
  8. public class CheckBox : View
  9. {
  10. private static MouseState _defaultHighlightStates = MouseState.PressedOutside | MouseState.Pressed | MouseState.In; // Resources/config.json overrides
  11. /// <summary>
  12. /// Gets or sets the default Highlight Style.
  13. /// </summary>
  14. [ConfigurationProperty (Scope = typeof (ThemeScope))]
  15. public static MouseState DefaultHighlightStates
  16. {
  17. get => _defaultHighlightStates;
  18. set => _defaultHighlightStates = value;
  19. }
  20. /// <summary>
  21. /// Initializes a new instance of <see cref="CheckBox"/>.
  22. /// </summary>
  23. public CheckBox ()
  24. {
  25. Width = Dim.Auto (DimAutoStyle.Text);
  26. Height = Dim.Auto (DimAutoStyle.Text, 1);
  27. CanFocus = true;
  28. // Activate (Space key and single-click) - Raise Activate event and Advance
  29. // - DO NOT raise Accept
  30. // - DO NOT SetFocus
  31. AddCommand (Command.Select, ActivateAndAdvance);
  32. // Accept (Enter key and double-click) - Raise Accept event
  33. // - DO NOT advance state
  34. // The default Accept handler does that.
  35. MouseBindings.Add (MouseFlags.Button1DoubleClicked, Command.Accept);
  36. TitleChanged += Checkbox_TitleChanged;
  37. HighlightStates = DefaultHighlightStates;
  38. }
  39. /// <inheritdoc />
  40. protected override bool OnHandlingHotKey (CommandEventArgs args)
  41. {
  42. // Invoke Activate on ourselves
  43. if (InvokeCommand (Command.Select, args.Context) is true)
  44. {
  45. // Default behavior for View is to set Focus on hotkey. We need to return
  46. // true here to indicate Activate was handled. That will prevent the default
  47. // behavior from setting focus, so we do it here.
  48. SetFocus ();
  49. return true;
  50. }
  51. return base.OnHandlingHotKey (args);
  52. }
  53. private bool? ActivateAndAdvance (ICommandContext? commandContext)
  54. {
  55. if (RaiseSelecting (commandContext) is true)
  56. {
  57. return true;
  58. }
  59. bool? cancelled = AdvanceCheckState ();
  60. if (cancelled is true)
  61. {
  62. return true;
  63. }
  64. return commandContext?.Command == Command.HotKey ? cancelled : cancelled is false;
  65. }
  66. private void Checkbox_TitleChanged (object? sender, EventArgs<string> e)
  67. {
  68. base.Text = e.Value;
  69. TextFormatter.HotKeySpecifier = HotKeySpecifier;
  70. }
  71. /// <inheritdoc/>
  72. public override string Text
  73. {
  74. get => Title;
  75. set => base.Text = Title = value;
  76. }
  77. /// <inheritdoc/>
  78. public override Rune HotKeySpecifier
  79. {
  80. get => base.HotKeySpecifier;
  81. set => TextFormatter.HotKeySpecifier = base.HotKeySpecifier = value;
  82. }
  83. private bool _allowNone;
  84. /// <summary>
  85. /// If <see langword="true"/> allows <see cref="CheckedState"/> to be <see cref="CheckState.None"/>. The default is
  86. /// <see langword="false"/>.
  87. /// </summary>
  88. public bool AllowCheckStateNone
  89. {
  90. get => _allowNone;
  91. set
  92. {
  93. if (_allowNone == value)
  94. {
  95. return;
  96. }
  97. _allowNone = value;
  98. if (CheckedState == CheckState.None)
  99. {
  100. CheckedState = CheckState.UnChecked;
  101. }
  102. }
  103. }
  104. private CheckState _checkedState = CheckState.UnChecked;
  105. /// <summary>
  106. /// The state of the <see cref="CheckBox"/>.
  107. /// </summary>
  108. /// <remarks>
  109. /// <para>
  110. /// If <see cref="AllowCheckStateNone"/> is <see langword="true"/> and <see cref="CheckState.None"/>, the
  111. /// <see cref="CheckBox"/>
  112. /// will display the <c>Glyphs.CheckStateNone</c> character (☒).
  113. /// </para>
  114. /// <para>
  115. /// If <see cref="CheckState.UnChecked"/>, the <see cref="CheckBox"/>
  116. /// will display the <c>Glyphs.CheckStateUnChecked</c> character (☐).
  117. /// </para>
  118. /// <para>
  119. /// If <see cref="CheckState.Checked"/>, the <see cref="CheckBox"/>
  120. /// will display the <c>Glyphs.CheckStateChecked</c> character (☑).
  121. /// </para>
  122. /// </remarks>
  123. public CheckState CheckedState
  124. {
  125. get => _checkedState;
  126. set => ChangeCheckedState (value);
  127. }
  128. /// <summary>
  129. /// INTERNAL Sets CheckedState.
  130. /// </summary>
  131. /// <param name="value"></param>
  132. /// <returns>
  133. /// <see langword="true"/> if state change was canceled, <see langword="false"/> if the state changed, and
  134. /// <see langword="null"/> if the state was not changed for some other reason.
  135. /// </returns>
  136. private bool? ChangeCheckedState (CheckState value)
  137. {
  138. if (_checkedState == value || (value is CheckState.None && !AllowCheckStateNone))
  139. {
  140. return null;
  141. }
  142. ResultEventArgs<CheckState> e = new (value);
  143. if (OnCheckedStateChanging (e))
  144. {
  145. return true;
  146. }
  147. CheckedStateChanging?.Invoke (this, e);
  148. if (e.Handled)
  149. {
  150. return e.Handled;
  151. }
  152. _checkedState = value;
  153. UpdateTextFormatterText ();
  154. SetNeedsLayout ();
  155. EventArgs<CheckState> args = new (in _checkedState);
  156. OnCheckedStateChanged (args);
  157. CheckedStateChanged?.Invoke (this, args);
  158. return false;
  159. }
  160. /// <summary>Called when the <see cref="CheckBox"/> state is changing.</summary>
  161. /// <remarks>
  162. /// <para>
  163. /// The state change can be cancelled by setting the args.Cancel to <see langword="true"/>.
  164. /// </para>
  165. /// </remarks>
  166. protected virtual bool OnCheckedStateChanging (ResultEventArgs<CheckState> args) { return false; }
  167. /// <summary>Raised when the <see cref="CheckBox"/> state is changing.</summary>
  168. /// <remarks>
  169. /// <para>
  170. /// This event can be cancelled. If cancelled, the <see cref="CheckBox"/> will not change its state.
  171. /// </para>
  172. /// </remarks>
  173. public event EventHandler<ResultEventArgs<CheckState>>? CheckedStateChanging;
  174. /// <summary>Called when the <see cref="CheckBox"/> state has changed.</summary>
  175. protected virtual void OnCheckedStateChanged (EventArgs<CheckState> args) { }
  176. /// <summary>Raised when the <see cref="CheckBox"/> state has changed.</summary>
  177. public event EventHandler<EventArgs<CheckState>>? CheckedStateChanged;
  178. /// <summary>
  179. /// Advances <see cref="CheckedState"/> to the next value. Invokes the cancelable <see cref="CheckedStateChanging"/>
  180. /// event.
  181. /// </summary>
  182. /// <remarks>
  183. /// <para>
  184. /// Cycles through the states <see cref="CheckState.None"/>, <see cref="CheckState.Checked"/>, and
  185. /// <see cref="CheckState.UnChecked"/>.
  186. /// </para>
  187. /// <para>
  188. /// If the <see cref="CheckedStateChanging"/> event is not canceled, the <see cref="CheckedState"/> will be updated
  189. /// and the <see cref="Command.Accept"/> event will be raised.
  190. /// </para>
  191. /// </remarks>
  192. /// <returns>
  193. /// <see langword="true"/> if state change was canceled, <see langword="false"/> if the state changed, and
  194. /// <see langword="null"/> if the state was not changed for some other reason.
  195. /// </returns>
  196. public bool? AdvanceCheckState ()
  197. {
  198. CheckState oldValue = CheckedState;
  199. ResultEventArgs<CheckState> e = new (oldValue);
  200. switch (CheckedState)
  201. {
  202. case CheckState.None:
  203. e.Result = CheckState.Checked;
  204. break;
  205. case CheckState.Checked:
  206. e.Result = CheckState.UnChecked;
  207. break;
  208. case CheckState.UnChecked:
  209. if (AllowCheckStateNone)
  210. {
  211. e.Result = CheckState.None;
  212. }
  213. else
  214. {
  215. e.Result = CheckState.Checked;
  216. }
  217. break;
  218. }
  219. bool? cancelled = ChangeCheckedState (e.Result);
  220. return cancelled;
  221. }
  222. /// <inheritdoc />
  223. protected override bool OnClearingViewport ()
  224. {
  225. SetAttributeForRole (HasFocus ? VisualRole.Focus : VisualRole.Normal);
  226. return base.OnClearingViewport ();
  227. }
  228. /// <inheritdoc/>
  229. protected override void UpdateTextFormatterText ()
  230. {
  231. base.UpdateTextFormatterText ();
  232. Rune glyph = RadioStyle ? GetRadioGlyph () : GetCheckGlyph ();
  233. switch (TextAlignment)
  234. {
  235. case Alignment.Start:
  236. case Alignment.Center:
  237. case Alignment.Fill:
  238. TextFormatter.Text = $"{glyph} {Text}";
  239. break;
  240. case Alignment.End:
  241. TextFormatter.Text = $"{Text} {glyph}";
  242. break;
  243. }
  244. }
  245. private Rune GetCheckGlyph ()
  246. {
  247. return CheckedState switch
  248. {
  249. CheckState.Checked => Glyphs.CheckStateChecked,
  250. CheckState.UnChecked => Glyphs.CheckStateUnChecked,
  251. CheckState.None => Glyphs.CheckStateNone,
  252. _ => throw new ArgumentOutOfRangeException ()
  253. };
  254. }
  255. /// <summary>
  256. /// If <see langword="true"/>, the <see cref="CheckBox"/> will display radio button style glyphs (●) instead of
  257. /// checkbox style glyphs (☑).
  258. /// </summary>
  259. public bool RadioStyle { get; set; }
  260. private Rune GetRadioGlyph ()
  261. {
  262. return CheckedState switch
  263. {
  264. CheckState.Checked => Glyphs.Selected,
  265. CheckState.UnChecked => Glyphs.UnSelected,
  266. CheckState.None => Glyphs.Dot,
  267. _ => throw new ArgumentOutOfRangeException ()
  268. };
  269. }
  270. }