Application.Keyboard.cs 11 KB

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