WindowsDriver.cs 41 KB

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