Application.Keyboard.cs 17 KB

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