NetDriver.cs 44 KB

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