CheckBox.cs 9.7 KB

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