FakeDriver.cs 18 KB

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