FakeDriver.cs 16 KB

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