2
0

KeyboardImpl.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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, IDisposable
  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 and subscribes to Application configuration property events.
  94. /// </summary>
  95. public KeyboardImpl ()
  96. {
  97. // Initialize from Application static properties (ConfigurationManager may have set these before we were created)
  98. _quitKey = Application.QuitKey;
  99. _arrangeKey = Application.ArrangeKey;
  100. _nextTabGroupKey = Application.NextTabGroupKey;
  101. _nextTabKey = Application.NextTabKey;
  102. _prevTabGroupKey = Application.PrevTabGroupKey;
  103. _prevTabKey = Application.PrevTabKey;
  104. // Subscribe to Application static property change events
  105. Application.QuitKeyChanged += OnQuitKeyChanged;
  106. Application.ArrangeKeyChanged += OnArrangeKeyChanged;
  107. Application.NextTabGroupKeyChanged += OnNextTabGroupKeyChanged;
  108. Application.NextTabKeyChanged += OnNextTabKeyChanged;
  109. Application.PrevTabGroupKeyChanged += OnPrevTabGroupKeyChanged;
  110. Application.PrevTabKeyChanged += OnPrevTabKeyChanged;
  111. AddKeyBindings ();
  112. }
  113. /// <inheritdoc/>
  114. public bool RaiseKeyDownEvent (Key key)
  115. {
  116. //ebug.Assert (App.Application.MainThreadId == Thread.CurrentThread.ManagedThreadId);
  117. //Logging.Debug ($"{key}");
  118. // TODO: Add a way to ignore certain keys, esp for debugging.
  119. //#if DEBUG
  120. // if (key == Key.Empty.WithAlt || key == Key.Empty.WithCtrl)
  121. // {
  122. // Logging.Debug ($"Ignoring {key}");
  123. // return false;
  124. // }
  125. //#endif
  126. // TODO: This should match standard event patterns
  127. KeyDown?.Invoke (null, key);
  128. if (key.Handled)
  129. {
  130. return true;
  131. }
  132. if (App?.Popover?.DispatchKeyDown (key) is true)
  133. {
  134. return true;
  135. }
  136. if (App?.TopRunnable is null)
  137. {
  138. if (App?.SessionStack is { })
  139. {
  140. foreach (Toplevel topLevel in App.SessionStack.ToList ())
  141. {
  142. if (topLevel.NewKeyDownEvent (key))
  143. {
  144. return true;
  145. }
  146. if (topLevel.Modal)
  147. {
  148. break;
  149. }
  150. }
  151. }
  152. }
  153. else
  154. {
  155. if (App.TopRunnable.NewKeyDownEvent (key))
  156. {
  157. return true;
  158. }
  159. }
  160. bool? commandHandled = InvokeCommandsBoundToKey (key);
  161. if(commandHandled is true)
  162. {
  163. return true;
  164. }
  165. return false;
  166. }
  167. /// <inheritdoc/>
  168. public bool RaiseKeyUpEvent (Key key)
  169. {
  170. if (App?.Initialized != true)
  171. {
  172. return true;
  173. }
  174. KeyUp?.Invoke (null, key);
  175. if (key.Handled)
  176. {
  177. return true;
  178. }
  179. // TODO: Add Popover support
  180. if (App?.SessionStack is { })
  181. {
  182. foreach (Toplevel topLevel in App.SessionStack.ToList ())
  183. {
  184. if (topLevel.NewKeyUpEvent (key))
  185. {
  186. return true;
  187. }
  188. if (topLevel.Modal)
  189. {
  190. break;
  191. }
  192. }
  193. }
  194. return false;
  195. }
  196. /// <inheritdoc/>
  197. public bool? InvokeCommandsBoundToKey (Key key)
  198. {
  199. bool? handled = null;
  200. // Invoke any Application-scoped KeyBindings.
  201. // The first view that handles the key will stop the loop.
  202. // foreach (KeyValuePair<Key, KeyBinding> binding in KeyBindings.GetBindings (key))
  203. if (KeyBindings.TryGet (key, out KeyBinding binding))
  204. {
  205. if (binding.Target is { })
  206. {
  207. if (!binding.Target.Enabled)
  208. {
  209. return null;
  210. }
  211. handled = binding.Target?.InvokeCommands (binding.Commands, binding);
  212. }
  213. else
  214. {
  215. bool? toReturn = null;
  216. foreach (Command command in binding.Commands)
  217. {
  218. toReturn = InvokeCommand (command, key, binding);
  219. }
  220. handled = toReturn ?? true;
  221. }
  222. }
  223. return handled;
  224. }
  225. /// <inheritdoc/>
  226. public bool? InvokeCommand (Command command, Key key, KeyBinding binding)
  227. {
  228. if (!_commandImplementations.ContainsKey (command))
  229. {
  230. throw new NotSupportedException (
  231. @$"A KeyBinding was set up for the command {command} ({key}) but that command is not supported by Application."
  232. );
  233. }
  234. if (_commandImplementations.TryGetValue (command, out View.CommandImplementation? implementation))
  235. {
  236. CommandContext<KeyBinding> context = new (command, null, binding); // Create the context here
  237. return implementation (context);
  238. }
  239. return null;
  240. }
  241. /// <summary>
  242. /// <para>
  243. /// Sets the function that will be invoked for a <see cref="Command"/>.
  244. /// </para>
  245. /// <para>
  246. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  247. /// replace the old one.
  248. /// </para>
  249. /// </summary>
  250. /// <remarks>
  251. /// <para>
  252. /// This version of AddCommand is for commands that do not require a <see cref="ICommandContext"/>.
  253. /// </para>
  254. /// </remarks>
  255. /// <param name="command">The command.</param>
  256. /// <param name="f">The function.</param>
  257. private void AddCommand (Command command, Func<bool?> f) { _commandImplementations [command] = ctx => f (); }
  258. internal void AddKeyBindings ()
  259. {
  260. _commandImplementations.Clear ();
  261. // Things Application knows how to do
  262. AddCommand (
  263. Command.Quit,
  264. () =>
  265. {
  266. App?.RequestStop ();
  267. return true;
  268. }
  269. );
  270. AddCommand (
  271. Command.Suspend,
  272. () =>
  273. {
  274. App?.Driver?.Suspend ();
  275. return true;
  276. }
  277. );
  278. AddCommand (
  279. Command.NextTabStop,
  280. () => App?.Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabStop));
  281. AddCommand (
  282. Command.PreviousTabStop,
  283. () => App?.Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabStop));
  284. AddCommand (
  285. Command.NextTabGroup,
  286. () => App?.Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabGroup));
  287. AddCommand (
  288. Command.PreviousTabGroup,
  289. () => App?.Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabGroup));
  290. AddCommand (
  291. Command.Refresh,
  292. () =>
  293. {
  294. App?.LayoutAndDraw (true);
  295. return true;
  296. }
  297. );
  298. AddCommand (
  299. Command.Arrange,
  300. () =>
  301. {
  302. View? viewToArrange = App?.Navigation?.GetFocused ();
  303. // Go up the superview hierarchy and find the first that is not ViewArrangement.Fixed
  304. while (viewToArrange is { SuperView: { }, Arrangement: ViewArrangement.Fixed })
  305. {
  306. viewToArrange = viewToArrange.SuperView;
  307. }
  308. if (viewToArrange is { })
  309. {
  310. return viewToArrange.Border?.EnterArrangeMode (ViewArrangement.Fixed);
  311. }
  312. return false;
  313. });
  314. //SetKeysToHardCodedDefaults ();
  315. // Need to clear after setting the above to ensure actually clear
  316. // because set_QuitKey etc.. may call Add
  317. KeyBindings.Clear ();
  318. KeyBindings.Add (QuitKey, Command.Quit);
  319. KeyBindings.Add (NextTabKey, Command.NextTabStop);
  320. KeyBindings.Add (PrevTabKey, Command.PreviousTabStop);
  321. KeyBindings.Add (NextTabGroupKey, Command.NextTabGroup);
  322. KeyBindings.Add (PrevTabGroupKey, Command.PreviousTabGroup);
  323. KeyBindings.Add (ArrangeKey, Command.Arrange);
  324. KeyBindings.Add (Key.CursorRight, Command.NextTabStop);
  325. KeyBindings.Add (Key.CursorDown, Command.NextTabStop);
  326. KeyBindings.Add (Key.CursorLeft, Command.PreviousTabStop);
  327. KeyBindings.Add (Key.CursorUp, Command.PreviousTabStop);
  328. // TODO: Refresh Key should be configurable
  329. KeyBindings.Add (Key.F5, Command.Refresh);
  330. // TODO: Suspend Key should be configurable
  331. if (Environment.OSVersion.Platform == PlatformID.Unix)
  332. {
  333. KeyBindings.Add (Key.Z.WithCtrl, Command.Suspend);
  334. }
  335. }
  336. // Event handlers for Application static property changes
  337. private void OnQuitKeyChanged (object? sender, ValueChangedEventArgs<Key> e)
  338. {
  339. QuitKey = e.NewValue;
  340. }
  341. private void OnArrangeKeyChanged (object? sender, ValueChangedEventArgs<Key> e)
  342. {
  343. ArrangeKey = e.NewValue;
  344. }
  345. private void OnNextTabGroupKeyChanged (object? sender, ValueChangedEventArgs<Key> e)
  346. {
  347. NextTabGroupKey = e.NewValue;
  348. }
  349. private void OnNextTabKeyChanged (object? sender, ValueChangedEventArgs<Key> e)
  350. {
  351. NextTabKey = e.NewValue;
  352. }
  353. private void OnPrevTabGroupKeyChanged (object? sender, ValueChangedEventArgs<Key> e)
  354. {
  355. PrevTabGroupKey = e.NewValue;
  356. }
  357. private void OnPrevTabKeyChanged (object? sender, ValueChangedEventArgs<Key> e)
  358. {
  359. PrevTabKey = e.NewValue;
  360. }
  361. /// <inheritdoc/>
  362. public void Dispose ()
  363. {
  364. // Unsubscribe from Application static property change events
  365. Application.QuitKeyChanged -= OnQuitKeyChanged;
  366. Application.ArrangeKeyChanged -= OnArrangeKeyChanged;
  367. Application.NextTabGroupKeyChanged -= OnNextTabGroupKeyChanged;
  368. Application.NextTabKeyChanged -= OnNextTabKeyChanged;
  369. Application.PrevTabGroupKeyChanged -= OnPrevTabGroupKeyChanged;
  370. Application.PrevTabKeyChanged -= OnPrevTabKeyChanged;
  371. }
  372. }