WindowsDriver.cs 60 KB

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