View.Command.cs 21 KB

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