NetDriver.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  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. }
  748. continue;
  749. }
  750. if (lastCol == -1) {
  751. lastCol = col;
  752. }
  753. var attr = Contents [row, col].Attribute.Value;
  754. // Performance: Only send the escape sequence if the attribute has changed.
  755. if (attr != redrawAttr) {
  756. redrawAttr = attr;
  757. if (Force16Colors) {
  758. output.Append (EscSeqUtils.CSI_SetGraphicsRendition (
  759. MapColors ((ConsoleColor)attr.Background.ColorName, false), MapColors ((ConsoleColor)attr.Foreground.ColorName, true)));
  760. } else {
  761. output.Append (EscSeqUtils.CSI_SetForegroundColorRGB (attr.Foreground.R, attr.Foreground.G, attr.Foreground.B));
  762. output.Append (EscSeqUtils.CSI_SetBackgroundColorRGB (attr.Background.R, attr.Background.G, attr.Background.B));
  763. }
  764. }
  765. outputWidth++;
  766. var rune = (Rune)Contents [row, col].Rune;
  767. output.Append (rune);
  768. if (Contents [row, col].CombiningMarks.Count > 0) {
  769. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  770. // compatible with the driver architecture. Any CMs (except in the first col)
  771. // are correctly combined with the base char, but are ALSO treated as 1 column
  772. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  773. //
  774. // For now, we just ignore the list of CMs.
  775. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  776. // output.Append (combMark);
  777. //}
  778. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  779. } else if (rune.IsSurrogatePair () && rune.GetColumns () < 2) {
  780. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  781. SetCursorPosition (col - 1, row);
  782. }
  783. Contents [row, col].IsDirty = false;
  784. }
  785. }
  786. if (output.Length > 0) {
  787. SetCursorPosition (lastCol, row);
  788. Console.Write (output);
  789. }
  790. }
  791. SetCursorPosition (0, 0);
  792. _cachedCursorVisibility = savedVisibitity;
  793. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  794. {
  795. SetCursorPosition (lastCol, row);
  796. Console.Write (output);
  797. output.Clear ();
  798. lastCol += outputWidth;
  799. outputWidth = 0;
  800. }
  801. }
  802. #region Color Handling
  803. // Cache the list of ConsoleColor values.
  804. static readonly HashSet<int> ConsoleColorValues = new (
  805. Enum.GetValues (typeof (ConsoleColor)).OfType<ConsoleColor> ().Select (c => (int)c)
  806. );
  807. // Dictionary for mapping ConsoleColor values to the values used by System.Net.Console.
  808. static Dictionary<ConsoleColor, int> colorMap = new () {
  809. { ConsoleColor.Black, COLOR_BLACK },
  810. { ConsoleColor.DarkBlue, COLOR_BLUE },
  811. { ConsoleColor.DarkGreen, COLOR_GREEN },
  812. { ConsoleColor.DarkCyan, COLOR_CYAN },
  813. { ConsoleColor.DarkRed, COLOR_RED },
  814. { ConsoleColor.DarkMagenta, COLOR_MAGENTA },
  815. { ConsoleColor.DarkYellow, COLOR_YELLOW },
  816. { ConsoleColor.Gray, COLOR_WHITE },
  817. { ConsoleColor.DarkGray, COLOR_BRIGHT_BLACK },
  818. { ConsoleColor.Blue, COLOR_BRIGHT_BLUE },
  819. { ConsoleColor.Green, COLOR_BRIGHT_GREEN },
  820. { ConsoleColor.Cyan, COLOR_BRIGHT_CYAN },
  821. { ConsoleColor.Red, COLOR_BRIGHT_RED },
  822. { ConsoleColor.Magenta, COLOR_BRIGHT_MAGENTA },
  823. { ConsoleColor.Yellow, COLOR_BRIGHT_YELLOW },
  824. { ConsoleColor.White, COLOR_BRIGHT_WHITE }
  825. };
  826. // Map a ConsoleColor to a platform dependent value.
  827. int MapColors (ConsoleColor color, bool isForeground = true) => colorMap.TryGetValue (color, out int colorValue) ? colorValue + (isForeground ? 0 : 10) : 0;
  828. ///// <remarks>
  829. ///// In the NetDriver, colors are encoded as an int.
  830. ///// However, the foreground color is stored in the most significant 16 bits,
  831. ///// and the background color is stored in the least significant 16 bits.
  832. ///// </remarks>
  833. //public override Attribute MakeColor (Color foreground, Color background)
  834. //{
  835. // // Encode the colors into the int value.
  836. // return new Attribute (
  837. // platformColor: ((((int)foreground.ColorName) & 0xffff) << 16) | (((int)background.ColorName) & 0xffff),
  838. // foreground: foreground,
  839. // background: background
  840. // );
  841. //}
  842. #endregion
  843. #region Cursor Handling
  844. bool SetCursorPosition (int col, int row)
  845. {
  846. if (IsWinPlatform) {
  847. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  848. try {
  849. Console.SetCursorPosition (col, row);
  850. return true;
  851. } catch (Exception) {
  852. return false;
  853. }
  854. } else {
  855. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  856. // Console.CursorTop/CursorLeft isn't reliable.
  857. Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1));
  858. return true;
  859. }
  860. }
  861. CursorVisibility? _cachedCursorVisibility;
  862. public override void UpdateCursor ()
  863. {
  864. EnsureCursorVisibility ();
  865. if (Col >= 0 && Col < Cols && Row >= 0 && Row < Rows) {
  866. SetCursorPosition (Col, Row);
  867. SetWindowPosition (0, Row);
  868. }
  869. }
  870. public override bool GetCursorVisibility (out CursorVisibility visibility)
  871. {
  872. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  873. return visibility == CursorVisibility.Default;
  874. }
  875. public override bool SetCursorVisibility (CursorVisibility visibility)
  876. {
  877. _cachedCursorVisibility = visibility;
  878. bool isVisible = RunningUnitTests ? visibility == CursorVisibility.Default : Console.CursorVisible = visibility == CursorVisibility.Default;
  879. Console.Out.Write (isVisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  880. return isVisible;
  881. }
  882. public override bool EnsureCursorVisibility ()
  883. {
  884. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows)) {
  885. GetCursorVisibility (out var cursorVisibility);
  886. _cachedCursorVisibility = cursorVisibility;
  887. SetCursorVisibility (CursorVisibility.Invisible);
  888. return false;
  889. }
  890. SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default);
  891. return _cachedCursorVisibility == CursorVisibility.Default;
  892. }
  893. #endregion
  894. #region Mouse Handling
  895. public void StartReportingMouseMoves ()
  896. {
  897. if (!RunningUnitTests) {
  898. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  899. }
  900. }
  901. public void StopReportingMouseMoves ()
  902. {
  903. if (!RunningUnitTests) {
  904. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  905. }
  906. }
  907. MouseEvent ToDriverMouse (NetEvents.MouseEvent me)
  908. {
  909. //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}");
  910. MouseFlags mouseFlag = 0;
  911. if ((me.ButtonState & MouseButtonState.Button1Pressed) != 0) {
  912. mouseFlag |= MouseFlags.Button1Pressed;
  913. }
  914. if ((me.ButtonState & MouseButtonState.Button1Released) != 0) {
  915. mouseFlag |= MouseFlags.Button1Released;
  916. }
  917. if ((me.ButtonState & MouseButtonState.Button1Clicked) != 0) {
  918. mouseFlag |= MouseFlags.Button1Clicked;
  919. }
  920. if ((me.ButtonState & MouseButtonState.Button1DoubleClicked) != 0) {
  921. mouseFlag |= MouseFlags.Button1DoubleClicked;
  922. }
  923. if ((me.ButtonState & MouseButtonState.Button1TripleClicked) != 0) {
  924. mouseFlag |= MouseFlags.Button1TripleClicked;
  925. }
  926. if ((me.ButtonState & MouseButtonState.Button2Pressed) != 0) {
  927. mouseFlag |= MouseFlags.Button2Pressed;
  928. }
  929. if ((me.ButtonState & MouseButtonState.Button2Released) != 0) {
  930. mouseFlag |= MouseFlags.Button2Released;
  931. }
  932. if ((me.ButtonState & MouseButtonState.Button2Clicked) != 0) {
  933. mouseFlag |= MouseFlags.Button2Clicked;
  934. }
  935. if ((me.ButtonState & MouseButtonState.Button2DoubleClicked) != 0) {
  936. mouseFlag |= MouseFlags.Button2DoubleClicked;
  937. }
  938. if ((me.ButtonState & MouseButtonState.Button2TripleClicked) != 0) {
  939. mouseFlag |= MouseFlags.Button2TripleClicked;
  940. }
  941. if ((me.ButtonState & MouseButtonState.Button3Pressed) != 0) {
  942. mouseFlag |= MouseFlags.Button3Pressed;
  943. }
  944. if ((me.ButtonState & MouseButtonState.Button3Released) != 0) {
  945. mouseFlag |= MouseFlags.Button3Released;
  946. }
  947. if ((me.ButtonState & MouseButtonState.Button3Clicked) != 0) {
  948. mouseFlag |= MouseFlags.Button3Clicked;
  949. }
  950. if ((me.ButtonState & MouseButtonState.Button3DoubleClicked) != 0) {
  951. mouseFlag |= MouseFlags.Button3DoubleClicked;
  952. }
  953. if ((me.ButtonState & MouseButtonState.Button3TripleClicked) != 0) {
  954. mouseFlag |= MouseFlags.Button3TripleClicked;
  955. }
  956. if ((me.ButtonState & MouseButtonState.ButtonWheeledUp) != 0) {
  957. mouseFlag |= MouseFlags.WheeledUp;
  958. }
  959. if ((me.ButtonState & MouseButtonState.ButtonWheeledDown) != 0) {
  960. mouseFlag |= MouseFlags.WheeledDown;
  961. }
  962. if ((me.ButtonState & MouseButtonState.ButtonWheeledLeft) != 0) {
  963. mouseFlag |= MouseFlags.WheeledLeft;
  964. }
  965. if ((me.ButtonState & MouseButtonState.ButtonWheeledRight) != 0) {
  966. mouseFlag |= MouseFlags.WheeledRight;
  967. }
  968. if ((me.ButtonState & MouseButtonState.Button4Pressed) != 0) {
  969. mouseFlag |= MouseFlags.Button4Pressed;
  970. }
  971. if ((me.ButtonState & MouseButtonState.Button4Released) != 0) {
  972. mouseFlag |= MouseFlags.Button4Released;
  973. }
  974. if ((me.ButtonState & MouseButtonState.Button4Clicked) != 0) {
  975. mouseFlag |= MouseFlags.Button4Clicked;
  976. }
  977. if ((me.ButtonState & MouseButtonState.Button4DoubleClicked) != 0) {
  978. mouseFlag |= MouseFlags.Button4DoubleClicked;
  979. }
  980. if ((me.ButtonState & MouseButtonState.Button4TripleClicked) != 0) {
  981. mouseFlag |= MouseFlags.Button4TripleClicked;
  982. }
  983. if ((me.ButtonState & MouseButtonState.ReportMousePosition) != 0) {
  984. mouseFlag |= MouseFlags.ReportMousePosition;
  985. }
  986. if ((me.ButtonState & MouseButtonState.ButtonShift) != 0) {
  987. mouseFlag |= MouseFlags.ButtonShift;
  988. }
  989. if ((me.ButtonState & MouseButtonState.ButtonCtrl) != 0) {
  990. mouseFlag |= MouseFlags.ButtonCtrl;
  991. }
  992. if ((me.ButtonState & MouseButtonState.ButtonAlt) != 0) {
  993. mouseFlag |= MouseFlags.ButtonAlt;
  994. }
  995. return new MouseEvent () {
  996. X = me.Position.X,
  997. Y = me.Position.Y,
  998. Flags = mouseFlag
  999. };
  1000. }
  1001. #endregion Mouse Handling
  1002. #region Keyboard Handling
  1003. ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  1004. {
  1005. if (consoleKeyInfo.Key != ConsoleKey.Packet) {
  1006. return consoleKeyInfo;
  1007. }
  1008. var mod = consoleKeyInfo.Modifiers;
  1009. bool shift = (mod & ConsoleModifiers.Shift) != 0;
  1010. bool alt = (mod & ConsoleModifiers.Alt) != 0;
  1011. bool control = (mod & ConsoleModifiers.Control) != 0;
  1012. var cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  1013. return new ConsoleKeyInfo (cKeyInfo.KeyChar, cKeyInfo.Key, shift, alt, control);
  1014. }
  1015. KeyCode MapKey (ConsoleKeyInfo keyInfo)
  1016. {
  1017. switch (keyInfo.Key) {
  1018. case ConsoleKey.OemPeriod:
  1019. case ConsoleKey.OemComma:
  1020. case ConsoleKey.OemPlus:
  1021. case ConsoleKey.OemMinus:
  1022. case ConsoleKey.Packet:
  1023. case ConsoleKey.Oem1:
  1024. case ConsoleKey.Oem2:
  1025. case ConsoleKey.Oem3:
  1026. case ConsoleKey.Oem4:
  1027. case ConsoleKey.Oem5:
  1028. case ConsoleKey.Oem6:
  1029. case ConsoleKey.Oem7:
  1030. case ConsoleKey.Oem8:
  1031. case ConsoleKey.Oem102:
  1032. if (keyInfo.KeyChar == 0) {
  1033. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  1034. return KeyCode.Null;// MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode)keyInfo.Key);
  1035. } else {
  1036. if (keyInfo.Modifiers != ConsoleModifiers.Shift) {
  1037. // If Shift wasn't down we don't need to do anything but return the keyInfo.KeyChar
  1038. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(keyInfo.KeyChar));
  1039. }
  1040. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç")
  1041. // and passing on Shift would be redundant.
  1042. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1043. }
  1044. break;
  1045. return (KeyCode)(uint)keyInfo.KeyChar;
  1046. }
  1047. var key = keyInfo.Key;
  1048. // A..Z are special cased:
  1049. // - Alone, they represent lowercase a...z
  1050. // - With ShiftMask they are A..Z
  1051. // - If CapsLock is on the above is reversed.
  1052. // - If Alt and/or Ctrl are present, treat as upper case
  1053. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z) {
  1054. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)) {
  1055. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  1056. }
  1057. if (keyInfo.Modifiers == ConsoleModifiers.Shift) {
  1058. // If ShiftMask is on add the ShiftMask
  1059. if (char.IsUpper (keyInfo.KeyChar)) {
  1060. return (KeyCode)((uint)keyInfo.Key) | KeyCode.ShiftMask;
  1061. }
  1062. }
  1063. return (KeyCode)(uint)keyInfo.KeyChar;
  1064. }
  1065. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  1066. if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key)) {
  1067. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(keyInfo.Key));
  1068. }
  1069. // Handle control keys (e.g. CursorUp)
  1070. if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), ((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))) {
  1071. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  1072. }
  1073. return (KeyCode)(uint)keyInfo.KeyChar;
  1074. }
  1075. #endregion Keyboard Handling
  1076. void ProcessInput (InputResult inputEvent)
  1077. {
  1078. switch (inputEvent.EventType) {
  1079. case NetEvents.EventType.Key:
  1080. var consoleKeyInfo = inputEvent.ConsoleKeyInfo;
  1081. //if (consoleKeyInfo.Key == ConsoleKey.Packet) {
  1082. // consoleKeyInfo = FromVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  1083. //}
  1084. //Debug.WriteLine ($"event: {inputEvent}");
  1085. var map = MapKey (consoleKeyInfo);
  1086. if (map == KeyCode.Null) {
  1087. break;
  1088. }
  1089. OnKeyDown (new Key (map));
  1090. OnKeyUp (new Key (map));
  1091. break;
  1092. case NetEvents.EventType.Mouse:
  1093. OnMouseEvent (new MouseEventEventArgs (ToDriverMouse (inputEvent.MouseEvent)));
  1094. break;
  1095. case NetEvents.EventType.WindowSize:
  1096. _winSizeChanging = true;
  1097. Top = 0;
  1098. Left = 0;
  1099. Cols = inputEvent.WindowSizeEvent.Size.Width;
  1100. Rows = Math.Max (inputEvent.WindowSizeEvent.Size.Height, 0);
  1101. ;
  1102. ResizeScreen ();
  1103. ClearContents ();
  1104. _winSizeChanging = false;
  1105. OnSizeChanged (new SizeChangedEventArgs (new Size (Cols, Rows)));
  1106. break;
  1107. case NetEvents.EventType.RequestResponse:
  1108. break;
  1109. case NetEvents.EventType.WindowPosition:
  1110. break;
  1111. default:
  1112. throw new ArgumentOutOfRangeException ();
  1113. }
  1114. }
  1115. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1116. {
  1117. var input = new InputResult {
  1118. EventType = NetEvents.EventType.Key,
  1119. ConsoleKeyInfo = new ConsoleKeyInfo (keyChar, key, shift, alt, control)
  1120. };
  1121. try {
  1122. ProcessInput (input);
  1123. } catch (OverflowException) { }
  1124. }
  1125. #region Not Implemented
  1126. public override void Suspend () => throw new NotImplementedException ();
  1127. #endregion
  1128. }
  1129. /// <summary>
  1130. /// Mainloop intended to be used with the .NET System.Console API, and can
  1131. /// be used on Windows and Unix, it is cross platform but lacks things like
  1132. /// file descriptor monitoring.
  1133. /// </summary>
  1134. /// <remarks>
  1135. /// This implementation is used for NetDriver.
  1136. /// </remarks>
  1137. class NetMainLoop : IMainLoopDriver {
  1138. readonly ManualResetEventSlim _eventReady = new (false);
  1139. readonly ManualResetEventSlim _waitForProbe = new (false);
  1140. readonly Queue<InputResult?> _resultQueue = new ();
  1141. MainLoop _mainLoop;
  1142. CancellationTokenSource _eventReadyTokenSource = new ();
  1143. readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  1144. internal NetEvents _netEvents;
  1145. /// <summary>
  1146. /// Invoked when a Key is pressed.
  1147. /// </summary>
  1148. internal Action<InputResult> ProcessInput;
  1149. /// <summary>
  1150. /// Initializes the class with the console driver.
  1151. /// </summary>
  1152. /// <remarks>
  1153. /// Passing a consoleDriver is provided to capture windows resizing.
  1154. /// </remarks>
  1155. /// <param name="consoleDriver">The console driver used by this Net main loop.</param>
  1156. /// <exception cref="ArgumentNullException"></exception>
  1157. public NetMainLoop (ConsoleDriver consoleDriver = null)
  1158. {
  1159. if (consoleDriver == null) {
  1160. throw new ArgumentNullException (nameof (consoleDriver));
  1161. }
  1162. _netEvents = new NetEvents (consoleDriver);
  1163. }
  1164. void NetInputHandler ()
  1165. {
  1166. while (_mainLoop != null) {
  1167. try {
  1168. if (!_inputHandlerTokenSource.IsCancellationRequested) {
  1169. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1170. }
  1171. } catch (OperationCanceledException) {
  1172. return;
  1173. } finally {
  1174. if (_waitForProbe.IsSet) {
  1175. _waitForProbe.Reset ();
  1176. }
  1177. }
  1178. if (_inputHandlerTokenSource.IsCancellationRequested) {
  1179. return;
  1180. }
  1181. if (_resultQueue.Count == 0) {
  1182. _resultQueue.Enqueue (_netEvents.DequeueInput ());
  1183. }
  1184. try {
  1185. while (_resultQueue.Peek () == null) {
  1186. _resultQueue.Dequeue ();
  1187. }
  1188. if (_resultQueue.Count > 0) {
  1189. _eventReady.Set ();
  1190. }
  1191. } catch (InvalidOperationException) {
  1192. // Ignore
  1193. }
  1194. }
  1195. }
  1196. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1197. {
  1198. _mainLoop = mainLoop;
  1199. Task.Run (NetInputHandler, _inputHandlerTokenSource.Token);
  1200. }
  1201. void IMainLoopDriver.Wakeup () => _eventReady.Set ();
  1202. bool IMainLoopDriver.EventsPending ()
  1203. {
  1204. _waitForProbe.Set ();
  1205. if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout)) {
  1206. return true;
  1207. }
  1208. try {
  1209. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1210. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1211. // are no timers, but there IS an idle handler waiting.
  1212. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1213. }
  1214. } catch (OperationCanceledException) {
  1215. return true;
  1216. } finally {
  1217. _eventReady.Reset ();
  1218. }
  1219. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1220. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1221. }
  1222. _eventReadyTokenSource.Dispose ();
  1223. _eventReadyTokenSource = new CancellationTokenSource ();
  1224. return true;
  1225. }
  1226. void IMainLoopDriver.Iteration ()
  1227. {
  1228. while (_resultQueue.Count > 0) {
  1229. ProcessInput?.Invoke (_resultQueue.Dequeue ().Value);
  1230. }
  1231. }
  1232. void IMainLoopDriver.TearDown ()
  1233. {
  1234. _inputHandlerTokenSource?.Cancel ();
  1235. _inputHandlerTokenSource?.Dispose ();
  1236. _eventReadyTokenSource?.Cancel ();
  1237. _eventReadyTokenSource?.Dispose ();
  1238. _eventReady?.Dispose ();
  1239. _resultQueue?.Clear ();
  1240. _waitForProbe?.Dispose ();
  1241. _netEvents?.Dispose ();
  1242. _netEvents = null;
  1243. _mainLoop = null;
  1244. }
  1245. }