View.Command.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. 
  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. (ctx) =>
  20. {
  21. if (RaiseHandlingHotKey (ctx) 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. /// <param name="ctx">The context to pass with the command.</param>
  225. /// <returns>
  226. /// <see langword="null"/> if no event was raised; input processing should continue.
  227. /// <see langword="false"/> if the event was raised and was not handled (or cancelled); input processing should
  228. /// continue.
  229. /// <see langword="true"/> if the event was raised and handled (or cancelled); input processing should stop.
  230. /// </returns>
  231. protected bool? RaiseHandlingHotKey (ICommandContext? ctx)
  232. {
  233. CommandEventArgs args = new () { Context = ctx };
  234. //Logging.Debug ($"{Title} ({args.Context?.Source?.Title})");
  235. // Best practice is to invoke the virtual method first.
  236. // This allows derived classes to handle the event and potentially cancel it.
  237. if (OnHandlingHotKey (args) || args.Handled)
  238. {
  239. return true;
  240. }
  241. // If the event is not canceled by the virtual method, raise the event to notify any external subscribers.
  242. HandlingHotKey?.Invoke (this, args);
  243. return HandlingHotKey is null ? null : args.Handled;
  244. }
  245. /// <summary>
  246. /// Called when the View is handling the user pressing the View's <see cref="HotKey"/>.
  247. /// Set CommandEventArgs.Handled to <see langword="true"/> to indicate the event was handled and processing should
  248. /// stop.
  249. /// </summary>
  250. /// <param name="args"></param>
  251. /// <returns><see langword="true"/> to stop processing.</returns>
  252. protected virtual bool OnHandlingHotKey (CommandEventArgs args) { return false; }
  253. /// <summary>
  254. /// Cancelable event raised when the View is handling the user pressing the View's <see cref="HotKey"/>. Set
  255. /// CommandEventArgs.Handled to <see langword="true"/> to indicate the event was handled and processing should stop.
  256. /// </summary>
  257. public event EventHandler<CommandEventArgs>? HandlingHotKey;
  258. #endregion Default Implementation
  259. /// <summary>
  260. /// Function signature commands.
  261. /// </summary>
  262. /// <param name="ctx">Provides context about the circumstances of invoking the command.</param>
  263. /// <returns>
  264. /// <see langword="null"/> if no event was raised; input processing should continue.
  265. /// <see langword="false"/> if the event was raised and was not handled (or cancelled); input processing should
  266. /// continue.
  267. /// <see langword="true"/> if the event was raised and handled (or cancelled); input processing should stop.
  268. /// </returns>
  269. public delegate bool? CommandImplementation (ICommandContext? ctx);
  270. /// <summary>
  271. /// <para>
  272. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call
  273. /// AddCommand for each command they support.
  274. /// </para>
  275. /// <para>
  276. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="impl"/> will
  277. /// replace the old one.
  278. /// </para>
  279. /// </summary>
  280. /// <remarks>
  281. /// <para>
  282. /// This version of AddCommand is for commands that require <see cref="ICommandContext"/>.
  283. /// </para>
  284. /// <para>
  285. /// See the Commands Deep Dive for more information: <see href="https://gui-cs.github.io/Terminal.Gui/docs/command.html"/>.
  286. /// </para>
  287. /// </remarks>
  288. /// <param name="command">The command.</param>
  289. /// <param name="impl">The delegate.</param>
  290. protected void AddCommand (Command command, CommandImplementation impl) { _commandImplementations [command] = impl; }
  291. /// <summary>
  292. /// <para>
  293. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call
  294. /// AddCommand for each command they support.
  295. /// </para>
  296. /// <para>
  297. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="impl"/> will
  298. /// replace the old one.
  299. /// </para>
  300. /// </summary>
  301. /// <remarks>
  302. /// <para>
  303. /// This version of AddCommand is for commands that do not require context.
  304. /// If the command requires context, use
  305. /// <see cref="AddCommand(Command,CommandImplementation)"/>
  306. /// </para>
  307. /// <para>
  308. /// See the Commands Deep Dive for more information: <see href="https://gui-cs.github.io/Terminal.Gui/docs/command.html"/>.
  309. /// </para>
  310. /// </remarks>
  311. /// <param name="command">The command.</param>
  312. /// <param name="impl">The delegate.</param>
  313. protected void AddCommand (Command command, Func<bool?> impl) { _commandImplementations [command] = ctx => impl (); }
  314. /// <summary>Returns all commands that are supported by this <see cref="View"/>.</summary>
  315. /// <returns></returns>
  316. public IEnumerable<Command> GetSupportedCommands () { return _commandImplementations.Keys; }
  317. /// <summary>
  318. /// Invokes the specified commands.
  319. /// </summary>
  320. /// <param name="commands">The set of commands 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
  325. /// continue.
  326. /// <see langword="true"/> if the command was invoked the command was handled (or cancelled); input processing should
  327. /// stop.
  328. /// </returns>
  329. public bool? InvokeCommands<TBindingType> (Command [] commands, TBindingType binding)
  330. {
  331. bool? toReturn = null;
  332. foreach (Command command in commands)
  333. {
  334. if (!_commandImplementations.ContainsKey (command))
  335. {
  336. Logging.Warning (@$"{command} is not supported by this View ({GetType ().Name}). Binding: {binding}.");
  337. }
  338. // each command has its own return value
  339. bool? thisReturn = InvokeCommand (command, binding);
  340. // if we haven't got anything yet, the current command result should be used
  341. toReturn ??= thisReturn;
  342. // if ever see a true then that's what we will return
  343. if (thisReturn ?? false)
  344. {
  345. toReturn = true;
  346. }
  347. }
  348. return toReturn;
  349. }
  350. /// <summary>
  351. /// Invokes the specified command.
  352. /// </summary>
  353. /// <param name="command">The command to invoke.</param>
  354. /// <param name="binding">The binding that caused the invocation, if any. This will be passed as context with the command.</param>
  355. /// <returns>
  356. /// <see langword="null"/> if no command was found; input processing should continue.
  357. /// <see langword="false"/> if the command was invoked and was not handled (or cancelled); input processing should
  358. /// continue.
  359. /// <see langword="true"/> if the command was invoked the command was handled (or cancelled); input processing should
  360. /// stop.
  361. /// </returns>
  362. public bool? InvokeCommand<TBindingType> (Command command, TBindingType binding)
  363. {
  364. if (!_commandImplementations.TryGetValue (command, out CommandImplementation? implementation))
  365. {
  366. _commandImplementations.TryGetValue (Command.NotBound, out implementation);
  367. }
  368. return implementation! (
  369. new CommandContext<TBindingType>
  370. {
  371. Command = command,
  372. Source = this,
  373. Binding = binding
  374. });
  375. }
  376. /// <summary>
  377. /// Invokes the specified command.
  378. /// </summary>
  379. /// <param name="command">The command to invoke.</param>
  380. /// <param name="ctx">The context to pass with the command.</param>
  381. /// <returns>
  382. /// <see langword="null"/> if no command was found; input processing should continue.
  383. /// <see langword="false"/> if the command was invoked and was not handled (or cancelled); input processing should
  384. /// continue.
  385. /// <see langword="true"/> if the command was invoked the command was handled (or cancelled); input processing should
  386. /// stop.
  387. /// </returns>
  388. public bool? InvokeCommand (Command command, ICommandContext? ctx)
  389. {
  390. if (!_commandImplementations.TryGetValue (command, out CommandImplementation? implementation))
  391. {
  392. _commandImplementations.TryGetValue (Command.NotBound, out implementation);
  393. }
  394. return implementation! (ctx);
  395. }
  396. /// <summary>
  397. /// Invokes the specified command without context.
  398. /// </summary>
  399. /// <param name="command">The command to invoke.</param>
  400. /// <returns>
  401. /// <see langword="null"/> if no command was found; input processing should continue.
  402. /// <see langword="false"/> if the command was invoked and was not handled (or cancelled); input processing should
  403. /// continue.
  404. /// <see langword="true"/> if the command was invoked the command was handled (or cancelled); input processing should
  405. /// stop.
  406. /// </returns>
  407. public bool? InvokeCommand (Command command)
  408. {
  409. if (!_commandImplementations.TryGetValue (command, out CommandImplementation? implementation))
  410. {
  411. _commandImplementations.TryGetValue (Command.NotBound, out implementation);
  412. }
  413. return implementation! (
  414. new CommandContext<object>
  415. {
  416. Command = command,
  417. Source = this,
  418. Binding = null
  419. });
  420. }
  421. }