WindowsDriver.cs 63 KB

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