Application.Keyboard.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. if (!CommandImplementations!.ContainsKey (command))
  129. {
  130. throw new NotSupportedException (
  131. @$"A KeyBinding was set up for the command {command} ({keyEvent}) but that command is not supported by Application."
  132. );
  133. }
  134. if (CommandImplementations.TryGetValue (command, out Func<CommandContext, bool?>? implementation))
  135. {
  136. var context = new CommandContext (command, keyEvent, appBinding); // Create the context here
  137. toReturn = implementation (context);
  138. }
  139. // if ever see a true then that's what we will return
  140. if (toReturn ?? false)
  141. {
  142. toReturn = true;
  143. }
  144. }
  145. return toReturn ?? true;
  146. }
  147. }
  148. return false;
  149. }
  150. /// <summary>
  151. /// Called by the <see cref="ConsoleDriver"/> when the user releases a key. Fires the <see cref="KeyUp"/> event
  152. /// then calls <see cref="View.NewKeyUpEvent"/> on all top level views. Called after <see cref="OnKeyDown"/>.
  153. /// </summary>
  154. /// <remarks>Can be used to simulate key press events.</remarks>
  155. /// <param name="a"></param>
  156. /// <returns><see langword="true"/> if the key was handled.</returns>
  157. public static bool OnKeyUp (Key a)
  158. {
  159. if (!IsInitialized)
  160. {
  161. return true;
  162. }
  163. KeyUp?.Invoke (null, a);
  164. if (a.Handled)
  165. {
  166. return true;
  167. }
  168. foreach (Toplevel topLevel in TopLevels.ToList ())
  169. {
  170. if (topLevel.NewKeyUpEvent (a))
  171. {
  172. return true;
  173. }
  174. if (topLevel.Modal)
  175. {
  176. break;
  177. }
  178. }
  179. return false;
  180. }
  181. /// <summary>Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.</summary>
  182. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  183. public static Key PrevTabGroupKey
  184. {
  185. get => _prevTabGroupKey;
  186. set
  187. {
  188. if (_prevTabGroupKey != value)
  189. {
  190. ReplaceKey (_prevTabGroupKey, value);
  191. _prevTabGroupKey = value;
  192. }
  193. }
  194. }
  195. /// <summary>Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.</summary>
  196. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  197. public static Key PrevTabKey
  198. {
  199. get => _prevTabKey;
  200. set
  201. {
  202. if (_prevTabKey != value)
  203. {
  204. ReplaceKey (_prevTabKey, value);
  205. _prevTabKey = value;
  206. }
  207. }
  208. }
  209. /// <summary>Gets or sets the key to quit the application.</summary>
  210. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  211. public static Key QuitKey
  212. {
  213. get => _quitKey;
  214. set
  215. {
  216. if (_quitKey != value)
  217. {
  218. ReplaceKey (_quitKey, value);
  219. _quitKey = value;
  220. }
  221. }
  222. }
  223. internal static void AddApplicationKeyBindings ()
  224. {
  225. CommandImplementations = new ();
  226. // Things this view knows how to do
  227. AddCommand (
  228. Command.QuitToplevel, // TODO: IRunnable: Rename to Command.Quit to make more generic.
  229. static () =>
  230. {
  231. if (ApplicationOverlapped.OverlappedTop is { })
  232. {
  233. RequestStop (Current!);
  234. }
  235. else
  236. {
  237. RequestStop ();
  238. }
  239. return true;
  240. }
  241. );
  242. AddCommand (
  243. Command.Suspend,
  244. static () =>
  245. {
  246. Driver?.Suspend ();
  247. return true;
  248. }
  249. );
  250. AddCommand (
  251. Command.NextView,
  252. static () => Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabStop));
  253. AddCommand (
  254. Command.PreviousView,
  255. static () => Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabStop));
  256. AddCommand (
  257. Command.NextViewOrTop,
  258. static () =>
  259. {
  260. // TODO: This OverlapppedTop tomfoolery goes away in addressing #2491
  261. if (ApplicationOverlapped.OverlappedTop is { })
  262. {
  263. ApplicationOverlapped.OverlappedMoveNext ();
  264. return true;
  265. }
  266. return Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabGroup);
  267. }
  268. );
  269. AddCommand (
  270. Command.PreviousViewOrTop,
  271. static () =>
  272. {
  273. // TODO: This OverlapppedTop tomfoolery goes away in addressing #2491
  274. if (ApplicationOverlapped.OverlappedTop is { })
  275. {
  276. ApplicationOverlapped.OverlappedMovePrevious ();
  277. return true;
  278. }
  279. return Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabGroup);
  280. }
  281. );
  282. AddCommand (
  283. Command.Refresh,
  284. static () =>
  285. {
  286. Refresh ();
  287. return true;
  288. }
  289. );
  290. KeyBindings.Clear ();
  291. // Resources/config.json overrrides
  292. NextTabKey = Key.Tab;
  293. PrevTabKey = Key.Tab.WithShift;
  294. NextTabGroupKey = Key.F6;
  295. PrevTabGroupKey = Key.F6.WithShift;
  296. QuitKey = Key.Esc;
  297. KeyBindings.Add (QuitKey, KeyBindingScope.Application, Command.QuitToplevel);
  298. KeyBindings.Add (Key.CursorRight, KeyBindingScope.Application, Command.NextView);
  299. KeyBindings.Add (Key.CursorDown, KeyBindingScope.Application, Command.NextView);
  300. KeyBindings.Add (Key.CursorLeft, KeyBindingScope.Application, Command.PreviousView);
  301. KeyBindings.Add (Key.CursorUp, KeyBindingScope.Application, Command.PreviousView);
  302. KeyBindings.Add (NextTabKey, KeyBindingScope.Application, Command.NextView);
  303. KeyBindings.Add (PrevTabKey, KeyBindingScope.Application, Command.PreviousView);
  304. KeyBindings.Add (NextTabGroupKey, KeyBindingScope.Application, Command.NextViewOrTop);
  305. KeyBindings.Add (PrevTabGroupKey, KeyBindingScope.Application, Command.PreviousViewOrTop);
  306. // TODO: Refresh Key should be configurable
  307. KeyBindings.Add (Key.F5, KeyBindingScope.Application, Command.Refresh);
  308. // TODO: Suspend Key should be configurable
  309. if (Environment.OSVersion.Platform == PlatformID.Unix)
  310. {
  311. KeyBindings.Add (Key.Z.WithCtrl, KeyBindingScope.Application, Command.Suspend);
  312. }
  313. #if UNIX_KEY_BINDINGS
  314. KeyBindings.Add (Key.L.WithCtrl, Command.Refresh); // Unix
  315. KeyBindings.Add (Key.F.WithCtrl, Command.NextView); // Unix
  316. KeyBindings.Add (Key.I.WithCtrl, Command.NextView); // Unix
  317. KeyBindings.Add (Key.B.WithCtrl, Command.PreviousView); // Unix
  318. #endif
  319. }
  320. /// <summary>
  321. /// Gets the list of Views that have <see cref="KeyBindingScope.Application"/> key bindings.
  322. /// </summary>
  323. /// <remarks>
  324. /// This is an internal method used by the <see cref="View"/> class to add Application key bindings.
  325. /// </remarks>
  326. /// <returns>The list of Views that have Application-scoped key bindings.</returns>
  327. internal static List<KeyBinding> GetViewKeyBindings ()
  328. {
  329. // Get the list of views that do not have Application-scoped key bindings
  330. return KeyBindings.Bindings
  331. .Where (kv => kv.Value.Scope != KeyBindingScope.Application)
  332. .Select (kv => kv.Value)
  333. .Distinct ()
  334. .ToList ();
  335. }
  336. /// <summary>
  337. /// <para>
  338. /// Sets the function that will be invoked for a <see cref="Command"/>.
  339. /// </para>
  340. /// <para>
  341. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  342. /// replace the old one.
  343. /// </para>
  344. /// </summary>
  345. /// <remarks>
  346. /// <para>
  347. /// This version of AddCommand is for commands that do not require a <see cref="CommandContext"/>.
  348. /// </para>
  349. /// </remarks>
  350. /// <param name="command">The command.</param>
  351. /// <param name="f">The function.</param>
  352. private static void AddCommand (Command command, Func<bool?> f) { CommandImplementations! [command] = ctx => f (); }
  353. /// <summary>
  354. /// Commands for Application.
  355. /// </summary>
  356. private static Dictionary<Command, Func<CommandContext, bool?>>? CommandImplementations { get; set; }
  357. private static void ReplaceKey (Key oldKey, Key newKey)
  358. {
  359. if (KeyBindings.Bindings.Count == 0)
  360. {
  361. return;
  362. }
  363. if (newKey == Key.Empty)
  364. {
  365. KeyBindings.Remove (oldKey);
  366. }
  367. else
  368. {
  369. KeyBindings.ReplaceKey (oldKey, newKey);
  370. }
  371. }
  372. }