feat(app): library, jobs, settings, server, welcome and about screens

Local-mode composition root (SQLite index, one JobEngine fed by a single
handler registration list), keyset-paged library with thumbnail cache and
hover scrub, live job list with throttled updates and the shell job bar,
settings with live template validation and encoder self-test, server
connection with trust-on-first-use and DPAPI token, first-run welcome,
About with update check, and --capture screenshots with synthetic data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 12:26:58 +00:00
1 parent 446daeae2b
commit ffbea7cb74
94 files changed
+10130 -374

No files matched your search

@@ -8,10 +8,11 @@ namespace Titano.App.Infrastructure;
/// </summary>
public sealed class AppEnvironment
{
private AppEnvironment(string dataDirectory, bool portable)
private AppEnvironment(string dataDirectory, bool portable, bool isCapture)
{
DataDirectory = dataDirectory;
IsPortable = portable;
IsCapture = isCapture;
Directory.CreateDirectory(DataDirectory);
Directory.CreateDirectory(LogDirectory);
Directory.CreateDirectory(CacheDirectory);
@@ -19,8 +20,13 @@ public sealed class AppEnvironment
public string DataDirectory { get; }
public bool IsPortable { get; }
/// <summary>A throw-away environment for <c>--capture</c>: nothing of the user's data is read or written.</summary>
public bool IsCapture { get; }
public string LogDirectory => Path.Combine(DataDirectory, "logs");
public string CacheDirectory => Path.Combine(DataDirectory, "cache");
public string BackupDirectory => Path.Combine(DataDirectory, "backups");
public string DatabasePath => Path.Combine(DataDirectory, "titano.db");
public string SettingsPath => Path.Combine(DataDirectory, "settings.json");
@@ -28,8 +34,29 @@ public sealed class AppEnvironment
{
var exeDir = AppContext.BaseDirectory;
if (File.Exists(Path.Combine(exeDir, "portable.txt")))
return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true);
return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true, isCapture: false);
var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return new AppEnvironment(Path.Combine(local, "Titano"), portable: false);
return new AppEnvironment(Path.Combine(local, "Titano"), portable: false, isCapture: false);
}
/// <summary>A fresh temporary data folder for screenshots and smoke tests; delete it with <see cref="DeleteCaptureData"/>.</summary>
public static AppEnvironment ForCapture() =>
new(Path.Combine(Path.GetTempPath(), "titano-capture-" + Guid.CreateVersion7().ToString("N")), portable: false, isCapture: true);
/// <summary>Removes the temporary data folder of a capture environment (never a real one).</summary>
public void DeleteCaptureData()
{
if (!IsCapture) return;
try
{
Directory.Delete(DataDirectory, recursive: true);
}
catch (IOException)
{
// Files still open (log, database) are left to the OS temp cleanup.
}
catch (UnauthorizedAccessException)
{
}
}
}
@@ -0,0 +1,136 @@
using System.Net.Http;
using System.Reflection;
using Titano.App.About;
using Titano.App.Jobs;
using Titano.App.Library;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.Core.Diagnostics;
using Titano.Data;
using Titano.Data.Jobs;
namespace Titano.App.Infrastructure;
/// <summary>
/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open), the one
/// <see cref="JobEngine"/> of this PC with the handlers of <see cref="CreateJobHandlers"/>, thumbnails, the server
/// session, the encoder inventory, the update check and the archive setup. Started after the window shows, stopped
/// when the app exits.
/// </summary>
/// <remarks>
/// Integration points (one place each):
/// <list type="bullet">
/// <item><see cref="CreateJobHandlers"/> — register the archive handlers (scan, rebuild, verify, adopt, …) and the
/// render handler here.</item>
/// <item><see cref="ArchiveSetup"/> — replace <see cref="LocalArchiveSetup"/> with the archive engine's
/// implementation (it receives the first-run choices: create a local archive, adopt a folder).</item>
/// </list>
/// </remarks>
public sealed class AppServices : IAsyncDisposable
{
private static readonly Lazy<HttpClient> Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) });
public AppServices(AppEnvironment environment, AppSettings settings, Action saveSettings, IAppDialogs dialogs)
{
Environment = environment;
Settings = settings;
SaveSettingsAction = saveSettings;
Dialogs = dialogs;
ArchiveSetup = new LocalArchiveSetup(settings, saveSettings);
Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct);
}
public AppEnvironment Environment { get; }
public AppSettings Settings { get; }
public IAppDialogs Dialogs { get; }
private Action SaveSettingsAction { get; }
/// <summary>First-run archive actions; replaced by the integrator with the archive engine's implementation.</summary>
public IArchiveSetup ArchiveSetup { get; set; }
public ServerSession Server { get; set; }
public IEncoderInventory Encoders { get; set; }
/// <summary>Latest public release (GitHub Releases API of the releases repository, BRIEF §18).</summary>
public Func<CancellationToken, Task<ReleaseInfo?>> CheckForUpdateAsync { get; set; }
/// <summary>The index; null until <see cref="OpenAsync"/> succeeded.</summary>
public TitanoDatabase? Database { get; private set; }
public JobEngine? Engine { get; private set; }
public IJobQueue? Jobs { get; private set; }
public ThumbnailService? Thumbnails { get; private set; }
/// <summary>Why the index could not be opened; null when it is open.</summary>
public Exception? OpenError { get; private set; }
/// <summary>Node id of this PC's workers.</summary>
public string WorkerId { get; init; } = System.Environment.MachineName;
/// <summary>"0.1.0" (informational version).</summary>
public static string VersionText { get; } =
typeof(AppServices).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
/// <summary>
/// The job handlers of this PC's engine — the single registration list. The integrator adds the archive
/// handlers and the render handler here; a kind without a handler stays queued (it is never claimed here).
/// </summary>
public static IReadOnlyList<IJobHandler> CreateJobHandlers(AppServices services) =>
[
];
public void SaveSettings() => SaveSettingsAction();
/// <summary>Opens (or creates) the index at <paramref name="databasePath"/>, migrates it and starts the job engine.</summary>
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
{
try
{
Database = await Task.Run(() => TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(databasePath), ct), ct);
Log.Info("app", $"Index open (schema {Database.SchemaVersion}) at {databasePath}");
}
catch (Exception ex) when (ex is DatabaseException or System.IO.IOException or UnauthorizedAccessException or DllNotFoundException)
{
OpenError = ex;
Log.Error("app", "The index could not be opened", ex);
return;
}
await StartJobsAsync(Database, startEngine: true, ct);
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
}
/// <summary>Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped.</summary>
public async Task AttachAsync(TitanoDatabase database, bool startEngine = true, CancellationToken ct = default)
{
Database = database;
await StartJobsAsync(database, startEngine, ct);
Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems);
}
public async ValueTask DisposeAsync()
{
(Jobs as IDisposable)?.Dispose();
if (Engine is not null) await Engine.DisposeAsync();
Thumbnails?.Dispose();
Server.Dispose();
if (Database is not null) await Database.DisposeAsync();
}
private async Task StartJobsAsync(TitanoDatabase database, bool startEngine, CancellationToken ct)
{
var handlers = CreateJobHandlers(this);
var kinds = handlers.Select(h => h.Kind).Distinct().ToArray();
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds });
// With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
var started = startEngine && handlers.Count > 0;
if (started) await Engine.StartAsync(ct);
Jobs = new EngineJobQueue(database, Engine, started);
Log.Info("jobs", started ? $"Job engine started with {Engine.Options.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued");
}
}
+112 -6
View File
@@ -2,21 +2,119 @@ using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Titano.Core.IO;
using Titano.Core.Naming;
using Titano.Data.Repositories;
using Titano.Ui.Theming;
namespace Titano.App.Infrastructure;
/// <summary>Per-user preferences needed before the database opens (language, theme, window layout).</summary>
/// <summary>Library presentation (BRIEF §12.2).</summary>
public enum LibraryLayout
{
Grid,
List,
}
/// <summary>Rendering quality profile (Settings › Rendering).</summary>
public enum QualityProfile
{
Best,
Balanced,
Fast,
}
/// <summary>Which encoders a render may use (Settings › Rendering).</summary>
public enum HardwarePreference
{
PreferHardware,
SoftwareOnly,
HardwareForPreviews,
}
/// <summary>A server certificate the user trusted on first use (BRIEF §12.7).</summary>
public sealed class TrustedCertificate
{
public string Fingerprint { get; set; } = string.Empty;
public string? Server { get; set; }
public DateTimeOffset TrustedAt { get; set; }
}
/// <summary>
/// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in
/// <c>settings.json</c> next to the database and written atomically, because language and theme apply before the
/// database opens.
/// </summary>
public sealed class AppSettings
{
public const int DefaultThumbnailMemoryItems = 2_000;
public const int DefaultCacheLimitGb = 20;
// ---- General ----
public string? Language { get; set; }
public AppTheme Theme { get; set; } = AppTheme.Dark;
public bool RailCollapsed { get; set; }
public bool CheckForUpdates { get; set; } = true;
public bool AnonymousUsageCounts { get; set; }
public string? LastArchivePath { get; set; }
public WindowPlacement? Window { get; set; }
/// <summary>The first-run choice (local archive, adopted folder or server) was made.</summary>
public bool FirstRunCompleted { get; set; }
// ---- Updates ----
public bool CheckForUpdates { get; set; } = true;
// ---- Archive ----
/// <summary>Root of the local archive; null until the first-run choice or Settings › Archive sets it.</summary>
public string? LastArchivePath { get; set; }
public string FolderTemplate { get; set; } = TemplateDefaults.Folder;
public string FileTemplate { get; set; } = TemplateDefaults.File;
/// <summary>Proxy long edge for new archives; 0 = full size.</summary>
public int ProxyLongEdge { get; set; } = 1920;
// ---- Library ----
public LibraryLayout LibraryLayout { get; set; } = LibraryLayout.Grid;
public SequenceSort LibrarySort { get; set; } = SequenceSort.Newest;
// ---- Rendering ----
public QualityProfile Quality { get; set; } = QualityProfile.Balanced;
/// <summary>Frame memory budget in GB; null = Auto (a quarter of installed memory).</summary>
public int? MemoryBudgetGb { get; set; }
/// <summary>Worker threads; null = Auto (cores minus four, at least one).</summary>
public int? Parallelism { get; set; }
public bool BackgroundPriority { get; set; } = true;
public HardwarePreference HardwareEncoding { get; set; } = HardwarePreference.PreferHardware;
// ---- Storage ----
/// <summary>Cache (spill frames, thumbnails); null = <c>cache</c> under the data folder.</summary>
public string? CacheFolder { get; set; }
/// <summary>Decoded thumbnails kept in memory.</summary>
public int ThumbnailMemoryItems { get; set; } = DefaultThumbnailMemoryItems;
/// <summary>Upper bound of the disk cache in GB.</summary>
public int CacheLimitGb { get; set; } = DefaultCacheLimitGb;
// ---- Server ----
public string? ServerUrl { get; set; }
public string? ServerUsername { get; set; }
/// <summary>The session token, encrypted for this Windows user with DPAPI (Base64).</summary>
public string? ProtectedToken { get; set; }
public List<TrustedCertificate> TrustedCertificates { get; set; } = [];
public List<string> RecentServers { get; set; } = [];
/// <summary>Let the server send render jobs to this PC (BRIEF §14.7).</summary>
public bool RenderNodeOptIn { get; set; }
// ---- Jobs ----
/// <summary>"Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history).</summary>
public DateTimeOffset? JobsClearedAt { get; set; }
public sealed class WindowPlacement
{
public double Left { get; set; }
@@ -30,8 +128,7 @@ public sealed class AppSettings
{
try
{
if (File.Exists(path))
return JsonSerializer.Deserialize(File.ReadAllText(path), AppSettingsJson.Default.AppSettings) ?? new AppSettings();
if (File.Exists(path)) return Parse(File.ReadAllText(path)) ?? new AppSettings();
}
catch (JsonException)
{
@@ -43,7 +140,16 @@ public sealed class AppSettings
return new AppSettings();
}
public void Save(string path) => AtomicFile.WriteAllText(path, JsonSerializer.Serialize(this, AppSettingsJson.Default.AppSettings));
/// <summary>Reads settings JSON (Settings › Import); null when the text is not a settings object.</summary>
/// <exception cref="JsonException">The text is not valid JSON.</exception>
public static AppSettings? Parse(string json) => JsonSerializer.Deserialize(json, AppSettingsJson.Default.AppSettings);
public string ToJson() => JsonSerializer.Serialize(this, AppSettingsJson.Default.AppSettings);
public void Save(string path) => AtomicFile.WriteAllText(path, ToJson());
/// <summary>A deep copy (JSON round trip), used for import and reset.</summary>
public AppSettings Clone() => Parse(ToJson()) ?? new AppSettings();
}
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)]
@@ -0,0 +1,104 @@
using System.IO;
using Titano.Core.Diagnostics;
namespace Titano.App.Infrastructure;
/// <summary>
/// First-run archive choices (BRIEF §12.1): create a local archive or adopt an existing folder tree. The
/// integrator replaces <see cref="LocalArchiveSetup"/> with an implementation backed by the archive engine (folder
/// layout, index, adopt job); see <see cref="AppServices"/>.
/// </summary>
public interface IArchiveSetup
{
/// <summary>Creates (or opens) the local archive rooted at <paramref name="root"/>.</summary>
Task CreateAsync(string root, CancellationToken cancellationToken = default);
/// <summary>Indexes the photos under <paramref name="folder"/> in place, or opens a previous Titano archive there.</summary>
Task AdoptAsync(string folder, CancellationToken cancellationToken = default);
}
/// <summary>Until the archive engine is connected: remembers the chosen root in the settings and nothing else.</summary>
public sealed class LocalArchiveSetup(AppSettings settings, Action save) : IArchiveSetup
{
public Task CreateAsync(string root, CancellationToken cancellationToken = default)
{
Remember(root);
Log.Info("archive", $"Local archive root set to {root}");
return Task.CompletedTask;
}
public Task AdoptAsync(string folder, CancellationToken cancellationToken = default)
{
Remember(folder);
Log.Info("archive", $"Adopted folder recorded: {folder}");
return Task.CompletedTask;
}
private void Remember(string path)
{
settings.LastArchivePath = Path.GetFullPath(path);
save();
}
}
/// <summary>Archive roots offered by default and their free space.</summary>
public static class ArchiveLocations
{
public const string DefaultFolderName = "TitanoArchive";
/// <summary>"&lt;fixed drive with the most free space&gt;\TitanoArchive".</summary>
public static string SuggestRoot()
{
try
{
var best = DriveInfo.GetDrives()
.Where(d => d.DriveType == DriveType.Fixed && d.IsReady)
.OrderByDescending(d => d.AvailableFreeSpace)
.FirstOrDefault();
if (best is not null) return Path.Combine(best.RootDirectory.FullName, DefaultFolderName);
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), DefaultFolderName);
}
/// <summary>Free bytes on the volume of <paramref name="path"/>; null when unknown.</summary>
public static long? FreeSpace(string? path)
{
if (string.IsNullOrWhiteSpace(path)) return null;
try
{
var root = Path.GetPathRoot(Path.GetFullPath(path));
if (string.IsNullOrEmpty(root)) return null;
var drive = new DriveInfo(root);
return drive.IsReady ? drive.AvailableFreeSpace : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
return null;
}
}
/// <summary>The problem of an archive root as a localized sentence; null when it can be used.</summary>
public static string? Validate(string? path)
{
if (string.IsNullOrWhiteSpace(path)) return Core.Localization.Loc.L("Errors.Path.Empty");
try
{
if (!Path.IsPathFullyQualified(path)) return Core.Localization.Loc.L("Errors.Path.NotAbsolute");
var full = Path.GetFullPath(path);
if (File.Exists(full)) return Core.Localization.Loc.L("Errors.Path.IsFile");
var root = Path.GetPathRoot(full);
if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) return Core.Localization.Loc.L("Errors.Path.NoDrive");
return null;
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return Core.Localization.Loc.L("Errors.Path.Invalid");
}
}
}
@@ -0,0 +1,147 @@
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Runtime.InteropServices;
using System.Text;
namespace Titano.App.Infrastructure;
/// <summary>
/// The diagnostics bundle of About and Settings › Advanced (BRIEF §12.9): the log files plus an environment report
/// (versions, OS, runtime, culture, folders), zipped into a folder the user chose. Settings and tokens are not included.
/// </summary>
public static class DiagnosticsBundle
{
/// <summary>Writes "Titano diagnostics yyyy-MM-dd HHmm.zip" into <paramref name="folder"/> and returns its path.</summary>
public static Task<string> CreateAsync(AppEnvironment environment, string folder, IEnumerable<string>? extraLines = null, CancellationToken ct = default) =>
Task.Run(() =>
{
var path = Path.Combine(folder, $"Titano diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}.zip");
var temp = path + ".tmp";
using (var zip = ZipFile.Open(temp, ZipArchiveMode.Create))
{
var report = zip.CreateEntry("environment.txt", CompressionLevel.Optimal);
using (var writer = new StreamWriter(report.Open(), new UTF8Encoding(false)))
{
writer.Write(Report(environment, extraLines));
}
if (Directory.Exists(environment.LogDirectory))
{
foreach (var log in Directory.EnumerateFiles(environment.LogDirectory, "*.log").OrderBy(f => f, StringComparer.Ordinal))
{
ct.ThrowIfCancellationRequested();
var entry = zip.CreateEntry("logs/" + Path.GetFileName(log), CompressionLevel.Optimal);
// The current log is open for writing: share the handle instead of copying the file.
using var source = new FileStream(log, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
using var target = entry.Open();
source.CopyTo(target);
}
}
}
File.Move(temp, path, overwrite: true);
return path;
}, ct);
/// <summary>Plain-text environment report.</summary>
public static string Report(AppEnvironment environment, IEnumerable<string>? extraLines = null)
{
var sb = new StringBuilder();
sb.AppendLine(CultureInfo.InvariantCulture, $"Titano {AppServices.VersionText}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Created {DateTimeOffset.Now:O}");
sb.AppendLine(CultureInfo.InvariantCulture, $"OS {RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture})");
sb.AppendLine(CultureInfo.InvariantCulture, $"Runtime {RuntimeInformation.FrameworkDescription} ({RuntimeInformation.ProcessArchitecture})");
sb.AppendLine(CultureInfo.InvariantCulture, $"Culture {CultureInfo.CurrentCulture.Name} / UI {CultureInfo.CurrentUICulture.Name}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Processors {Environment.ProcessorCount}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Memory {GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / (1024 * 1024)} MB");
sb.AppendLine(CultureInfo.InvariantCulture, $"Data {environment.DataDirectory} (portable: {environment.IsPortable})");
if (extraLines is not null)
{
foreach (var line in extraLines) sb.AppendLine(line);
}
return sb.ToString();
}
}
/// <summary>
/// The disk cache (spilled frames, thumbnails): its folder, its size and clearing it. Only a folder Titano created
/// (it carries a marker file) is ever emptied, so pointing the cache at a folder with user files cannot delete them.
/// </summary>
public static class CacheStore
{
public const string MarkerFile = ".titano-cache";
/// <summary>The cache folder in effect.</summary>
public static string Folder(AppEnvironment environment, AppSettings settings) =>
string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!;
/// <summary>Creates the folder (if needed) and marks it as Titano's.</summary>
public static void Prepare(string folder)
{
Directory.CreateDirectory(folder);
var marker = Path.Combine(folder, MarkerFile);
if (!File.Exists(marker)) File.WriteAllText(marker, "Titano cache folder. Its contents can be deleted at any time.");
}
/// <summary>True when <paramref name="folder"/> is a Titano cache folder (safe to empty).</summary>
public static bool IsOwned(string folder) => File.Exists(Path.Combine(folder, MarkerFile));
/// <summary>Total bytes of the files in the cache (0 when missing).</summary>
public static long Size(string folder)
{
if (!Directory.Exists(folder)) return 0;
long total = 0;
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", options)) total += file.Length;
return total;
}
/// <summary>Deletes everything inside an owned cache folder except the marker; returns the bytes freed.</summary>
/// <exception cref="InvalidOperationException">The folder is not a Titano cache folder.</exception>
public static long Clear(string folder)
{
if (!Directory.Exists(folder)) return 0;
if (!IsOwned(folder)) throw new InvalidOperationException("Not a Titano cache folder: " + folder);
long freed = 0;
var root = new DirectoryInfo(folder);
foreach (var file in root.EnumerateFiles())
{
if (file.Name == MarkerFile) continue;
freed += TryDelete(file);
}
foreach (var directory in root.EnumerateDirectories())
{
if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) continue;
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
foreach (var file in directory.EnumerateFiles("*", options)) freed += TryDelete(file);
try
{
directory.Delete(recursive: true);
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
}
return freed;
}
private static long TryDelete(FileInfo file)
{
try
{
var length = file.Length;
file.Delete();
return length;
}
catch (IOException)
{
return 0; // in use (a render spilling right now)
}
catch (UnauthorizedAccessException)
{
return 0;
}
}
}
@@ -26,9 +26,34 @@ public static class Formatting
/// <summary>Compact duration: "2 h 00 m", "5 min", "40 s".</summary>
public static string Duration(TimeSpan t)
{
if (t < TimeSpan.Zero) t = TimeSpan.Zero;
if (t.TotalHours >= 24) return Loc.L("Common.Duration.Days", (int)t.TotalDays, t.Hours);
if (t.TotalHours >= 1) return Loc.L("Common.Duration.Hours", (int)t.TotalHours, t.Minutes.ToString("00", Loc.Culture));
if (t.TotalMinutes >= 1) return Loc.L("Common.Duration.Minutes", (int)Math.Round(t.TotalMinutes));
return Loc.L("Common.Duration.Seconds", (int)Math.Round(t.TotalSeconds));
}
/// <summary>Clock-style elapsed time for finished jobs: "2:41", "1:02:41".</summary>
public static string Elapsed(TimeSpan t)
{
if (t < TimeSpan.Zero) t = TimeSpan.Zero;
return t.TotalHours >= 1
? ((int)t.TotalHours).ToString(Loc.Culture) + ":" + t.Minutes.ToString("00", Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture)
: ((int)t.TotalMinutes).ToString(Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture);
}
/// <summary>0.62 → "62 %".</summary>
public static string Percent(double fraction) => Loc.L("Common.Percent", Math.Round(Math.Clamp(fraction, 0, 1) * 100).ToString("0", Loc.Culture));
/// <summary>Items per second with one decimal below 100: "11.3", "118".</summary>
public static string Rate(double perSecond) => perSecond.ToString(perSecond < 100 ? "0.#" : "N0", Loc.Culture);
/// <summary>Local time of day in the culture's short format ("09:12").</summary>
public static string TimeOfDay(DateTimeOffset at) => at.ToLocalTime().ToString("t", Loc.Culture);
/// <summary>Calendar date in the culture's short format.</summary>
public static string Date(DateTimeOffset at) => at.ToLocalTime().ToString("d", Loc.Culture);
/// <summary>Camera wall-clock date in the culture's short format.</summary>
public static string Date(DateTime wallClock) => wallClock.ToString("d", Loc.Culture);
}
@@ -0,0 +1,39 @@
namespace Titano.App.Infrastructure;
/// <summary>Texts of a confirmation dialog (DESIGN §4: two buttons, safe action left and default).</summary>
public sealed record ConfirmRequest
{
public required string Heading { get; init; }
public required string Message { get; init; }
/// <summary>Monospaced detail (certificate fingerprint); null hides it.</summary>
public string? Detail { get; init; }
public string? DetailToolTip { get; init; }
public required string SafeText { get; init; }
public required string SafeToolTip { get; init; }
public required string ActionText { get; init; }
public required string ActionToolTip { get; init; }
/// <summary>Warning-outlined action (never a primary) for data-destroying choices.</summary>
public bool IsDestructive { get; init; }
}
/// <summary>Modal questions and OS pickers the view models ask for (BRIEF §12.1: modals only for confirmations and login).</summary>
public interface IAppDialogs
{
/// <summary>A folder chosen in the shell's folder picker; null when cancelled.</summary>
string? PickFolder(string title, string? initialFolder = null);
/// <summary>A JSON file chosen in the shell's Open dialog; null when cancelled.</summary>
string? PickJsonFile(string title);
/// <summary>True when the user chose the action.</summary>
bool Confirm(ConfirmRequest request);
/// <summary>
/// The login form. <paramref name="signIn"/> receives user and password and returns null on success or the
/// error sentence to show; the form stays open until it succeeds or the user cancels. True when signed in.
/// </summary>
bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn);
}
@@ -8,7 +8,15 @@ public static class ProductLinks
.OfType<System.Reflection.AssemblyMetadataAttribute>()
.FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value ?? "alby96/titano-releases";
public static string Releases => $"https://github.com/{ReleasesRepository}/releases";
public static string Repository => $"https://github.com/{ReleasesRepository}";
public static string Releases => $"{Repository}/releases";
public static string LatestReleaseApi => $"https://api.github.com/repos/{ReleasesRepository}/releases/latest";
/// <summary>The licence (EULA) published with the releases (BRIEF §12.9).</summary>
public static string Licence => $"{Repository}/blob/HEAD/LICENSE.md";
/// <summary>Where translations are reviewed by the community (BRIEF §16).</summary>
public static string Issues => $"{Repository}/issues";
}
+18 -7
View File
@@ -1,20 +1,31 @@
using System.Diagnostics;
using System.IO;
using Titano.Core.Diagnostics;
using Titano.Core.Windows.Shell;
namespace Titano.App.Infrastructure;
/// <summary>The only shell launches the product performs (BRIEF §8.6): open a URL, reveal a folder.</summary>
/// <summary>The only shell launches the product performs (BRIEF §8.6): open a web or Store link, reveal a folder or file.</summary>
public static class ShellActions
{
public static void OpenUrl(string url)
{
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("https" or "http" or "ms-windows-store")) return;
Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true });
if (!ShellLauncher.IsAllowedUrl(url)) return;
try
{
if (!ShellLauncher.OpenUrl(url)) Log.Warning("shell", $"The shell could not open {url}");
}
catch (Exception ex) when (ex is ArgumentException or System.ComponentModel.Win32Exception)
{
Log.Warning("shell", $"The shell could not open {url}", ex);
}
}
public static void OpenFolder(string path)
/// <summary>Opens a folder in Explorer, or shows a file selected in its folder.</summary>
public static void Reveal(string path)
{
if (!Directory.Exists(path)) return;
Process.Start(new ProcessStartInfo(path) { UseShellExecute = true, Verb = "explore" });
if (string.IsNullOrWhiteSpace(path) || !(Directory.Exists(path) || File.Exists(path))) return;
if (!ShellLauncher.RevealInExplorer(path)) Log.Warning("shell", $"Explorer could not show {path}");
}
public static void OpenFolder(string path) => Reveal(path);
}
@@ -0,0 +1,33 @@
using System.Globalization;
using System.Windows;
using Titano.Core.Localization;
namespace Titano.App.Infrastructure;
/// <summary>Switches the UI language at run time without restart (BRIEF §16), mirroring right-to-left languages.</summary>
public static class UiLanguage
{
/// <summary>Applies <paramref name="code"/> (or the OS language when null) and returns the culture in use.</summary>
public static CultureInfo Apply(string? code)
{
CultureInfo requested;
try
{
requested = code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code);
}
catch (CultureNotFoundException)
{
requested = CultureInfo.CurrentUICulture;
}
var culture = Languages.BestMatch(requested);
CultureInfo.DefaultThreadCurrentUICulture = culture;
CultureInfo.CurrentUICulture = culture;
Loc.SetCulture(culture);
if (Application.Current is { } app)
{
foreach (Window window in app.Windows)
window.FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
}
return culture;
}
}