WindowsDriver.cs 78 KB

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