merge: Uploader and installer after the visual, accessibility and RTL review

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-06 07:44:44 +00:00
commit 62c98224c0
37 files changed
+1597 -232

No files matched your search

+2 -1
View File
@@ -99,7 +99,8 @@ jobs:
timeout-minutes: 10
run: |
set +e
for exe in src/Titano.App/bin/Release/net10.0-windows/Titano.exe src/Titano.Uploader/bin/Release/net10.0-windows/Titano.Uploader.exe; do
for exe in src/Titano.App/bin/Release/net10.0-windows/Titano.exe src/Titano.Uploader/bin/Release/net10.0-windows/Titano.Uploader.exe \
src/Titano.Setup/bin/Release/net10.0-windows/Titano.Setup.exe; do
name=$(basename "$exe" .exe)
before=$(ls out/screenshots/*.png 2>/dev/null | wc -l)
"$exe" --capture out/screenshots 2> "out/capture-$name.log" &
+6
View File
@@ -13,4 +13,10 @@
<data name="Common.Open" xml:space="preserve"><value>Open</value></data>
<data name="Common.OpenLogs" xml:space="preserve"><value>Open logs</value></data>
<data name="Common.Percent" xml:space="preserve"><value>{0} %</value></data>
<data name="Common.Size.B" xml:space="preserve"><value>{0} B</value></data>
<data name="Common.Size.GB" xml:space="preserve"><value>{0} GB</value></data>
<data name="Common.Size.KB" xml:space="preserve"><value>{0} KB</value></data>
<data name="Common.Size.MB" xml:space="preserve"><value>{0} MB</value></data>
<data name="Common.Size.PB" xml:space="preserve"><value>{0} PB</value></data>
<data name="Common.Size.TB" xml:space="preserve"><value>{0} TB</value></data>
</root>
+3
View File
@@ -43,6 +43,9 @@
<data name="Setup.Scope.AllUsers" xml:space="preserve"><value>All users</value></data>
<data name="Setup.Scope.JustMe" xml:space="preserve"><value>Just me</value></data>
<data name="Setup.Space.Required" xml:space="preserve"><value>{0} needed</value></data>
<data name="Setup.Uninstall.More.one" xml:space="preserve"><value>{0:N0} more item</value></data>
<data name="Setup.Uninstall.More.other" xml:space="preserve"><value>{0:N0} more items</value></data>
<data name="Setup.Uninstall.Plan" xml:space="preserve"><value>Deletes {0}</value></data>
<data name="Setup.Uninstall.RemoveData" xml:space="preserve"><value>Remove my data</value></data>
<data name="Setup.Window.Title" xml:space="preserve"><value>{0} Setup</value></data>
<data name="Setup.Window.Uninstall" xml:space="preserve"><value>Remove {0}</value></data>
+6 -1
View File
@@ -479,6 +479,7 @@
<data name="Tooltips.Setup.AllUsers" xml:space="preserve"><value>Install in Program Files for every account · asks for administrator approval</value></data>
<data name="Tooltips.Setup.Back" xml:space="preserve"><value>Return to the options without changing anything</value></data>
<data name="Tooltips.Setup.Browse" xml:space="preserve"><value>Choose the installation folder</value></data>
<data name="Tooltips.Setup.Cancel" xml:space="preserve"><value>Close setup without changing anything</value></data>
<data name="Tooltips.Setup.Close" xml:space="preserve"><value>Close setup</value></data>
<data name="Tooltips.Setup.ClosePrograms" xml:space="preserve"><value>Ask the running programs to close · each one handles its unsaved work</value></data>
<data name="Tooltips.Setup.Component" xml:space="preserve"><value>Install this program</value></data>
@@ -495,7 +496,8 @@
<data name="Tooltips.Setup.Launch" xml:space="preserve"><value>Open the program when setup finishes</value></data>
<data name="Tooltips.Setup.LaunchNow" xml:space="preserve"><value>Open the installed program</value></data>
<data name="Tooltips.Setup.Locked" xml:space="preserve"><value>Already installed here · uninstall it first to change folder or scope</value></data>
<data name="Tooltips.Setup.RemoveData" xml:space="preserve"><value>Also delete database, settings and logs in %LOCALAPPDATA%\Titano · photos in archives are not touched</value></data>
<data name="Tooltips.Setup.NoComponent" xml:space="preserve"><value>Select at least one program to install</value></data>
<data name="Tooltips.Setup.RemoveData" xml:space="preserve"><value>Also delete %LOCALAPPDATA%\Titano: database, backups, cache, settings, logs, the uploader queue and sign-in · photos in archives are kept</value></data>
<data name="Tooltips.Setup.Retry" xml:space="preserve"><value>Run the same step again</value></data>
<data name="Tooltips.Setup.StartMenu" xml:space="preserve"><value>Add the programs to the Start menu</value></data>
<data name="Tooltips.Setup.Uninstall" xml:space="preserve"><value>Remove programs, shortcuts and file types · your data is kept unless selected</value></data>
@@ -521,13 +523,16 @@
<data name="Tooltips.Uploader.NewTitle" xml:space="preserve"><value>Title of the new sequence; leave empty to let the server name it</value></data>
<data name="Tooltips.Uploader.Password" xml:space="preserve"><value>Your password; only a sign-in token is kept, encrypted for your Windows account</value></data>
<data name="Tooltips.Uploader.Pause" xml:space="preserve"><value>Pause; the queue survives a restart</value></data>
<data name="Tooltips.Uploader.QueueEmpty" xml:space="preserve"><value>Nothing queued</value></data>
<data name="Tooltips.Uploader.Quota" xml:space="preserve"><value>Space left in your quota on the server</value></data>
<data name="Tooltips.Uploader.RemoveWatchFolder" xml:space="preserve"><value>Stop watching this folder; files already uploaded stay on the server</value></data>
<data name="Tooltips.Uploader.Resume" xml:space="preserve"><value>Resume uploading</value></data>
<data name="Tooltips.Uploader.Retry" xml:space="preserve"><value>Try again</value></data>
<data name="Tooltips.Uploader.RetryItem" xml:space="preserve"><value>Try this file again now</value></data>
<data name="Tooltips.Uploader.SequenceDisabled" xml:space="preserve"><value>Select Sequence to choose one</value></data>
<data name="Tooltips.Uploader.ServerAddress" xml:space="preserve"><value>Address of the Titano Server, such as https://nas.local:8443</value></data>
<data name="Tooltips.Uploader.Settings" xml:space="preserve"><value>Server, sign in, bandwidth, startup, tray</value></data>
<data name="Tooltips.Uploader.ShowFailed" xml:space="preserve"><value>Show the first file that failed · press Enter on it to try again</value></data>
<data name="Tooltips.Uploader.SignIn" xml:space="preserve"><value>Check the server certificate and sign in</value></data>
<data name="Tooltips.Uploader.SignOut" xml:space="preserve"><value>Sign out and forget the saved token</value></data>
<data name="Tooltips.Uploader.StartWithWindows" xml:space="preserve"><value>Run when you sign in to Windows</value></data>
+4 -1
View File
@@ -45,7 +45,7 @@
<data name="Uploader.Header.NotConnected" xml:space="preserve"><value>Not connected</value></data>
<data name="Uploader.Header.Quota" xml:space="preserve"><value>{0} free of {1}</value></data>
<data name="Uploader.Limit.Label" xml:space="preserve"><value>Limit</value></data>
<data name="Uploader.Limit.Unit" xml:space="preserve"><value>MB/s</value><comment>invariant</comment></data>
<data name="Uploader.Limit.Unit" xml:space="preserve"><value>MB/s</value></data>
<data name="Uploader.Options.DeleteSource" xml:space="preserve"><value>Delete after upload</value></data>
<data name="Uploader.Options.MinimizeToTray" xml:space="preserve"><value>Minimise to tray</value></data>
<data name="Uploader.Options.StartWithWindows" xml:space="preserve"><value>Start with Windows</value></data>
@@ -60,7 +60,9 @@
<data name="Uploader.Queue.Files.other" xml:space="preserve"><value>{0:N0} files</value></data>
<data name="Uploader.Queue.Label" xml:space="preserve"><value>Queue</value></data>
<data name="Uploader.Queue.Left" xml:space="preserve"><value>{0} left</value></data>
<data name="Uploader.Queue.List" xml:space="preserve"><value>Files in queue</value></data>
<data name="Uploader.Queue.Paused" xml:space="preserve"><value>Paused</value></data>
<data name="Uploader.Queue.Progress" xml:space="preserve"><value>Upload progress</value></data>
<data name="Uploader.Queue.Waiting" xml:space="preserve"><value>Waiting for server</value></data>
<data name="Uploader.Settings.Bandwidth" xml:space="preserve"><value>Bandwidth</value></data>
<data name="Uploader.Settings.Files" xml:space="preserve"><value>Files</value></data>
@@ -102,6 +104,7 @@
<data name="Uploader.Unit.PerSecond" xml:space="preserve"><value>{0}/s</value></data>
<data name="Uploader.Watch.Chip" xml:space="preserve"><value>{0} · every {1}</value></data>
<data name="Uploader.Watch.Every" xml:space="preserve"><value>Every {0}</value></data>
<data name="Uploader.Watch.Interval" xml:space="preserve"><value>every {0}</value></data>
<data name="Uploader.Watch.Label" xml:space="preserve"><value>Watch folders</value></data>
<data name="Uploader.Watch.Remove" xml:space="preserve"><value>Remove</value></data>
</root>
+6
View File
@@ -13,4 +13,10 @@
<data name="Common.Open" xml:space="preserve"><value>Apri</value></data>
<data name="Common.OpenLogs" xml:space="preserve"><value>Apri log</value></data>
<data name="Common.Percent" xml:space="preserve"><value>{0}%</value></data>
<data name="Common.Size.B" xml:space="preserve"><value>{0} byte</value></data>
<data name="Common.Size.GB" xml:space="preserve"><value>{0} GB</value></data>
<data name="Common.Size.KB" xml:space="preserve"><value>{0} KB</value></data>
<data name="Common.Size.MB" xml:space="preserve"><value>{0} MB</value></data>
<data name="Common.Size.PB" xml:space="preserve"><value>{0} PB</value></data>
<data name="Common.Size.TB" xml:space="preserve"><value>{0} TB</value></data>
</root>
+3
View File
@@ -43,6 +43,9 @@
<data name="Setup.Scope.AllUsers" xml:space="preserve"><value>Tutti gli utenti</value></data>
<data name="Setup.Scope.JustMe" xml:space="preserve"><value>Solo per me</value></data>
<data name="Setup.Space.Required" xml:space="preserve"><value>{0} necessari</value></data>
<data name="Setup.Uninstall.More.one" xml:space="preserve"><value>{0:N0} altro elemento</value></data>
<data name="Setup.Uninstall.More.other" xml:space="preserve"><value>altri {0:N0} elementi</value></data>
<data name="Setup.Uninstall.Plan" xml:space="preserve"><value>Elimina {0}</value></data>
<data name="Setup.Uninstall.RemoveData" xml:space="preserve"><value>Rimuovi i miei dati</value></data>
<data name="Setup.Window.Title" xml:space="preserve"><value>Installazione di {0}</value></data>
<data name="Setup.Window.Uninstall" xml:space="preserve"><value>Rimozione di {0}</value></data>
+6 -1
View File
@@ -479,6 +479,7 @@
<data name="Tooltips.Setup.AllUsers" xml:space="preserve"><value>Installa in Programmi per tutti gli account · chiede l'autorizzazione di amministratore</value></data>
<data name="Tooltips.Setup.Back" xml:space="preserve"><value>Torna alle opzioni senza modificare nulla</value></data>
<data name="Tooltips.Setup.Browse" xml:space="preserve"><value>Scegli la cartella di installazione</value></data>
<data name="Tooltips.Setup.Cancel" xml:space="preserve"><value>Chiudi l'installazione senza modificare nulla</value></data>
<data name="Tooltips.Setup.Close" xml:space="preserve"><value>Chiudi l'installazione</value></data>
<data name="Tooltips.Setup.ClosePrograms" xml:space="preserve"><value>Chiedi ai programmi aperti di chiudersi · ognuno gestisce il lavoro non salvato</value></data>
<data name="Tooltips.Setup.Component" xml:space="preserve"><value>Installa questo programma</value></data>
@@ -495,7 +496,8 @@
<data name="Tooltips.Setup.Launch" xml:space="preserve"><value>Apri il programma al termine dell'installazione</value></data>
<data name="Tooltips.Setup.LaunchNow" xml:space="preserve"><value>Apri il programma installato</value></data>
<data name="Tooltips.Setup.Locked" xml:space="preserve"><value>Già installato qui · disinstallalo prima per cambiare cartella o ambito</value></data>
<data name="Tooltips.Setup.RemoveData" xml:space="preserve"><value>Elimina anche database, impostazioni e log in %LOCALAPPDATA%\Titano · le foto negli archivi non vengono toccate</value></data>
<data name="Tooltips.Setup.NoComponent" xml:space="preserve"><value>Seleziona almeno un programma da installare</value></data>
<data name="Tooltips.Setup.RemoveData" xml:space="preserve"><value>Elimina anche %LOCALAPPDATA%\Titano: database, backup, cache, impostazioni, log, coda e accesso dell'uploader · le foto negli archivi restano</value></data>
<data name="Tooltips.Setup.Retry" xml:space="preserve"><value>Esegui di nuovo lo stesso passaggio</value></data>
<data name="Tooltips.Setup.StartMenu" xml:space="preserve"><value>Aggiungi i programmi al menu Start</value></data>
<data name="Tooltips.Setup.Uninstall" xml:space="preserve"><value>Rimuovi programmi, collegamenti e tipi di file · i dati restano salvo diversa scelta</value></data>
@@ -521,13 +523,16 @@
<data name="Tooltips.Uploader.NewTitle" xml:space="preserve"><value>Titolo della nuova sequenza; lascialo vuoto per farlo scegliere al server</value></data>
<data name="Tooltips.Uploader.Password" xml:space="preserve"><value>La tua password; viene conservato solo un token di accesso, cifrato per il tuo account Windows</value></data>
<data name="Tooltips.Uploader.Pause" xml:space="preserve"><value>Metti in pausa; la coda sopravvive a un riavvio</value></data>
<data name="Tooltips.Uploader.QueueEmpty" xml:space="preserve"><value>Nessun file in coda</value></data>
<data name="Tooltips.Uploader.Quota" xml:space="preserve"><value>Spazio rimasto nella tua quota sul server</value></data>
<data name="Tooltips.Uploader.RemoveWatchFolder" xml:space="preserve"><value>Smetti di controllare questa cartella; i file già inviati restano sul server</value></data>
<data name="Tooltips.Uploader.Resume" xml:space="preserve"><value>Riprendi l'invio</value></data>
<data name="Tooltips.Uploader.Retry" xml:space="preserve"><value>Riprova</value></data>
<data name="Tooltips.Uploader.RetryItem" xml:space="preserve"><value>Riprova subito questo file</value></data>
<data name="Tooltips.Uploader.SequenceDisabled" xml:space="preserve"><value>Seleziona Sequenza per sceglierne una</value></data>
<data name="Tooltips.Uploader.ServerAddress" xml:space="preserve"><value>Indirizzo del Titano Server, ad esempio https://nas.local:8443</value></data>
<data name="Tooltips.Uploader.Settings" xml:space="preserve"><value>Server, accesso, banda, avvio, area di notifica</value></data>
<data name="Tooltips.Uploader.ShowFailed" xml:space="preserve"><value>Mostra il primo file non riuscito · premi Invio per riprovarlo</value></data>
<data name="Tooltips.Uploader.SignIn" xml:space="preserve"><value>Controlla il certificato del server e accedi</value></data>
<data name="Tooltips.Uploader.SignOut" xml:space="preserve"><value>Esci e dimentica il token salvato</value></data>
<data name="Tooltips.Uploader.StartWithWindows" xml:space="preserve"><value>Avvia quando accedi a Windows</value></data>
+4
View File
@@ -43,6 +43,7 @@
<data name="Uploader.Header.NotConnected" xml:space="preserve"><value>Non connesso</value></data>
<data name="Uploader.Header.Quota" xml:space="preserve"><value>{0} liberi su {1}</value></data>
<data name="Uploader.Limit.Label" xml:space="preserve"><value>Limite</value></data>
<data name="Uploader.Limit.Unit" xml:space="preserve"><value>MB/s</value></data>
<data name="Uploader.Options.DeleteSource" xml:space="preserve"><value>Elimina dopo l'invio</value></data>
<data name="Uploader.Options.MinimizeToTray" xml:space="preserve"><value>Riduci nell'area notifiche</value></data>
<data name="Uploader.Options.StartWithWindows" xml:space="preserve"><value>Avvia con Windows</value></data>
@@ -57,7 +58,9 @@
<data name="Uploader.Queue.Files.other" xml:space="preserve"><value>{0:N0} file</value></data>
<data name="Uploader.Queue.Label" xml:space="preserve"><value>Coda</value></data>
<data name="Uploader.Queue.Left" xml:space="preserve"><value>mancano {0}</value></data>
<data name="Uploader.Queue.List" xml:space="preserve"><value>File in coda</value></data>
<data name="Uploader.Queue.Paused" xml:space="preserve"><value>In pausa</value></data>
<data name="Uploader.Queue.Progress" xml:space="preserve"><value>Avanzamento caricamento</value></data>
<data name="Uploader.Queue.Waiting" xml:space="preserve"><value>In attesa del server</value></data>
<data name="Uploader.Settings.Bandwidth" xml:space="preserve"><value>Banda</value></data>
<data name="Uploader.Settings.Files" xml:space="preserve"><value>File</value></data>
@@ -99,6 +102,7 @@
<data name="Uploader.Unit.PerSecond" xml:space="preserve"><value>{0}/s</value></data>
<data name="Uploader.Watch.Chip" xml:space="preserve"><value>{0} · ogni {1}</value></data>
<data name="Uploader.Watch.Every" xml:space="preserve"><value>Ogni {0}</value></data>
<data name="Uploader.Watch.Interval" xml:space="preserve"><value>ogni {0}</value></data>
<data name="Uploader.Watch.Label" xml:space="preserve"><value>Cartelle controllate</value></data>
<data name="Uploader.Watch.Remove" xml:space="preserve"><value>Rimuovi</value></data>
</root>
+42
View File
@@ -0,0 +1,42 @@
using System.IO;
namespace Titano.Setup.Engine;
/// <summary>One top-level file or folder of the user data folder and the bytes it holds.</summary>
internal sealed record UserDataEntry(string Name, long Bytes);
/// <summary>
/// Dry run of "Remove my data" (BRIEF §0.2 rule 8: a destructive operation shows its plan first): every top-level
/// entry of the user data folder with its size, largest first. Links are not followed, as the deletion does not
/// follow them either.
/// </summary>
internal sealed record UserDataPlan(IReadOnlyList<UserDataEntry> Entries)
{
private static readonly EnumerationOptions TopLevel = new() { IgnoreInaccessible = true, AttributesToSkip = 0 };
private static readonly EnumerationOptions Contents = new()
{
RecurseSubdirectories = true,
IgnoreInaccessible = true,
AttributesToSkip = FileAttributes.ReparsePoint,
};
public long TotalBytes => Entries.Sum(e => e.Bytes);
/// <summary>Measures <paramref name="folder"/>; empty when it does not exist. Reads sizes only, changes nothing.</summary>
public static UserDataPlan Measure(string folder)
{
var root = new DirectoryInfo(folder);
if (!root.Exists) return new UserDataPlan([]);
var entries = root.EnumerateFileSystemInfos("*", TopLevel).Select(e => new UserDataEntry(e.Name, SizeOf(e)));
return new UserDataPlan([.. entries.OrderByDescending(e => e.Bytes).ThenBy(e => e.Name, StringComparer.OrdinalIgnoreCase)]);
}
private static long SizeOf(FileSystemInfo entry) => entry switch
{
_ when entry.Attributes.HasFlag(FileAttributes.ReparsePoint) => 0,
DirectoryInfo folder => folder.EnumerateFiles("*", Contents).Sum(f => f.Length),
FileInfo file => file.Length,
_ => 0,
};
}
+2
View File
@@ -18,6 +18,8 @@ internal static class Program
using var log = new FileLogSink(SetupPaths.LogDirectory, "setup");
Log.SetSink(log);
Log.Info("setup", $"Titano.Setup {typeof(Program).Assembly.GetName().Version} {string.Join(' ', args)}");
// The screenshot mode of every Titano program (CI); it builds its own sample installer.
if (args is ["--capture", var captureDirectory]) return Views.SetupCapture.Run(captureDirectory);
SetupArguments arguments;
try
+4 -4
View File
@@ -30,20 +30,20 @@ internal sealed class ComponentOption(PayloadComponent component, bool selected,
/// <summary>Language offered in the picker.</summary>
internal sealed record LanguageOption(string Code, string Name);
/// <summary>Decimal byte sizes as Explorer shows them for drives ("1.5 MB").</summary>
/// <summary>Decimal byte sizes as Explorer shows them for drives ("1.5 MB"), units in the UI language ("1,5 Mo").</summary>
internal static class ByteSize
{
private static readonly string[] Units = ["B", "KB", "MB", "GB", "TB"];
private static readonly string[] Formats = ["Common.Size.B", "Common.Size.KB", "Common.Size.MB", "Common.Size.GB", "Common.Size.TB"];
public static string Format(long bytes)
{
double value = bytes;
var unit = 0;
while (value >= 1000 && unit < Units.Length - 1)
while (value >= 1000 && unit < Formats.Length - 1)
{
value /= 1000;
unit++;
}
return value.ToString(unit == 0 || value >= 100 ? "0" : "0.#", Loc.Culture) + " " + Units[unit];
return Loc.L(Formats[unit], value.ToString(unit == 0 || value >= 100 ? "0" : "0.#", Loc.Culture));
}
}
+196
View File
@@ -0,0 +1,196 @@
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.Core.Packaging;
using Titano.Setup.Cli;
using Titano.Setup.Engine;
using Titano.Ui.Theming;
namespace Titano.Setup.Views;
/// <summary>
/// <c>Titano.Setup.exe --capture &lt;dir&gt;</c>: renders the setup window in every stage (install options, programs
/// running, installing, installed, failed, uninstall with its data plan) in the dark and light themes, then in
/// Arabic (right to left, dark), from a small sample installer built in a temporary folder. Nothing is installed,
/// removed or registered.
/// </summary>
internal static class SetupCapture
{
private const string Product = "Titano";
private static readonly (string Name, SetupStage Stage)[] InstallStages =
[
("install", SetupStage.Options),
("running", SetupStage.Confirm),
("installing", SetupStage.Working),
("installed", SetupStage.Done),
("failed", SetupStage.Failed),
];
/// <summary>What a user data folder typically holds; eight entries, so the plan also shows its "more" line.</summary>
private static readonly UserDataPlan SamplePlan = new(
[
new UserDataEntry("cache", 2_140_000_000),
new UserDataEntry("backups", 1_210_000_000),
new UserDataEntry("titano.db", 41_000_000),
new UserDataEntry("logs", 12_400_000),
new UserDataEntry("titano.db-wal", 4_200_000),
new UserDataEntry("uploader-queue.json", 1_900_000),
new UserDataEntry("settings.json", 3_100),
new UserDataEntry("uploader.json", 1_200),
]);
/// <summary>Returns the process exit code: 0 when every screen was written.</summary>
public static int Run(string directory)
{
var work = Directory.CreateTempSubdirectory("titano-setup-capture-").FullName;
try
{
var installer = WriteSampleInstaller(work);
var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
ThemeManager.Initialize(app, AppTheme.Dark);
var code = 0;
app.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, () =>
{
try
{
Directory.CreateDirectory(directory);
CaptureLanguage(installer, directory, "en", string.Empty, [AppTheme.Dark, AppTheme.Light]);
// Mirrored layout with paths and file names kept left to right (BRIEF §16).
CaptureLanguage(installer, directory, "ar", "-ar", [AppTheme.Dark]);
Log.Info("capture", $"Screenshots written to {Path.GetFullPath(directory)}");
}
catch (Exception ex)
{
Log.Error("capture", "Capture failed", ex);
code = 1;
}
finally
{
app.Shutdown();
}
});
app.Run();
return code;
}
finally
{
try
{
Directory.Delete(work, recursive: true);
}
catch (IOException ex)
{
// The sample installer may still be mapped; the OS temp cleanup takes it.
Log.Warning("capture", $"Sample installer folder '{work}' not removed", ex);
}
}
}
private static void CaptureLanguage(string installer, string directory, string language, string suffix, IReadOnlyList<AppTheme> themes)
{
Program.ApplyLanguage(language);
using var payload = PayloadReader.Open(installer);
using var install = SetupViewModel.ForInstall(new SetupArguments(), payload);
using var uninstall = SetupViewModel.ForUninstall(new SetupArguments(), new InstalledProduct(
SetupPaths.DefaultDirectory(InstallScope.CurrentUser, Product), new InstallLog { Product = Product, Version = "1.0.0" }));
foreach (var theme in themes)
{
ThemeManager.Apply(theme);
var name = suffix + "-" + theme.ToString().ToLowerInvariant();
Capture(install, [.. InstallStages.Select(s => ("setup-" + s.Name + name, s.Stage, (UserDataPlan?)null))], directory);
Capture(uninstall, [("setup-uninstall" + name, SetupStage.Options, SamplePlan)], directory);
}
}
/// <summary>One window per model; each screen puts the model in its stage and is saved as <c>&lt;file&gt;.png</c>.</summary>
private static void Capture(SetupViewModel model, IReadOnlyList<(string File, SetupStage Stage, UserDataPlan? Plan)> screens, string directory)
{
var window = new SetupWindow(model)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
try
{
foreach (var (file, stage, plan) in screens)
{
model.Preview(stage, plan);
Save(window, Path.Combine(directory, file + ".png"));
}
}
finally
{
window.Close();
}
}
/// <summary>Three components of random (incompressible) bytes, with the shortcuts the real installer carries.</summary>
private static string WriteSampleInstaller(string work)
{
var random = new Random(1);
var components = new (string Id, string DisplayName, bool Selected, string Program, int Bytes)[]
{
("Titano", "Titano", true, "Titano.exe", 2_400_000),
("Uploader", "Titano Uploader", true, "Titano.Uploader.exe", 900_000),
("Server", "Titano Server", false, "Titano.Server.exe", 1_600_000),
};
foreach (var c in components)
{
var folder = Directory.CreateDirectory(Path.Combine(work, c.Id)).FullName;
var bytes = new byte[c.Bytes];
random.NextBytes(bytes);
File.WriteAllBytes(Path.Combine(folder, c.Program), bytes);
}
var installer = Path.Combine(work, "setup.exe");
PayloadWriter.Write(Environment.ProcessPath ?? throw new InvalidOperationException("No process path."), new PayloadSource
{
Product = Product,
Version = "1.0.0",
Components = [.. components.Select(c => new PayloadComponentSource(c.Id, c.DisplayName, c.Selected, Path.Combine(work, c.Id)))],
Shortcuts = [.. components.Select(c => new PayloadShortcut { Component = c.Id, Name = c.DisplayName, Target = c.Program, StartMenu = true, Desktop = c.Id != "Server" })],
}, installer);
return installer;
}
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(window.FlowDirection == FlowDirection.RightToLeft ? Mirrored(root) : root);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using var stream = File.Create(path);
encoder.Save(stream);
}
/// <summary>
/// A right-to-left window is mirrored by a transform on the window itself, which rendering its content alone
/// would leave out: draw the content through that mirror.
/// </summary>
private static DrawingVisual Mirrored(FrameworkElement root)
{
var size = new Rect(0, 0, root.ActualWidth, root.ActualHeight);
var visual = new DrawingVisual();
using var dc = visual.RenderOpen();
dc.PushTransform(new MatrixTransform(-1, 0, 0, 1, size.Width, 0));
dc.DrawRectangle(new VisualBrush(root) { Stretch = Stretch.Fill, ViewboxUnits = BrushMappingMode.Absolute, Viewbox = size }, null, size);
return visual;
}
}
+93 -3
View File
@@ -11,6 +11,9 @@ using Titano.Ui.Mvvm;
namespace Titano.Setup.Views;
/// <summary>A line of the "Remove my data" dry run: a file or folder name (or "3 more items") and its size.</summary>
internal sealed record DataPlanRow(string Name, string Size, bool IsFileName);
/// <summary>What the setup screen currently shows.</summary>
internal enum SetupStage
{
@@ -28,6 +31,10 @@ internal enum SetupStage
internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
{
private const string FallbackProduct = "Titano";
/// <summary>Largest entries listed in the data plan; the rest are summed in one line.</summary>
private const int PlanRows = 6;
private readonly SetupArguments _arguments;
private readonly PayloadReader? _payload;
private readonly InstallEngine? _engine;
@@ -42,6 +49,8 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
private bool _startMenu;
private bool _launchAfter;
private bool _removeUserData;
private UserDataPlan? _dataPlan;
private bool _measuring;
private bool _closeConfirmed;
private double _progress;
private bool _indeterminate;
@@ -197,6 +206,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
if (!Set(ref _directory, value ?? string.Empty)) return;
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Directory)));
OnPropertyChanged(nameof(DirectoryToolTip));
OnPropertyChanged(nameof(InstallToolTip));
}
}
@@ -206,6 +216,9 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
? Loc.L("Tooltips.Setup.Locked")
: IsDirectoryValid ? Loc.L("Tooltips.Setup.Folder") : Loc.L("Tooltips.Setup.FolderInvalid");
/// <summary>Browse is disabled when upgrading; its tooltip then says why (DESIGN §4).</summary>
public string BrowseToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.Browse") : Loc.L("Tooltips.Setup.Locked");
public string JustMeToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.JustMe") : Loc.L("Tooltips.Setup.Locked");
public string AllUsersToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.AllUsers") : Loc.L("Tooltips.Setup.Locked");
@@ -232,16 +245,46 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
public bool HasLaunchOption => _engine?.LaunchTarget(SelectedComponents) is not null;
public string InstallText => CanChangeLocation ? Loc.L("Setup.Action.Install") : Loc.L("Setup.Action.Update");
public string InstallToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.Install") : Loc.L("Tooltips.Setup.Update");
private bool CanStart => IsOptions && (IsUninstall || (IsInstall && IsDirectoryValid && Components.Any(c => c.IsSelected)));
/// <summary>What Install does, or why it is disabled: no program selected, or a folder it cannot use.</summary>
public string InstallToolTip => !Components.Any(c => c.IsSelected) ? Loc.L("Tooltips.Setup.NoComponent")
: !IsDirectoryValid ? Loc.L("Tooltips.Setup.FolderInvalid")
: CanChangeLocation ? Loc.L("Tooltips.Setup.Install") : Loc.L("Tooltips.Setup.Update");
/// <summary>Removing user data waits for its plan, so the user has seen what goes before choosing Uninstall.</summary>
private bool CanStart => IsOptions && (IsUninstall ? !_removeUserData || _dataPlan is not null : IsInstall && IsDirectoryValid && Components.Any(c => c.IsSelected));
// ---- Uninstall options ----
/// <summary>Checking it measures the user data folder; the plan is shown before Uninstall can run.</summary>
public bool RemoveUserData
{
get => _removeUserData;
set => Set(ref _removeUserData, value);
set
{
if (!Set(ref _removeUserData, value)) return;
OnPropertyChanged(nameof(IsDataPlanVisible));
CommandManager.InvalidateRequerySuggested();
if (value && _dataPlan is null) _ = MeasureUserDataAsync();
}
}
public bool IsDataPlanVisible => _removeUserData && _dataPlan is not null;
/// <summary>"Deletes 3.4 GB" over the plan's lines.</summary>
public string DataPlanText => _dataPlan is null ? string.Empty : Loc.L("Setup.Uninstall.Plan", ByteSize.Format(_dataPlan.TotalBytes));
/// <summary>The largest entries of the user data folder, then one line for the rest.</summary>
public IReadOnlyList<DataPlanRow> DataPlanRows
{
get
{
if (_dataPlan is null) return [];
var rows = _dataPlan.Entries.Take(PlanRows).Select(e => new DataPlanRow(e.Name, ByteSize.Format(e.Bytes), IsFileName: true)).ToList();
var rest = _dataPlan.Entries.Skip(PlanRows).ToList();
if (rest.Count > 0) rows.Add(new DataPlanRow(Loc.Plural("Setup.Uninstall.More", rest.Count), ByteSize.Format(rest.Sum(e => e.Bytes)), IsFileName: false));
return rows;
}
}
// ---- Confirm, progress, outcome ----
@@ -294,6 +337,12 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
public bool CanRetry => IsFailed && _failure is not (SetupExitCode.PayloadInvalid or SetupExitCode.NotInstalled or SetupExitCode.InvalidArguments);
/// <summary>Done or failed: Close is offered (and Esc closes).</summary>
public bool IsFinished => IsDone || IsFailed;
/// <summary>Close is the default action when there is nothing to launch or retry.</summary>
public bool IsCloseDefault => IsFinished && !CanLaunch && !CanRetry;
public ICommand PrimaryCommand { get; }
public ICommand BrowseCommand { get; }
public ICommand CloseProgramsCommand { get; }
@@ -313,6 +362,23 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
if (_arguments.Elevated && IsInstall && CanStart) Start(InstallAsync);
}
/// <summary>
/// For <c>--capture</c> only: shows <paramref name="stage"/> with sample progress and outcome (a program to
/// launch, a full disk) and, when given, a data plan with "Remove my data" checked. Nothing runs.
/// </summary>
internal void Preview(SetupStage stage, UserDataPlan? dataPlan = null)
{
_runningPrograms = "Titano Uploader";
_progress = 0.46;
_indeterminate = false;
_progressFile = @"Titano\Titano.Core.dll";
_launchProgram = IsInstall ? "Titano.exe" : null;
_failure = SetupExitCode.DiskFull;
_dataPlan = dataPlan;
_removeUserData = dataPlan is not null;
Stage = stage;
}
public override void Dispose()
{
foreach (var c in Components) c.Dispose();
@@ -498,9 +564,33 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
Stage = SetupStage.Failed;
}
private async Task MeasureUserDataAsync()
{
if (_measuring) return;
_measuring = true;
try
{
_dataPlan = await Task.Run(() => UserDataPlan.Measure(SetupPaths.UserData));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("setup", $"User data '{SetupPaths.UserData}' not measured", ex);
_dataPlan = new UserDataPlan([]);
}
finally
{
_measuring = false;
}
OnPropertyChanged(nameof(IsDataPlanVisible));
OnPropertyChanged(nameof(DataPlanText));
OnPropertyChanged(nameof(DataPlanRows));
CommandManager.InvalidateRequerySuggested();
}
private void OnComponentsChanged()
{
OnPropertyChanged(nameof(RequiredSpaceText));
OnPropertyChanged(nameof(InstallToolTip));
OnPropertyChanged(nameof(HasDesktopOption));
OnPropertyChanged(nameof(HasStartMenuOption));
OnPropertyChanged(nameof(HasLaunchOption));
+71 -28
View File
@@ -18,7 +18,8 @@
<DockPanel>
<ComboBox DockPanel.Dock="Right" MinWidth="180" VerticalAlignment="Center" ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}"
DisplayMemberPath="Name" IsEnabled="{Binding IsOptions}" ToolTip="{l:Loc Tooltips.Setup.Language}" AutomationProperties.Name="{l:Loc Setup.Field.Language}" />
<ui:BrandMarkIcon ShowPlate="True" Width="40" Height="40" Margin="0,0,14,0" VerticalAlignment="Center" />
<!-- The mark is artwork: its off-centre sun must not flip in right-to-left languages. -->
<ui:BrandMarkIcon ShowPlate="True" Width="40" Height="40" Margin="0,0,14,0" VerticalAlignment="Center" FlowDirection="LeftToRight" />
<StackPanel VerticalAlignment="Center">
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.PageTitle}" />
<TextBlock Text="{Binding SubHeading}" Style="{StaticResource Text.Secondary}" />
@@ -43,7 +44,7 @@
<ItemsControl.ItemTemplate>
<DataTemplate>
<DockPanel Margin="0,0,0,6">
<TextBlock DockPanel.Dock="Right" Text="{Binding SizeText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" />
<TextBlock DockPanel.Dock="Right" Text="{Binding SizeText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
<CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}" ToolTip="{Binding ToolTip}" />
</DockPanel>
</DataTemplate>
@@ -58,13 +59,18 @@
ToolTipService.ShowOnDisabled="True" ToolTip="{Binding AllUsersToolTip}" />
</StackPanel>
<!-- The field comes before Browse in the Tab order, as on screen; a path reads left to right in every language. -->
<TextBlock Grid.Row="2" Text="{l:Loc Setup.Field.Folder}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,16,0" />
<DockPanel Grid.Row="2" Grid.Column="1" VerticalAlignment="Center">
<Button DockPanel.Dock="Right" Margin="8,0,0,0" Content="{l:Loc Setup.Folder.Browse}" Command="{Binding BrowseCommand}"
ToolTipService.ShowOnDisabled="True" ToolTip="{l:Loc Tooltips.Setup.Browse}" />
<TextBox Text="{Binding Directory, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding CanChangeLocation}"
<Grid Grid.Row="2" Grid.Column="1" VerticalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding Directory, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding CanChangeLocation}" FlowDirection="LeftToRight"
ToolTipService.ShowOnDisabled="True" ToolTip="{Binding DirectoryToolTip}" AutomationProperties.Name="{l:Loc Setup.Field.Folder}" />
</DockPanel>
<Button Grid.Column="1" Margin="8,0,0,0" Content="{l:Loc Setup.Folder.Browse}" Command="{Binding BrowseCommand}"
ToolTipService.ShowOnDisabled="True" ToolTip="{Binding BrowseToolTip}" />
</Grid>
<TextBlock Grid.Row="3" Text="{l:Loc Setup.Field.Options}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,16,0" />
<StackPanel Grid.Row="3" Grid.Column="1" Margin="0,12,0,0">
@@ -77,7 +83,7 @@
</StackPanel>
</Grid>
<!-- Uninstall options -->
<!-- Uninstall options; "Remove my data" shows what it deletes before Uninstall can run (dry run). -->
<Grid Grid.Row="1" Margin="0,24,0,0" Visibility="{Binding IsUninstallOptions, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
@@ -86,66 +92,103 @@
<Grid.RowDefinitions>
<RowDefinition Height="44" />
<RowDefinition Height="44" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Setup.Field.Folder}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,16,0" />
<TextBox Grid.Column="1" VerticalAlignment="Center" IsReadOnly="True" Text="{Binding Directory, Mode=OneWay}"
<TextBox Grid.Column="1" VerticalAlignment="Center" IsReadOnly="True" Text="{Binding Directory, Mode=OneWay}" FlowDirection="LeftToRight"
ToolTip="{l:Loc Tooltips.Setup.Installed}" AutomationProperties.Name="{l:Loc Setup.Field.Folder}" />
<CheckBox Grid.Row="1" Grid.Column="1" Content="{l:Loc Setup.Uninstall.RemoveData}" IsChecked="{Binding RemoveUserData}"
<CheckBox Grid.Row="1" Grid.Column="1" Content="{l:Loc Setup.Uninstall.RemoveData}" IsChecked="{Binding RemoveUserData}" VerticalAlignment="Center"
Foreground="{DynamicResource Brush.Warning}" ToolTip="{l:Loc Tooltips.Setup.RemoveData}" />
<Border Grid.Row="2" Grid.Column="1" Style="{StaticResource Border.Card}" Padding="12,8"
Visibility="{Binding IsDataPlanVisible, Converter={StaticResource BoolToVisibility}}">
<StackPanel>
<TextBlock x:Name="DataPlanHeading" Text="{Binding DataPlanText}" Style="{StaticResource Text.Section}" Foreground="{DynamicResource Brush.Warning}" Margin="0,0,0,6"
AutomationProperties.LiveSetting="Polite" />
<ItemsControl ItemsSource="{Binding DataPlanRows}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="0,2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" MinWidth="72" />
</Grid.ColumnDefinitions>
<TextBlock x:Name="EntryName" Text="{Binding Name}" Style="{StaticResource Text.Secondary}" HorizontalAlignment="Left" />
<TextBlock Grid.Column="1" Text="{Binding Size}" Style="{StaticResource Text.Secondary}" HorizontalAlignment="Right" Margin="12,0,0,0"
Typography.NumeralAlignment="Tabular" />
</Grid>
<DataTemplate.Triggers>
<!-- File and folder names read left to right in every language. -->
<DataTrigger Binding="{Binding IsFileName}" Value="True">
<Setter TargetName="EntryName" Property="FlowDirection" Value="LeftToRight" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
</Grid>
<!-- Programs still running -->
<DockPanel Grid.Row="1" VerticalAlignment="Center" Visibility="{Binding IsConfirm, Converter={StaticResource BoolToVisibility}}">
<ui:Icon Glyph="{StaticResource Icon.Warning}" Size="20" Foreground="{DynamicResource Brush.Warning}" Margin="0,0,12,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding ConfirmText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center" />
<TextBlock x:Name="ConfirmMessage" Text="{Binding ConfirmText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center"
AutomationProperties.LiveSetting="Assertive" />
</DockPanel>
<!-- Progress -->
<StackPanel Grid.Row="1" VerticalAlignment="Center" Visibility="{Binding IsWorking, Converter={StaticResource BoolToVisibility}}">
<TextBlock Text="{Binding WorkingText}" Style="{StaticResource Text.Title}" Margin="0,0,0,14" />
<TextBlock x:Name="WorkingMessage" Text="{Binding WorkingText}" Style="{StaticResource Text.Title}" Margin="0,0,0,14" AutomationProperties.LiveSetting="Polite" />
<DockPanel>
<TextBlock DockPanel.Dock="Right" Text="{Binding ProgressText}" Style="{StaticResource Text.Secondary}" MinWidth="40" TextAlignment="Right" Margin="12,0,0,0" VerticalAlignment="Center" />
<ProgressBar Minimum="0" Maximum="1" Value="{Binding Progress, Mode=OneWay}" IsIndeterminate="{Binding IsIndeterminate}" VerticalAlignment="Center" />
<TextBlock DockPanel.Dock="Right" Text="{Binding ProgressText}" Style="{StaticResource Text.Secondary}" MinWidth="40" TextAlignment="Right" Margin="12,0,0,0"
VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
<ProgressBar Minimum="0" Maximum="1" Value="{Binding Progress, Mode=OneWay}" IsIndeterminate="{Binding IsIndeterminate}" VerticalAlignment="Center"
AutomationProperties.Name="{Binding WorkingText}" />
</DockPanel>
<TextBlock Text="{Binding ProgressFile}" Style="{StaticResource Text.Secondary}" TextTrimming="CharacterEllipsis" Margin="0,8,0,0" />
<TextBlock Text="{Binding ProgressFile}" Style="{StaticResource Text.Secondary}" TextTrimming="CharacterEllipsis" Margin="0,8,0,0"
FlowDirection="LeftToRight" HorizontalAlignment="Left" />
</StackPanel>
<!-- Success -->
<DockPanel Grid.Row="1" VerticalAlignment="Center" Visibility="{Binding IsDone, Converter={StaticResource BoolToVisibility}}">
<ui:Icon Glyph="{StaticResource Icon.SuccessCircle}" Size="20" Foreground="{DynamicResource Brush.Success}" Margin="0,0,12,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding DoneText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center" />
<TextBlock x:Name="DoneMessage" Text="{Binding DoneText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center"
AutomationProperties.LiveSetting="Assertive" />
</DockPanel>
<!-- Failure -->
<DockPanel Grid.Row="1" VerticalAlignment="Center" Visibility="{Binding IsFailed, Converter={StaticResource BoolToVisibility}}">
<ui:Icon Glyph="{StaticResource Icon.ErrorCircle}" Size="20" Foreground="{DynamicResource Brush.Error}" Margin="0,0,12,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding ErrorText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center" />
<TextBlock x:Name="FailedMessage" Text="{Binding ErrorText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center"
AutomationProperties.LiveSetting="Assertive" />
</DockPanel>
<!-- Footer: space needed and at most two actions per state -->
<!--
Footer: space needed and at most two actions per stage, the safe one first (DESIGN §4). Enter and Esc follow
Windows: Install, Launch and Retry are the default when shown; otherwise the safe action is; Esc is the safe action.
-->
<DockPanel Grid.Row="2" LastChildFill="False" Margin="0,16,0,0">
<TextBlock DockPanel.Dock="Left" Text="{Binding RequiredSpaceText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center"
Visibility="{Binding IsInstallOptions, Converter={StaticResource BoolToVisibility}}" />
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
<StackPanel x:Name="Footer" DockPanel.Dock="Right" Orientation="Horizontal">
<Button Content="{l:Loc Setup.Action.Cancel}" MinWidth="88" Margin="0,0,8,0" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Setup.Cancel}"
IsCancel="{Binding IsOptions}" IsDefault="{Binding IsUninstallOptions}" Visibility="{Binding IsOptions, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Primary}" MinWidth="104" Content="{Binding InstallText}" Command="{Binding PrimaryCommand}" ToolTip="{Binding InstallToolTip}"
ToolTipService.ShowOnDisabled="True" IsDefault="True" Visibility="{Binding IsInstallOptions, Converter={StaticResource BoolToVisibility}}" />
ToolTipService.ShowOnDisabled="True" IsDefault="{Binding IsInstallOptions}" Visibility="{Binding IsInstallOptions, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Destructive}" MinWidth="104" Content="{l:Loc Setup.Action.Uninstall}" Command="{Binding PrimaryCommand}" ToolTip="{l:Loc Tooltips.Setup.Uninstall}"
Visibility="{Binding IsUninstallOptions, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Setup.Action.Cancel}" Command="{Binding BackCommand}" ToolTip="{l:Loc Tooltips.Setup.Back}" IsCancel="True" Margin="0,0,8,0"
Visibility="{Binding IsConfirm, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Setup.Action.Cancel}" MinWidth="88" Command="{Binding BackCommand}" ToolTip="{l:Loc Tooltips.Setup.Back}" Margin="0,0,8,0"
IsCancel="{Binding IsConfirm}" IsDefault="{Binding IsConfirm}" Visibility="{Binding IsConfirm, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Setup.Action.ClosePrograms}" Command="{Binding CloseProgramsCommand}" ToolTip="{l:Loc Tooltips.Setup.ClosePrograms}"
Visibility="{Binding IsConfirm, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Setup.Action.Close}" MinWidth="88" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Setup.Close}"
Visibility="{Binding IsDone, Converter={StaticResource BoolToVisibility}}" />
IsCancel="{Binding IsFinished}" IsDefault="{Binding IsCloseDefault}" Visibility="{Binding IsFinished, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Primary}" MinWidth="88" Content="{l:Loc Setup.Action.Launch}" Command="{Binding LaunchCommand}" ToolTip="{l:Loc Tooltips.Setup.LaunchNow}" Margin="8,0,0,0"
Visibility="{Binding CanLaunch, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Setup.Action.Close}" MinWidth="88" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Setup.Close}"
Visibility="{Binding IsFailed, Converter={StaticResource BoolToVisibility}}" />
IsDefault="{Binding CanLaunch}" Visibility="{Binding CanLaunch, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Primary}" MinWidth="88" Content="{l:Loc Setup.Action.Retry}" Command="{Binding RetryCommand}" ToolTip="{l:Loc Tooltips.Setup.Retry}" Margin="8,0,0,0"
Visibility="{Binding CanRetry, Converter={StaticResource BoolToVisibility}}" />
IsDefault="{Binding CanRetry}" Visibility="{Binding CanRetry, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</DockPanel>
</Grid>
+60 -1
View File
@@ -1,28 +1,41 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;
using Titano.Core.Localization;
using Titano.Setup.Interop;
using Titano.Ui.Controls;
namespace Titano.Setup.Views;
/// <summary>The one setup screen (~720×520, dialog chrome). Closing is blocked while files are being written.</summary>
/// <summary>
/// The one setup screen (~720×520, dialog chrome). Closing is blocked while files are being written, and the
/// title-bar Close is disabled then. Each stage gives the keyboard to its default button and announces its outcome.
/// </summary>
internal sealed partial class SetupWindow : TitanoWindow
{
private readonly SetupViewModel _model;
private SetupStage _shownStage;
public SetupWindow(SetupViewModel model)
{
_model = model;
_shownStage = model.Stage;
DataContext = model;
InitializeComponent();
ApplyFlowDirection();
Loc.CultureChanged += OnCultureChanged;
// Ahead of the chrome's own Close binding, which is always enabled.
CommandBindings.Insert(0, new CommandBinding(SystemCommands.CloseWindowCommand, null, OnCanClose));
model.PickFolder = initial => FolderPicker.Pick(new WindowInteropHelper(this).Handle, Loc.L("Setup.Field.Folder"), initial);
model.Finished += (_, _) => Close();
model.VisibilityRequested += (_, visible) => Visibility = visible ? Visibility.Visible : Visibility.Hidden;
model.PropertyChanged += OnModelChanged;
SourceInitialized += (_, _) => model.WindowHandle = new WindowInteropHelper(this).Handle;
Loaded += (_, _) => FocusDefault();
ContentRendered += (_, _) => model.OnShown();
}
@@ -39,6 +52,52 @@ internal sealed partial class SetupWindow : TitanoWindow
base.OnClosed(e);
}
private void OnCanClose(object sender, CanExecuteRoutedEventArgs e)
{
if (!_model.IsWorking) return;
e.CanExecute = false;
e.Handled = true;
}
/// <summary>
/// A new stage collapses the focused button: the keyboard moves to the new default and the outcome is read out.
/// The "Remove my data" plan is read out when it appears.
/// </summary>
private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(SetupViewModel.IsDataPlanVisible) && _model.IsDataPlanVisible)
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => Announce(DataPlanHeading));
if (_model.Stage == _shownStage) return;
_shownStage = _model.Stage;
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () =>
{
FocusDefault();
if (StageMessage() is { } message) Announce(message);
});
}
/// <summary>Asks screen readers to read <paramref name="element"/> (it carries a live setting).</summary>
private static void Announce(UIElement element)
{
if (element.IsVisible) UIElementAutomationPeer.CreatePeerForElement(element)?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
}
private TextBlock? StageMessage() => _model.Stage switch
{
SetupStage.Confirm => ConfirmMessage,
SetupStage.Working => WorkingMessage,
SetupStage.Done => DoneMessage,
SetupStage.Failed => FailedMessage,
_ => null,
};
/// <summary>Focuses the visible default button of the footer, else its first visible one.</summary>
private void FocusDefault()
{
var buttons = Footer.Children.OfType<Button>().Where(b => b.IsVisible).ToList();
(buttons.FirstOrDefault(b => b.IsDefault) ?? buttons.FirstOrDefault())?.Focus();
}
private void OnCultureChanged(object? sender, EventArgs e) => ApplyFlowDirection();
private void ApplyFlowDirection() => FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
+1 -7
View File
@@ -7,7 +7,6 @@ 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;
@@ -304,13 +303,8 @@ public partial class App : Application
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);
ScreenCapture.Run(directory, ApplyLanguage);
}
private void HookUnhandledExceptions()
+5 -1
View File
@@ -12,7 +12,8 @@ namespace Titano.Uploader.DesignTime;
/// <summary>
/// Sample content for <c>--capture</c> 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.
/// with one failure, and three watch folders (one unreachable). Nothing here touches the network, the registry or the
/// user's data files.
/// </summary>
public sealed class SampleData
{
@@ -33,6 +34,7 @@ public sealed class SampleData
[
new UploaderSettings.WatchFolderSettings { Path = @"D:\Cam\Roof", IntervalSeconds = 60 },
new UploaderSettings.WatchFolderSettings { Path = @"\\garage-pi\cam", IntervalSeconds = 300 },
new UploaderSettings.WatchFolderSettings { Path = @"F:\Timelapse\Construction site north tower", IntervalSeconds = 900 },
],
};
@@ -45,6 +47,8 @@ public sealed class SampleData
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;
// A disconnected drive: its chip shows the hollow ring and wraps to a second line.
_vm.WatchFolders[^1].IsAvailable = false;
return _vm;
}
+5 -1
View File
@@ -1,6 +1,7 @@
using System.Runtime.InteropServices;
using System.Windows.Interop;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
namespace Titano.Uploader.Interop;
@@ -32,6 +33,7 @@ public sealed unsafe partial class TrayIcon : IDisposable
private const uint TpmRightButton = 0x2;
private const uint TpmNoNotify = 0x80;
private const uint TpmReturnCmd = 0x100;
private const uint TpmLayoutRtl = 0x8000;
private readonly HwndSource _window;
private readonly IntPtr _icon;
@@ -136,7 +138,9 @@ public sealed unsafe partial class TrayIcon : IDisposable
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);
// Right-to-left languages get a mirrored menu, as the window itself is (BRIEF §16).
var layout = Loc.IsRightToLeft ? TpmLayoutRtl : 0;
var chosen = TrackPopupMenuEx(menu, TpmReturnCmd | TpmRightButton | TpmNoNotify | layout, point.X, point.Y, _window.Handle, IntPtr.Zero);
PostMessageW(_window.Handle, 0, IntPtr.Zero, IntPtr.Zero);
if (chosen != 0) _command(chosen);
}
+5 -3
View File
@@ -3,19 +3,21 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
Title="{l:Loc Uploader.App.Title}"
Title="{l:Loc Uploader.App.Title}" AutomationProperties.Name="{Binding Heading}" AutomationProperties.HelpText="{Binding Message}"
IsDialog="True" ResizeMode="NoResize" SizeToContent="Height" Width="440"
WindowStartupLocation="CenterOwner" ShowInTaskbar="False">
<!-- DESIGN §4 dialog: two buttons, safe action left and default, the action on the right. -->
<StackPanel Margin="24,18,24,20">
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" TextTrimming="None" />
<TextBlock Text="{Binding Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" />
<!-- Address and fingerprint read left to right in every language. -->
<Border Style="{StaticResource Border.Card}" Margin="0,16,0,0" Padding="12,10" ToolTip="{Binding DetailToolTip}"
Visibility="{Binding Detail, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<TextBlock Text="{Binding Detail}" FontFamily="{StaticResource Font.Mono}" FontSize="{StaticResource Size.Secondary}" TextWrapping="Wrap" LineHeight="18" />
<TextBlock Text="{Binding Detail}" FontFamily="{StaticResource Font.Mono}" FontSize="{StaticResource Size.Secondary}" TextWrapping="Wrap" LineHeight="18"
FlowDirection="LeftToRight" />
</Border>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,24,0,0">
<Button Content="{Binding SafeText}" ToolTip="{Binding SafeToolTip}" IsDefault="True" IsCancel="True" MinWidth="96" Click="OnSafe" />
<Button x:Name="Safe" Content="{Binding SafeText}" ToolTip="{Binding SafeToolTip}" IsDefault="True" IsCancel="True" MinWidth="96" Click="OnSafe" />
<Button x:Name="Action" Content="{Binding ActionText}" ToolTip="{Binding ActionToolTip}" MinWidth="96" Margin="8,0,0,0" Click="OnAction" />
</StackPanel>
</StackPanel>
@@ -29,7 +29,10 @@ public sealed partial class ConfirmDialog : TitanoWindow
{
DataContext = request;
InitializeComponent();
WindowDirection.Follow(this);
Action.SetResourceReference(StyleProperty, request.IsDestructive ? "Button.Destructive" : "Button.Primary");
// The keyboard starts on the safe default, as in Windows dialogs.
Loaded += (_, _) => Safe.Focus();
}
/// <summary>True when the user chose the action.</summary>
+111 -23
View File
@@ -1,4 +1,6 @@
using System.Collections;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
using Titano.Core.Localization;
using Titano.Ui.Mvvm;
@@ -8,15 +10,22 @@ namespace Titano.Uploader.Shell;
/// <summary>
/// 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.
/// certificate is shown to the user once (trust on first use) before the password is sent. A wrong address or
/// password marks that field (DESIGN §4: error border, message in the tooltip); other failures show one sentence
/// with Retry where trying again can help.
/// </summary>
public sealed class ConnectViewModel : ObservableObject
public sealed class ConnectViewModel : ObservableObject, INotifyDataErrorInfo
{
private readonly IServerSession _session;
private readonly IUploaderDialogs _dialogs;
private string _address;
private string _username;
private string _password = string.Empty;
private string? _addressError;
private string? _passwordError;
private string? _errorText;
private bool _canRetry;
private bool _isSigningIn;
public ConnectViewModel(IServerSession session, IUploaderDialogs dialogs, string? address, string? username)
{
@@ -31,6 +40,8 @@ public sealed class ConnectViewModel : ObservableObject
});
}
public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
/// <summary>Servers that announced themselves on this network.</summary>
public ObservableCollection<DiscoveredServer> Discovered { get; } = [];
@@ -40,7 +51,10 @@ public sealed class ConnectViewModel : ObservableObject
public string Address
{
get => _address;
set => Set(ref _address, value);
set
{
if (Set(ref _address, value)) AddressError = null;
}
}
public string Username
@@ -50,15 +64,69 @@ public sealed class ConnectViewModel : ObservableObject
}
/// <summary>Set from the view's PasswordBox; never stored.</summary>
public string Password { private get; set; } = string.Empty;
public string Password
{
private get => _password;
set
{
if (_password == value) return;
_password = value;
PasswordError = null;
}
}
/// <summary>One sentence saying what went wrong; the retry action sits next to it.</summary>
/// <summary>Why the address was refused (invalid, or not a Titano Server); null when it is not in question.</summary>
public string? AddressError
{
get => _addressError;
private set
{
if (!Set(ref _addressError, value)) return;
OnPropertyChanged(nameof(AddressToolTip));
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Address)));
}
}
/// <summary>Wrong user name or password; null otherwise. The password box has no binding, so the view reads this.</summary>
public string? PasswordError
{
get => _passwordError;
private set
{
if (Set(ref _passwordError, value)) OnPropertyChanged(nameof(PasswordToolTip));
}
}
public string AddressToolTip => AddressError ?? Loc.L("Tooltips.Uploader.ServerAddress");
public string PasswordToolTip => PasswordError ?? Loc.L("Tooltips.Uploader.Password");
/// <summary>One sentence for failures that are not about a field; null otherwise.</summary>
public string? ErrorText
{
get => _errorText;
private set => Set(ref _errorText, value);
}
/// <summary>True when trying the same request again can help (no answer, server error).</summary>
public bool CanRetry
{
get => _canRetry;
private set => Set(ref _canRetry, value);
}
/// <summary>True while a sign-in started from this form runs; the form stays on screen until it has an outcome.</summary>
public bool IsSigningIn
{
get => _isSigningIn;
private set => Set(ref _isSigningIn, value);
}
public bool HasErrors => AddressError is not null;
public IEnumerable GetErrors(string? propertyName) =>
propertyName == nameof(Address) && AddressError is { } error ? new[] { error } : Array.Empty<string>();
/// <summary>Shows the server address without the trailing slash of the stored base URL.</summary>
public static string Display(string? address) => address?.TrimEnd('/') ?? string.Empty;
@@ -72,30 +140,50 @@ public sealed class ConnectViewModel : ObservableObject
private async Task SignInAsync()
{
if (_session.State is not (ConnectionState.NotConfigured or ConnectionState.SignedOut)) return;
ErrorText = null;
var (result, fingerprint) = await _session.SignInAsync(Address, Username.Trim(), Password, CancellationToken.None);
if (result == SignInResult.Untrusted && fingerprint is not null)
ShowResult(null);
IsSigningIn = true;
try
{
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);
var result = await SignInOrTrustAsync();
ShowResult(result);
if (result != SignInResult.Success) return;
Address = Display(_session.Address);
Password = string.Empty;
}
finally
{
IsSigningIn = false;
}
}
/// <summary>Signs in; an unknown self-signed certificate is shown to the user first and, once trusted, the sign-in is repeated.</summary>
private async Task<SignInResult> SignInOrTrustAsync()
{
var (result, fingerprint) = await _session.SignInAsync(Address, Username.Trim(), Password, CancellationToken.None);
if (result != SignInResult.Untrusted || fingerprint is null) return result;
if (!_dialogs.ConfirmTrust(Display(Address), fingerprint)) return SignInResult.Untrusted;
_session.Trust(fingerprint);
(result, _) = await _session.SignInAsync(Address, Username.Trim(), Password, CancellationToken.None);
return result;
}
/// <summary>Puts each failure where it belongs: on the field it is about, or in the sentence under the form.</summary>
private void ShowResult(SignInResult? result)
{
AddressError = result switch
{
SignInResult.InvalidAddress => Loc.L("Uploader.Connect.Error.InvalidAddress"),
SignInResult.NotTitano => Loc.L("Uploader.Connect.Error.NotTitano"),
_ => null,
};
PasswordError = result == SignInResult.BadCredentials ? Loc.L("Uploader.Connect.Error.BadCredentials") : null;
CanRetry = result is SignInResult.Unreachable or SignInResult.Failed;
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"),
SignInResult.Failed => Loc.L("Uploader.Connect.Error.Failed"),
_ => null,
};
if (result != SignInResult.Success) return;
Address = Display(_session.Address);
Password = string.Empty;
}
}
+22 -2
View File
@@ -31,7 +31,9 @@ public sealed class UploadStateTextConverter : IValueConverter
{
public static UploadStateTextConverter Instance { get; } = new();
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => value switch
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => value is UploadItemState state ? Text(state) : string.Empty;
public static string Text(UploadItemState state) => state switch
{
UploadItemState.Hashing => Loc.L("Uploader.State.Hashing"),
UploadItemState.Uploading => Loc.L("Uploader.State.Uploading"),
@@ -54,7 +56,7 @@ public sealed class FailureTextConverter : IMultiValueConverter
public object[] ConvertBack(object? value, Type[] targetTypes, object? parameter, CultureInfo culture) => throw new NotSupportedException();
private static string? Describe(UploadFailure failure, string? detail) => failure switch
public static string? Describe(UploadFailure failure, string? detail) => failure switch
{
UploadFailure.FileMissing => Loc.L("Uploader.Failure.FileMissing"),
UploadFailure.FileUnreadable => Loc.L("Uploader.Failure.FileUnreadable"),
@@ -65,6 +67,24 @@ public sealed class FailureTextConverter : IMultiValueConverter
};
}
/// <summary>
/// (file name, state, failure, detail) → a queue row's accessible name, "IMG_0413.CR2 · Failed · The file could not be
/// read.", so a screen reader announces each row instead of its type name.
/// </summary>
public sealed class QueueRowNameConverter : IMultiValueConverter
{
public static QueueRowNameConverter Instance { get; } = new();
public object Convert(object?[] values, Type targetType, object? parameter, CultureInfo culture)
{
if (values is not [string file, UploadItemState state, UploadFailure failure, var detail, ..]) return string.Empty;
var name = file + " · " + UploadStateTextConverter.Text(state);
return state == UploadItemState.Failed && FailureTextConverter.Describe(failure, detail as string) is { } reason ? name + " · " + reason : name;
}
public object[] ConvertBack(object? value, Type[] targetTypes, object? parameter, CultureInfo culture) => throw new NotSupportedException();
}
/// <summary>Visible only for <see cref="UploadItemState.Failed"/>; hidden (keeping its space) otherwise so rows stay aligned.</summary>
public sealed class FailedToVisibleConverter : IValueConverter
{
@@ -0,0 +1,20 @@
namespace Titano.Uploader.Shell;
/// <summary>Pickers and confirmations the view model asks for.</summary>
public interface IUploaderDialogs
{
/// <summary>Photos to add; empty when cancelled.</summary>
IReadOnlyList<string> PickFiles();
/// <summary>A folder or card root to add; null when cancelled.</summary>
string? PickFolder();
/// <summary>A folder to watch; null when cancelled.</summary>
string? PickWatchFolder();
/// <summary>Trust-on-first-use: shows the certificate fingerprint; true when the user trusts it.</summary>
bool ConfirmTrust(string address, string fingerprint);
/// <summary>Destructive confirmation for "Delete after upload"; true when the user turns it on.</summary>
bool ConfirmDeleteAfterUpload();
}
+46 -5
View File
@@ -47,9 +47,11 @@ public sealed class MainViewModel : LocalizedViewModel
private bool _startWithWindows;
private string _queueText = string.Empty;
private string _progressText = string.Empty;
private string? _failedText;
private string? _currentFileText;
private double _progress;
private UploadItem? _currentItem;
private QueueActivity _activity;
public MainViewModel(UploaderServices services)
{
@@ -58,6 +60,10 @@ public sealed class MainViewModel : LocalizedViewModel
_newTitle = services.Settings.NewSequenceTitle ?? string.Empty;
_startWithWindows = services.Startup.IsEnabled;
Connect = new ConnectViewModel(services.Session, services.Dialogs, services.Settings.ServerUrl, services.Settings.Username);
Connect.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(ConnectViewModel.IsSigningIn)) OnPropertyChanged(nameof(IsConnectVisible));
};
foreach (var w in services.Settings.WatchFolders) WatchFolders.Add(NewWatchFolder(w.Path, w.IntervalSeconds));
OpenSettingsCommand = new RelayCommand(() => IsSettingsOpen = true);
@@ -82,6 +88,8 @@ public sealed class MainViewModel : LocalizedViewModel
_s.Queue.Items.CollectionChanged += (_, _) =>
{
OnPropertyChanged(nameof(HasItems));
OnPropertyChanged(nameof(PauseToolTip));
OnPropertyChanged(nameof(StopToolTip));
CommandManager.InvalidateRequerySuggested();
};
_refresh = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(500) };
@@ -92,6 +100,9 @@ public sealed class MainViewModel : LocalizedViewModel
/// <summary>Raised when the queue finished while work was done, with the number of files the server confirmed.</summary>
public event Action<int>? UploadsCompleted;
/// <summary>Raised by the "Sign in" action of a session-ended toast; the view focuses the password box.</summary>
public event EventHandler? SignInRequested;
public ConnectViewModel Connect { get; }
/// <summary>In-window notifications; the window forwards them to its <see cref="ToastHost"/>.</summary>
@@ -139,8 +150,8 @@ public sealed class MainViewModel : LocalizedViewModel
? 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;
/// <summary>The sign-in form replaces the queue on first run and after signing out, and stays while its own sign-in runs.</summary>
public bool IsConnectVisible => Connect.IsSigningIn || _s.Session.State is ConnectionState.NotConfigured or ConnectionState.SignedOut;
public bool IsSettingsOpen
{
@@ -170,6 +181,9 @@ public sealed class MainViewModel : LocalizedViewModel
public ObservableCollection<SequenceOption> Sequences { get; } = [];
/// <summary>The sequence list is disabled unless "Sequence" is chosen; its tooltip then says so (DESIGN §4).</summary>
public string SequenceToolTip => Loc.L(IsSequenceTarget ? "Tooltips.Uploader.ChooseSequence" : "Tooltips.Uploader.SequenceDisabled");
public SequenceOption? SelectedSequence
{
get => _selectedSequence;
@@ -212,6 +226,20 @@ public sealed class MainViewModel : LocalizedViewModel
private set => Set(ref _progressText, value);
}
/// <summary>"3 failed", a link to the first failed file; null when nothing failed.</summary>
public string? FailedText
{
get => _failedText;
private set => Set(ref _failedText, value);
}
/// <summary>What the queue is doing; changes only when the activity does, so the view can announce it.</summary>
public QueueActivity Activity
{
get => _activity;
private set => Set(ref _activity, value);
}
public string? CurrentFileText
{
get => _currentFileText;
@@ -233,7 +261,10 @@ public sealed class MainViewModel : LocalizedViewModel
public bool IsPaused => _s.Queue.IsPaused;
public string PauseToolTip => Loc.L(IsPaused ? "Tooltips.Uploader.Resume" : "Tooltips.Uploader.Pause");
/// <summary>Pause and Stop are disabled while nothing is queued; their tooltips then say so (DESIGN §4).</summary>
public string PauseToolTip => Loc.L(!HasItems ? "Tooltips.Uploader.QueueEmpty" : IsPaused ? "Tooltips.Uploader.Resume" : "Tooltips.Uploader.Pause");
public string StopToolTip => Loc.L(HasItems ? "Tooltips.Uploader.Stop" : "Tooltips.Uploader.QueueEmpty");
/// <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");
@@ -356,6 +387,9 @@ public sealed class MainViewModel : LocalizedViewModel
if (folder is not null) folder.IsAvailable = available;
}
/// <summary>The failed file nearest the top of the queue; null when none failed.</summary>
public UploadItem? FirstFailed() => _s.Queue.Items.FirstOrDefault(i => i.State == UploadItemState.Failed);
/// <summary>Errors are one sentence plus one action (BRIEF §0.2 rule 6).</summary>
public void ReportError(Exception ex)
{
@@ -421,12 +455,15 @@ public sealed class MainViewModel : LocalizedViewModel
_ => QueueActivity.Done,
};
QueueText = UploaderText.QueueLine(summary, activity, rate, RateMeter.TimeLeft(summary.RemainingBytes, rate), Loc.Culture);
Activity = activity;
ProgressText = summary.Files == 0 ? string.Empty : UploaderText.ProgressLine(summary, Loc.Culture);
FailedText = UploaderText.Failed(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(StopToolTip));
OnPropertyChanged(nameof(PauseLabel));
OnPropertyChanged(nameof(TrayText));
}
@@ -440,6 +477,7 @@ public sealed class MainViewModel : LocalizedViewModel
OnPropertyChanged(nameof(IsSessionsTarget));
OnPropertyChanged(nameof(IsSequenceTarget));
OnPropertyChanged(nameof(IsNewTarget));
OnPropertyChanged(nameof(SequenceToolTip));
if (mode == UploadTargetMode.Sequence && Sequences.Count == 0) _ = LoadSequencesAsync();
}
@@ -524,7 +562,8 @@ public sealed class MainViewModel : LocalizedViewModel
OnPropertyChanged(nameof(BandwidthLimitText));
if (e.PropertyName != nameof(IServerSession.State)) return;
if (_s.Session.State == ConnectionState.Connected) _ = LoadSequencesAsync();
if (IsConnectVisible)
// The form's own sign-in keeps what the user typed; only a session that ended refills it.
if (IsConnectVisible && !Connect.IsSigningIn)
{
Connect.Address = ConnectViewModel.Display(_s.Session.Address);
Connect.Username = _s.Session.Username ?? Connect.Username;
@@ -532,8 +571,10 @@ public sealed class MainViewModel : LocalizedViewModel
CommandManager.InvalidateRequerySuggested();
}
/// <summary>One sentence plus one action (BRIEF §0.2 rule 6): "Sign in" takes the user to the password box.</summary>
private void OnSessionEnded(object? sender, ServerProblem problem) =>
ShowToast(Loc.L(problem == ServerProblem.CertificateChanged ? "Uploader.Toast.CertificateChanged" : "Uploader.Toast.SignedOut"));
ShowToast(Loc.L(problem == ServerProblem.CertificateChanged ? "Uploader.Toast.CertificateChanged" : "Uploader.Toast.SignedOut"),
Loc.L("Uploader.Connect.SignIn"), Loc.L("Tooltips.Uploader.SignIn"), new RelayCommand(() => SignInRequested?.Invoke(this, EventArgs.Empty)));
private void OnDrained(object? sender, EventArgs e)
{
+168 -83
View File
@@ -6,7 +6,7 @@
xmlns:s="clr-namespace:Titano.Uploader.Shell"
xmlns:u="clr-namespace:Titano.Uploader.Uploads"
Title="{l:Loc Uploader.App.Title}"
Width="760" Height="560" MinWidth="640" MinHeight="480"
Width="760" Height="700" MinWidth="640" MinHeight="630"
WindowStartupLocation="CenterScreen" AllowDrop="True">
<Window.Resources>
<Style x:Key="Text.Label" TargetType="TextBlock" BasedOn="{StaticResource Text.Base}">
@@ -15,6 +15,13 @@
<Setter Property="Margin" Value="0,0,12,0" />
</Style>
<!-- Labels of the settings panel's fixed label column wrap instead of being cut (+40 % text). -->
<Style x:Key="Text.PanelLabel" TargetType="TextBlock" BasedOn="{StaticResource Text.Label}">
<Setter Property="MinWidth" Value="0" />
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="TextTrimming" Value="None" />
</Style>
<!-- Watch-folder chip (mockup: 28 px pill, Card fill, status dot). -->
<Style x:Key="Button.Chip" TargetType="Button" BasedOn="{StaticResource Button.Base}">
<Setter Property="Height" Value="28" />
@@ -35,10 +42,31 @@
<Setter Property="Height" Value="30" />
</Style>
<!-- Queue rows: hover only, no selection. -->
<!-- Keyboard focus on a queue row: the accent ring drawn inside the row, so neighbours do not cover it. -->
<Style x:Key="Focus.Row">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Border BorderBrush="{DynamicResource Brush.Accent}" BorderThickness="2" CornerRadius="{StaticResource Radius.Control}" SnapsToDevicePixels="True" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Queue rows: hover and keyboard focus, no selection look; named "file · state" for screen readers. -->
<Style x:Key="QueueRow" TargetType="ListBoxItem">
<Setter Property="Focusable" Value="False" />
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Row}" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="AutomationProperties.Name">
<Setter.Value>
<MultiBinding Converter="{x:Static s:QueueRowNameConverter.Instance}">
<Binding Path="FileName" />
<Binding Path="State" />
<Binding Path="Failure" />
<Binding Path="FailureDetail" />
</MultiBinding>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
@@ -83,15 +111,16 @@
</Grid.RowDefinitions>
<!-- Header: server · user · connection, quota, settings. -->
<Border Height="40" Background="{DynamicResource Brush.Surface}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="16,0,10,0">
<Border Height="40" Background="{DynamicResource Brush.Surface}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="16,0">
<DockPanel LastChildFill="True">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Square}" ui:ButtonIcon.Glyph="{StaticResource Icon.Settings}"
<Button x:Name="SettingsButton" DockPanel.Dock="Right" Style="{StaticResource Button.Square}" ui:ButtonIcon.Glyph="{StaticResource Icon.Settings}"
Command="{Binding OpenSettingsCommand}" ToolTip="{l:Loc Tooltips.Uploader.Settings}" AutomationProperties.Name="{l:Loc Uploader.Settings.Title}" />
<TextBlock DockPanel.Dock="Right" Text="{Binding QuotaText}" Style="{StaticResource Text.Secondary}" Margin="12,0,12,0"
ToolTip="{l:Loc Tooltips.Uploader.Quota}" Visibility="{Binding QuotaText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<ui:Icon Glyph="{StaticResource Icon.Server}" Foreground="{DynamicResource Brush.Accent}" Margin="0,0,10,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding ServerText}" Style="{StaticResource Text.Body}" MaxWidth="320" />
<!-- An address reads left to right in every language. -->
<TextBlock Text="{Binding ServerText}" Style="{StaticResource Text.Body}" MaxWidth="320" FlowDirection="LeftToRight" />
<StackPanel Orientation="Horizontal" Visibility="{Binding UserText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<TextBlock Text="·" Foreground="{DynamicResource Brush.TextFaint}" Margin="10,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding UserText}" Style="{StaticResource Text.Body}" />
@@ -107,7 +136,8 @@
<!-- First run / signed out: connect form. -->
<Grid Grid.Row="1" Visibility="{Binding IsConnectVisible, Converter={StaticResource BoolToVisibility}}">
<StackPanel DataContext="{Binding Connect}" Width="440" HorizontalAlignment="Center" VerticalAlignment="Center">
<ui:BrandMarkIcon Width="48" Height="48" HorizontalAlignment="Center" />
<!-- The mark is artwork: its off-centre sun must not flip in right-to-left languages. -->
<ui:BrandMarkIcon Width="48" Height="48" HorizontalAlignment="Center" FlowDirection="LeftToRight" />
<TextBlock Text="{l:Loc Uploader.Connect.Title}" Style="{StaticResource Text.Title}" HorizontalAlignment="Center" Margin="0,14,0,20" />
<Grid>
<Grid.ColumnDefinitions>
@@ -124,10 +154,13 @@
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Uploader.Connect.Server}" Style="{StaticResource Text.Label}" />
<TextBox Grid.Column="1" Text="{Binding Address, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Server}"
ui:Field.Placeholder="{l:Loc Uploader.Connect.AddressPlaceholder}" ToolTip="{l:Loc Tooltips.Uploader.ServerAddress}" AutomationProperties.Name="{l:Loc Uploader.Connect.Server}" />
<!-- A wrong address shows the Error border; the message is the tooltip (DESIGN §4). -->
<TextBox x:Name="AddressBox" Grid.Column="1" Text="{Binding Address, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
ui:Field.Glyph="{StaticResource Icon.Server}" FlowDirection="LeftToRight"
ui:Field.Placeholder="{l:Loc Uploader.Connect.AddressPlaceholder}" ToolTip="{Binding AddressToolTip}" AutomationProperties.Name="{l:Loc Uploader.Connect.Server}" />
<TextBlock Grid.Row="1" Text="{l:Loc Uploader.Connect.Found}" Style="{StaticResource Text.Label}" Margin="0,8,12,0" VerticalAlignment="Top"
<!-- Top margin 14 = 8 + (28 − 16) / 2: the label sits on the chips' text line. -->
<TextBlock Grid.Row="1" Text="{l:Loc Uploader.Connect.Found}" Style="{StaticResource Text.Label}" Margin="0,14,12,0" VerticalAlignment="Top"
Visibility="{Binding Discovered.Count, Converter={x:Static ui:ZeroToCollapsedConverter.Instance}}" />
<ItemsControl Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Discovered}" Margin="0,8,0,0" Focusable="False"
Visibility="{Binding Discovered.Count, Converter={x:Static ui:ZeroToCollapsedConverter.Instance}}">
@@ -143,7 +176,7 @@
<StackPanel Orientation="Horizontal">
<Ellipse Width="8" Height="8" Fill="{DynamicResource Brush.Accent}" Margin="0,0,8,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" />
<TextBlock Text="{Binding Address}" Foreground="{DynamicResource Brush.TextMuted}" Margin="8,0,0,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding Address}" Foreground="{DynamicResource Brush.TextMuted}" Margin="8,0,0,0" VerticalAlignment="Center" FlowDirection="LeftToRight" />
</StackPanel>
</Button>
</DataTemplate>
@@ -151,26 +184,47 @@
</ItemsControl>
<TextBlock Grid.Row="2" Text="{l:Loc Uploader.Connect.User}" Style="{StaticResource Text.Label}" Margin="0,12,12,0" />
<TextBox Grid.Row="2" Grid.Column="1" Margin="0,12,0,0" Text="{Binding Username, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.User}"
<TextBox x:Name="UserBox" Grid.Row="2" Grid.Column="1" Margin="0,12,0,0" Text="{Binding Username, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.User}"
ToolTip="{l:Loc Tooltips.Uploader.User}" AutomationProperties.Name="{l:Loc Uploader.Connect.User}" />
<TextBlock Grid.Row="3" Text="{l:Loc Uploader.Connect.Password}" Style="{StaticResource Text.Label}" Margin="0,12,12,0" />
<PasswordBox x:Name="Password" Grid.Row="3" Grid.Column="1" Margin="0,12,0,0" PasswordChanged="OnPasswordChanged"
ToolTip="{l:Loc Tooltips.Uploader.Password}" AutomationProperties.Name="{l:Loc Uploader.Connect.Password}" />
ToolTip="{Binding PasswordToolTip}" AutomationProperties.Name="{l:Loc Uploader.Connect.Password}" />
<!--
A wrong password: the Error border (DESIGN §4), drawn over the box because the password box has no binding
to validate and its template paints the focus border over its own; the message is the tooltip.
-->
<Border x:Name="PasswordErrorRing" Grid.Row="3" Grid.Column="1" Margin="0,12,0,0" BorderBrush="{DynamicResource Brush.Error}" BorderThickness="1"
CornerRadius="{StaticResource Radius.Control}" SnapsToDevicePixels="True" IsHitTestVisible="False"
Visibility="{Binding PasswordError, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<Border Grid.Row="4" Grid.Column="1" Margin="0,12,0,0" Padding="10,6,6,6" CornerRadius="{StaticResource Radius.Control}" Background="{DynamicResource Brush.ErrorSubtle}"
Visibility="{Binding ErrorText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<DockPanel>
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Uploader.Action.Retry}" Command="{Binding SignInCommand}"
ToolTip="{l:Loc Tooltips.Uploader.Retry}" Margin="8,0,0,0" />
ToolTip="{l:Loc Tooltips.Uploader.Retry}" Margin="8,0,0,0" Visibility="{Binding CanRetry, Converter={StaticResource BoolToVisibility}}" />
<ui:Icon Glyph="{StaticResource Icon.ErrorCircle}" Foreground="{DynamicResource Brush.Error}" Margin="0,0,8,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding ErrorText}" TextWrapping="Wrap" VerticalAlignment="Center" />
<TextBlock x:Name="ErrorMessage" Text="{Binding ErrorText}" TextWrapping="Wrap" VerticalAlignment="Center" AutomationProperties.LiveSetting="Assertive" />
</DockPanel>
</Border>
<Button Grid.Row="5" Grid.Column="1" Margin="0,20,0,0" HorizontalAlignment="Left" Style="{StaticResource Button.Primary}" MinWidth="120"
IsDefault="{Binding IsVisible, RelativeSource={RelativeSource Self}}"
Content="{l:Loc Uploader.Connect.SignIn}" Command="{Binding SignInCommand}" ToolTip="{l:Loc Tooltips.Uploader.SignIn}" />
<!-- Enter signs in while the form is on screen, but not from the settings panel drawn over it. -->
<Button Grid.Row="5" Grid.Column="1" Margin="0,20,0,0" HorizontalAlignment="Left" MinWidth="120"
Content="{l:Loc Uploader.Connect.SignIn}" Command="{Binding SignInCommand}" ToolTip="{l:Loc Tooltips.Uploader.SignIn}">
<Button.Style>
<Style TargetType="Button" BasedOn="{StaticResource Button.Primary}">
<Setter Property="IsDefault" Value="True" />
<Style.Triggers>
<Trigger Property="IsVisible" Value="False">
<Setter Property="IsDefault" Value="False" />
</Trigger>
<DataTrigger Binding="{Binding DataContext.IsSettingsOpen, RelativeSource={RelativeSource AncestorType=Window}}" Value="True">
<Setter Property="IsDefault" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</Grid>
</StackPanel>
</Grid>
@@ -196,7 +250,7 @@
<ui:Icon Glyph="{StaticResource Icon.Upload}" Size="28" Foreground="{DynamicResource Brush.TextMuted}" HorizontalAlignment="Center" />
<TextBlock Text="{l:Loc Uploader.Drop.Message}" FontSize="{StaticResource Size.Section}" Foreground="{DynamicResource Brush.TextMuted}"
HorizontalAlignment="Center" Margin="0,10,0,10" />
<Button Content="{l:Loc Uploader.Browse.Button}" Height="30" Padding="14,0" HorizontalAlignment="Center"
<Button x:Name="BrowseButton" Content="{l:Loc Uploader.Browse.Button}" Height="30" Padding="14,0" HorizontalAlignment="Center"
ToolTip="{l:Loc Tooltips.Uploader.Browse}" Click="OnBrowseClick">
<Button.ContextMenu>
<ContextMenu>
@@ -208,26 +262,30 @@
</StackPanel>
</Grid>
<!-- Target -->
<!-- Target: each choice wraps together with its field; the negative margin keeps one line at 30 px. -->
<Grid Grid.Row="1" Margin="0,12,0,0" MinHeight="30">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Uploader.Target.Label}" Style="{StaticResource Text.Label}" />
<WrapPanel Grid.Column="1" VerticalAlignment="Center">
<RadioButton GroupName="Target" Content="{l:Loc Uploader.Target.Sessions}" IsChecked="{Binding IsSessionsTarget}" Margin="0,0,16,0" VerticalAlignment="Center"
<WrapPanel Grid.Column="1" VerticalAlignment="Center" Margin="0,-4,0,0">
<RadioButton GroupName="Target" Content="{l:Loc Uploader.Target.Sessions}" IsChecked="{Binding IsSessionsTarget}" Margin="0,4,16,0" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Uploader.TargetSessions}" />
<RadioButton GroupName="Target" Content="{l:Loc Uploader.Target.Sequence}" IsChecked="{Binding IsSequenceTarget}" Margin="0,0,8,0" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Uploader.TargetSequence}" />
<ComboBox Width="170" Height="30" Margin="0,0,16,0" ItemsSource="{Binding Sequences}" SelectedItem="{Binding SelectedSequence}" DisplayMemberPath="Title"
IsEnabled="{Binding IsSequenceTarget}" DropDownOpened="OnSequencesDropDownOpened" ToolTip="{l:Loc Tooltips.Uploader.ChooseSequence}"
AutomationProperties.Name="{l:Loc Uploader.Target.Sequence}" />
<RadioButton GroupName="Target" Content="{l:Loc Uploader.Target.New}" IsChecked="{Binding IsNewTarget}" Margin="0,0,8,0" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Uploader.TargetNew}" />
<TextBox Width="150" Height="30" Text="{Binding NewTitle}" ui:Field.Placeholder="{l:Loc Uploader.Target.TitlePlaceholder}"
Visibility="{Binding IsNewTarget, Converter={StaticResource BoolToVisibility}}" ToolTip="{l:Loc Tooltips.Uploader.NewTitle}"
AutomationProperties.Name="{l:Loc Uploader.Target.TitlePlaceholder}" />
<StackPanel Orientation="Horizontal" Margin="0,4,16,0">
<RadioButton GroupName="Target" Content="{l:Loc Uploader.Target.Sequence}" IsChecked="{Binding IsSequenceTarget}" Margin="0,0,8,0" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Uploader.TargetSequence}" />
<ComboBox Width="170" Height="30" ItemsSource="{Binding Sequences}" SelectedItem="{Binding SelectedSequence}" DisplayMemberPath="Title"
IsEnabled="{Binding IsSequenceTarget}" DropDownOpened="OnSequencesDropDownOpened" ToolTip="{Binding SequenceToolTip}"
AutomationProperties.Name="{l:Loc Uploader.Target.Sequence}" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,4,0,0">
<RadioButton GroupName="Target" Content="{l:Loc Uploader.Target.New}" IsChecked="{Binding IsNewTarget}" Margin="0,0,8,0" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Uploader.TargetNew}" />
<TextBox Width="170" Height="30" Text="{Binding NewTitle}" ui:Field.Placeholder="{l:Loc Uploader.Target.TitlePlaceholder}"
Visibility="{Binding IsNewTarget, Converter={StaticResource BoolToVisibility}}" ToolTip="{l:Loc Tooltips.Uploader.NewTitle}"
AutomationProperties.Name="{l:Loc Uploader.Target.TitlePlaceholder}" />
</StackPanel>
</WrapPanel>
</Grid>
@@ -240,9 +298,12 @@
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Uploader.Queue.Label}" Style="{StaticResource Text.Label}" />
<TextBlock Grid.Column="1" Text="{Binding QueueText}" Style="{StaticResource Text.Body}" Typography.NumeralAlignment="Tabular" />
<!-- Announced when the activity changes (running, paused, waiting, done), not on every refresh. -->
<TextBlock x:Name="QueueLine" Grid.Column="1" Text="{Binding QueueText}" Style="{StaticResource Text.Body}" Typography.NumeralAlignment="Tabular"
AutomationProperties.LiveSetting="Polite" />
<StackPanel Grid.Column="2" Orientation="Horizontal" Margin="10,0,0,0">
<Button Command="{Binding PauseCommand}" ToolTip="{Binding PauseToolTip}" AutomationProperties.Name="{Binding PauseLabel}">
<!-- Media glyphs (pause, play) keep their direction in right-to-left languages. -->
<Button Command="{Binding PauseCommand}" ToolTip="{Binding PauseToolTip}" AutomationProperties.Name="{Binding PauseLabel}" FlowDirection="LeftToRight">
<Button.Style>
<Style TargetType="Button" BasedOn="{StaticResource Button.Square}">
<Setter Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.Pause}" />
@@ -255,54 +316,66 @@
</Button.Style>
</Button>
<Button Style="{StaticResource Button.Square}" Margin="10,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.Stop}" Command="{Binding StopCommand}"
ToolTip="{l:Loc Tooltips.Uploader.Stop}" AutomationProperties.Name="{l:Loc Uploader.Action.Stop}" />
ToolTip="{Binding StopToolTip}" AutomationProperties.Name="{l:Loc Uploader.Action.Stop}" />
</StackPanel>
<StackPanel Grid.Column="3" Orientation="Horizontal" Margin="16,0,0,0">
<TextBlock Text="{l:Loc Uploader.Limit.Label}" Style="{StaticResource Text.Base}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,6,0" />
<TextBox Width="58" Height="30" Text="{Binding BandwidthLimitText}" TextAlignment="Right" ToolTip="{l:Loc Tooltips.Uploader.Limit}"
<TextBox Width="58" Height="30" Text="{Binding BandwidthLimitText}" TextAlignment="Right" FlowDirection="LeftToRight" ToolTip="{l:Loc Tooltips.Uploader.Limit}"
AutomationProperties.Name="{l:Loc Uploader.Limit.Label}" />
<TextBlock Text="{l:Loc Uploader.Limit.Unit}" Style="{StaticResource Text.Base}" Foreground="{DynamicResource Brush.TextMuted}" Margin="6,0,0,0" />
</StackPanel>
</Grid>
<!-- Progress: bar, current file, counts -->
<!-- Progress: bar, current file, counts, failures -->
<StackPanel Grid.Row="3" Margin="0,12,0,0" Visibility="{Binding HasItems, Converter={StaticResource BoolToVisibility}}">
<ProgressBar Height="8" Maximum="1" Value="{Binding Progress, Mode=OneWay}" />
<ProgressBar Height="8" Maximum="1" Value="{Binding Progress, Mode=OneWay}" AutomationProperties.Name="{l:Loc Uploader.Queue.Progress}" />
<Grid Margin="0,5,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding CurrentFileText}" Style="{StaticResource Text.Secondary}" />
<TextBlock Text="{Binding CurrentFileText}" Style="{StaticResource Text.Secondary}" FlowDirection="LeftToRight" HorizontalAlignment="Left" />
<TextBlock Grid.Column="1" Text="{Binding ProgressText}" Style="{StaticResource Text.Secondary}" Margin="12,0,0,0" Typography.NumeralAlignment="Tabular" />
<!-- "✕ 3 failed" (DESIGN §4 status glyph) takes the keyboard to the first failed file. -->
<Button x:Name="FailedLink" Grid.Column="2" Style="{StaticResource Button.Subtle}" Height="18" MinWidth="0" Padding="4,0" Margin="6,0,0,0"
Click="OnShowFailedClick" ToolTip="{l:Loc Tooltips.Uploader.ShowFailed}" AutomationProperties.Name="{Binding FailedText}"
Visibility="{Binding FailedText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<ui:StatusGlyph Kind="Failed" Text="{Binding FailedText}" FontSize="{StaticResource Size.Secondary}" Typography.NumeralAlignment="Tabular" />
</Button>
</Grid>
</StackPanel>
<!-- Watch folders -->
<!-- Watch folders: chips and the add button wrap; a long path is shortened (full path in the tooltip). -->
<Grid Grid.Row="4" Margin="0,12,0,0" MinHeight="30">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Uploader.Watch.Label}" Style="{StaticResource Text.Label}" VerticalAlignment="Top" Margin="0,6,12,0" />
<StackPanel Grid.Column="1" Orientation="Horizontal">
<WrapPanel Grid.Column="1">
<ItemsControl ItemsSource="{Binding WatchFolders}" Focusable="False">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type s:WatchFolderViewModel}">
<Button Style="{StaticResource Button.Chip}" Margin="0,0,10,0" Click="OnWatchChipClick" ToolTip="{Binding ToolTip}" AutomationProperties.Name="{Binding Path}">
<Button Style="{StaticResource Button.Chip}" Margin="0,0,10,4" Click="OnWatchChipClick" ToolTip="{Binding ToolTip}"
AutomationProperties.Name="{Binding Text}">
<Button.ContextMenu>
<ContextMenu ItemsSource="{Binding MenuOptions}" ItemContainerStyle="{StaticResource WatchMenuItem}" />
</Button.ContextMenu>
<StackPanel Orientation="Horizontal">
<Ellipse x:Name="Dot" Width="8" Height="8" Margin="0,0,8,0" VerticalAlignment="Center" StrokeThickness="1.5"
<DockPanel>
<Ellipse x:Name="Dot" DockPanel.Dock="Left" Width="8" Height="8" Margin="0,0,8,0" VerticalAlignment="Center" StrokeThickness="1.5"
Fill="{DynamicResource Brush.TextFaint}" />
<TextBlock Text="{Binding Text}" VerticalAlignment="Center" />
</StackPanel>
<TextBlock DockPanel.Dock="Right" Text="{Binding IntervalText}" VerticalAlignment="Center" />
<TextBlock DockPanel.Dock="Right" Text="·" Foreground="{DynamicResource Brush.TextFaint}" Margin="6,0" VerticalAlignment="Center" />
<!-- The button template lays content out without a width limit, so the path carries its own. -->
<TextBlock Text="{Binding Path}" MaxWidth="180" FlowDirection="LeftToRight" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis"
VerticalAlignment="Center" />
</DockPanel>
</Button>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsAvailable}" Value="True">
@@ -317,27 +390,28 @@
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button Style="{StaticResource Button.Round}" ui:ButtonIcon.Glyph="{StaticResource Icon.Plus}" Command="{Binding AddWatchFolderCommand}"
<Button Style="{StaticResource Button.Round}" Margin="0,0,0,4" ui:ButtonIcon.Glyph="{StaticResource Icon.Plus}" Command="{Binding AddWatchFolderCommand}"
ToolTip="{l:Loc Tooltips.Uploader.AddWatchFolder}" AutomationProperties.Name="{l:Loc Uploader.Action.AddFolder}" />
</StackPanel>
</WrapPanel>
</Grid>
<!-- Per-file state -->
<Border Grid.Row="5" Margin="0,12,0,0" Style="{StaticResource Border.Panel}" Padding="4"
<!-- Per-file state: rows take keyboard focus; Enter retries a failed file. -->
<Border Grid.Row="5" Margin="0,8,0,0" Style="{StaticResource Border.Panel}" Padding="4"
Visibility="{Binding HasItems, Converter={StaticResource BoolToVisibility}}">
<ListBox x:Name="ItemList" ItemsSource="{Binding Items}" ItemContainerStyle="{StaticResource QueueRow}">
<ListBox x:Name="ItemList" ItemsSource="{Binding Items}" ItemContainerStyle="{StaticResource QueueRow}" VirtualizingPanel.ScrollUnit="Item"
AutomationProperties.Name="{l:Loc Uploader.Queue.List}" KeyDown="OnItemListKeyDown">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type u:UploadItem}">
<Grid Height="28">
<Grid Height="{x:Static s:MainWindow.RowHeight}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" MinWidth="64" />
<ColumnDefinition Width="Auto" MinWidth="120" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding FileName}" Style="{StaticResource Text.Body}" />
<TextBlock Text="{Binding FileName}" Style="{StaticResource Text.Body}" FlowDirection="LeftToRight" HorizontalAlignment="Left" />
<TextBlock Grid.Column="1" Text="{Binding Size, Converter={x:Static s:SizeConverter.Instance}}" Style="{StaticResource Text.Secondary}"
Typography.NumeralAlignment="Tabular" Margin="12,0,0,0" />
Typography.NumeralAlignment="Tabular" HorizontalAlignment="Right" Margin="12,0,0,0" />
<ui:StatusGlyph Grid.Column="2" Margin="16,0,0,0" FontSize="{StaticResource Size.Secondary}" VerticalAlignment="Center"
Kind="{Binding State, Converter={x:Static s:UploadStateKindConverter.Instance}}"
Text="{Binding State, Converter={x:Static s:UploadStateTextConverter.Instance}}">
@@ -348,7 +422,12 @@
</MultiBinding>
</ui:StatusGlyph.ToolTip>
</ui:StatusGlyph>
<Button Grid.Column="3" Style="{StaticResource Button.IconSubtle}" Width="26" Height="26" MinWidth="26" Margin="4,0,0,0"
<!--
Mouse shortcut; keyboard users press Enter on the row, so the button is not a tab stop of its own.
The retry arrow turns clockwise, like a clock, in every language: it is not mirrored.
-->
<Button Grid.Column="3" Style="{StaticResource Button.IconSubtle}" Width="26" Height="26" MinWidth="26" Margin="4,0,0,0" IsTabStop="False"
FlowDirection="LeftToRight"
ui:ButtonIcon.Glyph="{StaticResource Icon.Retry}" CommandParameter="{Binding}"
Command="{Binding DataContext.RetryItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}"
Visibility="{Binding State, Converter={x:Static s:FailedToVisibleConverter.Instance}}"
@@ -370,59 +449,65 @@
</WrapPanel>
</Grid>
<!-- Settings panel over the window content. -->
<!-- Settings panel over the window content; Tab and arrow keys stay inside it while it is open. -->
<Grid Grid.RowSpan="2" Visibility="{Binding IsSettingsOpen, Converter={StaticResource BoolToVisibility}}">
<Border Background="{DynamicResource Brush.Scrim}">
<Border.InputBindings>
<MouseBinding MouseAction="LeftClick" Command="{Binding CloseSettingsCommand}" />
</Border.InputBindings>
</Border>
<Border HorizontalAlignment="Right" Width="340" Background="{DynamicResource Brush.Surface}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="1,0,0,0">
<Border x:Name="SettingsPanel" HorizontalAlignment="Right" Width="{StaticResource Width.SidePanel}" Background="{DynamicResource Brush.Surface}"
BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="1,0,0,0"
KeyboardNavigation.TabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Cycle" KeyboardNavigation.ControlTabNavigation="Cycle">
<DockPanel Margin="20,12,12,20">
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,12">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.IconSubtle}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}" Command="{Binding CloseSettingsCommand}"
ToolTip="{l:Loc Tooltips.Uploader.CloseSettings}" AutomationProperties.Name="{l:Loc Uploader.Action.Close}" />
<Button x:Name="CloseSettingsButton" DockPanel.Dock="Right" Style="{StaticResource Button.IconSubtle}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}"
Command="{Binding CloseSettingsCommand}" ToolTip="{l:Loc Tooltips.Uploader.CloseSettings}" AutomationProperties.Name="{l:Loc Uploader.Action.Close}" />
<TextBlock Text="{l:Loc Uploader.Settings.Title}" Style="{StaticResource Text.Title}" />
</DockPanel>
<Grid Margin="0,0,8,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="100" />
<ColumnDefinition Width="{StaticResource Grid.LabelColumn}" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="36" />
<RowDefinition Height="36" />
<RowDefinition Height="Auto" MinHeight="36" />
<RowDefinition Height="Auto" MinHeight="36" />
<RowDefinition Height="Auto" />
<RowDefinition Height="44" />
<RowDefinition Height="36" />
<RowDefinition Height="36" />
<RowDefinition Height="36" />
<RowDefinition Height="Auto" MinHeight="44" />
<RowDefinition Height="Auto" MinHeight="36" />
<RowDefinition Height="Auto" MinHeight="36" />
<RowDefinition Height="Auto" MinHeight="36" />
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Uploader.Settings.Server}" Style="{StaticResource Text.Label}" MinWidth="0" />
<TextBlock Grid.Column="1" Text="{Binding ServerText}" Style="{StaticResource Text.Body}" />
<TextBlock Grid.Row="1" Text="{l:Loc Uploader.Settings.User}" Style="{StaticResource Text.Label}" MinWidth="0" />
<TextBlock Text="{l:Loc Uploader.Settings.Server}" Style="{StaticResource Text.PanelLabel}" />
<TextBlock Grid.Column="1" Text="{Binding ServerText}" Style="{StaticResource Text.Body}" FlowDirection="LeftToRight" HorizontalAlignment="Left" />
<TextBlock Grid.Row="1" Text="{l:Loc Uploader.Settings.User}" Style="{StaticResource Text.PanelLabel}" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding UserText}" Style="{StaticResource Text.Body}" />
<Button Grid.Row="2" Grid.Column="1" HorizontalAlignment="Left" Margin="0,4,0,8" Content="{l:Loc Uploader.Settings.SignOut}" Command="{Binding SignOutCommand}"
ToolTip="{l:Loc Tooltips.Uploader.SignOut}" Visibility="{Binding IsConnectVisible, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<TextBlock Grid.Row="3" Text="{l:Loc Uploader.Settings.Bandwidth}" Style="{StaticResource Text.Label}" MinWidth="0" />
<StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Grid.Row="3" Text="{l:Loc Uploader.Settings.Bandwidth}" Style="{StaticResource Text.PanelLabel}" />
<WrapPanel Grid.Row="3" Grid.Column="1" VerticalAlignment="Center">
<TextBlock Text="{l:Loc Uploader.Limit.Label}" Style="{StaticResource Text.Base}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,6,0" />
<TextBox Width="58" Height="30" Text="{Binding BandwidthLimitText}" TextAlignment="Right" ToolTip="{l:Loc Tooltips.Uploader.Limit}"
<TextBox Width="58" Height="30" Text="{Binding BandwidthLimitText}" TextAlignment="Right" FlowDirection="LeftToRight" ToolTip="{l:Loc Tooltips.Uploader.Limit}"
AutomationProperties.Name="{l:Loc Uploader.Limit.Label}" />
<TextBlock Text="{l:Loc Uploader.Limit.Unit}" Style="{StaticResource Text.Base}" Foreground="{DynamicResource Brush.TextMuted}" Margin="6,0,0,0" />
</StackPanel>
</WrapPanel>
<TextBlock Grid.Row="4" Text="{l:Loc Uploader.Settings.Startup}" Style="{StaticResource Text.Label}" MinWidth="0" />
<CheckBox Grid.Row="4" Grid.Column="1" Content="{l:Loc Uploader.Options.StartWithWindows}" IsChecked="{Binding StartWithWindows}"
ToolTip="{l:Loc Tooltips.Uploader.StartWithWindows}" VerticalAlignment="Center" />
<CheckBox Grid.Row="5" Grid.Column="1" Content="{l:Loc Uploader.Options.MinimizeToTray}" IsChecked="{Binding MinimizeToTray}"
ToolTip="{l:Loc Tooltips.Uploader.MinimizeToTray}" VerticalAlignment="Center" />
<TextBlock Grid.Row="4" Text="{l:Loc Uploader.Settings.Startup}" Style="{StaticResource Text.PanelLabel}" />
<CheckBox Grid.Row="4" Grid.Column="1" IsChecked="{Binding StartWithWindows}" ToolTip="{l:Loc Tooltips.Uploader.StartWithWindows}" VerticalAlignment="Center">
<TextBlock Text="{l:Loc Uploader.Options.StartWithWindows}" TextWrapping="Wrap" />
</CheckBox>
<CheckBox Grid.Row="5" Grid.Column="1" IsChecked="{Binding MinimizeToTray}" ToolTip="{l:Loc Tooltips.Uploader.MinimizeToTray}" VerticalAlignment="Center">
<TextBlock Text="{l:Loc Uploader.Options.MinimizeToTray}" TextWrapping="Wrap" />
</CheckBox>
<TextBlock Grid.Row="6" Text="{l:Loc Uploader.Settings.Files}" Style="{StaticResource Text.Label}" MinWidth="0" />
<CheckBox Grid.Row="6" Grid.Column="1" Content="{l:Loc Uploader.Options.DeleteSource}" IsChecked="{Binding DeleteAfterUpload, Mode=OneWay}"
Command="{Binding ToggleDeleteAfterUploadCommand}" ToolTip="{l:Loc Tooltips.Uploader.DeleteSource}" VerticalAlignment="Center" />
<TextBlock Grid.Row="6" Text="{l:Loc Uploader.Settings.Files}" Style="{StaticResource Text.PanelLabel}" />
<CheckBox Grid.Row="6" Grid.Column="1" IsChecked="{Binding DeleteAfterUpload, Mode=OneWay}" Command="{Binding ToggleDeleteAfterUploadCommand}"
ToolTip="{l:Loc Tooltips.Uploader.DeleteSource}" VerticalAlignment="Center">
<TextBlock Text="{l:Loc Uploader.Options.DeleteSource}" TextWrapping="Wrap" />
</CheckBox>
</Grid>
</DockPanel>
</Border>
+112 -2
View File
@@ -1,31 +1,44 @@
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using Titano.Ui.Controls;
using Titano.Uploader.Infrastructure;
using Titano.Uploader.Uploads;
namespace Titano.Uploader.Shell;
/// <summary>The uploader's single window (mockup Uploader.html).</summary>
public sealed partial class MainWindow : TitanoWindow
{
/// <summary>Height of a queue row; the list scrolls by whole rows.</summary>
public const double RowHeight = 28;
private readonly MainViewModel _vm;
private readonly UploaderSettings _settings;
private bool _connectShown;
public MainWindow(MainViewModel vm, UploaderSettings settings)
{
_vm = vm;
_settings = settings;
_connectShown = vm.IsConnectVisible;
DataContext = vm;
InitializeComponent();
WindowDirection.Follow(this);
vm.PendingToasts.CollectionChanged += OnToastRequested;
vm.PropertyChanged += OnViewModelChanged;
vm.Connect.PropertyChanged += OnConnectChanged;
vm.SignInRequested += (_, _) => FocusLater(Password);
PreviewKeyDown += OnPreviewKeyDown;
Loaded += (_, _) => FocusStart();
RestorePlacement();
}
@@ -95,6 +108,23 @@ public sealed partial class MainWindow : TitanoWindow
private void OnPasswordChanged(object sender, RoutedEventArgs e) => _vm.Connect.Password = Password.Password;
/// <summary>The "3 failed" link: brings the first failed file into view and gives it the keyboard (Enter retries it).</summary>
private void OnShowFailedClick(object sender, RoutedEventArgs e)
{
if (_vm.FirstFailed() is not { } item) return;
ScrollNearTop(item);
ItemList.UpdateLayout();
if (ItemList.ItemContainerGenerator.ContainerFromItem(item) is ListBoxItem row) row.Focus();
}
/// <summary>Enter on a failed row retries it: the keyboard path to the row's Retry button.</summary>
private void OnItemListKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Enter || e.OriginalSource is not ListBoxItem { DataContext: UploadItem { State: UploadItemState.Failed } item }) return;
_vm.RetryItemCommand.Execute(item);
e.Handled = true;
}
/// <summary>DESIGN §4 inputs: Enter commits, Esc reverts; Esc also closes the settings panel.</summary>
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
@@ -114,8 +144,88 @@ public sealed partial class MainWindow : TitanoWindow
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();
switch (e.PropertyName)
{
case nameof(MainViewModel.CurrentItem) when _vm.CurrentItem is { } item && !ItemList.IsKeyboardFocusWithin:
// Follow the upload unless the user is reading the list with the keyboard; a list that has just
// appeared has its scroll viewer once it is laid out.
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => ScrollNearTop(item));
break;
// Raised with every session change; only a real switch between the form and the queue moves the keyboard.
case nameof(MainViewModel.IsConnectVisible) when _vm.IsConnectVisible != _connectShown:
_connectShown = _vm.IsConnectVisible;
if (_connectShown) Password.Clear();
FocusStart();
break;
case nameof(MainViewModel.IsSettingsOpen):
// Focus moves into the panel and comes back to the gear, so it is never left behind the scrim.
FocusLater(_vm.IsSettingsOpen ? CloseSettingsButton : SettingsButton);
break;
case nameof(MainViewModel.Activity):
Announce(QueueLine);
break;
}
}
/// <summary>A refused address or password takes the keyboard to that field; other failures are announced.</summary>
private void OnConnectChanged(object? sender, PropertyChangedEventArgs e)
{
var connect = _vm.Connect;
switch (e.PropertyName)
{
case nameof(ConnectViewModel.AddressError) when connect.AddressError is not null:
FocusLater(AddressBox);
break;
case nameof(ConnectViewModel.PasswordError) when connect.PasswordError is not null:
FocusLater(Password);
break;
case nameof(ConnectViewModel.ErrorText) when connect.ErrorText is not null:
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => Announce(ErrorMessage));
break;
}
}
/// <summary>Where the keyboard starts: the first empty field of the sign-in form, or Browse once signed in.</summary>
private void FocusStart()
{
if (!_vm.IsConnectVisible) FocusLater(BrowseButton);
else if (_vm.Connect.Address.Length == 0) FocusLater(AddressBox);
else FocusLater(_vm.Connect.Username.Length == 0 ? UserBox : Password);
}
/// <summary>Focuses <paramref name="target"/> once a visibility change has been laid out; text is selected so typing replaces it.</summary>
private void FocusLater(Control target) => Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () =>
{
if (!target.IsVisible || !target.Focus()) return;
if (target is TextBox box) box.SelectAll();
else if (target is PasswordBox password) password.SelectAll();
});
/// <summary>Scrolls so <paramref name="item"/> is the second visible row (the list scrolls by rows), unless it is already in view.</summary>
private void ScrollNearTop(UploadItem item)
{
if (FindScrollViewer(ItemList) is not { } scroll) return;
var index = ItemList.Items.IndexOf(item);
if (index < 0) return;
if (index >= scroll.VerticalOffset && index + 1 <= scroll.VerticalOffset + scroll.ViewportHeight) return;
scroll.ScrollToVerticalOffset(Math.Max(0, index - 1));
}
private static ScrollViewer? FindScrollViewer(DependencyObject node)
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
{
var child = VisualTreeHelper.GetChild(node, i);
if (child is ScrollViewer scroll) return scroll;
if (FindScrollViewer(child) is { } found) return found;
}
return null;
}
/// <summary>Asks screen readers to read <paramref name="element"/> again (it carries <see cref="AutomationProperties.LiveSettingProperty"/>).</summary>
private static void Announce(UIElement element)
{
if (element.IsVisible) UIElementAutomationPeer.CreatePeerForElement(element)?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
}
private void OnToastRequested(object? sender, NotifyCollectionChangedEventArgs e)
+68 -26
View File
@@ -10,39 +10,29 @@ using Titano.Uploader.DesignTime;
namespace Titano.Uploader.Shell;
/// <summary>
/// <c>Titano.Uploader.exe --capture &lt;dir&gt;</c>: renders the window at 760×560 in the dark and light themes —
/// first run (connect), queue running, settings panel — from <see cref="SampleData"/>, then exits.
/// <c>Titano.Uploader.exe --capture &lt;dir&gt;</c>: renders the window at its default 760×700 — first run (connect),
/// queue running, settings panel — from <see cref="SampleData"/> in the dark and light themes, then once more in
/// Arabic (right to left, dark), and exits.
/// </summary>
public static class ScreenCapture
{
public static void Run(MainWindow window, MainViewModel vm, SampleData sample, string directory)
private const double Width = 760;
private const double Height = 700;
/// <param name="directory">Where the PNG files go.</param>
/// <param name="applyLanguage">Switches the UI language (a culture name; null = the OS language).</param>
public static void Run(string directory, Action<string?> applyLanguage)
{
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, () =>
Application.Current.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;
}
applyLanguage(null);
CaptureScreens(directory, string.Empty, [AppTheme.Dark, AppTheme.Light]);
// Mirrored layout with paths, addresses and file names kept left to right (BRIEF §16).
applyLanguage("ar");
CaptureScreens(directory, "-ar", [AppTheme.Dark]);
Log.Info("capture", $"Screenshots written to {Path.GetFullPath(directory)}");
}
catch (Exception ex)
@@ -57,6 +47,44 @@ public static class ScreenCapture
});
}
/// <summary>A fresh window on fresh sample data, so every text is built in the current language.</summary>
private static void CaptureScreens(string directory, string language, IReadOnlyList<AppTheme> themes)
{
var sample = new SampleData();
var vm = sample.CreateViewModel();
var window = new MainWindow(vm, sample.Settings)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
Width = Width,
Height = Height,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
try
{
foreach (var theme in themes)
{
var suffix = language + "-" + 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;
}
}
finally
{
window.Close();
vm.Dispose();
}
}
private static void Save(Window window, string path)
{
// Let bindings, templates and deferred layout complete.
@@ -70,10 +98,24 @@ public static class ScreenCapture
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);
bitmap.Render(window.FlowDirection == FlowDirection.RightToLeft ? Mirrored(root) : root);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using var stream = File.Create(path);
encoder.Save(stream);
}
/// <summary>
/// A right-to-left window is mirrored by a transform on the window itself, which rendering its content alone
/// would leave out (mirrored glyphs, left-to-right layout): draw the content through that mirror.
/// </summary>
private static DrawingVisual Mirrored(FrameworkElement root)
{
var size = new Rect(0, 0, root.ActualWidth, root.ActualHeight);
var visual = new DrawingVisual();
using var dc = visual.RenderOpen();
dc.PushTransform(new MatrixTransform(-1, 0, 0, 1, size.Width, 0));
dc.DrawRectangle(new VisualBrush(root) { Stretch = Stretch.Fill, ViewboxUnits = BrushMappingMode.Absolute, Viewbox = size }, null, size);
return visual;
}
}
@@ -6,25 +6,6 @@ using Titano.Uploader.Interop;
namespace Titano.Uploader.Shell;
/// <summary>Pickers and confirmations the view model asks for.</summary>
public interface IUploaderDialogs
{
/// <summary>Photos to add; empty when cancelled.</summary>
IReadOnlyList<string> PickFiles();
/// <summary>A folder or card root to add; null when cancelled.</summary>
string? PickFolder();
/// <summary>A folder to watch; null when cancelled.</summary>
string? PickWatchFolder();
/// <summary>Trust-on-first-use: shows the certificate fingerprint; true when the user trusts it.</summary>
bool ConfirmTrust(string address, string fingerprint);
/// <summary>Destructive confirmation for "Delete after upload"; true when the user turns it on.</summary>
bool ConfirmDeleteAfterUpload();
}
/// <summary>Window-owned implementation: shell Open dialogs and <see cref="ConfirmDialog"/>.</summary>
public sealed class UploaderDialogs : IUploaderDialogs
{
@@ -41,6 +41,7 @@ public sealed class WatchFolderViewModel : ObservableObject
{
if (!Set(ref _intervalSeconds, value)) return;
OnPropertyChanged(nameof(Text));
OnPropertyChanged(nameof(IntervalText));
OnPropertyChanged(nameof(ToolTip));
OnPropertyChanged(nameof(MenuOptions));
}
@@ -56,12 +57,16 @@ public sealed class WatchFolderViewModel : ObservableObject
}
}
/// <summary>"D:\Cam\Roof · every 1 min".</summary>
/// <summary>"D:\Cam\Roof · every 1 min": the chip's accessible name.</summary>
public string Text => Loc.L("Uploader.Watch.Chip", Path, Interval(IntervalSeconds));
public string ToolTip => IsAvailable == false ? Loc.L("Tooltips.Uploader.WatchFolderMissing", Interval(IntervalSeconds))
/// <summary>"every 1 min", shown after the path, which the chip draws left to right on its own and may shorten.</summary>
public string IntervalText => Loc.L("Uploader.Watch.Interval", Interval(IntervalSeconds));
/// <summary>The full path (the chip may shorten it), then the folder's state and interval.</summary>
public string ToolTip => LeftToRight(Path) + " · " + (IsAvailable == false ? Loc.L("Tooltips.Uploader.WatchFolderMissing", Interval(IntervalSeconds))
: IsNetwork ? Loc.L("Tooltips.Uploader.WatchFolderNetwork", Interval(IntervalSeconds))
: Loc.L("Tooltips.Uploader.WatchFolder", Interval(IntervalSeconds));
: Loc.L("Tooltips.Uploader.WatchFolder", Interval(IntervalSeconds)));
public IReadOnlyList<WatchMenuOption> MenuOptions =>
[
@@ -75,4 +80,7 @@ public sealed class WatchFolderViewModel : ObservableObject
];
private static string Interval(int seconds) => UploaderText.Duration(TimeSpan.FromSeconds(seconds), Loc.Culture);
/// <summary>Embeds a path left to right (LRE … PDF) so a right-to-left tooltip does not reorder its separators.</summary>
private static string LeftToRight(string text) => "\u202A" + text + "\u202C";
}
@@ -0,0 +1,22 @@
using System.Windows;
using Titano.Core.Localization;
namespace Titano.Uploader.Shell;
/// <summary>
/// Mirrors a window for right-to-left languages (BRIEF §16: ar, he, fa, ur) and follows later language switches.
/// Windows do not inherit <see cref="FrameworkElement.FlowDirection"/> from their owner, so every window calls this.
/// </summary>
public static class WindowDirection
{
public static void Follow(Window window)
{
Apply(window);
void OnCultureChanged(object? sender, EventArgs e) => window.Dispatcher.Invoke(() => Apply(window));
Loc.CultureChanged += OnCultureChanged;
window.Closed += (_, _) => Loc.CultureChanged -= OnCultureChanged;
}
private static void Apply(Window window) =>
window.FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
}
+15 -16
View File
@@ -21,7 +21,9 @@ public enum QueueActivity
public static class UploaderText
{
private const string Separator = " · ";
private static readonly string[] ByteUnits = ["B", "KB", "MB", "GB", "TB", "PB"];
/// <summary>Localized "{0} KB" formats from bytes to petabytes (BRIEF §16: sizes follow the language, "96,2 Go").</summary>
private static readonly string[] SizeFormats = ["Common.Size.B", "Common.Size.KB", "Common.Size.MB", "Common.Size.GB", "Common.Size.TB", "Common.Size.PB"];
/// <summary>Localized string for <paramref name="key"/> in <paramref name="culture"/>, formatted with <paramref name="args"/>.</summary>
public static string L(string key, CultureInfo culture, params object?[] args)
@@ -43,7 +45,7 @@ public static class UploaderText
{
var (value, unit) = Scale(bytes);
var format = unit == 0 || value >= 100 ? "0" : "0.#";
return value.ToString(format, culture) + " " + ByteUnits[unit];
return L(SizeFormats[unit], culture, value.ToString(format, culture));
}
/// <summary>38,400,000 B/s → "38 MB/s"; one decimal below 10 units.</summary>
@@ -51,7 +53,7 @@ public static class UploaderText
{
var (value, unit) = Scale(Math.Max(0, bytesPerSecond));
var format = unit == 0 || value >= 10 ? "0" : "0.#";
return L("Uploader.Unit.PerSecond", culture, value.ToString(format, culture) + " " + ByteUnits[unit]);
return L("Uploader.Unit.PerSecond", culture, L(SizeFormats[unit], culture, value.ToString(format, culture)));
}
/// <summary>Compact duration: "2 h 05 m", "41 min", "40 s".</summary>
@@ -87,24 +89,21 @@ public static class UploaderText
return string.Join(Separator, parts);
}
/// <summary>"2,214 of 4,812 sent · 2,201 verified by the server · 0 retries", plus failures when there are any.</summary>
public static string ProgressLine(QueueSummary summary, CultureInfo culture)
{
var parts = new List<string>
{
L("Uploader.Progress.Sent", culture, summary.Sent, summary.Files),
L("Uploader.Progress.Verified", culture, summary.Verified),
Plural("Uploader.Progress.Retries", summary.Retries, culture),
};
if (summary.Failed > 0) parts.Add(L("Uploader.Progress.Failed", culture, summary.Failed));
return string.Join(Separator, parts);
}
/// <summary>"2,214 of 4,812 sent · 2,201 verified by the server · 0 retries" (failures have their own link, <see cref="Failed"/>).</summary>
public static string ProgressLine(QueueSummary summary, CultureInfo culture) => string.Join(Separator,
L("Uploader.Progress.Sent", culture, summary.Sent, summary.Files),
L("Uploader.Progress.Verified", culture, summary.Verified),
Plural("Uploader.Progress.Retries", summary.Retries, culture));
/// <summary>"3 failed"; null when nothing failed.</summary>
public static string? Failed(QueueSummary summary, CultureInfo culture) =>
summary.Failed > 0 ? L("Uploader.Progress.Failed", culture, summary.Failed) : null;
private static (double Value, int Unit) Scale(double bytes)
{
var value = bytes;
var unit = 0;
while (value >= 999.95 && unit < ByteUnits.Length - 1)
while (value >= 999.95 && unit < SizeFormats.Length - 1)
{
value /= 1000;
unit++;
@@ -130,6 +130,9 @@ public sealed class UploadItem : INotifyPropertyChanged
public event PropertyChangedEventHandler? PropertyChanged;
/// <summary>The file name: what UI Automation reads for a queue row the list has not realized (virtualized).</summary>
public override string ToString() => FileName;
private void Set<T>(ref T field, T value, [CallerMemberName] string? name = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return;
@@ -0,0 +1,203 @@
using System.ComponentModel;
using Titano.Core.Localization;
using Titano.Protocol;
using Titano.Testing;
using Titano.Uploader.Server;
using Titano.Uploader.Shell;
using Titano.Uploader.Uploads;
namespace Titano.App.Tests.Uploader;
/// <summary>
/// The sign-in form puts each failure where DESIGN §4 wants it: a refused address or password marks that field
/// (message in its tooltip), other failures are one sentence, with Retry only where trying again can help.
/// </summary>
public sealed class ConnectViewModelTests
{
private const string Fingerprint = "AB:CD";
[Test]
public void NoFieldShowsAnErrorBeforeSigningIn()
{
var form = Form(new FakeSession());
Assert.False(form.HasErrors);
Assert.Empty(form.GetErrors(nameof(ConnectViewModel.Address)));
Assert.Null(form.PasswordError);
Assert.Null(form.ErrorText);
Assert.False(form.CanRetry);
Assert.Equal(Loc.L("Tooltips.Uploader.ServerAddress"), form.AddressToolTip);
Assert.Equal(Loc.L("Tooltips.Uploader.Password"), form.PasswordToolTip);
}
[Test]
public void AnInvalidAddressMarksTheServerFieldUntilItChanges()
{
var form = Form(new FakeSession(SignInResult.InvalidAddress));
var changed = new List<string?>();
form.ErrorsChanged += (_, e) => changed.Add(e.PropertyName);
form.SignInCommand.Execute(null);
var message = Loc.L("Uploader.Connect.Error.InvalidAddress");
Assert.True(form.HasErrors);
Assert.SequenceEqual([message], form.GetErrors(nameof(ConnectViewModel.Address)).Cast<string>());
Assert.Equal(message, form.AddressToolTip);
Assert.Contains(nameof(ConnectViewModel.Address), changed);
Assert.Null(form.ErrorText, "a field error is not repeated under the form");
Assert.False(form.CanRetry);
form.Address = "https://nas.local:9443";
Assert.False(form.HasErrors);
Assert.Equal(Loc.L("Tooltips.Uploader.ServerAddress"), form.AddressToolTip);
}
[Test]
public void AServerThatIsNotTitanoMarksTheServerField()
{
var form = Form(new FakeSession(SignInResult.NotTitano));
form.SignInCommand.Execute(null);
Assert.Equal(Loc.L("Uploader.Connect.Error.NotTitano"), form.AddressError);
Assert.Null(form.ErrorText);
}
[Test]
public void AWrongPasswordMarksThePasswordFieldUntilTheUserTypes()
{
var form = Form(new FakeSession(SignInResult.BadCredentials));
form.SignInCommand.Execute(null);
var message = Loc.L("Uploader.Connect.Error.BadCredentials");
Assert.Equal(message, form.PasswordError);
Assert.Equal(message, form.PasswordToolTip);
Assert.False(form.HasErrors, "the address is not in question");
Assert.Null(form.ErrorText);
Assert.False(form.CanRetry, "the same password would fail again");
form.Password = "another";
Assert.Null(form.PasswordError);
}
[Theory]
[Case(SignInResult.Unreachable, "Uploader.Connect.Error.Unreachable")]
[Case(SignInResult.Failed, "Uploader.Connect.Error.Failed")]
public void FailuresThatMayPassOfferRetry(SignInResult result, string key)
{
var form = Form(new FakeSession(result));
form.SignInCommand.Execute(null);
Assert.Equal(Loc.L(key), form.ErrorText);
Assert.True(form.CanRetry);
Assert.False(form.HasErrors);
Assert.Null(form.PasswordError);
}
[Test]
public void ADeclinedCertificateIsReportedWithoutRetry()
{
var session = new FakeSession(SignInResult.Untrusted);
var form = Form(session, trust: false);
form.SignInCommand.Execute(null);
Assert.Equal(Loc.L("Uploader.Connect.Error.Untrusted"), form.ErrorText);
Assert.False(form.CanRetry);
Assert.Equal(1, session.Attempts);
Assert.Null(session.Trusted);
}
[Test]
public void ATrustedCertificateSignsInAgainAndClearsEveryError()
{
var session = new FakeSession(SignInResult.BadCredentials, SignInResult.Untrusted, SignInResult.Success);
var form = Form(session, trust: true);
form.SignInCommand.Execute(null);
Assert.NotNull(form.PasswordError);
form.SignInCommand.Execute(null);
Assert.Equal(Fingerprint, session.Trusted);
Assert.Equal(3, session.Attempts);
Assert.Null(form.PasswordError);
Assert.Null(form.ErrorText);
Assert.False(form.HasErrors);
}
[Test]
public void TheFormSaysWhileItsOwnSignInRuns()
{
var session = new FakeSession(SignInResult.Unreachable);
var form = Form(session);
session.During = () => Assert.True(form.IsSigningIn, "signing in while the request runs");
form.SignInCommand.Execute(null);
Assert.Equal(1, session.Attempts);
Assert.False(form.IsSigningIn);
}
private static ConnectViewModel Form(FakeSession session, bool trust = false) =>
new(session, new FakeDialogs(trust), "https://nas.local:8443/", "alberto") { Password = "secret" };
/// <summary>Answers each sign-in with the next scripted result, moving through SigningIn as the real session does.</summary>
private sealed class FakeSession(params SignInResult[] results) : IServerSession
{
private ConnectionState _state = ConnectionState.SignedOut;
public event PropertyChangedEventHandler? PropertyChanged;
public event EventHandler<ServerProblem>? SessionEnded
{
add { }
remove { }
}
public int Attempts { get; private set; }
public string? Trusted { get; private set; }
public Action? During { get; set; }
public ConnectionState State => _state;
public string? Address => "https://nas.local:8443/";
public string? Username => "alberto";
public long QuotaBytes => 0;
public long UsedBytes => 0;
public int BandwidthLimit { get; set; }
public Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct)
{
var result = results[Math.Min(Attempts, results.Length - 1)];
Attempts++;
SetState(ConnectionState.SigningIn);
During?.Invoke();
SetState(result == SignInResult.Success ? ConnectionState.Connected : ConnectionState.SignedOut);
return Task.FromResult<(SignInResult, string?)>((result, result == SignInResult.Untrusted ? Fingerprint : null));
}
public void Trust(string fingerprint) => Trusted = fingerprint;
public Task SignOutAsync() => Task.CompletedTask;
public Task RefreshAsync() => Task.CompletedTask;
public Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken ct) => Task.FromResult<IReadOnlyList<SequenceDto>>([]);
private void SetState(ConnectionState state)
{
_state = state;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(State)));
}
}
private sealed class FakeDialogs(bool trust) : IUploaderDialogs
{
public IReadOnlyList<string> PickFiles() => [];
public string? PickFolder() => null;
public string? PickWatchFolder() => null;
public bool ConfirmTrust(string address, string fingerprint) => trust;
public bool ConfirmDeleteAfterUpload() => false;
}
}
@@ -0,0 +1,200 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Titano.App.Infrastructure;
using Titano.App.Tests.Windows;
using Titano.Core.Localization;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Theming;
using Titano.Uploader.DesignTime;
using Titano.Uploader.Shell;
using Titano.Uploader.Uploads;
namespace Titano.App.Tests.Uploader;
/// <summary>
/// The uploader window on the <c>--capture</c> sample data, shown off screen: icon-only buttons and queue rows are
/// named for screen readers, rows take keyboard focus, no field shows an error before use, disabled controls say
/// why, and in a right-to-left language the window mirrors while paths, file names and the media glyph do not.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(120_000)]
public sealed class UploaderScreenSmokeTests
{
[Test]
public Task EveryScreenIsNamedFocusableAndCalm() => ScreenHost.RunAsync(async () =>
{
UiLanguage.Apply("en");
using var screen = await UploaderScreen.OpenAsync();
var vm = screen.ViewModel;
screen.Sample.ShowConnect();
await screen.SettleAsync();
Assert.Equal(FlowDirection.LeftToRight, screen.Window.FlowDirection);
Assert.False(vm.Connect.HasErrors, "the address is not marked before a sign-in");
Assert.Null(vm.Connect.PasswordError);
Assert.Null(vm.Connect.ErrorText);
foreach (var box in screen.Visible<TextBox>())
Assert.False(Validation.GetHasError(box), $"{AutomationProperties.GetName(box)} shows an error before use");
Assert.False(screen.Named<Border>("PasswordErrorRing").IsVisible, "the password box shows no error before use");
screen.AssertIconButtonsNamed("connect");
// Enter signs in from the form, not from the settings panel drawn over it.
var signIn = screen.Visible<Button>().Single(b => Equals(b.Content, Loc.L("Uploader.Connect.SignIn")));
Assert.True(signIn.IsDefault, "Enter signs in");
vm.IsSettingsOpen = true;
await screen.SettleAsync();
Assert.False(signIn.IsDefault, "Enter in the settings panel does not sign in");
vm.IsSettingsOpen = false;
await screen.SettleAsync();
screen.Sample.ShowQueue();
await screen.SettleAsync();
screen.AssertIconButtonsNamed("queue");
Assert.Equal(Loc.L("Uploader.Queue.List"), AutomationProperties.GetName(screen.Named<ListBox>("ItemList")));
var rows = screen.Visible<ListBoxItem>();
Assert.NotEmpty(rows);
foreach (var row in rows)
{
Assert.True(row.Focusable, "queue rows take keyboard focus");
var item = (UploadItem)row.DataContext;
var name = UIElementAutomationPeer.CreatePeerForElement(row)?.GetName();
Assert.Contains(item.FileName, name);
Assert.Contains(UploadStateTextConverter.Text(item.State), name);
}
Assert.Contains(rows, r => r.DataContext == vm.CurrentItem);
Assert.NotNull(vm.FirstFailed());
Assert.NotNull(vm.FailedText);
Assert.True(screen.Named<Button>("FailedLink").IsVisible, "the failure count is a link to the failed file");
// Disabled controls say why; the settings panel keeps Tab inside it.
Assert.Equal(Loc.L("Tooltips.Uploader.SequenceDisabled"), vm.SequenceToolTip);
Assert.Equal(Loc.L("Tooltips.Uploader.Pause"), vm.PauseToolTip);
Assert.Equal(Loc.L("Tooltips.Uploader.Stop"), vm.StopToolTip);
Assert.Equal(KeyboardNavigationMode.Cycle, KeyboardNavigation.GetTabNavigation(screen.Named<Border>("SettingsPanel")));
vm.IsSettingsOpen = true;
await screen.SettleAsync();
screen.AssertIconButtonsNamed("settings");
vm.IsSettingsOpen = false;
});
[Test]
public Task TheWindowMirrorsForRightToLeftLanguages() => ScreenHost.RunAsync(async () =>
{
UiLanguage.Apply("ar");
try
{
using var screen = await UploaderScreen.OpenAsync();
screen.Sample.ShowQueue();
await screen.SettleAsync();
Assert.Equal(FlowDirection.RightToLeft, screen.Window.FlowDirection);
// File names, paths and addresses read left to right in every language.
var fileNames = screen.Visible<ListBoxItem>().Select(r => ((UploadItem)r.DataContext).FileName).ToHashSet();
var islands = screen.Visible<TextBlock>()
.Where(t => fileNames.Contains(t.Text) || t.Text.Contains('\\') || t.Text.StartsWith("https://", StringComparison.Ordinal))
.ToList();
Assert.NotEmpty(islands);
foreach (var text in islands) Assert.Equal(FlowDirection.LeftToRight, text.FlowDirection, text.Text);
// Media glyphs (pause, play) are not mirrored.
var pause = screen.Visible<Button>().Single(b => AutomationProperties.GetName(b) == screen.ViewModel.PauseLabel);
Assert.Equal(FlowDirection.LeftToRight, pause.FlowDirection);
screen.Sample.ShowConnect();
await screen.SettleAsync();
Assert.Equal(FlowDirection.LeftToRight, screen.Named<TextBox>("AddressBox").FlowDirection);
var mark = screen.Visible<BrandMarkIcon>().Single(m => m.ActualWidth >= 48);
Assert.Equal(FlowDirection.LeftToRight, mark.FlowDirection);
}
finally
{
UiLanguage.Apply("en");
}
});
/// <summary>A <see cref="MainWindow"/> on <see cref="SampleData"/>, shown off screen like <c>--capture</c>.</summary>
private sealed class UploaderScreen : IDisposable
{
private UploaderScreen(SampleData sample, MainViewModel viewModel, MainWindow window)
{
Sample = sample;
ViewModel = viewModel;
Window = window;
}
public SampleData Sample { get; }
public MainViewModel ViewModel { get; }
public MainWindow Window { get; }
public static async Task<UploaderScreen> OpenAsync()
{
ThemeManager.Apply(AppTheme.Dark);
var sample = new SampleData();
var vm = sample.CreateViewModel();
var window = new MainWindow(vm, sample.Settings)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
Width = 760,
Height = 700,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
var screen = new UploaderScreen(sample, vm, window);
await screen.SettleAsync();
return screen;
}
public async Task SettleAsync()
{
Window.UpdateLayout();
// Bindings, templates and the work the window defers to the dispatcher (scrolling, focus).
await Window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
await Task.Delay(30);
await Window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
Window.UpdateLayout();
}
public List<T> Visible<T>()
where T : FrameworkElement => [.. All<T>(Window).Where(e => e.IsVisible)];
public T Named<T>(string name)
where T : FrameworkElement => All<T>(Window).Single(e => e.Name == name);
/// <summary>DESIGN §4: an icon-only button carries an accessible name (and a tooltip).</summary>
public void AssertIconButtonsNamed(string screen)
{
foreach (var button in Visible<Button>().Where(b => b.Content is null))
{
Assert.False(string.IsNullOrWhiteSpace(AutomationProperties.GetName(button)), $"{screen}: an icon-only button has no name");
Assert.True(button.ToolTip is not null, $"{screen}: {AutomationProperties.GetName(button)} has no tooltip");
}
}
public void Dispose()
{
Window.Close();
ViewModel.Dispose();
}
private static IEnumerable<T> All<T>(DependencyObject node)
where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
{
var child = VisualTreeHelper.GetChild(node, i);
if (child is T match) yield return match;
foreach (var nested in All<T>(child)) yield return nested;
}
}
}
}
@@ -47,7 +47,23 @@ public sealed class UploaderTextTests
public void ProgressLineMatchesTheMockup()
{
Assert.Equal("2,214 of 4,812 sent · 2,201 verified by the server · 0 retries", UploaderText.ProgressLine(Mockup, En));
Assert.Equal("2,214 of 4,812 sent · 2,201 verified by the server · 1 retry · 3 failed", UploaderText.ProgressLine(Mockup with { Retries = 1, Failed = 3 }, En));
Assert.Equal("2,214 of 4,812 sent · 2,201 verified by the server · 1 retry", UploaderText.ProgressLine(Mockup with { Retries = 1, Failed = 3 }, En));
}
[Test]
public void FailuresHaveTheirOwnTextOnlyWhenThereAreAny()
{
Assert.Null(UploaderText.Failed(Mockup, En));
Assert.Equal("1,203 failed", UploaderText.Failed(Mockup with { Failed = 1_203 }, En));
Assert.Equal("3 non riusciti", UploaderText.Failed(Mockup with { Failed = 3 }, It));
}
[Test]
public void SizeUnitsFollowTheLanguage()
{
Assert.Equal("999 byte", UploaderText.Bytes(999, It));
Assert.Equal("1,5 KB", UploaderText.Bytes(1_536, It));
Assert.Equal("4,2 MB/s", UploaderText.Rate(4_240_000, It));
}
[Theory]
@@ -0,0 +1,52 @@
using Titano.Core.Localization;
using Titano.Testing;
using Titano.Uploader.Shell;
using Titano.Uploader.Text;
namespace Titano.App.Tests.Uploader;
/// <summary>A watch-folder chip shows the path (which it may shorten) and the interval apart; the tooltip carries the whole path.</summary>
public sealed class WatchFolderViewModelTests
{
private const string Path = @"\\garage-pi\cam";
[Test]
public void TheChipNamesThePathAndTheInterval()
{
var chip = Chip(isNetwork: false);
var interval = UploaderText.Duration(TimeSpan.FromMinutes(5), Loc.Culture);
Assert.Equal(Loc.L("Uploader.Watch.Interval", interval), chip.IntervalText);
Assert.Equal(Loc.L("Uploader.Watch.Chip", Path, interval), chip.Text);
}
[Test]
public void TheTooltipStartsWithTheWholePathKeptLeftToRight()
{
var interval = UploaderText.Duration(TimeSpan.FromMinutes(5), Loc.Culture);
var embedded = "\u202A" + Path + "\u202C · ";
Assert.Equal(embedded + Loc.L("Tooltips.Uploader.WatchFolder", interval), Chip(isNetwork: false).ToolTip);
Assert.Equal(embedded + Loc.L("Tooltips.Uploader.WatchFolderNetwork", interval), Chip(isNetwork: true).ToolTip);
var missing = Chip(isNetwork: true);
missing.IsAvailable = false;
Assert.Equal(embedded + Loc.L("Tooltips.Uploader.WatchFolderMissing", interval), missing.ToolTip);
}
[Test]
public void ANewIntervalRefreshesTheChip()
{
var chip = Chip(isNetwork: false);
var changed = new List<string?>();
chip.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
chip.IntervalSeconds = 60;
Assert.Contains(nameof(WatchFolderViewModel.IntervalText), changed);
Assert.Contains(nameof(WatchFolderViewModel.Text), changed);
Assert.Contains(nameof(WatchFolderViewModel.ToolTip), changed);
Assert.Equal(Loc.L("Uploader.Watch.Interval", UploaderText.Duration(TimeSpan.FromMinutes(1), Loc.Culture)), chip.IntervalText);
}
private static WatchFolderViewModel Chip(bool isNetwork) => new(Path, 300, isNetwork, (_, _) => { }, _ => { });
}