WindowsDriver.cs 64 KB

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