In Docker lasciare la pagina «Browser» o la vista remota di Collegamento mentre Alberto guida (un'altra pagina, la scheda chiusa, il collegamento perso) valeva «Annulla» e la sessione non si copiava. Ora è come chiudere la finestra del browser su Windows: `cancel` con `pageLeft` va a LeavePageAsync, la vista remota chiusa dalla sua pagina lo dice alla connessione, e se per 5 secondi non si apre un'altra vista né arriva un `begin` (una pagina ricaricata) il controllo del permesso copia la sessione con CopyOnLetGoAsync, solo da una pagina del sito che non sia di accesso o di verifica, poi rilascia il permesso e il motore rimette il browser a riposo. Il pulsante «Annulla» continua a non copiare; Windows non cambia. Prove nuove per la copia lasciando la pagina, la ricarica che non è lasciare, la pagina di accesso, la vista sostituita o chiusa da Febe; guida, protocollo e una riga in decisioni.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
634 lines
23 KiB
C#
634 lines
23 KiB
C#
using System.Runtime.CompilerServices;
|
|
using System.Text.Json;
|
|
using Febe.App;
|
|
using Febe.Browser.Cdp;
|
|
using Febe.Browser.Diagnostics;
|
|
using Febe.Browser.Gestures;
|
|
using Febe.Browser.RemoteView;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Web.Connection;
|
|
using Febe.Web.Engine;
|
|
|
|
namespace Febe.Server;
|
|
|
|
/// <summary>
|
|
/// The remote view over the real Chromium (spec §4.1, §11, PROTOCOLLO.md): a <see cref="RemoteViewSession"/> per open
|
|
/// view, which holds the «Alberto is driving» lease while it is open, so the engine is still. One view at a time: a
|
|
/// view opened in another tab replaces the older one, also when two open at the same moment (opening is serialized, so
|
|
/// the older view is always ended — and its screencast stopped — before the newer one starts). Keys go to the browser
|
|
/// and nowhere else.
|
|
/// </summary>
|
|
internal sealed class BrowserRemoteViewHost : IRemoteViewHost
|
|
{
|
|
private readonly IFebeBrowser _browser;
|
|
private readonly BrowserUseTracker _tracker;
|
|
private readonly IClock _clock;
|
|
private readonly IClock _browserClock;
|
|
private readonly FebeLog _log;
|
|
private readonly Func<CancellationToken, Task>? _openStartPage;
|
|
private readonly Action? _viewClosed;
|
|
private readonly Lock _gate = new();
|
|
private readonly SemaphoreSlim _opening = new(1, 1);
|
|
private BrowserRemoteViewConnection? _current;
|
|
private bool _shuttingDown;
|
|
|
|
/// <param name="browser">The browser shown.</param>
|
|
/// <param name="tracker">Notes when Alberto last used the browser.</param>
|
|
/// <param name="clock">The composition's clock (the time of that note).</param>
|
|
/// <param name="log">Febe's log.</param>
|
|
/// <param name="browserClock">
|
|
/// Time for the waits on the browser itself and for the frames' watchdog; null: the wall clock, because the browser
|
|
/// commits a navigation and paints in real time whatever clock the engine runs on (the tests compress it).
|
|
/// </param>
|
|
/// <param name="openStartPage">
|
|
/// What «Pagina iniziale» does (issue #52): the connection opens the start page once the engine's session ended and
|
|
/// with the page's turn; null: the button does nothing.
|
|
/// </param>
|
|
/// <param name="viewClosed">
|
|
/// Told when a view ends from the page's side (the page left, the tab closed, the link lost), not when another view
|
|
/// takes its place or Febe stops: the connection then knows that Alberto may have left the browser (Docker, answer of
|
|
/// 25 November 2026, spec §6.0 «Quando si copia»); null: nobody is told.
|
|
/// </param>
|
|
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func<CancellationToken, Task>? openStartPage = null, Action? viewClosed = null)
|
|
{
|
|
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
|
|
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
|
|
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
|
_log = log ?? throw new ArgumentNullException(nameof(log));
|
|
_browserClock = browserClock ?? new SystemClock(clock.LocalZone);
|
|
_openStartPage = openStartPage;
|
|
_viewClosed = viewClosed;
|
|
}
|
|
|
|
/// <summary>
|
|
/// How an open view notices that frames stopped coming and starts them again (issue #52); null: never (tests whose
|
|
/// clock moves only when asked).
|
|
/// </summary>
|
|
public ScreencastWatchdog? Watchdog { get; set; } = ScreencastWatchdog.Default;
|
|
|
|
public async Task<IRemoteViewConnection> OpenAsync(CancellationToken ct)
|
|
{
|
|
if (!_browser.IsAvailable)
|
|
{
|
|
throw new RemoteViewUnavailableException(_browser.LastError is { } error
|
|
? "Il browser di Febe non è in funzione: " + error
|
|
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
|
|
}
|
|
|
|
// From the look at the current view to the new one in its place, one opening at a time: two views opened at once
|
|
// would both start and the later assignment would orphan the other (still holding its lease, and stopping the
|
|
// shared screencast when it closes).
|
|
await _opening.WaitAsync(ct).ConfigureAwait(false);
|
|
IDisposable? handover = null;
|
|
try
|
|
{
|
|
BrowserRemoteViewConnection? previous;
|
|
lock (_gate)
|
|
{
|
|
if (_shuttingDown)
|
|
{
|
|
throw new RemoteViewUnavailableException("Febe si sta fermando.");
|
|
}
|
|
|
|
previous = _current;
|
|
_current = null;
|
|
}
|
|
|
|
if (previous is not null)
|
|
{
|
|
// Alberto is still at the browser while one view takes the place of the other: without this lease the
|
|
// engine would see nobody driving for a moment and put the page back to rest (a navigation under the new
|
|
// view's start) or even begin a session.
|
|
handover = _browser.UserDriving.Begin();
|
|
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
|
|
}
|
|
|
|
var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock, _log.ForBrowser("vista"), _openStartPage, Watchdog);
|
|
try
|
|
{
|
|
await connection.StartAsync(_browser.WindowWidth, _browser.WindowHeight, ct).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// Whatever went wrong (the page gone away, an unexpected frame tree), nothing of the view stays behind:
|
|
// no lease, no screencast, no subscription. Ended by the server: the page did not leave the browser.
|
|
await connection.EndAsync(RemoteViewEnd.BrowserStopped).ConfigureAwait(false);
|
|
if (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
|
|
{
|
|
throw new RemoteViewUnavailableException("Il browser di Febe non risponde: riprova fra qualche secondo.", ex);
|
|
}
|
|
|
|
throw;
|
|
}
|
|
|
|
bool stopping;
|
|
lock (_gate)
|
|
{
|
|
stopping = _shuttingDown;
|
|
if (!stopping)
|
|
{
|
|
_current = connection;
|
|
}
|
|
}
|
|
|
|
if (stopping)
|
|
{
|
|
await connection.EndAsync(RemoteViewEnd.ShuttingDown).ConfigureAwait(false);
|
|
throw new RemoteViewUnavailableException("Febe si sta fermando.");
|
|
}
|
|
|
|
_log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
|
|
return connection;
|
|
}
|
|
finally
|
|
{
|
|
// The new view holds its own lease by now; if it did not start, nobody is at the browser any more.
|
|
handover?.Dispose();
|
|
_opening.Release();
|
|
}
|
|
}
|
|
|
|
/// <summary>Febe is stopping: the open view is closed with a reason the page can show.</summary>
|
|
public async Task ShutdownAsync()
|
|
{
|
|
BrowserRemoteViewConnection? current;
|
|
lock (_gate)
|
|
{
|
|
_shuttingDown = true;
|
|
current = _current;
|
|
_current = null;
|
|
}
|
|
|
|
if (current is not null)
|
|
{
|
|
await current.EndAsync(RemoteViewEnd.ShuttingDown).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
/// <param name="connection">The view that ended.</param>
|
|
/// <param name="byPage">True when the page ended it (left, tab closed, link lost), false when the server did.</param>
|
|
internal void Closed(BrowserRemoteViewConnection connection, bool byPage)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (ReferenceEquals(_current, connection))
|
|
{
|
|
_current = null;
|
|
}
|
|
}
|
|
|
|
_log.Info("vista", "Vista remota chiusa.");
|
|
if (byPage)
|
|
{
|
|
_viewClosed?.Invoke();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>One open remote view on the real browser.</summary>
|
|
internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
|
{
|
|
private readonly BrowserRemoteViewHost _owner;
|
|
private readonly IFebeBrowser _browser;
|
|
private readonly BrowserUseTracker _tracker;
|
|
private readonly IClock _clock;
|
|
private readonly RemoteViewSession _session;
|
|
private readonly Func<CancellationToken, Task>? _openStartPage;
|
|
private readonly ScreencastWatchdog? _watchdog;
|
|
private readonly IBrowserLog _log;
|
|
private readonly Lock _gate = new();
|
|
private readonly Queue<RemoteViewMeta> _meta = new();
|
|
private readonly SemaphoreSlim _signal = new(0, int.MaxValue);
|
|
private readonly CancellationTokenSource _ended = new();
|
|
private readonly List<IDisposable> _subscriptions = [];
|
|
|
|
// Full addresses of this view, for «back»: kept in memory only, never logged and never sent (the page gets them
|
|
// without query string).
|
|
private readonly List<string> _history = [];
|
|
private ScreencastFrame? _pendingFrame;
|
|
private string? _mainFrameId;
|
|
private string _url = "about:blank";
|
|
private int _width;
|
|
private int _height;
|
|
private int _disposed;
|
|
private bool _used;
|
|
private int _startPagePending;
|
|
private Task _startPage = Task.CompletedTask;
|
|
|
|
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock, IBrowserLog log, Func<CancellationToken, Task>? openStartPage, ScreencastWatchdog? watchdog)
|
|
{
|
|
_owner = owner;
|
|
_browser = browser;
|
|
_tracker = tracker;
|
|
_clock = clock;
|
|
_openStartPage = openStartPage;
|
|
_watchdog = watchdog;
|
|
_log = log;
|
|
|
|
// A real log (issue #52): the starts, restarts and silences of the frames reach the registro.
|
|
_session = new RemoteViewSession(browser.Cdp, browser.UserDriving, log, browserClock);
|
|
}
|
|
|
|
public RemoteViewEnd? Ended { get; private set; }
|
|
|
|
private ICdpSession Cdp => _browser.Cdp;
|
|
|
|
/// <summary>True while a «Pagina iniziale» waits or loads: the input of the view is dropped meanwhile.</summary>
|
|
internal bool StartPagePending => Volatile.Read(ref _startPagePending) != 0;
|
|
|
|
/// <summary>The last «Pagina iniziale» of this view (a completed task before the first): tests wait on it.</summary>
|
|
internal Task StartPageOpening
|
|
{
|
|
get
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return _startPage;
|
|
}
|
|
}
|
|
}
|
|
|
|
public async Task StartAsync(int width, int height, CancellationToken ct)
|
|
{
|
|
_width = width;
|
|
_height = height;
|
|
_subscriptions.Add(Cdp.On("Page.frameNavigated", OnFrameNavigated));
|
|
_subscriptions.Add(Cdp.On("Page.navigatedWithinDocument", OnNavigatedWithinDocument));
|
|
var tree = await Cdp.SendAsync("Page.getFrameTree", null, ct).ConfigureAwait(false);
|
|
var frame = tree.GetProperty("frameTree").GetProperty("frame");
|
|
_mainFrameId = frame.GetProperty("id").GetString();
|
|
var url = frame.TryGetProperty("url", out var u) ? u.GetString() ?? string.Empty : string.Empty;
|
|
lock (_gate)
|
|
{
|
|
_history.Add(url);
|
|
_url = WithoutQuery(url);
|
|
_meta.Enqueue(new RemoteViewMeta(_width, _height, _url));
|
|
}
|
|
|
|
_signal.Release();
|
|
_session.Screencast.FrameReceived += OnFrame;
|
|
await _session.StartAsync(new ScreencastOptions(Quality: 70, MaxWidth: width, MaxHeight: height, Watchdog: _watchdog), ct).ConfigureAwait(false);
|
|
}
|
|
|
|
public async IAsyncEnumerable<RemoteViewOutput> ReadAsync([EnumeratorCancellation] CancellationToken ct)
|
|
{
|
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _ended.Token);
|
|
while (true)
|
|
{
|
|
try
|
|
{
|
|
await _signal.WaitAsync(linked.Token).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
yield break;
|
|
}
|
|
|
|
RemoteViewMeta? meta = null;
|
|
ScreencastFrame? frame = null;
|
|
lock (_gate)
|
|
{
|
|
if (_meta.Count > 0)
|
|
{
|
|
meta = _meta.Dequeue();
|
|
}
|
|
else
|
|
{
|
|
frame = _pendingFrame;
|
|
_pendingFrame = null;
|
|
}
|
|
}
|
|
|
|
if (meta is not null)
|
|
{
|
|
yield return meta;
|
|
}
|
|
else if (frame is not null)
|
|
{
|
|
yield return new RemoteViewFrame(frame.Jpeg);
|
|
}
|
|
}
|
|
}
|
|
|
|
public Task MouseAsync(RemoteViewMouse input, CancellationToken ct)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(input);
|
|
if (_session.Screencast.LastFrame is null || StartPagePending)
|
|
{
|
|
// No frame yet: nothing on screen to point at. «Pagina iniziale» in progress: a click would land on the page
|
|
// about to go, or on the start page while it loads.
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
MarkUsed();
|
|
var action = input.Action switch
|
|
{
|
|
RemoteViewMouseAction.Down => RemoteMouseAction.Down,
|
|
RemoteViewMouseAction.Up => RemoteMouseAction.Up,
|
|
RemoteViewMouseAction.Wheel => RemoteMouseAction.Wheel,
|
|
_ => RemoteMouseAction.Move,
|
|
};
|
|
var button = input.Button switch
|
|
{
|
|
RemoteViewButton.Left => RemoteMouseButton.Left,
|
|
RemoteViewButton.Middle => RemoteMouseButton.Middle,
|
|
RemoteViewButton.Right => RemoteMouseButton.Right,
|
|
_ => RemoteMouseButton.None,
|
|
};
|
|
return _session.MouseAsync(new RemoteMouseEvent(action, input.X, input.Y, button, input.ClickCount, input.DeltaX, input.DeltaY), ct);
|
|
}
|
|
|
|
public Task KeyAsync(RemoteViewKey input, CancellationToken ct)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(input);
|
|
if (StartPagePending)
|
|
{
|
|
return Task.CompletedTask; // as for the mouse: not typed into a page about to change
|
|
}
|
|
|
|
MarkUsed();
|
|
if (input.Action == RemoteViewKeyAction.Char)
|
|
{
|
|
return _session.CharAsync(input.Text!, ct);
|
|
}
|
|
|
|
return _session.KeyAsync(new RemoteKeyEvent(input.Action == RemoteViewKeyAction.Down, RemoteKeys.ToStroke(input)), ct);
|
|
}
|
|
|
|
public async Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct)
|
|
{
|
|
MarkUsed();
|
|
if (action == RemoteViewNavigation.Home)
|
|
{
|
|
OpenStartPage();
|
|
return;
|
|
}
|
|
|
|
if (StartPagePending)
|
|
{
|
|
return; // the start page is about to replace the page anyway
|
|
}
|
|
|
|
string? target;
|
|
lock (_gate)
|
|
{
|
|
if (action == RemoteViewNavigation.Back)
|
|
{
|
|
// Back never lands on the empty rest page (issue #52): it skips it, and with nothing before it stays.
|
|
var previous = _history.Count - 2;
|
|
while (previous >= 0 && IsRest(_history[previous]))
|
|
{
|
|
previous--;
|
|
}
|
|
|
|
if (previous < 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_history.RemoveRange(previous + 1, _history.Count - previous - 1);
|
|
target = _history[^1];
|
|
}
|
|
else
|
|
{
|
|
target = _history.Count > 0 ? _history[^1] : null;
|
|
}
|
|
}
|
|
|
|
if (string.IsNullOrEmpty(target))
|
|
{
|
|
return;
|
|
}
|
|
|
|
// Alberto's own navigation while he drives (rule 7): not an engine action, no Governor.
|
|
await _session.NavigateAsync(target, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>
|
|
/// «Pagina iniziale»: Alberto's own navigation (rule 7), done by the connection — like the start page opened from the
|
|
/// rest page, it waits for the engine's session to end and takes the page's turn first, up to half a minute. So it runs
|
|
/// beside the view, not in its receive loop (the view would freeze meanwhile), for as long as the view and its lease
|
|
/// last; one at a time, and until it is done the view's input is dropped.
|
|
/// </summary>
|
|
private void OpenStartPage()
|
|
{
|
|
if (_openStartPage is not { } open || Interlocked.CompareExchange(ref _startPagePending, 1, 0) != 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var task = Task.Run(() => OpenStartPageAsync(open), CancellationToken.None);
|
|
lock (_gate)
|
|
{
|
|
_startPage = task;
|
|
}
|
|
}
|
|
|
|
private async Task OpenStartPageAsync(Func<CancellationToken, Task> open)
|
|
{
|
|
try
|
|
{
|
|
await open(_ended.Token).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException) when (_ended.IsCancellationRequested)
|
|
{
|
|
// The view closed first: its lease is gone, the page is the engine's.
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
|
{
|
|
_log.Write(BrowserLogLevel.Warning, $"«Pagina iniziale» non aperta ({ex.GetType().Name}).");
|
|
}
|
|
finally
|
|
{
|
|
Volatile.Write(ref _startPagePending, 0);
|
|
}
|
|
}
|
|
|
|
/// <summary>Ends the view from the server side (another tab, shutdown): the page is told why.</summary>
|
|
public async Task EndAsync(RemoteViewEnd reason)
|
|
{
|
|
Ended ??= reason;
|
|
await DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
if (Interlocked.Exchange(ref _disposed, 1) == 1)
|
|
{
|
|
return;
|
|
}
|
|
|
|
// No reason given by the server (another view, Febe stopping, the browser gone): the page closed it.
|
|
var byPage = Ended is null;
|
|
Ended ??= RemoteViewEnd.BrowserStopped;
|
|
await _ended.CancelAsync().ConfigureAwait(false);
|
|
_session.Screencast.FrameReceived -= OnFrame;
|
|
foreach (var subscription in _subscriptions)
|
|
{
|
|
subscription.Dispose();
|
|
}
|
|
|
|
try
|
|
{
|
|
await _session.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or OperationCanceledException)
|
|
{
|
|
// The browser is gone: the lease is released anyway.
|
|
}
|
|
|
|
_owner.Closed(this, byPage);
|
|
}
|
|
|
|
private void MarkUsed()
|
|
{
|
|
if (!_used)
|
|
{
|
|
_used = true;
|
|
_tracker.MarkUsed(_clock.Now);
|
|
}
|
|
}
|
|
|
|
private void OnFrame(object? sender, ScreencastFrame frame)
|
|
{
|
|
var width = (int)Math.Round(frame.DeviceWidth);
|
|
var height = (int)Math.Round(frame.DeviceHeight);
|
|
lock (_gate)
|
|
{
|
|
if (width > 0 && height > 0 && (width != _width || height != _height))
|
|
{
|
|
_width = width;
|
|
_height = height;
|
|
_meta.Enqueue(new RemoteViewMeta(width, height, _url));
|
|
_signal.Release();
|
|
}
|
|
|
|
var hadPending = _pendingFrame is not null;
|
|
_pendingFrame = frame;
|
|
if (hadPending)
|
|
{
|
|
return; // the older frame is replaced: the reader is behind
|
|
}
|
|
}
|
|
|
|
_signal.Release();
|
|
}
|
|
|
|
private void OnFrameNavigated(JsonElement e)
|
|
{
|
|
if (!e.TryGetProperty("frame", out var frame) || frame.TryGetProperty("parentId", out _))
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (frame.TryGetProperty("id", out var id) && id.GetString() is { } frameId)
|
|
{
|
|
_mainFrameId = frameId; // a new main frame after a browser restart
|
|
}
|
|
|
|
Navigated(frame.TryGetProperty("url", out var u) ? u.GetString() : null);
|
|
}
|
|
|
|
private void OnNavigatedWithinDocument(JsonElement e)
|
|
{
|
|
if (e.TryGetProperty("frameId", out var id) && id.GetString() is { } frameId && frameId == _mainFrameId)
|
|
{
|
|
Navigated(e.TryGetProperty("url", out var u) ? u.GetString() : null);
|
|
}
|
|
}
|
|
|
|
private void Navigated(string? url)
|
|
{
|
|
if (string.IsNullOrEmpty(url))
|
|
{
|
|
return;
|
|
}
|
|
|
|
lock (_gate)
|
|
{
|
|
if (_history.Count == 0 || _history[^1] != url)
|
|
{
|
|
_history.Add(url);
|
|
if (_history.Count > 50)
|
|
{
|
|
_history.RemoveAt(0);
|
|
}
|
|
}
|
|
|
|
var shown = WithoutQuery(url);
|
|
if (shown == _url)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_url = shown;
|
|
_meta.Enqueue(new RemoteViewMeta(_width, _height, shown));
|
|
}
|
|
|
|
_signal.Release();
|
|
}
|
|
|
|
/// <summary>The address without query string or fragment (they may carry tokens).</summary>
|
|
internal static string WithoutQuery(string url) => Addresses.WithoutQuery(url);
|
|
|
|
private static bool IsRest(string url) => url is "" or CdpPageExtensions.RestUrl;
|
|
}
|
|
|
|
/// <summary>Turns the DOM key of the page into what <c>Input.dispatchKeyEvent</c> needs (virtual key codes).</summary>
|
|
internal static class RemoteKeys
|
|
{
|
|
private static readonly Dictionary<string, int> Named = new(StringComparer.Ordinal)
|
|
{
|
|
["Backspace"] = 8, ["Tab"] = 9, ["Enter"] = 13, ["Shift"] = 16, ["Control"] = 17, ["Alt"] = 18, ["Pause"] = 19,
|
|
["CapsLock"] = 20, ["Escape"] = 27, [" "] = 32, ["PageUp"] = 33, ["PageDown"] = 34, ["End"] = 35, ["Home"] = 36,
|
|
["ArrowLeft"] = 37, ["ArrowUp"] = 38, ["ArrowRight"] = 39, ["ArrowDown"] = 40, ["Insert"] = 45, ["Delete"] = 46,
|
|
["Meta"] = 91, ["ContextMenu"] = 93,
|
|
};
|
|
|
|
private static readonly Dictionary<string, int> Codes = new(StringComparer.Ordinal)
|
|
{
|
|
["Space"] = 32, ["Semicolon"] = 186, ["Equal"] = 187, ["Comma"] = 188, ["Minus"] = 189, ["Period"] = 190,
|
|
["Slash"] = 191, ["Backquote"] = 192, ["BracketLeft"] = 219, ["Backslash"] = 220, ["BracketRight"] = 221,
|
|
["Quote"] = 222, ["IntlBackslash"] = 226, ["NumpadEnter"] = 13,
|
|
};
|
|
|
|
public static KeyStroke ToStroke(RemoteViewKey key)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(key);
|
|
var code = key.Code;
|
|
var keyCode = 0;
|
|
if (Named.TryGetValue(key.Key, out var named))
|
|
{
|
|
keyCode = named;
|
|
}
|
|
else if (code.Length == 4 && code.StartsWith("Key", StringComparison.Ordinal) && code[3] is >= 'A' and <= 'Z')
|
|
{
|
|
keyCode = code[3];
|
|
}
|
|
else if (code.Length == 6 && code.StartsWith("Digit", StringComparison.Ordinal) && code[5] is >= '0' and <= '9')
|
|
{
|
|
keyCode = code[5];
|
|
}
|
|
else if (code.Length == 7 && code.StartsWith("Numpad", StringComparison.Ordinal) && code[6] is >= '0' and <= '9')
|
|
{
|
|
keyCode = 96 + (code[6] - '0');
|
|
}
|
|
else if (code.Length is 2 or 3 && code[0] == 'F' && int.TryParse(code.AsSpan(1), out var f) && f is >= 1 and <= 12)
|
|
{
|
|
keyCode = 111 + f;
|
|
}
|
|
else if (Codes.TryGetValue(code, out var byCode))
|
|
{
|
|
keyCode = byCode;
|
|
}
|
|
else if (key.Key.Length == 1 && char.ToUpperInvariant(key.Key[0]) is var c && c is >= 'A' and <= 'Z' or >= '0' and <= '9')
|
|
{
|
|
keyCode = c;
|
|
}
|
|
|
|
// Enter must carry its text, or forms are not submitted.
|
|
var text = key.Text ?? (key.Key == "Enter" ? "\r" : null);
|
|
return new KeyStroke(key.Key, code, keyCode, (KeyModifiers)(key.Modifiers & 15), text);
|
|
}
|
|
}
|