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:
94 files changed
+10130
-374
No files matched your search
@@ -0,0 +1,76 @@
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Titano.App.About;
|
||||
|
||||
/// <summary>The newest public release (BRIEF §18).</summary>
|
||||
public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl);
|
||||
|
||||
/// <summary>
|
||||
/// Update check against the GitHub Releases API of the public releases repository (BRIEF §18, §19.4): reads the
|
||||
/// latest release, ignores drafts and pre-releases, and compares its tag with the running version.
|
||||
/// </summary>
|
||||
public static class UpdateCheck
|
||||
{
|
||||
/// <summary>"v1.2.3", "1.2.3", "v1.2.3-beta.1" → 1.2.3; null for anything else.</summary>
|
||||
public static Version? ParseVersion(string? tag)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tag)) return null;
|
||||
var text = tag.Trim();
|
||||
if (text.StartsWith('v') || text.StartsWith('V')) text = text[1..];
|
||||
var end = text.IndexOfAny(['-', '+', ' ']);
|
||||
if (end >= 0) text = text[..end];
|
||||
if (!Version.TryParse(text, out var version)) return null;
|
||||
// Normalise to three parts so 1.2 equals 1.2.0.
|
||||
return new Version(version.Major, version.Minor, Math.Max(0, version.Build));
|
||||
}
|
||||
|
||||
/// <summary>The release described by a <c>releases/latest</c> response; null for drafts, pre-releases or unparsable tags.</summary>
|
||||
public static ReleaseInfo? Parse(string json)
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
var root = document.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object) return null;
|
||||
if (Flag(root, "draft") || Flag(root, "prerelease")) return null;
|
||||
var tag = root.TryGetProperty("tag_name", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null;
|
||||
var url = root.TryGetProperty("html_url", out var u) && u.ValueKind == JsonValueKind.String ? u.GetString() : null;
|
||||
var version = ParseVersion(tag);
|
||||
if (version is null || tag is null || url is null || !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
return new ReleaseInfo(version, tag, url);
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="release"/> is newer than <paramref name="running"/> (build/revision ignored).</summary>
|
||||
public static bool IsNewer(ReleaseInfo release, Version running) =>
|
||||
release.Version > new Version(running.Major, running.Minor, Math.Max(0, running.Build));
|
||||
|
||||
/// <summary>The running version from an informational version such as "0.1.0" or "0.1.0+abc".</summary>
|
||||
public static Version RunningVersion(string informationalVersion) => ParseVersion(informationalVersion) ?? new Version(0, 0, 0);
|
||||
|
||||
/// <summary>Asks the releases API for the latest release; null when there is none (404) or it cannot be read.</summary>
|
||||
/// <exception cref="HttpRequestException">The request failed.</exception>
|
||||
public static async Task<ReleaseInfo?> FetchAsync(HttpClient http, string apiUrl, string userAgentVersion, CancellationToken ct)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, apiUrl);
|
||||
request.Headers.UserAgent.Add(new ProductInfoHeaderValue("Titano", userAgentVersion));
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
|
||||
using var response = await http.SendAsync(request, ct).ConfigureAwait(false);
|
||||
if (response.StatusCode == System.Net.HttpStatusCode.NotFound) return null;
|
||||
response.EnsureSuccessStatusCode();
|
||||
var json = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return Parse(json);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Flag(JsonElement root, string name) =>
|
||||
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True;
|
||||
|
||||
/// <summary>"0.2.0" for display.</summary>
|
||||
public static string Display(Version version) => version.ToString(Math.Clamp(version.Build < 0 ? 2 : 3, 2, 3));
|
||||
}
|
||||
+47
-20
@@ -1,37 +1,45 @@
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.DesignTime;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Ui.Mvvm;
|
||||
using Titano.Ui.Theming;
|
||||
|
||||
namespace Titano.App;
|
||||
|
||||
/// <summary>
|
||||
/// Titano desktop client. Local mode starts here: settings and language before the first window, then the window,
|
||||
/// then the index and the job engine (<see cref="AppServices"/>) off the UI thread. <c>--capture <dir></c>
|
||||
/// renders every screen with synthetic data in a throw-away data folder and exits.
|
||||
/// </summary>
|
||||
public partial class App : Application
|
||||
{
|
||||
private FileLogSink? _log;
|
||||
|
||||
public AppEnvironment Environment { get; private set; } = null!;
|
||||
public AppSettings Settings { get; private set; } = null!;
|
||||
public AppServices Services { get; private set; } = null!;
|
||||
|
||||
public static new App Current => (App)Application.Current;
|
||||
|
||||
protected override void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
base.OnStartup(e);
|
||||
Environment = AppEnvironment.Detect();
|
||||
var captureIndex = Array.IndexOf(e.Args, "--capture");
|
||||
var capture = captureIndex >= 0;
|
||||
// Capture never reads or writes the user's data folder.
|
||||
Environment = capture ? AppEnvironment.ForCapture() : AppEnvironment.Detect();
|
||||
_log = new FileLogSink(Environment.LogDirectory, "titano");
|
||||
var capture = Array.IndexOf(e.Args, "--capture") >= 0;
|
||||
// Capture runs in CI: mirror the log to stderr so failures are visible in the job output.
|
||||
Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log);
|
||||
Log.Info("app", $"Titano {typeof(App).Assembly.GetName().Version} starting; data at {Environment.DataDirectory}");
|
||||
Log.Info("app", $"Titano {AppServices.VersionText} starting; data at {Environment.DataDirectory}");
|
||||
|
||||
Settings = AppSettings.Load(Environment.SettingsPath);
|
||||
ApplyLanguage(Settings.Language);
|
||||
ThemeManager.Initialize(this, Settings.Theme);
|
||||
Settings = capture ? new AppSettings { Language = "en" } : AppSettings.Load(Environment.SettingsPath);
|
||||
UiLanguage.Apply(Settings.Language);
|
||||
ThemeManager.Initialize(this, capture ? AppTheme.Dark : Settings.Theme);
|
||||
AppResources.Merge(this);
|
||||
|
||||
DispatcherUnhandledException += OnUnhandledException;
|
||||
AppDomain.CurrentDomain.UnhandledException += (_, args) => Log.Error("app", "Unhandled exception", args.ExceptionObject as Exception);
|
||||
@@ -41,30 +49,37 @@ public partial class App : Application
|
||||
args.SetObserved();
|
||||
};
|
||||
|
||||
var shell = new ShellViewModel(Settings);
|
||||
var dialogs = new AppDialogs();
|
||||
Services = new AppServices(Environment, Settings, SaveSettings, dialogs);
|
||||
SampleData? sample = capture ? SampleData.Configure(Services) : null;
|
||||
var shell = new ShellViewModel(Services);
|
||||
AsyncRelayCommand.Failed += ex => shell.ReportError(ex);
|
||||
var window = new MainWindow(shell);
|
||||
dialogs.Owner = window;
|
||||
MainWindow = window;
|
||||
|
||||
var captureIndex = Array.IndexOf(e.Args, "--capture");
|
||||
if (capture)
|
||||
{
|
||||
var dir = captureIndex + 1 < e.Args.Length ? e.Args[captureIndex + 1] : "screenshots";
|
||||
ScreenCapture.Run(window, shell, dir);
|
||||
_ = ScreenCapture.RunAsync(window, shell, sample!, dir);
|
||||
return;
|
||||
}
|
||||
window.Show();
|
||||
_ = StartAsync(shell);
|
||||
}
|
||||
|
||||
/// <summary>Switches the UI language at run time (BRIEF §16) and remembers the choice.</summary>
|
||||
public void ApplyLanguage(string? code)
|
||||
/// <summary>Opens the index and the job engine after the window is visible, then fills the screens.</summary>
|
||||
private async Task StartAsync(ShellViewModel shell)
|
||||
{
|
||||
var culture = Languages.BestMatch(code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code));
|
||||
CultureInfo.DefaultThreadCurrentUICulture = culture;
|
||||
CultureInfo.CurrentUICulture = culture;
|
||||
Loc.SetCulture(culture);
|
||||
foreach (Window w in Windows)
|
||||
w.FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
|
||||
try
|
||||
{
|
||||
await Services.OpenAsync(Environment.DatabasePath);
|
||||
await shell.StartAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
shell.ReportError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void SaveSettings()
|
||||
@@ -73,7 +88,7 @@ public partial class App : Application
|
||||
{
|
||||
Settings.Save(Environment.SettingsPath);
|
||||
}
|
||||
catch (System.IO.IOException ex)
|
||||
catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("app", "Settings not saved", ex);
|
||||
}
|
||||
@@ -82,8 +97,20 @@ public partial class App : Application
|
||||
protected override void OnExit(ExitEventArgs e)
|
||||
{
|
||||
SaveSettings();
|
||||
if (MainWindow?.DataContext is ShellViewModel shell) shell.Dispose();
|
||||
try
|
||||
{
|
||||
// Data and engine code continue on the thread pool, so waiting here cannot deadlock the dispatcher.
|
||||
if (Services is not null && !Services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)))
|
||||
Log.Warning("app", "Services did not stop within 10 s");
|
||||
}
|
||||
catch (AggregateException ex)
|
||||
{
|
||||
Log.Warning("app", "Services stopped with an error", ex);
|
||||
}
|
||||
Log.Info("app", "Titano exiting");
|
||||
_log?.Dispose();
|
||||
if (Environment.IsCapture) Environment.DeleteCaptureData();
|
||||
base.OnExit(e);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using Titano.App.About;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Server;
|
||||
using Titano.App.Settings;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Data;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.App.DesignTime;
|
||||
|
||||
/// <summary>
|
||||
/// Synthetic content for <c>--capture</c> screenshots and the screen smoke tests ONLY: a temporary SQLite index
|
||||
/// with an archive of generated JPEGs (one sequence stores its thumbnail as an embedded preview inside a fake RAW
|
||||
/// file), jobs in every state, a fake signed-in server and a fake encoder inventory. Everything lives in the
|
||||
/// capture environment's temporary folder; nothing touches the network or the user's data.
|
||||
/// </summary>
|
||||
public sealed class SampleData
|
||||
{
|
||||
public const string ServerFingerprint = "9A:3C:71:E0:5B:12:C4:88:0F:6D:2A:91:E7:44:B3:5C:19:D2:6F:80:A1:3E:57:C9:0B:64:F8:2D:93:A6:71:CE";
|
||||
|
||||
private readonly AppServices _services;
|
||||
private TitanoDatabase? _db;
|
||||
|
||||
private SampleData(AppServices services) => _services = services;
|
||||
|
||||
/// <summary>Points the services at fakes (server, encoders, update check) for an empty first-run state.</summary>
|
||||
public static SampleData Configure(AppServices services)
|
||||
{
|
||||
if (!services.Environment.IsCapture) throw new InvalidOperationException("Sample data only runs in a capture environment.");
|
||||
var settings = services.Settings;
|
||||
services.Server.Dispose();
|
||||
services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(), new PlainTokenProtector());
|
||||
services.Encoders = new SampleEncoders();
|
||||
services.CheckForUpdateAsync = _ => Task.FromResult<ReleaseInfo?>(null);
|
||||
return new SampleData(services);
|
||||
}
|
||||
|
||||
/// <summary>Opens the empty temporary index (first run: no archive, nothing indexed).</summary>
|
||||
public async Task OpenEmptyAsync()
|
||||
{
|
||||
_db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(_services.Environment.DatabasePath));
|
||||
await _services.AttachAsync(_db, startEngine: false);
|
||||
}
|
||||
|
||||
/// <summary>Fills the index with sample sequences, frames and jobs, and saves a signed-in server session.</summary>
|
||||
public async Task FillAsync()
|
||||
{
|
||||
var db = _db ?? throw new InvalidOperationException("OpenEmptyAsync first.");
|
||||
var settings = _services.Settings;
|
||||
var root = Path.Combine(_services.Environment.DataDirectory, "archive");
|
||||
Directory.CreateDirectory(root);
|
||||
var archive = new Archive { Id = Guid.CreateVersion7(), Name = "TitanoArchive", RootPath = root, Created = DateTimeOffset.UtcNow.AddYears(-2) };
|
||||
await db.Archives.UpsertAsync(archive);
|
||||
|
||||
var sequences = Sequences(archive.Id).ToList();
|
||||
foreach (var (sequence, colours, raw) in sequences)
|
||||
{
|
||||
await db.Sequences.UpsertAsync(sequence);
|
||||
await db.Frames.BulkInsertAsync(WriteFrames(root, sequence, colours, raw));
|
||||
}
|
||||
await db.Sequences.SetTagsAsync(sequences[0].Sequence.Id, ["sunset", "harbour"]);
|
||||
await db.Sequences.SetTagsAsync(sequences[9].Sequence.Id, ["holy grail"]);
|
||||
|
||||
foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job);
|
||||
|
||||
settings.LastArchivePath = @"D:\TitanoArchive";
|
||||
settings.ServerUrl = "https://nas.local:8443";
|
||||
settings.ServerUsername = "alberto";
|
||||
settings.ProtectedToken = "sample-token";
|
||||
settings.TrustedCertificates = [new TrustedCertificate { Fingerprint = ServerFingerprint, Server = "https://nas.local:8443", TrustedAt = new DateTimeOffset(2026, 9, 1, 9, 30, 0, TimeSpan.Zero) }];
|
||||
settings.RecentServers = ["https://nas.local:8443"];
|
||||
settings.RenderNodeOptIn = true;
|
||||
settings.FirstRunCompleted = true;
|
||||
}
|
||||
|
||||
private IEnumerable<(Sequence Sequence, string[] Colours, bool Raw)> Sequences(Guid archiveId)
|
||||
{
|
||||
var now = new DateTime(2026, 9, 28, 18, 2, 11);
|
||||
(Sequence, string[], bool) Make(string? title, string folder, string make, string model, int frames, TimeSpan span, double interval, int daysAgo,
|
||||
SequenceStatus status, string[] colours, int renders = 0, int warnings = 0, SequenceOrigin origin = SequenceOrigin.Local,
|
||||
SyncState sync = SyncState.LocalOnly, bool raw = false)
|
||||
{
|
||||
var start = now.AddDays(-daysAgo);
|
||||
return (new Sequence
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArchiveId = archiveId,
|
||||
Title = title,
|
||||
Folder = folder,
|
||||
CameraMake = make,
|
||||
CameraModel = model,
|
||||
FirstCapture = start,
|
||||
LastCapture = start + span,
|
||||
FrameCount = frames,
|
||||
MedianInterval = interval,
|
||||
TotalBytes = frames * 24_000_000L,
|
||||
Status = status,
|
||||
RenderedCount = renders,
|
||||
WarningCount = warnings,
|
||||
Origin = origin,
|
||||
SyncState = sync,
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
}, colours, raw);
|
||||
}
|
||||
|
||||
const SequenceStatus Analysed = SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep;
|
||||
const SequenceStatus Full = Analysed | SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt | SequenceStatus.Verified;
|
||||
yield return Make("Harbour sunset", "2026/2026-09-28 Canon EOS R5", "Canon", "Canon EOS R5", 3_600, TimeSpan.FromHours(2), 2, 0, Full,
|
||||
["#2A2F6B", "#B8452F", "#F0A04B", "#2B2B33"], renders: 2, sync: SyncState.InSync, raw: true);
|
||||
yield return Make("Comet over the ridge", "2026/2026-08-13 GoPro HERO8 Black", "GoPro", "HERO8 Black", 1_005, new TimeSpan(5, 34, 0), 20, 46, Full,
|
||||
["#050914", "#0F1D3A", "#1E3A2F"], warnings: 1);
|
||||
yield return Make(null, "2026/2026-09-27 Sony ILCE-7M4", "SONY", "ILCE-7M4", 2_140, new TimeSpan(1, 11, 0), 2, 1, Analysed,
|
||||
["#4A7FB5", "#A9C9E6", "#6F7D6A"]);
|
||||
yield return Make("Aurora, Tromsø", "2026/2026-02-20 Nikon Z 8", "NIKON CORPORATION", "NIKON Z 8", 1_860, new TimeSpan(4, 8, 0), 8, 220, Full,
|
||||
["#0C2A3A", "#1AA08C", "#0B1A26"], sync: SyncState.InSync);
|
||||
yield return Make("Construction cam · week 38", "2026/2026-09-14 Brinno TLC2020", "Brinno", "TLC2020", 8_920, TimeSpan.FromDays(7), 60, 14,
|
||||
SequenceStatus.None, ["#7C8AA0", "#C9CFD6", "#4C5058"], origin: SequenceOrigin.Server, sync: SyncState.RemoteOnly);
|
||||
yield return Make("Milan skyline dusk", "2026/2026-06-03 Apple iPhone 16 Pro", "Apple", "iPhone 16 Pro", 2_400, new TimeSpan(1, 20, 0), 2, 117, Full,
|
||||
["#1B2B4A", "#D67A4E", "#3A2A2A"], renders: 1);
|
||||
yield return Make("Clouds over the Langhe", "2026/2026-05-11 Canon EOS R5", "Canon", "Canon EOS R5", 1_320, TimeSpan.FromMinutes(44), 2, 140,
|
||||
SequenceStatus.None, ["#3B6FA6", "#E6EEF5", "#5C7A52"]);
|
||||
yield return Make("Star trails, Colle del Nivolet", "2025/2025-08-02 Sony ILCE-7M4", "SONY", "ILCE-7M4", 640, new TimeSpan(5, 20, 0), 30, 422, Full,
|
||||
["#08101C", "#142A4A", "#0D0F14"], renders: 3);
|
||||
yield return Make("Fog lifting, Asti", "2025/2025-11-21 DJI Osmo Action 5 Pro", "DJI", "Osmo Action 5 Pro", 980, new TimeSpan(1, 38, 0), 6, 311,
|
||||
Analysed, ["#6A8FB0", "#F2E6D0", "#7A6A55"]);
|
||||
yield return Make("Holy grail · Monviso", "2025/2025-07-14 Nikon Z 8", "NIKON CORPORATION", "NIKON Z 8", 1_720, new TimeSpan(3, 2, 0), 6, 441, Full,
|
||||
["#2C1F4D", "#C2455A", "#F5A524", "#26262C"], renders: 1, sync: SyncState.InSync);
|
||||
for (var i = 0; i < 26; i++)
|
||||
{
|
||||
var shade = 40 + i * 6;
|
||||
yield return Make($"Rooftop · day {i + 1}", $"2025/2025-03-{i + 1:00} Canon EOS R6", "Canon", "Canon EOS R6", 1_200 + i * 37, TimeSpan.FromHours(9), 30,
|
||||
480 + i, i % 3 == 0 ? Analysed : Full, [$"#{shade:X2}5A8C", "#C9D6E2", "#3D4A3A"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Three small JPEG frames per sequence; a "raw" sequence wraps its JPEGs in a fake CR2 with an embedded preview.</summary>
|
||||
private static IEnumerable<Frame> WriteFrames(string root, Sequence sequence, string[] colours, bool raw)
|
||||
{
|
||||
var folder = Path.Combine(root, sequence.Folder.Replace('/', Path.DirectorySeparatorChar));
|
||||
Directory.CreateDirectory(folder);
|
||||
var count = sequence.Title?.StartsWith("Rooftop", StringComparison.Ordinal) == true ? 1 : 3;
|
||||
var frames = new List<Frame>(count);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var jpeg = Gradient(colours, 320, 180, i / 3.0);
|
||||
var name = $"{sequence.FirstCapture:yyyy-MM-dd}_{i + 1:0000}.{(raw ? "CR2" : "JPG")}";
|
||||
long? previewOffset = null;
|
||||
long? previewLength = null;
|
||||
var bytes = jpeg;
|
||||
if (raw)
|
||||
{
|
||||
// A fake RAW: a header the decoders cannot read, the JPEG preview, then trailing data.
|
||||
var header = new byte[4096];
|
||||
"II*\0"u8.CopyTo(header);
|
||||
bytes = [.. header, .. jpeg, .. new byte[2048]];
|
||||
previewOffset = header.Length;
|
||||
previewLength = jpeg.Length;
|
||||
}
|
||||
File.WriteAllBytes(Path.Combine(folder, name), bytes);
|
||||
frames.Add(new Frame
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = sequence.Id,
|
||||
Index = i,
|
||||
RelativePath = sequence.Folder + "/" + name,
|
||||
FileName = name,
|
||||
Size = bytes.Length,
|
||||
CapturedAt = sequence.FirstCapture!.Value.AddSeconds(i * (sequence.MedianInterval ?? 2)),
|
||||
TimestampSource = TimestampSource.ExifOriginal,
|
||||
Width = 320,
|
||||
Height = 180,
|
||||
Format = raw ? ImageFileFormat.Cr2 : ImageFileFormat.Jpeg,
|
||||
PreviewOffset = previewOffset,
|
||||
PreviewLength = previewLength,
|
||||
ExposureTime = 1.0 / 250,
|
||||
FNumber = 8,
|
||||
Iso = 100,
|
||||
});
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
|
||||
/// <summary>A vertical gradient through the given sRGB colours with a sun disc that moves with <paramref name="phase"/>.</summary>
|
||||
private static byte[] Gradient(string[] colours, int width, int height, double phase)
|
||||
{
|
||||
using var image = new ImageBuffer(width, height, 3, clear: false);
|
||||
var stops = colours.Select(Parse).ToArray();
|
||||
var sunX = width * (0.3 + 0.4 * phase);
|
||||
var sunY = height * (0.55 - 0.1 * phase);
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var t = y / (double)(height - 1) * (stops.Length - 1);
|
||||
var k = Math.Min((int)t, stops.Length - 2);
|
||||
var f = t - k;
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var d = Math.Sqrt((x - sunX) * (x - sunX) + (y - sunY) * (y - sunY));
|
||||
var sun = Math.Clamp(1 - d / 14, 0, 1);
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
var value = stops[k][c] * (1 - f) + stops[k + 1][c] * f;
|
||||
image.Plane(c)[y * width + x] = (float)(value + sun * (1.0 - value) * 0.9);
|
||||
}
|
||||
}
|
||||
}
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85 });
|
||||
|
||||
static double[] Parse(string hex)
|
||||
{
|
||||
var rgb = Convert.FromHexString(hex.TrimStart('#'));
|
||||
return [Linear(rgb[0]), Linear(rgb[1]), Linear(rgb[2])];
|
||||
}
|
||||
|
||||
static double Linear(byte v)
|
||||
{
|
||||
var s = v / 255.0;
|
||||
return s <= 0.04045 ? s / 12.92 : Math.Pow((s + 0.055) / 1.055, 2.4);
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<Job> Jobs(IReadOnlyList<Sequence> s, Guid archiveId)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var here = _services.WorkerId;
|
||||
Job Make(JobKind kind, Sequence? target, string label, JobState state, long done, long total, double? rate = null, TimeSpan? eta = null,
|
||||
TimeSpan? startedAgo = null, TimeSpan? runFor = null, string? node = null, string? error = null, string? log = null,
|
||||
JobPriority priority = JobPriority.Normal, TimeSpan? createdAgo = null) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = kind,
|
||||
TargetIds = target is null ? [archiveId] : [target.Id],
|
||||
TargetLabel = label,
|
||||
State = state,
|
||||
Priority = priority,
|
||||
ProgressDone = done,
|
||||
ProgressTotal = total,
|
||||
ItemsPerSecond = rate,
|
||||
Eta = eta,
|
||||
NodeId = state == JobState.Queued ? null : node ?? here,
|
||||
Error = error,
|
||||
LogTail = log,
|
||||
Attempts = state == JobState.Queued ? 0 : 1,
|
||||
Created = now - (createdAgo ?? startedAgo ?? TimeSpan.FromMinutes(1)),
|
||||
Started = startedAgo is { } ago ? now - ago : null,
|
||||
Finished = state is JobState.Done or JobState.Failed && startedAgo is { } a2 ? now - a2 + (runFor ?? TimeSpan.FromMinutes(1)) : null,
|
||||
};
|
||||
|
||||
yield return Make(JobKind.Render, s[0], "Harbour sunset → 4K 10-bit HEVC · 24 fps", JobState.Running, 2_232, 3_600, 11.3, TimeSpan.FromMinutes(2),
|
||||
startedAgo: TimeSpan.FromMinutes(3.4), log:
|
||||
"10:14:02 window 41 · deflicker −67 % · 3 exposure steps redistributed over 18 frames\n" +
|
||||
"10:14:03 stabilisation on · mean shake 0.42 px · crop 1.8 %\n" +
|
||||
"10:14:03 encoder NVENC HEVC Main10 · 3840×2160 · 120 Mb/s · 24 fps · GOP 48\n" +
|
||||
"10:15:41 frame 2232 / 3600 · 11.3 fps · spill 0 · memory 6.1 GB of 8 GB budget");
|
||||
yield return Make(JobKind.DeepAnalyse, s[4], s[4].DisplayTitle, JobState.Running, 2_498, 8_920, 41, TimeSpan.FromMinutes(6), startedAgo: TimeSpan.FromMinutes(1.1));
|
||||
yield return Make(JobKind.Proxies, s[1], s[1].DisplayTitle, JobState.Running, 915, 1_005, 118, TimeSpan.FromSeconds(8), startedAgo: TimeSpan.FromSeconds(8));
|
||||
yield return Make(JobKind.Render, s[3], "Aurora, Tromsø → 1080p share H.264", JobState.Queued, 0, 0, createdAgo: TimeSpan.FromMinutes(12));
|
||||
yield return Make(JobKind.Verify, null, "Archive · 2024", JobState.Queued, 0, 0, priority: JobPriority.Background, createdAgo: TimeSpan.FromMinutes(30));
|
||||
yield return Make(JobKind.Verify, s[7], s[7].DisplayTitle, JobState.Failed, 640, 640, 900, startedAgo: TimeSpan.FromMinutes(25), runFor: TimeSpan.FromSeconds(43),
|
||||
error: "2 files whose hash no longer matches the sidecar", log: "09:58:01 verify 640 files\n09:58:43 2 hash mismatches: 2025-08-02_0213.ARW, 2025-08-02_0214.ARW");
|
||||
yield return Make(JobKind.Render, s[5], "Milan skyline dusk → 4K HEVC", JobState.Done, 2_400, 2_400, 14.8, startedAgo: TimeSpan.FromMinutes(70),
|
||||
runFor: new TimeSpan(0, 2, 41), node: "studio-pc");
|
||||
yield return Make(JobKind.Import, s[0], "EOS R5 · card A → Archive · 4,812 photos", JobState.Done, 4_812, 4_812, 7.1, startedAgo: TimeSpan.FromMinutes(110),
|
||||
runFor: new TimeSpan(0, 11, 52));
|
||||
yield return Make(JobKind.Thumbs, s[2], s[2].DisplayTitle, JobState.Done, 2_140, 2_140, 2_300, startedAgo: TimeSpan.FromMinutes(108), runFor: TimeSpan.FromSeconds(1));
|
||||
}
|
||||
|
||||
/// <summary>A server that always answers as "Studio NAS" with a self-signed certificate the sample trusts.</summary>
|
||||
private sealed class SampleServerApiFactory : IServerApiFactory
|
||||
{
|
||||
public IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints) => new SampleServerApi(baseAddress, trustedFingerprints);
|
||||
}
|
||||
|
||||
private sealed class SampleServerApi(Uri baseAddress, IReadOnlyCollection<string> trusted) : IServerApi
|
||||
{
|
||||
private static readonly UserDto User = new(Guid.Empty, "alberto", "Alberto", "editor", 0, 5_000_000_000_000, 2_100_000_000_000, false, false,
|
||||
new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), DateTimeOffset.UtcNow);
|
||||
|
||||
public Uri BaseAddress { get; } = baseAddress;
|
||||
|
||||
public string? Token { get; set; }
|
||||
|
||||
public async Task<ServerInfo> GetInfoAsync(CancellationToken ct)
|
||||
{
|
||||
await Task.Delay(14, ct);
|
||||
if (!trusted.Contains(ServerFingerprint, StringComparer.OrdinalIgnoreCase)) throw new UntrustedCertificateException(ServerFingerprint);
|
||||
return new ServerInfo("Studio NAS", "1.3.0", 1, [], ServerFingerprint, [], new ServerLimits(0, 0));
|
||||
}
|
||||
|
||||
public Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct)
|
||||
{
|
||||
Token = "sample-token";
|
||||
return Task.FromResult(new LoginResponse(Token, User, false, DateTimeOffset.UtcNow.AddDays(30)));
|
||||
}
|
||||
|
||||
public Task<UserDto> MeAsync(CancellationToken ct) =>
|
||||
Token == "sample-token" ? Task.FromResult(User) : throw new TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("unauthorized", "Sign in"));
|
||||
|
||||
public Task LogoutAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>No encryption: the capture environment is thrown away.</summary>
|
||||
private sealed class PlainTokenProtector : ITokenProtector
|
||||
{
|
||||
public string Protect(string token) => token;
|
||||
|
||||
public string? Unprotect(string protectedToken) => protectedToken;
|
||||
}
|
||||
|
||||
/// <summary>The encoders of the mockup's PC (NVIDIA RTX with NVENC) and canned self-test speeds.</summary>
|
||||
private sealed class SampleEncoders : IEncoderInventory
|
||||
{
|
||||
public string? Adapter() => "NVIDIA GeForce RTX 4070";
|
||||
|
||||
public IReadOnlyList<EncoderRow> Detect() =>
|
||||
[
|
||||
new("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc),
|
||||
new("H.264", "NVIDIA H.264 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, false, 4096, 4096, VideoCodec.H264),
|
||||
new("AV1", "NVIDIA AV1 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Av1),
|
||||
new("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264),
|
||||
new("MJPEG · AVI", "Titano", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg),
|
||||
new("GIF · APNG", "Titano", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null),
|
||||
];
|
||||
|
||||
public Task<SelfTestResult> SelfTestAsync(EncoderRow row, CancellationToken ct) => Task.FromResult(row.Codec switch
|
||||
{
|
||||
"HEVC" => new SelfTestResult(true, 142, null),
|
||||
"AV1" => new SelfTestResult(true, 96, null),
|
||||
"H.264" when row.Hardware => new SelfTestResult(true, 188, null),
|
||||
"H.264" => new SelfTestResult(true, 21, null),
|
||||
_ => new SelfTestResult(true, 64, null),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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>"<fixed drive with the most free space>\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";
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.App.Interop;
|
||||
|
||||
/// <summary>A filter of the Open dialog: display name and patterns such as <c>*.jpg;*.cr2</c>.</summary>
|
||||
public readonly record struct FileFilter(string Name, string Patterns);
|
||||
|
||||
/// <summary>
|
||||
/// The shell's Open dialog through <c>IFileOpenDialog</c> COM (no WinForms): one or several files, or one folder
|
||||
/// (which also picks a card root such as <c>E:\</c>). Same wrapper as the uploader's (kept per program so neither
|
||||
/// depends on the other).
|
||||
/// </summary>
|
||||
public static class FileDialogs
|
||||
{
|
||||
private const uint FosPickFolders = 0x20;
|
||||
private const uint FosForceFileSystem = 0x40;
|
||||
private const uint FosAllowMultiSelect = 0x200;
|
||||
private const uint FosPathMustExist = 0x800;
|
||||
private const uint FosFileMustExist = 0x1000;
|
||||
private const uint SigdnFileSysPath = 0x80058000;
|
||||
private const int ErrorCancelled = unchecked((int)0x800704C7);
|
||||
|
||||
/// <summary>Selected files; empty when cancelled.</summary>
|
||||
public static IReadOnlyList<string> PickFiles(IntPtr owner, string title, IReadOnlyList<FileFilter> filters) =>
|
||||
Show(owner, title, FosAllowMultiSelect | FosFileMustExist, filters);
|
||||
|
||||
/// <summary>One selected file; null when cancelled.</summary>
|
||||
public static string? PickFile(IntPtr owner, string title, IReadOnlyList<FileFilter> filters) =>
|
||||
Show(owner, title, FosFileMustExist, filters).FirstOrDefault();
|
||||
|
||||
/// <summary>Selected folder; null when cancelled.</summary>
|
||||
public static string? PickFolder(IntPtr owner, string title) => Show(owner, title, FosPickFolders, []).FirstOrDefault();
|
||||
|
||||
private static List<string> Show(IntPtr owner, string title, uint options, IReadOnlyList<FileFilter> filters)
|
||||
{
|
||||
var dialog = (IFileOpenDialog)new FileOpenDialogClass();
|
||||
try
|
||||
{
|
||||
dialog.GetOptions(out var current);
|
||||
dialog.SetOptions(current | options | FosForceFileSystem | FosPathMustExist);
|
||||
dialog.SetTitle(title);
|
||||
if (filters.Count > 0)
|
||||
{
|
||||
var specs = filters.Select(f => new FilterSpec { Name = f.Name, Spec = f.Patterns }).ToArray();
|
||||
dialog.SetFileTypes((uint)specs.Length, specs);
|
||||
dialog.SetFileTypeIndex(1);
|
||||
}
|
||||
var hr = dialog.Show(owner);
|
||||
if (hr == ErrorCancelled) return [];
|
||||
Marshal.ThrowExceptionForHR(hr);
|
||||
|
||||
dialog.GetResults(out var items);
|
||||
try
|
||||
{
|
||||
items.GetCount(out var count);
|
||||
var paths = new List<string>((int)count);
|
||||
for (uint i = 0; i < count; i++)
|
||||
{
|
||||
items.GetItemAt(i, out var item);
|
||||
try
|
||||
{
|
||||
item.GetDisplayName(SigdnFileSysPath, out var path);
|
||||
paths.Add(path);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.ReleaseComObject(item);
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.ReleaseComObject(items);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.ReleaseComObject(dialog);
|
||||
}
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct FilterSpec
|
||||
{
|
||||
[MarshalAs(UnmanagedType.LPWStr)]
|
||||
public string Name;
|
||||
|
||||
[MarshalAs(UnmanagedType.LPWStr)]
|
||||
public string Spec;
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")]
|
||||
private class FileOpenDialogClass;
|
||||
|
||||
// Classic COM interop does not inherit vtables: IModalWindow and IFileDialog members are repeated in order.
|
||||
[ComImport]
|
||||
[Guid("d57c7288-d4ad-4768-be02-9d969532d960")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface IFileOpenDialog
|
||||
{
|
||||
[PreserveSig]
|
||||
int Show(IntPtr owner);
|
||||
|
||||
void SetFileTypes(uint count, [In, MarshalAs(UnmanagedType.LPArray)] FilterSpec[] filters);
|
||||
|
||||
void SetFileTypeIndex(uint index);
|
||||
|
||||
void GetFileTypeIndex(out uint index);
|
||||
|
||||
void Advise(IntPtr events, out uint cookie);
|
||||
|
||||
void Unadvise(uint cookie);
|
||||
|
||||
void SetOptions(uint options);
|
||||
|
||||
void GetOptions(out uint options);
|
||||
|
||||
void SetDefaultFolder(IShellItem item);
|
||||
|
||||
void SetFolder(IShellItem item);
|
||||
|
||||
void GetFolder(out IShellItem item);
|
||||
|
||||
void GetCurrentSelection(out IShellItem item);
|
||||
|
||||
void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
|
||||
|
||||
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
|
||||
|
||||
void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
|
||||
|
||||
void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string text);
|
||||
|
||||
void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
|
||||
|
||||
void GetResult(out IShellItem item);
|
||||
|
||||
void AddPlace(IShellItem item, int placement);
|
||||
|
||||
void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string extension);
|
||||
|
||||
void Close(int hr);
|
||||
|
||||
void SetClientGuid(ref Guid guid);
|
||||
|
||||
void ClearClientData();
|
||||
|
||||
void SetFilter(IntPtr filter);
|
||||
|
||||
void GetResults(out IShellItemArray items);
|
||||
|
||||
void GetSelectedItems(out IShellItemArray items);
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface IShellItem
|
||||
{
|
||||
void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
|
||||
|
||||
void GetParent(out IShellItem parent);
|
||||
|
||||
void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name);
|
||||
|
||||
void GetAttributes(uint mask, out uint attributes);
|
||||
|
||||
void Compare(IShellItem other, uint hint, out int order);
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("b63ea76d-1f85-456f-a19c-48159efa858b")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface IShellItemArray
|
||||
{
|
||||
void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
|
||||
|
||||
void GetPropertyStore(int flags, ref Guid iid, out IntPtr store);
|
||||
|
||||
void GetPropertyDescriptionList(IntPtr keyType, ref Guid iid, out IntPtr list);
|
||||
|
||||
void GetAttributes(int flags, uint mask, out uint attributes);
|
||||
|
||||
void GetCount(out uint count);
|
||||
|
||||
void GetItemAt(uint index, out IShellItem item);
|
||||
|
||||
void EnumItems(out IntPtr items);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
|
||||
namespace Titano.App.Jobs;
|
||||
|
||||
/// <summary>Filter chips of the Jobs screen (BRIEF §12.6).</summary>
|
||||
public enum JobFilter
|
||||
{
|
||||
All,
|
||||
Running,
|
||||
Queued,
|
||||
Done,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>One job as the Jobs screen knows it: the last stored snapshot plus live progress while it runs.</summary>
|
||||
public sealed class JobEntry(Job job)
|
||||
{
|
||||
public Job Job { get; internal set; } = job;
|
||||
|
||||
/// <summary>Latest progress event of the running job; null once it stops.</summary>
|
||||
public JobProgressInfo? Live { get; internal set; }
|
||||
|
||||
/// <summary><see cref="JobListModel.Stamp"/> of the last update.</summary>
|
||||
internal long Stamp { get; set; }
|
||||
|
||||
public Guid Id => Job.Id;
|
||||
public JobState State => Job.State;
|
||||
public long Done => Live?.Done ?? Job.ProgressDone;
|
||||
public long Total => Live?.Total ?? Job.ProgressTotal;
|
||||
public double? ItemsPerSecond => Live?.ItemsPerSecond ?? Job.ItemsPerSecond;
|
||||
public TimeSpan? Eta => Live?.Eta ?? Job.Eta;
|
||||
public string? Message => Live?.Message;
|
||||
|
||||
/// <summary>0…1, or null while the total is unknown.</summary>
|
||||
public double? Fraction => Total > 0 ? Math.Clamp((double)Done / Total, 0, 1) : null;
|
||||
|
||||
public bool IsFinished => State is JobState.Done or JobState.Failed or JobState.Cancelled;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The job list behind the Jobs screen and the job bar: merges stored snapshots (<see cref="JobEngine.JobChanged"/>,
|
||||
/// repository pages) with live progress (<see cref="JobEngine.Progress"/>), keeps queue order and answers the
|
||||
/// filters. WPF-free and not thread-safe; feed it on the UI thread (through <see cref="JobUpdateBuffer"/>).
|
||||
/// </summary>
|
||||
public sealed class JobListModel
|
||||
{
|
||||
private readonly Dictionary<Guid, JobEntry> _entries = [];
|
||||
|
||||
private long _stamp;
|
||||
|
||||
public int Count => _entries.Count;
|
||||
|
||||
public JobEntry? this[Guid id] => _entries.GetValueOrDefault(id);
|
||||
|
||||
/// <summary>
|
||||
/// Change counter. Read it before requesting a page from the database and pass it to <see cref="ApplyLoaded"/>,
|
||||
/// so a page that was read before an event cannot overwrite the newer state the event brought.
|
||||
/// </summary>
|
||||
public long Stamp => _stamp;
|
||||
|
||||
/// <summary>Inserts or replaces a snapshot that is known to be current (an engine event). True when something changed.</summary>
|
||||
public bool Apply(Job job) => Store(job, ++_stamp);
|
||||
|
||||
/// <summary>Inserts a snapshot read from the database; skipped when an event updated the job after <paramref name="readAt"/>.</summary>
|
||||
public bool ApplyLoaded(Job job, long readAt)
|
||||
{
|
||||
if (_entries.TryGetValue(job.Id, out var entry) && entry.Stamp > readAt) return false;
|
||||
return Store(job, readAt);
|
||||
}
|
||||
|
||||
private bool Store(Job job, long stamp)
|
||||
{
|
||||
if (!_entries.TryGetValue(job.Id, out var entry))
|
||||
{
|
||||
_entries[job.Id] = new JobEntry(job) { Stamp = stamp };
|
||||
return true;
|
||||
}
|
||||
entry.Stamp = Math.Max(entry.Stamp, stamp);
|
||||
if (entry.Job == job) return false;
|
||||
entry.Job = job;
|
||||
if (job.State != JobState.Running) entry.Live = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Live progress of a running job; ignored for unknown or no longer running jobs. True when something changed.</summary>
|
||||
public bool Apply(JobProgressInfo progress)
|
||||
{
|
||||
if (!_entries.TryGetValue(progress.JobId, out var entry) || entry.State != JobState.Running) return false;
|
||||
if (entry.Live == progress) return false;
|
||||
entry.Live = progress;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Removes jobs no longer present (e.g. purged history).</summary>
|
||||
public bool Remove(Guid id) => _entries.Remove(id);
|
||||
|
||||
/// <summary>
|
||||
/// Display order: running (oldest start first), paused, queued in the order workers claim them (priority, then
|
||||
/// age), then the history, newest finish first. Finished jobs before <paramref name="clearedBefore"/> are hidden.
|
||||
/// </summary>
|
||||
public IReadOnlyList<JobEntry> Ordered(JobFilter filter = JobFilter.All, string? search = null, DateTimeOffset? clearedBefore = null)
|
||||
{
|
||||
var text = string.IsNullOrWhiteSpace(search) ? null : search.Trim();
|
||||
return _entries.Values
|
||||
.Where(e => Matches(e, filter) && Visible(e, clearedBefore) && (text is null || MatchesText(e, text)))
|
||||
.OrderBy(Group)
|
||||
.ThenBy(e => e.State == JobState.Queued ? -(int)e.Job.Priority : 0)
|
||||
.ThenBy(e => e.IsFinished ? -(e.Job.Finished ?? e.Job.Created).UtcTicks : (e.Job.Started ?? e.Job.Created).UtcTicks)
|
||||
.ThenBy(e => e.Job.Created)
|
||||
.ThenBy(e => e.Id)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>Jobs per filter chip (after "Clear done").</summary>
|
||||
public int CountOf(JobFilter filter, DateTimeOffset? clearedBefore = null) =>
|
||||
_entries.Values.Count(e => Matches(e, filter) && Visible(e, clearedBefore));
|
||||
|
||||
/// <summary>1-based place of a queued job in the order workers claim jobs; 0 when it is not queued.</summary>
|
||||
public int QueuePosition(Guid id)
|
||||
{
|
||||
if (!_entries.TryGetValue(id, out var entry) || entry.State != JobState.Queued) return 0;
|
||||
return _entries.Values.Count(e => e.State == JobState.Queued && ClaimsBefore(e.Job, entry.Job)) + 1;
|
||||
}
|
||||
|
||||
/// <summary>The job the job bar mirrors: the running job with the most recent progress, else the first running one.</summary>
|
||||
public JobEntry? Current =>
|
||||
_entries.Values.Where(e => e.State == JobState.Running)
|
||||
.OrderByDescending(e => e.Live is not null)
|
||||
.ThenBy(e => (e.Job.Started ?? e.Job.Created).UtcTicks)
|
||||
.FirstOrDefault();
|
||||
|
||||
public int RunningCount => _entries.Values.Count(e => e.State == JobState.Running);
|
||||
|
||||
public int QueuedCount => _entries.Values.Count(e => e.State == JobState.Queued);
|
||||
|
||||
/// <summary>Same order as <c>JobRepository.ClaimNextAsync</c>: priority descending, then creation time and id.</summary>
|
||||
public static bool ClaimsBefore(Job a, Job b) =>
|
||||
a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0;
|
||||
|
||||
private static int Group(JobEntry e) => e.State switch
|
||||
{
|
||||
JobState.Running => 0,
|
||||
JobState.Paused => 1,
|
||||
JobState.Queued => 2,
|
||||
_ => 3,
|
||||
};
|
||||
|
||||
private static bool Matches(JobEntry e, JobFilter filter) => filter switch
|
||||
{
|
||||
JobFilter.Running => e.State is JobState.Running or JobState.Paused,
|
||||
JobFilter.Queued => e.State == JobState.Queued,
|
||||
JobFilter.Done => e.State == JobState.Done,
|
||||
JobFilter.Failed => e.State is JobState.Failed or JobState.Cancelled,
|
||||
_ => true,
|
||||
};
|
||||
|
||||
private static bool Visible(JobEntry e, DateTimeOffset? clearedBefore) =>
|
||||
clearedBefore is null || !e.IsFinished || (e.Job.Finished ?? e.Job.Created) > clearedBefore;
|
||||
|
||||
private static bool MatchesText(JobEntry e, string text) =>
|
||||
(e.Job.TargetLabel?.Contains(text, StringComparison.CurrentCultureIgnoreCase) ?? false)
|
||||
|| JobText.Kind(e.Job.Kind).Contains(text, StringComparison.CurrentCultureIgnoreCase);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Repositories;
|
||||
|
||||
namespace Titano.App.Jobs;
|
||||
|
||||
/// <summary>What the Jobs screen, the job bar and the Library need from the job system.</summary>
|
||||
public interface IJobQueue
|
||||
{
|
||||
/// <summary>A job changed state (any thread).</summary>
|
||||
event Action<Job>? JobChanged;
|
||||
|
||||
/// <summary>Progress of a running job (any thread, high frequency).</summary>
|
||||
event Action<JobProgressInfo>? Progress;
|
||||
|
||||
/// <summary>Node id stamped on jobs run by this PC.</summary>
|
||||
string WorkerId { get; }
|
||||
|
||||
/// <summary>Concurrent workers of the local engine; 0 when it runs no handler yet.</summary>
|
||||
int Workers { get; }
|
||||
|
||||
/// <summary>Kinds this PC can run.</summary>
|
||||
IReadOnlyCollection<JobKind> Kinds { get; }
|
||||
|
||||
Task<Page<Job>> ListAsync(string? cursor, int limit, CancellationToken ct = default);
|
||||
|
||||
Task<Job?> GetAsync(Guid id, CancellationToken ct = default);
|
||||
|
||||
Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, JobPriority priority = JobPriority.User, CancellationToken ct = default);
|
||||
|
||||
Task PauseAsync(Guid id);
|
||||
|
||||
/// <summary>Resumes a paused job, or retries a failed or cancelled one from its checkpoint.</summary>
|
||||
Task ResumeAsync(Guid id);
|
||||
|
||||
/// <summary>Cancels a running or queued job.</summary>
|
||||
Task CancelAsync(Guid id);
|
||||
|
||||
/// <summary>Moves a queued job ahead of lower-priority jobs (one priority level up).</summary>
|
||||
Task RaisePriorityAsync(Guid id);
|
||||
}
|
||||
|
||||
/// <summary><see cref="IJobQueue"/> over the local <see cref="JobEngine"/> and the job table.</summary>
|
||||
public sealed class EngineJobQueue : IJobQueue, IDisposable
|
||||
{
|
||||
private readonly TitanoDatabase _db;
|
||||
private readonly JobEngine _engine;
|
||||
private readonly bool _started;
|
||||
|
||||
public EngineJobQueue(TitanoDatabase db, JobEngine engine, bool started)
|
||||
{
|
||||
_db = db;
|
||||
_engine = engine;
|
||||
_started = started;
|
||||
_engine.JobChanged += OnJobChanged;
|
||||
_engine.Progress += OnProgress;
|
||||
}
|
||||
|
||||
public event Action<Job>? JobChanged;
|
||||
|
||||
public event Action<JobProgressInfo>? Progress;
|
||||
|
||||
public string WorkerId => _engine.Options.WorkerId;
|
||||
|
||||
public int Workers => _started ? _engine.Options.Workers : 0;
|
||||
|
||||
public IReadOnlyCollection<JobKind> Kinds => _engine.Options.Kinds ?? [];
|
||||
|
||||
public Task<Page<Job>> ListAsync(string? cursor, int limit, CancellationToken ct = default) => _db.Jobs.ListAsync(null, limit, cursor, ct);
|
||||
|
||||
public Task<Job?> GetAsync(Guid id, CancellationToken ct = default) => _db.Jobs.GetAsync(id, ct);
|
||||
|
||||
public Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, JobPriority priority = JobPriority.User, CancellationToken ct = default) =>
|
||||
_engine.EnqueueAsync(kind, targets, targetLabel, priority: priority, cancellationToken: ct);
|
||||
|
||||
public Task PauseAsync(Guid id) => _engine.PauseAsync(id);
|
||||
|
||||
public Task ResumeAsync(Guid id) => _engine.ResumeAsync(id);
|
||||
|
||||
public Task CancelAsync(Guid id) => _engine.CancelAsync(id);
|
||||
|
||||
public async Task RaisePriorityAsync(Guid id)
|
||||
{
|
||||
// JobRepository has no priority update yet; one guarded statement keeps it atomic (queued jobs only).
|
||||
var session = await _db.Database.OpenAsync(CancellationToken.None);
|
||||
await using (session)
|
||||
{
|
||||
await session.ExecuteAsync(
|
||||
$"UPDATE jobs SET priority = priority + 1 WHERE id = $1 AND state = {(int)JobState.Queued} AND priority < {(int)JobPriority.User}",
|
||||
[id], CancellationToken.None);
|
||||
}
|
||||
if (await _db.Jobs.GetAsync(id) is { } job) JobChanged?.Invoke(job);
|
||||
_engine.Wake();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_engine.JobChanged -= OnJobChanged;
|
||||
_engine.Progress -= OnProgress;
|
||||
}
|
||||
|
||||
private void OnJobChanged(Job job) => JobChanged?.Invoke(job);
|
||||
|
||||
private void OnProgress(JobProgressInfo progress) => Progress?.Invoke(progress);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Sections;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Jobs;
|
||||
|
||||
/// <summary>A row action: label, tooltip and command (26-px row buttons, DESIGN §4 tables).</summary>
|
||||
public sealed record JobAction(string Text, string ToolTip, ICommand Command, bool IsDestructive = false);
|
||||
|
||||
/// <summary>One row of the Jobs table (Jobs.html): kind, target, progress, speed, left, where, state, actions, log.</summary>
|
||||
public sealed class JobRowViewModel : ObservableObject
|
||||
{
|
||||
private readonly JobActions _actions;
|
||||
private JobEntry _entry;
|
||||
private int _queuePosition;
|
||||
private bool _isExpanded;
|
||||
private string? _logTail;
|
||||
|
||||
internal JobRowViewModel(JobEntry entry, int queuePosition, JobActions actions)
|
||||
{
|
||||
_entry = entry;
|
||||
_queuePosition = queuePosition;
|
||||
_actions = actions;
|
||||
ToggleLogCommand = new RelayCommand(() => IsExpanded = !IsExpanded);
|
||||
}
|
||||
|
||||
public JobEntry Entry => _entry;
|
||||
public Guid Id => _entry.Id;
|
||||
public Job Job => _entry.Job;
|
||||
|
||||
public string Kind => JobText.Kind(_entry.Job.Kind);
|
||||
|
||||
public string Target => _entry.Job.TargetLabel ?? string.Empty;
|
||||
|
||||
/// <summary>Progress 0…1 (0 while unknown).</summary>
|
||||
public double Progress => _entry.State == JobState.Done ? 1 : _entry.Fraction ?? 0;
|
||||
|
||||
/// <summary>"62 %", "—" while queued or unknown.</summary>
|
||||
public string PercentText => _entry.State == JobState.Done ? Formatting.Percent(1) : _entry.Fraction is { } f && _entry.State != JobState.Queued ? Formatting.Percent(f) : "—";
|
||||
|
||||
public string SpeedText => _entry.State is JobState.Running or JobState.Done ? Blank(JobText.Speed(_entry.Job.Kind, _entry.ItemsPerSecond)) : "—";
|
||||
|
||||
public string LeftText => Blank(JobText.Left(_entry, _queuePosition));
|
||||
|
||||
public string WhereText => _entry.State == JobState.Queued ? Loc.L("Jobs.Where.ThisPc") : Blank(JobText.Where(_entry.Job.NodeId, _actions.WorkerId));
|
||||
|
||||
public string StateText => JobText.State(_entry);
|
||||
|
||||
/// <summary>Glyph and colour of the state (paired with the word, never colour alone).</summary>
|
||||
public StatusKind StateKind => _entry.State switch
|
||||
{
|
||||
JobState.Running => StatusKind.Running,
|
||||
JobState.Queued => StatusKind.Queued,
|
||||
JobState.Paused => StatusKind.Paused,
|
||||
JobState.Done => StatusKind.Done,
|
||||
JobState.Failed => StatusKind.Failed,
|
||||
_ => StatusKind.Offline,
|
||||
};
|
||||
|
||||
/// <summary>The error of a failed job, or the state explanation.</summary>
|
||||
public string StateToolTip => _entry.Job.Error is { Length: > 0 } error ? error : Loc.L("Tooltips.Jobs.State." + _entry.State);
|
||||
|
||||
/// <summary>Muted text for rows that are not doing anything (queued, history), as in the mockup.</summary>
|
||||
public bool IsDimmed => _entry.State is JobState.Queued or JobState.Done or JobState.Cancelled;
|
||||
|
||||
public bool IsFailed => _entry.State == JobState.Failed;
|
||||
public bool IsDone => _entry.State == JobState.Done;
|
||||
|
||||
public IReadOnlyList<JobAction> Actions => _actions.For(_entry);
|
||||
|
||||
public ICommand ToggleLogCommand { get; }
|
||||
|
||||
public bool IsExpanded
|
||||
{
|
||||
get => _isExpanded;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _isExpanded, value)) return;
|
||||
OnPropertyChanged(nameof(ToggleToolTip));
|
||||
if (value) _ = _actions.LoadLogAsync(this);
|
||||
}
|
||||
}
|
||||
|
||||
public string ToggleToolTip => Loc.L(_isExpanded ? "Tooltips.Jobs.HideLog" : "Tooltips.Jobs.ShowLog");
|
||||
|
||||
/// <summary>The last lines of the job log, plus the live message while it runs.</summary>
|
||||
public string LogText
|
||||
{
|
||||
get
|
||||
{
|
||||
var tail = _logTail ?? _entry.Job.LogTail ?? string.Empty;
|
||||
if (_entry.State == JobState.Running && _entry.Message is { Length: > 0 } message && !tail.EndsWith(message, StringComparison.Ordinal))
|
||||
tail = tail.Length == 0 ? message : tail + "\n" + message;
|
||||
return tail.Length == 0 ? Loc.L("Jobs.Log.Empty") : tail;
|
||||
}
|
||||
}
|
||||
|
||||
internal void SetLog(string? logTail)
|
||||
{
|
||||
_logTail = logTail;
|
||||
OnPropertyChanged(nameof(LogText));
|
||||
}
|
||||
|
||||
/// <summary>Refreshes the row from the model; returns true when it changed position-relevant data.</summary>
|
||||
internal void Update(JobEntry entry, int queuePosition)
|
||||
{
|
||||
var stateChanged = entry.State != _entry.State;
|
||||
_entry = entry;
|
||||
_queuePosition = queuePosition;
|
||||
if (stateChanged)
|
||||
{
|
||||
_logTail = null;
|
||||
OnAllPropertiesChanged();
|
||||
if (_isExpanded) _ = _actions.LoadLogAsync(this);
|
||||
return;
|
||||
}
|
||||
OnPropertyChanged(nameof(Progress));
|
||||
OnPropertyChanged(nameof(PercentText));
|
||||
OnPropertyChanged(nameof(SpeedText));
|
||||
OnPropertyChanged(nameof(LeftText));
|
||||
OnPropertyChanged(nameof(WhereText));
|
||||
OnPropertyChanged(nameof(StateText));
|
||||
if (_isExpanded) OnPropertyChanged(nameof(LogText));
|
||||
}
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
|
||||
private static string Blank(string text) => text.Length == 0 ? "—" : text;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
|
||||
namespace Titano.App.Jobs;
|
||||
|
||||
/// <summary>Localized texts of jobs: kind, speed, time left, place in the queue, state (Jobs screen and job bar).</summary>
|
||||
public static class JobText
|
||||
{
|
||||
/// <summary>"Render", "Deep analysis", …</summary>
|
||||
public static string Kind(JobKind kind) => Loc.L("Jobs.Kind." + kind);
|
||||
|
||||
/// <summary>True for jobs whose items are frames, so their speed reads in fps.</summary>
|
||||
public static bool CountsFrames(JobKind kind) =>
|
||||
kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Verify;
|
||||
|
||||
/// <summary>"11.3 fps" for frame jobs, "41/s" otherwise; empty when unknown.</summary>
|
||||
public static string Speed(JobKind kind, double? perSecond) =>
|
||||
perSecond is > 0 and var rate
|
||||
? Loc.L(CountsFrames(kind) ? "Jobs.Speed.Fps" : "Jobs.Speed.PerSecond", Formatting.Rate(rate))
|
||||
: string.Empty;
|
||||
|
||||
/// <summary>"1,240 / 3,600"; empty while the total is unknown.</summary>
|
||||
public static string Counter(long done, long total) =>
|
||||
total > 0 ? Loc.L("Jobs.Counter", Formatting.Count(done), Formatting.Count(total)) : string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// The "Left" column: time left while running, "after n" while queued, the finish time of the history.
|
||||
/// </summary>
|
||||
public static string Left(JobEntry entry, int queuePosition) => entry.State switch
|
||||
{
|
||||
JobState.Running => entry.Eta is { } eta ? Formatting.Duration(eta) : string.Empty,
|
||||
JobState.Queued => queuePosition > 1 ? Loc.L("Jobs.Left.After", queuePosition - 1) : Loc.L("Jobs.Left.Next"),
|
||||
_ when entry.Job.Finished is { } finished => Formatting.TimeOfDay(finished),
|
||||
_ => string.Empty,
|
||||
};
|
||||
|
||||
/// <summary>State word, with the run time for done jobs ("done · 2:41").</summary>
|
||||
public static string State(JobEntry entry)
|
||||
{
|
||||
var word = Loc.L("Jobs.State." + entry.State);
|
||||
return entry.State == JobState.Done && entry.Job is { Started: { } started, Finished: { } finished }
|
||||
? Loc.L("Jobs.State.WithDetail", word, Formatting.Elapsed(finished - started))
|
||||
: word;
|
||||
}
|
||||
|
||||
/// <summary>Where the job runs: "this PC" for this machine's workers, the node name otherwise.</summary>
|
||||
public static string Where(string? nodeId, string localWorkerId)
|
||||
{
|
||||
if (string.IsNullOrEmpty(nodeId)) return string.Empty;
|
||||
var hash = nodeId.IndexOf('#', StringComparison.Ordinal);
|
||||
var name = hash < 0 ? nodeId : nodeId[..hash];
|
||||
return name.Equals(localWorkerId, StringComparison.OrdinalIgnoreCase) ? Loc.L("Jobs.Where.ThisPc") : name;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Job bar line (DESIGN §4): "Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left".
|
||||
/// </summary>
|
||||
public static string Bar(JobEntry entry)
|
||||
{
|
||||
var parts = new List<string>(5) { Kind(entry.Job.Kind) };
|
||||
if (!string.IsNullOrWhiteSpace(entry.Job.TargetLabel)) parts.Add(entry.Job.TargetLabel!);
|
||||
if (Counter(entry.Done, entry.Total) is { Length: > 0 } counter) parts.Add(counter);
|
||||
if (Speed(entry.Job.Kind, entry.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed);
|
||||
if (entry.Eta is { } eta) parts.Add(Loc.L("Jobs.Bar.Left", Formatting.Duration(eta)));
|
||||
return string.Join(" · ", parts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
|
||||
namespace Titano.App.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Collects job events from worker threads and hands them to the UI in batches: per job only the newest snapshot
|
||||
/// and the newest progress survive, so a handler reporting thousands of times per second costs the UI one update per
|
||||
/// flush. Thread-safe.
|
||||
/// </summary>
|
||||
public sealed class JobUpdateBuffer
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private Dictionary<Guid, Job> _jobs = [];
|
||||
private Dictionary<Guid, JobProgressInfo> _progress = [];
|
||||
private long _posted;
|
||||
|
||||
/// <summary>Events accepted since creation (diagnostics, tests).</summary>
|
||||
public long Posted => Interlocked.Read(ref _posted);
|
||||
|
||||
/// <summary>Records a state change; true when the buffer was empty (the caller schedules a flush).</summary>
|
||||
public bool Post(Job job)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var wasEmpty = IsEmptyLocked;
|
||||
_jobs[job.Id] = job;
|
||||
// A newer snapshot supersedes progress reported before it.
|
||||
_progress.Remove(job.Id);
|
||||
_posted++;
|
||||
return wasEmpty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Records progress; true when the buffer was empty (the caller schedules a flush).</summary>
|
||||
public bool Post(JobProgressInfo progress)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var wasEmpty = IsEmptyLocked;
|
||||
_progress[progress.JobId] = progress;
|
||||
_posted++;
|
||||
return wasEmpty;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsEmpty
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return IsEmptyLocked;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Takes everything collected since the last drain (snapshots first, then progress).</summary>
|
||||
public (IReadOnlyCollection<Job> Jobs, IReadOnlyCollection<JobProgressInfo> Progress) Drain()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var jobs = _jobs;
|
||||
var progress = _progress;
|
||||
_jobs = [];
|
||||
_progress = [];
|
||||
return (jobs.Values, progress.Values);
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsEmptyLocked => _jobs.Count == 0 && _progress.Count == 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs an action on a synchronization context at most once per interval, however often it is signalled from any
|
||||
/// thread: the first signal after a flush schedules the next flush for <c>interval</c> after the previous one
|
||||
/// (the job list refreshes at about 10 Hz).
|
||||
/// </summary>
|
||||
public sealed class CoalescingThrottle : IDisposable
|
||||
{
|
||||
private readonly TimeSpan _interval;
|
||||
private readonly SynchronizationContext? _context;
|
||||
private readonly Action _flush;
|
||||
private readonly Func<long> _now;
|
||||
private readonly Timer _timer;
|
||||
private readonly Lock _gate = new();
|
||||
private long _lastFlush = long.MinValue;
|
||||
private bool _scheduled;
|
||||
private bool _disposed;
|
||||
|
||||
/// <param name="interval">Minimum time between two flushes.</param>
|
||||
/// <param name="context">Where <paramref name="flush"/> runs (the UI); null runs it on the timer thread.</param>
|
||||
/// <param name="flush">The batched work.</param>
|
||||
/// <param name="clock">Milliseconds clock for tests; defaults to the high-resolution <see cref="System.Diagnostics.Stopwatch"/>.</param>
|
||||
public CoalescingThrottle(TimeSpan interval, SynchronizationContext? context, Action flush, Func<long>? clock = null)
|
||||
{
|
||||
_interval = interval;
|
||||
_context = context;
|
||||
_flush = flush;
|
||||
_now = clock ?? (() => System.Diagnostics.Stopwatch.GetTimestamp() * 1000 / System.Diagnostics.Stopwatch.Frequency);
|
||||
_timer = new Timer(_ => Dispatch(), null, Timeout.Infinite, Timeout.Infinite);
|
||||
}
|
||||
|
||||
/// <summary>Flushes performed (tests).</summary>
|
||||
public int Flushes { get; private set; }
|
||||
|
||||
/// <summary>Asks for a flush; coalesced with every other signal until it runs.</summary>
|
||||
public void Signal()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_scheduled || _disposed) return;
|
||||
_scheduled = true;
|
||||
var wait = _lastFlush == long.MinValue ? 0 : (long)_interval.TotalMilliseconds - (_now() - _lastFlush);
|
||||
if (wait <= 0) wait = 0;
|
||||
_timer.Change(wait, Timeout.Infinite);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_disposed = true;
|
||||
_timer.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private void Dispatch()
|
||||
{
|
||||
if (_context is null) Run();
|
||||
else _context.Post(_ => Run(), null);
|
||||
}
|
||||
|
||||
private void Run()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_scheduled = false;
|
||||
_lastFlush = _now();
|
||||
Flushes++;
|
||||
}
|
||||
_flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>
|
||||
/// One entry of a toolbar dropdown: <see cref="Label"/> in the open list, <see cref="BoxText"/> in the closed box
|
||||
/// (the filter's name while nothing is chosen, e.g. "Year", the chosen value otherwise).
|
||||
/// </summary>
|
||||
public sealed record FilterOption<T>(T Value, string Label, string BoxText, bool IsAny = false)
|
||||
{
|
||||
public override string ToString() => Label;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Repositories;
|
||||
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>Status choices of the Library toolbar; each maps onto status flags the index can filter on.</summary>
|
||||
public enum StatusFilter
|
||||
{
|
||||
Any,
|
||||
Analysed,
|
||||
NotAnalysed,
|
||||
Proxies,
|
||||
NoProxies,
|
||||
Verified,
|
||||
NotVerified,
|
||||
Warnings,
|
||||
}
|
||||
|
||||
/// <summary>Library filters (search, year, camera, status, tag) and sort; immutable so a page request can carry it.</summary>
|
||||
public sealed record LibraryFilter
|
||||
{
|
||||
public string? Text { get; init; }
|
||||
public int? Year { get; init; }
|
||||
public string? Camera { get; init; }
|
||||
public StatusFilter Status { get; init; }
|
||||
public string? Tag { get; init; }
|
||||
public SequenceSort Sort { get; init; } = SequenceSort.Newest;
|
||||
|
||||
/// <summary>No filter narrows the list (the sort may differ): an empty result means an empty library.</summary>
|
||||
public bool IsUnfiltered => string.IsNullOrWhiteSpace(Text) && Year is null && Camera is null && Status == StatusFilter.Any && Tag is null;
|
||||
|
||||
/// <summary>The same sort without filters ("Clear filters").</summary>
|
||||
public LibraryFilter Cleared() => new() { Sort = Sort };
|
||||
|
||||
/// <summary>The repository query for one page.</summary>
|
||||
public SequenceQuery ToQuery(int limit, string? cursor)
|
||||
{
|
||||
var (with, without) = Flags(Status);
|
||||
return new SequenceQuery
|
||||
{
|
||||
Text = string.IsNullOrWhiteSpace(Text) ? null : Text.Trim(),
|
||||
Year = Year,
|
||||
Camera = Camera,
|
||||
Tag = Tag,
|
||||
WithStatus = with,
|
||||
WithoutStatus = without,
|
||||
Sort = Sort,
|
||||
Limit = limit,
|
||||
Cursor = cursor,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Flags that must be set and clear for a status choice.</summary>
|
||||
public static (SequenceStatus With, SequenceStatus Without) Flags(StatusFilter status) => status switch
|
||||
{
|
||||
StatusFilter.Analysed => (SequenceStatus.AnalyzedLight, SequenceStatus.None),
|
||||
StatusFilter.NotAnalysed => (SequenceStatus.None, SequenceStatus.AnalyzedLight),
|
||||
StatusFilter.Proxies => (SequenceStatus.ProxiesBuilt, SequenceStatus.None),
|
||||
StatusFilter.NoProxies => (SequenceStatus.None, SequenceStatus.ProxiesBuilt),
|
||||
StatusFilter.Verified => (SequenceStatus.Verified, SequenceStatus.None),
|
||||
StatusFilter.NotVerified => (SequenceStatus.None, SequenceStatus.Verified),
|
||||
StatusFilter.Warnings => (SequenceStatus.HasWarnings, SequenceStatus.None),
|
||||
_ => (SequenceStatus.None, SequenceStatus.None),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Repositories;
|
||||
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>A page of the Library list. <see cref="IsFirst"/> pages replace the list, the others append to it.</summary>
|
||||
public sealed record LibraryPage(int Generation, IReadOnlyList<Sequence> Items, bool IsFirst, bool HasMore);
|
||||
|
||||
/// <summary>
|
||||
/// Keyset paging of the Library (BRIEF §5: pagination on <c>(first_capture, id)</c>): the first page after a filter
|
||||
/// change, then the next page whenever the view scrolls near the end. A filter change cancels the page in flight
|
||||
/// and every result of an older filter is dropped, so stale rows never reach the list. Not thread-safe: call from
|
||||
/// one thread (the UI).
|
||||
/// </summary>
|
||||
public sealed class LibraryPager(Func<SequenceQuery, CancellationToken, Task<Page<Sequence>>> fetch, int pageSize = LibraryPager.DefaultPageSize)
|
||||
{
|
||||
public const int DefaultPageSize = 200;
|
||||
|
||||
private CancellationTokenSource _cancellation = new();
|
||||
private Task<Page<Sequence>>? _pending;
|
||||
private string? _cursor;
|
||||
|
||||
public int PageSize { get; } = Math.Clamp(pageSize, 1, 1000);
|
||||
|
||||
public LibraryFilter Filter { get; private set; } = new();
|
||||
|
||||
/// <summary>Incremented by every <see cref="ResetAsync"/>; pages carry the generation they belong to.</summary>
|
||||
public int Generation { get; private set; }
|
||||
|
||||
/// <summary>More rows exist after the loaded ones.</summary>
|
||||
public bool HasMore { get; private set; }
|
||||
|
||||
public bool IsLoading => _pending is not null;
|
||||
|
||||
/// <summary>Rows delivered for the current filter.</summary>
|
||||
public int Loaded { get; private set; }
|
||||
|
||||
/// <summary>Starts over with <paramref name="filter"/>; null when a newer reset superseded this one.</summary>
|
||||
public Task<LibraryPage?> ResetAsync(LibraryFilter filter)
|
||||
{
|
||||
_cancellation.Cancel();
|
||||
_cancellation.Dispose();
|
||||
_cancellation = new CancellationTokenSource();
|
||||
_pending = null;
|
||||
Generation++;
|
||||
Filter = filter;
|
||||
_cursor = null;
|
||||
Loaded = 0;
|
||||
HasMore = true;
|
||||
return LoadAsync(first: true);
|
||||
}
|
||||
|
||||
/// <summary>The next page; null when everything is loaded, a page is already loading, or the filter changed meanwhile.</summary>
|
||||
public Task<LibraryPage?> LoadMoreAsync()
|
||||
{
|
||||
if (_pending is not null || !HasMore || Generation == 0) return Task.FromResult<LibraryPage?>(null);
|
||||
return LoadAsync(first: false);
|
||||
}
|
||||
|
||||
/// <summary>Stops the page in flight (screen closed).</summary>
|
||||
public void Cancel()
|
||||
{
|
||||
_cancellation.Cancel();
|
||||
_pending = null;
|
||||
}
|
||||
|
||||
private async Task<LibraryPage?> LoadAsync(bool first)
|
||||
{
|
||||
var generation = Generation;
|
||||
var cancellation = _cancellation;
|
||||
var pending = fetch(Filter.ToQuery(PageSize, _cursor), cancellation.Token);
|
||||
_pending = pending;
|
||||
Page<Sequence> page;
|
||||
try
|
||||
{
|
||||
page = await pending;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
catch (Exception) when (generation != Generation)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// A failing page stops the scroll-driven loading until the next reset instead of retrying on every scroll.
|
||||
HasMore = false;
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (ReferenceEquals(_pending, pending)) _pending = null;
|
||||
}
|
||||
if (generation != Generation || cancellation.IsCancellationRequested) return null;
|
||||
_cursor = page.NextCursor;
|
||||
HasMore = page.NextCursor is not null;
|
||||
Loaded += page.Items.Count;
|
||||
return new LibraryPage(generation, page.Items, first, HasMore);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
using System.Windows.Media;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Naming;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>One sequence of the Library grid and list (BRIEF §12.2).</summary>
|
||||
public sealed class SequenceItem : ObservableObject
|
||||
{
|
||||
private readonly ThumbnailService? _thumbnails;
|
||||
private Sequence _sequence;
|
||||
private ImageSource? _thumbnail;
|
||||
private IThumbnailSource? _scrub;
|
||||
private CancellationTokenSource? _loading;
|
||||
private int _requestedWidth;
|
||||
private bool _isSelected;
|
||||
private bool _isAnalysing;
|
||||
|
||||
public SequenceItem(Sequence sequence, ThumbnailService? thumbnails)
|
||||
{
|
||||
_sequence = sequence;
|
||||
_thumbnails = thumbnails;
|
||||
}
|
||||
|
||||
public Sequence Sequence => _sequence;
|
||||
public Guid Id => _sequence.Id;
|
||||
|
||||
/// <summary>User title or "{date} {camera}".</summary>
|
||||
public string Title => _sequence.DisplayTitle;
|
||||
|
||||
/// <summary>"Canon EOS R5" (brand not repeated).</summary>
|
||||
public string Camera => PathTemplate.CameraName(_sequence.CameraMake, _sequence.CameraModel);
|
||||
|
||||
/// <summary>Card line: count · camera · span.</summary>
|
||||
public string Subtitle => string.Join(" · ", new[] { FramesText, Camera, SpanText }.Where(s => s.Length > 0));
|
||||
|
||||
public string FramesText => Formatting.Count(_sequence.FrameCount);
|
||||
|
||||
/// <summary>First capture date (camera clock).</summary>
|
||||
public string DateText => _sequence.FirstCapture is { } first ? Formatting.Date(first) : string.Empty;
|
||||
|
||||
/// <summary>Time from first to last capture.</summary>
|
||||
public string SpanText => _sequence is { FirstCapture: { } a, LastCapture: { } b } && b > a ? Formatting.Duration(b - a) : string.Empty;
|
||||
|
||||
public string IntervalText => _sequence.MedianInterval is > 0 and var s ? Loc.L("Library.Interval", s.ToString(s < 10 ? "0.#" : "0", Loc.Culture)) : string.Empty;
|
||||
|
||||
public string SizeText => Formatting.Bytes(_sequence.TotalBytes);
|
||||
|
||||
public string TagsText => string.Join(", ", _sequence.Tags);
|
||||
|
||||
/// <summary>Status glyphs of the card and the list (DESIGN §4: glyph + word, never colour alone).</summary>
|
||||
public IReadOnlyList<CardStatus> Statuses => BuildStatuses(_sequence, _isAnalysing);
|
||||
|
||||
/// <summary>The single most relevant status for the list's State column.</summary>
|
||||
public CardStatus PrimaryStatus => Statuses.FirstOrDefault(s => s.Kind is StatusKind.Error or StatusKind.Warning or StatusKind.Analysing)
|
||||
?? Statuses[0];
|
||||
|
||||
public ImageSource? Thumbnail
|
||||
{
|
||||
get => _thumbnail;
|
||||
private set => Set(ref _thumbnail, value);
|
||||
}
|
||||
|
||||
/// <summary>Frames for hover scrubbing; created on first use.</summary>
|
||||
public IThumbnailSource? ScrubSource => _thumbnails is null || _sequence.FrameCount == 0 ? null : _scrub ??= _thumbnails.ScrubSource(_sequence);
|
||||
|
||||
public bool IsSelected
|
||||
{
|
||||
get => _isSelected;
|
||||
set => Set(ref _isSelected, value);
|
||||
}
|
||||
|
||||
/// <summary>An analysis job runs on this sequence ("◐ Analysing").</summary>
|
||||
public bool IsAnalysing
|
||||
{
|
||||
get => _isAnalysing;
|
||||
set
|
||||
{
|
||||
if (Set(ref _isAnalysing, value)) RaiseStatuses();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Replaces the row with a fresher copy of the same sequence.</summary>
|
||||
public void Update(Sequence sequence)
|
||||
{
|
||||
var heroChanged = sequence.HeroFrameId != _sequence.HeroFrameId || sequence.FrameCount != _sequence.FrameCount;
|
||||
_sequence = sequence;
|
||||
if (heroChanged)
|
||||
{
|
||||
_scrub = null;
|
||||
if (_requestedWidth > 0) RequestThumbnail(_requestedWidth, force: true);
|
||||
}
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>The card or row became visible: load the hero thumbnail (once per width).</summary>
|
||||
public void RequestThumbnail(int pixelWidth, bool force = false)
|
||||
{
|
||||
if (_thumbnails is null || pixelWidth <= 0) return;
|
||||
if (!force && _thumbnail is not null && pixelWidth <= _requestedWidth) return;
|
||||
if (!force && _loading is not null && pixelWidth <= _requestedWidth) return;
|
||||
_requestedWidth = pixelWidth;
|
||||
_loading?.Cancel();
|
||||
var cancellation = new CancellationTokenSource();
|
||||
_loading = cancellation;
|
||||
_ = LoadAsync(pixelWidth, cancellation);
|
||||
}
|
||||
|
||||
/// <summary>The card left the screen (recycled): stop its load.</summary>
|
||||
public void ReleaseThumbnail()
|
||||
{
|
||||
_loading?.Cancel();
|
||||
_loading = null;
|
||||
if (_thumbnail is null) _requestedWidth = 0;
|
||||
}
|
||||
|
||||
private async Task LoadAsync(int pixelWidth, CancellationTokenSource cancellation)
|
||||
{
|
||||
try
|
||||
{
|
||||
var image = await _thumbnails!.HeroAsync(_sequence, pixelWidth, cancellation.Token);
|
||||
if (!cancellation.IsCancellationRequested) Thumbnail = image;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("library", $"Thumbnail of {_sequence.Id} failed", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (ReferenceEquals(_loading, cancellation)) _loading = null;
|
||||
cancellation.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private void RaiseStatuses()
|
||||
{
|
||||
OnPropertyChanged(nameof(Statuses));
|
||||
OnPropertyChanged(nameof(PrimaryStatus));
|
||||
}
|
||||
|
||||
/// <summary>Card status row: analysed, proxies, renders, sync, warnings (Main.html).</summary>
|
||||
public static IReadOnlyList<CardStatus> BuildStatuses(Sequence s, bool analysing)
|
||||
{
|
||||
var list = new List<CardStatus>(5);
|
||||
if (analysing) list.Add(new CardStatus(StatusKind.Analysing, Loc.L("Library.Status.Analysing"), Loc.L("Tooltips.Library.Status.Analysing")));
|
||||
else if ((s.Status & SequenceStatus.AnalyzedLight) != 0) list.Add(new CardStatus(StatusKind.Analysed, Loc.L("Library.Status.Analysed"), Loc.L("Tooltips.Library.Status.Analysed")));
|
||||
else list.Add(new CardStatus(StatusKind.NotAnalysed, Loc.L("Library.Status.Analysed"), Loc.L("Tooltips.Library.Status.NotAnalysed")));
|
||||
|
||||
if (s.Origin == SequenceOrigin.Server && s.SyncState == SyncState.RemoteOnly)
|
||||
{
|
||||
list.Add(new CardStatus(StatusKind.Remote, Loc.L("Library.Status.Remote"), Loc.L("Tooltips.Library.Status.Remote")));
|
||||
}
|
||||
else
|
||||
{
|
||||
list.Add((s.Status & SequenceStatus.ProxiesBuilt) != 0
|
||||
? new CardStatus(StatusKind.Proxies, Loc.L("Library.Status.Proxies"), Loc.L("Tooltips.Library.Status.Proxies"))
|
||||
: new CardStatus(StatusKind.NoProxies, Loc.L("Library.Status.Proxies"), Loc.L("Tooltips.Library.Status.NoProxies")));
|
||||
}
|
||||
|
||||
if (s.RenderedCount > 0)
|
||||
list.Add(new CardStatus(StatusKind.Rendered, Formatting.Count(s.RenderedCount), Loc.Plural("Tooltips.Library.Status.Rendered", s.RenderedCount)));
|
||||
if (s.SyncState == SyncState.InSync)
|
||||
list.Add(new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.Synced")));
|
||||
if ((s.Status & SequenceStatus.HasErrors) != 0)
|
||||
list.Add(new CardStatus(StatusKind.Error, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.L("Tooltips.Library.Status.Errors")));
|
||||
else if (s.WarningCount > 0 || (s.Status & SequenceStatus.HasWarnings) != 0)
|
||||
list.Add(new CardStatus(StatusKind.Warning, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.Plural("Tooltips.Library.Status.Warnings", Math.Max(1, s.WarningCount))));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>
|
||||
/// Decoded thumbnails in a least-recently-used cache, with loads shared between requests for the same key. A load
|
||||
/// runs off the calling thread, at most <c>maxConcurrentLoads</c> at once; it is cancelled as soon as every request
|
||||
/// waiting for it is cancelled (the card scrolled away), so the decoder never works for rows nobody sees. Results,
|
||||
/// including "no thumbnail" (null), are cached; failures are not.
|
||||
/// </summary>
|
||||
public sealed class ThumbnailCache<TKey, TImage> : IDisposable
|
||||
where TKey : notnull
|
||||
where TImage : class
|
||||
{
|
||||
private readonly LruCache<TKey, TImage?> _cache;
|
||||
private readonly Dictionary<TKey, Load> _loading = [];
|
||||
private readonly Func<TKey, CancellationToken, Task<TImage?>> _load;
|
||||
private readonly SemaphoreSlim _slots;
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
public ThumbnailCache(int capacity, Func<TKey, CancellationToken, Task<TImage?>> load, int maxConcurrentLoads = 4)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(maxConcurrentLoads, 1);
|
||||
_cache = new LruCache<TKey, TImage?>(capacity);
|
||||
_load = load;
|
||||
_slots = new SemaphoreSlim(maxConcurrentLoads, maxConcurrentLoads);
|
||||
}
|
||||
|
||||
/// <summary>Cached entries.</summary>
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _cache.Count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Maximum cached entries; lowering it evicts the least recently used at once.</summary>
|
||||
public int Capacity
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _cache.Capacity;
|
||||
}
|
||||
set
|
||||
{
|
||||
lock (_gate) _cache.Capacity = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Loads started and not yet finished or cancelled.</summary>
|
||||
public int PendingLoads
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _loading.Count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The cached image without loading; true also for a cached "no thumbnail".</summary>
|
||||
public bool TryGet(TKey key, out TImage? image)
|
||||
{
|
||||
lock (_gate) return _cache.TryGet(key, out image);
|
||||
}
|
||||
|
||||
/// <summary>The image for <paramref name="key"/>, from the cache or a (shared) load.</summary>
|
||||
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was cancelled.</exception>
|
||||
public async Task<TImage?> GetAsync(TKey key, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
Load load;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_cache.TryGet(key, out var cached)) return cached;
|
||||
if (!_loading.TryGetValue(key, out load!))
|
||||
{
|
||||
load = new Load();
|
||||
_loading[key] = load;
|
||||
load.Task = Task.Run(() => RunAsync(key, load), CancellationToken.None);
|
||||
}
|
||||
load.Waiters++;
|
||||
}
|
||||
try
|
||||
{
|
||||
return await load.Task.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (--load.Waiters == 0 && !load.Task.IsCompleted)
|
||||
{
|
||||
load.Cancellation.Cancel();
|
||||
if (_loading.TryGetValue(key, out var current) && ReferenceEquals(current, load)) _loading.Remove(key);
|
||||
}
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forgets every cached image (loads in flight complete normally).</summary>
|
||||
public void Clear()
|
||||
{
|
||||
lock (_gate) _cache.Clear();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
foreach (var load in _loading.Values) load.Cancellation.Cancel();
|
||||
_loading.Clear();
|
||||
_cache.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<TImage?> RunAsync(TKey key, Load load)
|
||||
{
|
||||
var token = load.Cancellation.Token;
|
||||
try
|
||||
{
|
||||
await _slots.WaitAsync(token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var image = await _load(key, token).ConfigureAwait(false);
|
||||
lock (_gate)
|
||||
{
|
||||
if (!token.IsCancellationRequested) _cache.Set(key, image);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_loading.TryGetValue(key, out var current) && ReferenceEquals(current, load)) _loading.Remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Load
|
||||
{
|
||||
public CancellationTokenSource Cancellation { get; } = new();
|
||||
public Task<TImage?> Task { get; set; } = null!;
|
||||
public int Waiters { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>
|
||||
/// Attached behaviour of the card template: requests the hero thumbnail when a card shows a sequence and cancels
|
||||
/// it when the card is recycled for another sequence or leaves the tree (scrolled away).
|
||||
/// </summary>
|
||||
public static class ThumbnailLoading
|
||||
{
|
||||
/// <summary>Width of the thumbnail in device-independent pixels; 0 disables loading.</summary>
|
||||
public static readonly DependencyProperty WidthProperty = DependencyProperty.RegisterAttached(
|
||||
"Width", typeof(double), typeof(ThumbnailLoading), new PropertyMetadata(0.0, OnWidthChanged));
|
||||
|
||||
public static double GetWidth(DependencyObject d) => (double)d.GetValue(WidthProperty);
|
||||
|
||||
public static void SetWidth(DependencyObject d, double value) => d.SetValue(WidthProperty, value);
|
||||
|
||||
private static void OnWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is not FrameworkElement element) return;
|
||||
element.DataContextChanged -= OnDataContextChanged;
|
||||
element.Loaded -= OnLoaded;
|
||||
element.Unloaded -= OnUnloaded;
|
||||
if ((double)e.NewValue <= 0) return;
|
||||
element.DataContextChanged += OnDataContextChanged;
|
||||
element.Loaded += OnLoaded;
|
||||
element.Unloaded += OnUnloaded;
|
||||
Request(element);
|
||||
}
|
||||
|
||||
private static void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.OldValue is SequenceItem old) old.ReleaseThumbnail();
|
||||
Request((FrameworkElement)sender);
|
||||
}
|
||||
|
||||
private static void OnLoaded(object sender, RoutedEventArgs e) => Request((FrameworkElement)sender);
|
||||
|
||||
private static void OnUnloaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (((FrameworkElement)sender).DataContext is SequenceItem item) item.ReleaseThumbnail();
|
||||
}
|
||||
|
||||
private static void Request(FrameworkElement element)
|
||||
{
|
||||
if (element.DataContext is not SequenceItem item || !element.IsLoaded) return;
|
||||
var scale = VisualTreeHelper.GetDpi(element).DpiScaleX;
|
||||
item.RequestThumbnail((int)Math.Ceiling(GetWidth(element) * scale));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>A thumbnail request: one frame at a width bucket (so nearby sizes share a decode).</summary>
|
||||
public readonly record struct ThumbnailKey(Guid FrameId, int Width);
|
||||
|
||||
/// <summary>
|
||||
/// Library thumbnails (BRIEF §8.5): a frame's embedded preview, read straight from its offset/length in the
|
||||
/// original and decoded by WIC at the requested width (falling back to decoding the original), turned upright,
|
||||
/// frozen and kept in an LRU cache. Loads run off the UI thread and stop when the card scrolls away.
|
||||
/// </summary>
|
||||
public sealed class ThumbnailService : IDisposable
|
||||
{
|
||||
/// <summary>Embedded previews larger than this are not read (a damaged index would make us read gigabytes).</summary>
|
||||
private const long MaxPreviewBytes = 64L << 20;
|
||||
|
||||
private const int WidthStep = 64;
|
||||
|
||||
private readonly TitanoDatabase _db;
|
||||
private readonly ThumbnailCache<ThumbnailKey, ImageSource> _cache;
|
||||
private readonly ConcurrentDictionary<Guid, string?> _archiveRoots = new();
|
||||
private readonly ConcurrentDictionary<Guid, Guid?> _firstFrames = new();
|
||||
|
||||
public ThumbnailService(TitanoDatabase db, int capacity)
|
||||
{
|
||||
_db = db;
|
||||
_cache = new ThumbnailCache<ThumbnailKey, ImageSource>(Math.Max(16, capacity), LoadAsync, maxConcurrentLoads: Math.Clamp(Environment.ProcessorCount / 2, 2, 6));
|
||||
}
|
||||
|
||||
public int Count => _cache.Count;
|
||||
|
||||
/// <summary>Decodes in flight (capture waits for them).</summary>
|
||||
public int PendingLoads => _cache.PendingLoads;
|
||||
|
||||
/// <summary>Maximum thumbnails kept in memory (Settings › Storage).</summary>
|
||||
public int Capacity
|
||||
{
|
||||
get => _cache.Capacity;
|
||||
set => _cache.Capacity = Math.Max(16, value);
|
||||
}
|
||||
|
||||
/// <summary>The hero thumbnail of a sequence: its hero frame, or the first frame.</summary>
|
||||
public async Task<ImageSource?> HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct)
|
||||
{
|
||||
var frameId = sequence.HeroFrameId ?? await FirstFrameAsync(sequence.Id, ct).ConfigureAwait(false);
|
||||
return frameId is { } id ? await _cache.GetAsync(Key(id, pixelWidth), ct).ConfigureAwait(false) : null;
|
||||
}
|
||||
|
||||
/// <summary>A frame of a sequence by index (hover scrubbing).</summary>
|
||||
public async Task<ImageSource?> FrameAsync(Guid sequenceId, int index, int pixelWidth, CancellationToken ct)
|
||||
{
|
||||
var frames = await _db.Frames.ListBySequenceAsync(sequenceId, index - 1, 1, ct).ConfigureAwait(false);
|
||||
return frames.Count == 0 ? null : await _cache.GetAsync(Key(frames[0].Id, pixelWidth), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Hover-scrub frames of a sequence, sampled to at most <paramref name="positions"/> positions.</summary>
|
||||
public IThumbnailSource ScrubSource(Sequence sequence, int positions = 120) => new ScrubFrames(this, sequence, positions);
|
||||
|
||||
/// <summary>Drops decoded thumbnails (Settings › Storage › Clear).</summary>
|
||||
public void Clear()
|
||||
{
|
||||
_cache.Clear();
|
||||
_archiveRoots.Clear();
|
||||
_firstFrames.Clear();
|
||||
}
|
||||
|
||||
public void Dispose() => _cache.Dispose();
|
||||
|
||||
private static ThumbnailKey Key(Guid frameId, int pixelWidth) =>
|
||||
new(frameId, Math.Clamp((pixelWidth + WidthStep - 1) / WidthStep * WidthStep, WidthStep, 2048));
|
||||
|
||||
private async Task<Guid?> FirstFrameAsync(Guid sequenceId, CancellationToken ct)
|
||||
{
|
||||
if (_firstFrames.TryGetValue(sequenceId, out var cached)) return cached;
|
||||
var frames = await _db.Frames.ListBySequenceAsync(sequenceId, -1, 1, ct).ConfigureAwait(false);
|
||||
var id = frames.Count > 0 ? frames[0].Id : (Guid?)null;
|
||||
_firstFrames[sequenceId] = id;
|
||||
return id;
|
||||
}
|
||||
|
||||
private async Task<string?> ArchiveRootAsync(Guid sequenceId, CancellationToken ct)
|
||||
{
|
||||
var sequence = await _db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false);
|
||||
if (sequence is null) return null;
|
||||
if (_archiveRoots.TryGetValue(sequence.ArchiveId, out var root)) return root;
|
||||
root = (await _db.Archives.GetAsync(sequence.ArchiveId, ct).ConfigureAwait(false))?.RootPath;
|
||||
_archiveRoots[sequence.ArchiveId] = root;
|
||||
return root;
|
||||
}
|
||||
|
||||
private async Task<ImageSource?> LoadAsync(ThumbnailKey key, CancellationToken ct)
|
||||
{
|
||||
var frame = await _db.Frames.GetAsync(key.FrameId, ct).ConfigureAwait(false);
|
||||
if (frame is null) return null;
|
||||
var root = await ArchiveRootAsync(frame.SequenceId, ct).ConfigureAwait(false);
|
||||
if (root is null) return null;
|
||||
var path = Path.Combine(root, frame.RelativePath.Replace('/', Path.DirectorySeparatorChar));
|
||||
ct.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
return Decode(path, frame, key.Width, ct);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or FileFormatException or ArgumentException or InvalidOperationException)
|
||||
{
|
||||
Log.Debug("thumbs", $"No thumbnail for {path}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The embedded preview when the index knows it, otherwise the original, decoded at <paramref name="width"/>.</summary>
|
||||
internal static BitmapSource? Decode(string path, Frame frame, int width, CancellationToken ct)
|
||||
{
|
||||
if (!File.Exists(path)) return null;
|
||||
if (frame.PreviewOffset is > 0 and var offset && frame.PreviewLength is > 0 and <= MaxPreviewBytes and var length)
|
||||
{
|
||||
var bytes = new byte[length];
|
||||
using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, FileOptions.RandomAccess))
|
||||
{
|
||||
if (offset + length <= file.Length)
|
||||
{
|
||||
file.Seek(offset, SeekOrigin.Begin);
|
||||
file.ReadExactly(bytes);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
using var memory = new MemoryStream(bytes, writable: false);
|
||||
return DecodeStream(memory, frame.Orientation, width);
|
||||
}
|
||||
catch (Exception ex) when (ex is NotSupportedException or FileFormatException or ArgumentException)
|
||||
{
|
||||
// A broken preview falls through to the original.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ct.ThrowIfCancellationRequested();
|
||||
using var original = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.SequentialScan);
|
||||
return DecodeStream(original, frame.Orientation, width);
|
||||
}
|
||||
|
||||
/// <summary>WIC decode with scaling during decode (JPEG DCT scaling), then the Exif orientation; frozen for any thread.</summary>
|
||||
internal static BitmapSource DecodeStream(Stream stream, int orientation, int width)
|
||||
{
|
||||
var turned = orientation is 5 or 6 or 7 or 8;
|
||||
var image = new BitmapImage();
|
||||
image.BeginInit();
|
||||
image.CacheOption = BitmapCacheOption.OnLoad;
|
||||
image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
|
||||
if (turned) image.DecodePixelHeight = width;
|
||||
else image.DecodePixelWidth = width;
|
||||
image.StreamSource = stream;
|
||||
image.EndInit();
|
||||
BitmapSource result = image;
|
||||
if (orientation is > 1 and <= 8)
|
||||
{
|
||||
var transform = new TransformGroup();
|
||||
if (orientation is 2 or 4 or 5 or 7) transform.Children.Add(new ScaleTransform(-1, 1));
|
||||
var angle = orientation switch
|
||||
{
|
||||
3 or 4 => 180,
|
||||
5 or 6 => 90,
|
||||
7 or 8 => 270,
|
||||
_ => 0,
|
||||
};
|
||||
if (angle != 0) transform.Children.Add(new RotateTransform(angle));
|
||||
result = new TransformedBitmap(image, transform);
|
||||
}
|
||||
result.Freeze();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Evenly spaced frames of one sequence for <see cref="SequenceCard"/> hover scrubbing.</summary>
|
||||
private sealed class ScrubFrames(ThumbnailService owner, Sequence sequence, int positions) : IThumbnailSource
|
||||
{
|
||||
public int Count { get; } = Math.Clamp(Math.Min(sequence.FrameCount, positions), 0, positions);
|
||||
|
||||
public async ValueTask<ImageSource?> GetAsync(int index, int pixelWidth, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Count <= 1) return await owner.HeroAsync(sequence, pixelWidth, cancellationToken).ConfigureAwait(false);
|
||||
var frameIndex = (int)Math.Round(index * (sequence.FrameCount - 1) / (double)(Count - 1));
|
||||
return await owner.FrameAsync(sequence.Id, frameIndex, pixelWidth, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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">
|
||||
<!-- BRIEF §12.9 (no mockup): built from the kit — panel, label column, one primary action. -->
|
||||
<Grid Margin="20,16,20,20">
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="28,24" HorizontalAlignment="Left" VerticalAlignment="Top" MinWidth="560">
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="28,24" HorizontalAlignment="Left" VerticalAlignment="Top" MinWidth="600">
|
||||
<StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,20">
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,22">
|
||||
<ui:BrandMarkIcon Width="56" Height="56" ShowPlate="True" />
|
||||
<StackPanel Margin="16,0,0,0" VerticalAlignment="Center">
|
||||
<TextBlock Text="{l:Loc Shell.AppName}" Style="{StaticResource Text.PageTitle}" FontSize="22" />
|
||||
<TextBlock Text="{Binding Version}" Style="{StaticResource Text.Secondary}" Margin="0,2,0,0" />
|
||||
<TextBlock Text="{Binding Version}" Style="{StaticResource Text.Secondary}" Margin="0,2,0,0" Typography.NumeralAlignment="Tabular" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="140" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="140" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
@@ -23,20 +25,47 @@
|
||||
<RowDefinition Height="28" />
|
||||
<RowDefinition Height="28" />
|
||||
<RowDefinition Height="28" />
|
||||
<RowDefinition Height="28" />
|
||||
<RowDefinition Height="28" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="28" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{l:Loc About.Runtime}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding Runtime}" />
|
||||
<TextBlock Grid.Row="1" Text="{l:Loc About.System}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding OperatingSystem}" />
|
||||
<TextBlock Grid.Row="2" Text="{l:Loc About.ThirdParty}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="1" Text="{l:Loc About.ThirdPartyNone}" />
|
||||
<TextBlock Grid.Row="3" Text="{l:Loc About.Data}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding DataFolder}" />
|
||||
<TextBlock Style="{StaticResource Text.Label}" Text="{l:Loc About.Build}" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding Build}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
|
||||
<TextBlock Grid.Row="1" Style="{StaticResource Text.Label}" Text="{l:Loc About.Runtime}" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Runtime}" VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Row="2" Style="{StaticResource Text.Label}" Text="{l:Loc About.System}" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding OperatingSystem}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Grid.Row="3" Style="{StaticResource Text.Label}" Text="{l:Loc About.Licence}" />
|
||||
<Button Grid.Row="3" Grid.Column="1" Style="{StaticResource Button.Link}" FontSize="13" HorizontalAlignment="Left" VerticalAlignment="Center"
|
||||
Content="{l:Loc About.LicenceLink}" Command="{Binding OpenLicenceCommand}" ToolTip="{l:Loc Tooltips.About.Licence}" />
|
||||
<TextBlock Grid.Row="4" Style="{StaticResource Text.Label}" Text="{l:Loc About.ThirdParty}" />
|
||||
<TextBlock Grid.Row="4" Grid.Column="1" Text="{l:Loc About.ThirdPartyNone}" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.About.ThirdParty}" />
|
||||
<TextBlock Grid.Row="5" Style="{StaticResource Text.Label}" Text="{l:Loc About.Data}" />
|
||||
<TextBlock Grid.Row="5" Grid.Column="1" Text="{Binding DataFolder}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Grid.Row="6" Style="{StaticResource Text.Label}" Text="{l:Loc About.Translation}" Height="28"
|
||||
Visibility="{Binding IsTranslated, Converter={StaticResource BoolToVisibility}}" />
|
||||
<StackPanel Grid.Row="6" Grid.Column="1" Orientation="Horizontal" Height="28" Visibility="{Binding IsTranslated, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc About.MachineTranslated}" VerticalAlignment="Center" />
|
||||
<Button Style="{StaticResource Button.Link}" FontSize="13" Margin="12,0,0,0" VerticalAlignment="Center" Content="{l:Loc About.Review}"
|
||||
Command="{Binding ReviewTranslationCommand}" ToolTip="{l:Loc Tooltips.About.Review}" />
|
||||
</StackPanel>
|
||||
<TextBlock Grid.Row="7" Style="{StaticResource Text.Label}" Text="{l:Loc About.Updates}" />
|
||||
<StackPanel Grid.Row="7" Grid.Column="1" Orientation="Horizontal">
|
||||
<ui:StatusGlyph Kind="{Binding UpdateKind}" Text="{Binding UpdateText}" FontSize="13" VerticalAlignment="Center"
|
||||
Visibility="{Binding HasUpdateText, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Link}" FontSize="13" Margin="12,0,0,0" VerticalAlignment="Center" Content="{l:Loc About.Update.Download}"
|
||||
Command="{Binding DownloadCommand}" ToolTip="{l:Loc Tooltips.About.Download}"
|
||||
Visibility="{Binding IsUpdateAvailable, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<StackPanel Orientation="Horizontal" Margin="0,20,0,0">
|
||||
<Button Content="{l:Loc About.Releases}" Command="{Binding OpenReleasesCommand}" ToolTip="{l:Loc Tooltips.About.Releases}" Margin="0,0,8,0" ui:ButtonIcon.Glyph="{StaticResource Icon.ExternalLink}" />
|
||||
<Button Content="{l:Loc About.OpenData}" Command="{Binding OpenDataFolderCommand}" ToolTip="{l:Loc Tooltips.About.OpenData}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" />
|
||||
</StackPanel>
|
||||
|
||||
<WrapPanel Margin="0,22,0,0">
|
||||
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc About.Update.Check}" Command="{Binding CheckCommand}" ToolTip="{l:Loc Tooltips.About.Check}" Margin="0,0,8,8" />
|
||||
<Button Content="{l:Loc About.Releases}" Command="{Binding OpenReleasesCommand}" ToolTip="{l:Loc Tooltips.About.Releases}" ui:ButtonIcon.Glyph="{StaticResource Icon.ExternalLink}" Margin="0,0,8,8" />
|
||||
<Button Content="{l:Loc About.Diagnostics}" Command="{Binding DiagnosticsCommand}" ToolTip="{l:Loc Tooltips.About.Diagnostics}" ui:ButtonIcon.Glyph="{StaticResource Icon.Export}" Margin="0,0,8,8" />
|
||||
<Button Content="{l:Loc About.OpenData}" Command="{Binding OpenDataFolderCommand}" ToolTip="{l:Loc Tooltips.About.OpenData}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" Margin="0,0,8,8" />
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.About;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>
|
||||
/// About (BRIEF §12.9): version and build, licence link, third-party notice (none), translation notice,
|
||||
/// diagnostics bundle and the update check against the public releases repository (BRIEF §18).
|
||||
/// </summary>
|
||||
public sealed class AboutViewModel : SectionViewModel
|
||||
{
|
||||
private ReleaseInfo? _release;
|
||||
private UpdateState _state = UpdateState.Unknown;
|
||||
|
||||
public AboutViewModel(ShellViewModel shell)
|
||||
: base(SectionKey.About, "Icon.About")
|
||||
{
|
||||
Shell = shell;
|
||||
CheckCommand = new AsyncRelayCommand(() => CheckAsync(notify: false), () => _state != UpdateState.Checking);
|
||||
DownloadCommand = new RelayCommand(() =>
|
||||
{
|
||||
if (_release is { } release) ShellActions.OpenUrl(release.PageUrl);
|
||||
}, () => _release is not null);
|
||||
OpenReleasesCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Releases));
|
||||
OpenLicenceCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Licence));
|
||||
ReviewTranslationCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Issues));
|
||||
OpenDataFolderCommand = new RelayCommand(() => ShellActions.Reveal(DataFolder));
|
||||
DiagnosticsCommand = new AsyncRelayCommand(DiagnosticsAsync);
|
||||
}
|
||||
|
||||
private enum UpdateState
|
||||
{
|
||||
Unknown,
|
||||
Checking,
|
||||
UpToDate,
|
||||
Available,
|
||||
Failed,
|
||||
}
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
public string Version => AppServices.VersionText;
|
||||
|
||||
/// <summary>File version and processor architecture.</summary>
|
||||
public string Build =>
|
||||
(typeof(App).Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()?.Version ?? Version) + " · " + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant();
|
||||
|
||||
public string Runtime => RuntimeInformation.FrameworkDescription;
|
||||
|
||||
public string OperatingSystem => RuntimeInformation.OSDescription;
|
||||
|
||||
public string DataFolder => Shell.Services.Environment.DataDirectory;
|
||||
|
||||
/// <summary>Every language but English is machine-translated and open to review (BRIEF §16).</summary>
|
||||
public bool IsTranslated => !Loc.Culture.TwoLetterISOLanguageName.Equals("en", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public ICommand CheckCommand { get; }
|
||||
public ICommand DownloadCommand { get; }
|
||||
public ICommand OpenReleasesCommand { get; }
|
||||
public ICommand OpenLicenceCommand { get; }
|
||||
public ICommand ReviewTranslationCommand { get; }
|
||||
public ICommand OpenDataFolderCommand { get; }
|
||||
public ICommand DiagnosticsCommand { get; }
|
||||
|
||||
/// <summary>"Up to date", "Titano 0.2.0 available", …; null before the first check.</summary>
|
||||
public string? UpdateText => _state switch
|
||||
{
|
||||
UpdateState.Checking => Loc.L("About.Update.Checking"),
|
||||
UpdateState.UpToDate => Loc.L("About.Update.Current"),
|
||||
UpdateState.Available when _release is { } r => Loc.L("About.Update.Available", UpdateCheck.Display(r.Version)),
|
||||
UpdateState.Failed => Loc.L("About.Update.Failed"),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
public StatusKind UpdateKind => _state switch
|
||||
{
|
||||
UpdateState.Checking => StatusKind.Running,
|
||||
UpdateState.UpToDate => StatusKind.Done,
|
||||
UpdateState.Available => StatusKind.Warning,
|
||||
_ => StatusKind.Error,
|
||||
};
|
||||
|
||||
public bool HasUpdateText => UpdateText is not null;
|
||||
|
||||
public bool IsUpdateAvailable => _state == UpdateState.Available;
|
||||
|
||||
/// <summary>Starts the update check on start when allowed (opt-out, BRIEF §18).</summary>
|
||||
public void Attach()
|
||||
{
|
||||
if (Shell.Services.Settings.CheckForUpdates && !Shell.Services.Environment.IsCapture) _ = CheckAsync(notify: true);
|
||||
}
|
||||
|
||||
/// <summary>Sets a result without the network (capture, tests).</summary>
|
||||
internal void SetResult(ReleaseInfo? release, bool failed = false)
|
||||
{
|
||||
_release = release is not null && UpdateCheck.IsNewer(release, UpdateCheck.RunningVersion(Version)) ? release : null;
|
||||
_state = failed ? UpdateState.Failed : _release is null ? UpdateState.UpToDate : UpdateState.Available;
|
||||
RaiseUpdate();
|
||||
}
|
||||
|
||||
private async Task CheckAsync(bool notify)
|
||||
{
|
||||
_state = UpdateState.Checking;
|
||||
RaiseUpdate();
|
||||
try
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
||||
var release = await Shell.Services.CheckForUpdateAsync(timeout.Token);
|
||||
SetResult(release);
|
||||
if (notify && _release is { } newer)
|
||||
{
|
||||
Shell.Notify(Loc.L("About.Update.Available", UpdateCheck.Display(newer.Version)), actionText: Loc.L("About.Update.Download"),
|
||||
actionToolTip: Loc.L("Tooltips.About.Download"), action: () => ShellActions.OpenUrl(newer.PageUrl));
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException)
|
||||
{
|
||||
Log.Info("update", "Update check failed: " + ex.Message);
|
||||
SetResult(null, failed: true);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DiagnosticsAsync()
|
||||
{
|
||||
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Advanced.DiagnosticsTitle"));
|
||||
if (folder is null) return;
|
||||
var path = await DiagnosticsBundle.CreateAsync(Shell.Services.Environment, folder);
|
||||
Shell.Notify(Loc.L("Settings.Advanced.DiagnosticsDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
|
||||
}
|
||||
|
||||
private void RaiseUpdate()
|
||||
{
|
||||
OnPropertyChanged(nameof(UpdateText));
|
||||
OnPropertyChanged(nameof(UpdateKind));
|
||||
OnPropertyChanged(nameof(HasUpdateText));
|
||||
OnPropertyChanged(nameof(IsUpdateAvailable));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using Titano.App.Shell;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>Archive manager (BRIEF §12.5).</summary>
|
||||
public sealed class ArchiveViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Archive, "Icon.Archive")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using Titano.App.Shell;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>Card and folder import (BRIEF §12.4).</summary>
|
||||
public sealed class ImportViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Import, "Icon.Import")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
}
|
||||
@@ -2,8 +2,166 @@
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
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">
|
||||
<Grid Margin="20">
|
||||
<ui:EmptyState Message="{l:Loc Jobs.Empty}" />
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
|
||||
xmlns:s="clr-namespace:Titano.App.Sections"
|
||||
xmlns:j="clr-namespace:Titano.App.Jobs">
|
||||
<UserControl.Resources>
|
||||
<!-- Column layout shared by the header and the rows (Jobs.html grid-template-columns). -->
|
||||
<Style x:Key="Text.Muted" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsDimmed}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<Style x:Key="Text.MutedNumber" TargetType="TextBlock" BasedOn="{StaticResource Text.Muted}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
<Style x:Key="ProgressBar.Job" TargetType="ProgressBar" BasedOn="{StaticResource {x:Type ProgressBar}}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsDone}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Success}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding IsFailed}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Error}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<ItemsPanelTemplate x:Key="Panel.Row">
|
||||
<StackPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="56" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Toolbar: state chips · search · workers, Pause all, Clear done. -->
|
||||
<DockPanel Margin="20,0" LastChildFill="False">
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Jobs.ClearDone}" Command="{Binding ClearDoneCommand}" ToolTip="{l:Loc Tooltips.Jobs.ClearDone}" Margin="8,0,0,0" />
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Jobs.PauseAll}" Command="{Binding PauseAllCommand}" ToolTip="{l:Loc Tooltips.Jobs.PauseAll}" Margin="12,0,0,0" />
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding WorkersText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Jobs.Workers}" />
|
||||
<ItemsControl ItemsSource="{Binding Chips}" ItemsPanel="{StaticResource Panel.Row}" Focusable="False" VerticalAlignment="Center">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type s:JobFilterChip}">
|
||||
<Button Style="{StaticResource Button.Chip}" Content="{Binding Text}" Tag="{Binding IsSelected}" Command="{Binding SelectCommand}"
|
||||
ToolTip="{Binding ToolTip}" Margin="0,0,8,0" Typography.NumeralAlignment="Tabular" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<Border Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="6,0,14,0" VerticalAlignment="Center" />
|
||||
<TextBox Width="240" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
|
||||
ui:Field.Placeholder="{l:Loc Jobs.Search}" ToolTip="{l:Loc Tooltips.Jobs.Search}" AutomationProperties.Name="{l:Loc Jobs.Search}" />
|
||||
</DockPanel>
|
||||
|
||||
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Margin="20,0,20,12" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Header -->
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="28" />
|
||||
<ColumnDefinition Width="120" />
|
||||
<ColumnDefinition Width="1.6*" MinWidth="160" />
|
||||
<ColumnDefinition Width="200" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="110" />
|
||||
<ColumnDefinition Width="120" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="150" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Kind}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Target}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Progress}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Speed}" Margin="10,0,0,0" TextAlignment="Right" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Left}" Margin="10,0,0,0" TextAlignment="Right" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Where}" Margin="16,0,0,0" />
|
||||
<TextBlock Grid.Column="7" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.State}" Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Rows: queue order, then the history; expandable log tail. -->
|
||||
<ListBox Grid.Row="1" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.PlainRow}"
|
||||
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.ScrollChanged="OnScrollChanged" AutomationProperties.Name="{l:Loc Shell.Nav.Jobs}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:JobRowViewModel}">
|
||||
<StackPanel>
|
||||
<Grid x:Name="Row" Height="38" Background="Transparent">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="28" />
|
||||
<ColumnDefinition Width="120" />
|
||||
<ColumnDefinition Width="1.6*" MinWidth="160" />
|
||||
<ColumnDefinition Width="200" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="110" />
|
||||
<ColumnDefinition Width="120" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="150" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button x:Name="Toggle" Style="{StaticResource Button.IconSubtle}" Width="22" Height="22" MinWidth="22" Margin="14,0,0,0"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.ChevronRight}" Command="{Binding ToggleLogCommand}"
|
||||
ToolTip="{Binding ToggleToolTip}" AutomationProperties.Name="{Binding ToggleToolTip}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Muted}" Text="{Binding Kind}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding Target}" Margin="10,0,0,0" ToolTip="{Binding Target}" />
|
||||
<Grid Grid.Column="3" Margin="10,0,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="44" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ProgressBar Style="{StaticResource ProgressBar.Job}" Maximum="1" Value="{Binding Progress, Mode=OneWay}" VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.MutedNumber}" Text="{Binding PercentText}" />
|
||||
</Grid>
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.MutedNumber}" Text="{Binding SpeedText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.MutedNumber}" Text="{Binding LeftText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.Muted}" Text="{Binding WhereText}" Margin="16,0,0,0" />
|
||||
<ui:StatusGlyph Grid.Column="7" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}"
|
||||
FontSize="13" VerticalAlignment="Center" Margin="10,0,0,0" />
|
||||
<ItemsControl Grid.Column="8" ItemsSource="{Binding Actions}" ItemsPanel="{StaticResource Panel.Row}" Focusable="False"
|
||||
VerticalAlignment="Center" Margin="10,0,8,0">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:JobAction}">
|
||||
<Button Style="{StaticResource Button.Row}" Content="{Binding Text}" Command="{Binding Command}" ToolTip="{Binding ToolTip}" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
<Border x:Name="Log" Background="{DynamicResource Brush.Bg}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0"
|
||||
Padding="52,10,14,12" Visibility="Collapsed">
|
||||
<TextBlock Style="{StaticResource Text.Log}" Text="{Binding LogText}" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsExpanded}" Value="True">
|
||||
<Setter TargetName="Log" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Row" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter TargetName="Toggle" Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.ChevronDown}" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<!-- Footer -->
|
||||
<Border Grid.Row="2" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0" Padding="14,8">
|
||||
<DockPanel LastChildFill="False" TextElement.FontSize="12">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Jobs.RenderingSettings}" Command="{Binding RenderingSettingsCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.RenderingSettings}" />
|
||||
<TextBlock Text="{Binding HistoryText}" Foreground="{DynamicResource Brush.TextMuted}" ToolTip="{l:Loc Tooltips.Jobs.History}" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<ui:EmptyState Grid.Row="1" Message="{l:Loc Jobs.Empty}" Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -5,4 +5,11 @@ namespace Titano.App.Sections;
|
||||
public partial class JobsView : UserControl
|
||||
{
|
||||
public JobsView() => InitializeComponent();
|
||||
|
||||
/// <summary>Loads older history when the list scrolls near its end.</summary>
|
||||
private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
|
||||
{
|
||||
if (DataContext is not JobsViewModel vm || e.ExtentHeight <= 0) return;
|
||||
if (e.VerticalOffset + e.ViewportHeight >= e.ExtentHeight - Math.Max(e.ViewportHeight, 200)) _ = vm.LoadMoreAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Jobs;
|
||||
using Titano.App.Settings;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>A filter chip of the Jobs toolbar ("Running · 4").</summary>
|
||||
public sealed class JobFilterChip(JobFilter filter, Action<JobFilter> select) : ObservableObject
|
||||
{
|
||||
private int _count;
|
||||
private bool _isSelected;
|
||||
|
||||
public JobFilter Filter { get; } = filter;
|
||||
|
||||
public string Text => Loc.L("Jobs.Filter." + Filter, Formatting.Count(_count));
|
||||
|
||||
public string ToolTip => Loc.L("Tooltips.Jobs.Filter." + Filter);
|
||||
|
||||
public ICommand SelectCommand { get; } = new RelayCommand(() => select(filter));
|
||||
|
||||
public bool IsSelected
|
||||
{
|
||||
get => _isSelected;
|
||||
set => Set(ref _isSelected, value);
|
||||
}
|
||||
|
||||
public int Count
|
||||
{
|
||||
get => _count;
|
||||
set
|
||||
{
|
||||
if (Set(ref _count, value)) OnPropertyChanged(nameof(Text));
|
||||
}
|
||||
}
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Jobs (BRIEF §12.6, Jobs.html): queue and history with live progress from the engine (batched to about 10
|
||||
/// updates a second), filters, queue order, an expandable log tail per job, and the row actions. Also feeds the
|
||||
/// shell's job bar, the status strip and the rail badge.
|
||||
/// </summary>
|
||||
public sealed class JobsViewModel : SectionViewModel
|
||||
{
|
||||
private static readonly TimeSpan FlushInterval = TimeSpan.FromMilliseconds(100);
|
||||
private const int PageSize = 200;
|
||||
|
||||
private readonly JobListModel _model = new();
|
||||
private readonly JobUpdateBuffer _buffer = new();
|
||||
private readonly Dictionary<Guid, JobRowViewModel> _rows = [];
|
||||
private readonly JobActions _actions;
|
||||
private CoalescingThrottle? _throttle;
|
||||
private IJobQueue? _queue;
|
||||
private JobFilter _filter = JobFilter.All;
|
||||
private string _searchText = string.Empty;
|
||||
private string? _cursor;
|
||||
private bool _hasMore;
|
||||
private bool _loading;
|
||||
private bool _hasLoaded;
|
||||
|
||||
public JobsViewModel(ShellViewModel shell)
|
||||
: base(SectionKey.Jobs, "Icon.Jobs")
|
||||
{
|
||||
Shell = shell;
|
||||
_actions = new JobActions(this);
|
||||
Chips = [.. Enum.GetValues<JobFilter>().Select(f => new JobFilterChip(f, SelectFilter) { IsSelected = f == JobFilter.All })];
|
||||
PauseCurrentCommand = new AsyncRelayCommand(PauseCurrentAsync, () => _model.Current is not null);
|
||||
PauseAllCommand = new AsyncRelayCommand(PauseAllAsync, () => _model.RunningCount > 0);
|
||||
ClearDoneCommand = new RelayCommand(ClearDone, () => _model.CountOf(JobFilter.Done, ClearedAt) + _model.CountOf(JobFilter.Failed, ClearedAt) > 0);
|
||||
RenderingSettingsCommand = new RelayCommand(() =>
|
||||
{
|
||||
Shell.Settings.Page = SettingsPage.Rendering;
|
||||
Shell.Navigate(SectionKey.Settings);
|
||||
});
|
||||
LoadMoreCommand = new RelayCommand(() => _ = LoadMoreAsync());
|
||||
}
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
/// <summary>Rows in display order for the current filter and search.</summary>
|
||||
public ObservableCollection<JobRowViewModel> Rows { get; } = [];
|
||||
|
||||
public IReadOnlyList<JobFilterChip> Chips { get; }
|
||||
|
||||
public ICommand PauseCurrentCommand { get; }
|
||||
public ICommand PauseAllCommand { get; }
|
||||
public ICommand ClearDoneCommand { get; }
|
||||
public ICommand RenderingSettingsCommand { get; }
|
||||
public ICommand LoadMoreCommand { get; }
|
||||
|
||||
public JobFilter Filter
|
||||
{
|
||||
get => _filter;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _filter, value)) return;
|
||||
foreach (var chip in Chips) chip.IsSelected = chip.Filter == value;
|
||||
SyncRows();
|
||||
}
|
||||
}
|
||||
|
||||
public string SearchText
|
||||
{
|
||||
get => _searchText;
|
||||
set
|
||||
{
|
||||
if (Set(ref _searchText, value ?? string.Empty)) SyncRows();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Workers 1 / 4".</summary>
|
||||
public string WorkersText => Loc.L("Jobs.Workers", _model.RunningCount, _queue?.Workers ?? 0);
|
||||
|
||||
/// <summary>"History keeps 90 days".</summary>
|
||||
public string HistoryText => Loc.Plural("Jobs.History", (long)new JobEngineOptions().HistoryRetention.TotalDays);
|
||||
|
||||
public bool IsEmpty => _hasLoaded && Rows.Count == 0;
|
||||
|
||||
public bool HasRows => Rows.Count > 0;
|
||||
|
||||
internal IJobQueue? Queue => _queue;
|
||||
|
||||
internal JobListModel Model => _model;
|
||||
|
||||
private DateTimeOffset? ClearedAt => Shell.Services.Settings.JobsClearedAt;
|
||||
|
||||
/// <summary>Subscribes to the engine and loads the first page of jobs.</summary>
|
||||
public void Attach()
|
||||
{
|
||||
_queue = Shell.Services.Jobs;
|
||||
if (_queue is null)
|
||||
{
|
||||
_hasLoaded = true;
|
||||
RaiseState();
|
||||
return;
|
||||
}
|
||||
_throttle = new CoalescingThrottle(FlushInterval, SynchronizationContext.Current, Flush);
|
||||
_queue.JobChanged += OnJobChanged;
|
||||
_queue.Progress += OnProgress;
|
||||
_ = LoadMoreAsync();
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
if (_queue is not null)
|
||||
{
|
||||
_queue.JobChanged -= OnJobChanged;
|
||||
_queue.Progress -= OnProgress;
|
||||
}
|
||||
_throttle?.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Reads the job list again from the first page (after jobs were written outside the engine).</summary>
|
||||
public Task ReloadAsync()
|
||||
{
|
||||
_cursor = null;
|
||||
_hasMore = true;
|
||||
_hasLoaded = false;
|
||||
return LoadMoreAsync();
|
||||
}
|
||||
|
||||
/// <summary>Next page of the history (newest first); the view calls it when the list scrolls near its end.</summary>
|
||||
public async Task LoadMoreAsync()
|
||||
{
|
||||
if (_queue is null || _loading || (_hasLoaded && !_hasMore)) return;
|
||||
_loading = true;
|
||||
try
|
||||
{
|
||||
var stamp = _model.Stamp;
|
||||
var page = await _queue.ListAsync(_cursor, PageSize);
|
||||
foreach (var job in page.Items) _model.ApplyLoaded(job, stamp);
|
||||
_cursor = page.NextCursor;
|
||||
_hasMore = page.NextCursor is not null;
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("jobs", "Job list unavailable", ex);
|
||||
_hasMore = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_loading = false;
|
||||
_hasLoaded = true;
|
||||
}
|
||||
Flush();
|
||||
}
|
||||
|
||||
/// <summary>Applies everything buffered since the last flush (UI thread).</summary>
|
||||
internal void Flush()
|
||||
{
|
||||
var (jobs, progress) = _buffer.Drain();
|
||||
foreach (var job in jobs) _model.Apply(job);
|
||||
foreach (var p in progress) _model.Apply(p);
|
||||
SyncRows();
|
||||
UpdateShell();
|
||||
}
|
||||
|
||||
private void OnJobChanged(Job job)
|
||||
{
|
||||
_buffer.Post(job);
|
||||
_throttle?.Signal();
|
||||
}
|
||||
|
||||
private void OnProgress(JobProgressInfo progress)
|
||||
{
|
||||
_buffer.Post(progress);
|
||||
_throttle?.Signal();
|
||||
}
|
||||
|
||||
private void SelectFilter(JobFilter filter) => Filter = filter;
|
||||
|
||||
/// <summary>Brings <see cref="Rows"/> to the model's order with moves (rows keep their expanded log).</summary>
|
||||
private void SyncRows()
|
||||
{
|
||||
var ordered = _model.Ordered(_filter, _searchText, ClearedAt);
|
||||
var wanted = new HashSet<Guid>(ordered.Select(e => e.Id));
|
||||
for (var i = Rows.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (!wanted.Contains(Rows[i].Id)) Rows.RemoveAt(i);
|
||||
}
|
||||
for (var i = 0; i < ordered.Count; i++)
|
||||
{
|
||||
var entry = ordered[i];
|
||||
var position = entry.State == JobState.Queued ? _model.QueuePosition(entry.Id) : 0;
|
||||
if (!_rows.TryGetValue(entry.Id, out var row))
|
||||
{
|
||||
row = new JobRowViewModel(entry, position, _actions);
|
||||
_rows[entry.Id] = row;
|
||||
}
|
||||
else
|
||||
{
|
||||
row.Update(entry, position);
|
||||
}
|
||||
if (i < Rows.Count && ReferenceEquals(Rows[i], row)) continue;
|
||||
var existing = Rows.IndexOf(row);
|
||||
if (existing >= 0) Rows.Move(existing, i);
|
||||
else Rows.Insert(i, row);
|
||||
}
|
||||
foreach (var chip in Chips) chip.Count = _model.CountOf(chip.Filter, ClearedAt);
|
||||
RaiseState();
|
||||
}
|
||||
|
||||
private void UpdateShell()
|
||||
{
|
||||
if (_model.Current is { } current)
|
||||
Shell.SetJob(JobText.Bar(current), current.Fraction ?? 0, indeterminate: current.Fraction is null);
|
||||
else
|
||||
Shell.SetJob(null, 0);
|
||||
Shell.SetJobCount(_model.RunningCount + _model.QueuedCount, _model.QueuedCount);
|
||||
Badge = _model.RunningCount;
|
||||
OnPropertyChanged(nameof(WorkersText));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
private void RaiseState()
|
||||
{
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
OnPropertyChanged(nameof(HasRows));
|
||||
}
|
||||
|
||||
private async Task PauseCurrentAsync()
|
||||
{
|
||||
if (_model.Current is { } current && _queue is not null) await _queue.PauseAsync(current.Id);
|
||||
}
|
||||
|
||||
private async Task PauseAllAsync()
|
||||
{
|
||||
if (_queue is null) return;
|
||||
foreach (var entry in _model.Ordered(JobFilter.Running).Where(e => e.State == JobState.Running).ToList()) await _queue.PauseAsync(entry.Id);
|
||||
}
|
||||
|
||||
private void ClearDone()
|
||||
{
|
||||
Shell.Services.Settings.JobsClearedAt = DateTimeOffset.UtcNow;
|
||||
Shell.Services.SaveSettings();
|
||||
SyncRows();
|
||||
}
|
||||
|
||||
/// <summary>Opens what a job worked on inside Titano: its sequence in the editor, or the Archive screen.</summary>
|
||||
internal async Task OpenTargetAsync(Job job)
|
||||
{
|
||||
var db = Shell.Services.Database;
|
||||
if (db is null || job.TargetIds.Count == 0) return;
|
||||
if (await db.Sequences.GetAsync(job.TargetIds[0]) is { } sequence) Shell.OpenSequence(sequence.Id);
|
||||
else Shell.Navigate(SectionKey.Archive);
|
||||
}
|
||||
|
||||
/// <summary>Shows the folder of what a job worked on in Explorer.</summary>
|
||||
internal async Task RevealTargetAsync(Job job)
|
||||
{
|
||||
var db = Shell.Services.Database;
|
||||
if (db is null || job.TargetIds.Count == 0) return;
|
||||
var id = job.TargetIds[0];
|
||||
if (await db.Sequences.GetAsync(id) is { } sequence && await db.Archives.GetAsync(sequence.ArchiveId) is { } owner)
|
||||
ShellActions.Reveal(Path.Combine(owner.RootPath, sequence.Folder.Replace('/', Path.DirectorySeparatorChar)));
|
||||
else if (await db.Archives.GetAsync(id) is { } archive)
|
||||
ShellActions.Reveal(archive.RootPath);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Row actions per job state (Jobs.html) and their commands.</summary>
|
||||
internal sealed class JobActions(JobsViewModel owner)
|
||||
{
|
||||
public string WorkerId => owner.Queue?.WorkerId ?? Environment.MachineName;
|
||||
|
||||
public IReadOnlyList<JobAction> For(JobEntry entry)
|
||||
{
|
||||
var job = entry.Job;
|
||||
return entry.State switch
|
||||
{
|
||||
JobState.Running =>
|
||||
[
|
||||
Make("Jobs.Action.Pause", "Tooltips.Jobs.Pause", q => q.PauseAsync(job.Id)),
|
||||
Make("Jobs.Action.Cancel", "Tooltips.Jobs.Cancel", q => q.CancelAsync(job.Id)),
|
||||
],
|
||||
JobState.Paused =>
|
||||
[
|
||||
Make("Jobs.Action.Resume", "Tooltips.Jobs.Resume", q => q.ResumeAsync(job.Id)),
|
||||
Make("Jobs.Action.Cancel", "Tooltips.Jobs.Cancel", q => q.CancelAsync(job.Id)),
|
||||
],
|
||||
JobState.Queued when job.Priority < JobPriority.User =>
|
||||
[
|
||||
Make("Jobs.Action.MoveUp", "Tooltips.Jobs.MoveUp", q => q.RaisePriorityAsync(job.Id)),
|
||||
Make("Jobs.Action.Remove", "Tooltips.Jobs.Remove", q => q.CancelAsync(job.Id)),
|
||||
],
|
||||
JobState.Queued =>
|
||||
[
|
||||
Make("Jobs.Action.Pause", "Tooltips.Jobs.PauseQueued", q => q.PauseAsync(job.Id)),
|
||||
Make("Jobs.Action.Remove", "Tooltips.Jobs.Remove", q => q.CancelAsync(job.Id)),
|
||||
],
|
||||
JobState.Failed =>
|
||||
[
|
||||
Make("Jobs.Action.Retry", "Tooltips.Jobs.Retry", q => q.ResumeAsync(job.Id)),
|
||||
new JobAction(Loc.L("Jobs.Action.Show"), Loc.L("Tooltips.Jobs.Show"), new AsyncRelayCommand(() => owner.OpenTargetAsync(job))),
|
||||
],
|
||||
JobState.Cancelled =>
|
||||
[
|
||||
Make("Jobs.Action.Retry", "Tooltips.Jobs.Retry", q => q.ResumeAsync(job.Id)),
|
||||
],
|
||||
_ =>
|
||||
[
|
||||
new JobAction(Loc.L("Jobs.Action.Open"), Loc.L("Tooltips.Jobs.Open"), new AsyncRelayCommand(() => owner.OpenTargetAsync(job))),
|
||||
new JobAction(Loc.L("Jobs.Action.Folder"), Loc.L("Tooltips.Jobs.Folder"), new AsyncRelayCommand(() => owner.RevealTargetAsync(job))),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Reads the stored log tail of a row (persisted with each checkpoint).</summary>
|
||||
public async Task LoadLogAsync(JobRowViewModel row)
|
||||
{
|
||||
if (owner.Queue is not { } queue) return;
|
||||
try
|
||||
{
|
||||
if (await queue.GetAsync(row.Id) is { } job) row.SetLog(job.LogTail);
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("jobs", "Job log unavailable", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private JobAction Make(string textKey, string toolTipKey, Func<IJobQueue, Task> run) =>
|
||||
new(Loc.L(textKey), Loc.L(toolTipKey), new AsyncRelayCommand(async () =>
|
||||
{
|
||||
if (owner.Queue is { } queue) await run(queue);
|
||||
}));
|
||||
}
|
||||
@@ -2,14 +2,254 @@
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
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">
|
||||
<Grid Margin="20">
|
||||
<ui:EmptyState Message="{l:Loc Library.Empty}">
|
||||
xmlns:v="clr-namespace:Titano.Ui.Visuals;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
|
||||
xmlns:lib="clr-namespace:Titano.App.Library">
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="ListBoxItem.LibraryCard" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Card}">
|
||||
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
|
||||
</Style>
|
||||
<Style x:Key="ListBoxItem.LibraryRow" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
|
||||
<Setter Property="Height" Value="38" />
|
||||
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
|
||||
</Style>
|
||||
<Style x:Key="Button.Header" TargetType="Button" BasedOn="{StaticResource Button.Subtle}">
|
||||
<Setter Property="Height" Value="28" />
|
||||
<Setter Property="MinWidth" Value="0" />
|
||||
<Setter Property="Padding" Value="0" />
|
||||
<Setter Property="FontSize" Value="11" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextFaint}" />
|
||||
<Setter Property="HorizontalAlignment" Value="Stretch" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Left" />
|
||||
<Setter Property="ui:ControlState.HoverBackground" Value="Transparent" />
|
||||
</Style>
|
||||
<DataTemplate x:Key="Template.Status" DataType="{x:Type v:CardStatus}">
|
||||
<ui:StatusGlyph Kind="{Binding Kind}" Text="{Binding Text}" ToolTip="{Binding ToolTip}" Margin="0,0,8,0" />
|
||||
</DataTemplate>
|
||||
<ItemsPanelTemplate x:Key="Panel.Row">
|
||||
<StackPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="56" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Toolbar (Main.html): search, filters, sort · view switch, rescan. -->
|
||||
<DockPanel Grid.ColumnSpan="2" Margin="20,0" LastChildFill="False">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Icon}" ui:ButtonIcon.Glyph="{StaticResource Icon.Refresh}" Command="{Binding RescanCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Library.Rescan}" AutomationProperties.Name="{l:Loc Library.Rescan}" Margin="10,0,0,0" />
|
||||
<v:SegmentedControl DockPanel.Dock="Right" SelectedIndex="{Binding LayoutIndex, Mode=TwoWay}" AutomationProperties.Name="{l:Loc Library.View}">
|
||||
<v:SegmentedItem Glyph="{StaticResource Icon.ViewGrid}" ToolTip="{l:Loc Tooltips.Library.Grid}" AutomationProperties.Name="{l:Loc Library.View.Grid}" />
|
||||
<v:SegmentedItem Glyph="{StaticResource Icon.ViewList}" ToolTip="{l:Loc Tooltips.Library.List}" AutomationProperties.Name="{l:Loc Library.View.List}" />
|
||||
</v:SegmentedControl>
|
||||
<TextBox Width="260" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
|
||||
ui:Field.Placeholder="{l:Loc Library.Search}" ToolTip="{l:Loc Tooltips.Library.Search}" AutomationProperties.Name="{l:Loc Library.Search}" />
|
||||
<ComboBox Style="{StaticResource ComboBox.Filter}" Margin="10,0,0,0" ItemsSource="{Binding Years}" SelectedItem="{Binding SelectedYear}" Tag="{Binding IsYearFiltered}"
|
||||
ItemTemplate="{StaticResource Template.FilterOption}" ToolTip="{l:Loc Tooltips.Library.Year}" AutomationProperties.Name="{l:Loc Library.Filter.Year}" />
|
||||
<ComboBox Style="{StaticResource ComboBox.Filter}" Margin="10,0,0,0" ItemsSource="{Binding Cameras}" SelectedItem="{Binding SelectedCamera}" Tag="{Binding IsCameraFiltered}"
|
||||
ItemTemplate="{StaticResource Template.FilterOption}" ToolTip="{l:Loc Tooltips.Library.Camera}" AutomationProperties.Name="{l:Loc Library.Filter.Camera}" />
|
||||
<ComboBox Style="{StaticResource ComboBox.Filter}" Margin="10,0,0,0" ItemsSource="{Binding Statuses}" SelectedItem="{Binding SelectedStatus}" Tag="{Binding IsStatusFiltered}"
|
||||
ItemTemplate="{StaticResource Template.FilterOption}" ToolTip="{l:Loc Tooltips.Library.Status}" AutomationProperties.Name="{l:Loc Library.Filter.Status}" />
|
||||
<ComboBox Style="{StaticResource ComboBox.Filter}" Margin="10,0,0,0" ItemsSource="{Binding Tags}" SelectedItem="{Binding SelectedTag}" Tag="{Binding IsTagFiltered}"
|
||||
ItemTemplate="{StaticResource Template.FilterOption}" ToolTip="{l:Loc Tooltips.Library.Tags}" AutomationProperties.Name="{l:Loc Library.Filter.Tags}" />
|
||||
<ComboBox Style="{StaticResource ComboBox.Filter}" Margin="10,0,0,0" ItemsSource="{Binding Sorts}" SelectedItem="{Binding SelectedSort}"
|
||||
ItemTemplate="{StaticResource Template.FilterOption}" ToolTip="{l:Loc Tooltips.Library.Sort}" AutomationProperties.Name="{l:Loc Library.Sort}" />
|
||||
</DockPanel>
|
||||
|
||||
<!-- Grid view: virtualised, recycling card grid. -->
|
||||
<ListBox x:Name="CardGrid" Grid.Row="1" Style="{StaticResource ListBox.Cards}" ItemsSource="{Binding Items}" ItemContainerStyle="{StaticResource ListBoxItem.LibraryCard}"
|
||||
Visibility="{Binding IsGrid, Converter={StaticResource BoolToVisibility}}" AutomationProperties.Name="{l:Loc Shell.Nav.Library}"
|
||||
ScrollViewer.ScrollChanged="OnScrollChanged">
|
||||
<ListBox.InputBindings>
|
||||
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding OpenCommand}" />
|
||||
<KeyBinding Key="Enter" Command="{Binding OpenCommand}" />
|
||||
</ListBox.InputBindings>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type lib:SequenceItem}">
|
||||
<v:SequenceCard Title="{Binding Title}" Subtitle="{Binding Subtitle}" Statuses="{Binding Statuses}" Thumbnail="{Binding Thumbnail}"
|
||||
ScrubSource="{Binding ScrubSource}" lib:ThumbnailLoading.Width="236"
|
||||
IsSelected="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}, Mode=TwoWay}"
|
||||
SelectToolTip="{l:Loc Tooltips.Library.Select}" ToolTip="{l:Loc Tooltips.Library.Card}">
|
||||
<v:SequenceCard.ActionsContent>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Button Style="{StaticResource Button.Icon}" Width="28" Height="28" MinWidth="28" ui:ButtonIcon.Glyph="{StaticResource Icon.Sequence}"
|
||||
Command="{Binding DataContext.OpenItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
|
||||
ToolTip="{l:Loc Tooltips.Library.Open}" AutomationProperties.Name="{l:Loc Library.Action.Open}" Margin="0,0,6,0" />
|
||||
<Button Style="{StaticResource Button.Icon}" Width="28" Height="28" MinWidth="28" ui:ButtonIcon.Glyph="{StaticResource Icon.Analyse}"
|
||||
Command="{Binding DataContext.AnalyseItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
|
||||
ToolTip="{l:Loc Tooltips.Library.Analyse}" AutomationProperties.Name="{l:Loc Library.Action.Analyse}" />
|
||||
</StackPanel>
|
||||
</v:SequenceCard.ActionsContent>
|
||||
</v:SequenceCard>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<!-- List view: virtualised table with sortable headers. -->
|
||||
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Margin="20,4,20,12" Visibility="{Binding IsList, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,2">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" MinWidth="180" />
|
||||
<ColumnDefinition Width="110" />
|
||||
<ColumnDefinition Width="170" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="150" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button Style="{StaticResource Button.Header}" Content="{l:Loc Library.Column.Sequence}" Command="{Binding SortByCommand}" CommandParameter="Title" ToolTip="{l:Loc Tooltips.Library.SortTitle}" />
|
||||
<Button Grid.Column="1" Style="{StaticResource Button.Header}" Content="{l:Loc Library.Column.Date}" Command="{Binding SortByCommand}" CommandParameter="Date" ToolTip="{l:Loc Tooltips.Library.SortDate}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Library.Column.Camera}" Margin="10,0,0,0" />
|
||||
<Button Grid.Column="3" Style="{StaticResource Button.Header}" Content="{l:Loc Library.Column.Frames}" HorizontalContentAlignment="Right" Command="{Binding SortByCommand}" CommandParameter="FrameCount" ToolTip="{l:Loc Tooltips.Library.SortFrames}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Library.Column.Span}" TextAlignment="Right" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.Header}" Text="{l:Loc Library.Column.Interval}" TextAlignment="Right" Margin="10,0,0,0" />
|
||||
<Button Grid.Column="6" Style="{StaticResource Button.Header}" Content="{l:Loc Library.Column.Size}" HorizontalContentAlignment="Right" Command="{Binding SortByCommand}" CommandParameter="Size" ToolTip="{l:Loc Tooltips.Library.SortSize}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="7" Style="{StaticResource Text.Header}" Text="{l:Loc Library.Column.State}" Margin="16,0,0,0" />
|
||||
</Grid>
|
||||
</Border>
|
||||
<ListBox x:Name="RowList" Grid.Row="1" ItemsSource="{Binding Items}" ItemContainerStyle="{StaticResource ListBoxItem.LibraryRow}" SelectionMode="Extended"
|
||||
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.ScrollChanged="OnScrollChanged" AutomationProperties.Name="{l:Loc Shell.Nav.Library}">
|
||||
<ListBox.InputBindings>
|
||||
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding OpenCommand}" />
|
||||
<KeyBinding Key="Enter" Command="{Binding OpenCommand}" />
|
||||
</ListBox.InputBindings>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type lib:SequenceItem}">
|
||||
<Grid ToolTip="{l:Loc Tooltips.Library.Row}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" MinWidth="180" />
|
||||
<ColumnDefinition Width="110" />
|
||||
<ColumnDefinition Width="170" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="150" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Title}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding DateText}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding Camera}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.CellNumber}" Text="{Binding FramesText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.CellNumber}" Text="{Binding SpanText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.CellNumber}" Text="{Binding IntervalText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.CellNumber}" Text="{Binding SizeText}" Margin="10,0,0,0" />
|
||||
<ItemsControl Grid.Column="7" Margin="16,0,0,0" ItemsSource="{Binding Statuses}" ItemTemplate="{StaticResource Template.Status}"
|
||||
ItemsPanel="{StaticResource Panel.Row}" VerticalAlignment="Center" Focusable="False" ClipToBounds="True" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Empty states: one sentence plus the first actions (Components.html). -->
|
||||
<ui:EmptyState Grid.Row="1" Message="{l:Loc Library.Empty}" Visibility="{Binding IsLibraryEmpty, Converter={StaticResource BoolToVisibility}}">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Library.Empty.ImportCard}" Command="{Binding ImportCardCommand}" ToolTip="{l:Loc Tooltips.Library.ImportCard}" Margin="0,0,8,0" />
|
||||
<Button Content="{l:Loc Library.Empty.OpenArchive}" Command="{Binding OpenArchiveCommand}" ToolTip="{l:Loc Tooltips.Library.OpenArchive}" Margin="0,0,8,0" />
|
||||
<Button Content="{l:Loc Library.Empty.Adopt}" Command="{Binding AdoptFolderCommand}" ToolTip="{l:Loc Tooltips.Library.Adopt}" Margin="0,0,8,0" />
|
||||
<Button Content="{l:Loc Library.Empty.Connect}" Command="{Binding ConnectCommand}" ToolTip="{l:Loc Tooltips.Library.Connect}" />
|
||||
</StackPanel>
|
||||
</ui:EmptyState>
|
||||
<ui:EmptyState Grid.Row="1" Message="{l:Loc Library.NoMatch}" Visibility="{Binding IsNoMatch, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button Content="{l:Loc Library.ClearFilters}" Command="{Binding ClearFiltersCommand}" ToolTip="{l:Loc Tooltips.Library.ClearFilters}" />
|
||||
</ui:EmptyState>
|
||||
|
||||
<!-- Selection panel (320 px, DESIGN §3). -->
|
||||
<Border Grid.Row="1" Grid.Column="1" Width="320" Margin="0,4,20,12" Style="{StaticResource Border.Panel}" Padding="16"
|
||||
Visibility="{Binding HasSelection, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid>
|
||||
<!-- One sequence -->
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" Focusable="False" DataContext="{Binding Selected}"
|
||||
Visibility="{Binding DataContext.IsSingleSelection, RelativeSource={RelativeSource AncestorType=UserControl}, Converter={StaticResource BoolToVisibility}}">
|
||||
<StackPanel>
|
||||
<v:AspectRatioDecorator>
|
||||
<Border CornerRadius="6" Background="{DynamicResource Brush.Preview}">
|
||||
<Border CornerRadius="6">
|
||||
<Border.Background>
|
||||
<ImageBrush ImageSource="{Binding Thumbnail}" Stretch="UniformToFill" />
|
||||
</Border.Background>
|
||||
</Border>
|
||||
</Border>
|
||||
</v:AspectRatioDecorator>
|
||||
<TextBlock Text="{Binding Title}" Style="{StaticResource Text.Title}" Margin="0,12,0,0" TextWrapping="Wrap" TextTrimming="None" />
|
||||
<ItemsControl ItemsSource="{Binding Statuses}" ItemTemplate="{StaticResource Template.Status}" ItemsPanel="{StaticResource Panel.Row}" Margin="0,6,0,0" Focusable="False" />
|
||||
<Grid Margin="0,14,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="{StaticResource Grid.LabelColumn}" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="24" />
|
||||
<RowDefinition Height="24" />
|
||||
<RowDefinition Height="24" />
|
||||
<RowDefinition Height="24" />
|
||||
<RowDefinition Height="24" />
|
||||
<RowDefinition Height="24" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Date}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding DateText}" />
|
||||
<TextBlock Grid.Row="1" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Frames}" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding FramesText}" />
|
||||
<TextBlock Grid.Row="2" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Span}" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding SpanText}" />
|
||||
<TextBlock Grid.Row="3" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Interval}" />
|
||||
<TextBlock Grid.Row="3" Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding IntervalText}" />
|
||||
<TextBlock Grid.Row="4" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Camera}" />
|
||||
<TextBlock Grid.Row="4" Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Camera}" />
|
||||
<TextBlock Grid.Row="5" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Size}" />
|
||||
<TextBlock Grid.Row="5" Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding SizeText}" />
|
||||
<TextBlock Grid.Row="6" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Folder}" VerticalAlignment="Top" Margin="0,4,14,0" />
|
||||
<TextBlock Grid.Row="6" Grid.Column="1" Text="{Binding Sequence.Folder}" TextWrapping="Wrap" Margin="0,4,0,0" />
|
||||
<TextBlock Grid.Row="7" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Tags}" VerticalAlignment="Top" Margin="0,8,14,0" />
|
||||
<TextBlock Grid.Row="7" Grid.Column="1" Text="{Binding TagsText}" TextWrapping="Wrap" Margin="0,8,0,0" />
|
||||
</Grid>
|
||||
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Library.Action.Open}" HorizontalAlignment="Stretch" Margin="0,18,0,0"
|
||||
Command="{Binding DataContext.OpenCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" ToolTip="{l:Loc Tooltips.Library.Open}" />
|
||||
<WrapPanel Margin="0,8,0,0">
|
||||
<Button Content="{l:Loc Library.Action.Analyse}" Command="{Binding DataContext.AnalyseCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
|
||||
ToolTip="{l:Loc Tooltips.Library.Analyse}" ui:ButtonIcon.Glyph="{StaticResource Icon.Analyse}" Margin="0,0,8,8" />
|
||||
<Button Content="{l:Loc Library.Action.Proxies}" Command="{Binding DataContext.ProxiesCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
|
||||
ToolTip="{l:Loc Tooltips.Library.Proxies}" ui:ButtonIcon.Glyph="{StaticResource Icon.Layers}" Margin="0,0,8,8" />
|
||||
<Button Content="{l:Loc Library.Action.Verify}" Command="{Binding DataContext.VerifyCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
|
||||
ToolTip="{l:Loc Tooltips.Library.Verify}" ui:ButtonIcon.Glyph="{StaticResource Icon.Verify}" Margin="0,0,8,8" />
|
||||
<Button Content="{l:Loc Library.Action.Folder}" Command="{Binding DataContext.RevealCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
|
||||
ToolTip="{l:Loc Tooltips.Library.Folder}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" Margin="0,0,8,8" />
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
|
||||
<!-- Several sequences: mass actions. -->
|
||||
<StackPanel Visibility="{Binding IsMultiSelection, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{Binding SelectionTitle}" Style="{StaticResource Text.Title}" />
|
||||
<TextBlock Text="{Binding SelectionSummary}" Style="{StaticResource Text.Secondary}" Margin="0,4,0,0" />
|
||||
<WrapPanel Margin="0,16,0,0">
|
||||
<Button Content="{l:Loc Library.Action.Analyse}" Command="{Binding AnalyseCommand}" ToolTip="{l:Loc Tooltips.Library.AnalyseAll}" ui:ButtonIcon.Glyph="{StaticResource Icon.Analyse}" Margin="0,0,8,8" />
|
||||
<Button Content="{l:Loc Library.Action.Proxies}" Command="{Binding ProxiesCommand}" ToolTip="{l:Loc Tooltips.Library.ProxiesAll}" ui:ButtonIcon.Glyph="{StaticResource Icon.Layers}" Margin="0,0,8,8" />
|
||||
<Button Content="{l:Loc Library.Action.Verify}" Command="{Binding VerifyCommand}" ToolTip="{l:Loc Tooltips.Library.VerifyAll}" ui:ButtonIcon.Glyph="{StaticResource Icon.Verify}" Margin="0,0,8,8" />
|
||||
<Button Content="{l:Loc Library.Action.ExportList}" Command="{Binding ExportListCommand}" ToolTip="{l:Loc Tooltips.Library.ExportList}" ui:ButtonIcon.Glyph="{StaticResource Icon.Export}" Margin="0,0,8,8" />
|
||||
</WrapPanel>
|
||||
<Button Style="{StaticResource Button.Subtle}" Content="{l:Loc Library.Action.ClearSelection}" Command="{Binding ClearSelectionCommand}" ToolTip="{l:Loc Tooltips.Library.ClearSelection}" HorizontalAlignment="Left" Margin="0,8,0,0" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -5,4 +5,11 @@ namespace Titano.App.Sections;
|
||||
public partial class LibraryView : UserControl
|
||||
{
|
||||
public LibraryView() => InitializeComponent();
|
||||
|
||||
/// <summary>Loads the next page when the grid or the list scrolls within two screens of its end.</summary>
|
||||
private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
|
||||
{
|
||||
if (DataContext is not LibraryViewModel vm || e.ExtentHeight <= 0) return;
|
||||
if (e.VerticalOffset + e.ViewportHeight >= e.ExtentHeight - 2 * Math.Max(e.ViewportHeight, 200)) _ = vm.LoadMoreAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,630 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Jobs;
|
||||
using Titano.App.Library;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>
|
||||
/// Library (home, BRIEF §12.2): sequences of the index in a virtualised card grid or table, filtered by search,
|
||||
/// year, camera, status and tag, loaded page by page (keyset paging) as the view scrolls, with a selection panel.
|
||||
/// </summary>
|
||||
public sealed class LibraryViewModel : SectionViewModel
|
||||
{
|
||||
private const int AnalysingPollMs = 250;
|
||||
|
||||
private readonly DispatcherTimer _searchDelay;
|
||||
private readonly HashSet<Guid> _analysing = [];
|
||||
private LibraryPager? _pager;
|
||||
private TitanoDatabase? _db;
|
||||
private string _searchText = string.Empty;
|
||||
private FilterOption<int?> _year;
|
||||
private FilterOption<string?> _camera;
|
||||
private FilterOption<StatusFilter> _status;
|
||||
private FilterOption<string?> _tag;
|
||||
private FilterOption<SequenceSort> _sort;
|
||||
private IReadOnlyList<FilterOption<int?>> _years;
|
||||
private IReadOnlyList<FilterOption<string?>> _cameras;
|
||||
private IReadOnlyList<FilterOption<string?>> _tags;
|
||||
private IReadOnlyList<FilterOption<StatusFilter>> _statuses;
|
||||
private IReadOnlyList<FilterOption<SequenceSort>> _sorts;
|
||||
private bool _isLoading;
|
||||
private bool _hasLoaded;
|
||||
private bool _suppressReload;
|
||||
private int _layoutIndex;
|
||||
private SequenceItem? _selected;
|
||||
private int _selectionCount;
|
||||
private bool _hasArchive;
|
||||
|
||||
public LibraryViewModel(ShellViewModel shell)
|
||||
: base(SectionKey.Library, "Icon.Library")
|
||||
{
|
||||
Shell = shell;
|
||||
_years = [AnyYear()];
|
||||
_cameras = [AnyCamera()];
|
||||
_tags = [AnyTag()];
|
||||
_year = _years[0];
|
||||
_camera = _cameras[0];
|
||||
_tag = _tags[0];
|
||||
_statuses = BuildStatusOptions();
|
||||
_status = _statuses[0];
|
||||
_sorts = BuildSortOptions();
|
||||
_sort = _sorts.FirstOrDefault(s => s.Value == shell.Services.Settings.LibrarySort) ?? _sorts[0];
|
||||
Loc.CultureChanged += OnCultureChanged;
|
||||
_layoutIndex = shell.Services.Settings.LibraryLayout == LibraryLayout.List ? 1 : 0;
|
||||
_searchDelay = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
|
||||
_searchDelay.Tick += (_, _) =>
|
||||
{
|
||||
_searchDelay.Stop();
|
||||
Reload();
|
||||
};
|
||||
|
||||
LoadMoreCommand = new RelayCommand(() => _ = LoadMoreAsync());
|
||||
ClearFiltersCommand = new RelayCommand(ClearFilters);
|
||||
RescanCommand = new AsyncRelayCommand(RescanAsync, () => _db is not null && _hasArchive);
|
||||
OpenCommand = new RelayCommand(() =>
|
||||
{
|
||||
if (Selected is { } s) Shell.OpenSequence(s.Id);
|
||||
}, () => Selected is not null);
|
||||
RenderCommand = OpenCommand;
|
||||
AnalyseCommand = new AsyncRelayCommand(() => EnqueueAsync(JobKind.DeepAnalyse), () => SelectionCount > 0 && _db is not null);
|
||||
ProxiesCommand = new AsyncRelayCommand(() => EnqueueAsync(JobKind.Proxies), () => SelectionCount > 0 && _db is not null);
|
||||
VerifyCommand = new AsyncRelayCommand(() => EnqueueAsync(JobKind.Verify), () => SelectionCount > 0 && _db is not null);
|
||||
RevealCommand = new AsyncRelayCommand(RevealAsync, () => Selected is not null && _db is not null);
|
||||
ExportListCommand = new AsyncRelayCommand(ExportListAsync, () => SelectionCount > 0);
|
||||
ClearSelectionCommand = new RelayCommand(ClearSelection, () => SelectionCount > 0);
|
||||
SortByCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is "Date") SelectedSort = Sorts.First(o => o.Value == (_sort.Value == SequenceSort.Newest ? SequenceSort.Oldest : SequenceSort.Newest));
|
||||
else if (p is SequenceSort sort) SelectedSort = Sorts.First(o => o.Value == sort);
|
||||
else if (p is string name && Enum.TryParse<SequenceSort>(name, out var parsed)) SelectedSort = Sorts.First(o => o.Value == parsed);
|
||||
});
|
||||
OpenItemCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is SequenceItem item) Shell.OpenSequence(item.Id);
|
||||
});
|
||||
AnalyseItemCommand = new AsyncRelayCommand(async (p, _) =>
|
||||
{
|
||||
if (p is SequenceItem item && Shell.Services.Jobs is { } jobs)
|
||||
{
|
||||
await jobs.EnqueueAsync(JobKind.DeepAnalyse, [item.Id], item.Title);
|
||||
Shell.Notify(Loc.L("Library.Queued", JobText.Kind(JobKind.DeepAnalyse), item.Title), actionText: Loc.L("Shell.Nav.Jobs"),
|
||||
actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
|
||||
}
|
||||
});
|
||||
ImportCardCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import));
|
||||
AdoptFolderCommand = new AsyncRelayCommand(AdoptFolderAsync);
|
||||
ConnectCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Server));
|
||||
}
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
public ObservableCollection<SequenceItem> Items { get; } = [];
|
||||
|
||||
public ICommand LoadMoreCommand { get; }
|
||||
public ICommand ClearFiltersCommand { get; }
|
||||
public ICommand RescanCommand { get; }
|
||||
public ICommand OpenCommand { get; }
|
||||
public ICommand RenderCommand { get; }
|
||||
public ICommand AnalyseCommand { get; }
|
||||
public ICommand ProxiesCommand { get; }
|
||||
public ICommand VerifyCommand { get; }
|
||||
public ICommand RevealCommand { get; }
|
||||
public ICommand ExportListCommand { get; }
|
||||
public ICommand ClearSelectionCommand { get; }
|
||||
public ICommand SortByCommand { get; }
|
||||
public ICommand OpenItemCommand { get; }
|
||||
public ICommand AnalyseItemCommand { get; }
|
||||
public ICommand ImportCardCommand { get; }
|
||||
public ICommand AdoptFolderCommand { get; }
|
||||
public ICommand ConnectCommand { get; }
|
||||
|
||||
// ---------------- Layout ----------------
|
||||
|
||||
/// <summary>0 = grid, 1 = list (the SegmentedControl's index).</summary>
|
||||
public int LayoutIndex
|
||||
{
|
||||
get => _layoutIndex;
|
||||
set
|
||||
{
|
||||
if (value is < 0 or > 1 || !Set(ref _layoutIndex, value)) return;
|
||||
Shell.Services.Settings.LibraryLayout = value == 1 ? LibraryLayout.List : LibraryLayout.Grid;
|
||||
OnPropertyChanged(nameof(IsGrid));
|
||||
OnPropertyChanged(nameof(IsList));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsGrid => _layoutIndex == 0 && HasItems;
|
||||
public bool IsList => _layoutIndex == 1 && HasItems;
|
||||
|
||||
// ---------------- Filters ----------------
|
||||
|
||||
public string SearchText
|
||||
{
|
||||
get => _searchText;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _searchText, value ?? string.Empty)) return;
|
||||
_searchDelay.Stop();
|
||||
_searchDelay.Start();
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<FilterOption<int?>> Years { get => _years; private set => Set(ref _years, value); }
|
||||
public IReadOnlyList<FilterOption<string?>> Cameras { get => _cameras; private set => Set(ref _cameras, value); }
|
||||
public IReadOnlyList<FilterOption<StatusFilter>> Statuses { get => _statuses; private set => Set(ref _statuses, value); }
|
||||
public IReadOnlyList<FilterOption<string?>> Tags { get => _tags; private set => Set(ref _tags, value); }
|
||||
public IReadOnlyList<FilterOption<SequenceSort>> Sorts { get => _sorts; private set => Set(ref _sorts, value); }
|
||||
|
||||
public FilterOption<int?> SelectedYear
|
||||
{
|
||||
get => _year;
|
||||
set => SetFilter(ref _year, value ?? Years[0], nameof(IsYearFiltered));
|
||||
}
|
||||
|
||||
public FilterOption<string?> SelectedCamera
|
||||
{
|
||||
get => _camera;
|
||||
set => SetFilter(ref _camera, value ?? Cameras[0], nameof(IsCameraFiltered));
|
||||
}
|
||||
|
||||
public FilterOption<StatusFilter> SelectedStatus
|
||||
{
|
||||
get => _status;
|
||||
set => SetFilter(ref _status, value ?? Statuses[0], nameof(IsStatusFiltered));
|
||||
}
|
||||
|
||||
public FilterOption<string?> SelectedTag
|
||||
{
|
||||
get => _tag;
|
||||
set => SetFilter(ref _tag, value ?? Tags[0], nameof(IsTagFiltered));
|
||||
}
|
||||
|
||||
public FilterOption<SequenceSort> SelectedSort
|
||||
{
|
||||
get => _sort;
|
||||
set
|
||||
{
|
||||
if (value is null || !Set(ref _sort, value)) return;
|
||||
Shell.Services.Settings.LibrarySort = value.Value;
|
||||
OnPropertyChanged(nameof(SortColumn));
|
||||
Reload();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsYearFiltered => !_year.IsAny;
|
||||
public bool IsCameraFiltered => !_camera.IsAny;
|
||||
public bool IsStatusFiltered => !_status.IsAny;
|
||||
public bool IsTagFiltered => !_tag.IsAny;
|
||||
|
||||
/// <summary>The sort as a column name for the list header ("Newest", "Title", …).</summary>
|
||||
public string SortColumn => _sort.Value.ToString();
|
||||
|
||||
/// <summary>The filter the toolbar describes.</summary>
|
||||
public LibraryFilter Filter => new()
|
||||
{
|
||||
Text = _searchText,
|
||||
Year = _year.Value,
|
||||
Camera = _camera.Value,
|
||||
Status = _status.Value,
|
||||
Tag = _tag.Value,
|
||||
Sort = _sort.Value,
|
||||
};
|
||||
|
||||
// ---------------- State ----------------
|
||||
|
||||
public bool IsLoading
|
||||
{
|
||||
get => _isLoading;
|
||||
private set => Set(ref _isLoading, value);
|
||||
}
|
||||
|
||||
public bool HasItems => Items.Count > 0;
|
||||
|
||||
/// <summary>Loaded, nothing indexed and no filter: the first-run empty state (one sentence, three choices).</summary>
|
||||
public bool IsLibraryEmpty => _hasLoaded && !HasItems && !_isLoading && Filter.IsUnfiltered;
|
||||
|
||||
/// <summary>Loaded, but the filters match nothing.</summary>
|
||||
public bool IsNoMatch => _hasLoaded && !HasItems && !_isLoading && !Filter.IsUnfiltered;
|
||||
|
||||
// ---------------- Selection ----------------
|
||||
|
||||
/// <summary>The selected sequence when exactly one is selected.</summary>
|
||||
public SequenceItem? Selected
|
||||
{
|
||||
get => _selected;
|
||||
private set => Set(ref _selected, value);
|
||||
}
|
||||
|
||||
public int SelectionCount
|
||||
{
|
||||
get => _selectionCount;
|
||||
private set
|
||||
{
|
||||
if (!Set(ref _selectionCount, value)) return;
|
||||
OnPropertyChanged(nameof(HasSelection));
|
||||
OnPropertyChanged(nameof(IsSingleSelection));
|
||||
OnPropertyChanged(nameof(IsMultiSelection));
|
||||
OnPropertyChanged(nameof(SelectionTitle));
|
||||
OnPropertyChanged(nameof(SelectionSummary));
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasSelection => _selectionCount > 0;
|
||||
public bool IsSingleSelection => _selectionCount == 1;
|
||||
public bool IsMultiSelection => _selectionCount > 1;
|
||||
|
||||
/// <summary>"3 selected".</summary>
|
||||
public string SelectionTitle => Loc.Plural("Library.Selection.Count", _selectionCount);
|
||||
|
||||
/// <summary>"10,240 photos · 182 GB" of the selection.</summary>
|
||||
public string SelectionSummary
|
||||
{
|
||||
get
|
||||
{
|
||||
var chosen = SelectedItems().ToList();
|
||||
return Loc.Plural("Shell.Status.Photos", chosen.Sum(i => (long)i.Sequence.FrameCount)) + " · " + Formatting.Bytes(chosen.Sum(i => i.Sequence.TotalBytes));
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<SequenceItem> SelectedItems() => Items.Where(i => i.IsSelected);
|
||||
|
||||
// ---------------- Lifecycle ----------------
|
||||
|
||||
/// <summary>Binds to the index and loads filters, totals and the first page.</summary>
|
||||
public async Task AttachAsync()
|
||||
{
|
||||
_db = Shell.Services.Database;
|
||||
if (_db is null)
|
||||
{
|
||||
_hasLoaded = true;
|
||||
RaiseState();
|
||||
return;
|
||||
}
|
||||
_pager = new LibraryPager((q, ct) => _db.Sequences.ListAsync(q, ct));
|
||||
if (Shell.Services.Jobs is { } jobs)
|
||||
{
|
||||
jobs.JobChanged += OnJobChanged;
|
||||
}
|
||||
await RefreshFiltersAsync();
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
/// <summary>Re-reads filter choices and totals, then the list (after imports, archive changes).</summary>
|
||||
public async Task RefreshAsync()
|
||||
{
|
||||
await RefreshFiltersAsync();
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
Loc.CultureChanged -= OnCultureChanged;
|
||||
_searchDelay.Stop();
|
||||
_pager?.Cancel();
|
||||
if (Shell.Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>The view calls this when the list scrolls near its end.</summary>
|
||||
public Task LoadMoreAsync() => ApplyAsync(_pager?.LoadMoreAsync());
|
||||
|
||||
/// <summary>The view calls this when container selection changed.</summary>
|
||||
public void OnSelectionChanged()
|
||||
{
|
||||
var count = 0;
|
||||
SequenceItem? single = null;
|
||||
foreach (var item in Items)
|
||||
{
|
||||
if (!item.IsSelected) continue;
|
||||
count++;
|
||||
single = count == 1 ? item : null;
|
||||
}
|
||||
Selected = count == 1 ? single : null;
|
||||
SelectionCount = count;
|
||||
OnPropertyChanged(nameof(SelectionSummary));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
private void Reload()
|
||||
{
|
||||
if (_suppressReload) return;
|
||||
_ = ReloadAsync();
|
||||
}
|
||||
|
||||
private async Task ReloadAsync()
|
||||
{
|
||||
if (_pager is null) return;
|
||||
await ApplyAsync(_pager.ResetAsync(Filter));
|
||||
}
|
||||
|
||||
private async Task ApplyAsync(Task<LibraryPage?>? pending)
|
||||
{
|
||||
if (pending is null) return;
|
||||
IsLoading = true;
|
||||
RaiseState();
|
||||
try
|
||||
{
|
||||
var page = await pending;
|
||||
if (page is null) return;
|
||||
if (page.IsFirst)
|
||||
{
|
||||
foreach (var old in Items) old.PropertyChanged -= OnItemChanged;
|
||||
Items.Clear();
|
||||
Selected = null;
|
||||
SelectionCount = 0;
|
||||
}
|
||||
foreach (var sequence in page.Items)
|
||||
{
|
||||
var item = new SequenceItem(sequence, Shell.Services.Thumbnails) { IsAnalysing = _analysing.Contains(sequence.Id) };
|
||||
item.PropertyChanged += OnItemChanged;
|
||||
Items.Add(item);
|
||||
}
|
||||
_hasLoaded = true;
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or InvalidOperationException)
|
||||
{
|
||||
Shell.ReportError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsLoading = _pager?.IsLoading ?? false;
|
||||
RaiseState();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RefreshFiltersAsync()
|
||||
{
|
||||
if (_db is null) return;
|
||||
try
|
||||
{
|
||||
var stats = await _db.Sequences.GetStatsAsync(null);
|
||||
var tags = await _db.Tags.ListAsync();
|
||||
_hasArchive = (await _db.Archives.ListAsync()).Count > 0;
|
||||
Shell.SetLibraryTotals(stats.Sequences, stats.Photos, stats.Bytes);
|
||||
|
||||
_suppressReload = true;
|
||||
var year = _year.Value;
|
||||
var camera = _camera.Value;
|
||||
var tag = _tag.Value;
|
||||
Years = [AnyYear(), .. stats.ByYear.OrderByDescending(y => y.Year).Select(y => new FilterOption<int?>(y.Year, YearText(y.Year), YearText(y.Year)))];
|
||||
Cameras =
|
||||
[
|
||||
AnyCamera(),
|
||||
.. stats.ByCamera.Where(c => !string.IsNullOrWhiteSpace(c.Model))
|
||||
.GroupBy(c => c.Model!, StringComparer.Ordinal)
|
||||
.Select(g => (Model: g.Key, Name: Core.Naming.PathTemplate.CameraName(g.First().Make, g.Key)))
|
||||
.OrderBy(c => c.Name, StringComparer.CurrentCultureIgnoreCase)
|
||||
.Select(c => new FilterOption<string?>(c.Model, c.Name, c.Name)),
|
||||
];
|
||||
Tags = [AnyTag(), .. tags.OrderBy(t => t.Name, StringComparer.CurrentCultureIgnoreCase).Select(t => new FilterOption<string?>(t.Name, t.Name, t.Name))];
|
||||
SelectedYear = Years.FirstOrDefault(o => o.Value == year) ?? Years[0];
|
||||
SelectedCamera = Cameras.FirstOrDefault(o => o.Value == camera) ?? Cameras[0];
|
||||
SelectedTag = Tags.FirstOrDefault(o => o.Value == tag) ?? Tags[0];
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("library", "Library statistics unavailable", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_suppressReload = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetFilter<T>(ref FilterOption<T> field, FilterOption<T> value, string flagName, [System.Runtime.CompilerServices.CallerMemberName] string? propertyName = null)
|
||||
{
|
||||
if (!Set(ref field, value, propertyName)) return;
|
||||
OnPropertyChanged(flagName);
|
||||
Reload();
|
||||
}
|
||||
|
||||
private void ClearFilters()
|
||||
{
|
||||
_suppressReload = true;
|
||||
_searchDelay.Stop();
|
||||
SearchText = string.Empty;
|
||||
_searchDelay.Stop();
|
||||
SelectedYear = Years[0];
|
||||
SelectedCamera = Cameras[0];
|
||||
SelectedStatus = Statuses[0];
|
||||
SelectedTag = Tags[0];
|
||||
_suppressReload = false;
|
||||
Reload();
|
||||
}
|
||||
|
||||
private void ClearSelection()
|
||||
{
|
||||
foreach (var item in Items) item.IsSelected = false;
|
||||
OnSelectionChanged();
|
||||
}
|
||||
|
||||
private void OnItemChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName == nameof(SequenceItem.IsSelected)) OnSelectionChanged();
|
||||
}
|
||||
|
||||
private void RaiseState()
|
||||
{
|
||||
OnPropertyChanged(nameof(HasItems));
|
||||
OnPropertyChanged(nameof(IsGrid));
|
||||
OnPropertyChanged(nameof(IsList));
|
||||
OnPropertyChanged(nameof(IsLibraryEmpty));
|
||||
OnPropertyChanged(nameof(IsNoMatch));
|
||||
}
|
||||
|
||||
private void OnJobChanged(Job job)
|
||||
{
|
||||
// Engine events arrive on worker threads.
|
||||
System.Windows.Application.Current?.Dispatcher.BeginInvoke(() => ApplyJob(job));
|
||||
}
|
||||
|
||||
private void ApplyJob(Job job)
|
||||
{
|
||||
if (job.Kind is JobKind.LightAnalyse or JobKind.DeepAnalyse)
|
||||
{
|
||||
foreach (var id in job.TargetIds)
|
||||
{
|
||||
if (job.State == JobState.Running) _analysing.Add(id);
|
||||
else _analysing.Remove(id);
|
||||
}
|
||||
foreach (var item in Items.Where(i => job.TargetIds.Contains(i.Id))) item.IsAnalysing = _analysing.Contains(item.Id);
|
||||
}
|
||||
if (job.State == JobState.Done) _ = RefreshTargetsAsync(job);
|
||||
}
|
||||
|
||||
/// <summary>A finished job changed some sequences: refresh those rows in place and the totals.</summary>
|
||||
private async Task RefreshTargetsAsync(Job job)
|
||||
{
|
||||
if (_db is null) return;
|
||||
try
|
||||
{
|
||||
foreach (var item in Items.Where(i => job.TargetIds.Contains(i.Id)).ToList())
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(item.Id) is { } fresh) item.Update(fresh);
|
||||
}
|
||||
if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit) await RefreshAsync();
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("library", "Refresh after a job failed", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task EnqueueAsync(JobKind kind)
|
||||
{
|
||||
if (Shell.Services.Jobs is not { } jobs) return;
|
||||
var chosen = SelectedItems().ToList();
|
||||
if (chosen.Count == 0) return;
|
||||
var label = chosen.Count == 1 ? chosen[0].Title : Loc.Plural("Library.Selection.Count", chosen.Count);
|
||||
await jobs.EnqueueAsync(kind, [.. chosen.Select(i => i.Id)], label);
|
||||
Shell.Notify(Loc.L("Library.Queued", JobText.Kind(kind), label), actionText: Loc.L("Shell.Nav.Jobs"),
|
||||
actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
|
||||
}
|
||||
|
||||
private async Task RescanAsync()
|
||||
{
|
||||
if (_db is null || Shell.Services.Jobs is not { } jobs) return;
|
||||
var archives = await _db.Archives.ListAsync();
|
||||
foreach (var archive in archives) await jobs.EnqueueAsync(JobKind.Scan, [archive.Id], archive.Name);
|
||||
if (archives.Count > 0)
|
||||
Shell.Notify(Loc.L("Library.Queued", JobText.Kind(JobKind.Scan), archives[0].Name), actionText: Loc.L("Shell.Nav.Jobs"),
|
||||
actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
|
||||
}
|
||||
|
||||
private async Task RevealAsync()
|
||||
{
|
||||
if (_db is null || Selected is not { } item) return;
|
||||
var archive = await _db.Archives.GetAsync(item.Sequence.ArchiveId);
|
||||
if (archive is null) return;
|
||||
ShellActions.Reveal(Path.Combine(archive.RootPath, item.Sequence.Folder.Replace('/', Path.DirectorySeparatorChar)));
|
||||
}
|
||||
|
||||
private async Task AdoptFolderAsync()
|
||||
{
|
||||
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Library.Adopt.Title"));
|
||||
if (folder is null) return;
|
||||
await Shell.Services.ArchiveSetup.AdoptAsync(folder);
|
||||
await RefreshAsync();
|
||||
}
|
||||
|
||||
/// <summary>Writes the selected rows as CSV (UTF-8, invariant numbers) into a chosen folder.</summary>
|
||||
private async Task ExportListAsync()
|
||||
{
|
||||
var chosen = SelectedItems().Select(i => i.Sequence).ToList();
|
||||
if (chosen.Count == 0) return;
|
||||
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Library.Export.Title"));
|
||||
if (folder is null) return;
|
||||
var path = Path.Combine(folder, $"Titano sequences {DateTime.Now:yyyy-MM-dd HHmm}.csv");
|
||||
var csv = Csv(chosen);
|
||||
await Task.Run(() => AtomicFile.WriteAllText(path, csv));
|
||||
Shell.Notify(Loc.L("Library.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
|
||||
}
|
||||
|
||||
/// <summary>RFC 4180 CSV of sequences (header in English: it is a data file).</summary>
|
||||
public static string Csv(IEnumerable<Sequence> sequences)
|
||||
{
|
||||
var inv = CultureInfo.InvariantCulture;
|
||||
var sb = new StringBuilder("title,first_capture,last_capture,camera_make,camera_model,frames,bytes,folder,tags\r\n");
|
||||
foreach (var s in sequences)
|
||||
{
|
||||
sb.Append(Field(s.DisplayTitle)).Append(',')
|
||||
.Append(s.FirstCapture?.ToString("yyyy-MM-dd HH:mm:ss", inv)).Append(',')
|
||||
.Append(s.LastCapture?.ToString("yyyy-MM-dd HH:mm:ss", inv)).Append(',')
|
||||
.Append(Field(s.CameraMake)).Append(',')
|
||||
.Append(Field(s.CameraModel)).Append(',')
|
||||
.Append(s.FrameCount.ToString(inv)).Append(',')
|
||||
.Append(s.TotalBytes.ToString(inv)).Append(',')
|
||||
.Append(Field(s.Folder)).Append(',')
|
||||
.Append(Field(string.Join(';', s.Tags))).Append("\r\n");
|
||||
}
|
||||
return sb.ToString();
|
||||
|
||||
static string Field(string? value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value)) return string.Empty;
|
||||
// Formula-looking values are prefixed so spreadsheets do not execute them.
|
||||
if (value[0] is '=' or '+' or '-' or '@') value = "'" + value;
|
||||
return value.IndexOfAny([',', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Option labels and row texts follow a language switch without reloading.</summary>
|
||||
private void OnCultureChanged(object? sender, EventArgs e)
|
||||
{
|
||||
_suppressReload = true;
|
||||
try
|
||||
{
|
||||
var status = _status.Value;
|
||||
var sort = _sort.Value;
|
||||
Statuses = BuildStatusOptions();
|
||||
Sorts = BuildSortOptions();
|
||||
Years = [AnyYear(), .. Years.Skip(1)];
|
||||
Cameras = [AnyCamera(), .. Cameras.Skip(1)];
|
||||
Tags = [AnyTag(), .. Tags.Skip(1)];
|
||||
_status = Statuses.First(o => o.Value == status);
|
||||
_sort = Sorts.First(o => o.Value == sort);
|
||||
_year = _year.IsAny ? Years[0] : _year;
|
||||
_camera = _camera.IsAny ? Cameras[0] : _camera;
|
||||
_tag = _tag.IsAny ? Tags[0] : _tag;
|
||||
foreach (var item in Items) item.Update(item.Sequence);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_suppressReload = false;
|
||||
}
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
private static string YearText(int year) => year.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
private static FilterOption<int?> AnyYear() => new(null, Loc.L("Library.Filter.AnyYear"), Loc.L("Library.Filter.Year"), IsAny: true);
|
||||
|
||||
private static FilterOption<string?> AnyCamera() => new(null, Loc.L("Library.Filter.AnyCamera"), Loc.L("Library.Filter.Camera"), IsAny: true);
|
||||
|
||||
private static FilterOption<string?> AnyTag() => new(null, Loc.L("Library.Filter.AnyTag"), Loc.L("Library.Filter.Tags"), IsAny: true);
|
||||
|
||||
private static IReadOnlyList<FilterOption<StatusFilter>> BuildStatusOptions() =>
|
||||
[
|
||||
new(StatusFilter.Any, Loc.L("Library.Filter.AnyStatus"), Loc.L("Library.Filter.Status"), IsAny: true),
|
||||
.. Enum.GetValues<StatusFilter>().Where(s => s != StatusFilter.Any)
|
||||
.Select(s => new FilterOption<StatusFilter>(s, Loc.L("Library.Filter.Status." + s), Loc.L("Library.Filter.Status." + s))),
|
||||
];
|
||||
|
||||
private static IReadOnlyList<FilterOption<SequenceSort>> BuildSortOptions() =>
|
||||
[.. Enum.GetValues<SequenceSort>().Select(s => new FilterOption<SequenceSort>(s, Loc.L("Library.Sort." + s), Loc.L("Library.Sort." + s)))];
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Ui.Mvvm;
|
||||
using Titano.Ui.Theming;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>Library (home): sequences of the archive (BRIEF §12.2).</summary>
|
||||
public sealed class LibraryViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Library, "Icon.Library")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
public ICommand ImportCardCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Import));
|
||||
public ICommand OpenArchiveCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Archive));
|
||||
public ICommand ConnectCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Server));
|
||||
}
|
||||
|
||||
/// <summary>Card and folder import (BRIEF §12.4).</summary>
|
||||
public sealed class ImportViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Import, "Icon.Import")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
}
|
||||
|
||||
/// <summary>Sequence editor (BRIEF §12.3).</summary>
|
||||
public sealed class SequenceViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Sequence, "Icon.Sequence")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
public ICommand OpenLibraryCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Library));
|
||||
}
|
||||
|
||||
/// <summary>Archive manager (BRIEF §12.5).</summary>
|
||||
public sealed class ArchiveViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Archive, "Icon.Archive")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
}
|
||||
|
||||
/// <summary>Job queue and history (BRIEF §12.6).</summary>
|
||||
public sealed class JobsViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Jobs, "Icon.Jobs")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
}
|
||||
|
||||
/// <summary>Server connection and sync (BRIEF §12.7).</summary>
|
||||
public sealed class ServerViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Server, "Icon.Server")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
}
|
||||
|
||||
public sealed record LanguageOption(string Code, string Name);
|
||||
|
||||
/// <summary>Settings (BRIEF §12.8): section list on the left, controls on the right, tooltips only.</summary>
|
||||
public sealed class SettingsViewModel : SectionViewModel
|
||||
{
|
||||
private readonly AppSettings _settings;
|
||||
private string _page = "General";
|
||||
|
||||
public SettingsViewModel(ShellViewModel shell, AppSettings settings)
|
||||
: base(SectionKey.Settings, "Icon.Settings")
|
||||
{
|
||||
Shell = shell;
|
||||
_settings = settings;
|
||||
Languages = Core.Localization.Languages.Shipped
|
||||
.Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))
|
||||
.ToList();
|
||||
SelectPageCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is string page) Page = page;
|
||||
});
|
||||
}
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
public IReadOnlyList<string> Pages { get; } = ["General", "Advanced"];
|
||||
|
||||
public ICommand SelectPageCommand { get; }
|
||||
|
||||
public string Page
|
||||
{
|
||||
get => _page;
|
||||
set => Set(ref _page, value);
|
||||
}
|
||||
|
||||
public IReadOnlyList<LanguageOption> Languages { get; }
|
||||
|
||||
public LanguageOption SelectedLanguage
|
||||
{
|
||||
get => Languages.FirstOrDefault(l => l.Code.Equals(Loc.Culture.Name, StringComparison.OrdinalIgnoreCase)) ?? Languages[0];
|
||||
set
|
||||
{
|
||||
if (value is null) return;
|
||||
_settings.Language = value.Code;
|
||||
App.Current.ApplyLanguage(value.Code);
|
||||
App.Current.SaveSettings();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsDarkTheme
|
||||
{
|
||||
get => _settings.Theme == AppTheme.Dark;
|
||||
set
|
||||
{
|
||||
if (value) ApplyTheme(AppTheme.Dark);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsLightTheme
|
||||
{
|
||||
get => _settings.Theme == AppTheme.Light;
|
||||
set
|
||||
{
|
||||
if (value) ApplyTheme(AppTheme.Light);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsSystemTheme
|
||||
{
|
||||
get => _settings.Theme == AppTheme.System;
|
||||
set
|
||||
{
|
||||
if (value) ApplyTheme(AppTheme.System);
|
||||
}
|
||||
}
|
||||
|
||||
public bool CheckForUpdates
|
||||
{
|
||||
get => _settings.CheckForUpdates;
|
||||
set
|
||||
{
|
||||
_settings.CheckForUpdates = value;
|
||||
App.Current.SaveSettings();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyTheme(AppTheme theme)
|
||||
{
|
||||
_settings.Theme = theme;
|
||||
ThemeManager.Apply(theme);
|
||||
App.Current.SaveSettings();
|
||||
OnPropertyChanged(nameof(IsDarkTheme));
|
||||
OnPropertyChanged(nameof(IsLightTheme));
|
||||
OnPropertyChanged(nameof(IsSystemTheme));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>About (BRIEF §12.9).</summary>
|
||||
public sealed class AboutViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.About, "Icon.About")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
|
||||
public string Version => typeof(App).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
|
||||
|
||||
public string Runtime => System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription;
|
||||
|
||||
public string OperatingSystem => System.Runtime.InteropServices.RuntimeInformation.OSDescription;
|
||||
|
||||
public string DataFolder => App.Current.Environment.DataDirectory;
|
||||
|
||||
public ICommand OpenDataFolderCommand => new RelayCommand(() => ShellActions.OpenFolder(DataFolder));
|
||||
|
||||
public ICommand OpenReleasesCommand => new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Releases));
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>Sequence editor (BRIEF §12.3).</summary>
|
||||
public sealed class SequenceViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Sequence, "Icon.Sequence")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
public ICommand OpenLibraryCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Library));
|
||||
}
|
||||
@@ -2,8 +2,119 @@
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
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">
|
||||
<Grid Margin="20">
|
||||
<ui:EmptyState Message="{l:Loc Server.Empty}" />
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
|
||||
xmlns:srv="clr-namespace:Titano.App.Server">
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="Text.RowLabel" TargetType="TextBlock" BasedOn="{StaticResource Text.Label}">
|
||||
<Setter Property="MinWidth" Value="60" />
|
||||
<Setter Property="Margin" Value="0,0,10,0" />
|
||||
</Style>
|
||||
<Style x:Key="Text.Dot" TargetType="TextBlock">
|
||||
<Setter Property="Text" Value="·" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextFaint}" />
|
||||
<Setter Property="Margin" Value="8,0" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<!-- Server.html: the connection panel; the render-node panel (right) and the sync table (below) join later. -->
|
||||
<Grid Margin="20,16,20,12">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="16,14">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Address, servers found on the LAN, connect / disconnect. -->
|
||||
<TextBlock Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Label.Server}" />
|
||||
<DockPanel Grid.Column="1" LastChildFill="True">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Connect}" Command="{Binding ConnectCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Server.Connect}" Margin="10,0,0,0" MinWidth="96"
|
||||
Visibility="{Binding IsDisconnected, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Server.Disconnect}" Command="{Binding DisconnectCommand}" ToolTip="{l:Loc Tooltips.Server.Disconnect}"
|
||||
Margin="10,0,0,0" MinWidth="96" Visibility="{Binding IsConnected, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button x:Name="KnownButton" DockPanel.Dock="Right" Style="{StaticResource Button.Icon}" Margin="10,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.ChevronDown}"
|
||||
IsEnabled="{Binding HasKnownServers}" Click="OnShowKnown" ToolTip="{l:Loc Tooltips.Server.Found}" AutomationProperties.Name="{l:Loc Server.Found}">
|
||||
<Button.ContextMenu>
|
||||
<ContextMenu ItemsSource="{Binding KnownServers}">
|
||||
<ContextMenu.ItemContainerStyle>
|
||||
<Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
|
||||
<Setter Property="Header" Value="{Binding Address}" />
|
||||
<Setter Property="InputGestureText" Value="{Binding Name}" />
|
||||
<Setter Property="Command" Value="{Binding DataContext.UseServerCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
|
||||
<Setter Property="CommandParameter" Value="{Binding}" />
|
||||
<Setter Property="ToolTip" Value="{l:Loc Tooltips.Server.UseFound}" />
|
||||
</Style>
|
||||
</ContextMenu.ItemContainerStyle>
|
||||
</ContextMenu>
|
||||
</Button.ContextMenu>
|
||||
</Button>
|
||||
<TextBox x:Name="AddressBox" Text="{Binding Address, UpdateSourceTrigger=PropertyChanged}" ui:Field.Placeholder="{l:Loc Server.AddressPlaceholder}"
|
||||
ToolTip="{l:Loc Tooltips.Server.Address}" AutomationProperties.Name="{l:Loc Server.Label.Server}" IsEnabled="{Binding IsDisconnected}">
|
||||
<TextBox.InputBindings>
|
||||
<KeyBinding Key="Enter" Command="{Binding ConnectCommand}" />
|
||||
</TextBox.InputBindings>
|
||||
</TextBox>
|
||||
</DockPanel>
|
||||
|
||||
<!-- Status: state · server · version · latency · trusted certificate. -->
|
||||
<TextBlock Grid.Row="1" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Label.Status}" Margin="0,12,10,0" />
|
||||
<WrapPanel Grid.Row="1" Grid.Column="1" Margin="0,12,0,0" VerticalAlignment="Center">
|
||||
<ui:StatusGlyph Kind="{Binding StatusKind}" Text="{Binding StatusText}" FontSize="13" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Server.Status}" />
|
||||
<StackPanel Orientation="Horizontal" Visibility="{Binding ServerText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
|
||||
<TextBlock Style="{StaticResource Text.Dot}" />
|
||||
<TextBlock Text="{Binding ServerText}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Visibility="{Binding CertificateText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
|
||||
<TextBlock Style="{StaticResource Text.Dot}" />
|
||||
<TextBlock Text="{Binding CertificateText}" VerticalAlignment="Center" ToolTip="{Binding CertificateToolTip}" />
|
||||
<Button Style="{StaticResource Button.Row}" Content="{l:Loc Server.Certificate}" Command="{Binding CertificateCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Server.Certificate}" Height="24" Margin="10,0,0,0" />
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Visibility="{Binding ErrorText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
|
||||
<TextBlock Style="{StaticResource Text.Dot}" />
|
||||
<ui:StatusGlyph Kind="Error" Text="{Binding ErrorText}" FontSize="13" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</WrapPanel>
|
||||
|
||||
<!-- Account: user · role · quota · sign out. -->
|
||||
<TextBlock Grid.Row="2" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Label.Account}" Margin="0,12,10,0"
|
||||
Visibility="{Binding IsConnected, Converter={StaticResource BoolToVisibility}}" />
|
||||
<DockPanel Grid.Row="2" Grid.Column="1" Margin="0,12,0,0" LastChildFill="False" Visibility="{Binding IsConnected, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Server.SignOut}" Command="{Binding SignOutCommand}" ToolTip="{l:Loc Tooltips.Server.SignOut}" />
|
||||
<Border Width="28" Height="28" CornerRadius="14" Background="{DynamicResource Brush.Card}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="1">
|
||||
<TextBlock Text="{Binding Initial}" FontWeight="SemiBold" HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Text="{Binding Username}" Margin="10,0,0,0" VerticalAlignment="Center" />
|
||||
<TextBlock Style="{StaticResource Text.Dot}" />
|
||||
<TextBlock Text="{Binding RoleText}" ToolTip="{Binding RoleToolTip}" VerticalAlignment="Center" />
|
||||
<StackPanel Orientation="Horizontal" Visibility="{Binding HasQuota, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Style="{StaticResource Text.Dot}" />
|
||||
<ProgressBar Width="160" Maximum="1" Value="{Binding QuotaFraction, Mode=OneWay}" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Server.Quota}" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding QuotaText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Server.Quota}" />
|
||||
</DockPanel>
|
||||
|
||||
<!-- Options of this PC. -->
|
||||
<Border Grid.Row="3" Grid.ColumnSpan="2" Margin="0,14,0,0" Padding="0,10,0,0" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0">
|
||||
<WrapPanel>
|
||||
<CheckBox Content="{l:Loc Server.RenderNode}" IsChecked="{Binding RenderNodeOptIn}" ToolTip="{l:Loc Tooltips.Server.RenderNode}" Margin="0,0,22,0" />
|
||||
</WrapPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -1,8 +1,20 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
public partial class ServerView : UserControl
|
||||
{
|
||||
public ServerView() => InitializeComponent();
|
||||
|
||||
/// <summary>The ▾ button opens the list of servers found on the LAN under itself.</summary>
|
||||
private void OnShowKnown(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (KnownButton.ContextMenu is not { } menu) return;
|
||||
menu.DataContext = DataContext;
|
||||
menu.PlacementTarget = KnownButton;
|
||||
menu.Placement = PlacementMode.Bottom;
|
||||
menu.IsOpen = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
using System.ComponentModel;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Server;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>
|
||||
/// Server, connection part (BRIEF §12.7, Server.html): address with LAN-discovered servers, connect with
|
||||
/// trust-on-first-use and login, status (name, version, latency, certificate), account and quota, sign out, and
|
||||
/// the render-node opt-in. The sync table and render-node panel join this screen later.
|
||||
/// </summary>
|
||||
public sealed class ServerViewModel : SectionViewModel
|
||||
{
|
||||
private string _address;
|
||||
private string? _errorText;
|
||||
private ServerSession? _session;
|
||||
|
||||
public ServerViewModel(ShellViewModel shell)
|
||||
: base(SectionKey.Server, "Icon.Server")
|
||||
{
|
||||
Shell = shell;
|
||||
_address = ServerAddress.Display(shell.Services.Settings.ServerUrl);
|
||||
ConnectCommand = new AsyncRelayCommand(ConnectAsync, () => !IsBusy && !IsConnected && Address.Trim().Length > 0);
|
||||
DisconnectCommand = new RelayCommand(() => Session.Disconnect(), () => IsConnected);
|
||||
SignOutCommand = new AsyncRelayCommand(SignOutAsync, () => IsConnected);
|
||||
UseServerCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is DiscoveredServer s) Address = s.Address;
|
||||
else if (p is string text) Address = text;
|
||||
});
|
||||
CertificateCommand = new RelayCommand(ShowCertificate, () => Fingerprint is not null);
|
||||
}
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
private ServerSession Session => _session ?? Shell.Services.Server;
|
||||
|
||||
public ICommand ConnectCommand { get; }
|
||||
public ICommand DisconnectCommand { get; }
|
||||
public ICommand SignOutCommand { get; }
|
||||
public ICommand UseServerCommand { get; }
|
||||
public ICommand CertificateCommand { get; }
|
||||
|
||||
/// <summary>Servers found on the LAN plus recently used ones, for the ▾ list.</summary>
|
||||
public IEnumerable<DiscoveredServer> KnownServers =>
|
||||
Session.Discovered.Concat(Shell.Services.Settings.RecentServers
|
||||
.Where(r => !Session.Discovered.Any(d => d.Address.Equals(r, StringComparison.OrdinalIgnoreCase)))
|
||||
.Select(r => new DiscoveredServer(r, r)));
|
||||
|
||||
public bool HasKnownServers => KnownServers.Any();
|
||||
|
||||
public string Address
|
||||
{
|
||||
get => _address;
|
||||
set
|
||||
{
|
||||
if (Set(ref _address, value ?? string.Empty)) CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsBusy => Session.IsBusy;
|
||||
public bool IsConnected => Session.IsConnected;
|
||||
public bool IsDisconnected => !Session.IsConnected;
|
||||
|
||||
/// <summary>One sentence about the last failure; null when none.</summary>
|
||||
public string? ErrorText
|
||||
{
|
||||
get => _errorText;
|
||||
private set => Set(ref _errorText, value);
|
||||
}
|
||||
|
||||
// ---- Status row ----
|
||||
public StatusKind StatusKind => IsConnected ? StatusKind.Online : IsBusy ? StatusKind.Running : ErrorText is null ? StatusKind.Offline : StatusKind.Error;
|
||||
|
||||
public string StatusText => IsConnected ? Loc.L("Server.Status.Connected")
|
||||
: IsBusy ? Loc.L("Server.Status.Connecting")
|
||||
: Session.HasSavedSession ? Loc.L("Server.Status.Disconnected")
|
||||
: Loc.L("Server.Status.NotConnected");
|
||||
|
||||
/// <summary>"Studio NAS · v1.3.0 · 14 ms".</summary>
|
||||
public string? ServerText
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!IsConnected || Session.Flow.Info is not { } info) return null;
|
||||
var parts = new List<string> { info.Name, Loc.L("Server.Version", info.Version) };
|
||||
if (Session.Flow.Latency is { } latency) parts.Add(Loc.L("Server.Latency", Math.Max(1, (int)Math.Round(latency.TotalMilliseconds))));
|
||||
return string.Join(" · ", parts);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Fingerprint of the trusted self-signed certificate; null for a publicly valid certificate.</summary>
|
||||
public string? Fingerprint => IsConnected ? Session.TrustOf(Session.Flow.Info?.TlsFingerprint)?.Fingerprint : null;
|
||||
|
||||
/// <summary>"TLS 9A:3C:71:E0:… trusted 2026-09-01".</summary>
|
||||
public string? CertificateText => Fingerprint is { } fp && Session.TrustOf(fp) is { } trust
|
||||
? Loc.L("Server.Certificate.Trusted", ServerSession.ShortFingerprint(fp), Formatting.Date(trust.TrustedAt))
|
||||
: null;
|
||||
|
||||
public string CertificateToolTip => Loc.L("Tooltips.Server.CertificateTrusted");
|
||||
|
||||
// ---- Account row ----
|
||||
public string? Username => Session.User?.Username;
|
||||
public string Initial => Username is { Length: > 0 } u ? char.ToUpper(u[0], Loc.Culture).ToString() : string.Empty;
|
||||
|
||||
public string? RoleText => Session.User?.Role is { } role ? KnownRole(role) is { } known ? Loc.L("Server.Role." + known) : role : null;
|
||||
|
||||
public string? RoleToolTip => Session.User?.Role is { } role && KnownRole(role) is { } known ? Loc.L("Tooltips.Server.Role." + known) : null;
|
||||
|
||||
public bool HasQuota => Session.User is { QuotaBytes: > 0 };
|
||||
|
||||
public double QuotaFraction => Session.User is { QuotaBytes: > 0 } u ? Math.Clamp((double)u.UsedBytes / u.QuotaBytes, 0, 1) : 0;
|
||||
|
||||
/// <summary>"2.1 TB of 5 TB", or the used bytes when unlimited.</summary>
|
||||
public string? QuotaText => Session.User is not { } u ? null
|
||||
: u.QuotaBytes > 0 ? Loc.L("Server.Quota", Formatting.Bytes(u.UsedBytes), Formatting.Bytes(u.QuotaBytes))
|
||||
: Loc.L("Server.QuotaUnlimited", Formatting.Bytes(u.UsedBytes));
|
||||
|
||||
// ---- Options ----
|
||||
public bool RenderNodeOptIn
|
||||
{
|
||||
get => Shell.Services.Settings.RenderNodeOptIn;
|
||||
set
|
||||
{
|
||||
if (Shell.Services.Settings.RenderNodeOptIn == value) return;
|
||||
Shell.Services.Settings.RenderNodeOptIn = value;
|
||||
Shell.Services.SaveSettings();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Re-reads values another screen changed (Settings › Server).</summary>
|
||||
public void Refresh() => OnPropertyChanged(nameof(RenderNodeOptIn));
|
||||
|
||||
/// <summary>Restores the saved session and starts listening for LAN servers.</summary>
|
||||
public async Task AttachAsync()
|
||||
{
|
||||
_session = Shell.Services.Server;
|
||||
_session.PropertyChanged += OnSessionChanged;
|
||||
_session.Discovered.CollectionChanged += (_, _) =>
|
||||
{
|
||||
OnPropertyChanged(nameof(KnownServers));
|
||||
OnPropertyChanged(nameof(HasKnownServers));
|
||||
if (Address.Length == 0 && Session.Discovered.Count > 0) Address = Session.Discovered[0].Address;
|
||||
};
|
||||
if (!Shell.Services.Environment.IsCapture) _session.StartDiscovery();
|
||||
await _session.RestoreAsync();
|
||||
if (_session.Flow.Error is not ConnectError.None and var error && !_session.IsConnected) ErrorText = ServerSession.ErrorText(error);
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
if (_session is not null) _session.PropertyChanged -= OnSessionChanged;
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
private async Task ConnectAsync()
|
||||
{
|
||||
ErrorText = null;
|
||||
var connected = await Session.ConnectAsync(Address, Shell.Services.Dialogs);
|
||||
if (connected)
|
||||
{
|
||||
Address = ServerAddress.Display(Session.SavedAddress);
|
||||
return;
|
||||
}
|
||||
if (Session.Flow.Error is not ConnectError.None and var error) ErrorText = ServerSession.ErrorText(error);
|
||||
}
|
||||
|
||||
private async Task SignOutAsync()
|
||||
{
|
||||
await Session.SignOutAsync();
|
||||
ErrorText = null;
|
||||
}
|
||||
|
||||
private void ShowCertificate()
|
||||
{
|
||||
if (Fingerprint is not { } fingerprint) return;
|
||||
var forget = Shell.Services.Dialogs.Confirm(new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Server.Certificate.Title"),
|
||||
Message = Loc.L("Server.Certificate.Message"),
|
||||
Detail = ServerSession.FormatFingerprint(fingerprint),
|
||||
DetailToolTip = Loc.L("Tooltips.Server.Fingerprint"),
|
||||
SafeText = Loc.L("Server.Certificate.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Server.KeepTrust"),
|
||||
ActionText = Loc.L("Server.Certificate.Forget"),
|
||||
ActionToolTip = Loc.L("Tooltips.Server.ForgetTrust"),
|
||||
IsDestructive = true,
|
||||
});
|
||||
if (!forget) return;
|
||||
Session.Disconnect();
|
||||
Session.Forget(fingerprint);
|
||||
}
|
||||
|
||||
private void OnSessionChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
OnAllPropertiesChanged();
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
/// <summary>The <see cref="Core.Model.UserRole"/> name of a server role, or null for a role this build does not know.</summary>
|
||||
private static string? KnownRole(string role) =>
|
||||
Enum.TryParse<Core.Model.UserRole>(role, ignoreCase: true, out var parsed) ? parsed.ToString() : null;
|
||||
}
|
||||
@@ -3,86 +3,332 @@
|
||||
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"
|
||||
xmlns:s="clr-namespace:Titano.App.Sections">
|
||||
<Grid Margin="20,16,20,20">
|
||||
xmlns:shell="clr-namespace:Titano.App.Shell"
|
||||
xmlns:st="clr-namespace:Titano.App.Settings">
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="Page" TargetType="StackPanel">
|
||||
<Setter Property="Visibility" Value="Collapsed" />
|
||||
</Style>
|
||||
<Style x:Key="Slider.Budget" TargetType="Slider" BasedOn="{StaticResource {x:Type Slider}}">
|
||||
<Setter Property="ui:ControlState.Accent" Value="{DynamicResource Brush.Sun}" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsMemoryAuto}" Value="True">
|
||||
<Setter Property="ui:ControlState.Accent" Value="{DynamicResource Brush.Accent}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<Style x:Key="Button.Reset" TargetType="Button" BasedOn="{StaticResource Button.IconSubtle}">
|
||||
<Setter Property="Width" Value="24" />
|
||||
<Setter Property="Height" Value="24" />
|
||||
<Setter Property="MinWidth" Value="24" />
|
||||
<Setter Property="ui:ControlState.CornerRadius" Value="12" />
|
||||
<Setter Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.Reset}" />
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid Margin="20,16,20,16">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="200" />
|
||||
<ColumnDefinition Width="{StaticResource Width.SettingsList}" />
|
||||
<ColumnDefinition Width="16" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Section list -->
|
||||
<ListBox ItemsSource="{Binding Pages}" SelectedItem="{Binding Page}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Converter={x:Static s:SettingsPageNameConverter.Instance}}" />
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
<!-- Section list: search, sections, settings as JSON. -->
|
||||
<DockPanel>
|
||||
<TextBox DockPanel.Dock="Top" Margin="0,0,0,8" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
|
||||
ui:Field.Placeholder="{l:Loc Settings.Search}" ToolTip="{l:Loc Tooltips.Settings.Search}" AutomationProperties.Name="{l:Loc Settings.Search}" />
|
||||
<StackPanel DockPanel.Dock="Bottom">
|
||||
<Button Content="{l:Loc Settings.Export}" Command="{Binding ExportSettingsCommand}" ToolTip="{l:Loc Tooltips.Settings.Export}" HorizontalAlignment="Stretch" Margin="0,0,0,8" />
|
||||
<Button Content="{l:Loc Settings.Import}" Command="{Binding ImportSettingsCommand}" ToolTip="{l:Loc Tooltips.Settings.Import}" HorizontalAlignment="Stretch" />
|
||||
</StackPanel>
|
||||
<ListBox ItemsSource="{Binding VisiblePages}" SelectedItem="{Binding SelectedPageItem}" ItemContainerStyle="{StaticResource ListBoxItem.Section}"
|
||||
ScrollViewer.VerticalScrollBarVisibility="Auto" AutomationProperties.Name="{l:Loc Shell.Nav.Settings}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type st:SettingsPageItem}">
|
||||
<TextBlock Text="{Binding Label}" ToolTip="{Binding ToolTip}" TextTrimming="CharacterEllipsis" />
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</DockPanel>
|
||||
|
||||
<Border Grid.Column="2" Style="{StaticResource Border.Panel}" Padding="22,18">
|
||||
<Grid>
|
||||
<!-- General -->
|
||||
<StackPanel x:Name="General">
|
||||
<StackPanel.Style>
|
||||
<Style TargetType="StackPanel">
|
||||
<Setter Property="Visibility" Value="Collapsed" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding Page}" Value="General"><Setter Property="Visibility" Value="Visible" /></DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</StackPanel.Style>
|
||||
<TextBlock Text="{l:Loc Settings.Page.General}" Style="{StaticResource Text.PageTitle}" Margin="0,0,0,16" />
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="180" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="44" />
|
||||
<RowDefinition Height="44" />
|
||||
<RowDefinition Height="44" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{l:Loc Settings.General.Language}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<ComboBox Grid.Column="1" Width="240" HorizontalAlignment="Left" ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}"
|
||||
DisplayMemberPath="Name" ToolTip="{l:Loc Tooltips.Settings.Language}" />
|
||||
<TextBlock Grid.Row="1" Text="{l:Loc Settings.General.Theme}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<RadioButton GroupName="Theme" Content="{l:Loc Settings.General.Theme.Dark}" IsChecked="{Binding IsDarkTheme}" ToolTip="{l:Loc Tooltips.Settings.ThemeDark}" Margin="0,0,20,0" />
|
||||
<RadioButton GroupName="Theme" Content="{l:Loc Settings.General.Theme.Light}" IsChecked="{Binding IsLightTheme}" ToolTip="{l:Loc Tooltips.Settings.ThemeLight}" Margin="0,0,20,0" />
|
||||
<RadioButton GroupName="Theme" Content="{l:Loc Settings.General.Theme.System}" IsChecked="{Binding IsSystemTheme}" ToolTip="{l:Loc Tooltips.Settings.ThemeSystem}" />
|
||||
</StackPanel>
|
||||
<TextBlock Grid.Row="2" Text="{l:Loc Settings.General.Updates}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<CheckBox Grid.Row="2" Grid.Column="1" Content="{l:Loc Settings.General.CheckOnStart}" IsChecked="{Binding CheckForUpdates}" ToolTip="{l:Loc Tooltips.Settings.CheckForUpdates}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="{Binding PageTitle}" Style="{StaticResource Text.PageTitle}" Margin="0,0,0,18" />
|
||||
<Border DockPanel.Dock="Bottom" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0" Padding="0,12,0,0" Margin="0,12,0,0">
|
||||
<Button Style="{StaticResource Button.Subtle}" HorizontalAlignment="Right" Content="{l:Loc Settings.ResetSection}" Command="{Binding ResetSectionCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Settings.ResetSection}" BorderBrush="{DynamicResource Brush.Stroke}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
</Border>
|
||||
|
||||
<!-- Advanced -->
|
||||
<StackPanel>
|
||||
<StackPanel.Style>
|
||||
<Style TargetType="StackPanel">
|
||||
<Setter Property="Visibility" Value="Collapsed" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding Page}" Value="Advanced"><Setter Property="Visibility" Value="Visible" /></DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</StackPanel.Style>
|
||||
<TextBlock Text="{l:Loc Settings.Page.Advanced}" Style="{StaticResource Text.PageTitle}" Margin="0,0,0,16" />
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="180" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="44" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{l:Loc Settings.Advanced.DataFolder}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBox Grid.Column="1" IsReadOnly="True" Text="{Binding Shell.About.DataFolder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.DataFolder}" />
|
||||
<Button Grid.Column="2" Margin="8,0,0,0" Content="{l:Loc Common.Open}" Command="{Binding Shell.About.OpenDataFolderCommand}" ToolTip="{l:Loc Tooltips.Settings.OpenDataFolder}" />
|
||||
<!-- ================= General ================= -->
|
||||
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=General}">
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Language}">
|
||||
<ComboBox Width="240" HorizontalAlignment="Left" ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}" DisplayMemberPath="Name"
|
||||
ToolTip="{l:Loc Tooltips.Settings.Language}" AutomationProperties.Name="{l:Loc Settings.General.Language}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Theme}">
|
||||
<WrapPanel VerticalAlignment="Center" Margin="0,4,0,0">
|
||||
<RadioButton GroupName="Theme" Content="{l:Loc Settings.General.Theme.Dark}" IsChecked="{Binding IsDarkTheme}" ToolTip="{l:Loc Tooltips.Settings.ThemeDark}" Margin="0,0,20,0" />
|
||||
<RadioButton GroupName="Theme" Content="{l:Loc Settings.General.Theme.Light}" IsChecked="{Binding IsLightTheme}" ToolTip="{l:Loc Tooltips.Settings.ThemeLight}" Margin="0,0,20,0" />
|
||||
<RadioButton GroupName="Theme" Content="{l:Loc Settings.General.Theme.System}" IsChecked="{Binding IsSystemTheme}" ToolTip="{l:Loc Tooltips.Settings.ThemeSystem}" />
|
||||
</WrapPanel>
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Usage}">
|
||||
<CheckBox Content="{l:Loc Settings.General.UsageCounts}" IsChecked="{Binding UsageCounts}" ToolTip="{l:Loc Tooltips.Settings.UsageCounts}" Margin="0,4,0,0" />
|
||||
</HeaderedContentControl>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ================= Archive ================= -->
|
||||
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Archive}">
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Root}">
|
||||
<WrapPanel>
|
||||
<TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding ArchiveRoot.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding ArchiveRoot}" ToolTip="{Binding ArchiveRoot.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Archive.Root}" />
|
||||
<Button Style="{StaticResource Button.Icon}" Margin="10,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" Command="{Binding BrowseArchiveCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Settings.BrowseArchive}" AutomationProperties.Name="{l:Loc Settings.Browse}" />
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding ArchiveFreeText}" Margin="10,0,0,0" ToolTip="{l:Loc Tooltips.Settings.ArchiveFree}" />
|
||||
</WrapPanel>
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Folders}">
|
||||
<TextBox Style="{StaticResource TextBox.SettingMono}" Text="{Binding FolderTemplate.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding FolderTemplate}" ToolTip="{Binding FolderTemplate.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Archive.Folders}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Files}">
|
||||
<TextBox Style="{StaticResource TextBox.SettingMono}" Text="{Binding FileTemplate.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding FileTemplate}" ToolTip="{Binding FileTemplate.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Archive.Files}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Preview}">
|
||||
<ItemsControl ItemsSource="{Binding PreviewNames}" Focusable="False" Margin="0,7,0,0" ToolTip="{l:Loc Tooltips.Settings.Preview}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding}" FontFamily="{StaticResource Font.Mono}" FontSize="12" Foreground="{DynamicResource Brush.TextMuted}" LineHeight="20" TextTrimming="CharacterEllipsis" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Proxies}">
|
||||
<ComboBox Width="140" HorizontalAlignment="Left" ItemsSource="{Binding ProxySizes}" SelectedItem="{Binding SelectedProxySize}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Settings.Proxies}" AutomationProperties.Name="{l:Loc Settings.Archive.Proxies}" />
|
||||
</HeaderedContentControl>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ================= Rendering (Settings.html) ================= -->
|
||||
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Rendering}">
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Rendering.Quality}">
|
||||
<ComboBox Width="160" HorizontalAlignment="Left" ItemsSource="{Binding Qualities}" SelectedItem="{Binding SelectedQuality}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Settings.Quality}" AutomationProperties.Name="{l:Loc Settings.Rendering.Quality}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Rendering.Memory}">
|
||||
<WrapPanel>
|
||||
<Slider Style="{StaticResource Slider.Budget}" Width="320" Minimum="{Binding MemoryMinimum}" Maximum="{Binding MemoryMaximum}" Value="{Binding MemoryBudget}"
|
||||
TickFrequency="1" IsSnapToTickEnabled="True" SmallChange="1" LargeChange="2" VerticalAlignment="Center"
|
||||
ToolTip="{l:Loc Tooltips.Settings.Memory}" AutomationProperties.Name="{l:Loc Settings.Rendering.Memory}" />
|
||||
<TextBlock Text="{Binding MemoryText}" Margin="12,0,0,0" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding InstalledText}" Margin="12,0,0,0" />
|
||||
<Button Style="{StaticResource Button.AutoPill}" Content="{Binding MemoryAutoText}" Margin="12,0,0,0" ToolTip="{l:Loc Tooltips.Settings.MemoryAuto}"
|
||||
Visibility="{Binding IsMemoryAuto, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Reset}" Margin="12,0,0,0" Command="{Binding ResetMemoryCommand}" ToolTip="{l:Loc Tooltips.Settings.MemoryReset}"
|
||||
AutomationProperties.Name="{l:Loc Settings.BackToAuto}"
|
||||
Visibility="{Binding IsMemoryAuto, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
</WrapPanel>
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Rendering.Parallelism}">
|
||||
<WrapPanel>
|
||||
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding Parallelism.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding Parallelism}" ToolTip="{Binding Parallelism.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Rendering.Parallelism}" />
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding CoresText}" Margin="12,0,0,0" />
|
||||
<Button Style="{StaticResource Button.AutoPill}" Content="{Binding ParallelismAutoText}" Margin="12,0,0,0" ToolTip="{l:Loc Tooltips.Settings.ParallelismAuto}"
|
||||
Visibility="{Binding IsParallelismAuto, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Reset}" Margin="12,0,0,0" Command="{Binding ResetParallelismCommand}" ToolTip="{l:Loc Tooltips.Settings.ParallelismReset}"
|
||||
AutomationProperties.Name="{l:Loc Settings.BackToAuto}"
|
||||
Visibility="{Binding IsParallelismAuto, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
<CheckBox Content="{l:Loc Settings.Rendering.Background}" IsChecked="{Binding BackgroundPriority}" ToolTip="{l:Loc Tooltips.Settings.Background}"
|
||||
Margin="24,0,0,0" VerticalAlignment="Center" />
|
||||
</WrapPanel>
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Rendering.Hardware}">
|
||||
<WrapPanel Margin="0,4,0,0">
|
||||
<RadioButton GroupName="Hardware" Content="{l:Loc Settings.Rendering.PreferHardware}" IsChecked="{Binding IsPreferHardware}" ToolTip="{l:Loc Tooltips.Settings.PreferHardware}" Margin="0,0,18,0" />
|
||||
<RadioButton GroupName="Hardware" Content="{l:Loc Settings.Rendering.SoftwareOnly}" IsChecked="{Binding IsSoftwareOnly}" ToolTip="{l:Loc Tooltips.Settings.SoftwareOnly}" Margin="0,0,18,0" />
|
||||
<RadioButton GroupName="Hardware" Content="{l:Loc Settings.Rendering.PreviewsOnly}" IsChecked="{Binding IsHardwareForPreviews}" ToolTip="{l:Loc Tooltips.Settings.PreviewsOnly}" />
|
||||
</WrapPanel>
|
||||
</HeaderedContentControl>
|
||||
|
||||
<!-- Encoders on this PC -->
|
||||
<DockPanel Margin="0,4,0,8" LastChildFill="False">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Settings.Rendering.SelfTest}" Command="{Binding SelfTestCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Settings.SelfTest}" Margin="8,0,0,0" />
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Settings.Rendering.Redetect}" Command="{Binding RedetectCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Settings.Redetect}" />
|
||||
<TextBlock Text="{l:Loc Settings.Rendering.Encoders}" FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding AdapterText}" Margin="10,0,0,0" ToolTip="{l:Loc Tooltips.Settings.Adapter}" />
|
||||
</DockPanel>
|
||||
<Border Style="{StaticResource Border.Card}">
|
||||
<StackPanel>
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="110" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="160" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="120" />
|
||||
<ColumnDefinition Width="150" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Rendering.Column.Codec}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Rendering.Column.Encoder}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Rendering.Column.TenBit}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Rendering.Column.Max}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Rendering.Column.SelfTest}" Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
</Border>
|
||||
<ItemsControl ItemsSource="{Binding Encoders}" Focusable="False">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type st:EncoderRowViewModel}">
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Height="36" Padding="14,0">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="110" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="160" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="120" />
|
||||
<ColumnDefinition Width="150" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Codec}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Name}" Margin="10,0,0,0" ToolTip="{Binding Row.Name}" />
|
||||
<TextBlock x:Name="TenBit" Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding TenBitText}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextFaint}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding MaxText}" Margin="10,0,0,0" />
|
||||
<ui:StatusGlyph Grid.Column="4" Kind="{Binding ResultKind}" Text="{Binding ResultText}" ToolTip="{Binding ResultToolTip}" FontSize="13"
|
||||
VerticalAlignment="Center" Margin="10,0,0,0" Visibility="{Binding HasResult, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding HasTenBit}" Value="True">
|
||||
<Setter TargetName="TenBit" Property="Foreground" Value="{DynamicResource Brush.Success}" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ================= Storage ================= -->
|
||||
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Storage}">
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Storage.Folder}">
|
||||
<WrapPanel>
|
||||
<TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding CacheFolder.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding CacheFolder}" ToolTip="{Binding CacheFolder.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Storage.Folder}" />
|
||||
<Button Style="{StaticResource Button.Icon}" Margin="10,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" Command="{Binding BrowseCacheCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Settings.BrowseCache}" AutomationProperties.Name="{l:Loc Settings.Browse}" />
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding CacheUsageText}" Margin="10,0,0,0" ToolTip="{l:Loc Tooltips.Settings.CacheUsage}" />
|
||||
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Settings.Storage.Clear}" Command="{Binding ClearCacheCommand}" ToolTip="{l:Loc Tooltips.Settings.ClearCacheAsk}"
|
||||
Margin="10,0,0,0" />
|
||||
</WrapPanel>
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Storage.Thumbnails}">
|
||||
<WrapPanel>
|
||||
<TextBox Style="{StaticResource TextBox.Number}" Width="96" Text="{Binding ThumbnailMemory.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding ThumbnailMemory}" ToolTip="{Binding ThumbnailMemory.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Storage.Thumbnails}" />
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Storage.ThumbnailsUnit}" Margin="12,0,0,0" />
|
||||
</WrapPanel>
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Storage.Limit}">
|
||||
<WrapPanel>
|
||||
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding CacheLimit.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding CacheLimit}" ToolTip="{Binding CacheLimit.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Storage.Limit}" />
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Storage.LimitUnit}" Margin="12,0,0,0" />
|
||||
</WrapPanel>
|
||||
</HeaderedContentControl>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ================= Server ================= -->
|
||||
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Server}">
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Default}">
|
||||
<TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding DefaultServer.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding DefaultServer}" ToolTip="{Binding DefaultServer.ToolTip}" ui:Field.Placeholder="{l:Loc Server.AddressPlaceholder}"
|
||||
AutomationProperties.Name="{l:Loc Settings.Server.Default}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.RenderNode}">
|
||||
<CheckBox Content="{l:Loc Server.RenderNode}" IsChecked="{Binding RenderNodeOptIn}" ToolTip="{l:Loc Tooltips.Server.RenderNode}" Margin="0,4,0,0" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Certificates}">
|
||||
<Grid>
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Server.NoCertificates}" Margin="0,7,0,0" VerticalAlignment="Top"
|
||||
Visibility="{Binding HasCertificates, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
<ItemsControl ItemsSource="{Binding Certificates}" Focusable="False" Visibility="{Binding HasCertificates, Converter={StaticResource BoolToVisibility}}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type st:TrustedCertificateRow}">
|
||||
<Grid Height="36">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" MinWidth="160" />
|
||||
<ColumnDefinition Width="170" />
|
||||
<ColumnDefinition Width="110" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Server}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Fingerprint}" FontFamily="{StaticResource Font.Mono}" FontSize="12"
|
||||
ToolTip="{Binding FullFingerprint}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding TrustedText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" />
|
||||
<Button Grid.Column="3" Style="{StaticResource Button.Row}" Content="{l:Loc Server.Certificate.Forget}" Command="{Binding ForgetCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Server.ForgetTrust}" Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
</HeaderedContentControl>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ================= Updates ================= -->
|
||||
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Updates}">
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Updates}">
|
||||
<CheckBox Content="{l:Loc Settings.General.CheckOnStart}" IsChecked="{Binding CheckForUpdates}" ToolTip="{l:Loc Tooltips.Settings.CheckForUpdates}" Margin="0,4,0,0" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Updates.Latest}">
|
||||
<WrapPanel>
|
||||
<Button Content="{l:Loc About.Update.Check}" Command="{Binding Shell.About.CheckCommand}" ToolTip="{l:Loc Tooltips.About.Check}" />
|
||||
<ui:StatusGlyph Kind="{Binding Shell.About.UpdateKind}" Text="{Binding Shell.About.UpdateText}" FontSize="13" VerticalAlignment="Center" Margin="12,0,0,0"
|
||||
Visibility="{Binding Shell.About.HasUpdateText, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Link}" Content="{l:Loc About.Update.Download}" Command="{Binding Shell.About.DownloadCommand}" ToolTip="{l:Loc Tooltips.About.Download}"
|
||||
VerticalAlignment="Center" Margin="12,0,0,0" FontSize="13"
|
||||
Visibility="{Binding Shell.About.IsUpdateAvailable, Converter={StaticResource BoolToVisibility}}" />
|
||||
</WrapPanel>
|
||||
</HeaderedContentControl>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ================= Advanced ================= -->
|
||||
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Advanced}">
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Portable}">
|
||||
<TextBlock Text="{Binding PortableText}" Margin="0,7,0,0" ToolTip="{l:Loc Tooltips.Settings.Portable}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.DataFolder}">
|
||||
<WrapPanel>
|
||||
<TextBox Style="{StaticResource TextBox.Setting}" IsReadOnly="True" Text="{Binding DataFolder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.DataFolder}"
|
||||
AutomationProperties.Name="{l:Loc Settings.Advanced.DataFolder}" />
|
||||
<Button Content="{l:Loc Common.Open}" Command="{Binding OpenDataFolderCommand}" ToolTip="{l:Loc Tooltips.Settings.OpenDataFolder}" Margin="10,0,0,0" />
|
||||
</WrapPanel>
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Logs}">
|
||||
<WrapPanel>
|
||||
<TextBox Style="{StaticResource TextBox.Setting}" IsReadOnly="True" Text="{Binding LogsFolder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.LogsFolder}"
|
||||
AutomationProperties.Name="{l:Loc Settings.Advanced.Logs}" />
|
||||
<Button Content="{l:Loc Common.Open}" Command="{Binding OpenLogsCommand}" ToolTip="{l:Loc Tooltips.Common.OpenLogs}" Margin="10,0,0,0" />
|
||||
</WrapPanel>
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Diagnostics}">
|
||||
<Button HorizontalAlignment="Left" Content="{l:Loc Settings.Advanced.ExportBundle}" Command="{Binding ExportDiagnosticsCommand}" ToolTip="{l:Loc Tooltips.Settings.Diagnostics}"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.Export}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Backup}">
|
||||
<Button HorizontalAlignment="Left" Content="{l:Loc Settings.Advanced.BackupNow}" Command="{Binding BackupDatabaseCommand}" ToolTip="{l:Loc Tooltips.Settings.Backup}"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.Database}" />
|
||||
</HeaderedContentControl>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</ScrollViewer>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -1,7 +1,4 @@
|
||||
using System.Globalization;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
@@ -9,14 +6,3 @@ public partial class SettingsView : UserControl
|
||||
{
|
||||
public SettingsView() => InitializeComponent();
|
||||
}
|
||||
|
||||
/// <summary>Settings page id → localized page name.</summary>
|
||||
public sealed class SettingsPageNameConverter : IValueConverter
|
||||
{
|
||||
public static SettingsPageNameConverter Instance { get; } = new();
|
||||
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is string page ? Loc.L("Settings.Page." + page) : string.Empty;
|
||||
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
|
||||
}
|
||||
@@ -0,0 +1,803 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Server;
|
||||
using Titano.App.Settings;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Naming;
|
||||
using Titano.Data;
|
||||
using Titano.Ui.Mvvm;
|
||||
using Titano.Ui.Theming;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>
|
||||
/// Settings (BRIEF §12.8, Settings.html): a searchable section list on the left, the controls of one section on
|
||||
/// the right, tooltips only. Text fields commit on Enter and revert on Esc; invalid input shows the Error border
|
||||
/// with the reason in the tooltip. Everything persists through <see cref="AppSettings"/> (atomic writes).
|
||||
/// </summary>
|
||||
public sealed class SettingsViewModel : SectionViewModel
|
||||
{
|
||||
private readonly AppSettings _s;
|
||||
private SettingsPage _page = SettingsPage.General;
|
||||
private string _searchText = string.Empty;
|
||||
private IReadOnlyList<SettingsPageItem> _visiblePages;
|
||||
private IReadOnlyList<string> _previewNames = [];
|
||||
private string? _archiveFreeText;
|
||||
private string? _cacheUsageText;
|
||||
private string? _adapterText;
|
||||
private bool _isDetecting;
|
||||
private bool _isTesting;
|
||||
private CancellationTokenSource? _selfTest;
|
||||
|
||||
public SettingsViewModel(ShellViewModel shell)
|
||||
: base(SectionKey.Settings, "Icon.Settings")
|
||||
{
|
||||
Shell = shell;
|
||||
_s = shell.Services.Settings;
|
||||
AllPages =
|
||||
[
|
||||
new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", "Settings.General.Usage"]),
|
||||
new(SettingsPage.Archive, ["Settings.Archive.Root", "Settings.Archive.Folders", "Settings.Archive.Files", "Settings.Archive.Proxies"]),
|
||||
new(SettingsPage.Rendering, ["Settings.Rendering.Quality", "Settings.Rendering.Memory", "Settings.Rendering.Parallelism", "Settings.Rendering.Hardware", "Settings.Rendering.Encoders"]),
|
||||
new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
|
||||
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
|
||||
new(SettingsPage.Updates, ["Settings.General.CheckOnStart"]),
|
||||
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.Diagnostics", "Settings.Advanced.Backup"]),
|
||||
];
|
||||
_visiblePages = AllPages;
|
||||
|
||||
// ---- Archive ----
|
||||
ArchiveRoot = new EditableField(_s.LastArchivePath ?? string.Empty, v => v.Length == 0 ? null : ArchiveLocations.Validate(v), v =>
|
||||
{
|
||||
_s.LastArchivePath = v.Length == 0 ? null : Path.GetFullPath(v);
|
||||
Save();
|
||||
UpdateArchiveFree();
|
||||
}, () => Loc.L("Tooltips.Settings.ArchiveRoot"));
|
||||
FolderTemplate = new EditableField(_s.FolderTemplate, v => NamingPreview.Validate(v, isFolder: true), v =>
|
||||
{
|
||||
_s.FolderTemplate = v;
|
||||
Save();
|
||||
}, () => Loc.L("Tooltips.Settings.FolderTemplate"));
|
||||
FileTemplate = new EditableField(_s.FileTemplate, v => NamingPreview.Validate(v, isFolder: false), v =>
|
||||
{
|
||||
_s.FileTemplate = v;
|
||||
Save();
|
||||
}, () => Loc.L("Tooltips.Settings.FileTemplate"));
|
||||
FolderTemplate.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(EditableField.Text)) UpdatePreview();
|
||||
};
|
||||
FileTemplate.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(EditableField.Text)) UpdatePreview();
|
||||
};
|
||||
|
||||
// ---- Rendering ----
|
||||
InstalledGb = Math.Max(2, (int)Math.Round(GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 1e9));
|
||||
Parallelism = new EditableField(EffectiveParallelism.ToString(CultureInfo.CurrentCulture), ValidateParallelism, v =>
|
||||
{
|
||||
var n = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
|
||||
_s.Parallelism = n == ParallelismAuto ? null : n;
|
||||
Save();
|
||||
OnPropertyChanged(nameof(IsParallelismAuto));
|
||||
}, () => Loc.L("Tooltips.Settings.Parallelism"));
|
||||
|
||||
// ---- Storage ----
|
||||
CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v =>
|
||||
{
|
||||
var full = Path.GetFullPath(v);
|
||||
_s.CacheFolder = full.Equals(Shell.Services.Environment.CacheDirectory, StringComparison.OrdinalIgnoreCase) ? null : full;
|
||||
Save();
|
||||
_ = UpdateCacheUsageAsync();
|
||||
}, () => Loc.L("Tooltips.Settings.CacheFolder"));
|
||||
ThumbnailMemory = new EditableField(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture), v => ValidateInt(v, 100, 100_000), v =>
|
||||
{
|
||||
_s.ThumbnailMemoryItems = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
|
||||
Save();
|
||||
if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
|
||||
}, () => Loc.L("Tooltips.Settings.ThumbnailMemory"));
|
||||
CacheLimit = new EditableField(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture), v => ValidateInt(v, 1, 100_000), v =>
|
||||
{
|
||||
_s.CacheLimitGb = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
|
||||
Save();
|
||||
}, () => Loc.L("Tooltips.Settings.CacheLimit"));
|
||||
|
||||
// ---- Server ----
|
||||
DefaultServer = new EditableField(ServerAddress.Display(_s.ServerUrl), v => v.Trim().Length == 0 || ServerAddress.TryParse(v, out _) ? null : Loc.L("Errors.Server.Address"), v =>
|
||||
{
|
||||
var display = v.Trim().Length == 0 ? null : ServerAddress.TryParse(v, out var uri) ? ServerAddress.Display(uri) : null;
|
||||
if (!string.Equals(display, ServerAddress.Display(_s.ServerUrl), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// A saved token belongs to the old server: never send it elsewhere.
|
||||
_s.ProtectedToken = null;
|
||||
}
|
||||
_s.ServerUrl = display;
|
||||
Save();
|
||||
}, () => Loc.L("Tooltips.Settings.DefaultServer"));
|
||||
|
||||
SelectPageCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is SettingsPageItem item) Page = item.Page;
|
||||
else if (p is SettingsPage page) Page = page;
|
||||
});
|
||||
BrowseArchiveCommand = new RelayCommand(() => Browse(ArchiveRoot, "Settings.Archive.PickTitle"));
|
||||
BrowseCacheCommand = new RelayCommand(() => Browse(CacheFolder, "Settings.Storage.PickTitle"));
|
||||
ResetMemoryCommand = new RelayCommand(() => MemoryBudget = MemoryAuto, () => !IsMemoryAuto);
|
||||
ResetParallelismCommand = new RelayCommand(() =>
|
||||
{
|
||||
_s.Parallelism = null;
|
||||
Save();
|
||||
Parallelism.Load(ParallelismAuto.ToString(CultureInfo.CurrentCulture));
|
||||
OnPropertyChanged(nameof(IsParallelismAuto));
|
||||
}, () => !IsParallelismAuto);
|
||||
RedetectCommand = new AsyncRelayCommand(DetectEncodersAsync, () => !_isDetecting && !_isTesting);
|
||||
SelfTestCommand = new AsyncRelayCommand(SelfTestAsync, () => !_isDetecting && !_isTesting && Encoders.Any(e => e.Row.CanSelfTest));
|
||||
ClearCacheCommand = new AsyncRelayCommand(ClearCacheAsync);
|
||||
OpenDataFolderCommand = new RelayCommand(() => ShellActions.Reveal(DataFolder));
|
||||
OpenLogsCommand = new RelayCommand(() => ShellActions.Reveal(LogsFolder));
|
||||
ExportDiagnosticsCommand = new AsyncRelayCommand(ExportDiagnosticsAsync);
|
||||
BackupDatabaseCommand = new AsyncRelayCommand(BackupDatabaseAsync, () => Shell.Services.Database is not null);
|
||||
ResetSectionCommand = new RelayCommand(ResetSection);
|
||||
ExportSettingsCommand = new AsyncRelayCommand(ExportSettingsAsync);
|
||||
ImportSettingsCommand = new AsyncRelayCommand(ImportSettingsAsync);
|
||||
Loc.CultureChanged += OnCultureChanged;
|
||||
UpdatePreview();
|
||||
UpdateArchiveFree();
|
||||
}
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
public IReadOnlyList<SettingsPageItem> AllPages { get; }
|
||||
|
||||
// ---------------- Navigation ----------------
|
||||
|
||||
public ICommand SelectPageCommand { get; }
|
||||
|
||||
public SettingsPage Page
|
||||
{
|
||||
get => _page;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _page, value)) return;
|
||||
OnPropertyChanged(nameof(SelectedPageItem));
|
||||
OnPropertyChanged(nameof(PageTitle));
|
||||
if (value == SettingsPage.Rendering && Encoders.Count == 0 && !_isDetecting) _ = DetectEncodersAsync();
|
||||
if (value == SettingsPage.Storage) _ = UpdateCacheUsageAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public SettingsPageItem? SelectedPageItem
|
||||
{
|
||||
get => AllPages.First(p => p.Page == _page);
|
||||
set
|
||||
{
|
||||
if (value is not null) Page = value.Page;
|
||||
}
|
||||
}
|
||||
|
||||
public string PageTitle => Loc.L("Settings.Page." + _page);
|
||||
|
||||
/// <summary>Filters the section list.</summary>
|
||||
public string SearchText
|
||||
{
|
||||
get => _searchText;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _searchText, value ?? string.Empty)) return;
|
||||
var text = _searchText.Trim();
|
||||
VisiblePages = text.Length == 0 ? AllPages : [.. AllPages.Where(p => p.Matches(text))];
|
||||
if (VisiblePages.Count > 0 && VisiblePages.All(p => p.Page != _page)) Page = VisiblePages[0].Page;
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsPageItem> VisiblePages
|
||||
{
|
||||
get => _visiblePages;
|
||||
private set => Set(ref _visiblePages, value);
|
||||
}
|
||||
|
||||
// ---------------- General ----------------
|
||||
|
||||
public IReadOnlyList<LanguageOption> Languages => LanguageCatalog.Available;
|
||||
|
||||
public LanguageOption SelectedLanguage
|
||||
{
|
||||
get => LanguageCatalog.Match(Loc.Culture);
|
||||
set
|
||||
{
|
||||
if (value is null || value == SelectedLanguage) return;
|
||||
_s.Language = value.Code;
|
||||
UiLanguage.Apply(value.Code);
|
||||
Save();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsDarkTheme
|
||||
{
|
||||
get => _s.Theme == AppTheme.Dark;
|
||||
set
|
||||
{
|
||||
if (value) ApplyTheme(AppTheme.Dark);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsLightTheme
|
||||
{
|
||||
get => _s.Theme == AppTheme.Light;
|
||||
set
|
||||
{
|
||||
if (value) ApplyTheme(AppTheme.Light);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsSystemTheme
|
||||
{
|
||||
get => _s.Theme == AppTheme.System;
|
||||
set
|
||||
{
|
||||
if (value) ApplyTheme(AppTheme.System);
|
||||
}
|
||||
}
|
||||
|
||||
public bool UsageCounts
|
||||
{
|
||||
get => _s.AnonymousUsageCounts;
|
||||
set
|
||||
{
|
||||
if (_s.AnonymousUsageCounts == value) return;
|
||||
_s.AnonymousUsageCounts = value;
|
||||
Save();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- Archive ----------------
|
||||
|
||||
public EditableField ArchiveRoot { get; }
|
||||
public EditableField FolderTemplate { get; }
|
||||
public EditableField FileTemplate { get; }
|
||||
public ICommand BrowseArchiveCommand { get; }
|
||||
|
||||
/// <summary>"1.8 TB free".</summary>
|
||||
public string? ArchiveFreeText
|
||||
{
|
||||
get => _archiveFreeText;
|
||||
private set => Set(ref _archiveFreeText, value);
|
||||
}
|
||||
|
||||
/// <summary>The first three names the templates produce (live while typing).</summary>
|
||||
public IReadOnlyList<string> PreviewNames
|
||||
{
|
||||
get => _previewNames;
|
||||
private set => Set(ref _previewNames, value);
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<int>> ProxySizes =>
|
||||
[
|
||||
new(1280, "1280"),
|
||||
new(1920, "1920"),
|
||||
new(2560, "2560"),
|
||||
new(0, Loc.L("Settings.Archive.FullSize")),
|
||||
];
|
||||
|
||||
public SettingsOption<int> SelectedProxySize
|
||||
{
|
||||
get => ProxySizes.FirstOrDefault(p => p.Value == _s.ProxyLongEdge) ?? ProxySizes[1];
|
||||
set
|
||||
{
|
||||
if (value is null || value.Value == _s.ProxyLongEdge) return;
|
||||
_s.ProxyLongEdge = value.Value;
|
||||
Save();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- Rendering ----------------
|
||||
|
||||
public IReadOnlyList<SettingsOption<QualityProfile>> Qualities =>
|
||||
[.. Enum.GetValues<QualityProfile>().Select(q => new SettingsOption<QualityProfile>(q, Loc.L("Settings.Rendering.Quality." + q)))];
|
||||
|
||||
public SettingsOption<QualityProfile> SelectedQuality
|
||||
{
|
||||
get => Qualities.First(q => q.Value == _s.Quality);
|
||||
set
|
||||
{
|
||||
if (value is null || value.Value == _s.Quality) return;
|
||||
_s.Quality = value.Value;
|
||||
Save();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Installed memory in GB (rounded).</summary>
|
||||
public int InstalledGb { get; }
|
||||
|
||||
public int MemoryMinimum => 2;
|
||||
|
||||
public int MemoryMaximum => Math.Max(MemoryMinimum, InstalledGb - 2);
|
||||
|
||||
/// <summary>Auto: a quarter of installed memory.</summary>
|
||||
public int MemoryAuto => Math.Clamp(InstalledGb / 4, MemoryMinimum, MemoryMaximum);
|
||||
|
||||
public double MemoryBudget
|
||||
{
|
||||
get => _s.MemoryBudgetGb ?? MemoryAuto;
|
||||
set
|
||||
{
|
||||
var gb = (int)Math.Round(Math.Clamp(value, MemoryMinimum, MemoryMaximum));
|
||||
int? stored = gb == MemoryAuto ? null : gb;
|
||||
if (stored == _s.MemoryBudgetGb) return;
|
||||
_s.MemoryBudgetGb = stored;
|
||||
Save();
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(MemoryText));
|
||||
OnPropertyChanged(nameof(IsMemoryAuto));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsMemoryAuto => _s.MemoryBudgetGb is null;
|
||||
|
||||
public string MemoryText => Loc.L("Settings.Rendering.Gb", (int)MemoryBudget);
|
||||
|
||||
public string InstalledText => Loc.L("Settings.Rendering.Installed", InstalledGb);
|
||||
|
||||
public string MemoryAutoText => Loc.L("Settings.Rendering.AutoValue", MemoryAuto);
|
||||
|
||||
public ICommand ResetMemoryCommand { get; }
|
||||
|
||||
public EditableField Parallelism { get; }
|
||||
|
||||
public int LogicalCores => Environment.ProcessorCount;
|
||||
|
||||
/// <summary>Auto: cores minus four so the UI stays responsive.</summary>
|
||||
public int ParallelismAuto => Math.Max(1, LogicalCores - 4);
|
||||
|
||||
private int EffectiveParallelism => _s.Parallelism ?? ParallelismAuto;
|
||||
|
||||
public bool IsParallelismAuto => _s.Parallelism is null;
|
||||
|
||||
public string CoresText => Loc.L("Settings.Rendering.Cores", LogicalCores);
|
||||
|
||||
public string ParallelismAutoText => Loc.L("Settings.Rendering.AutoValue", ParallelismAuto);
|
||||
|
||||
public ICommand ResetParallelismCommand { get; }
|
||||
|
||||
public bool BackgroundPriority
|
||||
{
|
||||
get => _s.BackgroundPriority;
|
||||
set
|
||||
{
|
||||
if (_s.BackgroundPriority == value) return;
|
||||
_s.BackgroundPriority = value;
|
||||
Save();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsPreferHardware
|
||||
{
|
||||
get => _s.HardwareEncoding == HardwarePreference.PreferHardware;
|
||||
set => SetHardware(value, HardwarePreference.PreferHardware);
|
||||
}
|
||||
|
||||
public bool IsSoftwareOnly
|
||||
{
|
||||
get => _s.HardwareEncoding == HardwarePreference.SoftwareOnly;
|
||||
set => SetHardware(value, HardwarePreference.SoftwareOnly);
|
||||
}
|
||||
|
||||
public bool IsHardwareForPreviews
|
||||
{
|
||||
get => _s.HardwareEncoding == HardwarePreference.HardwareForPreviews;
|
||||
set => SetHardware(value, HardwarePreference.HardwareForPreviews);
|
||||
}
|
||||
|
||||
public ObservableCollection<EncoderRowViewModel> Encoders { get; } = [];
|
||||
|
||||
/// <summary>"NVIDIA GeForce RTX 4070 · 3 encoders".</summary>
|
||||
public string? AdapterText
|
||||
{
|
||||
get => _adapterText;
|
||||
private set => Set(ref _adapterText, value);
|
||||
}
|
||||
|
||||
public bool IsDetecting
|
||||
{
|
||||
get => _isDetecting;
|
||||
private set => Set(ref _isDetecting, value);
|
||||
}
|
||||
|
||||
public ICommand RedetectCommand { get; }
|
||||
public ICommand SelfTestCommand { get; }
|
||||
|
||||
// ---------------- Storage ----------------
|
||||
|
||||
public EditableField CacheFolder { get; }
|
||||
public EditableField ThumbnailMemory { get; }
|
||||
public EditableField CacheLimit { get; }
|
||||
public ICommand BrowseCacheCommand { get; }
|
||||
public ICommand ClearCacheCommand { get; }
|
||||
|
||||
/// <summary>"1.4 GB used · 612 GB free".</summary>
|
||||
public string? CacheUsageText
|
||||
{
|
||||
get => _cacheUsageText;
|
||||
private set => Set(ref _cacheUsageText, value);
|
||||
}
|
||||
|
||||
// ---------------- Server ----------------
|
||||
|
||||
public EditableField DefaultServer { get; }
|
||||
|
||||
public bool RenderNodeOptIn
|
||||
{
|
||||
get => _s.RenderNodeOptIn;
|
||||
set
|
||||
{
|
||||
if (_s.RenderNodeOptIn == value) return;
|
||||
_s.RenderNodeOptIn = value;
|
||||
Save();
|
||||
OnPropertyChanged();
|
||||
Shell.Server.Refresh();
|
||||
}
|
||||
}
|
||||
|
||||
public ObservableCollection<TrustedCertificateRow> Certificates { get; } = [];
|
||||
|
||||
public bool HasCertificates => Certificates.Count > 0;
|
||||
|
||||
// ---------------- Updates ----------------
|
||||
|
||||
public bool CheckForUpdates
|
||||
{
|
||||
get => _s.CheckForUpdates;
|
||||
set
|
||||
{
|
||||
if (_s.CheckForUpdates == value) return;
|
||||
_s.CheckForUpdates = value;
|
||||
Save();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- Advanced ----------------
|
||||
|
||||
public string DataFolder => Shell.Services.Environment.DataDirectory;
|
||||
public string LogsFolder => Shell.Services.Environment.LogDirectory;
|
||||
public string PortableText => Loc.L(Shell.Services.Environment.IsPortable ? "Settings.Advanced.PortableOn" : "Settings.Advanced.PortableOff");
|
||||
public ICommand OpenDataFolderCommand { get; }
|
||||
public ICommand OpenLogsCommand { get; }
|
||||
public ICommand ExportDiagnosticsCommand { get; }
|
||||
public ICommand BackupDatabaseCommand { get; }
|
||||
|
||||
// ---------------- Footer ----------------
|
||||
|
||||
public ICommand ResetSectionCommand { get; }
|
||||
public ICommand ExportSettingsCommand { get; }
|
||||
public ICommand ImportSettingsCommand { get; }
|
||||
|
||||
/// <summary>Loads what needs the services (certificates, cache usage).</summary>
|
||||
public void Attach()
|
||||
{
|
||||
try
|
||||
{
|
||||
CacheStore.Prepare(Shell.Services.Environment.CacheDirectory);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Log.Warning("settings", "Cache folder not prepared", ex);
|
||||
}
|
||||
LoadCertificates();
|
||||
Shell.Services.Server.PropertyChanged += (_, _) => LoadCertificates();
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
Loc.CultureChanged -= OnCultureChanged;
|
||||
_selfTest?.Cancel();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
// ---------------- Implementation ----------------
|
||||
|
||||
private void Save() => Shell.Services.SaveSettings();
|
||||
|
||||
private void ApplyTheme(AppTheme theme)
|
||||
{
|
||||
_s.Theme = theme;
|
||||
ThemeManager.Apply(theme);
|
||||
Save();
|
||||
OnPropertyChanged(nameof(IsDarkTheme));
|
||||
OnPropertyChanged(nameof(IsLightTheme));
|
||||
OnPropertyChanged(nameof(IsSystemTheme));
|
||||
}
|
||||
|
||||
private void SetHardware(bool value, HardwarePreference preference)
|
||||
{
|
||||
if (!value || _s.HardwareEncoding == preference) return;
|
||||
_s.HardwareEncoding = preference;
|
||||
Save();
|
||||
OnPropertyChanged(nameof(IsPreferHardware));
|
||||
OnPropertyChanged(nameof(IsSoftwareOnly));
|
||||
OnPropertyChanged(nameof(IsHardwareForPreviews));
|
||||
}
|
||||
|
||||
private void UpdatePreview() => PreviewNames = NamingPreview.FirstNames(FolderTemplate.Text, FileTemplate.Text);
|
||||
|
||||
private void UpdateArchiveFree()
|
||||
{
|
||||
var path = _s.LastArchivePath;
|
||||
ArchiveFreeText = ArchiveLocations.FreeSpace(path) is { } free ? Loc.L("Settings.Archive.Free", Formatting.Bytes(free)) : null;
|
||||
}
|
||||
|
||||
private string? ValidateParallelism(string text) => ValidateInt(text, 1, Math.Max(1, LogicalCores * 2));
|
||||
|
||||
private static string? ValidateInt(string text, int min, int max) =>
|
||||
int.TryParse(text.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture, out var n) && n >= min && n <= max
|
||||
? null
|
||||
: Loc.L("Errors.Number.Range", min.ToString("N0", Loc.Culture), max.ToString("N0", Loc.Culture));
|
||||
|
||||
private void Browse(EditableField field, string titleKey)
|
||||
{
|
||||
var folder = Shell.Services.Dialogs.PickFolder(Loc.L(titleKey), field.Value.Length > 0 ? field.Value : null);
|
||||
if (folder is null) return;
|
||||
field.Text = folder;
|
||||
field.Commit();
|
||||
}
|
||||
|
||||
/// <summary>Lists the encoders again (Re-detect).</summary>
|
||||
public async Task DetectEncodersAsync()
|
||||
{
|
||||
IsDetecting = true;
|
||||
try
|
||||
{
|
||||
var inventory = Shell.Services.Encoders;
|
||||
var (adapter, rows) = await Task.Run(() => (inventory.Adapter(), inventory.Detect()));
|
||||
Encoders.Clear();
|
||||
foreach (var row in rows) Encoders.Add(new EncoderRowViewModel(row));
|
||||
var hardware = rows.Count(r => r.Hardware);
|
||||
AdapterText = string.Join(" · ", new[] { adapter, Loc.Plural("Settings.Rendering.EncoderCount", rows.Count(r => r.Source == EncoderSource.MediaFoundation)) }
|
||||
.Where(s => !string.IsNullOrEmpty(s)));
|
||||
Log.Info("settings", $"{rows.Count} encoder(s), {hardware} hardware");
|
||||
}
|
||||
catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or PlatformNotSupportedException or DllNotFoundException)
|
||||
{
|
||||
Log.Warning("settings", "Encoders could not be detected", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsDetecting = false;
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Encodes the synthetic test clip with every encoder in turn (Run self-test).</summary>
|
||||
public async Task SelfTestAsync()
|
||||
{
|
||||
_isTesting = true;
|
||||
_selfTest = new CancellationTokenSource();
|
||||
try
|
||||
{
|
||||
foreach (var row in Encoders.Where(r => r.Row.CanSelfTest).ToList())
|
||||
{
|
||||
row.IsTesting = true;
|
||||
try
|
||||
{
|
||||
row.Result = await Shell.Services.Encoders.SelfTestAsync(row.Row, _selfTest.Token);
|
||||
}
|
||||
finally
|
||||
{
|
||||
row.IsTesting = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isTesting = false;
|
||||
_selfTest.Dispose();
|
||||
_selfTest = null;
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task UpdateCacheUsageAsync()
|
||||
{
|
||||
var folder = CacheStore.Folder(Shell.Services.Environment, _s);
|
||||
var (used, free) = await Task.Run(() => (CacheStore.Size(folder), ArchiveLocations.FreeSpace(folder)));
|
||||
CacheUsageText = free is { } f
|
||||
? Loc.L("Settings.Storage.Usage", Formatting.Bytes(used), Formatting.Bytes(f))
|
||||
: Loc.L("Settings.Storage.Used", Formatting.Bytes(used));
|
||||
}
|
||||
|
||||
private async Task ClearCacheAsync()
|
||||
{
|
||||
var folder = CacheStore.Folder(Shell.Services.Environment, _s);
|
||||
var confirmed = Shell.Services.Dialogs.Confirm(new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Settings.Storage.ClearTitle"),
|
||||
Message = Loc.L("Settings.Storage.ClearMessage"),
|
||||
Detail = folder,
|
||||
DetailToolTip = Loc.L("Tooltips.Settings.CacheFolder"),
|
||||
SafeText = Loc.L("Settings.Storage.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Settings.KeepCache"),
|
||||
ActionText = Loc.L("Settings.Storage.Clear"),
|
||||
ActionToolTip = Loc.L("Tooltips.Settings.ClearCache"),
|
||||
IsDestructive = true,
|
||||
});
|
||||
if (!confirmed) return;
|
||||
Shell.Services.Thumbnails?.Clear();
|
||||
if (!CacheStore.IsOwned(folder))
|
||||
{
|
||||
Shell.Notify(Loc.L("Settings.Storage.NotOwned"));
|
||||
return;
|
||||
}
|
||||
var freed = await Task.Run(() => CacheStore.Clear(folder));
|
||||
Shell.Notify(Loc.L("Settings.Storage.Cleared", Formatting.Bytes(freed)));
|
||||
await UpdateCacheUsageAsync();
|
||||
}
|
||||
|
||||
private async Task ExportDiagnosticsAsync()
|
||||
{
|
||||
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Advanced.DiagnosticsTitle"));
|
||||
if (folder is null) return;
|
||||
var extra = Encoders.Select(e => $"Encoder {e.Codec} {e.Row.DisplayName} hardware={e.Row.Hardware} selftest={e.ResultText}");
|
||||
var path = await DiagnosticsBundle.CreateAsync(Shell.Services.Environment, folder, extra.ToList());
|
||||
Shell.Notify(Loc.L("Settings.Advanced.DiagnosticsDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
|
||||
}
|
||||
|
||||
private async Task BackupDatabaseAsync()
|
||||
{
|
||||
if (Shell.Services.Database is not { } db) return;
|
||||
try
|
||||
{
|
||||
var path = await db.BackupAsync(Shell.Services.Environment.BackupDirectory);
|
||||
Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or NotSupportedException)
|
||||
{
|
||||
Shell.ReportError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void ResetSection()
|
||||
{
|
||||
var defaults = new AppSettings();
|
||||
switch (_page)
|
||||
{
|
||||
case SettingsPage.General:
|
||||
_s.AnonymousUsageCounts = defaults.AnonymousUsageCounts;
|
||||
ApplyTheme(defaults.Theme);
|
||||
_s.Language = null;
|
||||
UiLanguage.Apply(null);
|
||||
break;
|
||||
case SettingsPage.Archive:
|
||||
_s.FolderTemplate = defaults.FolderTemplate;
|
||||
_s.FileTemplate = defaults.FileTemplate;
|
||||
_s.ProxyLongEdge = defaults.ProxyLongEdge;
|
||||
FolderTemplate.Load(_s.FolderTemplate);
|
||||
FileTemplate.Load(_s.FileTemplate);
|
||||
UpdatePreview();
|
||||
break;
|
||||
case SettingsPage.Rendering:
|
||||
_s.Quality = defaults.Quality;
|
||||
_s.MemoryBudgetGb = null;
|
||||
_s.Parallelism = null;
|
||||
_s.BackgroundPriority = defaults.BackgroundPriority;
|
||||
_s.HardwareEncoding = defaults.HardwareEncoding;
|
||||
Parallelism.Load(ParallelismAuto.ToString(CultureInfo.CurrentCulture));
|
||||
break;
|
||||
case SettingsPage.Storage:
|
||||
_s.CacheFolder = null;
|
||||
_s.ThumbnailMemoryItems = defaults.ThumbnailMemoryItems;
|
||||
_s.CacheLimitGb = defaults.CacheLimitGb;
|
||||
CacheFolder.Load(CacheStore.Folder(Shell.Services.Environment, _s));
|
||||
ThumbnailMemory.Load(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture));
|
||||
CacheLimit.Load(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture));
|
||||
if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
|
||||
break;
|
||||
case SettingsPage.Server:
|
||||
_s.RenderNodeOptIn = defaults.RenderNodeOptIn;
|
||||
break;
|
||||
case SettingsPage.Updates:
|
||||
_s.CheckForUpdates = defaults.CheckForUpdates;
|
||||
break;
|
||||
case SettingsPage.Advanced:
|
||||
break;
|
||||
}
|
||||
Save();
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
private async Task ExportSettingsAsync()
|
||||
{
|
||||
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Export.Title"));
|
||||
if (folder is null) return;
|
||||
var copy = _s.Clone();
|
||||
// Secrets and machine-bound values stay on this PC.
|
||||
copy.ProtectedToken = null;
|
||||
copy.Window = null;
|
||||
var path = Path.Combine(folder, $"Titano settings {DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.json");
|
||||
await Task.Run(() => AtomicFile.WriteAllText(path, copy.ToJson()));
|
||||
Shell.Notify(Loc.L("Settings.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
|
||||
}
|
||||
|
||||
private async Task ImportSettingsAsync()
|
||||
{
|
||||
var file = Shell.Services.Dialogs.PickJsonFile(Loc.L("Settings.Import.Title"));
|
||||
if (file is null) return;
|
||||
AppSettings? imported;
|
||||
try
|
||||
{
|
||||
imported = AppSettings.Parse(await File.ReadAllTextAsync(file));
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("settings", $"Settings file {file} not imported", ex);
|
||||
imported = null;
|
||||
}
|
||||
if (imported is null)
|
||||
{
|
||||
Shell.Notify(Loc.L("Errors.Settings.Import"));
|
||||
return;
|
||||
}
|
||||
// Everything but the session, the window and the first-run flag.
|
||||
imported.ProtectedToken = _s.ProtectedToken;
|
||||
imported.ServerUrl = _s.ServerUrl;
|
||||
imported.Window = _s.Window;
|
||||
imported.FirstRunCompleted = _s.FirstRunCompleted;
|
||||
foreach (var property in typeof(AppSettings).GetProperties().Where(p => p.CanRead && p.CanWrite))
|
||||
property.SetValue(_s, property.GetValue(imported));
|
||||
Save();
|
||||
ThemeManager.Apply(_s.Theme);
|
||||
UiLanguage.Apply(_s.Language);
|
||||
ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty);
|
||||
FolderTemplate.Load(_s.FolderTemplate);
|
||||
FileTemplate.Load(_s.FileTemplate);
|
||||
Parallelism.Load(EffectiveParallelism.ToString(CultureInfo.CurrentCulture));
|
||||
CacheFolder.Load(CacheStore.Folder(Shell.Services.Environment, _s));
|
||||
ThumbnailMemory.Load(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture));
|
||||
CacheLimit.Load(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture));
|
||||
DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
|
||||
UpdatePreview();
|
||||
LoadCertificates();
|
||||
OnAllPropertiesChanged();
|
||||
Shell.Notify(Loc.L("Settings.Import.Done"));
|
||||
}
|
||||
|
||||
private void LoadCertificates()
|
||||
{
|
||||
Certificates.Clear();
|
||||
foreach (var certificate in _s.TrustedCertificates.OrderByDescending(c => c.TrustedAt))
|
||||
{
|
||||
Certificates.Add(new TrustedCertificateRow(certificate, new RelayCommand(() =>
|
||||
{
|
||||
Shell.Services.Server.Forget(certificate.Fingerprint);
|
||||
LoadCertificates();
|
||||
})));
|
||||
}
|
||||
OnPropertyChanged(nameof(HasCertificates));
|
||||
}
|
||||
|
||||
private void OnCultureChanged(object? sender, EventArgs e)
|
||||
{
|
||||
foreach (var page in AllPages) page.Refresh();
|
||||
foreach (var row in Encoders) row.Refresh();
|
||||
ArchiveRoot.Refresh();
|
||||
FolderTemplate.Refresh();
|
||||
FileTemplate.Refresh();
|
||||
Parallelism.Refresh();
|
||||
CacheFolder.Refresh();
|
||||
ThumbnailMemory.Refresh();
|
||||
CacheLimit.Refresh();
|
||||
DefaultServer.Refresh();
|
||||
UpdateArchiveFree();
|
||||
LoadCertificates();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<UserControl x:Class="Titano.App.Sections.WelcomeView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
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">
|
||||
<UserControl.Resources>
|
||||
<!-- Welcome.html choice: 68 px card, highlighted = accent border with the AccentSelected glow. -->
|
||||
<Style x:Key="RadioButton.Choice" TargetType="RadioButton">
|
||||
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Ring}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
<Setter Property="Height" Value="68" />
|
||||
<Setter Property="Margin" Value="0,0,0,10" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="RadioButton">
|
||||
<Grid>
|
||||
<Border x:Name="Glow" Margin="-3" CornerRadius="11" BorderThickness="3" BorderBrush="{DynamicResource Brush.AccentSelected}" Visibility="Collapsed" />
|
||||
<Border x:Name="Bd" Background="{DynamicResource Brush.Card}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="1"
|
||||
CornerRadius="{StaticResource Radius.Card}" Padding="16,0">
|
||||
<ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Stretch" />
|
||||
</Border>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.CardHover}" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter TargetName="Glow" Property="Visibility" Value="Visible" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
<Style x:Key="Text.ChoiceTitle" TargetType="TextBlock">
|
||||
<Setter Property="FontSize" Value="14" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
|
||||
</Style>
|
||||
<Style x:Key="Text.ChoiceDetail" TargetType="TextBlock">
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
<Setter Property="Margin" Value="0,3,0,0" />
|
||||
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Border Width="640" Background="{DynamicResource Brush.Surface}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="1"
|
||||
CornerRadius="{StaticResource Radius.Dialog}" Padding="32,28" Effect="{StaticResource Shadow.Popup}">
|
||||
<StackPanel>
|
||||
<DockPanel LastChildFill="True">
|
||||
<ComboBox DockPanel.Dock="Right" VerticalAlignment="Top" MinWidth="120" ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}"
|
||||
DisplayMemberPath="Name" ToolTip="{l:Loc Tooltips.Welcome.Language}" AutomationProperties.Name="{l:Loc Settings.General.Language}" />
|
||||
<ui:BrandMarkIcon Width="56" Height="56" ShowPlate="True" />
|
||||
<StackPanel Margin="16,0,16,0" VerticalAlignment="Center">
|
||||
<TextBlock Text="{l:Loc Shell.Welcome.Title}" FontSize="20" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{l:Loc Shell.Welcome.Question}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,4,0,0" TextTrimming="CharacterEllipsis" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
|
||||
<StackPanel Margin="0,20,0,0">
|
||||
<!-- Create a local archive -->
|
||||
<RadioButton Style="{StaticResource RadioButton.Choice}" GroupName="Welcome" IsChecked="{Binding IsLocal}" ToolTip="{l:Loc Tooltips.Welcome.Local}"
|
||||
AutomationProperties.Name="{l:Loc Shell.Welcome.Local}">
|
||||
<DockPanel>
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Subtle}" Content="{l:Loc Shell.Welcome.Change}" Command="{Binding ChangeRootCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Welcome.Change}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<ui:Icon Glyph="{StaticResource Icon.Folder}" Size="24" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
|
||||
<StackPanel Margin="14,0,8,0" VerticalAlignment="Center">
|
||||
<TextBlock Style="{StaticResource Text.ChoiceTitle}" Text="{l:Loc Shell.Welcome.Local}" />
|
||||
<TextBlock Style="{StaticResource Text.ChoiceDetail}" Text="{Binding LocalDetail}" Typography.NumeralAlignment="Tabular" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</RadioButton>
|
||||
|
||||
<!-- Adopt an existing folder -->
|
||||
<RadioButton Style="{StaticResource RadioButton.Choice}" GroupName="Welcome" IsChecked="{Binding IsAdopt}" ToolTip="{l:Loc Tooltips.Welcome.Adopt}"
|
||||
AutomationProperties.Name="{l:Loc Shell.Welcome.Adopt}">
|
||||
<DockPanel>
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Subtle}" Content="{l:Loc Shell.Welcome.Choose}" Command="{Binding ChooseAdoptCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Welcome.Choose}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<ui:Icon Glyph="{StaticResource Icon.Archive}" Size="24" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" />
|
||||
<StackPanel Margin="14,0,8,0" VerticalAlignment="Center">
|
||||
<TextBlock Style="{StaticResource Text.ChoiceTitle}" Text="{l:Loc Shell.Welcome.Adopt}" />
|
||||
<TextBlock Style="{StaticResource Text.ChoiceDetail}" Text="{Binding AdoptDetail}" Visibility="{Binding HasAdoptDetail, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</RadioButton>
|
||||
|
||||
<!-- Connect to a server -->
|
||||
<RadioButton Style="{StaticResource RadioButton.Choice}" GroupName="Welcome" IsChecked="{Binding IsServer}" ToolTip="{l:Loc Tooltips.Welcome.Server}"
|
||||
AutomationProperties.Name="{l:Loc Shell.Welcome.Server}" Margin="0">
|
||||
<DockPanel>
|
||||
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Online" Text="{l:Loc Shell.Welcome.Found}" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Welcome.Found}"
|
||||
Visibility="{Binding IsServerDiscovered, Converter={StaticResource BoolToVisibility}}" />
|
||||
<ui:Icon Glyph="{StaticResource Icon.Server}" Size="24" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" />
|
||||
<StackPanel Margin="14,0,8,0" VerticalAlignment="Center">
|
||||
<TextBlock Style="{StaticResource Text.ChoiceTitle}" Text="{l:Loc Shell.Welcome.Server}" />
|
||||
<TextBlock Style="{StaticResource Text.ChoiceDetail}" Text="{Binding ServerDetail}" Visibility="{Binding HasServerDetail, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</RadioButton>
|
||||
</StackPanel>
|
||||
|
||||
<DockPanel Margin="0,20,0,0" LastChildFill="False">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Height="36" Padding="22,0" Content="{l:Loc Shell.Welcome.Continue}"
|
||||
Command="{Binding ContinueCommand}" ToolTip="{l:Loc Tooltips.Welcome.Continue}" IsDefault="True" />
|
||||
<CheckBox Content="{l:Loc Shell.Welcome.Consent}" IsChecked="{Binding UsageCounts}" ToolTip="{l:Loc Tooltips.Settings.UsageCounts}" VerticalAlignment="Center"
|
||||
Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,8 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
public partial class WelcomeView : UserControl
|
||||
{
|
||||
public WelcomeView() => InitializeComponent();
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
using System.Collections.Specialized;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Server;
|
||||
using Titano.App.Settings;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>Where the time-lapses live (first run).</summary>
|
||||
public enum WelcomeChoice
|
||||
{
|
||||
LocalArchive,
|
||||
AdoptFolder,
|
||||
Server,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// First run (BRIEF §12.1, Welcome.html): create a local archive, adopt an existing folder or connect to a server,
|
||||
/// plus the language and the anonymous-usage consent. Shown once; the archive actions go through
|
||||
/// <see cref="IArchiveSetup"/>.
|
||||
/// </summary>
|
||||
public sealed class WelcomeViewModel : LocalizedViewModel
|
||||
{
|
||||
private readonly ShellViewModel _shell;
|
||||
private WelcomeChoice _choice = WelcomeChoice.LocalArchive;
|
||||
private string _localRoot;
|
||||
private string? _adoptFolder;
|
||||
private bool _isBusy;
|
||||
|
||||
public WelcomeViewModel(ShellViewModel shell)
|
||||
{
|
||||
_shell = shell;
|
||||
_localRoot = shell.Services.Settings.LastArchivePath ?? ArchiveLocations.SuggestRoot();
|
||||
ChooseCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is WelcomeChoice choice) Choice = choice;
|
||||
else if (p is string name && Enum.TryParse<WelcomeChoice>(name, out var parsed)) Choice = parsed;
|
||||
});
|
||||
ChangeRootCommand = new RelayCommand(ChangeRoot);
|
||||
ChooseAdoptCommand = new RelayCommand(() => PickAdoptFolder());
|
||||
ContinueCommand = new AsyncRelayCommand(ContinueAsync, () => !_isBusy);
|
||||
shell.Services.Server.Discovered.CollectionChanged += OnDiscovered;
|
||||
if (!shell.Services.Environment.IsCapture) shell.Services.Server.StartDiscovery();
|
||||
}
|
||||
|
||||
public ICommand ChooseCommand { get; }
|
||||
public ICommand ChangeRootCommand { get; }
|
||||
public ICommand ChooseAdoptCommand { get; }
|
||||
public ICommand ContinueCommand { get; }
|
||||
|
||||
public WelcomeChoice Choice
|
||||
{
|
||||
get => _choice;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _choice, value)) return;
|
||||
OnPropertyChanged(nameof(IsLocal));
|
||||
OnPropertyChanged(nameof(IsAdopt));
|
||||
OnPropertyChanged(nameof(IsServer));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsLocal
|
||||
{
|
||||
get => _choice == WelcomeChoice.LocalArchive;
|
||||
set
|
||||
{
|
||||
if (value) Choice = WelcomeChoice.LocalArchive;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsAdopt
|
||||
{
|
||||
get => _choice == WelcomeChoice.AdoptFolder;
|
||||
set
|
||||
{
|
||||
if (value) Choice = WelcomeChoice.AdoptFolder;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsServer
|
||||
{
|
||||
get => _choice == WelcomeChoice.Server;
|
||||
set
|
||||
{
|
||||
if (value) Choice = WelcomeChoice.Server;
|
||||
}
|
||||
}
|
||||
|
||||
public string LocalRoot
|
||||
{
|
||||
get => _localRoot;
|
||||
private set
|
||||
{
|
||||
if (Set(ref _localRoot, value)) OnPropertyChanged(nameof(LocalDetail));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"D:\TitanoArchive · 1.8 TB free".</summary>
|
||||
public string LocalDetail => ArchiveLocations.FreeSpace(_localRoot) is { } free
|
||||
? Loc.L("Shell.Welcome.Local.Detail", _localRoot, Formatting.Bytes(free))
|
||||
: _localRoot;
|
||||
|
||||
/// <summary>The chosen folder to adopt; null until picked.</summary>
|
||||
public string? AdoptDetail => _adoptFolder;
|
||||
|
||||
public bool HasAdoptDetail => _adoptFolder is not null;
|
||||
|
||||
/// <summary>The first server announced on the LAN (or the saved one).</summary>
|
||||
public DiscoveredServer? FoundServer =>
|
||||
_shell.Services.Server.Discovered.FirstOrDefault()
|
||||
?? (_shell.Services.Settings.ServerUrl is { } saved ? new DiscoveredServer(saved, saved) : null);
|
||||
|
||||
/// <summary>"Studio NAS on this network · https://nas.local:8443".</summary>
|
||||
public string? ServerDetail => FoundServer is { } s
|
||||
? s.Name == s.Address ? s.Address : Loc.L("Shell.Welcome.Server.Found", s.Name, s.Address)
|
||||
: null;
|
||||
|
||||
public bool HasServerDetail => ServerDetail is not null;
|
||||
|
||||
/// <summary>A server was heard on the LAN (the green dot).</summary>
|
||||
public bool IsServerDiscovered => _shell.Services.Server.Discovered.Count > 0;
|
||||
|
||||
public IReadOnlyList<LanguageOption> Languages => LanguageCatalog.Available;
|
||||
|
||||
public LanguageOption SelectedLanguage
|
||||
{
|
||||
get => LanguageCatalog.Match(Loc.Culture);
|
||||
set
|
||||
{
|
||||
if (value is null || value == SelectedLanguage) return;
|
||||
_shell.Services.Settings.Language = value.Code;
|
||||
UiLanguage.Apply(value.Code);
|
||||
_shell.Services.SaveSettings();
|
||||
}
|
||||
}
|
||||
|
||||
public bool UsageCounts
|
||||
{
|
||||
get => _shell.Services.Settings.AnonymousUsageCounts;
|
||||
set
|
||||
{
|
||||
_shell.Services.Settings.AnonymousUsageCounts = value;
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsBusy
|
||||
{
|
||||
get => _isBusy;
|
||||
private set => Set(ref _isBusy, value);
|
||||
}
|
||||
|
||||
/// <summary>Sample state for screenshots: a server heard on the LAN.</summary>
|
||||
internal void ShowDiscovered(DiscoveredServer server)
|
||||
{
|
||||
if (!_shell.Services.Server.Discovered.Contains(server)) _shell.Services.Server.Discovered.Add(server);
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_shell.Services.Server.Discovered.CollectionChanged -= OnDiscovered;
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
private void OnDiscovered(object? sender, NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
OnPropertyChanged(nameof(FoundServer));
|
||||
OnPropertyChanged(nameof(ServerDetail));
|
||||
OnPropertyChanged(nameof(HasServerDetail));
|
||||
OnPropertyChanged(nameof(IsServerDiscovered));
|
||||
}
|
||||
|
||||
private void ChangeRoot()
|
||||
{
|
||||
var folder = _shell.Services.Dialogs.PickFolder(Loc.L("Shell.Welcome.Local.PickTitle"), LocalRoot);
|
||||
if (folder is null) return;
|
||||
LocalRoot = folder;
|
||||
Choice = WelcomeChoice.LocalArchive;
|
||||
}
|
||||
|
||||
private bool PickAdoptFolder()
|
||||
{
|
||||
var folder = _shell.Services.Dialogs.PickFolder(Loc.L("Library.Adopt.Title"));
|
||||
if (folder is null) return false;
|
||||
_adoptFolder = folder;
|
||||
OnPropertyChanged(nameof(AdoptDetail));
|
||||
OnPropertyChanged(nameof(HasAdoptDetail));
|
||||
Choice = WelcomeChoice.AdoptFolder;
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task ContinueAsync()
|
||||
{
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
switch (_choice)
|
||||
{
|
||||
case WelcomeChoice.LocalArchive:
|
||||
if (ArchiveLocations.Validate(LocalRoot) is { } problem)
|
||||
{
|
||||
_shell.Notify(problem);
|
||||
return;
|
||||
}
|
||||
await _shell.Services.ArchiveSetup.CreateAsync(LocalRoot);
|
||||
break;
|
||||
case WelcomeChoice.AdoptFolder:
|
||||
if (_adoptFolder is null && !PickAdoptFolder()) return;
|
||||
await _shell.Services.ArchiveSetup.AdoptAsync(_adoptFolder!);
|
||||
break;
|
||||
case WelcomeChoice.Server:
|
||||
if (FoundServer is { } server) _shell.Server.Address = server.Address;
|
||||
break;
|
||||
}
|
||||
_shell.Services.SaveSettings();
|
||||
_shell.CompleteWelcome();
|
||||
Log.Info("app", $"First run completed: {_choice}");
|
||||
if (_choice == WelcomeChoice.Server) _shell.Navigate(SectionKey.Server);
|
||||
else await _shell.Library.RefreshAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.App.Server;
|
||||
|
||||
/// <summary>The calls the connection makes; implemented over <see cref="TitanoClient"/>, faked in tests.</summary>
|
||||
public interface IServerApi : IDisposable
|
||||
{
|
||||
Uri BaseAddress { get; }
|
||||
|
||||
/// <summary>Bearer token sent with every request.</summary>
|
||||
string? Token { get; set; }
|
||||
|
||||
/// <summary>Throws <see cref="UntrustedCertificateException"/> while the certificate is neither valid nor trusted.</summary>
|
||||
Task<ServerInfo> GetInfoAsync(CancellationToken ct);
|
||||
|
||||
Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct);
|
||||
|
||||
Task<UserDto> MeAsync(CancellationToken ct);
|
||||
|
||||
Task LogoutAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Creates API clients pinned to the certificates the user trusts.</summary>
|
||||
public interface IServerApiFactory
|
||||
{
|
||||
IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints);
|
||||
}
|
||||
|
||||
/// <summary>Certificates trusted on first use (persisted in the settings).</summary>
|
||||
public interface ITrustStore
|
||||
{
|
||||
IReadOnlyCollection<string> Fingerprints { get; }
|
||||
|
||||
void Trust(string server, string fingerprint);
|
||||
}
|
||||
|
||||
/// <summary>Where the connection stands (BRIEF §12.7).</summary>
|
||||
public enum ConnectStep
|
||||
{
|
||||
/// <summary>Nothing started, or signed out.</summary>
|
||||
Idle,
|
||||
|
||||
/// <summary>Reading the server's identity (no credentials are sent).</summary>
|
||||
Probing,
|
||||
|
||||
/// <summary>The certificate is self-signed and unknown: the user must confirm its fingerprint first.</summary>
|
||||
AwaitingTrust,
|
||||
|
||||
/// <summary>The server is identified and trusted: the login form may send the password.</summary>
|
||||
AwaitingCredentials,
|
||||
|
||||
SigningIn,
|
||||
Connected,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>Why the last step failed.</summary>
|
||||
public enum ConnectError
|
||||
{
|
||||
None,
|
||||
InvalidAddress,
|
||||
Unreachable,
|
||||
NotTitano,
|
||||
Untrusted,
|
||||
BadCredentials,
|
||||
|
||||
/// <summary>A saved session was rejected (expired or revoked token); sign in again.</summary>
|
||||
SessionExpired,
|
||||
|
||||
/// <summary>The certificate differs from the trusted one; the saved session was dropped.</summary>
|
||||
CertificateChanged,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Trust-on-first-use connection state machine, mirroring the uploader: the server's identity is read first
|
||||
/// (<c>GET server/info</c>, which needs no credentials); a self-signed certificate that is not trusted yet stops the
|
||||
/// flow at <see cref="ConnectStep.AwaitingTrust"/> until the user confirms its fingerprint; only then can
|
||||
/// <see cref="SignInAsync"/> send the password. A saved token is restored the same way, and a changed certificate
|
||||
/// never reuses it. Not thread-safe; drive it from the UI.
|
||||
/// </summary>
|
||||
public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) : IDisposable
|
||||
{
|
||||
private IServerApi? _api;
|
||||
|
||||
public ConnectStep Step { get; private set; } = ConnectStep.Idle;
|
||||
public ConnectError Error { get; private set; }
|
||||
|
||||
/// <summary>Normalised API base ("https://nas.local:8443/").</summary>
|
||||
public Uri? Address { get; private set; }
|
||||
|
||||
/// <summary>The fingerprint waiting for the user's decision.</summary>
|
||||
public string? PendingFingerprint { get; private set; }
|
||||
|
||||
public ServerInfo? Info { get; private set; }
|
||||
public UserDto? User { get; private set; }
|
||||
|
||||
/// <summary>Round trip of the identity request.</summary>
|
||||
public TimeSpan? Latency { get; private set; }
|
||||
|
||||
/// <summary>The token of the signed-in session (store it encrypted).</summary>
|
||||
public string? Token => Step == ConnectStep.Connected ? _api?.Token : null;
|
||||
|
||||
/// <summary>The signed-in client, for the screens that talk to the server.</summary>
|
||||
public IServerApi? Api => Step == ConnectStep.Connected ? _api : null;
|
||||
|
||||
/// <summary>Raised after every step change.</summary>
|
||||
public event EventHandler? Changed;
|
||||
|
||||
/// <summary>Identifies the server at <paramref name="address"/>: ends in AwaitingTrust, AwaitingCredentials or Failed.</summary>
|
||||
public async Task<ConnectStep> ProbeAsync(string address, CancellationToken ct = default)
|
||||
{
|
||||
Reset();
|
||||
if (!ServerAddress.TryParse(address, out var uri)) return Fail(ConnectError.InvalidAddress);
|
||||
Address = uri;
|
||||
return await IdentifyAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>The user's answer to the fingerprint question; trusting it identifies the server again.</summary>
|
||||
public async Task<ConnectStep> ConfirmTrustAsync(bool trusted, CancellationToken ct = default)
|
||||
{
|
||||
if (Step != ConnectStep.AwaitingTrust || PendingFingerprint is null || Address is null) return Step;
|
||||
if (!trusted) return Fail(ConnectError.Untrusted);
|
||||
trust.Trust(ServerAddress.Display(Address), PendingFingerprint);
|
||||
PendingFingerprint = null;
|
||||
return await IdentifyAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>Sends the credentials; only possible once the server is identified and trusted.</summary>
|
||||
public async Task<ConnectStep> SignInAsync(string username, string password, CancellationToken ct = default)
|
||||
{
|
||||
if (Step is not (ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) || _api is null) return Step;
|
||||
if (string.IsNullOrWhiteSpace(username)) return Retry(ConnectError.BadCredentials);
|
||||
Set(ConnectStep.SigningIn, ConnectError.None);
|
||||
try
|
||||
{
|
||||
var login = await _api.LoginAsync(username.Trim(), password, ct);
|
||||
if (login.Token is null) return Retry(ConnectError.BadCredentials);
|
||||
User = login.User;
|
||||
return Set(ConnectStep.Connected, ConnectError.None);
|
||||
}
|
||||
catch (Exception ex) when (Classify(ex, ct) is { } error)
|
||||
{
|
||||
return error is ConnectError.BadCredentials ? Retry(error) : Fail(error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Resumes a saved session: Connected, or AwaitingCredentials/AwaitingTrust when it cannot be reused.</summary>
|
||||
public async Task<ConnectStep> RestoreAsync(string address, string token, CancellationToken ct = default)
|
||||
{
|
||||
Reset();
|
||||
if (!ServerAddress.TryParse(address, out var uri)) return Fail(ConnectError.InvalidAddress);
|
||||
Address = uri;
|
||||
if (await IdentifyAsync(ct) != ConnectStep.AwaitingCredentials)
|
||||
{
|
||||
// Never resend a token to a server whose certificate is no longer the trusted one.
|
||||
if (Step == ConnectStep.AwaitingTrust) Error = ConnectError.CertificateChanged;
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
return Step;
|
||||
}
|
||||
_api!.Token = token;
|
||||
try
|
||||
{
|
||||
User = await _api.MeAsync(ct);
|
||||
return Set(ConnectStep.Connected, ConnectError.None);
|
||||
}
|
||||
catch (Exception ex) when (Classify(ex, ct) is { } error)
|
||||
{
|
||||
_api.Token = null;
|
||||
return error is ConnectError.BadCredentials ? Retry(ConnectError.SessionExpired) : Fail(error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ends the session on the server (best effort) and forgets it here.</summary>
|
||||
public async Task SignOutAsync()
|
||||
{
|
||||
if (_api is { Token: not null } api)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
await api.LogoutAsync(timeout.Token);
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TitanoApiException or OperationCanceledException or UntrustedCertificateException)
|
||||
{
|
||||
// The token is forgotten locally either way.
|
||||
}
|
||||
}
|
||||
Reset();
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <summary>Drops the connection without signing out (the saved token stays valid).</summary>
|
||||
public void Disconnect()
|
||||
{
|
||||
Reset();
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public void Dispose() => Reset();
|
||||
|
||||
private async Task<ConnectStep> IdentifyAsync(CancellationToken ct)
|
||||
{
|
||||
Set(ConnectStep.Probing, ConnectError.None);
|
||||
_api?.Dispose();
|
||||
_api = factory.Create(Address!, trust.Fingerprints);
|
||||
try
|
||||
{
|
||||
var clock = Stopwatch.StartNew();
|
||||
Info = await _api.GetInfoAsync(ct);
|
||||
Latency = clock.Elapsed;
|
||||
return Set(ConnectStep.AwaitingCredentials, ConnectError.None);
|
||||
}
|
||||
catch (UntrustedCertificateException untrusted)
|
||||
{
|
||||
PendingFingerprint = untrusted.Fingerprint;
|
||||
return Set(ConnectStep.AwaitingTrust, ConnectError.None);
|
||||
}
|
||||
catch (Exception ex) when (Classify(ex, ct) is { } error)
|
||||
{
|
||||
return Fail(error);
|
||||
}
|
||||
}
|
||||
|
||||
private void Reset()
|
||||
{
|
||||
_api?.Dispose();
|
||||
_api = null;
|
||||
Step = ConnectStep.Idle;
|
||||
Error = ConnectError.None;
|
||||
Address = null;
|
||||
PendingFingerprint = null;
|
||||
Info = null;
|
||||
User = null;
|
||||
Latency = null;
|
||||
}
|
||||
|
||||
private ConnectStep Set(ConnectStep step, ConnectError error)
|
||||
{
|
||||
Step = step;
|
||||
Error = error;
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
return step;
|
||||
}
|
||||
|
||||
/// <summary>Back to the login form with an error (wrong password, expired session).</summary>
|
||||
private ConnectStep Retry(ConnectError error) => Set(ConnectStep.AwaitingCredentials, error);
|
||||
|
||||
private ConnectStep Fail(ConnectError error)
|
||||
{
|
||||
_api?.Dispose();
|
||||
_api = null;
|
||||
return Set(ConnectStep.Failed, error);
|
||||
}
|
||||
|
||||
/// <summary>Expected failures as an error code; null lets unexpected exceptions propagate.</summary>
|
||||
internal static ConnectError? Classify(Exception ex, CancellationToken ct) => ex switch
|
||||
{
|
||||
UntrustedCertificateException => ConnectError.Untrusted,
|
||||
TitanoApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => ConnectError.BadCredentials,
|
||||
TitanoApiException { Status: HttpStatusCode.NotFound } => ConnectError.NotTitano,
|
||||
TitanoApiException api when api.IsTransient => ConnectError.Unreachable,
|
||||
TitanoApiException => ConnectError.Failed,
|
||||
JsonException or NotSupportedException => ConnectError.NotTitano,
|
||||
HttpRequestException => ConnectError.Unreachable,
|
||||
OperationCanceledException when !ct.IsCancellationRequested => ConnectError.Unreachable,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Server addresses as typed in the address field.</summary>
|
||||
public static class ServerAddress
|
||||
{
|
||||
/// <summary>Accepts "nas.local:8443" (https assumed) or a full http(s) URL; the result is the API base, ending with "/".</summary>
|
||||
public static bool TryParse(string? text, out Uri uri)
|
||||
{
|
||||
uri = null!;
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
var trimmed = text.Trim();
|
||||
if (!trimmed.Contains("://", StringComparison.Ordinal)) trimmed = "https://" + trimmed;
|
||||
if (!Uri.TryCreate(trimmed, UriKind.Absolute, out var parsed) || parsed.Scheme is not ("https" or "http") || parsed.Host.Length == 0) return false;
|
||||
var builder = new UriBuilder(parsed) { Query = string.Empty, Fragment = string.Empty };
|
||||
if (!builder.Path.EndsWith('/')) builder.Path += "/";
|
||||
uri = builder.Uri;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The address as shown in the field: the base URL without its trailing slash.</summary>
|
||||
public static string Display(Uri uri) => uri.ToString().TrimEnd('/');
|
||||
|
||||
/// <summary>Same, for stored text.</summary>
|
||||
public static string Display(string? address) => address?.TrimEnd('/') ?? string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Windows.Security;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.App.Server;
|
||||
|
||||
/// <summary><see cref="IServerApi"/> over the protocol's <see cref="TitanoClient"/>.</summary>
|
||||
public sealed class TitanoServerApi(TitanoClient client) : IServerApi
|
||||
{
|
||||
public TitanoClient Client { get; } = client;
|
||||
|
||||
public Uri BaseAddress => Client.BaseAddress;
|
||||
|
||||
public string? Token
|
||||
{
|
||||
get => Client.Token;
|
||||
set => Client.Token = value;
|
||||
}
|
||||
|
||||
public Task<ServerInfo> GetInfoAsync(CancellationToken ct) => Client.GetInfoAsync(ct);
|
||||
|
||||
public Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct) => Client.LoginAsync(username, password, ct);
|
||||
|
||||
public Task<UserDto> MeAsync(CancellationToken ct) => Client.MeAsync(ct);
|
||||
|
||||
public Task LogoutAsync(CancellationToken ct) => Client.LogoutAsync(ct);
|
||||
|
||||
public void Dispose() => Client.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Creates <see cref="TitanoServerApi"/> clients with a fresh certificate pinning per connection attempt.</summary>
|
||||
public sealed class TitanoServerApiFactory : IServerApiFactory
|
||||
{
|
||||
public IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints) =>
|
||||
// A fresh pinning per client: the last rejected fingerprint must not outlive a trust decision.
|
||||
new TitanoServerApi(new TitanoClient(baseAddress, new CertificatePinning(trustedFingerprints), $"Titano ({Environment.MachineName})"));
|
||||
}
|
||||
|
||||
/// <summary>Encrypts the session token at rest.</summary>
|
||||
public interface ITokenProtector
|
||||
{
|
||||
string Protect(string token);
|
||||
|
||||
/// <summary>The token, or null when the blob is corrupt or belongs to another Windows user.</summary>
|
||||
string? Unprotect(string protectedToken);
|
||||
}
|
||||
|
||||
/// <summary>DPAPI, current-user scope, with entropy that ties the blob to the desktop client.</summary>
|
||||
public sealed class DpapiTokenProtector : ITokenProtector
|
||||
{
|
||||
private static readonly byte[] Entropy = "Titano.App.Token.v1"u8.ToArray();
|
||||
|
||||
public string Protect(string token) => Dpapi.ProtectString(token, Entropy);
|
||||
|
||||
public string? Unprotect(string protectedToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Dpapi.UnprotectString(protectedToken, Entropy);
|
||||
}
|
||||
catch (Exception ex) when (ex is FormatException or CryptographicException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A Titano Server announced on the LAN.</summary>
|
||||
public sealed record DiscoveredServer(string Name, string Address);
|
||||
|
||||
/// <summary>
|
||||
/// Listens for the server's UDP beacon (<see cref="DiscoveryBeacon.Port"/>) and reports each server once.
|
||||
/// Beacons are unauthenticated: they only fill the address field, never trust a certificate.
|
||||
/// </summary>
|
||||
public sealed class DiscoveryListener : IDisposable
|
||||
{
|
||||
private readonly HashSet<string> _seen = new(StringComparer.OrdinalIgnoreCase);
|
||||
private CancellationTokenSource? _cts;
|
||||
|
||||
/// <summary>Raised on the synchronization context of the thread that called <see cref="Start"/>.</summary>
|
||||
public event Action<DiscoveredServer>? Found;
|
||||
|
||||
public bool IsRunning => _cts is not null;
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (_cts is not null) return;
|
||||
_cts = new CancellationTokenSource();
|
||||
var context = SynchronizationContext.Current;
|
||||
var token = _cts.Token;
|
||||
_ = Task.Run(() => ListenAsync(context, token));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_cts?.Cancel();
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
}
|
||||
|
||||
private static string AddressOf(DiscoveryBeacon beacon, IPAddress sender)
|
||||
{
|
||||
var host = sender.AddressFamily == AddressFamily.InterNetworkV6 ? "[" + sender + "]" : sender.ToString();
|
||||
return beacon.HttpsPort > 0 ? $"https://{host}:{beacon.HttpsPort}" : $"http://{host}:{beacon.HttpPort}";
|
||||
}
|
||||
|
||||
private async Task ListenAsync(SynchronizationContext? context, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var udp = new UdpClient();
|
||||
// The uploader may listen on the same port.
|
||||
udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
udp.Client.Bind(new IPEndPoint(IPAddress.Any, DiscoveryBeacon.Port));
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
var datagram = await udp.ReceiveAsync(ct).ConfigureAwait(false);
|
||||
if (DiscoveryBeacon.TryParse(datagram.Buffer) is not { } beacon) continue;
|
||||
var server = new DiscoveredServer(beacon.Name, AddressOf(beacon, datagram.RemoteEndPoint.Address));
|
||||
lock (_seen)
|
||||
{
|
||||
if (!_seen.Add(server.Address)) continue;
|
||||
}
|
||||
if (context is null) Found?.Invoke(server);
|
||||
else context.Post(_ => Found?.Invoke(server), null);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
Log.Info("discovery", "LAN discovery unavailable: " + ex.Message);
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Protocol;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Server;
|
||||
|
||||
/// <summary>
|
||||
/// The client's server connection (BRIEF §12.7): drives <see cref="ConnectFlow"/> with the dialogs (fingerprint
|
||||
/// confirmation before any password is sent, login form), keeps the session token encrypted with DPAPI in the
|
||||
/// settings, restores it at start, and lists servers announced on the LAN. Runs on the UI thread.
|
||||
/// </summary>
|
||||
public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
|
||||
{
|
||||
private readonly AppSettings _settings;
|
||||
private readonly Action _save;
|
||||
private readonly ITokenProtector _protector;
|
||||
private readonly ConnectFlow _flow;
|
||||
private DiscoveryListener? _discovery;
|
||||
private bool _busy;
|
||||
|
||||
public ServerSession(AppSettings settings, Action save, IServerApiFactory factory, ITokenProtector protector)
|
||||
{
|
||||
_settings = settings;
|
||||
_save = save;
|
||||
_protector = protector;
|
||||
_flow = new ConnectFlow(factory, this);
|
||||
_flow.Changed += (_, _) => OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
public ConnectFlow Flow => _flow;
|
||||
|
||||
/// <summary>Servers that announced themselves on this network.</summary>
|
||||
public ObservableCollection<DiscoveredServer> Discovered { get; } = [];
|
||||
|
||||
public bool IsConnected => _flow.Step == ConnectStep.Connected;
|
||||
|
||||
/// <summary>A connection attempt is running.</summary>
|
||||
public bool IsBusy
|
||||
{
|
||||
get => _busy;
|
||||
private set => Set(ref _busy, value);
|
||||
}
|
||||
|
||||
/// <summary>Server name for the status strip; null when not connected.</summary>
|
||||
public string? ServerName => IsConnected ? _flow.Info?.Name : null;
|
||||
|
||||
/// <summary>The saved address (last server used).</summary>
|
||||
public string? SavedAddress => _settings.ServerUrl;
|
||||
|
||||
/// <summary>The token of the saved session is present (Disconnect keeps it).</summary>
|
||||
public bool HasSavedSession => _settings.ServerUrl is not null && _settings.ProtectedToken is not null;
|
||||
|
||||
// ---------------- ITrustStore ----------------
|
||||
|
||||
public IReadOnlyCollection<string> Fingerprints => [.. _settings.TrustedCertificates.Select(c => c.Fingerprint)];
|
||||
|
||||
public void Trust(string server, string fingerprint)
|
||||
{
|
||||
if (_settings.TrustedCertificates.Any(c => c.Fingerprint.Equals(fingerprint, StringComparison.OrdinalIgnoreCase))) return;
|
||||
_settings.TrustedCertificates.Add(new TrustedCertificate { Fingerprint = fingerprint, Server = server, TrustedAt = DateTimeOffset.UtcNow });
|
||||
_save();
|
||||
Log.Info("server", $"Trusted certificate {fingerprint} of {server}");
|
||||
}
|
||||
|
||||
/// <summary>The trust record of a fingerprint, if the user trusted it.</summary>
|
||||
public TrustedCertificate? TrustOf(string? fingerprint) =>
|
||||
fingerprint is null ? null : _settings.TrustedCertificates.FirstOrDefault(c => c.Fingerprint.Equals(fingerprint, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>Forgets a trusted certificate; the next connection asks again.</summary>
|
||||
public void Forget(string fingerprint)
|
||||
{
|
||||
if (_settings.TrustedCertificates.RemoveAll(c => c.Fingerprint.Equals(fingerprint, StringComparison.OrdinalIgnoreCase)) == 0) return;
|
||||
_save();
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
// ---------------- Session ----------------
|
||||
|
||||
/// <summary>Resumes the saved session at start; stays signed out quietly when it cannot be reused.</summary>
|
||||
public async Task RestoreAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (_settings.ServerUrl is not { } address || _settings.ProtectedToken is not { } blob) return;
|
||||
var token = _protector.Unprotect(blob);
|
||||
if (token is null)
|
||||
{
|
||||
Log.Warning("server", "The saved session cannot be decrypted; sign in again");
|
||||
ForgetToken();
|
||||
return;
|
||||
}
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var step = await _flow.RestoreAsync(address, token, ct);
|
||||
if (step == ConnectStep.Connected) Log.Info("server", $"Session restored on {address}");
|
||||
else if (_flow.Error is ConnectError.SessionExpired or ConnectError.CertificateChanged) ForgetToken();
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connects to <paramref name="address"/>: identifies the server, asks to trust an unknown self-signed
|
||||
/// certificate, then reuses the saved session or shows the login form. True when connected.
|
||||
/// </summary>
|
||||
public async Task<bool> ConnectAsync(string address, IAppDialogs dialogs, CancellationToken ct = default)
|
||||
{
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var step = await _flow.ProbeAsync(address, ct);
|
||||
if (step == ConnectStep.AwaitingTrust && _flow.PendingFingerprint is { } fingerprint)
|
||||
{
|
||||
var trusted = dialogs.Confirm(TrustRequest(ServerAddress.Display(_flow.Address!), fingerprint));
|
||||
step = await _flow.ConfirmTrustAsync(trusted, ct);
|
||||
}
|
||||
if (step != ConnectStep.AwaitingCredentials) return false;
|
||||
|
||||
var display = ServerAddress.Display(_flow.Address!);
|
||||
if (HasSavedSession && ServerAddress.Display(_settings.ServerUrl) == display && _protector.Unprotect(_settings.ProtectedToken!) is { } token)
|
||||
{
|
||||
step = await _flow.RestoreAsync(display, token, ct);
|
||||
if (step == ConnectStep.Connected)
|
||||
{
|
||||
Remember();
|
||||
return true;
|
||||
}
|
||||
if (step != ConnectStep.AwaitingCredentials) return false;
|
||||
}
|
||||
|
||||
var signedIn = dialogs.SignIn(display, _settings.ServerUsername, async (user, password) =>
|
||||
{
|
||||
var result = await _flow.SignInAsync(user, password, ct);
|
||||
return result == ConnectStep.Connected ? null : ErrorText(_flow.Error);
|
||||
});
|
||||
if (signedIn && IsConnected)
|
||||
{
|
||||
Remember();
|
||||
return true;
|
||||
}
|
||||
if (!IsConnected && _flow.Step == ConnectStep.AwaitingCredentials) _flow.Disconnect();
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Signs out on the server and removes the token from this PC.</summary>
|
||||
public async Task SignOutAsync()
|
||||
{
|
||||
await _flow.SignOutAsync();
|
||||
ForgetToken();
|
||||
}
|
||||
|
||||
/// <summary>Closes the connection and works locally; the saved session is kept for the next Connect.</summary>
|
||||
public void Disconnect() => _flow.Disconnect();
|
||||
|
||||
public void StartDiscovery()
|
||||
{
|
||||
if (_discovery is not null) return;
|
||||
_discovery = new DiscoveryListener();
|
||||
_discovery.Found += server =>
|
||||
{
|
||||
if (Discovered.Any(d => d.Address.Equals(server.Address, StringComparison.OrdinalIgnoreCase))) return;
|
||||
Discovered.Add(server);
|
||||
};
|
||||
_discovery.Start();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_discovery?.Dispose();
|
||||
_discovery = null;
|
||||
_flow.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>One sentence for a failed step (BRIEF §0.2 rule 6).</summary>
|
||||
public static string ErrorText(ConnectError error) => Loc.L("Server.Error." + error);
|
||||
|
||||
/// <summary>The trust-on-first-use question with the fingerprint split over two lines.</summary>
|
||||
public static ConfirmRequest TrustRequest(string server, string fingerprint) => new()
|
||||
{
|
||||
Heading = Loc.L("Server.Trust.Title"),
|
||||
Message = Loc.L("Server.Trust.Message", server),
|
||||
Detail = FormatFingerprint(fingerprint),
|
||||
DetailToolTip = Loc.L("Tooltips.Server.Fingerprint"),
|
||||
SafeText = Loc.L("Server.Trust.Cancel"),
|
||||
SafeToolTip = Loc.L("Tooltips.Server.DontTrust"),
|
||||
ActionText = Loc.L("Server.Trust.Accept"),
|
||||
ActionToolTip = Loc.L("Tooltips.Server.Trust"),
|
||||
};
|
||||
|
||||
/// <summary>Splits the 32-byte SHA-256 fingerprint into two lines of 16 bytes.</summary>
|
||||
public static string FormatFingerprint(string fingerprint)
|
||||
{
|
||||
var bytes = fingerprint.Split(':');
|
||||
return bytes.Length <= 16 ? fingerprint : string.Join(':', bytes.Take(16)) + "\n" + string.Join(':', bytes.Skip(16));
|
||||
}
|
||||
|
||||
/// <summary>"9A:3C:71:E0:…" for the status line.</summary>
|
||||
public static string ShortFingerprint(string fingerprint)
|
||||
{
|
||||
var bytes = fingerprint.Split(':');
|
||||
return bytes.Length <= 4 ? fingerprint : string.Join(':', bytes.Take(4)) + ":…";
|
||||
}
|
||||
|
||||
/// <summary>The account of the session (role, quota) for the Server screen.</summary>
|
||||
public UserDto? User => IsConnected ? _flow.User : null;
|
||||
|
||||
private void Remember()
|
||||
{
|
||||
if (_flow.Address is null || _flow.Token is null) return;
|
||||
var display = ServerAddress.Display(_flow.Address);
|
||||
_settings.ServerUrl = display;
|
||||
_settings.ServerUsername = _flow.User?.Username ?? _settings.ServerUsername;
|
||||
_settings.ProtectedToken = _protector.Protect(_flow.Token);
|
||||
_settings.RecentServers.RemoveAll(s => s.Equals(display, StringComparison.OrdinalIgnoreCase));
|
||||
_settings.RecentServers.Insert(0, display);
|
||||
if (_settings.RecentServers.Count > 8) _settings.RecentServers.RemoveRange(8, _settings.RecentServers.Count - 8);
|
||||
_save();
|
||||
Log.Info("server", $"Signed in to {display} as {_settings.ServerUsername}");
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
private void ForgetToken()
|
||||
{
|
||||
if (_settings.ProtectedToken is null) return;
|
||||
_settings.ProtectedToken = null;
|
||||
_save();
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using System.Collections;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Titano.App.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// A text setting edited in place (DESIGN §4 inputs): the text box edits <see cref="Text"/>, validated on every
|
||||
/// keystroke; Enter (or leaving the field) commits a valid value, Esc reverts to the committed one. An invalid value
|
||||
/// shows the Error border (through <see cref="INotifyDataErrorInfo"/>) and the message in <see cref="ToolTip"/>.
|
||||
/// </summary>
|
||||
public sealed class EditableField : INotifyPropertyChanged, INotifyDataErrorInfo
|
||||
{
|
||||
private readonly Func<string, string?> _validate;
|
||||
private readonly Action<string> _commit;
|
||||
private readonly Func<string> _toolTip;
|
||||
private string _text;
|
||||
private string _committed;
|
||||
private string? _error;
|
||||
|
||||
/// <param name="value">The committed value.</param>
|
||||
/// <param name="validate">Returns the localized problem of a candidate value, or null when it is valid.</param>
|
||||
/// <param name="commit">Stores a valid, changed value.</param>
|
||||
/// <param name="toolTip">The tooltip while the value is valid.</param>
|
||||
public EditableField(string value, Func<string, string?> validate, Action<string> commit, Func<string> toolTip)
|
||||
{
|
||||
_text = value;
|
||||
_committed = value;
|
||||
_validate = validate;
|
||||
_commit = commit;
|
||||
_toolTip = toolTip;
|
||||
_error = validate(value);
|
||||
}
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
|
||||
public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
|
||||
|
||||
/// <summary>Raised after a value was committed.</summary>
|
||||
public event EventHandler? Committed;
|
||||
|
||||
/// <summary>The text being edited.</summary>
|
||||
public string Text
|
||||
{
|
||||
get => _text;
|
||||
set
|
||||
{
|
||||
value ??= string.Empty;
|
||||
if (_text == value) return;
|
||||
_text = value;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(IsDirty));
|
||||
SetError(_validate(value));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The value in effect.</summary>
|
||||
public string Value => _committed;
|
||||
|
||||
/// <summary>The problem of the current text; null when valid.</summary>
|
||||
public string? Error => _error;
|
||||
|
||||
public bool HasErrors => _error is not null;
|
||||
|
||||
public bool IsDirty => _text != _committed;
|
||||
|
||||
/// <summary>The problem while invalid, otherwise the field's own tooltip.</summary>
|
||||
public string ToolTip => _error ?? _toolTip();
|
||||
|
||||
/// <summary>Commits a valid text (Enter); false when the text is invalid.</summary>
|
||||
public bool Commit()
|
||||
{
|
||||
if (_error is not null) return false;
|
||||
if (!IsDirty) return true;
|
||||
_committed = _text;
|
||||
_commit(_committed);
|
||||
OnPropertyChanged(nameof(Value));
|
||||
OnPropertyChanged(nameof(IsDirty));
|
||||
Committed?.Invoke(this, EventArgs.Empty);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Returns the text to the committed value (Esc).</summary>
|
||||
public void Revert() => Text = _committed;
|
||||
|
||||
/// <summary>Replaces the committed value from outside (reset, import, picker) without calling the commit action.</summary>
|
||||
public void Load(string value)
|
||||
{
|
||||
_committed = value ?? string.Empty;
|
||||
OnPropertyChanged(nameof(Value));
|
||||
Text = _committed;
|
||||
OnPropertyChanged(nameof(IsDirty));
|
||||
SetError(_validate(_text));
|
||||
}
|
||||
|
||||
/// <summary>Re-evaluates the tooltip after a language change.</summary>
|
||||
public void Refresh()
|
||||
{
|
||||
SetError(_validate(_text), force: true);
|
||||
}
|
||||
|
||||
public IEnumerable GetErrors(string? propertyName) =>
|
||||
_error is not null && (string.IsNullOrEmpty(propertyName) || propertyName == nameof(Text)) ? new[] { _error } : Array.Empty<string>();
|
||||
|
||||
private void SetError(string? error, bool force = false)
|
||||
{
|
||||
if (_error == error && !force) return;
|
||||
_error = error;
|
||||
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Text)));
|
||||
OnPropertyChanged(nameof(Error));
|
||||
OnPropertyChanged(nameof(HasErrors));
|
||||
OnPropertyChanged(nameof(ToolTip));
|
||||
}
|
||||
|
||||
private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Core.Video.Avi;
|
||||
using Titano.Core.Windows.Dxgi;
|
||||
using Titano.Core.Windows.MediaFoundation;
|
||||
|
||||
namespace Titano.App.Settings;
|
||||
|
||||
/// <summary>Who provides an encoder row.</summary>
|
||||
public enum EncoderSource
|
||||
{
|
||||
/// <summary>A Media Foundation MFT (hardware or Microsoft software).</summary>
|
||||
MediaFoundation,
|
||||
|
||||
/// <summary>Titano's managed MJPEG/AVI writer.</summary>
|
||||
BuiltInMjpeg,
|
||||
|
||||
/// <summary>Titano's managed GIF/APNG encoders.</summary>
|
||||
BuiltInAnimation,
|
||||
}
|
||||
|
||||
/// <summary>One row of Settings › Rendering › Encoders.</summary>
|
||||
public sealed record EncoderRow(string Codec, string Name, string? Vendor, EncoderSource Source, bool Hardware, bool TenBit, int MaxWidth, int MaxHeight, VideoCodec? VideoCodec)
|
||||
{
|
||||
public bool CanSelfTest => Source != EncoderSource.BuiltInAnimation;
|
||||
|
||||
/// <summary>"NVIDIA · NVIDIA HEVC Encoder MFT" unless the name already carries the vendor.</summary>
|
||||
public string DisplayName => Vendor is { } vendor && !Name.Contains(vendor, StringComparison.OrdinalIgnoreCase) ? vendor + " · " + Name : Name;
|
||||
}
|
||||
|
||||
/// <summary>Outcome of encoding the synthetic test clip with one encoder.</summary>
|
||||
public sealed record SelfTestResult(bool Passed, double FramesPerSecond, string? Error);
|
||||
|
||||
/// <summary>Encoders on this PC and their self-test (BRIEF §11.3, §12.8).</summary>
|
||||
public interface IEncoderInventory
|
||||
{
|
||||
/// <summary>"NVIDIA GeForce RTX 4070"; null when no hardware adapter is found.</summary>
|
||||
string? Adapter();
|
||||
|
||||
/// <summary>Enumerates the encoders (slow: call off the UI thread).</summary>
|
||||
IReadOnlyList<EncoderRow> Detect();
|
||||
|
||||
/// <summary>Encodes <see cref="MediaFoundationInventory.TestFrames"/> synthetic frames and reports speed.</summary>
|
||||
Task<SelfTestResult> SelfTestAsync(EncoderRow row, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Media Foundation encoders (in MFTEnumEx merit order) plus Titano's built-in managed encoders.</summary>
|
||||
public sealed class MediaFoundationInventory : IEncoderInventory
|
||||
{
|
||||
public const int TestFrames = 48;
|
||||
public const int TestWidth = 1280;
|
||||
public const int TestHeight = 720;
|
||||
|
||||
public string? Adapter()
|
||||
{
|
||||
try
|
||||
{
|
||||
return GpuAdapters.Enumerate().Where(a => !a.IsSoftware).OrderByDescending(a => a.DedicatedVideoMemory).FirstOrDefault()?.Description;
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or DllNotFoundException or EntryPointNotFoundException)
|
||||
{
|
||||
Log.Warning("encoders", "Graphics adapters could not be listed", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<EncoderRow> Detect()
|
||||
{
|
||||
var rows = new List<EncoderRow>();
|
||||
foreach (var c in new MediaFoundationEncoderProvider().Capabilities)
|
||||
{
|
||||
rows.Add(new EncoderRow(CodecName(c.Codec), c.Name, c.Vendor, EncoderSource.MediaFoundation, c.Hardware, c.SupportsTenBit, c.MaxWidth, c.MaxHeight, c.Codec));
|
||||
}
|
||||
rows.Add(new EncoderRow("MJPEG · AVI", "Titano", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg));
|
||||
rows.Add(new EncoderRow("GIF · APNG", "Titano", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null));
|
||||
return rows;
|
||||
}
|
||||
|
||||
public Task<SelfTestResult> SelfTestAsync(EncoderRow row, CancellationToken ct) => Task.Run(() => SelfTest(row, ct), ct);
|
||||
|
||||
public static string CodecName(VideoCodec codec) => codec switch
|
||||
{
|
||||
VideoCodec.H264 => "H.264",
|
||||
VideoCodec.Hevc => "HEVC",
|
||||
VideoCodec.Av1 => "AV1",
|
||||
_ => codec.ToString(),
|
||||
};
|
||||
|
||||
private static SelfTestResult SelfTest(EncoderRow row, CancellationToken ct)
|
||||
{
|
||||
using var frame = TestPattern(TestWidth, TestHeight);
|
||||
var clock = Stopwatch.StartNew();
|
||||
try
|
||||
{
|
||||
switch (row.Source)
|
||||
{
|
||||
case EncoderSource.MediaFoundation:
|
||||
EncodeMediaFoundation(row, frame, ct);
|
||||
break;
|
||||
case EncoderSource.BuiltInMjpeg:
|
||||
EncodeMjpeg(frame, ct);
|
||||
break;
|
||||
default:
|
||||
return new SelfTestResult(false, 0, null);
|
||||
}
|
||||
clock.Stop();
|
||||
var fps = TestFrames / Math.Max(clock.Elapsed.TotalSeconds, 1e-3);
|
||||
Log.Info("encoders", $"Self-test {row.Codec} \"{row.Name}\": {fps:0.#} fps");
|
||||
return new SelfTestResult(true, fps, null);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or NotSupportedException or IOException or InvalidOperationException or PlatformNotSupportedException or InvalidDataException)
|
||||
{
|
||||
Log.Warning("encoders", $"Self-test {row.Codec} \"{row.Name}\" failed", ex);
|
||||
return new SelfTestResult(false, 0, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private static void EncodeMediaFoundation(EncoderRow row, ImageBuffer frame, CancellationToken ct)
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), "titano-selftest-" + Guid.NewGuid().ToString("N") + ".mp4");
|
||||
try
|
||||
{
|
||||
var fps = new Rational(30, 1);
|
||||
var settings = new EncodeSettings
|
||||
{
|
||||
OutputPath = path,
|
||||
Codec = row.VideoCodec ?? throw new NotSupportedException("No codec"),
|
||||
Width = TestWidth,
|
||||
Height = TestHeight,
|
||||
FrameRate = fps,
|
||||
BitRate = 8_000_000,
|
||||
PreferHardware = row.Hardware,
|
||||
EncoderName = row.Name,
|
||||
};
|
||||
using (var session = new MediaFoundationEncoderProvider().Open(settings))
|
||||
{
|
||||
for (var i = 0; i < TestFrames; i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
session.WriteFrame(frame, fps.FrameTicks90k);
|
||||
}
|
||||
session.Complete();
|
||||
}
|
||||
if (!File.Exists(path) || new FileInfo(path).Length == 0) throw new InvalidDataException("The encoder wrote no data.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void EncodeMjpeg(ImageBuffer frame, CancellationToken ct)
|
||||
{
|
||||
using var output = new MemoryStream();
|
||||
var writer = new AviMjpegWriter(output, TestWidth, TestHeight, new Rational(30, 1));
|
||||
var options = new JpegEncodeOptions { Quality = 90 };
|
||||
for (var i = 0; i < TestFrames; i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
writer.WriteFrame(JpegEncoder.Encode(frame, options));
|
||||
}
|
||||
writer.Complete();
|
||||
if (output.Length == 0) throw new InvalidDataException("The encoder wrote no data.");
|
||||
}
|
||||
|
||||
/// <summary>A smooth colour gradient: compressible, but not trivially so.</summary>
|
||||
internal static ImageBuffer TestPattern(int width, int height)
|
||||
{
|
||||
var image = new ImageBuffer(width, height, 3, clear: false);
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
var plane = image.Plane(c);
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var u = x / (float)width;
|
||||
var v = y / (float)height;
|
||||
plane[y * width + x] = c switch
|
||||
{
|
||||
0 => u * 0.8f,
|
||||
1 => v * 0.6f,
|
||||
_ => (1 - u) * (1 - v) * 0.7f,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using System.Globalization;
|
||||
using System.Resources;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.App.Settings;
|
||||
|
||||
/// <summary>A language of the language pickers: culture code and its own name ("Italiano").</summary>
|
||||
public sealed record LanguageOption(string Code, string Name);
|
||||
|
||||
/// <summary>
|
||||
/// The languages this build ships (BRIEF §16): English plus every language of <see cref="Languages.Shipped"/> whose
|
||||
/// resources are compiled in. Languages announced for later phases appear as soon as their resources exist, and
|
||||
/// never before (a picker entry that shows English text would mislead).
|
||||
/// </summary>
|
||||
public static class LanguageCatalog
|
||||
{
|
||||
private static readonly Lazy<IReadOnlyList<LanguageOption>> Detected = new(Detect);
|
||||
|
||||
/// <summary>Available languages, English first, then by native name.</summary>
|
||||
public static IReadOnlyList<LanguageOption> Available => Detected.Value;
|
||||
|
||||
/// <summary>True when the satellite resources of <paramref name="code"/> exist.</summary>
|
||||
public static bool HasResources(string code)
|
||||
{
|
||||
if (code.Equals("en", StringComparison.OrdinalIgnoreCase)) return true;
|
||||
var manager = new ResourceManager("Titano.Core.i18n.Common", typeof(Loc).Assembly);
|
||||
try
|
||||
{
|
||||
return manager.GetResourceSet(CultureInfo.GetCultureInfo(code), createIfNotExists: true, tryParents: false) is not null;
|
||||
}
|
||||
catch (MissingManifestResourceException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (CultureNotFoundException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The option matching <paramref name="culture"/> (or its parent), English when none does.</summary>
|
||||
public static LanguageOption Match(CultureInfo culture)
|
||||
{
|
||||
for (var c = culture; !Equals(c, CultureInfo.InvariantCulture); c = c.Parent)
|
||||
{
|
||||
var hit = Available.FirstOrDefault(o => o.Code.Equals(c.Name, StringComparison.OrdinalIgnoreCase));
|
||||
if (hit is not null) return hit;
|
||||
}
|
||||
return Available[0];
|
||||
}
|
||||
|
||||
private static IReadOnlyList<LanguageOption> Detect()
|
||||
{
|
||||
var found = Languages.Shipped
|
||||
.Where(code => !code.Equals("en", StringComparison.OrdinalIgnoreCase) && HasResources(code))
|
||||
.Select(code => new LanguageOption(code, Languages.NativeName(code)))
|
||||
.OrderBy(o => o.Name, StringComparer.CurrentCultureIgnoreCase)
|
||||
.ToList();
|
||||
found.Insert(0, new LanguageOption("en", Languages.NativeName("en")));
|
||||
return found;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Naming;
|
||||
|
||||
namespace Titano.App.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Live validation and preview of the archive naming templates (BRIEF §7.1): the first problem of a template as one
|
||||
/// localized sentence, and the first three names a typical import would produce.
|
||||
/// </summary>
|
||||
public static class NamingPreview
|
||||
{
|
||||
/// <summary>A sample session used for the preview: three frames, two seconds apart, from a Canon EOS R5.</summary>
|
||||
public static IReadOnlyList<NamingContext> SampleFrames { get; } = BuildSample();
|
||||
|
||||
/// <summary>The first problem of <paramref name="template"/>, localized; null when it is valid.</summary>
|
||||
public static string? Validate(string? template, bool isFolder)
|
||||
{
|
||||
var text = template ?? string.Empty;
|
||||
var parsed = PathTemplate.Parse(text);
|
||||
if (parsed.Errors.Count > 0)
|
||||
{
|
||||
var error = parsed.Errors[0];
|
||||
return Loc.L("Errors.Template." + error.Code, error.Token ?? string.Empty, error.Position + 1);
|
||||
}
|
||||
if (!isFolder && text.Contains('/', StringComparison.Ordinal)) return Loc.L("Errors.Template.FileSeparator");
|
||||
try
|
||||
{
|
||||
foreach (var frame in SampleFrames)
|
||||
{
|
||||
var name = isFolder ? parsed.ExpandFolder(frame) : parsed.ExpandFile(frame);
|
||||
if (name.Length == 0) return Loc.L("Errors.Template.Empty", string.Empty, 1);
|
||||
}
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return Loc.L("Errors.Template.Format");
|
||||
}
|
||||
if (!isFolder && !NumbersFrames(text)) return Loc.L("Errors.Template.NotUnique");
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Relative paths of the first three sample frames; empty when either template is invalid.</summary>
|
||||
public static IReadOnlyList<string> FirstNames(string? folderTemplate, string? fileTemplate)
|
||||
{
|
||||
if (Validate(folderTemplate, isFolder: true) is not null || Validate(fileTemplate, isFolder: false) is not null) return [];
|
||||
var folder = PathTemplate.Parse(folderTemplate!);
|
||||
var file = PathTemplate.Parse(fileTemplate!);
|
||||
return SampleFrames.Select(f => Combine(folder.ExpandFolder(f), file.ExpandFile(f))).ToList();
|
||||
}
|
||||
|
||||
private static string Combine(string folder, string file) => folder.Length == 0 ? file : folder + "/" + file;
|
||||
|
||||
/// <summary>File names must tell frames apart: a frame number, the time of day or the original name.</summary>
|
||||
private static bool NumbersFrames(string template)
|
||||
{
|
||||
var parsed = PathTemplate.Parse(template);
|
||||
var names = SampleFrames.Select(parsed.ExpandFile).ToList();
|
||||
return names.Distinct(StringComparer.OrdinalIgnoreCase).Count() == names.Count;
|
||||
}
|
||||
|
||||
private static List<NamingContext> BuildSample()
|
||||
{
|
||||
var start = new DateTime(2026, 9, 28, 18, 2, 11);
|
||||
return Enumerable.Range(0, 3).Select(i => new NamingContext
|
||||
{
|
||||
CapturedAt = start.AddSeconds(2 * i),
|
||||
SessionStart = start,
|
||||
Session = 1,
|
||||
Number = i + 1,
|
||||
NumberInSession = i + 1,
|
||||
CameraMake = "Canon",
|
||||
CameraModel = "Canon EOS R5",
|
||||
Lens = "RF15-35mm F2.8 L IS USM",
|
||||
Iso = 100,
|
||||
ExposureTime = 1.0 / 250,
|
||||
FNumber = 8,
|
||||
OriginalName = "IMG_" + (4211 + i).ToString("0000", System.Globalization.CultureInfo.InvariantCulture),
|
||||
Extension = "CR2",
|
||||
Title = "Harbour sunset",
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Settings;
|
||||
|
||||
/// <summary>Sections of the Settings screen (BRIEF §12.8).</summary>
|
||||
public enum SettingsPage
|
||||
{
|
||||
General,
|
||||
Archive,
|
||||
Rendering,
|
||||
Storage,
|
||||
Server,
|
||||
Updates,
|
||||
Advanced,
|
||||
}
|
||||
|
||||
/// <summary>An entry of the section list: name, tooltip (what is inside) and the words the search matches.</summary>
|
||||
public sealed class SettingsPageItem(SettingsPage page, string[] keywordKeys) : ObservableObject
|
||||
{
|
||||
public SettingsPage Page { get; } = page;
|
||||
|
||||
public string Label => Loc.L("Settings.Page." + Page);
|
||||
|
||||
public string ToolTip => Loc.L("Tooltips.Settings.Page." + Page);
|
||||
|
||||
/// <summary>True when <paramref name="text"/> appears in the page name, its tooltip or one of its labels.</summary>
|
||||
public bool Matches(string text) =>
|
||||
Label.Contains(text, StringComparison.CurrentCultureIgnoreCase)
|
||||
|| ToolTip.Contains(text, StringComparison.CurrentCultureIgnoreCase)
|
||||
|| keywordKeys.Any(k => Loc.L(k).Contains(text, StringComparison.CurrentCultureIgnoreCase));
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>A choice of a settings dropdown.</summary>
|
||||
public sealed record SettingsOption<T>(T Value, string Label)
|
||||
{
|
||||
public override string ToString() => Label;
|
||||
}
|
||||
|
||||
/// <summary>One row of the encoder table with its self-test state.</summary>
|
||||
public sealed class EncoderRowViewModel(EncoderRow row) : ObservableObject
|
||||
{
|
||||
private SelfTestResult? _result;
|
||||
private bool _isTesting;
|
||||
|
||||
public EncoderRow Row { get; } = row;
|
||||
|
||||
public string Codec => Row.Codec;
|
||||
|
||||
/// <summary>"NVIDIA NVENC (hardware)".</summary>
|
||||
public string Name => Row.Source switch
|
||||
{
|
||||
EncoderSource.MediaFoundation => Loc.L(Row.Hardware ? "Settings.Rendering.Encoder.Hardware" : "Settings.Rendering.Encoder.Software", Row.DisplayName),
|
||||
_ => Loc.L("Settings.Rendering.Encoder.BuiltIn", Row.DisplayName),
|
||||
};
|
||||
|
||||
/// <summary>"Main10", "10-bit" or "—".</summary>
|
||||
public string TenBitText => !Row.TenBit ? "—" : Row.VideoCodec == Core.Video.VideoCodec.Hevc ? "Main10" : Loc.L("Settings.Rendering.TenBit");
|
||||
|
||||
public bool HasTenBit => Row.TenBit;
|
||||
|
||||
/// <summary>"8192×8192" or "no limit".</summary>
|
||||
public string MaxText => Row.MaxWidth > 0 ? $"{Row.MaxWidth}×{Row.MaxHeight}" : Loc.L("Settings.Rendering.NoLimit");
|
||||
|
||||
public bool IsTesting
|
||||
{
|
||||
get => _isTesting;
|
||||
set
|
||||
{
|
||||
if (Set(ref _isTesting, value)) RaiseResult();
|
||||
}
|
||||
}
|
||||
|
||||
public SelfTestResult? Result
|
||||
{
|
||||
get => _result;
|
||||
set
|
||||
{
|
||||
if (Set(ref _result, value)) RaiseResult();
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasResult => _result is not null || _isTesting;
|
||||
|
||||
public StatusKind ResultKind => _isTesting ? StatusKind.Running : _result is { Passed: true } ? StatusKind.Done : StatusKind.Failed;
|
||||
|
||||
/// <summary>"142 fps · ok", "failed", "testing".</summary>
|
||||
public string ResultText => _isTesting ? Loc.L("Settings.Rendering.Testing")
|
||||
: _result is not { } r ? "—"
|
||||
: r.Passed ? Loc.L("Settings.Rendering.Passed", Formatting.Rate(r.FramesPerSecond))
|
||||
: Loc.L("Settings.Rendering.Failed");
|
||||
|
||||
public string ResultToolTip => _result is { Passed: false, Error: { } error } ? error : Loc.L("Tooltips.Settings.SelfTestResult");
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
|
||||
private void RaiseResult()
|
||||
{
|
||||
OnPropertyChanged(nameof(HasResult));
|
||||
OnPropertyChanged(nameof(ResultKind));
|
||||
OnPropertyChanged(nameof(ResultText));
|
||||
OnPropertyChanged(nameof(ResultToolTip));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A trusted server certificate in Settings › Server.</summary>
|
||||
public sealed class TrustedCertificateRow(TrustedCertificate certificate, ICommand forget)
|
||||
{
|
||||
public TrustedCertificate Certificate { get; } = certificate;
|
||||
public string Server => Certificate.Server ?? "—";
|
||||
public string Fingerprint => Titano.App.Server.ServerSession.ShortFingerprint(Certificate.Fingerprint);
|
||||
public string FullFingerprint => Certificate.Fingerprint;
|
||||
public string TrustedText => Formatting.Date(Certificate.TrustedAt);
|
||||
public ICommand ForgetCommand { get; } = forget;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Interop;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Interop;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.App.Shell;
|
||||
|
||||
/// <summary>Window-owned dialogs: the shell's folder and file pickers, confirmations and the login form.</summary>
|
||||
public sealed class AppDialogs : IAppDialogs
|
||||
{
|
||||
/// <summary>Owner of the dialogs; the main window once it exists.</summary>
|
||||
public Window? Owner { get; set; }
|
||||
|
||||
private IntPtr OwnerHandle => Owner is null ? IntPtr.Zero : new WindowInteropHelper(Owner).Handle;
|
||||
|
||||
public string? PickFolder(string title, string? initialFolder = null) => FileDialogs.PickFolder(OwnerHandle, title);
|
||||
|
||||
public string? PickJsonFile(string title) => FileDialogs.PickFile(OwnerHandle, title,
|
||||
[
|
||||
new FileFilter(Loc.L("Settings.Import.Filter"), "*.json"),
|
||||
]);
|
||||
|
||||
public bool Confirm(ConfirmRequest request) => ConfirmDialog.Ask(Owner, request);
|
||||
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => LoginDialog.Ask(Owner, server, username, signIn);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace Titano.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// The client's own styles (<c>Shell/AppStyles.xaml</c>) and view templates. They build on the Titano.Ui kit with
|
||||
/// StaticResource, so they are merged after <see cref="Ui.Theming.ThemeManager.Initialize"/> loaded the kit.
|
||||
/// </summary>
|
||||
public static class AppResources
|
||||
{
|
||||
private static readonly Uri Styles = new("pack://application:,,,/Titano;component/Shell/AppStyles.xaml", UriKind.Absolute);
|
||||
|
||||
/// <summary>Merges the client styles into <paramref name="app"/> once.</summary>
|
||||
public static void Merge(Application app)
|
||||
{
|
||||
if (app.Resources.MergedDictionaries.Any(d => d.Source == Styles)) return;
|
||||
app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = Styles });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:sys="clr-namespace:System;assembly=System.Runtime">
|
||||
<!--
|
||||
Styles shared by the client screens, built on the kit of Titano.Ui (DESIGN.md §3–4). Brushes are DynamicResource;
|
||||
sizes come from Typography.xaml through the kit's StaticResources.
|
||||
-->
|
||||
|
||||
<!-- Label column text (116 px panels, 180 px Settings). -->
|
||||
<Style x:Key="Text.Label" TargetType="TextBlock">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
|
||||
<Setter Property="Margin" Value="0,0,14,0" />
|
||||
</Style>
|
||||
|
||||
<!-- Faint helper value next to a control ("of 32 GB installed"). -->
|
||||
<Style x:Key="Text.Hint" TargetType="TextBlock">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextFaint}" />
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
|
||||
</Style>
|
||||
|
||||
<!-- Table header cell: 11 px faint. -->
|
||||
<Style x:Key="Text.Header" TargetType="TextBlock">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextFaint}" />
|
||||
<Setter Property="FontSize" Value="11" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
|
||||
</Style>
|
||||
|
||||
<!-- Table cell: one line, tabular figures, ellipsis. -->
|
||||
<Style x:Key="Text.Cell" TargetType="TextBlock">
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
|
||||
<Setter Property="Typography.NumeralAlignment" Value="Tabular" />
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Text.CellNumber" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
|
||||
<!-- Log tail: monospaced, muted. -->
|
||||
<Style x:Key="Text.Log" TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="{StaticResource Font.Mono}" />
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="LineHeight" Value="18" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
<Setter Property="TextWrapping" Value="Wrap" />
|
||||
</Style>
|
||||
|
||||
<!-- Table row container (DESIGN §4: 36–40 px, hover = Card fill, 1 px divider; selected = AccentSubtle). -->
|
||||
<Style x:Key="ListBoxItem.Row" TargetType="ListBoxItem">
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="Padding" Value="14,0" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ListBoxItem">
|
||||
<Border x:Name="Bd" Background="Transparent" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.AccentSubtle}" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsKeyboardFocused" Value="True">
|
||||
<Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Row container without selection (Jobs, encoder tables): hover only. -->
|
||||
<Style x:Key="ListBoxItem.PlainRow" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
|
||||
<Setter Property="Focusable" Value="False" />
|
||||
<Setter Property="Padding" Value="0" />
|
||||
</Style>
|
||||
|
||||
<!-- Section list entry of Settings: 34 px, active = Card fill + 3 px accent edge (Settings.html). -->
|
||||
<Style x:Key="ListBoxItem.Section" TargetType="ListBoxItem">
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
<Setter Property="Height" Value="34" />
|
||||
<Setter Property="Margin" Value="0,0,0,2" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ListBoxItem">
|
||||
<Border x:Name="Bd" Background="Transparent" CornerRadius="{StaticResource Radius.Control}">
|
||||
<Grid>
|
||||
<Border x:Name="Edge" Width="3" HorizontalAlignment="Left" CornerRadius="1.5" Margin="0,7" Background="{DynamicResource Brush.Accent}" Visibility="Hidden" />
|
||||
<ContentPresenter Margin="12,0" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter TargetName="Edge" Property="Visibility" Value="Visible" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsKeyboardFocused" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Filter chip (Jobs.html): 30 px pill, accent border and text when chosen (bind Tag to the chosen state). -->
|
||||
<Style x:Key="Button.Chip" TargetType="Button" BasedOn="{StaticResource Button.Base}">
|
||||
<Setter Property="Height" Value="30" />
|
||||
<Setter Property="Padding" Value="12,0" />
|
||||
<Setter Property="ui:ControlState.CornerRadius" Value="15" />
|
||||
<Style.Triggers>
|
||||
<Trigger Property="Tag">
|
||||
<Trigger.Value>
|
||||
<sys:Boolean>True</sys:Boolean>
|
||||
</Trigger.Value>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="ui:ControlState.HoverBorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
|
||||
<!-- Row action (26 px, DESIGN §4 tables). -->
|
||||
<Style x:Key="Button.Row" TargetType="Button" BasedOn="{StaticResource Button.Compact}">
|
||||
<Setter Property="Height" Value="26" />
|
||||
<Setter Property="Padding" Value="10,0" />
|
||||
<Setter Property="Margin" Value="0,0,6,0" />
|
||||
</Style>
|
||||
|
||||
<!-- "Auto · 8" pill (DESIGN §4 Auto/manual): accent outline, 24 px, 11 px text. -->
|
||||
<Style x:Key="Button.AutoPill" TargetType="Button" BasedOn="{StaticResource Button.Base}">
|
||||
<Setter Property="Height" Value="24" />
|
||||
<Setter Property="MinWidth" Value="0" />
|
||||
<Setter Property="Padding" Value="8,0" />
|
||||
<Setter Property="FontSize" Value="11" />
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="ui:ControlState.CornerRadius" Value="12" />
|
||||
<Setter Property="ui:ControlState.HoverBackground" Value="{DynamicResource Brush.AccentSubtle}" />
|
||||
<Setter Property="ui:ControlState.HoverBorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="ui:ControlState.PressedBackground" Value="{DynamicResource Brush.AccentSubtle}" />
|
||||
</Style>
|
||||
|
||||
<!-- Toolbar dropdown (Library filters): accent border while a filter is active (bind Tag to the active flag). -->
|
||||
<Style x:Key="ComboBox.Filter" TargetType="ComboBox" BasedOn="{StaticResource {x:Type ComboBox}}">
|
||||
<Setter Property="MinWidth" Value="88" />
|
||||
<Setter Property="MaxDropDownHeight" Value="420" />
|
||||
<Style.Triggers>
|
||||
<Trigger Property="Tag">
|
||||
<Trigger.Value>
|
||||
<sys:Boolean>True</sys:Boolean>
|
||||
</Trigger.Value>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
|
||||
<!-- Closed box shows BoxText ("Year"), the open list shows Label ("All years"). -->
|
||||
<DataTemplate x:Key="Template.FilterOption">
|
||||
<TextBlock x:Name="Text" Text="{Binding Label}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem}}" Value="{x:Null}">
|
||||
<Setter TargetName="Text" Property="Text" Value="{Binding BoxText}" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate x:Key="Template.Label">
|
||||
<TextBlock Text="{Binding Label}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Panel title (Text.Section, 14/600) for sub-sections inside a panel. -->
|
||||
<Style x:Key="Text.PanelTitle" TargetType="TextBlock" BasedOn="{StaticResource Text.Section}" />
|
||||
|
||||
<!-- One Settings row: 180 px label column, then the controls (Settings.html grid; 14 px between rows). -->
|
||||
<Style x:Key="Setting.Row" TargetType="HeaderedContentControl">
|
||||
<Setter Property="Focusable" Value="False" />
|
||||
<Setter Property="Margin" Value="0,0,0,14" />
|
||||
<Setter Property="MinHeight" Value="32" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="HeaderedContentControl">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="{StaticResource Grid.SettingsLabelColumn}" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{TemplateBinding Header}" Style="{StaticResource Text.Label}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="0,7,14,0" />
|
||||
<ContentPresenter Grid.Column="1" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
<Setter Property="VerticalContentAlignment" Value="Top" />
|
||||
</Style>
|
||||
|
||||
<!-- Path and template fields in Settings (360 px, DESIGN mockup). -->
|
||||
<Style x:Key="TextBox.Setting" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
|
||||
<Setter Property="Width" Value="360" />
|
||||
<Setter Property="HorizontalAlignment" Value="Left" />
|
||||
</Style>
|
||||
|
||||
<Style x:Key="TextBox.SettingMono" TargetType="TextBox" BasedOn="{StaticResource TextBox.Mono}">
|
||||
<Setter Property="Width" Value="360" />
|
||||
<Setter Property="HorizontalAlignment" Value="Left" />
|
||||
</Style>
|
||||
|
||||
<Style x:Key="TextBox.Number" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
|
||||
<Setter Property="Width" Value="72" />
|
||||
<Setter Property="Padding" Value="8,0" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Right" />
|
||||
<Setter Property="Typography.NumeralAlignment" Value="Tabular" />
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,22 @@
|
||||
<ui:TitanoWindow x:Class="Titano.App.Shell.ConfirmDialog"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
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 Shell.AppName}"
|
||||
IsDialog="True" ResizeMode="NoResize" SizeToContent="Height" Width="460"
|
||||
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" TextTrimming="None" LineHeight="18" />
|
||||
<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" TextTrimming="None" LineHeight="18" />
|
||||
</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="Action" Content="{Binding ActionText}" ToolTip="{Binding ActionToolTip}" MinWidth="96" Margin="8,0,0,0" Click="OnAction" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</ui:TitanoWindow>
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Windows;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Ui.Controls;
|
||||
|
||||
namespace Titano.App.Shell;
|
||||
|
||||
/// <summary>Modal confirmation for trusting a certificate and for destructive actions (BRIEF §12.1).</summary>
|
||||
public sealed partial class ConfirmDialog : TitanoWindow
|
||||
{
|
||||
public ConfirmDialog(ConfirmRequest request)
|
||||
{
|
||||
DataContext = request;
|
||||
InitializeComponent();
|
||||
Action.SetResourceReference(StyleProperty, request.IsDestructive ? "Button.Destructive" : "Button.Primary");
|
||||
}
|
||||
|
||||
/// <summary>True when the user chose the action.</summary>
|
||||
public static bool Ask(Window? owner, ConfirmRequest request)
|
||||
{
|
||||
var dialog = new ConfirmDialog(request);
|
||||
if (owner is { IsVisible: true }) dialog.Owner = owner;
|
||||
else dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
|
||||
return dialog.ShowDialog() == true;
|
||||
}
|
||||
|
||||
private void OnSafe(object sender, RoutedEventArgs e) => DialogResult = false;
|
||||
|
||||
private void OnAction(object sender, RoutedEventArgs e) => DialogResult = true;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Settings;
|
||||
|
||||
namespace Titano.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// Attaches an <see cref="EditableField"/> to a text box (DESIGN §4 inputs): Enter commits, Esc reverts, leaving
|
||||
/// the field commits a valid value.
|
||||
/// </summary>
|
||||
public static class EditBehavior
|
||||
{
|
||||
public static readonly DependencyProperty FieldProperty = DependencyProperty.RegisterAttached(
|
||||
"Field", typeof(EditableField), typeof(EditBehavior), new PropertyMetadata(null, OnFieldChanged));
|
||||
|
||||
public static EditableField? GetField(DependencyObject d) => (EditableField?)d.GetValue(FieldProperty);
|
||||
|
||||
public static void SetField(DependencyObject d, EditableField? value) => d.SetValue(FieldProperty, value);
|
||||
|
||||
private static void OnFieldChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is not TextBox box) return;
|
||||
box.PreviewKeyDown -= OnKeyDown;
|
||||
box.LostKeyboardFocus -= OnLostFocus;
|
||||
if (e.NewValue is null) return;
|
||||
box.PreviewKeyDown += OnKeyDown;
|
||||
box.LostKeyboardFocus += OnLostFocus;
|
||||
}
|
||||
|
||||
private static void OnKeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (sender is not TextBox box || GetField(box) is not { } field) return;
|
||||
if (e.Key == Key.Enter)
|
||||
{
|
||||
field.Commit();
|
||||
box.SelectAll();
|
||||
e.Handled = true;
|
||||
}
|
||||
else if (e.Key == Key.Escape)
|
||||
{
|
||||
field.Revert();
|
||||
box.SelectAll();
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnLostFocus(object sender, KeyboardFocusChangedEventArgs e)
|
||||
{
|
||||
if (sender is TextBox box && GetField(box) is { HasErrors: false } field) field.Commit();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Visible when the bound value's text equals the converter parameter (settings pages).</summary>
|
||||
public sealed class EqualsToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public static EqualsToVisibilityConverter Instance { get; } = new();
|
||||
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
string.Equals(value?.ToString(), parameter?.ToString(), StringComparison.Ordinal) ? Visibility.Visible : Visibility.Collapsed;
|
||||
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<ui:TitanoWindow x:Class="Titano.App.Shell.LoginDialog"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
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 Shell.AppName}"
|
||||
IsDialog="True" ResizeMode="NoResize" SizeToContent="Height" Width="440"
|
||||
WindowStartupLocation="CenterOwner" ShowInTaskbar="False">
|
||||
<!-- BRIEF §12.7 login modal: the server is already identified and its certificate trusted. -->
|
||||
<StackPanel Margin="24,18,24,20">
|
||||
<TextBlock Text="{l:Loc Server.Login.Title}" Style="{StaticResource Text.Title}" />
|
||||
<TextBlock x:Name="ServerText" Margin="0,4,0,0" Style="{StaticResource Text.Secondary}" />
|
||||
<Grid Margin="0,18,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="92" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="10" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{l:Loc Server.Login.User}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,12,0" />
|
||||
<TextBox x:Name="User" Grid.Column="1" ToolTip="{l:Loc Tooltips.Server.LoginUser}" AutomationProperties.Name="{l:Loc Server.Login.User}" />
|
||||
<TextBlock Grid.Row="2" Text="{l:Loc Server.Login.Password}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,12,0" />
|
||||
<PasswordBox x:Name="Password" Grid.Row="2" Grid.Column="1" ToolTip="{l:Loc Tooltips.Server.LoginPassword}" AutomationProperties.Name="{l:Loc Server.Login.Password}" />
|
||||
</Grid>
|
||||
<ui:StatusGlyph x:Name="Error" Kind="Error" Margin="0,12,0,0" FontSize="{StaticResource Size.Secondary}" Visibility="Collapsed" />
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,22,0,0">
|
||||
<Button Content="{l:Loc Server.Login.Cancel}" ToolTip="{l:Loc Tooltips.Server.LoginCancel}" IsCancel="True" MinWidth="96" Click="OnCancel" />
|
||||
<Button x:Name="SignIn" Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Login.SignIn}" ToolTip="{l:Loc Tooltips.Server.SignIn}" IsDefault="True" MinWidth="96" Margin="8,0,0,0" Click="OnSignIn" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</ui:TitanoWindow>
|
||||
@@ -0,0 +1,61 @@
|
||||
using System.Windows;
|
||||
using Titano.Ui.Controls;
|
||||
|
||||
namespace Titano.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// The login form (BRIEF §12.7). It calls back the connection with the credentials and stays open with the
|
||||
/// error sentence until the sign-in succeeds or the user cancels. The password never leaves the PasswordBox
|
||||
/// except for that call.
|
||||
/// </summary>
|
||||
public sealed partial class LoginDialog : TitanoWindow
|
||||
{
|
||||
private readonly Func<string, string, Task<string?>> _signIn;
|
||||
|
||||
private LoginDialog(string server, string? username, Func<string, string, Task<string?>> signIn)
|
||||
{
|
||||
_signIn = signIn;
|
||||
InitializeComponent();
|
||||
ServerText.Text = server;
|
||||
User.Text = username ?? string.Empty;
|
||||
Loaded += (_, _) =>
|
||||
{
|
||||
if (User.Text.Length == 0) User.Focus();
|
||||
else Password.Focus();
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>True when the user signed in.</summary>
|
||||
public static bool Ask(Window? owner, string server, string? username, Func<string, string, Task<string?>> signIn)
|
||||
{
|
||||
var dialog = new LoginDialog(server, username, signIn);
|
||||
if (owner is { IsVisible: true }) dialog.Owner = owner;
|
||||
else dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
|
||||
return dialog.ShowDialog() == true;
|
||||
}
|
||||
|
||||
private void OnCancel(object sender, RoutedEventArgs e) => DialogResult = false;
|
||||
|
||||
private async void OnSignIn(object sender, RoutedEventArgs e)
|
||||
{
|
||||
SignIn.IsEnabled = false;
|
||||
Error.Visibility = Visibility.Collapsed;
|
||||
try
|
||||
{
|
||||
var error = await _signIn(User.Text, Password.Password);
|
||||
if (error is null)
|
||||
{
|
||||
DialogResult = true;
|
||||
return;
|
||||
}
|
||||
Error.Text = error;
|
||||
Error.Visibility = Visibility.Visible;
|
||||
Password.Clear();
|
||||
Password.Focus();
|
||||
}
|
||||
finally
|
||||
{
|
||||
SignIn.IsEnabled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
|
||||
xmlns:shell="clr-namespace:Titano.App.Shell"
|
||||
xmlns:s="clr-namespace:Titano.App.Sections"
|
||||
Title="{Binding WindowTitle}"
|
||||
Width="1440" Height="900" MinWidth="1200" MinHeight="760"
|
||||
WindowStartupLocation="CenterScreen">
|
||||
@@ -47,23 +48,30 @@
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Job bar (DESIGN §4): current job, progress, time left, pause; "Ready" when idle. -->
|
||||
<ui:JobBar Text="{Binding JobText}" Progress="{Binding JobProgress}" IsActive="{Binding IsJobActive}" IsIndeterminate="{Binding IsJobIndeterminate}"
|
||||
StopCommand="{Binding StopJobCommand}" StopToolTip="{l:Loc Tooltips.Shell.StopJob}" />
|
||||
StopCommand="{Binding StopJobCommand}" StopToolTip="{l:Loc Tooltips.Shell.PauseJob}" ActionGlyph="{StaticResource Icon.Pause}" />
|
||||
|
||||
<ContentControl Grid.Row="1" Content="{Binding Current}" Focusable="False" />
|
||||
|
||||
<!-- Status strip -->
|
||||
<Border Grid.Row="2" Height="30" Background="{DynamicResource Brush.Chrome}" Padding="20,0">
|
||||
<StackPanel Orientation="Horizontal" TextElement.FontSize="12" TextElement.Foreground="{DynamicResource Brush.TextMuted}">
|
||||
<TextBlock Text="{Binding SequencesText}" Margin="0,0,18,0" />
|
||||
<TextBlock Text="{Binding PhotosText}" Margin="0,0,18,0" />
|
||||
<TextBlock Text="{Binding StorageText}" Margin="0,0,18,0" />
|
||||
<TextBlock x:Name="Connection" Text="{Binding ConnectionText}" Margin="0,0,18,0" />
|
||||
<TextBlock Text="{Binding JobsText}" />
|
||||
<TextBlock Text="{Binding SequencesText}" Margin="0,0,18,0" VerticalAlignment="Center" />
|
||||
<TextBlock Text="{Binding PhotosText}" Margin="0,0,18,0" VerticalAlignment="Center" />
|
||||
<TextBlock Text="{Binding StorageText}" Margin="0,0,18,0" VerticalAlignment="Center" />
|
||||
<TextBlock x:Name="Connection" Text="{Binding ConnectionText}" Margin="0,0,18,0" VerticalAlignment="Center" />
|
||||
<TextBlock Text="{Binding JobsText}" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<ui:ToastHost x:Name="Toasts" Grid.Row="0" Grid.RowSpan="3" />
|
||||
</Grid>
|
||||
|
||||
<!-- First run (Welcome.html): the shell dimmed behind one dialog. -->
|
||||
<Grid Grid.ColumnSpan="2" Visibility="{Binding IsWelcomeOpen, Converter={StaticResource BoolToVisibility}}">
|
||||
<Border Background="{DynamicResource Brush.Scrim}" />
|
||||
<s:WelcomeView DataContext="{Binding Welcome}" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,114,0,0" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
</ui:TitanoWindow>
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Collections.Specialized;
|
||||
using System.Windows;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Ui.Controls;
|
||||
|
||||
namespace Titano.App.Shell;
|
||||
@@ -14,18 +15,21 @@ public partial class MainWindow : TitanoWindow
|
||||
DataContext = shell;
|
||||
InitializeComponent();
|
||||
Rail.Width = shell.IsRailCollapsed ? 48 : 128;
|
||||
UpdateConnection();
|
||||
shell.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName is nameof(ShellViewModel.IsRailCollapsed) or "")
|
||||
Rail.Width = shell.IsRailCollapsed ? 48 : 128;
|
||||
if (e.PropertyName is nameof(ShellViewModel.IsConnected) or "")
|
||||
Connection.Foreground = (System.Windows.Media.Brush)FindResource(shell.IsConnected ? "Brush.Accent" : "Brush.TextMuted");
|
||||
if (e.PropertyName is nameof(ShellViewModel.IsConnected) or "") UpdateConnection();
|
||||
};
|
||||
shell.PendingToasts.CollectionChanged += OnToastRequested;
|
||||
RestorePlacement();
|
||||
Closing += (_, _) => SavePlacement();
|
||||
}
|
||||
|
||||
private void UpdateConnection() =>
|
||||
Connection.SetResourceReference(System.Windows.Controls.TextBlock.ForegroundProperty, _shell.IsConnected ? "Brush.Accent" : "Brush.TextMuted");
|
||||
|
||||
private void OnToastRequested(object? sender, NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
if (e.Action != NotifyCollectionChangedAction.Add || e.NewItems is null) return;
|
||||
@@ -35,8 +39,8 @@ public partial class MainWindow : TitanoWindow
|
||||
|
||||
private void RestorePlacement()
|
||||
{
|
||||
var p = App.Current.Settings.Window;
|
||||
if (p is null || p.Width < MinWidth || p.Height < MinHeight) return;
|
||||
var p = _shell.Services.Settings.Window;
|
||||
if (p is null || p.Width < MinWidth || p.Height < MinHeight || _shell.Services.Environment.IsCapture) return;
|
||||
var virtualScreen = new Rect(SystemParameters.VirtualScreenLeft, SystemParameters.VirtualScreenTop, SystemParameters.VirtualScreenWidth, SystemParameters.VirtualScreenHeight);
|
||||
var rect = new Rect(p.Left, p.Top, p.Width, p.Height);
|
||||
if (!virtualScreen.IntersectsWith(rect)) return;
|
||||
@@ -50,8 +54,9 @@ public partial class MainWindow : TitanoWindow
|
||||
|
||||
private void SavePlacement()
|
||||
{
|
||||
if (_shell.Services.Environment.IsCapture) return;
|
||||
var b = RestoreBounds;
|
||||
App.Current.Settings.Window = new Infrastructure.AppSettings.WindowPlacement
|
||||
_shell.Services.Settings.Window = new AppSettings.WindowPlacement
|
||||
{
|
||||
Left = b.Left,
|
||||
Top = b.Top,
|
||||
|
||||
@@ -3,64 +3,134 @@ using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.DesignTime;
|
||||
using Titano.App.Settings;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Ui.Theming;
|
||||
|
||||
namespace Titano.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// <c>Titano.exe --capture <dir></c>: renders every section at 1440×900 in dark and light themes to PNG for
|
||||
/// visual regression and phase reports (BRIEF §20.2), then exits.
|
||||
/// <c>Titano.exe --capture <dir></c>: renders every client screen at 1440×900 in the dark and light themes to
|
||||
/// <c><screen>-<theme>.png</c> from <see cref="SampleData"/> (first run on an empty index, then a populated
|
||||
/// one), for visual review and phase reports (BRIEF §20.2), then exits.
|
||||
/// </summary>
|
||||
public static class ScreenCapture
|
||||
{
|
||||
public static void Run(MainWindow window, ShellViewModel shell, string directory)
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
window.WindowStartupLocation = WindowStartupLocation.Manual;
|
||||
window.Left = -20000;
|
||||
window.Top = -20000;
|
||||
window.Width = 1440;
|
||||
window.Height = 900;
|
||||
window.ShowActivated = false;
|
||||
window.ShowInTaskbar = false;
|
||||
window.Show();
|
||||
private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light];
|
||||
|
||||
window.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, () =>
|
||||
public static async Task RunAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
|
||||
{
|
||||
var written = 0;
|
||||
try
|
||||
{
|
||||
var written = 0;
|
||||
try
|
||||
Directory.CreateDirectory(directory);
|
||||
window.WindowStartupLocation = WindowStartupLocation.Manual;
|
||||
window.Left = -20000;
|
||||
window.Top = -20000;
|
||||
window.Width = 1440;
|
||||
window.Height = 900;
|
||||
window.ShowActivated = false;
|
||||
window.ShowInTaskbar = false;
|
||||
window.Show();
|
||||
|
||||
// First run: empty index, nothing connected, the welcome dialog over the empty Library.
|
||||
await sample.OpenEmptyAsync();
|
||||
await shell.StartAsync();
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
foreach (var theme in new[] { AppTheme.Dark, AppTheme.Light })
|
||||
ThemeManager.Apply(theme);
|
||||
shell.Navigate(SectionKey.Library);
|
||||
shell.ShowWelcome();
|
||||
shell.Welcome!.ShowDiscovered(new Server.DiscoveredServer("Studio NAS", "https://nas.local:8443"));
|
||||
written += await SaveAsync(window, directory, "welcome", theme);
|
||||
shell.CompleteWelcome();
|
||||
written += await SaveAsync(window, directory, "library-empty", theme);
|
||||
shell.Navigate(SectionKey.Server);
|
||||
written += await SaveAsync(window, directory, "server-signedout", theme);
|
||||
}
|
||||
|
||||
// A populated archive, jobs in every state and a signed-in server.
|
||||
await sample.FillAsync();
|
||||
await shell.Library.RefreshAsync();
|
||||
await shell.Jobs.ReloadAsync();
|
||||
await shell.Services.Server.RestoreAsync();
|
||||
shell.About.SetResult(null);
|
||||
await shell.Settings.DetectEncodersAsync();
|
||||
await shell.Settings.SelfTestAsync();
|
||||
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
|
||||
shell.Library.LayoutIndex = 0;
|
||||
shell.Library.ClearSelectionCommand.Execute(null);
|
||||
shell.Navigate(SectionKey.Library);
|
||||
written += await SaveAsync(window, directory, "library", theme, waitForThumbnails: shell);
|
||||
if (shell.Library.Items.Count > 0) shell.Library.Items[0].IsSelected = true;
|
||||
written += await SaveAsync(window, directory, "library-selection", theme, waitForThumbnails: shell);
|
||||
shell.Library.LayoutIndex = 1;
|
||||
written += await SaveAsync(window, directory, "library-list", theme, waitForThumbnails: shell);
|
||||
shell.Library.LayoutIndex = 0;
|
||||
shell.Library.ClearSelectionCommand.Execute(null);
|
||||
|
||||
shell.Navigate(SectionKey.Jobs);
|
||||
if (shell.Jobs.Rows.Count > 0) shell.Jobs.Rows[0].IsExpanded = true;
|
||||
written += await SaveAsync(window, directory, "jobs", theme);
|
||||
|
||||
shell.Navigate(SectionKey.Server);
|
||||
written += await SaveAsync(window, directory, "server", theme);
|
||||
|
||||
shell.Navigate(SectionKey.Settings);
|
||||
foreach (var page in Enum.GetValues<SettingsPage>())
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
foreach (var section in shell.AllSections)
|
||||
{
|
||||
shell.Navigate(section.Key);
|
||||
Settle(window);
|
||||
if (Save(window, Path.Combine(directory, $"{section.Key}-{theme.ToString().ToLowerInvariant()}.png"))) written++;
|
||||
}
|
||||
shell.Settings.Page = page;
|
||||
written += await SaveAsync(window, directory, "settings-" + page.ToString().ToLowerInvariant(), theme);
|
||||
}
|
||||
|
||||
shell.Navigate(SectionKey.About);
|
||||
written += await SaveAsync(window, directory, "about", theme);
|
||||
|
||||
foreach (var key in new[] { SectionKey.Import, SectionKey.Sequence, SectionKey.Archive })
|
||||
{
|
||||
shell.Navigate(key);
|
||||
written += await SaveAsync(window, directory, key.ToString().ToLowerInvariant(), theme);
|
||||
}
|
||||
Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}");
|
||||
if (written == 0) Environment.ExitCode = 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error("capture", "Capture failed", ex);
|
||||
Environment.ExitCode = 1;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Application.Current.Shutdown();
|
||||
}
|
||||
});
|
||||
Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}");
|
||||
if (written == 0) Environment.ExitCode = 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error("capture", "Capture failed", ex);
|
||||
Environment.ExitCode = 1;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Application.Current.Shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
private static void Settle(Window window)
|
||||
private static async Task<int> SaveAsync(Window window, string directory, string screen, AppTheme theme, ShellViewModel? waitForThumbnails = null)
|
||||
{
|
||||
await Settle(window);
|
||||
if (waitForThumbnails?.Services.Thumbnails is { } thumbnails)
|
||||
{
|
||||
// Thumbnails decode on the thread pool; give them a moment, then settle again.
|
||||
for (var i = 0; i < 40 && thumbnails.PendingLoads > 0; i++) await Task.Delay(50);
|
||||
await Task.Delay(100);
|
||||
await Settle(window);
|
||||
}
|
||||
return Save(window, Path.Combine(directory, $"{screen}-{theme.ToString().ToLowerInvariant()}.png")) ? 1 : 0;
|
||||
}
|
||||
|
||||
private static async Task Settle(Window window)
|
||||
{
|
||||
window.UpdateLayout();
|
||||
// Let bindings, templates and deferred renders complete.
|
||||
window.Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, () => { });
|
||||
// Let bindings, templates, async continuations and deferred renders complete.
|
||||
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
|
||||
await Task.Delay(30);
|
||||
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
|
||||
window.UpdateLayout();
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Shell;
|
||||
|
||||
/// <summary>State of the main window: rail, current section, job bar and status strip (BRIEF §12.1).</summary>
|
||||
/// <summary>State of the main window: rail, current section, job bar, status strip and first run (BRIEF §12.1).</summary>
|
||||
public sealed class ShellViewModel : LocalizedViewModel
|
||||
{
|
||||
private readonly AppSettings _settings;
|
||||
@@ -24,18 +24,22 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
private long _totalBytes;
|
||||
private string? _serverName;
|
||||
private int _jobCount;
|
||||
private int _queuedCount;
|
||||
private WelcomeViewModel? _welcome;
|
||||
private Guid? _currentSequenceId;
|
||||
|
||||
public ShellViewModel(AppSettings settings)
|
||||
public ShellViewModel(AppServices services)
|
||||
{
|
||||
_settings = settings;
|
||||
_isRailCollapsed = settings.RailCollapsed;
|
||||
Services = services;
|
||||
_settings = services.Settings;
|
||||
_isRailCollapsed = _settings.RailCollapsed;
|
||||
Library = new LibraryViewModel(this);
|
||||
Import = new ImportViewModel(this);
|
||||
Sequence = new SequenceViewModel(this);
|
||||
Archive = new ArchiveViewModel(this);
|
||||
Jobs = new JobsViewModel(this);
|
||||
Server = new ServerViewModel(this);
|
||||
Settings = new SettingsViewModel(this, settings);
|
||||
Settings = new SettingsViewModel(this);
|
||||
About = new AboutViewModel(this);
|
||||
TopSections = [Library, Import, Sequence, Archive, Jobs, Server];
|
||||
BottomSections = [Settings, About];
|
||||
@@ -49,8 +53,12 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
else if (p is string name && Enum.TryParse<SectionKey>(name, out var key)) Navigate(key);
|
||||
});
|
||||
ToggleRailCommand = new RelayCommand(() => IsRailCollapsed = !IsRailCollapsed);
|
||||
services.Server.PropertyChanged += (_, _) => SetConnection(services.Server.ServerName);
|
||||
if (!_settings.FirstRunCompleted) _welcome = new WelcomeViewModel(this);
|
||||
}
|
||||
|
||||
public AppServices Services { get; }
|
||||
|
||||
public LibraryViewModel Library { get; }
|
||||
public ImportViewModel Import { get; }
|
||||
public SequenceViewModel Sequence { get; }
|
||||
@@ -70,6 +78,18 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
/// <summary>In-window notifications; the window binds its <see cref="ToastHost"/> here.</summary>
|
||||
public ObservableCollection<Toast> PendingToasts { get; } = [];
|
||||
|
||||
/// <summary>First-run choice (Welcome.html); null once made.</summary>
|
||||
public WelcomeViewModel? Welcome
|
||||
{
|
||||
get => _welcome;
|
||||
private set
|
||||
{
|
||||
if (Set(ref _welcome, value)) OnPropertyChanged(nameof(IsWelcomeOpen));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsWelcomeOpen => _welcome is not null;
|
||||
|
||||
public SectionViewModel Current
|
||||
{
|
||||
get => _current;
|
||||
@@ -94,12 +114,54 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
|
||||
public string RailToggleToolTip => Loc.L(IsRailCollapsed ? "Tooltips.Shell.ExpandRail" : "Tooltips.Shell.CollapseRail");
|
||||
|
||||
/// <summary>The sequence the editor opens (set by the Library and the Jobs screen).</summary>
|
||||
public Guid? CurrentSequenceId
|
||||
{
|
||||
get => _currentSequenceId;
|
||||
private set => Set(ref _currentSequenceId, value);
|
||||
}
|
||||
|
||||
/// <summary>Loads the data of every screen once the index is open (or failed to open).</summary>
|
||||
public async Task StartAsync()
|
||||
{
|
||||
if (Services.OpenError is { } error) ReportError(error);
|
||||
Jobs.Attach();
|
||||
await Library.AttachAsync();
|
||||
Settings.Attach();
|
||||
About.Attach();
|
||||
await Server.AttachAsync();
|
||||
}
|
||||
|
||||
/// <summary>Opens a sequence in the editor.</summary>
|
||||
public void OpenSequence(Guid sequenceId)
|
||||
{
|
||||
CurrentSequenceId = sequenceId;
|
||||
Navigate(SectionKey.Sequence);
|
||||
}
|
||||
|
||||
/// <summary>Closes the first-run overlay for good.</summary>
|
||||
public void CompleteWelcome()
|
||||
{
|
||||
_settings.FirstRunCompleted = true;
|
||||
Services.SaveSettings();
|
||||
Welcome?.Dispose();
|
||||
Welcome = null;
|
||||
}
|
||||
|
||||
/// <summary>Shows the first-run overlay again (capture, tests).</summary>
|
||||
public void ShowWelcome() => Welcome ??= new WelcomeViewModel(this);
|
||||
|
||||
// ---- Job bar ----
|
||||
public string JobText => _jobActive && _jobText is not null ? _jobText : Loc.L("Shell.JobBar.Ready", _jobCount);
|
||||
public string JobText => _jobActive && _jobText is not null
|
||||
? _jobText
|
||||
: _queuedCount > 0 ? Loc.L("Shell.JobBar.Ready", _queuedCount) : Loc.L("Shell.JobBar.Idle");
|
||||
|
||||
public double JobProgress { get => _jobProgress; private set => Set(ref _jobProgress, value); }
|
||||
public bool IsJobActive { get => _jobActive; private set => Set(ref _jobActive, value); }
|
||||
public bool IsJobIndeterminate { get => _jobIndeterminate; private set => Set(ref _jobIndeterminate, value); }
|
||||
public ICommand? StopJobCommand { get; set; }
|
||||
|
||||
/// <summary>Pauses the job the bar shows.</summary>
|
||||
public ICommand? StopJobCommand => Jobs.PauseCurrentCommand;
|
||||
|
||||
/// <summary>Updates the global job bar (and the taskbar progress through the window).</summary>
|
||||
public void SetJob(string? text, double progress, bool indeterminate = false)
|
||||
@@ -114,7 +176,7 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
// ---- Status strip ----
|
||||
public string SequencesText => Loc.Plural("Shell.Status.Sequences", _sequenceCount);
|
||||
public string PhotosText => Loc.Plural("Shell.Status.Photos", _photoCount);
|
||||
public string StorageText => Formatting.Bytes(_totalBytes);
|
||||
public string StorageText => _sequenceCount == 0 && _settings.LastArchivePath is null ? Loc.L("Shell.Status.NoArchive") : Formatting.Bytes(_totalBytes);
|
||||
public string ConnectionText => _serverName is null ? Loc.L("Shell.Status.NotConnected") : Loc.L("Shell.Status.Connected", _serverName);
|
||||
public bool IsConnected => _serverName is not null;
|
||||
public string JobsText => Loc.Plural("Shell.Status.Jobs", _jobCount);
|
||||
@@ -131,14 +193,17 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
|
||||
public void SetConnection(string? serverName)
|
||||
{
|
||||
if (_serverName == serverName) return;
|
||||
_serverName = serverName;
|
||||
OnPropertyChanged(nameof(ConnectionText));
|
||||
OnPropertyChanged(nameof(IsConnected));
|
||||
}
|
||||
|
||||
public void SetJobCount(int count)
|
||||
/// <summary>Active jobs (running + queued) for the status strip, queued ones for the idle job bar.</summary>
|
||||
public void SetJobCount(int active, int queued = 0)
|
||||
{
|
||||
_jobCount = count;
|
||||
_jobCount = active;
|
||||
_queuedCount = queued;
|
||||
OnPropertyChanged(nameof(JobsText));
|
||||
OnPropertyChanged(nameof(JobText));
|
||||
}
|
||||
@@ -152,6 +217,17 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
|
||||
public void ShowToast(Toast toast) => PendingToasts.Add(toast);
|
||||
|
||||
/// <summary>A one-line notice with one action (job done, update available).</summary>
|
||||
public void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null) =>
|
||||
ShowToast(new Toast
|
||||
{
|
||||
Title = title,
|
||||
Message = message,
|
||||
ActionText = actionText,
|
||||
ActionToolTip = actionToolTip,
|
||||
ActionCommand = action is null ? null : new RelayCommand(action),
|
||||
});
|
||||
|
||||
/// <summary>Errors are one sentence saying what happened plus one action (BRIEF §0.2 rule 6).</summary>
|
||||
public void ReportError(Exception ex)
|
||||
{
|
||||
@@ -162,7 +238,18 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
Message = ex.Message,
|
||||
ActionText = Loc.L("Common.OpenLogs"),
|
||||
ActionToolTip = Loc.L("Tooltips.Common.OpenLogs"),
|
||||
ActionCommand = new RelayCommand(() => ShellActions.OpenFolder(App.Current.Environment.LogDirectory)),
|
||||
ActionCommand = new RelayCommand(() => ShellActions.Reveal(Services.Environment.LogDirectory)),
|
||||
});
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
Jobs.Dispose();
|
||||
Library.Dispose();
|
||||
Server.Dispose();
|
||||
Settings.Dispose();
|
||||
About.Dispose();
|
||||
Welcome?.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user