FakeDriver.cs 18 KB

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