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