NetDriver.cs 17 KB

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