View.Command.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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, RaiseAccepting);
  14. // HotKey - SetFocus and raise HandlingHotKey
  15. AddCommand (Command.HotKey,
  16. () =>
  17. {
  18. if (RaiseHandlingHotKey () is true)
  19. {
  20. return true;
  21. }
  22. SetFocus ();
  23. return true;
  24. });
  25. // Space or single-click - Raise Selecting
  26. AddCommand (Command.Select, ctx =>
  27. {
  28. if (RaiseSelecting (ctx) is true)
  29. {
  30. return true;
  31. }
  32. if (CanFocus)
  33. {
  34. SetFocus ();
  35. return true;
  36. }
  37. return false;
  38. });
  39. }
  40. /// <summary>
  41. /// Called when the user is accepting the state of the View and the <see cref="Command.Accept"/> has been invoked. Calls <see cref="OnAccepting"/> which can be cancelled; if not cancelled raises <see cref="Accepting"/>.
  42. /// event. The default <see cref="Command.Accept"/> handler calls this method.
  43. /// </summary>
  44. /// <remarks>
  45. /// <para>
  46. /// The <see cref="Accepting"/> event should be raised after the state of the View has changed (after <see cref="Selecting"/> is raised).
  47. /// </para>
  48. /// <para>
  49. /// If the Accepting event is not handled, <see cref="Command.Accept"/> will be invoked on the SuperView, enabling default Accept behavior.
  50. /// </para>
  51. /// <para>
  52. /// If a peer-View raises the Accepting event and the event is not cancelled, the <see cref="Command.Accept"/> will be invoked on the
  53. /// first Button in the SuperView that has <see cref="Button.IsDefault"/> set to <see langword="true"/>.
  54. /// </para>
  55. /// </remarks>
  56. /// <returns>
  57. /// <see langword="null"/> if no event was raised; input processing should continue.
  58. /// <see langword="false"/> if the event was raised and was not handled (or cancelled); input processing should continue.
  59. /// <see langword="true"/> if the event was raised and handled (or cancelled); input processing should stop.
  60. /// </returns>
  61. protected bool? RaiseAccepting (ICommandContext? ctx)
  62. {
  63. CommandEventArgs args = new () { Context = ctx };
  64. // Best practice is to invoke the virtual method first.
  65. // This allows derived classes to handle the event and potentially cancel it.
  66. args.Cancel = OnAccepting (args) || args.Cancel;
  67. if (!args.Cancel)
  68. {
  69. // If the event is not canceled by the virtual method, raise the event to notify any external subscribers.
  70. Accepting?.Invoke (this, args);
  71. }
  72. // Accept is a special case where if the event is not canceled, the event is
  73. // - Invoked on any peer-View with IsDefault == true
  74. // - bubbled up the SuperView hierarchy.
  75. if (!args.Cancel)
  76. {
  77. // If there's an IsDefault peer view in Subviews, try it
  78. var isDefaultView = SuperView?.Subviews.FirstOrDefault (v => v is Button { IsDefault: true });
  79. if (isDefaultView != this && isDefaultView is Button { IsDefault: true } button)
  80. {
  81. bool? handled = isDefaultView.InvokeCommand<KeyBinding> (Command.Accept, new ([Command.Accept], 0, null, this));
  82. if (handled == true)
  83. {
  84. return true;
  85. }
  86. }
  87. return SuperView?.InvokeCommand<KeyBinding> (Command.Accept, new ([Command.Accept], 0, null, this)) == true;
  88. }
  89. return Accepting is null ? null : args.Cancel;
  90. }
  91. /// <summary>
  92. /// Called when the user is accepting the state of the View and the <see cref="Command.Accept"/> has been invoked. Set CommandEventArgs.Cancel to
  93. /// <see langword="true"/> and return <see langword="true"/> to stop processing.
  94. /// </summary>
  95. /// <remarks>
  96. /// <para>
  97. /// See <see cref="View.RaiseAccepting"/> for more information.
  98. /// </para>
  99. /// </remarks>
  100. /// <param name="args"></param>
  101. /// <returns><see langword="true"/> to stop processing.</returns>
  102. protected virtual bool OnAccepting (CommandEventArgs args) { return false; }
  103. /// <summary>
  104. /// Cancelable event raised when the user is accepting the state of the View and the <see cref="Command.Accept"/> has been invoked. Set
  105. /// CommandEventArgs.Cancel to cancel the event.
  106. /// </summary>
  107. /// <remarks>
  108. /// <para>
  109. /// See <see cref="View.RaiseAccepting"/> for more information.
  110. /// </para>
  111. /// </remarks>
  112. public event EventHandler<CommandEventArgs>? Accepting;
  113. /// <summary>
  114. /// Called when the user has performed an action (e.g. <see cref="Command.Select"/>) causing the View to change state. Calls <see cref="OnSelecting"/> which can be cancelled; if not cancelled raises <see cref="Accepting"/>.
  115. /// event. The default <see cref="Command.Select"/> handler calls this method.
  116. /// </summary>
  117. /// <remarks>
  118. /// The <see cref="Selecting"/> event should be raised after the state of the View has been changed and before see <see cref="Accepting"/>.
  119. /// </remarks>
  120. /// <returns>
  121. /// <see langword="null"/> if no event was raised; input processing should continue.
  122. /// <see langword="false"/> if the event was raised and was not handled (or cancelled); input processing should continue.
  123. /// <see langword="true"/> if the event was raised and handled (or cancelled); input processing should stop.
  124. /// </returns>
  125. protected bool? RaiseSelecting (ICommandContext? ctx)
  126. {
  127. CommandEventArgs args = new () { Context = ctx };
  128. // Best practice is to invoke the virtual method first.
  129. // This allows derived classes to handle the event and potentially cancel it.
  130. if (OnSelecting (args) || args.Cancel)
  131. {
  132. return true;
  133. }
  134. // If the event is not canceled by the virtual method, raise the event to notify any external subscribers.
  135. Selecting?.Invoke (this, args);
  136. return Selecting is null ? null : args.Cancel;
  137. }
  138. /// <summary>
  139. /// Called when the user has performed an action (e.g. <see cref="Command.Select"/>) causing the View to change state.
  140. /// Set CommandEventArgs.Cancel to
  141. /// <see langword="true"/> and return <see langword="true"/> to cancel the state change. The default implementation does nothing.
  142. /// </summary>
  143. /// <param name="args">The event arguments.</param>
  144. /// <returns><see langword="true"/> to stop processing.</returns>
  145. protected virtual bool OnSelecting (CommandEventArgs args) { return false; }
  146. /// <summary>
  147. /// Cancelable event raised when the user has performed an action (e.g. <see cref="Command.Select"/>) causing the View to change state.
  148. /// CommandEventArgs.Cancel to <see langword="true"/> to cancel the state change.
  149. /// </summary>
  150. public event EventHandler<CommandEventArgs>? Selecting;
  151. /// <summary>
  152. /// Called when the View is handling the user pressing the View's <see cref="HotKey"/>s. Calls <see cref="OnHandlingHotKey"/> which can be cancelled; if not cancelled raises <see cref="Accepting"/>.
  153. /// event. The default <see cref="Command.HotKey"/> handler calls this method.
  154. /// </summary>
  155. /// <returns>
  156. /// <see langword="null"/> if no event was raised; input processing should continue.
  157. /// <see langword="false"/> if the event was raised and was not handled (or cancelled); input processing should continue.
  158. /// <see langword="true"/> if the event was raised and handled (or cancelled); input processing should stop.
  159. /// </returns>
  160. protected bool? RaiseHandlingHotKey ()
  161. {
  162. CommandEventArgs args = new () { Context = new CommandContext<KeyBinding> () { Command = Command.HotKey } };
  163. // Best practice is to invoke the virtual method first.
  164. // This allows derived classes to handle the event and potentially cancel it.
  165. if (OnHandlingHotKey (args) || args.Cancel)
  166. {
  167. return true;
  168. }
  169. // If the event is not canceled by the virtual method, raise the event to notify any external subscribers.
  170. HandlingHotKey?.Invoke (this, args);
  171. return HandlingHotKey is null ? null : args.Cancel;
  172. }
  173. /// <summary>
  174. /// Called when the View is handling the user pressing the View's <see cref="HotKey"/>. Set CommandEventArgs.Cancel to
  175. /// <see langword="true"/> to stop processing.
  176. /// </summary>
  177. /// <param name="args"></param>
  178. /// <returns><see langword="true"/> to stop processing.</returns>
  179. protected virtual bool OnHandlingHotKey (CommandEventArgs args) { return false; }
  180. /// <summary>
  181. /// Cancelable event raised when the View is handling the user pressing the View's <see cref="HotKey"/>. Set
  182. /// CommandEventArgs.Cancel to cancel the event.
  183. /// </summary>
  184. public event EventHandler<CommandEventArgs>? HandlingHotKey;
  185. #endregion Default Implementation
  186. /// <summary>
  187. /// Function signature commands.
  188. /// </summary>
  189. /// <param name="ctx">Provides context about the circumstances of invoking the command.</param>
  190. /// <returns>
  191. /// <see langword="null"/> if no event was raised; input processing should continue.
  192. /// <see langword="false"/> if the event was raised and was not handled (or cancelled); input processing should continue.
  193. /// <see langword="true"/> if the event was raised and handled (or cancelled); input processing should stop.
  194. /// </returns>
  195. public delegate bool? CommandImplementation (ICommandContext? ctx);
  196. /// <summary>
  197. /// <para>
  198. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call
  199. /// AddCommand for each command they support.
  200. /// </para>
  201. /// <para>
  202. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="impl"/> will
  203. /// replace the old one.
  204. /// </para>
  205. /// </summary>
  206. /// <remarks>
  207. /// <para>
  208. /// This version of AddCommand is for commands that require <see cref="ICommandContext"/>.
  209. /// </para>
  210. /// </remarks>
  211. /// <param name="command">The command.</param>
  212. /// <param name="impl">The delegate.</param>
  213. protected void AddCommand (Command command, CommandImplementation impl) { CommandImplementations [command] = impl; }
  214. /// <summary>
  215. /// <para>
  216. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call
  217. /// AddCommand for each command they support.
  218. /// </para>
  219. /// <para>
  220. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="impl"/> will
  221. /// replace the old one.
  222. /// </para>
  223. /// </summary>
  224. /// <remarks>
  225. /// <para>
  226. /// This version of AddCommand is for commands that do not require context.
  227. /// If the command requires context, use
  228. /// <see cref="AddCommand(Command,CommandImplementation)"/>
  229. /// </para>
  230. /// </remarks>
  231. /// <param name="command">The command.</param>
  232. /// <param name="impl">The delegate.</param>
  233. protected void AddCommand (Command command, Func<bool?> impl) { CommandImplementations [command] = ctx => impl (); }
  234. /// <summary>Returns all commands that are supported by this <see cref="View"/>.</summary>
  235. /// <returns></returns>
  236. public IEnumerable<Command> GetSupportedCommands () { return CommandImplementations.Keys; }
  237. /// <summary>
  238. /// Invokes the specified commands.
  239. /// </summary>
  240. /// <param name="commands">The set of commands to invoke.</param>
  241. /// <param name="binding">The binding that caused the invocation, if any. This will be passed as context with the command.</param>
  242. /// <returns>
  243. /// <see langword="null"/> if no command was found; input processing should continue.
  244. /// <see langword="false"/> if the command was invoked and was not handled (or cancelled); input processing should continue.
  245. /// <see langword="true"/> if the command was invoked the command was handled (or cancelled); input processing should stop.
  246. /// </returns>
  247. public bool? InvokeCommands<TBindingType> (Command [] commands, TBindingType binding)
  248. {
  249. bool? toReturn = null;
  250. foreach (Command command in commands)
  251. {
  252. if (!CommandImplementations.ContainsKey (command))
  253. {
  254. throw new NotSupportedException (
  255. @$"A Binding was set up for the command {command} ({binding}) but that command is not supported by this View ({GetType ().Name})"
  256. );
  257. }
  258. // each command has its own return value
  259. bool? thisReturn = InvokeCommand<TBindingType> (command, binding);
  260. // if we haven't got anything yet, the current command result should be used
  261. toReturn ??= thisReturn;
  262. // if ever see a true then that's what we will return
  263. if (thisReturn ?? false)
  264. {
  265. toReturn = true;
  266. }
  267. }
  268. return toReturn;
  269. }
  270. /// <summary>
  271. /// Invokes the specified command.
  272. /// </summary>
  273. /// <param name="command">The command to invoke.</param>
  274. /// <param name="binding">The binding that caused the invocation, if any. This will be passed as context with the command.</param>
  275. /// <returns>
  276. /// <see langword="null"/> if no command was found; input processing should continue.
  277. /// <see langword="false"/> if the command was invoked and was not handled (or cancelled); input processing should continue.
  278. /// <see langword="true"/> if the command was invoked the command was handled (or cancelled); input processing should stop.
  279. /// </returns>
  280. public bool? InvokeCommand<TBindingType> (Command command, TBindingType binding)
  281. {
  282. if (CommandImplementations.TryGetValue (command, out CommandImplementation? implementation))
  283. {
  284. return implementation (new CommandContext<TBindingType> ()
  285. {
  286. Command = command,
  287. Binding = binding,
  288. });
  289. }
  290. return null;
  291. }
  292. /// <summary>
  293. /// Invokes the specified command without context.
  294. /// </summary>
  295. /// <param name="command">The command to invoke.</param>
  296. /// <returns>
  297. /// <see langword="null"/> if no command was found; input processing should continue.
  298. /// <see langword="false"/> if the command was invoked and was not handled (or cancelled); input processing should continue.
  299. /// <see langword="true"/> if the command was invoked the command was handled (or cancelled); input processing should stop.
  300. /// </returns>
  301. public bool? InvokeCommand (Command command)
  302. {
  303. if (CommandImplementations.TryGetValue (command, out CommandImplementation? implementation))
  304. {
  305. return implementation (null);
  306. }
  307. return null;
  308. }
  309. }