NetDriver.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  1. //
  2. // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient.
  3. //
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Runtime.InteropServices;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping;
  14. using static Terminal.Gui.NetEvents;
  15. using static Terminal.Gui.WindowsConsole;
  16. namespace Terminal.Gui;
  17. class NetWinVTConsole {
  18. IntPtr _inputHandle, _outputHandle, _errorHandle;
  19. uint _originalInputConsoleMode, _originalOutputConsoleMode, _originalErrorConsoleMode;
  20. public NetWinVTConsole ()
  21. {
  22. _inputHandle = GetStdHandle (STD_INPUT_HANDLE);
  23. if (!GetConsoleMode (_inputHandle, out uint mode)) {
  24. throw new ApplicationException ($"Failed to get input console mode, error code: {GetLastError ()}.");
  25. }
  26. _originalInputConsoleMode = mode;
  27. if ((mode & ENABLE_VIRTUAL_TERMINAL_INPUT) < ENABLE_VIRTUAL_TERMINAL_INPUT) {
  28. mode |= ENABLE_VIRTUAL_TERMINAL_INPUT;
  29. if (!SetConsoleMode (_inputHandle, mode)) {
  30. throw new ApplicationException ($"Failed to set input console mode, error code: {GetLastError ()}.");
  31. }
  32. }
  33. _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  34. if (!GetConsoleMode (_outputHandle, out mode)) {
  35. throw new ApplicationException ($"Failed to get output console mode, error code: {GetLastError ()}.");
  36. }
  37. _originalOutputConsoleMode = mode;
  38. if ((mode & (ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN)) < DISABLE_NEWLINE_AUTO_RETURN) {
  39. mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN;
  40. if (!SetConsoleMode (_outputHandle, mode)) {
  41. throw new ApplicationException ($"Failed to set output console mode, error code: {GetLastError ()}.");
  42. }
  43. }
  44. _errorHandle = GetStdHandle (STD_ERROR_HANDLE);
  45. if (!GetConsoleMode (_errorHandle, out mode)) {
  46. throw new ApplicationException ($"Failed to get error console mode, error code: {GetLastError ()}.");
  47. }
  48. _originalErrorConsoleMode = mode;
  49. if ((mode & DISABLE_NEWLINE_AUTO_RETURN) < DISABLE_NEWLINE_AUTO_RETURN) {
  50. mode |= DISABLE_NEWLINE_AUTO_RETURN;
  51. if (!SetConsoleMode (_errorHandle, mode)) {
  52. throw new ApplicationException ($"Failed to set error console mode, error code: {GetLastError ()}.");
  53. }
  54. }
  55. }
  56. public void Cleanup ()
  57. {
  58. if (!SetConsoleMode (_inputHandle, _originalInputConsoleMode)) {
  59. throw new ApplicationException ($"Failed to restore input console mode, error code: {GetLastError ()}.");
  60. }
  61. if (!SetConsoleMode (_outputHandle, _originalOutputConsoleMode)) {
  62. throw new ApplicationException ($"Failed to restore output console mode, error code: {GetLastError ()}.");
  63. }
  64. if (!SetConsoleMode (_errorHandle, _originalErrorConsoleMode)) {
  65. throw new ApplicationException ($"Failed to restore error console mode, error code: {GetLastError ()}.");
  66. }
  67. }
  68. const int STD_INPUT_HANDLE = -10;
  69. const int STD_OUTPUT_HANDLE = -11;
  70. const int STD_ERROR_HANDLE = -12;
  71. // Input modes.
  72. const uint ENABLE_PROCESSED_INPUT = 1;
  73. const uint ENABLE_LINE_INPUT = 2;
  74. const uint ENABLE_ECHO_INPUT = 4;
  75. const uint ENABLE_WINDOW_INPUT = 8;
  76. const uint ENABLE_MOUSE_INPUT = 16;
  77. const uint ENABLE_INSERT_MODE = 32;
  78. const uint ENABLE_QUICK_EDIT_MODE = 64;
  79. const uint ENABLE_EXTENDED_FLAGS = 128;
  80. const uint ENABLE_VIRTUAL_TERMINAL_INPUT = 512;
  81. // Output modes.
  82. const uint ENABLE_PROCESSED_OUTPUT = 1;
  83. const uint ENABLE_WRAP_AT_EOL_OUTPUT = 2;
  84. const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4;
  85. const uint DISABLE_NEWLINE_AUTO_RETURN = 8;
  86. const uint ENABLE_LVB_GRID_WORLDWIDE = 10;
  87. [DllImport ("kernel32.dll", SetLastError = true)]
  88. extern static IntPtr GetStdHandle (int nStdHandle);
  89. [DllImport ("kernel32.dll")]
  90. extern static bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  91. [DllImport ("kernel32.dll")]
  92. extern static bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  93. [DllImport ("kernel32.dll")]
  94. extern static uint GetLastError ();
  95. }
  96. class NetEvents : IDisposable {
  97. readonly ManualResetEventSlim _inputReady = new (false);
  98. CancellationTokenSource _inputReadyCancellationTokenSource;
  99. readonly ManualResetEventSlim _waitForStart = new (false);
  100. //CancellationTokenSource _waitForStartCancellationTokenSource;
  101. readonly ManualResetEventSlim _winChange = new (false);
  102. readonly Queue<InputResult?> _inputQueue = new ();
  103. readonly ConsoleDriver _consoleDriver;
  104. ConsoleKeyInfo [] _cki;
  105. bool _isEscSeq;
  106. #if PROCESS_REQUEST
  107. bool _neededProcessRequest;
  108. #endif
  109. public EscSeqRequests EscSeqRequests { get; } = new ();
  110. public NetEvents (ConsoleDriver consoleDriver)
  111. {
  112. _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver));
  113. _inputReadyCancellationTokenSource = new CancellationTokenSource ();
  114. Task.Run (ProcessInputQueue, _inputReadyCancellationTokenSource.Token);
  115. Task.Run (CheckWindowSizeChange, _inputReadyCancellationTokenSource.Token);
  116. }
  117. public InputResult? DequeueInput ()
  118. {
  119. while (_inputReadyCancellationTokenSource != null && !_inputReadyCancellationTokenSource.Token.IsCancellationRequested) {
  120. _waitForStart.Set ();
  121. _winChange.Set ();
  122. try {
  123. if (!_inputReadyCancellationTokenSource.Token.IsCancellationRequested) {
  124. if (_inputQueue.Count == 0) {
  125. _inputReady.Wait (_inputReadyCancellationTokenSource.Token);
  126. }
  127. }
  128. } catch (OperationCanceledException) {
  129. return null;
  130. } finally {
  131. _inputReady.Reset ();
  132. }
  133. #if PROCESS_REQUEST
  134. _neededProcessRequest = false;
  135. #endif
  136. if (_inputQueue.Count > 0) {
  137. return _inputQueue.Dequeue ();
  138. }
  139. }
  140. return null;
  141. }
  142. static ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, bool intercept = true)
  143. {
  144. // if there is a key available, return it without waiting
  145. // (or dispatching work to the thread queue)
  146. if (Console.KeyAvailable) {
  147. return Console.ReadKey (intercept);
  148. }
  149. while (!cancellationToken.IsCancellationRequested) {
  150. Task.Delay (100);
  151. if (Console.KeyAvailable) {
  152. return Console.ReadKey (intercept);
  153. }
  154. }
  155. cancellationToken.ThrowIfCancellationRequested ();
  156. return default;
  157. }
  158. void ProcessInputQueue ()
  159. {
  160. while (!_inputReadyCancellationTokenSource.Token.IsCancellationRequested) {
  161. try {
  162. _waitForStart.Wait (_inputReadyCancellationTokenSource.Token);
  163. } catch (OperationCanceledException) {
  164. return;
  165. }
  166. _waitForStart.Reset ();
  167. if (_inputQueue.Count == 0) {
  168. ConsoleKey key = 0;
  169. ConsoleModifiers mod = 0;
  170. ConsoleKeyInfo newConsoleKeyInfo = default;
  171. while (true) {
  172. if (_inputReadyCancellationTokenSource.Token.IsCancellationRequested) {
  173. return;
  174. }
  175. ConsoleKeyInfo consoleKeyInfo;
  176. try {
  177. consoleKeyInfo = ReadConsoleKeyInfo (_inputReadyCancellationTokenSource.Token, true);
  178. } catch (OperationCanceledException) {
  179. return;
  180. }
  181. if (consoleKeyInfo.KeyChar == (char)KeyCode.Esc && !_isEscSeq
  182. || consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq) {
  183. if (_cki == null && consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq) {
  184. _cki = EscSeqUtils.ResizeArray (new ConsoleKeyInfo ((char)KeyCode.Esc, 0,
  185. false, false, false), _cki);
  186. }
  187. _isEscSeq = true;
  188. newConsoleKeyInfo = consoleKeyInfo;
  189. _cki = EscSeqUtils.ResizeArray (consoleKeyInfo, _cki);
  190. if (Console.KeyAvailable) {
  191. continue;
  192. }
  193. ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod);
  194. _cki = null;
  195. _isEscSeq = false;
  196. break;
  197. } else if (consoleKeyInfo.KeyChar == (char)KeyCode.Esc && _isEscSeq && _cki != null) {
  198. ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod);
  199. _cki = null;
  200. if (Console.KeyAvailable) {
  201. _cki = EscSeqUtils.ResizeArray (consoleKeyInfo, _cki);
  202. } else {
  203. ProcessMapConsoleKeyInfo (consoleKeyInfo);
  204. }
  205. break;
  206. } else {
  207. ProcessMapConsoleKeyInfo (consoleKeyInfo);
  208. break;
  209. }
  210. }
  211. }
  212. _inputReady.Set ();
  213. }
  214. void ProcessMapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  215. {
  216. _inputQueue.Enqueue (new InputResult {
  217. EventType = EventType.Key,
  218. ConsoleKeyInfo = EscSeqUtils.MapConsoleKeyInfo (consoleKeyInfo)
  219. });
  220. _isEscSeq = false;
  221. }
  222. }
  223. void CheckWindowSizeChange ()
  224. {
  225. void RequestWindowSize (CancellationToken cancellationToken)
  226. {
  227. while (!cancellationToken.IsCancellationRequested) {
  228. // Wait for a while then check if screen has changed sizes
  229. Task.Delay (500, cancellationToken);
  230. int buffHeight, buffWidth;
  231. if (((NetDriver)_consoleDriver).IsWinPlatform) {
  232. buffHeight = Math.Max (Console.BufferHeight, 0);
  233. buffWidth = Math.Max (Console.BufferWidth, 0);
  234. } else {
  235. buffHeight = _consoleDriver.Rows;
  236. buffWidth = _consoleDriver.Cols;
  237. }
  238. if (EnqueueWindowSizeEvent (
  239. Math.Max (Console.WindowHeight, 0),
  240. Math.Max (Console.WindowWidth, 0),
  241. buffHeight,
  242. buffWidth)) {
  243. return;
  244. }
  245. }
  246. cancellationToken.ThrowIfCancellationRequested ();
  247. }
  248. while (true) {
  249. if (_inputReadyCancellationTokenSource.IsCancellationRequested) {
  250. return;
  251. }
  252. _winChange.Wait (_inputReadyCancellationTokenSource.Token);
  253. _winChange.Reset ();
  254. try {
  255. RequestWindowSize (_inputReadyCancellationTokenSource.Token);
  256. } catch (OperationCanceledException) {
  257. return;
  258. }
  259. _inputReady.Set ();
  260. }
  261. }
  262. /// <summary>
  263. /// Enqueue a window size event if the window size has changed.
  264. /// </summary>
  265. /// <param name="winHeight"></param>
  266. /// <param name="winWidth"></param>
  267. /// <param name="buffHeight"></param>
  268. /// <param name="buffWidth"></param>
  269. /// <returns></returns>
  270. bool EnqueueWindowSizeEvent (int winHeight, int winWidth, int buffHeight, int buffWidth)
  271. {
  272. if (winWidth == _consoleDriver.Cols && winHeight == _consoleDriver.Rows) {
  273. return false;
  274. }
  275. int w = Math.Max (winWidth, 0);
  276. int h = Math.Max (winHeight, 0);
  277. _inputQueue.Enqueue (new InputResult () {
  278. EventType = EventType.WindowSize,
  279. WindowSizeEvent = new WindowSizeEvent () {
  280. Size = new Size (w, h)
  281. }
  282. });
  283. return true;
  284. }
  285. // Process a CSI sequence received by the driver (key pressed, mouse event, or request/response event)
  286. void ProcessRequestResponse (ref ConsoleKeyInfo newConsoleKeyInfo, ref ConsoleKey key, ConsoleKeyInfo [] cki, ref ConsoleModifiers mod)
  287. {
  288. // isMouse is true if it's CSI<, false otherwise
  289. EscSeqUtils.DecodeEscSeq (EscSeqRequests, ref newConsoleKeyInfo, ref key, cki, ref mod,
  290. out string c1Control, out string code, out string [] values, out string terminating,
  291. out bool isMouse, out var mouseFlags,
  292. out var pos, out bool isReq,
  293. (f, p) => HandleMouseEvent (MapMouseFlags (f), p));
  294. if (isMouse) {
  295. foreach (var mf in mouseFlags) {
  296. HandleMouseEvent (MapMouseFlags (mf), pos);
  297. }
  298. return;
  299. } else if (isReq) {
  300. HandleRequestResponseEvent (c1Control, code, values, terminating);
  301. return;
  302. }
  303. HandleKeyboardEvent (newConsoleKeyInfo);
  304. }
  305. MouseButtonState MapMouseFlags (MouseFlags mouseFlags)
  306. {
  307. MouseButtonState mbs = default;
  308. foreach (object flag in Enum.GetValues (mouseFlags.GetType ())) {
  309. if (mouseFlags.HasFlag ((MouseFlags)flag)) {
  310. switch (flag) {
  311. case MouseFlags.Button1Pressed:
  312. mbs |= MouseButtonState.Button1Pressed;
  313. break;
  314. case MouseFlags.Button1Released:
  315. mbs |= MouseButtonState.Button1Released;
  316. break;
  317. case MouseFlags.Button1Clicked:
  318. mbs |= MouseButtonState.Button1Clicked;
  319. break;
  320. case MouseFlags.Button1DoubleClicked:
  321. mbs |= MouseButtonState.Button1DoubleClicked;
  322. break;
  323. case MouseFlags.Button1TripleClicked:
  324. mbs |= MouseButtonState.Button1TripleClicked;
  325. break;
  326. case MouseFlags.Button2Pressed:
  327. mbs |= MouseButtonState.Button2Pressed;
  328. break;
  329. case MouseFlags.Button2Released:
  330. mbs |= MouseButtonState.Button2Released;
  331. break;
  332. case MouseFlags.Button2Clicked:
  333. mbs |= MouseButtonState.Button2Clicked;
  334. break;
  335. case MouseFlags.Button2DoubleClicked:
  336. mbs |= MouseButtonState.Button2DoubleClicked;
  337. break;
  338. case MouseFlags.Button2TripleClicked:
  339. mbs |= MouseButtonState.Button2TripleClicked;
  340. break;
  341. case MouseFlags.Button3Pressed:
  342. mbs |= MouseButtonState.Button3Pressed;
  343. break;
  344. case MouseFlags.Button3Released:
  345. mbs |= MouseButtonState.Button3Released;
  346. break;
  347. case MouseFlags.Button3Clicked:
  348. mbs |= MouseButtonState.Button3Clicked;
  349. break;
  350. case MouseFlags.Button3DoubleClicked:
  351. mbs |= MouseButtonState.Button3DoubleClicked;
  352. break;
  353. case MouseFlags.Button3TripleClicked:
  354. mbs |= MouseButtonState.Button3TripleClicked;
  355. break;
  356. case MouseFlags.WheeledUp:
  357. mbs |= MouseButtonState.ButtonWheeledUp;
  358. break;
  359. case MouseFlags.WheeledDown:
  360. mbs |= MouseButtonState.ButtonWheeledDown;
  361. break;
  362. case MouseFlags.WheeledLeft:
  363. mbs |= MouseButtonState.ButtonWheeledLeft;
  364. break;
  365. case MouseFlags.WheeledRight:
  366. mbs |= MouseButtonState.ButtonWheeledRight;
  367. break;
  368. case MouseFlags.Button4Pressed:
  369. mbs |= MouseButtonState.Button4Pressed;
  370. break;
  371. case MouseFlags.Button4Released:
  372. mbs |= MouseButtonState.Button4Released;
  373. break;
  374. case MouseFlags.Button4Clicked:
  375. mbs |= MouseButtonState.Button4Clicked;
  376. break;
  377. case MouseFlags.Button4DoubleClicked:
  378. mbs |= MouseButtonState.Button4DoubleClicked;
  379. break;
  380. case MouseFlags.Button4TripleClicked:
  381. mbs |= MouseButtonState.Button4TripleClicked;
  382. break;
  383. case MouseFlags.ButtonShift:
  384. mbs |= MouseButtonState.ButtonShift;
  385. break;
  386. case MouseFlags.ButtonCtrl:
  387. mbs |= MouseButtonState.ButtonCtrl;
  388. break;
  389. case MouseFlags.ButtonAlt:
  390. mbs |= MouseButtonState.ButtonAlt;
  391. break;
  392. case MouseFlags.ReportMousePosition:
  393. mbs |= MouseButtonState.ReportMousePosition;
  394. break;
  395. case MouseFlags.AllEvents:
  396. mbs |= MouseButtonState.AllEvents;
  397. break;
  398. }
  399. }
  400. }
  401. return mbs;
  402. }
  403. Point _lastCursorPosition;
  404. void HandleRequestResponseEvent (string c1Control, string code, string [] values, string terminating)
  405. {
  406. switch (terminating) {
  407. // BUGBUG: I can't find where we send a request for cursor position (ESC[?6n), so I'm not sure if this is needed.
  408. case EscSeqUtils.CSI_RequestCursorPositionReport_Terminator:
  409. var point = new Point {
  410. X = int.Parse (values [1]) - 1,
  411. Y = int.Parse (values [0]) - 1
  412. };
  413. if (_lastCursorPosition.Y != point.Y) {
  414. _lastCursorPosition = point;
  415. var eventType = EventType.WindowPosition;
  416. var winPositionEv = new WindowPositionEvent () {
  417. CursorPosition = point
  418. };
  419. _inputQueue.Enqueue (new InputResult () {
  420. EventType = eventType,
  421. WindowPositionEvent = winPositionEv
  422. });
  423. } else {
  424. return;
  425. }
  426. break;
  427. case EscSeqUtils.CSI_ReportTerminalSizeInChars_Terminator:
  428. switch (values [0]) {
  429. case EscSeqUtils.CSI_ReportTerminalSizeInChars_ResponseValue:
  430. EnqueueWindowSizeEvent (
  431. Math.Max (int.Parse (values [1]), 0),
  432. Math.Max (int.Parse (values [2]), 0),
  433. Math.Max (int.Parse (values [1]), 0),
  434. Math.Max (int.Parse (values [2]), 0));
  435. break;
  436. default:
  437. EnqueueRequestResponseEvent (c1Control, code, values, terminating);
  438. break;
  439. }
  440. break;
  441. default:
  442. EnqueueRequestResponseEvent (c1Control, code, values, terminating);
  443. break;
  444. }
  445. _inputReady.Set ();
  446. }
  447. void EnqueueRequestResponseEvent (string c1Control, string code, string [] values, string terminating)
  448. {
  449. var eventType = EventType.RequestResponse;
  450. var requestRespEv = new RequestResponseEvent () {
  451. ResultTuple = (c1Control, code, values, terminating)
  452. };
  453. _inputQueue.Enqueue (new InputResult () {
  454. EventType = eventType,
  455. RequestResponseEvent = requestRespEv
  456. });
  457. }
  458. void HandleMouseEvent (MouseButtonState buttonState, Point pos)
  459. {
  460. var mouseEvent = new MouseEvent () {
  461. Position = pos,
  462. ButtonState = buttonState
  463. };
  464. _inputQueue.Enqueue (new InputResult () {
  465. EventType = EventType.Mouse,
  466. MouseEvent = mouseEvent
  467. });
  468. _inputReady.Set ();
  469. }
  470. public enum EventType {
  471. Key = 1,
  472. Mouse = 2,
  473. WindowSize = 3,
  474. WindowPosition = 4,
  475. RequestResponse = 5
  476. }
  477. [Flags]
  478. public enum MouseButtonState {
  479. Button1Pressed = 0x1,
  480. Button1Released = 0x2,
  481. Button1Clicked = 0x4,
  482. Button1DoubleClicked = 0x8,
  483. Button1TripleClicked = 0x10,
  484. Button2Pressed = 0x20,
  485. Button2Released = 0x40,
  486. Button2Clicked = 0x80,
  487. Button2DoubleClicked = 0x100,
  488. Button2TripleClicked = 0x200,
  489. Button3Pressed = 0x400,
  490. Button3Released = 0x800,
  491. Button3Clicked = 0x1000,
  492. Button3DoubleClicked = 0x2000,
  493. Button3TripleClicked = 0x4000,
  494. ButtonWheeledUp = 0x8000,
  495. ButtonWheeledDown = 0x10000,
  496. ButtonWheeledLeft = 0x20000,
  497. ButtonWheeledRight = 0x40000,
  498. Button4Pressed = 0x80000,
  499. Button4Released = 0x100000,
  500. Button4Clicked = 0x200000,
  501. Button4DoubleClicked = 0x400000,
  502. Button4TripleClicked = 0x800000,
  503. ButtonShift = 0x1000000,
  504. ButtonCtrl = 0x2000000,
  505. ButtonAlt = 0x4000000,
  506. ReportMousePosition = 0x8000000,
  507. AllEvents = -1
  508. }
  509. public struct MouseEvent {
  510. public Point Position;
  511. public MouseButtonState ButtonState;
  512. }
  513. public struct WindowSizeEvent {
  514. public Size Size;
  515. }
  516. public struct WindowPositionEvent {
  517. public int Top;
  518. public int Left;
  519. public Point CursorPosition;
  520. }
  521. public struct RequestResponseEvent {
  522. public (string c1Control, string code, string [] values, string terminating) ResultTuple;
  523. }
  524. public struct InputResult {
  525. public EventType EventType;
  526. public ConsoleKeyInfo ConsoleKeyInfo;
  527. public MouseEvent MouseEvent;
  528. public WindowSizeEvent WindowSizeEvent;
  529. public WindowPositionEvent WindowPositionEvent;
  530. public RequestResponseEvent RequestResponseEvent;
  531. public override readonly string ToString ()
  532. {
  533. return EventType switch {
  534. EventType.Key => ToString (ConsoleKeyInfo),
  535. EventType.Mouse => MouseEvent.ToString (),
  536. //EventType.WindowSize => WindowSize.ToString (),
  537. //EventType.RequestResponse => RequestResponse.ToString (),
  538. _ => "Unknown event type: " + EventType
  539. };
  540. }
  541. /// <summary>
  542. /// Prints a ConsoleKeyInfoEx structure
  543. /// </summary>
  544. /// <param name="cki"></param>
  545. /// <returns></returns>
  546. public readonly string ToString (ConsoleKeyInfo cki)
  547. {
  548. var ke = new Key ((KeyCode)cki.KeyChar);
  549. var sb = new StringBuilder ();
  550. sb.Append ($"Key: {(KeyCode)cki.Key} ({cki.Key})");
  551. sb.Append ((cki.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty);
  552. sb.Append ((cki.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty);
  553. sb.Append ((cki.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty);
  554. sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)cki.KeyChar}) ");
  555. var s = sb.ToString ().TrimEnd (',').TrimEnd (' ');
  556. return $"[ConsoleKeyInfo({s})]";
  557. }
  558. }
  559. void HandleKeyboardEvent (ConsoleKeyInfo cki)
  560. {
  561. var inputResult = new InputResult {
  562. EventType = EventType.Key,
  563. ConsoleKeyInfo = cki
  564. };
  565. _inputQueue.Enqueue (inputResult);
  566. }
  567. public void Dispose ()
  568. {
  569. _inputReadyCancellationTokenSource?.Cancel ();
  570. _inputReadyCancellationTokenSource?.Dispose ();
  571. _inputReadyCancellationTokenSource = null;
  572. try {
  573. // throws away any typeahead that has been typed by
  574. // the user and has not yet been read by the program.
  575. while (Console.KeyAvailable) {
  576. Console.ReadKey (true);
  577. }
  578. } catch (InvalidOperationException) {
  579. // Ignore - Console input has already been closed
  580. }
  581. }
  582. }
  583. class NetDriver : ConsoleDriver {
  584. const int COLOR_BLACK = 30;
  585. const int COLOR_RED = 31;
  586. const int COLOR_GREEN = 32;
  587. const int COLOR_YELLOW = 33;
  588. const int COLOR_BLUE = 34;
  589. const int COLOR_MAGENTA = 35;
  590. const int COLOR_CYAN = 36;
  591. const int COLOR_WHITE = 37;
  592. const int COLOR_BRIGHT_BLACK = 90;
  593. const int COLOR_BRIGHT_RED = 91;
  594. const int COLOR_BRIGHT_GREEN = 92;
  595. const int COLOR_BRIGHT_YELLOW = 93;
  596. const int COLOR_BRIGHT_BLUE = 94;
  597. const int COLOR_BRIGHT_MAGENTA = 95;
  598. const int COLOR_BRIGHT_CYAN = 96;
  599. const int COLOR_BRIGHT_WHITE = 97;
  600. NetMainLoop _mainLoopDriver = null;
  601. public override bool SupportsTrueColor => Environment.OSVersion.Platform == PlatformID.Unix || IsWinPlatform && Environment.OSVersion.Version.Build >= 14931;
  602. public NetWinVTConsole NetWinConsole { get; private set; }
  603. public bool IsWinPlatform { get; private set; }
  604. internal override MainLoop Init ()
  605. {
  606. var p = Environment.OSVersion.Platform;
  607. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) {
  608. IsWinPlatform = true;
  609. try {
  610. NetWinConsole = new NetWinVTConsole ();
  611. } catch (ApplicationException) {
  612. // Likely running as a unit test, or in a non-interactive session.
  613. }
  614. }
  615. if (IsWinPlatform) {
  616. Clipboard = new WindowsClipboard ();
  617. } else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
  618. Clipboard = new MacOSXClipboard ();
  619. } else {
  620. if (CursesDriver.Is_WSL_Platform ()) {
  621. Clipboard = new WSLClipboard ();
  622. } else {
  623. Clipboard = new CursesClipboard ();
  624. }
  625. }
  626. if (!RunningUnitTests) {
  627. Console.TreatControlCAsInput = true;
  628. Cols = Console.WindowWidth;
  629. Rows = Console.WindowHeight;
  630. //Enable alternative screen buffer.
  631. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  632. //Set cursor key to application.
  633. Console.Out.Write (EscSeqUtils.CSI_HideCursor);
  634. } else {
  635. // We are being run in an environment that does not support a console
  636. // such as a unit test, or a pipe.
  637. Cols = 80;
  638. Rows = 24;
  639. }
  640. ResizeScreen ();
  641. ClearContents ();
  642. CurrentAttribute = new Attribute (Color.White, Color.Black);
  643. StartReportingMouseMoves ();
  644. _mainLoopDriver = new NetMainLoop (this);
  645. _mainLoopDriver.ProcessInput = ProcessInput;
  646. return new MainLoop (_mainLoopDriver);
  647. }
  648. internal override void End ()
  649. {
  650. if (IsWinPlatform) {
  651. NetWinConsole?.Cleanup ();
  652. }
  653. StopReportingMouseMoves ();
  654. if (!RunningUnitTests) {
  655. Console.ResetColor ();
  656. //Disable alternative screen buffer.
  657. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  658. //Set cursor key to cursor.
  659. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  660. Console.Out.Close ();
  661. }
  662. }
  663. #region Size and Position Handling
  664. volatile bool _winSizeChanging;
  665. void SetWindowPosition (int col, int row)
  666. {
  667. if (!RunningUnitTests) {
  668. Top = Console.WindowTop;
  669. Left = Console.WindowLeft;
  670. } else {
  671. Top = row;
  672. Left = col;
  673. }
  674. }
  675. public virtual void ResizeScreen ()
  676. {
  677. // Not supported on Unix.
  678. if (IsWinPlatform) {
  679. // Can raise an exception while is still resizing.
  680. try {
  681. #pragma warning disable CA1416
  682. if (Console.WindowHeight > 0) {
  683. Console.CursorTop = 0;
  684. Console.CursorLeft = 0;
  685. Console.WindowTop = 0;
  686. Console.WindowLeft = 0;
  687. if (Console.WindowHeight > Rows) {
  688. Console.SetWindowSize (Cols, Rows);
  689. }
  690. Console.SetBufferSize (Cols, Rows);
  691. }
  692. #pragma warning restore CA1416
  693. } catch (IOException) {
  694. Clip = new Rect (0, 0, Cols, Rows);
  695. } catch (ArgumentOutOfRangeException) {
  696. Clip = new Rect (0, 0, Cols, Rows);
  697. }
  698. } else {
  699. Console.Out.Write (EscSeqUtils.CSI_SetTerminalWindowSize (Rows, Cols));
  700. }
  701. Clip = new Rect (0, 0, Cols, Rows);
  702. }
  703. #endregion
  704. public override void Refresh ()
  705. {
  706. UpdateScreen ();
  707. UpdateCursor ();
  708. }
  709. public override void UpdateScreen ()
  710. {
  711. if (RunningUnitTests || _winSizeChanging || Console.WindowHeight < 1 || Contents.Length != Rows * Cols || Rows != Console.WindowHeight) {
  712. return;
  713. }
  714. int top = 0;
  715. int left = 0;
  716. int rows = Rows;
  717. int cols = Cols;
  718. var output = new StringBuilder ();
  719. var redrawAttr = new Attribute ();
  720. int lastCol = -1;
  721. var savedVisibitity = _cachedCursorVisibility;
  722. SetCursorVisibility (CursorVisibility.Invisible);
  723. for (int row = top; row < rows; row++) {
  724. if (Console.WindowHeight < 1) {
  725. return;
  726. }
  727. if (!_dirtyLines [row]) {
  728. continue;
  729. }
  730. if (!SetCursorPosition (0, row)) {
  731. return;
  732. }
  733. _dirtyLines [row] = false;
  734. output.Clear ();
  735. for (int col = left; col < cols; col++) {
  736. lastCol = -1;
  737. int outputWidth = 0;
  738. for (; col < cols; col++) {
  739. if (!Contents [row, col].IsDirty) {
  740. if (output.Length > 0) {
  741. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  742. } else if (lastCol == -1) {
  743. lastCol = col;
  744. }
  745. if (lastCol + 1 < cols)
  746. lastCol++;
  747. continue;
  748. }
  749. if (lastCol == -1) {
  750. lastCol = col;
  751. }
  752. var attr = Contents [row, col].Attribute.Value;
  753. // Performance: Only send the escape sequence if the attribute has changed.
  754. if (attr != redrawAttr) {
  755. redrawAttr = attr;
  756. if (Force16Colors) {
  757. output.Append (EscSeqUtils.CSI_SetGraphicsRendition (
  758. MapColors ((ConsoleColor)attr.Background.ColorName, false), MapColors ((ConsoleColor)attr.Foreground.ColorName, true)));
  759. } else {
  760. output.Append (EscSeqUtils.CSI_SetForegroundColorRGB (attr.Foreground.R, attr.Foreground.G, attr.Foreground.B));
  761. output.Append (EscSeqUtils.CSI_SetBackgroundColorRGB (attr.Background.R, attr.Background.G, attr.Background.B));
  762. }
  763. }
  764. outputWidth++;
  765. var rune = (Rune)Contents [row, col].Rune;
  766. output.Append (rune);
  767. if (Contents [row, col].CombiningMarks.Count > 0) {
  768. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  769. // compatible with the driver architecture. Any CMs (except in the first col)
  770. // are correctly combined with the base char, but are ALSO treated as 1 column
  771. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  772. //
  773. // For now, we just ignore the list of CMs.
  774. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  775. // output.Append (combMark);
  776. //}
  777. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  778. } else if (rune.IsSurrogatePair () && rune.GetColumns () < 2) {
  779. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  780. SetCursorPosition (col - 1, row);
  781. }
  782. Contents [row, col].IsDirty = false;
  783. }
  784. }
  785. if (output.Length > 0) {
  786. SetCursorPosition (lastCol, row);
  787. Console.Write (output);
  788. }
  789. }
  790. SetCursorPosition (0, 0);
  791. _cachedCursorVisibility = savedVisibitity;
  792. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  793. {
  794. SetCursorPosition (lastCol, row);
  795. Console.Write (output);
  796. output.Clear ();
  797. lastCol += outputWidth;
  798. outputWidth = 0;
  799. }
  800. }
  801. #region Color Handling
  802. // Cache the list of ConsoleColor values.
  803. static readonly HashSet<int> ConsoleColorValues = new (
  804. Enum.GetValues (typeof (ConsoleColor)).OfType<ConsoleColor> ().Select (c => (int)c)
  805. );
  806. // Dictionary for mapping ConsoleColor values to the values used by System.Net.Console.
  807. static Dictionary<ConsoleColor, int> colorMap = new () {
  808. { ConsoleColor.Black, COLOR_BLACK },
  809. { ConsoleColor.DarkBlue, COLOR_BLUE },
  810. { ConsoleColor.DarkGreen, COLOR_GREEN },
  811. { ConsoleColor.DarkCyan, COLOR_CYAN },
  812. { ConsoleColor.DarkRed, COLOR_RED },
  813. { ConsoleColor.DarkMagenta, COLOR_MAGENTA },
  814. { ConsoleColor.DarkYellow, COLOR_YELLOW },
  815. { ConsoleColor.Gray, COLOR_WHITE },
  816. { ConsoleColor.DarkGray, COLOR_BRIGHT_BLACK },
  817. { ConsoleColor.Blue, COLOR_BRIGHT_BLUE },
  818. { ConsoleColor.Green, COLOR_BRIGHT_GREEN },
  819. { ConsoleColor.Cyan, COLOR_BRIGHT_CYAN },
  820. { ConsoleColor.Red, COLOR_BRIGHT_RED },
  821. { ConsoleColor.Magenta, COLOR_BRIGHT_MAGENTA },
  822. { ConsoleColor.Yellow, COLOR_BRIGHT_YELLOW },
  823. { ConsoleColor.White, COLOR_BRIGHT_WHITE }
  824. };
  825. // Map a ConsoleColor to a platform dependent value.
  826. int MapColors (ConsoleColor color, bool isForeground = true) => colorMap.TryGetValue (color, out int colorValue) ? colorValue + (isForeground ? 0 : 10) : 0;
  827. ///// <remarks>
  828. ///// In the NetDriver, colors are encoded as an int.
  829. ///// However, the foreground color is stored in the most significant 16 bits,
  830. ///// and the background color is stored in the least significant 16 bits.
  831. ///// </remarks>
  832. //public override Attribute MakeColor (Color foreground, Color background)
  833. //{
  834. // // Encode the colors into the int value.
  835. // return new Attribute (
  836. // platformColor: ((((int)foreground.ColorName) & 0xffff) << 16) | (((int)background.ColorName) & 0xffff),
  837. // foreground: foreground,
  838. // background: background
  839. // );
  840. //}
  841. #endregion
  842. #region Cursor Handling
  843. bool SetCursorPosition (int col, int row)
  844. {
  845. if (IsWinPlatform) {
  846. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  847. try {
  848. Console.SetCursorPosition (col, row);
  849. return true;
  850. } catch (Exception) {
  851. return false;
  852. }
  853. } else {
  854. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  855. // Console.CursorTop/CursorLeft isn't reliable.
  856. Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1));
  857. return true;
  858. }
  859. }
  860. CursorVisibility? _cachedCursorVisibility;
  861. public override void UpdateCursor ()
  862. {
  863. EnsureCursorVisibility ();
  864. if (Col >= 0 && Col < Cols && Row >= 0 && Row < Rows) {
  865. SetCursorPosition (Col, Row);
  866. SetWindowPosition (0, Row);
  867. }
  868. }
  869. public override bool GetCursorVisibility (out CursorVisibility visibility)
  870. {
  871. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  872. return visibility == CursorVisibility.Default;
  873. }
  874. public override bool SetCursorVisibility (CursorVisibility visibility)
  875. {
  876. _cachedCursorVisibility = visibility;
  877. bool isVisible = RunningUnitTests ? visibility == CursorVisibility.Default : Console.CursorVisible = visibility == CursorVisibility.Default;
  878. Console.Out.Write (isVisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  879. return isVisible;
  880. }
  881. public override bool EnsureCursorVisibility ()
  882. {
  883. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows)) {
  884. GetCursorVisibility (out var cursorVisibility);
  885. _cachedCursorVisibility = cursorVisibility;
  886. SetCursorVisibility (CursorVisibility.Invisible);
  887. return false;
  888. }
  889. SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default);
  890. return _cachedCursorVisibility == CursorVisibility.Default;
  891. }
  892. #endregion
  893. #region Mouse Handling
  894. public void StartReportingMouseMoves ()
  895. {
  896. if (!RunningUnitTests) {
  897. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  898. }
  899. }
  900. public void StopReportingMouseMoves ()
  901. {
  902. if (!RunningUnitTests) {
  903. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  904. }
  905. }
  906. MouseEvent ToDriverMouse (NetEvents.MouseEvent me)
  907. {
  908. //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}");
  909. MouseFlags mouseFlag = 0;
  910. if ((me.ButtonState & MouseButtonState.Button1Pressed) != 0) {
  911. mouseFlag |= MouseFlags.Button1Pressed;
  912. }
  913. if ((me.ButtonState & MouseButtonState.Button1Released) != 0) {
  914. mouseFlag |= MouseFlags.Button1Released;
  915. }
  916. if ((me.ButtonState & MouseButtonState.Button1Clicked) != 0) {
  917. mouseFlag |= MouseFlags.Button1Clicked;
  918. }
  919. if ((me.ButtonState & MouseButtonState.Button1DoubleClicked) != 0) {
  920. mouseFlag |= MouseFlags.Button1DoubleClicked;
  921. }
  922. if ((me.ButtonState & MouseButtonState.Button1TripleClicked) != 0) {
  923. mouseFlag |= MouseFlags.Button1TripleClicked;
  924. }
  925. if ((me.ButtonState & MouseButtonState.Button2Pressed) != 0) {
  926. mouseFlag |= MouseFlags.Button2Pressed;
  927. }
  928. if ((me.ButtonState & MouseButtonState.Button2Released) != 0) {
  929. mouseFlag |= MouseFlags.Button2Released;
  930. }
  931. if ((me.ButtonState & MouseButtonState.Button2Clicked) != 0) {
  932. mouseFlag |= MouseFlags.Button2Clicked;
  933. }
  934. if ((me.ButtonState & MouseButtonState.Button2DoubleClicked) != 0) {
  935. mouseFlag |= MouseFlags.Button2DoubleClicked;
  936. }
  937. if ((me.ButtonState & MouseButtonState.Button2TripleClicked) != 0) {
  938. mouseFlag |= MouseFlags.Button2TripleClicked;
  939. }
  940. if ((me.ButtonState & MouseButtonState.Button3Pressed) != 0) {
  941. mouseFlag |= MouseFlags.Button3Pressed;
  942. }
  943. if ((me.ButtonState & MouseButtonState.Button3Released) != 0) {
  944. mouseFlag |= MouseFlags.Button3Released;
  945. }
  946. if ((me.ButtonState & MouseButtonState.Button3Clicked) != 0) {
  947. mouseFlag |= MouseFlags.Button3Clicked;
  948. }
  949. if ((me.ButtonState & MouseButtonState.Button3DoubleClicked) != 0) {
  950. mouseFlag |= MouseFlags.Button3DoubleClicked;
  951. }
  952. if ((me.ButtonState & MouseButtonState.Button3TripleClicked) != 0) {
  953. mouseFlag |= MouseFlags.Button3TripleClicked;
  954. }
  955. if ((me.ButtonState & MouseButtonState.ButtonWheeledUp) != 0) {
  956. mouseFlag |= MouseFlags.WheeledUp;
  957. }
  958. if ((me.ButtonState & MouseButtonState.ButtonWheeledDown) != 0) {
  959. mouseFlag |= MouseFlags.WheeledDown;
  960. }
  961. if ((me.ButtonState & MouseButtonState.ButtonWheeledLeft) != 0) {
  962. mouseFlag |= MouseFlags.WheeledLeft;
  963. }
  964. if ((me.ButtonState & MouseButtonState.ButtonWheeledRight) != 0) {
  965. mouseFlag |= MouseFlags.WheeledRight;
  966. }
  967. if ((me.ButtonState & MouseButtonState.Button4Pressed) != 0) {
  968. mouseFlag |= MouseFlags.Button4Pressed;
  969. }
  970. if ((me.ButtonState & MouseButtonState.Button4Released) != 0) {
  971. mouseFlag |= MouseFlags.Button4Released;
  972. }
  973. if ((me.ButtonState & MouseButtonState.Button4Clicked) != 0) {
  974. mouseFlag |= MouseFlags.Button4Clicked;
  975. }
  976. if ((me.ButtonState & MouseButtonState.Button4DoubleClicked) != 0) {
  977. mouseFlag |= MouseFlags.Button4DoubleClicked;
  978. }
  979. if ((me.ButtonState & MouseButtonState.Button4TripleClicked) != 0) {
  980. mouseFlag |= MouseFlags.Button4TripleClicked;
  981. }
  982. if ((me.ButtonState & MouseButtonState.ReportMousePosition) != 0) {
  983. mouseFlag |= MouseFlags.ReportMousePosition;
  984. }
  985. if ((me.ButtonState & MouseButtonState.ButtonShift) != 0) {
  986. mouseFlag |= MouseFlags.ButtonShift;
  987. }
  988. if ((me.ButtonState & MouseButtonState.ButtonCtrl) != 0) {
  989. mouseFlag |= MouseFlags.ButtonCtrl;
  990. }
  991. if ((me.ButtonState & MouseButtonState.ButtonAlt) != 0) {
  992. mouseFlag |= MouseFlags.ButtonAlt;
  993. }
  994. return new MouseEvent () {
  995. X = me.Position.X,
  996. Y = me.Position.Y,
  997. Flags = mouseFlag
  998. };
  999. }
  1000. #endregion Mouse Handling
  1001. #region Keyboard Handling
  1002. ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  1003. {
  1004. if (consoleKeyInfo.Key != ConsoleKey.Packet) {
  1005. return consoleKeyInfo;
  1006. }
  1007. var mod = consoleKeyInfo.Modifiers;
  1008. bool shift = (mod & ConsoleModifiers.Shift) != 0;
  1009. bool alt = (mod & ConsoleModifiers.Alt) != 0;
  1010. bool control = (mod & ConsoleModifiers.Control) != 0;
  1011. var cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  1012. return new ConsoleKeyInfo (cKeyInfo.KeyChar, cKeyInfo.Key, shift, alt, control);
  1013. }
  1014. KeyCode MapKey (ConsoleKeyInfo keyInfo)
  1015. {
  1016. switch (keyInfo.Key) {
  1017. case ConsoleKey.OemPeriod:
  1018. case ConsoleKey.OemComma:
  1019. case ConsoleKey.OemPlus:
  1020. case ConsoleKey.OemMinus:
  1021. case ConsoleKey.Packet:
  1022. case ConsoleKey.Oem1:
  1023. case ConsoleKey.Oem2:
  1024. case ConsoleKey.Oem3:
  1025. case ConsoleKey.Oem4:
  1026. case ConsoleKey.Oem5:
  1027. case ConsoleKey.Oem6:
  1028. case ConsoleKey.Oem7:
  1029. case ConsoleKey.Oem8:
  1030. case ConsoleKey.Oem102:
  1031. if (keyInfo.KeyChar == 0) {
  1032. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  1033. return KeyCode.Null;// MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode)keyInfo.Key);
  1034. } else {
  1035. if (keyInfo.Modifiers != ConsoleModifiers.Shift) {
  1036. // If Shift wasn't down we don't need to do anything but return the keyInfo.KeyChar
  1037. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(keyInfo.KeyChar));
  1038. }
  1039. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç")
  1040. // and passing on Shift would be redundant.
  1041. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1042. }
  1043. }
  1044. var key = keyInfo.Key;
  1045. // A..Z are special cased:
  1046. // - Alone, they represent lowercase a...z
  1047. // - With ShiftMask they are A..Z
  1048. // - If CapsLock is on the above is reversed.
  1049. // - If Alt and/or Ctrl are present, treat as upper case
  1050. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z) {
  1051. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)) {
  1052. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  1053. }
  1054. if (keyInfo.Modifiers == ConsoleModifiers.Shift) {
  1055. // If ShiftMask is on add the ShiftMask
  1056. if (char.IsUpper (keyInfo.KeyChar)) {
  1057. return (KeyCode)((uint)keyInfo.Key) | KeyCode.ShiftMask;
  1058. }
  1059. }
  1060. return (KeyCode)(uint)keyInfo.KeyChar;
  1061. }
  1062. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  1063. if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key)) {
  1064. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(keyInfo.Key));
  1065. }
  1066. // Handle control keys (e.g. CursorUp)
  1067. if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), ((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))) {
  1068. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  1069. }
  1070. return (KeyCode)(uint)keyInfo.KeyChar;
  1071. }
  1072. #endregion Keyboard Handling
  1073. void ProcessInput (InputResult inputEvent)
  1074. {
  1075. switch (inputEvent.EventType) {
  1076. case NetEvents.EventType.Key:
  1077. var consoleKeyInfo = inputEvent.ConsoleKeyInfo;
  1078. //if (consoleKeyInfo.Key == ConsoleKey.Packet) {
  1079. // consoleKeyInfo = FromVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  1080. //}
  1081. //Debug.WriteLine ($"event: {inputEvent}");
  1082. var map = MapKey (consoleKeyInfo);
  1083. if (map == KeyCode.Null) {
  1084. break;
  1085. }
  1086. OnKeyDown (new Key (map));
  1087. OnKeyUp (new Key (map));
  1088. break;
  1089. case NetEvents.EventType.Mouse:
  1090. OnMouseEvent (new MouseEventEventArgs (ToDriverMouse (inputEvent.MouseEvent)));
  1091. break;
  1092. case NetEvents.EventType.WindowSize:
  1093. _winSizeChanging = true;
  1094. Top = 0;
  1095. Left = 0;
  1096. Cols = inputEvent.WindowSizeEvent.Size.Width;
  1097. Rows = Math.Max (inputEvent.WindowSizeEvent.Size.Height, 0);
  1098. ;
  1099. ResizeScreen ();
  1100. ClearContents ();
  1101. _winSizeChanging = false;
  1102. OnSizeChanged (new SizeChangedEventArgs (new Size (Cols, Rows)));
  1103. break;
  1104. case NetEvents.EventType.RequestResponse:
  1105. break;
  1106. case NetEvents.EventType.WindowPosition:
  1107. break;
  1108. default:
  1109. throw new ArgumentOutOfRangeException ();
  1110. }
  1111. }
  1112. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1113. {
  1114. var input = new InputResult {
  1115. EventType = NetEvents.EventType.Key,
  1116. ConsoleKeyInfo = new ConsoleKeyInfo (keyChar, key, shift, alt, control)
  1117. };
  1118. try {
  1119. ProcessInput (input);
  1120. } catch (OverflowException) { }
  1121. }
  1122. #region Not Implemented
  1123. public override void Suspend () => throw new NotImplementedException ();
  1124. #endregion
  1125. }
  1126. /// <summary>
  1127. /// Mainloop intended to be used with the .NET System.Console API, and can
  1128. /// be used on Windows and Unix, it is cross platform but lacks things like
  1129. /// file descriptor monitoring.
  1130. /// </summary>
  1131. /// <remarks>
  1132. /// This implementation is used for NetDriver.
  1133. /// </remarks>
  1134. class NetMainLoop : IMainLoopDriver {
  1135. readonly ManualResetEventSlim _eventReady = new (false);
  1136. readonly ManualResetEventSlim _waitForProbe = new (false);
  1137. readonly Queue<InputResult?> _resultQueue = new ();
  1138. MainLoop _mainLoop;
  1139. CancellationTokenSource _eventReadyTokenSource = new ();
  1140. readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  1141. internal NetEvents _netEvents;
  1142. /// <summary>
  1143. /// Invoked when a Key is pressed.
  1144. /// </summary>
  1145. internal Action<InputResult> ProcessInput;
  1146. /// <summary>
  1147. /// Initializes the class with the console driver.
  1148. /// </summary>
  1149. /// <remarks>
  1150. /// Passing a consoleDriver is provided to capture windows resizing.
  1151. /// </remarks>
  1152. /// <param name="consoleDriver">The console driver used by this Net main loop.</param>
  1153. /// <exception cref="ArgumentNullException"></exception>
  1154. public NetMainLoop (ConsoleDriver consoleDriver = null)
  1155. {
  1156. if (consoleDriver == null) {
  1157. throw new ArgumentNullException (nameof (consoleDriver));
  1158. }
  1159. _netEvents = new NetEvents (consoleDriver);
  1160. }
  1161. void NetInputHandler ()
  1162. {
  1163. while (_mainLoop != null) {
  1164. try {
  1165. if (!_inputHandlerTokenSource.IsCancellationRequested) {
  1166. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1167. }
  1168. } catch (OperationCanceledException) {
  1169. return;
  1170. } finally {
  1171. if (_waitForProbe.IsSet) {
  1172. _waitForProbe.Reset ();
  1173. }
  1174. }
  1175. if (_inputHandlerTokenSource.IsCancellationRequested) {
  1176. return;
  1177. }
  1178. if (_resultQueue.Count == 0) {
  1179. _resultQueue.Enqueue (_netEvents.DequeueInput ());
  1180. }
  1181. try {
  1182. while (_resultQueue.Peek () == null) {
  1183. _resultQueue.Dequeue ();
  1184. }
  1185. if (_resultQueue.Count > 0) {
  1186. _eventReady.Set ();
  1187. }
  1188. } catch (InvalidOperationException) {
  1189. // Ignore
  1190. }
  1191. }
  1192. }
  1193. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1194. {
  1195. _mainLoop = mainLoop;
  1196. Task.Run (NetInputHandler, _inputHandlerTokenSource.Token);
  1197. }
  1198. void IMainLoopDriver.Wakeup () => _eventReady.Set ();
  1199. bool IMainLoopDriver.EventsPending ()
  1200. {
  1201. _waitForProbe.Set ();
  1202. if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout)) {
  1203. return true;
  1204. }
  1205. try {
  1206. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1207. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1208. // are no timers, but there IS an idle handler waiting.
  1209. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1210. }
  1211. } catch (OperationCanceledException) {
  1212. return true;
  1213. } finally {
  1214. _eventReady.Reset ();
  1215. }
  1216. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1217. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1218. }
  1219. _eventReadyTokenSource.Dispose ();
  1220. _eventReadyTokenSource = new CancellationTokenSource ();
  1221. return true;
  1222. }
  1223. void IMainLoopDriver.Iteration ()
  1224. {
  1225. while (_resultQueue.Count > 0) {
  1226. ProcessInput?.Invoke (_resultQueue.Dequeue ().Value);
  1227. }
  1228. }
  1229. void IMainLoopDriver.TearDown ()
  1230. {
  1231. _inputHandlerTokenSource?.Cancel ();
  1232. _inputHandlerTokenSource?.Dispose ();
  1233. _eventReadyTokenSource?.Cancel ();
  1234. _eventReadyTokenSource?.Dispose ();
  1235. _eventReady?.Dispose ();
  1236. _resultQueue?.Clear ();
  1237. _waitForProbe?.Dispose ();
  1238. _netEvents?.Dispose ();
  1239. _netEvents = null;
  1240. _mainLoop = null;
  1241. }
  1242. }