NetDriver.cs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610
  1. //
  2. // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient.
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Diagnostics;
  10. using System.Linq;
  11. using System.Runtime.InteropServices;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using NStack;
  15. namespace Terminal.Gui {
  16. internal class NetWinVTConsole {
  17. IntPtr InputHandle, OutputHandle, ErrorHandle;
  18. uint originalInputConsoleMode, originalOutputConsoleMode, originalErrorConsoleMode;
  19. public NetWinVTConsole ()
  20. {
  21. InputHandle = GetStdHandle (STD_INPUT_HANDLE);
  22. if (!GetConsoleMode (InputHandle, out uint mode)) {
  23. throw new ApplicationException ($"Failed to get input console mode, error code: {GetLastError ()}.");
  24. }
  25. originalInputConsoleMode = mode;
  26. if ((mode & ENABLE_VIRTUAL_TERMINAL_INPUT) < ENABLE_VIRTUAL_TERMINAL_INPUT) {
  27. mode |= ENABLE_VIRTUAL_TERMINAL_INPUT;
  28. if (!SetConsoleMode (InputHandle, mode)) {
  29. throw new ApplicationException ($"Failed to set input console mode, error code: {GetLastError ()}.");
  30. }
  31. }
  32. OutputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  33. if (!GetConsoleMode (OutputHandle, out mode)) {
  34. throw new ApplicationException ($"Failed to get output console mode, error code: {GetLastError ()}.");
  35. }
  36. originalOutputConsoleMode = mode;
  37. if ((mode & (ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN)) < DISABLE_NEWLINE_AUTO_RETURN) {
  38. mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN;
  39. if (!SetConsoleMode (OutputHandle, mode)) {
  40. throw new ApplicationException ($"Failed to set output console mode, error code: {GetLastError ()}.");
  41. }
  42. }
  43. ErrorHandle = GetStdHandle (STD_ERROR_HANDLE);
  44. if (!GetConsoleMode (ErrorHandle, out mode)) {
  45. throw new ApplicationException ($"Failed to get error console mode, error code: {GetLastError ()}.");
  46. }
  47. originalErrorConsoleMode = mode;
  48. if ((mode & (DISABLE_NEWLINE_AUTO_RETURN)) < DISABLE_NEWLINE_AUTO_RETURN) {
  49. mode |= DISABLE_NEWLINE_AUTO_RETURN;
  50. if (!SetConsoleMode (ErrorHandle, mode)) {
  51. throw new ApplicationException ($"Failed to set error console mode, error code: {GetLastError ()}.");
  52. }
  53. }
  54. }
  55. public void Cleanup ()
  56. {
  57. if (!SetConsoleMode (InputHandle, originalInputConsoleMode)) {
  58. throw new ApplicationException ($"Failed to restore input console mode, error code: {GetLastError ()}.");
  59. }
  60. if (!SetConsoleMode (OutputHandle, originalOutputConsoleMode)) {
  61. throw new ApplicationException ($"Failed to restore output console mode, error code: {GetLastError ()}.");
  62. }
  63. if (!SetConsoleMode (ErrorHandle, originalErrorConsoleMode)) {
  64. throw new ApplicationException ($"Failed to restore error console mode, error code: {GetLastError ()}.");
  65. }
  66. }
  67. const int STD_INPUT_HANDLE = -10;
  68. const int STD_OUTPUT_HANDLE = -11;
  69. const int STD_ERROR_HANDLE = -12;
  70. // Input modes.
  71. const uint ENABLE_PROCESSED_INPUT = 1;
  72. const uint ENABLE_LINE_INPUT = 2;
  73. const uint ENABLE_ECHO_INPUT = 4;
  74. const uint ENABLE_WINDOW_INPUT = 8;
  75. const uint ENABLE_MOUSE_INPUT = 16;
  76. const uint ENABLE_INSERT_MODE = 32;
  77. const uint ENABLE_QUICK_EDIT_MODE = 64;
  78. const uint ENABLE_EXTENDED_FLAGS = 128;
  79. const uint ENABLE_VIRTUAL_TERMINAL_INPUT = 512;
  80. // Output modes.
  81. const uint ENABLE_PROCESSED_OUTPUT = 1;
  82. const uint ENABLE_WRAP_AT_EOL_OUTPUT = 2;
  83. const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4;
  84. const uint DISABLE_NEWLINE_AUTO_RETURN = 8;
  85. const uint ENABLE_LVB_GRID_WORLDWIDE = 10;
  86. [DllImport ("kernel32.dll", SetLastError = true)]
  87. static extern IntPtr GetStdHandle (int nStdHandle);
  88. [DllImport ("kernel32.dll")]
  89. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  90. [DllImport ("kernel32.dll")]
  91. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  92. [DllImport ("kernel32.dll")]
  93. static extern uint GetLastError ();
  94. }
  95. internal class NetEvents {
  96. ManualResetEventSlim inputReady = new ManualResetEventSlim (false);
  97. ManualResetEventSlim waitForStart = new ManualResetEventSlim (false);
  98. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  99. Queue<InputResult?> inputResultQueue = new Queue<InputResult?> ();
  100. ConsoleDriver consoleDriver;
  101. volatile ConsoleKeyInfo [] cki = null;
  102. static volatile bool isEscSeq;
  103. int lastWindowHeight;
  104. bool stopTasks;
  105. #if PROCESS_REQUEST
  106. bool neededProcessRequest;
  107. #endif
  108. public EscSeqReqProc EscSeqReqProc { get; } = new EscSeqReqProc ();
  109. public NetEvents (ConsoleDriver consoleDriver)
  110. {
  111. if (consoleDriver == null) {
  112. throw new ArgumentNullException ("Console driver instance must be provided.");
  113. }
  114. this.consoleDriver = consoleDriver;
  115. Task.Run (ProcessInputResultQueue);
  116. Task.Run (CheckWinChange);
  117. }
  118. internal void StopTasks ()
  119. {
  120. stopTasks = true;
  121. }
  122. public InputResult? ReadConsoleInput ()
  123. {
  124. while (true) {
  125. if (stopTasks) {
  126. return null;
  127. }
  128. waitForStart.Set ();
  129. winChange.Set ();
  130. if (inputResultQueue.Count == 0) {
  131. inputReady.Wait ();
  132. inputReady.Reset ();
  133. }
  134. #if PROCESS_REQUEST
  135. neededProcessRequest = false;
  136. #endif
  137. if (inputResultQueue.Count > 0) {
  138. return inputResultQueue.Dequeue ();
  139. }
  140. }
  141. }
  142. void ProcessInputResultQueue ()
  143. {
  144. while (true) {
  145. waitForStart.Wait ();
  146. waitForStart.Reset ();
  147. if (inputResultQueue.Count == 0) {
  148. GetConsoleKey ();
  149. }
  150. inputReady.Set ();
  151. }
  152. }
  153. void GetConsoleKey ()
  154. {
  155. ConsoleKey key = 0;
  156. ConsoleModifiers mod = 0;
  157. ConsoleKeyInfo newConsoleKeyInfo = default;
  158. while (true) {
  159. ConsoleKeyInfo consoleKeyInfo = Console.ReadKey (true);
  160. if ((consoleKeyInfo.KeyChar == (char)Key.Esc && !isEscSeq)
  161. || (consoleKeyInfo.KeyChar != (char)Key.Esc && isEscSeq)) {
  162. if (cki == null && consoleKeyInfo.KeyChar != (char)Key.Esc && isEscSeq) {
  163. cki = EscSeqUtils.ResizeArray (new ConsoleKeyInfo ((char)Key.Esc, 0,
  164. false, false, false), cki);
  165. }
  166. isEscSeq = true;
  167. newConsoleKeyInfo = consoleKeyInfo;
  168. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  169. if (!Console.KeyAvailable) {
  170. DecodeEscSeq (ref newConsoleKeyInfo, ref key, cki, ref mod);
  171. cki = null;
  172. isEscSeq = false;
  173. break;
  174. }
  175. } else if (consoleKeyInfo.KeyChar == (char)Key.Esc && isEscSeq) {
  176. DecodeEscSeq (ref newConsoleKeyInfo, ref key, cki, ref mod);
  177. cki = null;
  178. if (!Console.KeyAvailable) {
  179. isEscSeq = false;
  180. }
  181. break;
  182. } else {
  183. GetConsoleInputType (consoleKeyInfo);
  184. break;
  185. }
  186. }
  187. }
  188. void CheckWinChange ()
  189. {
  190. while (true) {
  191. if (stopTasks) {
  192. return;
  193. }
  194. winChange.Wait ();
  195. winChange.Reset ();
  196. WaitWinChange ();
  197. inputReady.Set ();
  198. }
  199. }
  200. void WaitWinChange ()
  201. {
  202. while (true) {
  203. // Wait for a while then check if screen has changed sizes
  204. Task.Delay (500).Wait ();
  205. if (stopTasks) {
  206. return;
  207. }
  208. int buffHeight, buffWidth;
  209. if (((NetDriver)consoleDriver).IsWinPlatform) {
  210. buffHeight = Math.Max (Console.BufferHeight, 0);
  211. buffWidth = Math.Max (Console.BufferWidth, 0);
  212. } else {
  213. buffHeight = consoleDriver.Rows;
  214. buffWidth = consoleDriver.Cols;
  215. }
  216. if (IsWinChanged (
  217. Math.Max (Console.WindowHeight, 0),
  218. Math.Max (Console.WindowWidth, 0),
  219. buffHeight,
  220. buffWidth)) {
  221. return;
  222. }
  223. }
  224. }
  225. bool IsWinChanged (int winHeight, int winWidth, int buffHeight, int buffWidth)
  226. {
  227. if (!consoleDriver.EnableConsoleScrolling) {
  228. if (winWidth != consoleDriver.Cols || winHeight != consoleDriver.Rows) {
  229. var w = Math.Max (winWidth, 0);
  230. var h = Math.Max (winHeight, 0);
  231. GetWindowSizeEvent (new Size (w, h));
  232. return true;
  233. }
  234. } else {
  235. if (winWidth != consoleDriver.Cols || winHeight != lastWindowHeight
  236. || buffWidth != consoleDriver.Cols || buffHeight != consoleDriver.Rows) {
  237. lastWindowHeight = Math.Max (winHeight, 0);
  238. GetWindowSizeEvent (new Size (winWidth, lastWindowHeight));
  239. return true;
  240. }
  241. }
  242. return false;
  243. }
  244. void GetWindowSizeEvent (Size size)
  245. {
  246. WindowSizeEvent windowSizeEvent = new WindowSizeEvent () {
  247. Size = size
  248. };
  249. inputResultQueue.Enqueue (new InputResult () {
  250. EventType = EventType.WindowSize,
  251. WindowSizeEvent = windowSizeEvent
  252. });
  253. }
  254. void GetConsoleInputType (ConsoleKeyInfo consoleKeyInfo)
  255. {
  256. InputResult inputResult = new InputResult {
  257. EventType = EventType.Key
  258. };
  259. MouseEvent mouseEvent = new MouseEvent ();
  260. ConsoleKeyInfo newConsoleKeyInfo = EscSeqUtils.GetConsoleInputKey (consoleKeyInfo);
  261. if (inputResult.EventType == EventType.Key) {
  262. inputResult.ConsoleKeyInfo = newConsoleKeyInfo;
  263. } else {
  264. inputResult.MouseEvent = mouseEvent;
  265. }
  266. inputResultQueue.Enqueue (inputResult);
  267. }
  268. void DecodeEscSeq (ref ConsoleKeyInfo newConsoleKeyInfo, ref ConsoleKey key, ConsoleKeyInfo [] cki, ref ConsoleModifiers mod)
  269. {
  270. string c1Control, code, terminating;
  271. string [] values;
  272. // isKeyMouse is true if it's CSI<, false otherwise
  273. bool isKeyMouse;
  274. bool isReq;
  275. List<MouseFlags> mouseFlags;
  276. Point pos;
  277. EscSeqUtils.DecodeEscSeq (EscSeqReqProc, ref newConsoleKeyInfo, ref key, cki, ref mod, out c1Control, out code, out values, out terminating, out isKeyMouse, out mouseFlags, out pos, out isReq, ProcessContinuousButtonPressed);
  278. if (isKeyMouse) {
  279. foreach (var mf in mouseFlags) {
  280. GetMouseEvent (MapMouseFlags (mf), pos);
  281. }
  282. return;
  283. } else if (isReq) {
  284. GetRequestEvent (c1Control, code, values, terminating);
  285. return;
  286. }
  287. InputResult inputResult = new InputResult {
  288. EventType = EventType.Key,
  289. ConsoleKeyInfo = newConsoleKeyInfo
  290. };
  291. inputResultQueue.Enqueue (inputResult);
  292. }
  293. void ProcessContinuousButtonPressed (MouseFlags mouseFlag, Point pos)
  294. {
  295. GetMouseEvent (MapMouseFlags (mouseFlag), pos);
  296. }
  297. MouseButtonState MapMouseFlags (MouseFlags mouseFlags)
  298. {
  299. MouseButtonState mbs = default;
  300. foreach (var flag in Enum.GetValues (mouseFlags.GetType ())) {
  301. if (mouseFlags.HasFlag ((MouseFlags)flag)) {
  302. switch (flag) {
  303. case MouseFlags.Button1Pressed:
  304. mbs |= MouseButtonState.Button1Pressed;
  305. break;
  306. case MouseFlags.Button1Released:
  307. mbs |= MouseButtonState.Button1Released;
  308. break;
  309. case MouseFlags.Button1Clicked:
  310. mbs |= MouseButtonState.Button1Clicked;
  311. break;
  312. case MouseFlags.Button1DoubleClicked:
  313. mbs |= MouseButtonState.Button1DoubleClicked;
  314. break;
  315. case MouseFlags.Button1TripleClicked:
  316. mbs |= MouseButtonState.Button1TripleClicked;
  317. break;
  318. case MouseFlags.Button2Pressed:
  319. mbs |= MouseButtonState.Button2Pressed;
  320. break;
  321. case MouseFlags.Button2Released:
  322. mbs |= MouseButtonState.Button2Released;
  323. break;
  324. case MouseFlags.Button2Clicked:
  325. mbs |= MouseButtonState.Button2Clicked;
  326. break;
  327. case MouseFlags.Button2DoubleClicked:
  328. mbs |= MouseButtonState.Button2DoubleClicked;
  329. break;
  330. case MouseFlags.Button2TripleClicked:
  331. mbs |= MouseButtonState.Button2TripleClicked;
  332. break;
  333. case MouseFlags.Button3Pressed:
  334. mbs |= MouseButtonState.Button3Pressed;
  335. break;
  336. case MouseFlags.Button3Released:
  337. mbs |= MouseButtonState.Button3Released;
  338. break;
  339. case MouseFlags.Button3Clicked:
  340. mbs |= MouseButtonState.Button3Clicked;
  341. break;
  342. case MouseFlags.Button3DoubleClicked:
  343. mbs |= MouseButtonState.Button3DoubleClicked;
  344. break;
  345. case MouseFlags.Button3TripleClicked:
  346. mbs |= MouseButtonState.Button3TripleClicked;
  347. break;
  348. case MouseFlags.WheeledUp:
  349. mbs |= MouseButtonState.ButtonWheeledUp;
  350. break;
  351. case MouseFlags.WheeledDown:
  352. mbs |= MouseButtonState.ButtonWheeledDown;
  353. break;
  354. case MouseFlags.WheeledLeft:
  355. mbs |= MouseButtonState.ButtonWheeledLeft;
  356. break;
  357. case MouseFlags.WheeledRight:
  358. mbs |= MouseButtonState.ButtonWheeledRight;
  359. break;
  360. case MouseFlags.Button4Pressed:
  361. mbs |= MouseButtonState.Button4Pressed;
  362. break;
  363. case MouseFlags.Button4Released:
  364. mbs |= MouseButtonState.Button4Released;
  365. break;
  366. case MouseFlags.Button4Clicked:
  367. mbs |= MouseButtonState.Button4Clicked;
  368. break;
  369. case MouseFlags.Button4DoubleClicked:
  370. mbs |= MouseButtonState.Button4DoubleClicked;
  371. break;
  372. case MouseFlags.Button4TripleClicked:
  373. mbs |= MouseButtonState.Button4TripleClicked;
  374. break;
  375. case MouseFlags.ButtonShift:
  376. mbs |= MouseButtonState.ButtonShift;
  377. break;
  378. case MouseFlags.ButtonCtrl:
  379. mbs |= MouseButtonState.ButtonCtrl;
  380. break;
  381. case MouseFlags.ButtonAlt:
  382. mbs |= MouseButtonState.ButtonAlt;
  383. break;
  384. case MouseFlags.ReportMousePosition:
  385. mbs |= MouseButtonState.ReportMousePosition;
  386. break;
  387. case MouseFlags.AllEvents:
  388. mbs |= MouseButtonState.AllEvents;
  389. break;
  390. }
  391. }
  392. }
  393. return mbs;
  394. }
  395. Point lastCursorPosition;
  396. void GetRequestEvent (string c1Control, string code, string [] values, string terminating)
  397. {
  398. EventType eventType = new EventType ();
  399. switch (terminating) {
  400. case "R": // Reports cursor position as CSI r ; c R
  401. Point point = new Point {
  402. X = int.Parse (values [1]) - 1,
  403. Y = int.Parse (values [0]) - 1
  404. };
  405. if (lastCursorPosition.Y != point.Y) {
  406. lastCursorPosition = point;
  407. eventType = EventType.WindowPosition;
  408. var winPositionEv = new WindowPositionEvent () {
  409. CursorPosition = point
  410. };
  411. inputResultQueue.Enqueue (new InputResult () {
  412. EventType = eventType,
  413. WindowPositionEvent = winPositionEv
  414. });
  415. } else {
  416. return;
  417. }
  418. break;
  419. default:
  420. SetRequestedEvent (c1Control, code, values, terminating);
  421. break;
  422. }
  423. inputReady.Set ();
  424. }
  425. void SetRequestedEvent (string c1Control, string code, string [] values, string terminating)
  426. {
  427. EventType eventType = EventType.RequestResponse;
  428. var requestRespEv = new RequestResponseEvent () {
  429. ResultTuple = (c1Control, code, values, terminating)
  430. };
  431. inputResultQueue.Enqueue (new InputResult () {
  432. EventType = eventType,
  433. RequestResponseEvent = requestRespEv
  434. });
  435. }
  436. void GetMouseEvent (MouseButtonState buttonState, Point pos)
  437. {
  438. MouseEvent mouseEvent = new MouseEvent () {
  439. Position = pos,
  440. ButtonState = buttonState,
  441. };
  442. inputResultQueue.Enqueue (new InputResult () {
  443. EventType = EventType.Mouse,
  444. MouseEvent = mouseEvent
  445. });
  446. inputReady.Set ();
  447. }
  448. public enum EventType {
  449. Key = 1,
  450. Mouse = 2,
  451. WindowSize = 3,
  452. WindowPosition = 4,
  453. RequestResponse = 5
  454. }
  455. [Flags]
  456. public enum MouseButtonState {
  457. Button1Pressed = 0x1,
  458. Button1Released = 0x2,
  459. Button1Clicked = 0x4,
  460. Button1DoubleClicked = 0x8,
  461. Button1TripleClicked = 0x10,
  462. Button2Pressed = 0x20,
  463. Button2Released = 0x40,
  464. Button2Clicked = 0x80,
  465. Button2DoubleClicked = 0x100,
  466. Button2TripleClicked = 0x200,
  467. Button3Pressed = 0x400,
  468. Button3Released = 0x800,
  469. Button3Clicked = 0x1000,
  470. Button3DoubleClicked = 0x2000,
  471. Button3TripleClicked = 0x4000,
  472. ButtonWheeledUp = 0x8000,
  473. ButtonWheeledDown = 0x10000,
  474. ButtonWheeledLeft = 0x20000,
  475. ButtonWheeledRight = 0x40000,
  476. Button4Pressed = 0x80000,
  477. Button4Released = 0x100000,
  478. Button4Clicked = 0x200000,
  479. Button4DoubleClicked = 0x400000,
  480. Button4TripleClicked = 0x800000,
  481. ButtonShift = 0x1000000,
  482. ButtonCtrl = 0x2000000,
  483. ButtonAlt = 0x4000000,
  484. ReportMousePosition = 0x8000000,
  485. AllEvents = -1
  486. }
  487. public struct MouseEvent {
  488. public Point Position;
  489. public MouseButtonState ButtonState;
  490. }
  491. public struct WindowSizeEvent {
  492. public Size Size;
  493. }
  494. public struct WindowPositionEvent {
  495. public int Top;
  496. public int Left;
  497. public Point CursorPosition;
  498. }
  499. public struct RequestResponseEvent {
  500. public (string c1Control, string code, string [] values, string terminating) ResultTuple;
  501. }
  502. public struct InputResult {
  503. public EventType EventType;
  504. public ConsoleKeyInfo ConsoleKeyInfo;
  505. public MouseEvent MouseEvent;
  506. public WindowSizeEvent WindowSizeEvent;
  507. public WindowPositionEvent WindowPositionEvent;
  508. public RequestResponseEvent RequestResponseEvent;
  509. }
  510. }
  511. internal class NetDriver : ConsoleDriver {
  512. const int COLOR_BLACK = 30;
  513. const int COLOR_RED = 31;
  514. const int COLOR_GREEN = 32;
  515. const int COLOR_YELLOW = 33;
  516. const int COLOR_BLUE = 34;
  517. const int COLOR_MAGENTA = 35;
  518. const int COLOR_CYAN = 36;
  519. const int COLOR_WHITE = 37;
  520. const int COLOR_BRIGHT_BLACK = 90;
  521. const int COLOR_BRIGHT_RED = 91;
  522. const int COLOR_BRIGHT_GREEN = 92;
  523. const int COLOR_BRIGHT_YELLOW = 93;
  524. const int COLOR_BRIGHT_BLUE = 94;
  525. const int COLOR_BRIGHT_MAGENTA = 95;
  526. const int COLOR_BRIGHT_CYAN = 96;
  527. const int COLOR_BRIGHT_WHITE = 97;
  528. int cols, rows, left, top;
  529. public override int Cols => cols;
  530. public override int Rows => rows;
  531. public override int Left => left;
  532. public override int Top => top;
  533. public override bool EnableConsoleScrolling { get; set; }
  534. [Obsolete ("This API is deprecated; use EnableConsoleScrolling instead.", false)]
  535. public override bool HeightAsBuffer {
  536. get => EnableConsoleScrolling;
  537. set => EnableConsoleScrolling = value;
  538. }
  539. public NetWinVTConsole NetWinConsole { get; }
  540. public bool IsWinPlatform { get; }
  541. public override IClipboard Clipboard { get; }
  542. public override int [,,] Contents => contents;
  543. int largestBufferHeight;
  544. public NetDriver ()
  545. {
  546. var p = Environment.OSVersion.Platform;
  547. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) {
  548. IsWinPlatform = true;
  549. NetWinConsole = new NetWinVTConsole ();
  550. }
  551. if (IsWinPlatform) {
  552. Clipboard = new WindowsClipboard ();
  553. } else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
  554. Clipboard = new MacOSXClipboard ();
  555. } else {
  556. if (CursesDriver.Is_WSL_Platform ()) {
  557. Clipboard = new WSLClipboard ();
  558. } else {
  559. Clipboard = new CursesClipboard ();
  560. }
  561. }
  562. }
  563. // The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  564. int [,,] contents;
  565. bool [] dirtyLine;
  566. static bool sync = false;
  567. // Current row, and current col, tracked by Move/AddCh only
  568. int ccol, crow;
  569. public override void Move (int col, int row)
  570. {
  571. ccol = col;
  572. crow = row;
  573. }
  574. public override void AddRune (Rune rune)
  575. {
  576. if (contents.Length != Rows * Cols * 3) {
  577. return;
  578. }
  579. rune = MakePrintable (rune);
  580. var runeWidth = Rune.ColumnWidth (rune);
  581. var validClip = IsValidContent (ccol, crow, Clip);
  582. if (validClip) {
  583. if (runeWidth == 0 && ccol > 0) {
  584. var r = contents [crow, ccol - 1, 0];
  585. var s = new string (new char [] { (char)r, (char)rune });
  586. string sn;
  587. if (!s.IsNormalized ()) {
  588. sn = s.Normalize ();
  589. } else {
  590. sn = s;
  591. }
  592. var c = sn [0];
  593. contents [crow, ccol - 1, 0] = c;
  594. contents [crow, ccol - 1, 1] = CurrentAttribute;
  595. contents [crow, ccol - 1, 2] = 1;
  596. } else {
  597. if (runeWidth < 2 && ccol > 0
  598. && Rune.ColumnWidth ((char)contents [crow, ccol - 1, 0]) > 1) {
  599. contents [crow, ccol - 1, 0] = (int)(uint)' ';
  600. } else if (runeWidth < 2 && ccol <= Clip.Right - 1
  601. && Rune.ColumnWidth ((char)contents [crow, ccol, 0]) > 1) {
  602. contents [crow, ccol + 1, 0] = (int)(uint)' ';
  603. contents [crow, ccol + 1, 2] = 1;
  604. }
  605. if (runeWidth > 1 && ccol == Clip.Right - 1) {
  606. contents [crow, ccol, 0] = (int)(uint)' ';
  607. } else {
  608. contents [crow, ccol, 0] = (int)(uint)rune;
  609. }
  610. contents [crow, ccol, 1] = CurrentAttribute;
  611. contents [crow, ccol, 2] = 1;
  612. }
  613. dirtyLine [crow] = true;
  614. }
  615. if (runeWidth < 0 || runeWidth > 0) {
  616. ccol++;
  617. }
  618. if (runeWidth > 1) {
  619. if (validClip && ccol < Clip.Right) {
  620. contents [crow, ccol, 1] = CurrentAttribute;
  621. contents [crow, ccol, 2] = 0;
  622. }
  623. ccol++;
  624. }
  625. if (sync) {
  626. UpdateScreen ();
  627. }
  628. }
  629. public override void AddStr (ustring str)
  630. {
  631. foreach (var rune in str)
  632. AddRune (rune);
  633. }
  634. public override void End ()
  635. {
  636. mainLoop.netEvents.StopTasks ();
  637. if (IsWinPlatform) {
  638. NetWinConsole.Cleanup ();
  639. }
  640. StopReportingMouseMoves ();
  641. Console.ResetColor ();
  642. //Disable alternative screen buffer.
  643. Console.Out.Write ("\x1b[?1049l");
  644. //Set cursor key to cursor.
  645. Console.Out.Write ("\x1b[?25h");
  646. Console.Out.Close ();
  647. }
  648. public override Attribute MakeColor (Color foreground, Color background)
  649. {
  650. return MakeColor ((ConsoleColor)foreground, (ConsoleColor)background);
  651. }
  652. static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  653. {
  654. // Encode the colors into the int value.
  655. return new Attribute (
  656. value: ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff),
  657. foreground: (Color)f,
  658. background: (Color)b
  659. );
  660. }
  661. public override void Init (Action terminalResized)
  662. {
  663. TerminalResized = terminalResized;
  664. //Enable alternative screen buffer.
  665. Console.Out.Write ("\x1b[?1049h");
  666. //Set cursor key to application.
  667. Console.Out.Write ("\x1b[?25l");
  668. Console.TreatControlCAsInput = true;
  669. if (EnableConsoleScrolling) {
  670. largestBufferHeight = Console.BufferHeight;
  671. } else {
  672. largestBufferHeight = Console.WindowHeight;
  673. }
  674. cols = Console.WindowWidth;
  675. rows = largestBufferHeight;
  676. CurrentAttribute = MakeColor (Color.White, Color.Black);
  677. InitalizeColorSchemes ();
  678. CurrentAttribute = MakeColor (Color.White, Color.Black);
  679. InitalizeColorSchemes ();
  680. ResizeScreen ();
  681. UpdateOffScreen ();
  682. StartReportingMouseMoves ();
  683. }
  684. public override void ResizeScreen ()
  685. {
  686. if (!EnableConsoleScrolling) {
  687. if (Console.WindowHeight > 0) {
  688. // Not supported on Unix.
  689. if (IsWinPlatform) {
  690. // Can raise an exception while is still resizing.
  691. try {
  692. #pragma warning disable CA1416
  693. Console.CursorTop = 0;
  694. Console.CursorLeft = 0;
  695. Console.WindowTop = 0;
  696. Console.WindowLeft = 0;
  697. if (Console.WindowHeight > Rows) {
  698. Console.SetWindowSize (Cols, Rows);
  699. }
  700. Console.SetBufferSize (Cols, Rows);
  701. #pragma warning restore CA1416
  702. } catch (System.IO.IOException) {
  703. setClip ();
  704. } catch (ArgumentOutOfRangeException) {
  705. setClip ();
  706. }
  707. } else {
  708. Console.Out.Write ($"\x1b[8;{Rows};{Cols}t");
  709. }
  710. }
  711. } else {
  712. if (IsWinPlatform) {
  713. if (Console.WindowHeight > 0) {
  714. // Can raise an exception while is still resizing.
  715. try {
  716. #pragma warning disable CA1416
  717. Console.CursorTop = 0;
  718. Console.CursorLeft = 0;
  719. if (Console.WindowHeight > Rows) {
  720. Console.SetWindowSize (Cols, Rows);
  721. }
  722. Console.SetBufferSize (Cols, Rows);
  723. #pragma warning restore CA1416
  724. } catch (System.IO.IOException) {
  725. setClip ();
  726. } catch (ArgumentOutOfRangeException) {
  727. setClip ();
  728. }
  729. }
  730. } else {
  731. Console.Out.Write ($"\x1b[30;{Rows};{Cols}t");
  732. }
  733. }
  734. setClip ();
  735. void setClip ()
  736. {
  737. Clip = new Rect (0, 0, Cols, Rows);
  738. }
  739. }
  740. public override void UpdateOffScreen ()
  741. {
  742. contents = new int [Rows, Cols, 3];
  743. dirtyLine = new bool [Rows];
  744. lock (contents) {
  745. // Can raise an exception while is still resizing.
  746. try {
  747. for (int row = 0; row < rows; row++) {
  748. for (int c = 0; c < cols; c++) {
  749. contents [row, c, 0] = ' ';
  750. contents [row, c, 1] = (ushort)Colors.TopLevel.Normal;
  751. contents [row, c, 2] = 0;
  752. dirtyLine [row] = true;
  753. }
  754. }
  755. } catch (IndexOutOfRangeException) { }
  756. }
  757. }
  758. public override Attribute MakeAttribute (Color fore, Color back)
  759. {
  760. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  761. }
  762. public override void Refresh ()
  763. {
  764. UpdateScreen ();
  765. UpdateCursor ();
  766. }
  767. public override void UpdateScreen ()
  768. {
  769. if (winChanging || Console.WindowHeight < 1 || contents.Length != Rows * Cols * 3
  770. || (!EnableConsoleScrolling && Rows != Console.WindowHeight)
  771. || (EnableConsoleScrolling && Rows != largestBufferHeight)) {
  772. return;
  773. }
  774. int top = 0;
  775. int left = 0;
  776. int rows = Rows;
  777. int cols = Cols;
  778. System.Text.StringBuilder output = new System.Text.StringBuilder ();
  779. int redrawAttr = -1;
  780. var lastCol = -1;
  781. Console.CursorVisible = false;
  782. for (int row = top; row < rows; row++) {
  783. if (Console.WindowHeight < 1) {
  784. return;
  785. }
  786. if (!dirtyLine [row]) {
  787. continue;
  788. }
  789. if (!SetCursorPosition (0, row)) {
  790. return;
  791. }
  792. dirtyLine [row] = false;
  793. output.Clear ();
  794. for (int col = left; col < cols; col++) {
  795. lastCol = -1;
  796. var outputWidth = 0;
  797. for (; col < cols; col++) {
  798. if (contents [row, col, 2] == 0) {
  799. if (output.Length > 0) {
  800. SetCursorPosition (lastCol, row);
  801. Console.Write (output);
  802. output.Clear ();
  803. lastCol += outputWidth;
  804. outputWidth = 0;
  805. } else if (lastCol == -1) {
  806. lastCol = col;
  807. }
  808. if (lastCol + 1 < cols)
  809. lastCol++;
  810. continue;
  811. }
  812. if (lastCol == -1)
  813. lastCol = col;
  814. var attr = contents [row, col, 1];
  815. if (attr != redrawAttr) {
  816. redrawAttr = attr;
  817. output.Append (WriteAttributes (attr));
  818. }
  819. outputWidth++;
  820. var rune = contents [row, col, 0];
  821. char [] spair;
  822. if (Rune.DecodeSurrogatePair ((uint)rune, out spair)) {
  823. output.Append (spair);
  824. } else {
  825. output.Append ((char)rune);
  826. }
  827. contents [row, col, 2] = 0;
  828. }
  829. }
  830. if (output.Length > 0) {
  831. SetCursorPosition (lastCol, row);
  832. Console.Write (output);
  833. }
  834. }
  835. SetCursorPosition (0, 0);
  836. }
  837. void SetVirtualCursorPosition (int col, int row)
  838. {
  839. Console.Out.Write ($"\x1b[{row + 1};{col + 1}H");
  840. }
  841. System.Text.StringBuilder WriteAttributes (int attr)
  842. {
  843. const string CSI = "\x1b[";
  844. int bg = 0;
  845. int fg = 0;
  846. System.Text.StringBuilder sb = new System.Text.StringBuilder ();
  847. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  848. .OfType<ConsoleColor> ()
  849. .Select (s => (int)s);
  850. if (values.Contains (attr & 0xffff)) {
  851. bg = MapColors ((ConsoleColor)(attr & 0xffff), false);
  852. }
  853. if (values.Contains ((attr >> 16) & 0xffff)) {
  854. fg = MapColors ((ConsoleColor)((attr >> 16) & 0xffff));
  855. }
  856. sb.Append ($"{CSI}{bg};{fg}m");
  857. return sb;
  858. }
  859. int MapColors (ConsoleColor color, bool isForeground = true)
  860. {
  861. switch (color) {
  862. case ConsoleColor.Black:
  863. return isForeground ? COLOR_BLACK : COLOR_BLACK + 10;
  864. case ConsoleColor.DarkBlue:
  865. return isForeground ? COLOR_BLUE : COLOR_BLUE + 10;
  866. case ConsoleColor.DarkGreen:
  867. return isForeground ? COLOR_GREEN : COLOR_GREEN + 10;
  868. case ConsoleColor.DarkCyan:
  869. return isForeground ? COLOR_CYAN : COLOR_CYAN + 10;
  870. case ConsoleColor.DarkRed:
  871. return isForeground ? COLOR_RED : COLOR_RED + 10;
  872. case ConsoleColor.DarkMagenta:
  873. return isForeground ? COLOR_MAGENTA : COLOR_MAGENTA + 10;
  874. case ConsoleColor.DarkYellow:
  875. return isForeground ? COLOR_YELLOW : COLOR_YELLOW + 10;
  876. case ConsoleColor.Gray:
  877. return isForeground ? COLOR_WHITE : COLOR_WHITE + 10;
  878. case ConsoleColor.DarkGray:
  879. return isForeground ? COLOR_BRIGHT_BLACK : COLOR_BRIGHT_BLACK + 10;
  880. case ConsoleColor.Blue:
  881. return isForeground ? COLOR_BRIGHT_BLUE : COLOR_BRIGHT_BLUE + 10;
  882. case ConsoleColor.Green:
  883. return isForeground ? COLOR_BRIGHT_GREEN : COLOR_BRIGHT_GREEN + 10;
  884. case ConsoleColor.Cyan:
  885. return isForeground ? COLOR_BRIGHT_CYAN : COLOR_BRIGHT_CYAN + 10;
  886. case ConsoleColor.Red:
  887. return isForeground ? COLOR_BRIGHT_RED : COLOR_BRIGHT_RED + 10;
  888. case ConsoleColor.Magenta:
  889. return isForeground ? COLOR_BRIGHT_MAGENTA : COLOR_BRIGHT_MAGENTA + 10;
  890. case ConsoleColor.Yellow:
  891. return isForeground ? COLOR_BRIGHT_YELLOW : COLOR_BRIGHT_YELLOW + 10;
  892. case ConsoleColor.White:
  893. return isForeground ? COLOR_BRIGHT_WHITE : COLOR_BRIGHT_WHITE + 10;
  894. }
  895. return 0;
  896. }
  897. bool SetCursorPosition (int col, int row)
  898. {
  899. if (IsWinPlatform) {
  900. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  901. try {
  902. Console.SetCursorPosition (col, row);
  903. return true;
  904. } catch (Exception) {
  905. return false;
  906. }
  907. } else {
  908. SetVirtualCursorPosition (col, row);
  909. return true;
  910. }
  911. }
  912. private void SetWindowPosition (int col, int row)
  913. {
  914. if (IsWinPlatform && EnableConsoleScrolling) {
  915. var winTop = Math.Max (Rows - Console.WindowHeight - row, 0);
  916. winTop = Math.Min (winTop, Rows - Console.WindowHeight + 1);
  917. winTop = Math.Max (winTop, 0);
  918. if (winTop != Console.WindowTop) {
  919. try {
  920. if (!EnsureBufferSize ()) {
  921. return;
  922. }
  923. #pragma warning disable CA1416
  924. Console.SetWindowPosition (col, winTop);
  925. #pragma warning restore CA1416
  926. } catch (System.IO.IOException) {
  927. } catch (System.ArgumentOutOfRangeException) { }
  928. }
  929. }
  930. top = Console.WindowTop;
  931. left = Console.WindowLeft;
  932. }
  933. private bool EnsureBufferSize ()
  934. {
  935. #pragma warning disable CA1416
  936. if (IsWinPlatform && Console.BufferHeight < Rows) {
  937. try {
  938. Console.SetBufferSize (Console.WindowWidth, Rows);
  939. } catch (Exception) {
  940. return false;
  941. }
  942. }
  943. #pragma warning restore CA1416
  944. return true;
  945. }
  946. private CursorVisibility? savedCursorVisibility;
  947. public override void UpdateCursor ()
  948. {
  949. EnsureCursorVisibility ();
  950. //Debug.WriteLine ($"Before - CursorTop: {Console.CursorTop};CursorLeft: {Console.CursorLeft}");
  951. if (ccol >= 0 && ccol < Cols && crow >= 0 && crow < Rows) {
  952. SetCursorPosition (ccol, crow);
  953. SetWindowPosition (0, crow);
  954. }
  955. //Debug.WriteLine ($"WindowTop: {Console.WindowTop};WindowLeft: {Console.WindowLeft}");
  956. //Debug.WriteLine ($"After - CursorTop: {Console.CursorTop};CursorLeft: {Console.CursorLeft}");
  957. }
  958. public override void StartReportingMouseMoves ()
  959. {
  960. Console.Out.Write (EscSeqUtils.EnableMouseEvents);
  961. }
  962. public override void StopReportingMouseMoves ()
  963. {
  964. Console.Out.Write (EscSeqUtils.DisableMouseEvents);
  965. }
  966. public override void Suspend ()
  967. {
  968. }
  969. public override void SetAttribute (Attribute c)
  970. {
  971. base.SetAttribute (c);
  972. }
  973. public ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  974. {
  975. if (consoleKeyInfo.Key != ConsoleKey.Packet) {
  976. return consoleKeyInfo;
  977. }
  978. var mod = consoleKeyInfo.Modifiers;
  979. var shift = (mod & ConsoleModifiers.Shift) != 0;
  980. var alt = (mod & ConsoleModifiers.Alt) != 0;
  981. var control = (mod & ConsoleModifiers.Control) != 0;
  982. var keyChar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (consoleKeyInfo.KeyChar, consoleKeyInfo.Modifiers, out uint virtualKey, out _);
  983. return new ConsoleKeyInfo ((char)keyChar, (ConsoleKey)virtualKey, shift, alt, control);
  984. }
  985. Key MapKey (ConsoleKeyInfo keyInfo)
  986. {
  987. MapKeyModifiers (keyInfo, (Key)keyInfo.Key);
  988. switch (keyInfo.Key) {
  989. case ConsoleKey.Escape:
  990. return MapKeyModifiers (keyInfo, Key.Esc);
  991. case ConsoleKey.Tab:
  992. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  993. case ConsoleKey.Home:
  994. return MapKeyModifiers (keyInfo, Key.Home);
  995. case ConsoleKey.End:
  996. return MapKeyModifiers (keyInfo, Key.End);
  997. case ConsoleKey.LeftArrow:
  998. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  999. case ConsoleKey.RightArrow:
  1000. return MapKeyModifiers (keyInfo, Key.CursorRight);
  1001. case ConsoleKey.UpArrow:
  1002. return MapKeyModifiers (keyInfo, Key.CursorUp);
  1003. case ConsoleKey.DownArrow:
  1004. return MapKeyModifiers (keyInfo, Key.CursorDown);
  1005. case ConsoleKey.PageUp:
  1006. return MapKeyModifiers (keyInfo, Key.PageUp);
  1007. case ConsoleKey.PageDown:
  1008. return MapKeyModifiers (keyInfo, Key.PageDown);
  1009. case ConsoleKey.Enter:
  1010. return MapKeyModifiers (keyInfo, Key.Enter);
  1011. case ConsoleKey.Spacebar:
  1012. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  1013. case ConsoleKey.Backspace:
  1014. return MapKeyModifiers (keyInfo, Key.Backspace);
  1015. case ConsoleKey.Delete:
  1016. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  1017. case ConsoleKey.Insert:
  1018. return MapKeyModifiers (keyInfo, Key.InsertChar);
  1019. case ConsoleKey.Oem1:
  1020. case ConsoleKey.Oem2:
  1021. case ConsoleKey.Oem3:
  1022. case ConsoleKey.Oem4:
  1023. case ConsoleKey.Oem5:
  1024. case ConsoleKey.Oem6:
  1025. case ConsoleKey.Oem7:
  1026. case ConsoleKey.Oem8:
  1027. case ConsoleKey.Oem102:
  1028. case ConsoleKey.OemPeriod:
  1029. case ConsoleKey.OemComma:
  1030. case ConsoleKey.OemPlus:
  1031. case ConsoleKey.OemMinus:
  1032. return (Key)((uint)keyInfo.KeyChar);
  1033. }
  1034. var key = keyInfo.Key;
  1035. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  1036. var delta = key - ConsoleKey.A;
  1037. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1038. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1039. }
  1040. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1041. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1042. }
  1043. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1044. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1045. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1046. }
  1047. }
  1048. return (Key)((uint)keyInfo.KeyChar);
  1049. }
  1050. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1051. var delta = key - ConsoleKey.D0;
  1052. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1053. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1054. }
  1055. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1056. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1057. }
  1058. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1059. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30 || keyInfo.KeyChar == ((uint)Key.D0 + delta)) {
  1060. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1061. }
  1062. }
  1063. return (Key)((uint)keyInfo.KeyChar);
  1064. }
  1065. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1066. var delta = key - ConsoleKey.F1;
  1067. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1068. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1069. }
  1070. return (Key)((uint)Key.F1 + delta);
  1071. }
  1072. if (keyInfo.KeyChar != 0) {
  1073. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1074. }
  1075. return (Key)(0xffffffff);
  1076. }
  1077. KeyModifiers keyModifiers;
  1078. Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1079. {
  1080. if (keyModifiers == null) {
  1081. keyModifiers = new KeyModifiers ();
  1082. }
  1083. Key keyMod = new Key ();
  1084. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0) {
  1085. keyMod = Key.ShiftMask;
  1086. keyModifiers.Shift = true;
  1087. }
  1088. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) {
  1089. keyMod |= Key.CtrlMask;
  1090. keyModifiers.Ctrl = true;
  1091. }
  1092. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0) {
  1093. keyMod |= Key.AltMask;
  1094. keyModifiers.Alt = true;
  1095. }
  1096. return keyMod != Key.Null ? keyMod | key : key;
  1097. }
  1098. Action<KeyEvent> keyHandler;
  1099. Action<KeyEvent> keyDownHandler;
  1100. Action<KeyEvent> keyUpHandler;
  1101. Action<MouseEvent> mouseHandler;
  1102. NetMainLoop mainLoop;
  1103. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  1104. {
  1105. this.keyHandler = keyHandler;
  1106. this.keyDownHandler = keyDownHandler;
  1107. this.keyUpHandler = keyUpHandler;
  1108. this.mouseHandler = mouseHandler;
  1109. var mLoop = this.mainLoop = mainLoop.Driver as NetMainLoop;
  1110. // Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will be simulated to be called.
  1111. mLoop.ProcessInput = (e) => ProcessInput (e);
  1112. }
  1113. void ProcessInput (NetEvents.InputResult inputEvent)
  1114. {
  1115. switch (inputEvent.EventType) {
  1116. case NetEvents.EventType.Key:
  1117. ConsoleKeyInfo consoleKeyInfo = inputEvent.ConsoleKeyInfo;
  1118. if (consoleKeyInfo.Key == ConsoleKey.Packet) {
  1119. consoleKeyInfo = FromVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  1120. }
  1121. keyModifiers = new KeyModifiers ();
  1122. var map = MapKey (consoleKeyInfo);
  1123. if (map == (Key)0xffffffff) {
  1124. return;
  1125. }
  1126. if (map == Key.Null) {
  1127. keyDownHandler (new KeyEvent (map, keyModifiers));
  1128. keyUpHandler (new KeyEvent (map, keyModifiers));
  1129. } else {
  1130. keyDownHandler (new KeyEvent (map, keyModifiers));
  1131. keyHandler (new KeyEvent (map, keyModifiers));
  1132. keyUpHandler (new KeyEvent (map, keyModifiers));
  1133. }
  1134. break;
  1135. case NetEvents.EventType.Mouse:
  1136. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  1137. break;
  1138. case NetEvents.EventType.WindowSize:
  1139. ChangeWin (inputEvent.WindowSizeEvent.Size);
  1140. break;
  1141. case NetEvents.EventType.RequestResponse:
  1142. Application.Top.Data = inputEvent.RequestResponseEvent.ResultTuple;
  1143. break;
  1144. }
  1145. }
  1146. volatile bool winChanging;
  1147. void ChangeWin (Size size)
  1148. {
  1149. winChanging = true;
  1150. if (!EnableConsoleScrolling) {
  1151. largestBufferHeight = Math.Max (size.Height, 0);
  1152. } else {
  1153. largestBufferHeight = Math.Max (size.Height, largestBufferHeight);
  1154. }
  1155. top = 0;
  1156. left = 0;
  1157. cols = size.Width;
  1158. rows = largestBufferHeight;
  1159. ResizeScreen ();
  1160. UpdateOffScreen ();
  1161. winChanging = false;
  1162. TerminalResized?.Invoke ();
  1163. }
  1164. MouseEvent ToDriverMouse (NetEvents.MouseEvent me)
  1165. {
  1166. //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}");
  1167. MouseFlags mouseFlag = 0;
  1168. if ((me.ButtonState & NetEvents.MouseButtonState.Button1Pressed) != 0) {
  1169. mouseFlag |= MouseFlags.Button1Pressed;
  1170. }
  1171. if ((me.ButtonState & NetEvents.MouseButtonState.Button1Released) != 0) {
  1172. mouseFlag |= MouseFlags.Button1Released;
  1173. }
  1174. if ((me.ButtonState & NetEvents.MouseButtonState.Button1Clicked) != 0) {
  1175. mouseFlag |= MouseFlags.Button1Clicked;
  1176. }
  1177. if ((me.ButtonState & NetEvents.MouseButtonState.Button1DoubleClicked) != 0) {
  1178. mouseFlag |= MouseFlags.Button1DoubleClicked;
  1179. }
  1180. if ((me.ButtonState & NetEvents.MouseButtonState.Button1TripleClicked) != 0) {
  1181. mouseFlag |= MouseFlags.Button1TripleClicked;
  1182. }
  1183. if ((me.ButtonState & NetEvents.MouseButtonState.Button2Pressed) != 0) {
  1184. mouseFlag |= MouseFlags.Button2Pressed;
  1185. }
  1186. if ((me.ButtonState & NetEvents.MouseButtonState.Button2Released) != 0) {
  1187. mouseFlag |= MouseFlags.Button2Released;
  1188. }
  1189. if ((me.ButtonState & NetEvents.MouseButtonState.Button2Clicked) != 0) {
  1190. mouseFlag |= MouseFlags.Button2Clicked;
  1191. }
  1192. if ((me.ButtonState & NetEvents.MouseButtonState.Button2DoubleClicked) != 0) {
  1193. mouseFlag |= MouseFlags.Button2DoubleClicked;
  1194. }
  1195. if ((me.ButtonState & NetEvents.MouseButtonState.Button2TripleClicked) != 0) {
  1196. mouseFlag |= MouseFlags.Button2TripleClicked;
  1197. }
  1198. if ((me.ButtonState & NetEvents.MouseButtonState.Button3Pressed) != 0) {
  1199. mouseFlag |= MouseFlags.Button3Pressed;
  1200. }
  1201. if ((me.ButtonState & NetEvents.MouseButtonState.Button3Released) != 0) {
  1202. mouseFlag |= MouseFlags.Button3Released;
  1203. }
  1204. if ((me.ButtonState & NetEvents.MouseButtonState.Button3Clicked) != 0) {
  1205. mouseFlag |= MouseFlags.Button3Clicked;
  1206. }
  1207. if ((me.ButtonState & NetEvents.MouseButtonState.Button3DoubleClicked) != 0) {
  1208. mouseFlag |= MouseFlags.Button3DoubleClicked;
  1209. }
  1210. if ((me.ButtonState & NetEvents.MouseButtonState.Button3TripleClicked) != 0) {
  1211. mouseFlag |= MouseFlags.Button3TripleClicked;
  1212. }
  1213. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonWheeledUp) != 0) {
  1214. mouseFlag |= MouseFlags.WheeledUp;
  1215. }
  1216. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonWheeledDown) != 0) {
  1217. mouseFlag |= MouseFlags.WheeledDown;
  1218. }
  1219. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonWheeledLeft) != 0) {
  1220. mouseFlag |= MouseFlags.WheeledLeft;
  1221. }
  1222. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonWheeledRight) != 0) {
  1223. mouseFlag |= MouseFlags.WheeledRight;
  1224. }
  1225. if ((me.ButtonState & NetEvents.MouseButtonState.Button4Pressed) != 0) {
  1226. mouseFlag |= MouseFlags.Button4Pressed;
  1227. }
  1228. if ((me.ButtonState & NetEvents.MouseButtonState.Button4Released) != 0) {
  1229. mouseFlag |= MouseFlags.Button4Released;
  1230. }
  1231. if ((me.ButtonState & NetEvents.MouseButtonState.Button4Clicked) != 0) {
  1232. mouseFlag |= MouseFlags.Button4Clicked;
  1233. }
  1234. if ((me.ButtonState & NetEvents.MouseButtonState.Button4DoubleClicked) != 0) {
  1235. mouseFlag |= MouseFlags.Button4DoubleClicked;
  1236. }
  1237. if ((me.ButtonState & NetEvents.MouseButtonState.Button4TripleClicked) != 0) {
  1238. mouseFlag |= MouseFlags.Button4TripleClicked;
  1239. }
  1240. if ((me.ButtonState & NetEvents.MouseButtonState.ReportMousePosition) != 0) {
  1241. mouseFlag |= MouseFlags.ReportMousePosition;
  1242. }
  1243. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonShift) != 0) {
  1244. mouseFlag |= MouseFlags.ButtonShift;
  1245. }
  1246. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonCtrl) != 0) {
  1247. mouseFlag |= MouseFlags.ButtonCtrl;
  1248. }
  1249. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonAlt) != 0) {
  1250. mouseFlag |= MouseFlags.ButtonAlt;
  1251. }
  1252. return new MouseEvent () {
  1253. X = me.Position.X,
  1254. Y = me.Position.Y,
  1255. Flags = mouseFlag
  1256. };
  1257. }
  1258. /// <inheritdoc/>
  1259. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1260. {
  1261. visibility = savedCursorVisibility ?? CursorVisibility.Default;
  1262. return visibility == CursorVisibility.Default;
  1263. }
  1264. /// <inheritdoc/>
  1265. public override bool SetCursorVisibility (CursorVisibility visibility)
  1266. {
  1267. savedCursorVisibility = visibility;
  1268. return Console.CursorVisible = visibility == CursorVisibility.Default;
  1269. }
  1270. /// <inheritdoc/>
  1271. public override bool EnsureCursorVisibility ()
  1272. {
  1273. if (!(ccol >= 0 && crow >= 0 && ccol < Cols && crow < Rows)) {
  1274. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1275. savedCursorVisibility = cursorVisibility;
  1276. SetCursorVisibility (CursorVisibility.Invisible);
  1277. return false;
  1278. }
  1279. SetCursorVisibility (savedCursorVisibility ?? CursorVisibility.Default);
  1280. return savedCursorVisibility == CursorVisibility.Default;
  1281. }
  1282. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1283. {
  1284. NetEvents.InputResult input = new NetEvents.InputResult ();
  1285. input.EventType = NetEvents.EventType.Key;
  1286. input.ConsoleKeyInfo = new ConsoleKeyInfo (keyChar, key, shift, alt, control);
  1287. try {
  1288. ProcessInput (input);
  1289. } catch (OverflowException) { }
  1290. }
  1291. public override bool GetColors (int value, out Color foreground, out Color background)
  1292. {
  1293. bool hasColor = false;
  1294. foreground = default;
  1295. background = default;
  1296. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  1297. .OfType<ConsoleColor> ()
  1298. .Select (s => (int)s);
  1299. if (values.Contains (value & 0xffff)) {
  1300. hasColor = true;
  1301. background = (Color)(ConsoleColor)(value & 0xffff);
  1302. }
  1303. if (values.Contains ((value >> 16) & 0xffff)) {
  1304. hasColor = true;
  1305. foreground = (Color)(ConsoleColor)((value >> 16) & 0xffff);
  1306. }
  1307. return hasColor;
  1308. }
  1309. #region Unused
  1310. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1311. {
  1312. }
  1313. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1314. {
  1315. }
  1316. public override void CookMouse ()
  1317. {
  1318. }
  1319. public override void UncookMouse ()
  1320. {
  1321. }
  1322. #endregion
  1323. //
  1324. // These are for the .NET driver, but running natively on Windows, wont run
  1325. // on the Mono emulation
  1326. //
  1327. }
  1328. /// <summary>
  1329. /// Mainloop intended to be used with the .NET System.Console API, and can
  1330. /// be used on Windows and Unix, it is cross platform but lacks things like
  1331. /// file descriptor monitoring.
  1332. /// </summary>
  1333. /// <remarks>
  1334. /// This implementation is used for NetDriver.
  1335. /// </remarks>
  1336. internal class NetMainLoop : IMainLoopDriver {
  1337. ManualResetEventSlim keyReady = new ManualResetEventSlim (false);
  1338. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  1339. Queue<NetEvents.InputResult?> inputResult = new Queue<NetEvents.InputResult?> ();
  1340. MainLoop mainLoop;
  1341. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  1342. internal NetEvents netEvents;
  1343. /// <summary>
  1344. /// Invoked when a Key is pressed.
  1345. /// </summary>
  1346. public Action<NetEvents.InputResult> ProcessInput;
  1347. /// <summary>
  1348. /// Initializes the class with the console driver.
  1349. /// </summary>
  1350. /// <remarks>
  1351. /// Passing a consoleDriver is provided to capture windows resizing.
  1352. /// </remarks>
  1353. /// <param name="consoleDriver">The console driver used by this Net main loop.</param>
  1354. public NetMainLoop (ConsoleDriver consoleDriver = null)
  1355. {
  1356. if (consoleDriver == null) {
  1357. throw new ArgumentNullException ("Console driver instance must be provided.");
  1358. }
  1359. netEvents = new NetEvents (consoleDriver);
  1360. }
  1361. void NetInputHandler ()
  1362. {
  1363. while (true) {
  1364. waitForProbe.Wait ();
  1365. waitForProbe.Reset ();
  1366. if (inputResult.Count == 0) {
  1367. inputResult.Enqueue (netEvents.ReadConsoleInput ());
  1368. }
  1369. try {
  1370. while (inputResult.Peek () == null) {
  1371. inputResult.Dequeue ();
  1372. }
  1373. if (inputResult.Count > 0) {
  1374. keyReady.Set ();
  1375. }
  1376. } catch (InvalidOperationException) { }
  1377. }
  1378. }
  1379. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1380. {
  1381. this.mainLoop = mainLoop;
  1382. Task.Run (NetInputHandler);
  1383. }
  1384. void IMainLoopDriver.Wakeup ()
  1385. {
  1386. keyReady.Set ();
  1387. }
  1388. bool IMainLoopDriver.EventsPending (bool wait)
  1389. {
  1390. waitForProbe.Set ();
  1391. if (CheckTimers (wait, out var waitTimeout)) {
  1392. return true;
  1393. }
  1394. try {
  1395. if (!tokenSource.IsCancellationRequested) {
  1396. keyReady.Wait (waitTimeout, tokenSource.Token);
  1397. }
  1398. } catch (OperationCanceledException) {
  1399. return true;
  1400. } finally {
  1401. keyReady.Reset ();
  1402. }
  1403. if (!tokenSource.IsCancellationRequested) {
  1404. return inputResult.Count > 0 || CheckTimers (wait, out _);
  1405. }
  1406. tokenSource.Dispose ();
  1407. tokenSource = new CancellationTokenSource ();
  1408. return true;
  1409. }
  1410. bool CheckTimers (bool wait, out int waitTimeout)
  1411. {
  1412. long now = DateTime.UtcNow.Ticks;
  1413. if (mainLoop.timeouts.Count > 0) {
  1414. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1415. if (waitTimeout < 0)
  1416. return true;
  1417. } else {
  1418. waitTimeout = -1;
  1419. }
  1420. if (!wait)
  1421. waitTimeout = 0;
  1422. int ic;
  1423. lock (mainLoop.idleHandlers) {
  1424. ic = mainLoop.idleHandlers.Count;
  1425. }
  1426. return ic > 0;
  1427. }
  1428. void IMainLoopDriver.MainIteration ()
  1429. {
  1430. while (inputResult.Count > 0) {
  1431. ProcessInput?.Invoke (inputResult.Dequeue ().Value);
  1432. }
  1433. }
  1434. }
  1435. }