Browser di Febe per Windows: ripartenze robuste, WebView2 toccato solo dal suo thread

Dopo la correzione dell'avvio, la revisione di tutto il percorso del browser per Windows ha
trovato altri punti della stessa famiglia: lavoro che, se va storto, lascia il browser morto o
riprova per sempre.

- WebView2Host: avvio, ripartenza, chiusura dopo un avvio fallito e arresto passano uno alla
  volta (ognuno aspetta WebView2 sul thread dell'interfaccia e prima potevano intrecciarsi);
  un arresto del processo del browser durante un avvio fa fallire quell'avvio invece di
  lasciare un WebView morto dato per buono; l'arresto del processo si annuncia solo dopo che il
  gestore dell'evento di WebView2 è tornato (WebView2 non regge chiusure e ricreazioni dentro i
  suoi gestori) e solo per il WebView in uso; versione e numero del processo sono valori
  semplici letti sul thread dell'interfaccia; MoveFocus, Bounds, Indietro e Ricarica non fanno
  più cadere eccezioni nell'interfaccia se il processo è appena morto; in primo piano il
  permesso di guida si prende prima di spostare il fuoco.
- WebView2Browser: dopo un arresto del processo e dopo un «Scollega» la cui ripartenza fallisce,
  il browser riparte con gli stessi tentativi del primo avvio (prima: un tentativo solo, poi
  morto fino al riavvio di Febe; e con «Scollega» anche il motore restava fermo, perché
  l'errore non era di cartella); un solo ciclo di ripartenza alla volta, sul pool e mai dentro
  un gestore di WebView2; la cancellazione del profilo non blocca più la finestra.

Prove nuove su WebView2 vero: un avvio che fallisce davvero si riprova una volta sola e poi
va; la finestra viene in primo piano e torna fuori vista con il permesso di guida, anche
chiudendola; «Scollega» cancella profilo e sessione e il browser riparte vuoto; ucciso (per
numero di processo) il browser avviato dalla prova, Febe lo fa ripartire da solo; l'ospitalità
«composizione» di S2 parte e disegna.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-20 10:29:59 +02:00
1 parent a6623e5736
commit ccfd8b5c08
4 files changed
+649 -114

No files matched your search

+198 -58
View File
@@ -12,8 +12,15 @@ namespace Febe.Desktop.Browser;
/// <summary>
/// The browser of Instagram on Windows as the shared composition sees it (<see cref="IFebeBrowser"/>): a
/// <see cref="WebView2Host"/> started with retries like <see cref="ChromiumBrowser"/> starts Chromium, started again
/// when its browser process goes away, and emptied by «Scollega» (spec §4.1) once WebView2 has closed.
/// (with the same retries) when its browser process goes away, and emptied by «Scollega» (spec §4.1) once WebView2 has
/// closed.
/// </summary>
/// <remarks>
/// Only a failed start is retried: what follows a start that worked (the log line, the state) is outside the retries,
/// and reads only plain values of the host, never WebView2 objects — this class runs on the threads of the composition,
/// while every WebView2 object lives on the UI thread (the error of 14 October 2026: the version of WebView2 read here,
/// on a thread-pool thread, threw after every successful start, and the start was undone and retried for ever).
/// </remarks>
internal sealed class WebView2Browser : IFebeBrowser
{
private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)];
@@ -22,6 +29,11 @@ internal sealed class WebView2Browser : IFebeBrowser
private readonly FebePlatformContext _context;
private readonly IClock _wallClock;
private readonly BrowserOptions _options;
private readonly CancellationTokenSource _lifetime = new();
private readonly Lock _gate = new();
private Task? _restartLoop;
private bool _restartWanted;
private Exception? _restartFailure;
private volatile bool _started;
private volatile string? _lastError;
@@ -39,7 +51,7 @@ internal sealed class WebView2Browser : IFebeBrowser
ui,
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now)),
context.Log);
Host.BrowserProcessFailed += (_, _) => _ = RecoverAsync();
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
}
/// <summary>The host: window «Browser di Febe», WebView2, CDP.</summary>
@@ -63,40 +75,10 @@ internal sealed class WebView2Browser : IFebeBrowser
public async Task RunAsync(CancellationToken ct)
{
for (var attempt = 0; !ct.IsCancellationRequested; attempt++)
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token);
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), stop.Token).ConfigureAwait(false))
{
try
{
await Host.StartAsync(_options, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_lastError = $"WebView2 non parte ({ex.GetType().Name}: {FirstLine(ex.Message)}).";
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
_context.Log.Error("browser", $"{_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
await Host.ResetAsync().ConfigureAwait(false);
try
{
await _wallClock.Delay(wait, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
continue;
}
// Outside the retries: what follows a start that worked never undoes it. This runs on a thread of the
// composition, so it reads only plain values of the host (the version was read on the UI thread).
_started = true;
_lastError = null;
_context.Log.Info("browser", $"Browser di Febe pronto: WebView2 {Host.Version}, pagina {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, {BrowserHostingNames.Name(_settings.Hosting)}, fuori vista.");
return;
_context.Log.Info("browser", ReadyMessage("Browser di Febe pronto"));
}
}
@@ -106,56 +88,214 @@ internal sealed class WebView2Browser : IFebeBrowser
public Task HideFromUserAsync(CancellationToken ct) => Host.HideFromUserAsync();
/// <summary>«Scollega»: WebView2 closes and its process exits, <c>Dati\browser</c> is deleted, the browser starts empty.</summary>
/// <summary>
/// «Scollega»: WebView2 closes and its process exits, <c>Dati\browser</c> is deleted, the browser starts empty. When
/// the profile cannot be deleted completely an <see cref="IOException"/> says so (the browser starts again anyway);
/// when WebView2 does not start again, the same retries as at start-up bring it back in the background, and
/// «Scollega» has still done its part (the connection service starts the engine again either way).
/// </summary>
public async Task RestartWithEmptyProfileAsync(CancellationToken ct)
{
try
Exception? deletion = null;
async Task DeleteProfileQuietlyAsync()
{
await Host.RestartAsync(DeleteProfileAsync, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
throw new IOException($"La cartella del browser ({ProfileDirectory}) non si è potuta cancellare del tutto: esci da Febe e cancellala tu, contiene la sessione di Instagram.", ex);
try
{
await DeleteProfileAsync().ConfigureAwait(true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
deletion = ex;
}
}
_context.Log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto.");
var restarted = false;
try
{
await Host.RestartAsync(DeleteProfileQuietlyAsync, ct).ConfigureAwait(false);
MarkStarted();
restarted = true;
}
catch (Exception ex) when (ex is not (OutOfMemoryException or ObjectDisposedException))
{
// The start that follows the deletion failed: never a dead browser after «Scollega».
RequestRestart(ex);
}
if (deletion is not null)
{
throw new IOException($"La cartella del browser ({ProfileDirectory}) non si è potuta cancellare del tutto: esci da Febe e cancellala tu, contiene la sessione di Instagram.", deletion);
}
_context.Log.Info("browser", restarted
? "Profilo del browser cancellato; il browser è ripartito vuoto."
: "Profilo del browser cancellato; il browser ripartirà vuoto.");
}
public ValueTask DisposeAsync() => Host.DisposeAsync();
/// <summary>The browser process of WebView2 went away by itself: it starts again with the same profile.</summary>
private async Task RecoverAsync()
/// <summary>
/// Stops the retries, waits for a restart in progress, then closes WebView2 and its window. <c>_lifetime</c> stays
/// undisposed on purpose: a late caller may still read its (cancelled) token.
/// </summary>
public async ValueTask DisposeAsync()
{
await _lifetime.CancelAsync().ConfigureAwait(false);
Task? restarting;
lock (_gate)
{
restarting = _restartLoop;
}
if (restarting is not null)
{
await restarting.ConfigureAwait(false);
}
await Host.DisposeAsync().ConfigureAwait(false);
}
/// <summary>
/// Runs <paramref name="start"/> until it works (true) or <paramref name="ct"/> is cancelled (false), waiting
/// <see cref="Retry"/> between attempts. With <paramref name="failedFirst"/> the first attempt already failed with it.
/// Only an exception of the start itself is a failed start; this method never throws.
/// </summary>
private async Task<bool> StartWithRetriesAsync(Func<CancellationToken, Task> start, CancellationToken ct, Exception? failedFirst = null)
{
var attempt = 0;
if (failedFirst is not null && !await AfterFailedStartAsync(failedFirst, attempt++, ct).ConfigureAwait(false))
{
return false;
}
while (!ct.IsCancellationRequested)
{
try
{
await start(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ct.IsCancellationRequested && ex is (OperationCanceledException or ObjectDisposedException))
{
return false;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (!await AfterFailedStartAsync(ex, attempt++, ct).ConfigureAwait(false))
{
return false;
}
continue;
}
MarkStarted();
return true;
}
return false;
}
/// <summary>A start failed: it is said, what it left is closed, and the next attempt waits. False when cancelled.</summary>
private async Task<bool> AfterFailedStartAsync(Exception error, int attempt, CancellationToken ct)
{
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
_lastError = $"WebView2 non parte ({error.GetType().Name}: {FirstLine(error.Message)}).";
_context.Log.Error("browser", $"{_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
try
{
await Host.RestartAsync(null, CancellationToken.None).ConfigureAwait(false);
_context.Log.Info("browser", "Browser di Febe ripartito dopo l'arresto del suo processo.");
await Host.ResetAsync().ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_started = false;
_lastError = $"WebView2 non riparte ({ex.GetType().Name}).";
_context.Log.Error("browser", _lastError);
_context.Log.Warn("browser", "WebView2: quello che l'avvio non riuscito ha lasciato aperto non si è chiuso del tutto.", ex);
}
try
{
await _wallClock.Delay(wait, ct).ConfigureAwait(false);
return true;
}
catch (OperationCanceledException)
{
return false;
}
}
/// <summary>Deletes the profile; a process of WebView2 may still hold a file for a moment.</summary>
private void MarkStarted()
{
_started = true;
_lastError = null;
}
/// <summary>
/// The browser must start again (its process went away by itself, or the start after «Scollega» failed with
/// <paramref name="failure"/>): one loop at a time restarts it, with the retries of the first start, on the thread
/// pool — never inside an event handler of WebView2. A request that comes while the loop runs makes it go round again.
/// </summary>
private void RequestRestart(Exception? failure)
{
lock (_gate)
{
if (_lifetime.IsCancellationRequested)
{
return;
}
_restartWanted = true;
_restartFailure ??= failure;
_restartLoop ??= Task.Run(RestartLoopAsync);
}
}
private async Task RestartLoopAsync()
{
while (true)
{
Exception? failure;
lock (_gate)
{
if (!_restartWanted || _lifetime.IsCancellationRequested)
{
_restartLoop = null;
return;
}
_restartWanted = false;
failure = _restartFailure;
_restartFailure = null;
}
if (await StartWithRetriesAsync(token => Host.RestartAsync(null, token), _lifetime.Token, failure).ConfigureAwait(false))
{
_context.Log.Info("browser", ReadyMessage("Browser di Febe ripartito"));
}
}
}
/// <summary>Plain values only (the version was read on the UI thread during the start).</summary>
private string ReadyMessage(string what) =>
$"{what}: WebView2 {Host.Version ?? "di versione sconosciuta"}, pagina {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, {BrowserHostingNames.Name(_settings.Hosting)}, fuori vista.";
/// <summary>
/// Deletes the profile — off the UI thread, it can be large — retrying while a process of WebView2 still holds a
/// file for a moment.
/// </summary>
private async Task DeleteProfileAsync()
{
for (var attempt = 0; ; attempt++)
{
try
{
if (Directory.Exists(ProfileDirectory))
await Task.Run(() =>
{
Directory.Delete(ProfileDirectory, recursive: true);
}
if (Directory.Exists(ProfileDirectory))
{
Directory.Delete(ProfileDirectory, recursive: true);
}
}).ConfigureAwait(true);
return;
}
catch (Exception ex) when ((ex is IOException or UnauthorizedAccessException) && attempt < 10)
{
await Task.Delay(500).ConfigureAwait(true);
await _wallClock.Delay(TimeSpan.FromMilliseconds(500), CancellationToken.None).ConfigureAwait(true);
}
}
}
+234 -53
View File
@@ -1,3 +1,4 @@
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Threading;
@@ -35,30 +36,47 @@ internal sealed record WebView2HostOptions(BrowserHosting Hosting, string Additi
/// «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>
/// <item>Threads: every WebView2 object (environment, controller, <c>CoreWebView2</c>, 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 (<see cref="Version"/>, <see cref="BrowserProcessId"/>), the CDP session, and tasks. Start,
/// restart, reset and stop run one at a time.</item>
/// </list>
/// </remarks>
internal sealed class WebView2Host : IBrowserHost
{
private static readonly TimeSpan ExitWait = TimeSpan.FromSeconds(15);
/// <summary>How long stopping waits for a start or restart in progress before closing what there is.</summary>
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, reset 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;
private bool _restarting;
// Read on the UI thread during the start: a plain value that any thread may read.
// 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)
{
@@ -88,7 +106,16 @@ internal sealed class WebView2Host : IBrowserHost
/// </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>
/// <summary>The browser process of WebView2 when it last started (0 before the first start). Any thread.</summary>
public int BrowserProcessId => Volatile.Read(ref _browserProcessId);
/// <summary>The window «Browser di Febe» (null before the first start). UI thread only, like every WPF object.</summary>
internal BrowserWindow? Window => _window;
/// <summary>
/// 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.
/// </summary>
public event EventHandler? BrowserProcessFailed;
/// <summary>Creates the window (once), the environment and the controller, and attaches the CDP session.</summary>
@@ -96,7 +123,7 @@ internal sealed class WebView2Host : IBrowserHost
{
ArgumentNullException.ThrowIfNull(options);
_options = options;
return OnUiAsync(StartCoreAsync);
return OnUiAsync(() => ExclusiveAsync(StartCoreAsync));
}
public Task ShowToUserAsync() => OnUiAsync(() =>
@@ -110,8 +137,18 @@ internal sealed class WebView2Host : IBrowserHost
window.Activate();
window.Topmost = true;
window.Topmost = false;
_controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
// 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;
});
@@ -125,55 +162,61 @@ internal sealed class WebView2Host : IBrowserHost
/// <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.
/// stays the same object. The browser starts again even when <paramref name="whileStopped"/> fails with an
/// <see cref="IOException"/> or <see cref="UnauthorizedAccessException"/>; that error is thrown afterwards. A failed
/// start throws its own error and, as after a failed <see cref="StartAsync"/>, the caller closes what it left with
/// <see cref="ResetAsync"/> before trying again.
/// </summary>
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(async () =>
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(() => ExclusiveAsync(async () =>
{
ObjectDisposedException.ThrowIf(_closing, this);
Exception? failure = null;
_restarting = true;
try
{
await CloseWebViewAsync().ConfigureAwait(true);
Exception? failure = null;
try
if (whileStopped is not null)
{
if (whileStopped is not null)
try
{
await whileStopped().ConfigureAwait(true);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
failure = ex;
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;
}
});
if (failure is not null)
{
ExceptionDispatchInfo.Throw(failure);
}
}));
/// <summary>Closes what a failed start left, so that the next start begins clean.</summary>
public Task ResetAsync() => OnUiAsync(CloseWebViewAsync);
public Task ResetAsync() => OnUiAsync(() => ExclusiveAsync(CloseWebViewAsync));
public async ValueTask DisposeAsync()
{
try
{
await OnUiAsync(async () =>
{
_closing = true;
ReleaseLease();
await CloseWebViewAsync().ConfigureAwait(true);
_window?.CloseForGood();
_window = null;
}).ConfigureAwait(false);
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)
{
@@ -183,9 +226,32 @@ internal sealed class WebView2Host : IBrowserHost
await _session.DisposeAsync().ConfigureAwait(false);
}
/// <summary>UI thread, one at a time (<see cref="ExclusiveAsync"/>).</summary>
private async Task StartCoreAsync()
{
_ui.VerifyAccess();
ObjectDisposedException.ThrowIf(_closing, this);
var options = _options ?? throw new InvalidOperationException("Opzioni del browser mancanti.");
_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.");
}
}
finally
{
_starting = false;
}
}
private async Task CreateWebViewAsync(BrowserOptions options)
{
if (_window is null)
{
var window = new BrowserWindow(options.WindowWidth, options.WindowHeight, _settings.Icon);
@@ -202,28 +268,31 @@ internal sealed class WebView2Host : IBrowserHost
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);
var environment = await CoreWebView2Environment.CreateAsync(null, profile, environmentOptions).ConfigureAwait(true);
_environment = environment;
_exited = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_environment.BrowserProcessExited += OnBrowserProcessExited;
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;
_version = environment.BrowserVersionString;
var hwnd = _window.Handle;
CoreWebView2Controller controller;
if (_settings.Hosting == BrowserHosting.Composition)
{
var composition = await _environment.CreateCoreWebView2CompositionControllerAsync(hwnd).ConfigureAwait(true);
var composition = await environment.CreateCoreWebView2CompositionControllerAsync(hwnd).ConfigureAwait(true);
controller = composition;
_controller = controller;
_composition = new CompositionHost(hwnd, () => _window?.PageBounds ?? default);
_composition.Attach(composition);
_controller = composition;
}
else
{
_controller = await _environment.CreateCoreWebView2ControllerAsync(hwnd).ConfigureAwait(true);
controller = await environment.CreateCoreWebView2ControllerAsync(hwnd).ConfigureAwait(true);
_controller = controller;
}
var controller = _controller;
controller.BoundsMode = CoreWebView2BoundsMode.UseRawPixels;
controller.Bounds = _window.PageBounds;
@@ -231,6 +300,8 @@ internal sealed class WebView2Host : IBrowserHost
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;
@@ -238,11 +309,14 @@ internal sealed class WebView2Host : IBrowserHost
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 += OnProcessFailed;
core.ProcessFailed += (sender, e) => OnProcessFailed(generation, sender, e);
core.Navigate(CdpPageExtensions.RestUrl);
_devTools = new CoreWebView2DevTools(_ui, core);
@@ -253,16 +327,30 @@ internal sealed class WebView2Host : IBrowserHost
/// <summary>Closes the controller and waits for the browser process to exit (the profile is written). UI thread.</summary>
private async Task CloseWebViewAsync()
{
_ui.VerifyAccess();
_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
{
_composition?.Dispose();
controller.Close();
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
@@ -270,7 +358,6 @@ internal sealed class WebView2Host : IBrowserHost
// 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);
@@ -286,24 +373,48 @@ internal sealed class WebView2Host : IBrowserHost
private void OnBrowserProcessExited(object? sender, CoreWebView2BrowserProcessExitedEventArgs e) => _exited?.TrySetResult();
private void OnProcessFailed(object? sender, CoreWebView2ProcessFailedEventArgs e)
private void OnProcessFailed(int generation, object? sender, CoreWebView2ProcessFailedEventArgs e)
{
_log.Warn("browser", $"WebView2: processo terminato ({e.ProcessFailedKind}).");
if (_closing || _restarting)
var kind = e.ProcessFailedKind;
_log.Warn("browser", $"WebView2: processo terminato ({kind}).");
// A closed or replaced WebView is not ours any more.
if (_closing || generation != _generation)
{
return;
}
if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
// During a start the failure is the start's own error (the caller retries); while a restart closes the old
// WebView the failure changes nothing.
if (_starting)
{
// 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);
_crashedWhileStarting |= kind == CoreWebView2ProcessFailedKind.BrowserProcessExited;
return;
}
else if (e.ProcessFailedKind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
if (_restarting)
{
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.
(sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl);
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.
}
}
}
@@ -341,19 +452,40 @@ internal sealed class WebView2Host : IBrowserHost
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))
if (_core is not { } core)
{
TakeLease();
action(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 { } controller && _window is { } window)
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()
@@ -378,5 +510,54 @@ internal sealed class WebView2Host : IBrowserHost
}
}
private Task OnUiAsync(Func<Task> action) => _ui.CheckAccess() ? action() : _ui.InvokeAsync(action).Task.Unwrap();
/// <summary>
/// Runs one step of the life of the WebView (start, restart, reset, stop) after the others. UI thread. With
/// <paramref name="wait"/> the step runs anyway once that time has passed (stopping must not hang behind a start
/// that WebView2 never completes).
/// </summary>
private async Task ExclusiveAsync(Func<Task> 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();
}
}
}
/// <summary>
/// Runs <paramref name="action"/> 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.
/// </summary>
private Task OnUiAsync(Func<Task> 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);
}
}
}