WindowsDriver.cs 60 KB

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