WindowsDriver.cs 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100
  1. //
  2. // WindowsDriver.cs: Windows specific driver
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. // Nick Van Dyck ([email protected])
  7. //
  8. // Copyright (c) 2018
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11. // of this software and associated documentation files (the "Software"), to deal
  12. // in the Software without restriction, including without limitation the rights
  13. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. // copies of the Software, and to permit persons to whom the Software is
  15. // furnished to do so, subject to the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be included in all
  18. // copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  26. // SOFTWARE.
  27. //
  28. using NStack;
  29. using System;
  30. using System.Collections.Generic;
  31. using System.ComponentModel;
  32. using System.Linq;
  33. using System.Runtime.InteropServices;
  34. using System.Threading;
  35. using System.Threading.Tasks;
  36. namespace Terminal.Gui {
  37. internal class WindowsConsole {
  38. public const int STD_OUTPUT_HANDLE = -11;
  39. public const int STD_INPUT_HANDLE = -10;
  40. public const int STD_ERROR_HANDLE = -12;
  41. internal IntPtr InputHandle, OutputHandle;
  42. IntPtr ScreenBuffer;
  43. readonly uint originalConsoleMode;
  44. CursorVisibility? initialCursorVisibility = null;
  45. CursorVisibility? currentCursorVisibility = null;
  46. CursorVisibility? pendingCursorVisibility = null;
  47. public WindowsConsole ()
  48. {
  49. InputHandle = GetStdHandle (STD_INPUT_HANDLE);
  50. OutputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  51. originalConsoleMode = ConsoleMode;
  52. var newConsoleMode = originalConsoleMode;
  53. newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
  54. newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
  55. newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput;
  56. ConsoleMode = newConsoleMode;
  57. }
  58. public CharInfo [] OriginalStdOutChars;
  59. public bool WriteToConsole (Size size, CharInfo [] charInfoBuffer, Coord coords, SmallRect window)
  60. {
  61. if (ScreenBuffer == IntPtr.Zero) {
  62. ReadFromConsoleOutput (size, coords, ref window);
  63. }
  64. return WriteConsoleOutput (ScreenBuffer, charInfoBuffer, coords, new Coord () { X = window.Left, Y = window.Top }, ref window);
  65. }
  66. public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window)
  67. {
  68. ScreenBuffer = CreateConsoleScreenBuffer (
  69. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  70. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  71. IntPtr.Zero,
  72. 1,
  73. IntPtr.Zero
  74. );
  75. if (ScreenBuffer == INVALID_HANDLE_VALUE) {
  76. var err = Marshal.GetLastWin32Error ();
  77. if (err != 0)
  78. throw new System.ComponentModel.Win32Exception (err);
  79. }
  80. if (!initialCursorVisibility.HasValue && GetCursorVisibility (out CursorVisibility visibility)) {
  81. initialCursorVisibility = visibility;
  82. }
  83. if (!SetConsoleActiveScreenBuffer (ScreenBuffer)) {
  84. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  85. }
  86. OriginalStdOutChars = new CharInfo [size.Height * size.Width];
  87. if (!ReadConsoleOutput (ScreenBuffer, OriginalStdOutChars, coords, new Coord () { X = 0, Y = 0 }, ref window)) {
  88. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  89. }
  90. }
  91. public bool SetCursorPosition (Coord position)
  92. {
  93. return SetConsoleCursorPosition (ScreenBuffer, position);
  94. }
  95. public void SetInitialCursorVisibility ()
  96. {
  97. if (initialCursorVisibility.HasValue == false && GetCursorVisibility (out CursorVisibility visibility)) {
  98. initialCursorVisibility = visibility;
  99. }
  100. }
  101. public bool GetCursorVisibility (out CursorVisibility visibility)
  102. {
  103. if (!GetConsoleCursorInfo (ScreenBuffer, out ConsoleCursorInfo info)) {
  104. var err = Marshal.GetLastWin32Error ();
  105. if (err != 0) {
  106. throw new System.ComponentModel.Win32Exception (err);
  107. }
  108. visibility = Gui.CursorVisibility.Default;
  109. return false;
  110. }
  111. if (!info.bVisible)
  112. visibility = CursorVisibility.Invisible;
  113. else if (info.dwSize > 50)
  114. visibility = CursorVisibility.Box;
  115. else
  116. visibility = CursorVisibility.Underline;
  117. return true;
  118. }
  119. public bool EnsureCursorVisibility ()
  120. {
  121. if (initialCursorVisibility.HasValue && pendingCursorVisibility.HasValue && SetCursorVisibility (pendingCursorVisibility.Value)) {
  122. pendingCursorVisibility = null;
  123. return true;
  124. }
  125. return false;
  126. }
  127. public void ForceRefreshCursorVisibility ()
  128. {
  129. if (currentCursorVisibility.HasValue) {
  130. pendingCursorVisibility = currentCursorVisibility;
  131. currentCursorVisibility = null;
  132. }
  133. }
  134. public bool SetCursorVisibility (CursorVisibility visibility)
  135. {
  136. if (initialCursorVisibility.HasValue == false) {
  137. pendingCursorVisibility = visibility;
  138. return false;
  139. }
  140. if (currentCursorVisibility.HasValue == false || currentCursorVisibility.Value != visibility) {
  141. ConsoleCursorInfo info = new ConsoleCursorInfo {
  142. dwSize = (uint)visibility & 0x00FF,
  143. bVisible = ((uint)visibility & 0xFF00) != 0
  144. };
  145. if (!SetConsoleCursorInfo (ScreenBuffer, ref info))
  146. return false;
  147. currentCursorVisibility = visibility;
  148. }
  149. return true;
  150. }
  151. public void Cleanup ()
  152. {
  153. if (initialCursorVisibility.HasValue) {
  154. SetCursorVisibility (initialCursorVisibility.Value);
  155. }
  156. SetConsoleOutputWindow (out _);
  157. ConsoleMode = originalConsoleMode;
  158. //ContinueListeningForConsoleEvents = false;
  159. if (!SetConsoleActiveScreenBuffer (OutputHandle)) {
  160. var err = Marshal.GetLastWin32Error ();
  161. Console.WriteLine ("Error: {0}", err);
  162. }
  163. if (ScreenBuffer != IntPtr.Zero)
  164. CloseHandle (ScreenBuffer);
  165. ScreenBuffer = IntPtr.Zero;
  166. }
  167. internal Size GetConsoleBufferWindow (out Point position)
  168. {
  169. if (ScreenBuffer == IntPtr.Zero) {
  170. position = Point.Empty;
  171. return Size.Empty;
  172. }
  173. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  174. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  175. if (!GetConsoleScreenBufferInfoEx (ScreenBuffer, ref csbi)) {
  176. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  177. position = Point.Empty;
  178. return Size.Empty;
  179. }
  180. var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
  181. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  182. position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
  183. return sz;
  184. }
  185. internal Size GetConsoleOutputWindow (out Point position)
  186. {
  187. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  188. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  189. if (!GetConsoleScreenBufferInfoEx (OutputHandle, ref csbi)) {
  190. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  191. }
  192. var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
  193. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  194. position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
  195. return sz;
  196. }
  197. internal Size SetConsoleWindow (short cols, short rows)
  198. {
  199. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  200. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  201. if (!GetConsoleScreenBufferInfoEx (ScreenBuffer, ref csbi)) {
  202. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  203. }
  204. var maxWinSize = GetLargestConsoleWindowSize (ScreenBuffer);
  205. var newCols = Math.Min (cols, maxWinSize.X);
  206. var newRows = Math.Min (rows, maxWinSize.Y);
  207. csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1));
  208. csbi.srWindow = new SmallRect (0, 0, newCols, newRows);
  209. csbi.dwMaximumWindowSize = new Coord (newCols, newRows);
  210. if (!SetConsoleScreenBufferInfoEx (ScreenBuffer, ref csbi)) {
  211. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  212. }
  213. var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0));
  214. if (!SetConsoleWindowInfo (OutputHandle, true, ref winRect)) {
  215. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  216. return new Size (cols, rows);
  217. }
  218. SetConsoleOutputWindow (csbi);
  219. return new Size (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1);
  220. }
  221. void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi)
  222. {
  223. if (ScreenBuffer != IntPtr.Zero && !SetConsoleScreenBufferInfoEx (ScreenBuffer, ref csbi)) {
  224. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  225. }
  226. }
  227. internal Size SetConsoleOutputWindow (out Point position)
  228. {
  229. if (ScreenBuffer == IntPtr.Zero) {
  230. position = Point.Empty;
  231. return Size.Empty;
  232. }
  233. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  234. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  235. if (!GetConsoleScreenBufferInfoEx (ScreenBuffer, ref csbi)) {
  236. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  237. }
  238. var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
  239. Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0));
  240. position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
  241. SetConsoleOutputWindow (csbi);
  242. var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0));
  243. if (!SetConsoleWindowInfo (OutputHandle, true, ref winRect)) {
  244. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  245. }
  246. return sz;
  247. }
  248. //bool ContinueListeningForConsoleEvents = true;
  249. public uint ConsoleMode {
  250. get {
  251. GetConsoleMode (InputHandle, out uint v);
  252. return v;
  253. }
  254. set {
  255. SetConsoleMode (InputHandle, value);
  256. }
  257. }
  258. [Flags]
  259. public enum ConsoleModes : uint {
  260. EnableProcessedInput = 1,
  261. EnableMouseInput = 16,
  262. EnableQuickEditMode = 64,
  263. EnableExtendedFlags = 128,
  264. }
  265. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  266. public struct KeyEventRecord {
  267. [FieldOffset (0), MarshalAs (UnmanagedType.Bool)]
  268. public bool bKeyDown;
  269. [FieldOffset (4), MarshalAs (UnmanagedType.U2)]
  270. public ushort wRepeatCount;
  271. [FieldOffset (6), MarshalAs (UnmanagedType.U2)]
  272. public ushort wVirtualKeyCode;
  273. [FieldOffset (8), MarshalAs (UnmanagedType.U2)]
  274. public ushort wVirtualScanCode;
  275. [FieldOffset (10)]
  276. public char UnicodeChar;
  277. [FieldOffset (12), MarshalAs (UnmanagedType.U4)]
  278. public ControlKeyState dwControlKeyState;
  279. }
  280. [Flags]
  281. public enum ButtonState {
  282. Button1Pressed = 1,
  283. Button2Pressed = 4,
  284. Button3Pressed = 8,
  285. Button4Pressed = 16,
  286. RightmostButtonPressed = 2
  287. }
  288. [Flags]
  289. public enum ControlKeyState {
  290. RightAltPressed = 1,
  291. LeftAltPressed = 2,
  292. RightControlPressed = 4,
  293. LeftControlPressed = 8,
  294. ShiftPressed = 16,
  295. NumlockOn = 32,
  296. ScrolllockOn = 64,
  297. CapslockOn = 128,
  298. EnhancedKey = 256
  299. }
  300. [Flags]
  301. public enum EventFlags {
  302. MouseMoved = 1,
  303. DoubleClick = 2,
  304. MouseWheeled = 4,
  305. MouseHorizontalWheeled = 8
  306. }
  307. [StructLayout (LayoutKind.Explicit)]
  308. public struct MouseEventRecord {
  309. [FieldOffset (0)]
  310. public Coord MousePosition;
  311. [FieldOffset (4)]
  312. public ButtonState ButtonState;
  313. [FieldOffset (8)]
  314. public ControlKeyState ControlKeyState;
  315. [FieldOffset (12)]
  316. public EventFlags EventFlags;
  317. public override string ToString ()
  318. {
  319. return $"[Mouse({MousePosition},{ButtonState},{ControlKeyState},{EventFlags}";
  320. }
  321. }
  322. public struct WindowBufferSizeRecord {
  323. public Coord size;
  324. public WindowBufferSizeRecord (short x, short y)
  325. {
  326. this.size = new Coord (x, y);
  327. }
  328. public override string ToString () => $"[WindowBufferSize{size}";
  329. }
  330. [StructLayout (LayoutKind.Sequential)]
  331. public struct MenuEventRecord {
  332. public uint dwCommandId;
  333. }
  334. [StructLayout (LayoutKind.Sequential)]
  335. public struct FocusEventRecord {
  336. public uint bSetFocus;
  337. }
  338. public enum EventType : ushort {
  339. Focus = 0x10,
  340. Key = 0x1,
  341. Menu = 0x8,
  342. Mouse = 2,
  343. WindowBufferSize = 4
  344. }
  345. [StructLayout (LayoutKind.Explicit)]
  346. public struct InputRecord {
  347. [FieldOffset (0)]
  348. public EventType EventType;
  349. [FieldOffset (4)]
  350. public KeyEventRecord KeyEvent;
  351. [FieldOffset (4)]
  352. public MouseEventRecord MouseEvent;
  353. [FieldOffset (4)]
  354. public WindowBufferSizeRecord WindowBufferSizeEvent;
  355. [FieldOffset (4)]
  356. public MenuEventRecord MenuEvent;
  357. [FieldOffset (4)]
  358. public FocusEventRecord FocusEvent;
  359. public override string ToString ()
  360. {
  361. switch (EventType) {
  362. case EventType.Focus:
  363. return FocusEvent.ToString ();
  364. case EventType.Key:
  365. return KeyEvent.ToString ();
  366. case EventType.Menu:
  367. return MenuEvent.ToString ();
  368. case EventType.Mouse:
  369. return MouseEvent.ToString ();
  370. case EventType.WindowBufferSize:
  371. return WindowBufferSizeEvent.ToString ();
  372. default:
  373. return "Unknown event type: " + EventType;
  374. }
  375. }
  376. };
  377. [Flags]
  378. enum ShareMode : uint {
  379. FileShareRead = 1,
  380. FileShareWrite = 2,
  381. }
  382. [Flags]
  383. enum DesiredAccess : uint {
  384. GenericRead = 2147483648,
  385. GenericWrite = 1073741824,
  386. }
  387. [StructLayout (LayoutKind.Sequential)]
  388. public struct ConsoleScreenBufferInfo {
  389. public Coord dwSize;
  390. public Coord dwCursorPosition;
  391. public ushort wAttributes;
  392. public SmallRect srWindow;
  393. public Coord dwMaximumWindowSize;
  394. }
  395. [StructLayout (LayoutKind.Sequential)]
  396. public struct Coord {
  397. public short X;
  398. public short Y;
  399. public Coord (short X, short Y)
  400. {
  401. this.X = X;
  402. this.Y = Y;
  403. }
  404. public override string ToString () => $"({X},{Y})";
  405. };
  406. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  407. public struct CharUnion {
  408. [FieldOffset (0)] public char UnicodeChar;
  409. [FieldOffset (0)] public byte AsciiChar;
  410. }
  411. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  412. public struct CharInfo {
  413. [FieldOffset (0)] public CharUnion Char;
  414. [FieldOffset (2)] public ushort Attributes;
  415. }
  416. [StructLayout (LayoutKind.Sequential)]
  417. public struct SmallRect {
  418. public short Left;
  419. public short Top;
  420. public short Right;
  421. public short Bottom;
  422. public SmallRect (short left, short top, short right, short bottom)
  423. {
  424. Left = left;
  425. Top = top;
  426. Right = right;
  427. Bottom = bottom;
  428. }
  429. public static void MakeEmpty (ref SmallRect rect)
  430. {
  431. rect.Left = -1;
  432. }
  433. public static void Update (ref SmallRect rect, short col, short row)
  434. {
  435. if (rect.Left == -1) {
  436. //System.Diagnostics.Debugger.Log (0, "debug", $"damager From Empty {col},{row}\n");
  437. rect.Left = rect.Right = col;
  438. rect.Bottom = rect.Top = row;
  439. return;
  440. }
  441. if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
  442. return;
  443. if (col < rect.Left)
  444. rect.Left = col;
  445. if (col > rect.Right)
  446. rect.Right = col;
  447. if (row < rect.Top)
  448. rect.Top = row;
  449. if (row > rect.Bottom)
  450. rect.Bottom = row;
  451. //System.Diagnostics.Debugger.Log (0, "debug", $"Expanding {rect.ToString ()}\n");
  452. }
  453. public override string ToString ()
  454. {
  455. return $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}";
  456. }
  457. }
  458. [StructLayout (LayoutKind.Sequential)]
  459. public struct ConsoleKeyInfoEx {
  460. public ConsoleKeyInfo consoleKeyInfo;
  461. public bool CapsLock;
  462. public bool NumLock;
  463. public bool Scrolllock;
  464. public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock, bool scrolllock)
  465. {
  466. this.consoleKeyInfo = consoleKeyInfo;
  467. CapsLock = capslock;
  468. NumLock = numlock;
  469. Scrolllock = scrolllock;
  470. }
  471. }
  472. [DllImport ("kernel32.dll", SetLastError = true)]
  473. static extern IntPtr GetStdHandle (int nStdHandle);
  474. [DllImport ("kernel32.dll", SetLastError = true)]
  475. static extern bool CloseHandle (IntPtr handle);
  476. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  477. public static extern bool ReadConsoleInput (
  478. IntPtr hConsoleInput,
  479. IntPtr lpBuffer,
  480. uint nLength,
  481. out uint lpNumberOfEventsRead);
  482. [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  483. static extern bool ReadConsoleOutput (
  484. IntPtr hConsoleOutput,
  485. [Out] CharInfo [] lpBuffer,
  486. Coord dwBufferSize,
  487. Coord dwBufferCoord,
  488. ref SmallRect lpReadRegion
  489. );
  490. [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutput", SetLastError = true, CharSet = CharSet.Unicode)]
  491. static extern bool WriteConsoleOutput (
  492. IntPtr hConsoleOutput,
  493. CharInfo [] lpBuffer,
  494. Coord dwBufferSize,
  495. Coord dwBufferCoord,
  496. ref SmallRect lpWriteRegion
  497. );
  498. [DllImport ("kernel32.dll")]
  499. static extern bool SetConsoleCursorPosition (IntPtr hConsoleOutput, Coord dwCursorPosition);
  500. [StructLayout (LayoutKind.Sequential)]
  501. public struct ConsoleCursorInfo {
  502. public uint dwSize;
  503. public bool bVisible;
  504. }
  505. [DllImport ("kernel32.dll", SetLastError = true)]
  506. static extern bool SetConsoleCursorInfo (IntPtr hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
  507. [DllImport ("kernel32.dll", SetLastError = true)]
  508. static extern bool GetConsoleCursorInfo (IntPtr hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
  509. [DllImport ("kernel32.dll")]
  510. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  511. [DllImport ("kernel32.dll")]
  512. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  513. [DllImport ("kernel32.dll", SetLastError = true)]
  514. static extern IntPtr CreateConsoleScreenBuffer (
  515. DesiredAccess dwDesiredAccess,
  516. ShareMode dwShareMode,
  517. IntPtr secutiryAttributes,
  518. uint flags,
  519. IntPtr screenBufferData
  520. );
  521. internal static IntPtr INVALID_HANDLE_VALUE = new IntPtr (-1);
  522. [DllImport ("kernel32.dll", SetLastError = true)]
  523. static extern bool SetConsoleActiveScreenBuffer (IntPtr Handle);
  524. [DllImport ("kernel32.dll", SetLastError = true)]
  525. static extern bool GetNumberOfConsoleInputEvents (IntPtr handle, out uint lpcNumberOfEvents);
  526. public uint InputEventCount {
  527. get {
  528. GetNumberOfConsoleInputEvents (InputHandle, out uint v);
  529. return v;
  530. }
  531. }
  532. public InputRecord [] ReadConsoleInput ()
  533. {
  534. const int bufferSize = 1;
  535. var pRecord = Marshal.AllocHGlobal (Marshal.SizeOf<InputRecord> () * bufferSize);
  536. try {
  537. ReadConsoleInput (InputHandle, pRecord, bufferSize,
  538. out var numberEventsRead);
  539. return numberEventsRead == 0
  540. ? null
  541. : new [] { Marshal.PtrToStructure<InputRecord> (pRecord) };
  542. } catch (Exception) {
  543. return null;
  544. } finally {
  545. Marshal.FreeHGlobal (pRecord);
  546. }
  547. }
  548. #if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
  549. [DllImport ("kernel32.dll", ExactSpelling = true)]
  550. static extern IntPtr GetConsoleWindow ();
  551. [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  552. static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
  553. public const int HIDE = 0;
  554. public const int MAXIMIZE = 3;
  555. public const int MINIMIZE = 6;
  556. public const int RESTORE = 9;
  557. internal void ShowWindow (int state)
  558. {
  559. IntPtr thisConsole = GetConsoleWindow ();
  560. ShowWindow (thisConsole, state);
  561. }
  562. #endif
  563. // See: https://github.com/gui-cs/Terminal.Gui/issues/357
  564. [StructLayout (LayoutKind.Sequential)]
  565. public struct CONSOLE_SCREEN_BUFFER_INFOEX {
  566. public uint cbSize;
  567. public Coord dwSize;
  568. public Coord dwCursorPosition;
  569. public ushort wAttributes;
  570. public SmallRect srWindow;
  571. public Coord dwMaximumWindowSize;
  572. public ushort wPopupAttributes;
  573. public bool bFullscreenSupported;
  574. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)]
  575. public COLORREF [] ColorTable;
  576. }
  577. [StructLayout (LayoutKind.Explicit, Size = 4)]
  578. public struct COLORREF {
  579. public COLORREF (byte r, byte g, byte b)
  580. {
  581. Value = 0;
  582. R = r;
  583. G = g;
  584. B = b;
  585. }
  586. public COLORREF (uint value)
  587. {
  588. R = 0;
  589. G = 0;
  590. B = 0;
  591. Value = value & 0x00FFFFFF;
  592. }
  593. [FieldOffset (0)]
  594. public byte R;
  595. [FieldOffset (1)]
  596. public byte G;
  597. [FieldOffset (2)]
  598. public byte B;
  599. [FieldOffset (0)]
  600. public uint Value;
  601. }
  602. [DllImport ("kernel32.dll", SetLastError = true)]
  603. static extern bool GetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  604. [DllImport ("kernel32.dll", SetLastError = true)]
  605. static extern bool SetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo);
  606. [DllImport ("kernel32.dll", SetLastError = true)]
  607. static extern bool SetConsoleWindowInfo (
  608. IntPtr hConsoleOutput,
  609. bool bAbsolute,
  610. [In] ref SmallRect lpConsoleWindow);
  611. [DllImport ("kernel32.dll", SetLastError = true)]
  612. static extern Coord GetLargestConsoleWindowSize (
  613. IntPtr hConsoleOutput);
  614. }
  615. internal class WindowsDriver : ConsoleDriver {
  616. static bool sync = false;
  617. WindowsConsole.CharInfo [] OutputBuffer;
  618. int cols, rows, left, top;
  619. WindowsConsole.SmallRect damageRegion;
  620. IClipboard clipboard;
  621. int [,,] contents;
  622. public override int Cols => cols;
  623. public override int Rows => rows;
  624. public override int Left => left;
  625. public override int Top => top;
  626. public override bool HeightAsBuffer { get; set; }
  627. public override IClipboard Clipboard => clipboard;
  628. public override int [,,] Contents => contents;
  629. public WindowsConsole WinConsole { get; private set; }
  630. Action<KeyEvent> keyHandler;
  631. Action<KeyEvent> keyDownHandler;
  632. Action<KeyEvent> keyUpHandler;
  633. Action<MouseEvent> mouseHandler;
  634. public WindowsDriver ()
  635. {
  636. WinConsole = new WindowsConsole ();
  637. clipboard = new WindowsClipboard ();
  638. }
  639. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  640. {
  641. this.keyHandler = keyHandler;
  642. this.keyDownHandler = keyDownHandler;
  643. this.keyUpHandler = keyUpHandler;
  644. this.mouseHandler = mouseHandler;
  645. var mLoop = mainLoop.Driver as WindowsMainLoop;
  646. mLoop.ProcessInput = (e) => ProcessInput (e);
  647. mLoop.WinChanged = (e) => {
  648. ChangeWin (e);
  649. };
  650. }
  651. private void ChangeWin (Size e)
  652. {
  653. if (!HeightAsBuffer) {
  654. var w = e.Width;
  655. if (w == cols - 3 && e.Height < rows) {
  656. w += 3;
  657. }
  658. var newSize = WinConsole.SetConsoleWindow (
  659. (short)Math.Max (w, 16), (short)Math.Max (e.Height, 0));
  660. left = 0;
  661. top = 0;
  662. cols = newSize.Width;
  663. rows = newSize.Height;
  664. ResizeScreen ();
  665. UpdateOffScreen ();
  666. TerminalResized.Invoke ();
  667. }
  668. }
  669. void ProcessInput (WindowsConsole.InputRecord inputEvent)
  670. {
  671. switch (inputEvent.EventType) {
  672. case WindowsConsole.EventType.Key:
  673. var fromPacketKey = inputEvent.KeyEvent.wVirtualKeyCode == (uint)ConsoleKey.Packet;
  674. if (fromPacketKey) {
  675. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  676. }
  677. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  678. //var ke = inputEvent.KeyEvent;
  679. //System.Diagnostics.Debug.WriteLine ($"fromPacketKey: {fromPacketKey}");
  680. //if (ke.UnicodeChar == '\0') {
  681. // System.Diagnostics.Debug.WriteLine ("UnicodeChar: 0'\\0'");
  682. //} else if (ke.UnicodeChar == 13) {
  683. // System.Diagnostics.Debug.WriteLine ("UnicodeChar: 13'\\n'");
  684. //} else {
  685. // System.Diagnostics.Debug.WriteLine ($"UnicodeChar: {(uint)ke.UnicodeChar}'{ke.UnicodeChar}'");
  686. //}
  687. //System.Diagnostics.Debug.WriteLine ($"bKeyDown: {ke.bKeyDown}");
  688. //System.Diagnostics.Debug.WriteLine ($"dwControlKeyState: {ke.dwControlKeyState}");
  689. //System.Diagnostics.Debug.WriteLine ($"wRepeatCount: {ke.wRepeatCount}");
  690. //System.Diagnostics.Debug.WriteLine ($"wVirtualKeyCode: {ke.wVirtualKeyCode}");
  691. //System.Diagnostics.Debug.WriteLine ($"wVirtualScanCode: {ke.wVirtualScanCode}");
  692. if (map == (Key)0xffffffff) {
  693. KeyEvent key = new KeyEvent ();
  694. // Shift = VK_SHIFT = 0x10
  695. // Ctrl = VK_CONTROL = 0x11
  696. // Alt = VK_MENU = 0x12
  697. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
  698. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
  699. }
  700. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
  701. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
  702. }
  703. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
  704. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
  705. }
  706. switch (inputEvent.KeyEvent.dwControlKeyState) {
  707. case WindowsConsole.ControlKeyState.RightAltPressed:
  708. case WindowsConsole.ControlKeyState.RightAltPressed |
  709. WindowsConsole.ControlKeyState.LeftControlPressed |
  710. WindowsConsole.ControlKeyState.EnhancedKey:
  711. case WindowsConsole.ControlKeyState.EnhancedKey:
  712. key = new KeyEvent (Key.CtrlMask | Key.AltMask, keyModifiers);
  713. break;
  714. case WindowsConsole.ControlKeyState.LeftAltPressed:
  715. key = new KeyEvent (Key.AltMask, keyModifiers);
  716. break;
  717. case WindowsConsole.ControlKeyState.RightControlPressed:
  718. case WindowsConsole.ControlKeyState.LeftControlPressed:
  719. key = new KeyEvent (Key.CtrlMask, keyModifiers);
  720. break;
  721. case WindowsConsole.ControlKeyState.ShiftPressed:
  722. key = new KeyEvent (Key.ShiftMask, keyModifiers);
  723. break;
  724. case WindowsConsole.ControlKeyState.NumlockOn:
  725. break;
  726. case WindowsConsole.ControlKeyState.ScrolllockOn:
  727. break;
  728. case WindowsConsole.ControlKeyState.CapslockOn:
  729. break;
  730. default:
  731. switch (inputEvent.KeyEvent.wVirtualKeyCode) {
  732. case 0x10:
  733. key = new KeyEvent (Key.ShiftMask, keyModifiers);
  734. break;
  735. case 0x11:
  736. key = new KeyEvent (Key.CtrlMask, keyModifiers);
  737. break;
  738. case 0x12:
  739. key = new KeyEvent (Key.AltMask, keyModifiers);
  740. break;
  741. default:
  742. key = new KeyEvent (Key.Unknown, keyModifiers);
  743. break;
  744. }
  745. break;
  746. }
  747. if (inputEvent.KeyEvent.bKeyDown)
  748. keyDownHandler (key);
  749. else
  750. keyUpHandler (key);
  751. } else {
  752. if (inputEvent.KeyEvent.bKeyDown) {
  753. // May occurs using SendKeys
  754. if (keyModifiers == null)
  755. keyModifiers = new KeyModifiers ();
  756. // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
  757. keyDownHandler (new KeyEvent (map, keyModifiers));
  758. keyHandler (new KeyEvent (map, keyModifiers));
  759. } else {
  760. keyUpHandler (new KeyEvent (map, keyModifiers));
  761. }
  762. }
  763. if (!inputEvent.KeyEvent.bKeyDown && inputEvent.KeyEvent.dwControlKeyState == 0) {
  764. keyModifiers = null;
  765. }
  766. break;
  767. case WindowsConsole.EventType.Mouse:
  768. var me = ToDriverMouse (inputEvent.MouseEvent);
  769. mouseHandler (me);
  770. if (processButtonClick) {
  771. mouseHandler (
  772. new MouseEvent () {
  773. X = me.X,
  774. Y = me.Y,
  775. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  776. });
  777. }
  778. break;
  779. case WindowsConsole.EventType.WindowBufferSize:
  780. var winSize = WinConsole.GetConsoleBufferWindow (out Point pos);
  781. left = pos.X;
  782. top = pos.Y;
  783. cols = inputEvent.WindowBufferSizeEvent.size.X;
  784. rows = inputEvent.WindowBufferSizeEvent.size.Y;
  785. //System.Diagnostics.Debug.WriteLine ($"{HeightAsBuffer},{cols},{rows}");
  786. ResizeScreen ();
  787. UpdateOffScreen ();
  788. TerminalResized?.Invoke ();
  789. break;
  790. case WindowsConsole.EventType.Focus:
  791. break;
  792. }
  793. }
  794. WindowsConsole.ButtonState? lastMouseButtonPressed = null;
  795. bool isButtonPressed = false;
  796. bool isButtonReleased = false;
  797. bool isButtonDoubleClicked = false;
  798. Point? point;
  799. Point pointMove;
  800. //int buttonPressedCount;
  801. bool isOneFingerDoubleClicked = false;
  802. bool processButtonClick;
  803. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  804. {
  805. MouseFlags mouseFlag = MouseFlags.AllEvents;
  806. //System.Diagnostics.Debug.WriteLine (
  807. // $"X:{mouseEvent.MousePosition.X};Y:{mouseEvent.MousePosition.Y};ButtonState:{mouseEvent.ButtonState};EventFlags:{mouseEvent.EventFlags}");
  808. if (isButtonDoubleClicked || isOneFingerDoubleClicked) {
  809. Application.MainLoop.AddIdle (() => {
  810. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  811. return false;
  812. });
  813. }
  814. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  815. // This will tell when a mouse button is pressed. When the button is released this event will
  816. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  817. // To map to the correct driver events we save the last pressed mouse button so we can
  818. // map to the correct clicked event.
  819. if ((lastMouseButtonPressed != null || isButtonReleased) && mouseEvent.ButtonState != 0) {
  820. lastMouseButtonPressed = null;
  821. //isButtonPressed = false;
  822. isButtonReleased = false;
  823. }
  824. var p = new Point () {
  825. X = mouseEvent.MousePosition.X,
  826. Y = mouseEvent.MousePosition.Y
  827. };
  828. //if (!isButtonPressed && buttonPressedCount < 2
  829. // && mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  830. // && (mouseEvent.ButtonState == WindowsConsole.ButtonState.Button1Pressed
  831. // || mouseEvent.ButtonState == WindowsConsole.ButtonState.Button2Pressed
  832. // || mouseEvent.ButtonState == WindowsConsole.ButtonState.Button3Pressed)) {
  833. // lastMouseButtonPressed = mouseEvent.ButtonState;
  834. // buttonPressedCount++;
  835. //} else if (!isButtonPressed && buttonPressedCount > 0 && mouseEvent.ButtonState == 0
  836. // && mouseEvent.EventFlags == 0) {
  837. // buttonPressedCount++;
  838. //}
  839. //System.Diagnostics.Debug.WriteLine ($"isButtonPressed: {isButtonPressed};buttonPressedCount: {buttonPressedCount};lastMouseButtonPressed: {lastMouseButtonPressed}");
  840. //System.Diagnostics.Debug.WriteLine ($"isOneFingerDoubleClicked: {isOneFingerDoubleClicked}");
  841. //if (buttonPressedCount == 1 && lastMouseButtonPressed != null && p == point
  842. // && lastMouseButtonPressed == WindowsConsole.ButtonState.Button1Pressed
  843. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button2Pressed
  844. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button3Pressed) {
  845. // switch (lastMouseButtonPressed) {
  846. // case WindowsConsole.ButtonState.Button1Pressed:
  847. // mouseFlag = MouseFlags.Button1DoubleClicked;
  848. // break;
  849. // case WindowsConsole.ButtonState.Button2Pressed:
  850. // mouseFlag = MouseFlags.Button2DoubleClicked;
  851. // break;
  852. // case WindowsConsole.ButtonState.Button3Pressed:
  853. // mouseFlag = MouseFlags.Button3DoubleClicked;
  854. // break;
  855. // }
  856. // isOneFingerDoubleClicked = true;
  857. //} else if (buttonPressedCount == 3 && lastMouseButtonPressed != null && isOneFingerDoubleClicked && p == point
  858. // && lastMouseButtonPressed == WindowsConsole.ButtonState.Button1Pressed
  859. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button2Pressed
  860. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button3Pressed) {
  861. // switch (lastMouseButtonPressed) {
  862. // case WindowsConsole.ButtonState.Button1Pressed:
  863. // mouseFlag = MouseFlags.Button1TripleClicked;
  864. // break;
  865. // case WindowsConsole.ButtonState.Button2Pressed:
  866. // mouseFlag = MouseFlags.Button2TripleClicked;
  867. // break;
  868. // case WindowsConsole.ButtonState.Button3Pressed:
  869. // mouseFlag = MouseFlags.Button3TripleClicked;
  870. // break;
  871. // }
  872. // buttonPressedCount = 0;
  873. // lastMouseButtonPressed = null;
  874. // isOneFingerDoubleClicked = false;
  875. // isButtonReleased = false;
  876. //}
  877. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && lastMouseButtonPressed == null && !isButtonDoubleClicked) ||
  878. (lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) &&
  879. mouseEvent.ButtonState != 0 && !isButtonReleased && !isButtonDoubleClicked)) {
  880. switch (mouseEvent.ButtonState) {
  881. case WindowsConsole.ButtonState.Button1Pressed:
  882. mouseFlag = MouseFlags.Button1Pressed;
  883. break;
  884. case WindowsConsole.ButtonState.Button2Pressed:
  885. mouseFlag = MouseFlags.Button2Pressed;
  886. break;
  887. case WindowsConsole.ButtonState.RightmostButtonPressed:
  888. mouseFlag = MouseFlags.Button3Pressed;
  889. break;
  890. }
  891. if (point == null)
  892. point = p;
  893. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  894. mouseFlag |= MouseFlags.ReportMousePosition;
  895. isButtonReleased = false;
  896. processButtonClick = false;
  897. }
  898. lastMouseButtonPressed = mouseEvent.ButtonState;
  899. isButtonPressed = true;
  900. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  901. Application.MainLoop.AddIdle (() => {
  902. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  903. return false;
  904. });
  905. }
  906. } else if (lastMouseButtonPressed != null && mouseEvent.EventFlags == 0
  907. && !isButtonReleased && !isButtonDoubleClicked && !isOneFingerDoubleClicked) {
  908. switch (lastMouseButtonPressed) {
  909. case WindowsConsole.ButtonState.Button1Pressed:
  910. mouseFlag = MouseFlags.Button1Released;
  911. break;
  912. case WindowsConsole.ButtonState.Button2Pressed:
  913. mouseFlag = MouseFlags.Button2Released;
  914. break;
  915. case WindowsConsole.ButtonState.RightmostButtonPressed:
  916. mouseFlag = MouseFlags.Button3Released;
  917. break;
  918. }
  919. isButtonPressed = false;
  920. isButtonReleased = true;
  921. if (point != null && (((Point)point).X == mouseEvent.MousePosition.X && ((Point)point).Y == mouseEvent.MousePosition.Y)) {
  922. processButtonClick = true;
  923. } else {
  924. point = null;
  925. }
  926. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  927. && !isOneFingerDoubleClicked && isButtonReleased && p == point) {
  928. mouseFlag = ProcessButtonClick (mouseEvent);
  929. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  930. switch (mouseEvent.ButtonState) {
  931. case WindowsConsole.ButtonState.Button1Pressed:
  932. mouseFlag = MouseFlags.Button1DoubleClicked;
  933. break;
  934. case WindowsConsole.ButtonState.Button2Pressed:
  935. mouseFlag = MouseFlags.Button2DoubleClicked;
  936. break;
  937. case WindowsConsole.ButtonState.RightmostButtonPressed:
  938. mouseFlag = MouseFlags.Button3DoubleClicked;
  939. break;
  940. }
  941. isButtonDoubleClicked = true;
  942. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && isButtonDoubleClicked) {
  943. switch (mouseEvent.ButtonState) {
  944. case WindowsConsole.ButtonState.Button1Pressed:
  945. mouseFlag = MouseFlags.Button1TripleClicked;
  946. break;
  947. case WindowsConsole.ButtonState.Button2Pressed:
  948. mouseFlag = MouseFlags.Button2TripleClicked;
  949. break;
  950. case WindowsConsole.ButtonState.RightmostButtonPressed:
  951. mouseFlag = MouseFlags.Button3TripleClicked;
  952. break;
  953. }
  954. isButtonDoubleClicked = false;
  955. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  956. switch ((int)mouseEvent.ButtonState) {
  957. case int v when v > 0:
  958. mouseFlag = MouseFlags.WheeledUp;
  959. break;
  960. case int v when v < 0:
  961. mouseFlag = MouseFlags.WheeledDown;
  962. break;
  963. }
  964. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  965. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  966. switch ((int)mouseEvent.ButtonState) {
  967. case int v when v > 0:
  968. mouseFlag = MouseFlags.WheeledLeft;
  969. break;
  970. case int v when v < 0:
  971. mouseFlag = MouseFlags.WheeledRight;
  972. break;
  973. }
  974. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled) {
  975. switch ((int)mouseEvent.ButtonState) {
  976. case int v when v < 0:
  977. mouseFlag = MouseFlags.WheeledLeft;
  978. break;
  979. case int v when v > 0:
  980. mouseFlag = MouseFlags.WheeledRight;
  981. break;
  982. }
  983. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  984. mouseFlag = MouseFlags.ReportMousePosition;
  985. if (mouseEvent.MousePosition.X != pointMove.X || mouseEvent.MousePosition.Y != pointMove.Y) {
  986. pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  987. }
  988. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  989. mouseFlag = 0;
  990. }
  991. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  992. //System.Diagnostics.Debug.WriteLine (
  993. // $"point.X:{(point != null ? ((Point)point).X : -1)};point.Y:{(point != null ? ((Point)point).Y : -1)}");
  994. return new MouseEvent () {
  995. X = mouseEvent.MousePosition.X,
  996. Y = mouseEvent.MousePosition.Y,
  997. Flags = mouseFlag
  998. };
  999. }
  1000. MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  1001. {
  1002. MouseFlags mouseFlag = 0;
  1003. switch (lastMouseButtonPressed) {
  1004. case WindowsConsole.ButtonState.Button1Pressed:
  1005. mouseFlag = MouseFlags.Button1Clicked;
  1006. break;
  1007. case WindowsConsole.ButtonState.Button2Pressed:
  1008. mouseFlag = MouseFlags.Button2Clicked;
  1009. break;
  1010. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1011. mouseFlag = MouseFlags.Button3Clicked;
  1012. break;
  1013. }
  1014. point = new Point () {
  1015. X = mouseEvent.MousePosition.X,
  1016. Y = mouseEvent.MousePosition.Y
  1017. };
  1018. lastMouseButtonPressed = null;
  1019. isButtonReleased = false;
  1020. processButtonClick = false;
  1021. point = null;
  1022. return mouseFlag;
  1023. }
  1024. async Task ProcessButtonDoubleClickedAsync ()
  1025. {
  1026. await Task.Delay (300);
  1027. isButtonDoubleClicked = false;
  1028. isOneFingerDoubleClicked = false;
  1029. //buttonPressedCount = 0;
  1030. }
  1031. async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1032. {
  1033. while (isButtonPressed) {
  1034. await Task.Delay (100);
  1035. var me = new MouseEvent () {
  1036. X = pointMove.X,
  1037. Y = pointMove.Y,
  1038. Flags = mouseFlag
  1039. };
  1040. var view = Application.WantContinuousButtonPressedView;
  1041. if (view == null) {
  1042. break;
  1043. }
  1044. if (isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1045. Application.MainLoop.Invoke (() => mouseHandler (me));
  1046. }
  1047. }
  1048. }
  1049. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1050. {
  1051. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  1052. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  1053. mouseFlag |= MouseFlags.ButtonCtrl;
  1054. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  1055. mouseFlag |= MouseFlags.ButtonShift;
  1056. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1057. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  1058. mouseFlag |= MouseFlags.ButtonAlt;
  1059. return mouseFlag;
  1060. }
  1061. KeyModifiers keyModifiers;
  1062. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1063. {
  1064. var state = keyEvent.dwControlKeyState;
  1065. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1066. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1067. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1068. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  1069. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  1070. bool scrolllock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  1071. if (keyModifiers == null)
  1072. keyModifiers = new KeyModifiers ();
  1073. if (shift)
  1074. keyModifiers.Shift = shift;
  1075. if (alt)
  1076. keyModifiers.Alt = alt;
  1077. if (control)
  1078. keyModifiers.Ctrl = control;
  1079. if (capslock)
  1080. keyModifiers.Capslock = capslock;
  1081. if (numlock)
  1082. keyModifiers.Numlock = numlock;
  1083. if (scrolllock)
  1084. keyModifiers.Scrolllock = scrolllock;
  1085. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1086. return new WindowsConsole.ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock, scrolllock);
  1087. }
  1088. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  1089. {
  1090. if (keyEvent.wVirtualKeyCode != (uint)ConsoleKey.Packet) {
  1091. return keyEvent;
  1092. }
  1093. var mod = new ConsoleModifiers ();
  1094. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1095. mod |= ConsoleModifiers.Shift;
  1096. }
  1097. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1098. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1099. mod |= ConsoleModifiers.Alt;
  1100. }
  1101. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed) ||
  1102. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)) {
  1103. mod |= ConsoleModifiers.Control;
  1104. }
  1105. var keyChar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyEvent.UnicodeChar, mod, out uint virtualKey, out uint scanCode);
  1106. return new WindowsConsole.KeyEventRecord {
  1107. UnicodeChar = (char)keyChar,
  1108. bKeyDown = keyEvent.bKeyDown,
  1109. dwControlKeyState = keyEvent.dwControlKeyState,
  1110. wRepeatCount = keyEvent.wRepeatCount,
  1111. wVirtualKeyCode = (ushort)virtualKey,
  1112. wVirtualScanCode = (ushort)scanCode
  1113. };
  1114. }
  1115. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  1116. {
  1117. var keyInfo = keyInfoEx.consoleKeyInfo;
  1118. switch (keyInfo.Key) {
  1119. case ConsoleKey.Escape:
  1120. return MapKeyModifiers (keyInfo, Key.Esc);
  1121. case ConsoleKey.Tab:
  1122. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  1123. case ConsoleKey.Clear:
  1124. return MapKeyModifiers (keyInfo, Key.Clear);
  1125. case ConsoleKey.Home:
  1126. return MapKeyModifiers (keyInfo, Key.Home);
  1127. case ConsoleKey.End:
  1128. return MapKeyModifiers (keyInfo, Key.End);
  1129. case ConsoleKey.LeftArrow:
  1130. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  1131. case ConsoleKey.RightArrow:
  1132. return MapKeyModifiers (keyInfo, Key.CursorRight);
  1133. case ConsoleKey.UpArrow:
  1134. return MapKeyModifiers (keyInfo, Key.CursorUp);
  1135. case ConsoleKey.DownArrow:
  1136. return MapKeyModifiers (keyInfo, Key.CursorDown);
  1137. case ConsoleKey.PageUp:
  1138. return MapKeyModifiers (keyInfo, Key.PageUp);
  1139. case ConsoleKey.PageDown:
  1140. return MapKeyModifiers (keyInfo, Key.PageDown);
  1141. case ConsoleKey.Enter:
  1142. return MapKeyModifiers (keyInfo, Key.Enter);
  1143. case ConsoleKey.Spacebar:
  1144. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  1145. case ConsoleKey.Backspace:
  1146. return MapKeyModifiers (keyInfo, Key.Backspace);
  1147. case ConsoleKey.Delete:
  1148. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  1149. case ConsoleKey.Insert:
  1150. return MapKeyModifiers (keyInfo, Key.InsertChar);
  1151. case ConsoleKey.PrintScreen:
  1152. return MapKeyModifiers (keyInfo, Key.PrintScreen);
  1153. case ConsoleKey.NumPad0:
  1154. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  1155. case ConsoleKey.NumPad1:
  1156. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  1157. case ConsoleKey.NumPad2:
  1158. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  1159. case ConsoleKey.NumPad3:
  1160. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  1161. case ConsoleKey.NumPad4:
  1162. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  1163. case ConsoleKey.NumPad5:
  1164. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  1165. case ConsoleKey.NumPad6:
  1166. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  1167. case ConsoleKey.NumPad7:
  1168. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  1169. case ConsoleKey.NumPad8:
  1170. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  1171. case ConsoleKey.NumPad9:
  1172. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  1173. case ConsoleKey.Oem1:
  1174. case ConsoleKey.Oem2:
  1175. case ConsoleKey.Oem3:
  1176. case ConsoleKey.Oem4:
  1177. case ConsoleKey.Oem5:
  1178. case ConsoleKey.Oem6:
  1179. case ConsoleKey.Oem7:
  1180. case ConsoleKey.Oem8:
  1181. case ConsoleKey.Oem102:
  1182. case ConsoleKey.OemPeriod:
  1183. case ConsoleKey.OemComma:
  1184. case ConsoleKey.OemPlus:
  1185. case ConsoleKey.OemMinus:
  1186. if (keyInfo.KeyChar == 0)
  1187. return Key.Unknown;
  1188. return (Key)((uint)keyInfo.KeyChar);
  1189. }
  1190. var key = keyInfo.Key;
  1191. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  1192. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  1193. var delta = key - ConsoleKey.A;
  1194. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1195. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1196. }
  1197. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1198. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1199. }
  1200. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1201. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1202. }
  1203. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1204. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1205. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1206. }
  1207. }
  1208. //return (Key)((uint)alphaBase + delta);
  1209. return (Key)((uint)keyInfo.KeyChar);
  1210. }
  1211. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1212. var delta = key - ConsoleKey.D0;
  1213. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1214. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1215. }
  1216. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1217. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1218. }
  1219. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1220. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1221. }
  1222. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1223. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30 || keyInfo.KeyChar == ((uint)Key.D0 + delta)) {
  1224. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1225. }
  1226. }
  1227. return (Key)((uint)keyInfo.KeyChar);
  1228. }
  1229. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1230. var delta = key - ConsoleKey.F1;
  1231. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1232. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1233. }
  1234. return (Key)((uint)Key.F1 + delta);
  1235. }
  1236. if (keyInfo.KeyChar != 0) {
  1237. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1238. }
  1239. return (Key)(0xffffffff);
  1240. }
  1241. private Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1242. {
  1243. Key keyMod = new Key ();
  1244. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
  1245. keyMod = Key.ShiftMask;
  1246. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
  1247. keyMod |= Key.CtrlMask;
  1248. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
  1249. keyMod |= Key.AltMask;
  1250. return keyMod != Key.Null ? keyMod | key : key;
  1251. }
  1252. public override void Init (Action terminalResized)
  1253. {
  1254. TerminalResized = terminalResized;
  1255. try {
  1256. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1257. cols = winSize.Width;
  1258. rows = winSize.Height;
  1259. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1260. ResizeScreen ();
  1261. UpdateOffScreen ();
  1262. CreateColors ();
  1263. } catch (Win32Exception e) {
  1264. throw new InvalidOperationException ("The Windows Console output window is not available.", e);
  1265. }
  1266. }
  1267. public override void ResizeScreen ()
  1268. {
  1269. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  1270. Clip = new Rect (0, 0, Cols, Rows);
  1271. damageRegion = new WindowsConsole.SmallRect () {
  1272. Top = 0,
  1273. Left = 0,
  1274. Bottom = (short)Rows,
  1275. Right = (short)Cols
  1276. };
  1277. WinConsole.ForceRefreshCursorVisibility ();
  1278. Console.Out.Write ("\x1b[3J");
  1279. Console.Out.Flush ();
  1280. }
  1281. public override void UpdateOffScreen ()
  1282. {
  1283. contents = new int [rows, cols, 3];
  1284. for (int row = 0; row < rows; row++) {
  1285. for (int col = 0; col < cols; col++) {
  1286. int position = row * cols + col;
  1287. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  1288. OutputBuffer [position].Char.UnicodeChar = ' ';
  1289. contents [row, col, 0] = OutputBuffer [position].Char.UnicodeChar;
  1290. contents [row, col, 1] = OutputBuffer [position].Attributes;
  1291. contents [row, col, 2] = 0;
  1292. }
  1293. }
  1294. }
  1295. int ccol, crow;
  1296. public override void Move (int col, int row)
  1297. {
  1298. ccol = col;
  1299. crow = row;
  1300. }
  1301. int GetOutputBufferPosition ()
  1302. {
  1303. return crow * Cols + ccol;
  1304. }
  1305. public override void AddRune (Rune rune)
  1306. {
  1307. rune = MakePrintable (rune);
  1308. var runeWidth = Rune.ColumnWidth (rune);
  1309. var position = GetOutputBufferPosition ();
  1310. var validClip = IsValidContent (ccol, crow, Clip);
  1311. if (validClip) {
  1312. if (runeWidth < 2 && ccol > 0
  1313. && Rune.ColumnWidth ((char)contents [crow, ccol - 1, 0]) > 1) {
  1314. var prevPosition = crow * Cols + (ccol - 1);
  1315. OutputBuffer [prevPosition].Char.UnicodeChar = ' ';
  1316. contents [crow, ccol - 1, 0] = (int)(uint)' ';
  1317. } else if (runeWidth < 2 && ccol <= Clip.Right - 1
  1318. && Rune.ColumnWidth ((char)contents [crow, ccol, 0]) > 1) {
  1319. var prevPosition = GetOutputBufferPosition () + 1;
  1320. OutputBuffer [prevPosition].Char.UnicodeChar = (char)' ';
  1321. contents [crow, ccol + 1, 0] = (int)(uint)' ';
  1322. }
  1323. if (runeWidth > 1 && ccol == Clip.Right - 1) {
  1324. OutputBuffer [position].Char.UnicodeChar = (char)' ';
  1325. contents [crow, ccol, 0] = (int)(uint)' ';
  1326. } else {
  1327. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  1328. contents [crow, ccol, 0] = (int)(uint)rune;
  1329. }
  1330. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  1331. contents [crow, ccol, 1] = currentAttribute;
  1332. contents [crow, ccol, 2] = 1;
  1333. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  1334. }
  1335. ccol++;
  1336. if (runeWidth > 1) {
  1337. if (validClip && ccol < Clip.Right) {
  1338. position = GetOutputBufferPosition ();
  1339. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  1340. OutputBuffer [position].Char.UnicodeChar = (char)0x00;
  1341. contents [crow, ccol, 0] = (int)(uint)0x00;
  1342. contents [crow, ccol, 1] = currentAttribute;
  1343. contents [crow, ccol, 2] = 0;
  1344. }
  1345. ccol++;
  1346. }
  1347. if (sync)
  1348. UpdateScreen ();
  1349. }
  1350. public override void AddStr (ustring str)
  1351. {
  1352. foreach (var rune in str)
  1353. AddRune (rune);
  1354. }
  1355. Attribute currentAttribute = new Attribute (Color.White, Color.Black);
  1356. public override void SetAttribute (Attribute c)
  1357. {
  1358. base.SetAttribute (c);
  1359. currentAttribute = c;
  1360. }
  1361. public override Attribute MakeColor (Color foreground, Color background)
  1362. {
  1363. return MakeColor ((ConsoleColor)foreground, (ConsoleColor)background);
  1364. }
  1365. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  1366. {
  1367. // Encode the colors into the int value.
  1368. return new Attribute (
  1369. value: ((int)f | (int)b << 4),
  1370. foreground: (Color)f,
  1371. background: (Color)b
  1372. );
  1373. }
  1374. public override Attribute MakeAttribute (Color fore, Color back)
  1375. {
  1376. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  1377. }
  1378. public override void Refresh ()
  1379. {
  1380. UpdateScreen ();
  1381. WinConsole.SetInitialCursorVisibility ();
  1382. UpdateCursor ();
  1383. #if false
  1384. var bufferCoords = new WindowsConsole.Coord (){
  1385. X = (short)Clip.Width,
  1386. Y = (short)Clip.Height
  1387. };
  1388. var window = new WindowsConsole.SmallRect (){
  1389. Top = 0,
  1390. Left = 0,
  1391. Right = (short)Clip.Right,
  1392. Bottom = (short)Clip.Bottom
  1393. };
  1394. UpdateCursor();
  1395. WinConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  1396. #endif
  1397. }
  1398. public override void UpdateScreen ()
  1399. {
  1400. if (damageRegion.Left == -1)
  1401. return;
  1402. if (!HeightAsBuffer) {
  1403. var windowSize = WinConsole.GetConsoleBufferWindow (out _);
  1404. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows))
  1405. return;
  1406. }
  1407. var bufferCoords = new WindowsConsole.Coord () {
  1408. X = (short)Clip.Width,
  1409. Y = (short)Clip.Height
  1410. };
  1411. //var window = new WindowsConsole.SmallRect () {
  1412. // Top = 0,
  1413. // Left = 0,
  1414. // Right = (short)Clip.Right,
  1415. // Bottom = (short)Clip.Bottom
  1416. //};
  1417. WinConsole.WriteToConsole (new Size (Cols, Rows), OutputBuffer, bufferCoords, damageRegion);
  1418. // System.Diagnostics.Debugger.Log (0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  1419. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1420. }
  1421. CursorVisibility savedCursorVisibility;
  1422. public override void UpdateCursor ()
  1423. {
  1424. if (ccol < 0 || crow < 0 || ccol > Cols || crow > Rows) {
  1425. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1426. savedCursorVisibility = cursorVisibility;
  1427. SetCursorVisibility (CursorVisibility.Invisible);
  1428. return;
  1429. }
  1430. SetCursorVisibility (savedCursorVisibility);
  1431. var position = new WindowsConsole.Coord () {
  1432. X = (short)ccol,
  1433. Y = (short)crow
  1434. };
  1435. WinConsole.SetCursorPosition (position);
  1436. }
  1437. public override void End ()
  1438. {
  1439. WinConsole.Cleanup ();
  1440. WinConsole = null;
  1441. }
  1442. public override Attribute GetAttribute ()
  1443. {
  1444. return currentAttribute;
  1445. }
  1446. /// <inheritdoc/>
  1447. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1448. {
  1449. return WinConsole.GetCursorVisibility (out visibility);
  1450. }
  1451. /// <inheritdoc/>
  1452. public override bool SetCursorVisibility (CursorVisibility visibility)
  1453. {
  1454. savedCursorVisibility = visibility;
  1455. return WinConsole.SetCursorVisibility (visibility);
  1456. }
  1457. /// <inheritdoc/>
  1458. public override bool EnsureCursorVisibility ()
  1459. {
  1460. return WinConsole.EnsureCursorVisibility ();
  1461. }
  1462. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1463. {
  1464. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1465. EventType = WindowsConsole.EventType.Key
  1466. };
  1467. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1468. bKeyDown = true
  1469. };
  1470. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1471. if (shift) {
  1472. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1473. keyEvent.UnicodeChar = '\0';
  1474. keyEvent.wVirtualKeyCode = 16;
  1475. }
  1476. if (alt) {
  1477. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1478. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1479. keyEvent.UnicodeChar = '\0';
  1480. keyEvent.wVirtualKeyCode = 18;
  1481. }
  1482. if (control) {
  1483. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1484. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1485. keyEvent.UnicodeChar = '\0';
  1486. keyEvent.wVirtualKeyCode = 17;
  1487. }
  1488. keyEvent.dwControlKeyState = controlKey;
  1489. input.KeyEvent = keyEvent;
  1490. if (shift || alt || control) {
  1491. ProcessInput (input);
  1492. }
  1493. keyEvent.UnicodeChar = keyChar;
  1494. if ((uint)key < 255) {
  1495. keyEvent.wVirtualKeyCode = (ushort)key;
  1496. } else {
  1497. keyEvent.wVirtualKeyCode = '\0';
  1498. }
  1499. input.KeyEvent = keyEvent;
  1500. try {
  1501. ProcessInput (input);
  1502. } catch (OverflowException) { } finally {
  1503. keyEvent.bKeyDown = false;
  1504. input.KeyEvent = keyEvent;
  1505. ProcessInput (input);
  1506. }
  1507. }
  1508. public override bool GetColors (int value, out Color foreground, out Color background)
  1509. {
  1510. bool hasColor = false;
  1511. foreground = default;
  1512. background = default;
  1513. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  1514. .OfType<ConsoleColor> ()
  1515. .Select (s => (int)s);
  1516. if (values.Contains ((value >> 4) & 0xffff)) {
  1517. hasColor = true;
  1518. background = (Color)(ConsoleColor)((value >> 4) & 0xffff);
  1519. }
  1520. if (values.Contains (value - ((int)background << 4))) {
  1521. hasColor = true;
  1522. foreground = (Color)(ConsoleColor)(value - ((int)background << 4));
  1523. }
  1524. return hasColor;
  1525. }
  1526. #region Unused
  1527. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1528. {
  1529. }
  1530. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1531. {
  1532. }
  1533. public override void Suspend ()
  1534. {
  1535. }
  1536. public override void StartReportingMouseMoves ()
  1537. {
  1538. }
  1539. public override void StopReportingMouseMoves ()
  1540. {
  1541. }
  1542. public override void UncookMouse ()
  1543. {
  1544. }
  1545. public override void CookMouse ()
  1546. {
  1547. }
  1548. #endregion
  1549. }
  1550. /// <summary>
  1551. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1552. /// only be used on Windows.
  1553. /// </summary>
  1554. /// <remarks>
  1555. /// This implementation is used for WindowsDriver.
  1556. /// </remarks>
  1557. internal class WindowsMainLoop : IMainLoopDriver {
  1558. ManualResetEventSlim eventReady = new ManualResetEventSlim (false);
  1559. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  1560. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  1561. MainLoop mainLoop;
  1562. ConsoleDriver consoleDriver;
  1563. WindowsConsole winConsole;
  1564. bool winChanged;
  1565. Size windowSize;
  1566. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  1567. // The records that we keep fetching
  1568. Queue<WindowsConsole.InputRecord []> resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1569. /// <summary>
  1570. /// Invoked when a Key is pressed or released.
  1571. /// </summary>
  1572. public Action<WindowsConsole.InputRecord> ProcessInput;
  1573. /// <summary>
  1574. /// Invoked when the window is changed.
  1575. /// </summary>
  1576. public Action<Size> WinChanged;
  1577. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1578. {
  1579. this.consoleDriver = consoleDriver ?? throw new ArgumentNullException ("Console driver instance must be provided.");
  1580. winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1581. }
  1582. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1583. {
  1584. this.mainLoop = mainLoop;
  1585. Task.Run (WindowsInputHandler);
  1586. Task.Run (CheckWinChange);
  1587. }
  1588. void WindowsInputHandler ()
  1589. {
  1590. while (true) {
  1591. waitForProbe.Wait ();
  1592. waitForProbe.Reset ();
  1593. if (resultQueue?.Count == 0) {
  1594. resultQueue.Enqueue (winConsole.ReadConsoleInput ());
  1595. }
  1596. eventReady.Set ();
  1597. }
  1598. }
  1599. void CheckWinChange ()
  1600. {
  1601. while (true) {
  1602. winChange.Wait ();
  1603. winChange.Reset ();
  1604. WaitWinChange ();
  1605. winChanged = true;
  1606. eventReady.Set ();
  1607. }
  1608. }
  1609. void WaitWinChange ()
  1610. {
  1611. while (true) {
  1612. Thread.Sleep (100);
  1613. if (!consoleDriver.HeightAsBuffer) {
  1614. windowSize = winConsole.GetConsoleBufferWindow (out _);
  1615. //System.Diagnostics.Debug.WriteLine ($"{consoleDriver.HeightAsBuffer},{windowSize.Width},{windowSize.Height}");
  1616. if (windowSize != Size.Empty && windowSize.Width != consoleDriver.Cols
  1617. || windowSize.Height != consoleDriver.Rows) {
  1618. return;
  1619. }
  1620. }
  1621. }
  1622. }
  1623. void IMainLoopDriver.Wakeup ()
  1624. {
  1625. //tokenSource.Cancel ();
  1626. eventReady.Set ();
  1627. }
  1628. bool IMainLoopDriver.EventsPending (bool wait)
  1629. {
  1630. waitForProbe.Set ();
  1631. winChange.Set ();
  1632. if (CheckTimers (wait, out var waitTimeout)) {
  1633. return true;
  1634. }
  1635. try {
  1636. if (!tokenSource.IsCancellationRequested) {
  1637. eventReady.Wait (waitTimeout, tokenSource.Token);
  1638. }
  1639. } catch (OperationCanceledException) {
  1640. return true;
  1641. } finally {
  1642. eventReady.Reset ();
  1643. }
  1644. if (!tokenSource.IsCancellationRequested) {
  1645. return resultQueue.Count > 0 || CheckTimers (wait, out _) || winChanged;
  1646. }
  1647. tokenSource.Dispose ();
  1648. tokenSource = new CancellationTokenSource ();
  1649. return true;
  1650. }
  1651. bool CheckTimers (bool wait, out int waitTimeout)
  1652. {
  1653. long now = DateTime.UtcNow.Ticks;
  1654. if (mainLoop.timeouts.Count > 0) {
  1655. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1656. if (waitTimeout < 0)
  1657. return true;
  1658. } else {
  1659. waitTimeout = -1;
  1660. }
  1661. if (!wait)
  1662. waitTimeout = 0;
  1663. int ic;
  1664. lock (mainLoop.idleHandlers) {
  1665. ic = mainLoop.idleHandlers.Count;
  1666. }
  1667. return ic > 0;
  1668. }
  1669. void IMainLoopDriver.MainIteration ()
  1670. {
  1671. while (resultQueue.Count > 0) {
  1672. var inputRecords = resultQueue.Dequeue ();
  1673. if (inputRecords != null && inputRecords.Length > 0) {
  1674. var inputEvent = inputRecords [0];
  1675. ProcessInput?.Invoke (inputEvent);
  1676. }
  1677. }
  1678. if (winChanged) {
  1679. winChanged = false;
  1680. WinChanged?.Invoke (windowSize);
  1681. }
  1682. }
  1683. }
  1684. class WindowsClipboard : ClipboardBase {
  1685. public WindowsClipboard ()
  1686. {
  1687. IsSupported = IsClipboardFormatAvailable (cfUnicodeText);
  1688. }
  1689. public override bool IsSupported { get; }
  1690. protected override string GetClipboardDataImpl ()
  1691. {
  1692. //if (!IsClipboardFormatAvailable (cfUnicodeText))
  1693. // return null;
  1694. try {
  1695. if (!OpenClipboard (IntPtr.Zero))
  1696. return null;
  1697. IntPtr handle = GetClipboardData (cfUnicodeText);
  1698. if (handle == IntPtr.Zero)
  1699. return null;
  1700. IntPtr pointer = IntPtr.Zero;
  1701. try {
  1702. pointer = GlobalLock (handle);
  1703. if (pointer == IntPtr.Zero)
  1704. return null;
  1705. int size = GlobalSize (handle);
  1706. byte [] buff = new byte [size];
  1707. Marshal.Copy (pointer, buff, 0, size);
  1708. return System.Text.Encoding.Unicode.GetString (buff)
  1709. .TrimEnd ('\0');
  1710. } finally {
  1711. if (pointer != IntPtr.Zero)
  1712. GlobalUnlock (handle);
  1713. }
  1714. } finally {
  1715. CloseClipboard ();
  1716. }
  1717. }
  1718. protected override void SetClipboardDataImpl (string text)
  1719. {
  1720. OpenClipboard ();
  1721. EmptyClipboard ();
  1722. IntPtr hGlobal = default;
  1723. try {
  1724. var bytes = (text.Length + 1) * 2;
  1725. hGlobal = Marshal.AllocHGlobal (bytes);
  1726. if (hGlobal == default) {
  1727. ThrowWin32 ();
  1728. }
  1729. var target = GlobalLock (hGlobal);
  1730. if (target == default) {
  1731. ThrowWin32 ();
  1732. }
  1733. try {
  1734. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1735. } finally {
  1736. GlobalUnlock (target);
  1737. }
  1738. if (SetClipboardData (cfUnicodeText, hGlobal) == default) {
  1739. ThrowWin32 ();
  1740. }
  1741. hGlobal = default;
  1742. } finally {
  1743. if (hGlobal != default) {
  1744. Marshal.FreeHGlobal (hGlobal);
  1745. }
  1746. CloseClipboard ();
  1747. }
  1748. }
  1749. void OpenClipboard ()
  1750. {
  1751. var num = 10;
  1752. while (true) {
  1753. if (OpenClipboard (default)) {
  1754. break;
  1755. }
  1756. if (--num == 0) {
  1757. ThrowWin32 ();
  1758. }
  1759. Thread.Sleep (100);
  1760. }
  1761. }
  1762. const uint cfUnicodeText = 13;
  1763. void ThrowWin32 ()
  1764. {
  1765. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1766. }
  1767. [DllImport ("User32.dll", SetLastError = true)]
  1768. [return: MarshalAs (UnmanagedType.Bool)]
  1769. static extern bool IsClipboardFormatAvailable (uint format);
  1770. [DllImport ("kernel32.dll", SetLastError = true)]
  1771. static extern int GlobalSize (IntPtr handle);
  1772. [DllImport ("kernel32.dll", SetLastError = true)]
  1773. static extern IntPtr GlobalLock (IntPtr hMem);
  1774. [DllImport ("kernel32.dll", SetLastError = true)]
  1775. [return: MarshalAs (UnmanagedType.Bool)]
  1776. static extern bool GlobalUnlock (IntPtr hMem);
  1777. [DllImport ("user32.dll", SetLastError = true)]
  1778. [return: MarshalAs (UnmanagedType.Bool)]
  1779. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1780. [DllImport ("user32.dll", SetLastError = true)]
  1781. [return: MarshalAs (UnmanagedType.Bool)]
  1782. static extern bool CloseClipboard ();
  1783. [DllImport ("user32.dll", SetLastError = true)]
  1784. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1785. [DllImport ("user32.dll")]
  1786. static extern bool EmptyClipboard ();
  1787. [DllImport ("user32.dll", SetLastError = true)]
  1788. static extern IntPtr GetClipboardData (uint uFormat);
  1789. }
  1790. }