WindowsDriver.cs 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  1. // TODO: #nullable enable
  2. //
  3. // WindowsDriver.cs: Windows specific driver
  4. //
  5. // HACK:
  6. // WindowsConsole/Terminal has two issues:
  7. // 1) Tearing can occur when the console is resized.
  8. // 2) The values provided during Init (and the first WindowsConsole.EventType.WindowBufferSize) are not correct.
  9. //
  10. // If HACK_CHECK_WINCHANGED is defined then we ignore WindowsConsole.EventType.WindowBufferSize events
  11. // and instead check the console size every 500ms in a thread in WidowsMainLoop.
  12. // As of Windows 11 23H2 25947.1000 and/or WT 1.19.2682 tearing no longer occurs when using
  13. // the WindowsConsole.EventType.WindowBufferSize event. However, on Init the window size is
  14. // still incorrect so we still need this hack.
  15. //#define HACK_CHECK_WINCHANGED
  16. using System.Collections.Concurrent;
  17. using System.ComponentModel;
  18. using System.Diagnostics;
  19. using System.Runtime.InteropServices;
  20. using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping;
  21. namespace Terminal.Gui;
  22. internal class WindowsDriver : ConsoleDriver
  23. {
  24. private readonly bool _isWindowsTerminal;
  25. private WindowsConsole.SmallRect _damageRegion;
  26. private bool _isButtonDoubleClicked;
  27. private bool _isButtonPressed;
  28. private bool _isButtonReleased;
  29. private bool _isOneFingerDoubleClicked;
  30. private WindowsConsole.ButtonState? _lastMouseButtonPressed;
  31. private WindowsMainLoop _mainLoopDriver;
  32. private WindowsConsole.ExtendedCharInfo [] _outputBuffer;
  33. private Point? _point;
  34. private Point _pointMove;
  35. private bool _processButtonClick;
  36. public WindowsDriver ()
  37. {
  38. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  39. {
  40. WinConsole = new WindowsConsole ();
  41. // otherwise we're probably running in unit tests
  42. Clipboard = new WindowsClipboard ();
  43. }
  44. else
  45. {
  46. Clipboard = new FakeDriver.FakeClipboard ();
  47. }
  48. // TODO: if some other Windows-based terminal supports true color, update this logic to not
  49. // force 16color mode (.e.g ConEmu which really doesn't work well at all).
  50. _isWindowsTerminal = _isWindowsTerminal =
  51. Environment.GetEnvironmentVariable ("WT_SESSION") is { } || Environment.GetEnvironmentVariable ("VSAPPIDNAME") != null;
  52. if (!_isWindowsTerminal)
  53. {
  54. Force16Colors = true;
  55. }
  56. }
  57. public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931 && _isWindowsTerminal);
  58. public WindowsConsole WinConsole { get; private set; }
  59. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  60. {
  61. if (keyEvent.wVirtualKeyCode != (VK)ConsoleKey.Packet)
  62. {
  63. return keyEvent;
  64. }
  65. var mod = new ConsoleModifiers ();
  66. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  67. {
  68. mod |= ConsoleModifiers.Shift;
  69. }
  70. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  71. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  72. {
  73. mod |= ConsoleModifiers.Alt;
  74. }
  75. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)
  76. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed))
  77. {
  78. mod |= ConsoleModifiers.Control;
  79. }
  80. var cKeyInfo = new ConsoleKeyInfo (
  81. keyEvent.UnicodeChar,
  82. (ConsoleKey)keyEvent.wVirtualKeyCode,
  83. mod.HasFlag (ConsoleModifiers.Shift),
  84. mod.HasFlag (ConsoleModifiers.Alt),
  85. mod.HasFlag (ConsoleModifiers.Control));
  86. cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  87. uint scanCode = GetScanCodeFromConsoleKeyInfo (cKeyInfo);
  88. return new WindowsConsole.KeyEventRecord
  89. {
  90. UnicodeChar = cKeyInfo.KeyChar,
  91. bKeyDown = keyEvent.bKeyDown,
  92. dwControlKeyState = keyEvent.dwControlKeyState,
  93. wRepeatCount = keyEvent.wRepeatCount,
  94. wVirtualKeyCode = (VK)cKeyInfo.Key,
  95. wVirtualScanCode = (ushort)scanCode
  96. };
  97. }
  98. public override bool IsRuneSupported (Rune rune) { return base.IsRuneSupported (rune) && rune.IsBmp; }
  99. public override void Refresh ()
  100. {
  101. if (!RunningUnitTests)
  102. {
  103. UpdateScreen ();
  104. //WinConsole?.SetInitialCursorVisibility ();
  105. UpdateCursor ();
  106. }
  107. }
  108. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  109. {
  110. var input = new WindowsConsole.InputRecord
  111. {
  112. EventType = WindowsConsole.EventType.Key
  113. };
  114. var keyEvent = new WindowsConsole.KeyEventRecord
  115. {
  116. bKeyDown = true
  117. };
  118. var controlKey = new WindowsConsole.ControlKeyState ();
  119. if (shift)
  120. {
  121. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  122. keyEvent.UnicodeChar = '\0';
  123. keyEvent.wVirtualKeyCode = VK.SHIFT;
  124. }
  125. if (alt)
  126. {
  127. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  128. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  129. keyEvent.UnicodeChar = '\0';
  130. keyEvent.wVirtualKeyCode = VK.MENU;
  131. }
  132. if (control)
  133. {
  134. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  135. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  136. keyEvent.UnicodeChar = '\0';
  137. keyEvent.wVirtualKeyCode = VK.CONTROL;
  138. }
  139. keyEvent.dwControlKeyState = controlKey;
  140. input.KeyEvent = keyEvent;
  141. if (shift || alt || control)
  142. {
  143. ProcessInput (input);
  144. }
  145. keyEvent.UnicodeChar = keyChar;
  146. //if ((uint)key < 255) {
  147. // keyEvent.wVirtualKeyCode = (ushort)key;
  148. //} else {
  149. // keyEvent.wVirtualKeyCode = '\0';
  150. //}
  151. keyEvent.wVirtualKeyCode = (VK)key;
  152. input.KeyEvent = keyEvent;
  153. try
  154. {
  155. ProcessInput (input);
  156. }
  157. catch (OverflowException)
  158. { }
  159. finally
  160. {
  161. keyEvent.bKeyDown = false;
  162. input.KeyEvent = keyEvent;
  163. ProcessInput (input);
  164. }
  165. }
  166. private readonly ManualResetEventSlim _waitAnsiResponse = new (false);
  167. private readonly CancellationTokenSource _ansiResponseTokenSource = new ();
  168. /// <inheritdoc/>
  169. public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest)
  170. {
  171. if (_mainLoopDriver is null)
  172. {
  173. return string.Empty;
  174. }
  175. try
  176. {
  177. lock (ansiRequest._responseLock)
  178. {
  179. ansiRequest.ResponseFromInput += (s, e) =>
  180. {
  181. Debug.Assert (s == ansiRequest);
  182. Debug.Assert (e == ansiRequest.Response);
  183. _waitAnsiResponse.Set ();
  184. };
  185. _mainLoopDriver.EscSeqRequests.Add (ansiRequest, this);
  186. _mainLoopDriver._forceRead = true;
  187. }
  188. if (!_ansiResponseTokenSource.IsCancellationRequested)
  189. {
  190. _mainLoopDriver._waitForProbe.Set ();
  191. _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token);
  192. }
  193. }
  194. catch (OperationCanceledException)
  195. {
  196. return string.Empty;
  197. }
  198. lock (ansiRequest._responseLock)
  199. {
  200. _mainLoopDriver._forceRead = false;
  201. if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request))
  202. {
  203. if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0
  204. && string.IsNullOrEmpty (request.AnsiRequest.Response))
  205. {
  206. lock (request!.AnsiRequest._responseLock)
  207. {
  208. // Bad request or no response at all
  209. _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _);
  210. }
  211. }
  212. }
  213. _waitAnsiResponse.Reset ();
  214. return ansiRequest.Response;
  215. }
  216. }
  217. public override void WriteRaw (string ansi)
  218. {
  219. WinConsole?.WriteANSI (ansi);
  220. }
  221. #region Not Implemented
  222. public override void Suspend () { throw new NotImplementedException (); }
  223. #endregion
  224. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  225. {
  226. WindowsConsole.ControlKeyState state = keyEvent.dwControlKeyState;
  227. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  228. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  229. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  230. bool capslock = (state & WindowsConsole.ControlKeyState.CapslockOn) != 0;
  231. bool numlock = (state & WindowsConsole.ControlKeyState.NumlockOn) != 0;
  232. bool scrolllock = (state & WindowsConsole.ControlKeyState.ScrolllockOn) != 0;
  233. var cki = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  234. return new WindowsConsole.ConsoleKeyInfoEx (cki, capslock, numlock, scrolllock);
  235. }
  236. #region Cursor Handling
  237. private CursorVisibility? _cachedCursorVisibility;
  238. public override void UpdateCursor ()
  239. {
  240. if (Col < 0 || Row < 0 || Col >= Cols || Row >= Rows)
  241. {
  242. GetCursorVisibility (out CursorVisibility cursorVisibility);
  243. _cachedCursorVisibility = cursorVisibility;
  244. SetCursorVisibility (CursorVisibility.Invisible);
  245. return;
  246. }
  247. var position = new WindowsConsole.Coord
  248. {
  249. X = (short)Col,
  250. Y = (short)Row
  251. };
  252. if (Force16Colors)
  253. {
  254. WinConsole?.SetCursorPosition (position);
  255. }
  256. else
  257. {
  258. var sb = new StringBuilder ();
  259. sb.Append (EscSeqUtils.CSI_SetCursorPosition (position.Y + 1, position.X + 1));
  260. WinConsole?.WriteANSI (sb.ToString ());
  261. }
  262. if (_cachedCursorVisibility is { })
  263. {
  264. SetCursorVisibility (_cachedCursorVisibility.Value);
  265. }
  266. //EnsureCursorVisibility ();
  267. }
  268. /// <inheritdoc/>
  269. public override bool GetCursorVisibility (out CursorVisibility visibility)
  270. {
  271. if (WinConsole is { })
  272. {
  273. return WinConsole.GetCursorVisibility (out visibility);
  274. }
  275. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  276. return true;
  277. }
  278. /// <inheritdoc/>
  279. public override bool SetCursorVisibility (CursorVisibility visibility)
  280. {
  281. _cachedCursorVisibility = visibility;
  282. if (Force16Colors)
  283. {
  284. return WinConsole is null || WinConsole.SetCursorVisibility (visibility);
  285. }
  286. else
  287. {
  288. var sb = new StringBuilder ();
  289. sb.Append (visibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  290. return WinConsole?.WriteANSI (sb.ToString ()) ?? false;
  291. }
  292. }
  293. /// <inheritdoc/>
  294. public override bool EnsureCursorVisibility ()
  295. {
  296. if (Force16Colors)
  297. {
  298. return WinConsole is null || WinConsole.EnsureCursorVisibility ();
  299. }
  300. else
  301. {
  302. var sb = new StringBuilder ();
  303. sb.Append (_cachedCursorVisibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  304. return WinConsole?.WriteANSI (sb.ToString ()) ?? false;
  305. }
  306. //if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  307. //{
  308. // GetCursorVisibility (out CursorVisibility cursorVisibility);
  309. // _cachedCursorVisibility = cursorVisibility;
  310. // SetCursorVisibility (CursorVisibility.Invisible);
  311. // return false;
  312. //}
  313. //SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default);
  314. //return _cachedCursorVisibility == CursorVisibility.Default;
  315. }
  316. #endregion Cursor Handling
  317. public override void UpdateScreen ()
  318. {
  319. Size windowSize = WinConsole?.GetConsoleOutputWindow (out Point _) ?? new Size (Cols, Rows);
  320. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows))
  321. {
  322. return;
  323. }
  324. var bufferCoords = new WindowsConsole.Coord
  325. {
  326. X = (short)Cols, //Clip.Width,
  327. Y = (short)Rows, //Clip.Height
  328. };
  329. for (var row = 0; row < Rows; row++)
  330. {
  331. if (!_dirtyLines [row])
  332. {
  333. continue;
  334. }
  335. _dirtyLines [row] = false;
  336. for (var col = 0; col < Cols; col++)
  337. {
  338. int position = row * Cols + col;
  339. _outputBuffer [position].Attribute = Contents [row, col].Attribute.GetValueOrDefault ();
  340. if (Contents [row, col].IsDirty == false)
  341. {
  342. _outputBuffer [position].Empty = true;
  343. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  344. continue;
  345. }
  346. _outputBuffer [position].Empty = false;
  347. if (Contents [row, col].Rune.IsBmp)
  348. {
  349. _outputBuffer [position].Char = (char)Contents [row, col].Rune.Value;
  350. }
  351. else
  352. {
  353. //_outputBuffer [position].Empty = true;
  354. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  355. if (Contents [row, col].Rune.GetColumns () > 1 && col + 1 < Cols)
  356. {
  357. // TODO: This is a hack to deal with non-BMP and wide characters.
  358. col++;
  359. position = row * Cols + col;
  360. _outputBuffer [position].Empty = false;
  361. _outputBuffer [position].Char = ' ';
  362. }
  363. }
  364. }
  365. }
  366. _damageRegion = new WindowsConsole.SmallRect
  367. {
  368. Top = 0,
  369. Left = 0,
  370. Bottom = (short)Rows,
  371. Right = (short)Cols
  372. };
  373. if (!RunningUnitTests
  374. && WinConsole != null
  375. && !WinConsole.WriteToConsole (new (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors))
  376. {
  377. int err = Marshal.GetLastWin32Error ();
  378. if (err != 0)
  379. {
  380. throw new Win32Exception (err);
  381. }
  382. }
  383. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  384. }
  385. internal override void End ()
  386. {
  387. if (_mainLoopDriver is { })
  388. {
  389. #if HACK_CHECK_WINCHANGED
  390. _mainLoopDriver.WinChanged -= ChangeWin;
  391. #endif
  392. }
  393. _mainLoopDriver = null;
  394. WinConsole?.Cleanup ();
  395. WinConsole = null;
  396. if (!RunningUnitTests && _isWindowsTerminal)
  397. {
  398. // Disable alternative screen buffer.
  399. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  400. }
  401. }
  402. internal override MainLoop Init ()
  403. {
  404. _mainLoopDriver = new WindowsMainLoop (this);
  405. if (!RunningUnitTests)
  406. {
  407. try
  408. {
  409. if (WinConsole is { })
  410. {
  411. // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init.
  412. // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED
  413. Size winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  414. Cols = winSize.Width;
  415. Rows = winSize.Height;
  416. }
  417. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  418. if (_isWindowsTerminal)
  419. {
  420. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  421. }
  422. }
  423. catch (Win32Exception e)
  424. {
  425. // We are being run in an environment that does not support a console
  426. // such as a unit test, or a pipe.
  427. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  428. WinConsole = null;
  429. }
  430. }
  431. CurrentAttribute = new Attribute (Color.White, Color.Black);
  432. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  433. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  434. Clip = new (0, 0, Cols, Rows);
  435. _damageRegion = new WindowsConsole.SmallRect
  436. {
  437. Top = 0,
  438. Left = 0,
  439. Bottom = (short)Rows,
  440. Right = (short)Cols
  441. };
  442. ClearContents ();
  443. #if HACK_CHECK_WINCHANGED
  444. _mainLoopDriver.WinChanged = ChangeWin;
  445. #endif
  446. if (!RunningUnitTests)
  447. {
  448. WinConsole?.SetInitialCursorVisibility ();
  449. }
  450. return new MainLoop (_mainLoopDriver);
  451. }
  452. internal void ProcessInput (WindowsConsole.InputRecord inputEvent)
  453. {
  454. switch (inputEvent.EventType)
  455. {
  456. case WindowsConsole.EventType.Key:
  457. if (inputEvent.KeyEvent.wVirtualKeyCode == (VK)ConsoleKey.Packet)
  458. {
  459. // Used to pass Unicode characters as if they were keystrokes.
  460. // The VK_PACKET key is the low word of a 32-bit
  461. // Virtual Key value used for non-keyboard input methods.
  462. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  463. }
  464. WindowsConsole.ConsoleKeyInfoEx keyInfo = ToConsoleKeyInfoEx (inputEvent.KeyEvent);
  465. //Debug.WriteLine ($"event: KBD: {GetKeyboardLayoutName()} {inputEvent.ToString ()} {keyInfo.ToString (keyInfo)}");
  466. KeyCode map = MapKey (keyInfo);
  467. if (map == KeyCode.Null)
  468. {
  469. break;
  470. }
  471. if (inputEvent.KeyEvent.bKeyDown)
  472. {
  473. // Avoid sending repeat key down events
  474. OnKeyDown (new Key (map));
  475. }
  476. else
  477. {
  478. OnKeyUp (new Key (map));
  479. }
  480. break;
  481. case WindowsConsole.EventType.Mouse:
  482. MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent);
  483. if (me is null || me.Flags == MouseFlags.None)
  484. {
  485. break;
  486. }
  487. OnMouseEvent (me);
  488. if (_processButtonClick)
  489. {
  490. OnMouseEvent (new ()
  491. {
  492. Position = me.Position,
  493. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  494. });
  495. }
  496. break;
  497. case WindowsConsole.EventType.Focus:
  498. break;
  499. #if !HACK_CHECK_WINCHANGED
  500. case WindowsConsole.EventType.WindowBufferSize:
  501. Cols = inputEvent.WindowBufferSizeEvent._size.X;
  502. Rows = inputEvent.WindowBufferSizeEvent._size.Y;
  503. ResizeScreen ();
  504. ClearContents ();
  505. Application.Top?.SetNeedsLayout ();
  506. Application.Refresh ();
  507. break;
  508. #endif
  509. }
  510. }
  511. #if HACK_CHECK_WINCHANGED
  512. private void ChangeWin (object s, SizeChangedEventArgs e)
  513. {
  514. if (e.Size is null)
  515. {
  516. return;
  517. }
  518. int w = e.Size.Value.Width;
  519. if (w == Cols - 3 && e.Size.Value.Height < Rows)
  520. {
  521. w += 3;
  522. }
  523. Left = 0;
  524. Top = 0;
  525. Cols = e.Size.Value.Width;
  526. Rows = e.Size.Value.Height;
  527. if (!RunningUnitTests)
  528. {
  529. Size newSize = WinConsole.SetConsoleWindow (
  530. (short)Math.Max (w, 16),
  531. (short)Math.Max (e.Size.Value.Height, 0));
  532. Cols = newSize.Width;
  533. Rows = newSize.Height;
  534. }
  535. ResizeScreen ();
  536. ClearContents ();
  537. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  538. }
  539. #endif
  540. private KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  541. {
  542. ConsoleKeyInfo keyInfo = keyInfoEx.ConsoleKeyInfo;
  543. switch (keyInfo.Key)
  544. {
  545. case ConsoleKey.D0:
  546. case ConsoleKey.D1:
  547. case ConsoleKey.D2:
  548. case ConsoleKey.D3:
  549. case ConsoleKey.D4:
  550. case ConsoleKey.D5:
  551. case ConsoleKey.D6:
  552. case ConsoleKey.D7:
  553. case ConsoleKey.D8:
  554. case ConsoleKey.D9:
  555. case ConsoleKey.NumPad0:
  556. case ConsoleKey.NumPad1:
  557. case ConsoleKey.NumPad2:
  558. case ConsoleKey.NumPad3:
  559. case ConsoleKey.NumPad4:
  560. case ConsoleKey.NumPad5:
  561. case ConsoleKey.NumPad6:
  562. case ConsoleKey.NumPad7:
  563. case ConsoleKey.NumPad8:
  564. case ConsoleKey.NumPad9:
  565. case ConsoleKey.Oem1:
  566. case ConsoleKey.Oem2:
  567. case ConsoleKey.Oem3:
  568. case ConsoleKey.Oem4:
  569. case ConsoleKey.Oem5:
  570. case ConsoleKey.Oem6:
  571. case ConsoleKey.Oem7:
  572. case ConsoleKey.Oem8:
  573. case ConsoleKey.Oem102:
  574. case ConsoleKey.Multiply:
  575. case ConsoleKey.Add:
  576. case ConsoleKey.Separator:
  577. case ConsoleKey.Subtract:
  578. case ConsoleKey.Decimal:
  579. case ConsoleKey.Divide:
  580. case ConsoleKey.OemPeriod:
  581. case ConsoleKey.OemComma:
  582. case ConsoleKey.OemPlus:
  583. case ConsoleKey.OemMinus:
  584. // These virtual key codes are mapped differently depending on the keyboard layout in use.
  585. // We use the Win32 API to map them to the correct character.
  586. uint mapResult = MapVKtoChar ((VK)keyInfo.Key);
  587. if (mapResult == 0)
  588. {
  589. // There is no mapping - this should not happen
  590. Debug.Assert (mapResult != 0, $@"Unable to map the virtual key code {keyInfo.Key}.");
  591. return KeyCode.Null;
  592. }
  593. // An un-shifted character value is in the low order word of the return value.
  594. var mappedChar = (char)(mapResult & 0x0000FFFF);
  595. if (keyInfo.KeyChar == 0)
  596. {
  597. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  598. // Dead keys (diacritics) are indicated by setting the top bit of the return value.
  599. if ((mapResult & 0x80000000) != 0)
  600. {
  601. // Dead key (e.g. Oem2 '~'/'^' on POR keyboard)
  602. // Option 1: Throw it out.
  603. // - Apps will never see the dead keys
  604. // - If user presses a key that can be combined with the dead key ('a'), the right thing happens (app will see '�').
  605. // - NOTE: With Dead Keys, KeyDown != KeyUp. The KeyUp event will have just the base char ('a').
  606. // - If user presses dead key again, the right thing happens (app will see `~~`)
  607. // - This is what Notepad etc... appear to do
  608. // Option 2: Expand the API to indicate the KeyCode is a dead key
  609. // - Enables apps to do their own dead key processing
  610. // - Adds complexity; no dev has asked for this (yet).
  611. // We choose Option 1 for now.
  612. return KeyCode.Null;
  613. // Note: Ctrl-Deadkey (like Oem3 '`'/'~` on ENG) can't be supported.
  614. // Sadly, the charVal is just the deadkey and subsequent key events do not contain
  615. // any info that the previous event was a deadkey.
  616. // Note WT does not support Ctrl-Deadkey either.
  617. }
  618. if (keyInfo.Modifiers != 0)
  619. {
  620. // These Oem keys have well-defined chars. We ensure the representative char is used.
  621. // If we don't do this, then on some keyboard layouts the wrong char is
  622. // returned (e.g. on ENG OemPlus un-shifted is =, not +). This is important
  623. // for key persistence ("Ctrl++" vs. "Ctrl+=").
  624. mappedChar = keyInfo.Key switch
  625. {
  626. ConsoleKey.OemPeriod => '.',
  627. ConsoleKey.OemComma => ',',
  628. ConsoleKey.OemPlus => '+',
  629. ConsoleKey.OemMinus => '-',
  630. _ => mappedChar
  631. };
  632. }
  633. // Return the mappedChar with modifiers. Because mappedChar is un-shifted, if Shift was down
  634. // we should keep it
  635. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  636. }
  637. // KeyChar is printable
  638. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  639. {
  640. // AltGr support - AltGr is equivalent to Ctrl+Alt - the correct char is in KeyChar
  641. return (KeyCode)keyInfo.KeyChar;
  642. }
  643. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  644. {
  645. // If Shift wasn't down we don't need to do anything but return the mappedChar
  646. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  647. }
  648. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "�")
  649. // and passing on Shift would be redundant.
  650. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  651. }
  652. // A..Z are special cased:
  653. // - Alone, they represent lowercase a...z
  654. // - With ShiftMask they are A..Z
  655. // - If CapsLock is on the above is reversed.
  656. // - If Alt and/or Ctrl are present, treat as upper case
  657. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z)
  658. {
  659. if (keyInfo.KeyChar == 0)
  660. {
  661. // KeyChar is not printable - possibly an AltGr key?
  662. // AltGr support - AltGr is equivalent to Ctrl+Alt
  663. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  664. {
  665. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  666. }
  667. }
  668. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  669. {
  670. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  671. }
  672. if ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ keyInfoEx.CapsLock)
  673. {
  674. // If (ShiftMask is on and CapsLock is off) or (ShiftMask is off and CapsLock is on) add the ShiftMask
  675. if (char.IsUpper (keyInfo.KeyChar))
  676. {
  677. // Always return the KeyChar because it may be an Á, À with Oem1, etc
  678. return (KeyCode)keyInfo.KeyChar | KeyCode.ShiftMask;
  679. }
  680. }
  681. // Always return the KeyChar because it may be an á, à with Oem1, etc
  682. return (KeyCode)keyInfo.KeyChar;
  683. }
  684. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  685. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  686. {
  687. // If the key is JUST a modifier, return it as just that key
  688. if (keyInfo.Key == (ConsoleKey)VK.SHIFT)
  689. { // Shift 16
  690. return KeyCode.ShiftMask;
  691. }
  692. if (keyInfo.Key == (ConsoleKey)VK.CONTROL)
  693. { // Ctrl 17
  694. return KeyCode.CtrlMask;
  695. }
  696. if (keyInfo.Key == (ConsoleKey)VK.MENU)
  697. { // Alt 18
  698. return KeyCode.AltMask;
  699. }
  700. if (keyInfo.KeyChar == 0)
  701. {
  702. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  703. }
  704. if (keyInfo.Key != ConsoleKey.None)
  705. {
  706. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  707. }
  708. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  709. }
  710. // Handle control keys (e.g. CursorUp)
  711. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  712. {
  713. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  714. }
  715. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  716. }
  717. private MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  718. {
  719. MouseFlags mouseFlag = 0;
  720. switch (_lastMouseButtonPressed)
  721. {
  722. case WindowsConsole.ButtonState.Button1Pressed:
  723. mouseFlag = MouseFlags.Button1Clicked;
  724. break;
  725. case WindowsConsole.ButtonState.Button2Pressed:
  726. mouseFlag = MouseFlags.Button2Clicked;
  727. break;
  728. case WindowsConsole.ButtonState.RightmostButtonPressed:
  729. mouseFlag = MouseFlags.Button3Clicked;
  730. break;
  731. }
  732. _point = new Point
  733. {
  734. X = mouseEvent.MousePosition.X,
  735. Y = mouseEvent.MousePosition.Y
  736. };
  737. _lastMouseButtonPressed = null;
  738. _isButtonReleased = false;
  739. _processButtonClick = false;
  740. _point = null;
  741. return mouseFlag;
  742. }
  743. private async Task ProcessButtonDoubleClickedAsync ()
  744. {
  745. await Task.Delay (200);
  746. _isButtonDoubleClicked = false;
  747. _isOneFingerDoubleClicked = false;
  748. //buttonPressedCount = 0;
  749. }
  750. private async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  751. {
  752. // When a user presses-and-holds, start generating pressed events every `startDelay`
  753. // After `iterationsUntilFast` iterations, speed them up to `fastDelay` ms
  754. const int startDelay = 500;
  755. const int iterationsUntilFast = 4;
  756. const int fastDelay = 50;
  757. int iterations = 0;
  758. int delay = startDelay;
  759. while (_isButtonPressed)
  760. {
  761. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  762. View view = Application.WantContinuousButtonPressedView;
  763. if (view is null)
  764. {
  765. break;
  766. }
  767. if (iterations++ >= iterationsUntilFast)
  768. {
  769. delay = fastDelay;
  770. }
  771. await Task.Delay (delay);
  772. var me = new MouseEventArgs
  773. {
  774. ScreenPosition = _pointMove,
  775. Flags = mouseFlag
  776. };
  777. //Debug.WriteLine($"ProcessContinuousButtonPressedAsync: {view}");
  778. if (_isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0)
  779. {
  780. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  781. Application.Invoke (() => OnMouseEvent (me));
  782. }
  783. }
  784. }
  785. private void ResizeScreen ()
  786. {
  787. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  788. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  789. Clip = new (0, 0, Cols, Rows);
  790. _damageRegion = new WindowsConsole.SmallRect
  791. {
  792. Top = 0,
  793. Left = 0,
  794. Bottom = (short)Rows,
  795. Right = (short)Cols
  796. };
  797. _dirtyLines = new bool [Rows];
  798. WinConsole?.ForceRefreshCursorVisibility ();
  799. }
  800. private static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  801. {
  802. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)
  803. || mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  804. {
  805. mouseFlag |= MouseFlags.ButtonCtrl;
  806. }
  807. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  808. {
  809. mouseFlag |= MouseFlags.ButtonShift;
  810. }
  811. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  812. || mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  813. {
  814. mouseFlag |= MouseFlags.ButtonAlt;
  815. }
  816. return mouseFlag;
  817. }
  818. [CanBeNull]
  819. private MouseEventArgs ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  820. {
  821. var mouseFlag = MouseFlags.AllEvents;
  822. //Debug.WriteLine ($"ToDriverMouse: {mouseEvent}");
  823. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked)
  824. {
  825. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  826. Application.MainLoop.AddIdle (
  827. () =>
  828. {
  829. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  830. return false;
  831. });
  832. }
  833. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  834. // This will tell when a mouse button is pressed. When the button is released this event will
  835. // be fired with its bit set to 0. So when the button is up ButtonState will be 0.
  836. // To map to the correct driver events we save the last pressed mouse button, so we can
  837. // map to the correct clicked event.
  838. if ((_lastMouseButtonPressed is { } || _isButtonReleased) && mouseEvent.ButtonState != 0)
  839. {
  840. _lastMouseButtonPressed = null;
  841. //isButtonPressed = false;
  842. _isButtonReleased = false;
  843. }
  844. var p = new Point
  845. {
  846. X = mouseEvent.MousePosition.X,
  847. Y = mouseEvent.MousePosition.Y
  848. };
  849. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed is null && !_isButtonDoubleClicked)
  850. || (_lastMouseButtonPressed == null
  851. && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved)
  852. && mouseEvent.ButtonState != 0
  853. && !_isButtonReleased
  854. && !_isButtonDoubleClicked))
  855. {
  856. switch (mouseEvent.ButtonState)
  857. {
  858. case WindowsConsole.ButtonState.Button1Pressed:
  859. mouseFlag = MouseFlags.Button1Pressed;
  860. break;
  861. case WindowsConsole.ButtonState.Button2Pressed:
  862. mouseFlag = MouseFlags.Button2Pressed;
  863. break;
  864. case WindowsConsole.ButtonState.RightmostButtonPressed:
  865. mouseFlag = MouseFlags.Button3Pressed;
  866. break;
  867. }
  868. if (_point is null)
  869. {
  870. _point = p;
  871. }
  872. if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved))
  873. {
  874. _pointMove = p;
  875. mouseFlag |= MouseFlags.ReportMousePosition;
  876. _isButtonReleased = false;
  877. _processButtonClick = false;
  878. }
  879. _lastMouseButtonPressed = mouseEvent.ButtonState;
  880. _isButtonPressed = true;
  881. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0)
  882. {
  883. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  884. Application.MainLoop.AddIdle (
  885. () =>
  886. {
  887. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  888. return false;
  889. });
  890. }
  891. }
  892. else if (_lastMouseButtonPressed != null
  893. && mouseEvent.EventFlags == 0
  894. && !_isButtonReleased
  895. && !_isButtonDoubleClicked
  896. && !_isOneFingerDoubleClicked)
  897. {
  898. switch (_lastMouseButtonPressed)
  899. {
  900. case WindowsConsole.ButtonState.Button1Pressed:
  901. mouseFlag = MouseFlags.Button1Released;
  902. break;
  903. case WindowsConsole.ButtonState.Button2Pressed:
  904. mouseFlag = MouseFlags.Button2Released;
  905. break;
  906. case WindowsConsole.ButtonState.RightmostButtonPressed:
  907. mouseFlag = MouseFlags.Button3Released;
  908. break;
  909. }
  910. _isButtonPressed = false;
  911. _isButtonReleased = true;
  912. if (_point is { } && ((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)
  913. {
  914. _processButtonClick = true;
  915. }
  916. else
  917. {
  918. _point = null;
  919. }
  920. _processButtonClick = true;
  921. }
  922. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  923. && !_isOneFingerDoubleClicked
  924. && _isButtonReleased
  925. && p == _point)
  926. {
  927. mouseFlag = ProcessButtonClick (mouseEvent);
  928. }
  929. else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick))
  930. {
  931. switch (mouseEvent.ButtonState)
  932. {
  933. case WindowsConsole.ButtonState.Button1Pressed:
  934. mouseFlag = MouseFlags.Button1DoubleClicked;
  935. break;
  936. case WindowsConsole.ButtonState.Button2Pressed:
  937. mouseFlag = MouseFlags.Button2DoubleClicked;
  938. break;
  939. case WindowsConsole.ButtonState.RightmostButtonPressed:
  940. mouseFlag = MouseFlags.Button3DoubleClicked;
  941. break;
  942. }
  943. _isButtonDoubleClicked = true;
  944. }
  945. else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked)
  946. {
  947. switch (mouseEvent.ButtonState)
  948. {
  949. case WindowsConsole.ButtonState.Button1Pressed:
  950. mouseFlag = MouseFlags.Button1TripleClicked;
  951. break;
  952. case WindowsConsole.ButtonState.Button2Pressed:
  953. mouseFlag = MouseFlags.Button2TripleClicked;
  954. break;
  955. case WindowsConsole.ButtonState.RightmostButtonPressed:
  956. mouseFlag = MouseFlags.Button3TripleClicked;
  957. break;
  958. }
  959. _isButtonDoubleClicked = false;
  960. }
  961. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled)
  962. {
  963. switch ((int)mouseEvent.ButtonState)
  964. {
  965. case int v when v > 0:
  966. mouseFlag = MouseFlags.WheeledUp;
  967. break;
  968. case int v when v < 0:
  969. mouseFlag = MouseFlags.WheeledDown;
  970. break;
  971. }
  972. }
  973. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled && mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed)
  974. {
  975. switch ((int)mouseEvent.ButtonState)
  976. {
  977. case int v when v > 0:
  978. mouseFlag = MouseFlags.WheeledLeft;
  979. break;
  980. case int v when v < 0:
  981. mouseFlag = MouseFlags.WheeledRight;
  982. break;
  983. }
  984. }
  985. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled)
  986. {
  987. switch ((int)mouseEvent.ButtonState)
  988. {
  989. case int v when v < 0:
  990. mouseFlag = MouseFlags.WheeledLeft;
  991. break;
  992. case int v when v > 0:
  993. mouseFlag = MouseFlags.WheeledRight;
  994. break;
  995. }
  996. }
  997. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved)
  998. {
  999. mouseFlag = MouseFlags.ReportMousePosition;
  1000. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y)
  1001. {
  1002. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  1003. }
  1004. }
  1005. else if (mouseEvent is { ButtonState: 0, EventFlags: 0 })
  1006. {
  1007. // This happens on a double or triple click event.
  1008. mouseFlag = MouseFlags.None;
  1009. }
  1010. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  1011. //System.Diagnostics.Debug.WriteLine (
  1012. // $"point.X:{(point is { } ? ((Point)point).X : -1)};point.Y:{(point is { } ? ((Point)point).Y : -1)}");
  1013. return new MouseEventArgs
  1014. {
  1015. Position = new (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y),
  1016. Flags = mouseFlag
  1017. };
  1018. }
  1019. }
  1020. /// <summary>
  1021. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1022. /// only be used on Windows.
  1023. /// </summary>
  1024. /// <remarks>
  1025. /// This implementation is used for WindowsDriver.
  1026. /// </remarks>
  1027. internal class WindowsMainLoop : IMainLoopDriver
  1028. {
  1029. /// <summary>
  1030. /// Invoked when the window is changed.
  1031. /// </summary>
  1032. public EventHandler<SizeChangedEventArgs> WinChanged;
  1033. private readonly ConsoleDriver _consoleDriver;
  1034. private readonly ManualResetEventSlim _eventReady = new (false);
  1035. // The records that we keep fetching
  1036. private readonly ConcurrentQueue<WindowsConsole.InputRecord []> _resultQueue = new ();
  1037. internal readonly ManualResetEventSlim _waitForProbe = new (false);
  1038. private readonly WindowsConsole _winConsole;
  1039. private CancellationTokenSource _eventReadyTokenSource = new ();
  1040. private readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  1041. private MainLoop _mainLoop;
  1042. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1043. {
  1044. _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver));
  1045. if (!ConsoleDriver.RunningUnitTests)
  1046. {
  1047. _winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1048. _winConsole._mainLoop = this;
  1049. }
  1050. }
  1051. public EscSeqRequests EscSeqRequests { get; } = new ();
  1052. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1053. {
  1054. _mainLoop = mainLoop;
  1055. if (ConsoleDriver.RunningUnitTests)
  1056. {
  1057. return;
  1058. }
  1059. Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token);
  1060. #if HACK_CHECK_WINCHANGED
  1061. Task.Run (CheckWinChange);
  1062. #endif
  1063. }
  1064. void IMainLoopDriver.Wakeup () { _eventReady.Set (); }
  1065. bool IMainLoopDriver.EventsPending ()
  1066. {
  1067. _waitForProbe.Set ();
  1068. #if HACK_CHECK_WINCHANGED
  1069. _winChange.Set ();
  1070. #endif
  1071. if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout))
  1072. {
  1073. return true;
  1074. }
  1075. try
  1076. {
  1077. if (!_eventReadyTokenSource.IsCancellationRequested)
  1078. {
  1079. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1080. // are no timers, but there IS an idle handler waiting.
  1081. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1082. }
  1083. }
  1084. catch (OperationCanceledException)
  1085. {
  1086. return true;
  1087. }
  1088. finally
  1089. {
  1090. _eventReady.Reset ();
  1091. }
  1092. if (!_eventReadyTokenSource.IsCancellationRequested)
  1093. {
  1094. #if HACK_CHECK_WINCHANGED
  1095. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  1096. #else
  1097. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1098. #endif
  1099. }
  1100. _eventReadyTokenSource.Dispose ();
  1101. _eventReadyTokenSource = new CancellationTokenSource ();
  1102. return true;
  1103. }
  1104. void IMainLoopDriver.Iteration ()
  1105. {
  1106. while (_resultQueue.Count > 0)
  1107. {
  1108. if (_resultQueue.TryDequeue (out WindowsConsole.InputRecord [] inputRecords))
  1109. {
  1110. if (inputRecords is { Length: > 0 })
  1111. {
  1112. ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords [0]);
  1113. }
  1114. }
  1115. }
  1116. #if HACK_CHECK_WINCHANGED
  1117. if (_winChanged)
  1118. {
  1119. _winChanged = false;
  1120. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  1121. }
  1122. #endif
  1123. }
  1124. void IMainLoopDriver.TearDown ()
  1125. {
  1126. _inputHandlerTokenSource?.Cancel ();
  1127. _inputHandlerTokenSource?.Dispose ();
  1128. if (_winConsole is { })
  1129. {
  1130. var numOfEvents = _winConsole.GetNumberOfConsoleInputEvents ();
  1131. if (numOfEvents > 0)
  1132. {
  1133. _winConsole.FlushConsoleInputBuffer ();
  1134. //Debug.WriteLine ($"Flushed {numOfEvents} events.");
  1135. }
  1136. }
  1137. _waitForProbe?.Dispose ();
  1138. _resultQueue?.Clear ();
  1139. _eventReadyTokenSource?.Cancel ();
  1140. _eventReadyTokenSource?.Dispose ();
  1141. _eventReady?.Dispose ();
  1142. #if HACK_CHECK_WINCHANGED
  1143. _winChange?.Dispose ();
  1144. #endif
  1145. _mainLoop = null;
  1146. }
  1147. internal bool _forceRead;
  1148. private void WindowsInputHandler ()
  1149. {
  1150. while (_mainLoop is { })
  1151. {
  1152. try
  1153. {
  1154. if (!_inputHandlerTokenSource.IsCancellationRequested && !_forceRead)
  1155. {
  1156. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1157. }
  1158. }
  1159. catch (OperationCanceledException)
  1160. {
  1161. // Wakes the _waitForProbe if it's waiting
  1162. _waitForProbe.Set ();
  1163. return;
  1164. }
  1165. finally
  1166. {
  1167. // If IsCancellationRequested is true the code after
  1168. // the `finally` block will not be executed.
  1169. if (!_inputHandlerTokenSource.IsCancellationRequested)
  1170. {
  1171. _waitForProbe.Reset ();
  1172. }
  1173. }
  1174. if (_resultQueue?.Count == 0 || _forceRead)
  1175. {
  1176. while (!_inputHandlerTokenSource.IsCancellationRequested)
  1177. {
  1178. WindowsConsole.InputRecord [] inpRec = _winConsole.ReadConsoleInput ();
  1179. if (inpRec is { })
  1180. {
  1181. _resultQueue!.Enqueue (inpRec);
  1182. break;
  1183. }
  1184. if (!_forceRead)
  1185. {
  1186. try
  1187. {
  1188. Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token);
  1189. }
  1190. catch (OperationCanceledException)
  1191. { }
  1192. }
  1193. }
  1194. }
  1195. _eventReady.Set ();
  1196. }
  1197. }
  1198. #if HACK_CHECK_WINCHANGED
  1199. private readonly ManualResetEventSlim _winChange = new (false);
  1200. private bool _winChanged;
  1201. private Size _windowSize;
  1202. private void CheckWinChange ()
  1203. {
  1204. while (_mainLoop is { })
  1205. {
  1206. _winChange.Wait ();
  1207. _winChange.Reset ();
  1208. // Check if the window size changed every half second.
  1209. // We do this to minimize the weird tearing seen on Windows when resizing the console
  1210. while (_mainLoop is { })
  1211. {
  1212. Task.Delay (500).Wait ();
  1213. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  1214. if (_windowSize != Size.Empty
  1215. && (_windowSize.Width != _consoleDriver.Cols
  1216. || _windowSize.Height != _consoleDriver.Rows))
  1217. {
  1218. break;
  1219. }
  1220. }
  1221. _winChanged = true;
  1222. _eventReady.Set ();
  1223. }
  1224. }
  1225. #endif
  1226. }
  1227. internal class WindowsClipboard : ClipboardBase
  1228. {
  1229. private const uint CF_UNICODE_TEXT = 13;
  1230. public override bool IsSupported { get; } = CheckClipboardIsAvailable ();
  1231. private static bool CheckClipboardIsAvailable ()
  1232. {
  1233. // Attempt to open the clipboard
  1234. if (OpenClipboard (nint.Zero))
  1235. {
  1236. // Clipboard is available
  1237. // Close the clipboard after use
  1238. CloseClipboard ();
  1239. return true;
  1240. }
  1241. // Clipboard is not available
  1242. return false;
  1243. }
  1244. protected override string GetClipboardDataImpl ()
  1245. {
  1246. try
  1247. {
  1248. if (!OpenClipboard (nint.Zero))
  1249. {
  1250. return string.Empty;
  1251. }
  1252. nint handle = GetClipboardData (CF_UNICODE_TEXT);
  1253. if (handle == nint.Zero)
  1254. {
  1255. return string.Empty;
  1256. }
  1257. nint pointer = nint.Zero;
  1258. try
  1259. {
  1260. pointer = GlobalLock (handle);
  1261. if (pointer == nint.Zero)
  1262. {
  1263. return string.Empty;
  1264. }
  1265. int size = GlobalSize (handle);
  1266. var buff = new byte [size];
  1267. Marshal.Copy (pointer, buff, 0, size);
  1268. return Encoding.Unicode.GetString (buff).TrimEnd ('\0');
  1269. }
  1270. finally
  1271. {
  1272. if (pointer != nint.Zero)
  1273. {
  1274. GlobalUnlock (handle);
  1275. }
  1276. }
  1277. }
  1278. finally
  1279. {
  1280. CloseClipboard ();
  1281. }
  1282. }
  1283. protected override void SetClipboardDataImpl (string text)
  1284. {
  1285. OpenClipboard ();
  1286. EmptyClipboard ();
  1287. nint hGlobal = default;
  1288. try
  1289. {
  1290. int bytes = (text.Length + 1) * 2;
  1291. hGlobal = Marshal.AllocHGlobal (bytes);
  1292. if (hGlobal == default (nint))
  1293. {
  1294. ThrowWin32 ();
  1295. }
  1296. nint target = GlobalLock (hGlobal);
  1297. if (target == default (nint))
  1298. {
  1299. ThrowWin32 ();
  1300. }
  1301. try
  1302. {
  1303. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1304. }
  1305. finally
  1306. {
  1307. GlobalUnlock (target);
  1308. }
  1309. if (SetClipboardData (CF_UNICODE_TEXT, hGlobal) == default (nint))
  1310. {
  1311. ThrowWin32 ();
  1312. }
  1313. hGlobal = default (nint);
  1314. }
  1315. finally
  1316. {
  1317. if (hGlobal != default (nint))
  1318. {
  1319. Marshal.FreeHGlobal (hGlobal);
  1320. }
  1321. CloseClipboard ();
  1322. }
  1323. }
  1324. [DllImport ("user32.dll", SetLastError = true)]
  1325. [return: MarshalAs (UnmanagedType.Bool)]
  1326. private static extern bool CloseClipboard ();
  1327. [DllImport ("user32.dll")]
  1328. private static extern bool EmptyClipboard ();
  1329. [DllImport ("user32.dll", SetLastError = true)]
  1330. private static extern nint GetClipboardData (uint uFormat);
  1331. [DllImport ("kernel32.dll", SetLastError = true)]
  1332. private static extern nint GlobalLock (nint hMem);
  1333. [DllImport ("kernel32.dll", SetLastError = true)]
  1334. private static extern int GlobalSize (nint handle);
  1335. [DllImport ("kernel32.dll", SetLastError = true)]
  1336. [return: MarshalAs (UnmanagedType.Bool)]
  1337. private static extern bool GlobalUnlock (nint hMem);
  1338. [DllImport ("User32.dll", SetLastError = true)]
  1339. [return: MarshalAs (UnmanagedType.Bool)]
  1340. private static extern bool IsClipboardFormatAvailable (uint format);
  1341. private void OpenClipboard ()
  1342. {
  1343. var num = 10;
  1344. while (true)
  1345. {
  1346. if (OpenClipboard (default (nint)))
  1347. {
  1348. break;
  1349. }
  1350. if (--num == 0)
  1351. {
  1352. ThrowWin32 ();
  1353. }
  1354. Thread.Sleep (100);
  1355. }
  1356. }
  1357. [DllImport ("user32.dll", SetLastError = true)]
  1358. [return: MarshalAs (UnmanagedType.Bool)]
  1359. private static extern bool OpenClipboard (nint hWndNewOwner);
  1360. [DllImport ("user32.dll", SetLastError = true)]
  1361. private static extern nint SetClipboardData (uint uFormat, nint data);
  1362. private void ThrowWin32 () { throw new Win32Exception (Marshal.GetLastWin32Error ()); }
  1363. }