WindowsDriver.cs 79 KB

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