WindowsDriver.cs 75 KB

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