Application.Keyboard.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. #nullable enable
  2. namespace Terminal.Gui;
  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 commmand.
  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. foreach (Toplevel topLevel in TopLevels.ToList ())
  165. {
  166. if (topLevel.NewKeyUpEvent (key))
  167. {
  168. return true;
  169. }
  170. if (topLevel.Modal)
  171. {
  172. break;
  173. }
  174. }
  175. return false;
  176. }
  177. #region Application-scoped KeyBindings
  178. static Application () { AddKeyBindings (); }
  179. /// <summary>Gets the Application-scoped key bindings.</summary>
  180. public static KeyBindings KeyBindings { get; internal set; } = new (null);
  181. internal static void AddKeyBindings ()
  182. {
  183. _commandImplementations.Clear ();
  184. // Things Application knows how to do
  185. AddCommand (
  186. Command.Quit,
  187. static () =>
  188. {
  189. RequestStop ();
  190. return true;
  191. }
  192. );
  193. AddCommand (
  194. Command.Suspend,
  195. static () =>
  196. {
  197. Driver?.Suspend ();
  198. return true;
  199. }
  200. );
  201. AddCommand (
  202. Command.NextTabStop,
  203. static () => Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabStop));
  204. AddCommand (
  205. Command.PreviousTabStop,
  206. static () => Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabStop));
  207. AddCommand (
  208. Command.NextTabGroup,
  209. static () => Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabGroup));
  210. AddCommand (
  211. Command.PreviousTabGroup,
  212. static () => Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabGroup));
  213. AddCommand (
  214. Command.Refresh,
  215. static () =>
  216. {
  217. LayoutAndDraw (true);
  218. return true;
  219. }
  220. );
  221. AddCommand (
  222. Command.Arrange,
  223. static () =>
  224. {
  225. View? viewToArrange = Navigation?.GetFocused ();
  226. // Go up the superview hierarchy and find the first that is not ViewArrangement.Fixed
  227. while (viewToArrange is { SuperView: { }, Arrangement: ViewArrangement.Fixed })
  228. {
  229. viewToArrange = viewToArrange.SuperView;
  230. }
  231. if (viewToArrange is { })
  232. {
  233. return viewToArrange.Border?.EnterArrangeMode (ViewArrangement.Fixed);
  234. }
  235. return false;
  236. });
  237. // Resources/config.json overrides
  238. QuitKey = Key.Esc;
  239. NextTabKey = Key.Tab;
  240. PrevTabKey = Key.Tab.WithShift;
  241. NextTabGroupKey = Key.F6;
  242. PrevTabGroupKey = Key.F6.WithShift;
  243. ArrangeKey = Key.F5.WithCtrl;
  244. // Need to clear after setting the above to ensure actually clear
  245. // because set_QuitKey etc.. may call Add
  246. KeyBindings.Clear ();
  247. KeyBindings.Add (QuitKey, Command.Quit);
  248. KeyBindings.Add (NextTabKey, Command.NextTabStop);
  249. KeyBindings.Add (PrevTabKey, Command.PreviousTabStop);
  250. KeyBindings.Add (NextTabGroupKey, Command.NextTabGroup);
  251. KeyBindings.Add (PrevTabGroupKey, Command.PreviousTabGroup);
  252. KeyBindings.Add (ArrangeKey, Command.Arrange);
  253. KeyBindings.Add (Key.CursorRight, Command.NextTabStop);
  254. KeyBindings.Add (Key.CursorDown, Command.NextTabStop);
  255. KeyBindings.Add (Key.CursorLeft, Command.PreviousTabStop);
  256. KeyBindings.Add (Key.CursorUp, Command.PreviousTabStop);
  257. // TODO: Refresh Key should be configurable
  258. KeyBindings.Add (Key.F5, Command.Refresh);
  259. // TODO: Suspend Key should be configurable
  260. if (Environment.OSVersion.Platform == PlatformID.Unix)
  261. {
  262. KeyBindings.Add (Key.Z.WithCtrl, Command.Suspend);
  263. }
  264. }
  265. #endregion Application-scoped KeyBindings
  266. /// <summary>
  267. /// <para>
  268. /// Sets the function that will be invoked for a <see cref="Command"/>.
  269. /// </para>
  270. /// <para>
  271. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  272. /// replace the old one.
  273. /// </para>
  274. /// </summary>
  275. /// <remarks>
  276. /// <para>
  277. /// This version of AddCommand is for commands that do not require a <see cref="ICommandContext"/>.
  278. /// </para>
  279. /// </remarks>
  280. /// <param name="command">The command.</param>
  281. /// <param name="f">The function.</param>
  282. private static void AddCommand (Command command, Func<bool?> f) { _commandImplementations! [command] = ctx => f (); }
  283. /// <summary>
  284. /// Commands for Application.
  285. /// </summary>
  286. private static readonly Dictionary<Command, View.CommandImplementation> _commandImplementations = new ();
  287. }