Application.Keyboard.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. #nullable enable
  2. namespace Terminal.Gui;
  3. public static partial class Application // Keyboard handling
  4. {
  5. private static Key _nextTabGroupKey = Key.F6; // Resources/config.json overrrides
  6. private static Key _nextTabKey = Key.Tab; // Resources/config.json overrrides
  7. private static Key _prevTabGroupKey = Key.F6.WithShift; // Resources/config.json overrrides
  8. private static Key _prevTabKey = Key.Tab.WithShift; // Resources/config.json overrrides
  9. private static Key _quitKey = Key.Esc; // Resources/config.json overrrides
  10. static Application () { AddApplicationKeyBindings (); }
  11. /// <summary>Gets the key bindings for this view.</summary>
  12. public static KeyBindings KeyBindings { get; internal set; } = new ();
  13. /// <summary>
  14. /// Event fired when the user presses a key. Fired by <see cref="OnKeyDown"/>.
  15. /// <para>
  16. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  17. /// additional processing.
  18. /// </para>
  19. /// </summary>
  20. /// <remarks>
  21. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  22. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  23. /// <para>Fired after <see cref="KeyDown"/> and before <see cref="KeyUp"/>.</para>
  24. /// </remarks>
  25. public static event EventHandler<Key>? KeyDown;
  26. /// <summary>
  27. /// Event fired when the user releases a key. Fired by <see cref="OnKeyUp"/>.
  28. /// <para>
  29. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  30. /// additional processing.
  31. /// </para>
  32. /// </summary>
  33. /// <remarks>
  34. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  35. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  36. /// <para>Fired after <see cref="KeyDown"/>.</para>
  37. /// </remarks>
  38. public static event EventHandler<Key>? KeyUp;
  39. /// <summary>Alternative key to navigate forwards through views. Ctrl+Tab is the primary key.</summary>
  40. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  41. public static Key NextTabGroupKey
  42. {
  43. get => _nextTabGroupKey;
  44. set
  45. {
  46. if (_nextTabGroupKey != value)
  47. {
  48. ReplaceKey (_nextTabGroupKey, value);
  49. _nextTabGroupKey = value;
  50. }
  51. }
  52. }
  53. /// <summary>Alternative key to navigate forwards through views. Ctrl+Tab is the primary key.</summary>
  54. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  55. public static Key NextTabKey
  56. {
  57. get => _nextTabKey;
  58. set
  59. {
  60. if (_nextTabKey != value)
  61. {
  62. ReplaceKey (_nextTabKey, value);
  63. _nextTabKey = value;
  64. }
  65. }
  66. }
  67. /// <summary>
  68. /// Called by the <see cref="ConsoleDriver"/> when the user presses a key. Fires the <see cref="KeyDown"/> event
  69. /// then calls <see cref="View.NewKeyDownEvent"/> on all top level views. Called after <see cref="OnKeyDown"/> and
  70. /// before <see cref="OnKeyUp"/>.
  71. /// </summary>
  72. /// <remarks>Can be used to simulate key press events.</remarks>
  73. /// <param name="keyEvent"></param>
  74. /// <returns><see langword="true"/> if the key was handled.</returns>
  75. public static bool OnKeyDown (Key keyEvent)
  76. {
  77. //if (!IsInitialized)
  78. //{
  79. // return true;
  80. //}
  81. KeyDown?.Invoke (null, keyEvent);
  82. if (keyEvent.Handled)
  83. {
  84. return true;
  85. }
  86. if (Current is null)
  87. {
  88. foreach (Toplevel topLevel in TopLevels.ToList ())
  89. {
  90. if (topLevel.NewKeyDownEvent (keyEvent))
  91. {
  92. return true;
  93. }
  94. if (topLevel.Modal)
  95. {
  96. break;
  97. }
  98. }
  99. }
  100. else
  101. {
  102. if (Current.NewKeyDownEvent (keyEvent))
  103. {
  104. return true;
  105. }
  106. }
  107. // Invoke any Application-scoped KeyBindings.
  108. // The first view that handles the key will stop the loop.
  109. foreach (KeyValuePair<Key, KeyBinding> binding in KeyBindings.Bindings.Where (b => b.Key == keyEvent.KeyCode))
  110. {
  111. if (binding.Value.BoundView is { })
  112. {
  113. bool? handled = binding.Value.BoundView?.InvokeCommands (binding.Value.Commands, binding.Key, binding.Value);
  114. if (handled != null && (bool)handled)
  115. {
  116. return true;
  117. }
  118. }
  119. else
  120. {
  121. if (!KeyBindings.TryGet (keyEvent, KeyBindingScope.Application, out KeyBinding appBinding))
  122. {
  123. continue;
  124. }
  125. bool? toReturn = null;
  126. foreach (Command command in appBinding.Commands)
  127. {
  128. toReturn = InvokeCommand (command, keyEvent, appBinding);
  129. }
  130. return toReturn ?? true;
  131. }
  132. }
  133. return false;
  134. }
  135. /// <summary>
  136. /// INTENRAL method to invoke one of the commands in <see cref="CommandImplementations"/>
  137. /// </summary>
  138. /// <param name="command"></param>
  139. /// <param name="keyEvent"></param>
  140. /// <param name="appBinding"></param>
  141. /// <returns></returns>
  142. /// <exception cref="NotSupportedException"></exception>
  143. private static bool? InvokeCommand (Command command, Key keyEvent, KeyBinding appBinding)
  144. {
  145. if (!CommandImplementations!.ContainsKey (command))
  146. {
  147. throw new NotSupportedException (
  148. @$"A KeyBinding was set up for the command {command} ({keyEvent}) but that command is not supported by Application."
  149. );
  150. }
  151. if (CommandImplementations.TryGetValue (command, out Func<CommandContext, bool?>? implementation))
  152. {
  153. var context = new CommandContext (command, keyEvent, appBinding); // Create the context here
  154. return implementation (context);
  155. }
  156. return false;
  157. }
  158. /// <summary>
  159. /// Called by the <see cref="ConsoleDriver"/> when the user releases a key. Fires the <see cref="KeyUp"/> event
  160. /// then calls <see cref="View.NewKeyUpEvent"/> on all top level views. Called after <see cref="OnKeyDown"/>.
  161. /// </summary>
  162. /// <remarks>Can be used to simulate key press events.</remarks>
  163. /// <param name="a"></param>
  164. /// <returns><see langword="true"/> if the key was handled.</returns>
  165. public static bool OnKeyUp (Key a)
  166. {
  167. if (!IsInitialized)
  168. {
  169. return true;
  170. }
  171. KeyUp?.Invoke (null, a);
  172. if (a.Handled)
  173. {
  174. return true;
  175. }
  176. foreach (Toplevel topLevel in TopLevels.ToList ())
  177. {
  178. if (topLevel.NewKeyUpEvent (a))
  179. {
  180. return true;
  181. }
  182. if (topLevel.Modal)
  183. {
  184. break;
  185. }
  186. }
  187. return false;
  188. }
  189. /// <summary>Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.</summary>
  190. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  191. public static Key PrevTabGroupKey
  192. {
  193. get => _prevTabGroupKey;
  194. set
  195. {
  196. if (_prevTabGroupKey != value)
  197. {
  198. ReplaceKey (_prevTabGroupKey, value);
  199. _prevTabGroupKey = value;
  200. }
  201. }
  202. }
  203. /// <summary>Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.</summary>
  204. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  205. public static Key PrevTabKey
  206. {
  207. get => _prevTabKey;
  208. set
  209. {
  210. if (_prevTabKey != value)
  211. {
  212. ReplaceKey (_prevTabKey, value);
  213. _prevTabKey = value;
  214. }
  215. }
  216. }
  217. /// <summary>Gets or sets the key to quit the application.</summary>
  218. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  219. public static Key QuitKey
  220. {
  221. get => _quitKey;
  222. set
  223. {
  224. if (_quitKey != value)
  225. {
  226. ReplaceKey (_quitKey, value);
  227. _quitKey = value;
  228. }
  229. }
  230. }
  231. internal static void AddApplicationKeyBindings ()
  232. {
  233. CommandImplementations = new ();
  234. // Things this view knows how to do
  235. AddCommand (
  236. Command.QuitToplevel, // TODO: IRunnable: Rename to Command.Quit to make more generic.
  237. static () =>
  238. {
  239. if (ApplicationOverlapped.OverlappedTop is { })
  240. {
  241. RequestStop (Current!);
  242. }
  243. else
  244. {
  245. RequestStop ();
  246. }
  247. return true;
  248. }
  249. );
  250. AddCommand (
  251. Command.Suspend,
  252. static () =>
  253. {
  254. Driver?.Suspend ();
  255. return true;
  256. }
  257. );
  258. AddCommand (
  259. Command.NextView,
  260. static () => Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabStop));
  261. AddCommand (
  262. Command.PreviousView,
  263. static () => Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabStop));
  264. AddCommand (
  265. Command.NextViewOrTop,
  266. static () =>
  267. {
  268. // TODO: This OverlapppedTop tomfoolery goes away in addressing #2491
  269. if (ApplicationOverlapped.OverlappedTop is { })
  270. {
  271. ApplicationOverlapped.OverlappedMoveNext ();
  272. return true;
  273. }
  274. return Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabGroup);
  275. }
  276. );
  277. AddCommand (
  278. Command.PreviousViewOrTop,
  279. static () =>
  280. {
  281. // TODO: This OverlapppedTop tomfoolery goes away in addressing #2491
  282. if (ApplicationOverlapped.OverlappedTop is { })
  283. {
  284. ApplicationOverlapped.OverlappedMovePrevious ();
  285. return true;
  286. }
  287. return Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabGroup);
  288. }
  289. );
  290. AddCommand (
  291. Command.Refresh,
  292. static () =>
  293. {
  294. Refresh ();
  295. return true;
  296. }
  297. );
  298. KeyBindings.Clear ();
  299. // Resources/config.json overrrides
  300. NextTabKey = Key.Tab;
  301. PrevTabKey = Key.Tab.WithShift;
  302. NextTabGroupKey = Key.F6;
  303. PrevTabGroupKey = Key.F6.WithShift;
  304. QuitKey = Key.Esc;
  305. KeyBindings.Add (QuitKey, KeyBindingScope.Application, Command.QuitToplevel);
  306. KeyBindings.Add (Key.CursorRight, KeyBindingScope.Application, Command.NextView);
  307. KeyBindings.Add (Key.CursorDown, KeyBindingScope.Application, Command.NextView);
  308. KeyBindings.Add (Key.CursorLeft, KeyBindingScope.Application, Command.PreviousView);
  309. KeyBindings.Add (Key.CursorUp, KeyBindingScope.Application, Command.PreviousView);
  310. KeyBindings.Add (NextTabKey, KeyBindingScope.Application, Command.NextView);
  311. KeyBindings.Add (PrevTabKey, KeyBindingScope.Application, Command.PreviousView);
  312. KeyBindings.Add (NextTabGroupKey, KeyBindingScope.Application, Command.NextViewOrTop);
  313. KeyBindings.Add (PrevTabGroupKey, KeyBindingScope.Application, Command.PreviousViewOrTop);
  314. // TODO: Refresh Key should be configurable
  315. KeyBindings.Add (Key.F5, KeyBindingScope.Application, Command.Refresh);
  316. // TODO: Suspend Key should be configurable
  317. if (Environment.OSVersion.Platform == PlatformID.Unix)
  318. {
  319. KeyBindings.Add (Key.Z.WithCtrl, KeyBindingScope.Application, Command.Suspend);
  320. }
  321. }
  322. /// <summary>
  323. /// Gets the list of Views that have <see cref="KeyBindingScope.Application"/> key bindings.
  324. /// </summary>
  325. /// <remarks>
  326. /// This is an internal method used by the <see cref="View"/> class to add Application key bindings.
  327. /// </remarks>
  328. /// <returns>The list of Views that have Application-scoped key bindings.</returns>
  329. internal static List<KeyBinding> GetViewKeyBindings ()
  330. {
  331. // Get the list of views that do not have Application-scoped key bindings
  332. return KeyBindings.Bindings
  333. .Where (kv => kv.Value.Scope != KeyBindingScope.Application)
  334. .Select (kv => kv.Value)
  335. .Distinct ()
  336. .ToList ();
  337. }
  338. /// <summary>
  339. /// <para>
  340. /// Sets the function that will be invoked for a <see cref="Command"/>.
  341. /// </para>
  342. /// <para>
  343. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  344. /// replace the old one.
  345. /// </para>
  346. /// </summary>
  347. /// <remarks>
  348. /// <para>
  349. /// This version of AddCommand is for commands that do not require a <see cref="CommandContext"/>.
  350. /// </para>
  351. /// </remarks>
  352. /// <param name="command">The command.</param>
  353. /// <param name="f">The function.</param>
  354. private static void AddCommand (Command command, Func<bool?> f) { CommandImplementations! [command] = ctx => f (); }
  355. /// <summary>
  356. /// Commands for Application.
  357. /// </summary>
  358. private static Dictionary<Command, Func<CommandContext, bool?>>? CommandImplementations { get; set; }
  359. private static void ReplaceKey (Key oldKey, Key newKey)
  360. {
  361. if (KeyBindings.Bindings.Count == 0)
  362. {
  363. return;
  364. }
  365. if (newKey == Key.Empty)
  366. {
  367. KeyBindings.Remove (oldKey);
  368. }
  369. else
  370. {
  371. KeyBindings.ReplaceKey (oldKey, newKey);
  372. }
  373. }
  374. }