using System.Runtime.CompilerServices;
using System.Text.Json;
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. Keys go to the browser and nowhere else.
///
internal sealed class BrowserRemoteViewHost(BrowserSupervisor browser, BrowserUseTracker tracker, IClock clock, ServerLog log) : IRemoteViewHost
{
private readonly Lock _gate = new();
private BrowserRemoteViewConnection? _current;
private bool _shuttingDown;
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.");
}
BrowserRemoteViewConnection? previous;
lock (_gate)
{
if (_shuttingDown)
{
throw new RemoteViewUnavailableException("Febe si sta fermando.");
}
previous = _current;
_current = null;
}
if (previous is not null)
{
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
}
var connection = new BrowserRemoteViewConnection(this, browser, tracker, clock);
try
{
await connection.StartAsync(browser.BrowserOptions.WindowWidth, browser.BrowserOptions.WindowHeight, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
await connection.DisposeAsync().ConfigureAwait(false);
throw new RemoteViewUnavailableException("Il browser di Febe non risponde: riprova fra qualche secondo.", ex);
}
lock (_gate)
{
_current = connection;
}
log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
return connection;
}
/// 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 BrowserSupervisor _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, BrowserSupervisor browser, BrowserUseTracker tracker, IClock clock)
{
_owner = owner;
_browser = browser;
_tracker = tracker;
_clock = clock;
_session = new RemoteViewSession(browser.Host.Cdp, browser.Host.UserDriving);
}
public RemoteViewEnd? Ended { get; private set; }
private ICdpSession Cdp => _browser.Host.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)
{
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
var cut = url.IndexOfAny(['?', '#']);
return cut < 0 ? url : url[..cut];
}
return uri.Scheme is "http" or "https" ? uri.GetLeftPart(UriPartial.Path) : uri.GetLeftPart(UriPartial.Scheme) + uri.AbsolutePath;
}
}
/// 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);
}
}