WindowsDriver.cs 74 KB

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