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:
Claude committed 2026-10-13 21:50:25 +00:00
1 parent dc4d1fc738
commit b443adfa8b
73 files changed
+7914 -699

No files matched your search

-4
View File
@@ -1,4 +0,0 @@
<Application x:Class="Febe.Desktop.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</Application>
-6
View File
@@ -1,6 +0,0 @@
namespace Febe.Desktop;
/// <summary>Windows shell. Filled in by milestone M6.</summary>
public partial class App : System.Windows.Application
{
}
+171
View File
@@ -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,
};
}
+169
View File
@@ -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();
}
}
+163
View File
@@ -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;
}
}
+372
View File
@@ -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();
}
+376
View File
@@ -0,0 +1,376 @@
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Febe.App;
using Febe.Core.Abstractions;
using Febe.Core.Storage;
using Febe.Desktop.Core;
using Febe.Web.Library;
namespace Febe.Desktop;
/// <summary>
/// Febe for Windows (spec §5, §12): the shared composition <see cref="FebeApp"/> with the <see cref="DesktopPlatform"/>,
/// the main window on the interface, the icon in the notification area, the window «Browser di Febe». Closing the main
/// window keeps Febe working in the notification area (setting «Chiudendo la finestra, Febe resta attivo…», on by
/// default); «Esci» stops everything in order, the browser of Instagram last but one, so its session is on disk.
/// </summary>
internal sealed class DesktopApplication : Application
{
private const string TrayNoticeKey = "desktop.avviso-area-di-notifica";
private readonly DesktopOptions _options;
private readonly DesktopFolders _folders;
private readonly IDataFolderLocationStore _locations;
private readonly bool _dataFolderFixed;
private readonly SingleInstanceGuard _instance;
private readonly CancellationTokenSource _lifetime = new();
private string _dataFolder;
private ImageSource? _iconImage;
private TrayIcon? _tray;
private DesktopPlatform? _platform;
private FebeApp? _app;
private MainWindow? _main;
private Task? _opening;
private bool _exiting;
public DesktopApplication(DesktopOptions options, DesktopFolders folders, IDataFolderLocationStore locations, string dataFolder, bool dataFolderFixed, SingleInstanceGuard instance)
{
_options = options;
_folders = folders;
_locations = locations;
_dataFolder = dataFolder;
_dataFolderFixed = dataFolderFixed;
_instance = instance;
ShutdownMode = ShutdownMode.OnExplicitShutdown;
DispatcherUnhandledException += OnDispatcherUnhandledException;
TaskScheduler.UnobservedTaskException += (_, e) => e.SetObserved();
SessionEnding += OnSessionEnding;
}
protected override async void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
try
{
await StartAsync().ConfigureAwait(true);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_app?.Log.Error("avvio", "Febe non è partito.", ex);
MessageBox.Show(
$"Febe non è riuscito a partire: {ex.Message}\n\nControlla il registro nella cartella dei dati ({Path.Combine(_dataFolder, "registro")}) e riprova.",
"Febe",
MessageBoxButton.OK,
MessageBoxImage.Error);
await ExitAsync().ConfigureAwait(true);
}
}
private async Task StartAsync()
{
var icon = LoadIcon();
_iconImage = LoadIconImage();
_tray = new TrayIcon(icon, NeedsResume);
_tray.OpenRequested += (_, _) => ShowMain();
_tray.PauseToggleRequested += (_, resume) => _ = TogglePauseAsync(resume);
_tray.ExitRequested += (_, _) => _ = ExitAsync();
// A move of the Data folder asked in Impostazioni happens now, before anything opens the folder.
DataFolderMoveResult? moved = null;
if (!_dataFolderFixed && _locations.Pending is not null)
{
moved = await MoveDataFolderAsync().ConfigureAwait(true);
_dataFolder = moved.DataFolder;
if (moved.Message is { } message)
{
_tray.Notify("Cartella dei dati", message, moved.Outcome != DataFolderMoveOutcome.Moved);
}
}
var native = new WindowsShell(Dispatcher, () => _main, () => _tray);
var shell = new DesktopShell(Dispatcher, _iconImage, native, new WindowsNotificationChannel(Dispatcher, () => _tray));
_platform = new DesktopPlatform(_options, shell, _locations, _dataFolderFixed);
_app = await FebeApp.StartAsync(_options.AppOptions(_dataFolder, _folders), _platform, new FebeAppHooks(), _lifetime.Token).ConfigureAwait(true);
if (moved?.Message is { } outcome)
{
if (moved.Outcome == DataFolderMoveOutcome.Moved)
{
_app.Log.Info("dati", outcome);
}
else
{
_app.Log.Warn("dati", outcome);
}
}
if (_app.Problems.FirstOrDefault(p => p.Code == DesktopStartupChecks.WebView2Missing) is { } missing)
{
// Without WebView2 not even the error page can be shown: a dialog of Windows says it.
var answer = MessageBox.Show(
$"{missing.Title}.\n\n{missing.Message}\n\n{missing.Remedy}\n\nVuoi aprire adesso la pagina di Microsoft?",
"Febe",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (answer == MessageBoxResult.Yes)
{
await native.OpenUrlAsync(new Uri(DesktopStartupChecks.WebView2DownloadPage), CancellationToken.None).ConfigureAwait(true);
}
await ExitAsync().ConfigureAwait(true);
return;
}
_instance.Listen(request => Dispatcher.InvokeAsync(() =>
{
if (request == InstanceRequest.Show)
{
ShowMain();
}
}));
_ = Task.Run(() => FollowEngineAsync(_lifetime.Token));
if (!_options.StartHidden || _app.Problems.Count > 0)
{
ShowMain();
}
}
/// <summary>Opens (the first time) and shows the main window.</summary>
private void ShowMain()
{
if (_exiting || _app is null || _platform is null)
{
return;
}
if (_main is null)
{
// The window keeps its own WebView2 data in Dati\interfaccia; with a problem of the Data folder (on a network
// share, not writable) it cannot go there, and the page that explains the problem must still show.
var interfaceData = _app.Problems.Count == 0
? Path.Combine(_dataFolder, "interfaccia")
: Path.Combine(Path.GetTempPath(), "Febe-interfaccia");
_main = new MainWindow(_iconImage, interfaceData, _app.Address, _options.DeveloperTools, uri => OpenOutside(uri));
_main.CloseRequested += (_, _) => _ = MainClosedAsync();
}
_main.Present();
_opening ??= OpenInterfaceAsync(_main, _platform.FirstAddress(_app.Address));
}
private async Task OpenInterfaceAsync(MainWindow window, Uri first)
{
try
{
await window.OpenAsync(first).ConfigureAwait(true);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_app?.Log.Error("finestra", "L'interfaccia non si è aperta nella finestra.", ex);
_opening = null;
}
}
private Task<bool> OpenOutside(Uri uri) =>
_app?.Web.Services.GetService(typeof(Febe.Web.Native.INativeShell)) is Febe.Web.Native.INativeShell shell
? shell.OpenUrlAsync(uri, CancellationToken.None)
: Task.FromResult(false);
/// <summary>The X of the main window: into the notification area (default), or exit.</summary>
private async Task MainClosedAsync()
{
if (_app is null || _main is null)
{
return;
}
var keep = _app.Problems.Count == 0
&& await _app.Database.Settings.GetBoolAsync(DesktopSettingKeys.KeepInTray, true, CancellationToken.None).ConfigureAwait(true);
if (!keep)
{
await ExitAsync().ConfigureAwait(true);
return;
}
_main.Hide();
if (!await _app.Database.Settings.GetBoolAsync(TrayNoticeKey, false, CancellationToken.None).ConfigureAwait(true))
{
await _app.Database.Settings.SetBoolAsync(TrayNoticeKey, true, CancellationToken.None).ConfigureAwait(true);
_tray?.Notify("Febe continua a lavorare", "Febe resta attivo qui, nell'area di notifica. Per fermarlo: clic destro sull'icona ▸ Esci.");
}
}
/// <summary>«Riprendi» needs Alberto: after a pause, a verification or a disconnection.</summary>
private bool NeedsResume()
{
if (_app?.Engine is not { } engine)
{
return false;
}
return engine.Services.Runtime.IsPaused
|| engine.Services.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected;
}
private async Task TogglePauseAsync(bool resume)
{
if (_app?.Engine is not { } engine || _tray is null)
{
return;
}
try
{
if (!resume)
{
await engine.PauseAsync(CancellationToken.None).ConfigureAwait(true);
_tray.Notify("Febe è in pausa", "Non apre nulla finché non premi «Riprendi».");
return;
}
var breaker = engine.Services.Breaker.State;
if (breaker.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected
&& !(_app.Tracker.LastUsedAt is { } used && used >= (breaker.LastSignal?.At ?? DateTimeOffset.MinValue)))
{
// The same rule as the interface (mockup 11): first the browser, then «Riprendi».
_tray.Notify("Prima il browser", "Instagram ha chiesto una verifica: completala nel browser di Febe (pagina Collegamento), poi premi «Riprendi».", warning: true);
ShowMain();
return;
}
var result = await engine.ResumeAsync(CancellationToken.None).ConfigureAwait(true);
_tray.Notify(result.Resumed ? "Febe riprende" : "Febe non riprende", result.Message, !result.Resumed);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_app.Log.Warn("area-di-notifica", "Comando del menu non riuscito.", ex);
}
}
/// <summary>The tooltip of the icon follows the engine (the line of the sidebar).</summary>
private async Task FollowEngineAsync(CancellationToken ct)
{
if (_app?.Engine is not { } engine)
{
return;
}
try
{
await foreach (var _ in engine.Monitor.SubscribeAsync(ct).ConfigureAwait(false))
{
var snapshot = await engine.Monitor.GetSnapshotAsync(ct).ConfigureAwait(false);
await Dispatcher.InvokeAsync(() => _tray?.SetStatus(snapshot.SidebarLine));
}
}
catch (OperationCanceledException)
{
}
catch (Exception ex) when (ex is InvalidOperationException or TaskCanceledException)
{
}
}
private async Task<DataFolderMoveResult> MoveDataFolderAsync()
{
var text = new TextBlock { Text = "Febe sposta la cartella dei dati: copia ogni file e lo controlla.", Margin = new Thickness(0, 0, 0, 12), TextWrapping = TextWrapping.Wrap };
var bar = new ProgressBar { Height = 16, Minimum = 0, Maximum = 1 };
var window = new Window
{
Title = "Febe",
Icon = _iconImage,
Width = 460,
SizeToContent = SizeToContent.Height,
ResizeMode = ResizeMode.NoResize,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
Content = new StackPanel { Margin = new Thickness(20), Children = { text, bar } },
};
window.Show();
try
{
var progress = new Progress<DataFolderMoveProgress>(p =>
{
bar.Maximum = Math.Max(1, p.FilesTotal);
bar.Value = p.FilesDone;
});
var current = _dataFolder;
return await Task.Run(() => DataFolderMove.ApplyPending(_locations, current, progress)).ConfigureAwait(true);
}
finally
{
window.Close();
}
}
/// <summary>«Esci»: everything stops in order (engine, downloads, browser, database), then the process ends.</summary>
private async Task ExitAsync()
{
if (_exiting)
{
return;
}
_exiting = true;
_main?.Hide();
await StopAsync().ConfigureAwait(true);
Shutdown();
}
private async Task StopAsync()
{
await _lifetime.CancelAsync().ConfigureAwait(true);
if (_app is { } app)
{
_app = null;
await app.DisposeAsync().ConfigureAwait(true);
}
_main?.CloseForGood();
_main = null;
_tray?.Dispose();
_tray = null;
}
/// <summary>Windows is shutting down or Alberto logs off: stop in order while the messages still flow (S3).</summary>
private void OnSessionEnding(object sender, SessionEndingCancelEventArgs e)
{
if (_exiting)
{
return;
}
_exiting = true;
var stop = StopAsync();
var frame = new DispatcherFrame();
_ = stop.ContinueWith(_ => frame.Continue = false, TaskScheduler.Default);
var timer = new DispatcherTimer(TimeSpan.FromSeconds(20), DispatcherPriority.Send, (_, _) => frame.Continue = false, Dispatcher);
timer.Start();
Dispatcher.PushFrame(frame);
timer.Stop();
}
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
// Logged by type and first line only (no addresses, see FebeLog); Febe keeps running.
_app?.Log.Error("finestra", "Errore imprevisto nell'interfaccia di Windows.", e.Exception);
e.Handled = true;
}
private static System.Drawing.Icon LoadIcon()
{
using var stream = typeof(DesktopApplication).Assembly.GetManifestResourceStream("Febe.ico")
?? throw new InvalidOperationException("Febe.ico non è incorporata.");
return new System.Drawing.Icon(stream, System.Windows.Forms.SystemInformation.SmallIconSize);
}
/// <summary>The icon for WPF windows: the frame of the .ico, whose decoder lets WPF pick the small and large sizes.</summary>
private static ImageSource? LoadIconImage()
{
using var stream = typeof(DesktopApplication).Assembly.GetManifestResourceStream("Febe.ico");
return stream is null ? null : BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
}
+107
View File
@@ -0,0 +1,107 @@
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
using Febe.App;
using Febe.Desktop.Browser;
using Febe.Desktop.Core;
using Febe.Desktop.Native;
using Febe.Web.Native;
using Microsoft.Web.WebView2.Core;
using Microsoft.Win32;
namespace Febe.Desktop;
/// <summary>The Windows-only part the desktop platform needs (WebView2, Edge's window, native shell, notifications).</summary>
internal sealed class DesktopShell(Dispatcher ui, ImageSource? icon, INativeShell native, IAlertChannel notifications) : IDesktopShell
{
public INativeShell Native { get; } = native;
public IAlertChannel? Notifications { get; } = notifications;
public string? WebView2Version()
{
try
{
return CoreWebView2Environment.GetAvailableBrowserVersionString();
}
catch (WebView2RuntimeNotFoundException)
{
return null;
}
}
public IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context) =>
new WebView2Browser(ui, settings, context, icon);
public string? FindEdge()
{
string? appPath = null;
foreach (var hive in new[] { Registry.CurrentUser, Registry.LocalMachine })
{
using var key = hive.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\App Paths\msedge.exe", writable: false);
if (key?.GetValue(null) is string value && !string.IsNullOrWhiteSpace(value))
{
appPath = value;
break;
}
}
return EdgeLocator.Find(EdgeLocator.Candidates(
appPath,
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)));
}
public Task ShowProcessWindowAsync(int processId, CancellationToken ct) => ui.InvokeAsync(() =>
{
if (MainWindowOf(processId) is not { } window)
{
return;
}
if (Win32.IsIconic(window))
{
Win32.ShowWindow(window, Win32.SwRestore);
}
var area = SystemParameters.WorkArea;
var dpi = Win32.SystemScale;
Win32.SetWindowPos(window, IntPtr.Zero, (int)(area.Left * dpi) + 40, (int)(area.Top * dpi) + 40, 0, 0, Win32.SwpNoSize | Win32.SwpNoZOrder);
Win32.SetForegroundWindow(window);
}).Task;
public Task HideProcessWindowAsync(int processId, CancellationToken ct) => ui.InvokeAsync(() =>
{
if (MainWindowOf(processId) is not { } window)
{
return;
}
// Out of view, never minimised (S2): just right of every screen.
var dpi = Win32.SystemScale;
var x = (int)((SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth) * dpi) + 64;
var y = (int)(SystemParameters.VirtualScreenTop * dpi);
if (Win32.IsIconic(window))
{
Win32.ShowWindow(window, Win32.SwShowNoActivate);
}
Win32.SetWindowPos(window, IntPtr.Zero, x, y, 0, 0, Win32.SwpNoSize | Win32.SwpNoZOrder | Win32.SwpNoActivate);
}).Task;
private static IntPtr? MainWindowOf(int processId)
{
try
{
using var process = Process.GetProcessById(processId);
process.Refresh();
return process.MainWindowHandle == IntPtr.Zero ? null : process.MainWindowHandle;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
return null;
}
}
}
+34 -1
View File
@@ -1,6 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Eseguibile Windows (WPF): finestra con l'interfaccia, icona nell'area di notifica, WebView2Host.
Si compila anche da Linux grazie a EnableWindowsTargeting (CI e rilascio). -->
Si compila anche da Linux grazie a EnableWindowsTargeting (CI e rilascio), ma gira solo su Windows.
Pubblicazione in un solo Febe.exe (specifica §12): il comando completo è in installer/costruisci.sh.
Le librerie native (e_sqlite3, libSkiaSharp, WebView2Loader e quelle di WPF) stanno dentro l'eseguibile e si
estraggono da sole al primo avvio; i file di configurazione e i simboli non escono accanto all'eseguibile. -->
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
@@ -9,12 +12,42 @@
<EnableWindowsTargeting>true</EnableWindowsTargeting>
<AssemblyName>Febe</AssemblyName>
<RootNamespace>Febe.Desktop</RootNamespace>
<ApplicationIcon>Febe.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
<StartupObject>Febe.Desktop.Program</StartupObject>
<InvariantGlobalization>false</InvariantGlobalization>
<!-- Un solo file anche per i simboli: nessun .pdb accanto a Febe.exe. -->
<DebugType>embedded</DebugType>
<CopyOutputSymbolsToPublishDirectory>false</CopyOutputSymbolsToPublishDirectory>
<!-- È un'applicazione WPF (Windows Forms serve solo per l'icona nell'area di notifica): la consapevolezza dei DPI per
monitor la legge WPF dal manifesto, non da ApplicationHighDpiMode di Windows Forms. -->
<NoWarn>$(NoWarn);WFO0003</NoWarn>
</PropertyGroup>
<ItemGroup>
<!-- WPF e Windows Forms insieme: niente using impliciti che rendano ambigui Point, Color, Application, MessageBox. -->
<Using Remove="System.Windows.Forms" />
<Using Remove="System.Drawing" />
<Using Include="System.IO" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Febe.Core\Febe.Core.csproj" />
<ProjectReference Include="..\Febe.Data\Febe.Data.csproj" />
<ProjectReference Include="..\Febe.Browser\Febe.Browser.csproj" />
<ProjectReference Include="..\Febe.Web\Febe.Web.csproj" />
<ProjectReference Include="..\Febe.App\Febe.App.csproj" />
<ProjectReference Include="..\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
<PackageReference Include="Microsoft.Web.WebView2" />
</ItemGroup>
<ItemGroup>
<!-- L'icona del marchio (appendice C), generata da BrandMark e IcoWriter: finestre e area di notifica la leggono da qui. -->
<EmbeddedResource Include="Febe.ico" LogicalName="Febe.ico" />
</ItemGroup>
<!-- Un solo file: la configurazione per sito (config/*.json) è già incorporata in Febe.Core e si sovrascrive dalla
cartella Dati; i simboli (anche il .pdb nativo di SkiaSharp, quasi 100 MB) e la documentazione XML dei pacchetti non
servono a chi usa Febe. Niente di tutto questo esce accanto all'eseguibile. -->
<Target Name="FebeSingleFileOnly" AfterTargets="ComputeResolvedFilesToPublishList" Condition="'$(PublishSingleFile)' == 'true'">
<ItemGroup>
<ResolvedFileToPublish Remove="@(ResolvedFileToPublish)" Condition="'%(ResolvedFileToPublish.Extension)' == '.pdb' or '%(ResolvedFileToPublish.Extension)' == '.xml' or $([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').StartsWith('config'))" />
</ItemGroup>
</Target>
</Project>
Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

+33
View File
@@ -0,0 +1,33 @@
# Febe.Desktop
L'eseguibile per Windows (WPF, `net10.0-windows`; specifica §5, §12). Si compila anche da Linux
(`EnableWindowsTargeting`), ma gira solo su Windows: tutto ciò che si può provare altrove sta in
`src/Febe.Desktop.Core` (`net10.0`, prove in `tests/Febe.Tests/Desktop`). Guida per l'uso: `docs/windows.md`.
## Come è fatto
| File | Che cosa fa |
|---|---|
| `Program.cs` | Riga di comando (`DesktopCommandLine`), cartella dei dati, istanza unica: un secondo avvio chiede al primo di mostrarsi ed esce |
| `DesktopApplication.cs` | Avvio: area di notifica, spostamento della cartella dei dati se chiesto, `FebeApp` con `DesktopPlatform`, finestra principale; «Esci», fine sessione di Windows |
| `MainWindow.cs` | La finestra con l'interfaccia (WebView2 di WPF, cartella `Dati\interfaccia`): apre `/?gettone=…` una volta, ogni altro indirizzo va al browser predefinito |
| `Browser/WebView2Host.cs` | `IBrowserHost` di Windows: finestra «Browser di Febe», ambiente e controllo WebView2 in `Dati\browser`, CDP con `WebView2CdpSession`, fuori vista e in primo piano (S2), chi guida |
| `Browser/WebView2Browser.cs` | `IFebeBrowser` per la composizione: avvio con nuovi tentativi, ripartenza dopo un arresto del processo, «Scollega» |
| `Browser/BrowserWindow.cs` | La finestra «Browser di Febe»: pagina a misura fissa, barra con Indietro, Ricarica e indirizzo; chiudere = fuori vista |
| `Browser/CoreWebView2DevTools.cs` | Le due chiamate di WebView2 per il CDP, sul thread dell'interfaccia (`IWebView2DevTools`) |
| `Browser/CompositionHost.cs` | Secondo tentativo di S2 (`--browser composizione`): visual di DirectComposition, mouse e puntatore inoltrati |
| `DesktopShell.cs` | `IDesktopShell`: sonda del runtime WebView2, Edge e la sua finestra (terzo tentativo di S2), notifiche |
| `WindowsShell.cs` | `INativeShell` (cartelle, Esplora risorse, browser predefinito, notifiche, avvio con il computer), canale degli avvisi, posizione della cartella dei dati nel registro |
| `TrayIcon.cs` | Icona nell'area di notifica (Windows Forms `NotifyIcon`): Apri, Metti in pausa/Riprendi, Esci, notifiche |
| `SingleInstanceGuard.cs` | Mutex con nome e pipe (solo l'utente corrente) per l'istanza unica |
| `Native/Win32.cs` | Le poche chiamate Win32 e le interfacce di DirectComposition |
| `Febe.ico` | Il marchio (appendice C) a 16–256 pixel, generato da `BrandMark`/`IcoWriter` (`FEBE_RIGENERA_ICONA=1 dotnet test --filter IconTests`) |
Regole che valgono anche qui: le chiamate a WebView2 solo sul thread dell'interfaccia; il browser di Febe non si nasconde
e non si riduce mai a icona (S2); nel registro mai indirizzi con il gettone, cookie o tasti; nessun pacchetto oltre a
`Microsoft.Web.WebView2` (WPF e Windows Forms vengono con il .NET per Windows).
## Pubblicazione
`installer/costruisci.sh` pubblica un solo `Febe.exe` (autosufficiente, compresso, librerie native incluse) e ne fa
`out/Febe-Setup-<versione>.exe` (NSIS, `installer/febe.nsi`) e `out/Febe-<versione>-portabile.zip`.
+144
View File
@@ -0,0 +1,144 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
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")
{
_ = _openOutside(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")
{
_ = _openOutside(uri);
}
}
}
+136
View File
@@ -0,0 +1,136 @@
using System.Runtime.InteropServices;
namespace Febe.Desktop.Native;
/// <summary>The few Win32 calls the desktop needs (windows of other processes, mouse capture, DirectComposition).</summary>
internal static class Win32
{
public const int SwRestore = 9;
public const int SwShowNoActivate = 4;
public const uint SwpNoSize = 0x0001;
public const uint SwpNoZOrder = 0x0004;
public const uint SwpNoActivate = 0x0010;
public const int WmSetCursor = 0x0020;
public const int WmMouseFirst = 0x0200;
public const int WmMouseWheel = 0x020A;
public const int WmMouseHWheel = 0x020E;
public const int WmMouseLeave = 0x02A3;
public const int HtClient = 1;
public const uint TmeLeave = 0x00000002;
[StructLayout(LayoutKind.Sequential)]
public struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
public int X;
public int Y;
}
[StructLayout(LayoutKind.Sequential)]
public struct TrackMouseEventInfo
{
public uint Size;
public uint Flags;
public IntPtr Window;
public uint HoverTime;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ShowWindow(IntPtr window, int command);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr window, IntPtr insertAfter, int x, int y, int width, int height, uint flags);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetWindowRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsIconic(IntPtr window);
[DllImport("user32.dll")]
public static extern IntPtr SetCursor(IntPtr cursor);
[DllImport("user32.dll")]
public static extern IntPtr SetCapture(IntPtr window);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ScreenToClient(IntPtr window, ref Point point);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool TrackMouseEvent(ref TrackMouseEventInfo info);
/// <summary>The DirectComposition device of the S2 fallback «composizione» (null rendering device: WebView2 draws).</summary>
[DllImport("dcomp.dll")]
public static extern int DCompositionCreateDevice2(IntPtr renderingDevice, ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object device);
/// <summary>The scale of the system DPI (SystemParameters are in device-independent pixels at this scale).</summary>
public static double SystemScale => GetDpiForSystem() / 96.0;
[DllImport("user32.dll")]
public static extern uint GetDpiForSystem();
public static int LowWord(IntPtr value) => unchecked((short)(long)value);
public static int HighWord(IntPtr value) => unchecked((short)((long)value >> 16));
}
/// <summary>IDCompositionDevice (dcomp.h): only the first methods, in their order in the table; the rest is never called.</summary>
[ComImport]
[Guid("C37EA93A-E7AA-450D-B16F-9746CB0407F3")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IDCompositionDevice
{
void Commit();
void WaitForCommitCompletion();
void GetFrameStatistics(IntPtr statistics);
[return: MarshalAs(UnmanagedType.Interface)]
IDCompositionTarget CreateTargetForHwnd(IntPtr window, [MarshalAs(UnmanagedType.Bool)] bool topmost);
[return: MarshalAs(UnmanagedType.Interface)]
IDCompositionVisual CreateVisual();
}
/// <summary>IDCompositionTarget (dcomp.h).</summary>
[ComImport]
[Guid("EACDD04C-117E-4E17-88F4-D1B12B0E3D89")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IDCompositionTarget
{
void SetRoot([MarshalAs(UnmanagedType.Interface)] IDCompositionVisual visual);
}
/// <summary>IDCompositionVisual (dcomp.h): handed to WebView2 as its root visual target, no method called here.</summary>
[ComImport]
[Guid("4D93059D-097B-4651-9A60-F0F25116E2F3")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IDCompositionVisual
{
}
+37
View File
@@ -0,0 +1,37 @@
using System.Windows;
using Febe.Desktop.Core;
namespace Febe.Desktop;
/// <summary>
/// Entry point of Febe.exe (spec §12). Reads the command line, finds the Data folder (<c>--dati</c>, the folder recorded
/// after a move, or <c>%LOCALAPPDATA%\Febe</c>), makes sure only one Febe runs on it — a second launch asks the first to
/// show its window and exits — and starts the application.
/// </summary>
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
// The menu of the notification-area icon is Windows Forms: with the visual styles of Windows.
System.Windows.Forms.Application.EnableVisualStyles();
if (!DesktopCommandLine.TryParse(args, out var options, out var problem))
{
MessageBox.Show($"{problem}\n\n{DesktopCommandLine.Usage}", "Febe", MessageBoxButton.OK, MessageBoxImage.Warning);
return 2;
}
var folders = DesktopFolders.Current();
var locations = new RegistryLocationStore();
var dataFolder = options.DataFolder ?? locations.Current ?? folders.DefaultDataFolder;
using var instance = SingleInstanceGuard.TryAcquire(dataFolder);
if (instance is null)
{
SingleInstanceGuard.SignalFirst(dataFolder, InstanceMessages.For(options));
return 0;
}
var application = new DesktopApplication(options, folders, locations, dataFolder, options.DataFolder is not null, instance);
return application.Run();
}
}
+124
View File
@@ -0,0 +1,124 @@
using System.IO.Pipes;
using System.Text;
using Febe.Desktop.Core;
namespace Febe.Desktop;
/// <summary>
/// One Febe at a time for a Data folder (spec §12): a named mutex in the session namespace, and a named pipe (current
/// user only) through which a second launch asks the first to show its window, then exits.
/// </summary>
internal sealed class SingleInstanceGuard : IDisposable
{
private readonly Mutex _mutex;
private readonly string _pipeName;
private readonly CancellationTokenSource _stop = new();
private Task? _listener;
private SingleInstanceGuard(Mutex mutex, string pipeName)
{
_mutex = mutex;
_pipeName = pipeName;
}
/// <summary>The guard of the first instance, or null when another Febe already runs on this Data folder.</summary>
public static SingleInstanceGuard? TryAcquire(string dataFolder)
{
var mutex = new Mutex(initiallyOwned: true, InstanceIdentity.MutexName(dataFolder), out var created);
if (!created)
{
mutex.Dispose();
return null;
}
return new SingleInstanceGuard(mutex, InstanceIdentity.PipeName(dataFolder));
}
/// <summary>A second launch: hands its request to the first instance (best effort, a few seconds at most).</summary>
public static void SignalFirst(string dataFolder, string message)
{
try
{
using var pipe = new NamedPipeClientStream(".", InstanceIdentity.PipeName(dataFolder), PipeDirection.Out, PipeOptions.CurrentUserOnly);
pipe.Connect(3000);
var bytes = Encoding.UTF8.GetBytes(message + "\n");
pipe.Write(bytes, 0, bytes.Length);
pipe.Flush();
}
catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException)
{
// The first instance is starting or stopping: nothing more to do.
}
}
/// <summary>Starts listening for second launches; <paramref name="onRequest"/> runs on a background thread.</summary>
public void Listen(Action<InstanceRequest> onRequest)
{
ArgumentNullException.ThrowIfNull(onRequest);
_listener = Task.Run(() => ListenAsync(onRequest, _stop.Token));
}
public void Dispose()
{
_stop.Cancel();
try
{
_listener?.Wait(TimeSpan.FromSeconds(2));
}
catch (AggregateException)
{
}
try
{
_mutex.ReleaseMutex();
}
catch (ApplicationException)
{
// Released on another thread already: Windows releases it when the process ends.
}
_mutex.Dispose();
_stop.Dispose();
}
private async Task ListenAsync(Action<InstanceRequest> onRequest, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await using var pipe = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
await pipe.WaitForConnectionAsync(ct).ConfigureAwait(false);
var buffer = new byte[InstanceMessages.MaxLength + 2];
var read = 0;
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
timeout.CancelAfter(TimeSpan.FromSeconds(3));
int n;
while (read < buffer.Length && (n = await pipe.ReadAsync(buffer.AsMemory(read), timeout.Token).ConfigureAwait(false)) > 0)
{
read += n;
if (Array.IndexOf(buffer, (byte)'\n', 0, read) >= 0)
{
break;
}
}
}
if (InstanceMessages.Parse(Encoding.UTF8.GetString(buffer, 0, read)) is { } request)
{
onRequest(request);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is IOException or OperationCanceledException or UnauthorizedAccessException)
{
// A broken or slow client: wait for the next one.
}
}
}
}
+80
View File
@@ -0,0 +1,80 @@
using Forms = System.Windows.Forms;
namespace Febe.Desktop;
/// <summary>
/// The icon in the notification area (spec §12): a click opens the window; the menu has «Apri», «Metti in pausa» or
/// «Riprendi», «Esci». Its balloon tips are the Windows notifications of Febe (spec §13.3): Windows 10 and 11 show them
/// as notifications, without any extra package.
/// </summary>
internal sealed class TrayIcon : IDisposable
{
private readonly Forms.NotifyIcon _icon;
private readonly Forms.ToolStripMenuItem _pause;
private readonly Func<bool> _isPaused;
/// <param name="icon">The icon of the mark.</param>
/// <param name="isPaused">Whether the engine is paused or stopped (the menu then says «Riprendi»).</param>
public TrayIcon(System.Drawing.Icon icon, Func<bool> isPaused)
{
_isPaused = isPaused ?? throw new ArgumentNullException(nameof(isPaused));
var menu = new Forms.ContextMenuStrip();
var open = new Forms.ToolStripMenuItem("Apri") { Font = new System.Drawing.Font(menu.Font, System.Drawing.FontStyle.Bold) };
open.Click += (_, _) => OpenRequested?.Invoke(this, EventArgs.Empty);
_pause = new Forms.ToolStripMenuItem("Metti in pausa");
_pause.Click += (_, _) => PauseToggleRequested?.Invoke(this, _isPaused());
var exit = new Forms.ToolStripMenuItem("Esci");
exit.Click += (_, _) => ExitRequested?.Invoke(this, EventArgs.Empty);
menu.Items.Add(open);
menu.Items.Add(_pause);
menu.Items.Add(new Forms.ToolStripSeparator());
menu.Items.Add(exit);
menu.Opening += (_, _) => _pause.Text = _isPaused() ? "Riprendi" : "Metti in pausa";
_icon = new Forms.NotifyIcon
{
Icon = icon,
Text = "Febe",
ContextMenuStrip = menu,
Visible = true,
};
_icon.MouseClick += (_, e) =>
{
if (e.Button == Forms.MouseButtons.Left)
{
OpenRequested?.Invoke(this, EventArgs.Empty);
}
};
_icon.BalloonTipClicked += (_, _) => OpenRequested?.Invoke(this, EventArgs.Empty);
}
/// <summary>«Apri», a click on the icon or on a notification.</summary>
public event EventHandler? OpenRequested;
/// <summary>«Metti in pausa» (false) or «Riprendi» (true: the engine was paused or stopped).</summary>
public event EventHandler<bool>? PauseToggleRequested;
/// <summary>«Esci».</summary>
public event EventHandler? ExitRequested;
/// <summary>A Windows notification. Title and text in Italian; never secrets, captions or addresses.</summary>
public void Notify(string title, string text, bool warning = false)
{
_icon.BalloonTipTitle = Trim(title, 63);
_icon.BalloonTipText = Trim(text, 255);
_icon.BalloonTipIcon = warning ? Forms.ToolTipIcon.Warning : Forms.ToolTipIcon.Info;
_icon.ShowBalloonTip(10_000);
}
/// <summary>The tooltip of the icon: what Febe is doing (at most 127 characters for Windows).</summary>
public void SetStatus(string status) => _icon.Text = Trim("Febe: " + status, 127);
public void Dispose()
{
_icon.Visible = false;
_icon.ContextMenuStrip?.Dispose();
_icon.Dispose();
}
private static string Trim(string text, int max) => text.Length <= max ? text : text[..(max - 1)] + "…";
}
+158
View File
@@ -0,0 +1,158 @@
using System.Diagnostics;
using System.Windows;
using System.Windows.Threading;
using Febe.App;
using Febe.Core.Alerts;
using Febe.Desktop.Core;
using Febe.Web.Native;
using Microsoft.Win32;
namespace Febe.Desktop;
/// <summary>
/// The native functions of Windows offered to the interface (spec §12): folder picker (<see cref="OpenFolderDialog"/>),
/// «Mostra nella cartella» (<c>explorer.exe /select,"…"</c>), addresses in the default browser (shell execute), Windows
/// notifications (balloon tips of the notification-area icon) and start with the computer
/// (<c>HKCU\…\Run</c>, value <c>Febe</c>). Paths and addresses never come from the page: the web layer resolves them.
/// </summary>
internal sealed class WindowsShell(Dispatcher ui, Func<Window?> owner, Func<TrayIcon?> tray) : INativeShell
{
public bool CanPickFolder => true;
public bool CanShowInFolder => true;
public bool CanOpenUrl => true;
public bool CanNotify => true;
public bool SupportsAutostart => true;
public Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct) =>
ui.InvokeAsync(() =>
{
var dialog = new OpenFolderDialog { Title = title, Multiselect = false };
if (!string.IsNullOrWhiteSpace(initialFolder) && Directory.Exists(initialFolder))
{
dialog.InitialDirectory = initialFolder;
}
var window = owner();
var chosen = window is { IsVisible: true } ? dialog.ShowDialog(window) : dialog.ShowDialog();
return chosen == true ? dialog.FolderName : null;
}).Task;
public Task<bool> ShowInFolderAsync(string fullPath, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(fullPath) || !Path.IsPathFullyQualified(fullPath) || fullPath.Contains('"', StringComparison.Ordinal) || !File.Exists(fullPath))
{
return Task.FromResult(false);
}
var explorer = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe");
try
{
using var process = Process.Start(new ProcessStartInfo(explorer, $"/select,\"{fullPath}\"") { UseShellExecute = false });
return Task.FromResult(process is not null);
}
catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)
{
return Task.FromResult(false);
}
}
public Task<bool> OpenUrlAsync(Uri address, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(address);
if (!address.IsAbsoluteUri || address.Scheme is not ("http" or "https"))
{
return Task.FromResult(false);
}
try
{
// The default browser of Alberto (never the browser of Febe), through the shell.
using var process = Process.Start(new ProcessStartInfo(address.AbsoluteUri) { UseShellExecute = true });
return Task.FromResult(true);
}
catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)
{
return Task.FromResult(false);
}
}
public Task NotifyAsync(string title, string message, CancellationToken ct) =>
ui.InvokeAsync(() => tray()?.Notify(title, message)).Task;
public Task<bool> GetAutostartAsync(CancellationToken ct)
{
using var key = Registry.CurrentUser.OpenSubKey(Autostart.RunKey, writable: false);
var value = key?.GetValue(Autostart.ValueName) as string;
return Task.FromResult(Environment.ProcessPath is { } exe && Autostart.PointsTo(value, exe));
}
public Task SetAutostartAsync(bool enabled, CancellationToken ct)
{
using var key = Registry.CurrentUser.CreateSubKey(Autostart.RunKey, writable: true);
if (enabled)
{
var exe = Environment.ProcessPath ?? throw new InvalidOperationException("Percorso di Febe.exe sconosciuto.");
key.SetValue(Autostart.ValueName, Autostart.Command(exe), RegistryValueKind.String);
}
else
{
key.DeleteValue(Autostart.ValueName, throwOnMissingValue: false);
}
return Task.CompletedTask;
}
}
/// <summary>Windows notifications for the alerts of spec §13.3 (Impostazioni ▸ Notifiche ▸ «Notifiche di Windows»).</summary>
internal sealed class WindowsNotificationChannel(Dispatcher ui, Func<TrayIcon?> tray) : IAlertChannel
{
public bool IsEnabled(AlertSettings settings) => settings?.WindowsNotifications == true;
public Task SendAsync(FebeAlert alert, AlertSettings settings, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(alert);
var warning = alert.Kind is AlertKind.Verification or AlertKind.Disconnection or AlertKind.Throttle or AlertKind.DiskLow;
return ui.InvokeAsync(() => tray()?.Notify(alert.Title, alert.Message, warning)).Task;
}
}
/// <summary>
/// The Data folder in use after a move, and a move asked for the next start (<see cref="DataFolderMove"/>), under
/// <c>HKCU\Software\Febe</c>: values «CartellaDati» and «NuovaCartellaDati». The uninstaller reads the first to say
/// where the data are.
/// </summary>
internal sealed class RegistryLocationStore : IDataFolderLocationStore
{
public const string Key = @"Software\Febe";
public string? Current => Read("CartellaDati");
public string? Pending => Read("NuovaCartellaDati");
public void SetCurrent(string? folder) => Write("CartellaDati", folder);
public void SetPending(string? folder) => Write("NuovaCartellaDati", folder);
private static string? Read(string name)
{
using var key = Registry.CurrentUser.OpenSubKey(Key, writable: false);
return key?.GetValue(name) is string value && !string.IsNullOrWhiteSpace(value) ? value : null;
}
private static void Write(string name, string? value)
{
using var key = Registry.CurrentUser.CreateSubKey(Key, writable: true);
if (value is null)
{
key.DeleteValue(name, throwOnMissingValue: false);
}
else
{
key.SetValue(name, value, RegistryValueKind.String);
}
}
}
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Febe per Windows: niente permessi di amministratore (installazione per utente), consapevole dei DPI per monitor,
Windows 10 e 11. -->
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="Febe.Desktop" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 e Windows 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
</assembly>