WindowsDriver.cs 59 KB

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