Files
Chronos/src/Titano.Uploader/App.xaml.cs
T
Claude 1187c36d66 fix(uploader): follow right-to-left languages, name and reach every control by keyboard
Uploader:
- Mirror the main window, the confirmation dialog and the tray menu for ar/he/fa/ur; keep paths, addresses,
  file names, the fingerprint, the brand mark and media glyphs left to right.
- Queue rows take keyboard focus, are named "file · state" for screen readers, and Enter retries a failed
  file; a "✕ n failed" link jumps to the first failure; the list follows the upload near its top.
- Focus moves into the settings panel (Tab cycles inside) and back to the gear, to Browse after sign-in and
  to the refused field after a failed one; activity changes and sign-in errors are announced.
- A wrong address or password marks its field (error border, message in the tooltip); Retry only where it
  can help; session-ended toasts offer Sign in; the form stays visible while its own sign-in runs.
- Watch chips and the add button wrap and shorten long paths; target choices wrap with their fields; the
  settings panel uses the side-panel width with wrapping labels; disabled controls say why.
- The window opens at 760x700 (min 630 high) so the per-file list shows five rows; --capture adds an
  Arabic pass.

Setup:
- Every stage has a default and a cancel button (safe action first), the keyboard moves to the new
  default and outcomes are announced; the title-bar Close is disabled while files are written.
- "Remove my data" measures the user data folder and shows the plan (largest entries, total) before
  Uninstall can run; the tooltip names backups and the uploader queue.
- Folder field before Browse in Tab order; paths and file names left to right; disabled tooltips say why.

Both: byte units come from the language (Common.Size.*).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-03 17:14:54 +00:00

340 lines
11 KiB
C#

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;
/// <summary>
/// Titano Uploader (BRIEF §15): one instance per session, logging, language and theme, the persisted queue, the
/// server session, watch folders and the tray icon. <c>--capture &lt;dir&gt;</c> renders screenshots and exits.
/// </summary>
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<string>()]);
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();
}
/// <summary>Switches the UI language (BRIEF §16); an unknown code falls back to the OS language.</summary>
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);
}
/// <summary>Writes the queue and the watch memory when they changed (every 2 s and at exit).</summary>
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<string> 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;
}
}
/// <summary>The tray icon exists while "Minimise to tray" is on.</summary>
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<TrayMenuItem> 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;
}
}
/// <summary>Listens for server beacons only while the sign-in form is shown.</summary>
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));
}
/// <summary>Closing keeps the uploader running in the tray when "Minimise to tray" is on.</summary>
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();
};
}
/// <summary>Paths handed to the running instance must not depend on this process's working directory.</summary>
private static string? Absolute(string path)
{
try
{
return Path.GetFullPath(path);
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return null;
}
}
}