FakeDriver.cs 13 KB

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