NetDriver.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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. void UpdateOffscreen ()
  24. {
  25. int cols = Cols;
  26. int rows = Rows;
  27. contents = new int [rows, cols, 3];
  28. dirtyLine = new bool [rows];
  29. for (int row = 0; row < rows; row++) {
  30. for (int c = 0; c < cols; c++) {
  31. contents [row, c, 0] = ' ';
  32. contents [row, c, 1] = (ushort)Colors.TopLevel.Normal;
  33. contents [row, c, 2] = 0;
  34. dirtyLine [row] = true;
  35. }
  36. }
  37. }
  38. static bool sync = false;
  39. // Current row, and current col, tracked by Move/AddCh only
  40. int ccol, crow;
  41. public override void Move (int col, int row)
  42. {
  43. ccol = col;
  44. crow = row;
  45. }
  46. public override void AddRune (Rune rune)
  47. {
  48. rune = MakePrintable (rune);
  49. if (Clip.Contains (ccol, crow)) {
  50. contents [crow, ccol, 0] = (int)(uint)rune;
  51. contents [crow, ccol, 1] = currentAttribute;
  52. contents [crow, ccol, 2] = 1;
  53. dirtyLine [crow] = true;
  54. }
  55. ccol++;
  56. var runeWidth = Rune.ColumnWidth (rune);
  57. if (runeWidth > 1) {
  58. for (int i = 1; i < runeWidth; i++) {
  59. contents [crow, ccol, 2] = 0;
  60. ccol++;
  61. }
  62. }
  63. //if (ccol == Cols) {
  64. // ccol = 0;
  65. // if (crow + 1 < Rows)
  66. // crow++;
  67. //}
  68. if (sync) {
  69. UpdateScreen ();
  70. }
  71. }
  72. public override void AddStr (ustring str)
  73. {
  74. foreach (var rune in str)
  75. AddRune (rune);
  76. }
  77. public override void End ()
  78. {
  79. Console.ResetColor ();
  80. Clear ();
  81. }
  82. void Clear ()
  83. {
  84. if (Rows > 0) {
  85. Console.Clear ();
  86. }
  87. }
  88. static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  89. {
  90. // Encode the colors into the int value.
  91. return new Attribute () { value = ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff) };
  92. }
  93. bool isWinPlatform;
  94. public override void Init (Action terminalResized)
  95. {
  96. TerminalResized = terminalResized;
  97. Console.TreatControlCAsInput = true;
  98. var p = Environment.OSVersion.Platform;
  99. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) {
  100. isWinPlatform = true;
  101. }
  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. Clear ();
  134. ResizeScreen ();
  135. UpdateOffscreen ();
  136. }
  137. void ResizeScreen ()
  138. {
  139. const int Min_WindowWidth = 14;
  140. switch (HeightSize) {
  141. case HeightSize.WindowHeight:
  142. if (Console.WindowHeight > 0) {
  143. // Can raise an exception while is still resizing.
  144. try {
  145. // Not supported on Unix.
  146. if (isWinPlatform) {
  147. Console.CursorTop = 0;
  148. Console.CursorLeft = 0;
  149. Console.WindowTop = 0;
  150. Console.WindowLeft = 0;
  151. Console.SetBufferSize (Math.Max (Min_WindowWidth, Console.WindowWidth),
  152. Console.WindowHeight);
  153. } else {
  154. //Console.Out.Write ($"\x1b[8;{Console.WindowHeight};{Console.WindowWidth}t");
  155. //Console.Out.Flush ();
  156. Console.Out.Write ($"\x1b[0;0" +
  157. $";{Console.WindowHeight};" +
  158. $"{Math.Max (Min_WindowWidth, Console.WindowWidth)}w");
  159. }
  160. } catch (System.IO.IOException) {
  161. return;
  162. } catch (ArgumentOutOfRangeException) {
  163. return;
  164. }
  165. }
  166. cols = Console.WindowWidth;
  167. rows = Console.WindowHeight;
  168. top = 0;
  169. break;
  170. case HeightSize.BufferHeight:
  171. if (isWinPlatform && Console.WindowHeight > 0) {
  172. if (isWinPlatform) {
  173. // Can raise an exception while is still resizing.
  174. try {
  175. Console.WindowTop = Math.Max (Math.Min (top, Console.BufferHeight - Console.WindowHeight), 0);
  176. } catch (Exception) {
  177. return;
  178. }
  179. }
  180. } else {
  181. Console.Out.Write ($"\x1b[{top};{Console.WindowLeft}" +
  182. $";{Console.BufferHeight}" +
  183. $";{Math.Max (Min_WindowWidth, Console.BufferWidth)}w");
  184. }
  185. cols = Console.BufferWidth;
  186. rows = Console.BufferHeight;
  187. break;
  188. }
  189. Clip = new Rect (0, 0, Cols, Rows);
  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. || (HeightSize == HeightSize.WindowHeight && Rows != Console.WindowHeight)
  213. || (HeightSize == HeightSize.BufferHeight && 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);
  281. switch (keyInfo.Key) {
  282. case ConsoleKey.Escape:
  283. return Key.Esc;
  284. case ConsoleKey.Tab:
  285. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  286. case ConsoleKey.Home:
  287. return Key.Home;
  288. case ConsoleKey.End:
  289. return Key.End;
  290. case ConsoleKey.LeftArrow:
  291. return Key.CursorLeft;
  292. case ConsoleKey.RightArrow:
  293. return Key.CursorRight;
  294. case ConsoleKey.UpArrow:
  295. return Key.CursorUp;
  296. case ConsoleKey.DownArrow:
  297. return Key.CursorDown;
  298. case ConsoleKey.PageUp:
  299. return Key.PageUp;
  300. case ConsoleKey.PageDown:
  301. return Key.PageDown;
  302. case ConsoleKey.Enter:
  303. return Key.Enter;
  304. case ConsoleKey.Spacebar:
  305. return Key.Space;
  306. case ConsoleKey.Backspace:
  307. return Key.Backspace;
  308. case ConsoleKey.Delete:
  309. return Key.Delete;
  310. case ConsoleKey.Oem1:
  311. case ConsoleKey.Oem2:
  312. case ConsoleKey.Oem3:
  313. case ConsoleKey.Oem4:
  314. case ConsoleKey.Oem5:
  315. case ConsoleKey.Oem6:
  316. case ConsoleKey.Oem7:
  317. case ConsoleKey.Oem8:
  318. case ConsoleKey.Oem102:
  319. case ConsoleKey.OemPeriod:
  320. case ConsoleKey.OemComma:
  321. case ConsoleKey.OemPlus:
  322. case ConsoleKey.OemMinus:
  323. return (Key)((uint)keyInfo.KeyChar);
  324. }
  325. var key = keyInfo.Key;
  326. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  327. var delta = key - ConsoleKey.A;
  328. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  329. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  330. }
  331. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  332. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  333. }
  334. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  335. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  336. return (Key)((uint)Key.A + delta);
  337. }
  338. }
  339. return (Key)((uint)keyInfo.KeyChar);
  340. }
  341. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  342. var delta = key - ConsoleKey.D0;
  343. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  344. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  345. }
  346. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  347. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  348. }
  349. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  350. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
  351. return (Key)((uint)Key.D0 + delta);
  352. }
  353. }
  354. return (Key)((uint)keyInfo.KeyChar);
  355. }
  356. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  357. var delta = key - ConsoleKey.F1;
  358. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  359. return (Key)((uint)Key.F1 + delta);
  360. }
  361. return (Key)((uint)Key.F1 + delta);
  362. }
  363. if (keyInfo.KeyChar != 0) {
  364. return (Key)((uint)keyInfo.KeyChar);
  365. }
  366. return (Key)(0xffffffff);
  367. }
  368. KeyModifiers keyModifiers;
  369. void MapKeyModifiers (ConsoleKeyInfo keyInfo)
  370. {
  371. if (keyModifiers == null)
  372. keyModifiers = new KeyModifiers ();
  373. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
  374. keyModifiers.Shift = true;
  375. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
  376. keyModifiers.Ctrl = true;
  377. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
  378. keyModifiers.Alt = true;
  379. }
  380. bool winChanging;
  381. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  382. {
  383. // Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  384. (mainLoop.Driver as NetMainLoop).KeyPressed = (consoleKey) => {
  385. var map = MapKey (consoleKey);
  386. if (map == (Key)0xffffffff) {
  387. return;
  388. }
  389. keyHandler (new KeyEvent (map, keyModifiers));
  390. keyUpHandler (new KeyEvent (map, keyModifiers));
  391. keyModifiers = null;
  392. };
  393. (mainLoop.Driver as NetMainLoop).WinChanged = (e) => {
  394. winChanging = true;
  395. top = e;
  396. ResizeScreen ();
  397. UpdateOffscreen ();
  398. winChanging = false;
  399. TerminalResized.Invoke ();
  400. };
  401. }
  402. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  403. {
  404. }
  405. public override void SetColors (short foregroundColorId, short backgroundColorId)
  406. {
  407. }
  408. public override void CookMouse ()
  409. {
  410. }
  411. public override void UncookMouse ()
  412. {
  413. }
  414. //
  415. // These are for the .NET driver, but running natively on Windows, wont run
  416. // on the Mono emulation
  417. //
  418. }
  419. /// <summary>
  420. /// Mainloop intended to be used with the .NET System.Console API, and can
  421. /// be used on Windows and Unix, it is cross platform but lacks things like
  422. /// file descriptor monitoring.
  423. /// </summary>
  424. /// <remarks>
  425. /// This implementation is used for NetDriver.
  426. /// </remarks>
  427. internal class NetMainLoop : IMainLoopDriver {
  428. ManualResetEventSlim keyReady = new ManualResetEventSlim (false);
  429. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  430. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  431. Queue<ConsoleKeyInfo?> keyResult = new Queue<ConsoleKeyInfo?> ();
  432. MainLoop mainLoop;
  433. ConsoleDriver consoleDriver;
  434. bool winChanged;
  435. int newTop;
  436. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  437. /// <summary>
  438. /// Invoked when a Key is pressed.
  439. /// </summary>
  440. public Action<ConsoleKeyInfo> KeyPressed;
  441. public Action<int> WinChanged;
  442. /// <summary>
  443. /// Initializes the class with the console driver.
  444. /// </summary>
  445. /// <remarks>
  446. /// Passing a consoleDriver is provided to capture windows resizing.
  447. /// </remarks>
  448. /// <param name="consoleDriver">The console driver used by this Net main loop.</param>
  449. public NetMainLoop (ConsoleDriver consoleDriver = null)
  450. {
  451. if (consoleDriver == null) {
  452. throw new ArgumentNullException ("Console driver instance must be provided.");
  453. }
  454. this.consoleDriver = consoleDriver;
  455. }
  456. void KeyReader ()
  457. {
  458. while (true) {
  459. waitForProbe.Wait ();
  460. waitForProbe.Reset ();
  461. if (keyResult.Count == 0) {
  462. keyResult.Enqueue (Console.ReadKey (true));
  463. }
  464. keyReady.Set ();
  465. }
  466. }
  467. void CheckWinChange ()
  468. {
  469. while (true) {
  470. winChange.Wait ();
  471. winChange.Reset ();
  472. WaitWinChange ();
  473. winChanged = true;
  474. keyReady.Set ();
  475. }
  476. }
  477. void WaitWinChange ()
  478. {
  479. while (true) {
  480. switch (consoleDriver.HeightSize) {
  481. case HeightSize.WindowHeight:
  482. if (Console.WindowWidth != consoleDriver.Cols || Console.WindowHeight != consoleDriver.Rows) {
  483. return;
  484. }
  485. break;
  486. case HeightSize.BufferHeight:
  487. if (Console.BufferWidth != consoleDriver.Cols || Console.BufferHeight != consoleDriver.Rows
  488. || Console.WindowTop != consoleDriver.Top) {
  489. newTop = Console.WindowTop;
  490. return;
  491. }
  492. break;
  493. }
  494. }
  495. }
  496. void IMainLoopDriver.Setup (MainLoop mainLoop)
  497. {
  498. this.mainLoop = mainLoop;
  499. Task.Run (KeyReader);
  500. Task.Run (CheckWinChange);
  501. }
  502. void IMainLoopDriver.Wakeup ()
  503. {
  504. keyReady.Set ();
  505. }
  506. bool IMainLoopDriver.EventsPending (bool wait)
  507. {
  508. waitForProbe.Set ();
  509. winChange.Set ();
  510. if (CheckTimers (wait, out var waitTimeout)) {
  511. return true;
  512. }
  513. try {
  514. if (!tokenSource.IsCancellationRequested) {
  515. keyReady.Wait (waitTimeout, tokenSource.Token);
  516. }
  517. } catch (OperationCanceledException) {
  518. return true;
  519. } finally {
  520. keyReady.Reset ();
  521. }
  522. if (!tokenSource.IsCancellationRequested) {
  523. return keyResult.Count > 0 || CheckTimers (wait, out _) || winChanged;
  524. }
  525. tokenSource.Dispose ();
  526. tokenSource = new CancellationTokenSource ();
  527. return true;
  528. }
  529. bool CheckTimers (bool wait, out int waitTimeout)
  530. {
  531. long now = DateTime.UtcNow.Ticks;
  532. if (mainLoop.timeouts.Count > 0) {
  533. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  534. if (waitTimeout < 0)
  535. return true;
  536. } else {
  537. waitTimeout = -1;
  538. }
  539. if (!wait)
  540. waitTimeout = 0;
  541. int ic;
  542. lock (mainLoop.idleHandlers) {
  543. ic = mainLoop.idleHandlers.Count;
  544. }
  545. return ic > 0;
  546. }
  547. void IMainLoopDriver.MainIteration ()
  548. {
  549. if (keyResult.Count > 0) {
  550. KeyPressed?.Invoke (keyResult.Dequeue ().Value);
  551. }
  552. if (winChanged) {
  553. winChanged = false;
  554. WinChanged.Invoke (newTop);
  555. }
  556. }
  557. }
  558. }