WindowsDriver.cs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039
  1. //
  2. // WindowsDriver.cs: Windows specific driver
  3. //
  4. using System.Text;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Linq;
  9. using System.Runtime.InteropServices;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using System.Diagnostics;
  13. using System.Management;
  14. namespace Terminal.Gui;
  15. internal class WindowsConsole {
  16. public const int STD_OUTPUT_HANDLE = -11;
  17. public const int STD_INPUT_HANDLE = -10;
  18. IntPtr _inputHandle, _outputHandle;
  19. IntPtr _screenBuffer;
  20. readonly uint _originalConsoleMode;
  21. CursorVisibility? _initialCursorVisibility = null;
  22. CursorVisibility? _currentCursorVisibility = null;
  23. CursorVisibility? _pendingCursorVisibility = null;
  24. readonly StringBuilder _stringBuilder = new StringBuilder (256 * 1024);
  25. public WindowsConsole ()
  26. {
  27. _inputHandle = GetStdHandle (STD_INPUT_HANDLE);
  28. _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  29. _originalConsoleMode = ConsoleMode;
  30. var newConsoleMode = _originalConsoleMode;
  31. newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
  32. newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
  33. newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput;
  34. ConsoleMode = newConsoleMode;
  35. }
  36. CharInfo [] _originalStdOutChars;
  37. public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord coords, SmallRect window, bool force16Colors)
  38. {
  39. if (_screenBuffer == IntPtr.Zero) {
  40. ReadFromConsoleOutput (size, coords, ref window);
  41. }
  42. bool result = false;
  43. if (force16Colors) {
  44. int i = 0;
  45. CharInfo [] ci = new CharInfo [charInfoBuffer.Length];
  46. foreach (ExtendedCharInfo info in charInfoBuffer) {
  47. ci [i++] = new CharInfo () {
  48. Char = new CharUnion () { UnicodeChar = info.Char },
  49. Attributes = (ushort)info.Attribute.Value
  50. };
  51. }
  52. result = WriteConsoleOutput (_screenBuffer, ci, coords, new Coord () { X = window.Left, Y = window.Top }, ref window);
  53. } else {
  54. _stringBuilder.Clear ();
  55. _stringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition);
  56. _stringBuilder.Append (EscSeqUtils.CSI_SetCursorPosition (0, 0));
  57. Attribute? prev = null;
  58. foreach (var info in charInfoBuffer) {
  59. var attr = info.Attribute;
  60. if (attr != prev) {
  61. prev = attr;
  62. _stringBuilder.Append (EscSeqUtils.CSI_SetForegroundColorRGB (attr.TrueColorForeground.Value.Red, attr.TrueColorForeground.Value.Green, attr.TrueColorForeground.Value.Blue));
  63. _stringBuilder.Append (EscSeqUtils.CSI_SetBackgroundColorRGB (attr.TrueColorBackground.Value.Red, attr.TrueColorBackground.Value.Green, attr.TrueColorBackground.Value.Blue));
  64. }
  65. if (info.Char != '\x1b') {
  66. if (!info.Empty) {
  67. _stringBuilder.Append (info.Char);
  68. }
  69. } else {
  70. _stringBuilder.Append (' ');
  71. }
  72. }
  73. _stringBuilder.Append (EscSeqUtils.CSI_RestoreCursorPosition);
  74. string s = _stringBuilder.ToString ();
  75. result = WriteConsole (_screenBuffer, s, (uint)(s.Length), out uint _, null);
  76. }
  77. if (!result) {
  78. var err = Marshal.GetLastWin32Error ();
  79. if (err != 0) {
  80. throw new System.ComponentModel.Win32Exception (err);
  81. }
  82. }
  83. return result;
  84. }
  85. public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window)
  86. {
  87. _screenBuffer = CreateConsoleScreenBuffer (
  88. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  89. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  90. IntPtr.Zero,
  91. 1,
  92. IntPtr.Zero
  93. );
  94. if (_screenBuffer == INVALID_HANDLE_VALUE) {
  95. var err = Marshal.GetLastWin32Error ();
  96. if (err != 0) {
  97. throw new System.ComponentModel.Win32Exception (err);
  98. }
  99. }
  100. if (!_initialCursorVisibility.HasValue && GetCursorVisibility (out CursorVisibility visibility)) {
  101. _initialCursorVisibility = visibility;
  102. }
  103. if (!SetConsoleActiveScreenBuffer (_screenBuffer)) {
  104. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  105. }
  106. _originalStdOutChars = new CharInfo [size.Height * size.Width];
  107. if (!ReadConsoleOutput (_screenBuffer, _originalStdOutChars, coords, new Coord () { X = 0, Y = 0 }, ref window)) {
  108. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  109. }
  110. }
  111. public bool SetCursorPosition (Coord position)
  112. {
  113. return SetConsoleCursorPosition (_screenBuffer, position);
  114. }
  115. public void SetInitialCursorVisibility ()
  116. {
  117. if (_initialCursorVisibility.HasValue == false && GetCursorVisibility (out CursorVisibility visibility)) {
  118. _initialCursorVisibility = visibility;
  119. }
  120. }
  121. public bool GetCursorVisibility (out CursorVisibility visibility)
  122. {
  123. if (_screenBuffer == IntPtr.Zero) {
  124. visibility = CursorVisibility.Invisible;
  125. return false;
  126. }
  127. if (!GetConsoleCursorInfo (_screenBuffer, out ConsoleCursorInfo info)) {
  128. var err = Marshal.GetLastWin32Error ();
  129. if (err != 0) {
  130. throw new System.ComponentModel.Win32Exception (err);
  131. }
  132. visibility = Gui.CursorVisibility.Default;
  133. return false;
  134. }
  135. if (!info.bVisible) {
  136. visibility = CursorVisibility.Invisible;
  137. } else if (info.dwSize > 50) {
  138. visibility = CursorVisibility.Box;
  139. } else {
  140. visibility = CursorVisibility.Underline;
  141. }
  142. return true;
  143. }
  144. public bool EnsureCursorVisibility ()
  145. {
  146. if (_initialCursorVisibility.HasValue && _pendingCursorVisibility.HasValue && SetCursorVisibility (_pendingCursorVisibility.Value)) {
  147. _pendingCursorVisibility = null;
  148. return true;
  149. }
  150. return false;
  151. }
  152. public void ForceRefreshCursorVisibility ()
  153. {
  154. if (_currentCursorVisibility.HasValue) {
  155. _pendingCursorVisibility = _currentCursorVisibility;
  156. _currentCursorVisibility = null;
  157. }
  158. }
  159. public bool SetCursorVisibility (CursorVisibility visibility)
  160. {
  161. if (_initialCursorVisibility.HasValue == false) {
  162. _pendingCursorVisibility = visibility;
  163. return false;
  164. }
  165. if (_currentCursorVisibility.HasValue == false || _currentCursorVisibility.Value != visibility) {
  166. ConsoleCursorInfo info = new ConsoleCursorInfo {
  167. dwSize = (uint)visibility & 0x00FF,
  168. bVisible = ((uint)visibility & 0xFF00) != 0
  169. };
  170. if (!SetConsoleCursorInfo (_screenBuffer, ref info)) {
  171. return false;
  172. }
  173. _currentCursorVisibility = visibility;
  174. }
  175. return true;
  176. }
  177. public void Cleanup ()
  178. {
  179. if (_initialCursorVisibility.HasValue) {
  180. SetCursorVisibility (_initialCursorVisibility.Value);
  181. }
  182. SetConsoleOutputWindow (out _);
  183. ConsoleMode = _originalConsoleMode;
  184. if (!SetConsoleActiveScreenBuffer (_outputHandle)) {
  185. var err = Marshal.GetLastWin32Error ();
  186. Console.WriteLine ("Error: {0}", err);
  187. }
  188. if (_screenBuffer != IntPtr.Zero) {
  189. CloseHandle (_screenBuffer);
  190. }
  191. _screenBuffer = IntPtr.Zero;
  192. }
  193. internal Size GetConsoleBufferWindow (out Point position)
  194. {
  195. if (_screenBuffer == IntPtr.Zero) {
  196. position = Point.Empty;
  197. return Size.Empty;
  198. }
  199. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  200. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  201. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  202. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  203. position = Point.Empty;
  204. return Size.Empty;
  205. }
  206. var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
  207. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  208. position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
  209. return sz;
  210. }
  211. internal Size GetConsoleOutputWindow (out Point position)
  212. {
  213. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  214. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  215. if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) {
  216. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  217. }
  218. var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
  219. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  220. position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
  221. return sz;
  222. }
  223. internal Size SetConsoleWindow (short cols, short rows)
  224. {
  225. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  226. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  227. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  228. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  229. }
  230. var maxWinSize = GetLargestConsoleWindowSize (_screenBuffer);
  231. var newCols = Math.Min (cols, maxWinSize.X);
  232. var newRows = Math.Min (rows, maxWinSize.Y);
  233. csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1));
  234. csbi.srWindow = new SmallRect (0, 0, newCols, newRows);
  235. csbi.dwMaximumWindowSize = new Coord (newCols, newRows);
  236. if (!SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  237. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  238. }
  239. var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0));
  240. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) {
  241. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  242. return new Size (cols, rows);
  243. }
  244. SetConsoleOutputWindow (csbi);
  245. return new Size (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1);
  246. }
  247. void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi)
  248. {
  249. if (_screenBuffer != IntPtr.Zero && !SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  250. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  251. }
  252. }
  253. internal Size SetConsoleOutputWindow (out Point position)
  254. {
  255. if (_screenBuffer == IntPtr.Zero) {
  256. position = Point.Empty;
  257. return Size.Empty;
  258. }
  259. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  260. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  261. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  262. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  263. }
  264. var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
  265. Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0));
  266. position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
  267. SetConsoleOutputWindow (csbi);
  268. var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0));
  269. if (!SetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) {
  270. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  271. }
  272. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) {
  273. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  274. }
  275. return sz;
  276. }
  277. uint ConsoleMode {
  278. get {
  279. GetConsoleMode (_inputHandle, out uint v);
  280. return v;
  281. }
  282. set {
  283. SetConsoleMode (_inputHandle, value);
  284. }
  285. }
  286. [Flags]
  287. public enum ConsoleModes : uint {
  288. EnableProcessedInput = 1,
  289. EnableMouseInput = 16,
  290. EnableQuickEditMode = 64,
  291. EnableExtendedFlags = 128,
  292. }
  293. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  294. public struct KeyEventRecord {
  295. [FieldOffset (0), MarshalAs (UnmanagedType.Bool)]
  296. public bool bKeyDown;
  297. [FieldOffset (4), MarshalAs (UnmanagedType.U2)]
  298. public ushort wRepeatCount;
  299. [FieldOffset (6), MarshalAs (UnmanagedType.U2)]
  300. public ushort wVirtualKeyCode;
  301. [FieldOffset (8), MarshalAs (UnmanagedType.U2)]
  302. public ushort wVirtualScanCode;
  303. [FieldOffset (10)]
  304. public char UnicodeChar;
  305. [FieldOffset (12), MarshalAs (UnmanagedType.U4)]
  306. public ControlKeyState dwControlKeyState;
  307. }
  308. [Flags]
  309. public enum ButtonState {
  310. Button1Pressed = 1,
  311. Button2Pressed = 4,
  312. Button3Pressed = 8,
  313. Button4Pressed = 16,
  314. RightmostButtonPressed = 2
  315. }
  316. [Flags]
  317. public enum ControlKeyState {
  318. RightAltPressed = 1,
  319. LeftAltPressed = 2,
  320. RightControlPressed = 4,
  321. LeftControlPressed = 8,
  322. ShiftPressed = 16,
  323. NumlockOn = 32,
  324. ScrolllockOn = 64,
  325. CapslockOn = 128,
  326. EnhancedKey = 256
  327. }
  328. [Flags]
  329. public enum EventFlags {
  330. MouseMoved = 1,
  331. DoubleClick = 2,
  332. MouseWheeled = 4,
  333. MouseHorizontalWheeled = 8
  334. }
  335. [StructLayout (LayoutKind.Explicit)]
  336. public struct MouseEventRecord {
  337. [FieldOffset (0)]
  338. public Coord MousePosition;
  339. [FieldOffset (4)]
  340. public ButtonState ButtonState;
  341. [FieldOffset (8)]
  342. public ControlKeyState ControlKeyState;
  343. [FieldOffset (12)]
  344. public EventFlags EventFlags;
  345. public override readonly string ToString () => $"[Mouse({MousePosition},{ButtonState},{ControlKeyState},{EventFlags}";
  346. }
  347. public struct WindowBufferSizeRecord {
  348. public Coord _size;
  349. public WindowBufferSizeRecord (short x, short y)
  350. {
  351. _size = new Coord (x, y);
  352. }
  353. public override readonly string ToString () => $"[WindowBufferSize{_size}";
  354. }
  355. [StructLayout (LayoutKind.Sequential)]
  356. public struct MenuEventRecord {
  357. public uint dwCommandId;
  358. }
  359. [StructLayout (LayoutKind.Sequential)]
  360. public struct FocusEventRecord {
  361. public uint bSetFocus;
  362. }
  363. public enum EventType : ushort {
  364. Focus = 0x10,
  365. Key = 0x1,
  366. Menu = 0x8,
  367. Mouse = 2,
  368. WindowBufferSize = 4
  369. }
  370. [StructLayout (LayoutKind.Explicit)]
  371. public struct InputRecord {
  372. [FieldOffset (0)]
  373. public EventType EventType;
  374. [FieldOffset (4)]
  375. public KeyEventRecord KeyEvent;
  376. [FieldOffset (4)]
  377. public MouseEventRecord MouseEvent;
  378. [FieldOffset (4)]
  379. public WindowBufferSizeRecord WindowBufferSizeEvent;
  380. [FieldOffset (4)]
  381. public MenuEventRecord MenuEvent;
  382. [FieldOffset (4)]
  383. public FocusEventRecord FocusEvent;
  384. public override readonly string ToString ()
  385. {
  386. return EventType switch {
  387. EventType.Focus => FocusEvent.ToString (),
  388. EventType.Key => KeyEvent.ToString (),
  389. EventType.Menu => MenuEvent.ToString (),
  390. EventType.Mouse => MouseEvent.ToString (),
  391. EventType.WindowBufferSize => WindowBufferSizeEvent.ToString (),
  392. _ => "Unknown event type: " + EventType
  393. };
  394. }
  395. };
  396. [Flags]
  397. enum ShareMode : uint {
  398. FileShareRead = 1,
  399. FileShareWrite = 2,
  400. }
  401. [Flags]
  402. enum DesiredAccess : uint {
  403. GenericRead = 2147483648,
  404. GenericWrite = 1073741824,
  405. }
  406. [StructLayout (LayoutKind.Sequential)]
  407. public struct ConsoleScreenBufferInfo {
  408. public Coord dwSize;
  409. public Coord dwCursorPosition;
  410. public ushort wAttributes;
  411. public SmallRect srWindow;
  412. public Coord dwMaximumWindowSize;
  413. }
  414. [StructLayout (LayoutKind.Sequential)]
  415. public struct Coord {
  416. public short X;
  417. public short Y;
  418. public Coord (short x, short y)
  419. {
  420. X = x;
  421. Y = y;
  422. }
  423. public override readonly string ToString () => $"({X},{Y})";
  424. };
  425. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  426. public struct CharUnion {
  427. [FieldOffset (0)] public char UnicodeChar;
  428. [FieldOffset (0)] public byte AsciiChar;
  429. }
  430. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  431. public struct CharInfo {
  432. [FieldOffset (0)] public CharUnion Char;
  433. [FieldOffset (2)] public ushort Attributes;
  434. }
  435. public struct ExtendedCharInfo {
  436. public char Char { get; set; }
  437. public Attribute Attribute { get; set; }
  438. public bool Empty { get; set; } // TODO: Temp hack until virutal terminal sequences
  439. public ExtendedCharInfo (char character, Attribute attribute)
  440. {
  441. Char = character;
  442. Attribute = attribute;
  443. Empty = false;
  444. }
  445. }
  446. [StructLayout (LayoutKind.Sequential)]
  447. public struct SmallRect {
  448. public short Left;
  449. public short Top;
  450. public short Right;
  451. public short Bottom;
  452. public SmallRect (short left, short top, short right, short bottom)
  453. {
  454. Left = left;
  455. Top = top;
  456. Right = right;
  457. Bottom = bottom;
  458. }
  459. public static void MakeEmpty (ref SmallRect rect)
  460. {
  461. rect.Left = -1;
  462. }
  463. public static void Update (ref SmallRect rect, short col, short row)
  464. {
  465. if (rect.Left == -1) {
  466. rect.Left = rect.Right = col;
  467. rect.Bottom = rect.Top = row;
  468. return;
  469. }
  470. if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
  471. return;
  472. if (col < rect.Left)
  473. rect.Left = col;
  474. if (col > rect.Right)
  475. rect.Right = col;
  476. if (row < rect.Top)
  477. rect.Top = row;
  478. if (row > rect.Bottom)
  479. rect.Bottom = row;
  480. }
  481. public override readonly string ToString () => $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}";
  482. }
  483. [StructLayout (LayoutKind.Sequential)]
  484. public struct ConsoleKeyInfoEx {
  485. public ConsoleKeyInfo ConsoleKeyInfo;
  486. public bool CapsLock;
  487. public bool NumLock;
  488. public bool ScrollLock;
  489. public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock, bool scrolllock)
  490. {
  491. ConsoleKeyInfo = consoleKeyInfo;
  492. CapsLock = capslock;
  493. NumLock = numlock;
  494. ScrollLock = scrolllock;
  495. }
  496. }
  497. [DllImport ("kernel32.dll", SetLastError = true)]
  498. static extern IntPtr GetStdHandle (int nStdHandle);
  499. [DllImport ("kernel32.dll", SetLastError = true)]
  500. static extern bool CloseHandle (IntPtr handle);
  501. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  502. public static extern bool ReadConsoleInput (
  503. IntPtr hConsoleInput,
  504. IntPtr lpBuffer,
  505. uint nLength,
  506. out uint lpNumberOfEventsRead);
  507. [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  508. static extern bool ReadConsoleOutput (
  509. IntPtr hConsoleOutput,
  510. [Out] CharInfo [] lpBuffer,
  511. Coord dwBufferSize,
  512. Coord dwBufferCoord,
  513. ref SmallRect lpReadRegion
  514. );
  515. // TODO: This API is obsolete. See https://learn.microsoft.com/en-us/windows/console/writeconsoleoutput
  516. [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutputW", SetLastError = true, CharSet = CharSet.Unicode)]
  517. static extern bool WriteConsoleOutput (
  518. IntPtr hConsoleOutput,
  519. CharInfo [] lpBuffer,
  520. Coord dwBufferSize,
  521. Coord dwBufferCoord,
  522. ref SmallRect lpWriteRegion
  523. );
  524. [DllImport ("kernel32.dll", EntryPoint = "WriteConsole", SetLastError = true, CharSet = CharSet.Unicode)]
  525. static extern bool WriteConsole (
  526. IntPtr hConsoleOutput,
  527. String lpbufer,
  528. UInt32 NumberOfCharsToWriten,
  529. out UInt32 lpNumberOfCharsWritten,
  530. object lpReserved
  531. );
  532. [DllImport ("kernel32.dll")]
  533. static extern bool SetConsoleCursorPosition (IntPtr hConsoleOutput, Coord dwCursorPosition);
  534. [StructLayout (LayoutKind.Sequential)]
  535. public struct ConsoleCursorInfo {
  536. public uint dwSize;
  537. public bool bVisible;
  538. }
  539. [DllImport ("kernel32.dll", SetLastError = true)]
  540. static extern bool SetConsoleCursorInfo (IntPtr hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
  541. [DllImport ("kernel32.dll", SetLastError = true)]
  542. static extern bool GetConsoleCursorInfo (IntPtr hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
  543. [DllImport ("kernel32.dll")]
  544. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  545. [DllImport ("kernel32.dll")]
  546. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  547. [DllImport ("kernel32.dll", SetLastError = true)]
  548. static extern IntPtr CreateConsoleScreenBuffer (
  549. DesiredAccess dwDesiredAccess,
  550. ShareMode dwShareMode,
  551. IntPtr secutiryAttributes,
  552. uint flags,
  553. IntPtr screenBufferData
  554. );
  555. internal static IntPtr INVALID_HANDLE_VALUE = new IntPtr (-1);
  556. [DllImport ("kernel32.dll", SetLastError = true)]
  557. static extern bool SetConsoleActiveScreenBuffer (IntPtr Handle);
  558. [DllImport ("kernel32.dll", SetLastError = true)]
  559. static extern bool GetNumberOfConsoleInputEvents (IntPtr handle, out uint lpcNumberOfEvents);
  560. public InputRecord [] ReadConsoleInput ()
  561. {
  562. const int bufferSize = 1;
  563. var pRecord = Marshal.AllocHGlobal (Marshal.SizeOf<InputRecord> () * bufferSize);
  564. try {
  565. ReadConsoleInput (_inputHandle, pRecord, bufferSize,
  566. out var numberEventsRead);
  567. return numberEventsRead == 0
  568. ? null
  569. : new [] { Marshal.PtrToStructure<InputRecord> (pRecord) };
  570. } catch (Exception) {
  571. return null;
  572. } finally {
  573. Marshal.FreeHGlobal (pRecord);
  574. }
  575. }
  576. #if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
  577. [DllImport ("kernel32.dll", ExactSpelling = true)]
  578. static extern IntPtr GetConsoleWindow ();
  579. [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  580. static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
  581. public const int HIDE = 0;
  582. public const int MAXIMIZE = 3;
  583. public const int MINIMIZE = 6;
  584. public const int RESTORE = 9;
  585. internal void ShowWindow (int state)
  586. {
  587. IntPtr thisConsole = GetConsoleWindow ();
  588. ShowWindow (thisConsole, state);
  589. }
  590. #endif
  591. // See: https://github.com/gui-cs/Terminal.Gui/issues/357
  592. [StructLayout (LayoutKind.Sequential)]
  593. public struct CONSOLE_SCREEN_BUFFER_INFOEX {
  594. public uint cbSize;
  595. public Coord dwSize;
  596. public Coord dwCursorPosition;
  597. public ushort wAttributes;
  598. public SmallRect srWindow;
  599. public Coord dwMaximumWindowSize;
  600. public ushort wPopupAttributes;
  601. public bool bFullscreenSupported;
  602. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)]
  603. public COLORREF [] ColorTable;
  604. }
  605. [StructLayout (LayoutKind.Explicit, Size = 4)]
  606. public struct COLORREF {
  607. public COLORREF (byte r, byte g, byte b)
  608. {
  609. Value = 0;
  610. R = r;
  611. G = g;
  612. B = b;
  613. }
  614. public COLORREF (uint value)
  615. {
  616. R = 0;
  617. G = 0;
  618. B = 0;
  619. Value = value & 0x00FFFFFF;
  620. }
  621. [FieldOffset (0)]
  622. public byte R;
  623. [FieldOffset (1)]
  624. public byte G;
  625. [FieldOffset (2)]
  626. public byte B;
  627. [FieldOffset (0)]
  628. public uint Value;
  629. }
  630. [DllImport ("kernel32.dll", SetLastError = true)]
  631. static extern bool GetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  632. [DllImport ("kernel32.dll", SetLastError = true)]
  633. static extern bool SetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo);
  634. [DllImport ("kernel32.dll", SetLastError = true)]
  635. static extern bool SetConsoleWindowInfo (
  636. IntPtr hConsoleOutput,
  637. bool bAbsolute,
  638. [In] ref SmallRect lpConsoleWindow);
  639. [DllImport ("kernel32.dll", SetLastError = true)]
  640. static extern Coord GetLargestConsoleWindowSize (
  641. IntPtr hConsoleOutput);
  642. }
  643. internal class WindowsDriver : ConsoleDriver {
  644. WindowsConsole.ExtendedCharInfo [] _outputBuffer;
  645. WindowsConsole.SmallRect _damageRegion;
  646. Action<KeyEvent> _keyHandler;
  647. Action<KeyEvent> _keyDownHandler;
  648. Action<KeyEvent> _keyUpHandler;
  649. Action<MouseEvent> _mouseHandler;
  650. public WindowsConsole WinConsole { get; private set; }
  651. public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931
  652. && (_isWindowsTerminal || _parentProcessName == "devenv"));
  653. readonly bool _isWindowsTerminal = false;
  654. readonly string _parentProcessName = "WindowsTerminal";
  655. public WindowsDriver ()
  656. {
  657. if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
  658. WinConsole = new WindowsConsole ();
  659. // otherwise we're probably running in unit tests
  660. Clipboard = new WindowsClipboard ();
  661. } else {
  662. Clipboard = new FakeDriver.FakeClipboard ();
  663. }
  664. if (!RunningUnitTests) {
  665. _parentProcessName = GetParentProcessName ();
  666. _isWindowsTerminal = _parentProcessName == "WindowsTerminal";
  667. if (!_isWindowsTerminal && _parentProcessName != "devenv") {
  668. Force16Colors = true;
  669. }
  670. }
  671. }
  672. private static string GetParentProcessName ()
  673. {
  674. #pragma warning disable CA1416 // Validate platform compatibility
  675. var myId = Process.GetCurrentProcess ().Id;
  676. var query = string.Format ($"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {myId}");
  677. var search = new ManagementObjectSearcher ("root\\CIMV2", query);
  678. var queryObj = search.Get ().OfType<ManagementBaseObject> ().FirstOrDefault ();
  679. if (queryObj == null) {
  680. return null;
  681. }
  682. var parentId = (uint)queryObj ["ParentProcessId"];
  683. var parent = Process.GetProcessById ((int)parentId);
  684. var prevParent = parent;
  685. // Check if the parent is from other parent
  686. while (queryObj != null) {
  687. query = string.Format ($"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {parentId}");
  688. search = new ManagementObjectSearcher ("root\\CIMV2", query);
  689. queryObj = search.Get ().OfType<ManagementBaseObject> ().FirstOrDefault ();
  690. if (queryObj == null) {
  691. return parent.ProcessName;
  692. }
  693. parentId = (uint)queryObj ["ParentProcessId"];
  694. try {
  695. parent = Process.GetProcessById ((int)parentId);
  696. if (string.Equals (parent.ProcessName, "explorer", StringComparison.InvariantCultureIgnoreCase)) {
  697. return prevParent.ProcessName;
  698. }
  699. prevParent = parent;
  700. } catch (ArgumentException) {
  701. return prevParent.ProcessName;
  702. }
  703. }
  704. return parent.ProcessName;
  705. #pragma warning restore CA1416 // Validate platform compatibility
  706. }
  707. WindowsMainLoop _mainLoop;
  708. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  709. {
  710. _keyHandler = keyHandler;
  711. _keyDownHandler = keyDownHandler;
  712. _keyUpHandler = keyUpHandler;
  713. _mouseHandler = mouseHandler;
  714. _mainLoop = mainLoop.MainLoopDriver as WindowsMainLoop;
  715. _mainLoop.ProcessInput += ProcessInput;
  716. _mainLoop.WinChanged += ChangeWin;
  717. }
  718. private void ChangeWin (Object s, SizeChangedEventArgs e)
  719. {
  720. var w = e.Size.Width;
  721. if (w == Cols - 3 && e.Size.Height < Rows) {
  722. w += 3;
  723. }
  724. Left = 0;
  725. Top = 0;
  726. Cols = e.Size.Width;
  727. Rows = e.Size.Height;
  728. if (!RunningUnitTests) {
  729. var newSize = WinConsole.SetConsoleWindow (
  730. (short)Math.Max (w, 16), (short)Math.Max (e.Size.Height, 0));
  731. Cols = newSize.Width;
  732. Rows = newSize.Height;
  733. }
  734. ResizeScreen ();
  735. ClearContents ();
  736. TerminalResized.Invoke ();
  737. }
  738. void ProcessInput (WindowsConsole.InputRecord inputEvent)
  739. {
  740. switch (inputEvent.EventType) {
  741. case WindowsConsole.EventType.Key:
  742. var fromPacketKey = inputEvent.KeyEvent.wVirtualKeyCode == (uint)ConsoleKey.Packet;
  743. if (fromPacketKey) {
  744. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  745. }
  746. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  747. //var ke = inputEvent.KeyEvent;
  748. //System.Diagnostics.Debug.WriteLine ($"fromPacketKey: {fromPacketKey}");
  749. //if (ke.UnicodeChar == '\0') {
  750. // System.Diagnostics.Debug.WriteLine ("UnicodeChar: 0'\\0'");
  751. //} else if (ke.UnicodeChar == 13) {
  752. // System.Diagnostics.Debug.WriteLine ("UnicodeChar: 13'\\n'");
  753. //} else {
  754. // System.Diagnostics.Debug.WriteLine ($"UnicodeChar: {(uint)ke.UnicodeChar}'{ke.UnicodeChar}'");
  755. //}
  756. //System.Diagnostics.Debug.WriteLine ($"bKeyDown: {ke.bKeyDown}");
  757. //System.Diagnostics.Debug.WriteLine ($"dwControlKeyState: {ke.dwControlKeyState}");
  758. //System.Diagnostics.Debug.WriteLine ($"wRepeatCount: {ke.wRepeatCount}");
  759. //System.Diagnostics.Debug.WriteLine ($"wVirtualKeyCode: {ke.wVirtualKeyCode}");
  760. //System.Diagnostics.Debug.WriteLine ($"wVirtualScanCode: {ke.wVirtualScanCode}");
  761. if (map == (Key)0xffffffff) {
  762. KeyEvent key = new KeyEvent ();
  763. // Shift = VK_SHIFT = 0x10
  764. // Ctrl = VK_CONTROL = 0x11
  765. // Alt = VK_MENU = 0x12
  766. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
  767. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
  768. }
  769. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
  770. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
  771. }
  772. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
  773. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
  774. }
  775. switch (inputEvent.KeyEvent.dwControlKeyState) {
  776. case WindowsConsole.ControlKeyState.RightAltPressed:
  777. case WindowsConsole.ControlKeyState.RightAltPressed |
  778. WindowsConsole.ControlKeyState.LeftControlPressed |
  779. WindowsConsole.ControlKeyState.EnhancedKey:
  780. case WindowsConsole.ControlKeyState.EnhancedKey:
  781. key = new KeyEvent (Key.CtrlMask | Key.AltMask, _keyModifiers);
  782. break;
  783. case WindowsConsole.ControlKeyState.LeftAltPressed:
  784. key = new KeyEvent (Key.AltMask, _keyModifiers);
  785. break;
  786. case WindowsConsole.ControlKeyState.RightControlPressed:
  787. case WindowsConsole.ControlKeyState.LeftControlPressed:
  788. key = new KeyEvent (Key.CtrlMask, _keyModifiers);
  789. break;
  790. case WindowsConsole.ControlKeyState.ShiftPressed:
  791. key = new KeyEvent (Key.ShiftMask, _keyModifiers);
  792. break;
  793. case WindowsConsole.ControlKeyState.NumlockOn:
  794. break;
  795. case WindowsConsole.ControlKeyState.ScrolllockOn:
  796. break;
  797. case WindowsConsole.ControlKeyState.CapslockOn:
  798. break;
  799. default:
  800. key = inputEvent.KeyEvent.wVirtualKeyCode switch {
  801. 0x10 => new KeyEvent (Key.ShiftMask, _keyModifiers),
  802. 0x11 => new KeyEvent (Key.CtrlMask, _keyModifiers),
  803. 0x12 => new KeyEvent (Key.AltMask, _keyModifiers),
  804. _ => new KeyEvent (Key.Unknown, _keyModifiers)
  805. };
  806. break;
  807. }
  808. if (inputEvent.KeyEvent.bKeyDown) {
  809. _keyDownHandler (key);
  810. } else {
  811. _keyUpHandler (key);
  812. }
  813. } else {
  814. if (inputEvent.KeyEvent.bKeyDown) {
  815. // May occurs using SendKeys
  816. _keyModifiers ??= new KeyModifiers ();
  817. // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
  818. _keyDownHandler (new KeyEvent (map, _keyModifiers));
  819. _keyHandler (new KeyEvent (map, _keyModifiers));
  820. } else {
  821. _keyUpHandler (new KeyEvent (map, _keyModifiers));
  822. }
  823. }
  824. if (!inputEvent.KeyEvent.bKeyDown && inputEvent.KeyEvent.dwControlKeyState == 0) {
  825. _keyModifiers = null;
  826. }
  827. break;
  828. case WindowsConsole.EventType.Mouse:
  829. var me = ToDriverMouse (inputEvent.MouseEvent);
  830. _mouseHandler (me);
  831. if (_processButtonClick) {
  832. _mouseHandler (
  833. new MouseEvent () {
  834. X = me.X,
  835. Y = me.Y,
  836. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  837. });
  838. }
  839. break;
  840. case WindowsConsole.EventType.Focus:
  841. break;
  842. }
  843. }
  844. WindowsConsole.ButtonState? _lastMouseButtonPressed = null;
  845. bool _isButtonPressed = false;
  846. bool _isButtonReleased = false;
  847. bool _isButtonDoubleClicked = false;
  848. Point? _point;
  849. Point _pointMove;
  850. bool _isOneFingerDoubleClicked = false;
  851. bool _processButtonClick;
  852. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  853. {
  854. MouseFlags mouseFlag = MouseFlags.AllEvents;
  855. //System.Diagnostics.Debug.WriteLine (
  856. // $"X:{mouseEvent.MousePosition.X};Y:{mouseEvent.MousePosition.Y};ButtonState:{mouseEvent.ButtonState};EventFlags:{mouseEvent.EventFlags}");
  857. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked) {
  858. Application.MainLoop.AddIdle (() => {
  859. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  860. return false;
  861. });
  862. }
  863. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  864. // This will tell when a mouse button is pressed. When the button is released this event will
  865. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  866. // To map to the correct driver events we save the last pressed mouse button so we can
  867. // map to the correct clicked event.
  868. if ((_lastMouseButtonPressed != null || _isButtonReleased) && mouseEvent.ButtonState != 0) {
  869. _lastMouseButtonPressed = null;
  870. //isButtonPressed = false;
  871. _isButtonReleased = false;
  872. }
  873. var p = new Point () {
  874. X = mouseEvent.MousePosition.X,
  875. Y = mouseEvent.MousePosition.Y
  876. };
  877. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed == null && !_isButtonDoubleClicked) ||
  878. (_lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) &&
  879. mouseEvent.ButtonState != 0 && !_isButtonReleased && !_isButtonDoubleClicked)) {
  880. switch (mouseEvent.ButtonState) {
  881. case WindowsConsole.ButtonState.Button1Pressed:
  882. mouseFlag = MouseFlags.Button1Pressed;
  883. break;
  884. case WindowsConsole.ButtonState.Button2Pressed:
  885. mouseFlag = MouseFlags.Button2Pressed;
  886. break;
  887. case WindowsConsole.ButtonState.RightmostButtonPressed:
  888. mouseFlag = MouseFlags.Button3Pressed;
  889. break;
  890. }
  891. if (_point == null) {
  892. _point = p;
  893. }
  894. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  895. mouseFlag |= MouseFlags.ReportMousePosition;
  896. _isButtonReleased = false;
  897. _processButtonClick = false;
  898. }
  899. _lastMouseButtonPressed = mouseEvent.ButtonState;
  900. _isButtonPressed = true;
  901. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  902. Application.MainLoop.AddIdle (() => {
  903. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  904. return false;
  905. });
  906. }
  907. } else if (_lastMouseButtonPressed != null && mouseEvent.EventFlags == 0
  908. && !_isButtonReleased && !_isButtonDoubleClicked && !_isOneFingerDoubleClicked) {
  909. switch (_lastMouseButtonPressed) {
  910. case WindowsConsole.ButtonState.Button1Pressed:
  911. mouseFlag = MouseFlags.Button1Released;
  912. break;
  913. case WindowsConsole.ButtonState.Button2Pressed:
  914. mouseFlag = MouseFlags.Button2Released;
  915. break;
  916. case WindowsConsole.ButtonState.RightmostButtonPressed:
  917. mouseFlag = MouseFlags.Button3Released;
  918. break;
  919. }
  920. _isButtonPressed = false;
  921. _isButtonReleased = true;
  922. if (_point != null && (((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)) {
  923. _processButtonClick = true;
  924. } else {
  925. _point = null;
  926. }
  927. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  928. && !_isOneFingerDoubleClicked && _isButtonReleased && p == _point) {
  929. mouseFlag = ProcessButtonClick (mouseEvent);
  930. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  931. switch (mouseEvent.ButtonState) {
  932. case WindowsConsole.ButtonState.Button1Pressed:
  933. mouseFlag = MouseFlags.Button1DoubleClicked;
  934. break;
  935. case WindowsConsole.ButtonState.Button2Pressed:
  936. mouseFlag = MouseFlags.Button2DoubleClicked;
  937. break;
  938. case WindowsConsole.ButtonState.RightmostButtonPressed:
  939. mouseFlag = MouseFlags.Button3DoubleClicked;
  940. break;
  941. }
  942. _isButtonDoubleClicked = true;
  943. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked) {
  944. switch (mouseEvent.ButtonState) {
  945. case WindowsConsole.ButtonState.Button1Pressed:
  946. mouseFlag = MouseFlags.Button1TripleClicked;
  947. break;
  948. case WindowsConsole.ButtonState.Button2Pressed:
  949. mouseFlag = MouseFlags.Button2TripleClicked;
  950. break;
  951. case WindowsConsole.ButtonState.RightmostButtonPressed:
  952. mouseFlag = MouseFlags.Button3TripleClicked;
  953. break;
  954. }
  955. _isButtonDoubleClicked = false;
  956. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  957. switch ((int)mouseEvent.ButtonState) {
  958. case int v when v > 0:
  959. mouseFlag = MouseFlags.WheeledUp;
  960. break;
  961. case int v when v < 0:
  962. mouseFlag = MouseFlags.WheeledDown;
  963. break;
  964. }
  965. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  966. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  967. switch ((int)mouseEvent.ButtonState) {
  968. case int v when v > 0:
  969. mouseFlag = MouseFlags.WheeledLeft;
  970. break;
  971. case int v when v < 0:
  972. mouseFlag = MouseFlags.WheeledRight;
  973. break;
  974. }
  975. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled) {
  976. switch ((int)mouseEvent.ButtonState) {
  977. case int v when v < 0:
  978. mouseFlag = MouseFlags.WheeledLeft;
  979. break;
  980. case int v when v > 0:
  981. mouseFlag = MouseFlags.WheeledRight;
  982. break;
  983. }
  984. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  985. mouseFlag = MouseFlags.ReportMousePosition;
  986. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y) {
  987. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  988. }
  989. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  990. mouseFlag = 0;
  991. }
  992. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  993. //System.Diagnostics.Debug.WriteLine (
  994. // $"point.X:{(point != null ? ((Point)point).X : -1)};point.Y:{(point != null ? ((Point)point).Y : -1)}");
  995. return new MouseEvent () {
  996. X = mouseEvent.MousePosition.X,
  997. Y = mouseEvent.MousePosition.Y,
  998. Flags = mouseFlag
  999. };
  1000. }
  1001. MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  1002. {
  1003. MouseFlags mouseFlag = 0;
  1004. switch (_lastMouseButtonPressed) {
  1005. case WindowsConsole.ButtonState.Button1Pressed:
  1006. mouseFlag = MouseFlags.Button1Clicked;
  1007. break;
  1008. case WindowsConsole.ButtonState.Button2Pressed:
  1009. mouseFlag = MouseFlags.Button2Clicked;
  1010. break;
  1011. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1012. mouseFlag = MouseFlags.Button3Clicked;
  1013. break;
  1014. }
  1015. _point = new Point () {
  1016. X = mouseEvent.MousePosition.X,
  1017. Y = mouseEvent.MousePosition.Y
  1018. };
  1019. _lastMouseButtonPressed = null;
  1020. _isButtonReleased = false;
  1021. _processButtonClick = false;
  1022. _point = null;
  1023. return mouseFlag;
  1024. }
  1025. async Task ProcessButtonDoubleClickedAsync ()
  1026. {
  1027. await Task.Delay (300);
  1028. _isButtonDoubleClicked = false;
  1029. _isOneFingerDoubleClicked = false;
  1030. //buttonPressedCount = 0;
  1031. }
  1032. async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1033. {
  1034. while (_isButtonPressed) {
  1035. await Task.Delay (100);
  1036. var me = new MouseEvent () {
  1037. X = _pointMove.X,
  1038. Y = _pointMove.Y,
  1039. Flags = mouseFlag
  1040. };
  1041. var view = Application.WantContinuousButtonPressedView;
  1042. if (view == null) {
  1043. break;
  1044. }
  1045. if (_isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1046. Application.MainLoop.Invoke (() => _mouseHandler (me));
  1047. }
  1048. }
  1049. }
  1050. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1051. {
  1052. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  1053. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)) {
  1054. mouseFlag |= MouseFlags.ButtonCtrl;
  1055. }
  1056. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1057. mouseFlag |= MouseFlags.ButtonShift;
  1058. }
  1059. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1060. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1061. mouseFlag |= MouseFlags.ButtonAlt;
  1062. }
  1063. return mouseFlag;
  1064. }
  1065. KeyModifiers _keyModifiers;
  1066. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1067. {
  1068. var state = keyEvent.dwControlKeyState;
  1069. var shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1070. var alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1071. var control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1072. var capsLock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  1073. var numLock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  1074. var scrollLock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  1075. _keyModifiers ??= new KeyModifiers ();
  1076. if (shift) {
  1077. _keyModifiers.Shift = true;
  1078. }
  1079. if (alt) {
  1080. _keyModifiers.Alt = true;
  1081. }
  1082. if (control) {
  1083. _keyModifiers.Ctrl = true;
  1084. }
  1085. if (capsLock) {
  1086. _keyModifiers.Capslock = true;
  1087. }
  1088. if (numLock) {
  1089. _keyModifiers.Numlock = true;
  1090. }
  1091. if (scrollLock) {
  1092. _keyModifiers.Scrolllock = true;
  1093. }
  1094. var consoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1095. return new WindowsConsole.ConsoleKeyInfoEx (consoleKeyInfo, capsLock, numLock, scrollLock);
  1096. }
  1097. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  1098. {
  1099. if (keyEvent.wVirtualKeyCode != (uint)ConsoleKey.Packet) {
  1100. return keyEvent;
  1101. }
  1102. var mod = new ConsoleModifiers ();
  1103. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1104. mod |= ConsoleModifiers.Shift;
  1105. }
  1106. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1107. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1108. mod |= ConsoleModifiers.Alt;
  1109. }
  1110. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed) ||
  1111. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)) {
  1112. mod |= ConsoleModifiers.Control;
  1113. }
  1114. var keyChar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyEvent.UnicodeChar, mod, out uint virtualKey, out uint scanCode);
  1115. return new WindowsConsole.KeyEventRecord {
  1116. UnicodeChar = (char)keyChar,
  1117. bKeyDown = keyEvent.bKeyDown,
  1118. dwControlKeyState = keyEvent.dwControlKeyState,
  1119. wRepeatCount = keyEvent.wRepeatCount,
  1120. wVirtualKeyCode = (ushort)virtualKey,
  1121. wVirtualScanCode = (ushort)scanCode
  1122. };
  1123. }
  1124. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  1125. {
  1126. var keyInfo = keyInfoEx.ConsoleKeyInfo;
  1127. switch (keyInfo.Key) {
  1128. case ConsoleKey.Escape:
  1129. return MapKeyModifiers (keyInfo, Key.Esc);
  1130. case ConsoleKey.Tab:
  1131. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  1132. case ConsoleKey.Clear:
  1133. return MapKeyModifiers (keyInfo, Key.Clear);
  1134. case ConsoleKey.Home:
  1135. return MapKeyModifiers (keyInfo, Key.Home);
  1136. case ConsoleKey.End:
  1137. return MapKeyModifiers (keyInfo, Key.End);
  1138. case ConsoleKey.LeftArrow:
  1139. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  1140. case ConsoleKey.RightArrow:
  1141. return MapKeyModifiers (keyInfo, Key.CursorRight);
  1142. case ConsoleKey.UpArrow:
  1143. return MapKeyModifiers (keyInfo, Key.CursorUp);
  1144. case ConsoleKey.DownArrow:
  1145. return MapKeyModifiers (keyInfo, Key.CursorDown);
  1146. case ConsoleKey.PageUp:
  1147. return MapKeyModifiers (keyInfo, Key.PageUp);
  1148. case ConsoleKey.PageDown:
  1149. return MapKeyModifiers (keyInfo, Key.PageDown);
  1150. case ConsoleKey.Enter:
  1151. return MapKeyModifiers (keyInfo, Key.Enter);
  1152. case ConsoleKey.Spacebar:
  1153. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  1154. case ConsoleKey.Backspace:
  1155. return MapKeyModifiers (keyInfo, Key.Backspace);
  1156. case ConsoleKey.Delete:
  1157. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  1158. case ConsoleKey.Insert:
  1159. return MapKeyModifiers (keyInfo, Key.InsertChar);
  1160. case ConsoleKey.PrintScreen:
  1161. return MapKeyModifiers (keyInfo, Key.PrintScreen);
  1162. case ConsoleKey.NumPad0:
  1163. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  1164. case ConsoleKey.NumPad1:
  1165. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  1166. case ConsoleKey.NumPad2:
  1167. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  1168. case ConsoleKey.NumPad3:
  1169. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  1170. case ConsoleKey.NumPad4:
  1171. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  1172. case ConsoleKey.NumPad5:
  1173. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  1174. case ConsoleKey.NumPad6:
  1175. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  1176. case ConsoleKey.NumPad7:
  1177. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  1178. case ConsoleKey.NumPad8:
  1179. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  1180. case ConsoleKey.NumPad9:
  1181. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  1182. case ConsoleKey.Oem1:
  1183. case ConsoleKey.Oem2:
  1184. case ConsoleKey.Oem3:
  1185. case ConsoleKey.Oem4:
  1186. case ConsoleKey.Oem5:
  1187. case ConsoleKey.Oem6:
  1188. case ConsoleKey.Oem7:
  1189. case ConsoleKey.Oem8:
  1190. case ConsoleKey.Oem102:
  1191. case ConsoleKey.OemPeriod:
  1192. case ConsoleKey.OemComma:
  1193. case ConsoleKey.OemPlus:
  1194. case ConsoleKey.OemMinus:
  1195. if (keyInfo.KeyChar == 0) {
  1196. return Key.Unknown;
  1197. }
  1198. return (Key)((uint)keyInfo.KeyChar);
  1199. }
  1200. var key = keyInfo.Key;
  1201. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  1202. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  1203. var delta = key - ConsoleKey.A;
  1204. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1205. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1206. }
  1207. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1208. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1209. }
  1210. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1211. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1212. }
  1213. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1214. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1215. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1216. }
  1217. }
  1218. //return (Key)((uint)alphaBase + delta);
  1219. return (Key)((uint)keyInfo.KeyChar);
  1220. }
  1221. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1222. var delta = key - ConsoleKey.D0;
  1223. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1224. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1225. }
  1226. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1227. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1228. }
  1229. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1230. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1231. }
  1232. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1233. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30 || keyInfo.KeyChar == ((uint)Key.D0 + delta)) {
  1234. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1235. }
  1236. }
  1237. return (Key)((uint)keyInfo.KeyChar);
  1238. }
  1239. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1240. var delta = key - ConsoleKey.F1;
  1241. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1242. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1243. }
  1244. return (Key)((uint)Key.F1 + delta);
  1245. }
  1246. if (keyInfo.KeyChar != 0) {
  1247. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1248. }
  1249. return (Key)(0xffffffff);
  1250. }
  1251. private Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1252. {
  1253. Key keyMod = new Key ();
  1254. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0) {
  1255. keyMod = Key.ShiftMask;
  1256. }
  1257. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) {
  1258. keyMod |= Key.CtrlMask;
  1259. }
  1260. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0) {
  1261. keyMod |= Key.AltMask;
  1262. }
  1263. return keyMod != Key.Null ? keyMod | key : key;
  1264. }
  1265. public override bool IsRuneSupported (Rune rune)
  1266. {
  1267. return base.IsRuneSupported (rune) && rune.IsBmp;
  1268. }
  1269. public override void Init (Action terminalResized)
  1270. {
  1271. TerminalResized = terminalResized;
  1272. if (RunningUnitTests) {
  1273. return;
  1274. }
  1275. try {
  1276. if (WinConsole != null) {
  1277. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1278. Cols = winSize.Width;
  1279. Rows = winSize.Height;
  1280. }
  1281. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1282. // Needed for Windows Terminal
  1283. // ESC [ ? 1047 h Save cursor position and activate xterm alternative buffer (no backscroll)
  1284. // ESC [ ? 1047 l Restore cursor position and restore xterm working buffer (with backscroll)
  1285. // ESC [ ? 1048 h Save cursor position
  1286. // ESC [ ? 1048 l Restore cursor position
  1287. // ESC [ ? 1049 h Activate xterm alternative buffer (no backscroll)
  1288. // ESC [ ? 1049 l Restore xterm working buffer (with backscroll)
  1289. // Per Issue #2264 using the alternative screen buffer is required for Windows Terminal to not
  1290. // wipe out the backscroll buffer when the application exits.
  1291. if (_isWindowsTerminal) {
  1292. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  1293. }
  1294. } catch (Win32Exception e) {
  1295. // We are being run in an environment that does not support a console
  1296. // such as a unit test, or a pipe.
  1297. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  1298. WinConsole = null;
  1299. }
  1300. CurrentAttribute = MakeColor (Color.White, Color.Black);
  1301. InitializeColorSchemes ();
  1302. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1303. Clip = new Rect (0, 0, Cols, Rows);
  1304. _damageRegion = new WindowsConsole.SmallRect () {
  1305. Top = 0,
  1306. Left = 0,
  1307. Bottom = (short)Rows,
  1308. Right = (short)Cols
  1309. };
  1310. ClearContents ();
  1311. }
  1312. void ResizeScreen ()
  1313. {
  1314. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1315. Clip = new Rect (0, 0, Cols, Rows);
  1316. _damageRegion = new WindowsConsole.SmallRect () {
  1317. Top = 0,
  1318. Left = 0,
  1319. Bottom = (short)Rows,
  1320. Right = (short)Cols
  1321. };
  1322. _dirtyLines = new bool [Rows];
  1323. WinConsole?.ForceRefreshCursorVisibility ();
  1324. }
  1325. public override void UpdateScreen ()
  1326. {
  1327. var windowSize = WinConsole?.GetConsoleBufferWindow (out _) ?? new Size (Cols, Rows);
  1328. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows)) {
  1329. return;
  1330. }
  1331. var bufferCoords = new WindowsConsole.Coord () {
  1332. X = (short)Clip.Width,
  1333. Y = (short)Clip.Height
  1334. };
  1335. for (int row = 0; row < Rows; row++) {
  1336. if (!_dirtyLines [row]) {
  1337. continue;
  1338. }
  1339. _dirtyLines [row] = false;
  1340. for (int col = 0; col < Cols; col++) {
  1341. int position = row * Cols + col;
  1342. _outputBuffer [position].Attribute = Contents [row, col].Attribute.GetValueOrDefault ();
  1343. if (Contents [row, col].IsDirty == false) {
  1344. _outputBuffer [position].Empty = true;
  1345. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1346. continue;
  1347. }
  1348. _outputBuffer [position].Empty = false;
  1349. if (Contents [row, col].Runes [0].IsBmp) {
  1350. _outputBuffer [position].Char = (char)Contents [row, col].Runes [0].Value;
  1351. } else {
  1352. //_outputBuffer [position].Empty = true;
  1353. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1354. if (Contents [row, col].Runes [0].GetColumns () > 1 && col + 1 < Cols) {
  1355. // TODO: This is a hack to deal with non-BMP and wide characters.
  1356. col++;
  1357. position = row * Cols + col;
  1358. _outputBuffer [position].Empty = false;
  1359. _outputBuffer [position].Char = ' ';
  1360. }
  1361. }
  1362. }
  1363. }
  1364. _damageRegion = new WindowsConsole.SmallRect () {
  1365. Top = 0,
  1366. Left = 0,
  1367. Bottom = (short)Rows,
  1368. Right = (short)Cols
  1369. };
  1370. if (!RunningUnitTests && WinConsole != null && !WinConsole.WriteToConsole (new Size (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors)) {
  1371. var err = Marshal.GetLastWin32Error ();
  1372. if (err != 0) {
  1373. throw new System.ComponentModel.Win32Exception (err);
  1374. }
  1375. }
  1376. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1377. }
  1378. public override void Refresh ()
  1379. {
  1380. UpdateScreen ();
  1381. WinConsole?.SetInitialCursorVisibility ();
  1382. UpdateCursor ();
  1383. }
  1384. #region Color Handling
  1385. /// <summary>
  1386. /// In the WindowsDriver, colors are encoded as an int.
  1387. /// The background color is stored in the least significant 4 bits,
  1388. /// and the foreground color is stored in the next 4 bits.
  1389. /// </summary>
  1390. public override Attribute MakeColor (Color foreground, Color background)
  1391. {
  1392. // Encode the colors into the int value.
  1393. return new Attribute (
  1394. value: (((int)foreground) | ((int)background << 4)),
  1395. foreground: foreground,
  1396. background: background
  1397. );
  1398. }
  1399. /// <summary>
  1400. /// Extracts the foreground and background colors from the encoded value.
  1401. /// Assumes a 4-bit encoded value for both foreground and background colors.
  1402. /// </summary>
  1403. internal override void GetColors (int value, out Color foreground, out Color background)
  1404. {
  1405. // Assume a 4-bit encoded value for both foreground and background colors.
  1406. foreground = (Color)((value >> 16) & 0xF);
  1407. background = (Color)(value & 0xF);
  1408. }
  1409. #endregion
  1410. CursorVisibility _cachedCursorVisibility;
  1411. public override void UpdateCursor ()
  1412. {
  1413. if (Col < 0 || Row < 0 || Col > Cols || Row > Rows) {
  1414. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1415. _cachedCursorVisibility = cursorVisibility;
  1416. SetCursorVisibility (CursorVisibility.Invisible);
  1417. return;
  1418. }
  1419. SetCursorVisibility (_cachedCursorVisibility);
  1420. var position = new WindowsConsole.Coord () {
  1421. X = (short)Col,
  1422. Y = (short)Row
  1423. };
  1424. WinConsole?.SetCursorPosition (position);
  1425. }
  1426. /// <inheritdoc/>
  1427. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1428. {
  1429. if (WinConsole != null) {
  1430. return WinConsole.GetCursorVisibility (out visibility);
  1431. }
  1432. visibility = _cachedCursorVisibility;
  1433. return true;
  1434. }
  1435. /// <inheritdoc/>
  1436. public override bool SetCursorVisibility (CursorVisibility visibility)
  1437. {
  1438. _cachedCursorVisibility = visibility;
  1439. return WinConsole == null || WinConsole.SetCursorVisibility (visibility);
  1440. }
  1441. /// <inheritdoc/>
  1442. public override bool EnsureCursorVisibility ()
  1443. {
  1444. return WinConsole == null || WinConsole.EnsureCursorVisibility ();
  1445. }
  1446. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1447. {
  1448. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1449. EventType = WindowsConsole.EventType.Key
  1450. };
  1451. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1452. bKeyDown = true
  1453. };
  1454. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1455. if (shift) {
  1456. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1457. keyEvent.UnicodeChar = '\0';
  1458. keyEvent.wVirtualKeyCode = 16;
  1459. }
  1460. if (alt) {
  1461. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1462. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1463. keyEvent.UnicodeChar = '\0';
  1464. keyEvent.wVirtualKeyCode = 18;
  1465. }
  1466. if (control) {
  1467. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1468. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1469. keyEvent.UnicodeChar = '\0';
  1470. keyEvent.wVirtualKeyCode = 17;
  1471. }
  1472. keyEvent.dwControlKeyState = controlKey;
  1473. input.KeyEvent = keyEvent;
  1474. if (shift || alt || control) {
  1475. ProcessInput (input);
  1476. }
  1477. keyEvent.UnicodeChar = keyChar;
  1478. if ((uint)key < 255) {
  1479. keyEvent.wVirtualKeyCode = (ushort)key;
  1480. } else {
  1481. keyEvent.wVirtualKeyCode = '\0';
  1482. }
  1483. input.KeyEvent = keyEvent;
  1484. try {
  1485. ProcessInput (input);
  1486. } catch (OverflowException) { } finally {
  1487. keyEvent.bKeyDown = false;
  1488. input.KeyEvent = keyEvent;
  1489. ProcessInput (input);
  1490. }
  1491. }
  1492. public override void End ()
  1493. {
  1494. if (_mainLoop != null) {
  1495. _mainLoop.ProcessInput -= ProcessInput;
  1496. _mainLoop.WinChanged -= ChangeWin;
  1497. //_mainLoop.Dispose ();
  1498. }
  1499. _mainLoop = null;
  1500. WinConsole?.Cleanup ();
  1501. WinConsole = null;
  1502. if (!RunningUnitTests && (_isWindowsTerminal || _parentProcessName == "devenv")) {
  1503. // Disable alternative screen buffer.
  1504. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndActivateAltBufferWithBackscroll);
  1505. }
  1506. }
  1507. #region Not Implemented
  1508. public override void Suspend ()
  1509. {
  1510. throw new NotImplementedException ();
  1511. }
  1512. #endregion
  1513. }
  1514. /// <summary>
  1515. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1516. /// only be used on Windows.
  1517. /// </summary>
  1518. /// <remarks>
  1519. /// This implementation is used for WindowsDriver.
  1520. /// </remarks>
  1521. internal class WindowsMainLoop : IMainLoopDriver {
  1522. readonly ManualResetEventSlim _eventReady = new ManualResetEventSlim (false);
  1523. readonly ManualResetEventSlim _waitForProbe = new ManualResetEventSlim (false);
  1524. readonly ManualResetEventSlim _winChange = new ManualResetEventSlim (false);
  1525. MainLoop _mainLoop;
  1526. readonly ConsoleDriver _consoleDriver;
  1527. readonly WindowsConsole _winConsole;
  1528. bool _winChanged;
  1529. Size _windowSize;
  1530. CancellationTokenSource _eventReadyTokenSource = new CancellationTokenSource ();
  1531. // The records that we keep fetching
  1532. readonly Queue<WindowsConsole.InputRecord []> _resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1533. /// <summary>
  1534. /// Invoked when a Key is pressed or released.
  1535. /// </summary>
  1536. public Action<WindowsConsole.InputRecord> ProcessInput;
  1537. /// <summary>
  1538. /// Invoked when the window is changed.
  1539. /// </summary>
  1540. public EventHandler<SizeChangedEventArgs> WinChanged;
  1541. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1542. {
  1543. _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof(consoleDriver));
  1544. _winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1545. }
  1546. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1547. {
  1548. _mainLoop = mainLoop;
  1549. Task.Run (WindowsInputHandler);
  1550. Task.Run (CheckWinChange);
  1551. }
  1552. void WindowsInputHandler ()
  1553. {
  1554. while (_mainLoop != null) {
  1555. _waitForProbe.Wait ();
  1556. _waitForProbe.Reset ();
  1557. if (_resultQueue?.Count == 0) {
  1558. _resultQueue.Enqueue (_winConsole.ReadConsoleInput ());
  1559. }
  1560. _eventReady.Set ();
  1561. }
  1562. }
  1563. void CheckWinChange ()
  1564. {
  1565. while (_mainLoop != null) {
  1566. _winChange.Wait ();
  1567. _winChange.Reset ();
  1568. while (_mainLoop != null) {
  1569. Task.Delay (500).Wait ();
  1570. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  1571. if (_windowSize != Size.Empty && (_windowSize.Width != _consoleDriver.Cols
  1572. || _windowSize.Height != _consoleDriver.Rows)) {
  1573. break;
  1574. }
  1575. }
  1576. _winChanged = true;
  1577. _eventReady.Set ();
  1578. }
  1579. }
  1580. void IMainLoopDriver.Wakeup ()
  1581. {
  1582. //tokenSource.Cancel ();
  1583. _eventReady.Set ();
  1584. }
  1585. bool IMainLoopDriver.EventsPending ()
  1586. {
  1587. _waitForProbe.Set ();
  1588. _winChange.Set ();
  1589. if (_mainLoop.CheckTimersAndIdleHandlers (out var waitTimeout)) {
  1590. return true;
  1591. }
  1592. try {
  1593. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1594. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1595. // are no timers, but there IS an idle handler waiting.
  1596. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1597. }
  1598. } catch (OperationCanceledException) {
  1599. return true;
  1600. } finally {
  1601. _eventReady.Reset ();
  1602. }
  1603. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1604. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  1605. }
  1606. _eventReadyTokenSource.Dispose ();
  1607. _eventReadyTokenSource = new CancellationTokenSource ();
  1608. return true;
  1609. }
  1610. void IMainLoopDriver.Iteration ()
  1611. {
  1612. while (_resultQueue.Count > 0) {
  1613. var inputRecords = _resultQueue.Dequeue ();
  1614. if (inputRecords is { Length: > 0 }) {
  1615. var inputEvent = inputRecords [0];
  1616. ProcessInput?.Invoke (inputEvent);
  1617. }
  1618. }
  1619. if (_winChanged) {
  1620. _winChanged = false;
  1621. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  1622. }
  1623. }
  1624. //public void Dispose ()
  1625. //{
  1626. // _eventReadyTokenSource?.Cancel ();
  1627. // _eventReadyTokenSource?.Dispose ();
  1628. // _eventReady?.Dispose ();
  1629. // _mainLoop = null;
  1630. // _winChange?.Dispose ();
  1631. // _waitForProbe?.Dispose ();
  1632. //}
  1633. }
  1634. class WindowsClipboard : ClipboardBase {
  1635. public WindowsClipboard ()
  1636. {
  1637. IsSupported = IsClipboardFormatAvailable (_cfUnicodeText);
  1638. }
  1639. public override bool IsSupported { get; }
  1640. protected override string GetClipboardDataImpl ()
  1641. {
  1642. try {
  1643. if (!OpenClipboard (IntPtr.Zero)) {
  1644. return string.Empty;
  1645. }
  1646. IntPtr handle = GetClipboardData (_cfUnicodeText);
  1647. if (handle == IntPtr.Zero) {
  1648. return string.Empty;
  1649. }
  1650. IntPtr pointer = IntPtr.Zero;
  1651. try {
  1652. pointer = GlobalLock (handle);
  1653. if (pointer == IntPtr.Zero) {
  1654. return string.Empty;
  1655. }
  1656. int size = GlobalSize (handle);
  1657. byte [] buff = new byte [size];
  1658. Marshal.Copy (pointer, buff, 0, size);
  1659. return System.Text.Encoding.Unicode.GetString (buff).TrimEnd ('\0');
  1660. } finally {
  1661. if (pointer != IntPtr.Zero) {
  1662. GlobalUnlock (handle);
  1663. }
  1664. }
  1665. } finally {
  1666. CloseClipboard ();
  1667. }
  1668. }
  1669. protected override void SetClipboardDataImpl (string text)
  1670. {
  1671. OpenClipboard ();
  1672. EmptyClipboard ();
  1673. IntPtr hGlobal = default;
  1674. try {
  1675. var bytes = (text.Length + 1) * 2;
  1676. hGlobal = Marshal.AllocHGlobal (bytes);
  1677. if (hGlobal == default) {
  1678. ThrowWin32 ();
  1679. }
  1680. var target = GlobalLock (hGlobal);
  1681. if (target == default) {
  1682. ThrowWin32 ();
  1683. }
  1684. try {
  1685. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1686. } finally {
  1687. GlobalUnlock (target);
  1688. }
  1689. if (SetClipboardData (_cfUnicodeText, hGlobal) == default) {
  1690. ThrowWin32 ();
  1691. }
  1692. hGlobal = default;
  1693. } finally {
  1694. if (hGlobal != default) {
  1695. Marshal.FreeHGlobal (hGlobal);
  1696. }
  1697. CloseClipboard ();
  1698. }
  1699. }
  1700. void OpenClipboard ()
  1701. {
  1702. var num = 10;
  1703. while (true) {
  1704. if (OpenClipboard (default)) {
  1705. break;
  1706. }
  1707. if (--num == 0) {
  1708. ThrowWin32 ();
  1709. }
  1710. Thread.Sleep (100);
  1711. }
  1712. }
  1713. const uint _cfUnicodeText = 13;
  1714. void ThrowWin32 ()
  1715. {
  1716. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1717. }
  1718. [DllImport ("User32.dll", SetLastError = true)]
  1719. [return: MarshalAs (UnmanagedType.Bool)]
  1720. static extern bool IsClipboardFormatAvailable (uint format);
  1721. [DllImport ("kernel32.dll", SetLastError = true)]
  1722. static extern int GlobalSize (IntPtr handle);
  1723. [DllImport ("kernel32.dll", SetLastError = true)]
  1724. static extern IntPtr GlobalLock (IntPtr hMem);
  1725. [DllImport ("kernel32.dll", SetLastError = true)]
  1726. [return: MarshalAs (UnmanagedType.Bool)]
  1727. static extern bool GlobalUnlock (IntPtr hMem);
  1728. [DllImport ("user32.dll", SetLastError = true)]
  1729. [return: MarshalAs (UnmanagedType.Bool)]
  1730. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1731. [DllImport ("user32.dll", SetLastError = true)]
  1732. [return: MarshalAs (UnmanagedType.Bool)]
  1733. static extern bool CloseClipboard ();
  1734. [DllImport ("user32.dll", SetLastError = true)]
  1735. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1736. [DllImport ("user32.dll")]
  1737. static extern bool EmptyClipboard ();
  1738. [DllImport ("user32.dll", SetLastError = true)]
  1739. static extern IntPtr GetClipboardData (uint uFormat);
  1740. }