NetDriver.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. //
  2. // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient.
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using NStack;
  13. namespace Terminal.Gui {
  14. internal class NetDriver : ConsoleDriver {
  15. int cols, rows, top;
  16. public override int Cols => cols;
  17. public override int Rows => rows;
  18. public override int Top => top;
  19. public override bool HeightAsBuffer { get; set; }
  20. // The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  21. int [,,] contents;
  22. bool [] dirtyLine;
  23. static bool sync = false;
  24. // Current row, and current col, tracked by Move/AddCh only
  25. int ccol, crow;
  26. public override void Move (int col, int row)
  27. {
  28. ccol = col;
  29. crow = row;
  30. }
  31. public override void AddRune (Rune rune)
  32. {
  33. if (contents.Length != Rows * Cols * 3) {
  34. return;
  35. }
  36. rune = MakePrintable (rune);
  37. var runeWidth = Rune.ColumnWidth (rune);
  38. if (Clip.Contains (ccol, crow) && ccol + Math.Max (runeWidth, 1) <= Cols) {
  39. contents [crow, ccol, 0] = (int)(uint)rune;
  40. contents [crow, ccol, 1] = currentAttribute;
  41. contents [crow, ccol, 2] = 1;
  42. dirtyLine [crow] = true;
  43. ccol++;
  44. if (runeWidth > 1) {
  45. for (int i = 1; i < runeWidth; i++) {
  46. if (ccol < cols) {
  47. contents [crow, ccol, 2] = 0;
  48. } else {
  49. break;
  50. }
  51. ccol++;
  52. }
  53. }
  54. } else if (ccol < cols && crow < rows) {
  55. contents [crow, ccol, 2] = 1;
  56. dirtyLine [crow] = true;
  57. }
  58. //if (ccol == Cols) {
  59. // ccol = 0;
  60. // if (crow + 1 < Rows)
  61. // crow++;
  62. //}
  63. if (sync) {
  64. UpdateScreen ();
  65. }
  66. }
  67. public override void AddStr (ustring str)
  68. {
  69. foreach (var rune in str)
  70. AddRune (rune);
  71. }
  72. public override void End ()
  73. {
  74. Console.ResetColor ();
  75. Clear ();
  76. }
  77. void Clear ()
  78. {
  79. if (Rows > 0) {
  80. Console.Clear ();
  81. }
  82. }
  83. static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  84. {
  85. // Encode the colors into the int value.
  86. return new Attribute (
  87. value: ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff),
  88. foreground: (Color)f,
  89. background: (Color)b
  90. );
  91. }
  92. bool isWinPlatform;
  93. public override void Init (Action terminalResized)
  94. {
  95. TerminalResized = terminalResized;
  96. Console.TreatControlCAsInput = true;
  97. var p = Environment.OSVersion.Platform;
  98. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) {
  99. isWinPlatform = true;
  100. }
  101. cols = Console.WindowWidth;
  102. rows = Console.WindowHeight;
  103. Clear ();
  104. ResizeScreen ();
  105. UpdateOffScreen ();
  106. Colors.TopLevel = new ColorScheme ();
  107. Colors.Base = new ColorScheme ();
  108. Colors.Dialog = new ColorScheme ();
  109. Colors.Menu = new ColorScheme ();
  110. Colors.Error = new ColorScheme ();
  111. Colors.TopLevel.Normal = MakeColor (ConsoleColor.Green, ConsoleColor.Black);
  112. Colors.TopLevel.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkCyan);
  113. Colors.TopLevel.HotNormal = MakeColor (ConsoleColor.DarkYellow, ConsoleColor.Black);
  114. Colors.TopLevel.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkCyan);
  115. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Blue);
  116. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  117. Colors.Base.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Blue);
  118. Colors.Base.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  119. // Focused,
  120. // Selected, Hot: Yellow on Black
  121. // Selected, text: white on black
  122. // Unselected, hot: yellow on cyan
  123. // unselected, text: same as unfocused
  124. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  125. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  126. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  127. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Cyan);
  128. Colors.Menu.Disabled = MakeColor (ConsoleColor.DarkGray, ConsoleColor.Cyan);
  129. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  130. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  131. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  132. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Cyan);
  133. Colors.Error.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Red);
  134. Colors.Error.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  135. Colors.Error.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Red);
  136. Colors.Error.HotFocus = Colors.Error.HotNormal;
  137. }
  138. void ResizeScreen ()
  139. {
  140. if (!HeightAsBuffer) {
  141. if (Console.WindowHeight > 0) {
  142. // Can raise an exception while is still resizing.
  143. try {
  144. // Not supported on Unix.
  145. if (isWinPlatform) {
  146. #pragma warning disable CA1416
  147. Console.CursorTop = 0;
  148. Console.CursorLeft = 0;
  149. Console.WindowTop = 0;
  150. Console.WindowLeft = 0;
  151. Console.SetBufferSize (Cols, Rows);
  152. #pragma warning restore CA1416
  153. } else {
  154. //Console.Out.Write ($"\x1b[8;{Console.WindowHeight};{Console.WindowWidth}t");
  155. Console.Out.Write ($"\x1b[0;0" +
  156. $";{Rows};{Cols}w");
  157. }
  158. } catch (System.IO.IOException) {
  159. return;
  160. } catch (ArgumentOutOfRangeException) {
  161. return;
  162. }
  163. }
  164. } else {
  165. if (isWinPlatform && Console.WindowHeight > 0) {
  166. // Can raise an exception while is still resizing.
  167. try {
  168. #pragma warning disable CA1416
  169. Console.WindowTop = Math.Max (Math.Min (top, Rows - Console.WindowHeight), 0);
  170. #pragma warning restore CA1416
  171. } catch (Exception) {
  172. return;
  173. }
  174. } else {
  175. Console.Out.Write ($"\x1b[{top};{Console.WindowLeft}" +
  176. $";{Rows};{Cols}w");
  177. }
  178. }
  179. Clip = new Rect (0, 0, Cols, Rows);
  180. contents = new int [Rows, Cols, 3];
  181. dirtyLine = new bool [Rows];
  182. }
  183. void UpdateOffScreen ()
  184. {
  185. // Can raise an exception while is still resizing.
  186. try {
  187. for (int row = 0; row < rows; row++) {
  188. for (int c = 0; c < cols; c++) {
  189. contents [row, c, 0] = ' ';
  190. contents [row, c, 1] = (ushort)Colors.TopLevel.Normal;
  191. contents [row, c, 2] = 0;
  192. dirtyLine [row] = true;
  193. }
  194. }
  195. } catch (IndexOutOfRangeException) { }
  196. winChanging = false;
  197. }
  198. public override Attribute MakeAttribute (Color fore, Color back)
  199. {
  200. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  201. }
  202. int redrawColor = -1;
  203. void SetColor (int color)
  204. {
  205. redrawColor = color;
  206. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  207. .OfType<ConsoleColor> ()
  208. .Select (s => (int)s);
  209. if (values.Contains (color & 0xffff)) {
  210. Console.BackgroundColor = (ConsoleColor)(color & 0xffff);
  211. }
  212. if (values.Contains ((color >> 16) & 0xffff)) {
  213. Console.ForegroundColor = (ConsoleColor)((color >> 16) & 0xffff);
  214. }
  215. }
  216. public override void UpdateScreen ()
  217. {
  218. if (winChanging || Console.WindowHeight == 0 || contents.Length != Rows * Cols * 3
  219. || (!HeightAsBuffer && Rows != Console.WindowHeight)
  220. || (HeightAsBuffer && Rows != Console.BufferHeight)) {
  221. return;
  222. }
  223. int top = Top;
  224. int rows = Math.Min (Console.WindowHeight + top, Rows);
  225. int cols = Cols;
  226. for (int row = top; row < rows; row++) {
  227. if (!dirtyLine [row]) {
  228. continue;
  229. }
  230. dirtyLine [row] = false;
  231. for (int col = 0; col < cols; col++) {
  232. if (contents [row, col, 2] != 1) {
  233. continue;
  234. }
  235. if (Console.WindowHeight > 0) {
  236. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  237. try {
  238. Console.SetCursorPosition (col, row);
  239. } catch (Exception) {
  240. return;
  241. }
  242. }
  243. for (; col < cols && contents [row, col, 2] == 1; col++) {
  244. // Needed for the .Net Framework.
  245. if (row == rows - 1 && col == cols - 1) {
  246. break;
  247. }
  248. var color = contents [row, col, 1];
  249. if (color != redrawColor) {
  250. SetColor (color);
  251. }
  252. Console.Write ((char)contents [row, col, 0]);
  253. contents [row, col, 2] = 0;
  254. }
  255. }
  256. }
  257. UpdateCursor ();
  258. }
  259. public override void Refresh ()
  260. {
  261. UpdateScreen ();
  262. }
  263. public override void UpdateCursor ()
  264. {
  265. // Prevents the exception of size changing during resizing.
  266. try {
  267. if (ccol >= 0 && ccol <= cols && crow >= 0 && crow <= rows) {
  268. Console.SetCursorPosition (ccol, crow);
  269. }
  270. } catch (System.IO.IOException) {
  271. } catch (ArgumentOutOfRangeException) {
  272. }
  273. }
  274. public override void StartReportingMouseMoves ()
  275. {
  276. }
  277. public override void StopReportingMouseMoves ()
  278. {
  279. }
  280. public override void Suspend ()
  281. {
  282. }
  283. int currentAttribute;
  284. public override void SetAttribute (Attribute c)
  285. {
  286. currentAttribute = c.Value;
  287. }
  288. Key MapKey (ConsoleKeyInfo keyInfo)
  289. {
  290. MapKeyModifiers (keyInfo, (Key)keyInfo.Key);
  291. switch (keyInfo.Key) {
  292. case ConsoleKey.Escape:
  293. return MapKeyModifiers (keyInfo, Key.Esc);
  294. case ConsoleKey.Tab:
  295. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  296. case ConsoleKey.Home:
  297. return MapKeyModifiers (keyInfo, Key.Home);
  298. case ConsoleKey.End:
  299. return MapKeyModifiers (keyInfo, Key.End);
  300. case ConsoleKey.LeftArrow:
  301. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  302. case ConsoleKey.RightArrow:
  303. return MapKeyModifiers (keyInfo, Key.CursorRight);
  304. case ConsoleKey.UpArrow:
  305. return MapKeyModifiers (keyInfo, Key.CursorUp);
  306. case ConsoleKey.DownArrow:
  307. return MapKeyModifiers (keyInfo, Key.CursorDown);
  308. case ConsoleKey.PageUp:
  309. return MapKeyModifiers (keyInfo, Key.PageUp);
  310. case ConsoleKey.PageDown:
  311. return MapKeyModifiers (keyInfo, Key.PageDown);
  312. case ConsoleKey.Enter:
  313. return MapKeyModifiers (keyInfo, Key.Enter);
  314. case ConsoleKey.Spacebar:
  315. return MapKeyModifiers (keyInfo, Key.Space);
  316. case ConsoleKey.Backspace:
  317. return MapKeyModifiers (keyInfo, Key.Backspace);
  318. case ConsoleKey.Delete:
  319. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  320. case ConsoleKey.Insert:
  321. return MapKeyModifiers (keyInfo, Key.InsertChar);
  322. case ConsoleKey.Oem1:
  323. case ConsoleKey.Oem2:
  324. case ConsoleKey.Oem3:
  325. case ConsoleKey.Oem4:
  326. case ConsoleKey.Oem5:
  327. case ConsoleKey.Oem6:
  328. case ConsoleKey.Oem7:
  329. case ConsoleKey.Oem8:
  330. case ConsoleKey.Oem102:
  331. case ConsoleKey.OemPeriod:
  332. case ConsoleKey.OemComma:
  333. case ConsoleKey.OemPlus:
  334. case ConsoleKey.OemMinus:
  335. return (Key)((uint)keyInfo.KeyChar);
  336. }
  337. var key = keyInfo.Key;
  338. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  339. var delta = key - ConsoleKey.A;
  340. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  341. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  342. }
  343. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  344. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  345. }
  346. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  347. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  348. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  349. }
  350. }
  351. return (Key)((uint)keyInfo.KeyChar);
  352. }
  353. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  354. var delta = key - ConsoleKey.D0;
  355. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  356. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  357. }
  358. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  359. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  360. }
  361. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  362. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
  363. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  364. }
  365. }
  366. return (Key)((uint)keyInfo.KeyChar);
  367. }
  368. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  369. var delta = key - ConsoleKey.F1;
  370. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  371. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  372. }
  373. return (Key)((uint)Key.F1 + delta);
  374. }
  375. if (keyInfo.KeyChar != 0) {
  376. return (Key)((uint)keyInfo.KeyChar);
  377. }
  378. return (Key)(0xffffffff);
  379. }
  380. KeyModifiers keyModifiers;
  381. Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  382. {
  383. if (keyModifiers == null) {
  384. keyModifiers = new KeyModifiers ();
  385. }
  386. Key keyMod = new Key ();
  387. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0) {
  388. keyMod = Key.ShiftMask;
  389. keyModifiers.Shift = true;
  390. }
  391. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) {
  392. keyMod |= Key.CtrlMask;
  393. keyModifiers.Ctrl = true;
  394. }
  395. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0) {
  396. keyMod |= Key.AltMask;
  397. keyModifiers.Alt = true;
  398. }
  399. return keyMod != Key.Null ? keyMod | key : key;
  400. }
  401. bool winChanging;
  402. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  403. {
  404. var mLoop = mainLoop.Driver as NetMainLoop;
  405. // Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  406. mLoop.KeyPressed = (consoleKey) => {
  407. var map = MapKey (consoleKey);
  408. if (map == (Key)0xffffffff) {
  409. return;
  410. }
  411. if (map == (Key.Space | Key.CtrlMask) || map == (Key.Space | Key.AltMask)) {
  412. map = Key.AltMask;
  413. keyModifiers.Alt = true;
  414. keyModifiers.Ctrl = false;
  415. keyDownHandler (new KeyEvent (map, keyModifiers));
  416. keyUpHandler (new KeyEvent (map, keyModifiers));
  417. } else {
  418. keyDownHandler (new KeyEvent (map, keyModifiers));
  419. keyHandler (new KeyEvent (map, keyModifiers));
  420. keyUpHandler (new KeyEvent (map, keyModifiers));
  421. }
  422. keyModifiers = new KeyModifiers ();
  423. };
  424. mLoop.WinChanged = (e) => {
  425. winChanging = true;
  426. const int Min_WindowWidth = 14;
  427. Size size = new Size ();
  428. if (!HeightAsBuffer) {
  429. size = new Size (Math.Max (Min_WindowWidth, Console.WindowWidth),
  430. Console.WindowHeight);
  431. top = 0;
  432. } else {
  433. size = new Size (Console.BufferWidth, Console.BufferHeight);
  434. top = e;
  435. }
  436. cols = size.Width;
  437. rows = size.Height;
  438. ResizeScreen ();
  439. UpdateOffScreen ();
  440. if (!winChanging) {
  441. TerminalResized.Invoke ();
  442. }
  443. };
  444. }
  445. public override Attribute GetAttribute ()
  446. {
  447. return currentAttribute;
  448. }
  449. #region Unused
  450. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  451. {
  452. }
  453. public override void SetColors (short foregroundColorId, short backgroundColorId)
  454. {
  455. }
  456. public override void CookMouse ()
  457. {
  458. }
  459. public override void UncookMouse ()
  460. {
  461. }
  462. #endregion
  463. //
  464. // These are for the .NET driver, but running natively on Windows, wont run
  465. // on the Mono emulation
  466. //
  467. }
  468. /// <summary>
  469. /// Mainloop intended to be used with the .NET System.Console API, and can
  470. /// be used on Windows and Unix, it is cross platform but lacks things like
  471. /// file descriptor monitoring.
  472. /// </summary>
  473. /// <remarks>
  474. /// This implementation is used for NetDriver.
  475. /// </remarks>
  476. internal class NetMainLoop : IMainLoopDriver {
  477. ManualResetEventSlim keyReady = new ManualResetEventSlim (false);
  478. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  479. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  480. Queue<ConsoleKeyInfo?> keyResult = new Queue<ConsoleKeyInfo?> ();
  481. MainLoop mainLoop;
  482. ConsoleDriver consoleDriver;
  483. bool winChanged;
  484. int newTop;
  485. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  486. /// <summary>
  487. /// Invoked when a Key is pressed.
  488. /// </summary>
  489. public Action<ConsoleKeyInfo> KeyPressed;
  490. /// <summary>
  491. /// Invoked when the window is changed.
  492. /// </summary>
  493. public Action<int> WinChanged;
  494. /// <summary>
  495. /// Initializes the class with the console driver.
  496. /// </summary>
  497. /// <remarks>
  498. /// Passing a consoleDriver is provided to capture windows resizing.
  499. /// </remarks>
  500. /// <param name="consoleDriver">The console driver used by this Net main loop.</param>
  501. public NetMainLoop (ConsoleDriver consoleDriver = null)
  502. {
  503. if (consoleDriver == null) {
  504. throw new ArgumentNullException ("Console driver instance must be provided.");
  505. }
  506. this.consoleDriver = consoleDriver;
  507. }
  508. void KeyReader ()
  509. {
  510. while (true) {
  511. waitForProbe.Wait ();
  512. waitForProbe.Reset ();
  513. if (keyResult.Count == 0) {
  514. keyResult.Enqueue (Console.ReadKey (true));
  515. }
  516. keyReady.Set ();
  517. }
  518. }
  519. void CheckWinChange ()
  520. {
  521. while (true) {
  522. winChange.Wait ();
  523. winChange.Reset ();
  524. WaitWinChange ();
  525. winChanged = true;
  526. keyReady.Set ();
  527. }
  528. }
  529. int lastWindowHeight;
  530. void WaitWinChange ()
  531. {
  532. while (true) {
  533. if (!consoleDriver.HeightAsBuffer) {
  534. if (Console.WindowWidth != consoleDriver.Cols || Console.WindowHeight != consoleDriver.Rows) {
  535. return;
  536. }
  537. } else {
  538. if (Console.BufferWidth != consoleDriver.Cols || Console.BufferHeight != consoleDriver.Rows
  539. || Console.WindowTop != consoleDriver.Top
  540. || Console.WindowHeight != lastWindowHeight) {
  541. // Top only working on Windows.
  542. newTop = Console.WindowTop;
  543. lastWindowHeight = Console.WindowHeight;
  544. return;
  545. }
  546. }
  547. }
  548. }
  549. void IMainLoopDriver.Setup (MainLoop mainLoop)
  550. {
  551. this.mainLoop = mainLoop;
  552. Task.Run (KeyReader);
  553. Task.Run (CheckWinChange);
  554. }
  555. void IMainLoopDriver.Wakeup ()
  556. {
  557. keyReady.Set ();
  558. }
  559. bool IMainLoopDriver.EventsPending (bool wait)
  560. {
  561. waitForProbe.Set ();
  562. winChange.Set ();
  563. if (CheckTimers (wait, out var waitTimeout)) {
  564. return true;
  565. }
  566. try {
  567. if (!tokenSource.IsCancellationRequested) {
  568. keyReady.Wait (waitTimeout, tokenSource.Token);
  569. }
  570. } catch (OperationCanceledException) {
  571. return true;
  572. } finally {
  573. keyReady.Reset ();
  574. }
  575. if (!tokenSource.IsCancellationRequested) {
  576. return keyResult.Count > 0 || CheckTimers (wait, out _) || winChanged;
  577. }
  578. tokenSource.Dispose ();
  579. tokenSource = new CancellationTokenSource ();
  580. return true;
  581. }
  582. bool CheckTimers (bool wait, out int waitTimeout)
  583. {
  584. long now = DateTime.UtcNow.Ticks;
  585. if (mainLoop.timeouts.Count > 0) {
  586. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  587. if (waitTimeout < 0)
  588. return true;
  589. } else {
  590. waitTimeout = -1;
  591. }
  592. if (!wait)
  593. waitTimeout = 0;
  594. int ic;
  595. lock (mainLoop.idleHandlers) {
  596. ic = mainLoop.idleHandlers.Count;
  597. }
  598. return ic > 0;
  599. }
  600. void IMainLoopDriver.MainIteration ()
  601. {
  602. if (keyResult.Count > 0) {
  603. KeyPressed?.Invoke (keyResult.Dequeue ().Value);
  604. }
  605. if (winChanged) {
  606. winChanged = false;
  607. WinChanged?.Invoke (newTop);
  608. }
  609. }
  610. }
  611. }