WindowsDriver.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145
  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. #pragma warning disable CA1416 // Validate platform compatibility
  1226. private static string GetParentProcessName ()
  1227. {
  1228. var myId = Process.GetCurrentProcess ().Id;
  1229. var query = string.Format ($"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {myId}");
  1230. var search = new ManagementObjectSearcher ("root\\CIMV2", query);
  1231. var queryObj = search.Get ().OfType<ManagementBaseObject> ().FirstOrDefault ();
  1232. if (queryObj == null) {
  1233. return null;
  1234. }
  1235. var parentId = (uint)queryObj ["ParentProcessId"];
  1236. var parent = Process.GetProcessById ((int)parentId);
  1237. var prevParent = parent;
  1238. // Check if the parent is from other parent
  1239. while (queryObj != null) {
  1240. query = string.Format ($"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {parentId}");
  1241. search = new ManagementObjectSearcher ("root\\CIMV2", query);
  1242. queryObj = search.Get ().OfType<ManagementBaseObject> ().FirstOrDefault ();
  1243. if (queryObj == null) {
  1244. return parent.ProcessName;
  1245. }
  1246. parentId = (uint)queryObj ["ParentProcessId"];
  1247. try {
  1248. parent = Process.GetProcessById ((int)parentId);
  1249. if (string.Equals (parent.ProcessName, "explorer", StringComparison.InvariantCultureIgnoreCase)) {
  1250. return prevParent.ProcessName;
  1251. }
  1252. prevParent = parent;
  1253. } catch (ArgumentException) {
  1254. return prevParent.ProcessName;
  1255. }
  1256. }
  1257. return parent.ProcessName;
  1258. }
  1259. #pragma warning restore CA1416 // Validate platform compatibility
  1260. public override void Init (Action terminalResized)
  1261. {
  1262. TerminalResized = terminalResized;
  1263. try {
  1264. // Needed for Windows Terminal
  1265. // ESC [ ? 1047 h Save cursor position and activate xterm alternative buffer (no backscroll)
  1266. // ESC [ ? 1047 l Restore cursor position and restore xterm working buffer (with backscroll)
  1267. // ESC [ ? 1048 h Save cursor position
  1268. // ESC [ ? 1048 l Restore cursor position
  1269. // ESC [ ? 1049 h Activate xterm alternative buffer (no backscroll)
  1270. // ESC [ ? 1049 l Restore xterm working buffer (with backscroll)
  1271. // Per Issue #2264 using the alternative screen buffer is required for Windows Terminal to not
  1272. // wipe out the backscroll buffer when the application exits.
  1273. if (string.Equals (GetParentProcessName (), "WindowsTerminal", StringComparison.InvariantCultureIgnoreCase)) {
  1274. Console.Out.Write ("\x1b[?1049h");
  1275. }
  1276. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1277. cols = winSize.Width;
  1278. rows = winSize.Height;
  1279. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1280. CurrentAttribute = MakeColor (Color.White, Color.Black);
  1281. InitalizeColorSchemes ();
  1282. CurrentAttribute = MakeColor (Color.White, Color.Black);
  1283. InitalizeColorSchemes ();
  1284. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  1285. Clip = new Rect (0, 0, Cols, Rows);
  1286. damageRegion = new WindowsConsole.SmallRect () {
  1287. Top = 0,
  1288. Left = 0,
  1289. Bottom = (short)Rows,
  1290. Right = (short)Cols
  1291. };
  1292. UpdateOffScreen ();
  1293. } catch (Win32Exception e) {
  1294. throw new InvalidOperationException ("The Windows Console output window is not available.", e);
  1295. }
  1296. }
  1297. public override void ResizeScreen ()
  1298. {
  1299. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  1300. Clip = new Rect (0, 0, Cols, Rows);
  1301. damageRegion = new WindowsConsole.SmallRect () {
  1302. Top = 0,
  1303. Left = 0,
  1304. Bottom = (short)Rows,
  1305. Right = (short)Cols
  1306. };
  1307. WinConsole.ForceRefreshCursorVisibility ();
  1308. }
  1309. public override void UpdateOffScreen ()
  1310. {
  1311. contents = new int [rows, cols, 3];
  1312. for (int row = 0; row < rows; row++) {
  1313. for (int col = 0; col < cols; col++) {
  1314. int position = row * cols + col;
  1315. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  1316. OutputBuffer [position].Char.UnicodeChar = ' ';
  1317. contents [row, col, 0] = OutputBuffer [position].Char.UnicodeChar;
  1318. contents [row, col, 1] = OutputBuffer [position].Attributes;
  1319. contents [row, col, 2] = 0;
  1320. }
  1321. }
  1322. }
  1323. int ccol, crow;
  1324. public override void Move (int col, int row)
  1325. {
  1326. ccol = col;
  1327. crow = row;
  1328. }
  1329. int GetOutputBufferPosition ()
  1330. {
  1331. return crow * Cols + ccol;
  1332. }
  1333. public override void AddRune (Rune rune)
  1334. {
  1335. rune = MakePrintable (rune);
  1336. var runeWidth = Rune.ColumnWidth (rune);
  1337. var position = GetOutputBufferPosition ();
  1338. var validClip = IsValidContent (ccol, crow, Clip);
  1339. if (validClip) {
  1340. if (runeWidth == 0 && ccol > 0) {
  1341. var r = contents [crow, ccol - 1, 0];
  1342. var s = new string (new char [] { (char)r, (char)rune });
  1343. string sn;
  1344. if (!s.IsNormalized ()) {
  1345. sn = s.Normalize ();
  1346. } else {
  1347. sn = s;
  1348. }
  1349. var c = sn [0];
  1350. var prevPosition = crow * Cols + (ccol - 1);
  1351. OutputBuffer [prevPosition].Char.UnicodeChar = c;
  1352. contents [crow, ccol - 1, 0] = c;
  1353. OutputBuffer [prevPosition].Attributes = (ushort)CurrentAttribute;
  1354. contents [crow, ccol - 1, 1] = CurrentAttribute;
  1355. contents [crow, ccol - 1, 2] = 1;
  1356. WindowsConsole.SmallRect.Update (ref damageRegion, (short)(ccol - 1), (short)crow);
  1357. } else {
  1358. if (runeWidth < 2 && ccol > 0
  1359. && Rune.ColumnWidth ((char)contents [crow, ccol - 1, 0]) > 1) {
  1360. var prevPosition = crow * Cols + (ccol - 1);
  1361. OutputBuffer [prevPosition].Char.UnicodeChar = ' ';
  1362. contents [crow, ccol - 1, 0] = (int)(uint)' ';
  1363. } else if (runeWidth < 2 && ccol <= Clip.Right - 1
  1364. && Rune.ColumnWidth ((char)contents [crow, ccol, 0]) > 1) {
  1365. var prevPosition = GetOutputBufferPosition () + 1;
  1366. OutputBuffer [prevPosition].Char.UnicodeChar = (char)' ';
  1367. contents [crow, ccol + 1, 0] = (int)(uint)' ';
  1368. }
  1369. if (runeWidth > 1 && ccol == Clip.Right - 1) {
  1370. OutputBuffer [position].Char.UnicodeChar = (char)' ';
  1371. contents [crow, ccol, 0] = (int)(uint)' ';
  1372. } else {
  1373. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  1374. contents [crow, ccol, 0] = (int)(uint)rune;
  1375. }
  1376. OutputBuffer [position].Attributes = (ushort)CurrentAttribute;
  1377. contents [crow, ccol, 1] = CurrentAttribute;
  1378. contents [crow, ccol, 2] = 1;
  1379. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  1380. }
  1381. }
  1382. if (runeWidth < 0 || runeWidth > 0) {
  1383. ccol++;
  1384. }
  1385. if (runeWidth > 1) {
  1386. if (validClip && ccol < Clip.Right) {
  1387. position = GetOutputBufferPosition ();
  1388. OutputBuffer [position].Attributes = (ushort)CurrentAttribute;
  1389. OutputBuffer [position].Char.UnicodeChar = (char)0x00;
  1390. contents [crow, ccol, 0] = (int)(uint)0x00;
  1391. contents [crow, ccol, 1] = CurrentAttribute;
  1392. contents [crow, ccol, 2] = 0;
  1393. }
  1394. ccol++;
  1395. }
  1396. if (sync) {
  1397. UpdateScreen ();
  1398. }
  1399. }
  1400. public override void AddStr (ustring str)
  1401. {
  1402. foreach (var rune in str)
  1403. AddRune (rune);
  1404. }
  1405. public override void SetAttribute (Attribute c)
  1406. {
  1407. base.SetAttribute (c);
  1408. }
  1409. public override Attribute MakeColor (Color foreground, Color background)
  1410. {
  1411. return MakeColor ((ConsoleColor)foreground, (ConsoleColor)background);
  1412. }
  1413. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  1414. {
  1415. // Encode the colors into the int value.
  1416. return new Attribute (
  1417. value: ((int)f | (int)b << 4),
  1418. foreground: (Color)f,
  1419. background: (Color)b
  1420. );
  1421. }
  1422. public override Attribute MakeAttribute (Color fore, Color back)
  1423. {
  1424. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  1425. }
  1426. public override void Refresh ()
  1427. {
  1428. UpdateScreen ();
  1429. WinConsole.SetInitialCursorVisibility ();
  1430. UpdateCursor ();
  1431. #if false
  1432. var bufferCoords = new WindowsConsole.Coord (){
  1433. X = (short)Clip.Width,
  1434. Y = (short)Clip.Height
  1435. };
  1436. var window = new WindowsConsole.SmallRect (){
  1437. Top = 0,
  1438. Left = 0,
  1439. Right = (short)Clip.Right,
  1440. Bottom = (short)Clip.Bottom
  1441. };
  1442. UpdateCursor();
  1443. WinConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  1444. #endif
  1445. }
  1446. public override void UpdateScreen ()
  1447. {
  1448. if (damageRegion.Left == -1)
  1449. return;
  1450. var windowSize = WinConsole.GetConsoleBufferWindow (out _);
  1451. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows))
  1452. return;
  1453. var bufferCoords = new WindowsConsole.Coord () {
  1454. X = (short)Clip.Width,
  1455. Y = (short)Clip.Height
  1456. };
  1457. WinConsole.WriteToConsole (new Size (Cols, Rows), OutputBuffer, bufferCoords, damageRegion);
  1458. // System.Diagnostics.Debugger.Log (0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  1459. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1460. }
  1461. CursorVisibility savedCursorVisibility;
  1462. public override void UpdateCursor ()
  1463. {
  1464. if (ccol < 0 || crow < 0 || ccol > Cols || crow > Rows) {
  1465. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1466. savedCursorVisibility = cursorVisibility;
  1467. SetCursorVisibility (CursorVisibility.Invisible);
  1468. return;
  1469. }
  1470. SetCursorVisibility (savedCursorVisibility);
  1471. var position = new WindowsConsole.Coord () {
  1472. X = (short)ccol,
  1473. Y = (short)crow
  1474. };
  1475. WinConsole.SetCursorPosition (position);
  1476. }
  1477. public override void End ()
  1478. {
  1479. WinConsole.Cleanup ();
  1480. WinConsole = null;
  1481. // Disable alternative screen buffer.
  1482. if (string.Equals (GetParentProcessName (), "WindowsTerminal", StringComparison.InvariantCultureIgnoreCase)) {
  1483. Console.Out.Write ("\x1b[?1049l");
  1484. }
  1485. }
  1486. /// <inheritdoc/>
  1487. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1488. {
  1489. return WinConsole.GetCursorVisibility (out visibility);
  1490. }
  1491. /// <inheritdoc/>
  1492. public override bool SetCursorVisibility (CursorVisibility visibility)
  1493. {
  1494. savedCursorVisibility = visibility;
  1495. return WinConsole.SetCursorVisibility (visibility);
  1496. }
  1497. /// <inheritdoc/>
  1498. public override bool EnsureCursorVisibility ()
  1499. {
  1500. return WinConsole.EnsureCursorVisibility ();
  1501. }
  1502. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1503. {
  1504. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1505. EventType = WindowsConsole.EventType.Key
  1506. };
  1507. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1508. bKeyDown = true
  1509. };
  1510. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1511. if (shift) {
  1512. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1513. keyEvent.UnicodeChar = '\0';
  1514. keyEvent.wVirtualKeyCode = 16;
  1515. }
  1516. if (alt) {
  1517. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1518. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1519. keyEvent.UnicodeChar = '\0';
  1520. keyEvent.wVirtualKeyCode = 18;
  1521. }
  1522. if (control) {
  1523. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1524. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1525. keyEvent.UnicodeChar = '\0';
  1526. keyEvent.wVirtualKeyCode = 17;
  1527. }
  1528. keyEvent.dwControlKeyState = controlKey;
  1529. input.KeyEvent = keyEvent;
  1530. if (shift || alt || control) {
  1531. ProcessInput (input);
  1532. }
  1533. keyEvent.UnicodeChar = keyChar;
  1534. if ((uint)key < 255) {
  1535. keyEvent.wVirtualKeyCode = (ushort)key;
  1536. } else {
  1537. keyEvent.wVirtualKeyCode = '\0';
  1538. }
  1539. input.KeyEvent = keyEvent;
  1540. try {
  1541. ProcessInput (input);
  1542. } catch (OverflowException) { } finally {
  1543. keyEvent.bKeyDown = false;
  1544. input.KeyEvent = keyEvent;
  1545. ProcessInput (input);
  1546. }
  1547. }
  1548. public override bool GetColors (int value, out Color foreground, out Color background)
  1549. {
  1550. bool hasColor = false;
  1551. foreground = default;
  1552. background = default;
  1553. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  1554. .OfType<ConsoleColor> ()
  1555. .Select (s => (int)s);
  1556. if (values.Contains ((value >> 4) & 0xffff)) {
  1557. hasColor = true;
  1558. background = (Color)(ConsoleColor)((value >> 4) & 0xffff);
  1559. }
  1560. if (values.Contains (value - ((int)background << 4))) {
  1561. hasColor = true;
  1562. foreground = (Color)(ConsoleColor)(value - ((int)background << 4));
  1563. }
  1564. return hasColor;
  1565. }
  1566. #region Unused
  1567. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1568. {
  1569. }
  1570. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1571. {
  1572. }
  1573. public override void Suspend ()
  1574. {
  1575. }
  1576. public override void StartReportingMouseMoves ()
  1577. {
  1578. }
  1579. public override void StopReportingMouseMoves ()
  1580. {
  1581. }
  1582. public override void UncookMouse ()
  1583. {
  1584. }
  1585. public override void CookMouse ()
  1586. {
  1587. }
  1588. #endregion
  1589. }
  1590. /// <summary>
  1591. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1592. /// only be used on Windows.
  1593. /// </summary>
  1594. /// <remarks>
  1595. /// This implementation is used for WindowsDriver.
  1596. /// </remarks>
  1597. internal class WindowsMainLoop : IMainLoopDriver {
  1598. ManualResetEventSlim eventReady = new ManualResetEventSlim (false);
  1599. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  1600. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  1601. MainLoop mainLoop;
  1602. ConsoleDriver consoleDriver;
  1603. WindowsConsole winConsole;
  1604. bool winChanged;
  1605. Size windowSize;
  1606. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  1607. // The records that we keep fetching
  1608. Queue<WindowsConsole.InputRecord []> resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1609. /// <summary>
  1610. /// Invoked when a Key is pressed or released.
  1611. /// </summary>
  1612. public Action<WindowsConsole.InputRecord> ProcessInput;
  1613. /// <summary>
  1614. /// Invoked when the window is changed.
  1615. /// </summary>
  1616. public Action<Size> WinChanged;
  1617. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1618. {
  1619. this.consoleDriver = consoleDriver ?? throw new ArgumentNullException ("Console driver instance must be provided.");
  1620. winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1621. }
  1622. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1623. {
  1624. this.mainLoop = mainLoop;
  1625. Task.Run (WindowsInputHandler);
  1626. Task.Run (CheckWinChange);
  1627. }
  1628. void WindowsInputHandler ()
  1629. {
  1630. while (true) {
  1631. waitForProbe.Wait ();
  1632. waitForProbe.Reset ();
  1633. if (resultQueue?.Count == 0) {
  1634. resultQueue.Enqueue (winConsole.ReadConsoleInput ());
  1635. }
  1636. eventReady.Set ();
  1637. }
  1638. }
  1639. void CheckWinChange ()
  1640. {
  1641. while (true) {
  1642. winChange.Wait ();
  1643. winChange.Reset ();
  1644. WaitWinChange ();
  1645. winChanged = true;
  1646. eventReady.Set ();
  1647. }
  1648. }
  1649. void WaitWinChange ()
  1650. {
  1651. while (true) {
  1652. // Wait for a while then check if screen has changed sizes
  1653. Task.Delay (500).Wait ();
  1654. windowSize = winConsole.GetConsoleBufferWindow (out _);
  1655. if (windowSize != Size.Empty && windowSize.Width != consoleDriver.Cols
  1656. || windowSize.Height != consoleDriver.Rows) {
  1657. return;
  1658. }
  1659. }
  1660. }
  1661. void IMainLoopDriver.Wakeup ()
  1662. {
  1663. //tokenSource.Cancel ();
  1664. eventReady.Set ();
  1665. }
  1666. bool IMainLoopDriver.EventsPending (bool wait)
  1667. {
  1668. waitForProbe.Set ();
  1669. winChange.Set ();
  1670. if (CheckTimers (wait, out var waitTimeout)) {
  1671. return true;
  1672. }
  1673. try {
  1674. if (!tokenSource.IsCancellationRequested) {
  1675. eventReady.Wait (waitTimeout, tokenSource.Token);
  1676. }
  1677. } catch (OperationCanceledException) {
  1678. return true;
  1679. } finally {
  1680. eventReady.Reset ();
  1681. }
  1682. if (!tokenSource.IsCancellationRequested) {
  1683. return resultQueue.Count > 0 || CheckTimers (wait, out _) || winChanged;
  1684. }
  1685. tokenSource.Dispose ();
  1686. tokenSource = new CancellationTokenSource ();
  1687. return true;
  1688. }
  1689. bool CheckTimers (bool wait, out int waitTimeout)
  1690. {
  1691. long now = DateTime.UtcNow.Ticks;
  1692. if (mainLoop.timeouts.Count > 0) {
  1693. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1694. if (waitTimeout < 0)
  1695. return true;
  1696. } else {
  1697. waitTimeout = -1;
  1698. }
  1699. if (!wait)
  1700. waitTimeout = 0;
  1701. int ic;
  1702. lock (mainLoop.idleHandlers) {
  1703. ic = mainLoop.idleHandlers.Count;
  1704. }
  1705. return ic > 0;
  1706. }
  1707. void IMainLoopDriver.MainIteration ()
  1708. {
  1709. while (resultQueue.Count > 0) {
  1710. var inputRecords = resultQueue.Dequeue ();
  1711. if (inputRecords != null && inputRecords.Length > 0) {
  1712. var inputEvent = inputRecords [0];
  1713. ProcessInput?.Invoke (inputEvent);
  1714. }
  1715. }
  1716. if (winChanged) {
  1717. winChanged = false;
  1718. WinChanged?.Invoke (windowSize);
  1719. }
  1720. }
  1721. }
  1722. class WindowsClipboard : ClipboardBase {
  1723. public WindowsClipboard ()
  1724. {
  1725. IsSupported = IsClipboardFormatAvailable (cfUnicodeText);
  1726. }
  1727. public override bool IsSupported { get; }
  1728. protected override string GetClipboardDataImpl ()
  1729. {
  1730. //if (!IsClipboardFormatAvailable (cfUnicodeText))
  1731. // return null;
  1732. try {
  1733. if (!OpenClipboard (IntPtr.Zero))
  1734. return null;
  1735. IntPtr handle = GetClipboardData (cfUnicodeText);
  1736. if (handle == IntPtr.Zero)
  1737. return null;
  1738. IntPtr pointer = IntPtr.Zero;
  1739. try {
  1740. pointer = GlobalLock (handle);
  1741. if (pointer == IntPtr.Zero)
  1742. return null;
  1743. int size = GlobalSize (handle);
  1744. byte [] buff = new byte [size];
  1745. Marshal.Copy (pointer, buff, 0, size);
  1746. return System.Text.Encoding.Unicode.GetString (buff)
  1747. .TrimEnd ('\0');
  1748. } finally {
  1749. if (pointer != IntPtr.Zero)
  1750. GlobalUnlock (handle);
  1751. }
  1752. } finally {
  1753. CloseClipboard ();
  1754. }
  1755. }
  1756. protected override void SetClipboardDataImpl (string text)
  1757. {
  1758. OpenClipboard ();
  1759. EmptyClipboard ();
  1760. IntPtr hGlobal = default;
  1761. try {
  1762. var bytes = (text.Length + 1) * 2;
  1763. hGlobal = Marshal.AllocHGlobal (bytes);
  1764. if (hGlobal == default) {
  1765. ThrowWin32 ();
  1766. }
  1767. var target = GlobalLock (hGlobal);
  1768. if (target == default) {
  1769. ThrowWin32 ();
  1770. }
  1771. try {
  1772. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1773. } finally {
  1774. GlobalUnlock (target);
  1775. }
  1776. if (SetClipboardData (cfUnicodeText, hGlobal) == default) {
  1777. ThrowWin32 ();
  1778. }
  1779. hGlobal = default;
  1780. } finally {
  1781. if (hGlobal != default) {
  1782. Marshal.FreeHGlobal (hGlobal);
  1783. }
  1784. CloseClipboard ();
  1785. }
  1786. }
  1787. void OpenClipboard ()
  1788. {
  1789. var num = 10;
  1790. while (true) {
  1791. if (OpenClipboard (default)) {
  1792. break;
  1793. }
  1794. if (--num == 0) {
  1795. ThrowWin32 ();
  1796. }
  1797. Thread.Sleep (100);
  1798. }
  1799. }
  1800. const uint cfUnicodeText = 13;
  1801. void ThrowWin32 ()
  1802. {
  1803. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1804. }
  1805. [DllImport ("User32.dll", SetLastError = true)]
  1806. [return: MarshalAs (UnmanagedType.Bool)]
  1807. static extern bool IsClipboardFormatAvailable (uint format);
  1808. [DllImport ("kernel32.dll", SetLastError = true)]
  1809. static extern int GlobalSize (IntPtr handle);
  1810. [DllImport ("kernel32.dll", SetLastError = true)]
  1811. static extern IntPtr GlobalLock (IntPtr hMem);
  1812. [DllImport ("kernel32.dll", SetLastError = true)]
  1813. [return: MarshalAs (UnmanagedType.Bool)]
  1814. static extern bool GlobalUnlock (IntPtr hMem);
  1815. [DllImport ("user32.dll", SetLastError = true)]
  1816. [return: MarshalAs (UnmanagedType.Bool)]
  1817. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1818. [DllImport ("user32.dll", SetLastError = true)]
  1819. [return: MarshalAs (UnmanagedType.Bool)]
  1820. static extern bool CloseClipboard ();
  1821. [DllImport ("user32.dll", SetLastError = true)]
  1822. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1823. [DllImport ("user32.dll")]
  1824. static extern bool EmptyClipboard ();
  1825. [DllImport ("user32.dll", SetLastError = true)]
  1826. static extern IntPtr GetClipboardData (uint uFormat);
  1827. }
  1828. }