using System.IO; using System.Text.Json; using Titano.Core.Advice; using Titano.Core.Analysis; using Titano.Core.Analysis.Deep; using Titano.Core.Archiving; using Titano.Core.Diagnostics; using Titano.Core.Imaging; using Titano.Core.IO; using Titano.Core.Localization; using Titano.Core.Model; using Titano.Core.Project; using Titano.Data; using Titano.Data.Archiving; using Titano.Data.Archiving.Jobs; using Titano.Data.Jobs; using Titano.Data.Repositories; namespace Titano.App.Editor; /// /// A sequence of an archive on this PC: rows from the index, originals decoded by the client's decoder chain, the /// project in .titano/project.json mirrored in the index's settings column, jobs on this PC's engine. Project /// writes follow the archive engine's protocol: under the sequence's lease file (so the server and the job engine wait /// for it), file first (atomically), then the index with its settings version as an optimistic check. /// public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, ImageDecoder decoder, JobEngine? engine, ArchiveServiceOptions? lease = null) : ISequenceSource { private const int PageSize = 1000; private const int SaveAttempts = 3; private readonly ArchiveServiceOptions _lease = lease ?? new ArchiveServiceOptions(); private string?[] _files = []; private ArchivePaths? _paths; private SequencePaths? _folder; public async Task LoadAsync(CancellationToken cancellationToken) { var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken) ?? throw Missing(); var archive = await db.Archives.GetAsync(sequence.ArchiveId, cancellationToken) ?? throw Missing(); var frames = new List(); while (true) { var page = await db.Frames.ListBySequenceAsync(sequenceId, frames.Count > 0 ? frames[^1].Index : -1, PageSize, cancellationToken); frames.AddRange(page); if (page.Count < PageSize) break; } var renders = await db.Renders.ListBySequenceAsync(sequenceId, cancellationToken); return await Task.Run(() => { var paths = new ArchivePaths(archive.RootPath); var folder = paths.Sequence(sequence.Folder); var files = new string?[frames.Count]; for (var i = 0; i < files.Length; i++) { if ((frames[i].Flags & FrameFlags.Missing) == 0) files[i] = paths.FromRelative(frames[i].RelativePath); } (_paths, _folder, _files) = (paths, folder, files); var context = SequenceContext.FromFrames(frames); return new SequenceContent(sequence, frames, ReadProject(sequence, folder), LightAnalyzer.Analyze(frames), ReadReport(folder, frames.Count), context.SourceWidth, context.SourceHeight, folder.Exports, [.. renders.OrderByDescending(r => r.Created)]); }, cancellationToken); } public async ValueTask DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) { if ((uint)index >= (uint)_files.Length || _files[index] is not { } file) return null; return await Task.Run(() => { try { // Thumbnails take an embedded preview when it is large enough (no RAW development for a filmstrip cell). var request = new DecodeRequest(file, maxLongEdge, purpose, ForcePreview: purpose == DecodePurpose.Thumbnail); return decoder.Decode(request, cancellationToken)?.Pixels; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Warning("editor", $"Frame {file} could not be read", ex); return null; } }, cancellationToken); } public Task SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(project); ArgumentNullException.ThrowIfNull(basis); var (paths, folder) = (_paths, _folder); if (paths is null || folder is null) throw new InvalidOperationException("LoadAsync first."); return Task.Run(async () => { ArchiveVolume.EnsureWritable(paths); using var held = await LeaseFile.AcquireAsync(paths.LocksDirectory, $"seq-{sequenceId:N}", _lease.Owner, _lease.LeaseWait, _lease.LeaseDuration, cancellationToken); for (var attempt = 1; ; attempt++) { var row = await db.Sequences.GetAsync(sequenceId, cancellationToken) ?? throw Missing(); var stored = ReadProject(row, folder); var merged = ProjectMerge.SameValues(stored, basis) ? project : ProjectMerge.Merge(basis, project, stored); var json = merged.ToJson(); if (json == stored.ToJson()) return merged; AtomicFile.WriteAllText(folder.ProjectPath, json); var result = await db.Sequences.EditAsync(sequenceId, new SequenceEdit { SettingsJson = json }, row.SettingsVersion, cancellationToken); switch (result.Outcome) { case SequenceEditOutcome.Updated: return merged; case SequenceEditOutcome.NotFound: throw Missing(); // The settings moved in the index meanwhile (server API): merge again on top of them; the file follows the next write. case SequenceEditOutcome.Conflict when attempt == SaveAttempts: throw new IOException(Loc.L("Editor.Error.SaveConflict")); } } }, cancellationToken); } public async Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken) { if (engine is null) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine")); var job = await engine.EnqueueAsync(request, cancellationToken: cancellationToken); return job.Id; } public ValueTask DisposeAsync() => ValueTask.CompletedTask; /// The settings in force: the index copy, else project.json, else defaults. /// The settings are not a project or come from a newer Titano. internal static ProjectSettings ReadProject(Sequence sequence, SequencePaths folder) { var json = sequence.SettingsJson ?? (File.Exists(folder.ProjectPath) ? File.ReadAllText(folder.ProjectPath) : null); if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings(); try { return ProjectSettings.FromJson(json); } catch (JsonException ex) { throw new InvalidDataException(Loc.L("Editor.Error.Project"), ex); } } /// The saved deep report when it describes the current frames. private static DeepAnalysisReport? ReadReport(SequencePaths folder, int frameCount) { if (!File.Exists(folder.AnalysisPath)) return null; try { var report = DeepAnalysisReport.Load(folder.AnalysisPath); return report.FrameCount == frameCount ? report : null; } catch (Exception ex) when (ex is IOException or InvalidDataException or JsonException) { Log.Warning("editor", $"{folder.AnalysisPath} cannot be read", ex); return null; } } private static InvalidOperationException Missing() => new(Loc.L("Editor.Error.Missing")); }