Application.Keyboard.cs 15 KB

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