NetDriver.cs 18 KB

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