View.Command.cs 14 KB

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