WindowsDriver.cs 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093
  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 (ScreenBuffer, 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 (OutputHandle, 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 ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock)
  464. {
  465. this.consoleKeyInfo = consoleKeyInfo;
  466. CapsLock = capslock;
  467. NumLock = numlock;
  468. }
  469. }
  470. [DllImport ("kernel32.dll", SetLastError = true)]
  471. static extern IntPtr GetStdHandle (int nStdHandle);
  472. [DllImport ("kernel32.dll", SetLastError = true)]
  473. static extern bool CloseHandle (IntPtr handle);
  474. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  475. public static extern bool ReadConsoleInput (
  476. IntPtr hConsoleInput,
  477. IntPtr lpBuffer,
  478. uint nLength,
  479. out uint lpNumberOfEventsRead);
  480. [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  481. static extern bool ReadConsoleOutput (
  482. IntPtr hConsoleOutput,
  483. [Out] CharInfo [] lpBuffer,
  484. Coord dwBufferSize,
  485. Coord dwBufferCoord,
  486. ref SmallRect lpReadRegion
  487. );
  488. [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutput", SetLastError = true, CharSet = CharSet.Unicode)]
  489. static extern bool WriteConsoleOutput (
  490. IntPtr hConsoleOutput,
  491. CharInfo [] lpBuffer,
  492. Coord dwBufferSize,
  493. Coord dwBufferCoord,
  494. ref SmallRect lpWriteRegion
  495. );
  496. [DllImport ("kernel32.dll")]
  497. static extern bool SetConsoleCursorPosition (IntPtr hConsoleOutput, Coord dwCursorPosition);
  498. [StructLayout (LayoutKind.Sequential)]
  499. public struct ConsoleCursorInfo {
  500. public uint dwSize;
  501. public bool bVisible;
  502. }
  503. [DllImport ("kernel32.dll", SetLastError = true)]
  504. static extern bool SetConsoleCursorInfo (IntPtr hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
  505. [DllImport ("kernel32.dll", SetLastError = true)]
  506. static extern bool GetConsoleCursorInfo (IntPtr hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
  507. [DllImport ("kernel32.dll")]
  508. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  509. [DllImport ("kernel32.dll")]
  510. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  511. [DllImport ("kernel32.dll", SetLastError = true)]
  512. static extern IntPtr CreateConsoleScreenBuffer (
  513. DesiredAccess dwDesiredAccess,
  514. ShareMode dwShareMode,
  515. IntPtr secutiryAttributes,
  516. uint flags,
  517. IntPtr screenBufferData
  518. );
  519. internal static IntPtr INVALID_HANDLE_VALUE = new IntPtr (-1);
  520. [DllImport ("kernel32.dll", SetLastError = true)]
  521. static extern bool SetConsoleActiveScreenBuffer (IntPtr Handle);
  522. [DllImport ("kernel32.dll", SetLastError = true)]
  523. static extern bool GetNumberOfConsoleInputEvents (IntPtr handle, out uint lpcNumberOfEvents);
  524. public uint InputEventCount {
  525. get {
  526. GetNumberOfConsoleInputEvents (InputHandle, out uint v);
  527. return v;
  528. }
  529. }
  530. public InputRecord [] ReadConsoleInput ()
  531. {
  532. const int bufferSize = 1;
  533. var pRecord = Marshal.AllocHGlobal (Marshal.SizeOf<InputRecord> () * bufferSize);
  534. try {
  535. ReadConsoleInput (InputHandle, pRecord, bufferSize,
  536. out var numberEventsRead);
  537. return numberEventsRead == 0
  538. ? null
  539. : new [] { Marshal.PtrToStructure<InputRecord> (pRecord) };
  540. } catch (Exception) {
  541. return null;
  542. } finally {
  543. Marshal.FreeHGlobal (pRecord);
  544. }
  545. }
  546. #if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
  547. [DllImport ("kernel32.dll", ExactSpelling = true)]
  548. static extern IntPtr GetConsoleWindow ();
  549. [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  550. static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
  551. public const int HIDE = 0;
  552. public const int MAXIMIZE = 3;
  553. public const int MINIMIZE = 6;
  554. public const int RESTORE = 9;
  555. internal void ShowWindow (int state)
  556. {
  557. IntPtr thisConsole = GetConsoleWindow ();
  558. ShowWindow (thisConsole, state);
  559. }
  560. #endif
  561. // See: https://github.com/gui-cs/Terminal.Gui/issues/357
  562. [StructLayout (LayoutKind.Sequential)]
  563. public struct CONSOLE_SCREEN_BUFFER_INFOEX {
  564. public uint cbSize;
  565. public Coord dwSize;
  566. public Coord dwCursorPosition;
  567. public ushort wAttributes;
  568. public SmallRect srWindow;
  569. public Coord dwMaximumWindowSize;
  570. public ushort wPopupAttributes;
  571. public bool bFullscreenSupported;
  572. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)]
  573. public COLORREF [] ColorTable;
  574. }
  575. [StructLayout (LayoutKind.Explicit, Size = 4)]
  576. public struct COLORREF {
  577. public COLORREF (byte r, byte g, byte b)
  578. {
  579. Value = 0;
  580. R = r;
  581. G = g;
  582. B = b;
  583. }
  584. public COLORREF (uint value)
  585. {
  586. R = 0;
  587. G = 0;
  588. B = 0;
  589. Value = value & 0x00FFFFFF;
  590. }
  591. [FieldOffset (0)]
  592. public byte R;
  593. [FieldOffset (1)]
  594. public byte G;
  595. [FieldOffset (2)]
  596. public byte B;
  597. [FieldOffset (0)]
  598. public uint Value;
  599. }
  600. [DllImport ("kernel32.dll", SetLastError = true)]
  601. static extern bool GetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  602. [DllImport ("kernel32.dll", SetLastError = true)]
  603. static extern bool SetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo);
  604. [DllImport ("kernel32.dll", SetLastError = true)]
  605. static extern bool SetConsoleWindowInfo (
  606. IntPtr hConsoleOutput,
  607. bool bAbsolute,
  608. [In] ref SmallRect lpConsoleWindow);
  609. [DllImport ("kernel32.dll", SetLastError = true)]
  610. static extern Coord GetLargestConsoleWindowSize (
  611. IntPtr hConsoleOutput);
  612. }
  613. internal class WindowsDriver : ConsoleDriver {
  614. static bool sync = false;
  615. WindowsConsole.CharInfo [] OutputBuffer;
  616. int cols, rows, left, top;
  617. WindowsConsole.SmallRect damageRegion;
  618. IClipboard clipboard;
  619. int [,,] contents;
  620. public override int Cols => cols;
  621. public override int Rows => rows;
  622. public override int Left => left;
  623. public override int Top => top;
  624. public override bool HeightAsBuffer { get; set; }
  625. public override IClipboard Clipboard => clipboard;
  626. public override int [,,] Contents => contents;
  627. public WindowsConsole WinConsole { get; private set; }
  628. Action<KeyEvent> keyHandler;
  629. Action<KeyEvent> keyDownHandler;
  630. Action<KeyEvent> keyUpHandler;
  631. Action<MouseEvent> mouseHandler;
  632. public WindowsDriver ()
  633. {
  634. WinConsole = new WindowsConsole ();
  635. clipboard = new WindowsClipboard ();
  636. }
  637. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  638. {
  639. this.keyHandler = keyHandler;
  640. this.keyDownHandler = keyDownHandler;
  641. this.keyUpHandler = keyUpHandler;
  642. this.mouseHandler = mouseHandler;
  643. var mLoop = mainLoop.Driver as WindowsMainLoop;
  644. mLoop.ProcessInput = (e) => ProcessInput (e);
  645. mLoop.WinChanged = (e) => {
  646. ChangeWin (e);
  647. };
  648. }
  649. private void ChangeWin (Size e)
  650. {
  651. if (!HeightAsBuffer) {
  652. var w = e.Width;
  653. if (w == cols - 3 && e.Height < rows) {
  654. w += 3;
  655. }
  656. var newSize = WinConsole.SetConsoleWindow (
  657. (short)Math.Max (w, 16), (short)Math.Max (e.Height, 1));
  658. left = 0;
  659. top = 0;
  660. cols = newSize.Width;
  661. rows = newSize.Height;
  662. ResizeScreen ();
  663. UpdateOffScreen ();
  664. TerminalResized.Invoke ();
  665. }
  666. }
  667. void ProcessInput (WindowsConsole.InputRecord inputEvent)
  668. {
  669. switch (inputEvent.EventType) {
  670. case WindowsConsole.EventType.Key:
  671. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  672. if (map == (Key)0xffffffff) {
  673. KeyEvent key = new KeyEvent ();
  674. // Shift = VK_SHIFT = 0x10
  675. // Ctrl = VK_CONTROL = 0x11
  676. // Alt = VK_MENU = 0x12
  677. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
  678. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
  679. }
  680. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
  681. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
  682. }
  683. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
  684. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
  685. }
  686. switch (inputEvent.KeyEvent.dwControlKeyState) {
  687. case WindowsConsole.ControlKeyState.RightAltPressed:
  688. case WindowsConsole.ControlKeyState.RightAltPressed |
  689. WindowsConsole.ControlKeyState.LeftControlPressed |
  690. WindowsConsole.ControlKeyState.EnhancedKey:
  691. case WindowsConsole.ControlKeyState.EnhancedKey:
  692. key = new KeyEvent (Key.CtrlMask | Key.AltMask, keyModifiers);
  693. break;
  694. case WindowsConsole.ControlKeyState.LeftAltPressed:
  695. key = new KeyEvent (Key.AltMask, keyModifiers);
  696. break;
  697. case WindowsConsole.ControlKeyState.RightControlPressed:
  698. case WindowsConsole.ControlKeyState.LeftControlPressed:
  699. key = new KeyEvent (Key.CtrlMask, keyModifiers);
  700. break;
  701. case WindowsConsole.ControlKeyState.ShiftPressed:
  702. key = new KeyEvent (Key.ShiftMask, keyModifiers);
  703. break;
  704. case WindowsConsole.ControlKeyState.NumlockOn:
  705. break;
  706. case WindowsConsole.ControlKeyState.ScrolllockOn:
  707. break;
  708. case WindowsConsole.ControlKeyState.CapslockOn:
  709. break;
  710. default:
  711. switch (inputEvent.KeyEvent.wVirtualKeyCode) {
  712. case 0x10:
  713. key = new KeyEvent (Key.ShiftMask, keyModifiers);
  714. break;
  715. case 0x11:
  716. key = new KeyEvent (Key.CtrlMask, keyModifiers);
  717. break;
  718. case 0x12:
  719. key = new KeyEvent (Key.AltMask, keyModifiers);
  720. break;
  721. default:
  722. key = new KeyEvent (Key.Unknown, keyModifiers);
  723. break;
  724. }
  725. break;
  726. }
  727. if (inputEvent.KeyEvent.bKeyDown)
  728. keyDownHandler (key);
  729. else
  730. keyUpHandler (key);
  731. } else {
  732. if (inputEvent.KeyEvent.bKeyDown) {
  733. // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
  734. keyDownHandler (new KeyEvent (map, keyModifiers));
  735. keyHandler (new KeyEvent (map, keyModifiers));
  736. } else {
  737. keyUpHandler (new KeyEvent (map, keyModifiers));
  738. }
  739. }
  740. if (!inputEvent.KeyEvent.bKeyDown) {
  741. keyModifiers = null;
  742. }
  743. break;
  744. case WindowsConsole.EventType.Mouse:
  745. var me = ToDriverMouse (inputEvent.MouseEvent);
  746. mouseHandler (me);
  747. if (processButtonClick) {
  748. mouseHandler (
  749. new MouseEvent () {
  750. X = me.X,
  751. Y = me.Y,
  752. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  753. });
  754. }
  755. break;
  756. case WindowsConsole.EventType.WindowBufferSize:
  757. var winSize = WinConsole.GetConsoleBufferWindow (out Point pos);
  758. left = pos.X;
  759. top = pos.Y;
  760. cols = inputEvent.WindowBufferSizeEvent.size.X;
  761. rows = inputEvent.WindowBufferSizeEvent.size.Y;
  762. //System.Diagnostics.Debug.WriteLine ($"{HeightAsBuffer},{cols},{rows}");
  763. ResizeScreen ();
  764. UpdateOffScreen ();
  765. TerminalResized?.Invoke ();
  766. break;
  767. case WindowsConsole.EventType.Focus:
  768. break;
  769. }
  770. }
  771. WindowsConsole.ButtonState? lastMouseButtonPressed = null;
  772. bool isButtonPressed = false;
  773. bool isButtonReleased = false;
  774. bool isButtonDoubleClicked = false;
  775. Point? point;
  776. Point pointMove;
  777. //int buttonPressedCount;
  778. bool isOneFingerDoubleClicked = false;
  779. bool processButtonClick;
  780. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  781. {
  782. MouseFlags mouseFlag = MouseFlags.AllEvents;
  783. //System.Diagnostics.Debug.WriteLine (
  784. // $"X:{mouseEvent.MousePosition.X};Y:{mouseEvent.MousePosition.Y};ButtonState:{mouseEvent.ButtonState};EventFlags:{mouseEvent.EventFlags}");
  785. if (isButtonDoubleClicked || isOneFingerDoubleClicked) {
  786. Application.MainLoop.AddIdle (() => {
  787. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  788. return false;
  789. });
  790. }
  791. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  792. // This will tell when a mouse button is pressed. When the button is released this event will
  793. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  794. // To map to the correct driver events we save the last pressed mouse button so we can
  795. // map to the correct clicked event.
  796. if ((lastMouseButtonPressed != null || isButtonReleased) && mouseEvent.ButtonState != 0) {
  797. lastMouseButtonPressed = null;
  798. //isButtonPressed = false;
  799. isButtonReleased = false;
  800. }
  801. var p = new Point () {
  802. X = mouseEvent.MousePosition.X,
  803. Y = mouseEvent.MousePosition.Y
  804. };
  805. //if (!isButtonPressed && buttonPressedCount < 2
  806. // && mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  807. // && (mouseEvent.ButtonState == WindowsConsole.ButtonState.Button1Pressed
  808. // || mouseEvent.ButtonState == WindowsConsole.ButtonState.Button2Pressed
  809. // || mouseEvent.ButtonState == WindowsConsole.ButtonState.Button3Pressed)) {
  810. // lastMouseButtonPressed = mouseEvent.ButtonState;
  811. // buttonPressedCount++;
  812. //} else if (!isButtonPressed && buttonPressedCount > 0 && mouseEvent.ButtonState == 0
  813. // && mouseEvent.EventFlags == 0) {
  814. // buttonPressedCount++;
  815. //}
  816. //System.Diagnostics.Debug.WriteLine ($"isButtonPressed: {isButtonPressed};buttonPressedCount: {buttonPressedCount};lastMouseButtonPressed: {lastMouseButtonPressed}");
  817. //System.Diagnostics.Debug.WriteLine ($"isOneFingerDoubleClicked: {isOneFingerDoubleClicked}");
  818. //if (buttonPressedCount == 1 && lastMouseButtonPressed != null && p == point
  819. // && lastMouseButtonPressed == WindowsConsole.ButtonState.Button1Pressed
  820. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button2Pressed
  821. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button3Pressed) {
  822. // switch (lastMouseButtonPressed) {
  823. // case WindowsConsole.ButtonState.Button1Pressed:
  824. // mouseFlag = MouseFlags.Button1DoubleClicked;
  825. // break;
  826. // case WindowsConsole.ButtonState.Button2Pressed:
  827. // mouseFlag = MouseFlags.Button2DoubleClicked;
  828. // break;
  829. // case WindowsConsole.ButtonState.Button3Pressed:
  830. // mouseFlag = MouseFlags.Button3DoubleClicked;
  831. // break;
  832. // }
  833. // isOneFingerDoubleClicked = true;
  834. //} else if (buttonPressedCount == 3 && lastMouseButtonPressed != null && isOneFingerDoubleClicked && p == point
  835. // && lastMouseButtonPressed == WindowsConsole.ButtonState.Button1Pressed
  836. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button2Pressed
  837. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button3Pressed) {
  838. // switch (lastMouseButtonPressed) {
  839. // case WindowsConsole.ButtonState.Button1Pressed:
  840. // mouseFlag = MouseFlags.Button1TripleClicked;
  841. // break;
  842. // case WindowsConsole.ButtonState.Button2Pressed:
  843. // mouseFlag = MouseFlags.Button2TripleClicked;
  844. // break;
  845. // case WindowsConsole.ButtonState.Button3Pressed:
  846. // mouseFlag = MouseFlags.Button3TripleClicked;
  847. // break;
  848. // }
  849. // buttonPressedCount = 0;
  850. // lastMouseButtonPressed = null;
  851. // isOneFingerDoubleClicked = false;
  852. // isButtonReleased = false;
  853. //}
  854. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && lastMouseButtonPressed == null && !isButtonDoubleClicked) ||
  855. (lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) &&
  856. mouseEvent.ButtonState != 0 && !isButtonReleased && !isButtonDoubleClicked)) {
  857. switch (mouseEvent.ButtonState) {
  858. case WindowsConsole.ButtonState.Button1Pressed:
  859. mouseFlag = MouseFlags.Button1Pressed;
  860. break;
  861. case WindowsConsole.ButtonState.Button2Pressed:
  862. mouseFlag = MouseFlags.Button2Pressed;
  863. break;
  864. case WindowsConsole.ButtonState.RightmostButtonPressed:
  865. mouseFlag = MouseFlags.Button3Pressed;
  866. break;
  867. }
  868. if (point == null)
  869. point = p;
  870. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  871. mouseFlag |= MouseFlags.ReportMousePosition;
  872. isButtonReleased = false;
  873. processButtonClick = false;
  874. }
  875. lastMouseButtonPressed = mouseEvent.ButtonState;
  876. isButtonPressed = true;
  877. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  878. Application.MainLoop.AddIdle (() => {
  879. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  880. return false;
  881. });
  882. }
  883. } else if (lastMouseButtonPressed != null && mouseEvent.EventFlags == 0
  884. && !isButtonReleased && !isButtonDoubleClicked && !isOneFingerDoubleClicked) {
  885. switch (lastMouseButtonPressed) {
  886. case WindowsConsole.ButtonState.Button1Pressed:
  887. mouseFlag = MouseFlags.Button1Released;
  888. break;
  889. case WindowsConsole.ButtonState.Button2Pressed:
  890. mouseFlag = MouseFlags.Button2Released;
  891. break;
  892. case WindowsConsole.ButtonState.RightmostButtonPressed:
  893. mouseFlag = MouseFlags.Button3Released;
  894. break;
  895. }
  896. isButtonPressed = false;
  897. isButtonReleased = true;
  898. if (point != null && (((Point)point).X == mouseEvent.MousePosition.X && ((Point)point).Y == mouseEvent.MousePosition.Y)) {
  899. processButtonClick = true;
  900. } else {
  901. point = null;
  902. }
  903. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  904. && !isOneFingerDoubleClicked && isButtonReleased && p == point) {
  905. mouseFlag = ProcessButtonClick (mouseEvent);
  906. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  907. switch (mouseEvent.ButtonState) {
  908. case WindowsConsole.ButtonState.Button1Pressed:
  909. mouseFlag = MouseFlags.Button1DoubleClicked;
  910. break;
  911. case WindowsConsole.ButtonState.Button2Pressed:
  912. mouseFlag = MouseFlags.Button2DoubleClicked;
  913. break;
  914. case WindowsConsole.ButtonState.RightmostButtonPressed:
  915. mouseFlag = MouseFlags.Button3DoubleClicked;
  916. break;
  917. }
  918. isButtonDoubleClicked = true;
  919. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && isButtonDoubleClicked) {
  920. switch (mouseEvent.ButtonState) {
  921. case WindowsConsole.ButtonState.Button1Pressed:
  922. mouseFlag = MouseFlags.Button1TripleClicked;
  923. break;
  924. case WindowsConsole.ButtonState.Button2Pressed:
  925. mouseFlag = MouseFlags.Button2TripleClicked;
  926. break;
  927. case WindowsConsole.ButtonState.RightmostButtonPressed:
  928. mouseFlag = MouseFlags.Button3TripleClicked;
  929. break;
  930. }
  931. isButtonDoubleClicked = false;
  932. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  933. switch ((int)mouseEvent.ButtonState) {
  934. case int v when v > 0:
  935. mouseFlag = MouseFlags.WheeledUp;
  936. break;
  937. case int v when v < 0:
  938. mouseFlag = MouseFlags.WheeledDown;
  939. break;
  940. }
  941. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  942. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  943. switch ((int)mouseEvent.ButtonState) {
  944. case int v when v > 0:
  945. mouseFlag = MouseFlags.WheeledLeft;
  946. break;
  947. case int v when v < 0:
  948. mouseFlag = MouseFlags.WheeledRight;
  949. break;
  950. }
  951. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled) {
  952. switch ((int)mouseEvent.ButtonState) {
  953. case int v when v < 0:
  954. mouseFlag = MouseFlags.WheeledLeft;
  955. break;
  956. case int v when v > 0:
  957. mouseFlag = MouseFlags.WheeledRight;
  958. break;
  959. }
  960. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  961. if (mouseEvent.MousePosition.X != pointMove.X || mouseEvent.MousePosition.Y != pointMove.Y) {
  962. mouseFlag = MouseFlags.ReportMousePosition;
  963. pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  964. } else {
  965. mouseFlag = 0;
  966. }
  967. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  968. mouseFlag = 0;
  969. }
  970. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  971. //System.Diagnostics.Debug.WriteLine (
  972. // $"point.X:{(point != null ? ((Point)point).X : -1)};point.Y:{(point != null ? ((Point)point).Y : -1)}");
  973. return new MouseEvent () {
  974. X = mouseEvent.MousePosition.X,
  975. Y = mouseEvent.MousePosition.Y,
  976. Flags = mouseFlag
  977. };
  978. }
  979. MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  980. {
  981. MouseFlags mouseFlag = 0;
  982. switch (lastMouseButtonPressed) {
  983. case WindowsConsole.ButtonState.Button1Pressed:
  984. mouseFlag = MouseFlags.Button1Clicked;
  985. break;
  986. case WindowsConsole.ButtonState.Button2Pressed:
  987. mouseFlag = MouseFlags.Button2Clicked;
  988. break;
  989. case WindowsConsole.ButtonState.RightmostButtonPressed:
  990. mouseFlag = MouseFlags.Button3Clicked;
  991. break;
  992. }
  993. point = new Point () {
  994. X = mouseEvent.MousePosition.X,
  995. Y = mouseEvent.MousePosition.Y
  996. };
  997. lastMouseButtonPressed = null;
  998. isButtonReleased = false;
  999. processButtonClick = false;
  1000. point = null;
  1001. return mouseFlag;
  1002. }
  1003. async Task ProcessButtonDoubleClickedAsync ()
  1004. {
  1005. await Task.Delay (300);
  1006. isButtonDoubleClicked = false;
  1007. isOneFingerDoubleClicked = false;
  1008. //buttonPressedCount = 0;
  1009. }
  1010. async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1011. {
  1012. while (isButtonPressed) {
  1013. await Task.Delay (100);
  1014. var me = new MouseEvent () {
  1015. X = pointMove.X,
  1016. Y = pointMove.Y,
  1017. Flags = mouseFlag
  1018. };
  1019. var view = Application.WantContinuousButtonPressedView;
  1020. if (view == null) {
  1021. break;
  1022. }
  1023. if (isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1024. Application.MainLoop.Invoke (() => mouseHandler (me));
  1025. }
  1026. }
  1027. }
  1028. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1029. {
  1030. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  1031. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  1032. mouseFlag |= MouseFlags.ButtonCtrl;
  1033. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  1034. mouseFlag |= MouseFlags.ButtonShift;
  1035. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1036. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  1037. mouseFlag |= MouseFlags.ButtonAlt;
  1038. return mouseFlag;
  1039. }
  1040. KeyModifiers keyModifiers;
  1041. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1042. {
  1043. var state = keyEvent.dwControlKeyState;
  1044. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1045. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1046. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1047. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  1048. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  1049. bool scrolllock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  1050. if (keyModifiers == null)
  1051. keyModifiers = new KeyModifiers ();
  1052. if (shift)
  1053. keyModifiers.Shift = shift;
  1054. if (alt)
  1055. keyModifiers.Alt = alt;
  1056. if (control)
  1057. keyModifiers.Ctrl = control;
  1058. if (capslock)
  1059. keyModifiers.Capslock = capslock;
  1060. if (numlock)
  1061. keyModifiers.Numlock = numlock;
  1062. if (scrolllock)
  1063. keyModifiers.Scrolllock = scrolllock;
  1064. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1065. return new WindowsConsole.ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock);
  1066. }
  1067. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  1068. {
  1069. // If keystroke is a virtual key
  1070. if (keyInfoEx.consoleKeyInfo.Key == ConsoleKey.Packet) {
  1071. // try to map the 'char' that came with it into a Key
  1072. if (TryRemapPacketKey (keyInfoEx.consoleKeyInfo, out var result)) {
  1073. return result;
  1074. }
  1075. }
  1076. var keyInfo = keyInfoEx.consoleKeyInfo;
  1077. switch (keyInfo.Key) {
  1078. case ConsoleKey.Escape:
  1079. return MapKeyModifiers (keyInfo, Key.Esc);
  1080. case ConsoleKey.Tab:
  1081. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  1082. case ConsoleKey.Home:
  1083. return MapKeyModifiers (keyInfo, Key.Home);
  1084. case ConsoleKey.End:
  1085. return MapKeyModifiers (keyInfo, Key.End);
  1086. case ConsoleKey.LeftArrow:
  1087. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  1088. case ConsoleKey.RightArrow:
  1089. return MapKeyModifiers (keyInfo, Key.CursorRight);
  1090. case ConsoleKey.UpArrow:
  1091. return MapKeyModifiers (keyInfo, Key.CursorUp);
  1092. case ConsoleKey.DownArrow:
  1093. return MapKeyModifiers (keyInfo, Key.CursorDown);
  1094. case ConsoleKey.PageUp:
  1095. return MapKeyModifiers (keyInfo, Key.PageUp);
  1096. case ConsoleKey.PageDown:
  1097. return MapKeyModifiers (keyInfo, Key.PageDown);
  1098. case ConsoleKey.Enter:
  1099. return MapKeyModifiers (keyInfo, Key.Enter);
  1100. case ConsoleKey.Spacebar:
  1101. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  1102. case ConsoleKey.Backspace:
  1103. return MapKeyModifiers (keyInfo, Key.Backspace);
  1104. case ConsoleKey.Delete:
  1105. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  1106. case ConsoleKey.Insert:
  1107. return MapKeyModifiers (keyInfo, Key.InsertChar);
  1108. case ConsoleKey.NumPad0:
  1109. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  1110. case ConsoleKey.NumPad1:
  1111. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  1112. case ConsoleKey.NumPad2:
  1113. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  1114. case ConsoleKey.NumPad3:
  1115. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  1116. case ConsoleKey.NumPad4:
  1117. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  1118. case ConsoleKey.NumPad5:
  1119. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  1120. case ConsoleKey.NumPad6:
  1121. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  1122. case ConsoleKey.NumPad7:
  1123. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  1124. case ConsoleKey.NumPad8:
  1125. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  1126. case ConsoleKey.NumPad9:
  1127. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  1128. case ConsoleKey.Oem1:
  1129. case ConsoleKey.Oem2:
  1130. case ConsoleKey.Oem3:
  1131. case ConsoleKey.Oem4:
  1132. case ConsoleKey.Oem5:
  1133. case ConsoleKey.Oem6:
  1134. case ConsoleKey.Oem7:
  1135. case ConsoleKey.Oem8:
  1136. case ConsoleKey.Oem102:
  1137. case ConsoleKey.OemPeriod:
  1138. case ConsoleKey.OemComma:
  1139. case ConsoleKey.OemPlus:
  1140. case ConsoleKey.OemMinus:
  1141. if (keyInfo.KeyChar == 0)
  1142. return Key.Unknown;
  1143. return (Key)((uint)keyInfo.KeyChar);
  1144. }
  1145. var key = keyInfo.Key;
  1146. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  1147. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  1148. var delta = key - ConsoleKey.A;
  1149. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1150. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1151. }
  1152. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1153. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1154. }
  1155. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1156. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1157. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1158. }
  1159. }
  1160. //return (Key)((uint)alphaBase + delta);
  1161. return (Key)((uint)keyInfo.KeyChar);
  1162. }
  1163. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1164. var delta = key - ConsoleKey.D0;
  1165. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1166. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1167. }
  1168. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1169. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1170. }
  1171. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1172. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
  1173. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1174. }
  1175. }
  1176. return (Key)((uint)keyInfo.KeyChar);
  1177. }
  1178. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1179. var delta = key - ConsoleKey.F1;
  1180. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1181. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1182. }
  1183. return (Key)((uint)Key.F1 + delta);
  1184. }
  1185. if (keyInfo.KeyChar != 0) {
  1186. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1187. }
  1188. return (Key)(0xffffffff);
  1189. }
  1190. Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1191. {
  1192. Key keyMod = new Key ();
  1193. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
  1194. keyMod = Key.ShiftMask;
  1195. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
  1196. keyMod |= Key.CtrlMask;
  1197. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
  1198. keyMod |= Key.AltMask;
  1199. return keyMod != Key.Null ? keyMod | key : key;
  1200. }
  1201. public override void Init (Action terminalResized)
  1202. {
  1203. TerminalResized = terminalResized;
  1204. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1205. cols = winSize.Width;
  1206. rows = winSize.Height;
  1207. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1208. ResizeScreen ();
  1209. UpdateOffScreen ();
  1210. CreateColors ();
  1211. }
  1212. public override void ResizeScreen ()
  1213. {
  1214. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  1215. Clip = new Rect (0, 0, Cols, Rows);
  1216. damageRegion = new WindowsConsole.SmallRect () {
  1217. Top = 0,
  1218. Left = 0,
  1219. Bottom = (short)Rows,
  1220. Right = (short)Cols
  1221. };
  1222. WinConsole.ForceRefreshCursorVisibility ();
  1223. Console.Out.Write ("\x1b[3J");
  1224. Console.Out.Flush ();
  1225. }
  1226. public override void UpdateOffScreen ()
  1227. {
  1228. contents = new int [rows, cols, 3];
  1229. for (int row = 0; row < rows; row++) {
  1230. for (int col = 0; col < cols; col++) {
  1231. int position = row * cols + col;
  1232. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  1233. OutputBuffer [position].Char.UnicodeChar = ' ';
  1234. contents [row, col, 0] = OutputBuffer [position].Char.UnicodeChar;
  1235. contents [row, col, 1] = OutputBuffer [position].Attributes;
  1236. contents [row, col, 2] = 0;
  1237. }
  1238. }
  1239. }
  1240. int ccol, crow;
  1241. public override void Move (int col, int row)
  1242. {
  1243. ccol = col;
  1244. crow = row;
  1245. }
  1246. public override void AddRune (Rune rune)
  1247. {
  1248. rune = MakePrintable (rune);
  1249. var runeWidth = Rune.ColumnWidth (rune);
  1250. var position = crow * Cols + ccol;
  1251. var validClip = IsValidContent (ccol, crow, Clip);
  1252. if (validClip) {
  1253. if (runeWidth < 2 && ccol > 0
  1254. && Rune.ColumnWidth ((char)contents [crow, ccol - 1, 0]) > 1) {
  1255. var prevPosition = crow * Cols + (ccol - 1);
  1256. OutputBuffer [prevPosition].Char.UnicodeChar = ' ';
  1257. contents [crow, ccol - 1, 0] = (int)(uint)' ';
  1258. } else if (runeWidth < 2 && ccol <= Clip.Right - 1
  1259. && Rune.ColumnWidth ((char)contents [crow, ccol, 0]) > 1) {
  1260. var prevPosition = crow * Cols + ccol + 1;
  1261. OutputBuffer [prevPosition].Char.UnicodeChar = (char)' ';
  1262. contents [crow, ccol + 1, 0] = (int)(uint)' ';
  1263. }
  1264. if (runeWidth > 1 && ccol == Clip.Right - 1) {
  1265. OutputBuffer [position].Char.UnicodeChar = (char)' ';
  1266. contents [crow, ccol, 0] = (int)(uint)' ';
  1267. } else {
  1268. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  1269. contents [crow, ccol, 0] = (int)(uint)rune;
  1270. }
  1271. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  1272. contents [crow, ccol, 1] = currentAttribute;
  1273. contents [crow, ccol, 2] = 1;
  1274. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  1275. }
  1276. ccol++;
  1277. if (runeWidth > 1) {
  1278. if (validClip && ccol < Clip.Right) {
  1279. position = crow * Cols + ccol;
  1280. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  1281. OutputBuffer [position].Char.UnicodeChar = (char)0x00;
  1282. contents [crow, ccol, 0] = (int)(uint)0x00;
  1283. contents [crow, ccol, 1] = currentAttribute;
  1284. contents [crow, ccol, 2] = 0;
  1285. }
  1286. ccol++;
  1287. }
  1288. if (sync)
  1289. UpdateScreen ();
  1290. }
  1291. public override void AddStr (ustring str)
  1292. {
  1293. foreach (var rune in str)
  1294. AddRune (rune);
  1295. }
  1296. Attribute currentAttribute;
  1297. public override void SetAttribute (Attribute c)
  1298. {
  1299. currentAttribute = c;
  1300. }
  1301. public override Attribute MakeColor (Color foreground, Color background)
  1302. {
  1303. return MakeColor ((ConsoleColor)foreground, (ConsoleColor)background);
  1304. }
  1305. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  1306. {
  1307. // Encode the colors into the int value.
  1308. return new Attribute (
  1309. value: ((int)f | (int)b << 4),
  1310. foreground: (Color)f,
  1311. background: (Color)b
  1312. );
  1313. }
  1314. public override Attribute MakeAttribute (Color fore, Color back)
  1315. {
  1316. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  1317. }
  1318. public override void Refresh ()
  1319. {
  1320. UpdateScreen ();
  1321. WinConsole.SetInitialCursorVisibility ();
  1322. UpdateCursor ();
  1323. #if false
  1324. var bufferCoords = new WindowsConsole.Coord (){
  1325. X = (short)Clip.Width,
  1326. Y = (short)Clip.Height
  1327. };
  1328. var window = new WindowsConsole.SmallRect (){
  1329. Top = 0,
  1330. Left = 0,
  1331. Right = (short)Clip.Right,
  1332. Bottom = (short)Clip.Bottom
  1333. };
  1334. UpdateCursor();
  1335. WinConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  1336. #endif
  1337. }
  1338. public override void UpdateScreen ()
  1339. {
  1340. if (damageRegion.Left == -1)
  1341. return;
  1342. if (!HeightAsBuffer) {
  1343. var windowSize = WinConsole.GetConsoleBufferWindow (out _);
  1344. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows))
  1345. return;
  1346. }
  1347. var bufferCoords = new WindowsConsole.Coord () {
  1348. X = (short)Clip.Width,
  1349. Y = (short)Clip.Height
  1350. };
  1351. //var window = new WindowsConsole.SmallRect () {
  1352. // Top = 0,
  1353. // Left = 0,
  1354. // Right = (short)Clip.Right,
  1355. // Bottom = (short)Clip.Bottom
  1356. //};
  1357. WinConsole.WriteToConsole (new Size (Cols, Rows), OutputBuffer, bufferCoords, damageRegion);
  1358. // System.Diagnostics.Debugger.Log (0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  1359. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1360. }
  1361. CursorVisibility savedCursorVisibility;
  1362. public override void UpdateCursor ()
  1363. {
  1364. if (ccol < 0 || crow < 0 || ccol > Cols || crow > Rows) {
  1365. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1366. savedCursorVisibility = cursorVisibility;
  1367. SetCursorVisibility (CursorVisibility.Invisible);
  1368. return;
  1369. }
  1370. SetCursorVisibility (savedCursorVisibility);
  1371. var position = new WindowsConsole.Coord () {
  1372. X = (short)ccol,
  1373. Y = (short)crow
  1374. };
  1375. WinConsole.SetCursorPosition (position);
  1376. }
  1377. public override void End ()
  1378. {
  1379. WinConsole.Cleanup ();
  1380. WinConsole = null;
  1381. }
  1382. public override Attribute GetAttribute ()
  1383. {
  1384. return currentAttribute;
  1385. }
  1386. /// <inheritdoc/>
  1387. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1388. {
  1389. return WinConsole.GetCursorVisibility (out visibility);
  1390. }
  1391. /// <inheritdoc/>
  1392. public override bool SetCursorVisibility (CursorVisibility visibility)
  1393. {
  1394. savedCursorVisibility = visibility;
  1395. return WinConsole.SetCursorVisibility (visibility);
  1396. }
  1397. /// <inheritdoc/>
  1398. public override bool EnsureCursorVisibility ()
  1399. {
  1400. return WinConsole.EnsureCursorVisibility ();
  1401. }
  1402. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1403. {
  1404. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1405. EventType = WindowsConsole.EventType.Key
  1406. };
  1407. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1408. bKeyDown = true
  1409. };
  1410. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1411. if (shift) {
  1412. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1413. keyEvent.UnicodeChar = '\0';
  1414. keyEvent.wVirtualKeyCode = 16;
  1415. }
  1416. if (alt) {
  1417. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1418. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1419. keyEvent.UnicodeChar = '\0';
  1420. keyEvent.wVirtualKeyCode = 18;
  1421. }
  1422. if (control) {
  1423. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1424. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1425. keyEvent.UnicodeChar = '\0';
  1426. keyEvent.wVirtualKeyCode = 17;
  1427. }
  1428. keyEvent.dwControlKeyState = controlKey;
  1429. input.KeyEvent = keyEvent;
  1430. if (shift || alt || control) {
  1431. ProcessInput (input);
  1432. }
  1433. keyEvent.UnicodeChar = keyChar;
  1434. if ((shift || alt || control)
  1435. && (key >= ConsoleKey.A && key <= ConsoleKey.Z
  1436. || key >= ConsoleKey.D0 && key <= ConsoleKey.D9)) {
  1437. keyEvent.wVirtualKeyCode = (ushort)key;
  1438. } else {
  1439. keyEvent.wVirtualKeyCode = '\0';
  1440. }
  1441. input.KeyEvent = keyEvent;
  1442. try {
  1443. ProcessInput (input);
  1444. } catch (OverflowException) { } finally {
  1445. keyEvent.bKeyDown = false;
  1446. input.KeyEvent = keyEvent;
  1447. ProcessInput (input);
  1448. }
  1449. }
  1450. public override bool GetColors (int value, out Color foreground, out Color background)
  1451. {
  1452. bool hasColor = false;
  1453. foreground = default;
  1454. background = default;
  1455. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  1456. .OfType<ConsoleColor> ()
  1457. .Select (s => (int)s);
  1458. if (values.Contains ((value >> 4) & 0xffff)) {
  1459. hasColor = true;
  1460. background = (Color)(ConsoleColor)((value >> 4) & 0xffff);
  1461. }
  1462. if (values.Contains (value - ((int)background << 4))) {
  1463. hasColor = true;
  1464. foreground = (Color)(ConsoleColor)(value - ((int)background << 4));
  1465. }
  1466. return hasColor;
  1467. }
  1468. #region Unused
  1469. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1470. {
  1471. }
  1472. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1473. {
  1474. }
  1475. public override void Suspend ()
  1476. {
  1477. }
  1478. public override void StartReportingMouseMoves ()
  1479. {
  1480. }
  1481. public override void StopReportingMouseMoves ()
  1482. {
  1483. }
  1484. public override void UncookMouse ()
  1485. {
  1486. }
  1487. public override void CookMouse ()
  1488. {
  1489. }
  1490. /// <summary>
  1491. /// Handles case when the 'key' providied is <see cref="ConsoleKey.Packet"/>
  1492. /// returning a <see cref="Key"/> that reflects the unicode char that came with
  1493. /// the OS event.
  1494. /// </summary>
  1495. /// <exception cref="ArgumentException">Thrown if passed key was not a <see cref="ConsoleKey.Packet"/></exception>
  1496. internal static bool TryRemapPacketKey (ConsoleKeyInfo original, out Key result)
  1497. {
  1498. result = default (Key);
  1499. var c = original.KeyChar;
  1500. if (original.Key != ConsoleKey.Packet)
  1501. throw new ArgumentException ("Expected a ConsoleKeyInfo with a Key of Packet", nameof (original));
  1502. // there is no unicode value passed
  1503. if (c == '\0') {
  1504. return false;
  1505. }
  1506. // do not have a explicit mapping and char is nonzero so
  1507. // we can just treat the `Key` as a regular unicode entry
  1508. result = ApplyModifiers ((Key)c,original.Modifiers);
  1509. return true;
  1510. }
  1511. /// <summary>
  1512. /// Applies
  1513. /// </summary>
  1514. /// <param name="c"></param>
  1515. /// <param name="modifiers"></param>
  1516. /// <returns></returns>
  1517. private static Key ApplyModifiers (Key c, ConsoleModifiers modifiers)
  1518. {
  1519. if(modifiers.HasFlag(ConsoleModifiers.Control)) {
  1520. c |= Key.CtrlMask;
  1521. }
  1522. if (modifiers.HasFlag (ConsoleModifiers.Alt)) {
  1523. c |= Key.AltMask;
  1524. }
  1525. /* TODO: Why not this too? I'm a bit confused
  1526. ALSO this method looks a lot like `Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)`
  1527. Maybe we should be using that instead?
  1528. if (modifiers.HasFlag (ConsoleModifiers.Shift)) {
  1529. c |= Key.ShiftMask;
  1530. }
  1531. */
  1532. return c;
  1533. }
  1534. #endregion
  1535. }
  1536. /// <summary>
  1537. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1538. /// only be used on Windows.
  1539. /// </summary>
  1540. /// <remarks>
  1541. /// This implementation is used for WindowsDriver.
  1542. /// </remarks>
  1543. internal class WindowsMainLoop : IMainLoopDriver {
  1544. ManualResetEventSlim eventReady = new ManualResetEventSlim (false);
  1545. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  1546. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  1547. MainLoop mainLoop;
  1548. ConsoleDriver consoleDriver;
  1549. WindowsConsole winConsole;
  1550. bool winChanged;
  1551. Size windowSize;
  1552. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  1553. // The records that we keep fetching
  1554. Queue<WindowsConsole.InputRecord []> resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1555. /// <summary>
  1556. /// Invoked when a Key is pressed or released.
  1557. /// </summary>
  1558. public Action<WindowsConsole.InputRecord> ProcessInput;
  1559. /// <summary>
  1560. /// Invoked when the window is changed.
  1561. /// </summary>
  1562. public Action<Size> WinChanged;
  1563. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1564. {
  1565. this.consoleDriver = consoleDriver ?? throw new ArgumentNullException ("Console driver instance must be provided.");
  1566. winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1567. }
  1568. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1569. {
  1570. this.mainLoop = mainLoop;
  1571. Task.Run (WindowsInputHandler);
  1572. Task.Run (CheckWinChange);
  1573. }
  1574. void WindowsInputHandler ()
  1575. {
  1576. while (true) {
  1577. waitForProbe.Wait ();
  1578. waitForProbe.Reset ();
  1579. if (resultQueue?.Count == 0) {
  1580. resultQueue.Enqueue (winConsole.ReadConsoleInput ());
  1581. }
  1582. eventReady.Set ();
  1583. }
  1584. }
  1585. void CheckWinChange ()
  1586. {
  1587. while (true) {
  1588. winChange.Wait ();
  1589. winChange.Reset ();
  1590. WaitWinChange ();
  1591. winChanged = true;
  1592. eventReady.Set ();
  1593. }
  1594. }
  1595. void WaitWinChange ()
  1596. {
  1597. while (true) {
  1598. Thread.Sleep (100);
  1599. if (!consoleDriver.HeightAsBuffer) {
  1600. windowSize = winConsole.GetConsoleBufferWindow (out _);
  1601. //System.Diagnostics.Debug.WriteLine ($"{consoleDriver.HeightAsBuffer},{windowSize.Width},{windowSize.Height}");
  1602. if (windowSize != Size.Empty && windowSize.Width != consoleDriver.Cols
  1603. || windowSize.Height != consoleDriver.Rows) {
  1604. return;
  1605. }
  1606. }
  1607. }
  1608. }
  1609. void IMainLoopDriver.Wakeup ()
  1610. {
  1611. //tokenSource.Cancel ();
  1612. eventReady.Set ();
  1613. }
  1614. bool IMainLoopDriver.EventsPending (bool wait)
  1615. {
  1616. waitForProbe.Set ();
  1617. winChange.Set ();
  1618. if (CheckTimers (wait, out var waitTimeout)) {
  1619. return true;
  1620. }
  1621. try {
  1622. if (!tokenSource.IsCancellationRequested) {
  1623. eventReady.Wait (waitTimeout, tokenSource.Token);
  1624. }
  1625. } catch (OperationCanceledException) {
  1626. return true;
  1627. } finally {
  1628. eventReady.Reset ();
  1629. }
  1630. if (!tokenSource.IsCancellationRequested) {
  1631. return resultQueue.Count > 0 || CheckTimers (wait, out _) || winChanged;
  1632. }
  1633. tokenSource.Dispose ();
  1634. tokenSource = new CancellationTokenSource ();
  1635. return true;
  1636. }
  1637. bool CheckTimers (bool wait, out int waitTimeout)
  1638. {
  1639. long now = DateTime.UtcNow.Ticks;
  1640. if (mainLoop.timeouts.Count > 0) {
  1641. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1642. if (waitTimeout < 0)
  1643. return true;
  1644. } else {
  1645. waitTimeout = -1;
  1646. }
  1647. if (!wait)
  1648. waitTimeout = 0;
  1649. int ic;
  1650. lock (mainLoop.idleHandlers) {
  1651. ic = mainLoop.idleHandlers.Count;
  1652. }
  1653. return ic > 0;
  1654. }
  1655. void IMainLoopDriver.MainIteration ()
  1656. {
  1657. while (resultQueue.Count > 0) {
  1658. var inputRecords = resultQueue.Dequeue ();
  1659. if (inputRecords != null && inputRecords.Length > 0) {
  1660. var inputEvent = inputRecords [0];
  1661. ProcessInput?.Invoke (inputEvent);
  1662. }
  1663. }
  1664. if (winChanged) {
  1665. winChanged = false;
  1666. WinChanged?.Invoke (windowSize);
  1667. }
  1668. }
  1669. }
  1670. class WindowsClipboard : ClipboardBase {
  1671. public WindowsClipboard ()
  1672. {
  1673. IsSupported = IsClipboardFormatAvailable (cfUnicodeText);
  1674. }
  1675. public override bool IsSupported { get; }
  1676. protected override string GetClipboardDataImpl ()
  1677. {
  1678. //if (!IsClipboardFormatAvailable (cfUnicodeText))
  1679. // return null;
  1680. try {
  1681. if (!OpenClipboard (IntPtr.Zero))
  1682. return null;
  1683. IntPtr handle = GetClipboardData (cfUnicodeText);
  1684. if (handle == IntPtr.Zero)
  1685. return null;
  1686. IntPtr pointer = IntPtr.Zero;
  1687. try {
  1688. pointer = GlobalLock (handle);
  1689. if (pointer == IntPtr.Zero)
  1690. return null;
  1691. int size = GlobalSize (handle);
  1692. byte [] buff = new byte [size];
  1693. Marshal.Copy (pointer, buff, 0, size);
  1694. return System.Text.Encoding.Unicode.GetString (buff)
  1695. .TrimEnd ('\0');
  1696. } finally {
  1697. if (pointer != IntPtr.Zero)
  1698. GlobalUnlock (handle);
  1699. }
  1700. } finally {
  1701. CloseClipboard ();
  1702. }
  1703. }
  1704. protected override void SetClipboardDataImpl (string text)
  1705. {
  1706. OpenClipboard ();
  1707. EmptyClipboard ();
  1708. IntPtr hGlobal = default;
  1709. try {
  1710. var bytes = (text.Length + 1) * 2;
  1711. hGlobal = Marshal.AllocHGlobal (bytes);
  1712. if (hGlobal == default) {
  1713. ThrowWin32 ();
  1714. }
  1715. var target = GlobalLock (hGlobal);
  1716. if (target == default) {
  1717. ThrowWin32 ();
  1718. }
  1719. try {
  1720. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1721. } finally {
  1722. GlobalUnlock (target);
  1723. }
  1724. if (SetClipboardData (cfUnicodeText, hGlobal) == default) {
  1725. ThrowWin32 ();
  1726. }
  1727. hGlobal = default;
  1728. } finally {
  1729. if (hGlobal != default) {
  1730. Marshal.FreeHGlobal (hGlobal);
  1731. }
  1732. CloseClipboard ();
  1733. }
  1734. }
  1735. void OpenClipboard ()
  1736. {
  1737. var num = 10;
  1738. while (true) {
  1739. if (OpenClipboard (default)) {
  1740. break;
  1741. }
  1742. if (--num == 0) {
  1743. ThrowWin32 ();
  1744. }
  1745. Thread.Sleep (100);
  1746. }
  1747. }
  1748. const uint cfUnicodeText = 13;
  1749. void ThrowWin32 ()
  1750. {
  1751. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1752. }
  1753. [DllImport ("User32.dll", SetLastError = true)]
  1754. [return: MarshalAs (UnmanagedType.Bool)]
  1755. static extern bool IsClipboardFormatAvailable (uint format);
  1756. [DllImport ("kernel32.dll", SetLastError = true)]
  1757. static extern int GlobalSize (IntPtr handle);
  1758. [DllImport ("kernel32.dll", SetLastError = true)]
  1759. static extern IntPtr GlobalLock (IntPtr hMem);
  1760. [DllImport ("kernel32.dll", SetLastError = true)]
  1761. [return: MarshalAs (UnmanagedType.Bool)]
  1762. static extern bool GlobalUnlock (IntPtr hMem);
  1763. [DllImport ("user32.dll", SetLastError = true)]
  1764. [return: MarshalAs (UnmanagedType.Bool)]
  1765. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1766. [DllImport ("user32.dll", SetLastError = true)]
  1767. [return: MarshalAs (UnmanagedType.Bool)]
  1768. static extern bool CloseClipboard ();
  1769. [DllImport ("user32.dll", SetLastError = true)]
  1770. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1771. [DllImport ("user32.dll")]
  1772. static extern bool EmptyClipboard ();
  1773. [DllImport ("user32.dll", SetLastError = true)]
  1774. static extern IntPtr GetClipboardData (uint uFormat);
  1775. }
  1776. }