CheckBox.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. if (RaiseSelectEvent () == true)
  126. {
  127. return true;
  128. }
  129. return false;
  130. }
  131. /// <summary>Called when the <see cref="CheckBox"/> state is changing.</summary>
  132. /// <remarks>
  133. /// <para>
  134. /// The state cahnge can be cancelled by setting the args.Cancel to <see langword="true"/>.
  135. /// </para>
  136. /// </remarks>
  137. protected virtual bool OnCheckedStateChanging (CancelEventArgs<CheckState> args) { return false; }
  138. /// <summary>Raised when the <see cref="CheckBox"/> state is changing.</summary>
  139. /// <remarks>
  140. /// <para>
  141. /// This event can be cancelled. If cancelled, the <see cref="CheckBox"/> will not change its state.
  142. /// </para>
  143. /// </remarks>
  144. public event EventHandler<CancelEventArgs<CheckState>>? CheckedStateChanging;
  145. /// <summary>Called when the <see cref="CheckBox"/> state has changed.</summary>
  146. protected virtual void OnCheckedStateChanged (EventArgs<CheckState> args) { }
  147. /// <summary>Raised when the <see cref="CheckBox"/> state has changed.</summary>
  148. public event EventHandler<EventArgs<CheckState>>? CheckedStateChanged;
  149. /// <summary>
  150. /// Advances <see cref="CheckedState"/> to the next value. Invokes the cancelable <see cref="CheckedStateChanging"/> event.
  151. /// </summary>
  152. /// <remarks>
  153. /// <para>
  154. /// Cycles through the states <see cref="CheckState.None"/>, <see cref="CheckState.Checked"/>, and <see cref="CheckState.UnChecked"/>.
  155. /// </para>
  156. /// <para>
  157. /// 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.
  158. /// </para>
  159. /// </remarks>
  160. /// <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>
  161. public bool? AdvanceCheckState ()
  162. {
  163. CheckState oldValue = CheckedState;
  164. CancelEventArgs<CheckState> e = new (in _checkedState, ref oldValue);
  165. switch (CheckedState)
  166. {
  167. case CheckState.None:
  168. e.NewValue = CheckState.Checked;
  169. break;
  170. case CheckState.Checked:
  171. e.NewValue = CheckState.UnChecked;
  172. break;
  173. case CheckState.UnChecked:
  174. if (AllowCheckStateNone)
  175. {
  176. e.NewValue = CheckState.None;
  177. }
  178. else
  179. {
  180. e.NewValue = CheckState.Checked;
  181. }
  182. break;
  183. }
  184. bool? cancelled = ChangeCheckedState (e.NewValue);
  185. return cancelled;
  186. }
  187. /// <inheritdoc/>
  188. protected override void UpdateTextFormatterText ()
  189. {
  190. base.UpdateTextFormatterText ();
  191. switch (TextAlignment)
  192. {
  193. case Alignment.Start:
  194. case Alignment.Center:
  195. case Alignment.Fill:
  196. TextFormatter.Text = $"{GetCheckedGlyph ()} {Text}";
  197. break;
  198. case Alignment.End:
  199. TextFormatter.Text = $"{Text} {GetCheckedGlyph ()}";
  200. break;
  201. }
  202. }
  203. private Rune GetCheckedGlyph ()
  204. {
  205. return CheckedState switch
  206. {
  207. CheckState.Checked => Glyphs.CheckStateChecked,
  208. CheckState.UnChecked => Glyphs.CheckStateUnChecked,
  209. CheckState.None => Glyphs.CheckStateNone,
  210. _ => throw new ArgumentOutOfRangeException ()
  211. };
  212. }
  213. }