View.Command.cs 19 KB

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