WindowsDriver.cs 80 KB

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