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