CheckBox.cs 9.0 KB

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