WindowsDriver.cs 78 KB

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