WindowsDriver.cs 79 KB

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