View.Command.cs 19 KB

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