WindowsDriver.cs 63 KB

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