WindowsDriver.cs 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100
  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.Text;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.ComponentModel;
  19. using System.Linq;
  20. using System.Runtime.InteropServices;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. using System.Diagnostics;
  24. using System.Management;
  25. namespace Terminal.Gui;
  26. internal class WindowsConsole {
  27. public const int STD_OUTPUT_HANDLE = -11;
  28. public const int STD_INPUT_HANDLE = -10;
  29. IntPtr _inputHandle, _outputHandle;
  30. IntPtr _screenBuffer;
  31. readonly uint _originalConsoleMode;
  32. CursorVisibility? _initialCursorVisibility = null;
  33. CursorVisibility? _currentCursorVisibility = null;
  34. CursorVisibility? _pendingCursorVisibility = null;
  35. readonly StringBuilder _stringBuilder = new StringBuilder (256 * 1024);
  36. public WindowsConsole ()
  37. {
  38. _inputHandle = GetStdHandle (STD_INPUT_HANDLE);
  39. _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  40. _originalConsoleMode = ConsoleMode;
  41. var newConsoleMode = _originalConsoleMode;
  42. newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
  43. newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
  44. newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput;
  45. ConsoleMode = newConsoleMode;
  46. }
  47. CharInfo [] _originalStdOutChars;
  48. public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord bufferSize, SmallRect window, bool force16Colors)
  49. {
  50. if (_screenBuffer == IntPtr.Zero) {
  51. ReadFromConsoleOutput (size, bufferSize, ref window);
  52. }
  53. bool result = false;
  54. if (force16Colors) {
  55. int i = 0;
  56. CharInfo [] ci = new CharInfo [charInfoBuffer.Length];
  57. foreach (ExtendedCharInfo info in charInfoBuffer) {
  58. ci [i++] = new CharInfo () {
  59. Char = new CharUnion () { UnicodeChar = info.Char },
  60. Attributes = (ushort)info.Attribute.Value
  61. };
  62. }
  63. result = WriteConsoleOutput (_screenBuffer, ci, bufferSize, new Coord () { X = window.Left, Y = window.Top }, ref window);
  64. } else {
  65. _stringBuilder.Clear ();
  66. _stringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition);
  67. _stringBuilder.Append (EscSeqUtils.CSI_SetCursorPosition (0, 0));
  68. Attribute? prev = null;
  69. foreach (var info in charInfoBuffer) {
  70. var attr = info.Attribute;
  71. if (attr != prev) {
  72. prev = attr;
  73. _stringBuilder.Append (EscSeqUtils.CSI_SetForegroundColorRGB (attr.TrueColorForeground.Value.Red, attr.TrueColorForeground.Value.Green, attr.TrueColorForeground.Value.Blue));
  74. _stringBuilder.Append (EscSeqUtils.CSI_SetBackgroundColorRGB (attr.TrueColorBackground.Value.Red, attr.TrueColorBackground.Value.Green, attr.TrueColorBackground.Value.Blue));
  75. }
  76. if (info.Char != '\x1b') {
  77. if (!info.Empty) {
  78. _stringBuilder.Append (info.Char);
  79. }
  80. } else {
  81. _stringBuilder.Append (' ');
  82. }
  83. }
  84. _stringBuilder.Append (EscSeqUtils.CSI_RestoreCursorPosition);
  85. string s = _stringBuilder.ToString ();
  86. result = WriteConsole (_screenBuffer, s, (uint)(s.Length), out uint _, null);
  87. }
  88. if (!result) {
  89. var err = Marshal.GetLastWin32Error ();
  90. if (err != 0) {
  91. throw new System.ComponentModel.Win32Exception (err);
  92. }
  93. }
  94. return result;
  95. }
  96. public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window)
  97. {
  98. _screenBuffer = CreateConsoleScreenBuffer (
  99. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  100. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  101. IntPtr.Zero,
  102. 1,
  103. IntPtr.Zero
  104. );
  105. if (_screenBuffer == INVALID_HANDLE_VALUE) {
  106. var err = Marshal.GetLastWin32Error ();
  107. if (err != 0) {
  108. throw new System.ComponentModel.Win32Exception (err);
  109. }
  110. }
  111. if (!_initialCursorVisibility.HasValue && GetCursorVisibility (out CursorVisibility visibility)) {
  112. _initialCursorVisibility = visibility;
  113. }
  114. if (!SetConsoleActiveScreenBuffer (_screenBuffer)) {
  115. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  116. }
  117. _originalStdOutChars = new CharInfo [size.Height * size.Width];
  118. if (!ReadConsoleOutput (_screenBuffer, _originalStdOutChars, coords, new Coord () { X = 0, Y = 0 }, ref window)) {
  119. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  120. }
  121. }
  122. public bool SetCursorPosition (Coord position)
  123. {
  124. return SetConsoleCursorPosition (_screenBuffer, position);
  125. }
  126. public void SetInitialCursorVisibility ()
  127. {
  128. if (_initialCursorVisibility.HasValue == false && GetCursorVisibility (out CursorVisibility visibility)) {
  129. _initialCursorVisibility = visibility;
  130. }
  131. }
  132. public bool GetCursorVisibility (out CursorVisibility visibility)
  133. {
  134. if (_screenBuffer == IntPtr.Zero) {
  135. visibility = CursorVisibility.Invisible;
  136. return false;
  137. }
  138. if (!GetConsoleCursorInfo (_screenBuffer, out ConsoleCursorInfo info)) {
  139. var err = Marshal.GetLastWin32Error ();
  140. if (err != 0) {
  141. throw new System.ComponentModel.Win32Exception (err);
  142. }
  143. visibility = Gui.CursorVisibility.Default;
  144. return false;
  145. }
  146. if (!info.bVisible) {
  147. visibility = CursorVisibility.Invisible;
  148. } else if (info.dwSize > 50) {
  149. visibility = CursorVisibility.Box;
  150. } else {
  151. visibility = CursorVisibility.Underline;
  152. }
  153. return true;
  154. }
  155. public bool EnsureCursorVisibility ()
  156. {
  157. if (_initialCursorVisibility.HasValue && _pendingCursorVisibility.HasValue && SetCursorVisibility (_pendingCursorVisibility.Value)) {
  158. _pendingCursorVisibility = null;
  159. return true;
  160. }
  161. return false;
  162. }
  163. public void ForceRefreshCursorVisibility ()
  164. {
  165. if (_currentCursorVisibility.HasValue) {
  166. _pendingCursorVisibility = _currentCursorVisibility;
  167. _currentCursorVisibility = null;
  168. }
  169. }
  170. public bool SetCursorVisibility (CursorVisibility visibility)
  171. {
  172. if (_initialCursorVisibility.HasValue == false) {
  173. _pendingCursorVisibility = visibility;
  174. return false;
  175. }
  176. if (_currentCursorVisibility.HasValue == false || _currentCursorVisibility.Value != visibility) {
  177. ConsoleCursorInfo info = new ConsoleCursorInfo {
  178. dwSize = (uint)visibility & 0x00FF,
  179. bVisible = ((uint)visibility & 0xFF00) != 0
  180. };
  181. if (!SetConsoleCursorInfo (_screenBuffer, ref info)) {
  182. return false;
  183. }
  184. _currentCursorVisibility = visibility;
  185. }
  186. return true;
  187. }
  188. public void Cleanup ()
  189. {
  190. if (_initialCursorVisibility.HasValue) {
  191. SetCursorVisibility (_initialCursorVisibility.Value);
  192. }
  193. SetConsoleOutputWindow (out _);
  194. ConsoleMode = _originalConsoleMode;
  195. if (!SetConsoleActiveScreenBuffer (_outputHandle)) {
  196. var err = Marshal.GetLastWin32Error ();
  197. Console.WriteLine ("Error: {0}", err);
  198. }
  199. if (_screenBuffer != IntPtr.Zero) {
  200. CloseHandle (_screenBuffer);
  201. }
  202. _screenBuffer = IntPtr.Zero;
  203. }
  204. internal Size GetConsoleBufferWindow (out Point position)
  205. {
  206. if (_screenBuffer == IntPtr.Zero) {
  207. position = Point.Empty;
  208. return Size.Empty;
  209. }
  210. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  211. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  212. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  213. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  214. position = Point.Empty;
  215. return Size.Empty;
  216. }
  217. var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
  218. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  219. position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
  220. return sz;
  221. }
  222. internal Size GetConsoleOutputWindow (out Point position)
  223. {
  224. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  225. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  226. if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) {
  227. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  228. }
  229. var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
  230. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  231. position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
  232. return sz;
  233. }
  234. internal Size SetConsoleWindow (short cols, short rows)
  235. {
  236. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  237. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  238. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  239. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  240. }
  241. var maxWinSize = GetLargestConsoleWindowSize (_screenBuffer);
  242. var newCols = Math.Min (cols, maxWinSize.X);
  243. var newRows = Math.Min (rows, maxWinSize.Y);
  244. csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1));
  245. csbi.srWindow = new SmallRect (0, 0, newCols, newRows);
  246. csbi.dwMaximumWindowSize = new Coord (newCols, newRows);
  247. if (!SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  248. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  249. }
  250. var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0));
  251. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) {
  252. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  253. return new Size (cols, rows);
  254. }
  255. SetConsoleOutputWindow (csbi);
  256. return new Size (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1);
  257. }
  258. void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi)
  259. {
  260. if (_screenBuffer != IntPtr.Zero && !SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  261. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  262. }
  263. }
  264. internal Size SetConsoleOutputWindow (out Point position)
  265. {
  266. if (_screenBuffer == IntPtr.Zero) {
  267. position = Point.Empty;
  268. return Size.Empty;
  269. }
  270. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  271. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  272. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  273. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  274. }
  275. var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
  276. Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0));
  277. position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
  278. SetConsoleOutputWindow (csbi);
  279. var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0));
  280. if (!SetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) {
  281. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  282. }
  283. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) {
  284. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  285. }
  286. return sz;
  287. }
  288. uint ConsoleMode {
  289. get {
  290. GetConsoleMode (_inputHandle, out uint v);
  291. return v;
  292. }
  293. set {
  294. SetConsoleMode (_inputHandle, value);
  295. }
  296. }
  297. [Flags]
  298. public enum ConsoleModes : uint {
  299. EnableProcessedInput = 1,
  300. EnableMouseInput = 16,
  301. EnableQuickEditMode = 64,
  302. EnableExtendedFlags = 128,
  303. }
  304. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  305. public struct KeyEventRecord {
  306. [FieldOffset (0), MarshalAs (UnmanagedType.Bool)]
  307. public bool bKeyDown;
  308. [FieldOffset (4), MarshalAs (UnmanagedType.U2)]
  309. public ushort wRepeatCount;
  310. [FieldOffset (6), MarshalAs (UnmanagedType.U2)]
  311. public ushort wVirtualKeyCode;
  312. [FieldOffset (8), MarshalAs (UnmanagedType.U2)]
  313. public ushort wVirtualScanCode;
  314. [FieldOffset (10)]
  315. public char UnicodeChar;
  316. [FieldOffset (12), MarshalAs (UnmanagedType.U4)]
  317. public ControlKeyState dwControlKeyState;
  318. }
  319. [Flags]
  320. public enum ButtonState {
  321. Button1Pressed = 1,
  322. Button2Pressed = 4,
  323. Button3Pressed = 8,
  324. Button4Pressed = 16,
  325. RightmostButtonPressed = 2
  326. }
  327. [Flags]
  328. public enum ControlKeyState {
  329. RightAltPressed = 1,
  330. LeftAltPressed = 2,
  331. RightControlPressed = 4,
  332. LeftControlPressed = 8,
  333. ShiftPressed = 16,
  334. NumlockOn = 32,
  335. ScrolllockOn = 64,
  336. CapslockOn = 128,
  337. EnhancedKey = 256
  338. }
  339. [Flags]
  340. public enum EventFlags {
  341. MouseMoved = 1,
  342. DoubleClick = 2,
  343. MouseWheeled = 4,
  344. MouseHorizontalWheeled = 8
  345. }
  346. [StructLayout (LayoutKind.Explicit)]
  347. public struct MouseEventRecord {
  348. [FieldOffset (0)]
  349. public Coord MousePosition;
  350. [FieldOffset (4)]
  351. public ButtonState ButtonState;
  352. [FieldOffset (8)]
  353. public ControlKeyState ControlKeyState;
  354. [FieldOffset (12)]
  355. public EventFlags EventFlags;
  356. public override readonly string ToString () => $"[Mouse({MousePosition},{ButtonState},{ControlKeyState},{EventFlags}";
  357. }
  358. public struct WindowBufferSizeRecord {
  359. public Coord _size;
  360. public WindowBufferSizeRecord (short x, short y)
  361. {
  362. _size = new Coord (x, y);
  363. }
  364. public override readonly string ToString () => $"[WindowBufferSize{_size}";
  365. }
  366. [StructLayout (LayoutKind.Sequential)]
  367. public struct MenuEventRecord {
  368. public uint dwCommandId;
  369. }
  370. [StructLayout (LayoutKind.Sequential)]
  371. public struct FocusEventRecord {
  372. public uint bSetFocus;
  373. }
  374. public enum EventType : ushort {
  375. Focus = 0x10,
  376. Key = 0x1,
  377. Menu = 0x8,
  378. Mouse = 2,
  379. WindowBufferSize = 4
  380. }
  381. [StructLayout (LayoutKind.Explicit)]
  382. public struct InputRecord {
  383. [FieldOffset (0)]
  384. public EventType EventType;
  385. [FieldOffset (4)]
  386. public KeyEventRecord KeyEvent;
  387. [FieldOffset (4)]
  388. public MouseEventRecord MouseEvent;
  389. [FieldOffset (4)]
  390. public WindowBufferSizeRecord WindowBufferSizeEvent;
  391. [FieldOffset (4)]
  392. public MenuEventRecord MenuEvent;
  393. [FieldOffset (4)]
  394. public FocusEventRecord FocusEvent;
  395. public override readonly string ToString ()
  396. {
  397. return EventType switch {
  398. EventType.Focus => FocusEvent.ToString (),
  399. EventType.Key => KeyEvent.ToString (),
  400. EventType.Menu => MenuEvent.ToString (),
  401. EventType.Mouse => MouseEvent.ToString (),
  402. EventType.WindowBufferSize => WindowBufferSizeEvent.ToString (),
  403. _ => "Unknown event type: " + EventType
  404. };
  405. }
  406. };
  407. [Flags]
  408. enum ShareMode : uint {
  409. FileShareRead = 1,
  410. FileShareWrite = 2,
  411. }
  412. [Flags]
  413. enum DesiredAccess : uint {
  414. GenericRead = 2147483648,
  415. GenericWrite = 1073741824,
  416. }
  417. [StructLayout (LayoutKind.Sequential)]
  418. public struct ConsoleScreenBufferInfo {
  419. public Coord dwSize;
  420. public Coord dwCursorPosition;
  421. public ushort wAttributes;
  422. public SmallRect srWindow;
  423. public Coord dwMaximumWindowSize;
  424. }
  425. [StructLayout (LayoutKind.Sequential)]
  426. public struct Coord {
  427. public short X;
  428. public short Y;
  429. public Coord (short x, short y)
  430. {
  431. X = x;
  432. Y = y;
  433. }
  434. public override readonly string ToString () => $"({X},{Y})";
  435. };
  436. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  437. public struct CharUnion {
  438. [FieldOffset (0)] public char UnicodeChar;
  439. [FieldOffset (0)] public byte AsciiChar;
  440. }
  441. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  442. public struct CharInfo {
  443. [FieldOffset (0)] public CharUnion Char;
  444. [FieldOffset (2)] public ushort Attributes;
  445. }
  446. public struct ExtendedCharInfo {
  447. public char Char { get; set; }
  448. public Attribute Attribute { get; set; }
  449. public bool Empty { get; set; } // TODO: Temp hack until virutal terminal sequences
  450. public ExtendedCharInfo (char character, Attribute attribute)
  451. {
  452. Char = character;
  453. Attribute = attribute;
  454. Empty = false;
  455. }
  456. }
  457. [StructLayout (LayoutKind.Sequential)]
  458. public struct SmallRect {
  459. public short Left;
  460. public short Top;
  461. public short Right;
  462. public short Bottom;
  463. public SmallRect (short left, short top, short right, short bottom)
  464. {
  465. Left = left;
  466. Top = top;
  467. Right = right;
  468. Bottom = bottom;
  469. }
  470. public static void MakeEmpty (ref SmallRect rect)
  471. {
  472. rect.Left = -1;
  473. }
  474. public static void Update (ref SmallRect rect, short col, short row)
  475. {
  476. if (rect.Left == -1) {
  477. rect.Left = rect.Right = col;
  478. rect.Bottom = rect.Top = row;
  479. return;
  480. }
  481. if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
  482. return;
  483. if (col < rect.Left)
  484. rect.Left = col;
  485. if (col > rect.Right)
  486. rect.Right = col;
  487. if (row < rect.Top)
  488. rect.Top = row;
  489. if (row > rect.Bottom)
  490. rect.Bottom = row;
  491. }
  492. public override readonly string ToString () => $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}";
  493. }
  494. [StructLayout (LayoutKind.Sequential)]
  495. public struct ConsoleKeyInfoEx {
  496. public ConsoleKeyInfo ConsoleKeyInfo;
  497. public bool CapsLock;
  498. public bool NumLock;
  499. public bool ScrollLock;
  500. public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock, bool scrolllock)
  501. {
  502. ConsoleKeyInfo = consoleKeyInfo;
  503. CapsLock = capslock;
  504. NumLock = numlock;
  505. ScrollLock = scrolllock;
  506. }
  507. }
  508. [DllImport ("kernel32.dll", SetLastError = true)]
  509. static extern IntPtr GetStdHandle (int nStdHandle);
  510. [DllImport ("kernel32.dll", SetLastError = true)]
  511. static extern bool CloseHandle (IntPtr handle);
  512. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  513. public static extern bool ReadConsoleInput (
  514. IntPtr hConsoleInput,
  515. IntPtr lpBuffer,
  516. uint nLength,
  517. out uint lpNumberOfEventsRead);
  518. [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  519. static extern bool ReadConsoleOutput (
  520. IntPtr hConsoleOutput,
  521. [Out] CharInfo [] lpBuffer,
  522. Coord dwBufferSize,
  523. Coord dwBufferCoord,
  524. ref SmallRect lpReadRegion
  525. );
  526. // TODO: This API is obsolete. See https://learn.microsoft.com/en-us/windows/console/writeconsoleoutput
  527. [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutputW", SetLastError = true, CharSet = CharSet.Unicode)]
  528. static extern bool WriteConsoleOutput (
  529. IntPtr hConsoleOutput,
  530. CharInfo [] lpBuffer,
  531. Coord dwBufferSize,
  532. Coord dwBufferCoord,
  533. ref SmallRect lpWriteRegion
  534. );
  535. [DllImport ("kernel32.dll", EntryPoint = "WriteConsole", SetLastError = true, CharSet = CharSet.Unicode)]
  536. static extern bool WriteConsole (
  537. IntPtr hConsoleOutput,
  538. String lpbufer,
  539. UInt32 NumberOfCharsToWriten,
  540. out UInt32 lpNumberOfCharsWritten,
  541. object lpReserved
  542. );
  543. [DllImport ("kernel32.dll")]
  544. static extern bool SetConsoleCursorPosition (IntPtr hConsoleOutput, Coord dwCursorPosition);
  545. [StructLayout (LayoutKind.Sequential)]
  546. public struct ConsoleCursorInfo {
  547. public uint dwSize;
  548. public bool bVisible;
  549. }
  550. [DllImport ("kernel32.dll", SetLastError = true)]
  551. static extern bool SetConsoleCursorInfo (IntPtr hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
  552. [DllImport ("kernel32.dll", SetLastError = true)]
  553. static extern bool GetConsoleCursorInfo (IntPtr hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
  554. [DllImport ("kernel32.dll")]
  555. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  556. [DllImport ("kernel32.dll")]
  557. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  558. [DllImport ("kernel32.dll", SetLastError = true)]
  559. static extern IntPtr CreateConsoleScreenBuffer (
  560. DesiredAccess dwDesiredAccess,
  561. ShareMode dwShareMode,
  562. IntPtr secutiryAttributes,
  563. uint flags,
  564. IntPtr screenBufferData
  565. );
  566. internal static IntPtr INVALID_HANDLE_VALUE = new IntPtr (-1);
  567. [DllImport ("kernel32.dll", SetLastError = true)]
  568. static extern bool SetConsoleActiveScreenBuffer (IntPtr Handle);
  569. [DllImport ("kernel32.dll", SetLastError = true)]
  570. static extern bool GetNumberOfConsoleInputEvents (IntPtr handle, out uint lpcNumberOfEvents);
  571. public InputRecord [] ReadConsoleInput ()
  572. {
  573. const int bufferSize = 1;
  574. var pRecord = Marshal.AllocHGlobal (Marshal.SizeOf<InputRecord> () * bufferSize);
  575. try {
  576. ReadConsoleInput (_inputHandle, pRecord, bufferSize,
  577. out var numberEventsRead);
  578. return numberEventsRead == 0
  579. ? null
  580. : new [] { Marshal.PtrToStructure<InputRecord> (pRecord) };
  581. } catch (Exception) {
  582. return null;
  583. } finally {
  584. Marshal.FreeHGlobal (pRecord);
  585. }
  586. }
  587. #if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
  588. [DllImport ("kernel32.dll", ExactSpelling = true)]
  589. static extern IntPtr GetConsoleWindow ();
  590. [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  591. static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
  592. public const int HIDE = 0;
  593. public const int MAXIMIZE = 3;
  594. public const int MINIMIZE = 6;
  595. public const int RESTORE = 9;
  596. internal void ShowWindow (int state)
  597. {
  598. IntPtr thisConsole = GetConsoleWindow ();
  599. ShowWindow (thisConsole, state);
  600. }
  601. #endif
  602. // See: https://github.com/gui-cs/Terminal.Gui/issues/357
  603. [StructLayout (LayoutKind.Sequential)]
  604. public struct CONSOLE_SCREEN_BUFFER_INFOEX {
  605. public uint cbSize;
  606. public Coord dwSize;
  607. public Coord dwCursorPosition;
  608. public ushort wAttributes;
  609. public SmallRect srWindow;
  610. public Coord dwMaximumWindowSize;
  611. public ushort wPopupAttributes;
  612. public bool bFullscreenSupported;
  613. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)]
  614. public COLORREF [] ColorTable;
  615. }
  616. [StructLayout (LayoutKind.Explicit, Size = 4)]
  617. public struct COLORREF {
  618. public COLORREF (byte r, byte g, byte b)
  619. {
  620. Value = 0;
  621. R = r;
  622. G = g;
  623. B = b;
  624. }
  625. public COLORREF (uint value)
  626. {
  627. R = 0;
  628. G = 0;
  629. B = 0;
  630. Value = value & 0x00FFFFFF;
  631. }
  632. [FieldOffset (0)]
  633. public byte R;
  634. [FieldOffset (1)]
  635. public byte G;
  636. [FieldOffset (2)]
  637. public byte B;
  638. [FieldOffset (0)]
  639. public uint Value;
  640. }
  641. [DllImport ("kernel32.dll", SetLastError = true)]
  642. static extern bool GetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  643. [DllImport ("kernel32.dll", SetLastError = true)]
  644. static extern bool SetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo);
  645. [DllImport ("kernel32.dll", SetLastError = true)]
  646. static extern bool SetConsoleWindowInfo (
  647. IntPtr hConsoleOutput,
  648. bool bAbsolute,
  649. [In] ref SmallRect lpConsoleWindow);
  650. [DllImport ("kernel32.dll", SetLastError = true)]
  651. static extern Coord GetLargestConsoleWindowSize (
  652. IntPtr hConsoleOutput);
  653. }
  654. internal class WindowsDriver : ConsoleDriver {
  655. WindowsConsole.ExtendedCharInfo [] _outputBuffer;
  656. WindowsConsole.SmallRect _damageRegion;
  657. Action<KeyEvent> _keyHandler;
  658. Action<KeyEvent> _keyDownHandler;
  659. Action<KeyEvent> _keyUpHandler;
  660. Action<MouseEvent> _mouseHandler;
  661. public WindowsConsole WinConsole { get; private set; }
  662. public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931
  663. && (_isWindowsTerminal || _parentProcessName == "devenv"));
  664. readonly bool _isWindowsTerminal = false;
  665. readonly string _parentProcessName = "WindowsTerminal";
  666. public WindowsDriver ()
  667. {
  668. if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
  669. WinConsole = new WindowsConsole ();
  670. // otherwise we're probably running in unit tests
  671. Clipboard = new WindowsClipboard ();
  672. } else {
  673. Clipboard = new FakeDriver.FakeClipboard ();
  674. }
  675. if (!RunningUnitTests) {
  676. _parentProcessName = GetParentProcessName ();
  677. _isWindowsTerminal = _parentProcessName == "WindowsTerminal";
  678. if (!_isWindowsTerminal && _parentProcessName != "devenv") {
  679. Force16Colors = true;
  680. }
  681. }
  682. }
  683. private static string GetParentProcessName ()
  684. {
  685. #pragma warning disable CA1416 // Validate platform compatibility
  686. var myId = Process.GetCurrentProcess ().Id;
  687. var query = string.Format ($"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {myId}");
  688. var search = new ManagementObjectSearcher ("root\\CIMV2", query);
  689. var queryObj = search.Get ().OfType<ManagementBaseObject> ().FirstOrDefault ();
  690. if (queryObj == null) {
  691. return null;
  692. }
  693. var parentId = (uint)queryObj ["ParentProcessId"];
  694. var parent = Process.GetProcessById ((int)parentId);
  695. var prevParent = parent;
  696. // Check if the parent is from other parent
  697. while (queryObj != null) {
  698. query = string.Format ($"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {parentId}");
  699. search = new ManagementObjectSearcher ("root\\CIMV2", query);
  700. queryObj = search.Get ().OfType<ManagementBaseObject> ().FirstOrDefault ();
  701. if (queryObj == null) {
  702. return parent.ProcessName;
  703. }
  704. parentId = (uint)queryObj ["ParentProcessId"];
  705. try {
  706. parent = Process.GetProcessById ((int)parentId);
  707. if (string.Equals (parent.ProcessName, "explorer", StringComparison.InvariantCultureIgnoreCase)) {
  708. return prevParent.ProcessName;
  709. }
  710. prevParent = parent;
  711. } catch (ArgumentException) {
  712. return prevParent.ProcessName;
  713. }
  714. }
  715. return parent.ProcessName;
  716. #pragma warning restore CA1416 // Validate platform compatibility
  717. }
  718. WindowsMainLoop _mainLoop;
  719. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  720. {
  721. _keyHandler = keyHandler;
  722. _keyDownHandler = keyDownHandler;
  723. _keyUpHandler = keyUpHandler;
  724. _mouseHandler = mouseHandler;
  725. _mainLoop = mainLoop.MainLoopDriver as WindowsMainLoop;
  726. _mainLoop.ProcessInput += ProcessInput;
  727. #if HACK_CHECK_WINCHANGED
  728. _mainLoop.WinChanged += ChangeWin;
  729. #endif
  730. }
  731. #if HACK_CHECK_WINCHANGED
  732. private void ChangeWin (Object s, SizeChangedEventArgs e)
  733. {
  734. var w = e.Size.Width;
  735. if (w == Cols - 3 && e.Size.Height < Rows) {
  736. w += 3;
  737. }
  738. Left = 0;
  739. Top = 0;
  740. Cols = e.Size.Width;
  741. Rows = e.Size.Height;
  742. if (!RunningUnitTests) {
  743. var newSize = WinConsole.SetConsoleWindow (
  744. (short)Math.Max (w, 16), (short)Math.Max (e.Size.Height, 0));
  745. Cols = newSize.Width;
  746. Rows = newSize.Height;
  747. }
  748. ResizeScreen ();
  749. ClearContents ();
  750. TerminalResized.Invoke ();
  751. }
  752. #endif
  753. void ProcessInput (WindowsConsole.InputRecord inputEvent)
  754. {
  755. switch (inputEvent.EventType) {
  756. case WindowsConsole.EventType.Key:
  757. var fromPacketKey = inputEvent.KeyEvent.wVirtualKeyCode == (uint)ConsoleKey.Packet;
  758. if (fromPacketKey) {
  759. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  760. }
  761. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  762. //var ke = inputEvent.KeyEvent;
  763. //System.Diagnostics.Debug.WriteLine ($"fromPacketKey: {fromPacketKey}");
  764. //if (ke.UnicodeChar == '\0') {
  765. // System.Diagnostics.Debug.WriteLine ("UnicodeChar: 0'\\0'");
  766. //} else if (ke.UnicodeChar == 13) {
  767. // System.Diagnostics.Debug.WriteLine ("UnicodeChar: 13'\\n'");
  768. //} else {
  769. // System.Diagnostics.Debug.WriteLine ($"UnicodeChar: {(uint)ke.UnicodeChar}'{ke.UnicodeChar}'");
  770. //}
  771. //System.Diagnostics.Debug.WriteLine ($"bKeyDown: {ke.bKeyDown}");
  772. //System.Diagnostics.Debug.WriteLine ($"dwControlKeyState: {ke.dwControlKeyState}");
  773. //System.Diagnostics.Debug.WriteLine ($"wRepeatCount: {ke.wRepeatCount}");
  774. //System.Diagnostics.Debug.WriteLine ($"wVirtualKeyCode: {ke.wVirtualKeyCode}");
  775. //System.Diagnostics.Debug.WriteLine ($"wVirtualScanCode: {ke.wVirtualScanCode}");
  776. if (map == (Key)0xffffffff) {
  777. KeyEvent key = new KeyEvent ();
  778. // Shift = VK_SHIFT = 0x10
  779. // Ctrl = VK_CONTROL = 0x11
  780. // Alt = VK_MENU = 0x12
  781. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
  782. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
  783. }
  784. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
  785. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
  786. }
  787. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
  788. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
  789. }
  790. switch (inputEvent.KeyEvent.dwControlKeyState) {
  791. case WindowsConsole.ControlKeyState.RightAltPressed:
  792. case WindowsConsole.ControlKeyState.RightAltPressed |
  793. WindowsConsole.ControlKeyState.LeftControlPressed |
  794. WindowsConsole.ControlKeyState.EnhancedKey:
  795. case WindowsConsole.ControlKeyState.EnhancedKey:
  796. key = new KeyEvent (Key.CtrlMask | Key.AltMask, _keyModifiers);
  797. break;
  798. case WindowsConsole.ControlKeyState.LeftAltPressed:
  799. key = new KeyEvent (Key.AltMask, _keyModifiers);
  800. break;
  801. case WindowsConsole.ControlKeyState.RightControlPressed:
  802. case WindowsConsole.ControlKeyState.LeftControlPressed:
  803. key = new KeyEvent (Key.CtrlMask, _keyModifiers);
  804. break;
  805. case WindowsConsole.ControlKeyState.ShiftPressed:
  806. key = new KeyEvent (Key.ShiftMask, _keyModifiers);
  807. break;
  808. case WindowsConsole.ControlKeyState.NumlockOn:
  809. break;
  810. case WindowsConsole.ControlKeyState.ScrolllockOn:
  811. break;
  812. case WindowsConsole.ControlKeyState.CapslockOn:
  813. break;
  814. default:
  815. key = inputEvent.KeyEvent.wVirtualKeyCode switch {
  816. 0x10 => new KeyEvent (Key.ShiftMask, _keyModifiers),
  817. 0x11 => new KeyEvent (Key.CtrlMask, _keyModifiers),
  818. 0x12 => new KeyEvent (Key.AltMask, _keyModifiers),
  819. _ => new KeyEvent (Key.Unknown, _keyModifiers)
  820. };
  821. break;
  822. }
  823. if (inputEvent.KeyEvent.bKeyDown) {
  824. _keyDownHandler (key);
  825. } else {
  826. _keyUpHandler (key);
  827. }
  828. } else {
  829. if (inputEvent.KeyEvent.bKeyDown) {
  830. // May occurs using SendKeys
  831. _keyModifiers ??= new KeyModifiers ();
  832. // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
  833. _keyDownHandler (new KeyEvent (map, _keyModifiers));
  834. _keyHandler (new KeyEvent (map, _keyModifiers));
  835. } else {
  836. _keyUpHandler (new KeyEvent (map, _keyModifiers));
  837. }
  838. }
  839. if (!inputEvent.KeyEvent.bKeyDown && inputEvent.KeyEvent.dwControlKeyState == 0) {
  840. _keyModifiers = null;
  841. }
  842. break;
  843. case WindowsConsole.EventType.Mouse:
  844. var me = ToDriverMouse (inputEvent.MouseEvent);
  845. _mouseHandler (me);
  846. if (_processButtonClick) {
  847. _mouseHandler (
  848. new MouseEvent () {
  849. X = me.X,
  850. Y = me.Y,
  851. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  852. });
  853. }
  854. break;
  855. case WindowsConsole.EventType.Focus:
  856. break;
  857. #if !HACK_CHECK_WINCHANGED
  858. case WindowsConsole.EventType.WindowBufferSize:
  859. Cols = inputEvent.WindowBufferSizeEvent._size.X;
  860. Rows = inputEvent.WindowBufferSizeEvent._size.Y;
  861. ResizeScreen ();
  862. ClearContents ();
  863. TerminalResized.Invoke ();
  864. break;
  865. #endif
  866. }
  867. }
  868. WindowsConsole.ButtonState? _lastMouseButtonPressed = null;
  869. bool _isButtonPressed = false;
  870. bool _isButtonReleased = false;
  871. bool _isButtonDoubleClicked = false;
  872. Point? _point;
  873. Point _pointMove;
  874. bool _isOneFingerDoubleClicked = false;
  875. bool _processButtonClick;
  876. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  877. {
  878. MouseFlags mouseFlag = MouseFlags.AllEvents;
  879. //System.Diagnostics.Debug.WriteLine (
  880. // $"X:{mouseEvent.MousePosition.X};Y:{mouseEvent.MousePosition.Y};ButtonState:{mouseEvent.ButtonState};EventFlags:{mouseEvent.EventFlags}");
  881. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked) {
  882. Application.MainLoop.AddIdle (() => {
  883. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  884. return false;
  885. });
  886. }
  887. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  888. // This will tell when a mouse button is pressed. When the button is released this event will
  889. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  890. // To map to the correct driver events we save the last pressed mouse button so we can
  891. // map to the correct clicked event.
  892. if ((_lastMouseButtonPressed != null || _isButtonReleased) && mouseEvent.ButtonState != 0) {
  893. _lastMouseButtonPressed = null;
  894. //isButtonPressed = false;
  895. _isButtonReleased = false;
  896. }
  897. var p = new Point () {
  898. X = mouseEvent.MousePosition.X,
  899. Y = mouseEvent.MousePosition.Y
  900. };
  901. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed == null && !_isButtonDoubleClicked) ||
  902. (_lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) &&
  903. mouseEvent.ButtonState != 0 && !_isButtonReleased && !_isButtonDoubleClicked)) {
  904. switch (mouseEvent.ButtonState) {
  905. case WindowsConsole.ButtonState.Button1Pressed:
  906. mouseFlag = MouseFlags.Button1Pressed;
  907. break;
  908. case WindowsConsole.ButtonState.Button2Pressed:
  909. mouseFlag = MouseFlags.Button2Pressed;
  910. break;
  911. case WindowsConsole.ButtonState.RightmostButtonPressed:
  912. mouseFlag = MouseFlags.Button3Pressed;
  913. break;
  914. }
  915. if (_point == null) {
  916. _point = p;
  917. }
  918. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  919. mouseFlag |= MouseFlags.ReportMousePosition;
  920. _isButtonReleased = false;
  921. _processButtonClick = false;
  922. }
  923. _lastMouseButtonPressed = mouseEvent.ButtonState;
  924. _isButtonPressed = true;
  925. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  926. Application.MainLoop.AddIdle (() => {
  927. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  928. return false;
  929. });
  930. }
  931. } else if (_lastMouseButtonPressed != null && mouseEvent.EventFlags == 0
  932. && !_isButtonReleased && !_isButtonDoubleClicked && !_isOneFingerDoubleClicked) {
  933. switch (_lastMouseButtonPressed) {
  934. case WindowsConsole.ButtonState.Button1Pressed:
  935. mouseFlag = MouseFlags.Button1Released;
  936. break;
  937. case WindowsConsole.ButtonState.Button2Pressed:
  938. mouseFlag = MouseFlags.Button2Released;
  939. break;
  940. case WindowsConsole.ButtonState.RightmostButtonPressed:
  941. mouseFlag = MouseFlags.Button3Released;
  942. break;
  943. }
  944. _isButtonPressed = false;
  945. _isButtonReleased = true;
  946. if (_point != null && (((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)) {
  947. _processButtonClick = true;
  948. } else {
  949. _point = null;
  950. }
  951. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  952. && !_isOneFingerDoubleClicked && _isButtonReleased && p == _point) {
  953. mouseFlag = ProcessButtonClick (mouseEvent);
  954. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  955. switch (mouseEvent.ButtonState) {
  956. case WindowsConsole.ButtonState.Button1Pressed:
  957. mouseFlag = MouseFlags.Button1DoubleClicked;
  958. break;
  959. case WindowsConsole.ButtonState.Button2Pressed:
  960. mouseFlag = MouseFlags.Button2DoubleClicked;
  961. break;
  962. case WindowsConsole.ButtonState.RightmostButtonPressed:
  963. mouseFlag = MouseFlags.Button3DoubleClicked;
  964. break;
  965. }
  966. _isButtonDoubleClicked = true;
  967. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked) {
  968. switch (mouseEvent.ButtonState) {
  969. case WindowsConsole.ButtonState.Button1Pressed:
  970. mouseFlag = MouseFlags.Button1TripleClicked;
  971. break;
  972. case WindowsConsole.ButtonState.Button2Pressed:
  973. mouseFlag = MouseFlags.Button2TripleClicked;
  974. break;
  975. case WindowsConsole.ButtonState.RightmostButtonPressed:
  976. mouseFlag = MouseFlags.Button3TripleClicked;
  977. break;
  978. }
  979. _isButtonDoubleClicked = false;
  980. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  981. switch ((int)mouseEvent.ButtonState) {
  982. case int v when v > 0:
  983. mouseFlag = MouseFlags.WheeledUp;
  984. break;
  985. case int v when v < 0:
  986. mouseFlag = MouseFlags.WheeledDown;
  987. break;
  988. }
  989. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  990. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  991. switch ((int)mouseEvent.ButtonState) {
  992. case int v when v > 0:
  993. mouseFlag = MouseFlags.WheeledLeft;
  994. break;
  995. case int v when v < 0:
  996. mouseFlag = MouseFlags.WheeledRight;
  997. break;
  998. }
  999. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled) {
  1000. switch ((int)mouseEvent.ButtonState) {
  1001. case int v when v < 0:
  1002. mouseFlag = MouseFlags.WheeledLeft;
  1003. break;
  1004. case int v when v > 0:
  1005. mouseFlag = MouseFlags.WheeledRight;
  1006. break;
  1007. }
  1008. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  1009. mouseFlag = MouseFlags.ReportMousePosition;
  1010. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y) {
  1011. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  1012. }
  1013. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  1014. mouseFlag = 0;
  1015. }
  1016. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  1017. //System.Diagnostics.Debug.WriteLine (
  1018. // $"point.X:{(point != null ? ((Point)point).X : -1)};point.Y:{(point != null ? ((Point)point).Y : -1)}");
  1019. return new MouseEvent () {
  1020. X = mouseEvent.MousePosition.X,
  1021. Y = mouseEvent.MousePosition.Y,
  1022. Flags = mouseFlag
  1023. };
  1024. }
  1025. MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  1026. {
  1027. MouseFlags mouseFlag = 0;
  1028. switch (_lastMouseButtonPressed) {
  1029. case WindowsConsole.ButtonState.Button1Pressed:
  1030. mouseFlag = MouseFlags.Button1Clicked;
  1031. break;
  1032. case WindowsConsole.ButtonState.Button2Pressed:
  1033. mouseFlag = MouseFlags.Button2Clicked;
  1034. break;
  1035. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1036. mouseFlag = MouseFlags.Button3Clicked;
  1037. break;
  1038. }
  1039. _point = new Point () {
  1040. X = mouseEvent.MousePosition.X,
  1041. Y = mouseEvent.MousePosition.Y
  1042. };
  1043. _lastMouseButtonPressed = null;
  1044. _isButtonReleased = false;
  1045. _processButtonClick = false;
  1046. _point = null;
  1047. return mouseFlag;
  1048. }
  1049. async Task ProcessButtonDoubleClickedAsync ()
  1050. {
  1051. await Task.Delay (300);
  1052. _isButtonDoubleClicked = false;
  1053. _isOneFingerDoubleClicked = false;
  1054. //buttonPressedCount = 0;
  1055. }
  1056. async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1057. {
  1058. while (_isButtonPressed) {
  1059. await Task.Delay (100);
  1060. var me = new MouseEvent () {
  1061. X = _pointMove.X,
  1062. Y = _pointMove.Y,
  1063. Flags = mouseFlag
  1064. };
  1065. var view = Application.WantContinuousButtonPressedView;
  1066. if (view == null) {
  1067. break;
  1068. }
  1069. if (_isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1070. Application.MainLoop.Invoke (() => _mouseHandler (me));
  1071. }
  1072. }
  1073. }
  1074. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1075. {
  1076. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  1077. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)) {
  1078. mouseFlag |= MouseFlags.ButtonCtrl;
  1079. }
  1080. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1081. mouseFlag |= MouseFlags.ButtonShift;
  1082. }
  1083. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1084. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1085. mouseFlag |= MouseFlags.ButtonAlt;
  1086. }
  1087. return mouseFlag;
  1088. }
  1089. KeyModifiers _keyModifiers;
  1090. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1091. {
  1092. var state = keyEvent.dwControlKeyState;
  1093. var shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1094. var alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1095. var control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1096. var capsLock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  1097. var numLock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  1098. var scrollLock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  1099. _keyModifiers ??= new KeyModifiers ();
  1100. if (shift) {
  1101. _keyModifiers.Shift = true;
  1102. }
  1103. if (alt) {
  1104. _keyModifiers.Alt = true;
  1105. }
  1106. if (control) {
  1107. _keyModifiers.Ctrl = true;
  1108. }
  1109. if (capsLock) {
  1110. _keyModifiers.Capslock = true;
  1111. }
  1112. if (numLock) {
  1113. _keyModifiers.Numlock = true;
  1114. }
  1115. if (scrollLock) {
  1116. _keyModifiers.Scrolllock = true;
  1117. }
  1118. var consoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1119. return new WindowsConsole.ConsoleKeyInfoEx (consoleKeyInfo, capsLock, numLock, scrollLock);
  1120. }
  1121. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  1122. {
  1123. if (keyEvent.wVirtualKeyCode != (uint)ConsoleKey.Packet) {
  1124. return keyEvent;
  1125. }
  1126. var mod = new ConsoleModifiers ();
  1127. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1128. mod |= ConsoleModifiers.Shift;
  1129. }
  1130. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1131. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1132. mod |= ConsoleModifiers.Alt;
  1133. }
  1134. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed) ||
  1135. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)) {
  1136. mod |= ConsoleModifiers.Control;
  1137. }
  1138. var keyChar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyEvent.UnicodeChar, mod, out uint virtualKey, out uint scanCode);
  1139. return new WindowsConsole.KeyEventRecord {
  1140. UnicodeChar = (char)keyChar,
  1141. bKeyDown = keyEvent.bKeyDown,
  1142. dwControlKeyState = keyEvent.dwControlKeyState,
  1143. wRepeatCount = keyEvent.wRepeatCount,
  1144. wVirtualKeyCode = (ushort)virtualKey,
  1145. wVirtualScanCode = (ushort)scanCode
  1146. };
  1147. }
  1148. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  1149. {
  1150. var keyInfo = keyInfoEx.ConsoleKeyInfo;
  1151. switch (keyInfo.Key) {
  1152. case ConsoleKey.Escape:
  1153. return MapKeyModifiers (keyInfo, Key.Esc);
  1154. case ConsoleKey.Tab:
  1155. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  1156. case ConsoleKey.Clear:
  1157. return MapKeyModifiers (keyInfo, Key.Clear);
  1158. case ConsoleKey.Home:
  1159. return MapKeyModifiers (keyInfo, Key.Home);
  1160. case ConsoleKey.End:
  1161. return MapKeyModifiers (keyInfo, Key.End);
  1162. case ConsoleKey.LeftArrow:
  1163. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  1164. case ConsoleKey.RightArrow:
  1165. return MapKeyModifiers (keyInfo, Key.CursorRight);
  1166. case ConsoleKey.UpArrow:
  1167. return MapKeyModifiers (keyInfo, Key.CursorUp);
  1168. case ConsoleKey.DownArrow:
  1169. return MapKeyModifiers (keyInfo, Key.CursorDown);
  1170. case ConsoleKey.PageUp:
  1171. return MapKeyModifiers (keyInfo, Key.PageUp);
  1172. case ConsoleKey.PageDown:
  1173. return MapKeyModifiers (keyInfo, Key.PageDown);
  1174. case ConsoleKey.Enter:
  1175. return MapKeyModifiers (keyInfo, Key.Enter);
  1176. case ConsoleKey.Spacebar:
  1177. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  1178. case ConsoleKey.Backspace:
  1179. return MapKeyModifiers (keyInfo, Key.Backspace);
  1180. case ConsoleKey.Delete:
  1181. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  1182. case ConsoleKey.Insert:
  1183. return MapKeyModifiers (keyInfo, Key.InsertChar);
  1184. case ConsoleKey.PrintScreen:
  1185. return MapKeyModifiers (keyInfo, Key.PrintScreen);
  1186. case ConsoleKey.NumPad0:
  1187. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  1188. case ConsoleKey.NumPad1:
  1189. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  1190. case ConsoleKey.NumPad2:
  1191. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  1192. case ConsoleKey.NumPad3:
  1193. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  1194. case ConsoleKey.NumPad4:
  1195. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  1196. case ConsoleKey.NumPad5:
  1197. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  1198. case ConsoleKey.NumPad6:
  1199. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  1200. case ConsoleKey.NumPad7:
  1201. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  1202. case ConsoleKey.NumPad8:
  1203. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  1204. case ConsoleKey.NumPad9:
  1205. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  1206. case ConsoleKey.Oem1:
  1207. case ConsoleKey.Oem2:
  1208. case ConsoleKey.Oem3:
  1209. case ConsoleKey.Oem4:
  1210. case ConsoleKey.Oem5:
  1211. case ConsoleKey.Oem6:
  1212. case ConsoleKey.Oem7:
  1213. case ConsoleKey.Oem8:
  1214. case ConsoleKey.Oem102:
  1215. case ConsoleKey.OemPeriod:
  1216. case ConsoleKey.OemComma:
  1217. case ConsoleKey.OemPlus:
  1218. case ConsoleKey.OemMinus:
  1219. if (keyInfo.KeyChar == 0) {
  1220. return Key.Unknown;
  1221. }
  1222. return (Key)((uint)keyInfo.KeyChar);
  1223. }
  1224. var key = keyInfo.Key;
  1225. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  1226. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  1227. var delta = key - ConsoleKey.A;
  1228. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1229. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1230. }
  1231. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1232. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1233. }
  1234. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1235. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1236. }
  1237. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1238. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1239. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1240. }
  1241. }
  1242. //return (Key)((uint)alphaBase + delta);
  1243. return (Key)((uint)keyInfo.KeyChar);
  1244. }
  1245. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1246. var delta = key - ConsoleKey.D0;
  1247. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1248. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1249. }
  1250. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1251. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1252. }
  1253. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1254. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1255. }
  1256. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1257. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30 || keyInfo.KeyChar == ((uint)Key.D0 + delta)) {
  1258. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1259. }
  1260. }
  1261. return (Key)((uint)keyInfo.KeyChar);
  1262. }
  1263. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1264. var delta = key - ConsoleKey.F1;
  1265. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1266. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1267. }
  1268. return (Key)((uint)Key.F1 + delta);
  1269. }
  1270. if (keyInfo.KeyChar != 0) {
  1271. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1272. }
  1273. return (Key)(0xffffffff);
  1274. }
  1275. private Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1276. {
  1277. Key keyMod = new Key ();
  1278. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0) {
  1279. keyMod = Key.ShiftMask;
  1280. }
  1281. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) {
  1282. keyMod |= Key.CtrlMask;
  1283. }
  1284. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0) {
  1285. keyMod |= Key.AltMask;
  1286. }
  1287. return keyMod != Key.Null ? keyMod | key : key;
  1288. }
  1289. public override bool IsRuneSupported (Rune rune)
  1290. {
  1291. return base.IsRuneSupported (rune) && rune.IsBmp;
  1292. }
  1293. public override void Init (Action terminalResized)
  1294. {
  1295. TerminalResized = terminalResized;
  1296. if (RunningUnitTests) {
  1297. return;
  1298. }
  1299. try {
  1300. if (WinConsole != null) {
  1301. // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init.
  1302. // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED
  1303. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1304. Cols = winSize.Width;
  1305. Rows = winSize.Height;
  1306. }
  1307. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1308. // Needed for Windows Terminal
  1309. // ESC [ ? 1047 h Save cursor position and activate xterm alternative buffer (no backscroll)
  1310. // ESC [ ? 1047 l Restore cursor position and restore xterm working buffer (with backscroll)
  1311. // ESC [ ? 1048 h Save cursor position
  1312. // ESC [ ? 1048 l Restore cursor position
  1313. // ESC [ ? 1049 h Activate xterm alternative buffer (no backscroll)
  1314. // ESC [ ? 1049 l Restore xterm working buffer (with backscroll)
  1315. // Per Issue #2264 using the alternative screen buffer is required for Windows Terminal to not
  1316. // wipe out the backscroll buffer when the application exits.
  1317. if (_isWindowsTerminal) {
  1318. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  1319. }
  1320. } catch (Win32Exception e) {
  1321. // We are being run in an environment that does not support a console
  1322. // such as a unit test, or a pipe.
  1323. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  1324. WinConsole = null;
  1325. }
  1326. CurrentAttribute = MakeColor (Color.White, Color.Black);
  1327. InitializeColorSchemes ();
  1328. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1329. Clip = new Rect (0, 0, Cols, Rows);
  1330. _damageRegion = new WindowsConsole.SmallRect () {
  1331. Top = 0,
  1332. Left = 0,
  1333. Bottom = (short)Rows,
  1334. Right = (short)Cols
  1335. };
  1336. ClearContents ();
  1337. }
  1338. void ResizeScreen ()
  1339. {
  1340. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1341. Clip = new Rect (0, 0, Cols, Rows);
  1342. _damageRegion = new WindowsConsole.SmallRect () {
  1343. Top = 0,
  1344. Left = 0,
  1345. Bottom = (short)Rows,
  1346. Right = (short)Cols
  1347. };
  1348. _dirtyLines = new bool [Rows];
  1349. WinConsole?.ForceRefreshCursorVisibility ();
  1350. }
  1351. public override void UpdateScreen ()
  1352. {
  1353. var windowSize = WinConsole?.GetConsoleBufferWindow (out _) ?? new Size (Cols, Rows);
  1354. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows)) {
  1355. return;
  1356. }
  1357. var bufferCoords = new WindowsConsole.Coord () {
  1358. X = (short)Clip.Width,
  1359. Y = (short)Clip.Height
  1360. };
  1361. for (int row = 0; row < Rows; row++) {
  1362. if (!_dirtyLines [row]) {
  1363. continue;
  1364. }
  1365. _dirtyLines [row] = false;
  1366. for (int col = 0; col < Cols; col++) {
  1367. int position = row * Cols + col;
  1368. _outputBuffer [position].Attribute = Contents [row, col].Attribute.GetValueOrDefault ();
  1369. if (Contents [row, col].IsDirty == false) {
  1370. _outputBuffer [position].Empty = true;
  1371. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1372. continue;
  1373. }
  1374. _outputBuffer [position].Empty = false;
  1375. if (Contents [row, col].Runes [0].IsBmp) {
  1376. _outputBuffer [position].Char = (char)Contents [row, col].Runes [0].Value;
  1377. } else {
  1378. //_outputBuffer [position].Empty = true;
  1379. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1380. if (Contents [row, col].Runes [0].GetColumns () > 1 && col + 1 < Cols) {
  1381. // TODO: This is a hack to deal with non-BMP and wide characters.
  1382. col++;
  1383. position = row * Cols + col;
  1384. _outputBuffer [position].Empty = false;
  1385. _outputBuffer [position].Char = ' ';
  1386. }
  1387. }
  1388. }
  1389. }
  1390. _damageRegion = new WindowsConsole.SmallRect () {
  1391. Top = 0,
  1392. Left = 0,
  1393. Bottom = (short)Rows,
  1394. Right = (short)Cols
  1395. };
  1396. if (!RunningUnitTests && WinConsole != null && !WinConsole.WriteToConsole (new Size (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors)) {
  1397. var err = Marshal.GetLastWin32Error ();
  1398. if (err != 0) {
  1399. throw new System.ComponentModel.Win32Exception (err);
  1400. }
  1401. }
  1402. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1403. }
  1404. public override void Refresh ()
  1405. {
  1406. UpdateScreen ();
  1407. WinConsole?.SetInitialCursorVisibility ();
  1408. UpdateCursor ();
  1409. }
  1410. #region Color Handling
  1411. /// <summary>
  1412. /// In the WindowsDriver, colors are encoded as an int.
  1413. /// The background color is stored in the least significant 4 bits,
  1414. /// and the foreground color is stored in the next 4 bits.
  1415. /// </summary>
  1416. public override Attribute MakeColor (Color foreground, Color background)
  1417. {
  1418. // Encode the colors into the int value.
  1419. return new Attribute (
  1420. value: (((int)foreground) | ((int)background << 4)),
  1421. foreground: foreground,
  1422. background: background
  1423. );
  1424. }
  1425. /// <summary>
  1426. /// Extracts the foreground and background colors from the encoded value.
  1427. /// Assumes a 4-bit encoded value for both foreground and background colors.
  1428. /// </summary>
  1429. internal override void GetColors (int value, out Color foreground, out Color background)
  1430. {
  1431. // Assume a 4-bit encoded value for both foreground and background colors.
  1432. foreground = (Color)((value >> 16) & 0xF);
  1433. background = (Color)(value & 0xF);
  1434. }
  1435. #endregion
  1436. CursorVisibility _cachedCursorVisibility;
  1437. public override void UpdateCursor ()
  1438. {
  1439. if (Col < 0 || Row < 0 || Col > Cols || Row > Rows) {
  1440. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1441. _cachedCursorVisibility = cursorVisibility;
  1442. SetCursorVisibility (CursorVisibility.Invisible);
  1443. return;
  1444. }
  1445. SetCursorVisibility (_cachedCursorVisibility);
  1446. var position = new WindowsConsole.Coord () {
  1447. X = (short)Col,
  1448. Y = (short)Row
  1449. };
  1450. WinConsole?.SetCursorPosition (position);
  1451. }
  1452. /// <inheritdoc/>
  1453. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1454. {
  1455. if (WinConsole != null) {
  1456. return WinConsole.GetCursorVisibility (out visibility);
  1457. }
  1458. visibility = _cachedCursorVisibility;
  1459. return true;
  1460. }
  1461. /// <inheritdoc/>
  1462. public override bool SetCursorVisibility (CursorVisibility visibility)
  1463. {
  1464. _cachedCursorVisibility = visibility;
  1465. return WinConsole == null || WinConsole.SetCursorVisibility (visibility);
  1466. }
  1467. /// <inheritdoc/>
  1468. public override bool EnsureCursorVisibility ()
  1469. {
  1470. return WinConsole == null || WinConsole.EnsureCursorVisibility ();
  1471. }
  1472. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1473. {
  1474. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1475. EventType = WindowsConsole.EventType.Key
  1476. };
  1477. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1478. bKeyDown = true
  1479. };
  1480. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1481. if (shift) {
  1482. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1483. keyEvent.UnicodeChar = '\0';
  1484. keyEvent.wVirtualKeyCode = 16;
  1485. }
  1486. if (alt) {
  1487. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1488. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1489. keyEvent.UnicodeChar = '\0';
  1490. keyEvent.wVirtualKeyCode = 18;
  1491. }
  1492. if (control) {
  1493. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1494. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1495. keyEvent.UnicodeChar = '\0';
  1496. keyEvent.wVirtualKeyCode = 17;
  1497. }
  1498. keyEvent.dwControlKeyState = controlKey;
  1499. input.KeyEvent = keyEvent;
  1500. if (shift || alt || control) {
  1501. ProcessInput (input);
  1502. }
  1503. keyEvent.UnicodeChar = keyChar;
  1504. if ((uint)key < 255) {
  1505. keyEvent.wVirtualKeyCode = (ushort)key;
  1506. } else {
  1507. keyEvent.wVirtualKeyCode = '\0';
  1508. }
  1509. input.KeyEvent = keyEvent;
  1510. try {
  1511. ProcessInput (input);
  1512. } catch (OverflowException) { } finally {
  1513. keyEvent.bKeyDown = false;
  1514. input.KeyEvent = keyEvent;
  1515. ProcessInput (input);
  1516. }
  1517. }
  1518. public override void End ()
  1519. {
  1520. if (_mainLoop != null) {
  1521. _mainLoop.ProcessInput -= ProcessInput;
  1522. #if HACK_CHECK_WINCHANGED
  1523. //_mainLoop.WinChanged -= ChangeWin;
  1524. #endif
  1525. }
  1526. _mainLoop = null;
  1527. WinConsole?.Cleanup ();
  1528. WinConsole = null;
  1529. if (!RunningUnitTests && (_isWindowsTerminal || _parentProcessName == "devenv")) {
  1530. // Disable alternative screen buffer.
  1531. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndActivateAltBufferWithBackscroll);
  1532. }
  1533. }
  1534. #region Not Implemented
  1535. public override void Suspend ()
  1536. {
  1537. throw new NotImplementedException ();
  1538. }
  1539. #endregion
  1540. }
  1541. /// <summary>
  1542. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1543. /// only be used on Windows.
  1544. /// </summary>
  1545. /// <remarks>
  1546. /// This implementation is used for WindowsDriver.
  1547. /// </remarks>
  1548. internal class WindowsMainLoop : IMainLoopDriver {
  1549. readonly ManualResetEventSlim _eventReady = new ManualResetEventSlim (false);
  1550. readonly ManualResetEventSlim _waitForProbe = new ManualResetEventSlim (false);
  1551. MainLoop _mainLoop;
  1552. readonly ConsoleDriver _consoleDriver;
  1553. readonly WindowsConsole _winConsole;
  1554. CancellationTokenSource _eventReadyTokenSource = new CancellationTokenSource ();
  1555. CancellationTokenSource _inputHandlerTokenSource = new CancellationTokenSource ();
  1556. // The records that we keep fetching
  1557. readonly Queue<WindowsConsole.InputRecord []> _resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1558. /// <summary>
  1559. /// Invoked when a Key is pressed or released.
  1560. /// </summary>
  1561. public Action<WindowsConsole.InputRecord> ProcessInput;
  1562. /// <summary>
  1563. /// Invoked when the window is changed.
  1564. /// </summary>
  1565. public EventHandler<SizeChangedEventArgs> WinChanged;
  1566. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1567. {
  1568. _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver));
  1569. _winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1570. }
  1571. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1572. {
  1573. _mainLoop = mainLoop;
  1574. Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token);
  1575. #if HACK_CHECK_WINCHANGED
  1576. Task.Run (CheckWinChange);
  1577. #endif
  1578. }
  1579. void WindowsInputHandler ()
  1580. {
  1581. while (_mainLoop != null) {
  1582. try {
  1583. if (!_inputHandlerTokenSource.IsCancellationRequested) {
  1584. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1585. }
  1586. } catch (OperationCanceledException) {
  1587. return;
  1588. } finally {
  1589. _waitForProbe.Reset ();
  1590. }
  1591. if (_resultQueue?.Count == 0) {
  1592. _resultQueue.Enqueue (_winConsole.ReadConsoleInput ());
  1593. }
  1594. _eventReady.Set ();
  1595. }
  1596. }
  1597. #if HACK_CHECK_WINCHANGED
  1598. readonly ManualResetEventSlim _winChange = new ManualResetEventSlim (false);
  1599. bool _winChanged;
  1600. Size _windowSize;
  1601. void CheckWinChange ()
  1602. {
  1603. while (_mainLoop != null) {
  1604. _winChange.Wait ();
  1605. _winChange.Reset ();
  1606. // Check if the window size changed every half second.
  1607. // We do this to minimize the weird tearing seen on Windows when resizing the console
  1608. while (_mainLoop != null) {
  1609. Task.Delay (500).Wait ();
  1610. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  1611. if (_windowSize != Size.Empty && (_windowSize.Width != _consoleDriver.Cols
  1612. || _windowSize.Height != _consoleDriver.Rows)) {
  1613. break;
  1614. }
  1615. }
  1616. _winChanged = true;
  1617. _eventReady.Set ();
  1618. }
  1619. }
  1620. #endif
  1621. void IMainLoopDriver.Wakeup ()
  1622. {
  1623. _eventReady.Set ();
  1624. }
  1625. bool IMainLoopDriver.EventsPending ()
  1626. {
  1627. _waitForProbe.Set ();
  1628. #if HACK_CHECK_WINCHANGED
  1629. _winChange.Set ();
  1630. #endif
  1631. if (_mainLoop.CheckTimersAndIdleHandlers (out var waitTimeout)) {
  1632. return true;
  1633. }
  1634. try {
  1635. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1636. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1637. // are no timers, but there IS an idle handler waiting.
  1638. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1639. }
  1640. } catch (OperationCanceledException) {
  1641. return true;
  1642. } finally {
  1643. _eventReady.Reset ();
  1644. }
  1645. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1646. #if HACK_CHECK_WINCHANGED
  1647. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  1648. #else
  1649. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1650. #endif
  1651. }
  1652. _eventReadyTokenSource.Dispose ();
  1653. _eventReadyTokenSource = new CancellationTokenSource ();
  1654. return true;
  1655. }
  1656. void IMainLoopDriver.Iteration ()
  1657. {
  1658. while (_resultQueue.Count > 0) {
  1659. var inputRecords = _resultQueue.Dequeue ();
  1660. if (inputRecords is { Length: > 0 }) {
  1661. var inputEvent = inputRecords [0];
  1662. ProcessInput?.Invoke (inputEvent);
  1663. }
  1664. }
  1665. #if HACK_CHECK_WINCHANGED
  1666. if (_winChanged) {
  1667. _winChanged = false;
  1668. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  1669. }
  1670. #endif
  1671. }
  1672. void IMainLoopDriver.TearDown ()
  1673. {
  1674. _inputHandlerTokenSource?.Cancel ();
  1675. _inputHandlerTokenSource?.Dispose ();
  1676. _eventReadyTokenSource?.Cancel ();
  1677. _eventReadyTokenSource?.Dispose ();
  1678. _eventReady?.Dispose ();
  1679. _resultQueue?.Clear ();
  1680. #if HACK_CHECK_WINCHANGED
  1681. _winChange?.Dispose ();
  1682. #endif
  1683. _waitForProbe?.Dispose ();
  1684. _mainLoop = null;
  1685. }
  1686. }
  1687. class WindowsClipboard : ClipboardBase {
  1688. public WindowsClipboard ()
  1689. {
  1690. IsSupported = IsClipboardFormatAvailable (_cfUnicodeText);
  1691. }
  1692. public override bool IsSupported { get; }
  1693. protected override string GetClipboardDataImpl ()
  1694. {
  1695. try {
  1696. if (!OpenClipboard (IntPtr.Zero)) {
  1697. return string.Empty;
  1698. }
  1699. IntPtr handle = GetClipboardData (_cfUnicodeText);
  1700. if (handle == IntPtr.Zero) {
  1701. return string.Empty;
  1702. }
  1703. IntPtr pointer = IntPtr.Zero;
  1704. try {
  1705. pointer = GlobalLock (handle);
  1706. if (pointer == IntPtr.Zero) {
  1707. return string.Empty;
  1708. }
  1709. int size = GlobalSize (handle);
  1710. byte [] buff = new byte [size];
  1711. Marshal.Copy (pointer, buff, 0, size);
  1712. return System.Text.Encoding.Unicode.GetString (buff).TrimEnd ('\0');
  1713. } finally {
  1714. if (pointer != IntPtr.Zero) {
  1715. GlobalUnlock (handle);
  1716. }
  1717. }
  1718. } finally {
  1719. CloseClipboard ();
  1720. }
  1721. }
  1722. protected override void SetClipboardDataImpl (string text)
  1723. {
  1724. OpenClipboard ();
  1725. EmptyClipboard ();
  1726. IntPtr hGlobal = default;
  1727. try {
  1728. var bytes = (text.Length + 1) * 2;
  1729. hGlobal = Marshal.AllocHGlobal (bytes);
  1730. if (hGlobal == default) {
  1731. ThrowWin32 ();
  1732. }
  1733. var target = GlobalLock (hGlobal);
  1734. if (target == default) {
  1735. ThrowWin32 ();
  1736. }
  1737. try {
  1738. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1739. } finally {
  1740. GlobalUnlock (target);
  1741. }
  1742. if (SetClipboardData (_cfUnicodeText, hGlobal) == default) {
  1743. ThrowWin32 ();
  1744. }
  1745. hGlobal = default;
  1746. } finally {
  1747. if (hGlobal != default) {
  1748. Marshal.FreeHGlobal (hGlobal);
  1749. }
  1750. CloseClipboard ();
  1751. }
  1752. }
  1753. void OpenClipboard ()
  1754. {
  1755. var num = 10;
  1756. while (true) {
  1757. if (OpenClipboard (default)) {
  1758. break;
  1759. }
  1760. if (--num == 0) {
  1761. ThrowWin32 ();
  1762. }
  1763. Thread.Sleep (100);
  1764. }
  1765. }
  1766. const uint _cfUnicodeText = 13;
  1767. void ThrowWin32 ()
  1768. {
  1769. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1770. }
  1771. [DllImport ("User32.dll", SetLastError = true)]
  1772. [return: MarshalAs (UnmanagedType.Bool)]
  1773. static extern bool IsClipboardFormatAvailable (uint format);
  1774. [DllImport ("kernel32.dll", SetLastError = true)]
  1775. static extern int GlobalSize (IntPtr handle);
  1776. [DllImport ("kernel32.dll", SetLastError = true)]
  1777. static extern IntPtr GlobalLock (IntPtr hMem);
  1778. [DllImport ("kernel32.dll", SetLastError = true)]
  1779. [return: MarshalAs (UnmanagedType.Bool)]
  1780. static extern bool GlobalUnlock (IntPtr hMem);
  1781. [DllImport ("user32.dll", SetLastError = true)]
  1782. [return: MarshalAs (UnmanagedType.Bool)]
  1783. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1784. [DllImport ("user32.dll", SetLastError = true)]
  1785. [return: MarshalAs (UnmanagedType.Bool)]
  1786. static extern bool CloseClipboard ();
  1787. [DllImport ("user32.dll", SetLastError = true)]
  1788. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1789. [DllImport ("user32.dll")]
  1790. static extern bool EmptyClipboard ();
  1791. [DllImport ("user32.dll", SetLastError = true)]
  1792. static extern IntPtr GetClipboardData (uint uFormat);
  1793. }