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 Febe.Desktop.Native; 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»). /// /// What «Pagina iniziale» does (issue #52): the connection opens the site's home when connected, the login page otherwise, /// once the engine's session ended and with the page's turn. Null: the button does nothing. /// internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func? OpenStartPage = null); /// What the host does when a process of WebView2 fails (issue #52). internal enum ProcessFailureResponse { /// Nothing: WebView2 recovers by itself (an unresponsive page while Alberto looks at it, a helper process). None, /// The whole browser is gone: the owner starts it again. Restart, /// The page crashed (or hangs while nobody looks): back to the rest page (spec §6.1). Rest, /// The GPU process restarted: the page is resized by a pixel and back, or the window may stay blank or black. Redraw, } /// /// 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. /// Issue #52: the bounds (and the zoom of a window shrunk to fit the screen) are given again, and WebView2 told of /// the window's new place, whenever the window moves on or off screen and after the GPU process restarted; a page that /// hangs while Alberto looks at it is left to recover instead of being replaced by the rest page. /// 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 CancellationTokenSource? _leaseEnded; 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(); if (window.WindowState == System.Windows.WindowState.Minimized) { window.WindowState = System.Windows.WindowState.Normal; } 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(); // On screen, perhaps shrunk to fit it: WebView2 gets its bounds again and learns where its window is now, and paints // again (WPF hid and showed the window, out of view, to give it its taskbar button). UpdateBounds(); Repaint(); 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(); NotifyPositionChanged(); return Task.CompletedTask; }); /// /// What a failed process of WebView2 asks of the host (issue #52). A page that does not answer while Alberto is at /// the window is his to wait for (WebView2 recovers, or he reloads): replacing it with the rest page would turn it /// white under his eyes. Nobody looking, it goes to rest as a crashed page does. /// internal static ProcessFailureResponse ResponseTo(CoreWebView2ProcessFailedKind kind, bool userIsDriving) => kind switch { CoreWebView2ProcessFailedKind.BrowserProcessExited => ProcessFailureResponse.Restart, CoreWebView2ProcessFailedKind.RenderProcessExited => ProcessFailureResponse.Rest, CoreWebView2ProcessFailedKind.RenderProcessUnresponsive => userIsDriving ? ProcessFailureResponse.None : ProcessFailureResponse.Rest, CoreWebView2ProcessFailedKind.GpuProcessExited => ProcessFailureResponse.Redraw, _ => ProcessFailureResponse.None, }; /// /// 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.HomeRequested += (_, _) => OpenStartPage(); window.DpiChanged += (_, _) => UpdateBounds(); window.PageAreaChanged += (_, _) => UpdateBounds(); // The raw controller does not follow its parent by itself: popups (lists of a