View.Command.cs 16 KB

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