KeyboardTests.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. using UnitTests;
  2. using Xunit.Abstractions;
  3. namespace Terminal.Gui.ApplicationTests;
  4. /// <summary>
  5. /// Application tests for keyboard support.
  6. /// </summary>
  7. public class KeyboardTests
  8. {
  9. public KeyboardTests (ITestOutputHelper output)
  10. {
  11. _output = output;
  12. #if DEBUG_IDISPOSABLE
  13. View.Instances.Clear ();
  14. RunState.Instances.Clear ();
  15. #endif
  16. }
  17. private readonly ITestOutputHelper _output;
  18. private object _timeoutLock;
  19. [Fact]
  20. [AutoInitShutdown]
  21. public void KeyBindings_Add_Adds ()
  22. {
  23. Application.KeyBindings.Add (Key.A, Command.Accept);
  24. Application.KeyBindings.Add (Key.B, Command.Accept);
  25. Assert.True (Application.KeyBindings.TryGet (Key.A, out KeyBinding binding));
  26. Assert.Null (binding.Target);
  27. Assert.True (Application.KeyBindings.TryGet (Key.B, out binding));
  28. Assert.Null (binding.Target);
  29. }
  30. [Fact]
  31. [AutoInitShutdown]
  32. public void KeyBindings_Remove_Removes ()
  33. {
  34. Application.KeyBindings.Add (Key.A, Command.Accept);
  35. Assert.True (Application.KeyBindings.TryGet (Key.A, out _));
  36. Application.KeyBindings.Remove (Key.A);
  37. Assert.False (Application.KeyBindings.TryGet (Key.A, out _));
  38. }
  39. [Fact]
  40. public void KeyBindings_OnKeyDown ()
  41. {
  42. Application.Top = new ();
  43. var view = new ScopedKeyBindingView ();
  44. var keyWasHandled = false;
  45. view.KeyDownNotHandled += (s, e) => keyWasHandled = true;
  46. Application.Top.Add (view);
  47. Application.RaiseKeyDownEvent (Key.A);
  48. Assert.False (keyWasHandled);
  49. Assert.True (view.ApplicationCommand);
  50. keyWasHandled = false;
  51. view.ApplicationCommand = false;
  52. Application.KeyBindings.Remove (KeyCode.A);
  53. Application.RaiseKeyDownEvent (Key.A); // old
  54. Assert.False (keyWasHandled);
  55. Assert.False (view.ApplicationCommand);
  56. Application.KeyBindings.Add (Key.A.WithCtrl, view, Command.Save);
  57. Application.RaiseKeyDownEvent (Key.A); // old
  58. Assert.False (keyWasHandled);
  59. Assert.False (view.ApplicationCommand);
  60. Application.RaiseKeyDownEvent (Key.A.WithCtrl); // new
  61. Assert.False (keyWasHandled);
  62. Assert.True (view.ApplicationCommand);
  63. keyWasHandled = false;
  64. Application.RaiseKeyDownEvent (Key.H);
  65. Assert.False (keyWasHandled);
  66. Assert.True (view.HotKeyCommand);
  67. keyWasHandled = false;
  68. Assert.False (view.HasFocus);
  69. Application.RaiseKeyDownEvent (Key.F);
  70. Assert.False (keyWasHandled);
  71. Assert.True (view.ApplicationCommand);
  72. Assert.True (view.HotKeyCommand);
  73. Assert.False (view.FocusedCommand);
  74. Application.Top.Dispose ();
  75. Application.ResetState (true);
  76. }
  77. [Fact]
  78. [AutoInitShutdown]
  79. public void KeyBindings_OnKeyDown_Negative ()
  80. {
  81. var view = new ScopedKeyBindingView ();
  82. var keyWasHandled = false;
  83. view.KeyDownNotHandled += (s, e) => keyWasHandled = true;
  84. var top = new Toplevel ();
  85. top.Add (view);
  86. Application.Begin (top);
  87. Application.RaiseKeyDownEvent (Key.A.WithCtrl);
  88. Assert.False (keyWasHandled);
  89. Assert.False (view.ApplicationCommand);
  90. Assert.False (view.HotKeyCommand);
  91. Assert.False (view.FocusedCommand);
  92. keyWasHandled = false;
  93. Assert.False (view.HasFocus);
  94. Application.RaiseKeyDownEvent (Key.Z);
  95. Assert.False (keyWasHandled);
  96. Assert.False (view.ApplicationCommand);
  97. Assert.False (view.HotKeyCommand);
  98. Assert.False (view.FocusedCommand);
  99. top.Dispose ();
  100. }
  101. [Fact]
  102. public void KeyUp_Event ()
  103. {
  104. Application.Init (new FakeDriver ());
  105. // Setup some fake keypresses (This)
  106. var input = "Tests";
  107. Key originalQuitKey = Application.QuitKey;
  108. Application.QuitKey = Key.Q.WithCtrl;
  109. // Put a control-q in at the end
  110. FakeConsole.MockKeyPresses.Push (new ('Q', ConsoleKey.Q, false, false, true));
  111. foreach (char c in input.Reverse ())
  112. {
  113. if (char.IsLetter (c))
  114. {
  115. FakeConsole.MockKeyPresses.Push (
  116. new (
  117. c,
  118. (ConsoleKey)char.ToUpper (c),
  119. char.IsUpper (c),
  120. false,
  121. false
  122. )
  123. );
  124. }
  125. else
  126. {
  127. FakeConsole.MockKeyPresses.Push (
  128. new (
  129. c,
  130. (ConsoleKey)c,
  131. false,
  132. false,
  133. false
  134. )
  135. );
  136. }
  137. }
  138. int stackSize = FakeConsole.MockKeyPresses.Count;
  139. var iterations = 0;
  140. Application.Iteration += (s, a) =>
  141. {
  142. iterations++;
  143. // Stop if we run out of control...
  144. if (iterations > 10)
  145. {
  146. Application.RequestStop ();
  147. }
  148. };
  149. var keyUps = 0;
  150. var output = string.Empty;
  151. var top = new Toplevel ();
  152. top.KeyUp += (sender, args) =>
  153. {
  154. if (args.KeyCode != (KeyCode.CtrlMask | KeyCode.Q))
  155. {
  156. output += args.AsRune;
  157. }
  158. keyUps++;
  159. };
  160. Application.Run (top);
  161. Application.QuitKey = originalQuitKey;
  162. // Input string should match output
  163. Assert.Equal (input, output);
  164. // # of key up events should match stack size
  165. //Assert.Equal (stackSize, keyUps);
  166. // We can't use numbers variables on the left side of an Assert.Equal/NotEqual,
  167. // it must be literal (Linux only).
  168. Assert.Equal (6, keyUps);
  169. // # of key up events should match # of iterations
  170. Assert.Equal (stackSize, iterations);
  171. top.Dispose ();
  172. Application.Shutdown ();
  173. Assert.Null (Application.Top);
  174. Assert.Null (Application.MainLoop);
  175. Assert.Null (Application.Driver);
  176. }
  177. [Fact]
  178. public void NextTabGroupKey_Moves_Focus_To_TabStop_In_Next_TabGroup ()
  179. {
  180. // Arrange
  181. Application.Navigation = new ();
  182. var top = new Toplevel ();
  183. var view1 = new View
  184. {
  185. Id = "view1",
  186. CanFocus = true,
  187. TabStop = TabBehavior.TabGroup
  188. };
  189. var subView1 = new View
  190. {
  191. Id = "subView1",
  192. CanFocus = true,
  193. TabStop = TabBehavior.TabStop
  194. };
  195. view1.Add (subView1);
  196. var view2 = new View
  197. {
  198. Id = "view2",
  199. CanFocus = true,
  200. TabStop = TabBehavior.TabGroup
  201. };
  202. var subView2 = new View
  203. {
  204. Id = "subView2",
  205. CanFocus = true,
  206. TabStop = TabBehavior.TabStop
  207. };
  208. view2.Add (subView2);
  209. top.Add (view1, view2);
  210. Application.Top = top;
  211. view1.SetFocus ();
  212. Assert.True (view1.HasFocus);
  213. Assert.True (subView1.HasFocus);
  214. // Act
  215. Application.RaiseKeyDownEvent (Application.NextTabGroupKey);
  216. // Assert
  217. Assert.True (view2.HasFocus);
  218. Assert.True (subView2.HasFocus);
  219. top.Dispose ();
  220. Application.Navigation = null;
  221. }
  222. [Fact]
  223. public void NextTabGroupKey_PrevTabGroupKey_Tests ()
  224. {
  225. Application.Init (new FakeDriver ());
  226. Toplevel top = new (); // TabGroup
  227. var w1 = new Window (); // TabGroup
  228. var v1 = new TextField (); // TabStop
  229. var v2 = new TextView (); // TabStop
  230. w1.Add (v1, v2);
  231. var w2 = new Window (); // TabGroup
  232. var v3 = new CheckBox (); // TabStop
  233. var v4 = new Button (); // TabStop
  234. w2.Add (v3, v4);
  235. top.Add (w1, w2);
  236. Application.Iteration += (s, a) =>
  237. {
  238. Assert.True (v1.HasFocus);
  239. // Across TabGroups
  240. Application.RaiseKeyDownEvent (Key.F6);
  241. Assert.True (v3.HasFocus);
  242. Application.RaiseKeyDownEvent (Key.F6);
  243. Assert.True (v1.HasFocus);
  244. Application.RaiseKeyDownEvent (Key.F6.WithShift);
  245. Assert.True (v3.HasFocus);
  246. Application.RaiseKeyDownEvent (Key.F6.WithShift);
  247. Assert.True (v1.HasFocus);
  248. // Restore?
  249. Application.RaiseKeyDownEvent (Key.Tab);
  250. Assert.True (v2.HasFocus);
  251. Application.RaiseKeyDownEvent (Key.F6);
  252. Assert.True (v3.HasFocus);
  253. Application.RaiseKeyDownEvent (Key.F6);
  254. Assert.True (v1.HasFocus);
  255. Application.RequestStop ();
  256. };
  257. Application.Run (top);
  258. // Replacing the defaults keys to avoid errors on others unit tests that are using it.
  259. Application.NextTabGroupKey = Key.PageDown.WithCtrl;
  260. Application.PrevTabGroupKey = Key.PageUp.WithCtrl;
  261. Application.QuitKey = Key.Q.WithCtrl;
  262. Assert.Equal (KeyCode.PageDown | KeyCode.CtrlMask, Application.NextTabGroupKey.KeyCode);
  263. Assert.Equal (KeyCode.PageUp | KeyCode.CtrlMask, Application.PrevTabGroupKey.KeyCode);
  264. Assert.Equal (KeyCode.Q | KeyCode.CtrlMask, Application.QuitKey.KeyCode);
  265. top.Dispose ();
  266. // Shutdown must be called to safely clean up Application if Init has been called
  267. Application.Shutdown ();
  268. }
  269. [Fact]
  270. public void NextTabKey_Moves_Focus_To_Next_TabStop ()
  271. {
  272. // Arrange
  273. Application.Navigation = new ();
  274. var top = new Toplevel ();
  275. var view1 = new View { Id = "view1", CanFocus = true };
  276. var view2 = new View { Id = "view2", CanFocus = true };
  277. top.Add (view1, view2);
  278. Application.Top = top;
  279. view1.SetFocus ();
  280. // Act
  281. Application.RaiseKeyDownEvent (Application.NextTabKey);
  282. // Assert
  283. Assert.True (view2.HasFocus);
  284. top.Dispose ();
  285. Application.Navigation = null;
  286. }
  287. [Fact]
  288. public void PrevTabGroupKey_Moves_Focus_To_TabStop_In_Prev_TabGroup ()
  289. {
  290. // Arrange
  291. Application.Navigation = new ();
  292. var top = new Toplevel ();
  293. var view1 = new View
  294. {
  295. Id = "view1",
  296. CanFocus = true,
  297. TabStop = TabBehavior.TabGroup
  298. };
  299. var subView1 = new View
  300. {
  301. Id = "subView1",
  302. CanFocus = true,
  303. TabStop = TabBehavior.TabStop
  304. };
  305. view1.Add (subView1);
  306. var view2 = new View
  307. {
  308. Id = "view2",
  309. CanFocus = true,
  310. TabStop = TabBehavior.TabGroup
  311. };
  312. var subView2 = new View
  313. {
  314. Id = "subView2",
  315. CanFocus = true,
  316. TabStop = TabBehavior.TabStop
  317. };
  318. view2.Add (subView2);
  319. top.Add (view1, view2);
  320. Application.Top = top;
  321. view1.SetFocus ();
  322. Assert.True (view1.HasFocus);
  323. Assert.True (subView1.HasFocus);
  324. // Act
  325. Application.RaiseKeyDownEvent (Application.PrevTabGroupKey);
  326. // Assert
  327. Assert.True (view2.HasFocus);
  328. Assert.True (subView2.HasFocus);
  329. top.Dispose ();
  330. Application.Navigation = null;
  331. }
  332. [Fact]
  333. public void PrevTabKey_Moves_Focus_To_Prev_TabStop ()
  334. {
  335. // Arrange
  336. Application.Navigation = new ();
  337. var top = new Toplevel ();
  338. var view1 = new View { Id = "view1", CanFocus = true };
  339. var view2 = new View { Id = "view2", CanFocus = true };
  340. top.Add (view1, view2);
  341. Application.Top = top;
  342. view1.SetFocus ();
  343. // Act
  344. Application.RaiseKeyDownEvent (Application.NextTabKey);
  345. // Assert
  346. Assert.True (view2.HasFocus);
  347. top.Dispose ();
  348. Application.Navigation = null;
  349. }
  350. [Fact]
  351. public void QuitKey_Default_Is_Esc ()
  352. {
  353. Application.ResetState (true);
  354. // Before Init
  355. Assert.Equal (Key.Esc, Application.QuitKey);
  356. Application.Init (new FakeDriver ());
  357. // After Init
  358. Assert.Equal (Key.Esc, Application.QuitKey);
  359. Application.Shutdown ();
  360. }
  361. [Fact]
  362. [AutoInitShutdown]
  363. public void QuitKey_Getter_Setter ()
  364. {
  365. Toplevel top = new ();
  366. var isQuiting = false;
  367. top.Closing += (s, e) =>
  368. {
  369. isQuiting = true;
  370. e.Cancel = true;
  371. };
  372. Application.Begin (top);
  373. top.Running = true;
  374. Key prevKey = Application.QuitKey;
  375. Application.RaiseKeyDownEvent (Application.QuitKey);
  376. Assert.True (isQuiting);
  377. isQuiting = false;
  378. Application.RaiseKeyDownEvent (Application.QuitKey);
  379. Assert.True (isQuiting);
  380. isQuiting = false;
  381. Application.QuitKey = Key.C.WithCtrl;
  382. Application.RaiseKeyDownEvent (prevKey); // Should not quit
  383. Assert.False (isQuiting);
  384. Application.RaiseKeyDownEvent (Key.Q.WithCtrl); // Should not quit
  385. Assert.False (isQuiting);
  386. Application.RaiseKeyDownEvent (Application.QuitKey);
  387. Assert.True (isQuiting);
  388. // Reset the QuitKey to avoid throws errors on another tests
  389. Application.QuitKey = prevKey;
  390. top.Dispose ();
  391. }
  392. [Fact]
  393. public void QuitKey_Quits ()
  394. {
  395. Assert.Null (_timeoutLock);
  396. _timeoutLock = new ();
  397. uint abortTime = 500;
  398. var initialized = false;
  399. var iteration = 0;
  400. var shutdown = false;
  401. object timeout = null;
  402. Application.InitializedChanged += OnApplicationOnInitializedChanged;
  403. Application.Init (new FakeDriver ());
  404. Assert.True (initialized);
  405. Assert.False (shutdown);
  406. _output.WriteLine ("Application.Run<Toplevel> ().Dispose ()..");
  407. Application.Run<Toplevel> ().Dispose ();
  408. _output.WriteLine ("Back from Application.Run<Toplevel> ().Dispose ()");
  409. Assert.True (initialized);
  410. Assert.False (shutdown);
  411. Assert.Equal (1, iteration);
  412. Application.Shutdown ();
  413. Application.InitializedChanged -= OnApplicationOnInitializedChanged;
  414. lock (_timeoutLock)
  415. {
  416. if (timeout is { })
  417. {
  418. Application.RemoveTimeout (timeout);
  419. timeout = null;
  420. }
  421. }
  422. Assert.True (initialized);
  423. Assert.True (shutdown);
  424. #if DEBUG_IDISPOSABLE
  425. Assert.Empty (View.Instances);
  426. #endif
  427. lock (_timeoutLock)
  428. {
  429. _timeoutLock = null;
  430. }
  431. return;
  432. void OnApplicationOnInitializedChanged (object s, EventArgs<bool> a)
  433. {
  434. _output.WriteLine ("OnApplicationOnInitializedChanged: {0}", a.CurrentValue);
  435. if (a.CurrentValue)
  436. {
  437. Application.Iteration += OnApplicationOnIteration;
  438. initialized = true;
  439. lock (_timeoutLock)
  440. {
  441. timeout = Application.AddTimeout (TimeSpan.FromMilliseconds (abortTime), ForceCloseCallback);
  442. }
  443. }
  444. else
  445. {
  446. Application.Iteration -= OnApplicationOnIteration;
  447. shutdown = true;
  448. }
  449. }
  450. bool ForceCloseCallback ()
  451. {
  452. lock (_timeoutLock)
  453. {
  454. _output.WriteLine ($"ForceCloseCallback. iteration: {iteration}");
  455. if (timeout is { })
  456. {
  457. timeout = null;
  458. }
  459. }
  460. Application.ResetState (true);
  461. Assert.Fail ($"Failed to Quit with {Application.QuitKey} after {abortTime}ms. Force quit.");
  462. return false;
  463. }
  464. void OnApplicationOnIteration (object s, IterationEventArgs a)
  465. {
  466. _output.WriteLine ("Iteration: {0}", iteration);
  467. iteration++;
  468. Assert.True (iteration < 2, "Too many iterations, something is wrong.");
  469. if (Application.Initialized)
  470. {
  471. _output.WriteLine (" Pressing QuitKey");
  472. Application.RaiseKeyDownEvent (Application.QuitKey);
  473. }
  474. }
  475. }
  476. // Test View for testing Application key Bindings
  477. public class ScopedKeyBindingView : View
  478. {
  479. public ScopedKeyBindingView ()
  480. {
  481. AddCommand (Command.Save, () => ApplicationCommand = true);
  482. AddCommand (Command.HotKey, () => HotKeyCommand = true);
  483. AddCommand (Command.Left, () => FocusedCommand = true);
  484. Application.KeyBindings.Add (Key.A, this, Command.Save);
  485. HotKey = KeyCode.H;
  486. KeyBindings.Add (Key.F, Command.Left);
  487. }
  488. public bool ApplicationCommand { get; set; }
  489. public bool FocusedCommand { get; set; }
  490. public bool HotKeyCommand { get; set; }
  491. }
  492. }