Application.Keyboard.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. #nullable enable
  2. namespace Terminal.Gui.App;
  3. public static partial class Application // Keyboard handling
  4. {
  5. /// <summary>
  6. /// Called when the user presses a key (by the <see cref="IConsoleDriver"/>). Raises the cancelable
  7. /// <see cref="KeyDown"/> event, then calls <see cref="View.NewKeyDownEvent"/> on all top level views, and finally
  8. /// if the key was not handled, invokes any Application-scoped <see cref="KeyBindings"/>.
  9. /// </summary>
  10. /// <remarks>Can be used to simulate key press events.</remarks>
  11. /// <param name="key"></param>
  12. /// <returns><see langword="true"/> if the key was handled.</returns>
  13. public static bool RaiseKeyDownEvent (Key key)
  14. {
  15. Logging.Debug ($"{key}");
  16. // TODO: Add a way to ignore certain keys, esp for debugging.
  17. //#if DEBUG
  18. // if (key == Key.Empty.WithAlt || key == Key.Empty.WithCtrl)
  19. // {
  20. // Logging.Debug ($"Ignoring {key}");
  21. // return false;
  22. // }
  23. //#endif
  24. // TODO: This should match standard event patterns
  25. KeyDown?.Invoke (null, key);
  26. if (key.Handled)
  27. {
  28. return true;
  29. }
  30. if (Popover?.DispatchKeyDown (key) is true)
  31. {
  32. return true;
  33. }
  34. if (Top is null)
  35. {
  36. foreach (Toplevel topLevel in TopLevels.ToList ())
  37. {
  38. if (topLevel.NewKeyDownEvent (key))
  39. {
  40. return true;
  41. }
  42. if (topLevel.Modal)
  43. {
  44. break;
  45. }
  46. }
  47. }
  48. else
  49. {
  50. if (Top.NewKeyDownEvent (key))
  51. {
  52. return true;
  53. }
  54. }
  55. bool? commandHandled = InvokeCommandsBoundToKey (key);
  56. if(commandHandled is true)
  57. {
  58. return true;
  59. }
  60. return false;
  61. }
  62. /// <summary>
  63. /// Invokes any commands bound at the Application-level to <paramref name="key"/>.
  64. /// </summary>
  65. /// <param name="key"></param>
  66. /// <returns>
  67. /// <see langword="null"/> if no command was found; input processing should continue.
  68. /// <see langword="false"/> if the command was invoked and was not handled (or cancelled); input processing should continue.
  69. /// <see langword="true"/> if the command was invoked the command was handled (or cancelled); input processing should stop.
  70. /// </returns>
  71. public static bool? InvokeCommandsBoundToKey (Key key)
  72. {
  73. bool? handled = null;
  74. // Invoke any Application-scoped KeyBindings.
  75. // The first view that handles the key will stop the loop.
  76. // foreach (KeyValuePair<Key, KeyBinding> binding in KeyBindings.GetBindings (key))
  77. if (KeyBindings.TryGet (key, out KeyBinding binding))
  78. {
  79. if (binding.Target is { })
  80. {
  81. if (!binding.Target.Enabled)
  82. {
  83. return null;
  84. }
  85. handled = binding.Target?.InvokeCommands (binding.Commands, binding);
  86. }
  87. else
  88. {
  89. bool? toReturn = null;
  90. foreach (Command command in binding.Commands)
  91. {
  92. toReturn = InvokeCommand (command, key, binding);
  93. }
  94. handled = toReturn ?? true;
  95. }
  96. }
  97. return handled;
  98. }
  99. /// <summary>
  100. /// Invokes an Application-bound command.
  101. /// </summary>
  102. /// <param name="command">The Command to invoke</param>
  103. /// <param name="key">The Application-bound Key that was pressed.</param>
  104. /// <param name="binding">Describes the binding.</param>
  105. /// <returns>
  106. /// <see langword="null"/> if no command was found; input processing should continue.
  107. /// <see langword="false"/> if the command was invoked and was not handled (or cancelled); input processing should continue.
  108. /// <see langword="true"/> if the command was invoked the command was handled (or cancelled); input processing should stop.
  109. /// </returns>
  110. /// <exception cref="NotSupportedException"></exception>
  111. public static bool? InvokeCommand (Command command, Key key, KeyBinding binding)
  112. {
  113. if (!_commandImplementations!.ContainsKey (command))
  114. {
  115. throw new NotSupportedException (
  116. @$"A KeyBinding was set up for the command {command} ({key}) but that command is not supported by Application."
  117. );
  118. }
  119. if (_commandImplementations.TryGetValue (command, out View.CommandImplementation? implementation))
  120. {
  121. CommandContext<KeyBinding> context = new (command, null, binding); // Create the context here
  122. return implementation (context);
  123. }
  124. return null;
  125. }
  126. /// <summary>
  127. /// Raised when the user presses a key.
  128. /// <para>
  129. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  130. /// additional processing.
  131. /// </para>
  132. /// </summary>
  133. /// <remarks>
  134. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Unix) do not support firing the
  135. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  136. /// <para>Fired after <see cref="KeyDown"/> and before <see cref="KeyUp"/>.</para>
  137. /// </remarks>
  138. public static event EventHandler<Key>? KeyDown;
  139. /// <summary>
  140. /// Called when the user releases a key (by the <see cref="IConsoleDriver"/>). Raises the cancelable
  141. /// <see cref="KeyUp"/>
  142. /// event
  143. /// then calls <see cref="View.NewKeyUpEvent"/> on all top level views. Called after <see cref="RaiseKeyDownEvent"/>.
  144. /// </summary>
  145. /// <remarks>Can be used to simulate key release events.</remarks>
  146. /// <param name="key"></param>
  147. /// <returns><see langword="true"/> if the key was handled.</returns>
  148. public static bool RaiseKeyUpEvent (Key key)
  149. {
  150. if (!Initialized)
  151. {
  152. return true;
  153. }
  154. KeyUp?.Invoke (null, key);
  155. if (key.Handled)
  156. {
  157. return true;
  158. }
  159. // TODO: Add Popover support
  160. foreach (Toplevel topLevel in TopLevels.ToList ())
  161. {
  162. if (topLevel.NewKeyUpEvent (key))
  163. {
  164. return true;
  165. }
  166. if (topLevel.Modal)
  167. {
  168. break;
  169. }
  170. }
  171. return false;
  172. }
  173. #region Application-scoped KeyBindings
  174. static Application ()
  175. {
  176. AddKeyBindings ();
  177. }
  178. /// <summary>Gets the Application-scoped key bindings.</summary>
  179. public static KeyBindings KeyBindings { get; internal set; } = new (null);
  180. internal static void AddKeyBindings ()
  181. {
  182. _commandImplementations.Clear ();
  183. // Things Application knows how to do
  184. AddCommand (
  185. Command.Quit,
  186. static () =>
  187. {
  188. RequestStop ();
  189. return true;
  190. }
  191. );
  192. AddCommand (
  193. Command.Suspend,
  194. static () =>
  195. {
  196. Driver?.Suspend ();
  197. return true;
  198. }
  199. );
  200. AddCommand (
  201. Command.NextTabStop,
  202. static () => Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabStop));
  203. AddCommand (
  204. Command.PreviousTabStop,
  205. static () => Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabStop));
  206. AddCommand (
  207. Command.NextTabGroup,
  208. static () => Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabGroup));
  209. AddCommand (
  210. Command.PreviousTabGroup,
  211. static () => Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabGroup));
  212. AddCommand (
  213. Command.Refresh,
  214. static () =>
  215. {
  216. LayoutAndDraw (true);
  217. return true;
  218. }
  219. );
  220. AddCommand (
  221. Command.Arrange,
  222. static () =>
  223. {
  224. View? viewToArrange = Navigation?.GetFocused ();
  225. // Go up the superview hierarchy and find the first that is not ViewArrangement.Fixed
  226. while (viewToArrange is { SuperView: { }, Arrangement: ViewArrangement.Fixed })
  227. {
  228. viewToArrange = viewToArrange.SuperView;
  229. }
  230. if (viewToArrange is { })
  231. {
  232. return viewToArrange.Border?.EnterArrangeMode (ViewArrangement.Fixed);
  233. }
  234. return false;
  235. });
  236. //SetKeysToHardCodedDefaults ();
  237. // Need to clear after setting the above to ensure actually clear
  238. // because set_QuitKey etc.. may call Add
  239. KeyBindings.Clear ();
  240. KeyBindings.Add (QuitKey, Command.Quit);
  241. KeyBindings.Add (NextTabKey, Command.NextTabStop);
  242. KeyBindings.Add (PrevTabKey, Command.PreviousTabStop);
  243. KeyBindings.Add (NextTabGroupKey, Command.NextTabGroup);
  244. KeyBindings.Add (PrevTabGroupKey, Command.PreviousTabGroup);
  245. KeyBindings.Add (ArrangeKey, Command.Arrange);
  246. KeyBindings.Add (Key.CursorRight, Command.NextTabStop);
  247. KeyBindings.Add (Key.CursorDown, Command.NextTabStop);
  248. KeyBindings.Add (Key.CursorLeft, Command.PreviousTabStop);
  249. KeyBindings.Add (Key.CursorUp, Command.PreviousTabStop);
  250. // TODO: Refresh Key should be configurable
  251. KeyBindings.Add (Key.F5, Command.Refresh);
  252. // TODO: Suspend Key should be configurable
  253. if (Environment.OSVersion.Platform == PlatformID.Unix)
  254. {
  255. KeyBindings.Add (Key.Z.WithCtrl, Command.Suspend);
  256. }
  257. }
  258. #endregion Application-scoped KeyBindings
  259. /// <summary>
  260. /// <para>
  261. /// Sets the function that will be invoked for a <see cref="Command"/>.
  262. /// </para>
  263. /// <para>
  264. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  265. /// replace the old one.
  266. /// </para>
  267. /// </summary>
  268. /// <remarks>
  269. /// <para>
  270. /// This version of AddCommand is for commands that do not require a <see cref="ICommandContext"/>.
  271. /// </para>
  272. /// </remarks>
  273. /// <param name="command">The command.</param>
  274. /// <param name="f">The function.</param>
  275. private static void AddCommand (Command command, Func<bool?> f) { _commandImplementations! [command] = ctx => f (); }
  276. /// <summary>
  277. /// Commands for Application.
  278. /// </summary>
  279. private static readonly Dictionary<Command, View.CommandImplementation> _commandImplementations = new ();
  280. }