WindowsDriver.cs 59 KB

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