WindowsDriver.cs 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147
  1. //
  2. // WindowsDriver.cs: Windows specific driver
  3. //
  4. using System.Text;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Linq;
  9. using System.Runtime.InteropServices;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. 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. public override IClipboard Clipboard => clipboard;
  611. public override int [,,] Contents => contents;
  612. public WindowsConsole WinConsole { get; private set; }
  613. Action<KeyEvent> keyHandler;
  614. Action<KeyEvent> keyDownHandler;
  615. Action<KeyEvent> keyUpHandler;
  616. Action<MouseEvent> mouseHandler;
  617. public WindowsDriver ()
  618. {
  619. WinConsole = new WindowsConsole ();
  620. clipboard = new WindowsClipboard ();
  621. }
  622. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  623. {
  624. this.keyHandler = keyHandler;
  625. this.keyDownHandler = keyDownHandler;
  626. this.keyUpHandler = keyUpHandler;
  627. this.mouseHandler = mouseHandler;
  628. var mLoop = mainLoop.Driver as WindowsMainLoop;
  629. mLoop.ProcessInput = (e) => ProcessInput (e);
  630. mLoop.WinChanged = (s, e) => {
  631. ChangeWin (e.Size);
  632. };
  633. }
  634. private void ChangeWin (Size e)
  635. {
  636. if (!EnableConsoleScrolling) {
  637. var w = e.Width;
  638. if (w == cols - 3 && e.Height < rows) {
  639. w += 3;
  640. }
  641. var newSize = WinConsole.SetConsoleWindow (
  642. (short)Math.Max (w, 16), (short)Math.Max (e.Height, 0));
  643. left = 0;
  644. top = 0;
  645. cols = newSize.Width;
  646. rows = newSize.Height;
  647. ResizeScreen ();
  648. UpdateOffScreen ();
  649. TerminalResized.Invoke ();
  650. }
  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) {
  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.WindowBufferSize:
  763. var winSize = WinConsole.GetConsoleBufferWindow (out Point pos);
  764. left = pos.X;
  765. top = pos.Y;
  766. cols = inputEvent.WindowBufferSizeEvent.size.X;
  767. if (EnableConsoleScrolling) {
  768. rows = Math.Max (inputEvent.WindowBufferSizeEvent.size.Y, rows);
  769. } else {
  770. rows = inputEvent.WindowBufferSizeEvent.size.Y;
  771. }
  772. //System.Diagnostics.Debug.WriteLine ($"{EnableConsoleScrolling},{cols},{rows}");
  773. ResizeScreen ();
  774. UpdateOffScreen ();
  775. TerminalResized?.Invoke ();
  776. break;
  777. case WindowsConsole.EventType.Focus:
  778. keyModifiers = null;
  779. break;
  780. }
  781. }
  782. WindowsConsole.ButtonState? lastMouseButtonPressed = null;
  783. bool isButtonPressed = false;
  784. bool isButtonReleased = false;
  785. bool isButtonDoubleClicked = false;
  786. Point? point;
  787. Point pointMove;
  788. //int buttonPressedCount;
  789. bool isOneFingerDoubleClicked = false;
  790. bool processButtonClick;
  791. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  792. {
  793. MouseFlags mouseFlag = MouseFlags.AllEvents;
  794. //System.Diagnostics.Debug.WriteLine (
  795. // $"X:{mouseEvent.MousePosition.X};Y:{mouseEvent.MousePosition.Y};ButtonState:{mouseEvent.ButtonState};EventFlags:{mouseEvent.EventFlags}");
  796. if (isButtonDoubleClicked || isOneFingerDoubleClicked) {
  797. Application.MainLoop.AddIdle (() => {
  798. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  799. return false;
  800. });
  801. }
  802. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  803. // This will tell when a mouse button is pressed. When the button is released this event will
  804. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  805. // To map to the correct driver events we save the last pressed mouse button so we can
  806. // map to the correct clicked event.
  807. if ((lastMouseButtonPressed != null || isButtonReleased) && mouseEvent.ButtonState != 0) {
  808. lastMouseButtonPressed = null;
  809. //isButtonPressed = false;
  810. isButtonReleased = false;
  811. }
  812. var p = new Point () {
  813. X = mouseEvent.MousePosition.X,
  814. Y = mouseEvent.MousePosition.Y
  815. };
  816. //if (!isButtonPressed && buttonPressedCount < 2
  817. // && mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  818. // && (mouseEvent.ButtonState == WindowsConsole.ButtonState.Button1Pressed
  819. // || mouseEvent.ButtonState == WindowsConsole.ButtonState.Button2Pressed
  820. // || mouseEvent.ButtonState == WindowsConsole.ButtonState.Button3Pressed)) {
  821. // lastMouseButtonPressed = mouseEvent.ButtonState;
  822. // buttonPressedCount++;
  823. //} else if (!isButtonPressed && buttonPressedCount > 0 && mouseEvent.ButtonState == 0
  824. // && mouseEvent.EventFlags == 0) {
  825. // buttonPressedCount++;
  826. //}
  827. //System.Diagnostics.Debug.WriteLine ($"isButtonPressed: {isButtonPressed};buttonPressedCount: {buttonPressedCount};lastMouseButtonPressed: {lastMouseButtonPressed}");
  828. //System.Diagnostics.Debug.WriteLine ($"isOneFingerDoubleClicked: {isOneFingerDoubleClicked}");
  829. //if (buttonPressedCount == 1 && lastMouseButtonPressed != null && p == point
  830. // && lastMouseButtonPressed == WindowsConsole.ButtonState.Button1Pressed
  831. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button2Pressed
  832. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button3Pressed) {
  833. // switch (lastMouseButtonPressed) {
  834. // case WindowsConsole.ButtonState.Button1Pressed:
  835. // mouseFlag = MouseFlags.Button1DoubleClicked;
  836. // break;
  837. // case WindowsConsole.ButtonState.Button2Pressed:
  838. // mouseFlag = MouseFlags.Button2DoubleClicked;
  839. // break;
  840. // case WindowsConsole.ButtonState.Button3Pressed:
  841. // mouseFlag = MouseFlags.Button3DoubleClicked;
  842. // break;
  843. // }
  844. // isOneFingerDoubleClicked = true;
  845. //} else if (buttonPressedCount == 3 && lastMouseButtonPressed != null && isOneFingerDoubleClicked && p == point
  846. // && lastMouseButtonPressed == WindowsConsole.ButtonState.Button1Pressed
  847. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button2Pressed
  848. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button3Pressed) {
  849. // switch (lastMouseButtonPressed) {
  850. // case WindowsConsole.ButtonState.Button1Pressed:
  851. // mouseFlag = MouseFlags.Button1TripleClicked;
  852. // break;
  853. // case WindowsConsole.ButtonState.Button2Pressed:
  854. // mouseFlag = MouseFlags.Button2TripleClicked;
  855. // break;
  856. // case WindowsConsole.ButtonState.Button3Pressed:
  857. // mouseFlag = MouseFlags.Button3TripleClicked;
  858. // break;
  859. // }
  860. // buttonPressedCount = 0;
  861. // lastMouseButtonPressed = null;
  862. // isOneFingerDoubleClicked = false;
  863. // isButtonReleased = false;
  864. //}
  865. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && lastMouseButtonPressed == null && !isButtonDoubleClicked) ||
  866. (lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) &&
  867. mouseEvent.ButtonState != 0 && !isButtonReleased && !isButtonDoubleClicked)) {
  868. switch (mouseEvent.ButtonState) {
  869. case WindowsConsole.ButtonState.Button1Pressed:
  870. mouseFlag = MouseFlags.Button1Pressed;
  871. break;
  872. case WindowsConsole.ButtonState.Button2Pressed:
  873. mouseFlag = MouseFlags.Button2Pressed;
  874. break;
  875. case WindowsConsole.ButtonState.RightmostButtonPressed:
  876. mouseFlag = MouseFlags.Button3Pressed;
  877. break;
  878. }
  879. if (point == null)
  880. point = p;
  881. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  882. mouseFlag |= MouseFlags.ReportMousePosition;
  883. isButtonReleased = false;
  884. processButtonClick = false;
  885. }
  886. lastMouseButtonPressed = mouseEvent.ButtonState;
  887. isButtonPressed = true;
  888. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  889. Application.MainLoop.AddIdle (() => {
  890. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  891. return false;
  892. });
  893. }
  894. } else if (lastMouseButtonPressed != null && mouseEvent.EventFlags == 0
  895. && !isButtonReleased && !isButtonDoubleClicked && !isOneFingerDoubleClicked) {
  896. switch (lastMouseButtonPressed) {
  897. case WindowsConsole.ButtonState.Button1Pressed:
  898. mouseFlag = MouseFlags.Button1Released;
  899. break;
  900. case WindowsConsole.ButtonState.Button2Pressed:
  901. mouseFlag = MouseFlags.Button2Released;
  902. break;
  903. case WindowsConsole.ButtonState.RightmostButtonPressed:
  904. mouseFlag = MouseFlags.Button3Released;
  905. break;
  906. }
  907. isButtonPressed = false;
  908. isButtonReleased = true;
  909. if (point != null && (((Point)point).X == mouseEvent.MousePosition.X && ((Point)point).Y == mouseEvent.MousePosition.Y)) {
  910. processButtonClick = true;
  911. } else {
  912. point = null;
  913. }
  914. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  915. && !isOneFingerDoubleClicked && isButtonReleased && p == point) {
  916. mouseFlag = ProcessButtonClick (mouseEvent);
  917. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  918. switch (mouseEvent.ButtonState) {
  919. case WindowsConsole.ButtonState.Button1Pressed:
  920. mouseFlag = MouseFlags.Button1DoubleClicked;
  921. break;
  922. case WindowsConsole.ButtonState.Button2Pressed:
  923. mouseFlag = MouseFlags.Button2DoubleClicked;
  924. break;
  925. case WindowsConsole.ButtonState.RightmostButtonPressed:
  926. mouseFlag = MouseFlags.Button3DoubleClicked;
  927. break;
  928. }
  929. isButtonDoubleClicked = true;
  930. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && isButtonDoubleClicked) {
  931. switch (mouseEvent.ButtonState) {
  932. case WindowsConsole.ButtonState.Button1Pressed:
  933. mouseFlag = MouseFlags.Button1TripleClicked;
  934. break;
  935. case WindowsConsole.ButtonState.Button2Pressed:
  936. mouseFlag = MouseFlags.Button2TripleClicked;
  937. break;
  938. case WindowsConsole.ButtonState.RightmostButtonPressed:
  939. mouseFlag = MouseFlags.Button3TripleClicked;
  940. break;
  941. }
  942. isButtonDoubleClicked = false;
  943. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  944. switch ((int)mouseEvent.ButtonState) {
  945. case int v when v > 0:
  946. mouseFlag = MouseFlags.WheeledUp;
  947. break;
  948. case int v when v < 0:
  949. mouseFlag = MouseFlags.WheeledDown;
  950. break;
  951. }
  952. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  953. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  954. switch ((int)mouseEvent.ButtonState) {
  955. case int v when v > 0:
  956. mouseFlag = MouseFlags.WheeledLeft;
  957. break;
  958. case int v when v < 0:
  959. mouseFlag = MouseFlags.WheeledRight;
  960. break;
  961. }
  962. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled) {
  963. switch ((int)mouseEvent.ButtonState) {
  964. case int v when v < 0:
  965. mouseFlag = MouseFlags.WheeledLeft;
  966. break;
  967. case int v when v > 0:
  968. mouseFlag = MouseFlags.WheeledRight;
  969. break;
  970. }
  971. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  972. mouseFlag = MouseFlags.ReportMousePosition;
  973. if (mouseEvent.MousePosition.X != pointMove.X || mouseEvent.MousePosition.Y != pointMove.Y) {
  974. pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  975. }
  976. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  977. mouseFlag = 0;
  978. }
  979. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  980. //System.Diagnostics.Debug.WriteLine (
  981. // $"point.X:{(point != null ? ((Point)point).X : -1)};point.Y:{(point != null ? ((Point)point).Y : -1)}");
  982. return new MouseEvent () {
  983. X = mouseEvent.MousePosition.X,
  984. Y = mouseEvent.MousePosition.Y,
  985. Flags = mouseFlag
  986. };
  987. }
  988. MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  989. {
  990. MouseFlags mouseFlag = 0;
  991. switch (lastMouseButtonPressed) {
  992. case WindowsConsole.ButtonState.Button1Pressed:
  993. mouseFlag = MouseFlags.Button1Clicked;
  994. break;
  995. case WindowsConsole.ButtonState.Button2Pressed:
  996. mouseFlag = MouseFlags.Button2Clicked;
  997. break;
  998. case WindowsConsole.ButtonState.RightmostButtonPressed:
  999. mouseFlag = MouseFlags.Button3Clicked;
  1000. break;
  1001. }
  1002. point = new Point () {
  1003. X = mouseEvent.MousePosition.X,
  1004. Y = mouseEvent.MousePosition.Y
  1005. };
  1006. lastMouseButtonPressed = null;
  1007. isButtonReleased = false;
  1008. processButtonClick = false;
  1009. point = null;
  1010. return mouseFlag;
  1011. }
  1012. async Task ProcessButtonDoubleClickedAsync ()
  1013. {
  1014. await Task.Delay (300);
  1015. isButtonDoubleClicked = false;
  1016. isOneFingerDoubleClicked = false;
  1017. //buttonPressedCount = 0;
  1018. }
  1019. async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1020. {
  1021. while (isButtonPressed) {
  1022. await Task.Delay (100);
  1023. var me = new MouseEvent () {
  1024. X = pointMove.X,
  1025. Y = pointMove.Y,
  1026. Flags = mouseFlag
  1027. };
  1028. var view = Application.WantContinuousButtonPressedView;
  1029. if (view == null) {
  1030. break;
  1031. }
  1032. if (isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1033. Application.MainLoop.Invoke (() => mouseHandler (me));
  1034. }
  1035. }
  1036. }
  1037. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1038. {
  1039. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  1040. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  1041. mouseFlag |= MouseFlags.ButtonCtrl;
  1042. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  1043. mouseFlag |= MouseFlags.ButtonShift;
  1044. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1045. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  1046. mouseFlag |= MouseFlags.ButtonAlt;
  1047. return mouseFlag;
  1048. }
  1049. KeyModifiers keyModifiers;
  1050. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1051. {
  1052. var state = keyEvent.dwControlKeyState;
  1053. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1054. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1055. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1056. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  1057. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  1058. bool scrolllock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  1059. if (keyModifiers == null)
  1060. keyModifiers = new KeyModifiers ();
  1061. if (shift)
  1062. keyModifiers.Shift = shift;
  1063. if (alt)
  1064. keyModifiers.Alt = alt;
  1065. if (control)
  1066. keyModifiers.Ctrl = control;
  1067. if (capslock)
  1068. keyModifiers.Capslock = capslock;
  1069. if (numlock)
  1070. keyModifiers.Numlock = numlock;
  1071. if (scrolllock)
  1072. keyModifiers.Scrolllock = scrolllock;
  1073. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1074. return new WindowsConsole.ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock, scrolllock);
  1075. }
  1076. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  1077. {
  1078. if (keyEvent.wVirtualKeyCode != (uint)ConsoleKey.Packet) {
  1079. return keyEvent;
  1080. }
  1081. var mod = new ConsoleModifiers ();
  1082. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1083. mod |= ConsoleModifiers.Shift;
  1084. }
  1085. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1086. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1087. mod |= ConsoleModifiers.Alt;
  1088. }
  1089. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed) ||
  1090. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)) {
  1091. mod |= ConsoleModifiers.Control;
  1092. }
  1093. var keyChar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyEvent.UnicodeChar, mod, out uint virtualKey, out uint scanCode);
  1094. return new WindowsConsole.KeyEventRecord {
  1095. UnicodeChar = (char)keyChar,
  1096. bKeyDown = keyEvent.bKeyDown,
  1097. dwControlKeyState = keyEvent.dwControlKeyState,
  1098. wRepeatCount = keyEvent.wRepeatCount,
  1099. wVirtualKeyCode = (ushort)virtualKey,
  1100. wVirtualScanCode = (ushort)scanCode
  1101. };
  1102. }
  1103. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  1104. {
  1105. var keyInfo = keyInfoEx.consoleKeyInfo;
  1106. switch (keyInfo.Key) {
  1107. case ConsoleKey.Escape:
  1108. return MapKeyModifiers (keyInfo, Key.Esc);
  1109. case ConsoleKey.Tab:
  1110. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  1111. case ConsoleKey.Clear:
  1112. return MapKeyModifiers (keyInfo, Key.Clear);
  1113. case ConsoleKey.Home:
  1114. return MapKeyModifiers (keyInfo, Key.Home);
  1115. case ConsoleKey.End:
  1116. return MapKeyModifiers (keyInfo, Key.End);
  1117. case ConsoleKey.LeftArrow:
  1118. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  1119. case ConsoleKey.RightArrow:
  1120. return MapKeyModifiers (keyInfo, Key.CursorRight);
  1121. case ConsoleKey.UpArrow:
  1122. return MapKeyModifiers (keyInfo, Key.CursorUp);
  1123. case ConsoleKey.DownArrow:
  1124. return MapKeyModifiers (keyInfo, Key.CursorDown);
  1125. case ConsoleKey.PageUp:
  1126. return MapKeyModifiers (keyInfo, Key.PageUp);
  1127. case ConsoleKey.PageDown:
  1128. return MapKeyModifiers (keyInfo, Key.PageDown);
  1129. case ConsoleKey.Enter:
  1130. return MapKeyModifiers (keyInfo, Key.Enter);
  1131. case ConsoleKey.Spacebar:
  1132. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  1133. case ConsoleKey.Backspace:
  1134. return MapKeyModifiers (keyInfo, Key.Backspace);
  1135. case ConsoleKey.Delete:
  1136. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  1137. case ConsoleKey.Insert:
  1138. return MapKeyModifiers (keyInfo, Key.InsertChar);
  1139. case ConsoleKey.PrintScreen:
  1140. return MapKeyModifiers (keyInfo, Key.PrintScreen);
  1141. case ConsoleKey.NumPad0:
  1142. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  1143. case ConsoleKey.NumPad1:
  1144. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  1145. case ConsoleKey.NumPad2:
  1146. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  1147. case ConsoleKey.NumPad3:
  1148. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  1149. case ConsoleKey.NumPad4:
  1150. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  1151. case ConsoleKey.NumPad5:
  1152. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  1153. case ConsoleKey.NumPad6:
  1154. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  1155. case ConsoleKey.NumPad7:
  1156. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  1157. case ConsoleKey.NumPad8:
  1158. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  1159. case ConsoleKey.NumPad9:
  1160. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  1161. case ConsoleKey.Oem1:
  1162. case ConsoleKey.Oem2:
  1163. case ConsoleKey.Oem3:
  1164. case ConsoleKey.Oem4:
  1165. case ConsoleKey.Oem5:
  1166. case ConsoleKey.Oem6:
  1167. case ConsoleKey.Oem7:
  1168. case ConsoleKey.Oem8:
  1169. case ConsoleKey.Oem102:
  1170. case ConsoleKey.OemPeriod:
  1171. case ConsoleKey.OemComma:
  1172. case ConsoleKey.OemPlus:
  1173. case ConsoleKey.OemMinus:
  1174. if (keyInfo.KeyChar == 0)
  1175. return Key.Unknown;
  1176. return (Key)((uint)keyInfo.KeyChar);
  1177. }
  1178. var key = keyInfo.Key;
  1179. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  1180. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  1181. var delta = key - ConsoleKey.A;
  1182. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1183. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1184. }
  1185. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1186. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1187. }
  1188. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1189. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1190. }
  1191. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1192. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1193. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1194. }
  1195. }
  1196. //return (Key)((uint)alphaBase + delta);
  1197. return (Key)((uint)keyInfo.KeyChar);
  1198. }
  1199. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1200. var delta = key - ConsoleKey.D0;
  1201. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1202. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1203. }
  1204. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1205. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1206. }
  1207. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  1208. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1209. }
  1210. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1211. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30 || keyInfo.KeyChar == ((uint)Key.D0 + delta)) {
  1212. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1213. }
  1214. }
  1215. return (Key)((uint)keyInfo.KeyChar);
  1216. }
  1217. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1218. var delta = key - ConsoleKey.F1;
  1219. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1220. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1221. }
  1222. return (Key)((uint)Key.F1 + delta);
  1223. }
  1224. if (keyInfo.KeyChar != 0) {
  1225. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1226. }
  1227. return (Key)(0xffffffff);
  1228. }
  1229. private Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1230. {
  1231. Key keyMod = new Key ();
  1232. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
  1233. keyMod = Key.ShiftMask;
  1234. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
  1235. keyMod |= Key.CtrlMask;
  1236. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
  1237. keyMod |= Key.AltMask;
  1238. return keyMod != Key.Null ? keyMod | key : key;
  1239. }
  1240. public override void Init (Action terminalResized)
  1241. {
  1242. TerminalResized = terminalResized;
  1243. try {
  1244. // Needed for Windows Terminal
  1245. // ESC [ ? 1047 h Activate xterm alternative buffer (no backscroll)
  1246. // ESC [ ? 1047 l Restore xterm working buffer (with backscroll)
  1247. // ESC [ ? 1048 h Save cursor position
  1248. // ESC [ ? 1048 l Restore cursor position
  1249. // ESC [ ? 1049 h Save cursor position and activate xterm alternative buffer (no backscroll)
  1250. // ESC [ ? 1049 l Restore cursor position and restore xterm working buffer (with backscroll)
  1251. // Per Issue #2264 using the alterantive screen buffer is required for Windows Terminal to not
  1252. // wipe out the backscroll buffer when the application exits.
  1253. Console.Out.Write ("\x1b[?1047h");
  1254. // Console.Out.Flush () is not needed. See https://stackoverflow.com/a/20450486/297526
  1255. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1256. cols = winSize.Width;
  1257. rows = winSize.Height;
  1258. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1259. CurrentAttribute = MakeColor (Color.White, Color.Black);
  1260. InitalizeColorSchemes ();
  1261. CurrentAttribute = MakeColor (Color.White, Color.Black);
  1262. InitalizeColorSchemes ();
  1263. ResizeScreen ();
  1264. UpdateOffScreen ();
  1265. } catch (Win32Exception e) {
  1266. throw new InvalidOperationException ("The Windows Console output window is not available.", e);
  1267. }
  1268. }
  1269. public override void ResizeScreen ()
  1270. {
  1271. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  1272. Clip = new Rect (0, 0, Cols, Rows);
  1273. damageRegion = new WindowsConsole.SmallRect () {
  1274. Top = 0,
  1275. Left = 0,
  1276. Bottom = (short)Rows,
  1277. Right = (short)Cols
  1278. };
  1279. WinConsole.ForceRefreshCursorVisibility ();
  1280. if (!EnableConsoleScrolling) {
  1281. // ANSI ESC "[xJ" Clears part of the screen.
  1282. // If n is 0 (or missing), clear from cursor to end of screen.
  1283. // If n is 1, clear from cursor to beginning of the screen.
  1284. // If n is 2, clear entire screen (and moves cursor to upper left on DOS ANSI.SYS).
  1285. // If n is 3, clear entire screen and delete all lines saved in the scrollback buffer
  1286. // DO NOT USE 3J - even with the alternate screen buffer, it clears the entire scrollback buffer
  1287. Console.Out.Write ("\x1b[3J");
  1288. }
  1289. }
  1290. public override void UpdateOffScreen ()
  1291. {
  1292. contents = new int [rows, cols, 3];
  1293. for (int row = 0; row < rows; row++) {
  1294. for (int col = 0; col < cols; col++) {
  1295. int position = row * cols + col;
  1296. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  1297. OutputBuffer [position].Char.UnicodeChar = ' ';
  1298. contents [row, col, 0] = OutputBuffer [position].Char.UnicodeChar;
  1299. contents [row, col, 1] = OutputBuffer [position].Attributes;
  1300. contents [row, col, 2] = 0;
  1301. }
  1302. }
  1303. }
  1304. int ccol, crow;
  1305. public override void Move (int col, int row)
  1306. {
  1307. ccol = col;
  1308. crow = row;
  1309. }
  1310. int GetOutputBufferPosition ()
  1311. {
  1312. return crow * Cols + ccol;
  1313. }
  1314. public override bool IsRuneSupported (Rune rune)
  1315. {
  1316. // See Issue #2610
  1317. return base.IsRuneSupported (rune) && rune.IsBmp;
  1318. }
  1319. public override void AddRune (Rune rune)
  1320. {
  1321. if (!IsRuneSupported (rune)) {
  1322. rune = Rune.ReplacementChar;
  1323. }
  1324. rune = rune.MakePrintable ();
  1325. var runeWidth = rune.GetColumns ();
  1326. var position = GetOutputBufferPosition ();
  1327. var validClip = IsValidContent (ccol, crow, Clip);
  1328. if (validClip) {
  1329. if (runeWidth == 0 && ccol > 0) {
  1330. var r = contents [crow, ccol - 1, 0];
  1331. var s = new string (new char [] { (char)r, (char)rune.Value });
  1332. string sn;
  1333. if (!s.IsNormalized ()) {
  1334. sn = s.Normalize ();
  1335. } else {
  1336. sn = s;
  1337. }
  1338. var c = sn [0];
  1339. var prevPosition = crow * Cols + (ccol - 1);
  1340. OutputBuffer [prevPosition].Char.UnicodeChar = c;
  1341. contents [crow, ccol - 1, 0] = c;
  1342. OutputBuffer [prevPosition].Attributes = (ushort)CurrentAttribute;
  1343. contents [crow, ccol - 1, 1] = CurrentAttribute;
  1344. contents [crow, ccol - 1, 2] = 1;
  1345. WindowsConsole.SmallRect.Update (ref damageRegion, (short)(ccol - 1), (short)crow);
  1346. } else {
  1347. if (runeWidth < 2 && ccol > 0
  1348. && ((Rune)(char)contents [crow, ccol - 1, 0]).GetColumns () > 1) {
  1349. var prevPosition = crow * Cols + (ccol - 1);
  1350. OutputBuffer [prevPosition].Char.UnicodeChar = ' ';
  1351. contents [crow, ccol - 1, 0] = (int)(uint)' ';
  1352. } else if (runeWidth < 2 && ccol <= Clip.Right - 1
  1353. && ((Rune)(char)contents [crow, ccol, 0]).GetColumns () > 1) {
  1354. var prevPosition = GetOutputBufferPosition () + 1;
  1355. OutputBuffer [prevPosition].Char.UnicodeChar = (char)' ';
  1356. contents [crow, ccol + 1, 0] = (int)(uint)' ';
  1357. }
  1358. if (runeWidth > 1 && ccol == Clip.Right - 1) {
  1359. OutputBuffer [position].Char.UnicodeChar = (char)' ';
  1360. contents [crow, ccol, 0] = (int)(uint)' ';
  1361. } else {
  1362. OutputBuffer [position].Char.UnicodeChar = (char)rune.Value;
  1363. contents [crow, ccol, 0] = (int)(uint)rune.Value;
  1364. }
  1365. OutputBuffer [position].Attributes = (ushort)CurrentAttribute;
  1366. contents [crow, ccol, 1] = CurrentAttribute;
  1367. contents [crow, ccol, 2] = 1;
  1368. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  1369. }
  1370. }
  1371. if (runeWidth < 0 || runeWidth > 0) {
  1372. ccol++;
  1373. }
  1374. if (runeWidth > 1) {
  1375. if (validClip && ccol < Clip.Right) {
  1376. position = GetOutputBufferPosition ();
  1377. OutputBuffer [position].Attributes = (ushort)CurrentAttribute;
  1378. OutputBuffer [position].Char.UnicodeChar = (char)0x00;
  1379. contents [crow, ccol, 0] = (int)(uint)0x00;
  1380. contents [crow, ccol, 1] = CurrentAttribute;
  1381. contents [crow, ccol, 2] = 0;
  1382. }
  1383. ccol++;
  1384. }
  1385. if (sync) {
  1386. UpdateScreen ();
  1387. }
  1388. }
  1389. public override void AddStr (string str)
  1390. {
  1391. foreach (var rune in str.EnumerateRunes ())
  1392. AddRune (rune);
  1393. }
  1394. public override void SetAttribute (Attribute c)
  1395. {
  1396. base.SetAttribute (c);
  1397. }
  1398. public override Attribute MakeColor (Color foreground, Color background)
  1399. {
  1400. return MakeColor ((ConsoleColor)foreground, (ConsoleColor)background);
  1401. }
  1402. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  1403. {
  1404. // Encode the colors into the int value.
  1405. return new Attribute (
  1406. value: ((int)f | (int)b << 4),
  1407. foreground: (Color)f,
  1408. background: (Color)b
  1409. );
  1410. }
  1411. public override Attribute MakeAttribute (Color fore, Color back)
  1412. {
  1413. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  1414. }
  1415. public override void Refresh ()
  1416. {
  1417. UpdateScreen ();
  1418. WinConsole.SetInitialCursorVisibility ();
  1419. UpdateCursor ();
  1420. #if false
  1421. var bufferCoords = new WindowsConsole.Coord (){
  1422. X = (short)Clip.Width,
  1423. Y = (short)Clip.Height
  1424. };
  1425. var window = new WindowsConsole.SmallRect (){
  1426. Top = 0,
  1427. Left = 0,
  1428. Right = (short)Clip.Right,
  1429. Bottom = (short)Clip.Bottom
  1430. };
  1431. UpdateCursor();
  1432. WinConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  1433. #endif
  1434. }
  1435. public override void UpdateScreen ()
  1436. {
  1437. if (damageRegion.Left == -1)
  1438. return;
  1439. if (!EnableConsoleScrolling) {
  1440. var windowSize = WinConsole.GetConsoleBufferWindow (out _);
  1441. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows))
  1442. return;
  1443. }
  1444. var bufferCoords = new WindowsConsole.Coord () {
  1445. X = (short)Clip.Width,
  1446. Y = (short)Clip.Height
  1447. };
  1448. //var window = new WindowsConsole.SmallRect () {
  1449. // Top = 0,
  1450. // Left = 0,
  1451. // Right = (short)Clip.Right,
  1452. // Bottom = (short)Clip.Bottom
  1453. //};
  1454. WinConsole.WriteToConsole (new Size (Cols, Rows), OutputBuffer, bufferCoords, damageRegion);
  1455. // System.Diagnostics.Debugger.Log (0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  1456. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1457. }
  1458. CursorVisibility savedCursorVisibility;
  1459. public override void UpdateCursor ()
  1460. {
  1461. if (ccol < 0 || crow < 0 || ccol > Cols || crow > Rows) {
  1462. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1463. savedCursorVisibility = cursorVisibility;
  1464. SetCursorVisibility (CursorVisibility.Invisible);
  1465. return;
  1466. }
  1467. SetCursorVisibility (savedCursorVisibility);
  1468. var position = new WindowsConsole.Coord () {
  1469. X = (short)ccol,
  1470. Y = (short)crow
  1471. };
  1472. WinConsole.SetCursorPosition (position);
  1473. }
  1474. public override void End ()
  1475. {
  1476. WinConsole.Cleanup ();
  1477. WinConsole = null;
  1478. // Needed for Windows Terminal
  1479. // Clear the alternative screen buffer from the cursor to the
  1480. // end of the screen.
  1481. // Note, [3J causes Windows Terminal to wipe out the entire NON ALTERNATIVE
  1482. // backbuffer! So we need to use [0J instead.
  1483. Console.Out.Write ("\x1b[0J");
  1484. // Disable alternative screen buffer.
  1485. Console.Out.Write ("\x1b[?1047l");
  1486. // Console.Out.Flush () is not needed. See https://stackoverflow.com/a/20450486/297526
  1487. }
  1488. /// <inheritdoc/>
  1489. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1490. {
  1491. return WinConsole.GetCursorVisibility (out visibility);
  1492. }
  1493. /// <inheritdoc/>
  1494. public override bool SetCursorVisibility (CursorVisibility visibility)
  1495. {
  1496. savedCursorVisibility = visibility;
  1497. return WinConsole.SetCursorVisibility (visibility);
  1498. }
  1499. /// <inheritdoc/>
  1500. public override bool EnsureCursorVisibility ()
  1501. {
  1502. return WinConsole.EnsureCursorVisibility ();
  1503. }
  1504. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1505. {
  1506. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1507. EventType = WindowsConsole.EventType.Key
  1508. };
  1509. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1510. bKeyDown = true
  1511. };
  1512. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1513. if (shift) {
  1514. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1515. keyEvent.UnicodeChar = '\0';
  1516. keyEvent.wVirtualKeyCode = 16;
  1517. }
  1518. if (alt) {
  1519. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1520. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1521. keyEvent.UnicodeChar = '\0';
  1522. keyEvent.wVirtualKeyCode = 18;
  1523. }
  1524. if (control) {
  1525. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1526. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1527. keyEvent.UnicodeChar = '\0';
  1528. keyEvent.wVirtualKeyCode = 17;
  1529. }
  1530. keyEvent.dwControlKeyState = controlKey;
  1531. input.KeyEvent = keyEvent;
  1532. if (shift || alt || control) {
  1533. ProcessInput (input);
  1534. }
  1535. keyEvent.UnicodeChar = keyChar;
  1536. if ((uint)key < 255) {
  1537. keyEvent.wVirtualKeyCode = (ushort)key;
  1538. } else {
  1539. keyEvent.wVirtualKeyCode = '\0';
  1540. }
  1541. input.KeyEvent = keyEvent;
  1542. try {
  1543. ProcessInput (input);
  1544. } catch (OverflowException) { } finally {
  1545. keyEvent.bKeyDown = false;
  1546. input.KeyEvent = keyEvent;
  1547. ProcessInput (input);
  1548. }
  1549. }
  1550. public override bool GetColors (int value, out Color foreground, out Color background)
  1551. {
  1552. bool hasColor = false;
  1553. foreground = default;
  1554. background = default;
  1555. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  1556. .OfType<ConsoleColor> ()
  1557. .Select (s => (int)s);
  1558. if (values.Contains ((value >> 4) & 0xffff)) {
  1559. hasColor = true;
  1560. background = (Color)(ConsoleColor)((value >> 4) & 0xffff);
  1561. }
  1562. if (values.Contains (value - ((int)background << 4))) {
  1563. hasColor = true;
  1564. foreground = (Color)(ConsoleColor)(value - ((int)background << 4));
  1565. }
  1566. return hasColor;
  1567. }
  1568. #region Unused
  1569. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1570. {
  1571. }
  1572. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1573. {
  1574. }
  1575. public override void Suspend ()
  1576. {
  1577. }
  1578. public override void StartReportingMouseMoves ()
  1579. {
  1580. }
  1581. public override void StopReportingMouseMoves ()
  1582. {
  1583. }
  1584. public override void UncookMouse ()
  1585. {
  1586. }
  1587. public override void CookMouse ()
  1588. {
  1589. }
  1590. #endregion
  1591. }
  1592. /// <summary>
  1593. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1594. /// only be used on Windows.
  1595. /// </summary>
  1596. /// <remarks>
  1597. /// This implementation is used for WindowsDriver.
  1598. /// </remarks>
  1599. internal class WindowsMainLoop : IMainLoopDriver {
  1600. ManualResetEventSlim eventReady = new ManualResetEventSlim (false);
  1601. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  1602. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  1603. MainLoop mainLoop;
  1604. ConsoleDriver consoleDriver;
  1605. WindowsConsole winConsole;
  1606. bool winChanged;
  1607. Size windowSize;
  1608. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  1609. // The records that we keep fetching
  1610. Queue<WindowsConsole.InputRecord []> resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1611. /// <summary>
  1612. /// Invoked when a Key is pressed or released.
  1613. /// </summary>
  1614. public Action<WindowsConsole.InputRecord> ProcessInput;
  1615. /// <summary>
  1616. /// Invoked when the window is changed.
  1617. /// </summary>
  1618. public EventHandler<SizeChangedEventArgs> WinChanged;
  1619. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1620. {
  1621. this.consoleDriver = consoleDriver ?? throw new ArgumentNullException ("Console driver instance must be provided.");
  1622. winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1623. }
  1624. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1625. {
  1626. this.mainLoop = mainLoop;
  1627. Task.Run (WindowsInputHandler);
  1628. Task.Run (CheckWinChange);
  1629. }
  1630. void WindowsInputHandler ()
  1631. {
  1632. while (true) {
  1633. waitForProbe.Wait ();
  1634. waitForProbe.Reset ();
  1635. if (resultQueue?.Count == 0) {
  1636. resultQueue.Enqueue (winConsole.ReadConsoleInput ());
  1637. }
  1638. eventReady.Set ();
  1639. }
  1640. }
  1641. void CheckWinChange ()
  1642. {
  1643. while (true) {
  1644. winChange.Wait ();
  1645. winChange.Reset ();
  1646. WaitWinChange ();
  1647. winChanged = true;
  1648. eventReady.Set ();
  1649. }
  1650. }
  1651. void WaitWinChange ()
  1652. {
  1653. while (true) {
  1654. Thread.Sleep (100);
  1655. if (!consoleDriver.EnableConsoleScrolling) {
  1656. windowSize = winConsole.GetConsoleBufferWindow (out _);
  1657. //System.Diagnostics.Debug.WriteLine ($"{consoleDriver.EnableConsoleScrolling},{windowSize.Width},{windowSize.Height}");
  1658. if (windowSize != Size.Empty && windowSize.Width != consoleDriver.Cols
  1659. || windowSize.Height != consoleDriver.Rows) {
  1660. return;
  1661. }
  1662. }
  1663. }
  1664. }
  1665. void IMainLoopDriver.Wakeup ()
  1666. {
  1667. //tokenSource.Cancel ();
  1668. eventReady.Set ();
  1669. }
  1670. bool IMainLoopDriver.EventsPending (bool wait)
  1671. {
  1672. waitForProbe.Set ();
  1673. winChange.Set ();
  1674. if (CheckTimers (wait, out var waitTimeout)) {
  1675. return true;
  1676. }
  1677. try {
  1678. if (!tokenSource.IsCancellationRequested) {
  1679. eventReady.Wait (waitTimeout, tokenSource.Token);
  1680. }
  1681. } catch (OperationCanceledException) {
  1682. return true;
  1683. } finally {
  1684. eventReady.Reset ();
  1685. }
  1686. if (!tokenSource.IsCancellationRequested) {
  1687. return resultQueue.Count > 0 || CheckTimers (wait, out _) || winChanged;
  1688. }
  1689. tokenSource.Dispose ();
  1690. tokenSource = new CancellationTokenSource ();
  1691. return true;
  1692. }
  1693. bool CheckTimers (bool wait, out int waitTimeout)
  1694. {
  1695. long now = DateTime.UtcNow.Ticks;
  1696. if (mainLoop.timeouts.Count > 0) {
  1697. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1698. if (waitTimeout < 0)
  1699. return true;
  1700. } else {
  1701. waitTimeout = -1;
  1702. }
  1703. if (!wait)
  1704. waitTimeout = 0;
  1705. int ic;
  1706. lock (mainLoop.idleHandlers) {
  1707. ic = mainLoop.idleHandlers.Count;
  1708. }
  1709. return ic > 0;
  1710. }
  1711. void IMainLoopDriver.Iteration ()
  1712. {
  1713. while (resultQueue.Count > 0) {
  1714. var inputRecords = resultQueue.Dequeue ();
  1715. if (inputRecords != null && inputRecords.Length > 0) {
  1716. var inputEvent = inputRecords [0];
  1717. ProcessInput?.Invoke (inputEvent);
  1718. }
  1719. }
  1720. if (winChanged) {
  1721. winChanged = false;
  1722. WinChanged?.Invoke (this, new SizeChangedEventArgs (windowSize));
  1723. }
  1724. }
  1725. }
  1726. class WindowsClipboard : ClipboardBase {
  1727. public WindowsClipboard ()
  1728. {
  1729. IsSupported = IsClipboardFormatAvailable (cfUnicodeText);
  1730. }
  1731. public override bool IsSupported { get; }
  1732. protected override string GetClipboardDataImpl ()
  1733. {
  1734. try {
  1735. if (!OpenClipboard (IntPtr.Zero)) {
  1736. return string.Empty;
  1737. }
  1738. IntPtr handle = GetClipboardData (cfUnicodeText);
  1739. if (handle == IntPtr.Zero) {
  1740. return string.Empty;
  1741. }
  1742. IntPtr pointer = IntPtr.Zero;
  1743. try {
  1744. pointer = GlobalLock (handle);
  1745. if (pointer == IntPtr.Zero) {
  1746. return string.Empty;
  1747. }
  1748. int size = GlobalSize (handle);
  1749. byte [] buff = new byte [size];
  1750. Marshal.Copy (pointer, buff, 0, size);
  1751. return Encoding.Unicode.GetString (buff).TrimEnd ('\0');
  1752. } finally {
  1753. if (pointer != IntPtr.Zero) {
  1754. GlobalUnlock (handle);
  1755. }
  1756. }
  1757. } finally {
  1758. CloseClipboard ();
  1759. }
  1760. }
  1761. protected override void SetClipboardDataImpl (string text)
  1762. {
  1763. OpenClipboard ();
  1764. EmptyClipboard ();
  1765. IntPtr hGlobal = default;
  1766. try {
  1767. var bytes = (text.Length + 1) * 2;
  1768. hGlobal = Marshal.AllocHGlobal (bytes);
  1769. if (hGlobal == default) {
  1770. ThrowWin32 ();
  1771. }
  1772. var target = GlobalLock (hGlobal);
  1773. if (target == default) {
  1774. ThrowWin32 ();
  1775. }
  1776. try {
  1777. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1778. } finally {
  1779. GlobalUnlock (target);
  1780. }
  1781. if (SetClipboardData (cfUnicodeText, hGlobal) == default) {
  1782. ThrowWin32 ();
  1783. }
  1784. hGlobal = default;
  1785. } finally {
  1786. if (hGlobal != default) {
  1787. Marshal.FreeHGlobal (hGlobal);
  1788. }
  1789. CloseClipboard ();
  1790. }
  1791. }
  1792. void OpenClipboard ()
  1793. {
  1794. var num = 10;
  1795. while (true) {
  1796. if (OpenClipboard (default)) {
  1797. break;
  1798. }
  1799. if (--num == 0) {
  1800. ThrowWin32 ();
  1801. }
  1802. Thread.Sleep (100);
  1803. }
  1804. }
  1805. const uint cfUnicodeText = 13;
  1806. void ThrowWin32 ()
  1807. {
  1808. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1809. }
  1810. [DllImport ("User32.dll", SetLastError = true)]
  1811. [return: MarshalAs (UnmanagedType.Bool)]
  1812. static extern bool IsClipboardFormatAvailable (uint format);
  1813. [DllImport ("kernel32.dll", SetLastError = true)]
  1814. static extern int GlobalSize (IntPtr handle);
  1815. [DllImport ("kernel32.dll", SetLastError = true)]
  1816. static extern IntPtr GlobalLock (IntPtr hMem);
  1817. [DllImport ("kernel32.dll", SetLastError = true)]
  1818. [return: MarshalAs (UnmanagedType.Bool)]
  1819. static extern bool GlobalUnlock (IntPtr hMem);
  1820. [DllImport ("user32.dll", SetLastError = true)]
  1821. [return: MarshalAs (UnmanagedType.Bool)]
  1822. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1823. [DllImport ("user32.dll", SetLastError = true)]
  1824. [return: MarshalAs (UnmanagedType.Bool)]
  1825. static extern bool CloseClipboard ();
  1826. [DllImport ("user32.dll", SetLastError = true)]
  1827. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1828. [DllImport ("user32.dll")]
  1829. static extern bool EmptyClipboard ();
  1830. [DllImport ("user32.dll", SetLastError = true)]
  1831. static extern IntPtr GetClipboardData (uint uFormat);
  1832. }
  1833. }