WindowsDriver.cs 54 KB

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