Application.Keyboard.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 () => Current?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabStop));
  253. AddCommand (
  254. Command.PreviousView,
  255. static () => Current?.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 null)
  262. {
  263. if ((View?)Current is { })
  264. {
  265. return Current.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabGroup);
  266. }
  267. }
  268. else
  269. {
  270. ApplicationOverlapped.OverlappedMoveNext ();
  271. return true;
  272. }
  273. return false;
  274. }
  275. );
  276. AddCommand (
  277. Command.PreviousViewOrTop,
  278. static () =>
  279. {
  280. // TODO: This OverlapppedTop tomfoolery goes away in addressing #2491
  281. if (ApplicationOverlapped.OverlappedTop is null)
  282. {
  283. if ((View?)Current is { })
  284. {
  285. return Current.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabGroup);
  286. }
  287. }
  288. else
  289. {
  290. ApplicationOverlapped.OverlappedMovePrevious ();
  291. return true;
  292. }
  293. return false;
  294. }
  295. );
  296. AddCommand (
  297. Command.Refresh,
  298. static () =>
  299. {
  300. Refresh ();
  301. return true;
  302. }
  303. );
  304. KeyBindings.Clear ();
  305. // Resources/config.json overrrides
  306. NextTabKey = Key.Tab;
  307. PrevTabKey = Key.Tab.WithShift;
  308. NextTabGroupKey = Key.F6;
  309. PrevTabGroupKey = Key.F6.WithShift;
  310. QuitKey = Key.Esc;
  311. KeyBindings.Add (QuitKey, KeyBindingScope.Application, Command.QuitToplevel);
  312. KeyBindings.Add (Key.CursorRight, KeyBindingScope.Application, Command.NextView);
  313. KeyBindings.Add (Key.CursorDown, KeyBindingScope.Application, Command.NextView);
  314. KeyBindings.Add (Key.CursorLeft, KeyBindingScope.Application, Command.PreviousView);
  315. KeyBindings.Add (Key.CursorUp, KeyBindingScope.Application, Command.PreviousView);
  316. KeyBindings.Add (NextTabKey, KeyBindingScope.Application, Command.NextView);
  317. KeyBindings.Add (PrevTabKey, KeyBindingScope.Application, Command.PreviousView);
  318. KeyBindings.Add (NextTabGroupKey, KeyBindingScope.Application, Command.NextViewOrTop); // Needed on Unix
  319. KeyBindings.Add (PrevTabGroupKey, KeyBindingScope.Application, Command.PreviousViewOrTop); // Needed on Unix
  320. // TODO: Refresh Key should be configurable
  321. KeyBindings.Add (Key.F5, KeyBindingScope.Application, Command.Refresh);
  322. // TODO: Suspend Key should be configurable
  323. if (Environment.OSVersion.Platform == PlatformID.Unix)
  324. {
  325. KeyBindings.Add (Key.Z.WithCtrl, KeyBindingScope.Application, Command.Suspend);
  326. }
  327. #if UNIX_KEY_BINDINGS
  328. KeyBindings.Add (Key.L.WithCtrl, Command.Refresh); // Unix
  329. KeyBindings.Add (Key.F.WithCtrl, Command.NextView); // Unix
  330. KeyBindings.Add (Key.I.WithCtrl, Command.NextView); // Unix
  331. KeyBindings.Add (Key.B.WithCtrl, Command.PreviousView); // Unix
  332. #endif
  333. }
  334. /// <summary>
  335. /// Gets the list of Views that have <see cref="KeyBindingScope.Application"/> key bindings.
  336. /// </summary>
  337. /// <remarks>
  338. /// This is an internal method used by the <see cref="View"/> class to add Application key bindings.
  339. /// </remarks>
  340. /// <returns>The list of Views that have Application-scoped key bindings.</returns>
  341. internal static List<KeyBinding> GetViewKeyBindings ()
  342. {
  343. // Get the list of views that do not have Application-scoped key bindings
  344. return KeyBindings.Bindings
  345. .Where (kv => kv.Value.Scope != KeyBindingScope.Application)
  346. .Select (kv => kv.Value)
  347. .Distinct ()
  348. .ToList ();
  349. }
  350. /// <summary>
  351. /// <para>
  352. /// Sets the function that will be invoked for a <see cref="Command"/>.
  353. /// </para>
  354. /// <para>
  355. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  356. /// replace the old one.
  357. /// </para>
  358. /// </summary>
  359. /// <remarks>
  360. /// <para>
  361. /// This version of AddCommand is for commands that do not require a <see cref="CommandContext"/>.
  362. /// </para>
  363. /// </remarks>
  364. /// <param name="command">The command.</param>
  365. /// <param name="f">The function.</param>
  366. private static void AddCommand (Command command, Func<bool?> f) { CommandImplementations! [command] = ctx => f (); }
  367. /// <summary>
  368. /// Commands for Application.
  369. /// </summary>
  370. private static Dictionary<Command, Func<CommandContext, bool?>>? CommandImplementations { get; set; }
  371. private static void ReplaceKey (Key oldKey, Key newKey)
  372. {
  373. if (KeyBindings.Bindings.Count == 0)
  374. {
  375. return;
  376. }
  377. if (newKey == Key.Empty)
  378. {
  379. KeyBindings.Remove (oldKey);
  380. }
  381. else
  382. {
  383. KeyBindings.ReplaceKey (oldKey, newKey);
  384. }
  385. }
  386. }