WindowsDriver.cs 78 KB

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