WindowsDriver.cs 62 KB

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