using System.Runtime.CompilerServices; using System.Text.Json; using Febe.App; using Febe.Browser.Cdp; using Febe.Browser.Gestures; using Febe.Browser.RemoteView; using Febe.Core.Abstractions; using Febe.Web.Connection; using Febe.Web.Engine; namespace Febe.Server; /// /// The remote view over the real Chromium (spec §4.1, §11, PROTOCOLLO.md): a 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. /// 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 Lock _gate = new(); private readonly SemaphoreSlim _opening = new(1, 1); private BrowserRemoteViewConnection? _current; private bool _shuttingDown; /// The browser shown. /// Notes when Alberto last used the browser. /// The composition's clock (the time of that note). /// Febe's log. /// /// Time for the waits on the browser itself; null: the wall clock, because the browser commits a navigation in real /// time whatever clock the engine runs on (the tests compress it). /// public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = 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); } public async Task 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); 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. await connection.DisposeAsync().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(); } } /// Febe is stopping: the open view is closed with a reason the page can show. 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); } } internal void Closed(BrowserRemoteViewConnection connection) { lock (_gate) { if (ReferenceEquals(_current, connection)) { _current = null; } } _log.Info("vista", "Vista remota chiusa."); } } /// One open remote view on the real browser. 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 Lock _gate = new(); private readonly Queue _meta = new(); private readonly SemaphoreSlim _signal = new(0, int.MaxValue); private readonly CancellationTokenSource _ended = new(); private readonly List _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 _history = []; private ScreencastFrame? _pendingFrame; private string? _mainFrameId; private string _url = "about:blank"; private int _width; private int _height; private int _disposed; private bool _used; public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock) { _owner = owner; _browser = browser; _tracker = tracker; _clock = clock; _session = new RemoteViewSession(browser.Cdp, browser.UserDriving, clock: browserClock); } public RemoteViewEnd? Ended { get; private set; } private ICdpSession Cdp => _browser.Cdp; 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), ct).ConfigureAwait(false); } public async IAsyncEnumerable 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) { return Task.CompletedTask; // no frame yet: nothing on screen to point at } 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); 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(); string? target; lock (_gate) { if (action == RemoteViewNavigation.Back) { if (_history.Count < 2) { return; } _history.RemoveAt(_history.Count - 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); } /// Ends the view from the server side (another tab, shutdown): the page is told why. public async Task EndAsync(RemoteViewEnd reason) { Ended ??= reason; await DisposeAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) == 1) { return; } 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); } 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(); } /// The address without query string or fragment (they may carry tokens). internal static string WithoutQuery(string url) => Addresses.WithoutQuery(url); } /// Turns the DOM key of the page into what Input.dispatchKeyEvent needs (virtual key codes). internal static class RemoteKeys { private static readonly Dictionary 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 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); } }