FakeDriver.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 bool UpdateScreen ()
  88. {
  89. bool updated = false;
  90. int savedRow = FakeConsole.CursorTop;
  91. int savedCol = FakeConsole.CursorLeft;
  92. bool savedCursorVisible = FakeConsole.CursorVisible;
  93. var top = 0;
  94. var left = 0;
  95. int rows = Rows;
  96. int cols = Cols;
  97. var output = new StringBuilder ();
  98. var redrawAttr = new Attribute ();
  99. int lastCol = -1;
  100. for (int row = top; row < rows; row++)
  101. {
  102. if (!_dirtyLines [row])
  103. {
  104. continue;
  105. }
  106. updated = true;
  107. FakeConsole.CursorTop = row;
  108. FakeConsole.CursorLeft = 0;
  109. _dirtyLines [row] = false;
  110. output.Clear ();
  111. for (int col = left; col < cols; col++)
  112. {
  113. lastCol = -1;
  114. var outputWidth = 0;
  115. for (; col < cols; col++)
  116. {
  117. if (!Contents [row, col].IsDirty)
  118. {
  119. if (output.Length > 0)
  120. {
  121. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  122. }
  123. else if (lastCol == -1)
  124. {
  125. lastCol = col;
  126. }
  127. if (lastCol + 1 < cols)
  128. {
  129. lastCol++;
  130. }
  131. continue;
  132. }
  133. if (lastCol == -1)
  134. {
  135. lastCol = col;
  136. }
  137. Attribute attr = Contents [row, col].Attribute.Value;
  138. // Performance: Only send the escape sequence if the attribute has changed.
  139. if (attr != redrawAttr)
  140. {
  141. redrawAttr = attr;
  142. FakeConsole.ForegroundColor = (ConsoleColor)attr.Foreground.GetClosestNamedColor16 ();
  143. FakeConsole.BackgroundColor = (ConsoleColor)attr.Background.GetClosestNamedColor16 ();
  144. }
  145. outputWidth++;
  146. Rune rune = Contents [row, col].Rune;
  147. output.Append (rune.ToString ());
  148. if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  149. {
  150. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  151. FakeConsole.CursorLeft--;
  152. }
  153. Contents [row, col].IsDirty = false;
  154. }
  155. }
  156. if (output.Length > 0)
  157. {
  158. FakeConsole.CursorTop = row;
  159. FakeConsole.CursorLeft = lastCol;
  160. foreach (char c in output.ToString ())
  161. {
  162. FakeConsole.Write (c);
  163. }
  164. }
  165. }
  166. FakeConsole.CursorTop = 0;
  167. FakeConsole.CursorLeft = 0;
  168. //SetCursorVisibility (savedVisibility);
  169. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  170. {
  171. FakeConsole.CursorTop = row;
  172. FakeConsole.CursorLeft = lastCol;
  173. foreach (char c in output.ToString ())
  174. {
  175. FakeConsole.Write (c);
  176. }
  177. output.Clear ();
  178. lastCol += outputWidth;
  179. outputWidth = 0;
  180. }
  181. FakeConsole.CursorTop = savedRow;
  182. FakeConsole.CursorLeft = savedCol;
  183. FakeConsole.CursorVisible = savedCursorVisible;
  184. return updated;
  185. }
  186. #region Color Handling
  187. ///// <remarks>
  188. ///// In the FakeDriver, colors are encoded as an int; same as NetDriver
  189. ///// However, the foreground color is stored in the most significant 16 bits,
  190. ///// and the background color is stored in the least significant 16 bits.
  191. ///// </remarks>
  192. //public override Attribute MakeColor (Color foreground, Color background)
  193. //{
  194. // // Encode the colors into the int value.
  195. // return new Attribute (
  196. // platformColor: 0,//((((int)foreground.ColorName) & 0xffff) << 16) | (((int)background.ColorName) & 0xffff),
  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. private void MockKeyPressedHandler (ConsoleKeyInfo consoleKeyInfo)
  285. {
  286. if (consoleKeyInfo.Key == ConsoleKey.Packet)
  287. {
  288. consoleKeyInfo = ConsoleKeyMapping.DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  289. }
  290. KeyCode map = MapKey (consoleKeyInfo);
  291. OnKeyDown (new Key (map));
  292. OnKeyUp (new Key (map));
  293. //OnKeyPressed (new KeyEventArgs (map));
  294. }
  295. /// <inheritdoc/>
  296. public override bool GetCursorVisibility (out CursorVisibility visibility)
  297. {
  298. visibility = FakeConsole.CursorVisible
  299. ? CursorVisibility.Default
  300. : CursorVisibility.Invisible;
  301. return FakeConsole.CursorVisible;
  302. }
  303. /// <inheritdoc/>
  304. public override bool SetCursorVisibility (CursorVisibility visibility)
  305. {
  306. _savedCursorVisibility = visibility;
  307. return FakeConsole.CursorVisible = visibility == CursorVisibility.Default;
  308. }
  309. /// <inheritdoc/>
  310. public override bool EnsureCursorVisibility ()
  311. {
  312. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  313. {
  314. GetCursorVisibility (out CursorVisibility cursorVisibility);
  315. _savedCursorVisibility = cursorVisibility;
  316. SetCursorVisibility (CursorVisibility.Invisible);
  317. return false;
  318. }
  319. SetCursorVisibility (_savedCursorVisibility);
  320. return FakeConsole.CursorVisible;
  321. }
  322. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  323. {
  324. MockKeyPressedHandler (new ConsoleKeyInfo (keyChar, key, shift, alt, control));
  325. }
  326. public void SetBufferSize (int width, int height)
  327. {
  328. FakeConsole.SetBufferSize (width, height);
  329. Cols = width;
  330. Rows = height;
  331. SetWindowSize (width, height);
  332. ProcessResize ();
  333. }
  334. public void SetWindowSize (int width, int height)
  335. {
  336. FakeConsole.SetWindowSize (width, height);
  337. if (width != Cols || height != Rows)
  338. {
  339. SetBufferSize (width, height);
  340. Cols = width;
  341. Rows = height;
  342. }
  343. ProcessResize ();
  344. }
  345. public void SetWindowPosition (int left, int top)
  346. {
  347. if (Left > 0 || Top > 0)
  348. {
  349. Left = 0;
  350. Top = 0;
  351. }
  352. FakeConsole.SetWindowPosition (Left, Top);
  353. }
  354. private void ProcessResize ()
  355. {
  356. ResizeScreen ();
  357. ClearContents ();
  358. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  359. }
  360. public virtual void ResizeScreen ()
  361. {
  362. if (FakeConsole.WindowHeight > 0)
  363. {
  364. // Can raise an exception while it is still resizing.
  365. try
  366. {
  367. FakeConsole.CursorTop = 0;
  368. FakeConsole.CursorLeft = 0;
  369. FakeConsole.WindowTop = 0;
  370. FakeConsole.WindowLeft = 0;
  371. }
  372. catch (IOException)
  373. {
  374. return;
  375. }
  376. catch (ArgumentOutOfRangeException)
  377. {
  378. return;
  379. }
  380. }
  381. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  382. Clip = new (new (0, 0, Cols, Rows));
  383. }
  384. public override void UpdateCursor ()
  385. {
  386. if (!EnsureCursorVisibility ())
  387. {
  388. return;
  389. }
  390. // Prevents the exception of size changing during resizing.
  391. try
  392. {
  393. // BUGBUG: Why is this using BufferWidth/Height and now Cols/Rows?
  394. if (Col >= 0 && Col < FakeConsole.BufferWidth && Row >= 0 && Row < FakeConsole.BufferHeight)
  395. {
  396. FakeConsole.SetCursorPosition (Col, Row);
  397. }
  398. }
  399. catch (IOException)
  400. { }
  401. catch (ArgumentOutOfRangeException)
  402. { }
  403. }
  404. #region Not Implemented
  405. public override void Suspend ()
  406. {
  407. //throw new NotImplementedException ();
  408. }
  409. #endregion
  410. public class FakeClipboard : ClipboardBase
  411. {
  412. public Exception FakeException;
  413. private readonly bool _isSupportedAlwaysFalse;
  414. private string _contents = string.Empty;
  415. public FakeClipboard (
  416. bool fakeClipboardThrowsNotSupportedException = false,
  417. bool isSupportedAlwaysFalse = false
  418. )
  419. {
  420. _isSupportedAlwaysFalse = isSupportedAlwaysFalse;
  421. if (fakeClipboardThrowsNotSupportedException)
  422. {
  423. FakeException = new NotSupportedException ("Fake clipboard exception");
  424. }
  425. }
  426. public override bool IsSupported => !_isSupportedAlwaysFalse;
  427. protected override string GetClipboardDataImpl ()
  428. {
  429. if (FakeException is { })
  430. {
  431. throw FakeException;
  432. }
  433. return _contents;
  434. }
  435. protected override void SetClipboardDataImpl (string text)
  436. {
  437. if (text is null)
  438. {
  439. throw new ArgumentNullException (nameof (text));
  440. }
  441. if (FakeException is { })
  442. {
  443. throw FakeException;
  444. }
  445. _contents = text;
  446. }
  447. }
  448. #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
  449. }