Una verifica indipendente di 654076d ha trovato tre punti deboli.
- «Pagina iniziale» guardava il permesso di guida una volta sola, prima di
aspettare fino a 15 s la fine della sessione e 15 s il turno della pagina
(che poi prendeva comunque). Se nel frattempo Alberto chiudeva la finestra,
Febe navigava senza permesso e fuori dal Governatore (regole 7 e 8). Ora la
pressione vale finché dura il permesso di chi l'ha premuta: la finestra di
Windows passa un gettone che si annulla con il suo permesso, la vista remota
quello della propria vita. Con il turno della pagina in mano la connessione
guarda di nuovo che Alberto guidi ancora; senza turno rinuncia invece di
prendere la pagina a un passo della ricerca. L'attesa del turno è
BrowserConnectionService.PageTurnWait (15 s, le prove la accorciano).
- Nella vista remota «Pagina iniziale» aspettava dentro il ciclo di ricezione:
la vista restava ferma fino a mezzo minuto e poi riversava clic e tasti sulla
pagina nuova. Ora la pressione corre a parte, una per volta, e intanto clic,
tasti, «Indietro» e «Ricarica» si scartano.
- Repaint chiedeva un ridisegno sincrono (RDW_UPDATENOW) a finestre figlie del
processo del browser di WebView2: uno bloccato avrebbe fermato il thread
dell'interfaccia. Ora si chiede solo di ridisegnare.
Prove nuove, che senza le correzioni non passano: la pressione dimenticata se
Alberto lascia il browser, quella che finisce con il permesso di chi l'ha
premuta, la pagina mai tolta a un passo della ricerca, la vista che non si
blocca e scarta l'input; su Windows con WebView2 vero, il gettone che si
annulla quando la finestra si chiude. PROTOCOLLO.md, la guida e decisioni.md
dicono il comportamento nuovo.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
800 lines
33 KiB
C#
800 lines
33 KiB
C#
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;
|
|
|
|
/// <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>
|
|
/// <param name="OpenStartPage">
|
|
/// 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.
|
|
/// </param>
|
|
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func<CancellationToken, Task>? OpenStartPage = null);
|
|
|
|
/// <summary>What the host does when a process of WebView2 fails (issue #52).</summary>
|
|
internal enum ProcessFailureResponse
|
|
{
|
|
/// <summary>Nothing: WebView2 recovers by itself (an unresponsive page while Alberto looks at it, a helper process).</summary>
|
|
None,
|
|
|
|
/// <summary>The whole browser is gone: the owner starts it again.</summary>
|
|
Restart,
|
|
|
|
/// <summary>The page crashed (or hangs while nobody looks): back to the rest page (spec §6.1).</summary>
|
|
Rest,
|
|
|
|
/// <summary>The GPU process restarted: the page is resized by a pixel and back, or the window may stay blank or black.</summary>
|
|
Redraw,
|
|
}
|
|
|
|
/// <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>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.</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 and stop run one at a time.</item>
|
|
/// <item>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.</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 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());
|
|
}
|
|
|
|
/// <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>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 — 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 <paramref name="ct"/> 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.
|
|
/// </summary>
|
|
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;
|
|
});
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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,
|
|
};
|
|
|
|
/// <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 with an
|
|
/// <see cref="IOException"/> or <see cref="UnauthorizedAccessException"/>; that error is thrown afterwards. A failed
|
|
/// start throws its own error and, like a failed <see cref="StartAsync"/>, leaves nothing open. Once begun it goes
|
|
/// to the end whatever <paramref name="ct"/> says (the profile with the Instagram session must go, and the engine
|
|
/// starts again after it); stopping waits for it at most <see cref="StopWait"/>.
|
|
/// </summary>
|
|
public Task RestartAsync(Func<Task>? 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);
|
|
}
|
|
|
|
/// <summary>True while a WebView is in the window and attached to the session (its browser process did not die).</summary>
|
|
private bool IsRunning => _controller is not null && _session.IsAttached;
|
|
|
|
/// <summary>
|
|
/// UI thread, one at a time (<see cref="ExclusiveAsync"/>): 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.
|
|
/// </summary>
|
|
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 <select>, menus, suggestions)
|
|
// would open where the window was, out of view.
|
|
window.LocationChanged += (_, _) => NotifyPositionChanged();
|
|
window.ShowAddress(null);
|
|
_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;
|
|
controller.ZoomFactor = _window.Fit;
|
|
|
|
// 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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;
|
|
}
|
|
|
|
switch (ResponseTo(kind, UserIsDriving))
|
|
{
|
|
case ProcessFailureResponse.Restart:
|
|
// 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);
|
|
break;
|
|
case ProcessFailureResponse.Rest:
|
|
// 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.
|
|
}
|
|
|
|
break;
|
|
case ProcessFailureResponse.Redraw:
|
|
// A windowed WebView can stay blank or black after the GPU process restarted until its size changes: the
|
|
// same bounds again may be no change at all, so one pixel less and then the real ones (never
|
|
// IsVisible = false, S2), once this handler has returned.
|
|
_ = _ui.InvokeAsync(Redraw, DispatcherPriority.Background);
|
|
break;
|
|
default:
|
|
if (kind == CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
|
|
{
|
|
_log.Info("browser", "WebView2: la pagina non risponde mentre usi il browser; Febe la lascia com'è (Ricarica, se non si riprende).");
|
|
}
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
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 the window (or left it minimised too long): done, out of view.</summary>
|
|
private void Done()
|
|
{
|
|
_window?.MoveOffScreen();
|
|
ReleaseLease();
|
|
NotifyPositionChanged();
|
|
}
|
|
|
|
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 (_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.
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// «Pagina iniziale»: Alberto's own navigation (rule 7), done by the connection, which first waits for the engine's
|
|
/// session to end and takes the page's turn (issue #52).
|
|
/// </summary>
|
|
private void OpenStartPage()
|
|
{
|
|
if (_settings.OpenStartPage is not { } open || _core is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
TakeLease();
|
|
|
|
// The press lasts as long as this lease: closed meanwhile, the window gives the page back to the engine and the
|
|
// connection forgets the press (rules 7 and 8).
|
|
_ = OpenStartPageQuietlyAsync(open, _leaseEnded!.Token);
|
|
}
|
|
|
|
private async Task OpenStartPageQuietlyAsync(Func<CancellationToken, Task> open, CancellationToken whileLeased)
|
|
{
|
|
try
|
|
{
|
|
await open(whileLeased).ConfigureAwait(true);
|
|
}
|
|
catch (OperationCanceledException) when (whileLeased.IsCancellationRequested)
|
|
{
|
|
// The window went out of view before the start page could open: nothing to say.
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
|
{
|
|
_log.Warn("browser", $"«Pagina iniziale» non aperta ({ex.GetType().Name}).");
|
|
}
|
|
}
|
|
|
|
/// <summary>After a GPU restart: a real change of size (one pixel less), then the real bounds and a repaint.</summary>
|
|
private void Redraw()
|
|
{
|
|
if (_controller is not { } controller || _window is not { } window)
|
|
{
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
var bounds = window.PageBounds;
|
|
if (bounds.Height > 1)
|
|
{
|
|
controller.Bounds = bounds with { Height = bounds.Height - 1 };
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
|
{
|
|
// The browser process is gone: the next start sizes the new WebView.
|
|
return;
|
|
}
|
|
|
|
_ = _ui.InvokeAsync(
|
|
() =>
|
|
{
|
|
UpdateBounds();
|
|
Repaint();
|
|
},
|
|
DispatcherPriority.Background);
|
|
}
|
|
|
|
/// <summary>Asks the window and WebView2's child windows to paint again; nothing the page can see changes.</summary>
|
|
private void Repaint()
|
|
{
|
|
if (_window is { } window)
|
|
{
|
|
// Only invalidated, never painted at once (RDW_UPDATENOW): the children belong to WebView2's browser process,
|
|
// and a hung one would hold the UI thread in a synchronous paint.
|
|
Win32.RedrawWindow(window.Handle, IntPtr.Zero, IntPtr.Zero, Win32.RdwInvalidate | Win32.RdwAllChildren);
|
|
}
|
|
}
|
|
|
|
private void UpdateBounds()
|
|
{
|
|
if (_controller is not { } controller || _window is not { } window)
|
|
{
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
controller.Bounds = window.PageBounds;
|
|
|
|
// Shrunk to fit a small screen, the page is zoomed out by as much: its size in CSS pixels stays the same.
|
|
controller.ZoomFactor = window.Fit;
|
|
controller.NotifyParentWindowPositionChanged();
|
|
}
|
|
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
|
{
|
|
// The browser process is gone: the next start sizes the new WebView.
|
|
}
|
|
}
|
|
|
|
private void NotifyPositionChanged()
|
|
{
|
|
try
|
|
{
|
|
_controller?.NotifyParentWindowPositionChanged();
|
|
}
|
|
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
|
{
|
|
// The browser process is gone: the next start places the new WebView.
|
|
}
|
|
}
|
|
|
|
private void TakeLease()
|
|
{
|
|
if (_lease is null)
|
|
{
|
|
_lease = UserDriving.Begin();
|
|
_leaseEnded = new CancellationTokenSource();
|
|
_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();
|
|
|
|
// Off the UI thread: whatever waited on this lease (a «Pagina iniziale» in progress) gives up there. The source
|
|
// has no timer and is never disposed, so a late look at its token is still safe.
|
|
if (_leaseEnded is { } ended)
|
|
{
|
|
_leaseEnded = null;
|
|
_ = ended.CancelAsync();
|
|
}
|
|
|
|
_log.Info("browser", "Browser di Febe fuori vista.");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Runs one step of the life of the WebView (start, restart, 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>
|
|
/// Waits for <paramref name="work"/> until <paramref name="ct"/> 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.
|
|
/// </summary>
|
|
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;
|
|
}
|
|
}
|
|
|
|
/// <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);
|
|
}
|
|
}
|
|
}
|