WindowsDriver.cs 79 KB

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