WindowsDriver.cs 43 KB

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