using System.ComponentModel; using System.Globalization; using System.IO; using System.Windows; using System.Windows.Threading; using Titano.Core.Diagnostics; using Titano.Core.Localization; using Titano.Ui.Mvvm; using Titano.Ui.Theming; using Titano.Uploader.Infrastructure; using Titano.Uploader.Interop; using Titano.Uploader.Server; using Titano.Uploader.Shell; using Titano.Uploader.Uploads; using Titano.Uploader.Watching; namespace Titano.Uploader; /// /// Titano Uploader (BRIEF §15): one instance per session, logging, language and theme, the persisted queue, the /// server session, watch folders and the tray icon. --capture <dir> renders screenshots and exits. /// public partial class App : Application { private const int TrayShow = 1; private const int TrayPause = 2; private const int TrayExit = 3; private readonly CoalescingWriter _writer = new(); private FileLogSink? _log; private SingleInstance? _instance; private UploaderEnvironment? _environment; private UploaderSettings? _settings; private UploadQueue? _queue; private ProcessedFileMemory? _memory; private ServerSession? _session; private UploadEngine? _engine; private WatchFolderService? _watch; private DiscoveryListener? _discovery; private MainViewModel? _vm; private Shell.MainWindow? _window; private TrayIcon? _tray; private DispatcherTimer? _persist; private bool _queueDirty; private bool _exiting; protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var command = CommandLine.Parse(e.Args); _environment = UploaderEnvironment.Detect(); _log = new FileLogSink(_environment.LogDirectory, "uploader"); Log.SetSink(_log); Log.Info("app", $"Titano Uploader {typeof(App).Assembly.GetName().Version} starting; data at {_environment.DataDirectory}"); HookUnhandledExceptions(); if (command.CaptureDirectory is { } captureDirectory) { RunCapture(captureDirectory); return; } _instance = SingleInstance.TryAcquire(); if (_instance is null) { SingleInstance.HandOver([.. command.Paths.Select(Absolute).OfType()]); Log.Info("app", "Another uploader runs in this session; arguments handed over"); Shutdown(); return; } _settings = UploaderSettings.Load(_environment.SettingsPath); ApplyLanguage(_settings.Language); ThemeManager.Initialize(this, _settings.Theme); BuildServices(_environment, _settings); _instance.Listen(args => Dispatcher.BeginInvoke(() => OnHandOver(args))); _session!.Start(); _engine!.Start(); _vm!.Start(); _vm.StartWatching(); UpdateTray(); UpdateDiscovery(); if (command.Paths.Count > 0) _ = _vm.EnqueueAsync(command.Paths); if (command.StartInTray && _settings.MinimizeToTray) return; if (command.StartInTray) _window!.WindowState = WindowState.Minimized; _window!.Show(); } protected override void OnExit(ExitEventArgs e) { _persist?.Stop(); _vm?.Dispose(); // Cancels transfers; interrupted items are written as queued and resume from the server's chunks. _engine?.Dispose(); if (_queue is not null && _environment is not null) { Persist(); _writer.Flush(TimeSpan.FromSeconds(10)); } if (_window is not null && _settings is not null) _window.SavePlacement(); SaveSettings(); _watch?.Dispose(); _discovery?.Dispose(); _session?.Dispose(); _tray?.Dispose(); _instance?.Dispose(); Log.Info("app", "Titano Uploader exiting"); _log?.Dispose(); base.OnExit(e); } private void BuildServices(UploaderEnvironment environment, UploaderSettings settings) { _queue = new UploadQueue(); QueueStore.Load(environment.QueuePath, _queue); _memory = ProcessedFileMemory.Load(environment.WatchMemoryPath); _session = new ServerSession(settings, SaveSettings); _engine = new UploadEngine(_queue, _session, () => settings.DeleteAfterUpload); _watch = new WatchFolderService(_memory, _queue.ContainsPath); var startup = new RunKeyStartupRegistration(); startup.Refresh(); var dialogs = new UploaderDialogs(); _vm = new MainViewModel(new UploaderServices(settings, SaveSettings, _session, _queue, _engine, startup, dialogs, _watch, _memory, environment.LogDirectory)); _window = new Shell.MainWindow(_vm, settings); dialogs.Owner = _window; MainWindow = _window; AsyncRelayCommand.Failed += _vm.ReportError; _engine.ItemConfirmed += (_, item) => { if (item.WatchRoot is { } root) _memory.Add(root, item.Path, item.Size, item.ModifiedUtc); }; _watch.FilesReady += _vm.OnWatchFilesReady; _watch.AvailabilityChanged += _vm.OnWatchAvailabilityChanged; _queue.Changed += (_, _) => _queueDirty = true; _vm.UploadsCompleted += OnUploadsCompleted; _vm.PropertyChanged += OnViewModelChanged; _window.Closing += OnWindowClosing; _window.Closed += (_, _) => ExitApplication(); _window.StateChanged += OnWindowStateChanged; _persist = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(2) }; _persist.Tick += (_, _) => Persist(); _persist.Start(); } /// Switches the UI language (BRIEF §16); an unknown code falls back to the OS language. private static void ApplyLanguage(string? code) { CultureInfo requested; try { requested = code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code); } catch (CultureNotFoundException) { requested = CultureInfo.CurrentUICulture; } var culture = Languages.BestMatch(requested); CultureInfo.DefaultThreadCurrentUICulture = culture; CultureInfo.CurrentUICulture = culture; Loc.SetCulture(culture); } /// Writes the queue and the watch memory when they changed (every 2 s and at exit). private void Persist() { if (_queue is null || _memory is null || _environment is null) return; if (_queueDirty) { _queueDirty = false; _writer.Write(_environment.QueuePath, QueueStore.Serialize(_queue)); } if (_memory.IsDirty) _writer.Write(_environment.WatchMemoryPath, _memory.Serialize()); } private void SaveSettings() { if (_settings is null || _environment is null) return; try { _settings.Save(_environment.SettingsPath); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Warning("app", "Settings not saved", ex); } } private void OnHandOver(IReadOnlyList paths) { ShowWindow(); if (paths.Count > 0) _ = _vm!.EnqueueAsync(paths); } private void OnViewModelChanged(object? sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(MainViewModel.MinimizeToTray): UpdateTray(); break; case nameof(MainViewModel.IsConnectVisible): UpdateDiscovery(); break; case nameof(MainViewModel.TrayText): _tray?.SetToolTip(_vm!.TrayText); break; } } /// The tray icon exists while "Minimise to tray" is on. private void UpdateTray() { if (_settings!.MinimizeToTray && _tray is null) { _tray = new TrayIcon(_vm!.TrayText, TrayMenu, OnTrayCommand, ShowWindow); } else if (!_settings.MinimizeToTray && _tray is not null) { _tray.Dispose(); _tray = null; if (_window is { IsVisible: false }) ShowWindow(); } } private IReadOnlyList TrayMenu() => [ new(TrayShow, Loc.L("Uploader.Tray.Show")), new(TrayPause, _vm!.PauseLabel), new(0, null), new(TrayExit, Loc.L("Uploader.Tray.Exit")), ]; private void OnTrayCommand(int id) { switch (id) { case TrayShow: ShowWindow(); break; case TrayPause: _vm!.TogglePause(); break; case TrayExit: ExitApplication(); break; } } /// Listens for server beacons only while the sign-in form is shown. private void UpdateDiscovery() { if (_vm!.IsConnectVisible) { if (_discovery is not null) return; _discovery = new DiscoveryListener(); _discovery.Found += _vm.Connect.AddDiscovered; _discovery.Start(); } else if (_discovery is not null) { _discovery.Dispose(); _discovery = null; } } private void OnUploadsCompleted(int count) { if (_window is { IsVisible: true, WindowState: not WindowState.Minimized }) return; _tray?.ShowBalloon(Loc.L("Uploader.Tray.Done.Title"), Loc.Plural("Uploader.Tray.Done.Message", count)); } /// Closing keeps the uploader running in the tray when "Minimise to tray" is on. private void OnWindowClosing(object? sender, CancelEventArgs e) { if (_exiting || !_settings!.MinimizeToTray) return; e.Cancel = true; _window!.SavePlacement(); _window.Hide(); } private void OnWindowStateChanged(object? sender, EventArgs e) { if (_window is { WindowState: WindowState.Minimized } && _settings!.MinimizeToTray) _window.Hide(); } private void ShowWindow() { if (_window is null) return; _window.Show(); if (_window.WindowState == WindowState.Minimized) _window.WindowState = WindowState.Normal; _window.Activate(); } private void ExitApplication() { if (_exiting) return; _exiting = true; Shutdown(); } private void RunCapture(string directory) { ThemeManager.Initialize(this, AppTheme.Dark); ScreenCapture.Run(directory, ApplyLanguage); } private void HookUnhandledExceptions() { DispatcherUnhandledException += (_, e) => { Log.Error("app", "Unhandled UI exception", e.Exception); if (_vm is null) return; _vm.ReportError(e.Exception); e.Handled = true; }; AppDomain.CurrentDomain.UnhandledException += (_, e) => Log.Error("app", "Unhandled exception", e.ExceptionObject as Exception); TaskScheduler.UnobservedTaskException += (_, e) => { Log.Error("app", "Unobserved task exception", e.Exception); e.SetObserved(); }; } /// Paths handed to the running instance must not depend on this process's working directory. private static string? Absolute(string path) { try { return Path.GetFullPath(path); } catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) { return null; } } }