NetDriver.cs 18 KB

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