WindowsDriver.cs 63 KB

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