WindowsDriver.cs 81 KB

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