CheckBox.cs 8.4 KB

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