FakeDriver.cs 13 KB

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