Application.Keyboard.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. // BUGBUG: this seems unneeded.
  90. if (!KeyBindings.TryGet (key, out KeyBinding keybinding))
  91. {
  92. return null;
  93. }
  94. bool? toReturn = null;
  95. foreach (Command command in keybinding.Commands)
  96. {
  97. toReturn = InvokeCommand (command, key, keybinding);
  98. }
  99. handled = toReturn ?? true;
  100. }
  101. }
  102. return handled;
  103. }
  104. /// <summary>
  105. /// Invokes an Application-bound command.
  106. /// </summary>
  107. /// <param name="command">The Command to invoke</param>
  108. /// <param name="key">The Application-bound Key that was pressed.</param>
  109. /// <param name="binding">Describes the binding.</param>
  110. /// <returns>
  111. /// <see langword="null"/> if no command was found; input processing should continue.
  112. /// <see langword="false"/> if the command was invoked and was not handled (or cancelled); input processing should continue.
  113. /// <see langword="true"/> if the command was invoked the command was handled (or cancelled); input processing should stop.
  114. /// </returns>
  115. /// <exception cref="NotSupportedException"></exception>
  116. public static bool? InvokeCommand (Command command, Key key, KeyBinding binding)
  117. {
  118. if (!_commandImplementations!.ContainsKey (command))
  119. {
  120. throw new NotSupportedException (
  121. @$"A KeyBinding was set up for the command {command} ({key}) but that command is not supported by Application."
  122. );
  123. }
  124. if (_commandImplementations.TryGetValue (command, out View.CommandImplementation? implementation))
  125. {
  126. CommandContext<KeyBinding> context = new (command, null, binding); // Create the context here
  127. return implementation (context);
  128. }
  129. return null;
  130. }
  131. /// <summary>
  132. /// Raised when the user presses a key.
  133. /// <para>
  134. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  135. /// additional processing.
  136. /// </para>
  137. /// </summary>
  138. /// <remarks>
  139. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  140. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  141. /// <para>Fired after <see cref="KeyDown"/> and before <see cref="KeyUp"/>.</para>
  142. /// </remarks>
  143. public static event EventHandler<Key>? KeyDown;
  144. /// <summary>
  145. /// Called when the user releases a key (by the <see cref="IConsoleDriver"/>). Raises the cancelable
  146. /// <see cref="KeyUp"/>
  147. /// event
  148. /// then calls <see cref="View.NewKeyUpEvent"/> on all top level views. Called after <see cref="RaiseKeyDownEvent"/>.
  149. /// </summary>
  150. /// <remarks>Can be used to simulate key release events.</remarks>
  151. /// <param name="key"></param>
  152. /// <returns><see langword="true"/> if the key was handled.</returns>
  153. public static bool RaiseKeyUpEvent (Key key)
  154. {
  155. if (!Initialized)
  156. {
  157. return true;
  158. }
  159. KeyUp?.Invoke (null, key);
  160. if (key.Handled)
  161. {
  162. return true;
  163. }
  164. // TODO: Add Popover support
  165. foreach (Toplevel topLevel in TopLevels.ToList ())
  166. {
  167. if (topLevel.NewKeyUpEvent (key))
  168. {
  169. return true;
  170. }
  171. if (topLevel.Modal)
  172. {
  173. break;
  174. }
  175. }
  176. return false;
  177. }
  178. #region Application-scoped KeyBindings
  179. static Application ()
  180. {
  181. AddKeyBindings ();
  182. }
  183. /// <summary>Gets the Application-scoped key bindings.</summary>
  184. public static KeyBindings KeyBindings { get; internal set; } = new (null);
  185. internal static void AddKeyBindings ()
  186. {
  187. _commandImplementations.Clear ();
  188. // Things Application knows how to do
  189. AddCommand (
  190. Command.Quit,
  191. static () =>
  192. {
  193. RequestStop ();
  194. return true;
  195. }
  196. );
  197. AddCommand (
  198. Command.Suspend,
  199. static () =>
  200. {
  201. Driver?.Suspend ();
  202. return true;
  203. }
  204. );
  205. AddCommand (
  206. Command.NextTabStop,
  207. static () => Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabStop));
  208. AddCommand (
  209. Command.PreviousTabStop,
  210. static () => Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabStop));
  211. AddCommand (
  212. Command.NextTabGroup,
  213. static () => Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabGroup));
  214. AddCommand (
  215. Command.PreviousTabGroup,
  216. static () => Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabGroup));
  217. AddCommand (
  218. Command.Refresh,
  219. static () =>
  220. {
  221. LayoutAndDraw (true);
  222. return true;
  223. }
  224. );
  225. AddCommand (
  226. Command.Arrange,
  227. static () =>
  228. {
  229. View? viewToArrange = Navigation?.GetFocused ();
  230. // Go up the superview hierarchy and find the first that is not ViewArrangement.Fixed
  231. while (viewToArrange is { SuperView: { }, Arrangement: ViewArrangement.Fixed })
  232. {
  233. viewToArrange = viewToArrange.SuperView;
  234. }
  235. if (viewToArrange is { })
  236. {
  237. return viewToArrange.Border?.EnterArrangeMode (ViewArrangement.Fixed);
  238. }
  239. return false;
  240. });
  241. //SetKeysToHardCodedDefaults ();
  242. // Need to clear after setting the above to ensure actually clear
  243. // because set_QuitKey etc.. may call Add
  244. KeyBindings.Clear ();
  245. KeyBindings.Add (QuitKey, Command.Quit);
  246. KeyBindings.Add (NextTabKey, Command.NextTabStop);
  247. KeyBindings.Add (PrevTabKey, Command.PreviousTabStop);
  248. KeyBindings.Add (NextTabGroupKey, Command.NextTabGroup);
  249. KeyBindings.Add (PrevTabGroupKey, Command.PreviousTabGroup);
  250. KeyBindings.Add (ArrangeKey, Command.Arrange);
  251. KeyBindings.Add (Key.CursorRight, Command.NextTabStop);
  252. KeyBindings.Add (Key.CursorDown, Command.NextTabStop);
  253. KeyBindings.Add (Key.CursorLeft, Command.PreviousTabStop);
  254. KeyBindings.Add (Key.CursorUp, Command.PreviousTabStop);
  255. // TODO: Refresh Key should be configurable
  256. KeyBindings.Add (Key.F5, Command.Refresh);
  257. // TODO: Suspend Key should be configurable
  258. if (Environment.OSVersion.Platform == PlatformID.Unix)
  259. {
  260. KeyBindings.Add (Key.Z.WithCtrl, Command.Suspend);
  261. }
  262. }
  263. #endregion Application-scoped KeyBindings
  264. /// <summary>
  265. /// <para>
  266. /// Sets the function that will be invoked for a <see cref="Command"/>.
  267. /// </para>
  268. /// <para>
  269. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  270. /// replace the old one.
  271. /// </para>
  272. /// </summary>
  273. /// <remarks>
  274. /// <para>
  275. /// This version of AddCommand is for commands that do not require a <see cref="ICommandContext"/>.
  276. /// </para>
  277. /// </remarks>
  278. /// <param name="command">The command.</param>
  279. /// <param name="f">The function.</param>
  280. private static void AddCommand (Command command, Func<bool?> f) { _commandImplementations! [command] = ctx => f (); }
  281. /// <summary>
  282. /// Commands for Application.
  283. /// </summary>
  284. private static readonly Dictionary<Command, View.CommandImplementation> _commandImplementations = new ();
  285. }