NetDriver.cs 18 KB

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