diff --git a/src/Titano.Uploader/App.xaml b/src/Titano.Uploader/App.xaml
index 6e70f617..ec3359f9 100644
--- a/src/Titano.Uploader/App.xaml
+++ b/src/Titano.Uploader/App.xaml
@@ -1,4 +1,5 @@
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ ShutdownMode="OnExplicitShutdown">
diff --git a/src/Titano.Uploader/App.xaml.cs b/src/Titano.Uploader/App.xaml.cs
index 67a0cc99..8fe2c3da 100644
--- a/src/Titano.Uploader/App.xaml.cs
+++ b/src/Titano.Uploader/App.xaml.cs
@@ -1,7 +1,345 @@
+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.DesignTime;
+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.TrySend([.. 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)
+ {
+ ApplyLanguage(null);
+ ThemeManager.Initialize(this, AppTheme.Dark);
+ var sample = new SampleData();
+ var vm = sample.CreateViewModel();
+ var window = new Shell.MainWindow(vm, sample.Settings);
+ MainWindow = window;
+ ScreenCapture.Run(window, vm, sample, directory);
+ }
+
+ 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;
+ }
+ }
}
diff --git a/src/Titano.Uploader/DesignTime/SampleData.cs b/src/Titano.Uploader/DesignTime/SampleData.cs
new file mode 100644
index 00000000..62dc5a99
--- /dev/null
+++ b/src/Titano.Uploader/DesignTime/SampleData.cs
@@ -0,0 +1,171 @@
+using System.ComponentModel;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using Titano.Protocol;
+using Titano.Uploader.Infrastructure;
+using Titano.Uploader.Server;
+using Titano.Uploader.Shell;
+using Titano.Uploader.Uploads;
+using Titano.Uploader.Watching;
+
+namespace Titano.Uploader.DesignTime;
+
+///
+/// Sample content for --capture screenshots ONLY: a fake signed-in session, a running queue of 4,812 files
+/// and two watch folders. Nothing here touches the network, the registry or the user's data files.
+///
+public sealed class SampleData
+{
+ private const int FileCount = 4_812;
+ private const long FileSize = 20_000_000;
+
+ private readonly SampleSession _session = new();
+ private readonly UploadQueue _queue = new();
+ private MainViewModel? _vm;
+
+ public UploaderSettings Settings { get; } = new()
+ {
+ ServerUrl = "https://nas.local:8443/",
+ Username = "alberto",
+ BandwidthLimit = 50,
+ MinimizeToTray = true,
+ WatchFolders =
+ [
+ new UploaderSettings.WatchFolderSettings { Path = @"D:\Cam\Roof", IntervalSeconds = 60 },
+ new UploaderSettings.WatchFolderSettings { Path = @"\\garage-pi\cam", IntervalSeconds = 300 },
+ ],
+ };
+
+ /// A view model over in-memory sample services; settings changes are discarded.
+ public MainViewModel CreateViewModel()
+ {
+ var memory = new ProcessedFileMemory();
+ _session.BandwidthLimit = Settings.BandwidthLimit;
+ _vm = new MainViewModel(new UploaderServices(
+ Settings, () => { }, _session, _queue, new SampleEngine(_queue), new SampleStartup(), new UploaderDialogs(),
+ new WatchFolderService(memory, _queue.ContainsPath), memory, string.Empty));
+ foreach (var w in _vm.WatchFolders) w.IsAvailable = true;
+ return _vm;
+ }
+
+ /// First run: no server yet, one server found on the LAN.
+ public void ShowConnect()
+ {
+ _session.SetState(ConnectionState.NotConfigured);
+ _vm!.Connect.Address = string.Empty;
+ _vm.Connect.Username = string.Empty;
+ _vm.Connect.Discovered.Clear();
+ _vm.Connect.Discovered.Add(new DiscoveredServer("Studio NAS", "https://192.168.1.20:8443"));
+ }
+
+ /// Signed in, a card being uploaded at 38 MB/s.
+ public void ShowQueue()
+ {
+ _session.SetState(ConnectionState.Connected);
+ if (_queue.Items.Count == 0) FillQueue();
+ _vm!.Sequences.Clear();
+ _vm.Sequences.Add(new SequenceOption(Guid.Empty, "Harbour sunset"));
+ _vm.SelectedSequence = _vm.Sequences[0];
+ _vm.RefreshQueue();
+ }
+
+ private void FillQueue()
+ {
+ var batch = new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions };
+ var start = new DateTime(2026, 9, 28, 15, 22, 0);
+ _queue.Add(batch, Enumerable.Range(0, FileCount).Select(i =>
+ {
+ var shot = start.AddSeconds(i * 5);
+ var name = shot.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture) + "_" + (i + 1).ToString("0000", CultureInfo.InvariantCulture) + ".CR2";
+ return new QueueEntry(@"E:\DCIM\100CANON\" + name, FileSize, shot.ToUniversalTime(), shot, "1a2b3c4d-20260928-152200", null);
+ }));
+ for (var i = 0; i < 2_201; i++) _queue.Items[i].State = i % 200 == 7 ? UploadItemState.Skipped : UploadItemState.Verified;
+ _queue.Items[1_640].Retries = 1;
+ _queue.Items[2_201].State = UploadItemState.Uploading;
+ _queue.Items[2_201].BytesSent = FileSize * 46 / 100;
+ _queue.Items[2_202].State = UploadItemState.Hashing;
+ _queue.Fail(_queue.Items[2_203], UploadFailure.FileUnreadable, null, DateTime.UtcNow);
+ }
+
+ private sealed class SampleSession : IServerSession
+ {
+ private ConnectionState _state = ConnectionState.Connected;
+
+ public event PropertyChangedEventHandler? PropertyChanged;
+
+ public event EventHandler? SessionEnded
+ {
+ add { }
+ remove { }
+ }
+
+ public ConnectionState State => _state;
+ public string? Address => "https://nas.local:8443/";
+ public string? Username => "alberto";
+ public long QuotaBytes => 5_000_000_000_000;
+ public long UsedBytes => 3_100_000_000_000;
+ public int BandwidthLimit { get; set; }
+
+ public void SetState(ConnectionState state)
+ {
+ _state = state;
+ Raise(nameof(State));
+ }
+
+ public Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct) =>
+ Task.FromResult<(SignInResult, string?)>((SignInResult.Failed, null));
+
+ public void Trust(string fingerprint)
+ {
+ }
+
+ public Task SignOutAsync() => Task.CompletedTask;
+
+ public Task RefreshAsync() => Task.CompletedTask;
+
+ public Task> ListSequencesAsync(CancellationToken ct) => Task.FromResult>([]);
+
+ private void Raise([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
+ }
+
+ private sealed class SampleEngine(UploadQueue queue) : IUploadEngine
+ {
+ public event PropertyChangedEventHandler? PropertyChanged
+ {
+ add { }
+ remove { }
+ }
+
+ public event EventHandler? Drained
+ {
+ add { }
+ remove { }
+ }
+
+ public EngineStatus Status => queue.IsPaused ? EngineStatus.Paused : EngineStatus.Running;
+ public double BytesPerSecond => 38_000_000;
+
+ public void Pump()
+ {
+ }
+
+ public void Pause() => queue.IsPaused = true;
+
+ public void Resume() => queue.IsPaused = false;
+
+ public void StopAndClear()
+ {
+ }
+
+ public void Retry(UploadItem item)
+ {
+ }
+ }
+
+ private sealed class SampleStartup : IStartupRegistration
+ {
+ public bool IsEnabled { get; private set; } = true;
+
+ public void SetEnabled(bool enabled) => IsEnabled = enabled;
+ }
+}
diff --git a/src/Titano.Uploader/Interop/FileDialogs.cs b/src/Titano.Uploader/Interop/FileDialogs.cs
new file mode 100644
index 00000000..39160398
--- /dev/null
+++ b/src/Titano.Uploader/Interop/FileDialogs.cs
@@ -0,0 +1,187 @@
+using System.Runtime.InteropServices;
+
+namespace Titano.Uploader.Interop;
+
+/// A filter of the Open dialog: display name and patterns such as *.jpg;*.cr2.
+public readonly record struct FileFilter(string Name, string Patterns);
+
+///
+/// The shell's Open dialog through IFileOpenDialog COM (no WinForms): several files at once, or one folder
+/// (which also picks a card root such as E:\).
+///
+public static class FileDialogs
+{
+ private const uint FosPickFolders = 0x20;
+ private const uint FosForceFileSystem = 0x40;
+ private const uint FosAllowMultiSelect = 0x200;
+ private const uint FosPathMustExist = 0x800;
+ private const uint FosFileMustExist = 0x1000;
+ private const uint SigdnFileSysPath = 0x80058000;
+ private const int ErrorCancelled = unchecked((int)0x800704C7);
+
+ /// Selected files; empty when cancelled.
+ public static IReadOnlyList PickFiles(IntPtr owner, string title, IReadOnlyList filters) =>
+ Show(owner, title, FosAllowMultiSelect | FosFileMustExist, filters);
+
+ /// Selected folder; null when cancelled.
+ public static string? PickFolder(IntPtr owner, string title) => Show(owner, title, FosPickFolders, []).FirstOrDefault();
+
+ private static List Show(IntPtr owner, string title, uint options, IReadOnlyList filters)
+ {
+ var dialog = (IFileOpenDialog)new FileOpenDialogClass();
+ try
+ {
+ dialog.GetOptions(out var current);
+ dialog.SetOptions(current | options | FosForceFileSystem | FosPathMustExist);
+ dialog.SetTitle(title);
+ if (filters.Count > 0)
+ {
+ var specs = filters.Select(f => new FilterSpec { Name = f.Name, Spec = f.Patterns }).ToArray();
+ dialog.SetFileTypes((uint)specs.Length, specs);
+ dialog.SetFileTypeIndex(1);
+ }
+ var hr = dialog.Show(owner);
+ if (hr == ErrorCancelled) return [];
+ Marshal.ThrowExceptionForHR(hr);
+
+ dialog.GetResults(out var items);
+ try
+ {
+ items.GetCount(out var count);
+ var paths = new List((int)count);
+ for (uint i = 0; i < count; i++)
+ {
+ items.GetItemAt(i, out var item);
+ try
+ {
+ item.GetDisplayName(SigdnFileSysPath, out var path);
+ paths.Add(path);
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(item);
+ }
+ }
+ return paths;
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(items);
+ }
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(dialog);
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct FilterSpec
+ {
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string Name;
+
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string Spec;
+ }
+
+ [ComImport]
+ [Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")]
+ private class FileOpenDialogClass;
+
+ // Classic COM interop does not inherit vtables: IModalWindow and IFileDialog members are repeated in order.
+ [ComImport]
+ [Guid("d57c7288-d4ad-4768-be02-9d969532d960")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IFileOpenDialog
+ {
+ [PreserveSig]
+ int Show(IntPtr owner);
+
+ void SetFileTypes(uint count, [In, MarshalAs(UnmanagedType.LPArray)] FilterSpec[] filters);
+
+ void SetFileTypeIndex(uint index);
+
+ void GetFileTypeIndex(out uint index);
+
+ void Advise(IntPtr events, out uint cookie);
+
+ void Unadvise(uint cookie);
+
+ void SetOptions(uint options);
+
+ void GetOptions(out uint options);
+
+ void SetDefaultFolder(IShellItem item);
+
+ void SetFolder(IShellItem item);
+
+ void GetFolder(out IShellItem item);
+
+ void GetCurrentSelection(out IShellItem item);
+
+ void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
+
+ void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
+
+ void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
+
+ void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string text);
+
+ void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
+
+ void GetResult(out IShellItem item);
+
+ void AddPlace(IShellItem item, int placement);
+
+ void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string extension);
+
+ void Close(int hr);
+
+ void SetClientGuid(ref Guid guid);
+
+ void ClearClientData();
+
+ void SetFilter(IntPtr filter);
+
+ void GetResults(out IShellItemArray items);
+
+ void GetSelectedItems(out IShellItemArray items);
+ }
+
+ [ComImport]
+ [Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IShellItem
+ {
+ void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
+
+ void GetParent(out IShellItem parent);
+
+ void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name);
+
+ void GetAttributes(uint mask, out uint attributes);
+
+ void Compare(IShellItem other, uint hint, out int order);
+ }
+
+ [ComImport]
+ [Guid("b63ea76d-1f85-456f-a19c-48159efa858b")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IShellItemArray
+ {
+ void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
+
+ void GetPropertyStore(int flags, ref Guid iid, out IntPtr store);
+
+ void GetPropertyDescriptionList(IntPtr keyType, ref Guid iid, out IntPtr list);
+
+ void GetAttributes(int flags, uint mask, out uint attributes);
+
+ void GetCount(out uint count);
+
+ void GetItemAt(uint index, out IShellItem item);
+
+ void EnumItems(out IntPtr items);
+ }
+}
diff --git a/src/Titano.Uploader/Interop/TrayIcon.cs b/src/Titano.Uploader/Interop/TrayIcon.cs
new file mode 100644
index 00000000..e6c52ec6
--- /dev/null
+++ b/src/Titano.Uploader/Interop/TrayIcon.cs
@@ -0,0 +1,251 @@
+using System.Runtime.InteropServices;
+using System.Windows.Interop;
+using Titano.Core.Diagnostics;
+
+namespace Titano.Uploader.Interop;
+
+/// One entry of the tray menu; an id of 0 is a separator.
+public readonly record struct TrayMenuItem(int Id, string? Text);
+
+///
+/// Notification-area icon through Shell_NotifyIconW: the program icon from the executable's resources, a tooltip,
+/// a native context menu and balloons. A hidden window receives the callbacks and re-adds the icon after Explorer restarts.
+///
+public sealed unsafe partial class TrayIcon : IDisposable
+{
+ private const uint NimAdd = 0;
+ private const uint NimModify = 1;
+ private const uint NimDelete = 2;
+ private const uint NifMessage = 0x1;
+ private const uint NifIcon = 0x2;
+ private const uint NifTip = 0x4;
+ private const uint NifInfo = 0x10;
+ private const uint NiifUser = 0x4;
+ private const int CallbackMessage = 0x8000 + 1; // WM_APP + 1
+ private const int WmContextMenu = 0x007B;
+ private const int WmLButtonUp = 0x0202;
+ private const int WmLButtonDblClk = 0x0203;
+ private const int WmRButtonUp = 0x0205;
+ private const int NinBalloonUserClick = 0x0405;
+ private const uint MfString = 0x0;
+ private const uint MfSeparator = 0x800;
+ private const uint TpmRightButton = 0x2;
+ private const uint TpmNoNotify = 0x80;
+ private const uint TpmReturnCmd = 0x100;
+
+ private readonly HwndSource _window;
+ private readonly IntPtr _icon;
+ private readonly bool _ownsIcon;
+ private readonly uint _taskbarCreated;
+ private readonly Func> _menu;
+ private readonly Action _command;
+ private readonly Action _show;
+ private string _toolTip;
+ private bool _added;
+
+ /// Hover text (up to 127 characters).
+ /// Builds the context menu when it opens.
+ /// Runs a chosen menu id.
+ /// Left click or balloon click.
+ public TrayIcon(string toolTip, Func> menu, Action command, Action show)
+ {
+ _toolTip = toolTip;
+ _menu = menu;
+ _command = command;
+ _show = show;
+ // A hidden top-level window: message-only windows miss the TaskbarCreated broadcast.
+ _window = new HwndSource(new HwndSourceParameters("TitanoUploaderTray") { Width = 0, Height = 0, WindowStyle = 0 });
+ _window.AddHook(WndProc);
+ _taskbarCreated = RegisterWindowMessageW("TaskbarCreated");
+ (_icon, _ownsIcon) = LoadProgramIcon();
+ Add();
+ }
+
+ public void SetToolTip(string text)
+ {
+ _toolTip = text;
+ var data = NewData(NifTip);
+ Copy(_toolTip, data.Tip, 128);
+ Notify(NimModify, &data);
+ }
+
+ /// Shows a balloon (a toast on Windows 10/11) with the program icon.
+ public void ShowBalloon(string title, string text)
+ {
+ var data = NewData(NifInfo);
+ Copy(title, data.InfoTitle, 64);
+ Copy(text, data.Info, 256);
+ data.InfoFlags = NiifUser;
+ Notify(NimModify, &data);
+ }
+
+ public void Dispose()
+ {
+ if (_added)
+ {
+ var data = NewData(0);
+ Notify(NimDelete, &data);
+ _added = false;
+ }
+ if (_ownsIcon) DestroyIcon(_icon);
+ _window.Dispose();
+ }
+
+ private void Add()
+ {
+ var data = NewData(NifMessage | NifIcon | NifTip);
+ data.CallbackMessage = CallbackMessage;
+ data.Icon = _icon;
+ Copy(_toolTip, data.Tip, 128);
+ _added = Notify(NimAdd, &data);
+ }
+
+ private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
+ {
+ if (msg == CallbackMessage)
+ {
+ switch ((int)(lParam.ToInt64() & 0xFFFF))
+ {
+ case WmLButtonUp or WmLButtonDblClk or NinBalloonUserClick:
+ _show();
+ break;
+ case WmRButtonUp or WmContextMenu:
+ ShowMenu();
+ break;
+ }
+ handled = true;
+ }
+ else if (_taskbarCreated != 0 && msg == (int)_taskbarCreated)
+ {
+ Add();
+ }
+ return IntPtr.Zero;
+ }
+
+ private void ShowMenu()
+ {
+ var menu = CreatePopupMenu();
+ if (menu == IntPtr.Zero) return;
+ try
+ {
+ foreach (var item in _menu())
+ {
+ if (item.Id == 0 || item.Text is null) AppendMenuW(menu, MfSeparator, 0, null);
+ else AppendMenuW(menu, MfString, (nuint)item.Id, item.Text);
+ }
+ GetCursorPos(out var point);
+ // Without foreground the menu would not close when the user clicks elsewhere.
+ SetForegroundWindow(_window.Handle);
+ var chosen = TrackPopupMenuEx(menu, TpmReturnCmd | TpmRightButton | TpmNoNotify, point.X, point.Y, _window.Handle, IntPtr.Zero);
+ PostMessageW(_window.Handle, 0, IntPtr.Zero, IntPtr.Zero);
+ if (chosen != 0) _command(chosen);
+ }
+ finally
+ {
+ DestroyMenu(menu);
+ }
+ }
+
+ private NotifyIconData NewData(uint flags) => new()
+ {
+ Size = (uint)sizeof(NotifyIconData),
+ Window = _window.Handle,
+ Id = 1,
+ Flags = flags,
+ };
+
+ private static bool Notify(uint message, NotifyIconData* data)
+ {
+ if (Shell_NotifyIconW(message, data)) return true;
+ Log.Info("tray", $"Shell_NotifyIcon({message}) failed");
+ return false;
+ }
+
+ private static void Copy(string text, char* destination, int capacity)
+ {
+ var length = Math.Min(text.Length, capacity - 1);
+ text.AsSpan(0, length).CopyTo(new Span(destination, capacity));
+ destination[length] = '\0';
+ }
+
+ /// The generated titano-uploader icon embedded in the executable; the stock icon if it cannot be read.
+ private static (IntPtr Icon, bool Owned) LoadProgramIcon()
+ {
+ if (Environment.ProcessPath is { } exe)
+ {
+ IntPtr small;
+ if (ExtractIconExW(exe, 0, null, &small, 1) > 0 && small != IntPtr.Zero) return (small, true);
+ }
+ return (LoadIconW(IntPtr.Zero, 32512), false); // IDI_APPLICATION
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct NotifyIconData
+ {
+ public uint Size;
+ public IntPtr Window;
+ public uint Id;
+ public uint Flags;
+ public uint CallbackMessage;
+ public IntPtr Icon;
+ public fixed char Tip[128];
+ public uint State;
+ public uint StateMask;
+ public fixed char Info[256];
+ public uint TimeoutOrVersion;
+ public fixed char InfoTitle[64];
+ public uint InfoFlags;
+ public Guid Item;
+ public IntPtr BalloonIcon;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct Point
+ {
+ public int X;
+ public int Y;
+ }
+
+ [LibraryImport("shell32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static partial bool Shell_NotifyIconW(uint message, NotifyIconData* data);
+
+ [LibraryImport("shell32.dll", StringMarshalling = StringMarshalling.Utf16)]
+ private static partial uint ExtractIconExW(string file, int index, IntPtr* large, IntPtr* small, uint count);
+
+ [LibraryImport("user32.dll")]
+ private static partial IntPtr LoadIconW(IntPtr instance, nint name);
+
+ [LibraryImport("user32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static partial bool DestroyIcon(IntPtr icon);
+
+ [LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16)]
+ private static partial uint RegisterWindowMessageW(string name);
+
+ [LibraryImport("user32.dll")]
+ private static partial IntPtr CreatePopupMenu();
+
+ [LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static partial bool AppendMenuW(IntPtr menu, uint flags, nuint id, string? text);
+
+ [LibraryImport("user32.dll")]
+ private static partial int TrackPopupMenuEx(IntPtr menu, uint flags, int x, int y, IntPtr window, IntPtr parameters);
+
+ [LibraryImport("user32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static partial bool DestroyMenu(IntPtr menu);
+
+ [LibraryImport("user32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static partial bool GetCursorPos(out Point point);
+
+ [LibraryImport("user32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static partial bool SetForegroundWindow(IntPtr window);
+
+ [LibraryImport("user32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static partial bool PostMessageW(IntPtr window, int message, IntPtr wParam, IntPtr lParam);
+}
diff --git a/src/Titano.Uploader/Shell/ConfirmDialog.xaml b/src/Titano.Uploader/Shell/ConfirmDialog.xaml
new file mode 100644
index 00000000..d3eab487
--- /dev/null
+++ b/src/Titano.Uploader/Shell/ConfirmDialog.xaml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.Uploader/Shell/ConfirmDialog.xaml.cs b/src/Titano.Uploader/Shell/ConfirmDialog.xaml.cs
new file mode 100644
index 00000000..eb7d1102
--- /dev/null
+++ b/src/Titano.Uploader/Shell/ConfirmDialog.xaml.cs
@@ -0,0 +1,47 @@
+using System.Windows;
+using Titano.Ui.Controls;
+
+namespace Titano.Uploader.Shell;
+
+/// Texts of a .
+public sealed record ConfirmRequest
+{
+ public required string Heading { get; init; }
+ public required string Message { get; init; }
+
+ /// Monospaced detail (certificate fingerprint); null hides it.
+ public string? Detail { get; init; }
+
+ public string? DetailToolTip { get; init; }
+ public required string SafeText { get; init; }
+ public required string SafeToolTip { get; init; }
+ public required string ActionText { get; init; }
+ public required string ActionToolTip { get; init; }
+
+ /// Warning-outlined action (never a primary) for data-destroying choices.
+ public bool IsDestructive { get; init; }
+}
+
+/// Modal confirmation used for trusting a certificate and for destructive options (BRIEF §12.1).
+public sealed partial class ConfirmDialog : TitanoWindow
+{
+ private ConfirmDialog(ConfirmRequest request)
+ {
+ DataContext = request;
+ InitializeComponent();
+ Action.SetResourceReference(StyleProperty, request.IsDestructive ? "Button.Destructive" : "Button.Primary");
+ }
+
+ /// True when the user chose the action.
+ public static bool Ask(Window? owner, ConfirmRequest request)
+ {
+ var dialog = new ConfirmDialog(request);
+ if (owner is { IsVisible: true }) dialog.Owner = owner;
+ else dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
+ return dialog.ShowDialog() == true;
+ }
+
+ private void OnSafe(object sender, RoutedEventArgs e) => DialogResult = false;
+
+ private void OnAction(object sender, RoutedEventArgs e) => DialogResult = true;
+}
diff --git a/src/Titano.Uploader/Shell/ConnectViewModel.cs b/src/Titano.Uploader/Shell/ConnectViewModel.cs
new file mode 100644
index 00000000..8e483491
--- /dev/null
+++ b/src/Titano.Uploader/Shell/ConnectViewModel.cs
@@ -0,0 +1,113 @@
+using System.Collections.ObjectModel;
+using System.Windows.Input;
+using Titano.Core.Localization;
+using Titano.Ui.Mvvm;
+using Titano.Uploader.Server;
+
+namespace Titano.Uploader.Shell;
+
+///
+/// First-run and signed-out form: server address (with servers found on the LAN), user, password. A self-signed
+/// certificate is shown to the user once (trust on first use) before the password is sent.
+///
+public sealed class ConnectViewModel : ObservableObject
+{
+ private readonly IServerSession _session;
+ private readonly IUploaderDialogs _dialogs;
+ private string _address;
+ private string _username;
+ private string? _errorText;
+ private bool _isBusy;
+
+ public ConnectViewModel(IServerSession session, IUploaderDialogs dialogs, string? address, string? username)
+ {
+ _session = session;
+ _dialogs = dialogs;
+ _address = Display(address);
+ _username = username ?? string.Empty;
+ SignInCommand = new AsyncRelayCommand(SignInAsync);
+ UseServerCommand = new RelayCommand(p =>
+ {
+ if (p is DiscoveredServer s) Address = s.Address;
+ });
+ }
+
+ /// Servers that announced themselves on this network.
+ public ObservableCollection Discovered { get; } = [];
+
+ public ICommand SignInCommand { get; }
+ public ICommand UseServerCommand { get; }
+
+ public string Address
+ {
+ get => _address;
+ set => Set(ref _address, value);
+ }
+
+ public string Username
+ {
+ get => _username;
+ set => Set(ref _username, value);
+ }
+
+ /// Set from the view's PasswordBox; never stored.
+ public string Password { private get; set; } = string.Empty;
+
+ public bool IsBusy
+ {
+ get => _isBusy;
+ private set => Set(ref _isBusy, value);
+ }
+
+ /// One sentence saying what went wrong; the retry action sits next to it.
+ public string? ErrorText
+ {
+ get => _errorText;
+ private set => Set(ref _errorText, value);
+ }
+
+ /// Shows the server address without the trailing slash of the stored base URL.
+ public static string Display(string? address) => address?.TrimEnd('/') ?? string.Empty;
+
+ public void AddDiscovered(DiscoveredServer server)
+ {
+ if (Discovered.Any(d => d.Address == server.Address)) return;
+ Discovered.Add(server);
+ if (Address.Length == 0 && Discovered.Count == 1) Address = server.Address;
+ }
+
+ private async Task SignInAsync()
+ {
+ ErrorText = null;
+ IsBusy = true;
+ try
+ {
+ var (result, fingerprint) = await _session.SignInAsync(Address, Username.Trim(), Password, CancellationToken.None);
+ if (result == SignInResult.Untrusted && fingerprint is not null)
+ {
+ if (!_dialogs.ConfirmTrust(Display(Address), fingerprint))
+ {
+ ErrorText = Loc.L("Uploader.Connect.Error.Untrusted");
+ return;
+ }
+ _session.Trust(fingerprint);
+ (result, _) = await _session.SignInAsync(Address, Username.Trim(), Password, CancellationToken.None);
+ }
+ ErrorText = result switch
+ {
+ SignInResult.Success => null,
+ SignInResult.InvalidAddress => Loc.L("Uploader.Connect.Error.InvalidAddress"),
+ SignInResult.Unreachable => Loc.L("Uploader.Connect.Error.Unreachable"),
+ SignInResult.NotTitano => Loc.L("Uploader.Connect.Error.NotTitano"),
+ SignInResult.BadCredentials => Loc.L("Uploader.Connect.Error.BadCredentials"),
+ SignInResult.Untrusted => Loc.L("Uploader.Connect.Error.Untrusted"),
+ _ => Loc.L("Uploader.Connect.Error.Failed"),
+ };
+ if (result == SignInResult.Success) Address = Display(_session.Address);
+ }
+ finally
+ {
+ IsBusy = false;
+ }
+ }
+}
diff --git a/src/Titano.Uploader/Shell/Converters.cs b/src/Titano.Uploader/Shell/Converters.cs
new file mode 100644
index 00000000..792d1162
--- /dev/null
+++ b/src/Titano.Uploader/Shell/Converters.cs
@@ -0,0 +1,88 @@
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using Titano.Core.Localization;
+using Titano.Ui.Controls;
+using Titano.Uploader.Text;
+using Titano.Uploader.Uploads;
+
+namespace Titano.Uploader.Shell;
+
+/// → status glyph kind (DESIGN §4: colour always paired with a glyph and a word).
+public sealed class UploadStateKindConverter : IValueConverter
+{
+ public static UploadStateKindConverter Instance { get; } = new();
+
+ public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => value switch
+ {
+ UploadItemState.Hashing => StatusKind.Analysing,
+ UploadItemState.Uploading => StatusKind.Running,
+ UploadItemState.Verified => StatusKind.Done,
+ UploadItemState.Skipped => StatusKind.Synced,
+ UploadItemState.Failed => StatusKind.Failed,
+ _ => StatusKind.Queued,
+ };
+
+ public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
+}
+
+/// → its localized word.
+public sealed class UploadStateTextConverter : IValueConverter
+{
+ public static UploadStateTextConverter Instance { get; } = new();
+
+ public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => value switch
+ {
+ UploadItemState.Hashing => Loc.L("Uploader.State.Hashing"),
+ UploadItemState.Uploading => Loc.L("Uploader.State.Uploading"),
+ UploadItemState.Verified => Loc.L("Uploader.State.Verified"),
+ UploadItemState.Skipped => Loc.L("Uploader.State.Skipped"),
+ UploadItemState.Failed => Loc.L("Uploader.State.Failed"),
+ _ => Loc.L("Uploader.State.Queued"),
+ };
+
+ public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
+}
+
+/// (, detail) → one sentence for the tooltip of a failed item; null otherwise.
+public sealed class FailureTextConverter : IMultiValueConverter
+{
+ public static FailureTextConverter Instance { get; } = new();
+
+ public object? Convert(object?[] values, Type targetType, object? parameter, CultureInfo culture) =>
+ values is [UploadFailure failure, var detail, ..] ? Describe(failure, detail as string) : null;
+
+ public object[] ConvertBack(object? value, Type[] targetTypes, object? parameter, CultureInfo culture) => throw new NotSupportedException();
+
+ private static string? Describe(UploadFailure failure, string? detail) => failure switch
+ {
+ UploadFailure.FileMissing => Loc.L("Uploader.Failure.FileMissing"),
+ UploadFailure.FileUnreadable => Loc.L("Uploader.Failure.FileUnreadable"),
+ UploadFailure.FileChanged => Loc.L("Uploader.Failure.FileChanged"),
+ UploadFailure.ServerRejected => Loc.L("Uploader.Failure.ServerRejected", detail ?? string.Empty),
+ UploadFailure.Unexpected => Loc.L("Uploader.Failure.Unexpected"),
+ _ => null,
+ };
+}
+
+/// Visible only for ; hidden (keeping its space) otherwise so rows stay aligned.
+public sealed class FailedToVisibleConverter : IValueConverter
+{
+ public static FailedToVisibleConverter Instance { get; } = new();
+
+ public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
+ value is UploadItemState.Failed ? Visibility.Visible : Visibility.Hidden;
+
+ public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
+}
+
+/// Byte count → "25.4 MB".
+public sealed class SizeConverter : IValueConverter
+{
+ public static SizeConverter Instance { get; } = new();
+
+ public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
+ value is long bytes ? UploaderText.Bytes(bytes, Loc.Culture) : string.Empty;
+
+ public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
+}
diff --git a/src/Titano.Uploader/Shell/MainViewModel.cs b/src/Titano.Uploader/Shell/MainViewModel.cs
new file mode 100644
index 00000000..664639a0
--- /dev/null
+++ b/src/Titano.Uploader/Shell/MainViewModel.cs
@@ -0,0 +1,548 @@
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.IO;
+using System.Windows.Input;
+using System.Windows.Threading;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Ui.Controls;
+using Titano.Ui.Mvvm;
+using Titano.Uploader.Infrastructure;
+using Titano.Uploader.Server;
+using Titano.Uploader.Sources;
+using Titano.Uploader.Text;
+using Titano.Uploader.Uploads;
+using Titano.Uploader.Watching;
+
+namespace Titano.Uploader.Shell;
+
+/// A sequence offered as upload target.
+public sealed record SequenceOption(Guid Id, string Title);
+
+/// Everything the window works with; the capture mode passes design-time implementations.
+public sealed record UploaderServices(
+ UploaderSettings Settings,
+ Action SaveSettings,
+ IServerSession Session,
+ UploadQueue Queue,
+ IUploadEngine Engine,
+ IStartupRegistration Startup,
+ IUploaderDialogs Dialogs,
+ WatchFolderService Watch,
+ ProcessedFileMemory Memory,
+ string LogDirectory);
+
+/// State of the uploader window (BRIEF §15, mockup Uploader.html).
+public sealed class MainViewModel : LocalizedViewModel
+{
+ private readonly UploaderServices _s;
+ private readonly DispatcherTimer _refresh;
+ private UploadTargetMode _target;
+ private SequenceOption? _selectedSequence;
+ private bool _loadingSequences;
+ private string _newTitle;
+ private bool _isSettingsOpen;
+ private bool _startWithWindows;
+ private string _queueText = string.Empty;
+ private string _progressText = string.Empty;
+ private string? _currentFileText;
+ private double _progress;
+ private UploadItem? _currentItem;
+
+ public MainViewModel(UploaderServices services)
+ {
+ _s = services;
+ _target = services.Settings.Target;
+ _newTitle = services.Settings.NewSequenceTitle ?? string.Empty;
+ _startWithWindows = services.Startup.IsEnabled;
+ Connect = new ConnectViewModel(services.Session, services.Dialogs, services.Settings.ServerUrl, services.Settings.Username);
+ foreach (var w in services.Settings.WatchFolders) WatchFolders.Add(NewWatchFolder(w.Path, w.IntervalSeconds));
+
+ OpenSettingsCommand = new RelayCommand(() => IsSettingsOpen = true);
+ CloseSettingsCommand = new RelayCommand(() => IsSettingsOpen = false);
+ SignOutCommand = new AsyncRelayCommand(SignOutAsync);
+ BrowseFilesCommand = new AsyncRelayCommand(() => EnqueueAsync(_s.Dialogs.PickFiles()));
+ BrowseFolderCommand = new AsyncRelayCommand(() => _s.Dialogs.PickFolder() is { } folder ? EnqueueAsync([folder]) : Task.CompletedTask);
+ RefreshSequencesCommand = new AsyncRelayCommand(LoadSequencesAsync);
+ PauseCommand = new RelayCommand(TogglePause, () => HasItems);
+ StopCommand = new RelayCommand(() => _s.Engine.StopAndClear(), () => HasItems);
+ RetryItemCommand = new RelayCommand(p =>
+ {
+ if (p is UploadItem item) _s.Engine.Retry(item);
+ });
+ AddWatchFolderCommand = new RelayCommand(AddWatchFolder);
+ ToggleDeleteAfterUploadCommand = new RelayCommand(ToggleDeleteAfterUpload);
+
+ _s.Session.PropertyChanged += OnSessionChanged;
+ _s.Session.SessionEnded += OnSessionEnded;
+ _s.Engine.PropertyChanged += (_, _) => RefreshQueue();
+ _s.Engine.Drained += OnDrained;
+ _s.Queue.Items.CollectionChanged += (_, _) =>
+ {
+ OnPropertyChanged(nameof(HasItems));
+ CommandManager.InvalidateRequerySuggested();
+ };
+ _refresh = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(500) };
+ _refresh.Tick += (_, _) => RefreshQueue();
+ RefreshQueue();
+ }
+
+ /// Raised when the queue finished while work was done, with the number of files the server confirmed.
+ public event Action? UploadsCompleted;
+
+ public ConnectViewModel Connect { get; }
+
+ /// In-window notifications; the window forwards them to its .
+ public ObservableCollection PendingToasts { get; } = [];
+
+ public ICommand OpenSettingsCommand { get; }
+ public ICommand CloseSettingsCommand { get; }
+ public ICommand SignOutCommand { get; }
+ public ICommand BrowseFilesCommand { get; }
+ public ICommand BrowseFolderCommand { get; }
+ public ICommand RefreshSequencesCommand { get; }
+ public ICommand PauseCommand { get; }
+ public ICommand StopCommand { get; }
+ public ICommand RetryItemCommand { get; }
+ public ICommand AddWatchFolderCommand { get; }
+ public ICommand ToggleDeleteAfterUploadCommand { get; }
+
+ // ---------------- Header ----------------
+
+ public string ServerText => _s.Session.State == ConnectionState.NotConfigured
+ ? Loc.L("Uploader.Header.NotConnected")
+ : ConnectViewModel.Display(_s.Session.Address);
+
+ public string? UserText => _s.Session.State is ConnectionState.Connected or ConnectionState.Offline or ConnectionState.SigningIn ? _s.Session.Username : null;
+
+ public StatusKind ConnectionKind => _s.Session.State switch
+ {
+ ConnectionState.Connected => StatusKind.Online,
+ ConnectionState.SigningIn => StatusKind.Running,
+ _ => StatusKind.Offline,
+ };
+
+ /// Null on first run, when the server line already says "Not connected".
+ public string? ConnectionText => _s.Session.State switch
+ {
+ ConnectionState.Connected => Loc.L("Uploader.Status.Connected"),
+ ConnectionState.SigningIn => Loc.L("Uploader.Status.SigningIn"),
+ ConnectionState.Offline => Loc.L("Uploader.Status.Offline"),
+ ConnectionState.SignedOut => Loc.L("Uploader.Status.SignedOut"),
+ _ => null,
+ };
+
+ /// "1.9 TB free of 5 TB"; null without a quota.
+ public string? QuotaText => _s.Session.State == ConnectionState.Connected && _s.Session.QuotaBytes > 0
+ ? Loc.L("Uploader.Header.Quota", UploaderText.Bytes(Math.Max(0, _s.Session.QuotaBytes - _s.Session.UsedBytes), Loc.Culture), UploaderText.Bytes(_s.Session.QuotaBytes, Loc.Culture))
+ : null;
+
+ /// The sign-in form replaces the queue on first run and after signing out.
+ public bool IsConnectVisible => _s.Session.State is ConnectionState.NotConfigured or ConnectionState.SignedOut;
+
+ public bool IsSettingsOpen
+ {
+ get => _isSettingsOpen;
+ set => Set(ref _isSettingsOpen, value);
+ }
+
+ // ---------------- Target ----------------
+
+ public bool IsSessionsTarget
+ {
+ get => _target == UploadTargetMode.Sessions;
+ set => SetTarget(value, UploadTargetMode.Sessions);
+ }
+
+ public bool IsSequenceTarget
+ {
+ get => _target == UploadTargetMode.Sequence;
+ set => SetTarget(value, UploadTargetMode.Sequence);
+ }
+
+ public bool IsNewTarget
+ {
+ get => _target == UploadTargetMode.NewSequence;
+ set => SetTarget(value, UploadTargetMode.NewSequence);
+ }
+
+ public ObservableCollection Sequences { get; } = [];
+
+ public SequenceOption? SelectedSequence
+ {
+ get => _selectedSequence;
+ set
+ {
+ if (_loadingSequences || !Set(ref _selectedSequence, value)) return;
+ _s.Settings.TargetSequenceId = value?.Id;
+ _s.SaveSettings();
+ }
+ }
+
+ public string NewTitle
+ {
+ get => _newTitle;
+ set
+ {
+ if (!Set(ref _newTitle, value)) return;
+ _s.Settings.NewSequenceTitle = value;
+ _s.SaveSettings();
+ }
+ }
+
+ // ---------------- Queue ----------------
+
+ public ObservableCollection Items => _s.Queue.Items;
+
+ public bool HasItems => _s.Queue.Items.Count > 0;
+
+ /// "4,812 files · 96.2 GB · 38 MB/s · 41 min left".
+ public string QueueText
+ {
+ get => _queueText;
+ private set => Set(ref _queueText, value);
+ }
+
+ /// "2,214 of 4,812 sent · 2,201 verified by the server · 0 retries".
+ public string ProgressText
+ {
+ get => _progressText;
+ private set => Set(ref _progressText, value);
+ }
+
+ public string? CurrentFileText
+ {
+ get => _currentFileText;
+ private set => Set(ref _currentFileText, value);
+ }
+
+ public double Progress
+ {
+ get => _progress;
+ private set => Set(ref _progress, value);
+ }
+
+ /// The item being uploaded; the list keeps it in view.
+ public UploadItem? CurrentItem
+ {
+ get => _currentItem;
+ private set => Set(ref _currentItem, value);
+ }
+
+ public bool IsPaused => _s.Queue.IsPaused;
+
+ public string PauseToolTip => Loc.L(IsPaused ? "Tooltips.Uploader.Resume" : "Tooltips.Uploader.Pause");
+
+ /// Accessible name of the pause/resume button (also the tray menu entry).
+ public string PauseLabel => Loc.L(IsPaused ? "Uploader.Action.Resume" : "Uploader.Action.Pause");
+
+ /// Upload limit in MB/s; 0 = unlimited.
+ public int BandwidthLimit
+ {
+ get => _s.Session.BandwidthLimit;
+ set
+ {
+ var clamped = Math.Clamp(value, 0, 100_000);
+ if (clamped == _s.Session.BandwidthLimit) return;
+ _s.Session.BandwidthLimit = clamped;
+ _s.Settings.BandwidthLimit = clamped;
+ _s.SaveSettings();
+ OnPropertyChanged();
+ }
+ }
+
+ /// Tray hover text.
+ public string TrayText => Loc.L("Uploader.App.Title") + (HasItems ? " · " + QueueText : string.Empty);
+
+ // ---------------- Watch folders ----------------
+
+ public ObservableCollection WatchFolders { get; } = [];
+
+ // ---------------- Options ----------------
+
+ /// Turned on only through , which asks first.
+ public bool DeleteAfterUpload => _s.Settings.DeleteAfterUpload;
+
+ public bool StartWithWindows
+ {
+ get => _startWithWindows;
+ set
+ {
+ _s.Startup.SetEnabled(value);
+ // Read back: the registry may refuse the change.
+ _startWithWindows = _s.Startup.IsEnabled;
+ OnPropertyChanged();
+ }
+ }
+
+ public bool MinimizeToTray
+ {
+ get => _s.Settings.MinimizeToTray;
+ set
+ {
+ if (_s.Settings.MinimizeToTray == value) return;
+ _s.Settings.MinimizeToTray = value;
+ _s.SaveSettings();
+ OnPropertyChanged();
+ }
+ }
+
+ // ---------------- Actions ----------------
+
+ /// Starts the periodic refresh and, when signed in, loads the sequence list.
+ public void Start()
+ {
+ _refresh.Start();
+ if (_s.Session.State == ConnectionState.Connected) _ = LoadSequencesAsync();
+ }
+
+ /// Starts watching every configured folder.
+ public void StartWatching()
+ {
+ foreach (var w in WatchFolders) _s.Watch.Watch(w.Path, TimeSpan.FromSeconds(w.IntervalSeconds));
+ }
+
+ /// Adds the photos under (files, folders, card roots) to the queue.
+ public async Task EnqueueAsync(IReadOnlyList paths)
+ {
+ if (paths.Count == 0) return;
+ if (_target == UploadTargetMode.Sequence && SelectedSequence is null)
+ {
+ ShowToast(Loc.L("Uploader.Toast.ChooseSequence"));
+ return;
+ }
+ var found = await Task.Run(() => PhotoScanner.Scan(paths));
+ var fresh = found.Where(f => !_s.Queue.ContainsPath(f.Path)).ToList();
+ if (fresh.Count == 0)
+ {
+ ShowToast(Loc.L("Uploader.Toast.NothingFound"));
+ return;
+ }
+ var batch = new UploadBatch
+ {
+ Id = Guid.CreateVersion7(),
+ Mode = _target,
+ SequenceId = _target == UploadTargetMode.Sequence ? SelectedSequence?.Id : null,
+ Title = _target == UploadTargetMode.NewSequence ? NewTitle.Trim() : null,
+ };
+ var entries = _target == UploadTargetMode.Sessions
+ ? SessionEntries(fresh, null, null, out _)
+ : [.. fresh.OrderBy(f => f.CapturedAt).Select(f => new QueueEntry(f.Path, f.Size, f.ModifiedUtc, f.CapturedAt, null, null))];
+ var added = Add(batch, entries);
+ Log.Info("queue", $"{added} file(s) added from {paths.Count} path(s), target {_target}");
+ ShowToast(Loc.Plural("Uploader.Toast.Added", added));
+ }
+
+ /// Queues stable new photos of a watch folder; they join the folder's last session when close in time.
+ public void OnWatchFilesReady(string root, IReadOnlyList files)
+ {
+ var fresh = files.Where(f => !_s.Queue.ContainsPath(f.Path)).ToList();
+ if (fresh.Count == 0) return;
+ var entries = SessionEntries(fresh, root, _s.Memory.GetSession(root), out var last);
+ Add(new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions }, entries);
+ _s.Memory.SetSession(root, last);
+ }
+
+ public void OnWatchAvailabilityChanged(string root, bool available)
+ {
+ var folder = WatchFolders.FirstOrDefault(w => string.Equals(w.Path, root, StringComparison.OrdinalIgnoreCase));
+ if (folder is not null) folder.IsAvailable = available;
+ }
+
+ /// Errors are one sentence plus one action (BRIEF §0.2 rule 6).
+ public void ReportError(Exception ex)
+ {
+ Log.Error("ui", "Operation failed", ex);
+ ShowToast(Loc.L("Errors.Unexpected"), Loc.L("Common.OpenLogs"), Loc.L("Tooltips.Common.OpenLogs"), new RelayCommand(OpenLogs));
+ }
+
+ public void TogglePause()
+ {
+ if (_s.Queue.IsPaused) _s.Engine.Resume();
+ else _s.Engine.Pause();
+ RefreshQueue();
+ }
+
+ public override void Dispose()
+ {
+ _refresh.Stop();
+ _s.Session.PropertyChanged -= OnSessionChanged;
+ _s.Session.SessionEnded -= OnSessionEnded;
+ _s.Engine.Drained -= OnDrained;
+ base.Dispose();
+ }
+
+ private int Add(UploadBatch batch, IReadOnlyList entries)
+ {
+ // A new batch after a finished one starts a fresh count.
+ if (!_s.Queue.HasPending) _s.Queue.RemoveCompleted();
+ var added = _s.Queue.Add(batch, entries);
+ _s.Engine.Pump();
+ RefreshQueue();
+ return added;
+ }
+
+ /// Session keys per source folder (BRIEF §13 rules), entries in capture order.
+ private static List SessionEntries(IReadOnlyList files, string? watchRoot, SessionContinuation? previous, out SessionContinuation? last)
+ {
+ var entries = new List(files.Count);
+ last = previous;
+ foreach (var group in files.GroupBy(f => watchRoot ?? f.Root, StringComparer.OrdinalIgnoreCase))
+ {
+ var ordered = group.OrderBy(f => f.CapturedAt).ToList();
+ var assignment = SessionGrouper.Assign([.. ordered.Select(f => f.CapturedAt)], SessionGrouper.SourceTag(group.Key), watchRoot is null ? null : previous);
+ for (var i = 0; i < ordered.Count; i++)
+ {
+ var f = ordered[i];
+ entries.Add(new QueueEntry(f.Path, f.Size, f.ModifiedUtc, f.CapturedAt, assignment.Keys[i], watchRoot));
+ }
+ last = assignment.Last;
+ }
+ return entries;
+ }
+
+ /// Recomputes the queue line, progress and current file (also every 500 ms once started).
+ public void RefreshQueue()
+ {
+ var summary = QueueSummary.From(_s.Queue.Items);
+ var rate = _s.Engine.BytesPerSecond;
+ var activity = summary.Files == 0 ? QueueActivity.Idle : _s.Engine.Status switch
+ {
+ EngineStatus.Paused => QueueActivity.Paused,
+ EngineStatus.WaitingForServer => QueueActivity.WaitingForServer,
+ EngineStatus.Running => QueueActivity.Running,
+ _ => QueueActivity.Done,
+ };
+ QueueText = UploaderText.QueueLine(summary, activity, rate, RateMeter.TimeLeft(summary.RemainingBytes, rate), Loc.Culture);
+ ProgressText = summary.Files == 0 ? string.Empty : UploaderText.ProgressLine(summary, Loc.Culture);
+ Progress = summary.Progress;
+ CurrentFileText = summary.CurrentFile;
+ CurrentItem = _s.Queue.Items.FirstOrDefault(i => i.State == UploadItemState.Uploading) ?? _s.Queue.Items.FirstOrDefault(i => i.IsActive);
+ OnPropertyChanged(nameof(IsPaused));
+ OnPropertyChanged(nameof(PauseToolTip));
+ OnPropertyChanged(nameof(PauseLabel));
+ OnPropertyChanged(nameof(TrayText));
+ }
+
+ private void SetTarget(bool selected, UploadTargetMode mode)
+ {
+ if (!selected || _target == mode) return;
+ _target = mode;
+ _s.Settings.Target = mode;
+ _s.SaveSettings();
+ OnPropertyChanged(nameof(IsSessionsTarget));
+ OnPropertyChanged(nameof(IsSequenceTarget));
+ OnPropertyChanged(nameof(IsNewTarget));
+ if (mode == UploadTargetMode.Sequence && Sequences.Count == 0) _ = LoadSequencesAsync();
+ }
+
+ private async Task LoadSequencesAsync()
+ {
+ var list = await _s.Session.ListSequencesAsync(CancellationToken.None);
+ if (list.Count == 0 && Sequences.Count > 0) return;
+ _loadingSequences = true;
+ try
+ {
+ Sequences.Clear();
+ foreach (var s in list.OrderBy(s => s.DisplayTitle, StringComparer.CurrentCultureIgnoreCase)) Sequences.Add(new SequenceOption(s.Id, s.DisplayTitle));
+ }
+ finally
+ {
+ _loadingSequences = false;
+ }
+ _selectedSequence = Sequences.FirstOrDefault(s => s.Id == _s.Settings.TargetSequenceId);
+ OnPropertyChanged(nameof(SelectedSequence));
+ }
+
+ private async Task SignOutAsync()
+ {
+ IsSettingsOpen = false;
+ await _s.Session.SignOutAsync();
+ }
+
+ private void ToggleDeleteAfterUpload()
+ {
+ var enable = !_s.Settings.DeleteAfterUpload;
+ if (enable && !_s.Dialogs.ConfirmDeleteAfterUpload())
+ {
+ // The check box toggled itself; put it back.
+ OnPropertyChanged(nameof(DeleteAfterUpload));
+ return;
+ }
+ _s.Settings.DeleteAfterUpload = enable;
+ _s.SaveSettings();
+ Log.Info("settings", "Delete after verified upload " + (enable ? "on" : "off"));
+ OnPropertyChanged(nameof(DeleteAfterUpload));
+ }
+
+ private void AddWatchFolder()
+ {
+ if (_s.Dialogs.PickWatchFolder() is not { } path) return;
+ if (WatchFolders.Any(w => string.Equals(w.Path, path, StringComparison.OrdinalIgnoreCase))) return;
+ var interval = (int)WatchFolderService.DefaultInterval(path).TotalSeconds;
+ _s.Settings.WatchFolders.Add(new UploaderSettings.WatchFolderSettings { Path = path, IntervalSeconds = interval });
+ _s.SaveSettings();
+ WatchFolders.Add(NewWatchFolder(path, interval));
+ _s.Watch.Watch(path, TimeSpan.FromSeconds(interval));
+ }
+
+ private WatchFolderViewModel NewWatchFolder(string path, int intervalSeconds) =>
+ new(path, intervalSeconds, WatchFolderService.IsNetworkPath(path), SetWatchInterval, RemoveWatchFolder);
+
+ private void SetWatchInterval(WatchFolderViewModel folder, int seconds)
+ {
+ folder.IntervalSeconds = seconds;
+ foreach (var w in _s.Settings.WatchFolders.Where(w => string.Equals(w.Path, folder.Path, StringComparison.OrdinalIgnoreCase))) w.IntervalSeconds = seconds;
+ _s.SaveSettings();
+ _s.Watch.Watch(folder.Path, TimeSpan.FromSeconds(seconds));
+ }
+
+ private void RemoveWatchFolder(WatchFolderViewModel folder)
+ {
+ _s.Watch.Stop(folder.Path);
+ _s.Memory.RemoveFolder(folder.Path);
+ _s.Settings.WatchFolders.RemoveAll(w => string.Equals(w.Path, folder.Path, StringComparison.OrdinalIgnoreCase));
+ _s.SaveSettings();
+ WatchFolders.Remove(folder);
+ }
+
+ private void OnSessionChanged(object? sender, PropertyChangedEventArgs e)
+ {
+ OnPropertyChanged(nameof(ServerText));
+ OnPropertyChanged(nameof(UserText));
+ OnPropertyChanged(nameof(ConnectionKind));
+ OnPropertyChanged(nameof(ConnectionText));
+ OnPropertyChanged(nameof(QuotaText));
+ OnPropertyChanged(nameof(IsConnectVisible));
+ OnPropertyChanged(nameof(BandwidthLimit));
+ if (e.PropertyName != nameof(IServerSession.State)) return;
+ if (_s.Session.State == ConnectionState.Connected) _ = LoadSequencesAsync();
+ if (IsConnectVisible)
+ {
+ Connect.Address = ConnectViewModel.Display(_s.Session.Address);
+ Connect.Username = _s.Session.Username ?? Connect.Username;
+ }
+ CommandManager.InvalidateRequerySuggested();
+ }
+
+ private void OnSessionEnded(object? sender, ServerProblem problem) =>
+ ShowToast(Loc.L(problem == ServerProblem.CertificateChanged ? "Uploader.Toast.CertificateChanged" : "Uploader.Toast.SignedOut"));
+
+ private void OnDrained(object? sender, EventArgs e)
+ {
+ // The queue restarts its count with each new batch, so every confirmed item belongs to this run.
+ var confirmed = _s.Queue.Items.Count(i => i.IsDone);
+ RefreshQueue();
+ _ = _s.Session.RefreshAsync();
+ if (confirmed > 0) UploadsCompleted?.Invoke(confirmed);
+ }
+
+ private void ShowToast(string title, string? actionText = null, string? actionToolTip = null, ICommand? action = null) =>
+ PendingToasts.Add(new Toast { Title = title, ActionText = actionText, ActionToolTip = actionToolTip, ActionCommand = action });
+
+ private void OpenLogs()
+ {
+ if (Directory.Exists(_s.LogDirectory)) Process.Start(new ProcessStartInfo(_s.LogDirectory) { UseShellExecute = true, Verb = "explore" });
+ }
+}
diff --git a/src/Titano.Uploader/Shell/MainWindow.xaml b/src/Titano.Uploader/Shell/MainWindow.xaml
new file mode 100644
index 00000000..9c9cebb2
--- /dev/null
+++ b/src/Titano.Uploader/Shell/MainWindow.xaml
@@ -0,0 +1,429 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.Uploader/Shell/MainWindow.xaml.cs b/src/Titano.Uploader/Shell/MainWindow.xaml.cs
new file mode 100644
index 00000000..3d69f4e4
--- /dev/null
+++ b/src/Titano.Uploader/Shell/MainWindow.xaml.cs
@@ -0,0 +1,139 @@
+using System.Collections.Specialized;
+using System.ComponentModel;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Shapes;
+using Titano.Ui.Controls;
+using Titano.Uploader.Infrastructure;
+
+namespace Titano.Uploader.Shell;
+
+/// The uploader's single window (mockup Uploader.html).
+public sealed partial class MainWindow : TitanoWindow
+{
+ private readonly MainViewModel _vm;
+ private readonly UploaderSettings _settings;
+
+ public MainWindow(MainViewModel vm, UploaderSettings settings)
+ {
+ _vm = vm;
+ _settings = settings;
+ DataContext = vm;
+ InitializeComponent();
+ vm.PendingToasts.CollectionChanged += OnToastRequested;
+ vm.PropertyChanged += OnViewModelChanged;
+ PreviewKeyDown += OnPreviewKeyDown;
+ RestorePlacement();
+ }
+
+ /// Remembers size and position (also when the window only hides to the tray).
+ public void SavePlacement()
+ {
+ var b = RestoreBounds;
+ if (b.IsEmpty || b.Width < MinWidth || b.Height < MinHeight) return;
+ _settings.Window = new UploaderSettings.WindowPlacement { Left = b.Left, Top = b.Top, Width = b.Width, Height = b.Height };
+ }
+
+ protected override void OnDragOver(DragEventArgs e)
+ {
+ var accepted = CanDrop(e);
+ e.Effects = accepted ? DragDropEffects.Copy : DragDropEffects.None;
+ SetDropHighlight(accepted);
+ e.Handled = true;
+ }
+
+ protected override void OnDragLeave(DragEventArgs e) => SetDropHighlight(false);
+
+ protected override void OnDrop(DragEventArgs e)
+ {
+ SetDropHighlight(false);
+ if (!CanDrop(e) || e.Data.GetData(DataFormats.FileDrop) is not string[] paths) return;
+ e.Handled = true;
+ _ = EnqueueAsync(paths);
+ }
+
+ private async Task EnqueueAsync(IReadOnlyList paths)
+ {
+ try
+ {
+ await _vm.EnqueueAsync(paths);
+ }
+ catch (Exception ex)
+ {
+ // UI boundary: a drop must never take the window down.
+ _vm.ReportError(ex);
+ }
+ }
+
+ private bool CanDrop(DragEventArgs e) => !_vm.IsConnectVisible && e.Data.GetDataPresent(DataFormats.FileDrop);
+
+ private void SetDropHighlight(bool on)
+ {
+ DropBorder.SetResourceReference(Shape.StrokeProperty, on ? "Brush.Accent" : "Brush.Stroke");
+ if (on) DropBorder.SetResourceReference(Shape.FillProperty, "Brush.AccentSubtle");
+ else DropBorder.Fill = Brushes.Transparent;
+ }
+
+ private void OnBrowseClick(object sender, RoutedEventArgs e) => OpenMenu((Button)sender);
+
+ private void OnWatchChipClick(object sender, RoutedEventArgs e) => OpenMenu((Button)sender);
+
+ /// Opens a button's menu under it on a normal click.
+ private static void OpenMenu(Button button)
+ {
+ if (button.ContextMenu is not { } menu) return;
+ menu.DataContext = button.DataContext;
+ menu.PlacementTarget = button;
+ menu.Placement = PlacementMode.Bottom;
+ menu.IsOpen = true;
+ }
+
+ private void OnSequencesDropDownOpened(object? sender, EventArgs e) => _vm.RefreshSequencesCommand.Execute(null);
+
+ private void OnPasswordChanged(object sender, RoutedEventArgs e) => _vm.Connect.Password = Password.Password;
+
+ /// DESIGN §4 inputs: Enter commits, Esc reverts; Esc also closes the settings panel.
+ private void OnPreviewKeyDown(object sender, KeyEventArgs e)
+ {
+ if (e.OriginalSource is TextBox box && (e.Key is Key.Enter or Key.Escape) && box.GetBindingExpression(TextBox.TextProperty) is { } binding)
+ {
+ if (e.Key == Key.Enter) binding.UpdateSource();
+ else binding.UpdateTarget();
+ if (e.Key == Key.Escape) e.Handled = true;
+ return;
+ }
+ if (e.Key == Key.Escape && _vm.IsSettingsOpen)
+ {
+ _vm.IsSettingsOpen = false;
+ e.Handled = true;
+ }
+ }
+
+ private void OnViewModelChanged(object? sender, PropertyChangedEventArgs e)
+ {
+ if (e.PropertyName == nameof(MainViewModel.CurrentItem) && _vm.CurrentItem is { } item) ItemList.ScrollIntoView(item);
+ if (e.PropertyName == nameof(MainViewModel.IsConnectVisible) && _vm.IsConnectVisible) Password.Clear();
+ }
+
+ private void OnToastRequested(object? sender, NotifyCollectionChangedEventArgs e)
+ {
+ if (e.Action != NotifyCollectionChangedAction.Add || e.NewItems is null) return;
+ foreach (Toast t in e.NewItems) Toasts.Show(t);
+ Dispatcher.BeginInvoke(() => _vm.PendingToasts.Clear());
+ }
+
+ private void RestorePlacement()
+ {
+ if (_settings.Window is not { } p || p.Width < MinWidth || p.Height < MinHeight) return;
+ var screen = new Rect(SystemParameters.VirtualScreenLeft, SystemParameters.VirtualScreenTop, SystemParameters.VirtualScreenWidth, SystemParameters.VirtualScreenHeight);
+ if (!screen.IntersectsWith(new Rect(p.Left, p.Top, p.Width, p.Height))) return;
+ WindowStartupLocation = WindowStartupLocation.Manual;
+ Left = p.Left;
+ Top = p.Top;
+ Width = p.Width;
+ Height = p.Height;
+ }
+}
diff --git a/src/Titano.Uploader/Shell/ScreenCapture.cs b/src/Titano.Uploader/Shell/ScreenCapture.cs
new file mode 100644
index 00000000..9a061f74
--- /dev/null
+++ b/src/Titano.Uploader/Shell/ScreenCapture.cs
@@ -0,0 +1,79 @@
+using System.IO;
+using System.Windows;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Threading;
+using Titano.Core.Diagnostics;
+using Titano.Ui.Theming;
+using Titano.Uploader.DesignTime;
+
+namespace Titano.Uploader.Shell;
+
+///
+/// Titano.Uploader.exe --capture <dir>: renders the window at 760×560 in the dark and light themes —
+/// first run (connect), queue running, settings panel — from , then exits.
+///
+public static class ScreenCapture
+{
+ public static void Run(MainWindow window, MainViewModel vm, SampleData sample, string directory)
+ {
+ Directory.CreateDirectory(directory);
+ window.WindowStartupLocation = WindowStartupLocation.Manual;
+ window.Left = -20000;
+ window.Top = -20000;
+ window.Width = 760;
+ window.Height = 560;
+ window.ShowActivated = false;
+ window.ShowInTaskbar = false;
+ window.Show();
+
+ window.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, () =>
+ {
+ try
+ {
+ foreach (var theme in new[] { AppTheme.Dark, AppTheme.Light })
+ {
+ var suffix = theme.ToString().ToLowerInvariant();
+ ThemeManager.Apply(theme);
+ sample.ShowConnect();
+ Save(window, Path.Combine(directory, $"uploader-connect-{suffix}.png"));
+ sample.ShowQueue();
+ Save(window, Path.Combine(directory, $"uploader-queue-{suffix}.png"));
+ vm.IsSettingsOpen = true;
+ Save(window, Path.Combine(directory, $"uploader-settings-{suffix}.png"));
+ vm.IsSettingsOpen = false;
+ }
+ Log.Info("capture", $"Screenshots written to {Path.GetFullPath(directory)}");
+ }
+ catch (Exception ex)
+ {
+ Log.Error("capture", "Capture failed", ex);
+ Environment.ExitCode = 1;
+ }
+ finally
+ {
+ Application.Current.Shutdown();
+ }
+ });
+ }
+
+ private static void Save(Window window, string path)
+ {
+ // Let bindings, templates and deferred layout complete.
+ window.UpdateLayout();
+ window.Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, () => { });
+ window.UpdateLayout();
+ if (VisualTreeHelper.GetChildrenCount(window) == 0) return;
+ var root = (FrameworkElement)VisualTreeHelper.GetChild(window, 0);
+ var dpi = VisualTreeHelper.GetDpi(window);
+ var width = (int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX);
+ var height = (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY);
+ if (width <= 0 || height <= 0) return;
+ var bitmap = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
+ bitmap.Render(root);
+ var encoder = new PngBitmapEncoder();
+ encoder.Frames.Add(BitmapFrame.Create(bitmap));
+ using var stream = File.Create(path);
+ encoder.Save(stream);
+ }
+}
diff --git a/src/Titano.Uploader/Shell/UploaderDialogs.cs b/src/Titano.Uploader/Shell/UploaderDialogs.cs
new file mode 100644
index 00000000..711abada
--- /dev/null
+++ b/src/Titano.Uploader/Shell/UploaderDialogs.cs
@@ -0,0 +1,80 @@
+using System.Windows;
+using System.Windows.Interop;
+using Titano.Core.Imaging;
+using Titano.Core.Localization;
+using Titano.Uploader.Interop;
+
+namespace Titano.Uploader.Shell;
+
+/// Pickers and confirmations the view model asks for.
+public interface IUploaderDialogs
+{
+ /// Photos to add; empty when cancelled.
+ IReadOnlyList PickFiles();
+
+ /// A folder or card root to add; null when cancelled.
+ string? PickFolder();
+
+ /// A folder to watch; null when cancelled.
+ string? PickWatchFolder();
+
+ /// Trust-on-first-use: shows the certificate fingerprint; true when the user trusts it.
+ bool ConfirmTrust(string address, string fingerprint);
+
+ /// Destructive confirmation for "Delete after upload"; true when the user turns it on.
+ bool ConfirmDeleteAfterUpload();
+}
+
+/// Window-owned implementation: shell Open dialogs and .
+public sealed class UploaderDialogs : IUploaderDialogs
+{
+ /// Owner of the dialogs; set once the main window exists.
+ public Window? Owner { get; set; }
+
+ private IntPtr OwnerHandle => Owner is null ? IntPtr.Zero : new WindowInteropHelper(Owner).Handle;
+
+ public IReadOnlyList PickFiles()
+ {
+ var photos = string.Join(';', ImageFormatInfo.Known.SelectMany(f => f.Extensions).Select(e => "*." + e));
+ return FileDialogs.PickFiles(OwnerHandle, Loc.L("Uploader.Browse.FilesTitle"),
+ [
+ new FileFilter(Loc.L("Uploader.Browse.Photos"), photos),
+ new FileFilter(Loc.L("Uploader.Browse.AllFiles"), "*.*"),
+ ]);
+ }
+
+ public string? PickFolder() => FileDialogs.PickFolder(OwnerHandle, Loc.L("Uploader.Browse.FolderTitle"));
+
+ public string? PickWatchFolder() => FileDialogs.PickFolder(OwnerHandle, Loc.L("Uploader.Browse.WatchTitle"));
+
+ public bool ConfirmTrust(string address, string fingerprint) => ConfirmDialog.Ask(Owner, new ConfirmRequest
+ {
+ Heading = Loc.L("Uploader.Trust.Title"),
+ Message = Loc.L("Uploader.Trust.Message"),
+ Detail = address + "\n" + FormatFingerprint(fingerprint),
+ DetailToolTip = Loc.L("Tooltips.Uploader.Fingerprint"),
+ SafeText = Loc.L("Uploader.Trust.Cancel"),
+ SafeToolTip = Loc.L("Tooltips.Uploader.CancelTrust"),
+ ActionText = Loc.L("Uploader.Trust.Accept"),
+ ActionToolTip = Loc.L("Tooltips.Uploader.Trust"),
+ IsDestructive = false,
+ });
+
+ public bool ConfirmDeleteAfterUpload() => ConfirmDialog.Ask(Owner, new ConfirmRequest
+ {
+ Heading = Loc.L("Uploader.Delete.Title"),
+ Message = Loc.L("Uploader.Delete.Message"),
+ SafeText = Loc.L("Uploader.Delete.Keep"),
+ SafeToolTip = Loc.L("Tooltips.Uploader.KeepFiles"),
+ ActionText = Loc.L("Uploader.Delete.Accept"),
+ ActionToolTip = Loc.L("Tooltips.Uploader.ConfirmDelete"),
+ IsDestructive = true,
+ });
+
+ /// Splits the 32-byte SHA-256 fingerprint into two readable lines of 16 bytes.
+ public static string FormatFingerprint(string fingerprint)
+ {
+ var bytes = fingerprint.Split(':');
+ return bytes.Length <= 16 ? fingerprint : string.Join(':', bytes.Take(16)) + "\n" + string.Join(':', bytes.Skip(16));
+ }
+}
diff --git a/src/Titano.Uploader/Shell/WatchFolderViewModel.cs b/src/Titano.Uploader/Shell/WatchFolderViewModel.cs
new file mode 100644
index 00000000..7950b876
--- /dev/null
+++ b/src/Titano.Uploader/Shell/WatchFolderViewModel.cs
@@ -0,0 +1,78 @@
+using System.Windows.Input;
+using Titano.Core.Localization;
+using Titano.Ui.Mvvm;
+using Titano.Uploader.Text;
+
+namespace Titano.Uploader.Shell;
+
+/// An entry of a watch folder chip's menu: an interval choice, a separator (no text) or "Remove".
+public sealed record WatchMenuOption(string? Text, string? ToolTip, ICommand? Command, bool IsChecked)
+{
+ public bool IsSeparator => Text is null;
+}
+
+/// One watch folder chip: path, interval, reachability.
+public sealed class WatchFolderViewModel : ObservableObject
+{
+ /// Intervals offered in the chip menu.
+ public static readonly int[] IntervalChoices = [30, 60, 300, 900];
+
+ private readonly Action _setInterval;
+ private readonly Action _remove;
+ private int _intervalSeconds;
+ private bool? _isAvailable;
+
+ public WatchFolderViewModel(string path, int intervalSeconds, bool isNetwork, Action setInterval, Action remove)
+ {
+ Path = path;
+ IsNetwork = isNetwork;
+ _intervalSeconds = intervalSeconds;
+ _setInterval = setInterval;
+ _remove = remove;
+ }
+
+ public string Path { get; }
+ public bool IsNetwork { get; }
+
+ public int IntervalSeconds
+ {
+ get => _intervalSeconds;
+ set
+ {
+ if (!Set(ref _intervalSeconds, value)) return;
+ OnPropertyChanged(nameof(Text));
+ OnPropertyChanged(nameof(ToolTip));
+ OnPropertyChanged(nameof(MenuOptions));
+ }
+ }
+
+ /// Null until the first check finished.
+ public bool? IsAvailable
+ {
+ get => _isAvailable;
+ set
+ {
+ if (Set(ref _isAvailable, value)) OnPropertyChanged(nameof(ToolTip));
+ }
+ }
+
+ /// "D:\Cam\Roof · every 1 min".
+ public string Text => Loc.L("Uploader.Watch.Chip", Path, Interval(IntervalSeconds));
+
+ public string ToolTip => IsAvailable == false ? Loc.L("Tooltips.Uploader.WatchFolderMissing", Interval(IntervalSeconds))
+ : IsNetwork ? Loc.L("Tooltips.Uploader.WatchFolderNetwork", Interval(IntervalSeconds))
+ : Loc.L("Tooltips.Uploader.WatchFolder", Interval(IntervalSeconds));
+
+ public IReadOnlyList MenuOptions =>
+ [
+ .. IntervalChoices.Select(s => new WatchMenuOption(
+ Loc.L("Uploader.Watch.Every", Interval(s)),
+ Loc.L("Tooltips.Uploader.WatchInterval"),
+ new RelayCommand(() => _setInterval(this, s)),
+ s == IntervalSeconds)),
+ new WatchMenuOption(null, null, null, false),
+ new WatchMenuOption(Loc.L("Uploader.Watch.Remove"), Loc.L("Tooltips.Uploader.RemoveWatchFolder"), new RelayCommand(() => _remove(this)), false),
+ ];
+
+ private static string Interval(int seconds) => UploaderText.Duration(TimeSpan.FromSeconds(seconds), Loc.Culture);
+}