CheckBox.cs 9.7 KB

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