feat(uploader): uploader window, dialogs, tray icon and screenshot mode

Single 760x560 window after the Uploader mockup: header with server,
user, connection glyph and quota; first-run connect form with LAN
servers and a TOFU fingerprint dialog; drop zone with an IFileOpenDialog
browse menu (files or folder/card); target choice; queue line,
pause/stop and MB/s limit; progress and per-file states with retry;
watch-folder chips; options, with a destructive confirmation before
"Delete after upload"; in-window settings panel. Shell_NotifyIcon tray
icon (program icon, Show/Pause/Exit menu, balloon on completion), app
bootstrap with logging, language, theme, single instance hand-over, and
--capture rendering connect/queue/settings in dark and light from a
design-time sample provider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 10:28:03 +00:00
1 parent 42d96c962d
commit 192fc7dcb3
15 files changed
+2572 -1

No files matched your search

+548
View File
@@ -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;
/// <summary>A sequence offered as upload target.</summary>
public sealed record SequenceOption(Guid Id, string Title);
/// <summary>Everything the window works with; the capture mode passes design-time implementations.</summary>
public sealed record UploaderServices(
UploaderSettings Settings,
Action SaveSettings,
IServerSession Session,
UploadQueue Queue,
IUploadEngine Engine,
IStartupRegistration Startup,
IUploaderDialogs Dialogs,
WatchFolderService Watch,
ProcessedFileMemory Memory,
string LogDirectory);
/// <summary>State of the uploader window (BRIEF §15, mockup Uploader.html).</summary>
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();
}
/// <summary>Raised when the queue finished while work was done, with the number of files the server confirmed.</summary>
public event Action<int>? UploadsCompleted;
public ConnectViewModel Connect { get; }
/// <summary>In-window notifications; the window forwards them to its <see cref="ToastHost"/>.</summary>
public ObservableCollection<Toast> 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,
};
/// <summary>Null on first run, when the server line already says "Not connected".</summary>
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,
};
/// <summary>"1.9 TB free of 5 TB"; null without a quota.</summary>
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;
/// <summary>The sign-in form replaces the queue on first run and after signing out.</summary>
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<SequenceOption> 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<UploadItem> Items => _s.Queue.Items;
public bool HasItems => _s.Queue.Items.Count > 0;
/// <summary>"4,812 files · 96.2 GB · 38 MB/s · 41 min left".</summary>
public string QueueText
{
get => _queueText;
private set => Set(ref _queueText, value);
}
/// <summary>"2,214 of 4,812 sent · 2,201 verified by the server · 0 retries".</summary>
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);
}
/// <summary>The item being uploaded; the list keeps it in view.</summary>
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");
/// <summary>Accessible name of the pause/resume button (also the tray menu entry).</summary>
public string PauseLabel => Loc.L(IsPaused ? "Uploader.Action.Resume" : "Uploader.Action.Pause");
/// <summary>Upload limit in MB/s; 0 = unlimited.</summary>
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();
}
}
/// <summary>Tray hover text.</summary>
public string TrayText => Loc.L("Uploader.App.Title") + (HasItems ? " · " + QueueText : string.Empty);
// ---------------- Watch folders ----------------
public ObservableCollection<WatchFolderViewModel> WatchFolders { get; } = [];
// ---------------- Options ----------------
/// <summary>Turned on only through <see cref="ToggleDeleteAfterUploadCommand"/>, which asks first.</summary>
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 ----------------
/// <summary>Starts the periodic refresh and, when signed in, loads the sequence list.</summary>
public void Start()
{
_refresh.Start();
if (_s.Session.State == ConnectionState.Connected) _ = LoadSequencesAsync();
}
/// <summary>Starts watching every configured folder.</summary>
public void StartWatching()
{
foreach (var w in WatchFolders) _s.Watch.Watch(w.Path, TimeSpan.FromSeconds(w.IntervalSeconds));
}
/// <summary>Adds the photos under <paramref name="paths"/> (files, folders, card roots) to the queue.</summary>
public async Task EnqueueAsync(IReadOnlyList<string> 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));
}
/// <summary>Queues stable new photos of a watch folder; they join the folder's last session when close in time.</summary>
public void OnWatchFilesReady(string root, IReadOnlyList<SourceFile> 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;
}
/// <summary>Errors are one sentence plus one action (BRIEF §0.2 rule 6).</summary>
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<QueueEntry> 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;
}
/// <summary>Session keys per source folder (BRIEF §13 rules), entries in capture order.</summary>
private static List<QueueEntry> SessionEntries(IReadOnlyList<SourceFile> files, string? watchRoot, SessionContinuation? previous, out SessionContinuation? last)
{
var entries = new List<QueueEntry>(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;
}
/// <summary>Recomputes the queue line, progress and current file (also every 500 ms once started).</summary>
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" });
}
}