WindowsDriver.cs 80 KB

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