WindowsDriver.cs 62 KB

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