View.Command.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 HotKeyHandled
  15. AddCommand (Command.HotKey,
  16. () =>
  17. {
  18. if (RaiseHotKeyHandled () is true)
  19. {
  20. return true;
  21. }
  22. SetFocus ();
  23. return true;
  24. });
  25. // Space or single-click - Raise Selected
  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 View's state has been accepted by the user. 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. HandledEventArgs 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.Handled = OnAccepted (args) || args.Handled;
  57. if (!args.Handled)
  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.Handled)
  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.Handled;
  80. }
  81. // TODO: Change this to CancelEventArgs
  82. /// <summary>
  83. /// Called when the View's state has been accepted by the user. Set <see cref="HandledEventArgs.Handled"/> to
  84. /// <see langword="true"/> to stop processing.
  85. /// </summary>
  86. /// <param name="args"></param>
  87. /// <returns><see langword="true"/> to stop processing.</returns>
  88. protected virtual bool OnAccepted (HandledEventArgs args) { return false; }
  89. /// <summary>
  90. /// Cancelable event raised when the View's state has been accepted by the user. Set
  91. /// <see cref="HandledEventArgs.Handled"/> to cancel the event.
  92. /// </summary>
  93. public event EventHandler<HandledEventArgs>? Accepted;
  94. /// <summary>
  95. /// 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"/>.
  96. /// event. The default <see cref="Command.Select"/> handler calls this method.
  97. /// </summary>
  98. /// <remarks>
  99. /// The <see cref="Selecting"/> event should raised after the state of the View has been changed and before see <see cref="Accepted"/>.
  100. /// </remarks>
  101. /// <returns>
  102. /// If <see langword="true"/> the event was canceled. If <see langword="false"/> the event was raised but not canceled.
  103. /// If <see langword="null"/> no event was raised.
  104. /// </returns>
  105. protected bool? RaiseSelecting (CommandContext ctx)
  106. {
  107. CommandEventArgs args = new () { Context = ctx };
  108. // Best practice is to invoke the virtual method first.
  109. // This allows derived classes to handle the event and potentially cancel it.
  110. if (OnSelecting (args) || args.Cancel)
  111. {
  112. return true;
  113. }
  114. // If the event is not canceled by the virtual method, raise the event to notify any external subscribers.
  115. Selecting?.Invoke (this, args);
  116. return Selecting is null ? null : args.Cancel;
  117. }
  118. /// <summary>
  119. /// Called when the user has performed an action (e.g. <see cref="Command.Select"/>) causing the View to change state.
  120. /// Set <see cref="CommandEventArgs.Cancel"/> to
  121. /// <see langword="true"/> and return <see langword="true"/> to cancel the state change. The default implementation does nothing.
  122. /// </summary>
  123. /// <param name="args">The event arguments.</param>
  124. /// <returns><see langword="true"/> to stop processing.</returns>
  125. protected virtual bool OnSelecting (CommandEventArgs args) { return false; }
  126. /// <summary>
  127. /// Cancelable event raised when the user has performed an action (e.g. <see cref="Command.Select"/>) causing the View to change state.
  128. /// Set <see cref="CommandEventArgs.Cancel"/> to
  129. /// <see langword="true"/> to cancel the state change.
  130. /// </summary>
  131. public event EventHandler<CommandEventArgs>? Selecting;
  132. // TODO: What does this event really do? "Called when the user has pressed the View's hot key or otherwise invoked the View's hot key command.???"
  133. /// <summary>
  134. /// Called when the View has handled the user pressing the View's <see cref="HotKey"/>. Calls <see cref="OnHotKeyHandled"/> which can be cancelled; if not cancelled raises <see cref="Accepted"/>.
  135. /// event. The default <see cref="Command.HotKey"/> handler calls this method.
  136. /// </summary>
  137. /// <returns>
  138. /// If <see langword="true"/> the event was handled. If <see langword="false"/> the event was raised but not handled.
  139. /// If <see langword="null"/> no event was raised.
  140. /// </returns>
  141. protected bool? RaiseHotKeyHandled ()
  142. {
  143. HandledEventArgs args = new ();
  144. // Best practice is to invoke the virtual method first.
  145. // This allows derived classes to handle the event and potentially cancel it.
  146. if (OnHotKeyHandled (args) || args.Handled)
  147. {
  148. return true;
  149. }
  150. // If the event is not canceled by the virtual method, raise the event to notify any external subscribers.
  151. HotKeyHandled?.Invoke (this, args);
  152. return HotKeyHandled is null ? null : args.Handled;
  153. }
  154. /// <summary>
  155. /// Called when the View has handled the user pressing the View's <see cref="HotKey"/>. Set <see cref="HandledEventArgs.Handled"/> to
  156. /// <see langword="true"/> to stop processing.
  157. /// </summary>
  158. /// <param name="args"></param>
  159. /// <returns><see langword="true"/> to stop processing.</returns>
  160. protected virtual bool OnHotKeyHandled (HandledEventArgs args) { return false; }
  161. /// <summary>
  162. /// Cancelable event raised when the <see cref="Command.HotKey"/> command is invoked. Set
  163. /// <see cref="HandledEventArgs.Handled"/>
  164. /// to cancel the event.
  165. /// </summary>
  166. public event EventHandler<HandledEventArgs>? HotKeyHandled;
  167. #endregion Default Implementation
  168. /// <summary>
  169. /// <para>
  170. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call
  171. /// AddCommand for each command they support.
  172. /// </para>
  173. /// <para>
  174. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  175. /// replace the old one.
  176. /// </para>
  177. /// </summary>
  178. /// <remarks>
  179. /// <para>
  180. /// This version of AddCommand is for commands that require <see cref="CommandContext"/>. Use
  181. /// <see cref="AddCommand(Command,Func{System.Nullable{bool}})"/>
  182. /// in cases where the command does not require a <see cref="CommandContext"/>.
  183. /// </para>
  184. /// </remarks>
  185. /// <param name="command">The command.</param>
  186. /// <param name="f">The function.</param>
  187. protected void AddCommand (Command command, Func<CommandContext, bool?> f) { CommandImplementations [command] = f; }
  188. /// <summary>
  189. /// <para>
  190. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call
  191. /// AddCommand for each command they support.
  192. /// </para>
  193. /// <para>
  194. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  195. /// replace the old one.
  196. /// </para>
  197. /// </summary>
  198. /// <remarks>
  199. /// <para>
  200. /// This version of AddCommand is for commands that do not require a <see cref="CommandContext"/>.
  201. /// If the command requires context, use
  202. /// <see cref="AddCommand(Command,Func{CommandContext,System.Nullable{bool}})"/>
  203. /// </para>
  204. /// </remarks>
  205. /// <param name="command">The command.</param>
  206. /// <param name="f">The function.</param>
  207. protected void AddCommand (Command command, Func<bool?> f) { CommandImplementations [command] = ctx => f (); }
  208. /// <summary>Returns all commands that are supported by this <see cref="View"/>.</summary>
  209. /// <returns></returns>
  210. public IEnumerable<Command> GetSupportedCommands () { return CommandImplementations.Keys; }
  211. /// <summary>
  212. /// Invokes the specified commands.
  213. /// </summary>
  214. /// <param name="commands"></param>
  215. /// <param name="key">The key that caused the commands to be invoked, if any.</param>
  216. /// <param name="keyBinding"></param>
  217. /// <returns>
  218. /// <see langword="null"/> if no command was found.
  219. /// <see langword="true"/> if the command was invoked the command was handled (or cancelled)
  220. /// <see langword="false"/> if the command was invoked and the command was not handled.
  221. /// </returns>
  222. public bool? InvokeCommands (Command [] commands, Key? key = null, KeyBinding? keyBinding = null)
  223. {
  224. bool? toReturn = null;
  225. foreach (Command command in commands)
  226. {
  227. if (!CommandImplementations.ContainsKey (command))
  228. {
  229. throw new NotSupportedException (@$"{command} is not supported by ({GetType ().Name}).");
  230. }
  231. // each command has its own return value
  232. bool? thisReturn = InvokeCommand (command, key, keyBinding);
  233. // if we haven't got anything yet, the current command result should be used
  234. toReturn ??= thisReturn;
  235. // if ever see a true then that's what we will return
  236. if (thisReturn ?? false)
  237. {
  238. toReturn = true;
  239. }
  240. }
  241. return toReturn;
  242. }
  243. /// <summary>Invokes the specified command.</summary>
  244. /// <param name="command">The command to invoke.</param>
  245. /// <param name="key">The key that caused the command to be invoked, if any.</param>
  246. /// <param name="keyBinding"></param>
  247. /// <returns>
  248. /// <see langword="null"/> if no command was found. <see langword="true"/> if the command was invoked, and it
  249. /// handled (or cancelled) the command. <see langword="false"/> if the command was invoked, and it did not handle (or cancel) the command.
  250. /// </returns>
  251. public bool? InvokeCommand (Command command, Key? key = null, KeyBinding? keyBinding = null)
  252. {
  253. if (CommandImplementations.TryGetValue (command, out Func<CommandContext, bool?>? implementation))
  254. {
  255. var context = new CommandContext (command, key, keyBinding); // Create the context here
  256. return implementation (context);
  257. }
  258. return null;
  259. }
  260. /// <summary>
  261. /// Invokes the specified command.
  262. /// </summary>
  263. /// <param name="command">The command to invoke.</param>
  264. /// <param name="ctx">Context to pass with the invocation.</param>
  265. /// <returns>
  266. /// <see langword="null"/> if no command was found. <see langword="true"/> if the command was invoked, and it
  267. /// handled (or cancelled) the command. <see langword="false"/> if the command was invoked, and it did not handle (or cancel) the command.
  268. /// </returns>
  269. public bool? InvokeCommand (Command command, CommandContext ctx)
  270. {
  271. if (CommandImplementations.TryGetValue (command, out Func<CommandContext, bool?>? implementation))
  272. {
  273. return implementation (ctx);
  274. }
  275. return null;
  276. }
  277. }