WindowsDriver.cs 81 KB

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