2
0

Application.Keyboard.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. ApplicationNavigation.MoveNextView ();
  266. return true;
  267. }
  268. );
  269. AddCommand (
  270. Command.PreviousView,
  271. () =>
  272. {
  273. ApplicationNavigation.MovePreviousView ();
  274. return true;
  275. }
  276. );
  277. AddCommand (
  278. Command.NextViewOrTop,
  279. () =>
  280. {
  281. ApplicationNavigation.MoveNextViewOrTop ();
  282. return true;
  283. }
  284. );
  285. AddCommand (
  286. Command.PreviousViewOrTop,
  287. () =>
  288. {
  289. ApplicationNavigation.MovePreviousViewOrTop ();
  290. return true;
  291. }
  292. );
  293. AddCommand (
  294. Command.Refresh,
  295. () =>
  296. {
  297. Refresh ();
  298. return true;
  299. }
  300. );
  301. KeyBindings.Add (Application.QuitKey, KeyBindingScope.Application, Command.QuitToplevel);
  302. KeyBindings.Add (Key.CursorRight, KeyBindingScope.Application, Command.NextView);
  303. KeyBindings.Add (Key.CursorDown, KeyBindingScope.Application, Command.NextView);
  304. KeyBindings.Add (Key.CursorLeft, KeyBindingScope.Application, Command.PreviousView);
  305. KeyBindings.Add (Key.CursorUp, KeyBindingScope.Application, Command.PreviousView);
  306. KeyBindings.Add (Key.Tab, KeyBindingScope.Application, Command.NextView);
  307. KeyBindings.Add (Key.Tab.WithShift, KeyBindingScope.Application, Command.PreviousView);
  308. KeyBindings.Add (Key.Tab.WithCtrl, KeyBindingScope.Application, Command.NextViewOrTop);
  309. KeyBindings.Add (Key.Tab.WithShift.WithCtrl, KeyBindingScope.Application, Command.PreviousViewOrTop);
  310. // TODO: Refresh Key should be configurable
  311. KeyBindings.Add (Key.F5, KeyBindingScope.Application, Command.Refresh);
  312. KeyBindings.Add (Application.AlternateForwardKey, KeyBindingScope.Application, Command.NextViewOrTop); // Needed on Unix
  313. KeyBindings.Add (Application.AlternateBackwardKey, KeyBindingScope.Application, Command.PreviousViewOrTop); // Needed on Unix
  314. if (Environment.OSVersion.Platform == PlatformID.Unix)
  315. {
  316. KeyBindings.Add (Key.Z.WithCtrl, KeyBindingScope.Application, Command.Suspend);
  317. }
  318. #if UNIX_KEY_BINDINGS
  319. KeyBindings.Add (Key.L.WithCtrl, Command.Refresh); // Unix
  320. KeyBindings.Add (Key.F.WithCtrl, Command.NextView); // Unix
  321. KeyBindings.Add (Key.I.WithCtrl, Command.NextView); // Unix
  322. KeyBindings.Add (Key.B.WithCtrl, Command.PreviousView); // Unix
  323. #endif
  324. }
  325. /// <summary>
  326. /// Gets the list of Views that have <see cref="KeyBindingScope.Application"/> key bindings.
  327. /// </summary>
  328. /// <remarks>
  329. /// This is an internal method used by the <see cref="View"/> class to add Application key bindings.
  330. /// </remarks>
  331. /// <returns>The list of Views that have Application-scoped key bindings.</returns>
  332. internal static List<KeyBinding> GetViewKeyBindings ()
  333. {
  334. // Get the list of views that do not have Application-scoped key bindings
  335. return KeyBindings.Bindings
  336. .Where (kv => kv.Value.Scope != KeyBindingScope.Application)
  337. .Select (kv => kv.Value)
  338. .Distinct ()
  339. .ToList ();
  340. }
  341. ///// <summary>
  342. ///// Gets the list of Views that have <see cref="KeyBindingScope.Application"/> key bindings for the specified key.
  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. ///// <param name="key">The key to check.</param>
  348. ///// <param name="views">Outputs the list of views bound to <paramref name="key"/></param>
  349. ///// <returns><see langword="True"/> if successful.</returns>
  350. //internal static bool TryGetKeyBindings (Key key, out List<View> views) { return _keyBindings.TryGetValue (key, out views); }
  351. /// <summary>
  352. /// Removes all <see cref="KeyBindingScope.Application"/> scoped key bindings for the specified view.
  353. /// </summary>
  354. /// <remarks>
  355. /// This is an internal method used by the <see cref="View"/> class to remove Application key bindings.
  356. /// </remarks>
  357. /// <param name="view">The view that is bound to the key.</param>
  358. internal static void RemoveKeyBindings (View view)
  359. {
  360. var list = KeyBindings.Bindings
  361. .Where (kv => kv.Value.Scope != KeyBindingScope.Application)
  362. .Select (kv => kv.Value)
  363. .Distinct ()
  364. .ToList ();
  365. }
  366. }