Application.Keyboard.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. #nullable enable
  2. using System.Text.Json.Serialization;
  3. namespace Terminal.Gui;
  4. public static partial class Application // Keyboard handling
  5. {
  6. private static Key _alternateForwardKey = Key.Empty; // Defined in config.json
  7. /// <summary>Alternative key to navigate forwards through views. Ctrl+Tab is the primary key.</summary>
  8. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  9. [JsonConverter (typeof (KeyJsonConverter))]
  10. public static Key AlternateForwardKey
  11. {
  12. get => _alternateForwardKey;
  13. set
  14. {
  15. if (_alternateForwardKey != value)
  16. {
  17. Key oldKey = _alternateForwardKey;
  18. _alternateForwardKey = value;
  19. OnAlternateForwardKeyChanged (new (oldKey, value));
  20. }
  21. }
  22. }
  23. private static void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  24. {
  25. // TODO: The fact Top has it's own AlternateForwardKey and events is needlessly complex. Remove it.
  26. foreach (Toplevel top in _topLevels.ToArray ())
  27. {
  28. top.OnAlternateForwardKeyChanged (e);
  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. OnAlternateBackwardKeyChanged (new (oldKey, value));
  45. }
  46. }
  47. }
  48. private static void OnAlternateBackwardKeyChanged (KeyChangedEventArgs oldKey)
  49. {
  50. // TODO: The fact Top has it's own AlternateBackwardKey and events is needlessly complex. Remove it.
  51. foreach (Toplevel top in _topLevels.ToArray ())
  52. {
  53. top.OnAlternateBackwardKeyChanged (oldKey);
  54. }
  55. }
  56. private static Key _quitKey = Key.Empty; // Defined in config.json
  57. /// <summary>Gets or sets the key to quit the application.</summary>
  58. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  59. [JsonConverter (typeof (KeyJsonConverter))]
  60. public static Key QuitKey
  61. {
  62. get => _quitKey;
  63. set
  64. {
  65. if (_quitKey != value)
  66. {
  67. Key oldKey = _quitKey;
  68. _quitKey = value;
  69. OnQuitKeyChanged (new (oldKey, value));
  70. }
  71. }
  72. }
  73. private static void OnQuitKeyChanged (KeyChangedEventArgs e)
  74. {
  75. // TODO: The fact Top has it's own QuitKey and events is needlessly complex. Remove it.
  76. // Duplicate the list so if it changes during enumeration we're safe
  77. foreach (Toplevel top in _topLevels.ToArray ())
  78. {
  79. top.OnQuitKeyChanged (e);
  80. }
  81. }
  82. /// <summary>
  83. /// Event fired when the user presses a key. Fired by <see cref="OnKeyDown"/>.
  84. /// <para>
  85. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  86. /// additional processing.
  87. /// </para>
  88. /// </summary>
  89. /// <remarks>
  90. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  91. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  92. /// <para>Fired after <see cref="KeyDown"/> and before <see cref="KeyUp"/>.</para>
  93. /// </remarks>
  94. public static event EventHandler<Key> KeyDown;
  95. /// <summary>
  96. /// Called by the <see cref="ConsoleDriver"/> when the user presses a key. Fires the <see cref="KeyDown"/> event
  97. /// then calls <see cref="View.NewKeyDownEvent"/> on all top level views. Called after <see cref="OnKeyDown"/> and
  98. /// before <see cref="OnKeyUp"/>.
  99. /// </summary>
  100. /// <remarks>Can be used to simulate key press events.</remarks>
  101. /// <param name="keyEvent"></param>
  102. /// <returns><see langword="true"/> if the key was handled.</returns>
  103. public static bool OnKeyDown (Key keyEvent)
  104. {
  105. if (!_initialized)
  106. {
  107. return true;
  108. }
  109. KeyDown?.Invoke (null, keyEvent);
  110. if (keyEvent.Handled)
  111. {
  112. return true;
  113. }
  114. foreach (Toplevel topLevel in _topLevels.ToList ())
  115. {
  116. if (topLevel.NewKeyDownEvent (keyEvent))
  117. {
  118. return true;
  119. }
  120. if (topLevel.Modal)
  121. {
  122. break;
  123. }
  124. }
  125. // Invoke any global (Application-scoped) KeyBindings.
  126. // The first view that handles the key will stop the loop.
  127. foreach (KeyValuePair<Key, List<View?>> binding in _keyBindings.Where (b => b.Key == keyEvent.KeyCode))
  128. {
  129. foreach (View view in binding.Value)
  130. {
  131. if (view is { }
  132. && view.KeyBindings.TryGet (binding.Key, KeyBindingScope.Focused | KeyBindingScope.HotKey | KeyBindingScope.Application, out KeyBinding kb))
  133. {
  134. //bool? handled = view.InvokeCommands (kb.Commands, binding.Key, kb);
  135. bool? handled = view?.OnInvokingKeyBindings (keyEvent, kb.Scope);
  136. if (handled != null && (bool)handled)
  137. {
  138. return true;
  139. }
  140. }
  141. }
  142. }
  143. return false;
  144. }
  145. /// <summary>
  146. /// Event fired when the user releases a key. Fired by <see cref="OnKeyUp"/>.
  147. /// <para>
  148. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  149. /// additional processing.
  150. /// </para>
  151. /// </summary>
  152. /// <remarks>
  153. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  154. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  155. /// <para>Fired after <see cref="KeyDown"/>.</para>
  156. /// </remarks>
  157. public static event EventHandler<Key> KeyUp;
  158. /// <summary>
  159. /// Called by the <see cref="ConsoleDriver"/> when the user releases a key. Fires the <see cref="KeyUp"/> event
  160. /// then calls <see cref="View.NewKeyUpEvent"/> on all top level views. Called after <see cref="OnKeyDown"/>.
  161. /// </summary>
  162. /// <remarks>Can be used to simulate key press events.</remarks>
  163. /// <param name="a"></param>
  164. /// <returns><see langword="true"/> if the key was handled.</returns>
  165. public static bool OnKeyUp (Key a)
  166. {
  167. if (!_initialized)
  168. {
  169. return true;
  170. }
  171. KeyUp?.Invoke (null, a);
  172. if (a.Handled)
  173. {
  174. return true;
  175. }
  176. foreach (Toplevel topLevel in _topLevels.ToList ())
  177. {
  178. if (topLevel.NewKeyUpEvent (a))
  179. {
  180. return true;
  181. }
  182. if (topLevel.Modal)
  183. {
  184. break;
  185. }
  186. }
  187. return false;
  188. }
  189. /// <summary>Gets the key bindings for this view.</summary>
  190. public static KeyBindings KeyBindings { get; internal set; } = new ();
  191. /// <summary>
  192. /// Commands for Application.
  193. /// </summary>
  194. private static Dictionary<Command, Func<CommandContext, bool?>> CommandImplementations { get; } = new ();
  195. /// <summary>
  196. /// <para>
  197. /// Sets the function that will be invoked for a <see cref="Command"/>.
  198. /// </para>
  199. /// <para>
  200. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  201. /// replace the old one.
  202. /// </para>
  203. /// </summary>
  204. /// <remarks>
  205. /// <para>
  206. /// This version of AddCommand is for commands that do not require a <see cref="CommandContext"/>.
  207. /// </para>
  208. /// </remarks>
  209. /// <param name="command">The command.</param>
  210. /// <param name="f">The function.</param>
  211. private static void AddCommand (Command command, Func<bool?> f)
  212. {
  213. CommandImplementations [command] = ctx => f ();
  214. }
  215. ///// <summary>
  216. ///// The <see cref="KeyBindingScope.Application"/> key bindings.
  217. ///// </summary>
  218. //private static readonly Dictionary<Key, List<View?>> _keyBindings = new ();
  219. ///// <summary>
  220. ///// Gets the list of <see cref="KeyBindingScope.Application"/> key bindings.
  221. ///// </summary>
  222. //public static Dictionary<Key, List<View?>> GetKeyBindings () { return _keyBindings; }
  223. ///// <summary>
  224. ///// Adds an <see cref="KeyBindingScope.Application"/> scoped key binding.
  225. ///// </summary>
  226. ///// <remarks>
  227. ///// This is an internal method used by the <see cref="View"/> class to add Application key bindings.
  228. ///// </remarks>
  229. ///// <param name="key">The key being bound.</param>
  230. ///// <param name="view">The view that is bound to the key. If <see langword="null"/>, <see cref="Application.Current"/> will be used.</param>
  231. //internal static void AddKeyBinding (Key key, View? view)
  232. //{
  233. // if (!_keyBindings.ContainsKey (key))
  234. // {
  235. // _keyBindings [key] = [];
  236. // }
  237. // _keyBindings [key].Add (view);
  238. //}
  239. internal static void AddApplicationKeyBindings ()
  240. {
  241. // Things this view knows how to do
  242. AddCommand (
  243. Command.QuitToplevel, // TODO: IRunnable: Rename to Command.Quit to make more generic.
  244. () =>
  245. {
  246. if (OverlappedTop is { })
  247. {
  248. RequestStop (Current);
  249. }
  250. else
  251. {
  252. Application.RequestStop ();
  253. }
  254. return true;
  255. }
  256. );
  257. AddCommand (
  258. Command.Suspend,
  259. () =>
  260. {
  261. Driver?.Suspend ();
  262. return true;
  263. }
  264. );
  265. AddCommand (
  266. Command.NextView, // TODO: Figure out how to move this to the View that is at the root of the view hierarchy (currently Application.Top)
  267. () =>
  268. {
  269. Current.MoveNextView ();
  270. return true;
  271. }
  272. );
  273. AddCommand (
  274. Command.PreviousView,// TODO: Figure out how to move this to the View that is at the root of the view hierarchy (currently Application.Top)
  275. () =>
  276. {
  277. Current.MovePreviousView ();
  278. return true;
  279. }
  280. );
  281. AddCommand (
  282. Command.NextViewOrTop,// TODO: Figure out how to move this to the View that is at the root of the view hierarchy (currently Application.Top)
  283. () =>
  284. {
  285. Current.MoveNextViewOrTop ();
  286. return true;
  287. }
  288. );
  289. AddCommand (
  290. Command.PreviousViewOrTop,// TODO: Figure out how to move this to the View that is at the root of the view hierarchy (currently Application.Top)
  291. () =>
  292. {
  293. Current.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, 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 an <see cref="KeyBindingScope.Application"/> scoped key binding.
  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="key">The key that was bound.</param>
  362. /// <param name="view">The view that is bound to the key.</param>
  363. internal static void RemoveKeyBinding (Key key, View view)
  364. {
  365. if (_keyBindings.TryGetValue (key, out List<View> views))
  366. {
  367. views.Remove (view);
  368. if (views.Count == 0)
  369. {
  370. _keyBindings.Remove (key);
  371. }
  372. }
  373. }
  374. /// <summary>
  375. /// Removes all <see cref="KeyBindingScope.Application"/> scoped key bindings for the specified view.
  376. /// </summary>
  377. /// <remarks>
  378. /// This is an internal method used by the <see cref="View"/> class to remove Application key bindings.
  379. /// </remarks>
  380. /// <param name="view">The view that is bound to the key.</param>
  381. internal static void ClearKeyBindings (View view)
  382. {
  383. foreach (Key key in _keyBindings.Keys)
  384. {
  385. _keyBindings [key].Remove (view);
  386. }
  387. }
  388. /// <summary>
  389. /// Removes all <see cref="KeyBindingScope.Application"/> scoped key bindings for the specified view.
  390. /// </summary>
  391. /// <remarks>
  392. /// This is an internal method used by the <see cref="View"/> class to remove Application key bindings.
  393. /// </remarks>
  394. internal static void ClearKeyBindings () { _keyBindings.Clear (); }
  395. }