WindowsDriver.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142
  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. if (!EnableConsoleScrolling) {
  644. var w = e.Width;
  645. if (w == cols - 3 && e.Height < rows) {
  646. w += 3;
  647. }
  648. var newSize = WinConsole.SetConsoleWindow (
  649. (short)Math.Max (w, 16), (short)Math.Max (e.Height, 0));
  650. left = 0;
  651. top = 0;
  652. cols = newSize.Width;
  653. rows = newSize.Height;
  654. ResizeScreen ();
  655. UpdateOffScreen ();
  656. TerminalResized.Invoke ();
  657. }
  658. }
  659. void ProcessInput (WindowsConsole.InputRecord inputEvent)
  660. {
  661. switch (inputEvent.EventType) {
  662. case WindowsConsole.EventType.Key:
  663. var fromPacketKey = inputEvent.KeyEvent.wVirtualKeyCode == (uint)ConsoleKey.Packet;
  664. if (fromPacketKey) {
  665. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  666. }
  667. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  668. //var ke = inputEvent.KeyEvent;
  669. //System.Diagnostics.Debug.WriteLine ($"fromPacketKey: {fromPacketKey}");
  670. //if (ke.UnicodeChar == '\0') {
  671. // System.Diagnostics.Debug.WriteLine ("UnicodeChar: 0'\\0'");
  672. //} else if (ke.UnicodeChar == 13) {
  673. // System.Diagnostics.Debug.WriteLine ("UnicodeChar: 13'\\n'");
  674. //} else {
  675. // System.Diagnostics.Debug.WriteLine ($"UnicodeChar: {(uint)ke.UnicodeChar}'{ke.UnicodeChar}'");
  676. //}
  677. //System.Diagnostics.Debug.WriteLine ($"bKeyDown: {ke.bKeyDown}");
  678. //System.Diagnostics.Debug.WriteLine ($"dwControlKeyState: {ke.dwControlKeyState}");
  679. //System.Diagnostics.Debug.WriteLine ($"wRepeatCount: {ke.wRepeatCount}");
  680. //System.Diagnostics.Debug.WriteLine ($"wVirtualKeyCode: {ke.wVirtualKeyCode}");
  681. //System.Diagnostics.Debug.WriteLine ($"wVirtualScanCode: {ke.wVirtualScanCode}");
  682. if (map == (Key)0xffffffff) {
  683. KeyEvent key = new KeyEvent ();
  684. // Shift = VK_SHIFT = 0x10
  685. // Ctrl = VK_CONTROL = 0x11
  686. // Alt = VK_MENU = 0x12
  687. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
  688. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
  689. }
  690. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
  691. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
  692. }
  693. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
  694. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
  695. }
  696. switch (inputEvent.KeyEvent.dwControlKeyState) {
  697. case WindowsConsole.ControlKeyState.RightAltPressed:
  698. case WindowsConsole.ControlKeyState.RightAltPressed |
  699. WindowsConsole.ControlKeyState.LeftControlPressed |
  700. WindowsConsole.ControlKeyState.EnhancedKey:
  701. case WindowsConsole.ControlKeyState.EnhancedKey:
  702. key = new KeyEvent (Key.CtrlMask | Key.AltMask, keyModifiers);
  703. break;
  704. case WindowsConsole.ControlKeyState.LeftAltPressed:
  705. key = new KeyEvent (Key.AltMask, keyModifiers);
  706. break;
  707. case WindowsConsole.ControlKeyState.RightControlPressed:
  708. case WindowsConsole.ControlKeyState.LeftControlPressed:
  709. key = new KeyEvent (Key.CtrlMask, keyModifiers);
  710. break;
  711. case WindowsConsole.ControlKeyState.ShiftPressed:
  712. key = new KeyEvent (Key.ShiftMask, keyModifiers);
  713. break;
  714. case WindowsConsole.ControlKeyState.NumlockOn:
  715. break;
  716. case WindowsConsole.ControlKeyState.ScrolllockOn:
  717. break;
  718. case WindowsConsole.ControlKeyState.CapslockOn:
  719. break;
  720. default:
  721. switch (inputEvent.KeyEvent.wVirtualKeyCode) {
  722. case 0x10:
  723. key = new KeyEvent (Key.ShiftMask, keyModifiers);
  724. break;
  725. case 0x11:
  726. key = new KeyEvent (Key.CtrlMask, keyModifiers);
  727. break;
  728. case 0x12:
  729. key = new KeyEvent (Key.AltMask, keyModifiers);
  730. break;
  731. default:
  732. key = new KeyEvent (Key.Unknown, keyModifiers);
  733. break;
  734. }
  735. break;
  736. }
  737. if (inputEvent.KeyEvent.bKeyDown)
  738. keyDownHandler (key);
  739. else
  740. keyUpHandler (key);
  741. } else {
  742. if (inputEvent.KeyEvent.bKeyDown) {
  743. // May occurs using SendKeys
  744. if (keyModifiers == null)
  745. keyModifiers = new KeyModifiers ();
  746. // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
  747. keyDownHandler (new KeyEvent (map, keyModifiers));
  748. keyHandler (new KeyEvent (map, keyModifiers));
  749. } else {
  750. keyUpHandler (new KeyEvent (map, keyModifiers));
  751. }
  752. }
  753. if (!inputEvent.KeyEvent.bKeyDown && (inputEvent.KeyEvent.dwControlKeyState == 0 || inputEvent.KeyEvent.dwControlKeyState == WindowsConsole.ControlKeyState.EnhancedKey)) {
  754. keyModifiers = null;
  755. }
  756. break;
  757. case WindowsConsole.EventType.Mouse:
  758. var me = ToDriverMouse (inputEvent.MouseEvent);
  759. mouseHandler (me);
  760. if (processButtonClick) {
  761. mouseHandler (
  762. new MouseEvent () {
  763. X = me.X,
  764. Y = me.Y,
  765. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  766. });
  767. }
  768. break;
  769. case WindowsConsole.EventType.Focus:
  770. keyModifiers = null;
  771. break;
  772. }
  773. }
  774. WindowsConsole.ButtonState? lastMouseButtonPressed = null;
  775. bool isButtonPressed = false;
  776. bool isButtonReleased = false;
  777. bool isButtonDoubleClicked = false;
  778. Point? point;
  779. Point pointMove;
  780. //int buttonPressedCount;
  781. bool isOneFingerDoubleClicked = false;
  782. bool processButtonClick;
  783. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  784. {
  785. MouseFlags mouseFlag = MouseFlags.AllEvents;
  786. //System.Diagnostics.Debug.WriteLine (
  787. // $"X:{mouseEvent.MousePosition.X};Y:{mouseEvent.MousePosition.Y};ButtonState:{mouseEvent.ButtonState};EventFlags:{mouseEvent.EventFlags}");
  788. if (isButtonDoubleClicked || isOneFingerDoubleClicked) {
  789. Application.MainLoop.AddIdle (() => {
  790. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  791. return false;
  792. });
  793. }
  794. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  795. // This will tell when a mouse button is pressed. When the button is released this event will
  796. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  797. // To map to the correct driver events we save the last pressed mouse button so we can
  798. // map to the correct clicked event.
  799. if ((lastMouseButtonPressed != null || isButtonReleased) && mouseEvent.ButtonState != 0) {
  800. lastMouseButtonPressed = null;
  801. //isButtonPressed = false;
  802. isButtonReleased = false;
  803. }
  804. var p = new Point () {
  805. X = mouseEvent.MousePosition.X,
  806. Y = mouseEvent.MousePosition.Y
  807. };
  808. //if (!isButtonPressed && buttonPressedCount < 2
  809. // && mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  810. // && (mouseEvent.ButtonState == WindowsConsole.ButtonState.Button1Pressed
  811. // || mouseEvent.ButtonState == WindowsConsole.ButtonState.Button2Pressed
  812. // || mouseEvent.ButtonState == WindowsConsole.ButtonState.Button3Pressed)) {
  813. // lastMouseButtonPressed = mouseEvent.ButtonState;
  814. // buttonPressedCount++;
  815. //} else if (!isButtonPressed && buttonPressedCount > 0 && mouseEvent.ButtonState == 0
  816. // && mouseEvent.EventFlags == 0) {
  817. // buttonPressedCount++;
  818. //}
  819. //System.Diagnostics.Debug.WriteLine ($"isButtonPressed: {isButtonPressed};buttonPressedCount: {buttonPressedCount};lastMouseButtonPressed: {lastMouseButtonPressed}");
  820. //System.Diagnostics.Debug.WriteLine ($"isOneFingerDoubleClicked: {isOneFingerDoubleClicked}");
  821. //if (buttonPressedCount == 1 && lastMouseButtonPressed != null && p == point
  822. // && lastMouseButtonPressed == WindowsConsole.ButtonState.Button1Pressed
  823. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button2Pressed
  824. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button3Pressed) {
  825. // switch (lastMouseButtonPressed) {
  826. // case WindowsConsole.ButtonState.Button1Pressed:
  827. // mouseFlag = MouseFlags.Button1DoubleClicked;
  828. // break;
  829. // case WindowsConsole.ButtonState.Button2Pressed:
  830. // mouseFlag = MouseFlags.Button2DoubleClicked;
  831. // break;
  832. // case WindowsConsole.ButtonState.Button3Pressed:
  833. // mouseFlag = MouseFlags.Button3DoubleClicked;
  834. // break;
  835. // }
  836. // isOneFingerDoubleClicked = true;
  837. //} else if (buttonPressedCount == 3 && lastMouseButtonPressed != null && isOneFingerDoubleClicked && p == point
  838. // && lastMouseButtonPressed == WindowsConsole.ButtonState.Button1Pressed
  839. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button2Pressed
  840. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button3Pressed) {
  841. // switch (lastMouseButtonPressed) {
  842. // case WindowsConsole.ButtonState.Button1Pressed:
  843. // mouseFlag = MouseFlags.Button1TripleClicked;
  844. // break;
  845. // case WindowsConsole.ButtonState.Button2Pressed:
  846. // mouseFlag = MouseFlags.Button2TripleClicked;
  847. // break;
  848. // case WindowsConsole.ButtonState.Button3Pressed:
  849. // mouseFlag = MouseFlags.Button3TripleClicked;
  850. // break;
  851. // }
  852. // buttonPressedCount = 0;
  853. // lastMouseButtonPressed = null;
  854. // isOneFingerDoubleClicked = false;
  855. // isButtonReleased = false;
  856. //}
  857. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && lastMouseButtonPressed == null && !isButtonDoubleClicked) ||
  858. (lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) &&
  859. mouseEvent.ButtonState != 0 && !isButtonReleased && !isButtonDoubleClicked)) {
  860. switch (mouseEvent.ButtonState) {
  861. case WindowsConsole.ButtonState.Button1Pressed:
  862. mouseFlag = MouseFlags.Button1Pressed;
  863. break;
  864. case WindowsConsole.ButtonState.Button2Pressed:
  865. mouseFlag = MouseFlags.Button2Pressed;
  866. break;
  867. case WindowsConsole.ButtonState.RightmostButtonPressed:
  868. mouseFlag = MouseFlags.Button3Pressed;
  869. break;
  870. }
  871. if (point == null)
  872. point = p;
  873. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  874. mouseFlag |= MouseFlags.ReportMousePosition;
  875. isButtonReleased = false;
  876. processButtonClick = false;
  877. }
  878. lastMouseButtonPressed = mouseEvent.ButtonState;
  879. isButtonPressed = true;
  880. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  881. Application.MainLoop.AddIdle (() => {
  882. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  883. return false;
  884. });
  885. }
  886. } else if (lastMouseButtonPressed != null && mouseEvent.EventFlags == 0
  887. && !isButtonReleased && !isButtonDoubleClicked && !isOneFingerDoubleClicked) {
  888. switch (lastMouseButtonPressed) {
  889. case WindowsConsole.ButtonState.Button1Pressed:
  890. mouseFlag = MouseFlags.Button1Released;
  891. break;
  892. case WindowsConsole.ButtonState.Button2Pressed:
  893. mouseFlag = MouseFlags.Button2Released;
  894. break;
  895. case WindowsConsole.ButtonState.RightmostButtonPressed:
  896. mouseFlag = MouseFlags.Button3Released;
  897. break;
  898. }
  899. isButtonPressed = false;
  900. isButtonReleased = true;
  901. if (point != null && (((Point)point).X == mouseEvent.MousePosition.X && ((Point)point).Y == mouseEvent.MousePosition.Y)) {
  902. processButtonClick = true;
  903. } else {
  904. point = null;
  905. }
  906. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  907. && !isOneFingerDoubleClicked && isButtonReleased && p == point) {
  908. mouseFlag = ProcessButtonClick (mouseEvent);
  909. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  910. switch (mouseEvent.ButtonState) {
  911. case WindowsConsole.ButtonState.Button1Pressed:
  912. mouseFlag = MouseFlags.Button1DoubleClicked;
  913. break;
  914. case WindowsConsole.ButtonState.Button2Pressed:
  915. mouseFlag = MouseFlags.Button2DoubleClicked;
  916. break;
  917. case WindowsConsole.ButtonState.RightmostButtonPressed:
  918. mouseFlag = MouseFlags.Button3DoubleClicked;
  919. break;
  920. }
  921. isButtonDoubleClicked = true;
  922. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && isButtonDoubleClicked) {
  923. switch (mouseEvent.ButtonState) {
  924. case WindowsConsole.ButtonState.Button1Pressed:
  925. mouseFlag = MouseFlags.Button1TripleClicked;
  926. break;
  927. case WindowsConsole.ButtonState.Button2Pressed:
  928. mouseFlag = MouseFlags.Button2TripleClicked;
  929. break;
  930. case WindowsConsole.ButtonState.RightmostButtonPressed:
  931. mouseFlag = MouseFlags.Button3TripleClicked;
  932. break;
  933. }
  934. isButtonDoubleClicked = false;
  935. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  936. switch ((int)mouseEvent.ButtonState) {
  937. case int v when v > 0:
  938. mouseFlag = MouseFlags.WheeledUp;
  939. break;
  940. case int v when v < 0:
  941. mouseFlag = MouseFlags.WheeledDown;
  942. break;
  943. }
  944. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  945. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  946. switch ((int)mouseEvent.ButtonState) {
  947. case int v when v > 0:
  948. mouseFlag = MouseFlags.WheeledLeft;
  949. break;
  950. case int v when v < 0:
  951. mouseFlag = MouseFlags.WheeledRight;
  952. break;
  953. }
  954. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled) {
  955. switch ((int)mouseEvent.ButtonState) {
  956. case int v when v < 0:
  957. mouseFlag = MouseFlags.WheeledLeft;
  958. break;
  959. case int v when v > 0:
  960. mouseFlag = MouseFlags.WheeledRight;
  961. break;
  962. }
  963. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  964. mouseFlag = MouseFlags.ReportMousePosition;
  965. if (mouseEvent.MousePosition.X != pointMove.X || mouseEvent.MousePosition.Y != pointMove.Y) {
  966. pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  967. }
  968. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  969. mouseFlag = 0;
  970. }
  971. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  972. //System.Diagnostics.Debug.WriteLine (
  973. // $"point.X:{(point != null ? ((Point)point).X : -1)};point.Y:{(point != null ? ((Point)point).Y : -1)}");
  974. return new MouseEvent () {
  975. X = mouseEvent.MousePosition.X,
  976. Y = mouseEvent.MousePosition.Y,
  977. Flags = mouseFlag
  978. };
  979. }
  980. MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  981. {
  982. MouseFlags mouseFlag = 0;
  983. switch (lastMouseButtonPressed) {
  984. case WindowsConsole.ButtonState.Button1Pressed:
  985. mouseFlag = MouseFlags.Button1Clicked;
  986. break;
  987. case WindowsConsole.ButtonState.Button2Pressed:
  988. mouseFlag = MouseFlags.Button2Clicked;
  989. break;
  990. case WindowsConsole.ButtonState.RightmostButtonPressed:
  991. mouseFlag = MouseFlags.Button3Clicked;
  992. break;
  993. }
  994. point = new Point () {
  995. X = mouseEvent.MousePosition.X,
  996. Y = mouseEvent.MousePosition.Y
  997. };
  998. lastMouseButtonPressed = null;
  999. isButtonReleased = false;
  1000. processButtonClick = false;
  1001. point = null;
  1002. return mouseFlag;
  1003. }
  1004. async Task ProcessButtonDoubleClickedAsync ()
  1005. {
  1006. await Task.Delay (300);
  1007. isButtonDoubleClicked = false;
  1008. isOneFingerDoubleClicked = false;
  1009. //buttonPressedCount = 0;
  1010. }
  1011. async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1012. {
  1013. while (isButtonPressed) {
  1014. await Task.Delay (100);
  1015. var me = new MouseEvent () {
  1016. X = pointMove.X,
  1017. Y = pointMove.Y,
  1018. Flags = mouseFlag
  1019. };
  1020. var view = Application.WantContinuousButtonPressedView;
  1021. if (view == null) {
  1022. break;
  1023. }
  1024. if (isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1025. Application.MainLoop.Invoke (() => mouseHandler (me));
  1026. }
  1027. }
  1028. }
  1029. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1030. {
  1031. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  1032. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  1033. mouseFlag |= MouseFlags.ButtonCtrl;
  1034. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  1035. mouseFlag |= MouseFlags.ButtonShift;
  1036. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1037. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  1038. mouseFlag |= MouseFlags.ButtonAlt;
  1039. return mouseFlag;
  1040. }
  1041. KeyModifiers keyModifiers;
  1042. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1043. {
  1044. var state = keyEvent.dwControlKeyState;
  1045. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1046. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1047. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1048. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  1049. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  1050. bool scrolllock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  1051. if (keyModifiers == null)
  1052. keyModifiers = new KeyModifiers ();
  1053. if (shift)
  1054. keyModifiers.Shift = shift;
  1055. if (alt)
  1056. keyModifiers.Alt = alt;
  1057. if (control)
  1058. keyModifiers.Ctrl = control;
  1059. if (capslock)
  1060. keyModifiers.Capslock = capslock;
  1061. if (numlock)
  1062. keyModifiers.Numlock = numlock;
  1063. if (scrolllock)
  1064. keyModifiers.Scrolllock = scrolllock;
  1065. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1066. return new WindowsConsole.ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock, scrolllock);
  1067. }
  1068. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  1069. {
  1070. if (keyEvent.wVirtualKeyCode != (uint)ConsoleKey.Packet) {
  1071. return keyEvent;
  1072. }
  1073. var mod = new ConsoleModifiers ();
  1074. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1075. mod |= ConsoleModifiers.Shift;
  1076. }
  1077. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1078. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1079. mod |= ConsoleModifiers.Alt;
  1080. }
  1081. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed) ||
  1082. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)) {
  1083. mod |= ConsoleModifiers.Control;
  1084. }
  1085. var keyChar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyEvent.UnicodeChar, mod, out uint virtualKey, out uint scanCode);
  1086. return new WindowsConsole.KeyEventRecord {
  1087. UnicodeChar = (char)keyChar,
  1088. bKeyDown = keyEvent.bKeyDown,
  1089. dwControlKeyState = keyEvent.dwControlKeyState,
  1090. wRepeatCount = keyEvent.wRepeatCount,
  1091. wVirtualKeyCode = (ushort)virtualKey,
  1092. wVirtualScanCode = (ushort)scanCode
  1093. };
  1094. }
  1095. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  1096. {
  1097. var keyInfo = keyInfoEx.consoleKeyInfo;
  1098. switch (keyInfo.Key) {
  1099. case ConsoleKey.Escape:
  1100. return MapKeyModifiers (keyInfo, Key.Esc);
  1101. case ConsoleKey.Tab:
  1102. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  1103. case ConsoleKey.Clear:
  1104. return MapKeyModifiers (keyInfo, Key.Clear);
  1105. case ConsoleKey.Home:
  1106. return MapKeyModifiers (keyInfo, Key.Home);
  1107. case ConsoleKey.End:
  1108. return MapKeyModifiers (keyInfo, Key.End);
  1109. case ConsoleKey.LeftArrow:
  1110. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  1111. case ConsoleKey.RightArrow:
  1112. return MapKeyModifiers (keyInfo, Key.CursorRight);
  1113. case ConsoleKey.UpArrow:
  1114. return MapKeyModifiers (keyInfo, Key.CursorUp);
  1115. case ConsoleKey.DownArrow:
  1116. return MapKeyModifiers (keyInfo, Key.CursorDown);
  1117. case ConsoleKey.PageUp:
  1118. return MapKeyModifiers (keyInfo, Key.PageUp);
  1119. case ConsoleKey.PageDown:
  1120. return MapKeyModifiers (keyInfo, Key.PageDown);
  1121. case ConsoleKey.Enter:
  1122. return MapKeyModifiers (keyInfo, Key.Enter);
  1123. case ConsoleKey.Spacebar:
  1124. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  1125. case ConsoleKey.Backspace:
  1126. return MapKeyModifiers (keyInfo, Key.Backspace);
  1127. case ConsoleKey.Delete:
  1128. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  1129. case ConsoleKey.Insert:
  1130. return MapKeyModifiers (keyInfo, Key.InsertChar);
  1131. case ConsoleKey.PrintScreen:
  1132. return MapKeyModifiers (keyInfo, Key.PrintScreen);
  1133. case ConsoleKey.NumPad0:
  1134. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  1135. case ConsoleKey.NumPad1:
  1136. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  1137. case ConsoleKey.NumPad2:
  1138. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  1139. case ConsoleKey.NumPad3:
  1140. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  1141. case ConsoleKey.NumPad4:
  1142. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  1143. case ConsoleKey.NumPad5:
  1144. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  1145. case ConsoleKey.NumPad6:
  1146. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  1147. case ConsoleKey.NumPad7:
  1148. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  1149. case ConsoleKey.NumPad8:
  1150. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  1151. case ConsoleKey.NumPad9:
  1152. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  1153. case ConsoleKey.Oem1:
  1154. case ConsoleKey.Oem2:
  1155. case ConsoleKey.Oem3:
  1156. case ConsoleKey.Oem4:
  1157. case ConsoleKey.Oem5:
  1158. case ConsoleKey.Oem6:
  1159. case ConsoleKey.Oem7:
  1160. case ConsoleKey.Oem8:
  1161. case ConsoleKey.Oem102:
  1162. case ConsoleKey.OemPeriod:
  1163. case ConsoleKey.OemComma:
  1164. case ConsoleKey.OemPlus:
  1165. case ConsoleKey.OemMinus:
  1166. if (keyInfo.KeyChar == 0)
  1167. return Key.Unknown;
  1168. return (Key)((uint)keyInfo.KeyChar);
  1169. }
  1170. var key = keyInfo.Key;
  1171. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  1172. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  1173. var delta = key - ConsoleKey.A;
  1174. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1175. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1176. }
  1177. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1178. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1179. }
  1180. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1181. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1182. }
  1183. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1184. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1185. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1186. }
  1187. }
  1188. //return (Key)((uint)alphaBase + delta);
  1189. return (Key)((uint)keyInfo.KeyChar);
  1190. }
  1191. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1192. var delta = key - ConsoleKey.D0;
  1193. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1194. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1195. }
  1196. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1197. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1198. }
  1199. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1200. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1201. }
  1202. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1203. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30 || keyInfo.KeyChar == ((uint)Key.D0 + delta)) {
  1204. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1205. }
  1206. }
  1207. return (Key)((uint)keyInfo.KeyChar);
  1208. }
  1209. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1210. var delta = key - ConsoleKey.F1;
  1211. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1212. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1213. }
  1214. return (Key)((uint)Key.F1 + delta);
  1215. }
  1216. if (keyInfo.KeyChar != 0) {
  1217. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1218. }
  1219. return (Key)(0xffffffff);
  1220. }
  1221. private Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1222. {
  1223. Key keyMod = new Key ();
  1224. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
  1225. keyMod = Key.ShiftMask;
  1226. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
  1227. keyMod |= Key.CtrlMask;
  1228. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
  1229. keyMod |= Key.AltMask;
  1230. return keyMod != Key.Null ? keyMod | key : key;
  1231. }
  1232. public override void Init (Action terminalResized)
  1233. {
  1234. TerminalResized = terminalResized;
  1235. try {
  1236. // Needed for Windows Terminal
  1237. // ESC [ ? 1047 h Activate xterm alternative buffer (no backscroll)
  1238. // ESC [ ? 1047 l Restore xterm working buffer (with backscroll)
  1239. // ESC [ ? 1048 h Save cursor position
  1240. // ESC [ ? 1048 l Restore cursor position
  1241. // ESC [ ? 1049 h Save cursor position and activate xterm alternative buffer (no backscroll)
  1242. // ESC [ ? 1049 l Restore cursor position and restore xterm working buffer (with backscroll)
  1243. // Per Issue #2264 using the alterantive screen buffer is required for Windows Terminal to not
  1244. // wipe out the backscroll buffer when the application exits.
  1245. Console.Out.Write ("\x1b[?1049h");
  1246. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1247. cols = winSize.Width;
  1248. rows = winSize.Height;
  1249. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1250. CurrentAttribute = MakeColor (Color.White, Color.Black);
  1251. InitalizeColorSchemes ();
  1252. CurrentAttribute = MakeColor (Color.White, Color.Black);
  1253. InitalizeColorSchemes ();
  1254. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  1255. Clip = new Rect (0, 0, Cols, Rows);
  1256. damageRegion = new WindowsConsole.SmallRect () {
  1257. Top = 0,
  1258. Left = 0,
  1259. Bottom = (short)Rows,
  1260. Right = (short)Cols
  1261. };
  1262. UpdateOffScreen ();
  1263. } catch (Win32Exception e) {
  1264. throw new InvalidOperationException ("The Windows Console output window is not available.", e);
  1265. }
  1266. }
  1267. public override void ResizeScreen ()
  1268. {
  1269. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  1270. Clip = new Rect (0, 0, Cols, Rows);
  1271. damageRegion = new WindowsConsole.SmallRect () {
  1272. Top = 0,
  1273. Left = 0,
  1274. Bottom = (short)Rows,
  1275. Right = (short)Cols
  1276. };
  1277. WinConsole.ForceRefreshCursorVisibility ();
  1278. if (!EnableConsoleScrolling) {
  1279. // ANSI ESC "[xJ" Clears part of the screen.
  1280. // If n is 0 (or missing), clear from cursor to end of screen.
  1281. // If n is 1, clear from cursor to beginning of the screen.
  1282. // If n is 2, clear entire screen (and moves cursor to upper left on DOS ANSI.SYS).
  1283. // If n is 3, clear entire screen and delete all lines saved in the scrollback buffer
  1284. // DO NOT USE 3J - even with the alternate screen buffer, it clears the entire scrollback buffer
  1285. //Console.Out.Write ("\x1b[1;1H");
  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. if (!EnableConsoleScrolling) {
  1431. var windowSize = WinConsole.GetConsoleBufferWindow (out _);
  1432. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows))
  1433. return;
  1434. }
  1435. var bufferCoords = new WindowsConsole.Coord () {
  1436. X = (short)Clip.Width,
  1437. Y = (short)Clip.Height
  1438. };
  1439. //var window = new WindowsConsole.SmallRect () {
  1440. // Top = 0,
  1441. // Left = 0,
  1442. // Right = (short)Clip.Right,
  1443. // Bottom = (short)Clip.Bottom
  1444. //};
  1445. WinConsole.WriteToConsole (new Size (Cols, Rows), OutputBuffer, bufferCoords, damageRegion);
  1446. // System.Diagnostics.Debugger.Log (0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  1447. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1448. }
  1449. CursorVisibility savedCursorVisibility;
  1450. public override void UpdateCursor ()
  1451. {
  1452. if (ccol < 0 || crow < 0 || ccol > Cols || crow > Rows) {
  1453. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1454. savedCursorVisibility = cursorVisibility;
  1455. SetCursorVisibility (CursorVisibility.Invisible);
  1456. return;
  1457. }
  1458. SetCursorVisibility (savedCursorVisibility);
  1459. var position = new WindowsConsole.Coord () {
  1460. X = (short)ccol,
  1461. Y = (short)crow
  1462. };
  1463. WinConsole.SetCursorPosition (position);
  1464. }
  1465. public override void End ()
  1466. {
  1467. WinConsole.Cleanup ();
  1468. WinConsole = null;
  1469. // Disable alternative screen buffer.
  1470. Console.Out.Write ("\x1b[?1049l");
  1471. // Needed for Windows Terminal
  1472. // Clear the alternative screen buffer from the cursor to the
  1473. // end of the screen.
  1474. // Note, [3J causes Windows Terminal to wipe out the entire NON ALTERNATIVE
  1475. // backbuffer! So we need to use [0J instead.
  1476. Console.Out.Write ("\x1b[0J");
  1477. Console.Out.Write ("\x1b[!p");
  1478. Console.Out.Write ("\x1b[!p");
  1479. }
  1480. /// <inheritdoc/>
  1481. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1482. {
  1483. return WinConsole.GetCursorVisibility (out visibility);
  1484. }
  1485. /// <inheritdoc/>
  1486. public override bool SetCursorVisibility (CursorVisibility visibility)
  1487. {
  1488. savedCursorVisibility = visibility;
  1489. return WinConsole.SetCursorVisibility (visibility);
  1490. }
  1491. /// <inheritdoc/>
  1492. public override bool EnsureCursorVisibility ()
  1493. {
  1494. return WinConsole.EnsureCursorVisibility ();
  1495. }
  1496. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1497. {
  1498. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1499. EventType = WindowsConsole.EventType.Key
  1500. };
  1501. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1502. bKeyDown = true
  1503. };
  1504. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1505. if (shift) {
  1506. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1507. keyEvent.UnicodeChar = '\0';
  1508. keyEvent.wVirtualKeyCode = 16;
  1509. }
  1510. if (alt) {
  1511. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1512. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1513. keyEvent.UnicodeChar = '\0';
  1514. keyEvent.wVirtualKeyCode = 18;
  1515. }
  1516. if (control) {
  1517. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1518. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1519. keyEvent.UnicodeChar = '\0';
  1520. keyEvent.wVirtualKeyCode = 17;
  1521. }
  1522. keyEvent.dwControlKeyState = controlKey;
  1523. input.KeyEvent = keyEvent;
  1524. if (shift || alt || control) {
  1525. ProcessInput (input);
  1526. }
  1527. keyEvent.UnicodeChar = keyChar;
  1528. if ((uint)key < 255) {
  1529. keyEvent.wVirtualKeyCode = (ushort)key;
  1530. } else {
  1531. keyEvent.wVirtualKeyCode = '\0';
  1532. }
  1533. input.KeyEvent = keyEvent;
  1534. try {
  1535. ProcessInput (input);
  1536. } catch (OverflowException) { } finally {
  1537. keyEvent.bKeyDown = false;
  1538. input.KeyEvent = keyEvent;
  1539. ProcessInput (input);
  1540. }
  1541. }
  1542. public override bool GetColors (int value, out Color foreground, out Color background)
  1543. {
  1544. bool hasColor = false;
  1545. foreground = default;
  1546. background = default;
  1547. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  1548. .OfType<ConsoleColor> ()
  1549. .Select (s => (int)s);
  1550. if (values.Contains ((value >> 4) & 0xffff)) {
  1551. hasColor = true;
  1552. background = (Color)(ConsoleColor)((value >> 4) & 0xffff);
  1553. }
  1554. if (values.Contains (value - ((int)background << 4))) {
  1555. hasColor = true;
  1556. foreground = (Color)(ConsoleColor)(value - ((int)background << 4));
  1557. }
  1558. return hasColor;
  1559. }
  1560. #region Unused
  1561. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1562. {
  1563. }
  1564. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1565. {
  1566. }
  1567. public override void Suspend ()
  1568. {
  1569. }
  1570. public override void StartReportingMouseMoves ()
  1571. {
  1572. }
  1573. public override void StopReportingMouseMoves ()
  1574. {
  1575. }
  1576. public override void UncookMouse ()
  1577. {
  1578. }
  1579. public override void CookMouse ()
  1580. {
  1581. }
  1582. #endregion
  1583. }
  1584. /// <summary>
  1585. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1586. /// only be used on Windows.
  1587. /// </summary>
  1588. /// <remarks>
  1589. /// This implementation is used for WindowsDriver.
  1590. /// </remarks>
  1591. internal class WindowsMainLoop : IMainLoopDriver {
  1592. ManualResetEventSlim eventReady = new ManualResetEventSlim (false);
  1593. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  1594. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  1595. MainLoop mainLoop;
  1596. ConsoleDriver consoleDriver;
  1597. WindowsConsole winConsole;
  1598. bool winChanged;
  1599. Size windowSize;
  1600. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  1601. // The records that we keep fetching
  1602. Queue<WindowsConsole.InputRecord []> resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1603. /// <summary>
  1604. /// Invoked when a Key is pressed or released.
  1605. /// </summary>
  1606. public Action<WindowsConsole.InputRecord> ProcessInput;
  1607. /// <summary>
  1608. /// Invoked when the window is changed.
  1609. /// </summary>
  1610. public Action<Size> WinChanged;
  1611. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1612. {
  1613. this.consoleDriver = consoleDriver ?? throw new ArgumentNullException ("Console driver instance must be provided.");
  1614. winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1615. }
  1616. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1617. {
  1618. this.mainLoop = mainLoop;
  1619. Task.Run (WindowsInputHandler);
  1620. Task.Run (CheckWinChange);
  1621. }
  1622. void WindowsInputHandler ()
  1623. {
  1624. while (true) {
  1625. waitForProbe.Wait ();
  1626. waitForProbe.Reset ();
  1627. if (resultQueue?.Count == 0) {
  1628. resultQueue.Enqueue (winConsole.ReadConsoleInput ());
  1629. }
  1630. eventReady.Set ();
  1631. }
  1632. }
  1633. void CheckWinChange ()
  1634. {
  1635. while (true) {
  1636. winChange.Wait ();
  1637. winChange.Reset ();
  1638. WaitWinChange ();
  1639. winChanged = true;
  1640. eventReady.Set ();
  1641. }
  1642. }
  1643. void WaitWinChange ()
  1644. {
  1645. while (true) {
  1646. // Wait for a while then check if screen has changed sizes
  1647. Task.Delay (500).Wait ();
  1648. if (!consoleDriver.EnableConsoleScrolling) {
  1649. windowSize = winConsole.GetConsoleBufferWindow (out _);
  1650. //System.Diagnostics.Debug.WriteLine ($"{consoleDriver.EnableConsoleScrolling},{windowSize.Width},{windowSize.Height}");
  1651. if (windowSize != Size.Empty && windowSize.Width != consoleDriver.Cols
  1652. || windowSize.Height != consoleDriver.Rows) {
  1653. return;
  1654. }
  1655. }
  1656. }
  1657. }
  1658. void IMainLoopDriver.Wakeup ()
  1659. {
  1660. //tokenSource.Cancel ();
  1661. eventReady.Set ();
  1662. }
  1663. bool IMainLoopDriver.EventsPending (bool wait)
  1664. {
  1665. waitForProbe.Set ();
  1666. winChange.Set ();
  1667. if (CheckTimers (wait, out var waitTimeout)) {
  1668. return true;
  1669. }
  1670. try {
  1671. if (!tokenSource.IsCancellationRequested) {
  1672. eventReady.Wait (waitTimeout, tokenSource.Token);
  1673. }
  1674. } catch (OperationCanceledException) {
  1675. return true;
  1676. } finally {
  1677. eventReady.Reset ();
  1678. }
  1679. if (!tokenSource.IsCancellationRequested) {
  1680. return resultQueue.Count > 0 || CheckTimers (wait, out _) || winChanged;
  1681. }
  1682. tokenSource.Dispose ();
  1683. tokenSource = new CancellationTokenSource ();
  1684. return true;
  1685. }
  1686. bool CheckTimers (bool wait, out int waitTimeout)
  1687. {
  1688. long now = DateTime.UtcNow.Ticks;
  1689. if (mainLoop.timeouts.Count > 0) {
  1690. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1691. if (waitTimeout < 0)
  1692. return true;
  1693. } else {
  1694. waitTimeout = -1;
  1695. }
  1696. if (!wait)
  1697. waitTimeout = 0;
  1698. int ic;
  1699. lock (mainLoop.idleHandlers) {
  1700. ic = mainLoop.idleHandlers.Count;
  1701. }
  1702. return ic > 0;
  1703. }
  1704. void IMainLoopDriver.MainIteration ()
  1705. {
  1706. while (resultQueue.Count > 0) {
  1707. var inputRecords = resultQueue.Dequeue ();
  1708. if (inputRecords != null && inputRecords.Length > 0) {
  1709. var inputEvent = inputRecords [0];
  1710. ProcessInput?.Invoke (inputEvent);
  1711. }
  1712. }
  1713. if (winChanged) {
  1714. winChanged = false;
  1715. WinChanged?.Invoke (windowSize);
  1716. }
  1717. }
  1718. }
  1719. class WindowsClipboard : ClipboardBase {
  1720. public WindowsClipboard ()
  1721. {
  1722. IsSupported = IsClipboardFormatAvailable (cfUnicodeText);
  1723. }
  1724. public override bool IsSupported { get; }
  1725. protected override string GetClipboardDataImpl ()
  1726. {
  1727. //if (!IsClipboardFormatAvailable (cfUnicodeText))
  1728. // return null;
  1729. try {
  1730. if (!OpenClipboard (IntPtr.Zero))
  1731. return null;
  1732. IntPtr handle = GetClipboardData (cfUnicodeText);
  1733. if (handle == IntPtr.Zero)
  1734. return null;
  1735. IntPtr pointer = IntPtr.Zero;
  1736. try {
  1737. pointer = GlobalLock (handle);
  1738. if (pointer == IntPtr.Zero)
  1739. return null;
  1740. int size = GlobalSize (handle);
  1741. byte [] buff = new byte [size];
  1742. Marshal.Copy (pointer, buff, 0, size);
  1743. return System.Text.Encoding.Unicode.GetString (buff)
  1744. .TrimEnd ('\0');
  1745. } finally {
  1746. if (pointer != IntPtr.Zero)
  1747. GlobalUnlock (handle);
  1748. }
  1749. } finally {
  1750. CloseClipboard ();
  1751. }
  1752. }
  1753. protected override void SetClipboardDataImpl (string text)
  1754. {
  1755. OpenClipboard ();
  1756. EmptyClipboard ();
  1757. IntPtr hGlobal = default;
  1758. try {
  1759. var bytes = (text.Length + 1) * 2;
  1760. hGlobal = Marshal.AllocHGlobal (bytes);
  1761. if (hGlobal == default) {
  1762. ThrowWin32 ();
  1763. }
  1764. var target = GlobalLock (hGlobal);
  1765. if (target == default) {
  1766. ThrowWin32 ();
  1767. }
  1768. try {
  1769. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1770. } finally {
  1771. GlobalUnlock (target);
  1772. }
  1773. if (SetClipboardData (cfUnicodeText, hGlobal) == default) {
  1774. ThrowWin32 ();
  1775. }
  1776. hGlobal = default;
  1777. } finally {
  1778. if (hGlobal != default) {
  1779. Marshal.FreeHGlobal (hGlobal);
  1780. }
  1781. CloseClipboard ();
  1782. }
  1783. }
  1784. void OpenClipboard ()
  1785. {
  1786. var num = 10;
  1787. while (true) {
  1788. if (OpenClipboard (default)) {
  1789. break;
  1790. }
  1791. if (--num == 0) {
  1792. ThrowWin32 ();
  1793. }
  1794. Thread.Sleep (100);
  1795. }
  1796. }
  1797. const uint cfUnicodeText = 13;
  1798. void ThrowWin32 ()
  1799. {
  1800. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1801. }
  1802. [DllImport ("User32.dll", SetLastError = true)]
  1803. [return: MarshalAs (UnmanagedType.Bool)]
  1804. static extern bool IsClipboardFormatAvailable (uint format);
  1805. [DllImport ("kernel32.dll", SetLastError = true)]
  1806. static extern int GlobalSize (IntPtr handle);
  1807. [DllImport ("kernel32.dll", SetLastError = true)]
  1808. static extern IntPtr GlobalLock (IntPtr hMem);
  1809. [DllImport ("kernel32.dll", SetLastError = true)]
  1810. [return: MarshalAs (UnmanagedType.Bool)]
  1811. static extern bool GlobalUnlock (IntPtr hMem);
  1812. [DllImport ("user32.dll", SetLastError = true)]
  1813. [return: MarshalAs (UnmanagedType.Bool)]
  1814. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1815. [DllImport ("user32.dll", SetLastError = true)]
  1816. [return: MarshalAs (UnmanagedType.Bool)]
  1817. static extern bool CloseClipboard ();
  1818. [DllImport ("user32.dll", SetLastError = true)]
  1819. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1820. [DllImport ("user32.dll")]
  1821. static extern bool EmptyClipboard ();
  1822. [DllImport ("user32.dll", SetLastError = true)]
  1823. static extern IntPtr GetClipboardData (uint uFormat);
  1824. }
  1825. }