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,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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user