NetDriver.cs 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119
  1. //#define PROCESS_REQUEST
  2. //
  3. // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient.
  4. //
  5. // Authors:
  6. // Miguel de Icaza ([email protected])
  7. //
  8. using System;
  9. using System.Collections.Generic;
  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. int lastWindowHeight;
  102. int largestWindowHeight;
  103. #if PROCESS_REQUEST
  104. bool neededProcessRequest;
  105. #endif
  106. public int NumberOfCSI { get; }
  107. public NetEvents (ConsoleDriver consoleDriver, int numberOfCSI = 1)
  108. {
  109. if (consoleDriver == null) {
  110. throw new ArgumentNullException ("Console driver instance must be provided.");
  111. }
  112. this.consoleDriver = consoleDriver;
  113. NumberOfCSI = numberOfCSI;
  114. Task.Run (ProcessInputResultQueue);
  115. Task.Run (CheckWinChange);
  116. }
  117. public InputResult? ReadConsoleInput ()
  118. {
  119. while (true) {
  120. waitForStart.Set ();
  121. winChange.Set ();
  122. if (inputResultQueue.Count == 0) {
  123. inputReady.Wait ();
  124. inputReady.Reset ();
  125. }
  126. #if PROCESS_REQUEST
  127. neededProcessRequest = false;
  128. #endif
  129. if (inputResultQueue.Count > 0) {
  130. return inputResultQueue.Dequeue ();
  131. }
  132. }
  133. }
  134. void ProcessInputResultQueue ()
  135. {
  136. while (true) {
  137. waitForStart.Wait ();
  138. waitForStart.Reset ();
  139. if (inputResultQueue.Count == 0) {
  140. GetConsoleInputType (Console.ReadKey (true));
  141. }
  142. inputReady.Set ();
  143. }
  144. }
  145. void CheckWinChange ()
  146. {
  147. while (true) {
  148. winChange.Wait ();
  149. winChange.Reset ();
  150. WaitWinChange ();
  151. inputReady.Set ();
  152. }
  153. }
  154. void WaitWinChange ()
  155. {
  156. while (true) {
  157. // HACK: Sleep for 10ms to mitigate high CPU usage (see issue #1502). 10ms was tested to address the problem, but may not be correct.
  158. Thread.Sleep (10);
  159. if (!consoleDriver.HeightAsBuffer) {
  160. if (Console.WindowWidth != consoleDriver.Cols || Console.WindowHeight != consoleDriver.Rows) {
  161. var w = Math.Max (Console.WindowWidth, 0);
  162. var h = Math.Max (Console.WindowHeight, 0);
  163. GetWindowSizeEvent (new Size (w, h));
  164. return;
  165. }
  166. } else {
  167. //largestWindowHeight = Math.Max (Console.BufferHeight, largestWindowHeight);
  168. largestWindowHeight = Console.BufferHeight;
  169. if (Console.BufferWidth != consoleDriver.Cols || largestWindowHeight != consoleDriver.Rows
  170. || Console.WindowHeight != lastWindowHeight) {
  171. lastWindowHeight = Console.WindowHeight;
  172. GetWindowSizeEvent (new Size (Console.BufferWidth, lastWindowHeight));
  173. return;
  174. }
  175. if (Console.WindowTop != consoleDriver.Top) {
  176. // Top only working on Windows.
  177. var winPositionEv = new WindowPositionEvent () {
  178. Top = Console.WindowTop,
  179. Left = Console.WindowLeft
  180. };
  181. inputResultQueue.Enqueue (new InputResult () {
  182. EventType = EventType.WindowPosition,
  183. WindowPositionEvent = winPositionEv
  184. });
  185. return;
  186. }
  187. #if PROCESS_REQUEST
  188. if (!neededProcessRequest) {
  189. Console.Out.Write ("\x1b[6n");
  190. neededProcessRequest = true;
  191. }
  192. #endif
  193. }
  194. }
  195. }
  196. void GetWindowSizeEvent (Size size)
  197. {
  198. WindowSizeEvent windowSizeEvent = new WindowSizeEvent () {
  199. Size = size
  200. };
  201. inputResultQueue.Enqueue (new InputResult () {
  202. EventType = EventType.WindowSize,
  203. WindowSizeEvent = windowSizeEvent
  204. });
  205. }
  206. void GetConsoleInputType (ConsoleKeyInfo consoleKeyInfo)
  207. {
  208. InputResult inputResult = new InputResult {
  209. EventType = EventType.Key
  210. };
  211. ConsoleKeyInfo newConsoleKeyInfo = consoleKeyInfo;
  212. ConsoleKey key = 0;
  213. MouseEvent mouseEvent = new MouseEvent ();
  214. var keyChar = consoleKeyInfo.KeyChar;
  215. switch ((uint)keyChar) {
  216. case 0:
  217. if (consoleKeyInfo.Key == (ConsoleKey)64) { // Ctrl+Space in Windows.
  218. newConsoleKeyInfo = new ConsoleKeyInfo (' ', ConsoleKey.Spacebar,
  219. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  220. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  221. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  222. }
  223. break;
  224. case uint n when (n >= '\u0001' && n <= '\u001a'):
  225. if (consoleKeyInfo.Key == 0 && consoleKeyInfo.KeyChar == '\r') {
  226. key = ConsoleKey.Enter;
  227. newConsoleKeyInfo = new ConsoleKeyInfo (consoleKeyInfo.KeyChar,
  228. key,
  229. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  230. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  231. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  232. } else if (consoleKeyInfo.Key == 0) {
  233. key = (ConsoleKey)(char)(consoleKeyInfo.KeyChar + (uint)ConsoleKey.A - 1);
  234. newConsoleKeyInfo = new ConsoleKeyInfo ((char)key,
  235. key,
  236. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  237. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  238. true);
  239. }
  240. break;
  241. case 27:
  242. //case 91:
  243. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] { consoleKeyInfo };
  244. ConsoleModifiers mod = consoleKeyInfo.Modifiers;
  245. int delay = 0;
  246. while (delay < 100) {
  247. if (Console.KeyAvailable) {
  248. do {
  249. var result = Console.ReadKey (true);
  250. Array.Resize (ref cki, cki == null ? 1 : cki.Length + 1);
  251. cki [cki.Length - 1] = result;
  252. } while (Console.KeyAvailable);
  253. break;
  254. }
  255. Thread.Sleep (50);
  256. delay += 50;
  257. }
  258. SplitCSI (cki, ref inputResult, ref newConsoleKeyInfo, ref key, ref mouseEvent, ref mod);
  259. return;
  260. case 127:
  261. newConsoleKeyInfo = new ConsoleKeyInfo (consoleKeyInfo.KeyChar, ConsoleKey.Backspace,
  262. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  263. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  264. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  265. break;
  266. default:
  267. newConsoleKeyInfo = consoleKeyInfo;
  268. break;
  269. }
  270. if (inputResult.EventType == EventType.Key) {
  271. inputResult.ConsoleKeyInfo = newConsoleKeyInfo;
  272. } else {
  273. inputResult.MouseEvent = mouseEvent;
  274. }
  275. inputResultQueue.Enqueue (inputResult);
  276. }
  277. void SplitCSI (ConsoleKeyInfo [] cki, ref InputResult inputResult, ref ConsoleKeyInfo newConsoleKeyInfo, ref ConsoleKey key, ref MouseEvent mouseEvent, ref ConsoleModifiers mod)
  278. {
  279. ConsoleKeyInfo [] splitedCki = new ConsoleKeyInfo [] { };
  280. int length = 0;
  281. var kChar = GetKeyCharArray (cki);
  282. var nCSI = GetNumberOfCSI (kChar);
  283. int curCSI = 0;
  284. char previousKChar = '\0';
  285. if (nCSI > 1) {
  286. for (int i = 0; i < cki.Length; i++) {
  287. var ck = cki [i];
  288. if (NumberOfCSI > 0 && nCSI - curCSI > NumberOfCSI) {
  289. if (i + 1 < cki.Length && cki [i + 1].KeyChar == '\x1b' && previousKChar != '\0') {
  290. curCSI++;
  291. previousKChar = '\0';
  292. } else {
  293. previousKChar = ck.KeyChar;
  294. }
  295. continue;
  296. }
  297. if (ck.KeyChar == '\x1b') {
  298. if (ck.KeyChar == 'R') {
  299. ResizeArray (ck);
  300. }
  301. if (splitedCki.Length > 1) {
  302. DecodeCSI (ref inputResult, ref newConsoleKeyInfo, ref key, ref mouseEvent, splitedCki, ref mod);
  303. }
  304. splitedCki = new ConsoleKeyInfo [] { };
  305. length = 0;
  306. }
  307. ResizeArray (ck);
  308. if (i == cki.Length - 1 && splitedCki.Length > 0) {
  309. DecodeCSI (ref inputResult, ref newConsoleKeyInfo, ref key, ref mouseEvent, splitedCki, ref mod);
  310. }
  311. }
  312. } else {
  313. DecodeCSI (ref inputResult, ref newConsoleKeyInfo, ref key, ref mouseEvent, cki, ref mod);
  314. }
  315. void ResizeArray (ConsoleKeyInfo ck)
  316. {
  317. length++;
  318. Array.Resize (ref splitedCki, length);
  319. splitedCki [length - 1] = ck;
  320. }
  321. }
  322. char [] GetKeyCharArray (ConsoleKeyInfo [] cki)
  323. {
  324. char [] kChar = new char [] { };
  325. var length = 0;
  326. foreach (var kc in cki) {
  327. length++;
  328. Array.Resize (ref kChar, length);
  329. kChar [length - 1] = kc.KeyChar;
  330. }
  331. return kChar;
  332. }
  333. int GetNumberOfCSI (char [] csi)
  334. {
  335. int nCSI = 0;
  336. for (int i = 0; i < csi.Length; i++) {
  337. if (csi [i] == '\x1b' || (csi [i] == '[' && (i == 0 || (i > 0 && csi [i - 1] != '\x1b')))) {
  338. nCSI++;
  339. }
  340. }
  341. return nCSI;
  342. }
  343. void DecodeCSI (ref InputResult inputResult, ref ConsoleKeyInfo newConsoleKeyInfo, ref ConsoleKey key, ref MouseEvent mouseEvent, ConsoleKeyInfo [] cki, ref ConsoleModifiers mod)
  344. {
  345. switch (cki.Length) {
  346. case 2:
  347. if ((uint)cki [1].KeyChar >= 1 && (uint)cki [1].KeyChar <= 26) {
  348. key = (ConsoleKey)(char)(cki [1].KeyChar + (uint)ConsoleKey.A - 1);
  349. newConsoleKeyInfo = new ConsoleKeyInfo (cki [1].KeyChar,
  350. key,
  351. false,
  352. true,
  353. true);
  354. } else {
  355. if (cki [1].KeyChar >= 97 && cki [1].KeyChar <= 122) {
  356. key = (ConsoleKey)cki [1].KeyChar.ToString ().ToUpper () [0];
  357. } else {
  358. key = (ConsoleKey)cki [1].KeyChar;
  359. }
  360. newConsoleKeyInfo = new ConsoleKeyInfo ((char)key,
  361. (ConsoleKey)Math.Min ((uint)key, 255),
  362. false,
  363. true,
  364. false);
  365. }
  366. break;
  367. case 3:
  368. if (cki [1].KeyChar == '[' || cki [1].KeyChar == 79) {
  369. key = GetConsoleKey (cki [2].KeyChar, ref mod, cki.Length);
  370. }
  371. newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
  372. key,
  373. (mod & ConsoleModifiers.Shift) != 0,
  374. (mod & ConsoleModifiers.Alt) != 0,
  375. (mod & ConsoleModifiers.Control) != 0);
  376. break;
  377. case 4:
  378. if (cki [1].KeyChar == '[' && cki [3].KeyChar == 126) {
  379. key = GetConsoleKey (cki [2].KeyChar, ref mod, cki.Length);
  380. newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
  381. key,
  382. (mod & ConsoleModifiers.Shift) != 0,
  383. (mod & ConsoleModifiers.Alt) != 0,
  384. (mod & ConsoleModifiers.Control) != 0);
  385. }
  386. break;
  387. case 5:
  388. if (cki [1].KeyChar == '[' && (cki [2].KeyChar == 49 || cki [2].KeyChar == 50)
  389. && cki [4].KeyChar == 126) {
  390. key = GetConsoleKey (cki [3].KeyChar, ref mod, cki.Length);
  391. } else if (cki [1].KeyChar == 49 && cki [2].KeyChar == ';') { // For WSL
  392. mod |= GetConsoleModifiers (cki [3].KeyChar);
  393. key = ConsoleKey.End;
  394. }
  395. newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
  396. key,
  397. (mod & ConsoleModifiers.Shift) != 0,
  398. (mod & ConsoleModifiers.Alt) != 0,
  399. (mod & ConsoleModifiers.Control) != 0);
  400. break;
  401. case 6:
  402. if (cki [1].KeyChar == '[' && cki [2].KeyChar == 49 && cki [3].KeyChar == ';') {
  403. mod |= GetConsoleModifiers (cki [4].KeyChar);
  404. key = GetConsoleKey (cki [5].KeyChar, ref mod, cki.Length);
  405. } else if (cki [1].KeyChar == '[' && cki [3].KeyChar == ';') {
  406. mod |= GetConsoleModifiers (cki [4].KeyChar);
  407. key = GetConsoleKey (cki [2].KeyChar, ref mod, cki.Length);
  408. }
  409. newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
  410. key,
  411. (mod & ConsoleModifiers.Shift) != 0,
  412. (mod & ConsoleModifiers.Alt) != 0,
  413. (mod & ConsoleModifiers.Control) != 0);
  414. break;
  415. case 7:
  416. GetRequestEvent (GetKeyCharArray (cki));
  417. return;
  418. case int n when n >= 8:
  419. GetMouseEvent (cki);
  420. return;
  421. }
  422. if (inputResult.EventType == EventType.Key) {
  423. inputResult.ConsoleKeyInfo = newConsoleKeyInfo;
  424. } else {
  425. inputResult.MouseEvent = mouseEvent;
  426. }
  427. inputResultQueue.Enqueue (inputResult);
  428. }
  429. Point lastCursorPosition;
  430. void GetRequestEvent (char [] kChar)
  431. {
  432. EventType eventType = new EventType ();
  433. Point point = new Point ();
  434. int foundPoint = 0;
  435. string value = "";
  436. for (int i = 0; i < kChar.Length; i++) {
  437. var c = kChar [i];
  438. if (c == '\u001b' || c == '[') {
  439. foundPoint++;
  440. } else if (foundPoint == 1 && c != ';' && c != '?') {
  441. value += c.ToString ();
  442. } else if (c == '?') {
  443. foundPoint++;
  444. } else if (c == ';') {
  445. if (foundPoint >= 1) {
  446. point.Y = int.Parse (value) - 1;
  447. }
  448. value = "";
  449. foundPoint++;
  450. } else if (foundPoint > 0 && i < kChar.Length - 1) {
  451. value += c.ToString ();
  452. } else if (i == kChar.Length - 1) {
  453. point.X = int.Parse (value) + Console.WindowTop - 1;
  454. switch (c) {
  455. case 'R':
  456. if (lastCursorPosition.Y != point.Y) {
  457. lastCursorPosition = point;
  458. eventType = EventType.WindowPosition;
  459. var winPositionEv = new WindowPositionEvent () {
  460. CursorPosition = point
  461. };
  462. inputResultQueue.Enqueue (new InputResult () {
  463. EventType = eventType,
  464. WindowPositionEvent = winPositionEv
  465. });
  466. } else {
  467. return;
  468. }
  469. break;
  470. case 'c': // CSI?1;0c ("VT101 with No Options")
  471. break;
  472. default:
  473. throw new NotImplementedException ();
  474. }
  475. }
  476. }
  477. inputReady.Set ();
  478. }
  479. MouseEvent lastMouseEvent;
  480. bool isButtonPressed;
  481. bool isButtonClicked;
  482. bool isButtonDoubleClicked;
  483. bool isButtonTripleClicked;
  484. bool isProcContBtnPressedRuning;
  485. int buttonPressedCount;
  486. //bool isButtonReleased;
  487. void GetMouseEvent (ConsoleKeyInfo [] cki)
  488. {
  489. MouseEvent mouseEvent = new MouseEvent ();
  490. MouseButtonState buttonState = 0;
  491. Point point = new Point ();
  492. int buttonCode = 0;
  493. bool foundButtonCode = false;
  494. int foundPoint = 0;
  495. string value = "";
  496. var kChar = GetKeyCharArray (cki);
  497. for (int i = 0; i < kChar.Length; i++) {
  498. var c = kChar [i];
  499. if (c == '<') {
  500. foundButtonCode = true;
  501. } else if (foundButtonCode && c != ';') {
  502. value += c.ToString ();
  503. } else if (c == ';') {
  504. if (foundButtonCode) {
  505. foundButtonCode = false;
  506. buttonCode = int.Parse (value);
  507. }
  508. if (foundPoint == 1) {
  509. point.X = int.Parse (value) - 1;
  510. }
  511. value = "";
  512. foundPoint++;
  513. } else if (foundPoint > 0 && c != 'm' && c != 'M') {
  514. value += c.ToString ();
  515. } else if (c == 'm' || c == 'M') {
  516. point.Y = int.Parse (value) + Console.WindowTop - 1;
  517. //if (c == 'M') {
  518. // isButtonPressed = true;
  519. //} else if (c == 'm') {
  520. // isButtonPressed = false;
  521. //}
  522. switch (buttonCode) {
  523. case 0:
  524. case 8:
  525. case 16:
  526. case 24:
  527. case 32:
  528. case 36:
  529. case 40:
  530. case 48:
  531. case 56:
  532. buttonState = c == 'M' ? MouseButtonState.Button1Pressed
  533. : MouseButtonState.Button1Released;
  534. break;
  535. case 1:
  536. case 9:
  537. case 17:
  538. case 25:
  539. case 33:
  540. case 37:
  541. case 41:
  542. case 45:
  543. case 49:
  544. case 53:
  545. case 57:
  546. case 61:
  547. buttonState = c == 'M' ? MouseButtonState.Button2Pressed
  548. : MouseButtonState.Button2Released;
  549. break;
  550. case 2:
  551. case 10:
  552. case 14:
  553. case 18:
  554. case 22:
  555. case 26:
  556. case 30:
  557. case 34:
  558. case 42:
  559. case 46:
  560. case 50:
  561. case 54:
  562. case 58:
  563. case 62:
  564. buttonState = c == 'M' ? MouseButtonState.Button3Pressed
  565. : MouseButtonState.Button3Released;
  566. break;
  567. case 35:
  568. case 39:
  569. case 43:
  570. case 47:
  571. case 55:
  572. case 59:
  573. case 63:
  574. buttonState = MouseButtonState.ReportMousePosition;
  575. break;
  576. case 64:
  577. buttonState = MouseButtonState.ButtonWheeledUp;
  578. break;
  579. case 65:
  580. buttonState = MouseButtonState.ButtonWheeledDown;
  581. break;
  582. case 68:
  583. case 72:
  584. case 80:
  585. buttonState = MouseButtonState.ButtonWheeledLeft; // Shift/Ctrl+ButtonWheeledUp
  586. break;
  587. case 69:
  588. case 73:
  589. case 81:
  590. buttonState = MouseButtonState.ButtonWheeledRight; // Shift/Ctrl+ButtonWheeledDown
  591. break;
  592. }
  593. // Modifiers.
  594. switch (buttonCode) {
  595. case 8:
  596. case 9:
  597. case 10:
  598. case 43:
  599. buttonState |= MouseButtonState.ButtonAlt;
  600. break;
  601. case 14:
  602. case 47:
  603. buttonState |= MouseButtonState.ButtonAlt | MouseButtonState.ButtonShift;
  604. break;
  605. case 16:
  606. case 17:
  607. case 18:
  608. case 51:
  609. buttonState |= MouseButtonState.ButtonCtrl;
  610. break;
  611. case 22:
  612. case 55:
  613. buttonState |= MouseButtonState.ButtonCtrl | MouseButtonState.ButtonShift;
  614. break;
  615. case 24:
  616. case 25:
  617. case 26:
  618. case 59:
  619. buttonState |= MouseButtonState.ButtonAlt | MouseButtonState.ButtonCtrl;
  620. break;
  621. case 30:
  622. case 63:
  623. buttonState |= MouseButtonState.ButtonCtrl | MouseButtonState.ButtonShift | MouseButtonState.ButtonAlt;
  624. break;
  625. case 32:
  626. case 33:
  627. case 34:
  628. buttonState |= MouseButtonState.ReportMousePosition;
  629. break;
  630. case 36:
  631. case 37:
  632. buttonState |= MouseButtonState.ReportMousePosition | MouseButtonState.ButtonShift;
  633. break;
  634. case 39:
  635. case 68:
  636. case 69:
  637. buttonState |= MouseButtonState.ButtonShift;
  638. break;
  639. case 40:
  640. case 41:
  641. case 42:
  642. buttonState |= MouseButtonState.ReportMousePosition | MouseButtonState.ButtonAlt;
  643. break;
  644. case 45:
  645. case 46:
  646. buttonState |= MouseButtonState.ReportMousePosition | MouseButtonState.ButtonAlt | MouseButtonState.ButtonShift;
  647. break;
  648. case 48:
  649. case 49:
  650. case 50:
  651. buttonState |= MouseButtonState.ReportMousePosition | MouseButtonState.ButtonCtrl;
  652. break;
  653. case 53:
  654. case 54:
  655. buttonState |= MouseButtonState.ReportMousePosition | MouseButtonState.ButtonCtrl | MouseButtonState.ButtonShift;
  656. break;
  657. case 56:
  658. case 57:
  659. case 58:
  660. buttonState |= MouseButtonState.ReportMousePosition | MouseButtonState.ButtonCtrl | MouseButtonState.ButtonAlt;
  661. break;
  662. case 61:
  663. case 62:
  664. buttonState |= MouseButtonState.ReportMousePosition | MouseButtonState.ButtonCtrl | MouseButtonState.ButtonShift | MouseButtonState.ButtonAlt;
  665. break;
  666. }
  667. }
  668. }
  669. mouseEvent.Position.X = point.X;
  670. mouseEvent.Position.Y = point.Y;
  671. mouseEvent.ButtonState = buttonState;
  672. //System.Diagnostics.Debug.WriteLine ($"ButtonState: {mouseEvent.ButtonState} X: {mouseEvent.Position.X} Y: {mouseEvent.Position.Y}");
  673. if (isButtonDoubleClicked) {
  674. Application.MainLoop.AddIdle (() => {
  675. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  676. return false;
  677. });
  678. }
  679. if ((buttonState & MouseButtonState.Button1Pressed) != 0
  680. || (buttonState & MouseButtonState.Button2Pressed) != 0
  681. || (buttonState & MouseButtonState.Button3Pressed) != 0) {
  682. if ((buttonState & MouseButtonState.ReportMousePosition) == 0) {
  683. buttonPressedCount++;
  684. } else {
  685. buttonPressedCount = 0;
  686. }
  687. //System.Diagnostics.Debug.WriteLine ($"buttonPressedCount: {buttonPressedCount}");
  688. isButtonPressed = true;
  689. } else {
  690. isButtonPressed = false;
  691. buttonPressedCount = 0;
  692. }
  693. if (buttonPressedCount == 2 && !isButtonDoubleClicked
  694. && (lastMouseEvent.ButtonState == MouseButtonState.Button1Pressed
  695. || lastMouseEvent.ButtonState == MouseButtonState.Button2Pressed
  696. || lastMouseEvent.ButtonState == MouseButtonState.Button3Pressed)) {
  697. isButtonDoubleClicked = true;
  698. ProcessButtonDoubleClicked (mouseEvent);
  699. inputReady.Set ();
  700. return;
  701. } else if (buttonPressedCount == 3 && isButtonDoubleClicked
  702. && (lastMouseEvent.ButtonState == MouseButtonState.Button1Pressed
  703. || lastMouseEvent.ButtonState == MouseButtonState.Button2Pressed
  704. || lastMouseEvent.ButtonState == MouseButtonState.Button3Pressed)) {
  705. isButtonDoubleClicked = false;
  706. isButtonTripleClicked = true;
  707. buttonPressedCount = 0;
  708. ProcessButtonTripleClicked (mouseEvent);
  709. lastMouseEvent = mouseEvent;
  710. inputReady.Set ();
  711. return;
  712. }
  713. //System.Diagnostics.Debug.WriteLine ($"isButtonClicked: {isButtonClicked} isButtonDoubleClicked: {isButtonDoubleClicked} isButtonTripleClicked: {isButtonTripleClicked}");
  714. if ((isButtonClicked || isButtonDoubleClicked || isButtonTripleClicked)
  715. && ((buttonState & MouseButtonState.Button1Released) != 0
  716. || (buttonState & MouseButtonState.Button2Released) != 0
  717. || (buttonState & MouseButtonState.Button3Released) != 0)) {
  718. //isButtonClicked = false;
  719. //isButtonDoubleClicked = false;
  720. isButtonTripleClicked = false;
  721. buttonPressedCount = 0;
  722. return;
  723. }
  724. if (isButtonClicked && !isButtonDoubleClicked && lastMouseEvent.Position != default && lastMouseEvent.Position == point
  725. && ((buttonState & MouseButtonState.Button1Pressed) != 0
  726. || (buttonState & MouseButtonState.Button2Pressed) != 0
  727. || (buttonState & MouseButtonState.Button3Pressed) != 0
  728. || (buttonState & MouseButtonState.Button1Released) != 0
  729. || (buttonState & MouseButtonState.Button2Released) != 0
  730. || (buttonState & MouseButtonState.Button3Released) != 0)) {
  731. isButtonClicked = false;
  732. isButtonDoubleClicked = true;
  733. ProcessButtonDoubleClicked (mouseEvent);
  734. Application.MainLoop.AddIdle (() => {
  735. Task.Run (async () => {
  736. await Task.Delay (600);
  737. isButtonDoubleClicked = false;
  738. });
  739. return false;
  740. });
  741. inputReady.Set ();
  742. return;
  743. }
  744. if (isButtonDoubleClicked && lastMouseEvent.Position != default && lastMouseEvent.Position == point
  745. && ((buttonState & MouseButtonState.Button1Pressed) != 0
  746. || (buttonState & MouseButtonState.Button2Pressed) != 0
  747. || (buttonState & MouseButtonState.Button3Pressed) != 0
  748. || (buttonState & MouseButtonState.Button1Released) != 0
  749. || (buttonState & MouseButtonState.Button2Released) != 0
  750. || (buttonState & MouseButtonState.Button3Released) != 0)) {
  751. isButtonDoubleClicked = false;
  752. isButtonTripleClicked = true;
  753. ProcessButtonTripleClicked (mouseEvent);
  754. inputReady.Set ();
  755. return;
  756. }
  757. //if (!isButtonPressed && !isButtonClicked && !isButtonDoubleClicked && !isButtonTripleClicked
  758. // && !isButtonReleased && lastMouseEvent.ButtonState != 0
  759. // && ((buttonState & MouseButtonState.Button1Released) == 0
  760. // && (buttonState & MouseButtonState.Button2Released) == 0
  761. // && (buttonState & MouseButtonState.Button3Released) == 0)) {
  762. // ProcessButtonReleased (lastMouseEvent);
  763. // inputReady.Set ();
  764. // return;
  765. //}
  766. inputResultQueue.Enqueue (new InputResult () {
  767. EventType = EventType.Mouse,
  768. MouseEvent = mouseEvent
  769. });
  770. if (!isButtonClicked && !lastMouseEvent.ButtonState.HasFlag (MouseButtonState.ReportMousePosition)
  771. && lastMouseEvent.Position != default && lastMouseEvent.Position == point
  772. && ((buttonState & MouseButtonState.Button1Released) != 0
  773. || (buttonState & MouseButtonState.Button2Released) != 0
  774. || (buttonState & MouseButtonState.Button3Released) != 0)) {
  775. isButtonClicked = true;
  776. ProcessButtonClicked (mouseEvent);
  777. Application.MainLoop.AddIdle (() => {
  778. Task.Run (async () => {
  779. await Task.Delay (300);
  780. isButtonClicked = false;
  781. });
  782. return false;
  783. });
  784. inputReady.Set ();
  785. return;
  786. }
  787. lastMouseEvent = mouseEvent;
  788. if (isButtonPressed && !isButtonClicked && !isButtonDoubleClicked && !isButtonTripleClicked && !isProcContBtnPressedRuning) {
  789. //isButtonReleased = false;
  790. if ((buttonState & MouseButtonState.ReportMousePosition) != 0) {
  791. point = new Point ();
  792. } else {
  793. point = new Point () {
  794. X = mouseEvent.Position.X,
  795. Y = mouseEvent.Position.Y
  796. };
  797. }
  798. if ((buttonState & MouseButtonState.ReportMousePosition) == 0) {
  799. Application.MainLoop.AddIdle (() => {
  800. Task.Run (async () => await ProcessContinuousButtonPressedAsync ());
  801. return false;
  802. });
  803. }
  804. }
  805. inputReady.Set ();
  806. }
  807. void ProcessButtonClicked (MouseEvent mouseEvent)
  808. {
  809. var me = new MouseEvent () {
  810. Position = mouseEvent.Position,
  811. ButtonState = mouseEvent.ButtonState
  812. };
  813. if ((mouseEvent.ButtonState & MouseButtonState.Button1Released) != 0) {
  814. me.ButtonState &= ~MouseButtonState.Button1Released;
  815. me.ButtonState |= MouseButtonState.Button1Clicked;
  816. } else if ((mouseEvent.ButtonState & MouseButtonState.Button2Released) != 0) {
  817. me.ButtonState &= ~MouseButtonState.Button2Released;
  818. me.ButtonState |= MouseButtonState.Button2Clicked;
  819. } else if ((mouseEvent.ButtonState & MouseButtonState.Button3Released) != 0) {
  820. me.ButtonState &= ~MouseButtonState.Button3Released;
  821. me.ButtonState |= MouseButtonState.Button3Clicked;
  822. }
  823. //isButtonReleased = true;
  824. inputResultQueue.Enqueue (new InputResult () {
  825. EventType = EventType.Mouse,
  826. MouseEvent = me
  827. });
  828. }
  829. async Task ProcessButtonDoubleClickedAsync ()
  830. {
  831. await Task.Delay (300);
  832. isButtonDoubleClicked = false;
  833. buttonPressedCount = 0;
  834. }
  835. void ProcessButtonDoubleClicked (MouseEvent mouseEvent)
  836. {
  837. var me = new MouseEvent () {
  838. Position = mouseEvent.Position,
  839. ButtonState = mouseEvent.ButtonState
  840. };
  841. if ((mouseEvent.ButtonState & MouseButtonState.Button1Pressed) != 0) {
  842. me.ButtonState &= ~MouseButtonState.Button1Pressed;
  843. me.ButtonState |= MouseButtonState.Button1DoubleClicked;
  844. } else if ((mouseEvent.ButtonState & MouseButtonState.Button2Pressed) != 0) {
  845. me.ButtonState &= ~MouseButtonState.Button2Pressed;
  846. me.ButtonState |= MouseButtonState.Button2DoubleClicked;
  847. } else if ((mouseEvent.ButtonState & MouseButtonState.Button3Pressed) != 0) {
  848. me.ButtonState &= ~MouseButtonState.Button3Pressed;
  849. me.ButtonState |= MouseButtonState.Button3DoubleClicked;
  850. }
  851. //isButtonReleased = true;
  852. inputResultQueue.Enqueue (new InputResult () {
  853. EventType = EventType.Mouse,
  854. MouseEvent = me
  855. });
  856. }
  857. void ProcessButtonTripleClicked (MouseEvent mouseEvent)
  858. {
  859. var me = new MouseEvent () {
  860. Position = mouseEvent.Position,
  861. ButtonState = mouseEvent.ButtonState
  862. };
  863. if ((mouseEvent.ButtonState & MouseButtonState.Button1Pressed) != 0) {
  864. me.ButtonState &= ~MouseButtonState.Button1Pressed;
  865. me.ButtonState |= MouseButtonState.Button1TripleClicked;
  866. } else if ((mouseEvent.ButtonState & MouseButtonState.Button2Pressed) != 0) {
  867. me.ButtonState &= ~MouseButtonState.Button2Pressed;
  868. me.ButtonState |= MouseButtonState.Button2TrippleClicked;
  869. } else if ((mouseEvent.ButtonState & MouseButtonState.Button3Pressed) != 0) {
  870. me.ButtonState &= ~MouseButtonState.Button3Pressed;
  871. me.ButtonState |= MouseButtonState.Button3TripleClicked;
  872. }
  873. //isButtonReleased = true;
  874. inputResultQueue.Enqueue (new InputResult () {
  875. EventType = EventType.Mouse,
  876. MouseEvent = me
  877. });
  878. }
  879. async Task ProcessContinuousButtonPressedAsync ()
  880. {
  881. isProcContBtnPressedRuning = true;
  882. await Task.Delay (200);
  883. while (isButtonPressed) {
  884. await Task.Delay (100);
  885. var view = Application.WantContinuousButtonPressedView;
  886. if (view == null) {
  887. break;
  888. }
  889. if (isButtonPressed && (lastMouseEvent.ButtonState & MouseButtonState.ReportMousePosition) == 0) {
  890. inputResultQueue.Enqueue (new InputResult () {
  891. EventType = EventType.Mouse,
  892. MouseEvent = lastMouseEvent
  893. });
  894. inputReady.Set ();
  895. }
  896. }
  897. isProcContBtnPressedRuning = false;
  898. //isButtonPressed = false;
  899. }
  900. //void ProcessButtonReleased (MouseEvent mouseEvent)
  901. //{
  902. // var me = new MouseEvent () {
  903. // Position = mouseEvent.Position,
  904. // ButtonState = mouseEvent.ButtonState
  905. // };
  906. // if ((mouseEvent.ButtonState & MouseButtonState.Button1Pressed) != 0) {
  907. // me.ButtonState &= ~(MouseButtonState.Button1Pressed | MouseButtonState.ReportMousePosition);
  908. // me.ButtonState |= MouseButtonState.Button1Released;
  909. // } else if ((mouseEvent.ButtonState & MouseButtonState.Button2Pressed) != 0) {
  910. // me.ButtonState &= ~(MouseButtonState.Button2Pressed | MouseButtonState.ReportMousePosition);
  911. // me.ButtonState |= MouseButtonState.Button2Released;
  912. // } else if ((mouseEvent.ButtonState & MouseButtonState.Button3Pressed) != 0) {
  913. // me.ButtonState &= ~(MouseButtonState.Button3Pressed | MouseButtonState.ReportMousePosition);
  914. // me.ButtonState |= MouseButtonState.Button3Released;
  915. // }
  916. // isButtonReleased = true;
  917. // lastMouseEvent = me;
  918. // inputResultQueue.Enqueue (new InputResult () {
  919. // EventType = EventType.Mouse,
  920. // MouseEvent = me
  921. // });
  922. //}
  923. ConsoleModifiers GetConsoleModifiers (uint keyChar)
  924. {
  925. switch (keyChar) {
  926. case 50:
  927. return ConsoleModifiers.Shift;
  928. case 51:
  929. return ConsoleModifiers.Alt;
  930. case 52:
  931. return ConsoleModifiers.Shift | ConsoleModifiers.Alt;
  932. case 53:
  933. return ConsoleModifiers.Control;
  934. case 54:
  935. return ConsoleModifiers.Shift | ConsoleModifiers.Control;
  936. case 55:
  937. return ConsoleModifiers.Alt | ConsoleModifiers.Control;
  938. case 56:
  939. return ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control;
  940. default:
  941. return 0;
  942. }
  943. }
  944. ConsoleKey GetConsoleKey (char keyChar, ref ConsoleModifiers mod, int length)
  945. {
  946. ConsoleKey key;
  947. switch (keyChar) {
  948. case 'A':
  949. key = ConsoleKey.UpArrow;
  950. break;
  951. case 'B':
  952. key = ConsoleKey.DownArrow;
  953. break;
  954. case 'C':
  955. key = ConsoleKey.RightArrow;
  956. break;
  957. case 'D':
  958. key = ConsoleKey.LeftArrow;
  959. break;
  960. case 'F':
  961. key = ConsoleKey.End;
  962. break;
  963. case 'H':
  964. key = ConsoleKey.Home;
  965. break;
  966. case 'P':
  967. key = ConsoleKey.F1;
  968. break;
  969. case 'Q':
  970. key = ConsoleKey.F2;
  971. break;
  972. case 'R':
  973. key = ConsoleKey.F3;
  974. break;
  975. case 'S':
  976. key = ConsoleKey.F4;
  977. break;
  978. case 'Z':
  979. key = ConsoleKey.Tab;
  980. mod |= ConsoleModifiers.Shift;
  981. break;
  982. case '0':
  983. key = ConsoleKey.F9;
  984. break;
  985. case '1':
  986. key = ConsoleKey.F10;
  987. break;
  988. case '2':
  989. key = ConsoleKey.Insert;
  990. break;
  991. case '3':
  992. if (length == 5) {
  993. key = ConsoleKey.F11;
  994. } else {
  995. key = ConsoleKey.Delete;
  996. }
  997. break;
  998. case '4':
  999. key = ConsoleKey.F12;
  1000. break;
  1001. case '5':
  1002. if (length == 5) {
  1003. key = ConsoleKey.F5;
  1004. } else {
  1005. key = ConsoleKey.PageUp;
  1006. }
  1007. break;
  1008. case '6':
  1009. key = ConsoleKey.PageDown;
  1010. break;
  1011. case '7':
  1012. key = ConsoleKey.F6;
  1013. break;
  1014. case '8':
  1015. key = ConsoleKey.F7;
  1016. break;
  1017. case '9':
  1018. key = ConsoleKey.F8;
  1019. break;
  1020. default:
  1021. key = 0;
  1022. break;
  1023. }
  1024. return key;
  1025. }
  1026. public enum EventType {
  1027. Key = 1,
  1028. Mouse = 2,
  1029. WindowSize = 3,
  1030. WindowPosition = 4
  1031. }
  1032. [Flags]
  1033. public enum MouseButtonState {
  1034. Button1Pressed = 0x1,
  1035. Button1Released = 0x2,
  1036. Button1Clicked = 0x4,
  1037. Button1DoubleClicked = 0x8,
  1038. Button1TripleClicked = 0x10,
  1039. Button2Pressed = 0x20,
  1040. Button2Released = 0x40,
  1041. Button2Clicked = 0x80,
  1042. Button2DoubleClicked = 0x100,
  1043. Button2TrippleClicked = 0x200,
  1044. Button3Pressed = 0x400,
  1045. Button3Released = 0x800,
  1046. Button3Clicked = 0x1000,
  1047. Button3DoubleClicked = 0x2000,
  1048. Button3TripleClicked = 0x4000,
  1049. ButtonWheeledUp = 0x8000,
  1050. ButtonWheeledDown = 0x10000,
  1051. ButtonWheeledLeft = 0x20000,
  1052. ButtonWheeledRight = 0x40000,
  1053. Button4Pressed = 0x80000,
  1054. Button4Released = 0x100000,
  1055. Button4Clicked = 0x200000,
  1056. Button4DoubleClicked = 0x400000,
  1057. Button4TripleClicked = 0x800000,
  1058. ButtonShift = 0x1000000,
  1059. ButtonCtrl = 0x2000000,
  1060. ButtonAlt = 0x4000000,
  1061. ReportMousePosition = 0x8000000,
  1062. AllEvents = Button1Pressed | Button1Released | Button1Clicked | Button1DoubleClicked | Button1TripleClicked | Button2Pressed | Button2Released | Button2Clicked | Button2DoubleClicked | Button2TrippleClicked | Button3Pressed | Button3Released | Button3Clicked | Button3DoubleClicked | Button3TripleClicked | ButtonWheeledUp | ButtonWheeledDown | ButtonWheeledLeft | ButtonWheeledRight | Button4Pressed | Button4Released | Button4Clicked | Button4DoubleClicked | Button4TripleClicked | ReportMousePosition
  1063. }
  1064. public struct MouseEvent {
  1065. public Point Position;
  1066. public MouseButtonState ButtonState;
  1067. }
  1068. public struct WindowSizeEvent {
  1069. public Size Size;
  1070. }
  1071. public struct WindowPositionEvent {
  1072. public int Top;
  1073. public int Left;
  1074. public Point CursorPosition;
  1075. }
  1076. public struct InputResult {
  1077. public EventType EventType;
  1078. public ConsoleKeyInfo ConsoleKeyInfo;
  1079. public MouseEvent MouseEvent;
  1080. public WindowSizeEvent WindowSizeEvent;
  1081. public WindowPositionEvent WindowPositionEvent;
  1082. }
  1083. }
  1084. internal class NetDriver : ConsoleDriver {
  1085. const int COLOR_BLACK = 30;
  1086. const int COLOR_RED = 31;
  1087. const int COLOR_GREEN = 32;
  1088. const int COLOR_YELLOW = 33;
  1089. const int COLOR_BLUE = 34;
  1090. const int COLOR_MAGENTA = 35;
  1091. const int COLOR_CYAN = 36;
  1092. const int COLOR_WHITE = 37;
  1093. const int COLOR_BRIGHT_BLACK = 90;
  1094. const int COLOR_BRIGHT_RED = 91;
  1095. const int COLOR_BRIGHT_GREEN = 92;
  1096. const int COLOR_BRIGHT_YELLOW = 93;
  1097. const int COLOR_BRIGHT_BLUE = 94;
  1098. const int COLOR_BRIGHT_MAGENTA = 95;
  1099. const int COLOR_BRIGHT_CYAN = 96;
  1100. const int COLOR_BRIGHT_WHITE = 97;
  1101. int cols, rows, left, top;
  1102. public override int Cols => cols;
  1103. public override int Rows => rows;
  1104. public override int Left => left;
  1105. public override int Top => top;
  1106. public override bool HeightAsBuffer { get; set; }
  1107. public NetWinVTConsole NetWinConsole { get; }
  1108. public bool IsWinPlatform { get; }
  1109. public override IClipboard Clipboard { get; }
  1110. public override int [,,] Contents => contents;
  1111. int largestWindowHeight;
  1112. public NetDriver ()
  1113. {
  1114. var p = Environment.OSVersion.Platform;
  1115. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) {
  1116. IsWinPlatform = true;
  1117. NetWinConsole = new NetWinVTConsole ();
  1118. }
  1119. //largestWindowHeight = Math.Max (Console.BufferHeight, largestWindowHeight);
  1120. largestWindowHeight = Console.BufferHeight;
  1121. if (IsWinPlatform) {
  1122. Clipboard = new WindowsClipboard ();
  1123. } else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
  1124. Clipboard = new MacOSXClipboard ();
  1125. } else {
  1126. if (CursesDriver.Is_WSL_Platform ()) {
  1127. Clipboard = new WSLClipboard ();
  1128. } else {
  1129. Clipboard = new CursesClipboard ();
  1130. }
  1131. }
  1132. }
  1133. // The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  1134. int [,,] contents;
  1135. bool [] dirtyLine;
  1136. static bool sync = false;
  1137. // Current row, and current col, tracked by Move/AddCh only
  1138. int ccol, crow;
  1139. public override void Move (int col, int row)
  1140. {
  1141. ccol = col;
  1142. crow = row;
  1143. }
  1144. public override void AddRune (Rune rune)
  1145. {
  1146. if (contents.Length != Rows * Cols * 3) {
  1147. return;
  1148. }
  1149. rune = MakePrintable (rune);
  1150. var runeWidth = Rune.ColumnWidth (rune);
  1151. var validClip = IsValidContent (ccol, crow, Clip);
  1152. if (validClip) {
  1153. if (runeWidth < 2 && ccol > 0
  1154. && Rune.ColumnWidth ((char)contents [crow, ccol - 1, 0]) > 1) {
  1155. contents [crow, ccol - 1, 0] = (int)(uint)' ';
  1156. } else if (runeWidth < 2 && ccol <= Clip.Right - 1
  1157. && Rune.ColumnWidth ((char)contents [crow, ccol, 0]) > 1) {
  1158. contents [crow, ccol + 1, 0] = (int)(uint)' ';
  1159. contents [crow, ccol + 1, 2] = 1;
  1160. }
  1161. if (runeWidth > 1 && ccol == Clip.Right - 1) {
  1162. contents [crow, ccol, 0] = (int)(uint)' ';
  1163. } else {
  1164. contents [crow, ccol, 0] = (int)(uint)rune;
  1165. }
  1166. contents [crow, ccol, 1] = currentAttribute;
  1167. contents [crow, ccol, 2] = 1;
  1168. dirtyLine [crow] = true;
  1169. }
  1170. ccol++;
  1171. if (runeWidth > 1) {
  1172. if (validClip && ccol < Clip.Right) {
  1173. contents [crow, ccol, 1] = currentAttribute;
  1174. contents [crow, ccol, 2] = 0;
  1175. }
  1176. ccol++;
  1177. }
  1178. //if (ccol == Cols) {
  1179. // ccol = 0;
  1180. // if (crow + 1 < Rows)
  1181. // crow++;
  1182. //}
  1183. if (sync) {
  1184. UpdateScreen ();
  1185. }
  1186. }
  1187. public override void AddStr (ustring str)
  1188. {
  1189. foreach (var rune in str)
  1190. AddRune (rune);
  1191. }
  1192. public override void End ()
  1193. {
  1194. if (IsWinPlatform) {
  1195. NetWinConsole.Cleanup ();
  1196. }
  1197. StopReportingMouseMoves ();
  1198. Console.ResetColor ();
  1199. Clear ();
  1200. //Set cursor key to cursor.
  1201. Console.Out.Write ("\x1b[?25h");
  1202. Console.Out.Flush ();
  1203. }
  1204. void Clear ()
  1205. {
  1206. if (Rows > 0) {
  1207. Console.Clear ();
  1208. Console.Out.Write ("\x1b[3J");
  1209. //Console.Out.Write ("\x1b[?25l");
  1210. }
  1211. }
  1212. public override Attribute MakeColor (Color foreground, Color background)
  1213. {
  1214. return MakeColor ((ConsoleColor)foreground, (ConsoleColor)background);
  1215. }
  1216. static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  1217. {
  1218. // Encode the colors into the int value.
  1219. return new Attribute (
  1220. value: ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff),
  1221. foreground: (Color)f,
  1222. background: (Color)b
  1223. );
  1224. }
  1225. public override void Init (Action terminalResized)
  1226. {
  1227. TerminalResized = terminalResized;
  1228. //Set cursor key to application.
  1229. Console.Out.Write ("\x1b[?25l");
  1230. Console.Out.Flush ();
  1231. Console.TreatControlCAsInput = true;
  1232. cols = Console.WindowWidth;
  1233. rows = Console.WindowHeight;
  1234. ResizeScreen ();
  1235. UpdateOffScreen ();
  1236. StartReportingMouseMoves ();
  1237. CreateColors ();
  1238. Clear ();
  1239. }
  1240. public override void ResizeScreen ()
  1241. {
  1242. if (!HeightAsBuffer) {
  1243. if (Console.WindowHeight > 0) {
  1244. // Can raise an exception while is still resizing.
  1245. try {
  1246. // Not supported on Unix.
  1247. if (IsWinPlatform) {
  1248. #pragma warning disable CA1416
  1249. Console.CursorTop = 0;
  1250. Console.CursorLeft = 0;
  1251. Console.WindowTop = 0;
  1252. Console.WindowLeft = 0;
  1253. Console.SetBufferSize (Cols, Rows);
  1254. #pragma warning restore CA1416
  1255. } else {
  1256. //Console.Out.Write ($"\x1b[8;{Console.WindowHeight};{Console.WindowWidth}t");
  1257. Console.Out.Write ($"\x1b[0;0" +
  1258. $";{Rows};{Cols}w");
  1259. }
  1260. } catch (System.IO.IOException) {
  1261. return;
  1262. } catch (ArgumentOutOfRangeException) {
  1263. return;
  1264. }
  1265. }
  1266. } else {
  1267. if (IsWinPlatform && Console.WindowHeight > 0) {
  1268. // Can raise an exception while is still resizing.
  1269. try {
  1270. #pragma warning disable CA1416
  1271. Console.WindowTop = Math.Max (Math.Min (top, Rows - Console.WindowHeight), 0);
  1272. #pragma warning restore CA1416
  1273. } catch (Exception) {
  1274. return;
  1275. }
  1276. } else {
  1277. Console.Out.Write ($"\x1b[{top};{Console.WindowLeft}" +
  1278. $";{Rows};{Cols}w");
  1279. }
  1280. }
  1281. Clip = new Rect (0, 0, Cols, Rows);
  1282. Console.Out.Write ("\x1b[3J");
  1283. Console.Out.Flush ();
  1284. }
  1285. public override void UpdateOffScreen ()
  1286. {
  1287. contents = new int [Rows, Cols, 3];
  1288. dirtyLine = new bool [Rows];
  1289. lock (contents) {
  1290. // Can raise an exception while is still resizing.
  1291. try {
  1292. for (int row = 0; row < rows; row++) {
  1293. for (int c = 0; c < cols; c++) {
  1294. contents [row, c, 0] = ' ';
  1295. contents [row, c, 1] = (ushort)Colors.TopLevel.Normal;
  1296. contents [row, c, 2] = 0;
  1297. dirtyLine [row] = true;
  1298. }
  1299. }
  1300. } catch (IndexOutOfRangeException) { }
  1301. }
  1302. }
  1303. public override Attribute MakeAttribute (Color fore, Color back)
  1304. {
  1305. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  1306. }
  1307. public override void Refresh ()
  1308. {
  1309. UpdateScreen ();
  1310. UpdateCursor ();
  1311. }
  1312. int redrawAttr = -1;
  1313. public override void UpdateScreen ()
  1314. {
  1315. if (Console.WindowHeight == 0 || contents.Length != Rows * Cols * 3
  1316. || (!HeightAsBuffer && Rows != Console.WindowHeight)
  1317. || (HeightAsBuffer && Rows != largestWindowHeight)) {
  1318. return;
  1319. }
  1320. int top = Top;
  1321. int left = Left;
  1322. int rows = Math.Min (Console.WindowHeight + top, Rows);
  1323. int cols = Cols;
  1324. System.Text.StringBuilder output = new System.Text.StringBuilder ();
  1325. var lastCol = -1;
  1326. Console.CursorVisible = false;
  1327. for (int row = top; row < rows; row++) {
  1328. if (!dirtyLine [row]) {
  1329. continue;
  1330. }
  1331. dirtyLine [row] = false;
  1332. output.Clear ();
  1333. for (int col = left; col < cols; col++) {
  1334. if (Console.WindowHeight > 0 && !SetCursorPosition (col, row)) {
  1335. return;
  1336. }
  1337. lastCol = -1;
  1338. var outputWidth = 0;
  1339. for (; col < cols; col++) {
  1340. if (contents [row, col, 2] == 0) {
  1341. if (output.Length > 0) {
  1342. //Console.CursorLeft = lastCol;
  1343. //Console.CursorTop = row;
  1344. SetVirtualCursorPosition (lastCol, row);
  1345. Console.Write (output);
  1346. output.Clear ();
  1347. lastCol += outputWidth;
  1348. outputWidth = 0;
  1349. } else if (lastCol == -1) {
  1350. lastCol = col;
  1351. }
  1352. if (lastCol + 1 < cols)
  1353. lastCol++;
  1354. continue;
  1355. }
  1356. if (lastCol == -1)
  1357. lastCol = col;
  1358. var attr = contents [row, col, 1];
  1359. if (attr != redrawAttr) {
  1360. output.Append (WriteAttributes (attr));
  1361. }
  1362. outputWidth++;
  1363. output.Append ((char)contents [row, col, 0]);
  1364. contents [row, col, 2] = 0;
  1365. }
  1366. }
  1367. if (output.Length > 0) {
  1368. //Console.CursorLeft = lastCol;
  1369. //Console.CursorTop = row;
  1370. SetVirtualCursorPosition (lastCol, row);
  1371. Console.Write (output);
  1372. }
  1373. }
  1374. }
  1375. void SetVirtualCursorPosition (int lastCol, int row)
  1376. {
  1377. Console.Out.Write ($"\x1b[{row + 1};{lastCol + 1}H");
  1378. Console.Out.Flush ();
  1379. }
  1380. System.Text.StringBuilder WriteAttributes (int attr)
  1381. {
  1382. const string CSI = "\x1b[";
  1383. int bg = 0;
  1384. int fg = 0;
  1385. System.Text.StringBuilder sb = new System.Text.StringBuilder ();
  1386. redrawAttr = attr;
  1387. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  1388. .OfType<ConsoleColor> ()
  1389. .Select (s => (int)s);
  1390. if (values.Contains (attr & 0xffff)) {
  1391. bg = MapColors ((ConsoleColor)(attr & 0xffff), false);
  1392. }
  1393. if (values.Contains ((attr >> 16) & 0xffff)) {
  1394. fg = MapColors ((ConsoleColor)((attr >> 16) & 0xffff));
  1395. }
  1396. sb.Append ($"{CSI}{bg};{fg}m");
  1397. return sb;
  1398. }
  1399. int MapColors (ConsoleColor color, bool isForeground = true)
  1400. {
  1401. switch (color) {
  1402. case ConsoleColor.Black:
  1403. return isForeground ? COLOR_BLACK : COLOR_BLACK + 10;
  1404. case ConsoleColor.DarkBlue:
  1405. return isForeground ? COLOR_BLUE : COLOR_BLUE + 10;
  1406. case ConsoleColor.DarkGreen:
  1407. return isForeground ? COLOR_GREEN : COLOR_GREEN + 10;
  1408. case ConsoleColor.DarkCyan:
  1409. return isForeground ? COLOR_CYAN : COLOR_CYAN + 10;
  1410. case ConsoleColor.DarkRed:
  1411. return isForeground ? COLOR_RED : COLOR_RED + 10;
  1412. case ConsoleColor.DarkMagenta:
  1413. return isForeground ? COLOR_MAGENTA : COLOR_MAGENTA + 10;
  1414. case ConsoleColor.DarkYellow:
  1415. return isForeground ? COLOR_YELLOW : COLOR_YELLOW + 10;
  1416. case ConsoleColor.Gray:
  1417. return isForeground ? COLOR_WHITE : COLOR_WHITE + 10;
  1418. case ConsoleColor.DarkGray:
  1419. return isForeground ? COLOR_BRIGHT_BLACK : COLOR_BRIGHT_BLACK + 10;
  1420. case ConsoleColor.Blue:
  1421. return isForeground ? COLOR_BRIGHT_BLUE : COLOR_BRIGHT_BLUE + 10;
  1422. case ConsoleColor.Green:
  1423. return isForeground ? COLOR_BRIGHT_GREEN : COLOR_BRIGHT_GREEN + 10;
  1424. case ConsoleColor.Cyan:
  1425. return isForeground ? COLOR_BRIGHT_CYAN : COLOR_BRIGHT_CYAN + 10;
  1426. case ConsoleColor.Red:
  1427. return isForeground ? COLOR_BRIGHT_RED : COLOR_BRIGHT_RED + 10;
  1428. case ConsoleColor.Magenta:
  1429. return isForeground ? COLOR_BRIGHT_MAGENTA : COLOR_BRIGHT_MAGENTA + 10;
  1430. case ConsoleColor.Yellow:
  1431. return isForeground ? COLOR_BRIGHT_YELLOW : COLOR_BRIGHT_YELLOW + 10;
  1432. case ConsoleColor.White:
  1433. return isForeground ? COLOR_BRIGHT_WHITE : COLOR_BRIGHT_WHITE + 10;
  1434. }
  1435. return 0;
  1436. }
  1437. bool SetCursorPosition (int col, int row)
  1438. {
  1439. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  1440. try {
  1441. Console.SetCursorPosition (col, row);
  1442. return true;
  1443. } catch (Exception) {
  1444. return false;
  1445. }
  1446. }
  1447. private CursorVisibility? savedCursorVisibility;
  1448. public override void UpdateCursor ()
  1449. {
  1450. if (!EnsureCursorVisibility ())
  1451. return;
  1452. // Prevents the exception of size changing during resizing.
  1453. try {
  1454. if (ccol >= 0 && ccol < Console.BufferWidth && crow >= 0 && crow < Console.BufferHeight) {
  1455. Console.SetCursorPosition (ccol, crow);
  1456. }
  1457. } catch (System.IO.IOException) {
  1458. } catch (ArgumentOutOfRangeException) {
  1459. }
  1460. }
  1461. public override void StartReportingMouseMoves ()
  1462. {
  1463. Console.Out.Write ("\x1b[?1003h\x1b[?1015h\x1b[?1006h");
  1464. Console.Out.Flush ();
  1465. }
  1466. public override void StopReportingMouseMoves ()
  1467. {
  1468. Console.Out.Write ("\x1b[?1003l\x1b[?1015l\x1b[?1006l");
  1469. Console.Out.Flush ();
  1470. }
  1471. public override void Suspend ()
  1472. {
  1473. }
  1474. Attribute currentAttribute;
  1475. public override void SetAttribute (Attribute c)
  1476. {
  1477. currentAttribute = c;
  1478. }
  1479. Key MapKey (ConsoleKeyInfo keyInfo)
  1480. {
  1481. MapKeyModifiers (keyInfo, (Key)keyInfo.Key);
  1482. switch (keyInfo.Key) {
  1483. case ConsoleKey.Escape:
  1484. return MapKeyModifiers (keyInfo, Key.Esc);
  1485. case ConsoleKey.Tab:
  1486. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  1487. case ConsoleKey.Home:
  1488. return MapKeyModifiers (keyInfo, Key.Home);
  1489. case ConsoleKey.End:
  1490. return MapKeyModifiers (keyInfo, Key.End);
  1491. case ConsoleKey.LeftArrow:
  1492. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  1493. case ConsoleKey.RightArrow:
  1494. return MapKeyModifiers (keyInfo, Key.CursorRight);
  1495. case ConsoleKey.UpArrow:
  1496. return MapKeyModifiers (keyInfo, Key.CursorUp);
  1497. case ConsoleKey.DownArrow:
  1498. return MapKeyModifiers (keyInfo, Key.CursorDown);
  1499. case ConsoleKey.PageUp:
  1500. return MapKeyModifiers (keyInfo, Key.PageUp);
  1501. case ConsoleKey.PageDown:
  1502. return MapKeyModifiers (keyInfo, Key.PageDown);
  1503. case ConsoleKey.Enter:
  1504. return MapKeyModifiers (keyInfo, Key.Enter);
  1505. case ConsoleKey.Spacebar:
  1506. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  1507. case ConsoleKey.Backspace:
  1508. return MapKeyModifiers (keyInfo, Key.Backspace);
  1509. case ConsoleKey.Delete:
  1510. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  1511. case ConsoleKey.Insert:
  1512. return MapKeyModifiers (keyInfo, Key.InsertChar);
  1513. case ConsoleKey.Oem1:
  1514. case ConsoleKey.Oem2:
  1515. case ConsoleKey.Oem3:
  1516. case ConsoleKey.Oem4:
  1517. case ConsoleKey.Oem5:
  1518. case ConsoleKey.Oem6:
  1519. case ConsoleKey.Oem7:
  1520. case ConsoleKey.Oem8:
  1521. case ConsoleKey.Oem102:
  1522. case ConsoleKey.OemPeriod:
  1523. case ConsoleKey.OemComma:
  1524. case ConsoleKey.OemPlus:
  1525. case ConsoleKey.OemMinus:
  1526. return (Key)((uint)keyInfo.KeyChar);
  1527. }
  1528. var key = keyInfo.Key;
  1529. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  1530. var delta = key - ConsoleKey.A;
  1531. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1532. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1533. }
  1534. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1535. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1536. }
  1537. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1538. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1539. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1540. }
  1541. }
  1542. return (Key)((uint)keyInfo.KeyChar);
  1543. }
  1544. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1545. var delta = key - ConsoleKey.D0;
  1546. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1547. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1548. }
  1549. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1550. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1551. }
  1552. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1553. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
  1554. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1555. }
  1556. }
  1557. return (Key)((uint)keyInfo.KeyChar);
  1558. }
  1559. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1560. var delta = key - ConsoleKey.F1;
  1561. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1562. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1563. }
  1564. return (Key)((uint)Key.F1 + delta);
  1565. }
  1566. if (keyInfo.KeyChar != 0) {
  1567. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1568. }
  1569. return (Key)(0xffffffff);
  1570. }
  1571. KeyModifiers keyModifiers;
  1572. Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1573. {
  1574. if (keyModifiers == null) {
  1575. keyModifiers = new KeyModifiers ();
  1576. }
  1577. Key keyMod = new Key ();
  1578. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0) {
  1579. keyMod = Key.ShiftMask;
  1580. keyModifiers.Shift = true;
  1581. }
  1582. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) {
  1583. keyMod |= Key.CtrlMask;
  1584. keyModifiers.Ctrl = true;
  1585. }
  1586. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0) {
  1587. keyMod |= Key.AltMask;
  1588. keyModifiers.Alt = true;
  1589. }
  1590. return keyMod != Key.Null ? keyMod | key : key;
  1591. }
  1592. Action<KeyEvent> keyHandler;
  1593. Action<KeyEvent> keyDownHandler;
  1594. Action<KeyEvent> keyUpHandler;
  1595. Action<MouseEvent> mouseHandler;
  1596. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  1597. {
  1598. this.keyHandler = keyHandler;
  1599. this.keyDownHandler = keyDownHandler;
  1600. this.keyUpHandler = keyUpHandler;
  1601. this.mouseHandler = mouseHandler;
  1602. var mLoop = mainLoop.Driver as NetMainLoop;
  1603. // Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will be simulated to be called.
  1604. mLoop.ProcessInput = (e) => ProcessInput (e);
  1605. }
  1606. void ProcessInput (NetEvents.InputResult inputEvent)
  1607. {
  1608. switch (inputEvent.EventType) {
  1609. case NetEvents.EventType.Key:
  1610. keyModifiers = new KeyModifiers ();
  1611. var map = MapKey (inputEvent.ConsoleKeyInfo);
  1612. if (map == (Key)0xffffffff) {
  1613. return;
  1614. }
  1615. keyDownHandler (new KeyEvent (map, keyModifiers));
  1616. keyHandler (new KeyEvent (map, keyModifiers));
  1617. keyUpHandler (new KeyEvent (map, keyModifiers));
  1618. break;
  1619. case NetEvents.EventType.Mouse:
  1620. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  1621. break;
  1622. case NetEvents.EventType.WindowSize:
  1623. ChangeWin ();
  1624. break;
  1625. case NetEvents.EventType.WindowPosition:
  1626. var newTop = inputEvent.WindowPositionEvent.Top;
  1627. var newLeft = inputEvent.WindowPositionEvent.Left;
  1628. if (HeightAsBuffer && (top != newTop || left != newLeft)) {
  1629. top = newTop;
  1630. left = newLeft;
  1631. Refresh ();
  1632. }
  1633. break;
  1634. }
  1635. }
  1636. void ChangeWin ()
  1637. {
  1638. const int Min_WindowWidth = 14;
  1639. Size size = new Size ();
  1640. if (!HeightAsBuffer) {
  1641. size = new Size (Math.Max (Min_WindowWidth, Console.WindowWidth),
  1642. Console.WindowHeight);
  1643. top = 0;
  1644. left = 0;
  1645. } else {
  1646. //largestWindowHeight = Math.Max (Console.BufferHeight, largestWindowHeight);
  1647. largestWindowHeight = Console.BufferHeight;
  1648. size = new Size (Console.BufferWidth, largestWindowHeight);
  1649. }
  1650. cols = size.Width;
  1651. rows = size.Height;
  1652. ResizeScreen ();
  1653. UpdateOffScreen ();
  1654. TerminalResized?.Invoke ();
  1655. }
  1656. MouseEvent ToDriverMouse (NetEvents.MouseEvent me)
  1657. {
  1658. MouseFlags mouseFlag = 0;
  1659. if ((me.ButtonState & NetEvents.MouseButtonState.Button1Pressed) != 0) {
  1660. mouseFlag |= MouseFlags.Button1Pressed;
  1661. }
  1662. if ((me.ButtonState & NetEvents.MouseButtonState.Button1Released) != 0) {
  1663. mouseFlag |= MouseFlags.Button1Released;
  1664. }
  1665. if ((me.ButtonState & NetEvents.MouseButtonState.Button1Clicked) != 0) {
  1666. mouseFlag |= MouseFlags.Button1Clicked;
  1667. }
  1668. if ((me.ButtonState & NetEvents.MouseButtonState.Button1DoubleClicked) != 0) {
  1669. mouseFlag |= MouseFlags.Button1DoubleClicked;
  1670. }
  1671. if ((me.ButtonState & NetEvents.MouseButtonState.Button1TripleClicked) != 0) {
  1672. mouseFlag |= MouseFlags.Button1TripleClicked;
  1673. }
  1674. if ((me.ButtonState & NetEvents.MouseButtonState.Button2Pressed) != 0) {
  1675. mouseFlag |= MouseFlags.Button2Pressed;
  1676. }
  1677. if ((me.ButtonState & NetEvents.MouseButtonState.Button2Released) != 0) {
  1678. mouseFlag |= MouseFlags.Button2Released;
  1679. }
  1680. if ((me.ButtonState & NetEvents.MouseButtonState.Button2Clicked) != 0) {
  1681. mouseFlag |= MouseFlags.Button2Clicked;
  1682. }
  1683. if ((me.ButtonState & NetEvents.MouseButtonState.Button2DoubleClicked) != 0) {
  1684. mouseFlag |= MouseFlags.Button2DoubleClicked;
  1685. }
  1686. if ((me.ButtonState & NetEvents.MouseButtonState.Button2TrippleClicked) != 0) {
  1687. mouseFlag |= MouseFlags.Button2TripleClicked;
  1688. }
  1689. if ((me.ButtonState & NetEvents.MouseButtonState.Button3Pressed) != 0) {
  1690. mouseFlag |= MouseFlags.Button3Pressed;
  1691. }
  1692. if ((me.ButtonState & NetEvents.MouseButtonState.Button3Released) != 0) {
  1693. mouseFlag |= MouseFlags.Button3Released;
  1694. }
  1695. if ((me.ButtonState & NetEvents.MouseButtonState.Button3Clicked) != 0) {
  1696. mouseFlag |= MouseFlags.Button3Clicked;
  1697. }
  1698. if ((me.ButtonState & NetEvents.MouseButtonState.Button3DoubleClicked) != 0) {
  1699. mouseFlag |= MouseFlags.Button3DoubleClicked;
  1700. }
  1701. if ((me.ButtonState & NetEvents.MouseButtonState.Button3TripleClicked) != 0) {
  1702. mouseFlag |= MouseFlags.Button3TripleClicked;
  1703. }
  1704. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonWheeledUp) != 0) {
  1705. mouseFlag |= MouseFlags.WheeledUp;
  1706. }
  1707. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonWheeledDown) != 0) {
  1708. mouseFlag |= MouseFlags.WheeledDown;
  1709. }
  1710. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonWheeledLeft) != 0) {
  1711. mouseFlag |= MouseFlags.WheeledLeft;
  1712. }
  1713. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonWheeledRight) != 0) {
  1714. mouseFlag |= MouseFlags.WheeledRight;
  1715. }
  1716. if ((me.ButtonState & NetEvents.MouseButtonState.Button4Pressed) != 0) {
  1717. mouseFlag |= MouseFlags.Button4Pressed;
  1718. }
  1719. if ((me.ButtonState & NetEvents.MouseButtonState.Button4Released) != 0) {
  1720. mouseFlag |= MouseFlags.Button4Released;
  1721. }
  1722. if ((me.ButtonState & NetEvents.MouseButtonState.Button4Clicked) != 0) {
  1723. mouseFlag |= MouseFlags.Button4Clicked;
  1724. }
  1725. if ((me.ButtonState & NetEvents.MouseButtonState.Button4DoubleClicked) != 0) {
  1726. mouseFlag |= MouseFlags.Button4DoubleClicked;
  1727. }
  1728. if ((me.ButtonState & NetEvents.MouseButtonState.Button4TripleClicked) != 0) {
  1729. mouseFlag |= MouseFlags.Button4TripleClicked;
  1730. }
  1731. if ((me.ButtonState & NetEvents.MouseButtonState.ReportMousePosition) != 0) {
  1732. mouseFlag |= MouseFlags.ReportMousePosition;
  1733. }
  1734. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonShift) != 0) {
  1735. mouseFlag |= MouseFlags.ButtonShift;
  1736. }
  1737. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonCtrl) != 0) {
  1738. mouseFlag |= MouseFlags.ButtonCtrl;
  1739. }
  1740. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonAlt) != 0) {
  1741. mouseFlag |= MouseFlags.ButtonAlt;
  1742. }
  1743. return new MouseEvent () {
  1744. X = me.Position.X,
  1745. Y = me.Position.Y,
  1746. Flags = mouseFlag
  1747. };
  1748. }
  1749. public override Attribute GetAttribute ()
  1750. {
  1751. return currentAttribute;
  1752. }
  1753. /// <inheritdoc/>
  1754. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1755. {
  1756. visibility = savedCursorVisibility ?? CursorVisibility.Default;
  1757. return visibility == CursorVisibility.Default;
  1758. }
  1759. /// <inheritdoc/>
  1760. public override bool SetCursorVisibility (CursorVisibility visibility)
  1761. {
  1762. savedCursorVisibility = visibility;
  1763. return Console.CursorVisible = visibility == CursorVisibility.Default;
  1764. }
  1765. /// <inheritdoc/>
  1766. public override bool EnsureCursorVisibility ()
  1767. {
  1768. if (!(ccol >= 0 && crow >= 0 && ccol < Cols && crow < Rows)) {
  1769. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1770. savedCursorVisibility = cursorVisibility;
  1771. SetCursorVisibility (CursorVisibility.Invisible);
  1772. return false;
  1773. }
  1774. SetCursorVisibility (savedCursorVisibility ?? CursorVisibility.Default);
  1775. return savedCursorVisibility == CursorVisibility.Default;
  1776. }
  1777. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1778. {
  1779. NetEvents.InputResult input = new NetEvents.InputResult ();
  1780. ConsoleKey ck;
  1781. if (char.IsLetter (keyChar)) {
  1782. ck = key;
  1783. } else {
  1784. ck = (ConsoleKey)'\0';
  1785. }
  1786. input.EventType = NetEvents.EventType.Key;
  1787. input.ConsoleKeyInfo = new ConsoleKeyInfo (keyChar, ck, shift, alt, control);
  1788. try {
  1789. ProcessInput (input);
  1790. } catch (OverflowException) { }
  1791. }
  1792. public override bool GetColors (int value, out Color foreground, out Color background)
  1793. {
  1794. bool hasColor = false;
  1795. foreground = default;
  1796. background = default;
  1797. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  1798. .OfType<ConsoleColor> ()
  1799. .Select (s => (int)s);
  1800. if (values.Contains (value & 0xffff)) {
  1801. hasColor = true;
  1802. background = (Color)(ConsoleColor)(value & 0xffff);
  1803. }
  1804. if (values.Contains ((value >> 16) & 0xffff)) {
  1805. hasColor = true;
  1806. foreground = (Color)(ConsoleColor)((value >> 16) & 0xffff);
  1807. }
  1808. return hasColor;
  1809. }
  1810. #region Unused
  1811. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1812. {
  1813. }
  1814. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1815. {
  1816. }
  1817. public override void CookMouse ()
  1818. {
  1819. }
  1820. public override void UncookMouse ()
  1821. {
  1822. }
  1823. #endregion
  1824. //
  1825. // These are for the .NET driver, but running natively on Windows, wont run
  1826. // on the Mono emulation
  1827. //
  1828. }
  1829. /// <summary>
  1830. /// Mainloop intended to be used with the .NET System.Console API, and can
  1831. /// be used on Windows and Unix, it is cross platform but lacks things like
  1832. /// file descriptor monitoring.
  1833. /// </summary>
  1834. /// <remarks>
  1835. /// This implementation is used for NetDriver.
  1836. /// </remarks>
  1837. internal class NetMainLoop : IMainLoopDriver {
  1838. ManualResetEventSlim keyReady = new ManualResetEventSlim (false);
  1839. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  1840. Queue<NetEvents.InputResult?> inputResult = new Queue<NetEvents.InputResult?> ();
  1841. MainLoop mainLoop;
  1842. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  1843. NetEvents netEvents;
  1844. /// <summary>
  1845. /// Invoked when a Key is pressed.
  1846. /// </summary>
  1847. public Action<NetEvents.InputResult> ProcessInput;
  1848. /// <summary>
  1849. /// Initializes the class with the console driver.
  1850. /// </summary>
  1851. /// <remarks>
  1852. /// Passing a consoleDriver is provided to capture windows resizing.
  1853. /// </remarks>
  1854. /// <param name="consoleDriver">The console driver used by this Net main loop.</param>
  1855. public NetMainLoop (ConsoleDriver consoleDriver = null)
  1856. {
  1857. if (consoleDriver == null) {
  1858. throw new ArgumentNullException ("Console driver instance must be provided.");
  1859. }
  1860. netEvents = new NetEvents (consoleDriver);
  1861. }
  1862. void NetInputHandler ()
  1863. {
  1864. while (true) {
  1865. waitForProbe.Wait ();
  1866. waitForProbe.Reset ();
  1867. if (inputResult.Count == 0) {
  1868. inputResult.Enqueue (netEvents.ReadConsoleInput ());
  1869. }
  1870. try {
  1871. while (inputResult.Peek () == null) {
  1872. inputResult.Dequeue ();
  1873. }
  1874. if (inputResult.Count > 0) {
  1875. keyReady.Set ();
  1876. }
  1877. } catch (InvalidOperationException) { }
  1878. }
  1879. }
  1880. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1881. {
  1882. this.mainLoop = mainLoop;
  1883. Task.Run (NetInputHandler);
  1884. }
  1885. void IMainLoopDriver.Wakeup ()
  1886. {
  1887. keyReady.Set ();
  1888. }
  1889. bool IMainLoopDriver.EventsPending (bool wait)
  1890. {
  1891. waitForProbe.Set ();
  1892. if (CheckTimers (wait, out var waitTimeout)) {
  1893. return true;
  1894. }
  1895. try {
  1896. if (!tokenSource.IsCancellationRequested) {
  1897. keyReady.Wait (waitTimeout, tokenSource.Token);
  1898. }
  1899. } catch (OperationCanceledException) {
  1900. return true;
  1901. } finally {
  1902. keyReady.Reset ();
  1903. }
  1904. if (!tokenSource.IsCancellationRequested) {
  1905. return inputResult.Count > 0 || CheckTimers (wait, out _);
  1906. }
  1907. tokenSource.Dispose ();
  1908. tokenSource = new CancellationTokenSource ();
  1909. return true;
  1910. }
  1911. bool CheckTimers (bool wait, out int waitTimeout)
  1912. {
  1913. long now = DateTime.UtcNow.Ticks;
  1914. if (mainLoop.timeouts.Count > 0) {
  1915. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1916. if (waitTimeout < 0)
  1917. return true;
  1918. } else {
  1919. waitTimeout = -1;
  1920. }
  1921. if (!wait)
  1922. waitTimeout = 0;
  1923. int ic;
  1924. lock (mainLoop.idleHandlers) {
  1925. ic = mainLoop.idleHandlers.Count;
  1926. }
  1927. return ic > 0;
  1928. }
  1929. void IMainLoopDriver.MainIteration ()
  1930. {
  1931. while (inputResult.Count > 0) {
  1932. ProcessInput?.Invoke (inputResult.Dequeue ().Value);
  1933. }
  1934. }
  1935. }
  1936. }