WindowsDriver.cs 80 KB

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