KeyboardImpl.cs 14 KB

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