FakeDriver.cs 18 KB

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