FakeDriver.cs 18 KB

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