WindowsDriver.cs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051
  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 unit tests
  673. Clipboard = new WindowsClipboard ();
  674. } else {
  675. Clipboard = new FakeDriver.FakeClipboard ();
  676. }
  677. _isWindowsTerminal = Environment.GetEnvironmentVariable ("WT_SESSION") != null;
  678. }
  679. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  680. {
  681. _keyHandler = keyHandler;
  682. _keyDownHandler = keyDownHandler;
  683. _keyUpHandler = keyUpHandler;
  684. _mouseHandler = mouseHandler;
  685. var mLoop = mainLoop.MainLoopDriver as WindowsMainLoop;
  686. mLoop.ProcessInput = (e) => ProcessInput (e);
  687. mLoop.WinChanged = (s, e) => {
  688. ChangeWin (e.Size);
  689. };
  690. }
  691. private void ChangeWin (Size e)
  692. {
  693. var w = e.Width;
  694. if (w == Cols - 3 && e.Height < Rows) {
  695. w += 3;
  696. }
  697. Left = 0;
  698. Top = 0;
  699. Cols = e.Width;
  700. Rows = e.Height;
  701. if (WinConsole != null) {
  702. var newSize = WinConsole.SetConsoleWindow (
  703. (short)Math.Max (w, 16), (short)Math.Max (e.Height, 0));
  704. Cols = newSize.Width;
  705. Rows = newSize.Height;
  706. }
  707. ResizeScreen ();
  708. ClearContents ();
  709. TerminalResized.Invoke ();
  710. }
  711. void ProcessInput (WindowsConsole.InputRecord inputEvent)
  712. {
  713. switch (inputEvent.EventType) {
  714. case WindowsConsole.EventType.Key:
  715. var fromPacketKey = inputEvent.KeyEvent.wVirtualKeyCode == (uint)ConsoleKey.Packet;
  716. if (fromPacketKey) {
  717. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  718. }
  719. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  720. //var ke = inputEvent.KeyEvent;
  721. //System.Diagnostics.Debug.WriteLine ($"fromPacketKey: {fromPacketKey}");
  722. //if (ke.UnicodeChar == '\0') {
  723. // System.Diagnostics.Debug.WriteLine ("UnicodeChar: 0'\\0'");
  724. //} else if (ke.UnicodeChar == 13) {
  725. // System.Diagnostics.Debug.WriteLine ("UnicodeChar: 13'\\n'");
  726. //} else {
  727. // System.Diagnostics.Debug.WriteLine ($"UnicodeChar: {(uint)ke.UnicodeChar}'{ke.UnicodeChar}'");
  728. //}
  729. //System.Diagnostics.Debug.WriteLine ($"bKeyDown: {ke.bKeyDown}");
  730. //System.Diagnostics.Debug.WriteLine ($"dwControlKeyState: {ke.dwControlKeyState}");
  731. //System.Diagnostics.Debug.WriteLine ($"wRepeatCount: {ke.wRepeatCount}");
  732. //System.Diagnostics.Debug.WriteLine ($"wVirtualKeyCode: {ke.wVirtualKeyCode}");
  733. //System.Diagnostics.Debug.WriteLine ($"wVirtualScanCode: {ke.wVirtualScanCode}");
  734. if (map == (Key)0xffffffff) {
  735. KeyEvent key = new KeyEvent ();
  736. // Shift = VK_SHIFT = 0x10
  737. // Ctrl = VK_CONTROL = 0x11
  738. // Alt = VK_MENU = 0x12
  739. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
  740. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
  741. }
  742. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
  743. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
  744. }
  745. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
  746. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
  747. }
  748. switch (inputEvent.KeyEvent.dwControlKeyState) {
  749. case WindowsConsole.ControlKeyState.RightAltPressed:
  750. case WindowsConsole.ControlKeyState.RightAltPressed |
  751. WindowsConsole.ControlKeyState.LeftControlPressed |
  752. WindowsConsole.ControlKeyState.EnhancedKey:
  753. case WindowsConsole.ControlKeyState.EnhancedKey:
  754. key = new KeyEvent (Key.CtrlMask | Key.AltMask, _keyModifiers);
  755. break;
  756. case WindowsConsole.ControlKeyState.LeftAltPressed:
  757. key = new KeyEvent (Key.AltMask, _keyModifiers);
  758. break;
  759. case WindowsConsole.ControlKeyState.RightControlPressed:
  760. case WindowsConsole.ControlKeyState.LeftControlPressed:
  761. key = new KeyEvent (Key.CtrlMask, _keyModifiers);
  762. break;
  763. case WindowsConsole.ControlKeyState.ShiftPressed:
  764. key = new KeyEvent (Key.ShiftMask, _keyModifiers);
  765. break;
  766. case WindowsConsole.ControlKeyState.NumlockOn:
  767. break;
  768. case WindowsConsole.ControlKeyState.ScrolllockOn:
  769. break;
  770. case WindowsConsole.ControlKeyState.CapslockOn:
  771. break;
  772. default:
  773. key = inputEvent.KeyEvent.wVirtualKeyCode switch {
  774. 0x10 => new KeyEvent (Key.ShiftMask, _keyModifiers),
  775. 0x11 => new KeyEvent (Key.CtrlMask, _keyModifiers),
  776. 0x12 => new KeyEvent (Key.AltMask, _keyModifiers),
  777. _ => new KeyEvent (Key.Unknown, _keyModifiers)
  778. };
  779. break;
  780. }
  781. if (inputEvent.KeyEvent.bKeyDown) {
  782. _keyDownHandler (key);
  783. } else {
  784. _keyUpHandler (key);
  785. }
  786. } else {
  787. if (inputEvent.KeyEvent.bKeyDown) {
  788. // May occurs using SendKeys
  789. _keyModifiers ??= new KeyModifiers ();
  790. // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
  791. _keyDownHandler (new KeyEvent (map, _keyModifiers));
  792. _keyHandler (new KeyEvent (map, _keyModifiers));
  793. } else {
  794. _keyUpHandler (new KeyEvent (map, _keyModifiers));
  795. }
  796. }
  797. if (!inputEvent.KeyEvent.bKeyDown && inputEvent.KeyEvent.dwControlKeyState == 0) {
  798. _keyModifiers = null;
  799. }
  800. break;
  801. case WindowsConsole.EventType.Mouse:
  802. var me = ToDriverMouse (inputEvent.MouseEvent);
  803. _mouseHandler (me);
  804. if (_processButtonClick) {
  805. _mouseHandler (
  806. new MouseEvent () {
  807. X = me.X,
  808. Y = me.Y,
  809. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  810. });
  811. }
  812. break;
  813. case WindowsConsole.EventType.Focus:
  814. break;
  815. }
  816. }
  817. WindowsConsole.ButtonState? _lastMouseButtonPressed = null;
  818. bool _isButtonPressed = false;
  819. bool _isButtonReleased = false;
  820. bool _isButtonDoubleClicked = false;
  821. Point? _point;
  822. Point _pointMove;
  823. bool _isOneFingerDoubleClicked = false;
  824. bool _processButtonClick;
  825. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  826. {
  827. MouseFlags mouseFlag = MouseFlags.AllEvents;
  828. //System.Diagnostics.Debug.WriteLine (
  829. // $"X:{mouseEvent.MousePosition.X};Y:{mouseEvent.MousePosition.Y};ButtonState:{mouseEvent.ButtonState};EventFlags:{mouseEvent.EventFlags}");
  830. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked) {
  831. Application.MainLoop.AddIdle (() => {
  832. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  833. return false;
  834. });
  835. }
  836. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  837. // This will tell when a mouse button is pressed. When the button is released this event will
  838. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  839. // To map to the correct driver events we save the last pressed mouse button so we can
  840. // map to the correct clicked event.
  841. if ((_lastMouseButtonPressed != null || _isButtonReleased) && mouseEvent.ButtonState != 0) {
  842. _lastMouseButtonPressed = null;
  843. //isButtonPressed = false;
  844. _isButtonReleased = false;
  845. }
  846. var p = new Point () {
  847. X = mouseEvent.MousePosition.X,
  848. Y = mouseEvent.MousePosition.Y
  849. };
  850. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed == null && !_isButtonDoubleClicked) ||
  851. (_lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) &&
  852. mouseEvent.ButtonState != 0 && !_isButtonReleased && !_isButtonDoubleClicked)) {
  853. switch (mouseEvent.ButtonState) {
  854. case WindowsConsole.ButtonState.Button1Pressed:
  855. mouseFlag = MouseFlags.Button1Pressed;
  856. break;
  857. case WindowsConsole.ButtonState.Button2Pressed:
  858. mouseFlag = MouseFlags.Button2Pressed;
  859. break;
  860. case WindowsConsole.ButtonState.RightmostButtonPressed:
  861. mouseFlag = MouseFlags.Button3Pressed;
  862. break;
  863. }
  864. if (_point == null) {
  865. _point = p;
  866. }
  867. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  868. mouseFlag |= MouseFlags.ReportMousePosition;
  869. _isButtonReleased = false;
  870. _processButtonClick = false;
  871. }
  872. _lastMouseButtonPressed = mouseEvent.ButtonState;
  873. _isButtonPressed = true;
  874. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  875. Application.MainLoop.AddIdle (() => {
  876. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  877. return false;
  878. });
  879. }
  880. } else if (_lastMouseButtonPressed != null && mouseEvent.EventFlags == 0
  881. && !_isButtonReleased && !_isButtonDoubleClicked && !_isOneFingerDoubleClicked) {
  882. switch (_lastMouseButtonPressed) {
  883. case WindowsConsole.ButtonState.Button1Pressed:
  884. mouseFlag = MouseFlags.Button1Released;
  885. break;
  886. case WindowsConsole.ButtonState.Button2Pressed:
  887. mouseFlag = MouseFlags.Button2Released;
  888. break;
  889. case WindowsConsole.ButtonState.RightmostButtonPressed:
  890. mouseFlag = MouseFlags.Button3Released;
  891. break;
  892. }
  893. _isButtonPressed = false;
  894. _isButtonReleased = true;
  895. if (_point != null && (((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)) {
  896. _processButtonClick = true;
  897. } else {
  898. _point = null;
  899. }
  900. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  901. && !_isOneFingerDoubleClicked && _isButtonReleased && p == _point) {
  902. mouseFlag = ProcessButtonClick (mouseEvent);
  903. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  904. switch (mouseEvent.ButtonState) {
  905. case WindowsConsole.ButtonState.Button1Pressed:
  906. mouseFlag = MouseFlags.Button1DoubleClicked;
  907. break;
  908. case WindowsConsole.ButtonState.Button2Pressed:
  909. mouseFlag = MouseFlags.Button2DoubleClicked;
  910. break;
  911. case WindowsConsole.ButtonState.RightmostButtonPressed:
  912. mouseFlag = MouseFlags.Button3DoubleClicked;
  913. break;
  914. }
  915. _isButtonDoubleClicked = true;
  916. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked) {
  917. switch (mouseEvent.ButtonState) {
  918. case WindowsConsole.ButtonState.Button1Pressed:
  919. mouseFlag = MouseFlags.Button1TripleClicked;
  920. break;
  921. case WindowsConsole.ButtonState.Button2Pressed:
  922. mouseFlag = MouseFlags.Button2TripleClicked;
  923. break;
  924. case WindowsConsole.ButtonState.RightmostButtonPressed:
  925. mouseFlag = MouseFlags.Button3TripleClicked;
  926. break;
  927. }
  928. _isButtonDoubleClicked = false;
  929. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  930. switch ((int)mouseEvent.ButtonState) {
  931. case int v when v > 0:
  932. mouseFlag = MouseFlags.WheeledUp;
  933. break;
  934. case int v when v < 0:
  935. mouseFlag = MouseFlags.WheeledDown;
  936. break;
  937. }
  938. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  939. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  940. switch ((int)mouseEvent.ButtonState) {
  941. case int v when v > 0:
  942. mouseFlag = MouseFlags.WheeledLeft;
  943. break;
  944. case int v when v < 0:
  945. mouseFlag = MouseFlags.WheeledRight;
  946. break;
  947. }
  948. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled) {
  949. switch ((int)mouseEvent.ButtonState) {
  950. case int v when v < 0:
  951. mouseFlag = MouseFlags.WheeledLeft;
  952. break;
  953. case int v when v > 0:
  954. mouseFlag = MouseFlags.WheeledRight;
  955. break;
  956. }
  957. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  958. mouseFlag = MouseFlags.ReportMousePosition;
  959. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y) {
  960. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  961. }
  962. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  963. mouseFlag = 0;
  964. }
  965. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  966. //System.Diagnostics.Debug.WriteLine (
  967. // $"point.X:{(point != null ? ((Point)point).X : -1)};point.Y:{(point != null ? ((Point)point).Y : -1)}");
  968. return new MouseEvent () {
  969. X = mouseEvent.MousePosition.X,
  970. Y = mouseEvent.MousePosition.Y,
  971. Flags = mouseFlag
  972. };
  973. }
  974. MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  975. {
  976. MouseFlags mouseFlag = 0;
  977. switch (_lastMouseButtonPressed) {
  978. case WindowsConsole.ButtonState.Button1Pressed:
  979. mouseFlag = MouseFlags.Button1Clicked;
  980. break;
  981. case WindowsConsole.ButtonState.Button2Pressed:
  982. mouseFlag = MouseFlags.Button2Clicked;
  983. break;
  984. case WindowsConsole.ButtonState.RightmostButtonPressed:
  985. mouseFlag = MouseFlags.Button3Clicked;
  986. break;
  987. }
  988. _point = new Point () {
  989. X = mouseEvent.MousePosition.X,
  990. Y = mouseEvent.MousePosition.Y
  991. };
  992. _lastMouseButtonPressed = null;
  993. _isButtonReleased = false;
  994. _processButtonClick = false;
  995. _point = null;
  996. return mouseFlag;
  997. }
  998. async Task ProcessButtonDoubleClickedAsync ()
  999. {
  1000. await Task.Delay (300);
  1001. _isButtonDoubleClicked = false;
  1002. _isOneFingerDoubleClicked = false;
  1003. //buttonPressedCount = 0;
  1004. }
  1005. async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1006. {
  1007. while (_isButtonPressed) {
  1008. await Task.Delay (100);
  1009. var me = new MouseEvent () {
  1010. X = _pointMove.X,
  1011. Y = _pointMove.Y,
  1012. Flags = mouseFlag
  1013. };
  1014. var view = Application.WantContinuousButtonPressedView;
  1015. if (view == null) {
  1016. break;
  1017. }
  1018. if (_isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1019. Application.MainLoop.Invoke (() => _mouseHandler (me));
  1020. }
  1021. }
  1022. }
  1023. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1024. {
  1025. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  1026. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)) {
  1027. mouseFlag |= MouseFlags.ButtonCtrl;
  1028. }
  1029. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1030. mouseFlag |= MouseFlags.ButtonShift;
  1031. }
  1032. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1033. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1034. mouseFlag |= MouseFlags.ButtonAlt;
  1035. }
  1036. return mouseFlag;
  1037. }
  1038. KeyModifiers _keyModifiers;
  1039. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1040. {
  1041. var state = keyEvent.dwControlKeyState;
  1042. var shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1043. var alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1044. var control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1045. var capsLock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  1046. var numLock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  1047. var scrollLock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  1048. _keyModifiers ??= new KeyModifiers ();
  1049. if (shift) {
  1050. _keyModifiers.Shift = true;
  1051. }
  1052. if (alt) {
  1053. _keyModifiers.Alt = true;
  1054. }
  1055. if (control) {
  1056. _keyModifiers.Ctrl = true;
  1057. }
  1058. if (capsLock) {
  1059. _keyModifiers.Capslock = true;
  1060. }
  1061. if (numLock) {
  1062. _keyModifiers.Numlock = true;
  1063. }
  1064. if (scrollLock) {
  1065. _keyModifiers.Scrolllock = true;
  1066. }
  1067. var consoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1068. return new WindowsConsole.ConsoleKeyInfoEx (consoleKeyInfo, capsLock, numLock, scrollLock);
  1069. }
  1070. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  1071. {
  1072. if (keyEvent.wVirtualKeyCode != (uint)ConsoleKey.Packet) {
  1073. return keyEvent;
  1074. }
  1075. var mod = new ConsoleModifiers ();
  1076. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1077. mod |= ConsoleModifiers.Shift;
  1078. }
  1079. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1080. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1081. mod |= ConsoleModifiers.Alt;
  1082. }
  1083. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed) ||
  1084. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)) {
  1085. mod |= ConsoleModifiers.Control;
  1086. }
  1087. var keyChar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyEvent.UnicodeChar, mod, out uint virtualKey, out uint scanCode);
  1088. return new WindowsConsole.KeyEventRecord {
  1089. UnicodeChar = (char)keyChar,
  1090. bKeyDown = keyEvent.bKeyDown,
  1091. dwControlKeyState = keyEvent.dwControlKeyState,
  1092. wRepeatCount = keyEvent.wRepeatCount,
  1093. wVirtualKeyCode = (ushort)virtualKey,
  1094. wVirtualScanCode = (ushort)scanCode
  1095. };
  1096. }
  1097. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  1098. {
  1099. var keyInfo = keyInfoEx.ConsoleKeyInfo;
  1100. switch (keyInfo.Key) {
  1101. case ConsoleKey.Escape:
  1102. return MapKeyModifiers (keyInfo, Key.Esc);
  1103. case ConsoleKey.Tab:
  1104. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  1105. case ConsoleKey.Clear:
  1106. return MapKeyModifiers (keyInfo, Key.Clear);
  1107. case ConsoleKey.Home:
  1108. return MapKeyModifiers (keyInfo, Key.Home);
  1109. case ConsoleKey.End:
  1110. return MapKeyModifiers (keyInfo, Key.End);
  1111. case ConsoleKey.LeftArrow:
  1112. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  1113. case ConsoleKey.RightArrow:
  1114. return MapKeyModifiers (keyInfo, Key.CursorRight);
  1115. case ConsoleKey.UpArrow:
  1116. return MapKeyModifiers (keyInfo, Key.CursorUp);
  1117. case ConsoleKey.DownArrow:
  1118. return MapKeyModifiers (keyInfo, Key.CursorDown);
  1119. case ConsoleKey.PageUp:
  1120. return MapKeyModifiers (keyInfo, Key.PageUp);
  1121. case ConsoleKey.PageDown:
  1122. return MapKeyModifiers (keyInfo, Key.PageDown);
  1123. case ConsoleKey.Enter:
  1124. return MapKeyModifiers (keyInfo, Key.Enter);
  1125. case ConsoleKey.Spacebar:
  1126. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  1127. case ConsoleKey.Backspace:
  1128. return MapKeyModifiers (keyInfo, Key.Backspace);
  1129. case ConsoleKey.Delete:
  1130. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  1131. case ConsoleKey.Insert:
  1132. return MapKeyModifiers (keyInfo, Key.InsertChar);
  1133. case ConsoleKey.PrintScreen:
  1134. return MapKeyModifiers (keyInfo, Key.PrintScreen);
  1135. case ConsoleKey.NumPad0:
  1136. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  1137. case ConsoleKey.NumPad1:
  1138. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  1139. case ConsoleKey.NumPad2:
  1140. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  1141. case ConsoleKey.NumPad3:
  1142. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  1143. case ConsoleKey.NumPad4:
  1144. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  1145. case ConsoleKey.NumPad5:
  1146. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  1147. case ConsoleKey.NumPad6:
  1148. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  1149. case ConsoleKey.NumPad7:
  1150. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  1151. case ConsoleKey.NumPad8:
  1152. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  1153. case ConsoleKey.NumPad9:
  1154. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  1155. case ConsoleKey.Oem1:
  1156. case ConsoleKey.Oem2:
  1157. case ConsoleKey.Oem3:
  1158. case ConsoleKey.Oem4:
  1159. case ConsoleKey.Oem5:
  1160. case ConsoleKey.Oem6:
  1161. case ConsoleKey.Oem7:
  1162. case ConsoleKey.Oem8:
  1163. case ConsoleKey.Oem102:
  1164. case ConsoleKey.OemPeriod:
  1165. case ConsoleKey.OemComma:
  1166. case ConsoleKey.OemPlus:
  1167. case ConsoleKey.OemMinus:
  1168. if (keyInfo.KeyChar == 0) {
  1169. return Key.Unknown;
  1170. }
  1171. return (Key)((uint)keyInfo.KeyChar);
  1172. }
  1173. var key = keyInfo.Key;
  1174. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  1175. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  1176. var delta = key - ConsoleKey.A;
  1177. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1178. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1179. }
  1180. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1181. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1182. }
  1183. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1184. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1185. }
  1186. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1187. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1188. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1189. }
  1190. }
  1191. //return (Key)((uint)alphaBase + delta);
  1192. return (Key)((uint)keyInfo.KeyChar);
  1193. }
  1194. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1195. var delta = key - ConsoleKey.D0;
  1196. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1197. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1198. }
  1199. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1200. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1201. }
  1202. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1203. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1204. }
  1205. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1206. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30 || keyInfo.KeyChar == ((uint)Key.D0 + delta)) {
  1207. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1208. }
  1209. }
  1210. return (Key)((uint)keyInfo.KeyChar);
  1211. }
  1212. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1213. var delta = key - ConsoleKey.F1;
  1214. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1215. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1216. }
  1217. return (Key)((uint)Key.F1 + delta);
  1218. }
  1219. if (keyInfo.KeyChar != 0) {
  1220. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1221. }
  1222. return (Key)(0xffffffff);
  1223. }
  1224. private Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1225. {
  1226. Key keyMod = new Key ();
  1227. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0) {
  1228. keyMod = Key.ShiftMask;
  1229. }
  1230. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) {
  1231. keyMod |= Key.CtrlMask;
  1232. }
  1233. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0) {
  1234. keyMod |= Key.AltMask;
  1235. }
  1236. return keyMod != Key.Null ? keyMod | key : key;
  1237. }
  1238. public override bool IsRuneSupported (Rune rune)
  1239. {
  1240. return base.IsRuneSupported (rune) && rune.IsBmp;
  1241. }
  1242. public override void Init (Action terminalResized)
  1243. {
  1244. TerminalResized = terminalResized;
  1245. try {
  1246. if (WinConsole != null) {
  1247. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1248. Cols = winSize.Width;
  1249. Rows = winSize.Height;
  1250. }
  1251. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1252. // Needed for Windows Terminal
  1253. // ESC [ ? 1047 h Save cursor position and activate xterm alternative buffer (no backscroll)
  1254. // ESC [ ? 1047 l Restore cursor position and restore xterm working buffer (with backscroll)
  1255. // ESC [ ? 1048 h Save cursor position
  1256. // ESC [ ? 1048 l Restore cursor position
  1257. // ESC [ ? 1049 h Activate xterm alternative buffer (no backscroll)
  1258. // ESC [ ? 1049 l Restore xterm working buffer (with backscroll)
  1259. // Per Issue #2264 using the alternative screen buffer is required for Windows Terminal to not
  1260. // wipe out the backscroll buffer when the application exits.
  1261. if (_isWindowsTerminal) {
  1262. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  1263. }
  1264. } catch (Win32Exception e) {
  1265. // Likely running unit tests. Set WinConsole to null so we can test it elsewhere.
  1266. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  1267. WinConsole = null;
  1268. }
  1269. CurrentAttribute = MakeColor (Color.White, Color.Black);
  1270. InitializeColorSchemes ();
  1271. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1272. Clip = new Rect (0, 0, Cols, Rows);
  1273. _damageRegion = new WindowsConsole.SmallRect () {
  1274. Top = 0,
  1275. Left = 0,
  1276. Bottom = (short)Rows,
  1277. Right = (short)Cols
  1278. };
  1279. ClearContents ();
  1280. }
  1281. void ResizeScreen ()
  1282. {
  1283. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1284. Clip = new Rect (0, 0, Cols, Rows);
  1285. _damageRegion = new WindowsConsole.SmallRect () {
  1286. Top = 0,
  1287. Left = 0,
  1288. Bottom = (short)Rows,
  1289. Right = (short)Cols
  1290. };
  1291. _dirtyLines = new bool [Rows];
  1292. WinConsole?.ForceRefreshCursorVisibility ();
  1293. }
  1294. public override void UpdateScreen ()
  1295. {
  1296. var windowSize = WinConsole?.GetConsoleBufferWindow (out _) ?? new Size (Cols, Rows);
  1297. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows)) {
  1298. return;
  1299. }
  1300. var bufferCoords = new WindowsConsole.Coord () {
  1301. X = (short)Clip.Width,
  1302. Y = (short)Clip.Height
  1303. };
  1304. for (int row = 0; row < Rows; row++) {
  1305. if (!_dirtyLines [row]) {
  1306. continue;
  1307. }
  1308. _dirtyLines [row] = false;
  1309. for (int col = 0; col < Cols; col++) {
  1310. int position = row * Cols + col;
  1311. _outputBuffer [position].Attribute = Contents [row, col].Attribute.GetValueOrDefault ();
  1312. if (Contents [row, col].IsDirty == false) {
  1313. _outputBuffer [position].Empty = true;
  1314. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1315. continue;
  1316. }
  1317. _outputBuffer [position].Empty = false;
  1318. if (Contents [row, col].Runes [0].IsBmp) {
  1319. _outputBuffer [position].Char = (char)Contents [row, col].Runes [0].Value;
  1320. } else {
  1321. //_outputBuffer [position].Empty = true;
  1322. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1323. if (Contents [row, col].Runes [0].GetColumns () > 1 && col + 1 < Cols) {
  1324. // TODO: This is a hack to deal with non-BMP and wide characters.
  1325. col++;
  1326. position = row * Cols + col;
  1327. _outputBuffer [position].Empty = false;
  1328. _outputBuffer [position].Char = ' ';
  1329. }
  1330. }
  1331. }
  1332. }
  1333. _damageRegion = new WindowsConsole.SmallRect () {
  1334. Top = 0,
  1335. Left = 0,
  1336. Bottom = (short)Rows,
  1337. Right = (short)Cols
  1338. };
  1339. if (WinConsole != null && !WinConsole.WriteToConsole (new Size (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors)) {
  1340. var err = Marshal.GetLastWin32Error ();
  1341. if (err != 0) {
  1342. throw new System.ComponentModel.Win32Exception (err);
  1343. }
  1344. }
  1345. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1346. }
  1347. public override void Refresh ()
  1348. {
  1349. UpdateScreen ();
  1350. WinConsole?.SetInitialCursorVisibility ();
  1351. UpdateCursor ();
  1352. }
  1353. #region Color Handling
  1354. /// <summary>
  1355. /// In the WindowsDriver, colors are encoded as an int.
  1356. /// The background color is stored in the least significant 4 bits,
  1357. /// and the foreground color is stored in the next 4 bits.
  1358. /// </summary>
  1359. public override Attribute MakeColor (Color foreground, Color background)
  1360. {
  1361. // Encode the colors into the int value.
  1362. return new Attribute (
  1363. value: (((int)foreground) | ((int)background << 4)),
  1364. foreground: foreground,
  1365. background: background
  1366. );
  1367. }
  1368. /// <summary>
  1369. /// Extracts the foreground and background colors from the encoded value.
  1370. /// Assumes a 4-bit encoded value for both foreground and background colors.
  1371. /// </summary>
  1372. internal override void GetColors (int value, out Color foreground, out Color background)
  1373. {
  1374. // Assume a 4-bit encoded value for both foreground and background colors.
  1375. foreground = (Color)((value >> 16) & 0xF);
  1376. background = (Color)(value & 0xF);
  1377. }
  1378. #endregion
  1379. CursorVisibility _cachedCursorVisibility;
  1380. public override void UpdateCursor ()
  1381. {
  1382. if (Col < 0 || Row < 0 || Col > Cols || Row > Rows) {
  1383. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1384. _cachedCursorVisibility = cursorVisibility;
  1385. SetCursorVisibility (CursorVisibility.Invisible);
  1386. return;
  1387. }
  1388. SetCursorVisibility (_cachedCursorVisibility);
  1389. var position = new WindowsConsole.Coord () {
  1390. X = (short)Col,
  1391. Y = (short)Row
  1392. };
  1393. WinConsole?.SetCursorPosition (position);
  1394. }
  1395. /// <inheritdoc/>
  1396. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1397. {
  1398. if (WinConsole != null) {
  1399. return WinConsole.GetCursorVisibility (out visibility);
  1400. }
  1401. visibility = _cachedCursorVisibility;
  1402. return true;
  1403. }
  1404. /// <inheritdoc/>
  1405. public override bool SetCursorVisibility (CursorVisibility visibility)
  1406. {
  1407. _cachedCursorVisibility = visibility;
  1408. return WinConsole == null || WinConsole.SetCursorVisibility (visibility);
  1409. }
  1410. /// <inheritdoc/>
  1411. public override bool EnsureCursorVisibility ()
  1412. {
  1413. return WinConsole == null || WinConsole.EnsureCursorVisibility ();
  1414. }
  1415. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1416. {
  1417. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1418. EventType = WindowsConsole.EventType.Key
  1419. };
  1420. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1421. bKeyDown = true
  1422. };
  1423. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1424. if (shift) {
  1425. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1426. keyEvent.UnicodeChar = '\0';
  1427. keyEvent.wVirtualKeyCode = 16;
  1428. }
  1429. if (alt) {
  1430. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1431. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1432. keyEvent.UnicodeChar = '\0';
  1433. keyEvent.wVirtualKeyCode = 18;
  1434. }
  1435. if (control) {
  1436. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1437. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1438. keyEvent.UnicodeChar = '\0';
  1439. keyEvent.wVirtualKeyCode = 17;
  1440. }
  1441. keyEvent.dwControlKeyState = controlKey;
  1442. input.KeyEvent = keyEvent;
  1443. if (shift || alt || control) {
  1444. ProcessInput (input);
  1445. }
  1446. keyEvent.UnicodeChar = keyChar;
  1447. if ((uint)key < 255) {
  1448. keyEvent.wVirtualKeyCode = (ushort)key;
  1449. } else {
  1450. keyEvent.wVirtualKeyCode = '\0';
  1451. }
  1452. input.KeyEvent = keyEvent;
  1453. try {
  1454. ProcessInput (input);
  1455. } catch (OverflowException) { } finally {
  1456. keyEvent.bKeyDown = false;
  1457. input.KeyEvent = keyEvent;
  1458. ProcessInput (input);
  1459. }
  1460. }
  1461. public override void End ()
  1462. {
  1463. WinConsole?.Cleanup ();
  1464. WinConsole = null;
  1465. if (_isWindowsTerminal) {
  1466. // Disable alternative screen buffer.
  1467. Console.Out.Write (EscSeqUtils.CSI_RestoreAltBufferWithBackscroll);
  1468. }
  1469. }
  1470. #region Not Implemented
  1471. public override void Suspend ()
  1472. {
  1473. throw new NotImplementedException ();
  1474. }
  1475. #endregion
  1476. static string GetParentProcessName ()
  1477. {
  1478. #pragma warning disable CA1416 // Validate platform compatibility
  1479. var myId = Process.GetCurrentProcess ().Id;
  1480. var query = string.Format ($"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {myId}");
  1481. var search = new ManagementObjectSearcher ("root\\CIMV2", query);
  1482. var queryObj = search.Get ().OfType<ManagementBaseObject> ().FirstOrDefault ();
  1483. if (queryObj == null) {
  1484. return null;
  1485. }
  1486. var parentId = (uint)queryObj ["ParentProcessId"];
  1487. var parent = Process.GetProcessById ((int)parentId);
  1488. var prevParent = parent;
  1489. // Check if the parent is from other parent
  1490. while (queryObj != null) {
  1491. query = string.Format ($"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {parentId}");
  1492. search = new ManagementObjectSearcher ("root\\CIMV2", query);
  1493. queryObj = search.Get ().OfType<ManagementBaseObject> ().FirstOrDefault ();
  1494. if (queryObj == null) {
  1495. return parent.ProcessName;
  1496. }
  1497. parentId = (uint)queryObj ["ParentProcessId"];
  1498. try {
  1499. parent = Process.GetProcessById ((int)parentId);
  1500. if (string.Equals (parent.ProcessName, "explorer", StringComparison.InvariantCultureIgnoreCase)) {
  1501. return prevParent.ProcessName;
  1502. }
  1503. prevParent = parent;
  1504. } catch (ArgumentException) {
  1505. return prevParent.ProcessName;
  1506. }
  1507. }
  1508. return parent.ProcessName;
  1509. #pragma warning restore CA1416 // Validate platform compatibility
  1510. }
  1511. }
  1512. /// <summary>
  1513. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1514. /// only be used on Windows.
  1515. /// </summary>
  1516. /// <remarks>
  1517. /// This implementation is used for WindowsDriver.
  1518. /// </remarks>
  1519. internal class WindowsMainLoop : IMainLoopDriver {
  1520. ManualResetEventSlim _eventReady = new ManualResetEventSlim (false);
  1521. ManualResetEventSlim _waitForProbe = new ManualResetEventSlim (false);
  1522. ManualResetEventSlim _winChange = new ManualResetEventSlim (false);
  1523. MainLoop _mainLoop;
  1524. ConsoleDriver _consoleDriver;
  1525. WindowsConsole _winConsole;
  1526. bool _winChanged;
  1527. Size _windowSize;
  1528. CancellationTokenSource _tokenSource = new CancellationTokenSource ();
  1529. // The records that we keep fetching
  1530. Queue<WindowsConsole.InputRecord []> _resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1531. /// <summary>
  1532. /// Invoked when a Key is pressed or released.
  1533. /// </summary>
  1534. public Action<WindowsConsole.InputRecord> ProcessInput;
  1535. /// <summary>
  1536. /// Invoked when the window is changed.
  1537. /// </summary>
  1538. public EventHandler<SizeChangedEventArgs> WinChanged;
  1539. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1540. {
  1541. _consoleDriver = consoleDriver ?? throw new ArgumentNullException ("Console driver instance must be provided.");
  1542. _winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1543. }
  1544. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1545. {
  1546. _mainLoop = mainLoop;
  1547. Task.Run (WindowsInputHandler);
  1548. Task.Run (CheckWinChange);
  1549. }
  1550. void WindowsInputHandler ()
  1551. {
  1552. while (true) {
  1553. _waitForProbe.Wait ();
  1554. _waitForProbe.Reset ();
  1555. if (_resultQueue?.Count == 0) {
  1556. _resultQueue.Enqueue (_winConsole.ReadConsoleInput ());
  1557. }
  1558. _eventReady.Set ();
  1559. }
  1560. }
  1561. void CheckWinChange ()
  1562. {
  1563. while (true) {
  1564. _winChange.Wait ();
  1565. _winChange.Reset ();
  1566. WaitWinChange ();
  1567. _winChanged = true;
  1568. _eventReady.Set ();
  1569. }
  1570. }
  1571. void WaitWinChange ()
  1572. {
  1573. while (true) {
  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. return;
  1579. }
  1580. }
  1581. }
  1582. void IMainLoopDriver.Wakeup ()
  1583. {
  1584. //tokenSource.Cancel ();
  1585. _eventReady.Set ();
  1586. }
  1587. bool IMainLoopDriver.EventsPending (bool wait)
  1588. {
  1589. _waitForProbe.Set ();
  1590. _winChange.Set ();
  1591. if (CheckTimers (wait, out var waitTimeout)) {
  1592. return true;
  1593. }
  1594. try {
  1595. if (!_tokenSource.IsCancellationRequested) {
  1596. _eventReady.Wait (waitTimeout, _tokenSource.Token);
  1597. }
  1598. } catch (OperationCanceledException) {
  1599. return true;
  1600. } finally {
  1601. _eventReady.Reset ();
  1602. }
  1603. if (!_tokenSource.IsCancellationRequested) {
  1604. return _resultQueue.Count > 0 || CheckTimers (wait, out _) || _winChanged;
  1605. }
  1606. _tokenSource.Dispose ();
  1607. _tokenSource = new CancellationTokenSource ();
  1608. return true;
  1609. }
  1610. bool CheckTimers (bool wait, out int waitTimeout)
  1611. {
  1612. long now = DateTime.UtcNow.Ticks;
  1613. if (_mainLoop.timeouts.Count > 0) {
  1614. waitTimeout = (int)((_mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1615. if (waitTimeout < 0)
  1616. return true;
  1617. } else {
  1618. waitTimeout = -1;
  1619. }
  1620. if (!wait)
  1621. waitTimeout = 0;
  1622. int ic;
  1623. lock (_mainLoop.idleHandlers) {
  1624. ic = _mainLoop.idleHandlers.Count;
  1625. }
  1626. return ic > 0;
  1627. }
  1628. void IMainLoopDriver.Iteration ()
  1629. {
  1630. while (_resultQueue.Count > 0) {
  1631. var inputRecords = _resultQueue.Dequeue ();
  1632. if (inputRecords != null && inputRecords.Length > 0) {
  1633. var inputEvent = inputRecords [0];
  1634. ProcessInput?.Invoke (inputEvent);
  1635. }
  1636. }
  1637. if (_winChanged) {
  1638. _winChanged = false;
  1639. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  1640. }
  1641. }
  1642. }
  1643. class WindowsClipboard : ClipboardBase {
  1644. public WindowsClipboard ()
  1645. {
  1646. IsSupported = IsClipboardFormatAvailable (_cfUnicodeText);
  1647. }
  1648. public override bool IsSupported { get; }
  1649. protected override string GetClipboardDataImpl ()
  1650. {
  1651. try {
  1652. if (!OpenClipboard (IntPtr.Zero)) {
  1653. return string.Empty;
  1654. }
  1655. IntPtr handle = GetClipboardData (_cfUnicodeText);
  1656. if (handle == IntPtr.Zero) {
  1657. return string.Empty;
  1658. }
  1659. IntPtr pointer = IntPtr.Zero;
  1660. try {
  1661. pointer = GlobalLock (handle);
  1662. if (pointer == IntPtr.Zero) {
  1663. return string.Empty;
  1664. }
  1665. int size = GlobalSize (handle);
  1666. byte [] buff = new byte [size];
  1667. Marshal.Copy (pointer, buff, 0, size);
  1668. return System.Text.Encoding.Unicode.GetString (buff).TrimEnd ('\0');
  1669. } finally {
  1670. if (pointer != IntPtr.Zero) {
  1671. GlobalUnlock (handle);
  1672. }
  1673. }
  1674. } finally {
  1675. CloseClipboard ();
  1676. }
  1677. }
  1678. protected override void SetClipboardDataImpl (string text)
  1679. {
  1680. OpenClipboard ();
  1681. EmptyClipboard ();
  1682. IntPtr hGlobal = default;
  1683. try {
  1684. var bytes = (text.Length + 1) * 2;
  1685. hGlobal = Marshal.AllocHGlobal (bytes);
  1686. if (hGlobal == default) {
  1687. ThrowWin32 ();
  1688. }
  1689. var target = GlobalLock (hGlobal);
  1690. if (target == default) {
  1691. ThrowWin32 ();
  1692. }
  1693. try {
  1694. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1695. } finally {
  1696. GlobalUnlock (target);
  1697. }
  1698. if (SetClipboardData (_cfUnicodeText, hGlobal) == default) {
  1699. ThrowWin32 ();
  1700. }
  1701. hGlobal = default;
  1702. } finally {
  1703. if (hGlobal != default) {
  1704. Marshal.FreeHGlobal (hGlobal);
  1705. }
  1706. CloseClipboard ();
  1707. }
  1708. }
  1709. void OpenClipboard ()
  1710. {
  1711. var num = 10;
  1712. while (true) {
  1713. if (OpenClipboard (default)) {
  1714. break;
  1715. }
  1716. if (--num == 0) {
  1717. ThrowWin32 ();
  1718. }
  1719. Thread.Sleep (100);
  1720. }
  1721. }
  1722. const uint _cfUnicodeText = 13;
  1723. void ThrowWin32 ()
  1724. {
  1725. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1726. }
  1727. [DllImport ("User32.dll", SetLastError = true)]
  1728. [return: MarshalAs (UnmanagedType.Bool)]
  1729. static extern bool IsClipboardFormatAvailable (uint format);
  1730. [DllImport ("kernel32.dll", SetLastError = true)]
  1731. static extern int GlobalSize (IntPtr handle);
  1732. [DllImport ("kernel32.dll", SetLastError = true)]
  1733. static extern IntPtr GlobalLock (IntPtr hMem);
  1734. [DllImport ("kernel32.dll", SetLastError = true)]
  1735. [return: MarshalAs (UnmanagedType.Bool)]
  1736. static extern bool GlobalUnlock (IntPtr hMem);
  1737. [DllImport ("user32.dll", SetLastError = true)]
  1738. [return: MarshalAs (UnmanagedType.Bool)]
  1739. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1740. [DllImport ("user32.dll", SetLastError = true)]
  1741. [return: MarshalAs (UnmanagedType.Bool)]
  1742. static extern bool CloseClipboard ();
  1743. [DllImport ("user32.dll", SetLastError = true)]
  1744. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1745. [DllImport ("user32.dll")]
  1746. static extern bool EmptyClipboard ();
  1747. [DllImport ("user32.dll", SetLastError = true)]
  1748. static extern IntPtr GetClipboardData (uint uFormat);
  1749. }