WindowsDriver.cs 63 KB

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