View.Command.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. #nullable enable
  2. using System.ComponentModel;
  3. namespace Terminal.Gui;
  4. public partial class View // Command APIs
  5. {
  6. #region Default Implementation
  7. /// <summary>
  8. /// Helper to configure all things Command related for a View. Called from the View constructor.
  9. /// </summary>
  10. private void SetupCommands ()
  11. {
  12. // Enter - Raise Accepted
  13. AddCommand (Command.Accept, RaiseAccepted);
  14. // HotKey - SetFocus and raise HotKeyHandled
  15. AddCommand (Command.HotKey,
  16. () =>
  17. {
  18. if (RaiseHotKeyHandled () is true)
  19. {
  20. return true;
  21. }
  22. SetFocus ();
  23. return true;
  24. });
  25. // Space or single-click - Raise Selected
  26. AddCommand (Command.Select, () =>
  27. {
  28. bool? cancelled = RaiseSelected ();
  29. if (cancelled is null or false && CanFocus)
  30. {
  31. SetFocus ();
  32. return true;
  33. }
  34. return cancelled is true;
  35. });
  36. }
  37. /// <summary>
  38. /// Called when the View's state has been accepted by the user. Calls <see cref="OnAccepted"/> which can be cancelled; if not cancelled raises <see cref="Accepted"/>.
  39. /// event. The default <see cref="Command.Accept"/> handler calls this method.
  40. /// </summary>
  41. /// <remarks>
  42. /// The <see cref="Accepted"/> event should raised after the state of the View has changed (after <see cref="Selected"/> is raised).
  43. /// </remarks>
  44. /// <returns>
  45. /// If <see langword="true"/> the event was canceled. If <see langword="false"/> the event was raised but not canceled.
  46. /// If <see langword="null"/> no event was raised.
  47. /// </returns>
  48. protected bool? RaiseAccepted ()
  49. {
  50. HandledEventArgs args = new ();
  51. // Best practice is to invoke the virtual method first.
  52. // This allows derived classes to handle the event and potentially cancel it.
  53. args.Handled = OnAccepted (args) || args.Handled;
  54. if (!args.Handled)
  55. {
  56. // If the event is not canceled by the virtual method, raise the event to notify any external subscribers.
  57. Accepted?.Invoke (this, args);
  58. }
  59. // Accept is a special case where if the event is not canceled, the event is
  60. // - Invoked on any peer-View with IsDefault == true
  61. // - bubbled up the SuperView hierarchy.
  62. if (!args.Handled)
  63. {
  64. // If there's an IsDefault peer view in Subviews, try it
  65. var isDefaultView = SuperView?.Subviews.FirstOrDefault (v => v is Button { IsDefault: true });
  66. if (isDefaultView != this && isDefaultView is Button { IsDefault: true } button)
  67. {
  68. bool? handled = isDefaultView.InvokeCommand (Command.Accept);
  69. if (handled == true)
  70. {
  71. return true;
  72. }
  73. }
  74. return SuperView?.InvokeCommand (Command.Accept) == true;
  75. }
  76. return Accepted is null ? null : args.Handled;
  77. }
  78. // TODO: Change this to CancelEventArgs
  79. /// <summary>
  80. /// Called when the View's state has been accepted by the user. Set <see cref="HandledEventArgs.Handled"/> to
  81. /// <see langword="true"/> to stop processing.
  82. /// </summary>
  83. /// <param name="args"></param>
  84. /// <returns><see langword="true"/> to stop processing.</returns>
  85. protected virtual bool OnAccepted (HandledEventArgs args) { return false; }
  86. /// <summary>
  87. /// Cancelable event raised when the View's state has been accepted by the user. Set
  88. /// <see cref="HandledEventArgs.Handled"/> to cancel the event.
  89. /// </summary>
  90. public event EventHandler<HandledEventArgs>? Accepted;
  91. /// <summary>
  92. /// Called when the user has selected the View or otherwise changed the state of the View. Calls <see cref="OnSelected"/> which can be cancelled; if not cancelled raises <see cref="Accepted"/>.
  93. /// event. The default <see cref="Command.Select"/> handler calls this method.
  94. /// </summary>
  95. /// <remarks>
  96. /// The <see cref="Selected"/> event should raised after the state of the View has been changed and before see <see cref="Accepted"/>.
  97. /// </remarks>
  98. /// <returns>
  99. /// If <see langword="true"/> the event was canceled. If <see langword="false"/> the event was raised but not canceled.
  100. /// If <see langword="null"/> no event was raised.
  101. /// </returns>
  102. protected bool? RaiseSelected ()
  103. {
  104. HandledEventArgs args = new ();
  105. // Best practice is to invoke the virtual method first.
  106. // This allows derived classes to handle the event and potentially cancel it.
  107. if (OnSelected (args) || args.Handled)
  108. {
  109. return true;
  110. }
  111. // If the event is not canceled by the virtual method, raise the event to notify any external subscribers.
  112. Selected?.Invoke (this, args);
  113. return Selected is null ? null : args.Handled;
  114. }
  115. /// <summary>
  116. /// Called when the user has selected the View or otherwise changed the state of the View. Set <see cref="HandledEventArgs.Handled"/> to
  117. /// <see langword="true"/> to stop processing.
  118. /// </summary>
  119. /// <param name="args"></param>
  120. /// <returns><see langword="true"/> to stop processing.</returns>
  121. protected virtual bool OnSelected (HandledEventArgs args) { return false; }
  122. /// <summary>
  123. /// Cancelable event raised when the user has selected the View or otherwise changed the state of the View. Set
  124. /// <see cref="HandledEventArgs.Handled"/>
  125. /// to cancel the event.
  126. /// </summary>
  127. public event EventHandler<HandledEventArgs>? Selected;
  128. // TODO: What does this event really do? "Called when the user has pressed the View's hot key or otherwise invoked the View's hot key command.???"
  129. /// <summary>
  130. /// Called when the View has handled the user pressing the View's <see cref="HotKey"/>. Calls <see cref="OnHotKeyHandled"/> which can be cancelled; if not cancelled raises <see cref="Accepted"/>.
  131. /// event. The default <see cref="Command.HotKey"/> handler calls this method.
  132. /// </summary>
  133. /// <returns>
  134. /// If <see langword="true"/> the event was handled. If <see langword="false"/> the event was raised but not handled.
  135. /// If <see langword="null"/> no event was raised.
  136. /// </returns>
  137. protected bool? RaiseHotKeyHandled ()
  138. {
  139. HandledEventArgs args = new ();
  140. // Best practice is to invoke the virtual method first.
  141. // This allows derived classes to handle the event and potentially cancel it.
  142. if (OnHotKeyHandled (args) || args.Handled)
  143. {
  144. return true;
  145. }
  146. // If the event is not canceled by the virtual method, raise the event to notify any external subscribers.
  147. HotKeyHandled?.Invoke (this, args);
  148. return HotKeyHandled is null ? null : args.Handled;
  149. }
  150. /// <summary>
  151. /// Called when the View has handled the user pressing the View's <see cref="HotKey"/>. Set <see cref="HandledEventArgs.Handled"/> to
  152. /// <see langword="true"/> to stop processing.
  153. /// </summary>
  154. /// <param name="args"></param>
  155. /// <returns><see langword="true"/> to stop processing.</returns>
  156. protected virtual bool OnHotKeyHandled (HandledEventArgs args) { return false; }
  157. /// <summary>
  158. /// Cancelable event raised when the <see cref="Command.HotKey"/> command is invoked. Set
  159. /// <see cref="HandledEventArgs.Handled"/>
  160. /// to cancel the event.
  161. /// </summary>
  162. public event EventHandler<HandledEventArgs>? HotKeyHandled;
  163. #endregion Default Implementation
  164. /// <summary>
  165. /// <para>
  166. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call
  167. /// AddCommand for each command they support.
  168. /// </para>
  169. /// <para>
  170. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  171. /// replace the old one.
  172. /// </para>
  173. /// </summary>
  174. /// <remarks>
  175. /// <para>
  176. /// This version of AddCommand is for commands that require <see cref="CommandContext"/>. Use
  177. /// <see cref="AddCommand(Command,Func{System.Nullable{bool}})"/>
  178. /// in cases where the command does not require a <see cref="CommandContext"/>.
  179. /// </para>
  180. /// </remarks>
  181. /// <param name="command">The command.</param>
  182. /// <param name="f">The function.</param>
  183. protected void AddCommand (Command command, Func<CommandContext, bool?> f) { CommandImplementations [command] = f; }
  184. /// <summary>
  185. /// <para>
  186. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call
  187. /// AddCommand for each command they support.
  188. /// </para>
  189. /// <para>
  190. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  191. /// replace the old one.
  192. /// </para>
  193. /// </summary>
  194. /// <remarks>
  195. /// <para>
  196. /// This version of AddCommand is for commands that do not require a <see cref="CommandContext"/>.
  197. /// If the command requires context, use
  198. /// <see cref="AddCommand(Command,Func{CommandContext,System.Nullable{bool}})"/>
  199. /// </para>
  200. /// </remarks>
  201. /// <param name="command">The command.</param>
  202. /// <param name="f">The function.</param>
  203. protected void AddCommand (Command command, Func<bool?> f) { CommandImplementations [command] = ctx => f (); }
  204. /// <summary>Returns all commands that are supported by this <see cref="View"/>.</summary>
  205. /// <returns></returns>
  206. public IEnumerable<Command> GetSupportedCommands () { return CommandImplementations.Keys; }
  207. /// <summary>
  208. /// Invokes the specified commands.
  209. /// </summary>
  210. /// <param name="commands"></param>
  211. /// <param name="key">The key that caused the commands to be invoked, if any.</param>
  212. /// <param name="keyBinding"></param>
  213. /// <returns>
  214. /// <see langword="null"/> if no command was found.
  215. /// <see langword="true"/> if the command was invoked the command was handled (or cancelled)
  216. /// <see langword="false"/> if the command was invoked and the command was not handled.
  217. /// </returns>
  218. public bool? InvokeCommands (Command [] commands, Key? key = null, KeyBinding? keyBinding = null)
  219. {
  220. bool? toReturn = null;
  221. foreach (Command command in commands)
  222. {
  223. if (!CommandImplementations.ContainsKey (command))
  224. {
  225. throw new NotSupportedException (@$"{command} is not supported by ({GetType ().Name}).");
  226. }
  227. // each command has its own return value
  228. bool? thisReturn = InvokeCommand (command, key, keyBinding);
  229. // if we haven't got anything yet, the current command result should be used
  230. toReturn ??= thisReturn;
  231. // if ever see a true then that's what we will return
  232. if (thisReturn ?? false)
  233. {
  234. toReturn = true;
  235. }
  236. }
  237. return toReturn;
  238. }
  239. /// <summary>Invokes the specified command.</summary>
  240. /// <param name="command">The command to invoke.</param>
  241. /// <param name="key">The key that caused the command to be invoked, if any.</param>
  242. /// <param name="keyBinding"></param>
  243. /// <returns>
  244. /// <see langword="null"/> if no command was found. <see langword="true"/> if the command was invoked, and it
  245. /// handled (or cancelled) the command. <see langword="false"/> if the command was invoked, and it did not handle (or cancel) the command.
  246. /// </returns>
  247. public bool? InvokeCommand (Command command, Key? key = null, KeyBinding? keyBinding = null)
  248. {
  249. if (CommandImplementations.TryGetValue (command, out Func<CommandContext, bool?>? implementation))
  250. {
  251. var context = new CommandContext (command, key, keyBinding); // Create the context here
  252. return implementation (context);
  253. }
  254. return null;
  255. }
  256. }