CheckBox.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. #nullable enable
  2. using System.Reflection.Metadata;
  3. namespace Terminal.Gui;
  4. /// <summary>Shows a check box that can be cycled between two or three states.</summary>
  5. public class CheckBox : View
  6. {
  7. /// <summary>
  8. /// Gets or sets the default Highlight Style.
  9. /// </summary>
  10. [SerializableConfigurationProperty (Scope = typeof (ThemeScope))]
  11. public static HighlightStyle DefaultHighlightStyle { get; set; } = HighlightStyle.PressedOutside | HighlightStyle.Pressed | HighlightStyle.Hover;
  12. /// <summary>
  13. /// Initializes a new instance of <see cref="CheckBox"/>.
  14. /// </summary>
  15. public CheckBox ()
  16. {
  17. Width = Dim.Auto (DimAutoStyle.Text);
  18. Height = Dim.Auto (DimAutoStyle.Text, minimumContentDim: 1);
  19. CanFocus = true;
  20. // Select (Space key and single-click) - Advance state and raise Select event
  21. AddCommand (Command.Select, AdvanceCheckState);
  22. // Accept (Enter key and double-click) - Raise Accept event - DO NOT advance state
  23. AddCommand (Command.Accept, () => RaiseAcceptEvent ());
  24. // Hotkey - Advance state and raise Select event - DO NOT raise Accept
  25. AddCommand (Command.HotKey, AdvanceCheckState);
  26. TitleChanged += Checkbox_TitleChanged;
  27. HighlightStyle = DefaultHighlightStyle;
  28. MouseClick += CheckBox_MouseClick;
  29. }
  30. private void CheckBox_MouseClick (object? sender, MouseEventEventArgs e)
  31. {
  32. #if CHECKBOX_SUPPORTS_DOUBLE_CLICK_ACCEPT
  33. CheckState savedCheckState = CheckedState;
  34. #endif
  35. if (e.MouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked))
  36. {
  37. AdvanceCheckState ();
  38. ;
  39. // e.Handled = AdvanceCheckState () == true;
  40. }
  41. #if CHECKBOX_SUPPORTS_DOUBLE_CLICK_ACCEPT
  42. if (e.MouseEvent.Flags.HasFlag (MouseFlags.Button1DoubleClicked))
  43. {
  44. if (RaiseAcceptEvent () == true)
  45. {
  46. e.Handled = false;
  47. _checkedState = savedCheckState;
  48. }
  49. // TODO: This needs to be made consistent with how Button.IsDefault works
  50. if (SuperView is { })
  51. {
  52. // TODO: This should pass context
  53. SuperView.InvokeCommand (Command.Accept);
  54. }
  55. }
  56. #endif
  57. }
  58. private void Checkbox_TitleChanged (object? sender, EventArgs<string> e)
  59. {
  60. base.Text = e.CurrentValue;
  61. TextFormatter.HotKeySpecifier = HotKeySpecifier;
  62. }
  63. /// <inheritdoc />
  64. public override string Text
  65. {
  66. get => base.Title;
  67. set => base.Text = base.Title = value;
  68. }
  69. /// <inheritdoc />
  70. public override Rune HotKeySpecifier
  71. {
  72. get => base.HotKeySpecifier;
  73. set => TextFormatter.HotKeySpecifier = base.HotKeySpecifier = value;
  74. }
  75. private bool _allowNone = false;
  76. /// <summary>
  77. /// If <see langword="true"/> allows <see cref="CheckedState"/> to be <see cref="CheckState.None"/>. The default is <see langword="false"/>.
  78. /// </summary>
  79. public bool AllowCheckStateNone
  80. {
  81. get => _allowNone;
  82. set
  83. {
  84. if (_allowNone == value)
  85. {
  86. return;
  87. }
  88. _allowNone = value;
  89. if (CheckedState == CheckState.None)
  90. {
  91. CheckedState = CheckState.UnChecked;
  92. }
  93. }
  94. }
  95. private CheckState _checkedState = CheckState.UnChecked;
  96. /// <summary>
  97. /// The state of the <see cref="CheckBox"/>.
  98. /// </summary>
  99. /// <remarks>
  100. /// <para>
  101. /// If <see cref="AllowCheckStateNone"/> is <see langword="true"/> and <see cref="CheckState.None"/>, the <see cref="CheckBox"/>
  102. /// will display the <c>ConfigurationManager.Glyphs.CheckStateNone</c> character (☒).
  103. /// </para>
  104. /// <para>
  105. /// If <see cref="CheckState.UnChecked"/>, the <see cref="CheckBox"/>
  106. /// will display the <c>ConfigurationManager.Glyphs.CheckStateUnChecked</c> character (☐).
  107. /// </para>
  108. /// <para>
  109. /// If <see cref="CheckState.Checked"/>, the <see cref="CheckBox"/>
  110. /// will display the <c>ConfigurationManager.Glyphs.CheckStateChecked</c> character (☑).
  111. /// </para>
  112. /// </remarks>
  113. public CheckState CheckedState
  114. {
  115. get => _checkedState;
  116. set => ChangeCheckedState (value);
  117. }
  118. /// <summary>
  119. /// INTERNAL Sets CheckedState.
  120. /// </summary>
  121. /// <param name="value"></param>
  122. /// <returns><see langword="true"/> if state change was canceled, <see langword="false"/> if the state changed, and <see langword="null"/> if the state was not changed for some other reason.</returns>
  123. private bool? ChangeCheckedState (CheckState value)
  124. {
  125. if (_checkedState == value || (value is CheckState.None && !AllowCheckStateNone))
  126. {
  127. return null;
  128. }
  129. CancelEventArgs<CheckState> e = new (in _checkedState, ref value);
  130. if (OnCheckedStateChanging (e))
  131. {
  132. return true;
  133. }
  134. CheckedStateChanging?.Invoke (this, e);
  135. if (e.Cancel)
  136. {
  137. return e.Cancel;
  138. }
  139. _checkedState = value;
  140. UpdateTextFormatterText ();
  141. OnResizeNeeded ();
  142. EventArgs<CheckState> args = new (in _checkedState);
  143. OnCheckedStateChanged (args);
  144. CheckedStateChanged?.Invoke (this, args);
  145. if (RaiseSelectEvent () == true)
  146. {
  147. return true;
  148. }
  149. return false;
  150. }
  151. /// <summary>Called when the <see cref="CheckBox"/> state is changing.</summary>
  152. /// <remarks>
  153. /// <para>
  154. /// The state cahnge can be cancelled by setting the args.Cancel to <see langword="true"/>.
  155. /// </para>
  156. /// </remarks>
  157. protected virtual bool OnCheckedStateChanging (CancelEventArgs<CheckState> args) { return false; }
  158. /// <summary>Raised when the <see cref="CheckBox"/> state is changing.</summary>
  159. /// <remarks>
  160. /// <para>
  161. /// This event can be cancelled. If cancelled, the <see cref="CheckBox"/> will not change its state.
  162. /// </para>
  163. /// </remarks>
  164. public event EventHandler<CancelEventArgs<CheckState>>? CheckedStateChanging;
  165. /// <summary>Called when the <see cref="CheckBox"/> state has changed.</summary>
  166. protected virtual void OnCheckedStateChanged (EventArgs<CheckState> args) { }
  167. /// <summary>Raised when the <see cref="CheckBox"/> state has changed.</summary>
  168. public event EventHandler<EventArgs<CheckState>>? CheckedStateChanged;
  169. /// <summary>
  170. /// Advances <see cref="CheckedState"/> to the next value. Invokes the cancelable <see cref="CheckedStateChanging"/> event.
  171. /// </summary>
  172. /// <remarks>
  173. /// <para>
  174. /// Cycles through the states <see cref="CheckState.None"/>, <see cref="CheckState.Checked"/>, and <see cref="CheckState.UnChecked"/>.
  175. /// </para>
  176. /// <para>
  177. /// If the <see cref="CheckedStateChanging"/> event is not canceled, the <see cref="CheckedState"/> will be updated and the <see cref="Command.Accept"/> event will be raised.
  178. /// </para>
  179. /// </remarks>
  180. /// <returns><see langword="true"/> if state change was canceled, <see langword="false"/> if the state changed, and <see langword="null"/> if the state was not changed for some other reason.</returns>
  181. public bool? AdvanceCheckState ()
  182. {
  183. CheckState oldValue = CheckedState;
  184. CancelEventArgs<CheckState> e = new (in _checkedState, ref oldValue);
  185. switch (CheckedState)
  186. {
  187. case CheckState.None:
  188. e.NewValue = CheckState.Checked;
  189. break;
  190. case CheckState.Checked:
  191. e.NewValue = CheckState.UnChecked;
  192. break;
  193. case CheckState.UnChecked:
  194. if (AllowCheckStateNone)
  195. {
  196. e.NewValue = CheckState.None;
  197. }
  198. else
  199. {
  200. e.NewValue = CheckState.Checked;
  201. }
  202. break;
  203. }
  204. bool? cancelled = ChangeCheckedState (e.NewValue);
  205. return cancelled;
  206. }
  207. /// <inheritdoc/>
  208. protected override void UpdateTextFormatterText ()
  209. {
  210. base.UpdateTextFormatterText ();
  211. switch (TextAlignment)
  212. {
  213. case Alignment.Start:
  214. case Alignment.Center:
  215. case Alignment.Fill:
  216. TextFormatter.Text = $"{GetCheckedGlyph ()} {Text}";
  217. break;
  218. case Alignment.End:
  219. TextFormatter.Text = $"{Text} {GetCheckedGlyph ()}";
  220. break;
  221. }
  222. }
  223. private Rune GetCheckedGlyph ()
  224. {
  225. return CheckedState switch
  226. {
  227. CheckState.Checked => Glyphs.CheckStateChecked,
  228. CheckState.UnChecked => Glyphs.CheckStateUnChecked,
  229. CheckState.None => Glyphs.CheckStateNone,
  230. _ => throw new ArgumentOutOfRangeException ()
  231. };
  232. }
  233. }