FakeDriver.cs 15 KB

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