WindowsDriver.cs 63 KB

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