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; /// /// Febe for Windows (spec §5, §12): the shared composition with the , /// 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. /// 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; // The single-instance guards this Febe holds: the one of the folder it started on (taken by Program, disposed there) // and, after a move, the one of the new folder — which every later launch finds recorded. private readonly List _instances; private readonly CancellationTokenSource _lifetime = new(); private string _dataFolder; private DataFolderLock? _dataLock; 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; _instances = [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.TargetGuard is SingleInstanceGuard guard) { _instances.Add(guard); } if (moved.Message is { } message) { _tray.Notify("Cartella dei dati", message, moved.Outcome != DataFolderMoveOutcome.Moved); } } // The folder itself is locked too: the guards are named after its path, the lock is the folder (spec §12). if (DataFolderLock.TryAcquire(_dataFolder, out _dataLock) == DataFolderLockOutcome.HeldByAnother) { if (!_options.StartHidden) { MessageBox.Show( $"Febe è già aperto con questa cartella dei dati ({_dataFolder}): cercalo nell'area di notifica, accanto all'orologio.", "Febe", MessageBoxButton.OK, MessageBoxImage.Information); } await ExitAsync().ConfigureAwait(true); return; } var native = new WindowsShell(Dispatcher, () => _main, () => _tray, _dataFolderFixed ? _dataFolder : null); var shell = new DesktopShell(Dispatcher, _iconImage, native); _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; } foreach (var instance in _instances) { instance.Listen(request => Dispatcher.InvokeAsync(() => { if (request == InstanceRequest.Show) { ShowMain(); } })); } _ = Task.Run(() => FollowEngineAsync(_lifetime.Token)); if (!_options.StartHidden || _app.Problems.Count > 0) { ShowMain(); } } /// Opens (the first time) and shows the main window. 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 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); /// The X of the main window: into the notification area (default), or exit. 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."); } } /// «Riprendi» needs Alberto: after a pause, a verification or a disconnection. 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); } } /// The tooltip of the icon follows the engine (the line of the sidebar). 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 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(p => { bar.Maximum = Math.Max(1, p.FilesTotal); bar.Value = p.FilesDone; }); var current = _dataFolder; return await Task.Run(() => DataFolderMove.ApplyPending(_locations, current, progress, claimTarget: SingleInstanceGuard.TryAcquire)).ConfigureAwait(true); } finally { window.Close(); } } /// «Esci»: everything stops in order (engine, downloads, browser, database), then the process ends. 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; } /// /// Everything has stopped: the lock of the Data folder and the guard of a moved folder go last. The guard of the /// folder Febe started on belongs to Program, which disposes it when the application returns. /// protected override void OnExit(ExitEventArgs e) { _dataLock?.Dispose(); foreach (var instance in _instances.Skip(1)) { instance.Dispose(); } base.OnExit(e); } /// Windows is shutting down or Alberto logs off: stop in order while the messages still flow (S3). 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); } /// The icon for WPF windows: the frame of the .ico, whose decoder lets WPF pick the small and large sizes. 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); } }