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