WindowsDriver.cs 59 KB

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