Application.Keyboard.cs 16 KB

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