FakeDriver.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. #nullable enable
  2. //
  3. // FakeDriver.cs: A fake IConsoleDriver for unit tests.
  4. //
  5. using System.Diagnostics;
  6. using System.Runtime.InteropServices;
  7. // Alias Console to MockConsole so we don't accidentally use Console
  8. namespace Terminal.Gui.Drivers;
  9. /// <summary>Implements a mock IConsoleDriver 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 { get; } = new ();
  33. public override bool SupportsTrueColor => false;
  34. /// <inheritdoc />
  35. public override void WriteRaw (string ansi)
  36. {
  37. }
  38. public FakeDriver ()
  39. {
  40. // FakeDriver implies UnitTests
  41. RunningUnitTests = true;
  42. base.Cols = FakeConsole.WindowWidth = FakeConsole.BufferWidth = FakeConsole.WIDTH;
  43. base.Rows = FakeConsole.WindowHeight = FakeConsole.BufferHeight = FakeConsole.HEIGHT;
  44. if (FakeBehaviors.UseFakeClipboard)
  45. {
  46. Clipboard = new FakeClipboard (
  47. FakeBehaviors.FakeClipboardAlwaysThrowsNotSupportedException,
  48. FakeBehaviors.FakeClipboardIsSupportedAlwaysFalse
  49. );
  50. }
  51. else
  52. {
  53. if (RuntimeInformation.IsOSPlatform (OSPlatform.Windows))
  54. {
  55. Clipboard = new WindowsClipboard ();
  56. }
  57. else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  58. {
  59. Clipboard = new MacOSXClipboard ();
  60. }
  61. else
  62. {
  63. if (PlatformDetection.IsWSLPlatform ())
  64. {
  65. Clipboard = new WSLClipboard ();
  66. }
  67. else
  68. {
  69. Clipboard = new UnixClipboard ();
  70. }
  71. }
  72. }
  73. }
  74. public override void End ()
  75. {
  76. FakeConsole.ResetColor ();
  77. FakeConsole.Clear ();
  78. }
  79. public override void Init ()
  80. {
  81. FakeConsole.MockKeyPresses.Clear ();
  82. Cols = FakeConsole.WindowWidth = FakeConsole.BufferWidth = FakeConsole.WIDTH;
  83. Rows = FakeConsole.WindowHeight = FakeConsole.BufferHeight = FakeConsole.HEIGHT;
  84. FakeConsole.Clear ();
  85. ResizeScreen ();
  86. CurrentAttribute = new Attribute (Color.White, Color.Black);
  87. }
  88. public override bool UpdateScreen ()
  89. {
  90. bool updated = false;
  91. int savedRow = FakeConsole.CursorTop;
  92. int savedCol = FakeConsole.CursorLeft;
  93. bool savedCursorVisible = FakeConsole.CursorVisible;
  94. var top = 0;
  95. var left = 0;
  96. int rows = Rows;
  97. int cols = Cols;
  98. var output = new StringBuilder ();
  99. var redrawAttr = new Attribute ();
  100. int lastCol = -1;
  101. for (int row = top; row < rows; row++)
  102. {
  103. if (!_dirtyLines! [row])
  104. {
  105. continue;
  106. }
  107. updated = true;
  108. FakeConsole.CursorTop = row;
  109. FakeConsole.CursorLeft = 0;
  110. _dirtyLines [row] = false;
  111. output.Clear ();
  112. for (int col = left; col < cols; col++)
  113. {
  114. lastCol = -1;
  115. var outputWidth = 0;
  116. for (; col < cols; col++)
  117. {
  118. if (!Contents! [row, col].IsDirty)
  119. {
  120. if (output.Length > 0)
  121. {
  122. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  123. }
  124. else if (lastCol == -1)
  125. {
  126. lastCol = col;
  127. }
  128. if (lastCol + 1 < cols)
  129. {
  130. lastCol++;
  131. }
  132. continue;
  133. }
  134. if (lastCol == -1)
  135. {
  136. lastCol = col;
  137. }
  138. Attribute attr = Contents [row, col].Attribute!.Value;
  139. // Performance: Only send the escape sequence if the attribute has changed.
  140. if (attr != redrawAttr)
  141. {
  142. redrawAttr = attr;
  143. FakeConsole.ForegroundColor = (ConsoleColor)attr.Foreground.GetClosestNamedColor16 ();
  144. FakeConsole.BackgroundColor = (ConsoleColor)attr.Background.GetClosestNamedColor16 ();
  145. }
  146. outputWidth++;
  147. Rune rune = Contents [row, col].Rune;
  148. output.Append (rune.ToString ());
  149. if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  150. {
  151. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  152. FakeConsole.CursorLeft--;
  153. }
  154. Contents [row, col].IsDirty = false;
  155. }
  156. }
  157. if (output.Length > 0)
  158. {
  159. FakeConsole.CursorTop = row;
  160. FakeConsole.CursorLeft = lastCol;
  161. foreach (char c in output.ToString ())
  162. {
  163. FakeConsole.Write (c);
  164. }
  165. }
  166. }
  167. FakeConsole.CursorTop = 0;
  168. FakeConsole.CursorLeft = 0;
  169. //SetCursorVisibility (savedVisibility);
  170. void WriteToConsole (StringBuilder outputSb, ref int lastColumn, int row, ref int outputWidth)
  171. {
  172. FakeConsole.CursorTop = row;
  173. FakeConsole.CursorLeft = lastColumn;
  174. foreach (char c in outputSb.ToString ())
  175. {
  176. FakeConsole.Write (c);
  177. }
  178. outputSb.Clear ();
  179. lastColumn += outputWidth;
  180. outputWidth = 0;
  181. }
  182. FakeConsole.CursorTop = savedRow;
  183. FakeConsole.CursorLeft = savedCol;
  184. FakeConsole.CursorVisible = savedCursorVisible;
  185. return updated;
  186. }
  187. #region Color Handling
  188. ///// <remarks>
  189. ///// In the FakeDriver, colors are encoded as an int; same as DotNetDriver
  190. ///// However, the foreground color is stored in the most significant 16 bits,
  191. ///// and the background color is stored in the least significant 16 bits.
  192. ///// </remarks>
  193. //public override Attribute MakeColor (Color foreground, Color background)
  194. //{
  195. // // Encode the colors into the int value.
  196. // return new Attribute (
  197. // foreground: foreground,
  198. // background: background
  199. // );
  200. //}
  201. #endregion
  202. private KeyCode MapKey (ConsoleKeyInfo keyInfo)
  203. {
  204. switch (keyInfo.Key)
  205. {
  206. case ConsoleKey.Escape:
  207. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Esc);
  208. case ConsoleKey.Tab:
  209. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Tab);
  210. case ConsoleKey.Clear:
  211. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Clear);
  212. case ConsoleKey.Home:
  213. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Home);
  214. case ConsoleKey.End:
  215. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.End);
  216. case ConsoleKey.LeftArrow:
  217. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.CursorLeft);
  218. case ConsoleKey.RightArrow:
  219. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.CursorRight);
  220. case ConsoleKey.UpArrow:
  221. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.CursorUp);
  222. case ConsoleKey.DownArrow:
  223. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.CursorDown);
  224. case ConsoleKey.PageUp:
  225. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.PageUp);
  226. case ConsoleKey.PageDown:
  227. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.PageDown);
  228. case ConsoleKey.Enter:
  229. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Enter);
  230. case ConsoleKey.Spacebar:
  231. return ConsoleKeyMapping.MapToKeyCodeModifiers (
  232. keyInfo.Modifiers,
  233. keyInfo.KeyChar == 0
  234. ? KeyCode.Space
  235. : (KeyCode)keyInfo.KeyChar
  236. );
  237. case ConsoleKey.Backspace:
  238. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Backspace);
  239. case ConsoleKey.Delete:
  240. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Delete);
  241. case ConsoleKey.Insert:
  242. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Insert);
  243. case ConsoleKey.PrintScreen:
  244. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.PrintScreen);
  245. case ConsoleKey.Oem1:
  246. case ConsoleKey.Oem2:
  247. case ConsoleKey.Oem3:
  248. case ConsoleKey.Oem4:
  249. case ConsoleKey.Oem5:
  250. case ConsoleKey.Oem6:
  251. case ConsoleKey.Oem7:
  252. case ConsoleKey.Oem8:
  253. case ConsoleKey.Oem102:
  254. case ConsoleKey.OemPeriod:
  255. case ConsoleKey.OemComma:
  256. case ConsoleKey.OemPlus:
  257. case ConsoleKey.OemMinus:
  258. if (keyInfo.KeyChar == 0)
  259. {
  260. return KeyCode.Null;
  261. }
  262. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  263. }
  264. ConsoleKey key = keyInfo.Key;
  265. if (key >= ConsoleKey.A && key <= ConsoleKey.Z)
  266. {
  267. int delta = key - ConsoleKey.A;
  268. if (keyInfo.KeyChar != (uint)key)
  269. {
  270. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.Key);
  271. }
  272. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)
  273. || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt)
  274. || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Shift))
  275. {
  276. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)KeyCode.A + delta));
  277. }
  278. char alphaBase = keyInfo.Modifiers != ConsoleModifiers.Shift ? 'A' : 'a';
  279. return (KeyCode)((uint)alphaBase + delta);
  280. }
  281. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  282. }
  283. private CursorVisibility _savedCursorVisibility;
  284. /// <inheritdoc/>
  285. public override bool GetCursorVisibility (out CursorVisibility visibility)
  286. {
  287. visibility = FakeConsole.CursorVisible
  288. ? CursorVisibility.Default
  289. : CursorVisibility.Invisible;
  290. return FakeConsole.CursorVisible;
  291. }
  292. /// <inheritdoc/>
  293. public override bool SetCursorVisibility (CursorVisibility visibility)
  294. {
  295. _savedCursorVisibility = visibility;
  296. return FakeConsole.CursorVisible = visibility == CursorVisibility.Default;
  297. }
  298. /// <inheritdoc/>
  299. private bool EnsureCursorVisibility ()
  300. {
  301. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  302. {
  303. GetCursorVisibility (out CursorVisibility cursorVisibility);
  304. _savedCursorVisibility = cursorVisibility;
  305. SetCursorVisibility (CursorVisibility.Invisible);
  306. return false;
  307. }
  308. SetCursorVisibility (_savedCursorVisibility);
  309. return FakeConsole.CursorVisible;
  310. }
  311. private AnsiResponseParser _parser = new ();
  312. /// <inheritdoc />
  313. internal override IAnsiResponseParser GetParser () => _parser;
  314. /// <summary>
  315. /// Sets the size of the fake console screen/buffer for testing purposes. This method updates
  316. /// the driver's dimensions (<see cref="ConsoleDriver.Cols"/> and <see cref="ConsoleDriver.Rows"/>),
  317. /// clears the contents, and fires the <see cref="ConsoleDriver.SizeChanged"/> event.
  318. /// </summary>
  319. /// <remarks>
  320. /// <para>
  321. /// This method is intended for use in unit tests to simulate terminal resize events.
  322. /// For FakeDriver, the buffer size and window size are always the same (there is no scrollback).
  323. /// </para>
  324. /// <para>
  325. /// When called, this method:
  326. /// <list type="number">
  327. /// <item>Updates the <see cref="FakeConsole"/> buffer size</item>
  328. /// <item>Sets <see cref="ConsoleDriver.Cols"/> and <see cref="ConsoleDriver.Rows"/> to the new dimensions</item>
  329. /// <item>Updates the window size to match</item>
  330. /// <item>Clears the screen contents</item>
  331. /// <item>Fires the <see cref="ConsoleDriver.SizeChanged"/> event</item>
  332. /// </list>
  333. /// </para>
  334. /// <para>
  335. /// <strong>Thread Safety:</strong> This method is not thread-safe. Tests using this method
  336. /// should ensure they are not accessing the driver concurrently.
  337. /// </para>
  338. /// <para>
  339. /// <strong>Relationship to Screen property:</strong> After calling this method,
  340. /// <see cref="ConsoleDriver.Screen"/> will return a rectangle with origin (0,0) and size (width, height).
  341. /// </para>
  342. /// </remarks>
  343. /// <param name="width">The new width in columns.</param>
  344. /// <param name="height">The new height in rows.</param>
  345. /// <example>
  346. /// <code>
  347. /// // Simulate a terminal resize to 120x30
  348. /// var driver = new FakeDriver();
  349. /// driver.SetBufferSize(120, 30);
  350. /// Assert.Equal(120, driver.Cols);
  351. /// Assert.Equal(30, driver.Rows);
  352. /// </code>
  353. /// </example>
  354. public void SetBufferSize (int width, int height)
  355. {
  356. FakeConsole.SetBufferSize (width, height);
  357. Cols = width;
  358. Rows = height;
  359. SetWindowSize (width, height);
  360. ProcessResize ();
  361. }
  362. /// <summary>
  363. /// Sets the window size of the fake console. For FakeDriver, this is functionally equivalent to
  364. /// <see cref="SetBufferSize"/> as the fake console does not support scrollback (window size == buffer size).
  365. /// </summary>
  366. /// <remarks>
  367. /// <para>
  368. /// This method exists for API compatibility with real console drivers, but in FakeDriver,
  369. /// the window size and buffer size are always kept in sync. Calling this method will update
  370. /// both the window and buffer to the specified size.
  371. /// </para>
  372. /// <para>
  373. /// Prefer using <see cref="SetBufferSize"/> for clarity in test code, as it more accurately
  374. /// describes what's happening (setting the entire screen size for the fake driver).
  375. /// </para>
  376. /// </remarks>
  377. /// <param name="width">The new width in columns.</param>
  378. /// <param name="height">The new height in rows.</param>
  379. /// <seealso cref="SetBufferSize"/>
  380. public void SetWindowSize (int width, int height)
  381. {
  382. FakeConsole.SetWindowSize (width, height);
  383. if (width != Cols || height != Rows)
  384. {
  385. SetBufferSize (width, height);
  386. Cols = width;
  387. Rows = height;
  388. }
  389. ProcessResize ();
  390. }
  391. public void SetWindowPosition (int left, int top)
  392. {
  393. if (Left > 0 || Top > 0)
  394. {
  395. Left = 0;
  396. Top = 0;
  397. }
  398. FakeConsole.SetWindowPosition (Left, Top);
  399. }
  400. private void ProcessResize ()
  401. {
  402. ResizeScreen ();
  403. ClearContents ();
  404. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  405. }
  406. public virtual void ResizeScreen ()
  407. {
  408. if (FakeConsole.WindowHeight > 0)
  409. {
  410. // Can raise an exception while it is still resizing.
  411. try
  412. {
  413. FakeConsole.CursorTop = 0;
  414. FakeConsole.CursorLeft = 0;
  415. FakeConsole.WindowTop = 0;
  416. FakeConsole.WindowLeft = 0;
  417. }
  418. catch (IOException)
  419. {
  420. return;
  421. }
  422. catch (ArgumentOutOfRangeException)
  423. {
  424. return;
  425. }
  426. }
  427. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  428. Clip = new (Screen);
  429. }
  430. public override void UpdateCursor ()
  431. {
  432. if (!EnsureCursorVisibility ())
  433. {
  434. return;
  435. }
  436. // Prevents the exception of size changing during resizing.
  437. try
  438. {
  439. // BUGBUG: Why is this using BufferWidth/Height and now Cols/Rows?
  440. if (Col >= 0 && Col < FakeConsole.BufferWidth && Row >= 0 && Row < FakeConsole.BufferHeight)
  441. {
  442. FakeConsole.SetCursorPosition (Col, Row);
  443. }
  444. }
  445. catch (IOException)
  446. { }
  447. catch (ArgumentOutOfRangeException)
  448. { }
  449. }
  450. #region Not Implemented
  451. public override void Suspend ()
  452. {
  453. //throw new NotImplementedException ();
  454. }
  455. #endregion
  456. public class FakeClipboard : ClipboardBase
  457. {
  458. public Exception? FakeException { get; set; }
  459. private readonly bool _isSupportedAlwaysFalse;
  460. private string _contents = string.Empty;
  461. public FakeClipboard (
  462. bool fakeClipboardThrowsNotSupportedException = false,
  463. bool isSupportedAlwaysFalse = false
  464. )
  465. {
  466. _isSupportedAlwaysFalse = isSupportedAlwaysFalse;
  467. if (fakeClipboardThrowsNotSupportedException)
  468. {
  469. FakeException = new NotSupportedException ("Fake clipboard exception");
  470. }
  471. }
  472. public override bool IsSupported => !_isSupportedAlwaysFalse;
  473. protected override string GetClipboardDataImpl ()
  474. {
  475. if (FakeException is { })
  476. {
  477. throw FakeException;
  478. }
  479. return _contents;
  480. }
  481. protected override void SetClipboardDataImpl (string? text)
  482. {
  483. if (FakeException is { })
  484. {
  485. throw FakeException;
  486. }
  487. _contents = text ?? throw new ArgumentNullException (nameof (text));
  488. }
  489. }
  490. #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
  491. }