Application.Keyboard.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. ///// <summary>
  236. ///// The <see cref="KeyBindingScope.Application"/> key bindings.
  237. ///// </summary>
  238. //private static readonly Dictionary<Key, List<View?>> _keyBindings = new ();
  239. ///// <summary>
  240. ///// Gets the list of <see cref="KeyBindingScope.Application"/> key bindings.
  241. ///// </summary>
  242. //public static Dictionary<Key, List<View?>> GetKeyBindings () { return _keyBindings; }
  243. ///// <summary>
  244. ///// Adds an <see cref="KeyBindingScope.Application"/> scoped key binding.
  245. ///// </summary>
  246. ///// <remarks>
  247. ///// This is an internal method used by the <see cref="View"/> class to add Application key bindings.
  248. ///// </remarks>
  249. ///// <param name="key">The key being bound.</param>
  250. ///// <param name="view">The view that is bound to the key. If <see langword="null"/>, <see cref="Application.Current"/> will be used.</param>
  251. //internal static void AddKeyBinding (Key key, View? view)
  252. //{
  253. // if (!_keyBindings.ContainsKey (key))
  254. // {
  255. // _keyBindings [key] = [];
  256. // }
  257. // _keyBindings [key].Add (view);
  258. //}
  259. internal static void AddApplicationKeyBindings ()
  260. {
  261. // Things this view knows how to do
  262. AddCommand (
  263. Command.QuitToplevel, // TODO: IRunnable: Rename to Command.Quit to make more generic.
  264. () =>
  265. {
  266. if (OverlappedTop is { })
  267. {
  268. RequestStop (Current!);
  269. }
  270. else
  271. {
  272. Application.RequestStop ();
  273. }
  274. return true;
  275. }
  276. );
  277. AddCommand (
  278. Command.Suspend,
  279. () =>
  280. {
  281. Driver?.Suspend ();
  282. return true;
  283. }
  284. );
  285. AddCommand (
  286. Command.NextView,
  287. () =>
  288. {
  289. // TODO: Move this method to Application.Navigation.cs
  290. ViewNavigation.MoveNextView ();
  291. return true;
  292. }
  293. );
  294. AddCommand (
  295. Command.PreviousView,
  296. () =>
  297. {
  298. // TODO: Move this method to Application.Navigation.cs
  299. ViewNavigation.MovePreviousView ();
  300. return true;
  301. }
  302. );
  303. AddCommand (
  304. Command.NextViewOrTop,
  305. () =>
  306. {
  307. // TODO: Move this method to Application.Navigation.cs
  308. ViewNavigation.MoveNextViewOrTop ();
  309. return true;
  310. }
  311. );
  312. AddCommand (
  313. Command.PreviousViewOrTop,
  314. () =>
  315. {
  316. // TODO: Move this method to Application.Navigation.cs
  317. ViewNavigation.MovePreviousViewOrTop ();
  318. return true;
  319. }
  320. );
  321. AddCommand (
  322. Command.Refresh,
  323. () =>
  324. {
  325. Refresh ();
  326. return true;
  327. }
  328. );
  329. KeyBindings.Add (Application.QuitKey, KeyBindingScope.Application, Command.QuitToplevel);
  330. KeyBindings.Add (Key.CursorRight, KeyBindingScope.Application, Command.NextView);
  331. KeyBindings.Add (Key.CursorDown, KeyBindingScope.Application, Command.NextView);
  332. KeyBindings.Add (Key.CursorLeft, KeyBindingScope.Application, Command.PreviousView);
  333. KeyBindings.Add (Key.CursorUp, KeyBindingScope.Application, Command.PreviousView);
  334. KeyBindings.Add (Key.Tab, KeyBindingScope.Application, Command.NextView);
  335. KeyBindings.Add (Key.Tab.WithShift, KeyBindingScope.Application, Command.PreviousView);
  336. KeyBindings.Add (Key.Tab.WithCtrl, KeyBindingScope.Application, Command.NextViewOrTop);
  337. KeyBindings.Add (Key.Tab.WithShift.WithCtrl, KeyBindingScope.Application, Command.PreviousViewOrTop);
  338. // TODO: Refresh Key should be configurable
  339. KeyBindings.Add (Key.F5, KeyBindingScope.Application, Command.Refresh);
  340. KeyBindings.Add (Application.AlternateForwardKey, KeyBindingScope.Application, Command.NextViewOrTop); // Needed on Unix
  341. KeyBindings.Add (Application.AlternateBackwardKey, KeyBindingScope.Application, Command.PreviousViewOrTop); // Needed on Unix
  342. if (Environment.OSVersion.Platform == PlatformID.Unix)
  343. {
  344. KeyBindings.Add (Key.Z.WithCtrl, KeyBindingScope.Application, Command.Suspend);
  345. }
  346. #if UNIX_KEY_BINDINGS
  347. KeyBindings.Add (Key.L.WithCtrl, Command.Refresh); // Unix
  348. KeyBindings.Add (Key.F.WithCtrl, Command.NextView); // Unix
  349. KeyBindings.Add (Key.I.WithCtrl, Command.NextView); // Unix
  350. KeyBindings.Add (Key.B.WithCtrl, Command.PreviousView); // Unix
  351. #endif
  352. }
  353. /// <summary>
  354. /// Gets the list of Views that have <see cref="KeyBindingScope.Application"/> key bindings.
  355. /// </summary>
  356. /// <remarks>
  357. /// This is an internal method used by the <see cref="View"/> class to add Application key bindings.
  358. /// </remarks>
  359. /// <returns>The list of Views that have Application-scoped key bindings.</returns>
  360. internal static List<KeyBinding> GetViewKeyBindings ()
  361. {
  362. // Get the list of views that do not have Application-scoped key bindings
  363. return KeyBindings.Bindings
  364. .Where (kv => kv.Value.Scope != KeyBindingScope.Application)
  365. .Select (kv => kv.Value)
  366. .Distinct ()
  367. .ToList ();
  368. }
  369. ///// <summary>
  370. ///// Gets the list of Views that have <see cref="KeyBindingScope.Application"/> key bindings for the specified key.
  371. ///// </summary>
  372. ///// <remarks>
  373. ///// This is an internal method used by the <see cref="View"/> class to add Application key bindings.
  374. ///// </remarks>
  375. ///// <param name="key">The key to check.</param>
  376. ///// <param name="views">Outputs the list of views bound to <paramref name="key"/></param>
  377. ///// <returns><see langword="True"/> if successful.</returns>
  378. //internal static bool TryGetKeyBindings (Key key, out List<View> views) { return _keyBindings.TryGetValue (key, out views); }
  379. /// <summary>
  380. /// Removes all <see cref="KeyBindingScope.Application"/> scoped key bindings for the specified view.
  381. /// </summary>
  382. /// <remarks>
  383. /// This is an internal method used by the <see cref="View"/> class to remove Application key bindings.
  384. /// </remarks>
  385. /// <param name="view">The view that is bound to the key.</param>
  386. internal static void RemoveKeyBindings (View view)
  387. {
  388. var list = KeyBindings.Bindings
  389. .Where (kv => kv.Value.Scope != KeyBindingScope.Application)
  390. .Select (kv => kv.Value)
  391. .Distinct ()
  392. .ToList ();
  393. }
  394. }