refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout and the system SQLite. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow; the throw-away server runs without durability) and pe-check. - Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR, 3 on the shared runner; the weekly performance gates keep theirs). BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,10 @@
|
||||
namespace Chronos.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,250 @@
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Jobs;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>
|
||||
/// What the Library's quick and mass actions run (BRIEF §12.2): analyses, proxies, verifies and renders as jobs on
|
||||
/// this PC's engine, or posted to the server for a sequence that only lives there; uploads, downloads and settings
|
||||
/// exchanges through the sync engine (as the Server screen does); ratings through the archive engine (sidecar and
|
||||
/// index together). Every queued job is announced with a toast that opens the Jobs screen.
|
||||
/// </summary>
|
||||
public sealed class LibraryActions(ShellViewModel shell)
|
||||
{
|
||||
/// <summary>Wire names of the job kinds a remote card posts (<c>POST /api/v1/jobs</c>).</summary>
|
||||
private const string RenderKind = "render";
|
||||
|
||||
private const string DeepAnalyseKind = "deep-analyse";
|
||||
|
||||
private Infrastructure.AppServices Services => shell.Services;
|
||||
|
||||
/// <summary>The signed-in server's sync engine and connection; null while signed out.</summary>
|
||||
public RemoteSource? Remote() =>
|
||||
Services.Sync is { Service: { } service, Server: { } server, Remote: { } remote } ? new RemoteSource(service, server, remote) : null;
|
||||
|
||||
/// <summary>What the signed-in account may do; nothing while signed out.</summary>
|
||||
public SyncRights Rights => Services.Server.User is { } user ? SyncRights.Of(user.Permissions) : default;
|
||||
|
||||
/// <summary>A job can be posted to the server now (a remote card's Analyse and Render).</summary>
|
||||
public bool CanPost => Services.Server is { IsConnected: true, Flow: { Address: not null, Token: not null } };
|
||||
|
||||
/// <summary>Deep analysis of sequences on this PC (one job), or of a remote card on the server.</summary>
|
||||
public async Task AnalyseAsync(IReadOnlyList<Sequence> sequences)
|
||||
{
|
||||
if (sequences is [{ Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly } remote])
|
||||
{
|
||||
await PostAsync(() => Task.FromResult(new CreateJobRequest(DeepAnalyseKind, [remote.Id], null)), JobKind.DeepAnalyse, remote.DisplayTitle);
|
||||
return;
|
||||
}
|
||||
await QueueAsync(ProcessingJobs.DeepAnalysis([.. sequences.Select(s => s.Id)], Label(sequences)));
|
||||
}
|
||||
|
||||
public Task ProxiesAsync(IReadOnlyList<Sequence> sequences) => QueueAsync(ArchiveJobs.Proxies([.. sequences.Select(s => s.Id)], Label(sequences)));
|
||||
|
||||
/// <summary>Verification is an archive job: one per archive, naming its sequences.</summary>
|
||||
public async Task VerifyAsync(IReadOnlyList<Sequence> sequences)
|
||||
{
|
||||
if (Services.Database is not { } db) return;
|
||||
foreach (var group in sequences.GroupBy(s => s.ArchiveId))
|
||||
{
|
||||
if (await db.Archives.GetAsync(group.Key) is { } archive) await QueueAsync(ArchiveJobs.Verify(archive, [.. group.Select(s => s.Id)]));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Render quick action: the sequence's own export with its project as stored — the preset chosen in the editor,
|
||||
/// else the advisor's recommendation the analyses store in the project, else the default — on this PC's engine, or
|
||||
/// posted to the server for a remote card, which renders it where the originals are.
|
||||
/// </summary>
|
||||
public async Task RenderAsync(Sequence sequence)
|
||||
{
|
||||
if (sequence is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly })
|
||||
{
|
||||
if (Remote() is not { } remote)
|
||||
{
|
||||
NotConnected();
|
||||
return;
|
||||
}
|
||||
await PostAsync(async () =>
|
||||
{
|
||||
var (project, width, height) = await RemoteProjectAsync(remote, sequence.Id);
|
||||
return new CreateJobRequest(RenderKind, [sequence.Id], ProcessingJobs.Render(sequence, project.Export with { Batch = [] }, width, height).ParametersJson);
|
||||
}, JobKind.Render, sequence.DisplayTitle);
|
||||
return;
|
||||
}
|
||||
if (Services.Database is not { } db) return;
|
||||
// The project as stored now: the editor may have changed it since the card was read.
|
||||
var current = await db.Sequences.GetAsync(sequence.Id) ?? sequence;
|
||||
var first = (await db.Frames.ListBySequenceAsync(sequence.Id, -1, 1)).FirstOrDefault();
|
||||
var (w, h) = first is null ? (0, 0) : first.Orientation is >= 5 and <= 8 ? (first.Height, first.Width) : (first.Width, first.Height);
|
||||
var export = Project(current.SettingsJson).Export with { Batch = [] };
|
||||
await QueueAsync(ProcessingJobs.Render(current, export, w, h));
|
||||
}
|
||||
|
||||
/// <summary>Runs one row action of the sync table on a sequence (the card's Sync, a mass Upload or Download); false when it could not start.</summary>
|
||||
public async Task<bool> SyncAsync(SelectedSequence selected, SyncAction action)
|
||||
{
|
||||
if (Remote() is not { } remote || Services.Engine is not { } engine) return false;
|
||||
var entry = selected.Sync;
|
||||
switch (action)
|
||||
{
|
||||
case SyncAction.Upload when !selected.IsRemote:
|
||||
await remote.Service.EnqueueUploadAsync(engine, remote.Server, selected.Sequence);
|
||||
return true;
|
||||
case SyncAction.SendExports when !selected.IsRemote:
|
||||
await remote.Service.EnqueueSendExportsAsync(engine, remote.Server, selected.Sequence);
|
||||
return true;
|
||||
case SyncAction.DownloadOriginals when entry is not null:
|
||||
if ((entry.Local?.ArchiveId ?? (await Services.Sync.CurrentArchiveAsync())?.Id) is not { } archive)
|
||||
{
|
||||
shell.Notify(Loc.L("Errors.Sync.NoArchive"));
|
||||
return false;
|
||||
}
|
||||
await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
|
||||
return true;
|
||||
case SyncAction.GetExports when entry is not null:
|
||||
await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Exports, null);
|
||||
return true;
|
||||
case SyncAction.SyncSettings when entry is not null:
|
||||
await remote.Service.SyncSettingsAsync(remote.Remote, entry.Id, Services.Sync.Policy, CancellationToken.None);
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a remote card with proxies (BRIEF §14.5): at once when its proxies are cached here, otherwise after the
|
||||
/// proxy download this queues. Returns that download job, or null when the editor opened (or nothing could start).
|
||||
/// </summary>
|
||||
public async Task<Guid?> OpenRemoteAsync(Sequence sequence)
|
||||
{
|
||||
if (Remote() is not { } remote || Services.Engine is not { } engine)
|
||||
{
|
||||
NotConnected();
|
||||
return null;
|
||||
}
|
||||
// The proxy cache is read off the UI thread: its manifest holds every frame.
|
||||
if (await Task.Run(() => remote.Service.OpenRemote(remote.Server, sequence.Id)) is not null)
|
||||
{
|
||||
shell.OpenSequence(sequence.Id);
|
||||
return null;
|
||||
}
|
||||
var job = await remote.Service.EnqueueDownloadAsync(engine, remote.Server, sequence.Id, sequence.DisplayTitle, SyncDownloadMode.Proxies, null);
|
||||
Queued(JobKind.Download, sequence.DisplayTitle);
|
||||
return job.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the rating of sequences on this PC (sidecar and index together), changing nothing else: the title, tags and
|
||||
/// notes are those the sidecar holds then, not the Library's copy. Returns how many changed.
|
||||
/// </summary>
|
||||
public async Task<int> RateAsync(IReadOnlyList<Sequence> sequences, int rating)
|
||||
{
|
||||
if (Services.Archives is not { } archives || Services.Database is not { } db) return 0;
|
||||
var changed = 0;
|
||||
try
|
||||
{
|
||||
foreach (var s in sequences)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(s.Id) is not { } current || current.Rating == rating) continue;
|
||||
await Task.Run(() => archives.EditSequenceInfoAsync(s.Id, info => info with { Rating = rating }));
|
||||
changed++;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
|
||||
{
|
||||
Log.Warning("library", "Rating failed", ex);
|
||||
shell.Notify(Loc.L("Library.Rate.Failed"), ArchiveFailures.Cause(ex));
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>"Deep analysis queued · Harbour sunset", with a way to the Jobs screen.</summary>
|
||||
public void Queued(JobKind kind, string 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));
|
||||
|
||||
public static string Label(IReadOnlyList<Sequence> sequences) =>
|
||||
sequences.Count == 1 ? sequences[0].DisplayTitle : Loc.Plural("Library.Selection.Count", sequences.Count);
|
||||
|
||||
private async Task QueueAsync(ArchiveJobRequest request)
|
||||
{
|
||||
if (request.Targets.Count == 0) return;
|
||||
if (Services.Engine is not { } engine)
|
||||
{
|
||||
shell.Notify(Loc.L("Library.Blocked.NoIndex"));
|
||||
return;
|
||||
}
|
||||
await engine.EnqueueAsync(request);
|
||||
Queued(request.Kind, request.Label ?? string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>Posts a job to the signed-in server, which runs it or hands it to a render node (BRIEF §14.6, §14.7).</summary>
|
||||
private async Task PostAsync(Func<Task<CreateJobRequest>> build, JobKind kind, string label)
|
||||
{
|
||||
var session = Services.Server;
|
||||
if (!CanPost || session.Flow is not { Address: { } address, Token: { } token })
|
||||
{
|
||||
NotConnected();
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
var request = await build();
|
||||
using var client = new ChronosClient(address, new CertificatePinning(session.Fingerprints), $"Chronos ({Environment.MachineName})") { Token = token };
|
||||
await client.CreateJobAsync(request);
|
||||
shell.Notify(Loc.L("Library.QueuedServer", JobText.Kind(kind), label));
|
||||
}
|
||||
// A certificate the server changed since sign-in is refused by the pin, not by the network (UntrustedCertificateException).
|
||||
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException)
|
||||
{
|
||||
Log.Warning("library", $"Posting a {kind} job to {address} failed", ex);
|
||||
shell.Notify(Loc.L("Library.Post.Failed"), ErrorText.ForServer(ex), isError: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A remote card's action could not start: the session ended since the card was drawn.</summary>
|
||||
private void NotConnected() => shell.Notify(Loc.L("Library.Remote.Unavailable"), Loc.L("Library.Blocked.NotConnected"));
|
||||
|
||||
/// <summary>The project of a remote card: from its proxy cache when it was opened here, else from the server's manifest; and its frame size when cached.</summary>
|
||||
private static async Task<(ProjectSettings Project, int Width, int Height)> RemoteProjectAsync(RemoteSource remote, Guid id)
|
||||
{
|
||||
if (await Task.Run(() => remote.Service.OpenRemote(remote.Server, id)) is { } cached)
|
||||
{
|
||||
var frame = cached.Frames.FirstOrDefault(f => f.Width > 0);
|
||||
var size = frame is null ? (0, 0) : frame.Orientation is >= 5 and <= 8 ? (frame.Height, frame.Width) : (frame.Width, frame.Height);
|
||||
return (Project(cached.Sequence.SettingsJson), size.Item1, size.Item2);
|
||||
}
|
||||
var manifest = await remote.Remote.GetManifestAsync(id, CancellationToken.None);
|
||||
return (Project(manifest.SettingsJson), 0, 0);
|
||||
}
|
||||
|
||||
private static ProjectSettings Project(string? json)
|
||||
{
|
||||
try
|
||||
{
|
||||
return json is null ? new ProjectSettings() : ProjectSettings.FromJson(json);
|
||||
}
|
||||
catch (System.Text.Json.JsonException ex)
|
||||
{
|
||||
Log.Warning("library", "Unreadable project settings; rendering the defaults", ex);
|
||||
return new ProjectSettings();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>The Library's "Export list as CSV" (BRIEF §12.2): RFC 4180, UTF-8, invariant numbers and dates.</summary>
|
||||
public static class LibraryCsv
|
||||
{
|
||||
/// <summary>One row per sequence; the header is English because the file is data, not UI.</summary>
|
||||
public static string Write(IEnumerable<Sequence> sequences)
|
||||
{
|
||||
var inv = CultureInfo.InvariantCulture;
|
||||
var sb = new StringBuilder("title,first_capture,last_capture,camera_make,camera_model,frames,bytes,folder,tags,origin\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(',')
|
||||
.Append(s is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly } ? "server" : "local").Append("\r\n");
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>
|
||||
/// What the Library's Year and Camera choices and its timeline bands count (BRIEF §4.4 mixed mode): the index's
|
||||
/// figures, the server's sequences without a copy here, or both, as the origin filter says.
|
||||
/// </summary>
|
||||
public static class LibraryFacets
|
||||
{
|
||||
/// <summary>
|
||||
/// <paramref name="local"/> with its years, months and cameras replaced by those of the origins in view: the index's
|
||||
/// own unless only the server's sequences show, plus the remote cards' unless only this PC's show.
|
||||
/// </summary>
|
||||
public static ArchiveStats Of(ArchiveStats local, IReadOnlyList<Sequence> remote, OriginFilter origin)
|
||||
{
|
||||
var keepLocal = origin != OriginFilter.Server;
|
||||
var years = keepLocal ? local.ByYear.ToDictionary(y => y.Year) : [];
|
||||
var months = keepLocal ? local.ByMonth.ToDictionary(m => (m.Year, m.Month)) : [];
|
||||
var cameras = keepLocal ? local.ByCamera.ToDictionary(c => (c.Make, c.Model)) : [];
|
||||
foreach (var s in origin == OriginFilter.Local ? [] : remote)
|
||||
{
|
||||
if (s.FirstCapture is { } at)
|
||||
{
|
||||
years[at.Year] = years.TryGetValue(at.Year, out var y)
|
||||
? y with { Sequences = y.Sequences + 1, Photos = y.Photos + s.FrameCount, Bytes = y.Bytes + s.TotalBytes }
|
||||
: new YearBucket(at.Year, 1, s.FrameCount, s.TotalBytes);
|
||||
months[(at.Year, at.Month)] = months.TryGetValue((at.Year, at.Month), out var m)
|
||||
? m with { Sequences = m.Sequences + 1, Photos = m.Photos + s.FrameCount }
|
||||
: new MonthBucket(at.Year, at.Month, 1, s.FrameCount);
|
||||
}
|
||||
cameras[(s.CameraMake, s.CameraModel)] = cameras.TryGetValue((s.CameraMake, s.CameraModel), out var c)
|
||||
? c with { Sequences = c.Sequences + 1, Photos = c.Photos + s.FrameCount, Bytes = c.Bytes + s.TotalBytes }
|
||||
: new CameraBucket(s.CameraMake, s.CameraModel, 1, s.FrameCount, s.TotalBytes);
|
||||
}
|
||||
return local with
|
||||
{
|
||||
ByYear = [.. years.Values.OrderBy(y => y.Year)],
|
||||
ByMonth = [.. months.Values.OrderBy(m => m.Year).ThenBy(m => m.Month)],
|
||||
ByCamera = [.. cameras.Values],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>Status choices of the Library toolbar (Main.html: analysed, proxies, rendered, synced); each is a test the index can run.</summary>
|
||||
public enum StatusFilter
|
||||
{
|
||||
Any,
|
||||
Analysed,
|
||||
NotAnalysed,
|
||||
Proxies,
|
||||
NoProxies,
|
||||
Rendered,
|
||||
NotRendered,
|
||||
Verified,
|
||||
NotVerified,
|
||||
Synced,
|
||||
Warnings,
|
||||
}
|
||||
|
||||
/// <summary>Where the sequences of the Library live (BRIEF §4.4 mixed mode): both, this PC, or only the signed-in server.</summary>
|
||||
public enum OriginFilter
|
||||
{
|
||||
Any,
|
||||
Local,
|
||||
Server,
|
||||
}
|
||||
|
||||
/// <summary>Library filters (search, year, camera, status, tag, origin) 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 OriginFilter Origin { 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
|
||||
&& Origin == OriginFilter.Any;
|
||||
|
||||
/// <summary>The same sort without filters ("Clear filters").</summary>
|
||||
public LibraryFilter Cleared() => new() { Sort = Sort };
|
||||
|
||||
/// <summary>Sync states a "Synced" sequence is in: the ones whose card wears the ● Synced glyph.</summary>
|
||||
public static IReadOnlyCollection<SyncState> SyncedStates { get; } = [SyncState.InSync, SyncState.LocalAhead];
|
||||
|
||||
/// <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,
|
||||
Rendered = Status switch
|
||||
{
|
||||
StatusFilter.Rendered => true,
|
||||
StatusFilter.NotRendered => false,
|
||||
_ => null,
|
||||
},
|
||||
SyncStates = Status == StatusFilter.Synced ? SyncedStates : null,
|
||||
Sort = Sort,
|
||||
Limit = limit,
|
||||
Cursor = cursor,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The same test the index applies to its rows (<see cref="ToQuery"/>), for sequences that are not in the index
|
||||
/// (server sequences without a local copy): title, camera or tag text, capture year, camera model, status, tag.
|
||||
/// </summary>
|
||||
public bool Matches(Sequence sequence)
|
||||
{
|
||||
if (Year is { } year && sequence.FirstCapture?.Year != year) return false;
|
||||
if (Camera is not null && sequence.CameraModel != Camera) return false;
|
||||
if (!MatchesStatus(sequence, Status)) return false;
|
||||
if (Tag is not null && !sequence.Tags.Contains(TagRepository.Normalize(Tag), StringComparer.OrdinalIgnoreCase)) return false;
|
||||
if (string.IsNullOrWhiteSpace(Text)) return true;
|
||||
var text = Text.Trim();
|
||||
return new[] { sequence.Title, sequence.CameraMake, sequence.CameraModel }.Any(v => v?.Contains(text, StringComparison.OrdinalIgnoreCase) == true)
|
||||
|| sequence.Tags.Any(t => t.Contains(text, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>The index's order of <see cref="Sort"/> (missing values last, the id as tie-breaker), for merging pages with other sequences.</summary>
|
||||
public int Compare(Sequence a, Sequence b)
|
||||
{
|
||||
var order = Sort switch
|
||||
{
|
||||
SequenceSort.Newest => Nullable(a.FirstCapture, b.FirstCapture, descending: true),
|
||||
SequenceSort.Oldest => Nullable(a.FirstCapture, b.FirstCapture, descending: false),
|
||||
SequenceSort.Title => string.CompareOrdinal(a.DisplayTitle.ToLowerInvariant(), b.DisplayTitle.ToLowerInvariant()),
|
||||
SequenceSort.FrameCount => b.FrameCount.CompareTo(a.FrameCount),
|
||||
_ => b.TotalBytes.CompareTo(a.TotalBytes),
|
||||
};
|
||||
if (order != 0) return order;
|
||||
var ids = string.CompareOrdinal(a.Id.ToString(), b.Id.ToString());
|
||||
return Sort is SequenceSort.Oldest or SequenceSort.Title ? ids : -ids;
|
||||
|
||||
static int Nullable(DateTime? x, DateTime? y, bool descending) => (x, y) switch
|
||||
{
|
||||
(null, null) => 0,
|
||||
(null, _) => 1,
|
||||
(_, null) => -1,
|
||||
_ => descending ? y!.Value.CompareTo(x!.Value) : x!.Value.CompareTo(y!.Value),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The status test of the index (<see cref="ToQuery"/>) on one sequence.</summary>
|
||||
public static bool MatchesStatus(Sequence sequence, StatusFilter status)
|
||||
{
|
||||
switch (status)
|
||||
{
|
||||
case StatusFilter.Rendered:
|
||||
return sequence.RenderedCount > 0;
|
||||
case StatusFilter.NotRendered:
|
||||
return sequence.RenderedCount == 0;
|
||||
case StatusFilter.Synced:
|
||||
return SyncedStates.Contains(sequence.SyncState);
|
||||
default:
|
||||
var (with, without) = Flags(status);
|
||||
return (sequence.Status & with) == with && (sequence.Status & without) == 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Flags that must be set and clear for a status choice (none for the choices that test renders or sync).</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 Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.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,68 @@
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Shell;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>
|
||||
/// The Library states that <c>--capture</c> renders (<c>library-<scene>-<theme>.png</c>) and the screen smoke
|
||||
/// tests check, on the sample index while signed in to the sample server: the timeline with a month chosen, a selection
|
||||
/// with the whole mass actions bar, the server's sequences without a copy here as remote cards, and "Save view" naming
|
||||
/// the filters on screen.
|
||||
/// </summary>
|
||||
public static class LibraryScenes
|
||||
{
|
||||
public static readonly IReadOnlyList<string> Scenes = ["timeline", "mass", "remote", "viewname"];
|
||||
|
||||
/// <summary>Sequences selected for the mass actions bar.</summary>
|
||||
public const int MassSelection = 3;
|
||||
|
||||
public static async Task ShowAsync(ShellViewModel shell, string scene)
|
||||
{
|
||||
var library = shell.Library;
|
||||
shell.Navigate(SectionKey.Library);
|
||||
library.Dialog?.CloseCommand.Execute(null);
|
||||
library.ClearSelectionCommand.Execute(null);
|
||||
library.ClearFiltersCommand.Execute(null);
|
||||
library.LayoutIndex = 0;
|
||||
await library.RefreshAsync();
|
||||
switch (scene)
|
||||
{
|
||||
case "timeline":
|
||||
library.LayoutIndex = 2;
|
||||
// A month further down the list: the year becomes the filter and the grid scrolls to the month.
|
||||
if (library.Items.Count > 0 && library.Items[Math.Min(12, library.Items.Count - 1)].Sequence.FirstCapture is { } month)
|
||||
{
|
||||
library.ShowMonth(month.Year, month.Month);
|
||||
await library.RefreshAsync();
|
||||
}
|
||||
break;
|
||||
case "mass":
|
||||
foreach (var item in library.Items.Where(i => !i.IsRemote).Take(MassSelection)) item.IsSelected = true;
|
||||
break;
|
||||
case "remote":
|
||||
library.SelectedOrigin = library.Origins.First(o => o.Value == OriginFilter.Server);
|
||||
await library.RefreshAsync();
|
||||
if (library.Items.FirstOrDefault() is { } remote) remote.IsSelected = true;
|
||||
// Remote thumbnails come through the sync engine's connection, not the local thumbnail service.
|
||||
for (var i = 0; i < 60 && library.Items.Any(item => item.Thumbnail is null); i++) await Task.Delay(50);
|
||||
break;
|
||||
case "viewname":
|
||||
library.SelectedStatus = library.Statuses.First(o => o.Value == StatusFilter.NotRendered);
|
||||
await library.RefreshAsync();
|
||||
library.OpenSaveView();
|
||||
if (library.Dialog is ViewNameDialogViewModel naming) naming.Name.Text = library.SelectedStatus.Label;
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(scene), scene, "Unknown Library scene.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The confirmation Delete shows for the selection: the archive engine's dry run (nothing moves).</summary>
|
||||
public static async Task<ConfirmRequest?> DeleteRequestAsync(ShellViewModel shell)
|
||||
{
|
||||
var archives = shell.Services.Archives ?? throw new InvalidOperationException("The sample index is not open.");
|
||||
var ids = shell.Library.SelectedItems().Where(i => !i.IsRemote).Select(i => i.Id).ToList();
|
||||
return DeletePlans.Request(await Task.Run(() => archives.PlanDeleteAsync(ids)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>
|
||||
/// The Library's timeline layout (BRIEF §12.2): one band per capture year, newest first, with the density of photos
|
||||
/// per month (the Archive heatmap's figures), and the way between a band's month and the sequences of the grid.
|
||||
/// </summary>
|
||||
public sealed class LibraryTimeline
|
||||
{
|
||||
private LibraryTimeline(IReadOnlyList<HeatRow> bands, IReadOnlyList<int> years)
|
||||
{
|
||||
Bands = bands;
|
||||
Years = years;
|
||||
}
|
||||
|
||||
public static LibraryTimeline Empty { get; } = new([], []);
|
||||
|
||||
/// <summary>One row per year, newest first; months to come are NaN.</summary>
|
||||
public IReadOnlyList<HeatRow> Bands { get; }
|
||||
|
||||
/// <summary>The year of each band.</summary>
|
||||
public IReadOnlyList<int> Years { get; }
|
||||
|
||||
public static LibraryTimeline From(ArchiveStats stats, DateTime today)
|
||||
{
|
||||
var rows = ArchiveFigures.PhotosPerMonth(stats, today).Reverse().ToList();
|
||||
var first = stats.ByMonth.Count == 0 ? 0 : stats.ByMonth.Max(m => m.Year);
|
||||
return new LibraryTimeline(rows, [.. Enumerable.Range(0, rows.Count).Select(i => first - i)]);
|
||||
}
|
||||
|
||||
/// <summary>Year and month of a band's slot; null outside the bands.</summary>
|
||||
public (int Year, int Month)? MonthAt(int band, int slot) =>
|
||||
band >= 0 && band < Years.Count && slot is >= 0 and < 12 ? (Years[band], slot + 1) : null;
|
||||
|
||||
/// <summary>Band and slot of a month; (−1, −1) when no band shows that year.</summary>
|
||||
public (int Band, int Slot) SlotOf(int year, int month)
|
||||
{
|
||||
var band = IndexOf(Years, year);
|
||||
return band < 0 || month is < 1 or > 12 ? (-1, -1) : (band, month - 1);
|
||||
}
|
||||
|
||||
/// <summary>Position of the first sequence first captured in that month, in list order; −1 when none of <paramref name="sequences"/> is.</summary>
|
||||
public static int FirstOfMonth(IReadOnlyList<Sequence> sequences, int year, int month)
|
||||
{
|
||||
for (var i = 0; i < sequences.Count; i++)
|
||||
{
|
||||
if (sequences[i].FirstCapture is { } at && at.Year == year && at.Month == month) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static int IndexOf(IReadOnlyList<int> values, int value)
|
||||
{
|
||||
for (var i = 0; i < values.Count; i++)
|
||||
{
|
||||
if (values[i] == value) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using Chronos.App.Server;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Sync;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>The actions of the Library's mass actions bar (BRIEF §12.2).</summary>
|
||||
public enum MassAction
|
||||
{
|
||||
Analyse,
|
||||
Proxies,
|
||||
Verify,
|
||||
Tag,
|
||||
Rate,
|
||||
Move,
|
||||
Upload,
|
||||
Download,
|
||||
Delete,
|
||||
ExportList,
|
||||
}
|
||||
|
||||
/// <summary>A selected sequence and, while signed in, its row of the sync table.</summary>
|
||||
public sealed record SelectedSequence(Sequence Sequence, SyncEntry? Sync)
|
||||
{
|
||||
/// <summary>Only on the server: no copy on this PC (a remote card).</summary>
|
||||
public bool IsRemote => Sequence is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly };
|
||||
}
|
||||
|
||||
/// <summary>What this PC can do right now.</summary>
|
||||
/// <param name="HasEngine">The index and the job engine are open.</param>
|
||||
/// <param name="IsSignedIn">A server session is open (uploads, downloads, remote cards).</param>
|
||||
public sealed record SelectionContext(bool HasEngine, bool IsSignedIn, SyncRights Rights);
|
||||
|
||||
/// <summary>
|
||||
/// Which selected sequences each mass action works on and, when it works on none, why (the disabled button's
|
||||
/// tooltip, DESIGN §4). Archive actions touch sequences on this PC; Upload and Download follow the sync table's own
|
||||
/// row actions (<see cref="SyncText.Actions"/>), so the Library and the Server screen never disagree.
|
||||
/// </summary>
|
||||
public static class MassActions
|
||||
{
|
||||
/// <summary>The selected sequences <paramref name="action"/> works on.</summary>
|
||||
public static IReadOnlyList<SelectedSequence> Targets(MassAction action, IReadOnlyList<SelectedSequence> selection, SelectionContext context) => action switch
|
||||
{
|
||||
MassAction.ExportList => selection,
|
||||
MassAction.Upload => [.. selection.Where(s => !s.IsRemote && UploadStep(s, context.Rights) is not null)],
|
||||
MassAction.Download => [.. selection.Where(s => DownloadStep(s, context.Rights) is not null)],
|
||||
_ => [.. selection.Where(s => !s.IsRemote)],
|
||||
};
|
||||
|
||||
/// <summary>Why <paramref name="action"/> cannot run on the selection, localized; null when it can.</summary>
|
||||
public static string? Blocker(MassAction action, IReadOnlyList<SelectedSequence> selection, SelectionContext context)
|
||||
{
|
||||
if (selection.Count == 0) return Loc.L("Library.Blocked.NoSelection");
|
||||
if (action == MassAction.ExportList) return null;
|
||||
if (!context.HasEngine) return Loc.L("Library.Blocked.NoIndex");
|
||||
var targets = Targets(action, selection, context);
|
||||
switch (action)
|
||||
{
|
||||
case MassAction.Upload or MassAction.Download when !context.IsSignedIn:
|
||||
return Loc.L("Library.Blocked.NotConnected");
|
||||
case MassAction.Upload when !context.Rights.CanUpload:
|
||||
return Loc.L("Library.Blocked.NoUploadRight");
|
||||
case MassAction.Download when !context.Rights.CanFetchOriginals:
|
||||
return Loc.L("Library.Blocked.NoDownloadRight");
|
||||
case MassAction.Upload when targets.Count == 0:
|
||||
return Loc.L("Library.Blocked.NothingToUpload");
|
||||
case MassAction.Download when targets.Count == 0:
|
||||
return Loc.L("Library.Blocked.NothingToDownload");
|
||||
case MassAction.Upload or MassAction.Download:
|
||||
return null;
|
||||
}
|
||||
if (targets.Count == 0) return Loc.L("Library.Blocked.ServerOnly");
|
||||
return action == MassAction.Move && targets.Select(t => t.Sequence.ArchiveId).Distinct().Count() > 1 ? Loc.L("Library.Blocked.Archives") : null;
|
||||
}
|
||||
|
||||
/// <summary>The enabled tooltip: what the action does to how many sequences.</summary>
|
||||
public static string ToolTip(MassAction action, int targets) => Loc.Plural("Tooltips.Library.Mass." + action, targets);
|
||||
|
||||
/// <summary>What an upload of a selected local sequence sends: its originals and settings, or only its renders; null when nothing.</summary>
|
||||
public static SyncAction? UploadStep(SelectedSequence selected, SyncRights rights)
|
||||
{
|
||||
// Compared before the table lists it: the sequence is only here.
|
||||
if (selected.Sync is not { } entry) return rights.CanUpload && !selected.IsRemote ? SyncAction.Upload : null;
|
||||
var actions = SyncText.Actions(entry, rights);
|
||||
return actions.Contains(SyncAction.Upload) ? SyncAction.Upload : actions.Contains(SyncAction.SendExports) ? SyncAction.SendExports : null;
|
||||
}
|
||||
|
||||
/// <summary>What a download of a selected sequence fetches: the server's originals, or only its renders; null when nothing.</summary>
|
||||
public static SyncAction? DownloadStep(SelectedSequence selected, SyncRights rights)
|
||||
{
|
||||
if (selected.Sync is not { } entry) return null;
|
||||
var actions = SyncText.Actions(entry, rights);
|
||||
return actions.Contains(SyncAction.DownloadOriginals) ? SyncAction.DownloadOriginals : actions.Contains(SyncAction.GetExports) ? SyncAction.GetExports : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The card's Sync quick action: the first transfer or settings exchange the sync table offers, or Resolve
|
||||
/// (on the Server screen) for a conflict; null with <paramref name="blocker"/> when there is nothing to do.
|
||||
/// </summary>
|
||||
public static SyncAction? QuickSync(SelectedSequence selected, SelectionContext context, out string? blocker)
|
||||
{
|
||||
blocker = null;
|
||||
if (!context.IsSignedIn)
|
||||
{
|
||||
blocker = Loc.L("Library.Blocked.NotConnected");
|
||||
return null;
|
||||
}
|
||||
if (selected.Sync is not { } entry) return UploadStep(selected, context.Rights) ?? Blocked(Loc.L("Library.Blocked.NoUploadRight"), out blocker);
|
||||
if (entry.Transfer is not null) return Blocked(Loc.L("Library.Blocked.Transferring"), out blocker);
|
||||
if (entry.Status == SyncStatus.Conflict) return SyncAction.KeepMine;
|
||||
var actions = SyncText.Actions(entry, context.Rights);
|
||||
SyncAction[] preferred = [SyncAction.Upload, SyncAction.DownloadOriginals, SyncAction.SyncSettings, SyncAction.SendExports, SyncAction.GetExports];
|
||||
foreach (var action in preferred)
|
||||
{
|
||||
if (actions.Contains(action)) return action;
|
||||
}
|
||||
return Blocked(Loc.L(entry.Status == SyncStatus.InSync ? "Library.Blocked.InSync" : "Library.Blocked.NoSyncRight"), out blocker);
|
||||
|
||||
static SyncAction? Blocked(string reason, out string? why)
|
||||
{
|
||||
why = reason;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>
|
||||
/// Server sequences without a copy on this PC, as Library cards (BRIEF §4.4 mixed mode): from the sync table of the
|
||||
/// signed-in server, with the details of the server's listing when it was read, else what the table keeps.
|
||||
/// </summary>
|
||||
public static class RemoteCards
|
||||
{
|
||||
/// <summary>Entries of the sync table that have no local copy (only on the server, or kept here as proxies).</summary>
|
||||
public static IEnumerable<SyncEntry> RemoteOnly(IEnumerable<SyncEntry> entries) => entries.Where(e => e is { Local: null, Link: not null });
|
||||
|
||||
/// <summary>One card per remote-only entry: the listing's sequence when known, else the table's title, counts and status.</summary>
|
||||
public static IReadOnlyList<Sequence> Build(IEnumerable<SyncEntry> entries, IReadOnlyDictionary<Guid, SequenceDto>? listing) =>
|
||||
[
|
||||
.. RemoteOnly(entries).Select(e => listing is not null && listing.TryGetValue(e.Link!.RemoteId, out var dto) ? ToSequence(dto) : FromLink(e.Link!)),
|
||||
];
|
||||
|
||||
/// <summary>A server sequence as a card: origin server, remote only, no archive on this PC.</summary>
|
||||
public static Sequence ToSequence(SequenceDto dto) => new()
|
||||
{
|
||||
Id = dto.Id,
|
||||
ArchiveId = Guid.Empty,
|
||||
Title = dto.Title,
|
||||
Folder = dto.Folder,
|
||||
CameraMake = dto.CameraMake,
|
||||
CameraModel = dto.CameraModel,
|
||||
Lens = dto.Lens,
|
||||
FirstCapture = dto.FirstCapture,
|
||||
LastCapture = dto.LastCapture,
|
||||
FrameCount = dto.FrameCount,
|
||||
MedianInterval = dto.MedianInterval,
|
||||
TotalBytes = dto.TotalBytes,
|
||||
Status = (SequenceStatus)dto.Status,
|
||||
RenderedCount = dto.RenderedCount,
|
||||
HeroFrameId = dto.HeroFrameId,
|
||||
Tags = dto.Tags,
|
||||
Rating = dto.Rating,
|
||||
Notes = dto.Notes,
|
||||
SettingsVersion = dto.SettingsVersion,
|
||||
FramesVersion = dto.FramesVersion,
|
||||
WarningCount = dto.WarningCount,
|
||||
PreviewOnlyCount = dto.PreviewOnlyCount,
|
||||
OwnerUserId = dto.OwnerUserId,
|
||||
UpdatedAt = dto.UpdatedAt,
|
||||
Origin = SequenceOrigin.Server,
|
||||
SyncState = SyncState.RemoteOnly,
|
||||
};
|
||||
|
||||
/// <summary>What the sync table knows of a server sequence when its listing could not be read.</summary>
|
||||
public static Sequence FromLink(SyncLink link) => new()
|
||||
{
|
||||
Id = link.RemoteId,
|
||||
ArchiveId = Guid.Empty,
|
||||
Title = link.Title,
|
||||
Folder = string.Empty,
|
||||
FrameCount = link.FrameCount,
|
||||
TotalBytes = link.TotalBytes,
|
||||
Status = link.RemoteStatus,
|
||||
RenderedCount = link.RenderCount,
|
||||
SettingsVersion = link.RemoteSettingsVersion,
|
||||
FramesVersion = link.RemoteFramesVersion,
|
||||
UpdatedAt = link.RemoteUpdatedAt,
|
||||
Origin = SequenceOrigin.Server,
|
||||
SyncState = SyncState.RemoteOnly,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interleaves remote cards with the index's pages in the order of the filter's sort: each page brings the remote
|
||||
/// cards that sort before its last row; the last page brings the rest. Not thread-safe: call from one thread (the UI).
|
||||
/// </summary>
|
||||
public sealed class RemoteMerge
|
||||
{
|
||||
private readonly List<Sequence> _pending = [];
|
||||
private LibraryFilter _filter = new();
|
||||
|
||||
/// <summary>Remote cards not yet handed out.</summary>
|
||||
public int Pending => _pending.Count;
|
||||
|
||||
/// <summary>Starts over with the cards that match <paramref name="filter"/>, in its order.</summary>
|
||||
public void Reset(LibraryFilter filter, IEnumerable<Sequence> remote)
|
||||
{
|
||||
_filter = filter;
|
||||
_pending.Clear();
|
||||
if (filter.Origin != OriginFilter.Local) _pending.AddRange(remote.Where(filter.Matches));
|
||||
_pending.Sort(filter.Compare);
|
||||
}
|
||||
|
||||
/// <summary>A page of the index with the remote cards that belong among it, in order; <paramref name="last"/> adds every card left.</summary>
|
||||
public IReadOnlyList<Sequence> Merge(IReadOnlyList<Sequence> page, bool last)
|
||||
{
|
||||
var take = last ? _pending.Count
|
||||
: page.Count == 0 ? 0
|
||||
: _pending.FindIndex(r => _filter.Compare(r, page[^1]) > 0) is var after and >= 0 ? after : _pending.Count;
|
||||
if (take == 0) return page;
|
||||
var merged = new List<Sequence>(page.Count + take);
|
||||
int a = 0, b = 0;
|
||||
while (a < page.Count || b < take)
|
||||
{
|
||||
if (b >= take || (a < page.Count && _filter.Compare(page[a], _pending[b]) <= 0)) merged.Add(page[a++]);
|
||||
else merged.Add(_pending[b++]);
|
||||
}
|
||||
_pending.RemoveRange(0, take);
|
||||
return merged;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Windows.Media;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>Hero thumbnails (and hover-scrub frames, where there are any) of the Library's cards.</summary>
|
||||
public interface ISequenceThumbnails
|
||||
{
|
||||
Task<ImageSource?> HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct);
|
||||
|
||||
/// <summary>Frames for hover scrubbing; null when the sequence has none to scrub.</summary>
|
||||
IThumbnailSource? ScrubSource(Sequence sequence);
|
||||
}
|
||||
|
||||
/// <summary>The signed-in server as remote cards see it: its sync engine, its key and a connection.</summary>
|
||||
public sealed record RemoteSource(SyncService Service, string Server, ISyncRemote Remote);
|
||||
|
||||
/// <summary>
|
||||
/// Thumbnails of server sequences without a copy here (BRIEF §4.4): the hero frame (else the first) from the proxy
|
||||
/// cache when the sequence was fetched with proxies, otherwise the server's thumbnail of that frame through the API.
|
||||
/// The first frame of a sequence without a hero is asked once (one row of its frames page) and remembered. Decoded at
|
||||
/// a 64 px width step and kept in an LRU cache; failed downloads are not cached, so they are tried again.
|
||||
/// </summary>
|
||||
public sealed class RemoteThumbnails(Func<RemoteSource?> source, int capacity = 256) : ISequenceThumbnails, IDisposable
|
||||
{
|
||||
private const int WidthStep = 64;
|
||||
|
||||
private readonly ConcurrentDictionary<Guid, Guid?> _heroes = new();
|
||||
|
||||
/// <summary>The first frame of sequences without a hero frame (a sequence with no frame yet is asked again later).</summary>
|
||||
private readonly ConcurrentDictionary<Guid, Guid> _firstFrames = new();
|
||||
private ThumbnailCache<(Guid Sequence, int Width), ImageSource>? _cache;
|
||||
|
||||
private ThumbnailCache<(Guid Sequence, int Width), ImageSource> Cache => _cache ??= new(capacity, LoadAsync, maxConcurrentLoads: 4);
|
||||
|
||||
public Task<ImageSource?> HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct)
|
||||
{
|
||||
_heroes[sequence.Id] = sequence.HeroFrameId;
|
||||
return Cache.GetAsync((sequence.Id, Math.Clamp((pixelWidth + WidthStep - 1) / WidthStep * WidthStep, WidthStep, 1024)), ct);
|
||||
}
|
||||
|
||||
/// <summary>Remote cards do not scrub: every frame would be a download.</summary>
|
||||
public IThumbnailSource? ScrubSource(Sequence sequence) => null;
|
||||
|
||||
/// <summary>Forgets every thumbnail (another server, or the cache was cleared).</summary>
|
||||
public void Clear()
|
||||
{
|
||||
_cache?.Clear();
|
||||
_firstFrames.Clear();
|
||||
}
|
||||
|
||||
public void Dispose() => _cache?.Dispose();
|
||||
|
||||
private async Task<ImageSource?> LoadAsync((Guid Sequence, int Width) key, CancellationToken ct)
|
||||
{
|
||||
if (source() is not { } connection) return null;
|
||||
var hero = _heroes.GetValueOrDefault(key.Sequence);
|
||||
if (connection.Service.OpenRemote(connection.Server, key.Sequence) is { CachedCount: > 0 } cached)
|
||||
{
|
||||
var index = hero is { } id ? IndexOf(cached.Frames, id) : -1;
|
||||
if (index < 0 || cached.Files[index] is null) index = FirstCached(cached.Files);
|
||||
await using var file = new FileStream(cached.Files[index]!, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous);
|
||||
return ThumbnailService.DecodeStream(file, cached.Frames[index].Orientation, key.Width);
|
||||
}
|
||||
var frameId = hero ?? await FirstFrameAsync(connection.Remote, key.Sequence, ct).ConfigureAwait(false);
|
||||
if (frameId is null) return null;
|
||||
using var thumbnail = new MemoryStream();
|
||||
await connection.Remote.DownloadFrameAsync(frameId.Value, "thumb", thumbnail, ct).ConfigureAwait(false);
|
||||
thumbnail.Position = 0;
|
||||
// The server draws its thumbnails upright.
|
||||
return ThumbnailService.DecodeStream(thumbnail, 1, key.Width);
|
||||
}
|
||||
|
||||
private async Task<Guid?> FirstFrameAsync(ISyncRemote remote, Guid sequence, CancellationToken ct)
|
||||
{
|
||||
if (_firstFrames.TryGetValue(sequence, out var known)) return known;
|
||||
if ((await remote.FirstFrameAsync(sequence, ct).ConfigureAwait(false))?.Id is not { } first) return null;
|
||||
_firstFrames[sequence] = first;
|
||||
return first;
|
||||
}
|
||||
|
||||
private static int IndexOf(IReadOnlyList<Frame> frames, Guid id)
|
||||
{
|
||||
for (var i = 0; i < frames.Count; i++)
|
||||
{
|
||||
if (frames[i].Id == id) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static int FirstCached(IReadOnlyList<string?> files)
|
||||
{
|
||||
for (var i = 0; i < files.Count; i++)
|
||||
{
|
||||
if (files[i] is not null) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>A named set of Library filters and sort ("Night, 4K, not rendered"), BRIEF §12.2.</summary>
|
||||
public sealed record SavedView
|
||||
{
|
||||
public const int MaxName = 40;
|
||||
|
||||
public required Guid Id { get; init; }
|
||||
public required string Name { get; init; }
|
||||
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 OriginFilter Origin { get; init; }
|
||||
public SequenceSort Sort { get; init; } = SequenceSort.Newest;
|
||||
|
||||
public static SavedView Of(Guid id, string name, LibraryFilter filter) => new()
|
||||
{
|
||||
Id = id,
|
||||
Name = name.Trim(),
|
||||
Text = string.IsNullOrWhiteSpace(filter.Text) ? null : filter.Text.Trim(),
|
||||
Year = filter.Year,
|
||||
Camera = filter.Camera,
|
||||
Status = filter.Status,
|
||||
Tag = filter.Tag,
|
||||
Origin = filter.Origin,
|
||||
Sort = filter.Sort,
|
||||
};
|
||||
|
||||
public LibraryFilter ToFilter() => new() { Text = Text, Year = Year, Camera = Camera, Status = Status, Tag = Tag, Origin = Origin, Sort = Sort };
|
||||
|
||||
/// <summary>The Library shows exactly this view (search text compared trimmed and case-insensitively).</summary>
|
||||
public bool Matches(LibraryFilter filter) =>
|
||||
string.Equals(Text ?? string.Empty, filter.Text?.Trim() ?? string.Empty, StringComparison.OrdinalIgnoreCase)
|
||||
&& Year == filter.Year && Camera == filter.Camera && Status == filter.Status && Tag == filter.Tag && Origin == filter.Origin && Sort == filter.Sort;
|
||||
|
||||
/// <summary>The problem of a view name, localized; null when it can be used.</summary>
|
||||
/// <param name="others">Names of the other saved views (a name is used once).</param>
|
||||
public static string? Validate(string? name, IEnumerable<string> others)
|
||||
{
|
||||
var trimmed = name?.Trim() ?? string.Empty;
|
||||
if (trimmed.Length == 0) return Loc.L("Library.Views.Error.Empty");
|
||||
if (trimmed.Length > MaxName || trimmed.Any(char.IsControl)) return Loc.L("Library.Views.Error.Long", MaxName);
|
||||
return others.Contains(trimmed, StringComparer.CurrentCultureIgnoreCase) ? Loc.L("Library.Views.Error.Taken") : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Saved views as app-scope settings rows (<c>library.view.<id></c>), one row per view.</summary>
|
||||
public sealed class SavedViewStore(SettingsRepository settings)
|
||||
{
|
||||
private const string Prefix = "library.view.";
|
||||
|
||||
/// <summary>Every saved view by name; unreadable rows are skipped.</summary>
|
||||
public async Task<IReadOnlyList<SavedView>> ListAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var views = new List<SavedView>();
|
||||
foreach (var (key, json) in await settings.ListAsync(SettingScope.App, null, cancellationToken))
|
||||
{
|
||||
if (!key.StartsWith(Prefix, StringComparison.Ordinal)) continue;
|
||||
try
|
||||
{
|
||||
if (JsonSerializer.Deserialize(json, SavedViewJson.Default.SavedView) is { } view) views.Add(view);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
Log.Warning("library", $"Saved view {key} is unreadable", ex);
|
||||
}
|
||||
}
|
||||
return [.. views.OrderBy(v => v.Name, StringComparer.CurrentCultureIgnoreCase)];
|
||||
}
|
||||
|
||||
/// <summary>Adds the view or replaces the one with its id.</summary>
|
||||
public Task SaveAsync(SavedView view, CancellationToken cancellationToken = default) =>
|
||||
settings.SetAsync(SettingScope.App, null, Key(view.Id), view, SavedViewJson.Default.SavedView, cancellationToken);
|
||||
|
||||
public Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default) => settings.DeleteAsync(SettingScope.App, null, Key(id), cancellationToken);
|
||||
|
||||
private static string Key(Guid id) => Prefix + id.ToString("N");
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
UseStringEnumConverter = true)]
|
||||
[JsonSerializable(typeof(SavedView))]
|
||||
internal sealed partial class SavedViewJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,276 @@
|
||||
using System.Text.Json;
|
||||
using System.Windows.Media;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>One sequence of the Library grid and list (BRIEF §12.2): on this PC, or a server sequence without a copy here (a remote card).</summary>
|
||||
public sealed class SequenceItem : ObservableObject
|
||||
{
|
||||
private readonly ISequenceThumbnails? _thumbnails;
|
||||
private Sequence _sequence;
|
||||
private SyncEntry? _sync;
|
||||
private string? _syncToolTip;
|
||||
private bool _canSync;
|
||||
private string? _quickBlocker;
|
||||
private string? _presetName;
|
||||
private ImageSource? _thumbnail;
|
||||
private IThumbnailSource? _scrub;
|
||||
private CancellationTokenSource? _loading;
|
||||
private int _requestedWidth;
|
||||
private bool _isSelected;
|
||||
private bool _isAnalysing;
|
||||
|
||||
public SequenceItem(Sequence sequence, ISequenceThumbnails? thumbnails)
|
||||
{
|
||||
_sequence = sequence;
|
||||
_thumbnails = thumbnails;
|
||||
}
|
||||
|
||||
public Sequence Sequence => _sequence;
|
||||
public Guid Id => _sequence.Id;
|
||||
|
||||
/// <summary>Only on the signed-in server (the editor opens it with proxies; archive actions do not apply).</summary>
|
||||
public bool IsRemote => _sequence is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly };
|
||||
|
||||
/// <summary>Its row of the sync table of the signed-in server; null while signed out or not compared yet.</summary>
|
||||
public SyncEntry? Sync => _sync;
|
||||
|
||||
/// <summary>The Sync quick action can run (<see cref="SyncToolTip"/> says what it does, or why not).</summary>
|
||||
public bool CanSync => _canSync;
|
||||
|
||||
public string SyncToolTip => _syncToolTip ?? Loc.L("Library.Blocked.NotConnected");
|
||||
|
||||
/// <summary>The Analyse and Render quick actions can start (<see cref="AnalyseToolTip"/> says why not).</summary>
|
||||
public bool CanRunQuick => _quickBlocker is null;
|
||||
|
||||
/// <summary>What Analyse does here or on the server, or why it cannot start.</summary>
|
||||
public string AnalyseToolTip => _quickBlocker ?? Loc.L(IsRemote ? "Tooltips.Library.AnalyseServer" : "Tooltips.Library.Analyse");
|
||||
|
||||
/// <summary>
|
||||
/// "Queue a render with 4K archive…": the preset the Render quick action queues, or why it cannot start. A remote
|
||||
/// card's project lives on the server, which renders it with the sequence's own preset.
|
||||
/// </summary>
|
||||
public string RenderToolTip => _quickBlocker ?? (IsRemote ? Loc.L("Tooltips.Library.QuickRenderServer") : Loc.L("Tooltips.Library.QuickRender", PresetName));
|
||||
|
||||
/// <summary>
|
||||
/// The export preset of the sequence's project: the one chosen in the editor, else the advisor's recommendation the
|
||||
/// analyses store in the project (Auto), else the default.
|
||||
/// </summary>
|
||||
public string PresetName => _presetName ??= ResolvePreset(_sequence.SettingsJson);
|
||||
|
||||
/// <summary>How the card reacts to the mouse; remote cards have no frames here to scrub.</summary>
|
||||
public string CardToolTip => Loc.L(IsRemote ? "Tooltips.Library.CardRemote" : "Tooltips.Library.Card");
|
||||
|
||||
/// <summary>User title or "{date} {camera}".</summary>
|
||||
public string Title => _sequence.DisplayTitle;
|
||||
|
||||
/// <summary>The title (what UI Automation reads for a row a list has not realised).</summary>
|
||||
public override string ToString() => Title;
|
||||
|
||||
/// <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(Loc.Separator, 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);
|
||||
|
||||
/// <summary>The sync table's row of this sequence and what its Sync quick action does (or why it cannot).</summary>
|
||||
public void SetSync(SyncEntry? entry, bool canSync, string toolTip)
|
||||
{
|
||||
_sync = entry;
|
||||
_canSync = canSync;
|
||||
_syncToolTip = toolTip;
|
||||
OnPropertyChanged(nameof(Sync));
|
||||
OnPropertyChanged(nameof(CanSync));
|
||||
OnPropertyChanged(nameof(SyncToolTip));
|
||||
}
|
||||
|
||||
/// <summary>Why Analyse and Render cannot start now (no engine here, or the server is not connected); null when they can.</summary>
|
||||
public void SetQuickBlocker(string? blocker)
|
||||
{
|
||||
if (_quickBlocker == blocker) return;
|
||||
_quickBlocker = blocker;
|
||||
OnPropertyChanged(nameof(CanRunQuick));
|
||||
OnPropertyChanged(nameof(AnalyseToolTip));
|
||||
OnPropertyChanged(nameof(RenderToolTip));
|
||||
}
|
||||
|
||||
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;
|
||||
if (sequence.SettingsJson != _sequence.SettingsJson) _presetName = null;
|
||||
_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 static string ResolvePreset(string? settingsJson)
|
||||
{
|
||||
try
|
||||
{
|
||||
var project = settingsJson is null ? new ProjectSettings() : ProjectSettings.FromJson(settingsJson);
|
||||
return ProcessingJobs.PresetName(ExportResolver.Resolve(project.Export));
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return ProcessingJobs.PresetName(ExportResolver.Resolve(new ExportSettings()));
|
||||
}
|
||||
}
|
||||
|
||||
private void RaiseStatuses()
|
||||
{
|
||||
OnPropertyChanged(nameof(Statuses));
|
||||
OnPropertyChanged(nameof(PrimaryStatus));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where a local copy stands against the server (the sync engine writes the state), in one word as DESIGN §4 draws
|
||||
/// it ("● Synced", "● Remote", "▲ Conflict") with the detail in the tooltip; null while it is only here.
|
||||
/// </summary>
|
||||
public static CardStatus? SyncStatus(SyncState state) => state switch
|
||||
{
|
||||
SyncState.InSync => new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.Synced")),
|
||||
SyncState.LocalAhead => new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.LocalAhead")),
|
||||
SyncState.ServerAhead => new CardStatus(StatusKind.Remote, Loc.L("Library.Status.Remote"), Loc.L("Tooltips.Library.Status.ServerAhead")),
|
||||
SyncState.Conflict => new CardStatus(StatusKind.Warning, Loc.L("Library.Status.Conflict"), Loc.L("Tooltips.Library.Status.Conflict")),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Card status row: analysed, proxies, renders, preview-only frames (BRIEF §8.2), errors or warnings, sync (Main.html);
|
||||
/// the sync glyph is last so a narrow card cuts it first.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<CardStatus> BuildStatuses(Sequence s, bool analysing)
|
||||
{
|
||||
var list = new List<CardStatus>(6);
|
||||
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.PreviewOnlyCount > 0)
|
||||
list.Add(new CardStatus(StatusKind.PreviewOnly, Formatting.Count(s.PreviewOnlyCount), Loc.Plural("Tooltips.Library.Status.PreviewOnly", s.PreviewOnlyCount)));
|
||||
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))));
|
||||
if (SyncStatus(s.SyncState) is { } sync) list.Add(sync);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.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 Chronos.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,211 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.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 : ISequenceThumbnails, 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 ChronosDatabase _db;
|
||||
private readonly ThumbnailCache<ThumbnailKey, ImageSource> _cache;
|
||||
private readonly ConcurrentDictionary<Guid, string?> _archiveRoots = new();
|
||||
private readonly ConcurrentDictionary<Guid, Guid?> _firstFrames = new();
|
||||
private int _requests;
|
||||
|
||||
public ThumbnailService(ChronosDatabase 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>Thumbnail requests in flight, index lookups included (capture and tests wait for them).</summary>
|
||||
public int PendingLoads => Math.Max(Volatile.Read(ref _requests), _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)
|
||||
{
|
||||
Interlocked.Increment(ref _requests);
|
||||
try
|
||||
{
|
||||
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;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Decrement(ref _requests);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A frame of a sequence by index (hover scrubbing).</summary>
|
||||
public async Task<ImageSource?> FrameAsync(Guid sequenceId, int index, int pixelWidth, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _requests);
|
||||
try
|
||||
{
|
||||
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);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Decrement(ref _requests);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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);
|
||||
|
||||
IThumbnailSource? ISequenceThumbnails.ScrubSource(Sequence sequence) => ScrubSource(sequence);
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>Names a saved view: "Save view" (the current filters under a new name) or "Rename view".</summary>
|
||||
public sealed class ViewNameDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
private readonly Func<string, Task> _save;
|
||||
|
||||
/// <param name="others">Names of the other saved views (each name is used once).</param>
|
||||
public ViewNameDialogViewModel(bool rename, string name, IReadOnlyList<string> others, Func<string, Task> save, Action<ArchiveDialogViewModel> close)
|
||||
: base(close)
|
||||
{
|
||||
IsRename = rename;
|
||||
_save = save;
|
||||
Name = new EditableField(name, n => SavedView.Validate(n, others), _ => { }, () => Loc.L("Tooltips.Library.ViewName"));
|
||||
Name.PropertyChanged += (_, _) =>
|
||||
{
|
||||
OnPropertyChanged(nameof(SaveToolTip));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
};
|
||||
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy && !Name.HasErrors);
|
||||
}
|
||||
|
||||
public bool IsRename { get; }
|
||||
|
||||
public string Heading => Loc.L(IsRename ? "Library.Views.RenameHeading" : "Library.Views.SaveHeading");
|
||||
|
||||
public EditableField Name { get; }
|
||||
|
||||
public ICommand SaveCommand { get; }
|
||||
|
||||
public string SaveToolTip => Name.Error ?? Loc.L(IsRename ? "Tooltips.Library.ViewRenameApply" : "Tooltips.Library.ViewSaveApply");
|
||||
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
ClearError();
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
await _save(Name.Text.Trim());
|
||||
Close();
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("library", "Saving a view failed", ex);
|
||||
ShowError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user