NetDriver.cs 60 KB

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