WindowsDriver.cs 79 KB

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