WindowsDriver.cs 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757
  1. //
  2. // WindowsDriver.cs: Windows specific driver
  3. //
  4. // HACK:
  5. // WindowsConsole/Terminal has two issues:
  6. // 1) Tearing can occur when the console is resized.
  7. // 2) The values provided during Init (and the first WindowsConsole.EventType.WindowBufferSize) are not correct.
  8. //
  9. // If HACK_CHECK_WINCHANGED is defined then we ignore WindowsConsole.EventType.WindowBufferSize events
  10. // and instead check the console size every 500ms in a thread in WidowsMainLoop.
  11. // As of Windows 11 23H2 25947.1000 and/or WT 1.19.2682 tearing no longer occurs when using
  12. // the WindowsConsole.EventType.WindowBufferSize event. However, on Init the window size is
  13. // still incorrect so we still need this hack.
  14. //#define HACK_CHECK_WINCHANGED
  15. using System.Collections.Concurrent;
  16. using System.ComponentModel;
  17. using System.Diagnostics;
  18. using System.Runtime.InteropServices;
  19. using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping;
  20. namespace Terminal.Gui;
  21. internal class WindowsConsole
  22. {
  23. internal WindowsMainLoop _mainLoop;
  24. public const int STD_OUTPUT_HANDLE = -11;
  25. public const int STD_INPUT_HANDLE = -10;
  26. private readonly nint _inputHandle;
  27. private nint _outputHandle;
  28. private nint _screenBuffer;
  29. private readonly uint _originalConsoleMode;
  30. private CursorVisibility? _initialCursorVisibility;
  31. private CursorVisibility? _currentCursorVisibility;
  32. private CursorVisibility? _pendingCursorVisibility;
  33. private readonly StringBuilder _stringBuilder = new (256 * 1024);
  34. private string _lastWrite = string.Empty;
  35. public WindowsConsole ()
  36. {
  37. _inputHandle = GetStdHandle (STD_INPUT_HANDLE);
  38. _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  39. _originalConsoleMode = ConsoleMode;
  40. uint newConsoleMode = _originalConsoleMode;
  41. newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
  42. newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
  43. newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput;
  44. ConsoleMode = newConsoleMode;
  45. }
  46. private CharInfo [] _originalStdOutChars;
  47. public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord bufferSize, SmallRect window, bool force16Colors)
  48. {
  49. //Debug.WriteLine ("WriteToConsole");
  50. if (_screenBuffer == nint.Zero)
  51. {
  52. ReadFromConsoleOutput (size, bufferSize, ref window);
  53. }
  54. var result = false;
  55. if (force16Colors)
  56. {
  57. var i = 0;
  58. CharInfo [] ci = new CharInfo [charInfoBuffer.Length];
  59. foreach (ExtendedCharInfo info in charInfoBuffer)
  60. {
  61. ci [i++] = new CharInfo
  62. {
  63. Char = new CharUnion { UnicodeChar = info.Char },
  64. Attributes =
  65. (ushort)((int)info.Attribute.Foreground.GetClosestNamedColor16 () | ((int)info.Attribute.Background.GetClosestNamedColor16 () << 4))
  66. };
  67. }
  68. result = WriteConsoleOutput (_screenBuffer, ci, bufferSize, new Coord { X = window.Left, Y = window.Top }, ref window);
  69. }
  70. else
  71. {
  72. _stringBuilder.Clear ();
  73. _stringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition);
  74. _stringBuilder.Append (EscSeqUtils.CSI_SetCursorPosition (0, 0));
  75. Attribute? prev = null;
  76. foreach (ExtendedCharInfo info in charInfoBuffer)
  77. {
  78. Attribute attr = info.Attribute;
  79. if (attr != prev)
  80. {
  81. prev = attr;
  82. _stringBuilder.Append (EscSeqUtils.CSI_SetForegroundColorRGB (attr.Foreground.R, attr.Foreground.G, attr.Foreground.B));
  83. _stringBuilder.Append (EscSeqUtils.CSI_SetBackgroundColorRGB (attr.Background.R, attr.Background.G, attr.Background.B));
  84. }
  85. if (info.Char != '\x1b')
  86. {
  87. if (!info.Empty)
  88. {
  89. _stringBuilder.Append (info.Char);
  90. }
  91. }
  92. else
  93. {
  94. _stringBuilder.Append (' ');
  95. }
  96. }
  97. _stringBuilder.Append (EscSeqUtils.CSI_RestoreCursorPosition);
  98. _stringBuilder.Append (EscSeqUtils.CSI_HideCursor);
  99. var s = _stringBuilder.ToString ();
  100. // TODO: requires extensive testing if we go down this route
  101. // If console output has changed
  102. if (s != _lastWrite)
  103. {
  104. // supply console with the new content
  105. result = WriteConsole (_screenBuffer, s, (uint)s.Length, out uint _, nint.Zero);
  106. }
  107. _lastWrite = s;
  108. foreach (var sixel in Application.Sixel)
  109. {
  110. SetCursorPosition (new Coord ((short)sixel.ScreenPosition.X, (short)sixel.ScreenPosition.Y));
  111. WriteConsole (_screenBuffer, sixel.SixelData, (uint)sixel.SixelData.Length, out uint _, nint.Zero);
  112. }
  113. }
  114. if (!result)
  115. {
  116. int err = Marshal.GetLastWin32Error ();
  117. if (err != 0)
  118. {
  119. throw new Win32Exception (err);
  120. }
  121. }
  122. return result;
  123. }
  124. internal bool WriteANSI (string ansi)
  125. {
  126. if (WriteConsole (_screenBuffer, ansi, (uint)ansi.Length, out uint _, nint.Zero))
  127. {
  128. // Flush the output to make sure it's sent immediately
  129. return FlushFileBuffers (_screenBuffer);
  130. }
  131. return false;
  132. }
  133. public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window)
  134. {
  135. _screenBuffer = CreateConsoleScreenBuffer (
  136. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  137. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  138. nint.Zero,
  139. 1,
  140. nint.Zero
  141. );
  142. if (_screenBuffer == INVALID_HANDLE_VALUE)
  143. {
  144. int err = Marshal.GetLastWin32Error ();
  145. if (err != 0)
  146. {
  147. throw new Win32Exception (err);
  148. }
  149. }
  150. SetInitialCursorVisibility ();
  151. if (!SetConsoleActiveScreenBuffer (_screenBuffer))
  152. {
  153. throw new Win32Exception (Marshal.GetLastWin32Error ());
  154. }
  155. _originalStdOutChars = new CharInfo [size.Height * size.Width];
  156. if (!ReadConsoleOutput (_screenBuffer, _originalStdOutChars, coords, new Coord { X = 0, Y = 0 }, ref window))
  157. {
  158. throw new Win32Exception (Marshal.GetLastWin32Error ());
  159. }
  160. }
  161. public bool SetCursorPosition (Coord position)
  162. {
  163. return SetConsoleCursorPosition (_screenBuffer, position);
  164. }
  165. public void SetInitialCursorVisibility ()
  166. {
  167. if (_initialCursorVisibility.HasValue == false && GetCursorVisibility (out CursorVisibility visibility))
  168. {
  169. _initialCursorVisibility = visibility;
  170. }
  171. }
  172. public bool GetCursorVisibility (out CursorVisibility visibility)
  173. {
  174. if (_screenBuffer == nint.Zero)
  175. {
  176. visibility = CursorVisibility.Invisible;
  177. return false;
  178. }
  179. if (!GetConsoleCursorInfo (_screenBuffer, out ConsoleCursorInfo info))
  180. {
  181. int err = Marshal.GetLastWin32Error ();
  182. if (err != 0)
  183. {
  184. throw new Win32Exception (err);
  185. }
  186. visibility = CursorVisibility.Default;
  187. return false;
  188. }
  189. if (!info.bVisible)
  190. {
  191. visibility = CursorVisibility.Invisible;
  192. }
  193. else if (info.dwSize > 50)
  194. {
  195. visibility = CursorVisibility.Default;
  196. }
  197. else
  198. {
  199. visibility = CursorVisibility.Default;
  200. }
  201. return true;
  202. }
  203. public bool EnsureCursorVisibility ()
  204. {
  205. if (_initialCursorVisibility.HasValue && _pendingCursorVisibility.HasValue && SetCursorVisibility (_pendingCursorVisibility.Value))
  206. {
  207. _pendingCursorVisibility = null;
  208. return true;
  209. }
  210. return false;
  211. }
  212. public void ForceRefreshCursorVisibility ()
  213. {
  214. if (_currentCursorVisibility.HasValue)
  215. {
  216. _pendingCursorVisibility = _currentCursorVisibility;
  217. _currentCursorVisibility = null;
  218. }
  219. }
  220. public bool SetCursorVisibility (CursorVisibility visibility)
  221. {
  222. if (_initialCursorVisibility.HasValue == false)
  223. {
  224. _pendingCursorVisibility = visibility;
  225. return false;
  226. }
  227. if (_currentCursorVisibility.HasValue == false || _currentCursorVisibility.Value != visibility)
  228. {
  229. var info = new ConsoleCursorInfo
  230. {
  231. dwSize = (uint)visibility & 0x00FF,
  232. bVisible = ((uint)visibility & 0xFF00) != 0
  233. };
  234. if (!SetConsoleCursorInfo (_screenBuffer, ref info))
  235. {
  236. return false;
  237. }
  238. _currentCursorVisibility = visibility;
  239. }
  240. return true;
  241. }
  242. public void Cleanup ()
  243. {
  244. if (_initialCursorVisibility.HasValue)
  245. {
  246. SetCursorVisibility (_initialCursorVisibility.Value);
  247. }
  248. SetConsoleOutputWindow (out _);
  249. ConsoleMode = _originalConsoleMode;
  250. _outputHandle = CreateConsoleScreenBuffer (
  251. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  252. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  253. nint.Zero,
  254. 1,
  255. nint.Zero
  256. );
  257. if (!SetConsoleActiveScreenBuffer (_outputHandle))
  258. {
  259. int err = Marshal.GetLastWin32Error ();
  260. Console.WriteLine ("Error: {0}", err);
  261. }
  262. if (_screenBuffer != nint.Zero)
  263. {
  264. CloseHandle (_screenBuffer);
  265. }
  266. _screenBuffer = nint.Zero;
  267. }
  268. internal Size GetConsoleBufferWindow (out Point position)
  269. {
  270. if (_screenBuffer == nint.Zero)
  271. {
  272. position = Point.Empty;
  273. return Size.Empty;
  274. }
  275. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  276. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  277. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  278. {
  279. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  280. position = Point.Empty;
  281. return Size.Empty;
  282. }
  283. Size sz = new (
  284. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  285. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  286. position = new (csbi.srWindow.Left, csbi.srWindow.Top);
  287. return sz;
  288. }
  289. internal Size GetConsoleOutputWindow (out Point position)
  290. {
  291. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  292. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  293. if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi))
  294. {
  295. throw new Win32Exception (Marshal.GetLastWin32Error ());
  296. }
  297. Size sz = new (
  298. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  299. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  300. position = new (csbi.srWindow.Left, csbi.srWindow.Top);
  301. return sz;
  302. }
  303. internal Size SetConsoleWindow (short cols, short rows)
  304. {
  305. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  306. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  307. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  308. {
  309. throw new Win32Exception (Marshal.GetLastWin32Error ());
  310. }
  311. Coord maxWinSize = GetLargestConsoleWindowSize (_screenBuffer);
  312. short newCols = Math.Min (cols, maxWinSize.X);
  313. short newRows = Math.Min (rows, maxWinSize.Y);
  314. csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1));
  315. csbi.srWindow = new SmallRect (0, 0, newCols, newRows);
  316. csbi.dwMaximumWindowSize = new Coord (newCols, newRows);
  317. if (!SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  318. {
  319. throw new Win32Exception (Marshal.GetLastWin32Error ());
  320. }
  321. var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0));
  322. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect))
  323. {
  324. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  325. return new (cols, rows);
  326. }
  327. SetConsoleOutputWindow (csbi);
  328. return new (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1);
  329. }
  330. private void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi)
  331. {
  332. if (_screenBuffer != nint.Zero && !SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  333. {
  334. throw new Win32Exception (Marshal.GetLastWin32Error ());
  335. }
  336. }
  337. internal Size SetConsoleOutputWindow (out Point position)
  338. {
  339. if (_screenBuffer == nint.Zero)
  340. {
  341. position = Point.Empty;
  342. return Size.Empty;
  343. }
  344. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  345. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  346. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  347. {
  348. throw new Win32Exception (Marshal.GetLastWin32Error ());
  349. }
  350. Size sz = new (
  351. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  352. Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0));
  353. position = new (csbi.srWindow.Left, csbi.srWindow.Top);
  354. SetConsoleOutputWindow (csbi);
  355. var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0));
  356. if (!SetConsoleScreenBufferInfoEx (_outputHandle, ref csbi))
  357. {
  358. throw new Win32Exception (Marshal.GetLastWin32Error ());
  359. }
  360. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect))
  361. {
  362. throw new Win32Exception (Marshal.GetLastWin32Error ());
  363. }
  364. return sz;
  365. }
  366. private uint ConsoleMode
  367. {
  368. get
  369. {
  370. GetConsoleMode (_inputHandle, out uint v);
  371. return v;
  372. }
  373. set => SetConsoleMode (_inputHandle, value);
  374. }
  375. [Flags]
  376. public enum ConsoleModes : uint
  377. {
  378. EnableProcessedInput = 1,
  379. EnableMouseInput = 16,
  380. EnableQuickEditMode = 64,
  381. EnableExtendedFlags = 128
  382. }
  383. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  384. public struct KeyEventRecord
  385. {
  386. [FieldOffset (0)]
  387. [MarshalAs (UnmanagedType.Bool)]
  388. public bool bKeyDown;
  389. [FieldOffset (4)]
  390. [MarshalAs (UnmanagedType.U2)]
  391. public ushort wRepeatCount;
  392. [FieldOffset (6)]
  393. [MarshalAs (UnmanagedType.U2)]
  394. public VK wVirtualKeyCode;
  395. [FieldOffset (8)]
  396. [MarshalAs (UnmanagedType.U2)]
  397. public ushort wVirtualScanCode;
  398. [FieldOffset (10)]
  399. public char UnicodeChar;
  400. [FieldOffset (12)]
  401. [MarshalAs (UnmanagedType.U4)]
  402. public ControlKeyState dwControlKeyState;
  403. public readonly override string ToString ()
  404. {
  405. return
  406. $"[KeyEventRecord({(bKeyDown ? "down" : "up")},{wRepeatCount},{wVirtualKeyCode},{wVirtualScanCode},{new Rune (UnicodeChar).MakePrintable ()},{dwControlKeyState})]";
  407. }
  408. }
  409. [Flags]
  410. public enum ButtonState
  411. {
  412. NoButtonPressed = 0,
  413. Button1Pressed = 1,
  414. Button2Pressed = 4,
  415. Button3Pressed = 8,
  416. Button4Pressed = 16,
  417. RightmostButtonPressed = 2
  418. }
  419. [Flags]
  420. public enum ControlKeyState
  421. {
  422. NoControlKeyPressed = 0,
  423. RightAltPressed = 1,
  424. LeftAltPressed = 2,
  425. RightControlPressed = 4,
  426. LeftControlPressed = 8,
  427. ShiftPressed = 16,
  428. NumlockOn = 32,
  429. ScrolllockOn = 64,
  430. CapslockOn = 128,
  431. EnhancedKey = 256
  432. }
  433. [Flags]
  434. public enum EventFlags
  435. {
  436. NoEvent = 0,
  437. MouseMoved = 1,
  438. DoubleClick = 2,
  439. MouseWheeled = 4,
  440. MouseHorizontalWheeled = 8
  441. }
  442. [StructLayout (LayoutKind.Explicit)]
  443. public struct MouseEventRecord
  444. {
  445. [FieldOffset (0)]
  446. public Coord MousePosition;
  447. [FieldOffset (4)]
  448. public ButtonState ButtonState;
  449. [FieldOffset (8)]
  450. public ControlKeyState ControlKeyState;
  451. [FieldOffset (12)]
  452. public EventFlags EventFlags;
  453. public readonly override string ToString () { return $"[Mouse{MousePosition},{ButtonState},{ControlKeyState},{EventFlags}]"; }
  454. }
  455. public struct WindowBufferSizeRecord
  456. {
  457. public Coord _size;
  458. public WindowBufferSizeRecord (short x, short y) { _size = new Coord (x, y); }
  459. public readonly override string ToString () { return $"[WindowBufferSize{_size}"; }
  460. }
  461. [StructLayout (LayoutKind.Sequential)]
  462. public struct MenuEventRecord
  463. {
  464. public uint dwCommandId;
  465. }
  466. [StructLayout (LayoutKind.Sequential)]
  467. public struct FocusEventRecord
  468. {
  469. public uint bSetFocus;
  470. }
  471. public enum EventType : ushort
  472. {
  473. Focus = 0x10,
  474. Key = 0x1,
  475. Menu = 0x8,
  476. Mouse = 2,
  477. WindowBufferSize = 4
  478. }
  479. [StructLayout (LayoutKind.Explicit)]
  480. public struct InputRecord
  481. {
  482. [FieldOffset (0)]
  483. public EventType EventType;
  484. [FieldOffset (4)]
  485. public KeyEventRecord KeyEvent;
  486. [FieldOffset (4)]
  487. public MouseEventRecord MouseEvent;
  488. [FieldOffset (4)]
  489. public WindowBufferSizeRecord WindowBufferSizeEvent;
  490. [FieldOffset (4)]
  491. public MenuEventRecord MenuEvent;
  492. [FieldOffset (4)]
  493. public FocusEventRecord FocusEvent;
  494. public readonly override string ToString ()
  495. {
  496. return EventType switch
  497. {
  498. EventType.Focus => FocusEvent.ToString (),
  499. EventType.Key => KeyEvent.ToString (),
  500. EventType.Menu => MenuEvent.ToString (),
  501. EventType.Mouse => MouseEvent.ToString (),
  502. EventType.WindowBufferSize => WindowBufferSizeEvent.ToString (),
  503. _ => "Unknown event type: " + EventType
  504. };
  505. }
  506. }
  507. [Flags]
  508. private enum ShareMode : uint
  509. {
  510. FileShareRead = 1,
  511. FileShareWrite = 2
  512. }
  513. [Flags]
  514. private enum DesiredAccess : uint
  515. {
  516. GenericRead = 2147483648,
  517. GenericWrite = 1073741824
  518. }
  519. [StructLayout (LayoutKind.Sequential)]
  520. public struct ConsoleScreenBufferInfo
  521. {
  522. public Coord dwSize;
  523. public Coord dwCursorPosition;
  524. public ushort wAttributes;
  525. public SmallRect srWindow;
  526. public Coord dwMaximumWindowSize;
  527. }
  528. [StructLayout (LayoutKind.Sequential)]
  529. public struct Coord
  530. {
  531. public short X;
  532. public short Y;
  533. public Coord (short x, short y)
  534. {
  535. X = x;
  536. Y = y;
  537. }
  538. public readonly override string ToString () { return $"({X},{Y})"; }
  539. }
  540. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  541. public struct CharUnion
  542. {
  543. [FieldOffset (0)]
  544. public char UnicodeChar;
  545. [FieldOffset (0)]
  546. public byte AsciiChar;
  547. }
  548. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  549. public struct CharInfo
  550. {
  551. [FieldOffset (0)]
  552. public CharUnion Char;
  553. [FieldOffset (2)]
  554. public ushort Attributes;
  555. }
  556. public struct ExtendedCharInfo
  557. {
  558. public char Char { get; set; }
  559. public Attribute Attribute { get; set; }
  560. public bool Empty { get; set; } // TODO: Temp hack until virtual terminal sequences
  561. public ExtendedCharInfo (char character, Attribute attribute)
  562. {
  563. Char = character;
  564. Attribute = attribute;
  565. Empty = false;
  566. }
  567. }
  568. [StructLayout (LayoutKind.Sequential)]
  569. public struct SmallRect
  570. {
  571. public short Left;
  572. public short Top;
  573. public short Right;
  574. public short Bottom;
  575. public SmallRect (short left, short top, short right, short bottom)
  576. {
  577. Left = left;
  578. Top = top;
  579. Right = right;
  580. Bottom = bottom;
  581. }
  582. public static void MakeEmpty (ref SmallRect rect) { rect.Left = -1; }
  583. public static void Update (ref SmallRect rect, short col, short row)
  584. {
  585. if (rect.Left == -1)
  586. {
  587. rect.Left = rect.Right = col;
  588. rect.Bottom = rect.Top = row;
  589. return;
  590. }
  591. if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
  592. {
  593. return;
  594. }
  595. if (col < rect.Left)
  596. {
  597. rect.Left = col;
  598. }
  599. if (col > rect.Right)
  600. {
  601. rect.Right = col;
  602. }
  603. if (row < rect.Top)
  604. {
  605. rect.Top = row;
  606. }
  607. if (row > rect.Bottom)
  608. {
  609. rect.Bottom = row;
  610. }
  611. }
  612. public readonly override string ToString () { return $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}"; }
  613. }
  614. [StructLayout (LayoutKind.Sequential)]
  615. public struct ConsoleKeyInfoEx
  616. {
  617. public ConsoleKeyInfo ConsoleKeyInfo;
  618. public bool CapsLock;
  619. public bool NumLock;
  620. public bool ScrollLock;
  621. public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock, bool scrolllock)
  622. {
  623. ConsoleKeyInfo = consoleKeyInfo;
  624. CapsLock = capslock;
  625. NumLock = numlock;
  626. ScrollLock = scrolllock;
  627. }
  628. /// <summary>
  629. /// Prints a ConsoleKeyInfoEx structure
  630. /// </summary>
  631. /// <param name="ex"></param>
  632. /// <returns></returns>
  633. public readonly string ToString (ConsoleKeyInfoEx ex)
  634. {
  635. var ke = new Key ((KeyCode)ex.ConsoleKeyInfo.KeyChar);
  636. var sb = new StringBuilder ();
  637. sb.Append ($"Key: {(KeyCode)ex.ConsoleKeyInfo.Key} ({ex.ConsoleKeyInfo.Key})");
  638. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty);
  639. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty);
  640. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty);
  641. sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)ex.ConsoleKeyInfo.KeyChar}) ");
  642. sb.Append (ex.CapsLock ? "caps," : string.Empty);
  643. sb.Append (ex.NumLock ? "num," : string.Empty);
  644. sb.Append (ex.ScrollLock ? "scroll," : string.Empty);
  645. string s = sb.ToString ().TrimEnd (',').TrimEnd (' ');
  646. return $"[ConsoleKeyInfoEx({s})]";
  647. }
  648. }
  649. [DllImport ("kernel32.dll", SetLastError = true)]
  650. private static extern nint GetStdHandle (int nStdHandle);
  651. [DllImport ("kernel32.dll", SetLastError = true)]
  652. private static extern bool CloseHandle (nint handle);
  653. [DllImport ("kernel32.dll", SetLastError = true)]
  654. public static extern bool PeekConsoleInput (nint hConsoleInput, out InputRecord lpBuffer, uint nLength, out uint lpNumberOfEventsRead);
  655. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  656. public static extern bool ReadConsoleInput (
  657. nint hConsoleInput,
  658. out InputRecord lpBuffer,
  659. uint nLength,
  660. out uint lpNumberOfEventsRead
  661. );
  662. [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  663. private static extern bool ReadConsoleOutput (
  664. nint hConsoleOutput,
  665. [Out] CharInfo [] lpBuffer,
  666. Coord dwBufferSize,
  667. Coord dwBufferCoord,
  668. ref SmallRect lpReadRegion
  669. );
  670. // TODO: This API is obsolete. See https://learn.microsoft.com/en-us/windows/console/writeconsoleoutput
  671. [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutputW", SetLastError = true, CharSet = CharSet.Unicode)]
  672. private static extern bool WriteConsoleOutput (
  673. nint hConsoleOutput,
  674. CharInfo [] lpBuffer,
  675. Coord dwBufferSize,
  676. Coord dwBufferCoord,
  677. ref SmallRect lpWriteRegion
  678. );
  679. [DllImport ("kernel32.dll", EntryPoint = "WriteConsole", SetLastError = true, CharSet = CharSet.Unicode)]
  680. private static extern bool WriteConsole (
  681. nint hConsoleOutput,
  682. string lpbufer,
  683. uint NumberOfCharsToWriten,
  684. out uint lpNumberOfCharsWritten,
  685. nint lpReserved
  686. );
  687. [DllImport ("kernel32.dll", SetLastError = true)]
  688. static extern bool FlushFileBuffers (nint hFile);
  689. [DllImport ("kernel32.dll")]
  690. private static extern bool SetConsoleCursorPosition (nint hConsoleOutput, Coord dwCursorPosition);
  691. [StructLayout (LayoutKind.Sequential)]
  692. public struct ConsoleCursorInfo
  693. {
  694. /// <summary>
  695. /// The percentage of the character cell that is filled by the cursor.This value is between 1 and 100.
  696. /// The cursor appearance varies, ranging from completely filling the cell to showing up as a horizontal
  697. /// line at the bottom of the cell.
  698. /// </summary>
  699. public uint dwSize;
  700. public bool bVisible;
  701. }
  702. [DllImport ("kernel32.dll", SetLastError = true)]
  703. private static extern bool SetConsoleCursorInfo (nint hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
  704. [DllImport ("kernel32.dll", SetLastError = true)]
  705. private static extern bool GetConsoleCursorInfo (nint hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
  706. [DllImport ("kernel32.dll")]
  707. private static extern bool GetConsoleMode (nint hConsoleHandle, out uint lpMode);
  708. [DllImport ("kernel32.dll")]
  709. private static extern bool SetConsoleMode (nint hConsoleHandle, uint dwMode);
  710. [DllImport ("kernel32.dll", SetLastError = true)]
  711. private static extern nint CreateConsoleScreenBuffer (
  712. DesiredAccess dwDesiredAccess,
  713. ShareMode dwShareMode,
  714. nint secutiryAttributes,
  715. uint flags,
  716. nint screenBufferData
  717. );
  718. internal static nint INVALID_HANDLE_VALUE = new (-1);
  719. [DllImport ("kernel32.dll", SetLastError = true)]
  720. private static extern bool SetConsoleActiveScreenBuffer (nint Handle);
  721. [DllImport ("kernel32.dll", SetLastError = true)]
  722. private static extern bool GetNumberOfConsoleInputEvents (nint handle, out uint lpcNumberOfEvents);
  723. internal uint GetNumberOfConsoleInputEvents ()
  724. {
  725. if (!GetNumberOfConsoleInputEvents (_inputHandle, out uint numOfEvents))
  726. {
  727. Console.WriteLine ($"Error: {Marshal.GetLastWin32Error ()}");
  728. return 0;
  729. }
  730. return numOfEvents;
  731. }
  732. [DllImport ("kernel32.dll", SetLastError = true)]
  733. private static extern bool FlushConsoleInputBuffer (nint handle);
  734. internal void FlushConsoleInputBuffer ()
  735. {
  736. if (!FlushConsoleInputBuffer (_inputHandle))
  737. {
  738. Console.WriteLine ($"Error: {Marshal.GetLastWin32Error ()}");
  739. }
  740. }
  741. private int _retries;
  742. public InputRecord [] ReadConsoleInput ()
  743. {
  744. const int bufferSize = 1;
  745. InputRecord inputRecord = default;
  746. uint numberEventsRead = 0;
  747. StringBuilder ansiSequence = new StringBuilder ();
  748. bool readingSequence = false;
  749. bool raisedResponse = false;
  750. while (true)
  751. {
  752. try
  753. {
  754. // Peek to check if there is any input available
  755. if (PeekConsoleInput (_inputHandle, out _, bufferSize, out uint eventsRead) && eventsRead > 0)
  756. {
  757. // Read the input since it is available
  758. ReadConsoleInput (
  759. _inputHandle,
  760. out inputRecord,
  761. bufferSize,
  762. out numberEventsRead);
  763. if (inputRecord.EventType == EventType.Key)
  764. {
  765. KeyEventRecord keyEvent = inputRecord.KeyEvent;
  766. if (keyEvent.bKeyDown)
  767. {
  768. char inputChar = keyEvent.UnicodeChar;
  769. // Check if input is part of an ANSI escape sequence
  770. if (inputChar == '\u001B') // Escape character
  771. {
  772. // Peek to check if there is any input available with key event and bKeyDown
  773. if (PeekConsoleInput (_inputHandle, out InputRecord peekRecord, bufferSize, out eventsRead) && eventsRead > 0)
  774. {
  775. if (peekRecord is { EventType: EventType.Key, KeyEvent.bKeyDown: true })
  776. {
  777. // It's really an ANSI request response
  778. readingSequence = true;
  779. ansiSequence.Clear (); // Start a new sequence
  780. ansiSequence.Append (inputChar);
  781. continue;
  782. }
  783. }
  784. }
  785. else if (readingSequence)
  786. {
  787. ansiSequence.Append (inputChar);
  788. // Check if the sequence has ended with an expected command terminator
  789. if (_mainLoop.EscSeqRequests is { } && _mainLoop.EscSeqRequests.HasResponse (inputChar.ToString (), out EscSeqReqStatus seqReqStatus))
  790. {
  791. // Finished reading the sequence and remove the enqueued request
  792. _mainLoop.EscSeqRequests.Remove (seqReqStatus);
  793. lock (seqReqStatus!.AnsiRequest._responseLock)
  794. {
  795. raisedResponse = true;
  796. seqReqStatus.AnsiRequest.Response = ansiSequence.ToString ();
  797. seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, seqReqStatus.AnsiRequest.Response);
  798. // Clear the terminator for not be enqueued
  799. inputRecord = default (InputRecord);
  800. }
  801. }
  802. continue;
  803. }
  804. }
  805. }
  806. }
  807. if (readingSequence && !raisedResponse && EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 })
  808. {
  809. _mainLoop.EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus);
  810. lock (seqReqStatus!.AnsiRequest._responseLock)
  811. {
  812. seqReqStatus.AnsiRequest.Response = ansiSequence.ToString ();
  813. seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, seqReqStatus.AnsiRequest.Response);
  814. }
  815. _retries = 0;
  816. }
  817. else if (EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 })
  818. {
  819. if (_retries > 1)
  820. {
  821. if (_mainLoop.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response))
  822. {
  823. lock (seqReqStatus!.AnsiRequest._responseLock)
  824. {
  825. _mainLoop.EscSeqRequests.Statuses.TryDequeue (out _);
  826. seqReqStatus.AnsiRequest.Response = string.Empty;
  827. seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty);
  828. }
  829. }
  830. _retries = 0;
  831. }
  832. else
  833. {
  834. _retries++;
  835. }
  836. }
  837. else
  838. {
  839. _retries = 0;
  840. }
  841. return numberEventsRead == 0
  842. ? null
  843. : [inputRecord];
  844. }
  845. catch (Exception)
  846. {
  847. return null;
  848. }
  849. }
  850. }
  851. #if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
  852. [DllImport ("kernel32.dll", ExactSpelling = true)]
  853. static extern IntPtr GetConsoleWindow ();
  854. [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  855. static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
  856. public const int HIDE = 0;
  857. public const int MAXIMIZE = 3;
  858. public const int MINIMIZE = 6;
  859. public const int RESTORE = 9;
  860. internal void ShowWindow (int state)
  861. {
  862. IntPtr thisConsole = GetConsoleWindow ();
  863. ShowWindow (thisConsole, state);
  864. }
  865. #endif
  866. // See: https://github.com/gui-cs/Terminal.Gui/issues/357
  867. [StructLayout (LayoutKind.Sequential)]
  868. public struct CONSOLE_SCREEN_BUFFER_INFOEX
  869. {
  870. public uint cbSize;
  871. public Coord dwSize;
  872. public Coord dwCursorPosition;
  873. public ushort wAttributes;
  874. public SmallRect srWindow;
  875. public Coord dwMaximumWindowSize;
  876. public ushort wPopupAttributes;
  877. public bool bFullscreenSupported;
  878. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)]
  879. public COLORREF [] ColorTable;
  880. }
  881. [StructLayout (LayoutKind.Explicit, Size = 4)]
  882. public struct COLORREF
  883. {
  884. public COLORREF (byte r, byte g, byte b)
  885. {
  886. Value = 0;
  887. R = r;
  888. G = g;
  889. B = b;
  890. }
  891. public COLORREF (uint value)
  892. {
  893. R = 0;
  894. G = 0;
  895. B = 0;
  896. Value = value & 0x00FFFFFF;
  897. }
  898. [FieldOffset (0)]
  899. public byte R;
  900. [FieldOffset (1)]
  901. public byte G;
  902. [FieldOffset (2)]
  903. public byte B;
  904. [FieldOffset (0)]
  905. public uint Value;
  906. }
  907. [DllImport ("kernel32.dll", SetLastError = true)]
  908. private static extern bool GetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  909. [DllImport ("kernel32.dll", SetLastError = true)]
  910. private static extern bool SetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo);
  911. [DllImport ("kernel32.dll", SetLastError = true)]
  912. private static extern bool SetConsoleWindowInfo (
  913. nint hConsoleOutput,
  914. bool bAbsolute,
  915. [In] ref SmallRect lpConsoleWindow
  916. );
  917. [DllImport ("kernel32.dll", SetLastError = true)]
  918. private static extern Coord GetLargestConsoleWindowSize (
  919. nint hConsoleOutput
  920. );
  921. }
  922. internal class WindowsDriver : ConsoleDriver
  923. {
  924. private readonly bool _isWindowsTerminal;
  925. private WindowsConsole.SmallRect _damageRegion;
  926. private bool _isButtonDoubleClicked;
  927. private bool _isButtonPressed;
  928. private bool _isButtonReleased;
  929. private bool _isOneFingerDoubleClicked;
  930. private WindowsConsole.ButtonState? _lastMouseButtonPressed;
  931. private WindowsMainLoop _mainLoopDriver;
  932. private WindowsConsole.ExtendedCharInfo [] _outputBuffer;
  933. private Point? _point;
  934. private Point _pointMove;
  935. private bool _processButtonClick;
  936. public WindowsDriver ()
  937. {
  938. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  939. {
  940. WinConsole = new WindowsConsole ();
  941. // otherwise we're probably running in unit tests
  942. Clipboard = new WindowsClipboard ();
  943. }
  944. else
  945. {
  946. Clipboard = new FakeDriver.FakeClipboard ();
  947. }
  948. // TODO: if some other Windows-based terminal supports true color, update this logic to not
  949. // force 16color mode (.e.g ConEmu which really doesn't work well at all).
  950. _isWindowsTerminal = _isWindowsTerminal =
  951. Environment.GetEnvironmentVariable ("WT_SESSION") is { } || Environment.GetEnvironmentVariable ("VSAPPIDNAME") != null;
  952. if (!_isWindowsTerminal)
  953. {
  954. Force16Colors = true;
  955. }
  956. }
  957. public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931 && _isWindowsTerminal);
  958. public WindowsConsole WinConsole { get; private set; }
  959. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  960. {
  961. if (keyEvent.wVirtualKeyCode != (VK)ConsoleKey.Packet)
  962. {
  963. return keyEvent;
  964. }
  965. var mod = new ConsoleModifiers ();
  966. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  967. {
  968. mod |= ConsoleModifiers.Shift;
  969. }
  970. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  971. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  972. {
  973. mod |= ConsoleModifiers.Alt;
  974. }
  975. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)
  976. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed))
  977. {
  978. mod |= ConsoleModifiers.Control;
  979. }
  980. var cKeyInfo = new ConsoleKeyInfo (
  981. keyEvent.UnicodeChar,
  982. (ConsoleKey)keyEvent.wVirtualKeyCode,
  983. mod.HasFlag (ConsoleModifiers.Shift),
  984. mod.HasFlag (ConsoleModifiers.Alt),
  985. mod.HasFlag (ConsoleModifiers.Control));
  986. cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  987. uint scanCode = GetScanCodeFromConsoleKeyInfo (cKeyInfo);
  988. return new WindowsConsole.KeyEventRecord
  989. {
  990. UnicodeChar = cKeyInfo.KeyChar,
  991. bKeyDown = keyEvent.bKeyDown,
  992. dwControlKeyState = keyEvent.dwControlKeyState,
  993. wRepeatCount = keyEvent.wRepeatCount,
  994. wVirtualKeyCode = (VK)cKeyInfo.Key,
  995. wVirtualScanCode = (ushort)scanCode
  996. };
  997. }
  998. public override bool IsRuneSupported (Rune rune) { return base.IsRuneSupported (rune) && rune.IsBmp; }
  999. public override void Refresh ()
  1000. {
  1001. UpdateScreen ();
  1002. //WinConsole?.SetInitialCursorVisibility ();
  1003. UpdateCursor ();
  1004. }
  1005. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1006. {
  1007. var input = new WindowsConsole.InputRecord
  1008. {
  1009. EventType = WindowsConsole.EventType.Key
  1010. };
  1011. var keyEvent = new WindowsConsole.KeyEventRecord
  1012. {
  1013. bKeyDown = true
  1014. };
  1015. var controlKey = new WindowsConsole.ControlKeyState ();
  1016. if (shift)
  1017. {
  1018. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1019. keyEvent.UnicodeChar = '\0';
  1020. keyEvent.wVirtualKeyCode = VK.SHIFT;
  1021. }
  1022. if (alt)
  1023. {
  1024. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1025. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1026. keyEvent.UnicodeChar = '\0';
  1027. keyEvent.wVirtualKeyCode = VK.MENU;
  1028. }
  1029. if (control)
  1030. {
  1031. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1032. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1033. keyEvent.UnicodeChar = '\0';
  1034. keyEvent.wVirtualKeyCode = VK.CONTROL;
  1035. }
  1036. keyEvent.dwControlKeyState = controlKey;
  1037. input.KeyEvent = keyEvent;
  1038. if (shift || alt || control)
  1039. {
  1040. ProcessInput (input);
  1041. }
  1042. keyEvent.UnicodeChar = keyChar;
  1043. //if ((uint)key < 255) {
  1044. // keyEvent.wVirtualKeyCode = (ushort)key;
  1045. //} else {
  1046. // keyEvent.wVirtualKeyCode = '\0';
  1047. //}
  1048. keyEvent.wVirtualKeyCode = (VK)key;
  1049. input.KeyEvent = keyEvent;
  1050. try
  1051. {
  1052. ProcessInput (input);
  1053. }
  1054. catch (OverflowException)
  1055. { }
  1056. finally
  1057. {
  1058. keyEvent.bKeyDown = false;
  1059. input.KeyEvent = keyEvent;
  1060. ProcessInput (input);
  1061. }
  1062. }
  1063. private readonly ManualResetEventSlim _waitAnsiResponse = new (false);
  1064. private readonly CancellationTokenSource _ansiResponseTokenSource = new ();
  1065. /// <inheritdoc/>
  1066. public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest)
  1067. {
  1068. if (_mainLoopDriver is null)
  1069. {
  1070. return string.Empty;
  1071. }
  1072. var response = string.Empty;
  1073. try
  1074. {
  1075. lock (ansiRequest._responseLock)
  1076. {
  1077. ansiRequest.ResponseFromInput += (s, e) =>
  1078. {
  1079. Debug.Assert (s == ansiRequest);
  1080. ansiRequest.Response = response = e;
  1081. _waitAnsiResponse.Set ();
  1082. };
  1083. _mainLoopDriver.EscSeqRequests.Add (ansiRequest, this);
  1084. _mainLoopDriver._forceRead = true;
  1085. }
  1086. if (!_ansiResponseTokenSource.IsCancellationRequested)
  1087. {
  1088. _mainLoopDriver._waitForProbe.Set ();
  1089. _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token);
  1090. }
  1091. }
  1092. catch (OperationCanceledException)
  1093. {
  1094. return string.Empty;
  1095. }
  1096. finally
  1097. {
  1098. _mainLoopDriver._forceRead = false;
  1099. if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request))
  1100. {
  1101. if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0
  1102. && string.IsNullOrEmpty (request.AnsiRequest.Response))
  1103. {
  1104. // Bad request or no response at all
  1105. _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _);
  1106. }
  1107. }
  1108. _waitAnsiResponse.Reset ();
  1109. }
  1110. return response;
  1111. }
  1112. public override void WriteRaw (string ansi)
  1113. {
  1114. WinConsole?.WriteANSI (ansi);
  1115. }
  1116. #region Not Implemented
  1117. public override void Suspend () { throw new NotImplementedException (); }
  1118. #endregion
  1119. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1120. {
  1121. WindowsConsole.ControlKeyState state = keyEvent.dwControlKeyState;
  1122. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1123. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1124. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1125. bool capslock = (state & WindowsConsole.ControlKeyState.CapslockOn) != 0;
  1126. bool numlock = (state & WindowsConsole.ControlKeyState.NumlockOn) != 0;
  1127. bool scrolllock = (state & WindowsConsole.ControlKeyState.ScrolllockOn) != 0;
  1128. var cki = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1129. return new WindowsConsole.ConsoleKeyInfoEx (cki, capslock, numlock, scrolllock);
  1130. }
  1131. #region Cursor Handling
  1132. private CursorVisibility? _cachedCursorVisibility;
  1133. public override void UpdateCursor ()
  1134. {
  1135. if (Col < 0 || Row < 0 || Col >= Cols || Row >= Rows)
  1136. {
  1137. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1138. _cachedCursorVisibility = cursorVisibility;
  1139. SetCursorVisibility (CursorVisibility.Invisible);
  1140. return;
  1141. }
  1142. var position = new WindowsConsole.Coord
  1143. {
  1144. X = (short)Col,
  1145. Y = (short)Row
  1146. };
  1147. if (Force16Colors)
  1148. {
  1149. WinConsole?.SetCursorPosition (position);
  1150. }
  1151. else
  1152. {
  1153. var sb = new StringBuilder ();
  1154. sb.Append (EscSeqUtils.CSI_SetCursorPosition (position.Y + 1, position.X + 1));
  1155. WinConsole?.WriteANSI (sb.ToString ());
  1156. }
  1157. if (_cachedCursorVisibility is { })
  1158. {
  1159. SetCursorVisibility (_cachedCursorVisibility.Value);
  1160. }
  1161. //EnsureCursorVisibility ();
  1162. }
  1163. /// <inheritdoc/>
  1164. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1165. {
  1166. if (WinConsole is { })
  1167. {
  1168. return WinConsole.GetCursorVisibility (out visibility);
  1169. }
  1170. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  1171. return true;
  1172. }
  1173. /// <inheritdoc/>
  1174. public override bool SetCursorVisibility (CursorVisibility visibility)
  1175. {
  1176. _cachedCursorVisibility = visibility;
  1177. if (Force16Colors)
  1178. {
  1179. return WinConsole is null || WinConsole.SetCursorVisibility (visibility);
  1180. }
  1181. else
  1182. {
  1183. var sb = new StringBuilder ();
  1184. sb.Append (visibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  1185. return WinConsole?.WriteANSI (sb.ToString ()) ?? false;
  1186. }
  1187. }
  1188. /// <inheritdoc/>
  1189. public override bool EnsureCursorVisibility ()
  1190. {
  1191. if (Force16Colors)
  1192. {
  1193. return WinConsole is null || WinConsole.EnsureCursorVisibility ();
  1194. }
  1195. else
  1196. {
  1197. var sb = new StringBuilder ();
  1198. sb.Append (_cachedCursorVisibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  1199. return WinConsole?.WriteANSI (sb.ToString ()) ?? false;
  1200. }
  1201. //if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  1202. //{
  1203. // GetCursorVisibility (out CursorVisibility cursorVisibility);
  1204. // _cachedCursorVisibility = cursorVisibility;
  1205. // SetCursorVisibility (CursorVisibility.Invisible);
  1206. // return false;
  1207. //}
  1208. //SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default);
  1209. //return _cachedCursorVisibility == CursorVisibility.Default;
  1210. }
  1211. #endregion Cursor Handling
  1212. public override void UpdateScreen ()
  1213. {
  1214. Size windowSize = WinConsole?.GetConsoleBufferWindow (out Point _) ?? new Size (Cols, Rows);
  1215. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows))
  1216. {
  1217. return;
  1218. }
  1219. var bufferCoords = new WindowsConsole.Coord
  1220. {
  1221. X = (short)Cols, //Clip.Width,
  1222. Y = (short)Rows, //Clip.Height
  1223. };
  1224. for (var row = 0; row < Rows; row++)
  1225. {
  1226. if (!_dirtyLines [row])
  1227. {
  1228. continue;
  1229. }
  1230. _dirtyLines [row] = false;
  1231. for (var col = 0; col < Cols; col++)
  1232. {
  1233. int position = row * Cols + col;
  1234. _outputBuffer [position].Attribute = Contents [row, col].Attribute.GetValueOrDefault ();
  1235. if (Contents [row, col].IsDirty == false)
  1236. {
  1237. _outputBuffer [position].Empty = true;
  1238. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1239. continue;
  1240. }
  1241. _outputBuffer [position].Empty = false;
  1242. if (Contents [row, col].Rune.IsBmp)
  1243. {
  1244. _outputBuffer [position].Char = (char)Contents [row, col].Rune.Value;
  1245. }
  1246. else
  1247. {
  1248. //_outputBuffer [position].Empty = true;
  1249. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1250. if (Contents [row, col].Rune.GetColumns () > 1 && col + 1 < Cols)
  1251. {
  1252. // TODO: This is a hack to deal with non-BMP and wide characters.
  1253. col++;
  1254. position = row * Cols + col;
  1255. _outputBuffer [position].Empty = false;
  1256. _outputBuffer [position].Char = ' ';
  1257. }
  1258. }
  1259. }
  1260. }
  1261. _damageRegion = new WindowsConsole.SmallRect
  1262. {
  1263. Top = 0,
  1264. Left = 0,
  1265. Bottom = (short)Rows,
  1266. Right = (short)Cols
  1267. };
  1268. if (!RunningUnitTests
  1269. && WinConsole != null
  1270. && !WinConsole.WriteToConsole (new (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors))
  1271. {
  1272. int err = Marshal.GetLastWin32Error ();
  1273. if (err != 0)
  1274. {
  1275. throw new Win32Exception (err);
  1276. }
  1277. }
  1278. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1279. }
  1280. internal override void End ()
  1281. {
  1282. if (_mainLoopDriver is { })
  1283. {
  1284. #if HACK_CHECK_WINCHANGED
  1285. _mainLoopDriver.WinChanged -= ChangeWin;
  1286. #endif
  1287. }
  1288. _mainLoopDriver = null;
  1289. WinConsole?.Cleanup ();
  1290. WinConsole = null;
  1291. if (!RunningUnitTests && _isWindowsTerminal)
  1292. {
  1293. // Disable alternative screen buffer.
  1294. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  1295. }
  1296. }
  1297. internal override MainLoop Init ()
  1298. {
  1299. _mainLoopDriver = new WindowsMainLoop (this);
  1300. if (!RunningUnitTests)
  1301. {
  1302. try
  1303. {
  1304. if (WinConsole is { })
  1305. {
  1306. // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init.
  1307. // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED
  1308. Size winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1309. Cols = winSize.Width;
  1310. Rows = winSize.Height;
  1311. }
  1312. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1313. if (_isWindowsTerminal)
  1314. {
  1315. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  1316. }
  1317. }
  1318. catch (Win32Exception e)
  1319. {
  1320. // We are being run in an environment that does not support a console
  1321. // such as a unit test, or a pipe.
  1322. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  1323. WinConsole = null;
  1324. }
  1325. }
  1326. CurrentAttribute = new Attribute (Color.White, Color.Black);
  1327. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1328. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  1329. Clip = new (0, 0, Cols, Rows);
  1330. _damageRegion = new WindowsConsole.SmallRect
  1331. {
  1332. Top = 0,
  1333. Left = 0,
  1334. Bottom = (short)Rows,
  1335. Right = (short)Cols
  1336. };
  1337. ClearContents ();
  1338. #if HACK_CHECK_WINCHANGED
  1339. _mainLoopDriver.WinChanged = ChangeWin;
  1340. #endif
  1341. WinConsole?.SetInitialCursorVisibility ();
  1342. return new MainLoop (_mainLoopDriver);
  1343. }
  1344. internal void ProcessInput (WindowsConsole.InputRecord inputEvent)
  1345. {
  1346. switch (inputEvent.EventType)
  1347. {
  1348. case WindowsConsole.EventType.Key:
  1349. if (inputEvent.KeyEvent.wVirtualKeyCode == (VK)ConsoleKey.Packet)
  1350. {
  1351. // Used to pass Unicode characters as if they were keystrokes.
  1352. // The VK_PACKET key is the low word of a 32-bit
  1353. // Virtual Key value used for non-keyboard input methods.
  1354. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  1355. }
  1356. WindowsConsole.ConsoleKeyInfoEx keyInfo = ToConsoleKeyInfoEx (inputEvent.KeyEvent);
  1357. //Debug.WriteLine ($"event: KBD: {GetKeyboardLayoutName()} {inputEvent.ToString ()} {keyInfo.ToString (keyInfo)}");
  1358. KeyCode map = MapKey (keyInfo);
  1359. if (map == KeyCode.Null)
  1360. {
  1361. break;
  1362. }
  1363. if (inputEvent.KeyEvent.bKeyDown)
  1364. {
  1365. // Avoid sending repeat key down events
  1366. OnKeyDown (new Key (map));
  1367. }
  1368. else
  1369. {
  1370. OnKeyUp (new Key (map));
  1371. }
  1372. break;
  1373. case WindowsConsole.EventType.Mouse:
  1374. MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent);
  1375. if (me is null || me.Flags == MouseFlags.None)
  1376. {
  1377. break;
  1378. }
  1379. OnMouseEvent (me);
  1380. if (_processButtonClick)
  1381. {
  1382. OnMouseEvent (new ()
  1383. {
  1384. Position = me.Position,
  1385. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  1386. });
  1387. }
  1388. break;
  1389. case WindowsConsole.EventType.Focus:
  1390. break;
  1391. #if !HACK_CHECK_WINCHANGED
  1392. case WindowsConsole.EventType.WindowBufferSize:
  1393. Cols = inputEvent.WindowBufferSizeEvent._size.X;
  1394. Rows = inputEvent.WindowBufferSizeEvent._size.Y;
  1395. ResizeScreen ();
  1396. ClearContents ();
  1397. Application.Top?.SetNeedsLayout ();
  1398. Application.Refresh ();
  1399. break;
  1400. #endif
  1401. }
  1402. }
  1403. #if HACK_CHECK_WINCHANGED
  1404. private void ChangeWin (object s, SizeChangedEventArgs e)
  1405. {
  1406. if (e.Size is null)
  1407. {
  1408. return;
  1409. }
  1410. int w = e.Size.Value.Width;
  1411. if (w == Cols - 3 && e.Size.Value.Height < Rows)
  1412. {
  1413. w += 3;
  1414. }
  1415. Left = 0;
  1416. Top = 0;
  1417. Cols = e.Size.Value.Width;
  1418. Rows = e.Size.Value.Height;
  1419. if (!RunningUnitTests)
  1420. {
  1421. Size newSize = WinConsole.SetConsoleWindow (
  1422. (short)Math.Max (w, 16),
  1423. (short)Math.Max (e.Size.Value.Height, 0));
  1424. Cols = newSize.Width;
  1425. Rows = newSize.Height;
  1426. }
  1427. ResizeScreen ();
  1428. ClearContents ();
  1429. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  1430. }
  1431. #endif
  1432. private KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  1433. {
  1434. ConsoleKeyInfo keyInfo = keyInfoEx.ConsoleKeyInfo;
  1435. switch (keyInfo.Key)
  1436. {
  1437. case ConsoleKey.D0:
  1438. case ConsoleKey.D1:
  1439. case ConsoleKey.D2:
  1440. case ConsoleKey.D3:
  1441. case ConsoleKey.D4:
  1442. case ConsoleKey.D5:
  1443. case ConsoleKey.D6:
  1444. case ConsoleKey.D7:
  1445. case ConsoleKey.D8:
  1446. case ConsoleKey.D9:
  1447. case ConsoleKey.NumPad0:
  1448. case ConsoleKey.NumPad1:
  1449. case ConsoleKey.NumPad2:
  1450. case ConsoleKey.NumPad3:
  1451. case ConsoleKey.NumPad4:
  1452. case ConsoleKey.NumPad5:
  1453. case ConsoleKey.NumPad6:
  1454. case ConsoleKey.NumPad7:
  1455. case ConsoleKey.NumPad8:
  1456. case ConsoleKey.NumPad9:
  1457. case ConsoleKey.Oem1:
  1458. case ConsoleKey.Oem2:
  1459. case ConsoleKey.Oem3:
  1460. case ConsoleKey.Oem4:
  1461. case ConsoleKey.Oem5:
  1462. case ConsoleKey.Oem6:
  1463. case ConsoleKey.Oem7:
  1464. case ConsoleKey.Oem8:
  1465. case ConsoleKey.Oem102:
  1466. case ConsoleKey.Multiply:
  1467. case ConsoleKey.Add:
  1468. case ConsoleKey.Separator:
  1469. case ConsoleKey.Subtract:
  1470. case ConsoleKey.Decimal:
  1471. case ConsoleKey.Divide:
  1472. case ConsoleKey.OemPeriod:
  1473. case ConsoleKey.OemComma:
  1474. case ConsoleKey.OemPlus:
  1475. case ConsoleKey.OemMinus:
  1476. // These virtual key codes are mapped differently depending on the keyboard layout in use.
  1477. // We use the Win32 API to map them to the correct character.
  1478. uint mapResult = MapVKtoChar ((VK)keyInfo.Key);
  1479. if (mapResult == 0)
  1480. {
  1481. // There is no mapping - this should not happen
  1482. Debug.Assert (mapResult != 0, $@"Unable to map the virtual key code {keyInfo.Key}.");
  1483. return KeyCode.Null;
  1484. }
  1485. // An un-shifted character value is in the low order word of the return value.
  1486. var mappedChar = (char)(mapResult & 0x0000FFFF);
  1487. if (keyInfo.KeyChar == 0)
  1488. {
  1489. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  1490. // Dead keys (diacritics) are indicated by setting the top bit of the return value.
  1491. if ((mapResult & 0x80000000) != 0)
  1492. {
  1493. // Dead key (e.g. Oem2 '~'/'^' on POR keyboard)
  1494. // Option 1: Throw it out.
  1495. // - Apps will never see the dead keys
  1496. // - If user presses a key that can be combined with the dead key ('a'), the right thing happens (app will see '�').
  1497. // - NOTE: With Dead Keys, KeyDown != KeyUp. The KeyUp event will have just the base char ('a').
  1498. // - If user presses dead key again, the right thing happens (app will see `~~`)
  1499. // - This is what Notepad etc... appear to do
  1500. // Option 2: Expand the API to indicate the KeyCode is a dead key
  1501. // - Enables apps to do their own dead key processing
  1502. // - Adds complexity; no dev has asked for this (yet).
  1503. // We choose Option 1 for now.
  1504. return KeyCode.Null;
  1505. // Note: Ctrl-Deadkey (like Oem3 '`'/'~` on ENG) can't be supported.
  1506. // Sadly, the charVal is just the deadkey and subsequent key events do not contain
  1507. // any info that the previous event was a deadkey.
  1508. // Note WT does not support Ctrl-Deadkey either.
  1509. }
  1510. if (keyInfo.Modifiers != 0)
  1511. {
  1512. // These Oem keys have well-defined chars. We ensure the representative char is used.
  1513. // If we don't do this, then on some keyboard layouts the wrong char is
  1514. // returned (e.g. on ENG OemPlus un-shifted is =, not +). This is important
  1515. // for key persistence ("Ctrl++" vs. "Ctrl+=").
  1516. mappedChar = keyInfo.Key switch
  1517. {
  1518. ConsoleKey.OemPeriod => '.',
  1519. ConsoleKey.OemComma => ',',
  1520. ConsoleKey.OemPlus => '+',
  1521. ConsoleKey.OemMinus => '-',
  1522. _ => mappedChar
  1523. };
  1524. }
  1525. // Return the mappedChar with modifiers. Because mappedChar is un-shifted, if Shift was down
  1526. // we should keep it
  1527. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  1528. }
  1529. // KeyChar is printable
  1530. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1531. {
  1532. // AltGr support - AltGr is equivalent to Ctrl+Alt - the correct char is in KeyChar
  1533. return (KeyCode)keyInfo.KeyChar;
  1534. }
  1535. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  1536. {
  1537. // If Shift wasn't down we don't need to do anything but return the mappedChar
  1538. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  1539. }
  1540. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "�")
  1541. // and passing on Shift would be redundant.
  1542. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1543. }
  1544. // A..Z are special cased:
  1545. // - Alone, they represent lowercase a...z
  1546. // - With ShiftMask they are A..Z
  1547. // - If CapsLock is on the above is reversed.
  1548. // - If Alt and/or Ctrl are present, treat as upper case
  1549. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z)
  1550. {
  1551. if (keyInfo.KeyChar == 0)
  1552. {
  1553. // KeyChar is not printable - possibly an AltGr key?
  1554. // AltGr support - AltGr is equivalent to Ctrl+Alt
  1555. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1556. {
  1557. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  1558. }
  1559. }
  1560. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1561. {
  1562. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  1563. }
  1564. if ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ keyInfoEx.CapsLock)
  1565. {
  1566. // If (ShiftMask is on and CapsLock is off) or (ShiftMask is off and CapsLock is on) add the ShiftMask
  1567. if (char.IsUpper (keyInfo.KeyChar))
  1568. {
  1569. // Always return the KeyChar because it may be an Á, À with Oem1, etc
  1570. return (KeyCode)keyInfo.KeyChar | KeyCode.ShiftMask;
  1571. }
  1572. }
  1573. // Always return the KeyChar because it may be an á, à with Oem1, etc
  1574. return (KeyCode)keyInfo.KeyChar;
  1575. }
  1576. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  1577. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  1578. {
  1579. // If the key is JUST a modifier, return it as just that key
  1580. if (keyInfo.Key == (ConsoleKey)VK.SHIFT)
  1581. { // Shift 16
  1582. return KeyCode.ShiftMask;
  1583. }
  1584. if (keyInfo.Key == (ConsoleKey)VK.CONTROL)
  1585. { // Ctrl 17
  1586. return KeyCode.CtrlMask;
  1587. }
  1588. if (keyInfo.Key == (ConsoleKey)VK.MENU)
  1589. { // Alt 18
  1590. return KeyCode.AltMask;
  1591. }
  1592. if (keyInfo.KeyChar == 0)
  1593. {
  1594. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1595. }
  1596. if (keyInfo.Key != ConsoleKey.None)
  1597. {
  1598. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1599. }
  1600. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1601. }
  1602. // Handle control keys (e.g. CursorUp)
  1603. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  1604. {
  1605. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  1606. }
  1607. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1608. }
  1609. private MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  1610. {
  1611. MouseFlags mouseFlag = 0;
  1612. switch (_lastMouseButtonPressed)
  1613. {
  1614. case WindowsConsole.ButtonState.Button1Pressed:
  1615. mouseFlag = MouseFlags.Button1Clicked;
  1616. break;
  1617. case WindowsConsole.ButtonState.Button2Pressed:
  1618. mouseFlag = MouseFlags.Button2Clicked;
  1619. break;
  1620. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1621. mouseFlag = MouseFlags.Button3Clicked;
  1622. break;
  1623. }
  1624. _point = new Point
  1625. {
  1626. X = mouseEvent.MousePosition.X,
  1627. Y = mouseEvent.MousePosition.Y
  1628. };
  1629. _lastMouseButtonPressed = null;
  1630. _isButtonReleased = false;
  1631. _processButtonClick = false;
  1632. _point = null;
  1633. return mouseFlag;
  1634. }
  1635. private async Task ProcessButtonDoubleClickedAsync ()
  1636. {
  1637. await Task.Delay (200);
  1638. _isButtonDoubleClicked = false;
  1639. _isOneFingerDoubleClicked = false;
  1640. //buttonPressedCount = 0;
  1641. }
  1642. private async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1643. {
  1644. // When a user presses-and-holds, start generating pressed events every `startDelay`
  1645. // After `iterationsUntilFast` iterations, speed them up to `fastDelay` ms
  1646. const int startDelay = 500;
  1647. const int iterationsUntilFast = 4;
  1648. const int fastDelay = 50;
  1649. int iterations = 0;
  1650. int delay = startDelay;
  1651. while (_isButtonPressed)
  1652. {
  1653. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  1654. View view = Application.WantContinuousButtonPressedView;
  1655. if (view is null)
  1656. {
  1657. break;
  1658. }
  1659. if (iterations++ >= iterationsUntilFast)
  1660. {
  1661. delay = fastDelay;
  1662. }
  1663. await Task.Delay (delay);
  1664. var me = new MouseEventArgs
  1665. {
  1666. ScreenPosition = _pointMove,
  1667. Flags = mouseFlag
  1668. };
  1669. //Debug.WriteLine($"ProcessContinuousButtonPressedAsync: {view}");
  1670. if (_isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0)
  1671. {
  1672. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  1673. Application.Invoke (() => OnMouseEvent (me));
  1674. }
  1675. }
  1676. }
  1677. private void ResizeScreen ()
  1678. {
  1679. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1680. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  1681. Clip = new (0, 0, Cols, Rows);
  1682. _damageRegion = new WindowsConsole.SmallRect
  1683. {
  1684. Top = 0,
  1685. Left = 0,
  1686. Bottom = (short)Rows,
  1687. Right = (short)Cols
  1688. };
  1689. _dirtyLines = new bool [Rows];
  1690. WinConsole?.ForceRefreshCursorVisibility ();
  1691. }
  1692. private static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1693. {
  1694. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)
  1695. || mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  1696. {
  1697. mouseFlag |= MouseFlags.ButtonCtrl;
  1698. }
  1699. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  1700. {
  1701. mouseFlag |= MouseFlags.ButtonShift;
  1702. }
  1703. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  1704. || mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  1705. {
  1706. mouseFlag |= MouseFlags.ButtonAlt;
  1707. }
  1708. return mouseFlag;
  1709. }
  1710. [CanBeNull]
  1711. private MouseEventArgs ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  1712. {
  1713. var mouseFlag = MouseFlags.AllEvents;
  1714. //Debug.WriteLine ($"ToDriverMouse: {mouseEvent}");
  1715. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked)
  1716. {
  1717. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  1718. Application.MainLoop.AddIdle (
  1719. () =>
  1720. {
  1721. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  1722. return false;
  1723. });
  1724. }
  1725. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  1726. // This will tell when a mouse button is pressed. When the button is released this event will
  1727. // be fired with its bit set to 0. So when the button is up ButtonState will be 0.
  1728. // To map to the correct driver events we save the last pressed mouse button, so we can
  1729. // map to the correct clicked event.
  1730. if ((_lastMouseButtonPressed is { } || _isButtonReleased) && mouseEvent.ButtonState != 0)
  1731. {
  1732. _lastMouseButtonPressed = null;
  1733. //isButtonPressed = false;
  1734. _isButtonReleased = false;
  1735. }
  1736. var p = new Point
  1737. {
  1738. X = mouseEvent.MousePosition.X,
  1739. Y = mouseEvent.MousePosition.Y
  1740. };
  1741. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed is null && !_isButtonDoubleClicked)
  1742. || (_lastMouseButtonPressed == null
  1743. && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved)
  1744. && mouseEvent.ButtonState != 0
  1745. && !_isButtonReleased
  1746. && !_isButtonDoubleClicked))
  1747. {
  1748. switch (mouseEvent.ButtonState)
  1749. {
  1750. case WindowsConsole.ButtonState.Button1Pressed:
  1751. mouseFlag = MouseFlags.Button1Pressed;
  1752. break;
  1753. case WindowsConsole.ButtonState.Button2Pressed:
  1754. mouseFlag = MouseFlags.Button2Pressed;
  1755. break;
  1756. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1757. mouseFlag = MouseFlags.Button3Pressed;
  1758. break;
  1759. }
  1760. if (_point is null)
  1761. {
  1762. _point = p;
  1763. }
  1764. if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved))
  1765. {
  1766. _pointMove = p;
  1767. mouseFlag |= MouseFlags.ReportMousePosition;
  1768. _isButtonReleased = false;
  1769. _processButtonClick = false;
  1770. }
  1771. _lastMouseButtonPressed = mouseEvent.ButtonState;
  1772. _isButtonPressed = true;
  1773. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0)
  1774. {
  1775. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  1776. Application.MainLoop.AddIdle (
  1777. () =>
  1778. {
  1779. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  1780. return false;
  1781. });
  1782. }
  1783. }
  1784. else if (_lastMouseButtonPressed != null
  1785. && mouseEvent.EventFlags == 0
  1786. && !_isButtonReleased
  1787. && !_isButtonDoubleClicked
  1788. && !_isOneFingerDoubleClicked)
  1789. {
  1790. switch (_lastMouseButtonPressed)
  1791. {
  1792. case WindowsConsole.ButtonState.Button1Pressed:
  1793. mouseFlag = MouseFlags.Button1Released;
  1794. break;
  1795. case WindowsConsole.ButtonState.Button2Pressed:
  1796. mouseFlag = MouseFlags.Button2Released;
  1797. break;
  1798. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1799. mouseFlag = MouseFlags.Button3Released;
  1800. break;
  1801. }
  1802. _isButtonPressed = false;
  1803. _isButtonReleased = true;
  1804. if (_point is { } && ((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)
  1805. {
  1806. _processButtonClick = true;
  1807. }
  1808. else
  1809. {
  1810. _point = null;
  1811. }
  1812. _processButtonClick = true;
  1813. }
  1814. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  1815. && !_isOneFingerDoubleClicked
  1816. && _isButtonReleased
  1817. && p == _point)
  1818. {
  1819. mouseFlag = ProcessButtonClick (mouseEvent);
  1820. }
  1821. else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick))
  1822. {
  1823. switch (mouseEvent.ButtonState)
  1824. {
  1825. case WindowsConsole.ButtonState.Button1Pressed:
  1826. mouseFlag = MouseFlags.Button1DoubleClicked;
  1827. break;
  1828. case WindowsConsole.ButtonState.Button2Pressed:
  1829. mouseFlag = MouseFlags.Button2DoubleClicked;
  1830. break;
  1831. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1832. mouseFlag = MouseFlags.Button3DoubleClicked;
  1833. break;
  1834. }
  1835. _isButtonDoubleClicked = true;
  1836. }
  1837. else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked)
  1838. {
  1839. switch (mouseEvent.ButtonState)
  1840. {
  1841. case WindowsConsole.ButtonState.Button1Pressed:
  1842. mouseFlag = MouseFlags.Button1TripleClicked;
  1843. break;
  1844. case WindowsConsole.ButtonState.Button2Pressed:
  1845. mouseFlag = MouseFlags.Button2TripleClicked;
  1846. break;
  1847. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1848. mouseFlag = MouseFlags.Button3TripleClicked;
  1849. break;
  1850. }
  1851. _isButtonDoubleClicked = false;
  1852. }
  1853. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled)
  1854. {
  1855. switch ((int)mouseEvent.ButtonState)
  1856. {
  1857. case int v when v > 0:
  1858. mouseFlag = MouseFlags.WheeledUp;
  1859. break;
  1860. case int v when v < 0:
  1861. mouseFlag = MouseFlags.WheeledDown;
  1862. break;
  1863. }
  1864. }
  1865. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled && mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed)
  1866. {
  1867. switch ((int)mouseEvent.ButtonState)
  1868. {
  1869. case int v when v > 0:
  1870. mouseFlag = MouseFlags.WheeledLeft;
  1871. break;
  1872. case int v when v < 0:
  1873. mouseFlag = MouseFlags.WheeledRight;
  1874. break;
  1875. }
  1876. }
  1877. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled)
  1878. {
  1879. switch ((int)mouseEvent.ButtonState)
  1880. {
  1881. case int v when v < 0:
  1882. mouseFlag = MouseFlags.WheeledLeft;
  1883. break;
  1884. case int v when v > 0:
  1885. mouseFlag = MouseFlags.WheeledRight;
  1886. break;
  1887. }
  1888. }
  1889. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved)
  1890. {
  1891. mouseFlag = MouseFlags.ReportMousePosition;
  1892. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y)
  1893. {
  1894. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  1895. }
  1896. }
  1897. else if (mouseEvent is { ButtonState: 0, EventFlags: 0 })
  1898. {
  1899. // This happens on a double or triple click event.
  1900. mouseFlag = MouseFlags.None;
  1901. }
  1902. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  1903. //System.Diagnostics.Debug.WriteLine (
  1904. // $"point.X:{(point is { } ? ((Point)point).X : -1)};point.Y:{(point is { } ? ((Point)point).Y : -1)}");
  1905. return new MouseEventArgs
  1906. {
  1907. Position = new (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y),
  1908. Flags = mouseFlag
  1909. };
  1910. }
  1911. }
  1912. /// <summary>
  1913. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1914. /// only be used on Windows.
  1915. /// </summary>
  1916. /// <remarks>
  1917. /// This implementation is used for WindowsDriver.
  1918. /// </remarks>
  1919. internal class WindowsMainLoop : IMainLoopDriver
  1920. {
  1921. /// <summary>
  1922. /// Invoked when the window is changed.
  1923. /// </summary>
  1924. public EventHandler<SizeChangedEventArgs> WinChanged;
  1925. private readonly ConsoleDriver _consoleDriver;
  1926. private readonly ManualResetEventSlim _eventReady = new (false);
  1927. // The records that we keep fetching
  1928. private readonly ConcurrentQueue<WindowsConsole.InputRecord []> _resultQueue = new ();
  1929. internal readonly ManualResetEventSlim _waitForProbe = new (false);
  1930. private readonly WindowsConsole _winConsole;
  1931. private CancellationTokenSource _eventReadyTokenSource = new ();
  1932. private readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  1933. private MainLoop _mainLoop;
  1934. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1935. {
  1936. _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver));
  1937. if (!ConsoleDriver.RunningUnitTests)
  1938. {
  1939. _winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1940. _winConsole._mainLoop = this;
  1941. }
  1942. }
  1943. public EscSeqRequests EscSeqRequests { get; } = new ();
  1944. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1945. {
  1946. _mainLoop = mainLoop;
  1947. if (ConsoleDriver.RunningUnitTests)
  1948. {
  1949. return;
  1950. }
  1951. Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token);
  1952. #if HACK_CHECK_WINCHANGED
  1953. Task.Run (CheckWinChange);
  1954. #endif
  1955. }
  1956. void IMainLoopDriver.Wakeup () { _eventReady.Set (); }
  1957. bool IMainLoopDriver.EventsPending ()
  1958. {
  1959. _waitForProbe.Set ();
  1960. #if HACK_CHECK_WINCHANGED
  1961. _winChange.Set ();
  1962. #endif
  1963. if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout))
  1964. {
  1965. return true;
  1966. }
  1967. try
  1968. {
  1969. if (!_eventReadyTokenSource.IsCancellationRequested)
  1970. {
  1971. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1972. // are no timers, but there IS an idle handler waiting.
  1973. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1974. }
  1975. }
  1976. catch (OperationCanceledException)
  1977. {
  1978. return true;
  1979. }
  1980. finally
  1981. {
  1982. _eventReady.Reset ();
  1983. }
  1984. if (!_eventReadyTokenSource.IsCancellationRequested)
  1985. {
  1986. #if HACK_CHECK_WINCHANGED
  1987. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  1988. #else
  1989. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1990. #endif
  1991. }
  1992. _eventReadyTokenSource.Dispose ();
  1993. _eventReadyTokenSource = new CancellationTokenSource ();
  1994. return true;
  1995. }
  1996. void IMainLoopDriver.Iteration ()
  1997. {
  1998. while (_resultQueue.Count > 0)
  1999. {
  2000. if (_resultQueue.TryDequeue (out WindowsConsole.InputRecord [] inputRecords))
  2001. {
  2002. if (inputRecords is { Length: > 0 })
  2003. {
  2004. ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords [0]);
  2005. }
  2006. }
  2007. }
  2008. #if HACK_CHECK_WINCHANGED
  2009. if (_winChanged)
  2010. {
  2011. _winChanged = false;
  2012. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  2013. }
  2014. #endif
  2015. }
  2016. void IMainLoopDriver.TearDown ()
  2017. {
  2018. _inputHandlerTokenSource?.Cancel ();
  2019. _inputHandlerTokenSource?.Dispose ();
  2020. if (_winConsole is { })
  2021. {
  2022. var numOfEvents = _winConsole.GetNumberOfConsoleInputEvents ();
  2023. if (numOfEvents > 0)
  2024. {
  2025. _winConsole.FlushConsoleInputBuffer ();
  2026. //Debug.WriteLine ($"Flushed {numOfEvents} events.");
  2027. }
  2028. }
  2029. _waitForProbe?.Dispose ();
  2030. _resultQueue?.Clear ();
  2031. _eventReadyTokenSource?.Cancel ();
  2032. _eventReadyTokenSource?.Dispose ();
  2033. _eventReady?.Dispose ();
  2034. #if HACK_CHECK_WINCHANGED
  2035. _winChange?.Dispose ();
  2036. #endif
  2037. _mainLoop = null;
  2038. }
  2039. internal bool _forceRead;
  2040. private void WindowsInputHandler ()
  2041. {
  2042. while (_mainLoop is { })
  2043. {
  2044. try
  2045. {
  2046. if (!_inputHandlerTokenSource.IsCancellationRequested && !_forceRead)
  2047. {
  2048. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  2049. }
  2050. }
  2051. catch (OperationCanceledException)
  2052. {
  2053. // Wakes the _waitForProbe if it's waiting
  2054. _waitForProbe.Set ();
  2055. return;
  2056. }
  2057. finally
  2058. {
  2059. // If IsCancellationRequested is true the code after
  2060. // the `finally` block will not be executed.
  2061. if (!_inputHandlerTokenSource.IsCancellationRequested)
  2062. {
  2063. _waitForProbe.Reset ();
  2064. }
  2065. }
  2066. if (_resultQueue?.Count == 0 || _forceRead)
  2067. {
  2068. while (!_inputHandlerTokenSource.IsCancellationRequested)
  2069. {
  2070. WindowsConsole.InputRecord [] inpRec = _winConsole.ReadConsoleInput ();
  2071. if (inpRec is { })
  2072. {
  2073. _resultQueue!.Enqueue (inpRec);
  2074. break;
  2075. }
  2076. if (!_forceRead)
  2077. {
  2078. try
  2079. {
  2080. Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token);
  2081. }
  2082. catch (OperationCanceledException)
  2083. { }
  2084. }
  2085. }
  2086. }
  2087. _eventReady.Set ();
  2088. }
  2089. }
  2090. #if HACK_CHECK_WINCHANGED
  2091. private readonly ManualResetEventSlim _winChange = new (false);
  2092. private bool _winChanged;
  2093. private Size _windowSize;
  2094. private void CheckWinChange ()
  2095. {
  2096. while (_mainLoop is { })
  2097. {
  2098. _winChange.Wait ();
  2099. _winChange.Reset ();
  2100. // Check if the window size changed every half second.
  2101. // We do this to minimize the weird tearing seen on Windows when resizing the console
  2102. while (_mainLoop is { })
  2103. {
  2104. Task.Delay (500).Wait ();
  2105. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  2106. if (_windowSize != Size.Empty
  2107. && (_windowSize.Width != _consoleDriver.Cols
  2108. || _windowSize.Height != _consoleDriver.Rows))
  2109. {
  2110. break;
  2111. }
  2112. }
  2113. _winChanged = true;
  2114. _eventReady.Set ();
  2115. }
  2116. }
  2117. #endif
  2118. }
  2119. internal class WindowsClipboard : ClipboardBase
  2120. {
  2121. private const uint CF_UNICODE_TEXT = 13;
  2122. public override bool IsSupported { get; } = CheckClipboardIsAvailable ();
  2123. private static bool CheckClipboardIsAvailable ()
  2124. {
  2125. // Attempt to open the clipboard
  2126. if (OpenClipboard (nint.Zero))
  2127. {
  2128. // Clipboard is available
  2129. // Close the clipboard after use
  2130. CloseClipboard ();
  2131. return true;
  2132. }
  2133. // Clipboard is not available
  2134. return false;
  2135. }
  2136. protected override string GetClipboardDataImpl ()
  2137. {
  2138. try
  2139. {
  2140. if (!OpenClipboard (nint.Zero))
  2141. {
  2142. return string.Empty;
  2143. }
  2144. nint handle = GetClipboardData (CF_UNICODE_TEXT);
  2145. if (handle == nint.Zero)
  2146. {
  2147. return string.Empty;
  2148. }
  2149. nint pointer = nint.Zero;
  2150. try
  2151. {
  2152. pointer = GlobalLock (handle);
  2153. if (pointer == nint.Zero)
  2154. {
  2155. return string.Empty;
  2156. }
  2157. int size = GlobalSize (handle);
  2158. var buff = new byte [size];
  2159. Marshal.Copy (pointer, buff, 0, size);
  2160. return Encoding.Unicode.GetString (buff).TrimEnd ('\0');
  2161. }
  2162. finally
  2163. {
  2164. if (pointer != nint.Zero)
  2165. {
  2166. GlobalUnlock (handle);
  2167. }
  2168. }
  2169. }
  2170. finally
  2171. {
  2172. CloseClipboard ();
  2173. }
  2174. }
  2175. protected override void SetClipboardDataImpl (string text)
  2176. {
  2177. OpenClipboard ();
  2178. EmptyClipboard ();
  2179. nint hGlobal = default;
  2180. try
  2181. {
  2182. int bytes = (text.Length + 1) * 2;
  2183. hGlobal = Marshal.AllocHGlobal (bytes);
  2184. if (hGlobal == default (nint))
  2185. {
  2186. ThrowWin32 ();
  2187. }
  2188. nint target = GlobalLock (hGlobal);
  2189. if (target == default (nint))
  2190. {
  2191. ThrowWin32 ();
  2192. }
  2193. try
  2194. {
  2195. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  2196. }
  2197. finally
  2198. {
  2199. GlobalUnlock (target);
  2200. }
  2201. if (SetClipboardData (CF_UNICODE_TEXT, hGlobal) == default (nint))
  2202. {
  2203. ThrowWin32 ();
  2204. }
  2205. hGlobal = default (nint);
  2206. }
  2207. finally
  2208. {
  2209. if (hGlobal != default (nint))
  2210. {
  2211. Marshal.FreeHGlobal (hGlobal);
  2212. }
  2213. CloseClipboard ();
  2214. }
  2215. }
  2216. [DllImport ("user32.dll", SetLastError = true)]
  2217. [return: MarshalAs (UnmanagedType.Bool)]
  2218. private static extern bool CloseClipboard ();
  2219. [DllImport ("user32.dll")]
  2220. private static extern bool EmptyClipboard ();
  2221. [DllImport ("user32.dll", SetLastError = true)]
  2222. private static extern nint GetClipboardData (uint uFormat);
  2223. [DllImport ("kernel32.dll", SetLastError = true)]
  2224. private static extern nint GlobalLock (nint hMem);
  2225. [DllImport ("kernel32.dll", SetLastError = true)]
  2226. private static extern int GlobalSize (nint handle);
  2227. [DllImport ("kernel32.dll", SetLastError = true)]
  2228. [return: MarshalAs (UnmanagedType.Bool)]
  2229. private static extern bool GlobalUnlock (nint hMem);
  2230. [DllImport ("User32.dll", SetLastError = true)]
  2231. [return: MarshalAs (UnmanagedType.Bool)]
  2232. private static extern bool IsClipboardFormatAvailable (uint format);
  2233. private void OpenClipboard ()
  2234. {
  2235. var num = 10;
  2236. while (true)
  2237. {
  2238. if (OpenClipboard (default (nint)))
  2239. {
  2240. break;
  2241. }
  2242. if (--num == 0)
  2243. {
  2244. ThrowWin32 ();
  2245. }
  2246. Thread.Sleep (100);
  2247. }
  2248. }
  2249. [DllImport ("user32.dll", SetLastError = true)]
  2250. [return: MarshalAs (UnmanagedType.Bool)]
  2251. private static extern bool OpenClipboard (nint hWndNewOwner);
  2252. [DllImport ("user32.dll", SetLastError = true)]
  2253. private static extern nint SetClipboardData (uint uFormat, nint data);
  2254. private void ThrowWin32 () { throw new Win32Exception (Marshal.GetLastWin32Error ()); }
  2255. }