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