M6 Windows: composizione condivisa Febe.App per Server e Desktop; Febe per Windows (WPF) con l'interfaccia in WebView2, area di notifica, istanza unica, «Browser di Febe» su WebView2 con CDP filtrato (WebView2CdpSession) e ripieghi di S2 (composizione, Edge), guscio nativo, avvisi, spostamento verificato della cartella dei dati, icona del marchio; un solo Febe.exe, installatore NSIS e zip portabile; guida docs/windows.md e prove dal vivo S1–S3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
73 files changed
+7914
-699
No files matched your search
@@ -0,0 +1,171 @@
|
||||
using System.ComponentModel;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace Febe.Desktop.Browser;
|
||||
|
||||
/// <summary>
|
||||
/// The window «Browser di Febe» (spec §4.1, §12): the page of Instagram at a fixed size, always the same, and below it a
|
||||
/// thin bar with «Indietro», «Ricarica» and the address without its query string. WebView2 draws into the upper area
|
||||
/// (as a child window, or as a DirectComposition visual for S2). When Alberto does not use it the window stays open
|
||||
/// but out of view, never hidden nor minimised: WebView2 would stop painting (S2). Closing it only puts it out of view.
|
||||
/// </summary>
|
||||
internal sealed class BrowserWindow : Window
|
||||
{
|
||||
/// <summary>Height of the bar under the page, in device-independent pixels.</summary>
|
||||
public const double BarHeight = 40;
|
||||
|
||||
private readonly TextBlock _address;
|
||||
private bool _allowClose;
|
||||
|
||||
public BrowserWindow(int pageWidth, int pageHeight, ImageSource? icon)
|
||||
{
|
||||
PageWidth = pageWidth;
|
||||
PageHeight = pageHeight;
|
||||
Title = "Browser di Febe";
|
||||
Icon = icon;
|
||||
ResizeMode = ResizeMode.CanMinimize;
|
||||
SizeToContent = SizeToContent.WidthAndHeight;
|
||||
WindowStartupLocation = WindowStartupLocation.Manual;
|
||||
ShowActivated = false;
|
||||
|
||||
// No taskbar button: out of view the window must not be reachable by accident (a click on a button that shows
|
||||
// nothing). It comes to the front from the interface: «Apri il browser», «Portalo in primo piano», the login.
|
||||
ShowInTaskbar = false;
|
||||
Background = new SolidColorBrush(Color.FromRgb(0xF4, 0xF5, 0xF7));
|
||||
|
||||
var back = BarButton("Indietro", "Torna alla pagina precedente");
|
||||
back.Click += (_, _) => BackRequested?.Invoke(this, EventArgs.Empty);
|
||||
var reload = BarButton("Ricarica", "Ricarica la pagina");
|
||||
reload.Click += (_, _) => ReloadRequested?.Invoke(this, EventArgs.Empty);
|
||||
_address = new TextBlock
|
||||
{
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Margin = new Thickness(12, 0, 12, 0),
|
||||
TextTrimming = TextTrimming.CharacterEllipsis,
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(0x2A, 0x2F, 0x36)),
|
||||
FontFamily = new FontFamily("Segoe UI"),
|
||||
FontSize = 13,
|
||||
};
|
||||
var hint = new TextBlock
|
||||
{
|
||||
Text = "Chiudi questa finestra quando hai finito: Febe la tiene aperta fuori vista.",
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Margin = new Thickness(0, 0, 12, 0),
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(0x5B, 0x63, 0x6E)),
|
||||
FontFamily = new FontFamily("Segoe UI"),
|
||||
FontSize = 12,
|
||||
};
|
||||
|
||||
var bar = new DockPanel { Height = BarHeight, LastChildFill = true, Background = new SolidColorBrush(Color.FromRgb(0xFF, 0xFF, 0xFF)) };
|
||||
DockPanel.SetDock(back, Dock.Left);
|
||||
DockPanel.SetDock(reload, Dock.Left);
|
||||
DockPanel.SetDock(hint, Dock.Right);
|
||||
bar.Children.Add(back);
|
||||
bar.Children.Add(reload);
|
||||
bar.Children.Add(hint);
|
||||
bar.Children.Add(_address);
|
||||
|
||||
// The page area: WebView2 covers it (its bounds are computed from PageWidth/PageHeight and the DPI).
|
||||
var page = new Border { Width = pageWidth, Height = pageHeight, Background = Brushes.White };
|
||||
var layout = new DockPanel { LastChildFill = true };
|
||||
DockPanel.SetDock(bar, Dock.Bottom);
|
||||
layout.Children.Add(bar);
|
||||
layout.Children.Add(page);
|
||||
Content = layout;
|
||||
}
|
||||
|
||||
/// <summary>Width of the page in device-independent pixels (CSS pixels of the page at zoom 100%).</summary>
|
||||
public int PageWidth { get; }
|
||||
|
||||
public int PageHeight { get; }
|
||||
|
||||
/// <summary>Raised by «Indietro».</summary>
|
||||
public event EventHandler? BackRequested;
|
||||
|
||||
/// <summary>Raised by «Ricarica».</summary>
|
||||
public event EventHandler? ReloadRequested;
|
||||
|
||||
/// <summary>Raised when Alberto closes or minimises the window: the owner puts it out of view.</summary>
|
||||
public event EventHandler? DoneRequested;
|
||||
|
||||
/// <summary>The window handle (created on first use).</summary>
|
||||
public IntPtr Handle => new WindowInteropHelper(this).EnsureHandle();
|
||||
|
||||
/// <summary>The scale of the monitor the window is on (1 at 96 DPI).</summary>
|
||||
public double Scale => VisualTreeHelper.GetDpi(this).DpiScaleX;
|
||||
|
||||
/// <summary>Where WebView2 draws, in physical pixels of the client area.</summary>
|
||||
public System.Drawing.Rectangle PageBounds => new(0, 0, (int)Math.Round(PageWidth * Scale), (int)Math.Round(PageHeight * Scale));
|
||||
|
||||
/// <summary>True while the window is on a screen, false while it is parked out of view.</summary>
|
||||
public bool IsOnScreen =>
|
||||
Left < SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth
|
||||
&& Left + ActualWidth > SystemParameters.VirtualScreenLeft;
|
||||
|
||||
/// <summary>Shows the address of the page, without query string or fragment (they may carry tokens).</summary>
|
||||
public void ShowAddress(string? address) => _address.Text = address ?? string.Empty;
|
||||
|
||||
/// <summary>Centres the window on the work area of the primary screen.</summary>
|
||||
public void MoveOnScreen()
|
||||
{
|
||||
var area = SystemParameters.WorkArea;
|
||||
var width = ActualWidth > 0 ? ActualWidth : PageWidth;
|
||||
var height = ActualHeight > 0 ? ActualHeight : PageHeight + BarHeight;
|
||||
Left = area.Left + Math.Max(0, (area.Width - width) / 2);
|
||||
Top = area.Top + Math.Max(0, (area.Height - height) / 2);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parks the window just right of every screen: open, «visible» for Windows and for WebView2, out of Alberto's view
|
||||
/// (S2). Never <c>Hide()</c> and never minimised.
|
||||
/// </summary>
|
||||
public void MoveOffScreen()
|
||||
{
|
||||
Left = SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth + 64;
|
||||
Top = SystemParameters.VirtualScreenTop;
|
||||
}
|
||||
|
||||
/// <summary>Lets the window really close (Febe is stopping).</summary>
|
||||
public void CloseForGood()
|
||||
{
|
||||
_allowClose = true;
|
||||
Close();
|
||||
}
|
||||
|
||||
protected override void OnClosing(CancelEventArgs e)
|
||||
{
|
||||
if (!_allowClose)
|
||||
{
|
||||
// The browser stays open: closing the window means «ho finito», it goes out of view.
|
||||
e.Cancel = true;
|
||||
DoneRequested?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
base.OnClosing(e);
|
||||
}
|
||||
|
||||
protected override void OnStateChanged(EventArgs e)
|
||||
{
|
||||
if (WindowState == WindowState.Minimized)
|
||||
{
|
||||
// A minimised window stops painting (S2): back to normal, out of view.
|
||||
WindowState = WindowState.Normal;
|
||||
DoneRequested?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
base.OnStateChanged(e);
|
||||
}
|
||||
|
||||
private static Button BarButton(string text, string tip) => new()
|
||||
{
|
||||
Content = text,
|
||||
ToolTip = tip,
|
||||
Margin = new Thickness(8, 6, 0, 6),
|
||||
Padding = new Thickness(12, 0, 12, 0),
|
||||
FontFamily = new FontFamily("Segoe UI"),
|
||||
FontSize = 13,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Interop;
|
||||
using Febe.Desktop.Native;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
|
||||
namespace Febe.Desktop.Browser;
|
||||
|
||||
/// <summary>
|
||||
/// The second attempt of S2 (spec §6.6, «composizione»): WebView2 hosted as a DirectComposition visual of the window
|
||||
/// «Browser di Febe» instead of a child window. The window owns the visual tree (a topmost target with one visual,
|
||||
/// the WebView at its origin over the page area); WebView2 gets no window of its own to be occluded or hidden, but
|
||||
/// then the host forwards the mouse (<c>SendMouseInput</c>) and the cursor. The keyboard reaches the page through the
|
||||
/// focus WebView2 keeps (<c>MoveFocus</c>). The bar of the window stays below the page and keeps its own input.
|
||||
/// </summary>
|
||||
/// <remarks>To be tested on Windows (docs/windows.md, S2): it cannot run here.</remarks>
|
||||
internal sealed class CompositionHost : IDisposable
|
||||
{
|
||||
private readonly IntPtr _window;
|
||||
private readonly Func<System.Drawing.Rectangle> _page;
|
||||
private readonly IDCompositionDevice _device;
|
||||
private readonly IDCompositionTarget _target;
|
||||
private readonly IDCompositionVisual _visual;
|
||||
private HwndSource? _source;
|
||||
private CoreWebView2CompositionController? _controller;
|
||||
private bool _tracking;
|
||||
private bool _captured;
|
||||
|
||||
public CompositionHost(IntPtr window, Func<System.Drawing.Rectangle> pageBounds)
|
||||
{
|
||||
_window = window;
|
||||
_page = pageBounds ?? throw new ArgumentNullException(nameof(pageBounds));
|
||||
var iid = typeof(IDCompositionDevice).GUID;
|
||||
Marshal.ThrowExceptionForHR(Win32.DCompositionCreateDevice2(IntPtr.Zero, ref iid, out var device));
|
||||
_device = (IDCompositionDevice)device;
|
||||
_target = _device.CreateTargetForHwnd(window, topmost: true);
|
||||
_visual = _device.CreateVisual();
|
||||
_target.SetRoot(_visual);
|
||||
_device.Commit();
|
||||
}
|
||||
|
||||
/// <summary>Gives the visual to WebView2 and starts forwarding the mouse of the page area.</summary>
|
||||
public void Attach(CoreWebView2CompositionController controller)
|
||||
{
|
||||
_controller = controller ?? throw new ArgumentNullException(nameof(controller));
|
||||
controller.RootVisualTarget = _visual;
|
||||
_device.Commit();
|
||||
_source = HwndSource.FromHwnd(_window);
|
||||
_source?.AddHook(Hook);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_source?.RemoveHook(Hook);
|
||||
_source = null;
|
||||
if (_controller is { } controller)
|
||||
{
|
||||
try
|
||||
{
|
||||
controller.RootVisualTarget = null;
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or COMException)
|
||||
{
|
||||
// The WebView is already closed.
|
||||
}
|
||||
}
|
||||
|
||||
_controller = null;
|
||||
Marshal.ReleaseComObject(_visual);
|
||||
Marshal.ReleaseComObject(_target);
|
||||
Marshal.ReleaseComObject(_device);
|
||||
}
|
||||
|
||||
private IntPtr Hook(IntPtr window, int message, IntPtr wParam, IntPtr lParam, ref bool handled)
|
||||
{
|
||||
if (_controller is not { } controller)
|
||||
{
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
if (message == Win32.WmSetCursor)
|
||||
{
|
||||
if (Win32.LowWord(lParam) == Win32.HtClient && CursorInPage(window, out _))
|
||||
{
|
||||
Win32.SetCursor(controller.Cursor);
|
||||
handled = true;
|
||||
return new IntPtr(1);
|
||||
}
|
||||
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
var isMouse = message is >= Win32.WmMouseFirst and <= Win32.WmMouseHWheel || message == Win32.WmMouseLeave;
|
||||
if (!isMouse)
|
||||
{
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
var point = new Win32.Point { X = Win32.LowWord(lParam), Y = Win32.HighWord(lParam) };
|
||||
if (message is Win32.WmMouseWheel or Win32.WmMouseHWheel)
|
||||
{
|
||||
// Wheel messages carry screen coordinates.
|
||||
Win32.ScreenToClient(window, ref point);
|
||||
}
|
||||
|
||||
var page = _page();
|
||||
var inside = point.X >= page.Left && point.X < page.Right && point.Y >= page.Top && point.Y < page.Bottom;
|
||||
if (message != Win32.WmMouseLeave && !inside && !_captured)
|
||||
{
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
var kind = (CoreWebView2MouseEventKind)message;
|
||||
var keys = message == Win32.WmMouseLeave ? CoreWebView2MouseEventVirtualKeys.None : (CoreWebView2MouseEventVirtualKeys)(Win32.LowWord(wParam) & 0xFFFF);
|
||||
uint data = message switch
|
||||
{
|
||||
Win32.WmMouseWheel or Win32.WmMouseHWheel => unchecked((uint)Win32.HighWord(wParam)),
|
||||
0x020B or 0x020C or 0x020D => unchecked((uint)Win32.HighWord(wParam)), // X buttons: which one
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
switch (message)
|
||||
{
|
||||
case 0x0201 or 0x0204 or 0x0207 or 0x020B:
|
||||
Win32.SetCapture(window);
|
||||
_captured = true;
|
||||
break;
|
||||
case 0x0202 or 0x0205 or 0x0208 or 0x020C:
|
||||
Win32.ReleaseCapture();
|
||||
_captured = false;
|
||||
break;
|
||||
case Win32.WmMouseLeave:
|
||||
_tracking = false;
|
||||
break;
|
||||
}
|
||||
|
||||
if (message == Win32.WmMouseFirst && !_tracking)
|
||||
{
|
||||
var track = new Win32.TrackMouseEventInfo
|
||||
{
|
||||
Size = (uint)Marshal.SizeOf<Win32.TrackMouseEventInfo>(),
|
||||
Flags = Win32.TmeLeave,
|
||||
Window = window,
|
||||
};
|
||||
_tracking = Win32.TrackMouseEvent(ref track);
|
||||
}
|
||||
|
||||
controller.SendMouseInput(kind, keys, data, new System.Drawing.Point(point.X - page.Left, point.Y - page.Top));
|
||||
handled = true;
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
private bool CursorInPage(IntPtr window, out Win32.Point point)
|
||||
{
|
||||
point = default;
|
||||
if (!GetCursorPos(out var screen))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
point = screen;
|
||||
Win32.ScreenToClient(window, ref point);
|
||||
var page = _page();
|
||||
return point.X >= page.Left && point.X < page.Right && point.Y >= page.Top && point.Y < page.Bottom;
|
||||
}
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool GetCursorPos(out Win32.Point point);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using System.Windows.Threading;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.WebView2;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
|
||||
namespace Febe.Desktop.Browser;
|
||||
|
||||
/// <summary>
|
||||
/// The two WebView2 calls of <see cref="IWebView2DevTools"/> on a <see cref="CoreWebView2"/> (spec §6.1, Windows):
|
||||
/// <c>CallDevToolsProtocolMethodAsync</c> and <c>GetDevToolsProtocolEventReceiver</c>. WebView2 objects live on the UI
|
||||
/// thread: every call is queued on its dispatcher (in order), never waited for synchronously, so no thread of the
|
||||
/// engine can block the window. Allowlist, guard, JSON and logging are in <see cref="WebView2CdpSession"/>.
|
||||
/// </summary>
|
||||
internal sealed class CoreWebView2DevTools(Dispatcher ui, CoreWebView2 core) : IWebView2DevTools
|
||||
{
|
||||
private volatile bool _closed;
|
||||
|
||||
/// <summary>The WebView is closing: calls fail with <see cref="CdpDisconnectedException"/> from now on.</summary>
|
||||
public void Close() => _closed = true;
|
||||
|
||||
public Task<string> CallMethodAsync(string methodName, string parametersAsJson)
|
||||
{
|
||||
if (_closed)
|
||||
{
|
||||
return Task.FromException<string>(new CdpDisconnectedException("Il browser di Febe si sta chiudendo."));
|
||||
}
|
||||
|
||||
return ui.InvokeAsync(() =>
|
||||
{
|
||||
if (_closed)
|
||||
{
|
||||
throw new CdpDisconnectedException("Il browser di Febe si sta chiudendo.");
|
||||
}
|
||||
|
||||
return core.CallDevToolsProtocolMethodAsync(methodName, parametersAsJson);
|
||||
}).Task.Unwrap();
|
||||
}
|
||||
|
||||
public IDisposable Subscribe(string eventName, Action<string> onEvent)
|
||||
{
|
||||
CoreWebView2DevToolsProtocolEventReceiver? receiver = null;
|
||||
void Handler(object? sender, CoreWebView2DevToolsProtocolEventReceivedEventArgs e) => onEvent(e.ParameterObjectAsJson);
|
||||
|
||||
// Queued, not waited for: the session may call this while holding its lock.
|
||||
ui.InvokeAsync(() =>
|
||||
{
|
||||
if (_closed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
receiver = core.GetDevToolsProtocolEventReceiver(eventName);
|
||||
receiver.DevToolsProtocolEventReceived += Handler;
|
||||
});
|
||||
|
||||
return new Removal(() => ui.InvokeAsync(() =>
|
||||
{
|
||||
if (receiver is not null && !_closed)
|
||||
{
|
||||
receiver.DevToolsProtocolEventReceived -= Handler;
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private sealed class Removal(Action remove) : IDisposable
|
||||
{
|
||||
private Action? _remove = remove;
|
||||
|
||||
public void Dispose() => Interlocked.Exchange(ref _remove, null)?.Invoke();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using System.Globalization;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using Febe.App;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Desktop.Core;
|
||||
|
||||
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.
|
||||
/// </summary>
|
||||
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)];
|
||||
|
||||
private readonly WebView2BrowserSettings _settings;
|
||||
private readonly FebePlatformContext _context;
|
||||
private readonly IClock _wallClock;
|
||||
private readonly BrowserOptions _options;
|
||||
private volatile bool _started;
|
||||
private volatile string? _lastError;
|
||||
|
||||
public WebView2Browser(Dispatcher ui, WebView2BrowserSettings settings, FebePlatformContext context, ImageSource? icon)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ui);
|
||||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||||
_context = context ?? throw new ArgumentNullException(nameof(context));
|
||||
|
||||
// Starts and retries in wall-clock time, whatever clock the engine runs on.
|
||||
_wallClock = new SystemClock(context.Clock.LocalZone);
|
||||
ProfileDirectory = Path.GetFullPath(settings.ProfileDirectory);
|
||||
_options = new BrowserOptions(ProfileDirectory, settings.Width, settings.Height);
|
||||
Host = new WebView2Host(
|
||||
ui,
|
||||
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now)),
|
||||
context.Log);
|
||||
Host.BrowserProcessFailed += (_, _) => _ = RecoverAsync();
|
||||
}
|
||||
|
||||
/// <summary>The host: window «Browser di Febe», WebView2, CDP.</summary>
|
||||
public WebView2Host Host { get; }
|
||||
|
||||
public ICdpSession Cdp => Host.Cdp;
|
||||
|
||||
public UserDrivingGate UserDriving => Host.UserDriving;
|
||||
|
||||
public bool UserIsDriving => Host.UserIsDriving;
|
||||
|
||||
public bool IsAvailable => _started && Host.IsAttached;
|
||||
|
||||
public string? LastError => _lastError;
|
||||
|
||||
public string ProfileDirectory { get; }
|
||||
|
||||
public int WindowWidth => _settings.Width;
|
||||
|
||||
public int WindowHeight => _settings.Height;
|
||||
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
for (var attempt = 0; !ct.IsCancellationRequested; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Host.StartAsync(_options, ct).ConfigureAwait(false);
|
||||
_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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Task<NavigationResult> RestAsync(CancellationToken ct) => Host.Cdp.RestAsync(ct);
|
||||
|
||||
public Task ShowToUserAsync(CancellationToken ct) => Host.ShowToUserAsync();
|
||||
|
||||
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>
|
||||
public async Task RestartWithEmptyProfileAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
_context.Log.Info("browser", "Profilo del browser cancellato; il browser è ripartito 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()
|
||||
{
|
||||
try
|
||||
{
|
||||
await Host.RestartAsync(null, CancellationToken.None).ConfigureAwait(false);
|
||||
_context.Log.Info("browser", "Browser di Febe ripartito dopo l'arresto del suo processo.");
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_started = false;
|
||||
_lastError = $"WebView2 non riparte ({ex.GetType().Name}).";
|
||||
_context.Log.Error("browser", _lastError);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Deletes the profile; a process of WebView2 may still hold a file for a moment.</summary>
|
||||
private async Task DeleteProfileAsync()
|
||||
{
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(ProfileDirectory))
|
||||
{
|
||||
Directory.Delete(ProfileDirectory, recursive: true);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when ((ex is IOException or UnauthorizedAccessException) && attempt < 10)
|
||||
{
|
||||
await Task.Delay(500).ConfigureAwait(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string FirstLine(string text)
|
||||
{
|
||||
var line = text.Split('\n')[0].Trim();
|
||||
return line.Length > 200 ? line[..200] : line;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
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;
|
||||
|
||||
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 in use (for the log).</summary>
|
||||
public string? Version => _environment?.BrowserVersionString;
|
||||
|
||||
/// <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;
|
||||
|
||||
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();
|
||||
}
|
||||
Reference in new issue
Block a user