Application.Keyboard.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. if (Current is null)
  112. {
  113. foreach (Toplevel topLevel in TopLevels.ToList ())
  114. {
  115. if (topLevel.NewKeyDownEvent (keyEvent))
  116. {
  117. return true;
  118. }
  119. if (topLevel.Modal)
  120. {
  121. break;
  122. }
  123. }
  124. }
  125. else
  126. {
  127. if (Application.Current.NewKeyDownEvent (keyEvent))
  128. {
  129. return true;
  130. }
  131. }
  132. // Invoke any Application-scoped KeyBindings.
  133. // The first view that handles the key will stop the loop.
  134. foreach (var binding in KeyBindings.Bindings.Where (b => b.Key == keyEvent.KeyCode))
  135. {
  136. if (binding.Value.BoundView is { })
  137. {
  138. bool? handled = binding.Value.BoundView?.InvokeCommands (binding.Value.Commands, binding.Key, binding.Value);
  139. if (handled != null && (bool)handled)
  140. {
  141. return true;
  142. }
  143. }
  144. else
  145. {
  146. if (!KeyBindings.TryGet (keyEvent, KeyBindingScope.Application, out KeyBinding appBinding))
  147. {
  148. continue;
  149. }
  150. bool? toReturn = null;
  151. foreach (Command command in appBinding.Commands)
  152. {
  153. if (!CommandImplementations.ContainsKey (command))
  154. {
  155. throw new NotSupportedException (
  156. @$"A KeyBinding was set up for the command {command} ({keyEvent}) but that command is not supported by Application."
  157. );
  158. }
  159. if (CommandImplementations.TryGetValue (command, out Func<CommandContext, bool?>? implementation))
  160. {
  161. var context = new CommandContext (command, keyEvent, appBinding); // Create the context here
  162. toReturn = implementation (context);
  163. }
  164. // if ever see a true then that's what we will return
  165. if (toReturn ?? false)
  166. {
  167. toReturn = true;
  168. }
  169. }
  170. return toReturn ?? true;
  171. }
  172. }
  173. return false;
  174. }
  175. /// <summary>
  176. /// Event fired when the user releases a key. Fired by <see cref="OnKeyUp"/>.
  177. /// <para>
  178. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  179. /// additional processing.
  180. /// </para>
  181. /// </summary>
  182. /// <remarks>
  183. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  184. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  185. /// <para>Fired after <see cref="KeyDown"/>.</para>
  186. /// </remarks>
  187. public static event EventHandler<Key>? KeyUp;
  188. /// <summary>
  189. /// Called by the <see cref="ConsoleDriver"/> when the user releases a key. Fires the <see cref="KeyUp"/> event
  190. /// then calls <see cref="View.NewKeyUpEvent"/> on all top level views. Called after <see cref="OnKeyDown"/>.
  191. /// </summary>
  192. /// <remarks>Can be used to simulate key press events.</remarks>
  193. /// <param name="a"></param>
  194. /// <returns><see langword="true"/> if the key was handled.</returns>
  195. public static bool OnKeyUp (Key a)
  196. {
  197. if (!IsInitialized)
  198. {
  199. return true;
  200. }
  201. KeyUp?.Invoke (null, a);
  202. if (a.Handled)
  203. {
  204. return true;
  205. }
  206. foreach (Toplevel topLevel in TopLevels.ToList ())
  207. {
  208. if (topLevel.NewKeyUpEvent (a))
  209. {
  210. return true;
  211. }
  212. if (topLevel.Modal)
  213. {
  214. break;
  215. }
  216. }
  217. return false;
  218. }
  219. /// <summary>Gets the key bindings for this view.</summary>
  220. public static KeyBindings KeyBindings { get; internal set; } = new ();
  221. /// <summary>
  222. /// Commands for Application.
  223. /// </summary>
  224. private static Dictionary<Command, Func<CommandContext, bool?>> CommandImplementations { get; set; }
  225. /// <summary>
  226. /// <para>
  227. /// Sets the function that will be invoked for a <see cref="Command"/>.
  228. /// </para>
  229. /// <para>
  230. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  231. /// replace the old one.
  232. /// </para>
  233. /// </summary>
  234. /// <remarks>
  235. /// <para>
  236. /// This version of AddCommand is for commands that do not require a <see cref="CommandContext"/>.
  237. /// </para>
  238. /// </remarks>
  239. /// <param name="command">The command.</param>
  240. /// <param name="f">The function.</param>
  241. private static void AddCommand (Command command, Func<bool?> f)
  242. {
  243. CommandImplementations [command] = ctx => f ();
  244. }
  245. static Application ()
  246. {
  247. AddApplicationKeyBindings();
  248. }
  249. internal static void AddApplicationKeyBindings ()
  250. {
  251. CommandImplementations = new Dictionary<Command, Func<CommandContext, bool?>> ();
  252. // Things this view knows how to do
  253. AddCommand (
  254. Command.QuitToplevel, // TODO: IRunnable: Rename to Command.Quit to make more generic.
  255. () =>
  256. {
  257. if (ApplicationOverlapped.OverlappedTop is { })
  258. {
  259. RequestStop (Current!);
  260. }
  261. else
  262. {
  263. Application.RequestStop ();
  264. }
  265. return true;
  266. }
  267. );
  268. AddCommand (
  269. Command.Suspend,
  270. () =>
  271. {
  272. Driver?.Suspend ();
  273. return true;
  274. }
  275. );
  276. AddCommand (
  277. Command.NextView,
  278. () =>
  279. {
  280. ApplicationNavigation.MoveNextView ();
  281. return true;
  282. }
  283. );
  284. AddCommand (
  285. Command.PreviousView,
  286. () =>
  287. {
  288. ApplicationNavigation.MovePreviousView ();
  289. return true;
  290. }
  291. );
  292. AddCommand (
  293. Command.NextViewOrTop,
  294. () =>
  295. {
  296. ApplicationNavigation.MoveNextViewOrTop ();
  297. return true;
  298. }
  299. );
  300. AddCommand (
  301. Command.PreviousViewOrTop,
  302. () =>
  303. {
  304. ApplicationNavigation.MovePreviousViewOrTop ();
  305. return true;
  306. }
  307. );
  308. AddCommand (
  309. Command.Refresh,
  310. () =>
  311. {
  312. Refresh ();
  313. return true;
  314. }
  315. );
  316. KeyBindings.Clear ();
  317. KeyBindings.Add (Application.QuitKey, KeyBindingScope.Application, Command.QuitToplevel);
  318. KeyBindings.Add (Key.CursorRight, KeyBindingScope.Application, Command.NextView);
  319. KeyBindings.Add (Key.CursorDown, KeyBindingScope.Application, Command.NextView);
  320. KeyBindings.Add (Key.CursorLeft, KeyBindingScope.Application, Command.PreviousView);
  321. KeyBindings.Add (Key.CursorUp, KeyBindingScope.Application, Command.PreviousView);
  322. KeyBindings.Add (Key.Tab, KeyBindingScope.Application, Command.NextView);
  323. KeyBindings.Add (Key.Tab.WithShift, KeyBindingScope.Application, Command.PreviousView);
  324. KeyBindings.Add (Key.Tab.WithCtrl, KeyBindingScope.Application, Command.NextViewOrTop);
  325. KeyBindings.Add (Key.Tab.WithShift.WithCtrl, KeyBindingScope.Application, Command.PreviousViewOrTop);
  326. // TODO: Refresh Key should be configurable
  327. KeyBindings.Add (Key.F5, KeyBindingScope.Application, Command.Refresh);
  328. KeyBindings.Add (Application.AlternateForwardKey, KeyBindingScope.Application, Command.NextViewOrTop); // Needed on Unix
  329. KeyBindings.Add (Application.AlternateBackwardKey, KeyBindingScope.Application, Command.PreviousViewOrTop); // Needed on Unix
  330. if (Environment.OSVersion.Platform == PlatformID.Unix)
  331. {
  332. KeyBindings.Add (Key.Z.WithCtrl, KeyBindingScope.Application, Command.Suspend);
  333. }
  334. #if UNIX_KEY_BINDINGS
  335. KeyBindings.Add (Key.L.WithCtrl, Command.Refresh); // Unix
  336. KeyBindings.Add (Key.F.WithCtrl, Command.NextView); // Unix
  337. KeyBindings.Add (Key.I.WithCtrl, Command.NextView); // Unix
  338. KeyBindings.Add (Key.B.WithCtrl, Command.PreviousView); // Unix
  339. #endif
  340. }
  341. /// <summary>
  342. /// Gets the list of Views that have <see cref="KeyBindingScope.Application"/> key bindings.
  343. /// </summary>
  344. /// <remarks>
  345. /// This is an internal method used by the <see cref="View"/> class to add Application key bindings.
  346. /// </remarks>
  347. /// <returns>The list of Views that have Application-scoped key bindings.</returns>
  348. internal static List<KeyBinding> GetViewKeyBindings ()
  349. {
  350. // Get the list of views that do not have Application-scoped key bindings
  351. return KeyBindings.Bindings
  352. .Where (kv => kv.Value.Scope != KeyBindingScope.Application)
  353. .Select (kv => kv.Value)
  354. .Distinct ()
  355. .ToList ();
  356. }
  357. ///// <summary>
  358. ///// Gets the list of Views that have <see cref="KeyBindingScope.Application"/> key bindings for the specified key.
  359. ///// </summary>
  360. ///// <remarks>
  361. ///// This is an internal method used by the <see cref="View"/> class to add Application key bindings.
  362. ///// </remarks>
  363. ///// <param name="key">The key to check.</param>
  364. ///// <param name="views">Outputs the list of views bound to <paramref name="key"/></param>
  365. ///// <returns><see langword="True"/> if successful.</returns>
  366. //internal static bool TryGetKeyBindings (Key key, out List<View> views) { return _keyBindings.TryGetValue (key, out views); }
  367. /// <summary>
  368. /// Removes all <see cref="KeyBindingScope.Application"/> scoped key bindings for the specified view.
  369. /// </summary>
  370. /// <remarks>
  371. /// This is an internal method used by the <see cref="View"/> class to remove Application key bindings.
  372. /// </remarks>
  373. /// <param name="view">The view that is bound to the key.</param>
  374. internal static void RemoveKeyBindings (View view)
  375. {
  376. var list = KeyBindings.Bindings
  377. .Where (kv => kv.Value.Scope != KeyBindingScope.Application)
  378. .Select (kv => kv.Value)
  379. .Distinct ()
  380. .ToList ();
  381. }
  382. }