FakeDriver.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. private FakeMainLoop? _mainLoopDriver;
  80. public override MainLoop Init ()
  81. {
  82. FakeConsole.MockKeyPresses.Clear ();
  83. Cols = FakeConsole.WindowWidth = FakeConsole.BufferWidth = FakeConsole.WIDTH;
  84. Rows = FakeConsole.WindowHeight = FakeConsole.BufferHeight = FakeConsole.HEIGHT;
  85. FakeConsole.Clear ();
  86. ResizeScreen ();
  87. CurrentAttribute = new Attribute (Color.White, Color.Black);
  88. //ClearContents ();
  89. _mainLoopDriver = new FakeMainLoop (this);
  90. _mainLoopDriver.MockKeyPressed = MockKeyPressedHandler;
  91. return new MainLoop (_mainLoopDriver);
  92. }
  93. public override bool UpdateScreen ()
  94. {
  95. bool updated = false;
  96. int savedRow = FakeConsole.CursorTop;
  97. int savedCol = FakeConsole.CursorLeft;
  98. bool savedCursorVisible = FakeConsole.CursorVisible;
  99. var top = 0;
  100. var left = 0;
  101. int rows = Rows;
  102. int cols = Cols;
  103. var output = new StringBuilder ();
  104. var redrawAttr = new Attribute ();
  105. int lastCol = -1;
  106. for (int row = top; row < rows; row++)
  107. {
  108. if (!_dirtyLines! [row])
  109. {
  110. continue;
  111. }
  112. updated = true;
  113. FakeConsole.CursorTop = row;
  114. FakeConsole.CursorLeft = 0;
  115. _dirtyLines [row] = false;
  116. output.Clear ();
  117. for (int col = left; col < cols; col++)
  118. {
  119. lastCol = -1;
  120. var outputWidth = 0;
  121. for (; col < cols; col++)
  122. {
  123. if (!Contents! [row, col].IsDirty)
  124. {
  125. if (output.Length > 0)
  126. {
  127. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  128. }
  129. else if (lastCol == -1)
  130. {
  131. lastCol = col;
  132. }
  133. if (lastCol + 1 < cols)
  134. {
  135. lastCol++;
  136. }
  137. continue;
  138. }
  139. if (lastCol == -1)
  140. {
  141. lastCol = col;
  142. }
  143. Attribute attr = Contents [row, col].Attribute!.Value;
  144. // Performance: Only send the escape sequence if the attribute has changed.
  145. if (attr != redrawAttr)
  146. {
  147. redrawAttr = attr;
  148. FakeConsole.ForegroundColor = (ConsoleColor)attr.Foreground.GetClosestNamedColor16 ();
  149. FakeConsole.BackgroundColor = (ConsoleColor)attr.Background.GetClosestNamedColor16 ();
  150. }
  151. outputWidth++;
  152. Rune rune = Contents [row, col].Rune;
  153. output.Append (rune.ToString ());
  154. if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  155. {
  156. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  157. FakeConsole.CursorLeft--;
  158. }
  159. Contents [row, col].IsDirty = false;
  160. }
  161. }
  162. if (output.Length > 0)
  163. {
  164. FakeConsole.CursorTop = row;
  165. FakeConsole.CursorLeft = lastCol;
  166. foreach (char c in output.ToString ())
  167. {
  168. FakeConsole.Write (c);
  169. }
  170. }
  171. }
  172. FakeConsole.CursorTop = 0;
  173. FakeConsole.CursorLeft = 0;
  174. //SetCursorVisibility (savedVisibility);
  175. void WriteToConsole (StringBuilder outputSb, ref int lastColumn, int row, ref int outputWidth)
  176. {
  177. FakeConsole.CursorTop = row;
  178. FakeConsole.CursorLeft = lastColumn;
  179. foreach (char c in outputSb.ToString ())
  180. {
  181. FakeConsole.Write (c);
  182. }
  183. outputSb.Clear ();
  184. lastColumn += outputWidth;
  185. outputWidth = 0;
  186. }
  187. FakeConsole.CursorTop = savedRow;
  188. FakeConsole.CursorLeft = savedCol;
  189. FakeConsole.CursorVisible = savedCursorVisible;
  190. return updated;
  191. }
  192. #region Color Handling
  193. ///// <remarks>
  194. ///// In the FakeDriver, colors are encoded as an int; same as DotNetDriver
  195. ///// However, the foreground color is stored in the most significant 16 bits,
  196. ///// and the background color is stored in the least significant 16 bits.
  197. ///// </remarks>
  198. //public override Attribute MakeColor (Color foreground, Color background)
  199. //{
  200. // // Encode the colors into the int value.
  201. // return new Attribute (
  202. // foreground: foreground,
  203. // background: background
  204. // );
  205. //}
  206. #endregion
  207. private KeyCode MapKey (ConsoleKeyInfo keyInfo)
  208. {
  209. switch (keyInfo.Key)
  210. {
  211. case ConsoleKey.Escape:
  212. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Esc);
  213. case ConsoleKey.Tab:
  214. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Tab);
  215. case ConsoleKey.Clear:
  216. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Clear);
  217. case ConsoleKey.Home:
  218. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Home);
  219. case ConsoleKey.End:
  220. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.End);
  221. case ConsoleKey.LeftArrow:
  222. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.CursorLeft);
  223. case ConsoleKey.RightArrow:
  224. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.CursorRight);
  225. case ConsoleKey.UpArrow:
  226. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.CursorUp);
  227. case ConsoleKey.DownArrow:
  228. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.CursorDown);
  229. case ConsoleKey.PageUp:
  230. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.PageUp);
  231. case ConsoleKey.PageDown:
  232. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.PageDown);
  233. case ConsoleKey.Enter:
  234. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Enter);
  235. case ConsoleKey.Spacebar:
  236. return ConsoleKeyMapping.MapToKeyCodeModifiers (
  237. keyInfo.Modifiers,
  238. keyInfo.KeyChar == 0
  239. ? KeyCode.Space
  240. : (KeyCode)keyInfo.KeyChar
  241. );
  242. case ConsoleKey.Backspace:
  243. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Backspace);
  244. case ConsoleKey.Delete:
  245. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Delete);
  246. case ConsoleKey.Insert:
  247. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.Insert);
  248. case ConsoleKey.PrintScreen:
  249. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode.PrintScreen);
  250. case ConsoleKey.Oem1:
  251. case ConsoleKey.Oem2:
  252. case ConsoleKey.Oem3:
  253. case ConsoleKey.Oem4:
  254. case ConsoleKey.Oem5:
  255. case ConsoleKey.Oem6:
  256. case ConsoleKey.Oem7:
  257. case ConsoleKey.Oem8:
  258. case ConsoleKey.Oem102:
  259. case ConsoleKey.OemPeriod:
  260. case ConsoleKey.OemComma:
  261. case ConsoleKey.OemPlus:
  262. case ConsoleKey.OemMinus:
  263. if (keyInfo.KeyChar == 0)
  264. {
  265. return KeyCode.Null;
  266. }
  267. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  268. }
  269. ConsoleKey key = keyInfo.Key;
  270. if (key >= ConsoleKey.A && key <= ConsoleKey.Z)
  271. {
  272. int delta = key - ConsoleKey.A;
  273. if (keyInfo.KeyChar != (uint)key)
  274. {
  275. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.Key);
  276. }
  277. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)
  278. || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt)
  279. || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Shift))
  280. {
  281. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)KeyCode.A + delta));
  282. }
  283. char alphaBase = keyInfo.Modifiers != ConsoleModifiers.Shift ? 'A' : 'a';
  284. return (KeyCode)((uint)alphaBase + delta);
  285. }
  286. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  287. }
  288. private CursorVisibility _savedCursorVisibility;
  289. private void MockKeyPressedHandler (ConsoleKeyInfo consoleKeyInfo)
  290. {
  291. if (consoleKeyInfo.Key == ConsoleKey.Packet)
  292. {
  293. consoleKeyInfo = ConsoleKeyMapping.DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  294. }
  295. KeyCode map = MapKey (consoleKeyInfo);
  296. if (IsValidInput (map, out map))
  297. {
  298. OnKeyDown (new (map));
  299. OnKeyUp (new (map));
  300. }
  301. //OnKeyPressed (new KeyEventArgs (map));
  302. }
  303. /// <inheritdoc/>
  304. public override bool GetCursorVisibility (out CursorVisibility visibility)
  305. {
  306. visibility = FakeConsole.CursorVisible
  307. ? CursorVisibility.Default
  308. : CursorVisibility.Invisible;
  309. return FakeConsole.CursorVisible;
  310. }
  311. /// <inheritdoc/>
  312. public override bool SetCursorVisibility (CursorVisibility visibility)
  313. {
  314. _savedCursorVisibility = visibility;
  315. return FakeConsole.CursorVisible = visibility == CursorVisibility.Default;
  316. }
  317. /// <inheritdoc/>
  318. private bool EnsureCursorVisibility ()
  319. {
  320. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  321. {
  322. GetCursorVisibility (out CursorVisibility cursorVisibility);
  323. _savedCursorVisibility = cursorVisibility;
  324. SetCursorVisibility (CursorVisibility.Invisible);
  325. return false;
  326. }
  327. SetCursorVisibility (_savedCursorVisibility);
  328. return FakeConsole.CursorVisible;
  329. }
  330. private AnsiResponseParser _parser = new ();
  331. /// <inheritdoc />
  332. internal override IAnsiResponseParser GetParser () => _parser;
  333. public void SetBufferSize (int width, int height)
  334. {
  335. FakeConsole.SetBufferSize (width, height);
  336. Cols = width;
  337. Rows = height;
  338. SetWindowSize (width, height);
  339. ProcessResize ();
  340. }
  341. public void SetWindowSize (int width, int height)
  342. {
  343. FakeConsole.SetWindowSize (width, height);
  344. if (width != Cols || height != Rows)
  345. {
  346. SetBufferSize (width, height);
  347. Cols = width;
  348. Rows = height;
  349. }
  350. ProcessResize ();
  351. }
  352. public void SetWindowPosition (int left, int top)
  353. {
  354. if (Left > 0 || Top > 0)
  355. {
  356. Left = 0;
  357. Top = 0;
  358. }
  359. FakeConsole.SetWindowPosition (Left, Top);
  360. }
  361. private void ProcessResize ()
  362. {
  363. ResizeScreen ();
  364. ClearContents ();
  365. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  366. }
  367. public virtual void ResizeScreen ()
  368. {
  369. if (FakeConsole.WindowHeight > 0)
  370. {
  371. // Can raise an exception while it is still resizing.
  372. try
  373. {
  374. FakeConsole.CursorTop = 0;
  375. FakeConsole.CursorLeft = 0;
  376. FakeConsole.WindowTop = 0;
  377. FakeConsole.WindowLeft = 0;
  378. }
  379. catch (IOException)
  380. {
  381. return;
  382. }
  383. catch (ArgumentOutOfRangeException)
  384. {
  385. return;
  386. }
  387. }
  388. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  389. Clip = new (Screen);
  390. }
  391. public override void UpdateCursor ()
  392. {
  393. if (!EnsureCursorVisibility ())
  394. {
  395. return;
  396. }
  397. // Prevents the exception of size changing during resizing.
  398. try
  399. {
  400. // BUGBUG: Why is this using BufferWidth/Height and now Cols/Rows?
  401. if (Col >= 0 && Col < FakeConsole.BufferWidth && Row >= 0 && Row < FakeConsole.BufferHeight)
  402. {
  403. FakeConsole.SetCursorPosition (Col, Row);
  404. }
  405. }
  406. catch (IOException)
  407. { }
  408. catch (ArgumentOutOfRangeException)
  409. { }
  410. }
  411. #region Not Implemented
  412. public override void Suspend ()
  413. {
  414. //throw new NotImplementedException ();
  415. }
  416. #endregion
  417. public class FakeClipboard : ClipboardBase
  418. {
  419. public Exception? FakeException { get; set; }
  420. private readonly bool _isSupportedAlwaysFalse;
  421. private string _contents = string.Empty;
  422. public FakeClipboard (
  423. bool fakeClipboardThrowsNotSupportedException = false,
  424. bool isSupportedAlwaysFalse = false
  425. )
  426. {
  427. _isSupportedAlwaysFalse = isSupportedAlwaysFalse;
  428. if (fakeClipboardThrowsNotSupportedException)
  429. {
  430. FakeException = new NotSupportedException ("Fake clipboard exception");
  431. }
  432. }
  433. public override bool IsSupported => !_isSupportedAlwaysFalse;
  434. protected override string GetClipboardDataImpl ()
  435. {
  436. if (FakeException is { })
  437. {
  438. throw FakeException;
  439. }
  440. return _contents;
  441. }
  442. protected override void SetClipboardDataImpl (string? text)
  443. {
  444. if (FakeException is { })
  445. {
  446. throw FakeException;
  447. }
  448. _contents = text ?? throw new ArgumentNullException (nameof (text));
  449. }
  450. }
  451. #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
  452. }