using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Windows.Media; using System.Windows.Threading; using Febe.App; using Febe.Browser.Cdp; using Febe.Browser.Diagnostics; using Febe.Browser.Hosting; using Febe.Browser.WebView2; using Febe.Core.Abstractions; using Febe.Desktop.Core; using Microsoft.Web.WebView2.Core; namespace Febe.Desktop.Browser; /// Windows-only settings of , on top of . /// or (S2). /// The switches of S2 (). /// The icon of the window. /// Called when Alberto uses the browser and when he is done with it («Riprendi»). internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed); /// /// The browser host of the Windows edition (spec §5, §6.1, §12): WebView2 in the window «Browser di Febe», with its own /// user data folder (, Dati\browser), driven through /// — the same allowlist and refusals as the Chromium client — over /// CallDevToolsProtocolMethodAsync and GetDevToolsProtocolEventReceiver. No port, no process of ours. /// /// /// /// Password saving and general autofill off; no developer tools, no zoom: the page has a fixed size. /// S2: the window is open but parked out of view when Alberto does not use it; the controller stays visible; the /// switches of turn off occlusion detection. Never hidden, never minimised. /// Alberto is driving (the engine is still) from «Apri il browser», «Portalo in primo piano» or the login — the /// window comes on screen — and whenever he clicks into it while it is on screen, until he closes it or presses /// «Ho finito»; using and closing it marks the browser as used for «Riprendi». /// Stopping closes the WebView and waits for its browser process to exit, so the session is on disk (S3); /// («Scollega») does the same before deleting the profile. /// Threads: every WebView2 object (environment, controller, CoreWebView2, its settings and DevTools /// receivers) and the window are touched only on the UI thread, through its dispatcher; WebView2 throws on any other /// thread. Callers on other threads (the composition, the engine) get only plain values captured on the UI thread /// during the start (, ), the CDP session, and tasks. Start, /// restart and stop run one at a time. /// One WebView at a time, whoever starts it (the first start and its retries, «Scollega», the start after a /// crash): a start finds the WebView running and does nothing, closes what a dead one left before creating a new one, /// and when it fails it closes what it created itself. Events of a closed WebView never count. /// /// internal sealed class WebView2Host : IBrowserHost { private static readonly TimeSpan ExitWait = TimeSpan.FromSeconds(15); /// How long stopping waits for a start or restart in progress before closing what there is. private static readonly TimeSpan StopWait = TimeSpan.FromSeconds(30); private readonly Dispatcher _ui; private readonly WebView2HostOptions _settings; private readonly FebeLog _log; private readonly WebView2CdpSession _session; // Start, restart and dispose each await WebView2 on the UI thread: without this they could interleave there. private readonly SemaphoreSlim _lifecycle = new(1, 1); // The fields below are touched on the UI thread only. private BrowserOptions? _options; private BrowserWindow? _window; private CoreWebView2Environment? _environment; private CoreWebView2Controller? _controller; private CoreWebView2? _core; private CompositionHost? _composition; private CoreWebView2DevTools? _devTools; private TaskCompletionSource? _exited; private IDisposable? _lease; private int _generation; private bool _starting; private bool _crashedWhileStarting; private bool _closing; // Plain values read on the UI thread during the start: any thread may read them. private volatile string? _version; private int _browserProcessId; public WebView2Host(Dispatcher ui, WebView2HostOptions settings, FebeLog log) { _ui = ui ?? throw new ArgumentNullException(nameof(ui)); _settings = settings ?? throw new ArgumentNullException(nameof(settings)); _log = log ?? throw new ArgumentNullException(nameof(log)); _session = new WebView2CdpSession(log.ForBrowser()); } /// The page session: stable for the whole life of the host (a restart attaches a new WebView to it). public ICdpSession Cdp => _session; /// Raised when a new WebView replaced the previous one (subscriptions survive; domains are enabled again). public ICdpConnectionEvents Connection => _session; /// Leases taken while Alberto uses the browser. public UserDrivingGate UserDriving { get; } = new(); public bool UserIsDriving => UserDriving.IsDriving; /// True while a WebView is attached (commands can be sent). public bool IsAttached => _session.IsAttached; /// /// The version of the WebView2 runtime of the browser in use (for the log), read on the UI thread when it started; /// null before the first start. Any thread: it is a plain value, never a member of a WebView2 object. /// public string? Version => _version; /// The browser process of WebView2 when it last started (0 before the first start). Any thread. public int BrowserProcessId => Volatile.Read(ref _browserProcessId); /// The window «Browser di Febe» (null before the first start). UI thread only, like every WPF object. internal BrowserWindow? Window => _window; /// /// Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts), after the /// handler of WebView2's own event has returned: WebView2 does not support closing and recreating inside it. /// public event EventHandler? BrowserProcessFailed; /// /// Creates the window (once), the environment and the controller, and attaches the CDP session — unless a WebView /// is already running, because another way in started it («Scollega», the start after a crash): then it does nothing /// and the start counts as done. A failed start leaves nothing open. When is cancelled (Febe /// is exiting) the caller stops waiting at once, even while WebView2 has not answered: a start not yet begun does not /// begin, one under way on the UI thread ends by itself, and stopping closes what it leaves. /// public Task StartAsync(BrowserOptions options, CancellationToken ct) { ArgumentNullException.ThrowIfNull(options); _options = options; var start = OnUiAsync(() => ExclusiveAsync(() => { ct.ThrowIfCancellationRequested(); return StartCoreAsync(); })); return UntilCancelledAsync(start, ct); } public Task ShowToUserAsync() => OnUiAsync(() => { if (_window is not { } window) { return Task.CompletedTask; } window.MoveOnScreen(); window.Activate(); window.Topmost = true; window.Topmost = false; // The lease first: once the window is on screen the engine must be still, whatever happens to the focus. TakeLease(); try { _controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic); } catch (Exception ex) when (ex is COMException or InvalidOperationException) { // The browser process is gone (it is starting again): the window is on screen anyway. } return Task.CompletedTask; }); public Task HideFromUserAsync() => OnUiAsync(() => { _window?.MoveOffScreen(); ReleaseLease(); return Task.CompletedTask; }); /// /// Closes the WebView, waits for its browser process to exit (the profile is free and written), runs /// — «Scollega» deletes the profile there — and starts it again. /// stays the same object. The browser starts again even when fails with an /// or ; that error is thrown afterwards. A failed /// start throws its own error and, like a failed , leaves nothing open. Once begun it goes /// to the end whatever says (the profile with the Instagram session must go, and the engine /// starts again after it); stopping waits for it at most . /// public Task RestartAsync(Func? whileStopped, CancellationToken ct) => OnUiAsync(() => ExclusiveAsync(async () => { ObjectDisposedException.ThrowIf(_closing, this); Exception? failure = null; await CloseWebViewAsync().ConfigureAwait(true); if (whileStopped is not null) { try { await whileStopped().ConfigureAwait(true); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { failure = ex; } } await StartCoreAsync().ConfigureAwait(true); if (failure is not null) { ExceptionDispatchInfo.Throw(failure); } })); public async ValueTask DisposeAsync() { try { await OnUiAsync(() => ExclusiveAsync( async () => { _closing = true; ReleaseLease(); await CloseWebViewAsync().ConfigureAwait(true); _window?.CloseForGood(); _window = null; }, StopWait)).ConfigureAwait(false); } catch (Exception ex) when (ex is InvalidOperationException or TaskCanceledException) { // The dispatcher already stopped: Windows closes what is left. } await _session.DisposeAsync().ConfigureAwait(false); } /// True while a WebView is in the window and attached to the session (its browser process did not die). private bool IsRunning => _controller is not null && _session.IsAttached; /// /// UI thread, one at a time (): the only place a WebView is created, so the window never /// holds two. A WebView already running stays (the start is done); what a dead one left is closed first; a failed /// start closes what it created. /// private async Task StartCoreAsync() { _ui.VerifyAccess(); ObjectDisposedException.ThrowIf(_closing, this); var options = _options ?? throw new InvalidOperationException("Opzioni del browser mancanti."); // Started already, by «Scollega» or by the start after a crash, while this start waited for its turn or for its // next attempt: a second WebView would orphan the first, whose browser process then holds the profile. if (IsRunning) { return; } // A WebView whose browser process died (the session is detached) is closed before the new one exists. await CloseWebViewAsync().ConfigureAwait(true); _starting = true; _crashedWhileStarting = false; try { await CreateWebViewAsync(options).ConfigureAwait(true); // The browser process went away while the start awaited WebView2: this start failed, the caller retries. if (_crashedWhileStarting) { throw new InvalidOperationException("Il processo del browser WebView2 si è chiuso durante l'avvio."); } // Stopping gave up waiting for this start (WebView2 took longer than StopWait) and closed what there was: // what this start created goes too. ObjectDisposedException.ThrowIf(_closing, this); } catch (Exception ex) when (ex is not OutOfMemoryException) { // Nothing stays open after a failed start, whoever retries it and whenever: here, inside the same step. await CloseAfterFailedStartAsync().ConfigureAwait(true); throw; } finally { _starting = false; } } private async Task CloseAfterFailedStartAsync() { try { await CloseWebViewAsync().ConfigureAwait(true); } catch (Exception ex) when (ex is not OutOfMemoryException) { _log.Warn("browser", "WebView2: quello che l'avvio non riuscito ha lasciato aperto non si è chiuso del tutto.", ex); } } private async Task CreateWebViewAsync(BrowserOptions options) { if (_window is null) { var window = new BrowserWindow(options.WindowWidth, options.WindowHeight, _settings.Icon); window.MoveOffScreen(); window.Show(); window.Activated += OnActivated; window.DoneRequested += (_, _) => Done(); window.BackRequested += (_, _) => UserNavigation(core => core.GoBack(), core => core.CanGoBack); window.ReloadRequested += (_, _) => UserNavigation(core => core.Reload(), _ => true); window.DpiChanged += (_, _) => UpdateBounds(); _window = window; } var profile = Path.GetFullPath(options.ProfileDirectory); Directory.CreateDirectory(profile); var environmentOptions = new CoreWebView2EnvironmentOptions { AdditionalBrowserArguments = _settings.AdditionalBrowserArguments }; var environment = await CoreWebView2Environment.CreateAsync(null, profile, environmentOptions).ConfigureAwait(true); _environment = environment; _exited = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); environment.BrowserProcessExited += OnBrowserProcessExited; // Read here, on the UI thread, for the log line the composition writes from another thread: a member of the // environment read there throws «CoreWebView2Environment members can only be accessed from the UI thread». _version = environment.BrowserVersionString; var hwnd = _window.Handle; CoreWebView2Controller controller; if (_settings.Hosting == BrowserHosting.Composition) { var composition = await environment.CreateCoreWebView2CompositionControllerAsync(hwnd).ConfigureAwait(true); controller = composition; _controller = controller; _composition = new CompositionHost(hwnd, () => _window?.PageBounds ?? default); _composition.Attach(composition); } else { controller = await environment.CreateCoreWebView2ControllerAsync(hwnd).ConfigureAwait(true); _controller = controller; } controller.BoundsMode = CoreWebView2BoundsMode.UseRawPixels; controller.Bounds = _window.PageBounds; // WebView2 stops painting when IsVisible is false (S2): it stays true for the whole life of the browser. controller.IsVisible = true; var core = controller.CoreWebView2; _core = core; Volatile.Write(ref _browserProcessId, unchecked((int)core.BrowserProcessId)); var s = core.Settings; s.IsPasswordAutosaveEnabled = false; s.IsGeneralAutofillEnabled = false; s.AreDevToolsEnabled = false; s.IsZoomControlEnabled = false; s.IsPinchZoomEnabled = false; s.IsSwipeNavigationEnabled = false; // Events of an earlier WebView (closed, or crashed) must not act on this one. var generation = ++_generation; core.NewWindowRequested += OnNewWindowRequested; core.DownloadStarting += (_, e) => e.Cancel = true; core.PermissionRequested += (_, e) => e.State = CoreWebView2PermissionState.Deny; core.SourceChanged += (_, _) => _window?.ShowAddress(Addresses.WithoutQuery(core.Source)); core.ProcessFailed += (sender, e) => OnProcessFailed(generation, sender, e); core.Navigate(CdpPageExtensions.RestUrl); _devTools = new CoreWebView2DevTools(_ui, core); _session.Attach(_devTools); await _session.SendAsync("Page.enable", null, CancellationToken.None).ConfigureAwait(true); } /// /// Closes the controller and waits for the browser process to exit (the profile is written). UI thread. From here on /// the events of the WebView being closed belong to an old generation: they change nothing. /// private async Task CloseWebViewAsync() { _ui.VerifyAccess(); _generation++; _session.Detach(); _devTools?.Close(); _devTools = null; _core = null; var exited = _exited; if (_composition is { } composition) { _composition = null; try { composition.Dispose(); } catch (Exception ex) when (ex is COMException or InvalidOperationException) { // The visual tree goes with the window. } } if (_controller is { } controller) { _controller = null; try { controller.Close(); } catch (Exception ex) when (ex is COMException or InvalidOperationException) { // The browser process is already gone (it crashed): nothing left to close. } if (exited is not null) { await Task.WhenAny(exited.Task, Task.Delay(ExitWait)).ConfigureAwait(true); } } if (_environment is { } environment) { environment.BrowserProcessExited -= OnBrowserProcessExited; _environment = null; } } private void OnBrowserProcessExited(object? sender, CoreWebView2BrowserProcessExitedEventArgs e) => _exited?.TrySetResult(); private void OnProcessFailed(int generation, object? sender, CoreWebView2ProcessFailedEventArgs e) { var kind = e.ProcessFailedKind; _log.Warn("browser", $"WebView2: processo terminato ({kind})."); // A WebView that is closing, closed or replaced is not ours any more (a restart, «Scollega», a failed start). if (_closing || generation != _generation) { return; } // During a start the failure is the start's own error: the start closes what it created and the caller retries. if (_starting) { _crashedWhileStarting |= kind == CoreWebView2ProcessFailedKind.BrowserProcessExited; return; } if (kind == CoreWebView2ProcessFailedKind.BrowserProcessExited) { // The whole browser is gone: commands fail from now on, and the owner starts it again (same profile), as // the supervisor does with Chromium — once this handler has returned (threading model of WebView2). _session.Detach(); _ = _ui.InvokeAsync(() => BrowserProcessFailed?.Invoke(this, EventArgs.Empty), DispatcherPriority.Background); } else if (kind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive) { // The page crashed: back to the rest page (spec §6.1); a running recipe ends on its own errors. try { (sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl); } catch (Exception ex) when (ex is COMException or InvalidOperationException) { // The browser went with the page: its own ProcessFailed follows. } } } private void OnNewWindowRequested(object? sender, CoreWebView2NewWindowRequestedEventArgs e) { // Pages that open a new window stay in this one: the session stays in the profile of Febe. e.Handled = true; if (sender is CoreWebView2 core && Uri.TryCreate(e.Uri, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https") { core.Navigate(uri.AbsoluteUri); } } /// /// Alberto clicked into the window while it is on screen: he is driving. An activation while it is parked out of view /// is not his (Windows activates the next window when another one closes) and changes nothing. /// private void OnActivated(object? sender, EventArgs e) { if (_window is not { } window || _closing || !window.IsOnScreen) { return; } TakeLease(); } /// Alberto closed or minimised the window: done, out of view. private void Done() { _window?.MoveOffScreen(); ReleaseLease(); } private void UserNavigation(Action action, Func allowed) { // «Indietro» and «Ricarica» of the bar are Alberto's own navigation (rule 7): never an engine action. if (_core is not { } core) { return; } try { if (allowed(core)) { TakeLease(); action(core); } } catch (Exception ex) when (ex is COMException or InvalidOperationException) { // The browser process is gone (it is starting again): the button does nothing. } } private void UpdateBounds() { if (_controller is not { } controller || _window is not { } window) { return; } try { controller.Bounds = window.PageBounds; } catch (Exception ex) when (ex is COMException or InvalidOperationException) { // The browser process is gone: the next start sizes the new WebView. } } private void TakeLease() { if (_lease is null) { _lease = UserDriving.Begin(); _log.Info("browser", "Alberto usa il browser di Febe: il motore resta fermo."); } _settings.MarkUsed(); } private void ReleaseLease() { if (_lease is { } lease) { _lease = null; _settings.MarkUsed(); lease.Dispose(); _log.Info("browser", "Browser di Febe fuori vista."); } } /// /// Runs one step of the life of the WebView (start, restart, stop) after the others. UI thread. With /// the step runs anyway once that time has passed (stopping must not hang behind a start /// that WebView2 never completes). /// private async Task ExclusiveAsync(Func step, TimeSpan? wait = null) { var entered = true; if (wait is { } limit) { entered = await _lifecycle.WaitAsync(limit).ConfigureAwait(true); } else { await _lifecycle.WaitAsync().ConfigureAwait(true); } try { await step().ConfigureAwait(true); } finally { if (entered) { _lifecycle.Release(); } } } /// /// Waits for until is cancelled. Then the caller goes on and the work /// is left to end by itself; its outcome is observed here, so a late error is never an unobserved task. /// private static async Task UntilCancelledAsync(Task work, CancellationToken ct) { try { await work.WaitAsync(ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { _ = work.ContinueWith( static done => _ = done.Exception, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); throw; } } /// /// Runs on the UI thread — at once when already there — and returns its task: an exception /// is always in the task, never thrown to the caller. /// private Task OnUiAsync(Func action) { if (!_ui.CheckAccess()) { return _ui.InvokeAsync(action).Task.Unwrap(); } try { return action(); } catch (Exception ex) when (ex is not OutOfMemoryException) { return Task.FromException(ex); } } }