WindowsDriver.cs 63 KB

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