Application.Keyboard.cs 9.7 KB

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