FakeDriver.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. //
  2. // FakeDriver.cs: A fake ConsoleDriver for unit tests.
  3. //
  4. using System;
  5. using System.Buffers;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Linq;
  9. using System.Runtime.InteropServices;
  10. using System.Threading;
  11. using System.Text;
  12. // Alias Console to MockConsole so we don't accidentally use Console
  13. using Console = Terminal.Gui.FakeConsole;
  14. using Unix.Terminal;
  15. using static Terminal.Gui.WindowsConsole;
  16. using System.Drawing;
  17. namespace Terminal.Gui;
  18. /// <summary>
  19. /// Implements a mock ConsoleDriver for unit testing
  20. /// </summary>
  21. public class FakeDriver : ConsoleDriver {
  22. #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
  23. public class Behaviors {
  24. public bool UseFakeClipboard { get; internal set; }
  25. public bool FakeClipboardAlwaysThrowsNotSupportedException { get; internal set; }
  26. public bool FakeClipboardIsSupportedAlwaysFalse { get; internal set; }
  27. public Behaviors (bool useFakeClipboard = false, bool fakeClipboardAlwaysThrowsNotSupportedException = false, bool fakeClipboardIsSupportedAlwaysTrue = false)
  28. {
  29. UseFakeClipboard = useFakeClipboard;
  30. FakeClipboardAlwaysThrowsNotSupportedException = fakeClipboardAlwaysThrowsNotSupportedException;
  31. FakeClipboardIsSupportedAlwaysFalse = fakeClipboardIsSupportedAlwaysTrue;
  32. // double check usage is correct
  33. Debug.Assert (useFakeClipboard == false && fakeClipboardAlwaysThrowsNotSupportedException == false);
  34. Debug.Assert (useFakeClipboard == false && fakeClipboardIsSupportedAlwaysTrue == false);
  35. }
  36. }
  37. public static FakeDriver.Behaviors FakeBehaviors = new Behaviors ();
  38. public override bool SupportsTrueColor => false;
  39. public FakeDriver ()
  40. {
  41. if (FakeBehaviors.UseFakeClipboard) {
  42. Clipboard = new FakeClipboard (FakeBehaviors.FakeClipboardAlwaysThrowsNotSupportedException, FakeBehaviors.FakeClipboardIsSupportedAlwaysFalse);
  43. } else {
  44. if (RuntimeInformation.IsOSPlatform (OSPlatform.Windows)) {
  45. Clipboard = new WindowsClipboard ();
  46. } else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
  47. Clipboard = new MacOSXClipboard ();
  48. } else {
  49. if (CursesDriver.Is_WSL_Platform ()) {
  50. Clipboard = new WSLClipboard ();
  51. } else {
  52. Clipboard = new CursesClipboard ();
  53. }
  54. }
  55. }
  56. }
  57. public override void End ()
  58. {
  59. FakeConsole.ResetColor ();
  60. FakeConsole.Clear ();
  61. }
  62. public override void Init (Action terminalResized)
  63. {
  64. FakeConsole.MockKeyPresses.Clear ();
  65. TerminalResized = terminalResized;
  66. Cols = FakeConsole.WindowWidth = FakeConsole.BufferWidth = FakeConsole.WIDTH;
  67. Rows = FakeConsole.WindowHeight = FakeConsole.BufferHeight = FakeConsole.HEIGHT;
  68. FakeConsole.Clear ();
  69. ResizeScreen ();
  70. // Call InitializeColorSchemes before UpdateOffScreen as it references Colors
  71. CurrentAttribute = MakeColor (Color.White, Color.Black);
  72. InitializeColorSchemes ();
  73. ClearContents ();
  74. }
  75. public override void UpdateScreen ()
  76. {
  77. var savedRow = FakeConsole.CursorTop;
  78. var savedCol = FakeConsole.CursorLeft;
  79. var savedCursorVisible = FakeConsole.CursorVisible;
  80. var top = 0;
  81. var left = 0;
  82. var rows = Rows;
  83. var cols = Cols;
  84. System.Text.StringBuilder output = new System.Text.StringBuilder ();
  85. Attribute redrawAttr = new Attribute ();
  86. var lastCol = -1;
  87. for (var row = top; row < rows; row++) {
  88. if (!_dirtyLines [row]) {
  89. continue;
  90. }
  91. FakeConsole.CursorTop = row;
  92. FakeConsole.CursorLeft = 0;
  93. _dirtyLines [row] = false;
  94. output.Clear ();
  95. for (var col = left; col < cols; col++) {
  96. lastCol = -1;
  97. var outputWidth = 0;
  98. for (; col < cols; col++) {
  99. if (!Contents [row, col].IsDirty) {
  100. if (output.Length > 0) {
  101. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  102. } else if (lastCol == -1) {
  103. lastCol = col;
  104. }
  105. if (lastCol + 1 < cols)
  106. lastCol++;
  107. continue;
  108. }
  109. if (lastCol == -1) {
  110. lastCol = col;
  111. }
  112. Attribute attr = Contents [row, col].Attribute.Value;
  113. // Performance: Only send the escape sequence if the attribute has changed.
  114. if (attr != redrawAttr) {
  115. redrawAttr = attr;
  116. FakeConsole.ForegroundColor = (ConsoleColor)attr.Foreground.Value;
  117. FakeConsole.BackgroundColor = (ConsoleColor)attr.Background.Value;
  118. }
  119. outputWidth++;
  120. var rune = (Rune)Contents [row, col].Runes [0];
  121. output.Append (rune.ToString ());
  122. if (rune.IsSurrogatePair () && rune.GetColumns () < 2) {
  123. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  124. FakeConsole.CursorLeft--;
  125. }
  126. Contents [row, col].IsDirty = false;
  127. }
  128. }
  129. if (output.Length > 0) {
  130. FakeConsole.CursorTop = row;
  131. FakeConsole.CursorLeft = lastCol;
  132. foreach (var c in output.ToString ()) {
  133. FakeConsole.Write (c);
  134. }
  135. }
  136. }
  137. FakeConsole.CursorTop = 0;
  138. FakeConsole.CursorLeft = 0;
  139. //SetCursorVisibility (savedVisibitity);
  140. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  141. {
  142. FakeConsole.CursorTop = row;
  143. FakeConsole.CursorLeft = lastCol;
  144. foreach (var c in output.ToString ()) {
  145. FakeConsole.Write (c);
  146. }
  147. output.Clear ();
  148. lastCol += outputWidth;
  149. outputWidth = 0;
  150. }
  151. FakeConsole.CursorTop = savedRow;
  152. FakeConsole.CursorLeft = savedCol;
  153. FakeConsole.CursorVisible = savedCursorVisible;
  154. }
  155. public override void Refresh ()
  156. {
  157. UpdateScreen ();
  158. UpdateCursor ();
  159. }
  160. #region Color Handling
  161. /// <remarks>
  162. /// In the FakeDriver, colors are encoded as an int; same as NetDriver
  163. /// Extracts the foreground and background colors from the encoded value.
  164. /// Assumes a 4-bit encoded value for both foreground and background colors.
  165. /// </remarks>
  166. internal override void GetColors (int value, out ColorNames foreground, out ColorNames background)
  167. {
  168. // Assume a 4-bit encoded value for both foreground and background colors.
  169. foreground = (ColorNames)((value >> 16) & 0xF);
  170. background = (ColorNames)(value & 0xF);
  171. }
  172. /// <remarks>
  173. /// In the FakeDriver, colors are encoded as an int; same as NetDriver
  174. /// However, the foreground color is stored in the most significant 16 bits,
  175. /// and the background color is stored in the least significant 16 bits.
  176. /// </remarks>
  177. public override Attribute MakeColor (Color foreground, Color background)
  178. {
  179. // Encode the colors into the int value.
  180. return new Attribute (
  181. platformColor: ((((int)foreground.ColorName) & 0xffff) << 16) | (((int)background.ColorName) & 0xffff),
  182. foreground: foreground,
  183. background: background
  184. );
  185. }
  186. public override Attribute MakeColor (ColorNames foreground, ColorNames background)
  187. {
  188. return MakeColor (new Color (foreground), new Color (background));
  189. }
  190. #endregion
  191. public ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  192. {
  193. if (consoleKeyInfo.Key != ConsoleKey.Packet) {
  194. return consoleKeyInfo;
  195. }
  196. var mod = consoleKeyInfo.Modifiers;
  197. var shift = (mod & ConsoleModifiers.Shift) != 0;
  198. var alt = (mod & ConsoleModifiers.Alt) != 0;
  199. var control = (mod & ConsoleModifiers.Control) != 0;
  200. var keyChar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (consoleKeyInfo.KeyChar, consoleKeyInfo.Modifiers, out uint virtualKey, out _);
  201. return new ConsoleKeyInfo ((char)keyChar, (ConsoleKey)virtualKey, shift, alt, control);
  202. }
  203. Key MapKey (ConsoleKeyInfo keyInfo)
  204. {
  205. switch (keyInfo.Key) {
  206. case ConsoleKey.Escape:
  207. return MapKeyModifiers (keyInfo, Key.Esc);
  208. case ConsoleKey.Tab:
  209. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  210. case ConsoleKey.Clear:
  211. return MapKeyModifiers (keyInfo, Key.Clear);
  212. case ConsoleKey.Home:
  213. return MapKeyModifiers (keyInfo, Key.Home);
  214. case ConsoleKey.End:
  215. return MapKeyModifiers (keyInfo, Key.End);
  216. case ConsoleKey.LeftArrow:
  217. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  218. case ConsoleKey.RightArrow:
  219. return MapKeyModifiers (keyInfo, Key.CursorRight);
  220. case ConsoleKey.UpArrow:
  221. return MapKeyModifiers (keyInfo, Key.CursorUp);
  222. case ConsoleKey.DownArrow:
  223. return MapKeyModifiers (keyInfo, Key.CursorDown);
  224. case ConsoleKey.PageUp:
  225. return MapKeyModifiers (keyInfo, Key.PageUp);
  226. case ConsoleKey.PageDown:
  227. return MapKeyModifiers (keyInfo, Key.PageDown);
  228. case ConsoleKey.Enter:
  229. return MapKeyModifiers (keyInfo, Key.Enter);
  230. case ConsoleKey.Spacebar:
  231. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  232. case ConsoleKey.Backspace:
  233. return MapKeyModifiers (keyInfo, Key.Backspace);
  234. case ConsoleKey.Delete:
  235. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  236. case ConsoleKey.Insert:
  237. return MapKeyModifiers (keyInfo, Key.InsertChar);
  238. case ConsoleKey.PrintScreen:
  239. return MapKeyModifiers (keyInfo, Key.PrintScreen);
  240. case ConsoleKey.Oem1:
  241. case ConsoleKey.Oem2:
  242. case ConsoleKey.Oem3:
  243. case ConsoleKey.Oem4:
  244. case ConsoleKey.Oem5:
  245. case ConsoleKey.Oem6:
  246. case ConsoleKey.Oem7:
  247. case ConsoleKey.Oem8:
  248. case ConsoleKey.Oem102:
  249. case ConsoleKey.OemPeriod:
  250. case ConsoleKey.OemComma:
  251. case ConsoleKey.OemPlus:
  252. case ConsoleKey.OemMinus:
  253. if (keyInfo.KeyChar == 0) {
  254. return Key.Unknown;
  255. }
  256. return (Key)((uint)keyInfo.KeyChar);
  257. }
  258. var key = keyInfo.Key;
  259. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  260. var delta = key - ConsoleKey.A;
  261. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  262. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  263. }
  264. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  265. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  266. }
  267. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  268. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  269. }
  270. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  271. if (keyInfo.KeyChar == 0) {
  272. return (Key)(((uint)Key.AltMask | (uint)Key.CtrlMask) | ((uint)Key.A + delta));
  273. } else {
  274. return (Key)((uint)keyInfo.KeyChar);
  275. }
  276. }
  277. return (Key)((uint)keyInfo.KeyChar);
  278. }
  279. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  280. var delta = key - ConsoleKey.D0;
  281. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  282. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  283. }
  284. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  285. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  286. }
  287. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  288. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  289. }
  290. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  291. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
  292. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  293. }
  294. }
  295. return (Key)((uint)keyInfo.KeyChar);
  296. }
  297. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  298. var delta = key - ConsoleKey.F1;
  299. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  300. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  301. }
  302. return (Key)((uint)Key.F1 + delta);
  303. }
  304. if (keyInfo.KeyChar != 0) {
  305. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  306. }
  307. return (Key)(0xffffffff);
  308. }
  309. KeyModifiers keyModifiers;
  310. private Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  311. {
  312. Key keyMod = new Key ();
  313. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0) {
  314. keyMod = Key.ShiftMask;
  315. }
  316. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) {
  317. keyMod |= Key.CtrlMask;
  318. }
  319. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0) {
  320. keyMod |= Key.AltMask;
  321. }
  322. return keyMod != Key.Null ? keyMod | key : key;
  323. }
  324. Action<KeyEvent> _keyDownHandler;
  325. Action<KeyEvent> _keyHandler;
  326. Action<KeyEvent> _keyUpHandler;
  327. private CursorVisibility _savedCursorVisibility;
  328. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  329. {
  330. _keyDownHandler = keyDownHandler;
  331. _keyHandler = keyHandler;
  332. _keyUpHandler = keyUpHandler;
  333. // Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  334. (mainLoop.MainLoopDriver as FakeMainLoop).KeyPressed += (consoleKey) => ProcessInput (consoleKey);
  335. }
  336. void ProcessInput (ConsoleKeyInfo consoleKey)
  337. {
  338. if (consoleKey.Key == ConsoleKey.Packet) {
  339. consoleKey = FromVKPacketToKConsoleKeyInfo (consoleKey);
  340. }
  341. keyModifiers = new KeyModifiers ();
  342. if (consoleKey.Modifiers.HasFlag (ConsoleModifiers.Shift)) {
  343. keyModifiers.Shift = true;
  344. }
  345. if (consoleKey.Modifiers.HasFlag (ConsoleModifiers.Alt)) {
  346. keyModifiers.Alt = true;
  347. }
  348. if (consoleKey.Modifiers.HasFlag (ConsoleModifiers.Control)) {
  349. keyModifiers.Ctrl = true;
  350. }
  351. var map = MapKey (consoleKey);
  352. if (map == (Key)0xffffffff) {
  353. if ((consoleKey.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  354. _keyDownHandler (new KeyEvent (map, keyModifiers));
  355. _keyUpHandler (new KeyEvent (map, keyModifiers));
  356. }
  357. return;
  358. }
  359. _keyDownHandler (new KeyEvent (map, keyModifiers));
  360. _keyHandler (new KeyEvent (map, keyModifiers));
  361. _keyUpHandler (new KeyEvent (map, keyModifiers));
  362. }
  363. /// <inheritdoc/>
  364. public override bool GetCursorVisibility (out CursorVisibility visibility)
  365. {
  366. visibility = FakeConsole.CursorVisible
  367. ? CursorVisibility.Default
  368. : CursorVisibility.Invisible;
  369. return FakeConsole.CursorVisible;
  370. }
  371. /// <inheritdoc/>
  372. public override bool SetCursorVisibility (CursorVisibility visibility)
  373. {
  374. _savedCursorVisibility = visibility;
  375. return FakeConsole.CursorVisible = visibility == CursorVisibility.Default;
  376. }
  377. /// <inheritdoc/>
  378. public override bool EnsureCursorVisibility ()
  379. {
  380. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows)) {
  381. GetCursorVisibility (out CursorVisibility cursorVisibility);
  382. _savedCursorVisibility = cursorVisibility;
  383. SetCursorVisibility (CursorVisibility.Invisible);
  384. return false;
  385. }
  386. SetCursorVisibility (_savedCursorVisibility);
  387. return FakeConsole.CursorVisible;
  388. }
  389. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  390. {
  391. ProcessInput (new ConsoleKeyInfo (keyChar, key, shift, alt, control));
  392. }
  393. public void SetBufferSize (int width, int height)
  394. {
  395. FakeConsole.SetBufferSize (width, height);
  396. Cols = width;
  397. Rows = height;
  398. SetWindowSize (width, height);
  399. ProcessResize ();
  400. }
  401. public void SetWindowSize (int width, int height)
  402. {
  403. FakeConsole.SetWindowSize (width, height);
  404. if (width != Cols || height != Rows) {
  405. SetBufferSize (width, height);
  406. Cols = width;
  407. Rows = height;
  408. }
  409. ProcessResize ();
  410. }
  411. public void SetWindowPosition (int left, int top)
  412. {
  413. if (Left > 0 || Top > 0) {
  414. Left = 0;
  415. Top = 0;
  416. }
  417. FakeConsole.SetWindowPosition (Left, Top);
  418. }
  419. void ProcessResize ()
  420. {
  421. ResizeScreen ();
  422. ClearContents ();
  423. TerminalResized?.Invoke ();
  424. }
  425. public virtual void ResizeScreen ()
  426. {
  427. if (FakeConsole.WindowHeight > 0) {
  428. // Can raise an exception while is still resizing.
  429. try {
  430. FakeConsole.CursorTop = 0;
  431. FakeConsole.CursorLeft = 0;
  432. FakeConsole.WindowTop = 0;
  433. FakeConsole.WindowLeft = 0;
  434. } catch (System.IO.IOException) {
  435. return;
  436. } catch (ArgumentOutOfRangeException) {
  437. return;
  438. }
  439. }
  440. Clip = new Rect (0, 0, Cols, Rows);
  441. }
  442. public override void UpdateCursor ()
  443. {
  444. if (!EnsureCursorVisibility ()) {
  445. return;
  446. }
  447. // Prevents the exception of size changing during resizing.
  448. try {
  449. // BUGBUG: Why is this using BufferWidth/Height and now Cols/Rows?
  450. if (Col >= 0 && Col < FakeConsole.BufferWidth && Row >= 0 && Row < FakeConsole.BufferHeight) {
  451. FakeConsole.SetCursorPosition (Col, Row);
  452. }
  453. } catch (System.IO.IOException) {
  454. } catch (ArgumentOutOfRangeException) {
  455. }
  456. }
  457. #region Not Implemented
  458. public override void Suspend ()
  459. {
  460. throw new NotImplementedException ();
  461. }
  462. #endregion
  463. public class FakeClipboard : ClipboardBase {
  464. public Exception FakeException = null;
  465. string _contents = string.Empty;
  466. bool _isSupportedAlwaysFalse = false;
  467. public override bool IsSupported => !_isSupportedAlwaysFalse;
  468. public FakeClipboard (bool fakeClipboardThrowsNotSupportedException = false, bool isSupportedAlwaysFalse = false)
  469. {
  470. _isSupportedAlwaysFalse = isSupportedAlwaysFalse;
  471. if (fakeClipboardThrowsNotSupportedException) {
  472. FakeException = new NotSupportedException ("Fake clipboard exception");
  473. }
  474. }
  475. protected override string GetClipboardDataImpl ()
  476. {
  477. if (FakeException != null) {
  478. throw FakeException;
  479. }
  480. return _contents;
  481. }
  482. protected override void SetClipboardDataImpl (string text)
  483. {
  484. if (text == null) {
  485. throw new ArgumentNullException (nameof (text));
  486. }
  487. if (FakeException != null) {
  488. throw FakeException;
  489. }
  490. _contents = text;
  491. }
  492. }
  493. #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
  494. }