Files
Febe/src/Febe.Desktop/MainWindow.cs
T
Alby96andClaude Opus 5.5 2ef098226b Finestra di Febe: gli indirizzi esterni si aprono dopo il gestore di WebView2
La finestra dell'interfaccia apriva gli indirizzi esterni (guida, repository, «Apri su
Instagram») nel browser predefinito dentro i gestori NavigationStarting e NewWindowRequested
di WebView2. L'apertura passa dalla shell di Windows, che può far girare un ciclo di messaggi
suo, e WebView2 non regge di essere richiamato dentro i propri gestori (modello dei thread di
WebView2). Ora l'apertura si mette in coda sul thread dell'interfaccia e parte quando il
gestore è tornato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:30:20 +02:00

152 lines
5.2 KiB
C#

using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
namespace Febe.Desktop;
/// <summary>
/// The main window (spec §12): a WebView2 showing the interface served in this process on 127.0.0.1. It opens
/// <c>/?gettone=…</c> once — the token of this start becomes an HttpOnly cookie and leaves the address — and never
/// leaves the interface: any other address opens in Alberto's default browser. Its WebView2 has a user data folder of
/// its own (<c>Dati\interfaccia</c>), separate from the browser of Instagram.
/// </summary>
internal sealed class MainWindow : Window
{
private readonly WebView2 _view;
private readonly Uri _origin;
private readonly Func<Uri, Task> _openOutside;
private bool _allowClose;
public MainWindow(ImageSource? icon, string userDataFolder, Uri origin, bool developerTools, Func<Uri, Task> openOutside)
{
_origin = origin ?? throw new ArgumentNullException(nameof(origin));
_openOutside = openOutside ?? throw new ArgumentNullException(nameof(openOutside));
Title = "Febe";
Icon = icon;
var area = SystemParameters.WorkArea;
Width = Math.Min(1440, area.Width * 0.92);
Height = Math.Min(900, area.Height * 0.92);
MinWidth = 380;
MinHeight = 480;
WindowStartupLocation = WindowStartupLocation.CenterScreen;
Background = new SolidColorBrush(Color.FromRgb(0xF4, 0xF5, 0xF7));
_view = new WebView2
{
CreationProperties = new CoreWebView2CreationProperties { UserDataFolder = userDataFolder },
};
Content = _view;
DeveloperTools = developerTools;
}
/// <summary>The developer tools of the interface (only with <c>--sviluppo</c>).</summary>
public bool DeveloperTools { get; }
/// <summary>Raised when Alberto closes the window; the application decides (notification area or exit).</summary>
public event EventHandler? CloseRequested;
/// <summary>Creates the WebView and opens the interface at <paramref name="first"/> (the address with the token).</summary>
public async Task OpenAsync(Uri first)
{
await _view.EnsureCoreWebView2Async().ConfigureAwait(true);
var core = _view.CoreWebView2;
var s = core.Settings;
s.AreDevToolsEnabled = DeveloperTools;
s.IsPasswordAutosaveEnabled = false;
s.IsGeneralAutofillEnabled = false;
s.IsStatusBarEnabled = false;
core.NavigationStarting += OnNavigationStarting;
core.NewWindowRequested += OnNewWindowRequested;
core.ProcessFailed += (_, e) =>
{
if (e.ProcessFailedKind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
{
core.Reload();
}
};
core.Navigate(first.AbsoluteUri);
}
/// <summary>Shows the window in front, restoring it if minimised.</summary>
public void Present()
{
if (!IsVisible)
{
Show();
}
if (WindowState == WindowState.Minimized)
{
WindowState = WindowState.Normal;
}
Activate();
Topmost = true;
Topmost = false;
_view.Focus();
}
/// <summary>Closes the window for good (Febe is stopping).</summary>
public void CloseForGood()
{
_allowClose = true;
Close();
_view.Dispose();
}
protected override void OnClosing(CancelEventArgs e)
{
if (!_allowClose)
{
e.Cancel = true;
CloseRequested?.Invoke(this, EventArgs.Empty);
}
base.OnClosing(e);
}
private bool IsInterface(Uri uri) =>
uri.Scheme == _origin.Scheme && string.Equals(uri.Authority, _origin.Authority, StringComparison.OrdinalIgnoreCase);
private void OnNavigationStarting(object? sender, CoreWebView2NavigationStartingEventArgs e)
{
if (!Uri.TryCreate(e.Uri, UriKind.Absolute, out var uri) || IsInterface(uri) || uri.Scheme is "about" or "data")
{
return;
}
// The window shows only Febe: the guide, the repository, Instagram links open in Alberto's own browser.
e.Cancel = true;
if (uri.Scheme is "http" or "https")
{
OpenOutsideLater(uri);
}
}
private void OnNewWindowRequested(object? sender, CoreWebView2NewWindowRequestedEventArgs e)
{
e.Handled = true;
if (!Uri.TryCreate(e.Uri, UriKind.Absolute, out var uri))
{
return;
}
if (IsInterface(uri))
{
_view.CoreWebView2.Navigate(uri.AbsoluteUri);
}
else if (uri.Scheme is "http" or "https")
{
OpenOutsideLater(uri);
}
}
/// <summary>
/// Opens <paramref name="uri"/> in Alberto's browser once the handler of WebView2's event has returned: the shell
/// may run a message loop of its own, and WebView2 does not support re-entering its handlers (threading model).
/// </summary>
private void OpenOutsideLater(Uri uri) => Dispatcher.InvokeAsync(() => _openOutside(uri), DispatcherPriority.Background);
}