NetDriver.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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. int [,,] damage = new int [0, 0, 0];
  225. for (int col = 0; col < cols; col++) {
  226. if (contents [row, col, 2] != 1) {
  227. continue;
  228. }
  229. if (Console.WindowHeight > 0) {
  230. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  231. try {
  232. Console.SetCursorPosition (col, row);
  233. } catch (Exception) {
  234. return;
  235. }
  236. }
  237. for (; col < cols && contents [row, col, 2] == 1; col++) {
  238. var color = contents [row, col, 1];
  239. if (color != redrawColor) {
  240. SetColor (color);
  241. }
  242. Console.Write ((char)contents [row, col, 0]);
  243. contents [row, col, 2] = 0;
  244. }
  245. }
  246. }
  247. UpdateCursor ();
  248. }
  249. public override void Refresh ()
  250. {
  251. UpdateScreen ();
  252. }
  253. public override void UpdateCursor ()
  254. {
  255. // Prevents the exception of size changing during resizing.
  256. try {
  257. if (ccol >= 0 && ccol <= cols && crow >= 0 && crow <= rows) {
  258. Console.SetCursorPosition (ccol, crow);
  259. }
  260. } catch (System.IO.IOException) {
  261. } catch (ArgumentOutOfRangeException) {
  262. }
  263. }
  264. public override void StartReportingMouseMoves ()
  265. {
  266. }
  267. public override void StopReportingMouseMoves ()
  268. {
  269. }
  270. public override void Suspend ()
  271. {
  272. }
  273. int currentAttribute;
  274. public override void SetAttribute (Attribute c)
  275. {
  276. currentAttribute = c.value;
  277. }
  278. Key MapKey (ConsoleKeyInfo keyInfo)
  279. {
  280. MapKeyModifiers (keyInfo, (Key)keyInfo.Key);
  281. switch (keyInfo.Key) {
  282. case ConsoleKey.Escape:
  283. return MapKeyModifiers (keyInfo, Key.Esc);
  284. case ConsoleKey.Tab:
  285. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  286. case ConsoleKey.Home:
  287. return MapKeyModifiers (keyInfo, Key.Home);
  288. case ConsoleKey.End:
  289. return MapKeyModifiers (keyInfo, Key.End);
  290. case ConsoleKey.LeftArrow:
  291. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  292. case ConsoleKey.RightArrow:
  293. return MapKeyModifiers (keyInfo, Key.CursorRight);
  294. case ConsoleKey.UpArrow:
  295. return MapKeyModifiers (keyInfo, Key.CursorUp);
  296. case ConsoleKey.DownArrow:
  297. return MapKeyModifiers (keyInfo, Key.CursorDown);
  298. case ConsoleKey.PageUp:
  299. return MapKeyModifiers (keyInfo, Key.PageUp);
  300. case ConsoleKey.PageDown:
  301. return MapKeyModifiers (keyInfo, Key.PageDown);
  302. case ConsoleKey.Enter:
  303. return MapKeyModifiers (keyInfo, Key.Enter);
  304. case ConsoleKey.Spacebar:
  305. return MapKeyModifiers (keyInfo, Key.Space);
  306. case ConsoleKey.Backspace:
  307. return MapKeyModifiers (keyInfo, Key.Backspace);
  308. case ConsoleKey.Delete:
  309. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  310. case ConsoleKey.Insert:
  311. return MapKeyModifiers (keyInfo, Key.InsertChar);
  312. case ConsoleKey.Oem1:
  313. case ConsoleKey.Oem2:
  314. case ConsoleKey.Oem3:
  315. case ConsoleKey.Oem4:
  316. case ConsoleKey.Oem5:
  317. case ConsoleKey.Oem6:
  318. case ConsoleKey.Oem7:
  319. case ConsoleKey.Oem8:
  320. case ConsoleKey.Oem102:
  321. case ConsoleKey.OemPeriod:
  322. case ConsoleKey.OemComma:
  323. case ConsoleKey.OemPlus:
  324. case ConsoleKey.OemMinus:
  325. return (Key)((uint)keyInfo.KeyChar);
  326. }
  327. var key = keyInfo.Key;
  328. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  329. var delta = key - ConsoleKey.A;
  330. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  331. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  332. }
  333. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  334. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  335. }
  336. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  337. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  338. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  339. }
  340. }
  341. return (Key)((uint)keyInfo.KeyChar);
  342. }
  343. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  344. var delta = key - ConsoleKey.D0;
  345. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  346. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  347. }
  348. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  349. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  350. }
  351. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  352. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
  353. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  354. }
  355. }
  356. return (Key)((uint)keyInfo.KeyChar);
  357. }
  358. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  359. var delta = key - ConsoleKey.F1;
  360. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  361. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  362. }
  363. return (Key)((uint)Key.F1 + delta);
  364. }
  365. if (keyInfo.KeyChar != 0) {
  366. return (Key)((uint)keyInfo.KeyChar);
  367. }
  368. return (Key)(0xffffffff);
  369. }
  370. KeyModifiers keyModifiers;
  371. Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  372. {
  373. if (keyModifiers == null) {
  374. keyModifiers = new KeyModifiers ();
  375. }
  376. Key keyMod = new Key ();
  377. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0) {
  378. keyMod = Key.ShiftMask;
  379. keyModifiers.Shift = true;
  380. }
  381. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) {
  382. keyMod |= Key.CtrlMask;
  383. keyModifiers.Ctrl = true;
  384. }
  385. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0) {
  386. keyMod |= Key.AltMask;
  387. keyModifiers.Alt = true;
  388. }
  389. return keyMod != Key.Null ? keyMod | key : key;
  390. }
  391. bool winChanging;
  392. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  393. {
  394. // Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  395. (mainLoop.Driver as NetMainLoop).KeyPressed = (consoleKey) => {
  396. var map = MapKey (consoleKey);
  397. if (map == (Key)0xffffffff) {
  398. return;
  399. }
  400. if (map == (Key.Space | Key.CtrlMask) || map == (Key.Space | Key.AltMask)) {
  401. map = Key.AltMask;
  402. keyModifiers.Alt = true;
  403. keyModifiers.Ctrl = false;
  404. keyDownHandler (new KeyEvent (map, keyModifiers));
  405. keyUpHandler (new KeyEvent (map, keyModifiers));
  406. } else {
  407. keyDownHandler (new KeyEvent (map, keyModifiers));
  408. keyHandler (new KeyEvent (map, keyModifiers));
  409. keyUpHandler (new KeyEvent (map, keyModifiers));
  410. }
  411. keyModifiers = new KeyModifiers ();
  412. };
  413. (mainLoop.Driver as NetMainLoop).WinChanged = (e) => {
  414. winChanging = true;
  415. const int Min_WindowWidth = 14;
  416. Size size = new Size ();
  417. if (!HeightAsBuffer) {
  418. size = new Size (Math.Max (Min_WindowWidth, Console.WindowWidth),
  419. Console.WindowHeight);
  420. top = 0;
  421. } else {
  422. size = new Size (Console.BufferWidth, Console.BufferHeight);
  423. top = e;
  424. }
  425. cols = size.Width;
  426. rows = size.Height;
  427. ResizeScreen ();
  428. UpdateOffscreen ();
  429. if (!winChanging) {
  430. TerminalResized.Invoke ();
  431. }
  432. };
  433. }
  434. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  435. {
  436. }
  437. public override void SetColors (short foregroundColorId, short backgroundColorId)
  438. {
  439. }
  440. public override void CookMouse ()
  441. {
  442. }
  443. public override void UncookMouse ()
  444. {
  445. }
  446. //
  447. // These are for the .NET driver, but running natively on Windows, wont run
  448. // on the Mono emulation
  449. //
  450. }
  451. /// <summary>
  452. /// Mainloop intended to be used with the .NET System.Console API, and can
  453. /// be used on Windows and Unix, it is cross platform but lacks things like
  454. /// file descriptor monitoring.
  455. /// </summary>
  456. /// <remarks>
  457. /// This implementation is used for NetDriver.
  458. /// </remarks>
  459. internal class NetMainLoop : IMainLoopDriver {
  460. ManualResetEventSlim keyReady = new ManualResetEventSlim (false);
  461. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  462. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  463. Queue<ConsoleKeyInfo?> keyResult = new Queue<ConsoleKeyInfo?> ();
  464. MainLoop mainLoop;
  465. ConsoleDriver consoleDriver;
  466. bool winChanged;
  467. int newTop;
  468. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  469. /// <summary>
  470. /// Invoked when a Key is pressed.
  471. /// </summary>
  472. public Action<ConsoleKeyInfo> KeyPressed;
  473. public Action<int> WinChanged;
  474. /// <summary>
  475. /// Initializes the class with the console driver.
  476. /// </summary>
  477. /// <remarks>
  478. /// Passing a consoleDriver is provided to capture windows resizing.
  479. /// </remarks>
  480. /// <param name="consoleDriver">The console driver used by this Net main loop.</param>
  481. public NetMainLoop (ConsoleDriver consoleDriver = null)
  482. {
  483. if (consoleDriver == null) {
  484. throw new ArgumentNullException ("Console driver instance must be provided.");
  485. }
  486. this.consoleDriver = consoleDriver;
  487. }
  488. void KeyReader ()
  489. {
  490. while (true) {
  491. waitForProbe.Wait ();
  492. waitForProbe.Reset ();
  493. if (keyResult.Count == 0) {
  494. keyResult.Enqueue (Console.ReadKey (true));
  495. }
  496. keyReady.Set ();
  497. }
  498. }
  499. void CheckWinChange ()
  500. {
  501. while (true) {
  502. winChange.Wait ();
  503. winChange.Reset ();
  504. WaitWinChange ();
  505. winChanged = true;
  506. keyReady.Set ();
  507. }
  508. }
  509. int lastWindowHeight;
  510. void WaitWinChange ()
  511. {
  512. while (true) {
  513. if (!consoleDriver.HeightAsBuffer) {
  514. if (Console.WindowWidth != consoleDriver.Cols || Console.WindowHeight != consoleDriver.Rows) {
  515. return;
  516. }
  517. } else {
  518. if (Console.BufferWidth != consoleDriver.Cols || Console.BufferHeight != consoleDriver.Rows
  519. || Console.WindowTop != consoleDriver.Top
  520. || Console.WindowHeight != lastWindowHeight) {
  521. newTop = Console.WindowTop;
  522. lastWindowHeight = Console.WindowHeight;
  523. return;
  524. }
  525. }
  526. }
  527. }
  528. void IMainLoopDriver.Setup (MainLoop mainLoop)
  529. {
  530. this.mainLoop = mainLoop;
  531. Task.Run (KeyReader);
  532. Task.Run (CheckWinChange);
  533. }
  534. void IMainLoopDriver.Wakeup ()
  535. {
  536. keyReady.Set ();
  537. }
  538. bool IMainLoopDriver.EventsPending (bool wait)
  539. {
  540. waitForProbe.Set ();
  541. winChange.Set ();
  542. if (CheckTimers (wait, out var waitTimeout)) {
  543. return true;
  544. }
  545. try {
  546. if (!tokenSource.IsCancellationRequested) {
  547. keyReady.Wait (waitTimeout, tokenSource.Token);
  548. }
  549. } catch (OperationCanceledException) {
  550. return true;
  551. } finally {
  552. keyReady.Reset ();
  553. }
  554. if (!tokenSource.IsCancellationRequested) {
  555. return keyResult.Count > 0 || CheckTimers (wait, out _) || winChanged;
  556. }
  557. tokenSource.Dispose ();
  558. tokenSource = new CancellationTokenSource ();
  559. return true;
  560. }
  561. bool CheckTimers (bool wait, out int waitTimeout)
  562. {
  563. long now = DateTime.UtcNow.Ticks;
  564. if (mainLoop.timeouts.Count > 0) {
  565. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  566. if (waitTimeout < 0)
  567. return true;
  568. } else {
  569. waitTimeout = -1;
  570. }
  571. if (!wait)
  572. waitTimeout = 0;
  573. int ic;
  574. lock (mainLoop.idleHandlers) {
  575. ic = mainLoop.idleHandlers.Count;
  576. }
  577. return ic > 0;
  578. }
  579. void IMainLoopDriver.MainIteration ()
  580. {
  581. if (keyResult.Count > 0) {
  582. KeyPressed?.Invoke (keyResult.Dequeue ().Value);
  583. }
  584. if (winChanged) {
  585. winChanged = false;
  586. WinChanged.Invoke (newTop);
  587. }
  588. }
  589. }
  590. }