FakeDriver.cs 16 KB

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