WindowsDriver.cs 80 KB

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