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