WindowsDriver.cs 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472
  1. //
  2. // WindowsDriver.cs: Windows specific driver
  3. //
  4. // HACK:
  5. // WindowsConsole/Terminal has two issues:
  6. // 1) Tearing can occur when the console is resized.
  7. // 2) The values provided during Init (and the first WindowsConsole.EventType.WindowBufferSize) are not correct.
  8. //
  9. // If HACK_CHECK_WINCHANGED is defined then we ignore WindowsConsole.EventType.WindowBufferSize events
  10. // and instead check the console size every every 500ms in a thread in WidowsMainLoop.
  11. // As of Windows 11 23H2 25947.1000 and/or WT 1.19.2682 tearing no longer occurs when using
  12. // the WindowsConsole.EventType.WindowBufferSize event. However, on Init the window size is
  13. // still incorrect so we still need this hack.
  14. #define HACK_CHECK_WINCHANGED
  15. using System.ComponentModel;
  16. using System.Diagnostics;
  17. using System.Runtime.InteropServices;
  18. using System.Text;
  19. using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping;
  20. namespace Terminal.Gui;
  21. internal class WindowsConsole
  22. {
  23. public const int STD_OUTPUT_HANDLE = -11;
  24. public const int STD_INPUT_HANDLE = -10;
  25. private readonly nint _inputHandle;
  26. private readonly nint _outputHandle;
  27. private nint _screenBuffer;
  28. private readonly uint _originalConsoleMode;
  29. private CursorVisibility? _initialCursorVisibility;
  30. private CursorVisibility? _currentCursorVisibility;
  31. private CursorVisibility? _pendingCursorVisibility;
  32. private readonly StringBuilder _stringBuilder = new (256 * 1024);
  33. public WindowsConsole ()
  34. {
  35. _inputHandle = GetStdHandle (STD_INPUT_HANDLE);
  36. _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  37. _originalConsoleMode = ConsoleMode;
  38. uint newConsoleMode = _originalConsoleMode;
  39. newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
  40. newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
  41. newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput;
  42. ConsoleMode = newConsoleMode;
  43. }
  44. private CharInfo [] _originalStdOutChars;
  45. public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord bufferSize, SmallRect window, bool force16Colors)
  46. {
  47. if (_screenBuffer == nint.Zero)
  48. {
  49. ReadFromConsoleOutput (size, bufferSize, ref window);
  50. }
  51. var result = false;
  52. if (force16Colors)
  53. {
  54. var i = 0;
  55. CharInfo [] ci = new CharInfo [charInfoBuffer.Length];
  56. foreach (ExtendedCharInfo info in charInfoBuffer)
  57. {
  58. ci [i++] = new CharInfo
  59. {
  60. Char = new CharUnion { UnicodeChar = info.Char },
  61. Attributes =
  62. (ushort)((int)info.Attribute.Foreground.GetClosestNamedColor () | ((int)info.Attribute.Background.GetClosestNamedColor () << 4))
  63. };
  64. }
  65. result = WriteConsoleOutput (_screenBuffer, ci, bufferSize, new Coord { X = window.Left, Y = window.Top }, ref window);
  66. }
  67. else
  68. {
  69. _stringBuilder.Clear ();
  70. _stringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition);
  71. _stringBuilder.Append (EscSeqUtils.CSI_SetCursorPosition (0, 0));
  72. Attribute? prev = null;
  73. foreach (ExtendedCharInfo info in charInfoBuffer)
  74. {
  75. Attribute attr = info.Attribute;
  76. if (attr != prev)
  77. {
  78. prev = attr;
  79. _stringBuilder.Append (EscSeqUtils.CSI_SetForegroundColorRGB (attr.Foreground.R, attr.Foreground.G, attr.Foreground.B));
  80. _stringBuilder.Append (EscSeqUtils.CSI_SetBackgroundColorRGB (attr.Background.R, attr.Background.G, attr.Background.B));
  81. }
  82. if (info.Char != '\x1b')
  83. {
  84. if (!info.Empty)
  85. {
  86. _stringBuilder.Append (info.Char);
  87. }
  88. }
  89. else
  90. {
  91. _stringBuilder.Append (' ');
  92. }
  93. }
  94. _stringBuilder.Append (EscSeqUtils.CSI_RestoreCursorPosition);
  95. _stringBuilder.Append (EscSeqUtils.CSI_HideCursor);
  96. var s = _stringBuilder.ToString ();
  97. result = WriteConsole (_screenBuffer, s, (uint)s.Length, out uint _, null);
  98. }
  99. if (!result)
  100. {
  101. int err = Marshal.GetLastWin32Error ();
  102. if (err != 0)
  103. {
  104. throw new Win32Exception (err);
  105. }
  106. }
  107. return result;
  108. }
  109. public bool WriteANSI (string ansi)
  110. {
  111. return WriteConsole (_screenBuffer, ansi, (uint)ansi.Length, out uint _, null);
  112. }
  113. public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window)
  114. {
  115. _screenBuffer = CreateConsoleScreenBuffer (
  116. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  117. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  118. nint.Zero,
  119. 1,
  120. nint.Zero
  121. );
  122. if (_screenBuffer == INVALID_HANDLE_VALUE)
  123. {
  124. int err = Marshal.GetLastWin32Error ();
  125. if (err != 0)
  126. {
  127. throw new Win32Exception (err);
  128. }
  129. }
  130. if (!_initialCursorVisibility.HasValue && GetCursorVisibility (out CursorVisibility visibility))
  131. {
  132. _initialCursorVisibility = visibility;
  133. }
  134. if (!SetConsoleActiveScreenBuffer (_screenBuffer))
  135. {
  136. throw new Win32Exception (Marshal.GetLastWin32Error ());
  137. }
  138. _originalStdOutChars = new CharInfo [size.Height * size.Width];
  139. if (!ReadConsoleOutput (_screenBuffer, _originalStdOutChars, coords, new Coord { X = 0, Y = 0 }, ref window))
  140. {
  141. throw new Win32Exception (Marshal.GetLastWin32Error ());
  142. }
  143. }
  144. public bool SetCursorPosition (Coord position)
  145. {
  146. return SetConsoleCursorPosition (_screenBuffer, position);
  147. }
  148. public void SetInitialCursorVisibility ()
  149. {
  150. if (_initialCursorVisibility.HasValue == false && GetCursorVisibility (out CursorVisibility visibility))
  151. {
  152. _initialCursorVisibility = visibility;
  153. }
  154. }
  155. public bool GetCursorVisibility (out CursorVisibility visibility)
  156. {
  157. if (_screenBuffer == nint.Zero)
  158. {
  159. visibility = CursorVisibility.Invisible;
  160. return false;
  161. }
  162. if (!GetConsoleCursorInfo (_screenBuffer, out ConsoleCursorInfo info))
  163. {
  164. int err = Marshal.GetLastWin32Error ();
  165. if (err != 0)
  166. {
  167. throw new Win32Exception (err);
  168. }
  169. visibility = CursorVisibility.Default;
  170. return false;
  171. }
  172. if (!info.bVisible)
  173. {
  174. visibility = CursorVisibility.Invisible;
  175. }
  176. else if (info.dwSize > 50)
  177. {
  178. visibility = CursorVisibility.Box;
  179. }
  180. else
  181. {
  182. visibility = CursorVisibility.Underline;
  183. }
  184. return true;
  185. }
  186. public bool EnsureCursorVisibility ()
  187. {
  188. if (_initialCursorVisibility.HasValue && _pendingCursorVisibility.HasValue && SetCursorVisibility (_pendingCursorVisibility.Value))
  189. {
  190. _pendingCursorVisibility = null;
  191. return true;
  192. }
  193. return false;
  194. }
  195. public void ForceRefreshCursorVisibility ()
  196. {
  197. if (_currentCursorVisibility.HasValue)
  198. {
  199. _pendingCursorVisibility = _currentCursorVisibility;
  200. _currentCursorVisibility = null;
  201. }
  202. }
  203. public bool SetCursorVisibility (CursorVisibility visibility)
  204. {
  205. if (_initialCursorVisibility.HasValue == false)
  206. {
  207. _pendingCursorVisibility = visibility;
  208. return false;
  209. }
  210. if (_currentCursorVisibility.HasValue == false || _currentCursorVisibility.Value != visibility)
  211. {
  212. var info = new ConsoleCursorInfo
  213. {
  214. dwSize = (uint)visibility & 0x00FF,
  215. bVisible = ((uint)visibility & 0xFF00) != 0
  216. };
  217. if (!SetConsoleCursorInfo (_screenBuffer, ref info))
  218. {
  219. return false;
  220. }
  221. _currentCursorVisibility = visibility;
  222. }
  223. return true;
  224. }
  225. public void Cleanup ()
  226. {
  227. if (_initialCursorVisibility.HasValue)
  228. {
  229. SetCursorVisibility (_initialCursorVisibility.Value);
  230. }
  231. SetConsoleOutputWindow (out _);
  232. ConsoleMode = _originalConsoleMode;
  233. if (!SetConsoleActiveScreenBuffer (_outputHandle))
  234. {
  235. int err = Marshal.GetLastWin32Error ();
  236. Console.WriteLine ("Error: {0}", err);
  237. }
  238. if (_screenBuffer != nint.Zero)
  239. {
  240. CloseHandle (_screenBuffer);
  241. }
  242. _screenBuffer = nint.Zero;
  243. }
  244. internal Size GetConsoleBufferWindow (out Point position)
  245. {
  246. if (_screenBuffer == nint.Zero)
  247. {
  248. position = Point.Empty;
  249. return Size.Empty;
  250. }
  251. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  252. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  253. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  254. {
  255. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  256. position = Point.Empty;
  257. return Size.Empty;
  258. }
  259. Size sz = new (
  260. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  261. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  262. position = new (csbi.srWindow.Left, csbi.srWindow.Top);
  263. return sz;
  264. }
  265. internal Size GetConsoleOutputWindow (out Point position)
  266. {
  267. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  268. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  269. if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi))
  270. {
  271. throw new Win32Exception (Marshal.GetLastWin32Error ());
  272. }
  273. Size sz = new (
  274. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  275. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  276. position = new (csbi.srWindow.Left, csbi.srWindow.Top);
  277. return sz;
  278. }
  279. internal Size SetConsoleWindow (short cols, short rows)
  280. {
  281. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  282. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  283. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  284. {
  285. throw new Win32Exception (Marshal.GetLastWin32Error ());
  286. }
  287. Coord maxWinSize = GetLargestConsoleWindowSize (_screenBuffer);
  288. short newCols = Math.Min (cols, maxWinSize.X);
  289. short newRows = Math.Min (rows, maxWinSize.Y);
  290. csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1));
  291. csbi.srWindow = new SmallRect (0, 0, newCols, newRows);
  292. csbi.dwMaximumWindowSize = new Coord (newCols, newRows);
  293. if (!SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  294. {
  295. throw new Win32Exception (Marshal.GetLastWin32Error ());
  296. }
  297. var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0));
  298. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect))
  299. {
  300. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  301. return new (cols, rows);
  302. }
  303. SetConsoleOutputWindow (csbi);
  304. return new (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1);
  305. }
  306. private void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi)
  307. {
  308. if (_screenBuffer != nint.Zero && !SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  309. {
  310. throw new Win32Exception (Marshal.GetLastWin32Error ());
  311. }
  312. }
  313. internal Size SetConsoleOutputWindow (out Point position)
  314. {
  315. if (_screenBuffer == nint.Zero)
  316. {
  317. position = Point.Empty;
  318. return Size.Empty;
  319. }
  320. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  321. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  322. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  323. {
  324. throw new Win32Exception (Marshal.GetLastWin32Error ());
  325. }
  326. Size sz = new (
  327. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  328. Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0));
  329. position = new (csbi.srWindow.Left, csbi.srWindow.Top);
  330. SetConsoleOutputWindow (csbi);
  331. var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0));
  332. if (!SetConsoleScreenBufferInfoEx (_outputHandle, ref csbi))
  333. {
  334. throw new Win32Exception (Marshal.GetLastWin32Error ());
  335. }
  336. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect))
  337. {
  338. throw new Win32Exception (Marshal.GetLastWin32Error ());
  339. }
  340. return sz;
  341. }
  342. private uint ConsoleMode
  343. {
  344. get
  345. {
  346. GetConsoleMode (_inputHandle, out uint v);
  347. return v;
  348. }
  349. set => SetConsoleMode (_inputHandle, value);
  350. }
  351. [Flags]
  352. public enum ConsoleModes : uint
  353. {
  354. EnableProcessedInput = 1,
  355. EnableMouseInput = 16,
  356. EnableQuickEditMode = 64,
  357. EnableExtendedFlags = 128
  358. }
  359. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  360. public struct KeyEventRecord
  361. {
  362. [FieldOffset (0)]
  363. [MarshalAs (UnmanagedType.Bool)]
  364. public bool bKeyDown;
  365. [FieldOffset (4)]
  366. [MarshalAs (UnmanagedType.U2)]
  367. public ushort wRepeatCount;
  368. [FieldOffset (6)]
  369. [MarshalAs (UnmanagedType.U2)]
  370. public VK wVirtualKeyCode;
  371. [FieldOffset (8)]
  372. [MarshalAs (UnmanagedType.U2)]
  373. public ushort wVirtualScanCode;
  374. [FieldOffset (10)]
  375. public char UnicodeChar;
  376. [FieldOffset (12)]
  377. [MarshalAs (UnmanagedType.U4)]
  378. public ControlKeyState dwControlKeyState;
  379. public readonly override string ToString ()
  380. {
  381. return
  382. $"[KeyEventRecord({(bKeyDown ? "down" : "up")},{wRepeatCount},{wVirtualKeyCode},{wVirtualScanCode},{new Rune (UnicodeChar).MakePrintable ()},{dwControlKeyState})]";
  383. }
  384. }
  385. [Flags]
  386. public enum ButtonState
  387. {
  388. NoButtonPressed = 0,
  389. Button1Pressed = 1,
  390. Button2Pressed = 4,
  391. Button3Pressed = 8,
  392. Button4Pressed = 16,
  393. RightmostButtonPressed = 2
  394. }
  395. [Flags]
  396. public enum ControlKeyState
  397. {
  398. NoControlKeyPressed = 0,
  399. RightAltPressed = 1,
  400. LeftAltPressed = 2,
  401. RightControlPressed = 4,
  402. LeftControlPressed = 8,
  403. ShiftPressed = 16,
  404. NumlockOn = 32,
  405. ScrolllockOn = 64,
  406. CapslockOn = 128,
  407. EnhancedKey = 256
  408. }
  409. [Flags]
  410. public enum EventFlags
  411. {
  412. NoEvent = 0,
  413. MouseMoved = 1,
  414. DoubleClick = 2,
  415. MouseWheeled = 4,
  416. MouseHorizontalWheeled = 8
  417. }
  418. [StructLayout (LayoutKind.Explicit)]
  419. public struct MouseEventRecord
  420. {
  421. [FieldOffset (0)]
  422. public Coord MousePosition;
  423. [FieldOffset (4)]
  424. public ButtonState ButtonState;
  425. [FieldOffset (8)]
  426. public ControlKeyState ControlKeyState;
  427. [FieldOffset (12)]
  428. public EventFlags EventFlags;
  429. public readonly override string ToString () { return $"[Mouse{MousePosition},{ButtonState},{ControlKeyState},{EventFlags}]"; }
  430. }
  431. public struct WindowBufferSizeRecord
  432. {
  433. public Coord _size;
  434. public WindowBufferSizeRecord (short x, short y) { _size = new Coord (x, y); }
  435. public readonly override string ToString () { return $"[WindowBufferSize{_size}"; }
  436. }
  437. [StructLayout (LayoutKind.Sequential)]
  438. public struct MenuEventRecord
  439. {
  440. public uint dwCommandId;
  441. }
  442. [StructLayout (LayoutKind.Sequential)]
  443. public struct FocusEventRecord
  444. {
  445. public uint bSetFocus;
  446. }
  447. public enum EventType : ushort
  448. {
  449. Focus = 0x10,
  450. Key = 0x1,
  451. Menu = 0x8,
  452. Mouse = 2,
  453. WindowBufferSize = 4
  454. }
  455. [StructLayout (LayoutKind.Explicit)]
  456. public struct InputRecord
  457. {
  458. [FieldOffset (0)]
  459. public EventType EventType;
  460. [FieldOffset (4)]
  461. public KeyEventRecord KeyEvent;
  462. [FieldOffset (4)]
  463. public MouseEventRecord MouseEvent;
  464. [FieldOffset (4)]
  465. public WindowBufferSizeRecord WindowBufferSizeEvent;
  466. [FieldOffset (4)]
  467. public MenuEventRecord MenuEvent;
  468. [FieldOffset (4)]
  469. public FocusEventRecord FocusEvent;
  470. public readonly override string ToString ()
  471. {
  472. return EventType switch
  473. {
  474. EventType.Focus => FocusEvent.ToString (),
  475. EventType.Key => KeyEvent.ToString (),
  476. EventType.Menu => MenuEvent.ToString (),
  477. EventType.Mouse => MouseEvent.ToString (),
  478. EventType.WindowBufferSize => WindowBufferSizeEvent.ToString (),
  479. _ => "Unknown event type: " + EventType
  480. };
  481. }
  482. }
  483. [Flags]
  484. private enum ShareMode : uint
  485. {
  486. FileShareRead = 1,
  487. FileShareWrite = 2
  488. }
  489. [Flags]
  490. private enum DesiredAccess : uint
  491. {
  492. GenericRead = 2147483648,
  493. GenericWrite = 1073741824
  494. }
  495. [StructLayout (LayoutKind.Sequential)]
  496. public struct ConsoleScreenBufferInfo
  497. {
  498. public Coord dwSize;
  499. public Coord dwCursorPosition;
  500. public ushort wAttributes;
  501. public SmallRect srWindow;
  502. public Coord dwMaximumWindowSize;
  503. }
  504. [StructLayout (LayoutKind.Sequential)]
  505. public struct Coord
  506. {
  507. public short X;
  508. public short Y;
  509. public Coord (short x, short y)
  510. {
  511. X = x;
  512. Y = y;
  513. }
  514. public readonly override string ToString () { return $"({X},{Y})"; }
  515. }
  516. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  517. public struct CharUnion
  518. {
  519. [FieldOffset (0)]
  520. public char UnicodeChar;
  521. [FieldOffset (0)]
  522. public byte AsciiChar;
  523. }
  524. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  525. public struct CharInfo
  526. {
  527. [FieldOffset (0)]
  528. public CharUnion Char;
  529. [FieldOffset (2)]
  530. public ushort Attributes;
  531. }
  532. public struct ExtendedCharInfo
  533. {
  534. public char Char { get; set; }
  535. public Attribute Attribute { get; set; }
  536. public bool Empty { get; set; } // TODO: Temp hack until virutal terminal sequences
  537. public ExtendedCharInfo (char character, Attribute attribute)
  538. {
  539. Char = character;
  540. Attribute = attribute;
  541. Empty = false;
  542. }
  543. }
  544. [StructLayout (LayoutKind.Sequential)]
  545. public struct SmallRect
  546. {
  547. public short Left;
  548. public short Top;
  549. public short Right;
  550. public short Bottom;
  551. public SmallRect (short left, short top, short right, short bottom)
  552. {
  553. Left = left;
  554. Top = top;
  555. Right = right;
  556. Bottom = bottom;
  557. }
  558. public static void MakeEmpty (ref SmallRect rect) { rect.Left = -1; }
  559. public static void Update (ref SmallRect rect, short col, short row)
  560. {
  561. if (rect.Left == -1)
  562. {
  563. rect.Left = rect.Right = col;
  564. rect.Bottom = rect.Top = row;
  565. return;
  566. }
  567. if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
  568. {
  569. return;
  570. }
  571. if (col < rect.Left)
  572. {
  573. rect.Left = col;
  574. }
  575. if (col > rect.Right)
  576. {
  577. rect.Right = col;
  578. }
  579. if (row < rect.Top)
  580. {
  581. rect.Top = row;
  582. }
  583. if (row > rect.Bottom)
  584. {
  585. rect.Bottom = row;
  586. }
  587. }
  588. public readonly override string ToString () { return $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}"; }
  589. }
  590. [StructLayout (LayoutKind.Sequential)]
  591. public struct ConsoleKeyInfoEx
  592. {
  593. public ConsoleKeyInfo ConsoleKeyInfo;
  594. public bool CapsLock;
  595. public bool NumLock;
  596. public bool ScrollLock;
  597. public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock, bool scrolllock)
  598. {
  599. ConsoleKeyInfo = consoleKeyInfo;
  600. CapsLock = capslock;
  601. NumLock = numlock;
  602. ScrollLock = scrolllock;
  603. }
  604. /// <summary>
  605. /// Prints a ConsoleKeyInfoEx structure
  606. /// </summary>
  607. /// <param name="ex"></param>
  608. /// <returns></returns>
  609. public readonly string ToString (ConsoleKeyInfoEx ex)
  610. {
  611. var ke = new Key ((KeyCode)ex.ConsoleKeyInfo.KeyChar);
  612. var sb = new StringBuilder ();
  613. sb.Append ($"Key: {(KeyCode)ex.ConsoleKeyInfo.Key} ({ex.ConsoleKeyInfo.Key})");
  614. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty);
  615. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty);
  616. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty);
  617. sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)ex.ConsoleKeyInfo.KeyChar}) ");
  618. sb.Append (ex.CapsLock ? "caps," : string.Empty);
  619. sb.Append (ex.NumLock ? "num," : string.Empty);
  620. sb.Append (ex.ScrollLock ? "scroll," : string.Empty);
  621. string s = sb.ToString ().TrimEnd (',').TrimEnd (' ');
  622. return $"[ConsoleKeyInfoEx({s})]";
  623. }
  624. }
  625. [DllImport ("kernel32.dll", SetLastError = true)]
  626. private static extern nint GetStdHandle (int nStdHandle);
  627. [DllImport ("kernel32.dll", SetLastError = true)]
  628. private static extern bool CloseHandle (nint handle);
  629. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  630. public static extern bool ReadConsoleInput (
  631. nint hConsoleInput,
  632. nint lpBuffer,
  633. uint nLength,
  634. out uint lpNumberOfEventsRead
  635. );
  636. [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  637. private static extern bool ReadConsoleOutput (
  638. nint hConsoleOutput,
  639. [Out] CharInfo [] lpBuffer,
  640. Coord dwBufferSize,
  641. Coord dwBufferCoord,
  642. ref SmallRect lpReadRegion
  643. );
  644. // TODO: This API is obsolete. See https://learn.microsoft.com/en-us/windows/console/writeconsoleoutput
  645. [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutputW", SetLastError = true, CharSet = CharSet.Unicode)]
  646. private static extern bool WriteConsoleOutput (
  647. nint hConsoleOutput,
  648. CharInfo [] lpBuffer,
  649. Coord dwBufferSize,
  650. Coord dwBufferCoord,
  651. ref SmallRect lpWriteRegion
  652. );
  653. [DllImport ("kernel32.dll", EntryPoint = "WriteConsole", SetLastError = true, CharSet = CharSet.Unicode)]
  654. private static extern bool WriteConsole (
  655. nint hConsoleOutput,
  656. string lpbufer,
  657. uint NumberOfCharsToWriten,
  658. out uint lpNumberOfCharsWritten,
  659. object lpReserved
  660. );
  661. [DllImport ("kernel32.dll")]
  662. private static extern bool SetConsoleCursorPosition (nint hConsoleOutput, Coord dwCursorPosition);
  663. [StructLayout (LayoutKind.Sequential)]
  664. public struct ConsoleCursorInfo
  665. {
  666. public uint dwSize;
  667. public bool bVisible;
  668. }
  669. [DllImport ("kernel32.dll", SetLastError = true)]
  670. private static extern bool SetConsoleCursorInfo (nint hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
  671. [DllImport ("kernel32.dll", SetLastError = true)]
  672. private static extern bool GetConsoleCursorInfo (nint hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
  673. [DllImport ("kernel32.dll")]
  674. private static extern bool GetConsoleMode (nint hConsoleHandle, out uint lpMode);
  675. [DllImport ("kernel32.dll")]
  676. private static extern bool SetConsoleMode (nint hConsoleHandle, uint dwMode);
  677. [DllImport ("kernel32.dll", SetLastError = true)]
  678. private static extern nint CreateConsoleScreenBuffer (
  679. DesiredAccess dwDesiredAccess,
  680. ShareMode dwShareMode,
  681. nint secutiryAttributes,
  682. uint flags,
  683. nint screenBufferData
  684. );
  685. internal static nint INVALID_HANDLE_VALUE = new (-1);
  686. [DllImport ("kernel32.dll", SetLastError = true)]
  687. private static extern bool SetConsoleActiveScreenBuffer (nint Handle);
  688. [DllImport ("kernel32.dll", SetLastError = true)]
  689. private static extern bool GetNumberOfConsoleInputEvents (nint handle, out uint lpcNumberOfEvents);
  690. public InputRecord [] ReadConsoleInput ()
  691. {
  692. const int bufferSize = 1;
  693. nint pRecord = Marshal.AllocHGlobal (Marshal.SizeOf<InputRecord> () * bufferSize);
  694. try
  695. {
  696. ReadConsoleInput (
  697. _inputHandle,
  698. pRecord,
  699. bufferSize,
  700. out uint numberEventsRead);
  701. return numberEventsRead == 0
  702. ? null
  703. : new [] { Marshal.PtrToStructure<InputRecord> (pRecord) };
  704. }
  705. catch (Exception)
  706. {
  707. return null;
  708. }
  709. finally
  710. {
  711. Marshal.FreeHGlobal (pRecord);
  712. }
  713. }
  714. #if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
  715. [DllImport ("kernel32.dll", ExactSpelling = true)]
  716. static extern IntPtr GetConsoleWindow ();
  717. [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  718. static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
  719. public const int HIDE = 0;
  720. public const int MAXIMIZE = 3;
  721. public const int MINIMIZE = 6;
  722. public const int RESTORE = 9;
  723. internal void ShowWindow (int state)
  724. {
  725. IntPtr thisConsole = GetConsoleWindow ();
  726. ShowWindow (thisConsole, state);
  727. }
  728. #endif
  729. // See: https://github.com/gui-cs/Terminal.Gui/issues/357
  730. [StructLayout (LayoutKind.Sequential)]
  731. public struct CONSOLE_SCREEN_BUFFER_INFOEX
  732. {
  733. public uint cbSize;
  734. public Coord dwSize;
  735. public Coord dwCursorPosition;
  736. public ushort wAttributes;
  737. public SmallRect srWindow;
  738. public Coord dwMaximumWindowSize;
  739. public ushort wPopupAttributes;
  740. public bool bFullscreenSupported;
  741. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)]
  742. public COLORREF [] ColorTable;
  743. }
  744. [StructLayout (LayoutKind.Explicit, Size = 4)]
  745. public struct COLORREF
  746. {
  747. public COLORREF (byte r, byte g, byte b)
  748. {
  749. Value = 0;
  750. R = r;
  751. G = g;
  752. B = b;
  753. }
  754. public COLORREF (uint value)
  755. {
  756. R = 0;
  757. G = 0;
  758. B = 0;
  759. Value = value & 0x00FFFFFF;
  760. }
  761. [FieldOffset (0)]
  762. public byte R;
  763. [FieldOffset (1)]
  764. public byte G;
  765. [FieldOffset (2)]
  766. public byte B;
  767. [FieldOffset (0)]
  768. public uint Value;
  769. }
  770. [DllImport ("kernel32.dll", SetLastError = true)]
  771. private static extern bool GetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  772. [DllImport ("kernel32.dll", SetLastError = true)]
  773. private static extern bool SetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo);
  774. [DllImport ("kernel32.dll", SetLastError = true)]
  775. private static extern bool SetConsoleWindowInfo (
  776. nint hConsoleOutput,
  777. bool bAbsolute,
  778. [In] ref SmallRect lpConsoleWindow
  779. );
  780. [DllImport ("kernel32.dll", SetLastError = true)]
  781. private static extern Coord GetLargestConsoleWindowSize (
  782. nint hConsoleOutput
  783. );
  784. }
  785. internal class WindowsDriver : ConsoleDriver
  786. {
  787. private readonly bool _isWindowsTerminal;
  788. private WindowsConsole.SmallRect _damageRegion;
  789. private bool _isButtonDoubleClicked;
  790. private bool _isButtonPressed;
  791. private bool _isButtonReleased;
  792. private bool _isOneFingerDoubleClicked;
  793. private WindowsConsole.ButtonState? _lastMouseButtonPressed;
  794. private WindowsMainLoop _mainLoopDriver;
  795. private WindowsConsole.ExtendedCharInfo [] _outputBuffer;
  796. private Point? _point;
  797. private Point _pointMove;
  798. private bool _processButtonClick;
  799. public WindowsDriver ()
  800. {
  801. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  802. {
  803. WinConsole = new WindowsConsole ();
  804. // otherwise we're probably running in unit tests
  805. Clipboard = new WindowsClipboard ();
  806. }
  807. else
  808. {
  809. Clipboard = new FakeDriver.FakeClipboard ();
  810. }
  811. // TODO: if some other Windows-based terminal supports true color, update this logic to not
  812. // force 16color mode (.e.g ConEmu which really doesn't work well at all).
  813. _isWindowsTerminal = _isWindowsTerminal =
  814. Environment.GetEnvironmentVariable ("WT_SESSION") is { } || Environment.GetEnvironmentVariable ("VSAPPIDNAME") != null;
  815. if (!_isWindowsTerminal)
  816. {
  817. Force16Colors = true;
  818. }
  819. }
  820. public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931 && _isWindowsTerminal);
  821. public WindowsConsole WinConsole { get; private set; }
  822. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  823. {
  824. if (keyEvent.wVirtualKeyCode != (VK)ConsoleKey.Packet)
  825. {
  826. return keyEvent;
  827. }
  828. var mod = new ConsoleModifiers ();
  829. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  830. {
  831. mod |= ConsoleModifiers.Shift;
  832. }
  833. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  834. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  835. {
  836. mod |= ConsoleModifiers.Alt;
  837. }
  838. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)
  839. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed))
  840. {
  841. mod |= ConsoleModifiers.Control;
  842. }
  843. var cKeyInfo = new ConsoleKeyInfo (
  844. keyEvent.UnicodeChar,
  845. (ConsoleKey)keyEvent.wVirtualKeyCode,
  846. mod.HasFlag (ConsoleModifiers.Shift),
  847. mod.HasFlag (ConsoleModifiers.Alt),
  848. mod.HasFlag (ConsoleModifiers.Control));
  849. cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  850. uint scanCode = GetScanCodeFromConsoleKeyInfo (cKeyInfo);
  851. return new WindowsConsole.KeyEventRecord
  852. {
  853. UnicodeChar = cKeyInfo.KeyChar,
  854. bKeyDown = keyEvent.bKeyDown,
  855. dwControlKeyState = keyEvent.dwControlKeyState,
  856. wRepeatCount = keyEvent.wRepeatCount,
  857. wVirtualKeyCode = (VK)cKeyInfo.Key,
  858. wVirtualScanCode = (ushort)scanCode
  859. };
  860. }
  861. public override bool IsRuneSupported (Rune rune) { return base.IsRuneSupported (rune) && rune.IsBmp; }
  862. public override void Refresh ()
  863. {
  864. UpdateScreen ();
  865. //WinConsole?.SetInitialCursorVisibility ();
  866. UpdateCursor ();
  867. }
  868. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  869. {
  870. var input = new WindowsConsole.InputRecord
  871. {
  872. EventType = WindowsConsole.EventType.Key
  873. };
  874. var keyEvent = new WindowsConsole.KeyEventRecord
  875. {
  876. bKeyDown = true
  877. };
  878. var controlKey = new WindowsConsole.ControlKeyState ();
  879. if (shift)
  880. {
  881. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  882. keyEvent.UnicodeChar = '\0';
  883. keyEvent.wVirtualKeyCode = VK.SHIFT;
  884. }
  885. if (alt)
  886. {
  887. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  888. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  889. keyEvent.UnicodeChar = '\0';
  890. keyEvent.wVirtualKeyCode = VK.MENU;
  891. }
  892. if (control)
  893. {
  894. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  895. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  896. keyEvent.UnicodeChar = '\0';
  897. keyEvent.wVirtualKeyCode = VK.CONTROL;
  898. }
  899. keyEvent.dwControlKeyState = controlKey;
  900. input.KeyEvent = keyEvent;
  901. if (shift || alt || control)
  902. {
  903. ProcessInput (input);
  904. }
  905. keyEvent.UnicodeChar = keyChar;
  906. //if ((uint)key < 255) {
  907. // keyEvent.wVirtualKeyCode = (ushort)key;
  908. //} else {
  909. // keyEvent.wVirtualKeyCode = '\0';
  910. //}
  911. keyEvent.wVirtualKeyCode = (VK)key;
  912. input.KeyEvent = keyEvent;
  913. try
  914. {
  915. ProcessInput (input);
  916. }
  917. catch (OverflowException)
  918. { }
  919. finally
  920. {
  921. keyEvent.bKeyDown = false;
  922. input.KeyEvent = keyEvent;
  923. ProcessInput (input);
  924. }
  925. }
  926. #region Not Implemented
  927. public override void Suspend () { throw new NotImplementedException (); }
  928. #endregion
  929. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  930. {
  931. WindowsConsole.ControlKeyState state = keyEvent.dwControlKeyState;
  932. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  933. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  934. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  935. bool capslock = (state & WindowsConsole.ControlKeyState.CapslockOn) != 0;
  936. bool numlock = (state & WindowsConsole.ControlKeyState.NumlockOn) != 0;
  937. bool scrolllock = (state & WindowsConsole.ControlKeyState.ScrolllockOn) != 0;
  938. var cki = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  939. return new WindowsConsole.ConsoleKeyInfoEx (cki, capslock, numlock, scrolllock);
  940. }
  941. #region Cursor Handling
  942. private CursorVisibility? _cachedCursorVisibility;
  943. public override void UpdateCursor ()
  944. {
  945. if (Col < 0 || Row < 0 || Col >= Cols || Row >= Rows)
  946. {
  947. GetCursorVisibility (out CursorVisibility cursorVisibility);
  948. _cachedCursorVisibility = cursorVisibility;
  949. SetCursorVisibility (CursorVisibility.Invisible);
  950. return;
  951. }
  952. var position = new WindowsConsole.Coord
  953. {
  954. X = (short)Col,
  955. Y = (short)Row
  956. };
  957. if (Force16Colors)
  958. {
  959. WinConsole?.SetCursorPosition (position);
  960. }
  961. else
  962. {
  963. var sb = new StringBuilder ();
  964. sb.Append (EscSeqUtils.CSI_SetCursorPosition (position.Y + 1, position.X + 1));
  965. WinConsole?.WriteANSI (sb.ToString ());
  966. }
  967. if (_cachedCursorVisibility is { })
  968. {
  969. SetCursorVisibility (_cachedCursorVisibility.Value);
  970. }
  971. //EnsureCursorVisibility ();
  972. }
  973. /// <inheritdoc/>
  974. public override bool GetCursorVisibility (out CursorVisibility visibility)
  975. {
  976. if (WinConsole is { })
  977. {
  978. return WinConsole.GetCursorVisibility (out visibility);
  979. }
  980. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  981. return true;
  982. }
  983. /// <inheritdoc/>
  984. public override bool SetCursorVisibility (CursorVisibility visibility)
  985. {
  986. _cachedCursorVisibility = visibility;
  987. if (Force16Colors)
  988. {
  989. return WinConsole is null || WinConsole.SetCursorVisibility (visibility);
  990. }
  991. else
  992. {
  993. var sb = new StringBuilder ();
  994. sb.Append (visibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  995. return WinConsole?.WriteANSI (sb.ToString ()) ?? false;
  996. }
  997. }
  998. /// <inheritdoc/>
  999. public override bool EnsureCursorVisibility ()
  1000. {
  1001. if (Force16Colors)
  1002. {
  1003. return WinConsole is null || WinConsole.EnsureCursorVisibility ();
  1004. }
  1005. else
  1006. {
  1007. var sb = new StringBuilder ();
  1008. sb.Append (_cachedCursorVisibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  1009. return WinConsole?.WriteANSI (sb.ToString ()) ?? false;
  1010. }
  1011. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  1012. {
  1013. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1014. _cachedCursorVisibility = cursorVisibility;
  1015. SetCursorVisibility (CursorVisibility.Invisible);
  1016. return false;
  1017. }
  1018. SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default);
  1019. return _cachedCursorVisibility == CursorVisibility.Default;
  1020. }
  1021. #endregion Cursor Handling
  1022. public override void UpdateScreen ()
  1023. {
  1024. Size windowSize = WinConsole?.GetConsoleBufferWindow (out Point _) ?? new Size (Cols, Rows);
  1025. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows))
  1026. {
  1027. return;
  1028. }
  1029. var bufferCoords = new WindowsConsole.Coord
  1030. {
  1031. X = (short)Clip.Width,
  1032. Y = (short)Clip.Height
  1033. };
  1034. for (var row = 0; row < Rows; row++)
  1035. {
  1036. if (!_dirtyLines [row])
  1037. {
  1038. continue;
  1039. }
  1040. _dirtyLines [row] = false;
  1041. for (var col = 0; col < Cols; col++)
  1042. {
  1043. int position = row * Cols + col;
  1044. _outputBuffer [position].Attribute = Contents [row, col].Attribute.GetValueOrDefault ();
  1045. if (Contents [row, col].IsDirty == false)
  1046. {
  1047. _outputBuffer [position].Empty = true;
  1048. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1049. continue;
  1050. }
  1051. _outputBuffer [position].Empty = false;
  1052. if (Contents [row, col].Rune.IsBmp)
  1053. {
  1054. _outputBuffer [position].Char = (char)Contents [row, col].Rune.Value;
  1055. }
  1056. else
  1057. {
  1058. //_outputBuffer [position].Empty = true;
  1059. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1060. if (Contents [row, col].Rune.GetColumns () > 1 && col + 1 < Cols)
  1061. {
  1062. // TODO: This is a hack to deal with non-BMP and wide characters.
  1063. col++;
  1064. position = row * Cols + col;
  1065. _outputBuffer [position].Empty = false;
  1066. _outputBuffer [position].Char = ' ';
  1067. }
  1068. }
  1069. }
  1070. }
  1071. _damageRegion = new WindowsConsole.SmallRect
  1072. {
  1073. Top = 0,
  1074. Left = 0,
  1075. Bottom = (short)Rows,
  1076. Right = (short)Cols
  1077. };
  1078. if (!RunningUnitTests
  1079. && WinConsole != null
  1080. && !WinConsole.WriteToConsole (new (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors))
  1081. {
  1082. int err = Marshal.GetLastWin32Error ();
  1083. if (err != 0)
  1084. {
  1085. throw new Win32Exception (err);
  1086. }
  1087. }
  1088. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1089. }
  1090. internal override void End ()
  1091. {
  1092. if (_mainLoopDriver is { })
  1093. {
  1094. #if HACK_CHECK_WINCHANGED
  1095. //_mainLoop.WinChanged -= ChangeWin;
  1096. #endif
  1097. }
  1098. _mainLoopDriver = null;
  1099. WinConsole?.Cleanup ();
  1100. WinConsole = null;
  1101. if (!RunningUnitTests && _isWindowsTerminal)
  1102. {
  1103. // Disable alternative screen buffer.
  1104. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  1105. }
  1106. }
  1107. internal override MainLoop Init ()
  1108. {
  1109. _mainLoopDriver = new WindowsMainLoop (this);
  1110. if (!RunningUnitTests)
  1111. {
  1112. try
  1113. {
  1114. if (WinConsole is { })
  1115. {
  1116. // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init.
  1117. // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED
  1118. Size winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1119. Cols = winSize.Width;
  1120. Rows = winSize.Height;
  1121. }
  1122. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1123. if (_isWindowsTerminal)
  1124. {
  1125. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  1126. }
  1127. }
  1128. catch (Win32Exception e)
  1129. {
  1130. // We are being run in an environment that does not support a console
  1131. // such as a unit test, or a pipe.
  1132. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  1133. WinConsole = null;
  1134. }
  1135. }
  1136. CurrentAttribute = new Attribute (Color.White, Color.Black);
  1137. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1138. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  1139. Clip = new (0, 0, Cols, Rows);
  1140. _damageRegion = new WindowsConsole.SmallRect
  1141. {
  1142. Top = 0,
  1143. Left = 0,
  1144. Bottom = (short)Rows,
  1145. Right = (short)Cols
  1146. };
  1147. ClearContents ();
  1148. #if HACK_CHECK_WINCHANGED
  1149. _mainLoopDriver.WinChanged = ChangeWin;
  1150. #endif
  1151. return new MainLoop (_mainLoopDriver);
  1152. }
  1153. internal void ProcessInput (WindowsConsole.InputRecord inputEvent)
  1154. {
  1155. switch (inputEvent.EventType)
  1156. {
  1157. case WindowsConsole.EventType.Key:
  1158. if (inputEvent.KeyEvent.wVirtualKeyCode == (VK)ConsoleKey.Packet)
  1159. {
  1160. // Used to pass Unicode characters as if they were keystrokes.
  1161. // The VK_PACKET key is the low word of a 32-bit
  1162. // Virtual Key value used for non-keyboard input methods.
  1163. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  1164. }
  1165. WindowsConsole.ConsoleKeyInfoEx keyInfo = ToConsoleKeyInfoEx (inputEvent.KeyEvent);
  1166. //Debug.WriteLine ($"event: KBD: {GetKeyboardLayoutName()} {inputEvent.ToString ()} {keyInfo.ToString (keyInfo)}");
  1167. KeyCode map = MapKey (keyInfo);
  1168. if (map == KeyCode.Null)
  1169. {
  1170. break;
  1171. }
  1172. if (inputEvent.KeyEvent.bKeyDown)
  1173. {
  1174. // Avoid sending repeat key down events
  1175. OnKeyDown (new Key (map));
  1176. }
  1177. else
  1178. {
  1179. OnKeyUp (new Key (map));
  1180. }
  1181. break;
  1182. case WindowsConsole.EventType.Mouse:
  1183. MouseEvent me = ToDriverMouse (inputEvent.MouseEvent);
  1184. if (me is null || me.Flags == MouseFlags.None)
  1185. {
  1186. break;
  1187. }
  1188. OnMouseEvent (me);
  1189. if (_processButtonClick)
  1190. {
  1191. OnMouseEvent (new ()
  1192. {
  1193. X = me.X,
  1194. Y = me.Y,
  1195. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  1196. });
  1197. }
  1198. break;
  1199. case WindowsConsole.EventType.Focus:
  1200. break;
  1201. #if !HACK_CHECK_WINCHANGED
  1202. case WindowsConsole.EventType.WindowBufferSize:
  1203. Cols = inputEvent.WindowBufferSizeEvent._size.X;
  1204. Rows = inputEvent.WindowBufferSizeEvent._size.Y;
  1205. ResizeScreen ();
  1206. ClearContents ();
  1207. TerminalResized.Invoke ();
  1208. break;
  1209. #endif
  1210. }
  1211. }
  1212. #if HACK_CHECK_WINCHANGED
  1213. private void ChangeWin (object s, SizeChangedEventArgs e)
  1214. {
  1215. int w = e.Size.Width;
  1216. if (w == Cols - 3 && e.Size.Height < Rows)
  1217. {
  1218. w += 3;
  1219. }
  1220. Left = 0;
  1221. Top = 0;
  1222. Cols = e.Size.Width;
  1223. Rows = e.Size.Height;
  1224. if (!RunningUnitTests)
  1225. {
  1226. Size newSize = WinConsole.SetConsoleWindow (
  1227. (short)Math.Max (w, 16),
  1228. (short)Math.Max (e.Size.Height, 0));
  1229. Cols = newSize.Width;
  1230. Rows = newSize.Height;
  1231. }
  1232. ResizeScreen ();
  1233. ClearContents ();
  1234. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  1235. }
  1236. #endif
  1237. private KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  1238. {
  1239. ConsoleKeyInfo keyInfo = keyInfoEx.ConsoleKeyInfo;
  1240. switch (keyInfo.Key)
  1241. {
  1242. case ConsoleKey.D0:
  1243. case ConsoleKey.D1:
  1244. case ConsoleKey.D2:
  1245. case ConsoleKey.D3:
  1246. case ConsoleKey.D4:
  1247. case ConsoleKey.D5:
  1248. case ConsoleKey.D6:
  1249. case ConsoleKey.D7:
  1250. case ConsoleKey.D8:
  1251. case ConsoleKey.D9:
  1252. case ConsoleKey.NumPad0:
  1253. case ConsoleKey.NumPad1:
  1254. case ConsoleKey.NumPad2:
  1255. case ConsoleKey.NumPad3:
  1256. case ConsoleKey.NumPad4:
  1257. case ConsoleKey.NumPad5:
  1258. case ConsoleKey.NumPad6:
  1259. case ConsoleKey.NumPad7:
  1260. case ConsoleKey.NumPad8:
  1261. case ConsoleKey.NumPad9:
  1262. case ConsoleKey.Oem1:
  1263. case ConsoleKey.Oem2:
  1264. case ConsoleKey.Oem3:
  1265. case ConsoleKey.Oem4:
  1266. case ConsoleKey.Oem5:
  1267. case ConsoleKey.Oem6:
  1268. case ConsoleKey.Oem7:
  1269. case ConsoleKey.Oem8:
  1270. case ConsoleKey.Oem102:
  1271. case ConsoleKey.Multiply:
  1272. case ConsoleKey.Add:
  1273. case ConsoleKey.Separator:
  1274. case ConsoleKey.Subtract:
  1275. case ConsoleKey.Decimal:
  1276. case ConsoleKey.Divide:
  1277. case ConsoleKey.OemPeriod:
  1278. case ConsoleKey.OemComma:
  1279. case ConsoleKey.OemPlus:
  1280. case ConsoleKey.OemMinus:
  1281. // These virtual key codes are mapped differently depending on the keyboard layout in use.
  1282. // We use the Win32 API to map them to the correct character.
  1283. uint mapResult = MapVKtoChar ((VK)keyInfo.Key);
  1284. if (mapResult == 0)
  1285. {
  1286. // There is no mapping - this should not happen
  1287. Debug.Assert (mapResult != 0, $@"Unable to map the virtual key code {keyInfo.Key}.");
  1288. return KeyCode.Null;
  1289. }
  1290. // An un-shifted character value is in the low order word of the return value.
  1291. var mappedChar = (char)(mapResult & 0x0000FFFF);
  1292. if (keyInfo.KeyChar == 0)
  1293. {
  1294. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  1295. // Dead keys (diacritics) are indicated by setting the top bit of the return value.
  1296. if ((mapResult & 0x80000000) != 0)
  1297. {
  1298. // Dead key (e.g. Oem2 '~'/'^' on POR keyboard)
  1299. // Option 1: Throw it out.
  1300. // - Apps will never see the dead keys
  1301. // - If user presses a key that can be combined with the dead key ('a'), the right thing happens (app will see '�').
  1302. // - NOTE: With Dead Keys, KeyDown != KeyUp. The KeyUp event will have just the base char ('a').
  1303. // - If user presses dead key again, the right thing happens (app will see `~~`)
  1304. // - This is what Notepad etc... appear to do
  1305. // Option 2: Expand the API to indicate the KeyCode is a dead key
  1306. // - Enables apps to do their own dead key processing
  1307. // - Adds complexity; no dev has asked for this (yet).
  1308. // We choose Option 1 for now.
  1309. return KeyCode.Null;
  1310. // Note: Ctrl-Deadkey (like Oem3 '`'/'~` on ENG) can't be supported.
  1311. // Sadly, the charVal is just the deadkey and subsequent key events do not contain
  1312. // any info that the previous event was a deadkey.
  1313. // Note WT does not support Ctrl-Deadkey either.
  1314. }
  1315. if (keyInfo.Modifiers != 0)
  1316. {
  1317. // These Oem keys have well defined chars. We ensure the representative char is used.
  1318. // If we don't do this, then on some keyboard layouts the wrong char is
  1319. // returned (e.g. on ENG OemPlus un-shifted is =, not +). This is important
  1320. // for key persistence ("Ctrl++" vs. "Ctrl+=").
  1321. mappedChar = keyInfo.Key switch
  1322. {
  1323. ConsoleKey.OemPeriod => '.',
  1324. ConsoleKey.OemComma => ',',
  1325. ConsoleKey.OemPlus => '+',
  1326. ConsoleKey.OemMinus => '-',
  1327. _ => mappedChar
  1328. };
  1329. }
  1330. // Return the mappedChar with they modifiers. Because mappedChar is un-shifted, if Shift was down
  1331. // we should keep it
  1332. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  1333. }
  1334. // KeyChar is printable
  1335. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1336. {
  1337. // AltGr support - AltGr is equivalent to Ctrl+Alt - the correct char is in KeyChar
  1338. return (KeyCode)keyInfo.KeyChar;
  1339. }
  1340. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  1341. {
  1342. // If Shift wasn't down we don't need to do anything but return the mappedChar
  1343. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  1344. }
  1345. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "�")
  1346. // and passing on Shift would be redundant.
  1347. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1348. }
  1349. // A..Z are special cased:
  1350. // - Alone, they represent lowercase a...z
  1351. // - With ShiftMask they are A..Z
  1352. // - If CapsLock is on the above is reversed.
  1353. // - If Alt and/or Ctrl are present, treat as upper case
  1354. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z)
  1355. {
  1356. if (keyInfo.KeyChar == 0)
  1357. {
  1358. // KeyChar is not printable - possibly an AltGr key?
  1359. // AltGr support - AltGr is equivalent to Ctrl+Alt
  1360. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1361. {
  1362. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  1363. }
  1364. }
  1365. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1366. {
  1367. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  1368. }
  1369. if ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ keyInfoEx.CapsLock)
  1370. {
  1371. // If (ShiftMask is on and CapsLock is off) or (ShiftMask is off and CapsLock is on) add the ShiftMask
  1372. if (char.IsUpper (keyInfo.KeyChar))
  1373. {
  1374. return (KeyCode)(uint)keyInfo.Key | KeyCode.ShiftMask;
  1375. }
  1376. }
  1377. // Return the Key (not KeyChar!)
  1378. return (KeyCode)keyInfo.Key;
  1379. }
  1380. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  1381. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  1382. {
  1383. // If the key is JUST a modifier, return it as just that key
  1384. if (keyInfo.Key == (ConsoleKey)VK.SHIFT)
  1385. { // Shift 16
  1386. return KeyCode.ShiftMask;
  1387. }
  1388. if (keyInfo.Key == (ConsoleKey)VK.CONTROL)
  1389. { // Ctrl 17
  1390. return KeyCode.CtrlMask;
  1391. }
  1392. if (keyInfo.Key == (ConsoleKey)VK.MENU)
  1393. { // Alt 18
  1394. return KeyCode.AltMask;
  1395. }
  1396. if (keyInfo.KeyChar == 0)
  1397. {
  1398. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1399. }
  1400. if (keyInfo.Key != ConsoleKey.None)
  1401. {
  1402. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1403. }
  1404. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1405. }
  1406. // Handle control keys (e.g. CursorUp)
  1407. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  1408. {
  1409. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  1410. }
  1411. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1412. }
  1413. private MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  1414. {
  1415. MouseFlags mouseFlag = 0;
  1416. switch (_lastMouseButtonPressed)
  1417. {
  1418. case WindowsConsole.ButtonState.Button1Pressed:
  1419. mouseFlag = MouseFlags.Button1Clicked;
  1420. break;
  1421. case WindowsConsole.ButtonState.Button2Pressed:
  1422. mouseFlag = MouseFlags.Button2Clicked;
  1423. break;
  1424. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1425. mouseFlag = MouseFlags.Button3Clicked;
  1426. break;
  1427. }
  1428. _point = new Point
  1429. {
  1430. X = mouseEvent.MousePosition.X,
  1431. Y = mouseEvent.MousePosition.Y
  1432. };
  1433. _lastMouseButtonPressed = null;
  1434. _isButtonReleased = false;
  1435. _processButtonClick = false;
  1436. _point = null;
  1437. return mouseFlag;
  1438. }
  1439. private async Task ProcessButtonDoubleClickedAsync ()
  1440. {
  1441. // Only delay if there's not a view wanting continuous button presses
  1442. if (Application.WantContinuousButtonPressedView is null)
  1443. {
  1444. // QUESTION: Why 300ms?
  1445. await Task.Delay (300);
  1446. }
  1447. _isButtonDoubleClicked = false;
  1448. _isOneFingerDoubleClicked = false;
  1449. //buttonPressedCount = 0;
  1450. }
  1451. private async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1452. {
  1453. // When a user presses-and-holds, start generating pressed events every `startDelay`
  1454. // After `iterationsUntilFast` iterations, speed them up to `fastDelay` ms
  1455. const int startDelay = 500;
  1456. const int iterationsUntilFast = 4;
  1457. const int fastDelay = 50;
  1458. int iterations = 0;
  1459. int delay = startDelay;
  1460. while (_isButtonPressed)
  1461. {
  1462. var me = new MouseEvent
  1463. {
  1464. X = _pointMove.X,
  1465. Y = _pointMove.Y,
  1466. Flags = mouseFlag
  1467. };
  1468. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  1469. View view = Application.WantContinuousButtonPressedView;
  1470. if (view is null)
  1471. {
  1472. break;
  1473. }
  1474. if (iterations++ >= iterationsUntilFast)
  1475. {
  1476. delay = fastDelay;
  1477. }
  1478. await Task.Delay (delay);
  1479. //Debug.WriteLine($"ProcessContinuousButtonPressedAsync: {view}");
  1480. if (_isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0)
  1481. {
  1482. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  1483. Application.Invoke (() => OnMouseEvent (me));
  1484. }
  1485. }
  1486. }
  1487. private void ResizeScreen ()
  1488. {
  1489. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1490. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  1491. Clip = new (0, 0, Cols, Rows);
  1492. _damageRegion = new WindowsConsole.SmallRect
  1493. {
  1494. Top = 0,
  1495. Left = 0,
  1496. Bottom = (short)Rows,
  1497. Right = (short)Cols
  1498. };
  1499. _dirtyLines = new bool [Rows];
  1500. WinConsole?.ForceRefreshCursorVisibility ();
  1501. }
  1502. private static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1503. {
  1504. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)
  1505. || mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  1506. {
  1507. mouseFlag |= MouseFlags.ButtonCtrl;
  1508. }
  1509. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  1510. {
  1511. mouseFlag |= MouseFlags.ButtonShift;
  1512. }
  1513. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  1514. || mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  1515. {
  1516. mouseFlag |= MouseFlags.ButtonAlt;
  1517. }
  1518. return mouseFlag;
  1519. }
  1520. [CanBeNull]
  1521. private MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  1522. {
  1523. var mouseFlag = MouseFlags.AllEvents;
  1524. //Debug.WriteLine ($"ToDriverMouse: {mouseEvent}");
  1525. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked)
  1526. {
  1527. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  1528. Application.MainLoop.AddIdle (
  1529. () =>
  1530. {
  1531. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  1532. return false;
  1533. });
  1534. }
  1535. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  1536. // This will tell when a mouse button is pressed. When the button is released this event will
  1537. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  1538. // To map to the correct driver events we save the last pressed mouse button so we can
  1539. // map to the correct clicked event.
  1540. if ((_lastMouseButtonPressed is { } || _isButtonReleased) && mouseEvent.ButtonState != 0)
  1541. {
  1542. _lastMouseButtonPressed = null;
  1543. //isButtonPressed = false;
  1544. _isButtonReleased = false;
  1545. }
  1546. var p = new Point
  1547. {
  1548. X = mouseEvent.MousePosition.X,
  1549. Y = mouseEvent.MousePosition.Y
  1550. };
  1551. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed is null && !_isButtonDoubleClicked)
  1552. || (_lastMouseButtonPressed == null
  1553. && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved)
  1554. && mouseEvent.ButtonState != 0
  1555. && !_isButtonReleased
  1556. && !_isButtonDoubleClicked))
  1557. {
  1558. switch (mouseEvent.ButtonState)
  1559. {
  1560. case WindowsConsole.ButtonState.Button1Pressed:
  1561. mouseFlag = MouseFlags.Button1Pressed;
  1562. break;
  1563. case WindowsConsole.ButtonState.Button2Pressed:
  1564. mouseFlag = MouseFlags.Button2Pressed;
  1565. break;
  1566. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1567. mouseFlag = MouseFlags.Button3Pressed;
  1568. break;
  1569. }
  1570. if (_point is null)
  1571. {
  1572. _point = p;
  1573. }
  1574. if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved))
  1575. {
  1576. _pointMove = p;
  1577. mouseFlag |= MouseFlags.ReportMousePosition;
  1578. _isButtonReleased = false;
  1579. _processButtonClick = false;
  1580. }
  1581. _lastMouseButtonPressed = mouseEvent.ButtonState;
  1582. _isButtonPressed = true;
  1583. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0)
  1584. {
  1585. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  1586. Application.MainLoop.AddIdle (
  1587. () =>
  1588. {
  1589. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  1590. return false;
  1591. });
  1592. }
  1593. }
  1594. else if (_lastMouseButtonPressed != null
  1595. && mouseEvent.EventFlags == 0
  1596. && !_isButtonReleased
  1597. && !_isButtonDoubleClicked
  1598. && !_isOneFingerDoubleClicked)
  1599. {
  1600. switch (_lastMouseButtonPressed)
  1601. {
  1602. case WindowsConsole.ButtonState.Button1Pressed:
  1603. mouseFlag = MouseFlags.Button1Released;
  1604. break;
  1605. case WindowsConsole.ButtonState.Button2Pressed:
  1606. mouseFlag = MouseFlags.Button2Released;
  1607. break;
  1608. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1609. mouseFlag = MouseFlags.Button3Released;
  1610. break;
  1611. }
  1612. _isButtonPressed = false;
  1613. _isButtonReleased = true;
  1614. if (_point is { } && ((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)
  1615. {
  1616. _processButtonClick = true;
  1617. }
  1618. else
  1619. {
  1620. _point = null;
  1621. }
  1622. _processButtonClick = true;
  1623. }
  1624. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  1625. && !_isOneFingerDoubleClicked
  1626. && _isButtonReleased
  1627. && p == _point)
  1628. {
  1629. mouseFlag = ProcessButtonClick (mouseEvent);
  1630. }
  1631. else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick))
  1632. {
  1633. switch (mouseEvent.ButtonState)
  1634. {
  1635. case WindowsConsole.ButtonState.Button1Pressed:
  1636. mouseFlag = MouseFlags.Button1DoubleClicked;
  1637. break;
  1638. case WindowsConsole.ButtonState.Button2Pressed:
  1639. mouseFlag = MouseFlags.Button2DoubleClicked;
  1640. break;
  1641. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1642. mouseFlag = MouseFlags.Button3DoubleClicked;
  1643. break;
  1644. }
  1645. _isButtonDoubleClicked = true;
  1646. }
  1647. else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked)
  1648. {
  1649. switch (mouseEvent.ButtonState)
  1650. {
  1651. case WindowsConsole.ButtonState.Button1Pressed:
  1652. mouseFlag = MouseFlags.Button1TripleClicked;
  1653. break;
  1654. case WindowsConsole.ButtonState.Button2Pressed:
  1655. mouseFlag = MouseFlags.Button2TripleClicked;
  1656. break;
  1657. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1658. mouseFlag = MouseFlags.Button3TripleClicked;
  1659. break;
  1660. }
  1661. _isButtonDoubleClicked = false;
  1662. }
  1663. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled)
  1664. {
  1665. switch ((int)mouseEvent.ButtonState)
  1666. {
  1667. case int v when v > 0:
  1668. mouseFlag = MouseFlags.WheeledUp;
  1669. break;
  1670. case int v when v < 0:
  1671. mouseFlag = MouseFlags.WheeledDown;
  1672. break;
  1673. }
  1674. }
  1675. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled && mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed)
  1676. {
  1677. switch ((int)mouseEvent.ButtonState)
  1678. {
  1679. case int v when v > 0:
  1680. mouseFlag = MouseFlags.WheeledLeft;
  1681. break;
  1682. case int v when v < 0:
  1683. mouseFlag = MouseFlags.WheeledRight;
  1684. break;
  1685. }
  1686. }
  1687. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled)
  1688. {
  1689. switch ((int)mouseEvent.ButtonState)
  1690. {
  1691. case int v when v < 0:
  1692. mouseFlag = MouseFlags.WheeledLeft;
  1693. break;
  1694. case int v when v > 0:
  1695. mouseFlag = MouseFlags.WheeledRight;
  1696. break;
  1697. }
  1698. }
  1699. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved)
  1700. {
  1701. mouseFlag = MouseFlags.ReportMousePosition;
  1702. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y)
  1703. {
  1704. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  1705. }
  1706. }
  1707. else if (mouseEvent is { ButtonState: 0, EventFlags: 0 })
  1708. {
  1709. // This happens on a double or triple click event.
  1710. mouseFlag = MouseFlags.None;
  1711. }
  1712. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  1713. //System.Diagnostics.Debug.WriteLine (
  1714. // $"point.X:{(point is { } ? ((Point)point).X : -1)};point.Y:{(point is { } ? ((Point)point).Y : -1)}");
  1715. return new MouseEvent
  1716. {
  1717. X = mouseEvent.MousePosition.X,
  1718. Y = mouseEvent.MousePosition.Y,
  1719. Flags = mouseFlag
  1720. };
  1721. }
  1722. }
  1723. /// <summary>
  1724. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1725. /// only be used on Windows.
  1726. /// </summary>
  1727. /// <remarks>
  1728. /// This implementation is used for WindowsDriver.
  1729. /// </remarks>
  1730. internal class WindowsMainLoop : IMainLoopDriver
  1731. {
  1732. /// <summary>
  1733. /// Invoked when the window is changed.
  1734. /// </summary>
  1735. public EventHandler<SizeChangedEventArgs> WinChanged;
  1736. private readonly ConsoleDriver _consoleDriver;
  1737. private readonly ManualResetEventSlim _eventReady = new (false);
  1738. // The records that we keep fetching
  1739. private readonly Queue<WindowsConsole.InputRecord []> _resultQueue = new ();
  1740. private readonly ManualResetEventSlim _waitForProbe = new (false);
  1741. private readonly WindowsConsole _winConsole;
  1742. private CancellationTokenSource _eventReadyTokenSource = new ();
  1743. private readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  1744. private MainLoop _mainLoop;
  1745. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1746. {
  1747. _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver));
  1748. _winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1749. }
  1750. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1751. {
  1752. _mainLoop = mainLoop;
  1753. Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token);
  1754. #if HACK_CHECK_WINCHANGED
  1755. Task.Run (CheckWinChange);
  1756. #endif
  1757. }
  1758. void IMainLoopDriver.Wakeup () { _eventReady.Set (); }
  1759. bool IMainLoopDriver.EventsPending ()
  1760. {
  1761. _waitForProbe.Set ();
  1762. #if HACK_CHECK_WINCHANGED
  1763. _winChange.Set ();
  1764. #endif
  1765. if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout))
  1766. {
  1767. return true;
  1768. }
  1769. try
  1770. {
  1771. if (!_eventReadyTokenSource.IsCancellationRequested)
  1772. {
  1773. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1774. // are no timers, but there IS an idle handler waiting.
  1775. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1776. }
  1777. }
  1778. catch (OperationCanceledException)
  1779. {
  1780. return true;
  1781. }
  1782. finally
  1783. {
  1784. _eventReady.Reset ();
  1785. }
  1786. if (!_eventReadyTokenSource.IsCancellationRequested)
  1787. {
  1788. #if HACK_CHECK_WINCHANGED
  1789. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  1790. #else
  1791. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1792. #endif
  1793. }
  1794. _eventReadyTokenSource.Dispose ();
  1795. _eventReadyTokenSource = new CancellationTokenSource ();
  1796. return true;
  1797. }
  1798. void IMainLoopDriver.Iteration ()
  1799. {
  1800. while (_resultQueue.Count > 0)
  1801. {
  1802. WindowsConsole.InputRecord [] inputRecords = _resultQueue.Dequeue ();
  1803. if (inputRecords is { Length: > 0 })
  1804. {
  1805. ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords [0]);
  1806. }
  1807. }
  1808. #if HACK_CHECK_WINCHANGED
  1809. if (_winChanged)
  1810. {
  1811. _winChanged = false;
  1812. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  1813. }
  1814. #endif
  1815. }
  1816. void IMainLoopDriver.TearDown ()
  1817. {
  1818. // Eat any outstanding events. See #
  1819. //var records =
  1820. _winConsole.ReadConsoleInput ();
  1821. //if (records != null)
  1822. //{
  1823. // foreach (var rec in records)
  1824. // {
  1825. // Debug.WriteLine ($"Teardown: {rec.ToString ()}");
  1826. // //Debug.Assert (rec is not { EventType: WindowsConsole.EventType.Mouse, MouseEvent.ButtonState: WindowsConsole.ButtonState.Button1Pressed });
  1827. // }
  1828. //}
  1829. _inputHandlerTokenSource?.Cancel ();
  1830. _inputHandlerTokenSource?.Dispose ();
  1831. _eventReadyTokenSource?.Cancel ();
  1832. _eventReadyTokenSource?.Dispose ();
  1833. _eventReady?.Dispose ();
  1834. _resultQueue?.Clear ();
  1835. #if HACK_CHECK_WINCHANGED
  1836. _winChange?.Dispose ();
  1837. #endif
  1838. //_waitForProbe?.Dispose ();
  1839. _mainLoop = null;
  1840. }
  1841. private void WindowsInputHandler ()
  1842. {
  1843. while (_mainLoop is { })
  1844. {
  1845. try
  1846. {
  1847. if (!_inputHandlerTokenSource.IsCancellationRequested)
  1848. {
  1849. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1850. }
  1851. }
  1852. catch (OperationCanceledException)
  1853. {
  1854. return;
  1855. }
  1856. finally
  1857. {
  1858. _waitForProbe.Reset ();
  1859. }
  1860. if (_resultQueue?.Count == 0)
  1861. {
  1862. _resultQueue.Enqueue (_winConsole.ReadConsoleInput ());
  1863. }
  1864. _eventReady.Set ();
  1865. }
  1866. }
  1867. #if HACK_CHECK_WINCHANGED
  1868. private readonly ManualResetEventSlim _winChange = new (false);
  1869. private bool _winChanged;
  1870. private Size _windowSize;
  1871. private void CheckWinChange ()
  1872. {
  1873. while (_mainLoop is { })
  1874. {
  1875. _winChange.Wait ();
  1876. _winChange.Reset ();
  1877. // Check if the window size changed every half second.
  1878. // We do this to minimize the weird tearing seen on Windows when resizing the console
  1879. while (_mainLoop is { })
  1880. {
  1881. Task.Delay (500).Wait ();
  1882. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  1883. if (_windowSize != Size.Empty
  1884. && (_windowSize.Width != _consoleDriver.Cols
  1885. || _windowSize.Height != _consoleDriver.Rows))
  1886. {
  1887. break;
  1888. }
  1889. }
  1890. _winChanged = true;
  1891. _eventReady.Set ();
  1892. }
  1893. }
  1894. #endif
  1895. }
  1896. internal class WindowsClipboard : ClipboardBase
  1897. {
  1898. private const uint _cfUnicodeText = 13;
  1899. public WindowsClipboard () { IsSupported = IsClipboardFormatAvailable (_cfUnicodeText); }
  1900. public override bool IsSupported { get; }
  1901. protected override string GetClipboardDataImpl ()
  1902. {
  1903. try
  1904. {
  1905. if (!OpenClipboard (nint.Zero))
  1906. {
  1907. return string.Empty;
  1908. }
  1909. nint handle = GetClipboardData (_cfUnicodeText);
  1910. if (handle == nint.Zero)
  1911. {
  1912. return string.Empty;
  1913. }
  1914. nint pointer = nint.Zero;
  1915. try
  1916. {
  1917. pointer = GlobalLock (handle);
  1918. if (pointer == nint.Zero)
  1919. {
  1920. return string.Empty;
  1921. }
  1922. int size = GlobalSize (handle);
  1923. var buff = new byte [size];
  1924. Marshal.Copy (pointer, buff, 0, size);
  1925. return Encoding.Unicode.GetString (buff).TrimEnd ('\0');
  1926. }
  1927. finally
  1928. {
  1929. if (pointer != nint.Zero)
  1930. {
  1931. GlobalUnlock (handle);
  1932. }
  1933. }
  1934. }
  1935. finally
  1936. {
  1937. CloseClipboard ();
  1938. }
  1939. }
  1940. protected override void SetClipboardDataImpl (string text)
  1941. {
  1942. OpenClipboard ();
  1943. EmptyClipboard ();
  1944. nint hGlobal = default;
  1945. try
  1946. {
  1947. int bytes = (text.Length + 1) * 2;
  1948. hGlobal = Marshal.AllocHGlobal (bytes);
  1949. if (hGlobal == default (nint))
  1950. {
  1951. ThrowWin32 ();
  1952. }
  1953. nint target = GlobalLock (hGlobal);
  1954. if (target == default (nint))
  1955. {
  1956. ThrowWin32 ();
  1957. }
  1958. try
  1959. {
  1960. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1961. }
  1962. finally
  1963. {
  1964. GlobalUnlock (target);
  1965. }
  1966. if (SetClipboardData (_cfUnicodeText, hGlobal) == default (nint))
  1967. {
  1968. ThrowWin32 ();
  1969. }
  1970. hGlobal = default (nint);
  1971. }
  1972. finally
  1973. {
  1974. if (hGlobal != default (nint))
  1975. {
  1976. Marshal.FreeHGlobal (hGlobal);
  1977. }
  1978. CloseClipboard ();
  1979. }
  1980. }
  1981. [DllImport ("user32.dll", SetLastError = true)]
  1982. [return: MarshalAs (UnmanagedType.Bool)]
  1983. private static extern bool CloseClipboard ();
  1984. [DllImport ("user32.dll")]
  1985. private static extern bool EmptyClipboard ();
  1986. [DllImport ("user32.dll", SetLastError = true)]
  1987. private static extern nint GetClipboardData (uint uFormat);
  1988. [DllImport ("kernel32.dll", SetLastError = true)]
  1989. private static extern nint GlobalLock (nint hMem);
  1990. [DllImport ("kernel32.dll", SetLastError = true)]
  1991. private static extern int GlobalSize (nint handle);
  1992. [DllImport ("kernel32.dll", SetLastError = true)]
  1993. [return: MarshalAs (UnmanagedType.Bool)]
  1994. private static extern bool GlobalUnlock (nint hMem);
  1995. [DllImport ("User32.dll", SetLastError = true)]
  1996. [return: MarshalAs (UnmanagedType.Bool)]
  1997. private static extern bool IsClipboardFormatAvailable (uint format);
  1998. private void OpenClipboard ()
  1999. {
  2000. var num = 10;
  2001. while (true)
  2002. {
  2003. if (OpenClipboard (default (nint)))
  2004. {
  2005. break;
  2006. }
  2007. if (--num == 0)
  2008. {
  2009. ThrowWin32 ();
  2010. }
  2011. Thread.Sleep (100);
  2012. }
  2013. }
  2014. [DllImport ("user32.dll", SetLastError = true)]
  2015. [return: MarshalAs (UnmanagedType.Bool)]
  2016. private static extern bool OpenClipboard (nint hWndNewOwner);
  2017. [DllImport ("user32.dll", SetLastError = true)]
  2018. private static extern nint SetClipboardData (uint uFormat, nint data);
  2019. private void ThrowWin32 () { throw new Win32Exception (Marshal.GetLastWin32Error ()); }
  2020. }