WindowsDriver.cs 88 KB

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