Application.Keyboard.cs 17 KB

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