WindowsDriver.cs 58 KB

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