WindowsDriver.cs 79 KB

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