WindowsDriver.cs 64 KB

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