WindowsDriver.cs 54 KB

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