NetDriver.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. #pragma warning disable CA1416
  148. Console.CursorTop = 0;
  149. Console.CursorLeft = 0;
  150. Console.WindowTop = 0;
  151. Console.WindowLeft = 0;
  152. Console.SetBufferSize (Math.Max (Min_WindowWidth, Console.WindowWidth),
  153. Console.WindowHeight);
  154. #pragma warning restore CA1416
  155. } else {
  156. //Console.Out.Write ($"\x1b[8;{Console.WindowHeight};{Console.WindowWidth}t");
  157. //Console.Out.Flush ();
  158. Console.Out.Write ($"\x1b[0;0" +
  159. $";{Console.WindowHeight};" +
  160. $"{Math.Max (Min_WindowWidth, Console.WindowWidth)}w");
  161. }
  162. } catch (System.IO.IOException) {
  163. return;
  164. } catch (ArgumentOutOfRangeException) {
  165. return;
  166. }
  167. }
  168. cols = Console.WindowWidth;
  169. rows = Console.WindowHeight;
  170. top = 0;
  171. break;
  172. case HeightSize.BufferHeight:
  173. if (isWinPlatform && Console.WindowHeight > 0) {
  174. // Can raise an exception while is still resizing.
  175. try {
  176. #pragma warning disable CA1416
  177. Console.WindowTop = Math.Max (Math.Min (top, Console.BufferHeight - Console.WindowHeight), 0);
  178. #pragma warning restore CA1416
  179. } catch (Exception) {
  180. return;
  181. }
  182. } else {
  183. Console.Out.Write ($"\x1b[{top};{Console.WindowLeft}" +
  184. $";{Console.BufferHeight}" +
  185. $";{Math.Max (Min_WindowWidth, Console.BufferWidth)}w");
  186. }
  187. cols = Console.BufferWidth;
  188. rows = Console.BufferHeight;
  189. break;
  190. }
  191. Clip = new Rect (0, 0, Cols, Rows);
  192. }
  193. public override Attribute MakeAttribute (Color fore, Color back)
  194. {
  195. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  196. }
  197. int redrawColor = -1;
  198. void SetColor (int color)
  199. {
  200. redrawColor = color;
  201. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  202. .OfType<ConsoleColor> ()
  203. .Select (s => (int)s);
  204. if (values.Contains (color & 0xffff)) {
  205. Console.BackgroundColor = (ConsoleColor)(color & 0xffff);
  206. }
  207. if (values.Contains ((color >> 16) & 0xffff)) {
  208. Console.ForegroundColor = (ConsoleColor)((color >> 16) & 0xffff);
  209. }
  210. }
  211. public override void UpdateScreen ()
  212. {
  213. if (winChanging || Console.WindowHeight == 0
  214. || (HeightSize == HeightSize.WindowHeight && Rows != Console.WindowHeight)
  215. || (HeightSize == HeightSize.BufferHeight && Rows != Console.BufferHeight)) {
  216. return;
  217. }
  218. int top = Top;
  219. int rows = Math.Min (Console.WindowHeight + top, Rows);
  220. int cols = Cols;
  221. for (int row = top; row < rows; row++) {
  222. if (!dirtyLine [row]) {
  223. continue;
  224. }
  225. dirtyLine [row] = false;
  226. int [,,] damage = new int [0, 0, 0];
  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. var color = contents [row, col, 1];
  241. if (color != redrawColor) {
  242. SetColor (color);
  243. }
  244. Console.Write ((char)contents [row, col, 0]);
  245. contents [row, col, 2] = 0;
  246. }
  247. }
  248. }
  249. UpdateCursor ();
  250. }
  251. public override void Refresh ()
  252. {
  253. UpdateScreen ();
  254. }
  255. public override void UpdateCursor ()
  256. {
  257. // Prevents the exception of size changing during resizing.
  258. try {
  259. if (ccol >= 0 && ccol <= cols && crow >= 0 && crow <= rows) {
  260. Console.SetCursorPosition (ccol, crow);
  261. }
  262. } catch (System.IO.IOException) {
  263. } catch (ArgumentOutOfRangeException) {
  264. }
  265. }
  266. public override void StartReportingMouseMoves ()
  267. {
  268. }
  269. public override void StopReportingMouseMoves ()
  270. {
  271. }
  272. public override void Suspend ()
  273. {
  274. }
  275. int currentAttribute;
  276. public override void SetAttribute (Attribute c)
  277. {
  278. currentAttribute = c.value;
  279. }
  280. Key MapKey (ConsoleKeyInfo keyInfo)
  281. {
  282. MapKeyModifiers (keyInfo);
  283. switch (keyInfo.Key) {
  284. case ConsoleKey.Escape:
  285. return Key.Esc;
  286. case ConsoleKey.Tab:
  287. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  288. case ConsoleKey.Home:
  289. return Key.Home;
  290. case ConsoleKey.End:
  291. return Key.End;
  292. case ConsoleKey.LeftArrow:
  293. return Key.CursorLeft;
  294. case ConsoleKey.RightArrow:
  295. return Key.CursorRight;
  296. case ConsoleKey.UpArrow:
  297. return Key.CursorUp;
  298. case ConsoleKey.DownArrow:
  299. return Key.CursorDown;
  300. case ConsoleKey.PageUp:
  301. return Key.PageUp;
  302. case ConsoleKey.PageDown:
  303. return Key.PageDown;
  304. case ConsoleKey.Enter:
  305. return Key.Enter;
  306. case ConsoleKey.Spacebar:
  307. return Key.Space;
  308. case ConsoleKey.Backspace:
  309. return Key.Backspace;
  310. case ConsoleKey.Delete:
  311. return Key.Delete;
  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 (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 (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 (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. void MapKeyModifiers (ConsoleKeyInfo keyInfo)
  372. {
  373. if (keyModifiers == null)
  374. keyModifiers = new KeyModifiers ();
  375. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
  376. keyModifiers.Shift = true;
  377. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
  378. keyModifiers.Ctrl = true;
  379. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
  380. keyModifiers.Alt = true;
  381. }
  382. bool winChanging;
  383. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  384. {
  385. // Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  386. (mainLoop.Driver as NetMainLoop).KeyPressed = (consoleKey) => {
  387. var map = MapKey (consoleKey);
  388. if (map == (Key)0xffffffff) {
  389. return;
  390. }
  391. keyHandler (new KeyEvent (map, keyModifiers));
  392. keyUpHandler (new KeyEvent (map, keyModifiers));
  393. keyModifiers = null;
  394. };
  395. (mainLoop.Driver as NetMainLoop).WinChanged = (e) => {
  396. winChanging = true;
  397. top = e;
  398. ResizeScreen ();
  399. UpdateOffscreen ();
  400. winChanging = false;
  401. TerminalResized.Invoke ();
  402. };
  403. }
  404. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  405. {
  406. }
  407. public override void SetColors (short foregroundColorId, short backgroundColorId)
  408. {
  409. }
  410. public override void CookMouse ()
  411. {
  412. }
  413. public override void UncookMouse ()
  414. {
  415. }
  416. //
  417. // These are for the .NET driver, but running natively on Windows, wont run
  418. // on the Mono emulation
  419. //
  420. }
  421. /// <summary>
  422. /// Mainloop intended to be used with the .NET System.Console API, and can
  423. /// be used on Windows and Unix, it is cross platform but lacks things like
  424. /// file descriptor monitoring.
  425. /// </summary>
  426. /// <remarks>
  427. /// This implementation is used for NetDriver.
  428. /// </remarks>
  429. internal class NetMainLoop : IMainLoopDriver {
  430. ManualResetEventSlim keyReady = new ManualResetEventSlim (false);
  431. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  432. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  433. Queue<ConsoleKeyInfo?> keyResult = new Queue<ConsoleKeyInfo?> ();
  434. MainLoop mainLoop;
  435. ConsoleDriver consoleDriver;
  436. bool winChanged;
  437. int newTop;
  438. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  439. /// <summary>
  440. /// Invoked when a Key is pressed.
  441. /// </summary>
  442. public Action<ConsoleKeyInfo> KeyPressed;
  443. public Action<int> WinChanged;
  444. /// <summary>
  445. /// Initializes the class with the console driver.
  446. /// </summary>
  447. /// <remarks>
  448. /// Passing a consoleDriver is provided to capture windows resizing.
  449. /// </remarks>
  450. /// <param name="consoleDriver">The console driver used by this Net main loop.</param>
  451. public NetMainLoop (ConsoleDriver consoleDriver = null)
  452. {
  453. if (consoleDriver == null) {
  454. throw new ArgumentNullException ("Console driver instance must be provided.");
  455. }
  456. this.consoleDriver = consoleDriver;
  457. }
  458. void KeyReader ()
  459. {
  460. while (true) {
  461. waitForProbe.Wait ();
  462. waitForProbe.Reset ();
  463. if (keyResult.Count == 0) {
  464. keyResult.Enqueue (Console.ReadKey (true));
  465. }
  466. keyReady.Set ();
  467. }
  468. }
  469. void CheckWinChange ()
  470. {
  471. while (true) {
  472. winChange.Wait ();
  473. winChange.Reset ();
  474. WaitWinChange ();
  475. winChanged = true;
  476. keyReady.Set ();
  477. }
  478. }
  479. void WaitWinChange ()
  480. {
  481. while (true) {
  482. switch (consoleDriver.HeightSize) {
  483. case HeightSize.WindowHeight:
  484. if (Console.WindowWidth != consoleDriver.Cols || Console.WindowHeight != consoleDriver.Rows) {
  485. return;
  486. }
  487. break;
  488. case HeightSize.BufferHeight:
  489. if (Console.BufferWidth != consoleDriver.Cols || Console.BufferHeight != consoleDriver.Rows
  490. || Console.WindowTop != consoleDriver.Top) {
  491. newTop = Console.WindowTop;
  492. return;
  493. }
  494. break;
  495. }
  496. }
  497. }
  498. void IMainLoopDriver.Setup (MainLoop mainLoop)
  499. {
  500. this.mainLoop = mainLoop;
  501. Task.Run (KeyReader);
  502. Task.Run (CheckWinChange);
  503. }
  504. void IMainLoopDriver.Wakeup ()
  505. {
  506. keyReady.Set ();
  507. }
  508. bool IMainLoopDriver.EventsPending (bool wait)
  509. {
  510. waitForProbe.Set ();
  511. winChange.Set ();
  512. if (CheckTimers (wait, out var waitTimeout)) {
  513. return true;
  514. }
  515. try {
  516. if (!tokenSource.IsCancellationRequested) {
  517. keyReady.Wait (waitTimeout, tokenSource.Token);
  518. }
  519. } catch (OperationCanceledException) {
  520. return true;
  521. } finally {
  522. keyReady.Reset ();
  523. }
  524. if (!tokenSource.IsCancellationRequested) {
  525. return keyResult.Count > 0 || CheckTimers (wait, out _) || winChanged;
  526. }
  527. tokenSource.Dispose ();
  528. tokenSource = new CancellationTokenSource ();
  529. return true;
  530. }
  531. bool CheckTimers (bool wait, out int waitTimeout)
  532. {
  533. long now = DateTime.UtcNow.Ticks;
  534. if (mainLoop.timeouts.Count > 0) {
  535. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  536. if (waitTimeout < 0)
  537. return true;
  538. } else {
  539. waitTimeout = -1;
  540. }
  541. if (!wait)
  542. waitTimeout = 0;
  543. int ic;
  544. lock (mainLoop.idleHandlers) {
  545. ic = mainLoop.idleHandlers.Count;
  546. }
  547. return ic > 0;
  548. }
  549. void IMainLoopDriver.MainIteration ()
  550. {
  551. if (keyResult.Count > 0) {
  552. KeyPressed?.Invoke (keyResult.Dequeue ().Value);
  553. }
  554. if (winChanged) {
  555. winChanged = false;
  556. WinChanged.Invoke (newTop);
  557. }
  558. }
  559. }
  560. }