WindowsDriver.cs 59 KB

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