WindowsDriver.cs 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056
  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. public override bool Force16Colors {
  657. get => base.Force16Colors;
  658. set {
  659. base.Force16Colors = value;
  660. // BUGBUG: This is a hack until we fully support VirtualTerminalSequences
  661. if (WinConsole != null) {
  662. WinConsole = new WindowsConsole ();
  663. }
  664. Refresh ();
  665. }
  666. }
  667. readonly bool _isWindowsTerminal = false;
  668. public WindowsDriver ()
  669. {
  670. if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
  671. WinConsole = new WindowsConsole ();
  672. // otherwise we're probably running in unit tests
  673. Clipboard = new WindowsClipboard ();
  674. } else {
  675. Clipboard = new FakeDriver.FakeClipboard ();
  676. }
  677. if (!RunningUnitTests) {
  678. _isWindowsTerminal = GetParentProcessName () == "WindowsTerminal";
  679. }
  680. }
  681. private static string GetParentProcessName ()
  682. {
  683. #pragma warning disable CA1416 // Validate platform compatibility
  684. var myId = Process.GetCurrentProcess ().Id;
  685. var query = string.Format ($"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {myId}");
  686. var search = new ManagementObjectSearcher ("root\\CIMV2", query);
  687. var queryObj = search.Get ().OfType<ManagementBaseObject> ().FirstOrDefault ();
  688. if (queryObj == null) {
  689. return null;
  690. }
  691. var parentId = (uint)queryObj ["ParentProcessId"];
  692. var parent = Process.GetProcessById ((int)parentId);
  693. var prevParent = parent;
  694. // Check if the parent is from other parent
  695. while (queryObj != null) {
  696. query = string.Format ($"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {parentId}");
  697. search = new ManagementObjectSearcher ("root\\CIMV2", query);
  698. queryObj = search.Get ().OfType<ManagementBaseObject> ().FirstOrDefault ();
  699. if (queryObj == null) {
  700. return parent.ProcessName;
  701. }
  702. parentId = (uint)queryObj ["ParentProcessId"];
  703. try {
  704. parent = Process.GetProcessById ((int)parentId);
  705. if (string.Equals (parent.ProcessName, "explorer", StringComparison.InvariantCultureIgnoreCase)) {
  706. return prevParent.ProcessName;
  707. }
  708. prevParent = parent;
  709. } catch (ArgumentException) {
  710. return prevParent.ProcessName;
  711. }
  712. }
  713. return parent.ProcessName;
  714. #pragma warning restore CA1416 // Validate platform compatibility
  715. }
  716. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  717. {
  718. _keyHandler = keyHandler;
  719. _keyDownHandler = keyDownHandler;
  720. _keyUpHandler = keyUpHandler;
  721. _mouseHandler = mouseHandler;
  722. var mLoop = mainLoop.MainLoopDriver as WindowsMainLoop;
  723. mLoop.ProcessInput = (e) => ProcessInput (e);
  724. mLoop.WinChanged = (s, e) => {
  725. ChangeWin (e.Size);
  726. };
  727. }
  728. private void ChangeWin (Size e)
  729. {
  730. var w = e.Width;
  731. if (w == Cols - 3 && e.Height < Rows) {
  732. w += 3;
  733. }
  734. Left = 0;
  735. Top = 0;
  736. Cols = e.Width;
  737. Rows = e.Height;
  738. if (!RunningUnitTests) {
  739. var newSize = WinConsole.SetConsoleWindow (
  740. (short)Math.Max (w, 16), (short)Math.Max (e.Height, 0));
  741. Cols = newSize.Width;
  742. Rows = newSize.Height;
  743. }
  744. ResizeScreen ();
  745. ClearContents ();
  746. TerminalResized.Invoke ();
  747. }
  748. void ProcessInput (WindowsConsole.InputRecord inputEvent)
  749. {
  750. switch (inputEvent.EventType) {
  751. case WindowsConsole.EventType.Key:
  752. var fromPacketKey = inputEvent.KeyEvent.wVirtualKeyCode == (uint)ConsoleKey.Packet;
  753. if (fromPacketKey) {
  754. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  755. }
  756. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  757. //var ke = inputEvent.KeyEvent;
  758. //System.Diagnostics.Debug.WriteLine ($"fromPacketKey: {fromPacketKey}");
  759. //if (ke.UnicodeChar == '\0') {
  760. // System.Diagnostics.Debug.WriteLine ("UnicodeChar: 0'\\0'");
  761. //} else if (ke.UnicodeChar == 13) {
  762. // System.Diagnostics.Debug.WriteLine ("UnicodeChar: 13'\\n'");
  763. //} else {
  764. // System.Diagnostics.Debug.WriteLine ($"UnicodeChar: {(uint)ke.UnicodeChar}'{ke.UnicodeChar}'");
  765. //}
  766. //System.Diagnostics.Debug.WriteLine ($"bKeyDown: {ke.bKeyDown}");
  767. //System.Diagnostics.Debug.WriteLine ($"dwControlKeyState: {ke.dwControlKeyState}");
  768. //System.Diagnostics.Debug.WriteLine ($"wRepeatCount: {ke.wRepeatCount}");
  769. //System.Diagnostics.Debug.WriteLine ($"wVirtualKeyCode: {ke.wVirtualKeyCode}");
  770. //System.Diagnostics.Debug.WriteLine ($"wVirtualScanCode: {ke.wVirtualScanCode}");
  771. if (map == (Key)0xffffffff) {
  772. KeyEvent key = new KeyEvent ();
  773. // Shift = VK_SHIFT = 0x10
  774. // Ctrl = VK_CONTROL = 0x11
  775. // Alt = VK_MENU = 0x12
  776. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
  777. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
  778. }
  779. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
  780. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
  781. }
  782. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
  783. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
  784. }
  785. switch (inputEvent.KeyEvent.dwControlKeyState) {
  786. case WindowsConsole.ControlKeyState.RightAltPressed:
  787. case WindowsConsole.ControlKeyState.RightAltPressed |
  788. WindowsConsole.ControlKeyState.LeftControlPressed |
  789. WindowsConsole.ControlKeyState.EnhancedKey:
  790. case WindowsConsole.ControlKeyState.EnhancedKey:
  791. key = new KeyEvent (Key.CtrlMask | Key.AltMask, _keyModifiers);
  792. break;
  793. case WindowsConsole.ControlKeyState.LeftAltPressed:
  794. key = new KeyEvent (Key.AltMask, _keyModifiers);
  795. break;
  796. case WindowsConsole.ControlKeyState.RightControlPressed:
  797. case WindowsConsole.ControlKeyState.LeftControlPressed:
  798. key = new KeyEvent (Key.CtrlMask, _keyModifiers);
  799. break;
  800. case WindowsConsole.ControlKeyState.ShiftPressed:
  801. key = new KeyEvent (Key.ShiftMask, _keyModifiers);
  802. break;
  803. case WindowsConsole.ControlKeyState.NumlockOn:
  804. break;
  805. case WindowsConsole.ControlKeyState.ScrolllockOn:
  806. break;
  807. case WindowsConsole.ControlKeyState.CapslockOn:
  808. break;
  809. default:
  810. key = inputEvent.KeyEvent.wVirtualKeyCode switch {
  811. 0x10 => new KeyEvent (Key.ShiftMask, _keyModifiers),
  812. 0x11 => new KeyEvent (Key.CtrlMask, _keyModifiers),
  813. 0x12 => new KeyEvent (Key.AltMask, _keyModifiers),
  814. _ => new KeyEvent (Key.Unknown, _keyModifiers)
  815. };
  816. break;
  817. }
  818. if (inputEvent.KeyEvent.bKeyDown) {
  819. _keyDownHandler (key);
  820. } else {
  821. _keyUpHandler (key);
  822. }
  823. } else {
  824. if (inputEvent.KeyEvent.bKeyDown) {
  825. // May occurs using SendKeys
  826. _keyModifiers ??= new KeyModifiers ();
  827. // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
  828. _keyDownHandler (new KeyEvent (map, _keyModifiers));
  829. _keyHandler (new KeyEvent (map, _keyModifiers));
  830. } else {
  831. _keyUpHandler (new KeyEvent (map, _keyModifiers));
  832. }
  833. }
  834. if (!inputEvent.KeyEvent.bKeyDown && inputEvent.KeyEvent.dwControlKeyState == 0) {
  835. _keyModifiers = null;
  836. }
  837. break;
  838. case WindowsConsole.EventType.Mouse:
  839. var me = ToDriverMouse (inputEvent.MouseEvent);
  840. _mouseHandler (me);
  841. if (_processButtonClick) {
  842. _mouseHandler (
  843. new MouseEvent () {
  844. X = me.X,
  845. Y = me.Y,
  846. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  847. });
  848. }
  849. break;
  850. case WindowsConsole.EventType.Focus:
  851. break;
  852. }
  853. }
  854. WindowsConsole.ButtonState? _lastMouseButtonPressed = null;
  855. bool _isButtonPressed = false;
  856. bool _isButtonReleased = false;
  857. bool _isButtonDoubleClicked = false;
  858. Point? _point;
  859. Point _pointMove;
  860. bool _isOneFingerDoubleClicked = false;
  861. bool _processButtonClick;
  862. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  863. {
  864. MouseFlags mouseFlag = MouseFlags.AllEvents;
  865. //System.Diagnostics.Debug.WriteLine (
  866. // $"X:{mouseEvent.MousePosition.X};Y:{mouseEvent.MousePosition.Y};ButtonState:{mouseEvent.ButtonState};EventFlags:{mouseEvent.EventFlags}");
  867. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked) {
  868. Application.MainLoop.AddIdle (() => {
  869. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  870. return false;
  871. });
  872. }
  873. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  874. // This will tell when a mouse button is pressed. When the button is released this event will
  875. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  876. // To map to the correct driver events we save the last pressed mouse button so we can
  877. // map to the correct clicked event.
  878. if ((_lastMouseButtonPressed != null || _isButtonReleased) && mouseEvent.ButtonState != 0) {
  879. _lastMouseButtonPressed = null;
  880. //isButtonPressed = false;
  881. _isButtonReleased = false;
  882. }
  883. var p = new Point () {
  884. X = mouseEvent.MousePosition.X,
  885. Y = mouseEvent.MousePosition.Y
  886. };
  887. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed == null && !_isButtonDoubleClicked) ||
  888. (_lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) &&
  889. mouseEvent.ButtonState != 0 && !_isButtonReleased && !_isButtonDoubleClicked)) {
  890. switch (mouseEvent.ButtonState) {
  891. case WindowsConsole.ButtonState.Button1Pressed:
  892. mouseFlag = MouseFlags.Button1Pressed;
  893. break;
  894. case WindowsConsole.ButtonState.Button2Pressed:
  895. mouseFlag = MouseFlags.Button2Pressed;
  896. break;
  897. case WindowsConsole.ButtonState.RightmostButtonPressed:
  898. mouseFlag = MouseFlags.Button3Pressed;
  899. break;
  900. }
  901. if (_point == null) {
  902. _point = p;
  903. }
  904. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  905. mouseFlag |= MouseFlags.ReportMousePosition;
  906. _isButtonReleased = false;
  907. _processButtonClick = false;
  908. }
  909. _lastMouseButtonPressed = mouseEvent.ButtonState;
  910. _isButtonPressed = true;
  911. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  912. Application.MainLoop.AddIdle (() => {
  913. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  914. return false;
  915. });
  916. }
  917. } else if (_lastMouseButtonPressed != null && mouseEvent.EventFlags == 0
  918. && !_isButtonReleased && !_isButtonDoubleClicked && !_isOneFingerDoubleClicked) {
  919. switch (_lastMouseButtonPressed) {
  920. case WindowsConsole.ButtonState.Button1Pressed:
  921. mouseFlag = MouseFlags.Button1Released;
  922. break;
  923. case WindowsConsole.ButtonState.Button2Pressed:
  924. mouseFlag = MouseFlags.Button2Released;
  925. break;
  926. case WindowsConsole.ButtonState.RightmostButtonPressed:
  927. mouseFlag = MouseFlags.Button3Released;
  928. break;
  929. }
  930. _isButtonPressed = false;
  931. _isButtonReleased = true;
  932. if (_point != null && (((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)) {
  933. _processButtonClick = true;
  934. } else {
  935. _point = null;
  936. }
  937. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  938. && !_isOneFingerDoubleClicked && _isButtonReleased && p == _point) {
  939. mouseFlag = ProcessButtonClick (mouseEvent);
  940. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  941. switch (mouseEvent.ButtonState) {
  942. case WindowsConsole.ButtonState.Button1Pressed:
  943. mouseFlag = MouseFlags.Button1DoubleClicked;
  944. break;
  945. case WindowsConsole.ButtonState.Button2Pressed:
  946. mouseFlag = MouseFlags.Button2DoubleClicked;
  947. break;
  948. case WindowsConsole.ButtonState.RightmostButtonPressed:
  949. mouseFlag = MouseFlags.Button3DoubleClicked;
  950. break;
  951. }
  952. _isButtonDoubleClicked = true;
  953. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked) {
  954. switch (mouseEvent.ButtonState) {
  955. case WindowsConsole.ButtonState.Button1Pressed:
  956. mouseFlag = MouseFlags.Button1TripleClicked;
  957. break;
  958. case WindowsConsole.ButtonState.Button2Pressed:
  959. mouseFlag = MouseFlags.Button2TripleClicked;
  960. break;
  961. case WindowsConsole.ButtonState.RightmostButtonPressed:
  962. mouseFlag = MouseFlags.Button3TripleClicked;
  963. break;
  964. }
  965. _isButtonDoubleClicked = false;
  966. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  967. switch ((int)mouseEvent.ButtonState) {
  968. case int v when v > 0:
  969. mouseFlag = MouseFlags.WheeledUp;
  970. break;
  971. case int v when v < 0:
  972. mouseFlag = MouseFlags.WheeledDown;
  973. break;
  974. }
  975. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  976. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  977. switch ((int)mouseEvent.ButtonState) {
  978. case int v when v > 0:
  979. mouseFlag = MouseFlags.WheeledLeft;
  980. break;
  981. case int v when v < 0:
  982. mouseFlag = MouseFlags.WheeledRight;
  983. break;
  984. }
  985. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled) {
  986. switch ((int)mouseEvent.ButtonState) {
  987. case int v when v < 0:
  988. mouseFlag = MouseFlags.WheeledLeft;
  989. break;
  990. case int v when v > 0:
  991. mouseFlag = MouseFlags.WheeledRight;
  992. break;
  993. }
  994. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  995. mouseFlag = MouseFlags.ReportMousePosition;
  996. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y) {
  997. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  998. }
  999. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  1000. mouseFlag = 0;
  1001. }
  1002. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  1003. //System.Diagnostics.Debug.WriteLine (
  1004. // $"point.X:{(point != null ? ((Point)point).X : -1)};point.Y:{(point != null ? ((Point)point).Y : -1)}");
  1005. return new MouseEvent () {
  1006. X = mouseEvent.MousePosition.X,
  1007. Y = mouseEvent.MousePosition.Y,
  1008. Flags = mouseFlag
  1009. };
  1010. }
  1011. MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  1012. {
  1013. MouseFlags mouseFlag = 0;
  1014. switch (_lastMouseButtonPressed) {
  1015. case WindowsConsole.ButtonState.Button1Pressed:
  1016. mouseFlag = MouseFlags.Button1Clicked;
  1017. break;
  1018. case WindowsConsole.ButtonState.Button2Pressed:
  1019. mouseFlag = MouseFlags.Button2Clicked;
  1020. break;
  1021. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1022. mouseFlag = MouseFlags.Button3Clicked;
  1023. break;
  1024. }
  1025. _point = new Point () {
  1026. X = mouseEvent.MousePosition.X,
  1027. Y = mouseEvent.MousePosition.Y
  1028. };
  1029. _lastMouseButtonPressed = null;
  1030. _isButtonReleased = false;
  1031. _processButtonClick = false;
  1032. _point = null;
  1033. return mouseFlag;
  1034. }
  1035. async Task ProcessButtonDoubleClickedAsync ()
  1036. {
  1037. await Task.Delay (300);
  1038. _isButtonDoubleClicked = false;
  1039. _isOneFingerDoubleClicked = false;
  1040. //buttonPressedCount = 0;
  1041. }
  1042. async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1043. {
  1044. while (_isButtonPressed) {
  1045. await Task.Delay (100);
  1046. var me = new MouseEvent () {
  1047. X = _pointMove.X,
  1048. Y = _pointMove.Y,
  1049. Flags = mouseFlag
  1050. };
  1051. var view = Application.WantContinuousButtonPressedView;
  1052. if (view == null) {
  1053. break;
  1054. }
  1055. if (_isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1056. Application.MainLoop.Invoke (() => _mouseHandler (me));
  1057. }
  1058. }
  1059. }
  1060. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1061. {
  1062. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  1063. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)) {
  1064. mouseFlag |= MouseFlags.ButtonCtrl;
  1065. }
  1066. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1067. mouseFlag |= MouseFlags.ButtonShift;
  1068. }
  1069. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1070. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1071. mouseFlag |= MouseFlags.ButtonAlt;
  1072. }
  1073. return mouseFlag;
  1074. }
  1075. KeyModifiers _keyModifiers;
  1076. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1077. {
  1078. var state = keyEvent.dwControlKeyState;
  1079. var shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1080. var alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1081. var control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1082. var capsLock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  1083. var numLock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  1084. var scrollLock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  1085. _keyModifiers ??= new KeyModifiers ();
  1086. if (shift) {
  1087. _keyModifiers.Shift = true;
  1088. }
  1089. if (alt) {
  1090. _keyModifiers.Alt = true;
  1091. }
  1092. if (control) {
  1093. _keyModifiers.Ctrl = true;
  1094. }
  1095. if (capsLock) {
  1096. _keyModifiers.Capslock = true;
  1097. }
  1098. if (numLock) {
  1099. _keyModifiers.Numlock = true;
  1100. }
  1101. if (scrollLock) {
  1102. _keyModifiers.Scrolllock = true;
  1103. }
  1104. var consoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1105. return new WindowsConsole.ConsoleKeyInfoEx (consoleKeyInfo, capsLock, numLock, scrollLock);
  1106. }
  1107. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  1108. {
  1109. if (keyEvent.wVirtualKeyCode != (uint)ConsoleKey.Packet) {
  1110. return keyEvent;
  1111. }
  1112. var mod = new ConsoleModifiers ();
  1113. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1114. mod |= ConsoleModifiers.Shift;
  1115. }
  1116. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1117. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1118. mod |= ConsoleModifiers.Alt;
  1119. }
  1120. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed) ||
  1121. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)) {
  1122. mod |= ConsoleModifiers.Control;
  1123. }
  1124. var keyChar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyEvent.UnicodeChar, mod, out uint virtualKey, out uint scanCode);
  1125. return new WindowsConsole.KeyEventRecord {
  1126. UnicodeChar = (char)keyChar,
  1127. bKeyDown = keyEvent.bKeyDown,
  1128. dwControlKeyState = keyEvent.dwControlKeyState,
  1129. wRepeatCount = keyEvent.wRepeatCount,
  1130. wVirtualKeyCode = (ushort)virtualKey,
  1131. wVirtualScanCode = (ushort)scanCode
  1132. };
  1133. }
  1134. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  1135. {
  1136. var keyInfo = keyInfoEx.ConsoleKeyInfo;
  1137. switch (keyInfo.Key) {
  1138. case ConsoleKey.Escape:
  1139. return MapKeyModifiers (keyInfo, Key.Esc);
  1140. case ConsoleKey.Tab:
  1141. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  1142. case ConsoleKey.Clear:
  1143. return MapKeyModifiers (keyInfo, Key.Clear);
  1144. case ConsoleKey.Home:
  1145. return MapKeyModifiers (keyInfo, Key.Home);
  1146. case ConsoleKey.End:
  1147. return MapKeyModifiers (keyInfo, Key.End);
  1148. case ConsoleKey.LeftArrow:
  1149. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  1150. case ConsoleKey.RightArrow:
  1151. return MapKeyModifiers (keyInfo, Key.CursorRight);
  1152. case ConsoleKey.UpArrow:
  1153. return MapKeyModifiers (keyInfo, Key.CursorUp);
  1154. case ConsoleKey.DownArrow:
  1155. return MapKeyModifiers (keyInfo, Key.CursorDown);
  1156. case ConsoleKey.PageUp:
  1157. return MapKeyModifiers (keyInfo, Key.PageUp);
  1158. case ConsoleKey.PageDown:
  1159. return MapKeyModifiers (keyInfo, Key.PageDown);
  1160. case ConsoleKey.Enter:
  1161. return MapKeyModifiers (keyInfo, Key.Enter);
  1162. case ConsoleKey.Spacebar:
  1163. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  1164. case ConsoleKey.Backspace:
  1165. return MapKeyModifiers (keyInfo, Key.Backspace);
  1166. case ConsoleKey.Delete:
  1167. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  1168. case ConsoleKey.Insert:
  1169. return MapKeyModifiers (keyInfo, Key.InsertChar);
  1170. case ConsoleKey.PrintScreen:
  1171. return MapKeyModifiers (keyInfo, Key.PrintScreen);
  1172. case ConsoleKey.NumPad0:
  1173. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  1174. case ConsoleKey.NumPad1:
  1175. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  1176. case ConsoleKey.NumPad2:
  1177. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  1178. case ConsoleKey.NumPad3:
  1179. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  1180. case ConsoleKey.NumPad4:
  1181. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  1182. case ConsoleKey.NumPad5:
  1183. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  1184. case ConsoleKey.NumPad6:
  1185. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  1186. case ConsoleKey.NumPad7:
  1187. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  1188. case ConsoleKey.NumPad8:
  1189. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  1190. case ConsoleKey.NumPad9:
  1191. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  1192. case ConsoleKey.Oem1:
  1193. case ConsoleKey.Oem2:
  1194. case ConsoleKey.Oem3:
  1195. case ConsoleKey.Oem4:
  1196. case ConsoleKey.Oem5:
  1197. case ConsoleKey.Oem6:
  1198. case ConsoleKey.Oem7:
  1199. case ConsoleKey.Oem8:
  1200. case ConsoleKey.Oem102:
  1201. case ConsoleKey.OemPeriod:
  1202. case ConsoleKey.OemComma:
  1203. case ConsoleKey.OemPlus:
  1204. case ConsoleKey.OemMinus:
  1205. if (keyInfo.KeyChar == 0) {
  1206. return Key.Unknown;
  1207. }
  1208. return (Key)((uint)keyInfo.KeyChar);
  1209. }
  1210. var key = keyInfo.Key;
  1211. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  1212. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  1213. var delta = key - ConsoleKey.A;
  1214. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1215. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1216. }
  1217. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1218. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1219. }
  1220. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1221. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1222. }
  1223. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1224. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1225. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1226. }
  1227. }
  1228. //return (Key)((uint)alphaBase + delta);
  1229. return (Key)((uint)keyInfo.KeyChar);
  1230. }
  1231. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1232. var delta = key - ConsoleKey.D0;
  1233. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1234. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1235. }
  1236. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1237. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1238. }
  1239. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1240. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1241. }
  1242. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1243. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30 || keyInfo.KeyChar == ((uint)Key.D0 + delta)) {
  1244. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1245. }
  1246. }
  1247. return (Key)((uint)keyInfo.KeyChar);
  1248. }
  1249. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1250. var delta = key - ConsoleKey.F1;
  1251. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1252. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1253. }
  1254. return (Key)((uint)Key.F1 + delta);
  1255. }
  1256. if (keyInfo.KeyChar != 0) {
  1257. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1258. }
  1259. return (Key)(0xffffffff);
  1260. }
  1261. private Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1262. {
  1263. Key keyMod = new Key ();
  1264. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0) {
  1265. keyMod = Key.ShiftMask;
  1266. }
  1267. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) {
  1268. keyMod |= Key.CtrlMask;
  1269. }
  1270. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0) {
  1271. keyMod |= Key.AltMask;
  1272. }
  1273. return keyMod != Key.Null ? keyMod | key : key;
  1274. }
  1275. public override bool IsRuneSupported (Rune rune)
  1276. {
  1277. return base.IsRuneSupported (rune) && rune.IsBmp;
  1278. }
  1279. public override void Init (Action terminalResized)
  1280. {
  1281. TerminalResized = terminalResized;
  1282. if (RunningUnitTests) {
  1283. return;
  1284. }
  1285. try {
  1286. if (WinConsole != null) {
  1287. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1288. Cols = winSize.Width;
  1289. Rows = winSize.Height;
  1290. }
  1291. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1292. // Needed for Windows Terminal
  1293. // ESC [ ? 1047 h Save cursor position and activate xterm alternative buffer (no backscroll)
  1294. // ESC [ ? 1047 l Restore cursor position and restore xterm working buffer (with backscroll)
  1295. // ESC [ ? 1048 h Save cursor position
  1296. // ESC [ ? 1048 l Restore cursor position
  1297. // ESC [ ? 1049 h Activate xterm alternative buffer (no backscroll)
  1298. // ESC [ ? 1049 l Restore xterm working buffer (with backscroll)
  1299. // Per Issue #2264 using the alternative screen buffer is required for Windows Terminal to not
  1300. // wipe out the backscroll buffer when the application exits.
  1301. if (_isWindowsTerminal) {
  1302. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  1303. }
  1304. } catch (Win32Exception e) {
  1305. // We are being run in an environment that does not support a console
  1306. // such as a unit test, or a pipe.
  1307. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  1308. WinConsole = null;
  1309. }
  1310. CurrentAttribute = MakeColor (Color.White, Color.Black);
  1311. InitializeColorSchemes ();
  1312. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1313. Clip = new Rect (0, 0, Cols, Rows);
  1314. _damageRegion = new WindowsConsole.SmallRect () {
  1315. Top = 0,
  1316. Left = 0,
  1317. Bottom = (short)Rows,
  1318. Right = (short)Cols
  1319. };
  1320. ClearContents ();
  1321. }
  1322. void ResizeScreen ()
  1323. {
  1324. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1325. Clip = new Rect (0, 0, Cols, Rows);
  1326. _damageRegion = new WindowsConsole.SmallRect () {
  1327. Top = 0,
  1328. Left = 0,
  1329. Bottom = (short)Rows,
  1330. Right = (short)Cols
  1331. };
  1332. _dirtyLines = new bool [Rows];
  1333. WinConsole?.ForceRefreshCursorVisibility ();
  1334. }
  1335. public override void UpdateScreen ()
  1336. {
  1337. var windowSize = WinConsole?.GetConsoleBufferWindow (out _) ?? new Size (Cols, Rows);
  1338. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows)) {
  1339. return;
  1340. }
  1341. var bufferCoords = new WindowsConsole.Coord () {
  1342. X = (short)Clip.Width,
  1343. Y = (short)Clip.Height
  1344. };
  1345. for (int row = 0; row < Rows; row++) {
  1346. if (!_dirtyLines [row]) {
  1347. continue;
  1348. }
  1349. _dirtyLines [row] = false;
  1350. for (int col = 0; col < Cols; col++) {
  1351. int position = row * Cols + col;
  1352. _outputBuffer [position].Attribute = Contents [row, col].Attribute.GetValueOrDefault ();
  1353. if (Contents [row, col].IsDirty == false) {
  1354. _outputBuffer [position].Empty = true;
  1355. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1356. continue;
  1357. }
  1358. _outputBuffer [position].Empty = false;
  1359. if (Contents [row, col].Runes [0].IsBmp) {
  1360. _outputBuffer [position].Char = (char)Contents [row, col].Runes [0].Value;
  1361. } else {
  1362. //_outputBuffer [position].Empty = true;
  1363. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1364. if (Contents [row, col].Runes [0].GetColumns () > 1 && col + 1 < Cols) {
  1365. // TODO: This is a hack to deal with non-BMP and wide characters.
  1366. col++;
  1367. position = row * Cols + col;
  1368. _outputBuffer [position].Empty = false;
  1369. _outputBuffer [position].Char = ' ';
  1370. }
  1371. }
  1372. }
  1373. }
  1374. _damageRegion = new WindowsConsole.SmallRect () {
  1375. Top = 0,
  1376. Left = 0,
  1377. Bottom = (short)Rows,
  1378. Right = (short)Cols
  1379. };
  1380. if (!RunningUnitTests && WinConsole != null && !WinConsole.WriteToConsole (new Size (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors)) {
  1381. var err = Marshal.GetLastWin32Error ();
  1382. if (err != 0) {
  1383. throw new System.ComponentModel.Win32Exception (err);
  1384. }
  1385. }
  1386. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1387. }
  1388. public override void Refresh ()
  1389. {
  1390. UpdateScreen ();
  1391. WinConsole?.SetInitialCursorVisibility ();
  1392. UpdateCursor ();
  1393. }
  1394. #region Color Handling
  1395. /// <summary>
  1396. /// In the WindowsDriver, colors are encoded as an int.
  1397. /// The background color is stored in the least significant 4 bits,
  1398. /// and the foreground color is stored in the next 4 bits.
  1399. /// </summary>
  1400. public override Attribute MakeColor (Color foreground, Color background)
  1401. {
  1402. // Encode the colors into the int value.
  1403. return new Attribute (
  1404. value: (((int)foreground) | ((int)background << 4)),
  1405. foreground: foreground,
  1406. background: background
  1407. );
  1408. }
  1409. /// <summary>
  1410. /// Extracts the foreground and background colors from the encoded value.
  1411. /// Assumes a 4-bit encoded value for both foreground and background colors.
  1412. /// </summary>
  1413. internal override void GetColors (int value, out Color foreground, out Color background)
  1414. {
  1415. // Assume a 4-bit encoded value for both foreground and background colors.
  1416. foreground = (Color)((value >> 16) & 0xF);
  1417. background = (Color)(value & 0xF);
  1418. }
  1419. #endregion
  1420. CursorVisibility _cachedCursorVisibility;
  1421. public override void UpdateCursor ()
  1422. {
  1423. if (Col < 0 || Row < 0 || Col > Cols || Row > Rows) {
  1424. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1425. _cachedCursorVisibility = cursorVisibility;
  1426. SetCursorVisibility (CursorVisibility.Invisible);
  1427. return;
  1428. }
  1429. SetCursorVisibility (_cachedCursorVisibility);
  1430. var position = new WindowsConsole.Coord () {
  1431. X = (short)Col,
  1432. Y = (short)Row
  1433. };
  1434. WinConsole?.SetCursorPosition (position);
  1435. }
  1436. /// <inheritdoc/>
  1437. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1438. {
  1439. if (WinConsole != null) {
  1440. return WinConsole.GetCursorVisibility (out visibility);
  1441. }
  1442. visibility = _cachedCursorVisibility;
  1443. return true;
  1444. }
  1445. /// <inheritdoc/>
  1446. public override bool SetCursorVisibility (CursorVisibility visibility)
  1447. {
  1448. _cachedCursorVisibility = visibility;
  1449. return WinConsole == null || WinConsole.SetCursorVisibility (visibility);
  1450. }
  1451. /// <inheritdoc/>
  1452. public override bool EnsureCursorVisibility ()
  1453. {
  1454. return WinConsole == null || WinConsole.EnsureCursorVisibility ();
  1455. }
  1456. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1457. {
  1458. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1459. EventType = WindowsConsole.EventType.Key
  1460. };
  1461. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1462. bKeyDown = true
  1463. };
  1464. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1465. if (shift) {
  1466. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1467. keyEvent.UnicodeChar = '\0';
  1468. keyEvent.wVirtualKeyCode = 16;
  1469. }
  1470. if (alt) {
  1471. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1472. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1473. keyEvent.UnicodeChar = '\0';
  1474. keyEvent.wVirtualKeyCode = 18;
  1475. }
  1476. if (control) {
  1477. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1478. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1479. keyEvent.UnicodeChar = '\0';
  1480. keyEvent.wVirtualKeyCode = 17;
  1481. }
  1482. keyEvent.dwControlKeyState = controlKey;
  1483. input.KeyEvent = keyEvent;
  1484. if (shift || alt || control) {
  1485. ProcessInput (input);
  1486. }
  1487. keyEvent.UnicodeChar = keyChar;
  1488. if ((uint)key < 255) {
  1489. keyEvent.wVirtualKeyCode = (ushort)key;
  1490. } else {
  1491. keyEvent.wVirtualKeyCode = '\0';
  1492. }
  1493. input.KeyEvent = keyEvent;
  1494. try {
  1495. ProcessInput (input);
  1496. } catch (OverflowException) { } finally {
  1497. keyEvent.bKeyDown = false;
  1498. input.KeyEvent = keyEvent;
  1499. ProcessInput (input);
  1500. }
  1501. }
  1502. public override void End ()
  1503. {
  1504. WinConsole?.Cleanup ();
  1505. WinConsole = null;
  1506. if (!RunningUnitTests && _isWindowsTerminal) {
  1507. // Disable alternative screen buffer.
  1508. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndActivateAltBufferWithBackscroll);
  1509. }
  1510. }
  1511. #region Not Implemented
  1512. public override void Suspend ()
  1513. {
  1514. throw new NotImplementedException ();
  1515. }
  1516. #endregion
  1517. }
  1518. /// <summary>
  1519. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1520. /// only be used on Windows.
  1521. /// </summary>
  1522. /// <remarks>
  1523. /// This implementation is used for WindowsDriver.
  1524. /// </remarks>
  1525. internal class WindowsMainLoop : IMainLoopDriver {
  1526. ManualResetEventSlim _eventReady = new ManualResetEventSlim (false);
  1527. ManualResetEventSlim _waitForProbe = new ManualResetEventSlim (false);
  1528. ManualResetEventSlim _winChange = new ManualResetEventSlim (false);
  1529. MainLoop _mainLoop;
  1530. ConsoleDriver _consoleDriver;
  1531. WindowsConsole _winConsole;
  1532. bool _winChanged;
  1533. Size _windowSize;
  1534. CancellationTokenSource _tokenSource = new CancellationTokenSource ();
  1535. // The records that we keep fetching
  1536. Queue<WindowsConsole.InputRecord []> _resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1537. /// <summary>
  1538. /// Invoked when a Key is pressed or released.
  1539. /// </summary>
  1540. public Action<WindowsConsole.InputRecord> ProcessInput;
  1541. /// <summary>
  1542. /// Invoked when the window is changed.
  1543. /// </summary>
  1544. public EventHandler<SizeChangedEventArgs> WinChanged;
  1545. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1546. {
  1547. _consoleDriver = consoleDriver ?? throw new ArgumentNullException ("Console driver instance must be provided.");
  1548. _winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1549. }
  1550. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1551. {
  1552. _mainLoop = mainLoop;
  1553. Task.Run (WindowsInputHandler);
  1554. Task.Run (CheckWinChange);
  1555. }
  1556. void WindowsInputHandler ()
  1557. {
  1558. while (true) {
  1559. _waitForProbe.Wait ();
  1560. _waitForProbe.Reset ();
  1561. if (_resultQueue?.Count == 0) {
  1562. _resultQueue.Enqueue (_winConsole.ReadConsoleInput ());
  1563. }
  1564. _eventReady.Set ();
  1565. }
  1566. }
  1567. void CheckWinChange ()
  1568. {
  1569. while (true) {
  1570. _winChange.Wait ();
  1571. _winChange.Reset ();
  1572. WaitWinChange ();
  1573. _winChanged = true;
  1574. _eventReady.Set ();
  1575. }
  1576. }
  1577. void WaitWinChange ()
  1578. {
  1579. while (true) {
  1580. Task.Delay (500).Wait ();
  1581. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  1582. if (_windowSize != Size.Empty && (_windowSize.Width != _consoleDriver.Cols
  1583. || _windowSize.Height != _consoleDriver.Rows)) {
  1584. return;
  1585. }
  1586. }
  1587. }
  1588. void IMainLoopDriver.Wakeup ()
  1589. {
  1590. //tokenSource.Cancel ();
  1591. _eventReady.Set ();
  1592. }
  1593. bool IMainLoopDriver.EventsPending (bool wait)
  1594. {
  1595. _waitForProbe.Set ();
  1596. _winChange.Set ();
  1597. if (CheckTimers (wait, out var waitTimeout)) {
  1598. return true;
  1599. }
  1600. try {
  1601. if (!_tokenSource.IsCancellationRequested) {
  1602. _eventReady.Wait (waitTimeout, _tokenSource.Token);
  1603. }
  1604. } catch (OperationCanceledException) {
  1605. return true;
  1606. } finally {
  1607. _eventReady.Reset ();
  1608. }
  1609. if (!_tokenSource.IsCancellationRequested) {
  1610. return _resultQueue.Count > 0 || CheckTimers (wait, out _) || _winChanged;
  1611. }
  1612. _tokenSource.Dispose ();
  1613. _tokenSource = new CancellationTokenSource ();
  1614. return true;
  1615. }
  1616. bool CheckTimers (bool wait, out int waitTimeout)
  1617. {
  1618. long now = DateTime.UtcNow.Ticks;
  1619. if (_mainLoop.timeouts.Count > 0) {
  1620. waitTimeout = (int)((_mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1621. if (waitTimeout < 0)
  1622. return true;
  1623. } else {
  1624. waitTimeout = -1;
  1625. }
  1626. if (!wait)
  1627. waitTimeout = 0;
  1628. int ic;
  1629. lock (_mainLoop.idleHandlers) {
  1630. ic = _mainLoop.idleHandlers.Count;
  1631. }
  1632. return ic > 0;
  1633. }
  1634. void IMainLoopDriver.Iteration ()
  1635. {
  1636. while (_resultQueue.Count > 0) {
  1637. var inputRecords = _resultQueue.Dequeue ();
  1638. if (inputRecords != null && inputRecords.Length > 0) {
  1639. var inputEvent = inputRecords [0];
  1640. ProcessInput?.Invoke (inputEvent);
  1641. }
  1642. }
  1643. if (_winChanged) {
  1644. _winChanged = false;
  1645. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  1646. }
  1647. }
  1648. }
  1649. class WindowsClipboard : ClipboardBase {
  1650. public WindowsClipboard ()
  1651. {
  1652. IsSupported = IsClipboardFormatAvailable (_cfUnicodeText);
  1653. }
  1654. public override bool IsSupported { get; }
  1655. protected override string GetClipboardDataImpl ()
  1656. {
  1657. try {
  1658. if (!OpenClipboard (IntPtr.Zero)) {
  1659. return string.Empty;
  1660. }
  1661. IntPtr handle = GetClipboardData (_cfUnicodeText);
  1662. if (handle == IntPtr.Zero) {
  1663. return string.Empty;
  1664. }
  1665. IntPtr pointer = IntPtr.Zero;
  1666. try {
  1667. pointer = GlobalLock (handle);
  1668. if (pointer == IntPtr.Zero) {
  1669. return string.Empty;
  1670. }
  1671. int size = GlobalSize (handle);
  1672. byte [] buff = new byte [size];
  1673. Marshal.Copy (pointer, buff, 0, size);
  1674. return System.Text.Encoding.Unicode.GetString (buff).TrimEnd ('\0');
  1675. } finally {
  1676. if (pointer != IntPtr.Zero) {
  1677. GlobalUnlock (handle);
  1678. }
  1679. }
  1680. } finally {
  1681. CloseClipboard ();
  1682. }
  1683. }
  1684. protected override void SetClipboardDataImpl (string text)
  1685. {
  1686. OpenClipboard ();
  1687. EmptyClipboard ();
  1688. IntPtr hGlobal = default;
  1689. try {
  1690. var bytes = (text.Length + 1) * 2;
  1691. hGlobal = Marshal.AllocHGlobal (bytes);
  1692. if (hGlobal == default) {
  1693. ThrowWin32 ();
  1694. }
  1695. var target = GlobalLock (hGlobal);
  1696. if (target == default) {
  1697. ThrowWin32 ();
  1698. }
  1699. try {
  1700. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1701. } finally {
  1702. GlobalUnlock (target);
  1703. }
  1704. if (SetClipboardData (_cfUnicodeText, hGlobal) == default) {
  1705. ThrowWin32 ();
  1706. }
  1707. hGlobal = default;
  1708. } finally {
  1709. if (hGlobal != default) {
  1710. Marshal.FreeHGlobal (hGlobal);
  1711. }
  1712. CloseClipboard ();
  1713. }
  1714. }
  1715. void OpenClipboard ()
  1716. {
  1717. var num = 10;
  1718. while (true) {
  1719. if (OpenClipboard (default)) {
  1720. break;
  1721. }
  1722. if (--num == 0) {
  1723. ThrowWin32 ();
  1724. }
  1725. Thread.Sleep (100);
  1726. }
  1727. }
  1728. const uint _cfUnicodeText = 13;
  1729. void ThrowWin32 ()
  1730. {
  1731. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1732. }
  1733. [DllImport ("User32.dll", SetLastError = true)]
  1734. [return: MarshalAs (UnmanagedType.Bool)]
  1735. static extern bool IsClipboardFormatAvailable (uint format);
  1736. [DllImport ("kernel32.dll", SetLastError = true)]
  1737. static extern int GlobalSize (IntPtr handle);
  1738. [DllImport ("kernel32.dll", SetLastError = true)]
  1739. static extern IntPtr GlobalLock (IntPtr hMem);
  1740. [DllImport ("kernel32.dll", SetLastError = true)]
  1741. [return: MarshalAs (UnmanagedType.Bool)]
  1742. static extern bool GlobalUnlock (IntPtr hMem);
  1743. [DllImport ("user32.dll", SetLastError = true)]
  1744. [return: MarshalAs (UnmanagedType.Bool)]
  1745. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1746. [DllImport ("user32.dll", SetLastError = true)]
  1747. [return: MarshalAs (UnmanagedType.Bool)]
  1748. static extern bool CloseClipboard ();
  1749. [DllImport ("user32.dll", SetLastError = true)]
  1750. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1751. [DllImport ("user32.dll")]
  1752. static extern bool EmptyClipboard ();
  1753. [DllImport ("user32.dll", SetLastError = true)]
  1754. static extern IntPtr GetClipboardData (uint uFormat);
  1755. }