CheckBox.cs 8.7 KB

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