WindowsDriver.cs 62 KB

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