WindowsDriver.cs 56 KB

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