NetDriver.cs 58 KB

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