WindowsDriver.cs 62 KB

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