KeyboardImpl.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. namespace Terminal.Gui.App;
  2. /// <summary>
  3. /// INTERNAL: Implements <see cref="IKeyboard"/> to manage keyboard input and key bindings at the Application level.
  4. /// <para>
  5. /// This implementation decouples keyboard handling state from the static <see cref="App"/> class,
  6. /// enabling parallelizable unit tests and better testability.
  7. /// </para>
  8. /// <para>
  9. /// See <see cref="IKeyboard"/> for usage details.
  10. /// </para>
  11. /// </summary>
  12. internal class KeyboardImpl : IKeyboard
  13. {
  14. private Key _quitKey = Key.Esc; // Resources/config.json overrides
  15. private Key _arrangeKey = Key.F5.WithCtrl; // Resources/config.json overrides
  16. private Key _nextTabGroupKey = Key.F6; // Resources/config.json overrides
  17. private Key _nextTabKey = Key.Tab; // Resources/config.json overrides
  18. private Key _prevTabGroupKey = Key.F6.WithShift; // Resources/config.json overrides
  19. private Key _prevTabKey = Key.Tab.WithShift; // Resources/config.json overrides
  20. /// <summary>
  21. /// Commands for Application.
  22. /// </summary>
  23. private readonly Dictionary<Command, View.CommandImplementation> _commandImplementations = new ();
  24. /// <inheritdoc/>
  25. public IApplication? App { get; set; }
  26. /// <inheritdoc/>
  27. public KeyBindings KeyBindings { get; internal set; } = new (null);
  28. /// <inheritdoc/>
  29. public Key QuitKey
  30. {
  31. get => _quitKey;
  32. set
  33. {
  34. KeyBindings.Replace (_quitKey, value);
  35. _quitKey = value;
  36. }
  37. }
  38. /// <inheritdoc/>
  39. public Key ArrangeKey
  40. {
  41. get => _arrangeKey;
  42. set
  43. {
  44. KeyBindings.Replace (_arrangeKey, value);
  45. _arrangeKey = value;
  46. }
  47. }
  48. /// <inheritdoc/>
  49. public Key NextTabGroupKey
  50. {
  51. get => _nextTabGroupKey;
  52. set
  53. {
  54. KeyBindings.Replace (_nextTabGroupKey, value);
  55. _nextTabGroupKey = value;
  56. }
  57. }
  58. /// <inheritdoc/>
  59. public Key NextTabKey
  60. {
  61. get => _nextTabKey;
  62. set
  63. {
  64. KeyBindings.Replace (_nextTabKey, value);
  65. _nextTabKey = value;
  66. }
  67. }
  68. /// <inheritdoc/>
  69. public Key PrevTabGroupKey
  70. {
  71. get => _prevTabGroupKey;
  72. set
  73. {
  74. KeyBindings.Replace (_prevTabGroupKey, value);
  75. _prevTabGroupKey = value;
  76. }
  77. }
  78. /// <inheritdoc/>
  79. public Key PrevTabKey
  80. {
  81. get => _prevTabKey;
  82. set
  83. {
  84. KeyBindings.Replace (_prevTabKey, value);
  85. _prevTabKey = value;
  86. }
  87. }
  88. /// <inheritdoc/>
  89. public event EventHandler<Key>? KeyDown;
  90. /// <inheritdoc/>
  91. public event EventHandler<Key>? KeyUp;
  92. /// <summary>
  93. /// Initializes keyboard bindings.
  94. /// </summary>
  95. public KeyboardImpl ()
  96. {
  97. AddKeyBindings ();
  98. }
  99. /// <inheritdoc/>
  100. public bool RaiseKeyDownEvent (Key key)
  101. {
  102. //ebug.Assert (App.Application.MainThreadId == Thread.CurrentThread.ManagedThreadId);
  103. //Logging.Debug ($"{key}");
  104. // TODO: Add a way to ignore certain keys, esp for debugging.
  105. //#if DEBUG
  106. // if (key == Key.Empty.WithAlt || key == Key.Empty.WithCtrl)
  107. // {
  108. // Logging.Debug ($"Ignoring {key}");
  109. // return false;
  110. // }
  111. //#endif
  112. // TODO: This should match standard event patterns
  113. KeyDown?.Invoke (null, key);
  114. if (key.Handled)
  115. {
  116. return true;
  117. }
  118. if (App?.Popover?.DispatchKeyDown (key) is true)
  119. {
  120. return true;
  121. }
  122. if (App?.Current is null)
  123. {
  124. if (App?.SessionStack is { })
  125. {
  126. foreach (Toplevel topLevel in App.SessionStack.ToList ())
  127. {
  128. if (topLevel.NewKeyDownEvent (key))
  129. {
  130. return true;
  131. }
  132. if (topLevel.Modal)
  133. {
  134. break;
  135. }
  136. }
  137. }
  138. }
  139. else
  140. {
  141. if (App.Current.NewKeyDownEvent (key))
  142. {
  143. return true;
  144. }
  145. }
  146. bool? commandHandled = InvokeCommandsBoundToKey (key);
  147. if(commandHandled is true)
  148. {
  149. return true;
  150. }
  151. return false;
  152. }
  153. /// <inheritdoc/>
  154. public bool RaiseKeyUpEvent (Key key)
  155. {
  156. if (App?.Initialized != true)
  157. {
  158. return true;
  159. }
  160. KeyUp?.Invoke (null, key);
  161. if (key.Handled)
  162. {
  163. return true;
  164. }
  165. // TODO: Add Popover support
  166. if (App?.SessionStack is { })
  167. {
  168. foreach (Toplevel topLevel in App.SessionStack.ToList ())
  169. {
  170. if (topLevel.NewKeyUpEvent (key))
  171. {
  172. return true;
  173. }
  174. if (topLevel.Modal)
  175. {
  176. break;
  177. }
  178. }
  179. }
  180. return false;
  181. }
  182. /// <inheritdoc/>
  183. public bool? InvokeCommandsBoundToKey (Key key)
  184. {
  185. bool? handled = null;
  186. // Invoke any Application-scoped KeyBindings.
  187. // The first view that handles the key will stop the loop.
  188. // foreach (KeyValuePair<Key, KeyBinding> binding in KeyBindings.GetBindings (key))
  189. if (KeyBindings.TryGet (key, out KeyBinding binding))
  190. {
  191. if (binding.Target is { })
  192. {
  193. if (!binding.Target.Enabled)
  194. {
  195. return null;
  196. }
  197. handled = binding.Target?.InvokeCommands (binding.Commands, binding);
  198. }
  199. else
  200. {
  201. bool? toReturn = null;
  202. foreach (Command command in binding.Commands)
  203. {
  204. toReturn = InvokeCommand (command, key, binding);
  205. }
  206. handled = toReturn ?? true;
  207. }
  208. }
  209. return handled;
  210. }
  211. /// <inheritdoc/>
  212. public bool? InvokeCommand (Command command, Key key, KeyBinding binding)
  213. {
  214. if (!_commandImplementations.ContainsKey (command))
  215. {
  216. throw new NotSupportedException (
  217. @$"A KeyBinding was set up for the command {command} ({key}) but that command is not supported by Application."
  218. );
  219. }
  220. if (_commandImplementations.TryGetValue (command, out View.CommandImplementation? implementation))
  221. {
  222. CommandContext<KeyBinding> context = new (command, null, binding); // Create the context here
  223. return implementation (context);
  224. }
  225. return null;
  226. }
  227. /// <summary>
  228. /// <para>
  229. /// Sets the function that will be invoked for a <see cref="Command"/>.
  230. /// </para>
  231. /// <para>
  232. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  233. /// replace the old one.
  234. /// </para>
  235. /// </summary>
  236. /// <remarks>
  237. /// <para>
  238. /// This version of AddCommand is for commands that do not require a <see cref="ICommandContext"/>.
  239. /// </para>
  240. /// </remarks>
  241. /// <param name="command">The command.</param>
  242. /// <param name="f">The function.</param>
  243. private void AddCommand (Command command, Func<bool?> f) { _commandImplementations [command] = ctx => f (); }
  244. internal void AddKeyBindings ()
  245. {
  246. _commandImplementations.Clear ();
  247. // Things Application knows how to do
  248. AddCommand (
  249. Command.Quit,
  250. () =>
  251. {
  252. App?.RequestStop ();
  253. return true;
  254. }
  255. );
  256. AddCommand (
  257. Command.Suspend,
  258. () =>
  259. {
  260. App?.Driver?.Suspend ();
  261. return true;
  262. }
  263. );
  264. AddCommand (
  265. Command.NextTabStop,
  266. () => App?.Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabStop));
  267. AddCommand (
  268. Command.PreviousTabStop,
  269. () => App?.Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabStop));
  270. AddCommand (
  271. Command.NextTabGroup,
  272. () => App?.Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabGroup));
  273. AddCommand (
  274. Command.PreviousTabGroup,
  275. () => App?.Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabGroup));
  276. AddCommand (
  277. Command.Refresh,
  278. () =>
  279. {
  280. App?.LayoutAndDraw (true);
  281. return true;
  282. }
  283. );
  284. AddCommand (
  285. Command.Arrange,
  286. () =>
  287. {
  288. View? viewToArrange = App?.Navigation?.GetFocused ();
  289. // Go up the superview hierarchy and find the first that is not ViewArrangement.Fixed
  290. while (viewToArrange is { SuperView: { }, Arrangement: ViewArrangement.Fixed })
  291. {
  292. viewToArrange = viewToArrange.SuperView;
  293. }
  294. if (viewToArrange is { })
  295. {
  296. return viewToArrange.Border?.EnterArrangeMode (ViewArrangement.Fixed);
  297. }
  298. return false;
  299. });
  300. //SetKeysToHardCodedDefaults ();
  301. // Need to clear after setting the above to ensure actually clear
  302. // because set_QuitKey etc.. may call Add
  303. KeyBindings.Clear ();
  304. KeyBindings.Add (QuitKey, Command.Quit);
  305. KeyBindings.Add (NextTabKey, Command.NextTabStop);
  306. KeyBindings.Add (PrevTabKey, Command.PreviousTabStop);
  307. KeyBindings.Add (NextTabGroupKey, Command.NextTabGroup);
  308. KeyBindings.Add (PrevTabGroupKey, Command.PreviousTabGroup);
  309. KeyBindings.Add (ArrangeKey, Command.Arrange);
  310. KeyBindings.Add (Key.CursorRight, Command.NextTabStop);
  311. KeyBindings.Add (Key.CursorDown, Command.NextTabStop);
  312. KeyBindings.Add (Key.CursorLeft, Command.PreviousTabStop);
  313. KeyBindings.Add (Key.CursorUp, Command.PreviousTabStop);
  314. // TODO: Refresh Key should be configurable
  315. KeyBindings.Add (Key.F5, Command.Refresh);
  316. // TODO: Suspend Key should be configurable
  317. if (Environment.OSVersion.Platform == PlatformID.Unix)
  318. {
  319. KeyBindings.Add (Key.Z.WithCtrl, Command.Suspend);
  320. }
  321. }
  322. }