WebView2Host avviava WebView2 correttamente sul thread dell'interfaccia, ma WebView2Browser
aspettava l'avvio con ConfigureAwait(false) e, su un thread del pool, scriveva nel registro
«Browser di Febe pronto: WebView2 {Host.Version}»: Version leggeva BrowserVersionString
dall'ambiente di WebView2 fuori dal thread dell'interfaccia, WebView2 lanciava
InvalidOperationException, il ciclo la prendeva per un avvio fallito, chiudeva il WebView che
funzionava e riprovava per sempre (5, 15, 30, 60, 300 s). La finestra «Browser di Febe» non
diventava mai disponibile e l'accesso a Instagram non poteva nemmeno cominciare.
Ora la versione si legge sul thread dell'interfaccia durante l'avvio e Version restituisce un
valore semplice, leggibile da qualunque thread; e quello che segue un avvio riuscito (stato e
riga del registro) sta fuori dal blocco dei tentativi, così non può più disfarlo: si riprova
solo quando fallisce l'avvio stesso. La prova di regressione del commit precedente ora passa.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
383 lines
15 KiB
C#
383 lines
15 KiB
C#
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;
|
|
|
|
/// <summary>Windows-only settings of <see cref="WebView2Host"/>, on top of <see cref="BrowserOptions"/>.</summary>
|
|
/// <param name="Hosting"><see cref="BrowserHosting.Window"/> or <see cref="BrowserHosting.Composition"/> (S2).</param>
|
|
/// <param name="AdditionalBrowserArguments">The switches of S2 (<see cref="BrowserArguments.ForWebView2"/>).</param>
|
|
/// <param name="Icon">The icon of the window.</param>
|
|
/// <param name="MarkUsed">Called when Alberto uses the browser and when he is done with it («Riprendi»).</param>
|
|
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed);
|
|
|
|
/// <summary>
|
|
/// 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 (<see cref="BrowserOptions.ProfileDirectory"/>, <c>Dati\browser</c>), driven through
|
|
/// <see cref="WebView2CdpSession"/> — the same allowlist and refusals as the Chromium client — over
|
|
/// <c>CallDevToolsProtocolMethodAsync</c> and <c>GetDevToolsProtocolEventReceiver</c>. No port, no process of ours.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <list type="bullet">
|
|
/// <item>Password saving and general autofill off; no developer tools, no zoom: the page has a fixed size.</item>
|
|
/// <item>S2: the window is open but parked out of view when Alberto does not use it; the controller stays visible; the
|
|
/// switches of <see cref="BrowserArguments"/> turn off occlusion detection. Never hidden, never minimised.</item>
|
|
/// <item>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».</item>
|
|
/// <item>Stopping closes the WebView and waits for its browser process to exit, so the session is on disk (S3);
|
|
/// <see cref="RestartAsync"/> («Scollega») does the same before deleting the profile.</item>
|
|
/// <item>Every WebView2 call runs on the UI thread through its dispatcher.</item>
|
|
/// </list>
|
|
/// </remarks>
|
|
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());
|
|
}
|
|
|
|
/// <summary>The page session: stable for the whole life of the host (a restart attaches a new WebView to it).</summary>
|
|
public ICdpSession Cdp => _session;
|
|
|
|
/// <summary>Raised when a new WebView replaced the previous one (subscriptions survive; domains are enabled again).</summary>
|
|
public ICdpConnectionEvents Connection => _session;
|
|
|
|
/// <summary>Leases taken while Alberto uses the browser.</summary>
|
|
public UserDrivingGate UserDriving { get; } = new();
|
|
|
|
public bool UserIsDriving => UserDriving.IsDriving;
|
|
|
|
/// <summary>True while a WebView is attached (commands can be sent).</summary>
|
|
public bool IsAttached => _session.IsAttached;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public string? Version => _version;
|
|
|
|
/// <summary>Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts).</summary>
|
|
public event EventHandler? BrowserProcessFailed;
|
|
|
|
/// <summary>Creates the window (once), the environment and the controller, and attaches the CDP session.</summary>
|
|
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;
|
|
});
|
|
|
|
/// <summary>
|
|
/// Closes the WebView, waits for its browser process to exit (the profile is free and written), runs
|
|
/// <paramref name="whileStopped"/> — «Scollega» deletes the profile there — and starts it again. <see cref="Cdp"/>
|
|
/// stays the same object. The browser starts again even when <paramref name="whileStopped"/> fails; its error is
|
|
/// thrown afterwards.
|
|
/// </summary>
|
|
public Task RestartAsync(Func<Task>? 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;
|
|
}
|
|
});
|
|
|
|
/// <summary>Closes what a failed start left, so that the next start begins clean.</summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>Closes the controller and waits for the browser process to exit (the profile is written). UI thread.</summary>
|
|
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);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
private void OnActivated(object? sender, EventArgs e)
|
|
{
|
|
if (_window is not { } window || _closing || !window.IsOnScreen)
|
|
{
|
|
return;
|
|
}
|
|
|
|
TakeLease();
|
|
}
|
|
|
|
/// <summary>Alberto closed or minimised the window: done, out of view.</summary>
|
|
private void Done()
|
|
{
|
|
_window?.MoveOffScreen();
|
|
ReleaseLease();
|
|
}
|
|
|
|
private void UserNavigation(Action<CoreWebView2> action, Func<CoreWebView2, bool> 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<Task> action) => _ui.CheckAccess() ? action() : _ui.InvokeAsync(action).Task.Unwrap();
|
|
}
|