Application.Keyboard.cs 15 KB

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