FakeDriver.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. //
  2. // FakeDriver.cs: A fake ConsoleDriver for unit tests.
  3. //
  4. // Authors:
  5. // Charlie Kindel (github.com/tig)
  6. //
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Runtime.InteropServices;
  11. using System.Threading;
  12. using NStack;
  13. // Alias Console to MockConsole so we don't accidentally use Console
  14. using Console = Terminal.Gui.FakeConsole;
  15. namespace Terminal.Gui {
  16. /// <summary>
  17. /// Implements a mock ConsoleDriver for unit testing
  18. /// </summary>
  19. public class FakeDriver : ConsoleDriver {
  20. #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
  21. int cols, rows, left, top;
  22. public override int Cols => cols;
  23. public override int Rows => rows;
  24. // Only handling left here because not all terminals has a horizontal scroll bar.
  25. public override int Left => 0;
  26. public override int Top => 0;
  27. public override bool HeightAsBuffer { get; set; }
  28. public override IClipboard Clipboard { get; }
  29. // The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  30. int [,,] contents;
  31. bool [] dirtyLine;
  32. /// <summary>
  33. /// Assists with testing, the format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  34. /// </summary>
  35. public int [,,] Contents => contents;
  36. void UpdateOffscreen ()
  37. {
  38. int cols = Cols;
  39. int rows = Rows;
  40. contents = new int [rows, cols, 3];
  41. for (int r = 0; r < rows; r++) {
  42. for (int c = 0; c < cols; c++) {
  43. contents [r, c, 0] = ' ';
  44. contents [r, c, 1] = MakeColor (ConsoleColor.Gray, ConsoleColor.Black);
  45. contents [r, c, 2] = 0;
  46. }
  47. }
  48. dirtyLine = new bool [rows];
  49. for (int row = 0; row < rows; row++)
  50. dirtyLine [row] = true;
  51. }
  52. static bool sync = false;
  53. public FakeDriver ()
  54. {
  55. if (RuntimeInformation.IsOSPlatform (OSPlatform.Windows)) {
  56. Clipboard = new WindowsClipboard ();
  57. } else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
  58. Clipboard = new MacOSXClipboard ();
  59. } else {
  60. Clipboard = new CursesClipboard ();
  61. }
  62. }
  63. bool needMove;
  64. // Current row, and current col, tracked by Move/AddCh only
  65. int ccol, crow;
  66. public override void Move (int col, int row)
  67. {
  68. ccol = col;
  69. crow = row;
  70. if (Clip.Contains (col, row)) {
  71. FakeConsole.CursorTop = row;
  72. FakeConsole.CursorLeft = col;
  73. needMove = false;
  74. } else {
  75. FakeConsole.CursorTop = Clip.Y;
  76. FakeConsole.CursorLeft = Clip.X;
  77. needMove = true;
  78. }
  79. }
  80. public override void AddRune (Rune rune)
  81. {
  82. rune = MakePrintable (rune);
  83. if (Clip.Contains (ccol, crow)) {
  84. if (needMove) {
  85. //MockConsole.CursorLeft = ccol;
  86. //MockConsole.CursorTop = crow;
  87. needMove = false;
  88. }
  89. contents [crow, ccol, 0] = (int)(uint)rune;
  90. contents [crow, ccol, 1] = currentAttribute;
  91. contents [crow, ccol, 2] = 1;
  92. dirtyLine [crow] = true;
  93. } else
  94. needMove = true;
  95. ccol++;
  96. //if (ccol == Cols) {
  97. // ccol = 0;
  98. // if (crow + 1 < Rows)
  99. // crow++;
  100. //}
  101. if (sync)
  102. UpdateScreen ();
  103. }
  104. public override void AddStr (ustring str)
  105. {
  106. foreach (var rune in str)
  107. AddRune (rune);
  108. }
  109. public override void End ()
  110. {
  111. FakeConsole.ResetColor ();
  112. FakeConsole.Clear ();
  113. }
  114. static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  115. {
  116. // Encode the colors into the int value.
  117. return new Attribute (
  118. value: ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff),
  119. foreground: (Color)f,
  120. background: (Color)b
  121. );
  122. }
  123. public override void Init (Action terminalResized)
  124. {
  125. TerminalResized = terminalResized;
  126. cols = FakeConsole.WindowWidth = FakeConsole.BufferWidth = FakeConsole.WIDTH;
  127. rows = FakeConsole.WindowHeight = FakeConsole.BufferHeight = FakeConsole.HEIGHT;
  128. UpdateOffscreen ();
  129. Colors.TopLevel = new ColorScheme ();
  130. Colors.Base = new ColorScheme ();
  131. Colors.Dialog = new ColorScheme ();
  132. Colors.Menu = new ColorScheme ();
  133. Colors.Error = new ColorScheme ();
  134. Clip = new Rect (0, 0, Cols, Rows);
  135. Colors.TopLevel.Normal = MakeColor (ConsoleColor.Green, ConsoleColor.Black);
  136. Colors.TopLevel.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkCyan);
  137. Colors.TopLevel.HotNormal = MakeColor (ConsoleColor.DarkYellow, ConsoleColor.Black);
  138. Colors.TopLevel.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkCyan);
  139. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Blue);
  140. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  141. Colors.Base.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Blue);
  142. Colors.Base.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  143. // Focused,
  144. // Selected, Hot: Yellow on Black
  145. // Selected, text: white on black
  146. // Unselected, hot: yellow on cyan
  147. // unselected, text: same as unfocused
  148. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  149. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  150. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  151. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Cyan);
  152. Colors.Menu.Disabled = MakeColor (ConsoleColor.DarkGray, ConsoleColor.Cyan);
  153. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  154. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  155. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  156. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Cyan);
  157. Colors.Error.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Red);
  158. Colors.Error.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  159. Colors.Error.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Red);
  160. Colors.Error.HotFocus = Colors.Error.HotNormal;
  161. //MockConsole.Clear ();
  162. }
  163. public override Attribute MakeAttribute (Color fore, Color back)
  164. {
  165. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  166. }
  167. int redrawColor = -1;
  168. void SetColor (int color)
  169. {
  170. redrawColor = color;
  171. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  172. .OfType<ConsoleColor> ()
  173. .Select (s => (int)s);
  174. if (values.Contains (color & 0xffff)) {
  175. FakeConsole.BackgroundColor = (ConsoleColor)(color & 0xffff);
  176. }
  177. if (values.Contains ((color >> 16) & 0xffff)) {
  178. FakeConsole.ForegroundColor = (ConsoleColor)((color >> 16) & 0xffff);
  179. }
  180. }
  181. public override void UpdateScreen ()
  182. {
  183. int top = Top;
  184. int left = Left;
  185. int rows = Math.Min (Console.WindowHeight + top, Rows);
  186. int cols = Cols;
  187. FakeConsole.CursorTop = 0;
  188. FakeConsole.CursorLeft = 0;
  189. for (int row = top; row < rows; row++) {
  190. dirtyLine [row] = false;
  191. for (int col = left; col < cols; col++) {
  192. contents [row, col, 2] = 0;
  193. var color = contents [row, col, 1];
  194. if (color != redrawColor)
  195. SetColor (color);
  196. FakeConsole.Write ((char)contents [row, col, 0]);
  197. }
  198. }
  199. }
  200. public override void Refresh ()
  201. {
  202. int rows = Rows;
  203. int cols = Cols;
  204. var savedRow = FakeConsole.CursorTop;
  205. var savedCol = FakeConsole.CursorLeft;
  206. for (int row = 0; row < rows; row++) {
  207. if (!dirtyLine [row])
  208. continue;
  209. dirtyLine [row] = false;
  210. for (int col = 0; col < cols; col++) {
  211. if (contents [row, col, 2] != 1)
  212. continue;
  213. FakeConsole.CursorTop = row;
  214. FakeConsole.CursorLeft = col;
  215. for (; col < cols && contents [row, col, 2] == 1; col++) {
  216. var color = contents [row, col, 1];
  217. if (color != redrawColor)
  218. SetColor (color);
  219. FakeConsole.Write ((char)contents [row, col, 0]);
  220. contents [row, col, 2] = 0;
  221. }
  222. }
  223. }
  224. FakeConsole.CursorTop = savedRow;
  225. FakeConsole.CursorLeft = savedCol;
  226. }
  227. public override void UpdateCursor ()
  228. {
  229. //
  230. }
  231. public override void StartReportingMouseMoves ()
  232. {
  233. }
  234. public override void StopReportingMouseMoves ()
  235. {
  236. }
  237. public override void Suspend ()
  238. {
  239. }
  240. Attribute currentAttribute;
  241. public override void SetAttribute (Attribute c)
  242. {
  243. currentAttribute = c;
  244. }
  245. Key MapKey (ConsoleKeyInfo keyInfo)
  246. {
  247. switch (keyInfo.Key) {
  248. case ConsoleKey.Escape:
  249. return MapKeyModifiers (keyInfo, Key.Esc);
  250. case ConsoleKey.Tab:
  251. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  252. case ConsoleKey.Home:
  253. return MapKeyModifiers (keyInfo, Key.Home);
  254. case ConsoleKey.End:
  255. return MapKeyModifiers (keyInfo, Key.End);
  256. case ConsoleKey.LeftArrow:
  257. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  258. case ConsoleKey.RightArrow:
  259. return MapKeyModifiers (keyInfo, Key.CursorRight);
  260. case ConsoleKey.UpArrow:
  261. return MapKeyModifiers (keyInfo, Key.CursorUp);
  262. case ConsoleKey.DownArrow:
  263. return MapKeyModifiers (keyInfo, Key.CursorDown);
  264. case ConsoleKey.PageUp:
  265. return MapKeyModifiers (keyInfo, Key.PageUp);
  266. case ConsoleKey.PageDown:
  267. return MapKeyModifiers (keyInfo, Key.PageDown);
  268. case ConsoleKey.Enter:
  269. return MapKeyModifiers (keyInfo, Key.Enter);
  270. case ConsoleKey.Spacebar:
  271. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  272. case ConsoleKey.Backspace:
  273. return MapKeyModifiers (keyInfo, Key.Backspace);
  274. case ConsoleKey.Delete:
  275. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  276. case ConsoleKey.Insert:
  277. return MapKeyModifiers (keyInfo, Key.InsertChar);
  278. case ConsoleKey.Oem1:
  279. case ConsoleKey.Oem2:
  280. case ConsoleKey.Oem3:
  281. case ConsoleKey.Oem4:
  282. case ConsoleKey.Oem5:
  283. case ConsoleKey.Oem6:
  284. case ConsoleKey.Oem7:
  285. case ConsoleKey.Oem8:
  286. case ConsoleKey.Oem102:
  287. case ConsoleKey.OemPeriod:
  288. case ConsoleKey.OemComma:
  289. case ConsoleKey.OemPlus:
  290. case ConsoleKey.OemMinus:
  291. if (keyInfo.KeyChar == 0)
  292. return Key.Unknown;
  293. return (Key)((uint)keyInfo.KeyChar);
  294. }
  295. var key = keyInfo.Key;
  296. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  297. var delta = key - ConsoleKey.A;
  298. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  299. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  300. }
  301. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  302. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  303. }
  304. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  305. if (keyInfo.KeyChar == 0) {
  306. return (Key)(((uint)Key.AltMask | (uint)Key.CtrlMask) | ((uint)Key.A + delta));
  307. } else {
  308. return (Key)((uint)keyInfo.KeyChar);
  309. }
  310. }
  311. return (Key)((uint)keyInfo.KeyChar);
  312. }
  313. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  314. var delta = key - ConsoleKey.D0;
  315. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  316. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  317. }
  318. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  319. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  320. }
  321. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
  322. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  323. }
  324. return (Key)((uint)keyInfo.KeyChar);
  325. }
  326. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  327. var delta = key - ConsoleKey.F1;
  328. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  329. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  330. }
  331. return (Key)((uint)Key.F1 + delta);
  332. }
  333. if (keyInfo.KeyChar != 0) {
  334. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  335. }
  336. return (Key)(0xffffffff);
  337. }
  338. KeyModifiers keyModifiers;
  339. private Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  340. {
  341. Key keyMod = new Key ();
  342. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
  343. keyMod = Key.ShiftMask;
  344. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
  345. keyMod |= Key.CtrlMask;
  346. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
  347. keyMod |= Key.AltMask;
  348. return keyMod != Key.Null ? keyMod | key : key;
  349. }
  350. Action<KeyEvent> keyHandler;
  351. Action<KeyEvent> keyUpHandler;
  352. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  353. {
  354. this.keyHandler = keyHandler;
  355. this.keyUpHandler = keyUpHandler;
  356. // Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  357. (mainLoop.Driver as FakeMainLoop).KeyPressed += (consoleKey) => ProcessInput (consoleKey);
  358. }
  359. void ProcessInput (ConsoleKeyInfo consoleKey)
  360. {
  361. var map = MapKey (consoleKey);
  362. if (map == (Key)0xffffffff)
  363. return;
  364. if (keyModifiers == null) {
  365. keyModifiers = new KeyModifiers ();
  366. }
  367. if (consoleKey.Modifiers.HasFlag (ConsoleModifiers.Alt)) {
  368. keyModifiers.Alt = true;
  369. }
  370. if (consoleKey.Modifiers.HasFlag (ConsoleModifiers.Shift)) {
  371. keyModifiers.Shift = true;
  372. }
  373. if (consoleKey.Modifiers.HasFlag (ConsoleModifiers.Control)) {
  374. keyModifiers.Ctrl = true;
  375. }
  376. keyHandler (new KeyEvent (map, keyModifiers));
  377. keyUpHandler (new KeyEvent (map, keyModifiers));
  378. keyModifiers = new KeyModifiers ();
  379. }
  380. public override Attribute GetAttribute ()
  381. {
  382. return currentAttribute;
  383. }
  384. /// <inheritdoc/>
  385. public override bool GetCursorVisibility (out CursorVisibility visibility)
  386. {
  387. visibility = CursorVisibility.Default;
  388. return false;
  389. }
  390. /// <inheritdoc/>
  391. public override bool SetCursorVisibility (CursorVisibility visibility)
  392. {
  393. return false;
  394. }
  395. /// <inheritdoc/>
  396. public override bool EnsureCursorVisibility ()
  397. {
  398. return false;
  399. }
  400. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  401. {
  402. ProcessInput (new ConsoleKeyInfo (keyChar, key, shift, alt, control));
  403. }
  404. public void SetBufferSize (int width, int height)
  405. {
  406. cols = FakeConsole.WindowWidth = FakeConsole.BufferWidth = width;
  407. rows = FakeConsole.WindowHeight = FakeConsole.BufferHeight = height;
  408. ProcessResize ();
  409. }
  410. public void SetWindowSize (int width, int height)
  411. {
  412. FakeConsole.WindowWidth = width;
  413. FakeConsole.WindowHeight = height;
  414. if (width > cols || !HeightAsBuffer) {
  415. cols = FakeConsole.BufferWidth = width;
  416. }
  417. if (height > rows || !HeightAsBuffer) {
  418. rows = FakeConsole.BufferHeight = height;
  419. }
  420. ProcessResize ();
  421. }
  422. public void SetWindowPosition (int left, int top)
  423. {
  424. if (HeightAsBuffer) {
  425. this.left = FakeConsole.WindowLeft = Math.Max (Math.Min (left, Cols - FakeConsole.WindowWidth), 0);
  426. this.top = FakeConsole.WindowTop = Math.Max (Math.Min (top, Rows - Console.WindowHeight), 0);
  427. } else if (this.left > 0 || this.top > 0) {
  428. this.left = FakeConsole.WindowLeft = 0;
  429. this.top = FakeConsole.WindowTop = 0;
  430. }
  431. }
  432. void ProcessResize ()
  433. {
  434. ResizeScreen ();
  435. UpdateOffScreen ();
  436. TerminalResized?.Invoke ();
  437. }
  438. void ResizeScreen ()
  439. {
  440. if (!HeightAsBuffer) {
  441. if (Console.WindowHeight > 0) {
  442. // Can raise an exception while is still resizing.
  443. try {
  444. #pragma warning disable CA1416
  445. Console.CursorTop = 0;
  446. Console.CursorLeft = 0;
  447. Console.WindowTop = 0;
  448. Console.WindowLeft = 0;
  449. #pragma warning restore CA1416
  450. } catch (System.IO.IOException) {
  451. return;
  452. } catch (ArgumentOutOfRangeException) {
  453. return;
  454. }
  455. }
  456. } else {
  457. try {
  458. #pragma warning disable CA1416
  459. Console.WindowLeft = Math.Max (Math.Min (left, Cols - Console.WindowWidth), 0);
  460. Console.WindowTop = Math.Max (Math.Min (top, Rows - Console.WindowHeight), 0);
  461. #pragma warning restore CA1416
  462. } catch (Exception) {
  463. return;
  464. }
  465. }
  466. Clip = new Rect (0, 0, Cols, Rows);
  467. contents = new int [Rows, Cols, 3];
  468. dirtyLine = new bool [Rows];
  469. }
  470. void UpdateOffScreen ()
  471. {
  472. // Can raise an exception while is still resizing.
  473. try {
  474. for (int row = 0; row < rows; row++) {
  475. for (int c = 0; c < cols; c++) {
  476. contents [row, c, 0] = ' ';
  477. contents [row, c, 1] = (ushort)Colors.TopLevel.Normal;
  478. contents [row, c, 2] = 0;
  479. dirtyLine [row] = true;
  480. }
  481. }
  482. } catch (IndexOutOfRangeException) { }
  483. }
  484. #region Unused
  485. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  486. {
  487. }
  488. public override void SetColors (short foregroundColorId, short backgroundColorId)
  489. {
  490. throw new NotImplementedException ();
  491. }
  492. public override void CookMouse ()
  493. {
  494. }
  495. public override void UncookMouse ()
  496. {
  497. }
  498. #endregion
  499. #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
  500. }
  501. }