WindowsDriver.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  1. #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.ComponentModel;
  17. using System.Diagnostics;
  18. using System.Runtime.InteropServices;
  19. using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping;
  20. namespace Terminal.Gui;
  21. internal class WindowsDriver : ConsoleDriver
  22. {
  23. private readonly bool _isWindowsTerminal;
  24. private WindowsConsole.SmallRect _damageRegion;
  25. private bool _isButtonDoubleClicked;
  26. private bool _isButtonPressed;
  27. private bool _isButtonReleased;
  28. private bool _isOneFingerDoubleClicked;
  29. private WindowsConsole.ButtonState? _lastMouseButtonPressed;
  30. private WindowsMainLoop? _mainLoopDriver;
  31. private WindowsConsole.ExtendedCharInfo [] _outputBuffer;
  32. private Point? _point;
  33. private Point _pointMove;
  34. private bool _processButtonClick;
  35. public WindowsDriver ()
  36. {
  37. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  38. {
  39. WinConsole = new ();
  40. // otherwise we're probably running in unit tests
  41. Clipboard = new WindowsClipboard ();
  42. }
  43. else
  44. {
  45. Clipboard = new FakeDriver.FakeClipboard ();
  46. }
  47. // TODO: if some other Windows-based terminal supports true color, update this logic to not
  48. // force 16color mode (.e.g ConEmu which really doesn't work well at all).
  49. _isWindowsTerminal = _isWindowsTerminal =
  50. Environment.GetEnvironmentVariable ("WT_SESSION") is { } || Environment.GetEnvironmentVariable ("VSAPPIDNAME") != null;
  51. if (!_isWindowsTerminal)
  52. {
  53. Force16Colors = true;
  54. }
  55. }
  56. public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931 && _isWindowsTerminal);
  57. public WindowsConsole? WinConsole { get; private set; }
  58. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  59. {
  60. if (keyEvent.wVirtualKeyCode != (VK)ConsoleKey.Packet)
  61. {
  62. return keyEvent;
  63. }
  64. var mod = new ConsoleModifiers ();
  65. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  66. {
  67. mod |= ConsoleModifiers.Shift;
  68. }
  69. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  70. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  71. {
  72. mod |= ConsoleModifiers.Alt;
  73. }
  74. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)
  75. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed))
  76. {
  77. mod |= ConsoleModifiers.Control;
  78. }
  79. var cKeyInfo = new ConsoleKeyInfo (
  80. keyEvent.UnicodeChar,
  81. (ConsoleKey)keyEvent.wVirtualKeyCode,
  82. mod.HasFlag (ConsoleModifiers.Shift),
  83. mod.HasFlag (ConsoleModifiers.Alt),
  84. mod.HasFlag (ConsoleModifiers.Control));
  85. cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  86. uint scanCode = GetScanCodeFromConsoleKeyInfo (cKeyInfo);
  87. return new WindowsConsole.KeyEventRecord
  88. {
  89. UnicodeChar = cKeyInfo.KeyChar,
  90. bKeyDown = keyEvent.bKeyDown,
  91. dwControlKeyState = keyEvent.dwControlKeyState,
  92. wRepeatCount = keyEvent.wRepeatCount,
  93. wVirtualKeyCode = (VK)cKeyInfo.Key,
  94. wVirtualScanCode = (ushort)scanCode
  95. };
  96. }
  97. public override bool IsRuneSupported (Rune rune) { return base.IsRuneSupported (rune) && rune.IsBmp; }
  98. public override void Refresh ()
  99. {
  100. if (!RunningUnitTests)
  101. {
  102. UpdateScreen ();
  103. //WinConsole?.SetInitialCursorVisibility ();
  104. UpdateCursor ();
  105. }
  106. }
  107. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  108. {
  109. var input = new WindowsConsole.InputRecord
  110. {
  111. EventType = WindowsConsole.EventType.Key
  112. };
  113. var keyEvent = new WindowsConsole.KeyEventRecord
  114. {
  115. bKeyDown = true
  116. };
  117. var controlKey = new WindowsConsole.ControlKeyState ();
  118. if (shift)
  119. {
  120. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  121. keyEvent.UnicodeChar = '\0';
  122. keyEvent.wVirtualKeyCode = VK.SHIFT;
  123. }
  124. if (alt)
  125. {
  126. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  127. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  128. keyEvent.UnicodeChar = '\0';
  129. keyEvent.wVirtualKeyCode = VK.MENU;
  130. }
  131. if (control)
  132. {
  133. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  134. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  135. keyEvent.UnicodeChar = '\0';
  136. keyEvent.wVirtualKeyCode = VK.CONTROL;
  137. }
  138. keyEvent.dwControlKeyState = controlKey;
  139. input.KeyEvent = keyEvent;
  140. if (shift || alt || control)
  141. {
  142. ProcessInput (input);
  143. }
  144. keyEvent.UnicodeChar = keyChar;
  145. //if ((uint)key < 255) {
  146. // keyEvent.wVirtualKeyCode = (ushort)key;
  147. //} else {
  148. // keyEvent.wVirtualKeyCode = '\0';
  149. //}
  150. keyEvent.wVirtualKeyCode = (VK)key;
  151. input.KeyEvent = keyEvent;
  152. try
  153. {
  154. ProcessInput (input);
  155. }
  156. catch (OverflowException)
  157. { }
  158. finally
  159. {
  160. keyEvent.bKeyDown = false;
  161. input.KeyEvent = keyEvent;
  162. ProcessInput (input);
  163. }
  164. }
  165. private readonly ManualResetEventSlim _waitAnsiResponse = new (false);
  166. private CancellationTokenSource? _ansiResponseTokenSource;
  167. /// <inheritdoc/>
  168. public override bool TryWriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest)
  169. {
  170. if (_mainLoopDriver is null)
  171. {
  172. return false;
  173. }
  174. _ansiResponseTokenSource ??= new ();
  175. try
  176. {
  177. lock (ansiRequest._responseLock)
  178. {
  179. ansiRequest.ResponseFromInput += (s, e) =>
  180. {
  181. Debug.Assert (s == ansiRequest);
  182. Debug.Assert (e == ansiRequest.AnsiEscapeSequenceResponse);
  183. _waitAnsiResponse.Set ();
  184. };
  185. _mainLoopDriver.EscSeqRequests.Add (ansiRequest, this);
  186. _mainLoopDriver._forceRead = true;
  187. }
  188. _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token);
  189. }
  190. catch (OperationCanceledException)
  191. {
  192. return false;
  193. }
  194. lock (ansiRequest._responseLock)
  195. {
  196. _mainLoopDriver._forceRead = false;
  197. if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus? request))
  198. {
  199. if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0
  200. && string.IsNullOrEmpty (request.AnsiRequest.AnsiEscapeSequenceResponse?.Response))
  201. {
  202. lock (request.AnsiRequest._responseLock)
  203. {
  204. // Bad request or no response at all
  205. _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _);
  206. }
  207. }
  208. }
  209. _waitAnsiResponse.Reset ();
  210. return ansiRequest.AnsiEscapeSequenceResponse is { Valid: true };
  211. }
  212. }
  213. internal override void WriteRaw (string ansi)
  214. {
  215. WinConsole?.WriteANSI (ansi);
  216. }
  217. #region Not Implemented
  218. public override void Suspend () { throw new NotImplementedException (); }
  219. #endregion
  220. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  221. {
  222. WindowsConsole.ControlKeyState state = keyEvent.dwControlKeyState;
  223. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  224. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  225. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  226. bool capslock = (state & WindowsConsole.ControlKeyState.CapslockOn) != 0;
  227. bool numlock = (state & WindowsConsole.ControlKeyState.NumlockOn) != 0;
  228. bool scrolllock = (state & WindowsConsole.ControlKeyState.ScrolllockOn) != 0;
  229. var cki = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  230. return new WindowsConsole.ConsoleKeyInfoEx (cki, capslock, numlock, scrolllock);
  231. }
  232. #region Cursor Handling
  233. private CursorVisibility? _cachedCursorVisibility;
  234. public override void UpdateCursor ()
  235. {
  236. if (Col < 0 || Row < 0 || Col >= Cols || Row >= Rows)
  237. {
  238. GetCursorVisibility (out CursorVisibility cursorVisibility);
  239. _cachedCursorVisibility = cursorVisibility;
  240. SetCursorVisibility (CursorVisibility.Invisible);
  241. return;
  242. }
  243. var position = new WindowsConsole.Coord
  244. {
  245. X = (short)Col,
  246. Y = (short)Row
  247. };
  248. if (Force16Colors)
  249. {
  250. WinConsole?.SetCursorPosition (position);
  251. }
  252. else
  253. {
  254. var sb = new StringBuilder ();
  255. sb.Append (AnsiEscapeSequenceRequestUtils.CSI_SetCursorPosition (position.Y + 1, position.X + 1));
  256. WinConsole?.WriteANSI (sb.ToString ());
  257. }
  258. if (_cachedCursorVisibility is { })
  259. {
  260. SetCursorVisibility (_cachedCursorVisibility.Value);
  261. }
  262. //EnsureCursorVisibility ();
  263. }
  264. /// <inheritdoc/>
  265. public override bool GetCursorVisibility (out CursorVisibility visibility)
  266. {
  267. if (WinConsole is { })
  268. {
  269. return WinConsole.GetCursorVisibility (out visibility);
  270. }
  271. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  272. return true;
  273. }
  274. /// <inheritdoc/>
  275. public override bool SetCursorVisibility (CursorVisibility visibility)
  276. {
  277. _cachedCursorVisibility = visibility;
  278. if (Force16Colors)
  279. {
  280. return WinConsole is null || WinConsole.SetCursorVisibility (visibility);
  281. }
  282. else
  283. {
  284. var sb = new StringBuilder ();
  285. sb.Append (visibility != CursorVisibility.Invisible ? AnsiEscapeSequenceRequestUtils.CSI_ShowCursor : AnsiEscapeSequenceRequestUtils.CSI_HideCursor);
  286. return WinConsole?.WriteANSI (sb.ToString ()) ?? false;
  287. }
  288. }
  289. /// <inheritdoc/>
  290. public override bool EnsureCursorVisibility ()
  291. {
  292. if (Force16Colors)
  293. {
  294. return WinConsole is null || WinConsole.EnsureCursorVisibility ();
  295. }
  296. else
  297. {
  298. var sb = new StringBuilder ();
  299. sb.Append (_cachedCursorVisibility != CursorVisibility.Invisible ? AnsiEscapeSequenceRequestUtils.CSI_ShowCursor : AnsiEscapeSequenceRequestUtils.CSI_HideCursor);
  300. return WinConsole?.WriteANSI (sb.ToString ()) ?? false;
  301. }
  302. //if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  303. //{
  304. // GetCursorVisibility (out CursorVisibility cursorVisibility);
  305. // _cachedCursorVisibility = cursorVisibility;
  306. // SetCursorVisibility (CursorVisibility.Invisible);
  307. // return false;
  308. //}
  309. //SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default);
  310. //return _cachedCursorVisibility == CursorVisibility.Default;
  311. }
  312. #endregion Cursor Handling
  313. public override void UpdateScreen ()
  314. {
  315. Size windowSize = WinConsole?.GetConsoleOutputWindow (out Point _) ?? new Size (Cols, Rows);
  316. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows))
  317. {
  318. return;
  319. }
  320. var bufferCoords = new WindowsConsole.Coord
  321. {
  322. X = (short)Cols, //Clip.Width,
  323. Y = (short)Rows, //Clip.Height
  324. };
  325. for (var row = 0; row < Rows; row++)
  326. {
  327. if (!_dirtyLines! [row])
  328. {
  329. continue;
  330. }
  331. _dirtyLines [row] = false;
  332. for (var col = 0; col < Cols; col++)
  333. {
  334. int position = row * Cols + col;
  335. _outputBuffer [position].Attribute = Contents! [row, col].Attribute.GetValueOrDefault ();
  336. if (Contents [row, col].IsDirty == false)
  337. {
  338. _outputBuffer [position].Empty = true;
  339. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  340. continue;
  341. }
  342. _outputBuffer [position].Empty = false;
  343. if (Contents [row, col].Rune.IsBmp)
  344. {
  345. _outputBuffer [position].Char = (char)Contents [row, col].Rune.Value;
  346. }
  347. else
  348. {
  349. //_outputBuffer [position].Empty = true;
  350. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  351. if (Contents [row, col].Rune.GetColumns () > 1 && col + 1 < Cols)
  352. {
  353. // TODO: This is a hack to deal with non-BMP and wide characters.
  354. col++;
  355. position = row * Cols + col;
  356. _outputBuffer [position].Empty = false;
  357. _outputBuffer [position].Char = ' ';
  358. }
  359. }
  360. }
  361. }
  362. _damageRegion = new WindowsConsole.SmallRect
  363. {
  364. Top = 0,
  365. Left = 0,
  366. Bottom = (short)Rows,
  367. Right = (short)Cols
  368. };
  369. if (!RunningUnitTests
  370. && WinConsole != null
  371. && !WinConsole.WriteToConsole (new (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors))
  372. {
  373. int err = Marshal.GetLastWin32Error ();
  374. if (err != 0)
  375. {
  376. throw new Win32Exception (err);
  377. }
  378. }
  379. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  380. }
  381. internal override void End ()
  382. {
  383. if (_mainLoopDriver is { })
  384. {
  385. #if HACK_CHECK_WINCHANGED
  386. _mainLoopDriver.WinChanged -= ChangeWin;
  387. #endif
  388. }
  389. _mainLoopDriver = null;
  390. WinConsole?.Cleanup ();
  391. WinConsole = null;
  392. if (!RunningUnitTests && _isWindowsTerminal)
  393. {
  394. // Disable alternative screen buffer.
  395. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  396. }
  397. }
  398. internal override MainLoop Init ()
  399. {
  400. _mainLoopDriver = new WindowsMainLoop (this);
  401. if (!RunningUnitTests)
  402. {
  403. try
  404. {
  405. if (WinConsole is { })
  406. {
  407. // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init.
  408. // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED
  409. Size winSize = WinConsole.GetConsoleOutputWindow (out Point _);
  410. Cols = winSize.Width;
  411. Rows = winSize.Height;
  412. }
  413. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  414. if (_isWindowsTerminal)
  415. {
  416. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  417. }
  418. }
  419. catch (Win32Exception e)
  420. {
  421. // We are being run in an environment that does not support a console
  422. // such as a unit test, or a pipe.
  423. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  424. WinConsole = null;
  425. }
  426. }
  427. CurrentAttribute = new Attribute (Color.White, Color.Black);
  428. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  429. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  430. Clip = new (0, 0, Cols, Rows);
  431. _damageRegion = new WindowsConsole.SmallRect
  432. {
  433. Top = 0,
  434. Left = 0,
  435. Bottom = (short)Rows,
  436. Right = (short)Cols
  437. };
  438. ClearContents ();
  439. #if HACK_CHECK_WINCHANGED
  440. _mainLoopDriver.WinChanged = ChangeWin;
  441. #endif
  442. if (!RunningUnitTests)
  443. {
  444. WinConsole?.SetInitialCursorVisibility ();
  445. }
  446. return new MainLoop (_mainLoopDriver);
  447. }
  448. internal void ProcessInput (WindowsConsole.InputRecord inputEvent)
  449. {
  450. switch (inputEvent.EventType)
  451. {
  452. case WindowsConsole.EventType.Key:
  453. if (inputEvent.KeyEvent.wVirtualKeyCode == (VK)ConsoleKey.Packet)
  454. {
  455. // Used to pass Unicode characters as if they were keystrokes.
  456. // The VK_PACKET key is the low word of a 32-bit
  457. // Virtual Key value used for non-keyboard input methods.
  458. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  459. }
  460. WindowsConsole.ConsoleKeyInfoEx keyInfo = ToConsoleKeyInfoEx (inputEvent.KeyEvent);
  461. //Debug.WriteLine ($"event: KBD: {GetKeyboardLayoutName()} {inputEvent.ToString ()} {keyInfo.ToString (keyInfo)}");
  462. KeyCode map = MapKey (keyInfo);
  463. if (map == KeyCode.Null)
  464. {
  465. break;
  466. }
  467. if (inputEvent.KeyEvent.bKeyDown)
  468. {
  469. // Avoid sending repeat key down events
  470. OnKeyDown (new Key (map));
  471. }
  472. else
  473. {
  474. OnKeyUp (new Key (map));
  475. }
  476. break;
  477. case WindowsConsole.EventType.Mouse:
  478. MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent);
  479. if (me.Flags == MouseFlags.None)
  480. {
  481. break;
  482. }
  483. OnMouseEvent (me);
  484. if (_processButtonClick)
  485. {
  486. OnMouseEvent (new ()
  487. {
  488. Position = me.Position,
  489. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  490. });
  491. }
  492. break;
  493. case WindowsConsole.EventType.Focus:
  494. break;
  495. #if !HACK_CHECK_WINCHANGED
  496. case WindowsConsole.EventType.WindowBufferSize:
  497. Cols = inputEvent.WindowBufferSizeEvent._size.X;
  498. Rows = inputEvent.WindowBufferSizeEvent._size.Y;
  499. ResizeScreen ();
  500. ClearContents ();
  501. Application.Top?.SetNeedsLayout ();
  502. Application.Refresh ();
  503. break;
  504. #endif
  505. }
  506. }
  507. #if HACK_CHECK_WINCHANGED
  508. private void ChangeWin (object s, SizeChangedEventArgs e)
  509. {
  510. if (e.Size is null)
  511. {
  512. return;
  513. }
  514. int w = e.Size.Value.Width;
  515. if (w == Cols - 3 && e.Size.Value.Height < Rows)
  516. {
  517. w += 3;
  518. }
  519. Left = 0;
  520. Top = 0;
  521. Cols = e.Size.Value.Width;
  522. Rows = e.Size.Value.Height;
  523. if (!RunningUnitTests)
  524. {
  525. Size newSize = WinConsole.SetConsoleWindow (
  526. (short)Math.Max (w, 16),
  527. (short)Math.Max (e.Size.Value.Height, 0));
  528. Cols = newSize.Width;
  529. Rows = newSize.Height;
  530. }
  531. ResizeScreen ();
  532. ClearContents ();
  533. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  534. }
  535. #endif
  536. private KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  537. {
  538. ConsoleKeyInfo keyInfo = keyInfoEx.ConsoleKeyInfo;
  539. switch (keyInfo.Key)
  540. {
  541. case ConsoleKey.D0:
  542. case ConsoleKey.D1:
  543. case ConsoleKey.D2:
  544. case ConsoleKey.D3:
  545. case ConsoleKey.D4:
  546. case ConsoleKey.D5:
  547. case ConsoleKey.D6:
  548. case ConsoleKey.D7:
  549. case ConsoleKey.D8:
  550. case ConsoleKey.D9:
  551. case ConsoleKey.NumPad0:
  552. case ConsoleKey.NumPad1:
  553. case ConsoleKey.NumPad2:
  554. case ConsoleKey.NumPad3:
  555. case ConsoleKey.NumPad4:
  556. case ConsoleKey.NumPad5:
  557. case ConsoleKey.NumPad6:
  558. case ConsoleKey.NumPad7:
  559. case ConsoleKey.NumPad8:
  560. case ConsoleKey.NumPad9:
  561. case ConsoleKey.Oem1:
  562. case ConsoleKey.Oem2:
  563. case ConsoleKey.Oem3:
  564. case ConsoleKey.Oem4:
  565. case ConsoleKey.Oem5:
  566. case ConsoleKey.Oem6:
  567. case ConsoleKey.Oem7:
  568. case ConsoleKey.Oem8:
  569. case ConsoleKey.Oem102:
  570. case ConsoleKey.Multiply:
  571. case ConsoleKey.Add:
  572. case ConsoleKey.Separator:
  573. case ConsoleKey.Subtract:
  574. case ConsoleKey.Decimal:
  575. case ConsoleKey.Divide:
  576. case ConsoleKey.OemPeriod:
  577. case ConsoleKey.OemComma:
  578. case ConsoleKey.OemPlus:
  579. case ConsoleKey.OemMinus:
  580. // These virtual key codes are mapped differently depending on the keyboard layout in use.
  581. // We use the Win32 API to map them to the correct character.
  582. uint mapResult = MapVKtoChar ((VK)keyInfo.Key);
  583. if (mapResult == 0)
  584. {
  585. // There is no mapping - this should not happen
  586. Debug.Assert (true, $@"Unable to map the virtual key code {keyInfo.Key}.");
  587. return KeyCode.Null;
  588. }
  589. // An un-shifted character value is in the low order word of the return value.
  590. var mappedChar = (char)(mapResult & 0x0000FFFF);
  591. if (keyInfo.KeyChar == 0)
  592. {
  593. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  594. // Dead keys (diacritics) are indicated by setting the top bit of the return value.
  595. if ((mapResult & 0x80000000) != 0)
  596. {
  597. // Dead key (e.g. Oem2 '~'/'^' on POR keyboard)
  598. // Option 1: Throw it out.
  599. // - Apps will never see the dead keys
  600. // - If user presses a key that can be combined with the dead key ('a'), the right thing happens (app will see '�').
  601. // - NOTE: With Dead Keys, KeyDown != KeyUp. The KeyUp event will have just the base char ('a').
  602. // - If user presses dead key again, the right thing happens (app will see `~~`)
  603. // - This is what Notepad etc... appear to do
  604. // Option 2: Expand the API to indicate the KeyCode is a dead key
  605. // - Enables apps to do their own dead key processing
  606. // - Adds complexity; no dev has asked for this (yet).
  607. // We choose Option 1 for now.
  608. return KeyCode.Null;
  609. // Note: Ctrl-Deadkey (like Oem3 '`'/'~` on ENG) can't be supported.
  610. // Sadly, the charVal is just the deadkey and subsequent key events do not contain
  611. // any info that the previous event was a deadkey.
  612. // Note WT does not support Ctrl-Deadkey either.
  613. }
  614. if (keyInfo.Modifiers != 0)
  615. {
  616. // These Oem keys have well-defined chars. We ensure the representative char is used.
  617. // If we don't do this, then on some keyboard layouts the wrong char is
  618. // returned (e.g. on ENG OemPlus un-shifted is =, not +). This is important
  619. // for key persistence ("Ctrl++" vs. "Ctrl+=").
  620. mappedChar = keyInfo.Key switch
  621. {
  622. ConsoleKey.OemPeriod => '.',
  623. ConsoleKey.OemComma => ',',
  624. ConsoleKey.OemPlus => '+',
  625. ConsoleKey.OemMinus => '-',
  626. _ => mappedChar
  627. };
  628. }
  629. // Return the mappedChar with modifiers. Because mappedChar is un-shifted, if Shift was down
  630. // we should keep it
  631. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  632. }
  633. // KeyChar is printable
  634. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  635. {
  636. // AltGr support - AltGr is equivalent to Ctrl+Alt - the correct char is in KeyChar
  637. return (KeyCode)keyInfo.KeyChar;
  638. }
  639. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  640. {
  641. // If Shift wasn't down we don't need to do anything but return the mappedChar
  642. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  643. }
  644. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "�")
  645. // and passing on Shift would be redundant.
  646. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  647. }
  648. // A..Z are special cased:
  649. // - Alone, they represent lowercase a...z
  650. // - With ShiftMask they are A..Z
  651. // - If CapsLock is on the above is reversed.
  652. // - If Alt and/or Ctrl are present, treat as upper case
  653. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z)
  654. {
  655. if (keyInfo.KeyChar == 0)
  656. {
  657. // KeyChar is not printable - possibly an AltGr key?
  658. // AltGr support - AltGr is equivalent to Ctrl+Alt
  659. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  660. {
  661. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  662. }
  663. }
  664. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  665. {
  666. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  667. }
  668. if ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ keyInfoEx.CapsLock)
  669. {
  670. // If (ShiftMask is on and CapsLock is off) or (ShiftMask is off and CapsLock is on) add the ShiftMask
  671. if (char.IsUpper (keyInfo.KeyChar))
  672. {
  673. if (keyInfo.KeyChar <= 'Z')
  674. {
  675. return (KeyCode)keyInfo.Key | KeyCode.ShiftMask;
  676. }
  677. // Always return the KeyChar because it may be an Á, À with Oem1, etc
  678. return (KeyCode)keyInfo.KeyChar;
  679. }
  680. }
  681. if (keyInfo.KeyChar <= 'z')
  682. {
  683. return (KeyCode)keyInfo.Key;
  684. }
  685. // Always return the KeyChar because it may be an á, à with Oem1, etc
  686. return (KeyCode)keyInfo.KeyChar;
  687. }
  688. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  689. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  690. {
  691. // If the key is JUST a modifier, return it as just that key
  692. if (keyInfo.Key == (ConsoleKey)VK.SHIFT)
  693. { // Shift 16
  694. return KeyCode.ShiftMask;
  695. }
  696. if (keyInfo.Key == (ConsoleKey)VK.CONTROL)
  697. { // Ctrl 17
  698. return KeyCode.CtrlMask;
  699. }
  700. if (keyInfo.Key == (ConsoleKey)VK.MENU)
  701. { // Alt 18
  702. return KeyCode.AltMask;
  703. }
  704. if (keyInfo.KeyChar == 0)
  705. {
  706. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  707. }
  708. if (keyInfo.Key != ConsoleKey.None)
  709. {
  710. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  711. }
  712. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  713. }
  714. // Handle control keys (e.g. CursorUp)
  715. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  716. {
  717. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  718. }
  719. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  720. }
  721. private MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  722. {
  723. MouseFlags mouseFlag = 0;
  724. switch (_lastMouseButtonPressed)
  725. {
  726. case WindowsConsole.ButtonState.Button1Pressed:
  727. mouseFlag = MouseFlags.Button1Clicked;
  728. break;
  729. case WindowsConsole.ButtonState.Button2Pressed:
  730. mouseFlag = MouseFlags.Button2Clicked;
  731. break;
  732. case WindowsConsole.ButtonState.RightmostButtonPressed:
  733. mouseFlag = MouseFlags.Button3Clicked;
  734. break;
  735. }
  736. _point = new Point
  737. {
  738. X = mouseEvent.MousePosition.X,
  739. Y = mouseEvent.MousePosition.Y
  740. };
  741. _lastMouseButtonPressed = null;
  742. _isButtonReleased = false;
  743. _processButtonClick = false;
  744. _point = null;
  745. return mouseFlag;
  746. }
  747. private async Task ProcessButtonDoubleClickedAsync ()
  748. {
  749. await Task.Delay (200);
  750. _isButtonDoubleClicked = false;
  751. _isOneFingerDoubleClicked = false;
  752. //buttonPressedCount = 0;
  753. }
  754. private async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  755. {
  756. // When a user presses-and-holds, start generating pressed events every `startDelay`
  757. // After `iterationsUntilFast` iterations, speed them up to `fastDelay` ms
  758. const int START_DELAY = 500;
  759. const int ITERATIONS_UNTIL_FAST = 4;
  760. const int FAST_DELAY = 50;
  761. int iterations = 0;
  762. int delay = START_DELAY;
  763. while (_isButtonPressed)
  764. {
  765. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  766. View? view = Application.WantContinuousButtonPressedView;
  767. if (view is null)
  768. {
  769. break;
  770. }
  771. if (iterations++ >= ITERATIONS_UNTIL_FAST)
  772. {
  773. delay = FAST_DELAY;
  774. }
  775. await Task.Delay (delay);
  776. var me = new MouseEventArgs
  777. {
  778. ScreenPosition = _pointMove,
  779. Flags = mouseFlag
  780. };
  781. //Debug.WriteLine($"ProcessContinuousButtonPressedAsync: {view}");
  782. if (_isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0)
  783. {
  784. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  785. Application.Invoke (() => OnMouseEvent (me));
  786. }
  787. }
  788. }
  789. private void ResizeScreen ()
  790. {
  791. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  792. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  793. Clip = new (0, 0, Cols, Rows);
  794. _damageRegion = new WindowsConsole.SmallRect
  795. {
  796. Top = 0,
  797. Left = 0,
  798. Bottom = (short)Rows,
  799. Right = (short)Cols
  800. };
  801. _dirtyLines = new bool [Rows];
  802. WinConsole?.ForceRefreshCursorVisibility ();
  803. }
  804. private static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  805. {
  806. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)
  807. || mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  808. {
  809. mouseFlag |= MouseFlags.ButtonCtrl;
  810. }
  811. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  812. {
  813. mouseFlag |= MouseFlags.ButtonShift;
  814. }
  815. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  816. || mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  817. {
  818. mouseFlag |= MouseFlags.ButtonAlt;
  819. }
  820. return mouseFlag;
  821. }
  822. [CanBeNull]
  823. private MouseEventArgs ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  824. {
  825. var mouseFlag = MouseFlags.AllEvents;
  826. //Debug.WriteLine ($"ToDriverMouse: {mouseEvent}");
  827. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked)
  828. {
  829. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  830. Application.MainLoop!.AddIdle (
  831. () =>
  832. {
  833. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  834. return false;
  835. });
  836. }
  837. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  838. // This will tell when a mouse button is pressed. When the button is released this event will
  839. // be fired with its bit set to 0. So when the button is up ButtonState will be 0.
  840. // To map to the correct driver events we save the last pressed mouse button, so we can
  841. // map to the correct clicked event.
  842. if ((_lastMouseButtonPressed is { } || _isButtonReleased) && mouseEvent.ButtonState != 0)
  843. {
  844. _lastMouseButtonPressed = null;
  845. //isButtonPressed = false;
  846. _isButtonReleased = false;
  847. }
  848. var p = new Point
  849. {
  850. X = mouseEvent.MousePosition.X,
  851. Y = mouseEvent.MousePosition.Y
  852. };
  853. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed is null && !_isButtonDoubleClicked)
  854. || (_lastMouseButtonPressed == null
  855. && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved)
  856. && mouseEvent.ButtonState != 0
  857. && !_isButtonReleased
  858. && !_isButtonDoubleClicked))
  859. {
  860. switch (mouseEvent.ButtonState)
  861. {
  862. case WindowsConsole.ButtonState.Button1Pressed:
  863. mouseFlag = MouseFlags.Button1Pressed;
  864. break;
  865. case WindowsConsole.ButtonState.Button2Pressed:
  866. mouseFlag = MouseFlags.Button2Pressed;
  867. break;
  868. case WindowsConsole.ButtonState.RightmostButtonPressed:
  869. mouseFlag = MouseFlags.Button3Pressed;
  870. break;
  871. }
  872. if (_point is null)
  873. {
  874. _point = p;
  875. }
  876. if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved))
  877. {
  878. _pointMove = p;
  879. mouseFlag |= MouseFlags.ReportMousePosition;
  880. _isButtonReleased = false;
  881. _processButtonClick = false;
  882. }
  883. _lastMouseButtonPressed = mouseEvent.ButtonState;
  884. _isButtonPressed = true;
  885. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0)
  886. {
  887. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  888. Application.MainLoop!.AddIdle (
  889. () =>
  890. {
  891. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  892. return false;
  893. });
  894. }
  895. }
  896. else if (_lastMouseButtonPressed != null
  897. && mouseEvent.EventFlags == 0
  898. && !_isButtonReleased
  899. && !_isButtonDoubleClicked
  900. && !_isOneFingerDoubleClicked)
  901. {
  902. switch (_lastMouseButtonPressed)
  903. {
  904. case WindowsConsole.ButtonState.Button1Pressed:
  905. mouseFlag = MouseFlags.Button1Released;
  906. break;
  907. case WindowsConsole.ButtonState.Button2Pressed:
  908. mouseFlag = MouseFlags.Button2Released;
  909. break;
  910. case WindowsConsole.ButtonState.RightmostButtonPressed:
  911. mouseFlag = MouseFlags.Button3Released;
  912. break;
  913. }
  914. _isButtonPressed = false;
  915. _isButtonReleased = true;
  916. if (_point is { } && ((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)
  917. {
  918. _processButtonClick = true;
  919. }
  920. else
  921. {
  922. _point = null;
  923. }
  924. _processButtonClick = true;
  925. }
  926. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  927. && !_isOneFingerDoubleClicked
  928. && _isButtonReleased
  929. && p == _point)
  930. {
  931. mouseFlag = ProcessButtonClick (mouseEvent);
  932. }
  933. else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick))
  934. {
  935. switch (mouseEvent.ButtonState)
  936. {
  937. case WindowsConsole.ButtonState.Button1Pressed:
  938. mouseFlag = MouseFlags.Button1DoubleClicked;
  939. break;
  940. case WindowsConsole.ButtonState.Button2Pressed:
  941. mouseFlag = MouseFlags.Button2DoubleClicked;
  942. break;
  943. case WindowsConsole.ButtonState.RightmostButtonPressed:
  944. mouseFlag = MouseFlags.Button3DoubleClicked;
  945. break;
  946. }
  947. _isButtonDoubleClicked = true;
  948. }
  949. else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked)
  950. {
  951. switch (mouseEvent.ButtonState)
  952. {
  953. case WindowsConsole.ButtonState.Button1Pressed:
  954. mouseFlag = MouseFlags.Button1TripleClicked;
  955. break;
  956. case WindowsConsole.ButtonState.Button2Pressed:
  957. mouseFlag = MouseFlags.Button2TripleClicked;
  958. break;
  959. case WindowsConsole.ButtonState.RightmostButtonPressed:
  960. mouseFlag = MouseFlags.Button3TripleClicked;
  961. break;
  962. }
  963. _isButtonDoubleClicked = false;
  964. }
  965. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled)
  966. {
  967. switch ((int)mouseEvent.ButtonState)
  968. {
  969. case int v when v > 0:
  970. mouseFlag = MouseFlags.WheeledUp;
  971. break;
  972. case int v when v < 0:
  973. mouseFlag = MouseFlags.WheeledDown;
  974. break;
  975. }
  976. }
  977. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled && mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed)
  978. {
  979. switch ((int)mouseEvent.ButtonState)
  980. {
  981. case int v when v > 0:
  982. mouseFlag = MouseFlags.WheeledLeft;
  983. break;
  984. case int v when v < 0:
  985. mouseFlag = MouseFlags.WheeledRight;
  986. break;
  987. }
  988. }
  989. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled)
  990. {
  991. switch ((int)mouseEvent.ButtonState)
  992. {
  993. case int v when v < 0:
  994. mouseFlag = MouseFlags.WheeledLeft;
  995. break;
  996. case int v when v > 0:
  997. mouseFlag = MouseFlags.WheeledRight;
  998. break;
  999. }
  1000. }
  1001. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved)
  1002. {
  1003. mouseFlag = MouseFlags.ReportMousePosition;
  1004. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y)
  1005. {
  1006. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  1007. }
  1008. }
  1009. else if (mouseEvent is { ButtonState: 0, EventFlags: 0 })
  1010. {
  1011. // This happens on a double or triple click event.
  1012. mouseFlag = MouseFlags.None;
  1013. }
  1014. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  1015. //System.Diagnostics.Debug.WriteLine (
  1016. // $"point.X:{(point is { } ? ((Point)point).X : -1)};point.Y:{(point is { } ? ((Point)point).Y : -1)}");
  1017. return new MouseEventArgs
  1018. {
  1019. Position = new (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y),
  1020. Flags = mouseFlag
  1021. };
  1022. }
  1023. }