CheckBox.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. e.Handled = AdvanceCheckState () == true;
  38. }
  39. #if CHECKBOX_SUPPORTS_DOUBLE_CLICK_ACCEPT
  40. if (e.MouseEvent.Flags.HasFlag (MouseFlags.Button1DoubleClicked))
  41. {
  42. if (RaiseAcceptEvent () == true)
  43. {
  44. e.Handled = false;
  45. _checkedState = savedCheckState;
  46. }
  47. // TODO: This needs to be made consistent with how Button.IsDefault works
  48. if (SuperView is { })
  49. {
  50. // TODO: This should pass context
  51. SuperView.InvokeCommand (Command.Accept);
  52. }
  53. }
  54. #endif
  55. }
  56. private void Checkbox_TitleChanged (object? sender, EventArgs<string> e)
  57. {
  58. base.Text = e.CurrentValue;
  59. TextFormatter.HotKeySpecifier = HotKeySpecifier;
  60. }
  61. /// <inheritdoc />
  62. public override string Text
  63. {
  64. get => base.Title;
  65. set => base.Text = base.Title = value;
  66. }
  67. /// <inheritdoc />
  68. public override Rune HotKeySpecifier
  69. {
  70. get => base.HotKeySpecifier;
  71. set => TextFormatter.HotKeySpecifier = base.HotKeySpecifier = value;
  72. }
  73. private bool _allowNone = false;
  74. /// <summary>
  75. /// If <see langword="true"/> allows <see cref="CheckedState"/> to be <see cref="CheckState.None"/>. The default is <see langword="false"/>.
  76. /// </summary>
  77. public bool AllowCheckStateNone
  78. {
  79. get => _allowNone;
  80. set
  81. {
  82. if (_allowNone == value)
  83. {
  84. return;
  85. }
  86. _allowNone = value;
  87. if (CheckedState == CheckState.None)
  88. {
  89. CheckedState = CheckState.UnChecked;
  90. }
  91. }
  92. }
  93. private CheckState _checkedState = CheckState.UnChecked;
  94. /// <summary>
  95. /// The state of the <see cref="CheckBox"/>.
  96. /// </summary>
  97. /// <remarks>
  98. /// <para>
  99. /// If <see cref="AllowCheckStateNone"/> is <see langword="true"/> and <see cref="CheckState.None"/>, the <see cref="CheckBox"/>
  100. /// will display the <c>ConfigurationManager.Glyphs.CheckStateNone</c> character (☒).
  101. /// </para>
  102. /// <para>
  103. /// If <see cref="CheckState.UnChecked"/>, the <see cref="CheckBox"/>
  104. /// will display the <c>ConfigurationManager.Glyphs.CheckStateUnChecked</c> character (☐).
  105. /// </para>
  106. /// <para>
  107. /// If <see cref="CheckState.Checked"/>, the <see cref="CheckBox"/>
  108. /// will display the <c>ConfigurationManager.Glyphs.CheckStateChecked</c> character (☑).
  109. /// </para>
  110. /// </remarks>
  111. public CheckState CheckedState
  112. {
  113. get => _checkedState;
  114. set => ChangeCheckedState (value);
  115. }
  116. /// <summary>
  117. /// INTERNAL Sets CheckedState.
  118. /// </summary>
  119. /// <param name="value"></param>
  120. /// <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>
  121. private bool? ChangeCheckedState (CheckState value)
  122. {
  123. if (_checkedState == value || (value is CheckState.None && !AllowCheckStateNone))
  124. {
  125. return null;
  126. }
  127. if (RaiseSelectEvent () == true)
  128. {
  129. return true;
  130. }
  131. CancelEventArgs<CheckState> e = new (in _checkedState, ref value);
  132. if (OnCheckedStateChanging (e))
  133. {
  134. return true;
  135. }
  136. CheckedStateChanging?.Invoke (this, e);
  137. if (e.Cancel)
  138. {
  139. return e.Cancel;
  140. }
  141. _checkedState = value;
  142. UpdateTextFormatterText ();
  143. OnResizeNeeded ();
  144. EventArgs<CheckState> args = new (in _checkedState);
  145. OnCheckedStateChanged (args);
  146. CheckedStateChanged?.Invoke (this, args);
  147. return false;
  148. }
  149. /// <summary>Called when the <see cref="CheckBox"/> state is changing.</summary>
  150. /// <remarks>
  151. /// <para>
  152. /// The state cahnge can be cancelled by setting the args.Cancel to <see langword="true"/>.
  153. /// </para>
  154. /// </remarks>
  155. protected virtual bool OnCheckedStateChanging (CancelEventArgs<CheckState> args) { return false;}
  156. /// <summary>Raised when the <see cref="CheckBox"/> state is changing.</summary>
  157. /// <remarks>
  158. /// <para>
  159. /// This event can be cancelled. If cancelled, the <see cref="CheckBox"/> will not change its state.
  160. /// </para>
  161. /// </remarks>
  162. public event EventHandler<CancelEventArgs<CheckState>>? CheckedStateChanging;
  163. /// <summary>Called when the <see cref="CheckBox"/> state has changed.</summary>
  164. protected virtual void OnCheckedStateChanged (EventArgs<CheckState> args) { }
  165. /// <summary>Raised when the <see cref="CheckBox"/> state has changed.</summary>
  166. public event EventHandler<EventArgs<CheckState>>? CheckedStateChanged;
  167. /// <summary>
  168. /// Advances <see cref="CheckedState"/> to the next value. Invokes the cancelable <see cref="CheckedStateChanging"/> event.
  169. /// </summary>
  170. /// <remarks>
  171. /// <para>
  172. /// Cycles through the states <see cref="CheckState.None"/>, <see cref="CheckState.Checked"/>, and <see cref="CheckState.UnChecked"/>.
  173. /// </para>
  174. /// <para>
  175. /// 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.
  176. /// </para>
  177. /// </remarks>
  178. /// <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>
  179. public bool? AdvanceCheckState ()
  180. {
  181. CheckState oldValue = CheckedState;
  182. CancelEventArgs<CheckState> e = new (in _checkedState, ref oldValue);
  183. switch (CheckedState)
  184. {
  185. case CheckState.None:
  186. e.NewValue = CheckState.Checked;
  187. break;
  188. case CheckState.Checked:
  189. e.NewValue = CheckState.UnChecked;
  190. break;
  191. case CheckState.UnChecked:
  192. if (AllowCheckStateNone)
  193. {
  194. e.NewValue = CheckState.None;
  195. }
  196. else
  197. {
  198. e.NewValue = CheckState.Checked;
  199. }
  200. break;
  201. }
  202. bool? cancelled = ChangeCheckedState (e.NewValue);
  203. return !cancelled;
  204. }
  205. /// <inheritdoc/>
  206. protected override void UpdateTextFormatterText ()
  207. {
  208. base.UpdateTextFormatterText ();
  209. switch (TextAlignment)
  210. {
  211. case Alignment.Start:
  212. case Alignment.Center:
  213. case Alignment.Fill:
  214. TextFormatter.Text = $"{GetCheckedGlyph ()} {Text}";
  215. break;
  216. case Alignment.End:
  217. TextFormatter.Text = $"{Text} {GetCheckedGlyph ()}";
  218. break;
  219. }
  220. }
  221. private Rune GetCheckedGlyph ()
  222. {
  223. return CheckedState switch
  224. {
  225. CheckState.Checked => Glyphs.CheckStateChecked,
  226. CheckState.UnChecked => Glyphs.CheckStateUnChecked,
  227. CheckState.None => Glyphs.CheckStateNone,
  228. _ => throw new ArgumentOutOfRangeException ()
  229. };
  230. }
  231. }