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. /// Every WebView2 call runs on the UI thread through its dispatcher. /// /// internal sealed class WebView2Host : IBrowserHost { private static readonly TimeSpan ExitWait = TimeSpan.FromSeconds(15); private readonly Dispatcher _ui; private readonly WebView2HostOptions _settings; private readonly FebeLog _log; private readonly WebView2CdpSession _session; private BrowserOptions? _options; private BrowserWindow? _window; private CoreWebView2Environment? _environment; private CoreWebView2Controller? _controller; private CompositionHost? _composition; private CoreWebView2DevTools? _devTools; private TaskCompletionSource? _exited; private IDisposable? _lease; private bool _closing; private bool _restarting; // Read on the UI thread during the start: a plain value that any thread may read. private volatile string? _version; 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; /// Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts). public event EventHandler? BrowserProcessFailed; /// Creates the window (once), the environment and the controller, and attaches the CDP session. public Task StartAsync(BrowserOptions options, CancellationToken ct) { ArgumentNullException.ThrowIfNull(options); _options = options; return OnUiAsync(StartCoreAsync); } public Task ShowToUserAsync() => OnUiAsync(() => { if (_window is not { } window) { return Task.CompletedTask; } window.MoveOnScreen(); window.Activate(); window.Topmost = true; window.Topmost = false; _controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic); TakeLease(); 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; its error is /// thrown afterwards. /// public Task RestartAsync(Func? whileStopped, CancellationToken ct) => OnUiAsync(async () => { _restarting = true; try { await CloseWebViewAsync().ConfigureAwait(true); Exception? failure = null; try { if (whileStopped is not null) { await whileStopped().ConfigureAwait(true); } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { failure = ex; } await StartCoreAsync().ConfigureAwait(true); if (failure is not null) { throw failure; } } finally { _restarting = false; } }); /// Closes what a failed start left, so that the next start begins clean. public Task ResetAsync() => OnUiAsync(CloseWebViewAsync); public async ValueTask DisposeAsync() { try { await OnUiAsync(async () => { _closing = true; ReleaseLease(); await CloseWebViewAsync().ConfigureAwait(true); _window?.CloseForGood(); _window = null; }).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); } private async Task StartCoreAsync() { var options = _options ?? throw new InvalidOperationException("Opzioni del browser mancanti."); 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 }; _environment = await CoreWebView2Environment.CreateAsync(null, profile, environmentOptions).ConfigureAwait(true); _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; if (_settings.Hosting == BrowserHosting.Composition) { var composition = await _environment.CreateCoreWebView2CompositionControllerAsync(hwnd).ConfigureAwait(true); _composition = new CompositionHost(hwnd, () => _window?.PageBounds ?? default); _composition.Attach(composition); _controller = composition; } else { _controller = await _environment.CreateCoreWebView2ControllerAsync(hwnd).ConfigureAwait(true); } var 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; var s = core.Settings; s.IsPasswordAutosaveEnabled = false; s.IsGeneralAutofillEnabled = false; s.AreDevToolsEnabled = false; s.IsZoomControlEnabled = false; s.IsPinchZoomEnabled = false; s.IsSwipeNavigationEnabled = false; 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 += OnProcessFailed; 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. private async Task CloseWebViewAsync() { _session.Detach(); _devTools?.Close(); _devTools = null; var exited = _exited; if (_controller is { } controller) { _controller = null; try { _composition?.Dispose(); controller.Close(); } catch (Exception ex) when (ex is COMException or InvalidOperationException) { // The browser process is already gone (it crashed): nothing left to close. } _composition = null; 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(object? sender, CoreWebView2ProcessFailedEventArgs e) { _log.Warn("browser", $"WebView2: processo terminato ({e.ProcessFailedKind})."); if (_closing || _restarting) { return; } if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.BrowserProcessExited) { // The whole browser is gone: the owner starts it again (same profile), as the supervisor does with Chromium. _session.Detach(); BrowserProcessFailed?.Invoke(this, EventArgs.Empty); } else if (e.ProcessFailedKind 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. (sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl); } } 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 (_controller?.CoreWebView2 is { } core && allowed(core)) { TakeLease(); action(core); } } private void UpdateBounds() { if (_controller is { } controller && _window is { } window) { controller.Bounds = window.PageBounds; } } 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."); } } private Task OnUiAsync(Func action) => _ui.CheckAccess() ? action() : _ui.InvokeAsync(action).Task.Unwrap(); }