WindowsDriver.cs 63 KB

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