WindowsDriver.cs 64 KB

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