WindowsDriver.cs 80 KB

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