using System.Text; using System.Text.Json; using System.Threading.Channels; using Febe.Browser.Cdp; using Febe.Browser.Diagnostics; using Febe.Core.Abstractions; namespace Febe.Browser.WebView2; /// /// The two WebView2 calls Febe needs for the DevTools protocol (spec §6.1, Windows): CallDevToolsProtocolMethodAsync /// and GetDevToolsProtocolEventReceiver, never the deprecated DevToolsProtocolExtension package. The desktop /// implements it on CoreWebView2, on the UI thread; tests use a fake. Everything else — the allowlist, the /// read-only guard, JSON, event dispatch, logging — is , testable without Windows. /// public interface IWebView2DevTools { /// /// CoreWebView2.CallDevToolsProtocolMethodAsync(methodName, parametersAsJson): the result object as JSON. A /// protocol error faults the task; its message may carry the error object ({"code":…,"message":…}). When the /// WebView is gone the task faults with . /// Task CallMethodAsync(string methodName, string parametersAsJson); /// /// GetDevToolsProtocolEventReceiver(eventName).DevToolsProtocolEventReceived: gets /// ParameterObjectAsJson. Disposing removes the handler. /// IDisposable Subscribe(string eventName, Action onEvent); } /// Options of . /// How long to wait for the answer to a command before giving up (60 s by default). public sealed record WebView2CdpOptions(TimeSpan? CommandTimeout = null) { internal TimeSpan EffectiveTimeout => CommandTimeout ?? TimeSpan.FromSeconds(60); } /// /// The of WebView2 (spec §5, §6.1): the same rules as over the two /// WebView2 calls of . /// /// /// /// Only commands of are sent; Runtime.evaluate also passes /// . A refused command never reaches WebView2. /// The log receives command and event names only: never parameters, results, event payloads or the text of /// WebView2's exceptions (a protocol error keeps only its code and message, like ). /// Events arrive on WebView2's UI thread; they are queued and handed to the handlers in order on one background /// loop, so a slow handler never blocks the window and a handler may send commands without deadlocking it. /// Like : subscriptions survive a new WebView ( after the /// browser process restarted), and commands fail fast with while detached. /// /// public sealed class WebView2CdpSession : ICdpSession, ICdpConnectionEvents, IAsyncDisposable { private static readonly JsonSerializerOptions ParameterOptions = new(JsonSerializerDefaults.Web) { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, }; private readonly IBrowserLog _log; private readonly WebView2CdpOptions _options; private readonly Lock _gate = new(); private readonly Dictionary>> _handlers = new(StringComparer.Ordinal); private readonly Dictionary _native = new(StringComparer.Ordinal); private readonly Channel _events = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true }); private readonly Task _dispatch; private IWebView2DevTools? _devTools; private bool _everAttached; private int _disposed; public WebView2CdpSession(IBrowserLog? log = null, WebView2CdpOptions? options = null) { _log = log ?? NullBrowserLog.Instance; _options = options ?? new WebView2CdpOptions(); _dispatch = Task.Run(DispatchLoopAsync); } /// Raised after replaced an earlier WebView (not for the first one). public event EventHandler? Reconnected; /// True while a WebView is attached. public bool IsAttached { get { lock (_gate) { return _devTools is not null; } } } /// Uses from now on and subscribes it to every event that has handlers. public void Attach(IWebView2DevTools devTools) { ArgumentNullException.ThrowIfNull(devTools); bool reconnect; lock (_gate) { DetachLocked(); _devTools = devTools; foreach (var name in _handlers.Keys) { _native[name] = SubscribeNative(devTools, name); } reconnect = _everAttached; _everAttached = true; } _log.Write(BrowserLogLevel.Debug, "CDP: WebView2 collegato."); if (reconnect) { RaiseReconnected(); } } /// Stops using the current WebView (it is closing or gone); commands fail until the next . public void Detach() { lock (_gate) { DetachLocked(); } } public async Task SendAsync(string method, object? parameters = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrEmpty(method); CdpCommandPolicy.EnsureAllowed(method); var node = CdpParameters.ToNode(parameters, ParameterOptions); if (method == "Runtime.evaluate") { ReadOnlyScriptGuard.EnsureReadOnly(CdpParameters.GetString(node, "expression")); } IWebView2DevTools devTools; lock (_gate) { ObjectDisposedException.ThrowIf(_disposed == 1, this); devTools = _devTools ?? throw new BrowserUnavailableException(); } var json = node?.ToJsonString() ?? "{}"; _log.Write(BrowserLogLevel.Debug, $"CDP → {method}"); string result; try { result = await devTools.CallMethodAsync(method, json).WaitAsync(_options.EffectiveTimeout, ct).ConfigureAwait(false); } catch (TimeoutException) { throw new TimeoutException($"Il browser non ha risposto al comando «{method}» entro {_options.EffectiveTimeout.TotalSeconds:0} s."); } catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or OperationCanceledException) { throw; } catch (Exception ex) when (ex is not OutOfMemoryException) { var error = ProtocolError(method, ex); _log.Write(BrowserLogLevel.Debug, $"CDP ✗ {method} (codice {error.Code})"); throw error; } return Parse(result); } public IDisposable On(string eventName, Action handler) { ArgumentException.ThrowIfNullOrEmpty(eventName); ArgumentNullException.ThrowIfNull(handler); lock (_gate) { if (!_handlers.TryGetValue(eventName, out var list)) { list = []; _handlers[eventName] = list; if (_devTools is { } devTools) { _native[eventName] = SubscribeNative(devTools, eventName); } } list.Add(handler); } return new Subscription(() => { lock (_gate) { if (_handlers.TryGetValue(eventName, out var list) && list.Remove(handler) && list.Count == 0) { _handlers.Remove(eventName); if (_native.Remove(eventName, out var native)) { native.Dispose(); } } } }); } /// Waits until every event received so far was handed to its handlers (tests). public Task DrainAsync() { var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); if (!_events.Writer.TryWrite(new QueuedEvent(string.Empty, string.Empty, done))) { done.TrySetResult(); } return done.Task; } public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) == 1) { return; } lock (_gate) { DetachLocked(); } _events.Writer.TryComplete(); await _dispatch.ConfigureAwait(false); } /// /// The protocol error of a failed WebView2 call. WebView2 puts the error object in the exception's message; only its /// code and message are kept (never the text around it nor its data, which can echo parameters). /// internal static CdpCommandException ProtocolError(string method, Exception ex) { var bytes = Encoding.UTF8.GetBytes(ex.Message ?? string.Empty); CdpCommandException? found = null; // The last object with a numeric code and a string message: text and other JSON around it are ignored. for (var i = Array.IndexOf(bytes, (byte)'{'); i >= 0; i = Array.IndexOf(bytes, (byte)'{', i + 1)) { try { var reader = new Utf8JsonReader(bytes.AsSpan(i)); using var document = JsonDocument.ParseValue(ref reader); var root = document.RootElement; if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty("message", out var m) && m.ValueKind == JsonValueKind.String && root.TryGetProperty("code", out var c) && c.TryGetInt32(out var code)) { found = new CdpCommandException(method, code, m.GetString() ?? string.Empty); } } catch (JsonException) { } } return found ?? new CdpCommandException(method, ex.HResult, "errore di WebView2"); } private static JsonElement Parse(string? json) { if (string.IsNullOrWhiteSpace(json)) { return default; } // ParseValue yields a self-contained element and needs no serializer (trimmed and single-file builds). var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json)); return JsonElement.ParseValue(ref reader); } /// /// , on the thread of (WebView2's UI thread), one handler at a time: an /// error of a handler is logged and never reaches , so it cannot undo the start of the new /// WebView that called it. Handlers only queue their work (re-enabling a domain is a command, never sent from here). /// private void RaiseReconnected() { if (Reconnected is not { } handlers) { return; } foreach (var handler in handlers.GetInvocationList().Cast()) { try { handler(this, EventArgs.Empty); } catch (Exception ex) when (ex is not OutOfMemoryException) { _log.Write(BrowserLogLevel.Warning, "CDP: errore in chi ascolta il nuovo collegamento con WebView2.", ex); } } } private IDisposable SubscribeNative(IWebView2DevTools devTools, string eventName) => devTools.Subscribe(eventName, json => _events.Writer.TryWrite(new QueuedEvent(eventName, json ?? string.Empty, null))); private void DetachLocked() { foreach (var native in _native.Values) { try { native.Dispose(); } catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException or CdpDisconnectedException) { // The WebView is already gone: its handlers went with it. } } _native.Clear(); _devTools = null; } private async Task DispatchLoopAsync() { await foreach (var (name, json, drained) in _events.Reader.ReadAllAsync().ConfigureAwait(false)) { if (drained is not null) { drained.TrySetResult(); continue; } Action[] handlers; lock (_gate) { if (!_handlers.TryGetValue(name, out var list) || list.Count == 0) { continue; } handlers = [.. list]; } JsonElement parameters; try { parameters = Parse(json); } catch (JsonException ex) { _log.Write(BrowserLogLevel.Warning, $"CDP: evento {name} non leggibile.", ex); continue; } foreach (var handler in handlers) { try { handler(parameters); } catch (Exception ex) when (ex is not OutOfMemoryException) { _log.Write(BrowserLogLevel.Warning, $"CDP: errore nel gestore dell'evento {name}.", ex); } } } } /// An event waiting for its handlers, or (with ) the mark of . private readonly record struct QueuedEvent(string Name, string Json, TaskCompletionSource? Drained); }