feat: owner review 2 phase 5a: workspace and projects with a local home (#14)
CI / Build and test (push) Successful in 9m43s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 27s
CI / PostgreSQL 16 integration (push) Failing after 8m41s
CI / PostgreSQL 17 integration (push) Successful in 12m37s
CI / Docker image (push) Successful in 56s
Release / Build, test and publish (push) Successful in 14m59s
Release / Server image (push) Successful in 1m51s

Edit opens a sequence as a project of a workspace folder outside the library. Projects have linear version histories kept as sidecars in .chronos/projects/, Main mirrors the sequence's settings, and sync merges setting by setting. Migration 0009, JobKind.WorkspaceCopy = 20, Settings › Workspace, and 241 new strings in 38 languages.

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 #14.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-04 09:22:08 +01:00
1 parent efa87f68ce
commit 9b24cf74fc
370 files changed
+29237 -287

No files matched your search

+10
View File
@@ -1,3 +1,6 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Chronos.Core.Project;
/// <summary>
@@ -24,6 +27,13 @@ public sealed record Auto<T>
public IReadOnlyList<string>? ReasonArgs { get; init; }
/// <summary>
/// Members this Chronos does not know (written by a newer one, such as the advisor's confidence): kept as they are, so
/// they survive a round trip and every edit of the parameter (owner review 2, R8).
/// </summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
/// <summary>The value in force: manual when set by the user, otherwise the advisor's, otherwise <paramref name="fallback"/>.</summary>
public T Resolve(T fallback) => !IsAuto && Manual is not null ? Manual : HasAdvice && AutoValue is not null ? AutoValue : fallback;
+78 -1
View File
@@ -35,10 +35,28 @@ public sealed class FramePhotos
private readonly Dictionary<string, List<int>> _bySha = new(StringComparer.Ordinal);
private readonly Dictionary<(long Size, long Time), List<int>> _bySizeAndTime = [];
/// <summary>Each SHA-256 an alias links, and the one its photo is known by among them (empty without aliases).</summary>
private readonly Dictionary<string, string> _canonical;
/// <summary>The frames holding each linked photo, by the SHA-256 it is known by (<see cref="_canonical"/>).</summary>
private readonly Dictionary<string, List<int>> _byCanonical = new(StringComparer.Ordinal);
/// <param name="frames">Each frame's index and photo, in any order.</param>
public FramePhotos(IEnumerable<(int Index, FramePhoto Photo)> frames)
: this(frames, null)
{
}
/// <param name="frames">Each frame's index and photo, in any order.</param>
/// <param name="aliases">
/// Encodings of one photo (owner review 2, R7: a conversion replaced a frame's file, its undo put it back): a photo
/// named by an encoding no frame holds is held by the frames holding another encoding the links join to it.
/// </param>
public FramePhotos(IEnumerable<(int Index, FramePhoto Photo)> frames, IEnumerable<PhotoAlias>? aliases)
{
ArgumentNullException.ThrowIfNull(frames);
Aliases = aliases is null ? [] : [.. aliases.Where(a => a is not null)];
_canonical = PhotoAlias.Classes(Aliases);
var list = frames.Where(f => f.Index >= 0).ToList();
_byIndex = new FramePhoto?[list.Count == 0 ? 0 : list.Max(f => f.Index) + 1];
foreach (var (index, photo) in list) _byIndex[index] = photo;
@@ -50,6 +68,11 @@ public sealed class FramePhotos
var sha = photo.Sha256!.ToLowerInvariant();
if (!_bySha.TryGetValue(sha, out var copies)) _bySha[sha] = copies = [];
copies.Add(i);
if (_canonical.TryGetValue(sha, out var known))
{
if (!_byCanonical.TryGetValue(known, out var linked)) _byCanonical[known] = linked = [];
linked.Add(i);
}
}
if (photo.CapturedAt is not { } time) continue;
var key = (photo.Size, FramePhoto.Millisecond(time));
@@ -60,6 +83,9 @@ public sealed class FramePhotos
public int Count => _byIndex.Length;
/// <summary>The links between encodings of one photo these frames were given (empty without any): another copy's frames can take them.</summary>
public IReadOnlyList<PhotoAlias> Aliases { get; }
/// <summary>The photo at <paramref name="index"/>; null when no frame has that index.</summary>
public FramePhoto? this[int index] => (uint)index < (uint)_byIndex.Length ? _byIndex[index] : null;
@@ -91,7 +117,13 @@ public sealed class FramePhotos
/// </summary>
private List<int> Holding(FramePhoto photo)
{
if (photo.IsHashed && _bySha.TryGetValue(photo.Sha256!.ToLowerInvariant(), out var hashed)) return hashed;
if (photo.IsHashed)
{
var sha = photo.Sha256!.ToLowerInvariant();
if (_bySha.TryGetValue(sha, out var hashed)) return hashed;
// Another encoding of the photo (a conversion, or its undo) is what the frames hold now.
if (_canonical.TryGetValue(sha, out var known) && _byCanonical.TryGetValue(known, out var linked)) return linked;
}
var holding = new List<int>(1);
if (photo.CapturedAt is not { } time || !_bySizeAndTime.TryGetValue((photo.Size, FramePhoto.Millisecond(time)), out var candidates)) return holding;
foreach (var index in candidates)
@@ -114,3 +146,48 @@ public sealed class FramePhotos
return true;
}
}
/// <summary>
/// Two encodings of one photo (owner review 2, R7): a frame's file holding <see cref="Sha256"/> that a conversion replaced
/// by one holding <see cref="Replacement"/> (a tombstone of reason "replaced"), or the undo of one. Links join in either
/// direction and through chains (a conversion of a conversion), so a position parked on any encoding finds the frame that
/// holds another (<see cref="FramePhotos"/>).
/// </summary>
public sealed record PhotoAlias(string Sha256, string Replacement)
{
/// <summary>
/// Each SHA-256 the links join (union-find), lower-case, mapped to the ordinal-smallest of its photo, so the result does
/// not depend on the order of the links. Empty without links.
/// </summary>
internal static Dictionary<string, string> Classes(IEnumerable<PhotoAlias>? aliases)
{
var parent = new Dictionary<string, string>(StringComparer.Ordinal);
if (aliases is null) return parent;
foreach (var alias in aliases)
{
if (alias is null || string.IsNullOrEmpty(alias.Sha256) || string.IsNullOrEmpty(alias.Replacement)) continue;
var (a, b) = (alias.Sha256.ToLowerInvariant(), alias.Replacement.ToLowerInvariant());
if (a == b) continue;
parent.TryAdd(a, a);
parent.TryAdd(b, b);
var (x, y) = (Find(a), Find(b));
if (x == y) continue;
if (string.CompareOrdinal(x, y) < 0) parent[y] = x;
else parent[x] = y;
}
return parent.Keys.ToList().ToDictionary(k => k, Find, StringComparer.Ordinal);
string Find(string sha)
{
var root = sha;
while (parent[root] != root) root = parent[root];
while (parent[sha] != root)
{
var next = parent[sha];
parent[sha] = root;
sha = next;
}
return root;
}
}
}
+140 -8
View File
@@ -2,31 +2,89 @@ using System.Globalization;
using System.Text;
using System.Text.Json;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Naming;
namespace Chronos.Core.Project;
/// <summary>A project file that would be larger than <see cref="ProjectBundle.MaxBytes"/>: refused before it is written, with a sentence for the user.</summary>
public sealed class ProjectTooLargeException(long bytes)
: IOException(Loc.L("Errors.Project.TooLarge", ProjectBundle.MaxBytes >> 20))
{
/// <summary>The size the file would have had.</summary>
public long Bytes { get; } = bytes;
}
/// <summary>The archive a project file's sequence lives in: its id, and its name and folder when the file was saved.</summary>
public sealed record BundleArchive(Guid Id, string Name, string? Path);
/// <summary>The sequence a project file applies to: its id, folder (relative to the archive), title and frame count when saved.</summary>
public sealed record BundleSequence(Guid Id, string Folder, string? Title, int Frames);
/// <summary>
/// Where a workspace project's versions live (owner review 2, R8): this PC's archive (<see cref="ArchiveKind"/>, with the
/// archive's id) or a server (<see cref="ServerKind"/>, with its address), and the sequence there.
/// </summary>
public sealed record BundleHome(string Kind, Guid SequenceId, Guid? ArchiveId = null, string? Server = null)
{
public const string ArchiveKind = "archive";
public const string ServerKind = "server";
public bool IsArchive => Kind == ArchiveKind;
}
/// <summary>The version of the home a workspace project was last in step with: its id, number and content hash.</summary>
public sealed record BundleBase(Guid VersionId, int Number, string ContentHash);
/// <summary>What a workspace holds of the sequence's photos: <see cref="Proxies"/> (the default) or <see cref="Originals"/>, at a frames version of the home.</summary>
public sealed record BundleMedia(string Kind, int FramesVersion)
{
public const string Proxies = "proxies";
public const string Originals = "originals";
}
/// <summary>
/// The workspace section of a project file (format 2, owner review 2, R8): the project of the home it belongs to, its
/// name, whether it is the sequence's Main project, the home, the version it was last in step with (none before its
/// first pull) and the media the workspace holds.
/// </summary>
public sealed record BundleWorkspace(Guid ProjectId, string Name, bool IsMain, BundleHome Home, BundleBase? Base, BundleMedia Media);
/// <summary>
/// A <c>.chronos</c> project file (BRIEF §18, file associations): which sequence of which archive, and the project
/// settings to open it with. The photos stay in the archive; opening the file opens that sequence in the editor with
/// these settings. UTF-8 JSON with a format name and version, so a newer file is refused rather than misread:
/// <code>{ "format": "chronos-project", "formatVersion": 1, "saved": …, "archive": { "id", "name", "path" },
/// "sequence": { "id", "folder", "title", "frames" }, "project": { …project.json… } }</code>
/// Format 2 (owner review 2, R8) adds the <see cref="Workspace"/> section of a workspace's working state:
/// <code>"workspace": { "projectId", "name", "isMain", "home": { "kind": "archive"|"server", "server"?, "archiveId"?, "sequenceId" },
/// "base": { "versionId", "number", "contentHash" }?, "media": { "kind": "proxies"|"originals", "framesVersion" } }</code>
/// A file without that section is still written as format 1, so earlier versions of Chronos open it. A format 2 file
/// opens a project of a newer settings format too, read-only (<see cref="IsReadOnly"/>).
/// </summary>
public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequence, ProjectSettings Project, DateTimeOffset Saved)
{
public const string Extension = ".chronos";
public const string FormatName = "chronos-project";
public const int CurrentFormatVersion = 1;
/// <summary>Project settings take a few kilobytes; a larger file is not a project file.</summary>
public const int MaxBytes = 4 << 20;
/// <summary>The newest format this Chronos reads and writes (2: with a workspace section).</summary>
public const int CurrentFormatVersion = 2;
/// <summary>The format of a file without a workspace section.</summary>
public const int PlainFormatVersion = 1;
/// <summary>The workspace section (format 2); null for a plain project file.</summary>
public BundleWorkspace? Workspace { get; init; }
/// <summary>The settings come from a newer Chronos (<see cref="ProjectSettings.IsNewerFormat"/>): show them, never edit them.</summary>
public bool IsReadOnly => Project.IsNewerFormat;
/// <summary>
/// The largest project file read or written, one limit for both: a workspace's working state parks every position by
/// photo until its media are copied (some 260 bytes each), so a 100,000-frame sequence with every frame excluded takes
/// some 26 MB; a larger file is not a project file.
/// </summary>
public const int MaxBytes = 64 << 20;
private static readonly JsonWriterOptions Indented = new() { Indented = true };
@@ -37,7 +95,7 @@ public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequenc
{
w.WriteStartObject();
w.WriteString("format", FormatName);
w.WriteNumber("formatVersion", CurrentFormatVersion);
w.WriteNumber("formatVersion", Workspace is null ? PlainFormatVersion : CurrentFormatVersion);
w.WriteString("saved", Saved);
w.WriteStartObject("archive");
w.WriteString("id", Archive.Id);
@@ -50,6 +108,7 @@ public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequenc
if (Sequence.Title is not null) w.WriteString("title", Sequence.Title);
w.WriteNumber("frames", Sequence.Frames);
w.WriteEndObject();
if (Workspace is { } workspace) WriteWorkspace(w, workspace);
w.WritePropertyName("project");
// The project as project.json holds it, so both are read by the same tolerant reader.
using (var project = JsonDocument.Parse(Project.ToJson())) project.RootElement.WriteTo(w);
@@ -89,7 +148,8 @@ public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequenc
ProjectSettings settings;
try
{
settings = ProjectSettings.FromJson(project.GetRawText());
// A format 1 file refuses newer settings as it always did; a workspace's opens them read-only.
settings = ProjectSettings.FromJson(project.GetRawText(), allowNewer: version >= 2);
}
catch (JsonException ex)
{
@@ -100,7 +160,10 @@ public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequenc
new BundleArchive(Id(archive), Text(archive, "name") ?? string.Empty, Text(archive, "path")),
new BundleSequence(Id(sequence), folder, Text(sequence, "title"), frames),
settings,
saved);
saved)
{
Workspace = version >= 2 && root.TryGetProperty("workspace", out var workspace) ? ReadWorkspace(workspace) : null,
};
}
}
@@ -115,8 +178,17 @@ public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequenc
return Parse(reader.ReadToEnd());
}
/// <summary>Writes the file atomically (temp, flush, rename): an interrupted save never leaves half a file.</summary>
public void Save(string path) => AtomicFile.WriteAllText(path, ToJson());
/// <summary>
/// Writes the file atomically (temp, flush, rename): an interrupted save never leaves half a file. A file larger than
/// <see cref="MaxBytes"/> is refused before anything is written, as no read could take it back.
/// </summary>
/// <exception cref="ProjectTooLargeException">The file would be larger than <see cref="MaxBytes"/>.</exception>
public void Save(string path)
{
var bytes = new UTF8Encoding(false).GetBytes(ToJson());
if (bytes.Length > MaxBytes) throw new ProjectTooLargeException(bytes.Length);
AtomicFile.WriteAllBytes(path, bytes);
}
/// <summary>
/// The settings to give the sequence when the file is opened, the sequence having <paramref name="frameCount"/>
@@ -151,6 +223,66 @@ public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequenc
return path;
}
private static void WriteWorkspace(Utf8JsonWriter w, BundleWorkspace workspace)
{
w.WriteStartObject("workspace");
w.WriteString("projectId", workspace.ProjectId);
w.WriteString("name", workspace.Name);
w.WriteBoolean("isMain", workspace.IsMain);
w.WriteStartObject("home");
w.WriteString("kind", workspace.Home.Kind);
if (workspace.Home.Server is { } server) w.WriteString("server", server);
if (workspace.Home.ArchiveId is { } archiveId) w.WriteString("archiveId", archiveId);
w.WriteString("sequenceId", workspace.Home.SequenceId);
w.WriteEndObject();
if (workspace.Base is { } basis)
{
w.WriteStartObject("base");
w.WriteString("versionId", basis.VersionId);
w.WriteNumber("number", basis.Number);
w.WriteString("contentHash", basis.ContentHash);
w.WriteEndObject();
}
w.WriteStartObject("media");
w.WriteString("kind", workspace.Media.Kind);
w.WriteNumber("framesVersion", workspace.Media.FramesVersion);
w.WriteEndObject();
w.WriteEndObject();
}
/// <exception cref="InvalidDataException">The section is not a workspace section this Chronos can use.</exception>
private static BundleWorkspace ReadWorkspace(JsonElement section)
{
if (section.ValueKind != JsonValueKind.Object) throw new InvalidDataException("The project file's workspace section is not an object.");
var projectId = OptionalId(section, "projectId") ?? throw new InvalidDataException("The workspace section names no project.");
var home = Section(section, "home");
var kind = Text(home, "kind");
if (kind is not (BundleHome.ArchiveKind or BundleHome.ServerKind)) throw new InvalidDataException($"The workspace's home is of an unknown kind '{kind}'.");
var sequenceId = OptionalId(home, "sequenceId") ?? throw new InvalidDataException("The workspace's home names no sequence.");
BundleBase? basis = null;
if (section.TryGetProperty("base", out var b) && b.ValueKind == JsonValueKind.Object)
{
basis = new BundleBase(
OptionalId(b, "versionId") ?? throw new InvalidDataException("The workspace's base names no version."),
Number(b, "number"),
Text(b, "contentHash") ?? throw new InvalidDataException("The workspace's base has no content hash."));
}
var media = section.TryGetProperty("media", out var m) && m.ValueKind == JsonValueKind.Object
? new BundleMedia(Text(m, "kind") ?? BundleMedia.Proxies, Number(m, "framesVersion"))
: new BundleMedia(BundleMedia.Proxies, 0);
return new BundleWorkspace(projectId, Text(section, "name") ?? string.Empty,
section.TryGetProperty("isMain", out var main) && main.ValueKind == JsonValueKind.True,
new BundleHome(kind, sequenceId, OptionalId(home, "archiveId"), Text(home, "server")), basis, media);
}
private static Guid? OptionalId(JsonElement section, string name) =>
section.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String && value.TryGetGuid(out var guid) && guid != Guid.Empty
? guid
: null;
private static int Number(JsonElement section, string name) =>
section.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number && value.TryGetInt32(out var number) && number >= 0 ? number : 0;
private static JsonElement Section(JsonElement root, string name)
{
if (!root.TryGetProperty(name, out var section) || section.ValueKind != JsonValueKind.Object)
+292
View File
@@ -0,0 +1,292 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Chronos.Core.Project;
/// <summary>
/// The portable form of a project (owner review 2, R8): the settings with every frame position (exclusions, hero, camera
/// keyframes) parked by photo as <see cref="ProjectSettings.PendingFrames"/>, so the same text means the same thing on
/// every copy of the sequence (the archive, a workspace's proxies, a server) whatever frames were inserted or removed
/// since. Project versions store this form; a copy places the positions on its own frames when it opens one
/// (<see cref="Place"/>). The text is canonical (<see cref="Canonical"/>), so equal settings give equal text and an
/// equal <see cref="Hash"/>.
/// </summary>
public static class ProjectContent
{
private static readonly FramePhotos NoFrames = new([]);
/// <summary>
/// The portable form of <paramref name="settingsJson"/>, whose positions name the frames <paramref name="frames"/>
/// (by index). A position naming no frame of <paramref name="frames"/> names nothing and goes. A project of a newer
/// Chronos is only made canonical: its positions are its own business.
/// </summary>
/// <exception cref="JsonException">The text is not a project object.</exception>
public static string ToPortable(string settingsJson, FramePhotos frames)
{
ArgumentNullException.ThrowIfNull(frames);
var canonical = Canonical(settingsJson);
if (FormatOf(canonical) > ProjectSettings.CurrentVersion) return canonical;
// With no frames there is nothing to name: a translation to no frames would keep the positions as they are.
var translated = frames.Count == 0 ? WithoutPositions(canonical) : ProjectSettings.TranslateFramePositions(canonical, frames, NoFrames);
return translated is null ? canonical : Canonical(translated);
}
/// <inheritdoc cref="ToPortable(string, FramePhotos)"/>
public static string ToPortable(ProjectSettings settings, FramePhotos frames)
{
ArgumentNullException.ThrowIfNull(settings);
return ToPortable(settings.ToJson(), frames);
}
/// <summary>
/// The settings of a portable project with its positions placed on <paramref name="frames"/>: each pending frame whose
/// photo a frame holds becomes a position again; those whose photo is not there keep waiting.
/// </summary>
/// <exception cref="JsonException">The text is not a project object.</exception>
public static string Place(string portableJson, FramePhotos frames)
{
ArgumentNullException.ThrowIfNull(frames);
ArgumentNullException.ThrowIfNull(portableJson);
if (FormatOf(portableJson) > ProjectSettings.CurrentVersion) return portableJson;
return ProjectSettings.TranslateFramePositions(portableJson, null, frames) ?? portableJson;
}
/// <summary>
/// The portable text with each pending frame whose photo <paramref name="frames"/> hold named as they hold it now: an
/// encoding a conversion replaced by the one the frame holds (<see cref="PhotoAlias"/>, also its undo), a photo parked
/// before it was hashed by its SHA-256, size and capture time, and which copy of that photo it is among the frames
/// holding it under that name (a photo of a burst told apart by its order while unhashed is unique once hashed). Entries
/// that name one photo once renamed become one (<see cref="Fold"/>). The same choices on the same photos then read as
/// the same text (<see cref="SameChoices"/>), whichever encoding or hashing state they were saved against; a placement
/// finds the same frames either way. Canonical when anything is renamed or folded; the text as it is otherwise, and for
/// a newer format.
/// </summary>
/// <exception cref="JsonException">The text is not a project object.</exception>
public static string Rebind(string portableJson, FramePhotos frames)
{
ArgumentNullException.ThrowIfNull(portableJson);
ArgumentNullException.ThrowIfNull(frames);
return Renamed(portableJson, frames, hashedOnly: true);
}
/// <summary>
/// The portable text with each pending frame whose photo <paramref name="frames"/> hold named as the frame holding it is,
/// hashed or not, which copy of it included: what the text places on these frames, read so to compare two texts only
/// (<see cref="SameChoices"/>). Unlike <see cref="Rebind"/>, a SHA-256 the frames do not know yet (the photo hashed where
/// the text was saved, not when the frames were copied) gives way to the frame's size and capture time, so a text saved
/// on hashed frames and one saved on frames not hashed yet read alike. Always canonical.
/// </summary>
private static string Bound(string portableJson, FramePhotos frames) => Canonical(Renamed(portableJson, frames, hashedOnly: false));
/// <summary><see cref="Rebind"/> (<paramref name="hashedOnly"/>: only onto frames that are hashed), else <see cref="Bound"/>'s renaming.</summary>
private static string Renamed(string portableJson, FramePhotos frames, bool hashedOnly)
{
if (frames.Count == 0 || !portableJson.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase)) return portableJson;
if (FormatOf(portableJson) > ProjectSettings.CurrentVersion) return portableJson;
if (JsonNode.Parse(portableJson, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is not JsonObject project
|| project["pendingFrames"] is not JsonArray pending) return portableJson;
var renamed = false;
foreach (var entry in pending.OfType<JsonObject>())
{
var sha = entry["sha256"] is JsonValue s && s.TryGetValue<string>(out var text) ? text : null;
var size = entry["size"] is JsonValue z && z.TryGetValue<long>(out var bytes) ? bytes : -1;
DateTime? captured = entry["capturedAt"] is JsonValue t && t.TryGetValue<DateTime>(out var time) ? time : null;
if (string.IsNullOrEmpty(sha) && (captured is null || size < 0)) continue;
var occurrence = entry["occurrence"] is JsonValue o && o.TryGetValue<int>(out var n) && n > 0 ? n : 0;
// Only a frame that is hashed names a photo better than the entry does (to keep; to compare, any frame does).
if (frames.IndexOf(new FramePhoto(sha, size, captured), occurrence) is not { } at || frames[at] is not { } held || (hashedOnly && !held.IsHashed)) continue;
// The copy a placement looks for under the new name: among the frames holding that SHA-256, not those of that size and time.
var copy = frames.Occurrence(at);
var sameTime = held.CapturedAt is { } heldAt
? captured is { } entryAt && FramePhoto.Millisecond(heldAt) == FramePhoto.Millisecond(entryAt)
: captured is null;
if (string.Equals(held.Sha256 ?? string.Empty, sha ?? string.Empty, StringComparison.OrdinalIgnoreCase) && held.Size == size && sameTime
&& copy == occurrence) continue;
if (held.IsHashed) entry["sha256"] = held.Sha256!.ToLowerInvariant();
else entry.Remove("sha256");
entry["size"] = held.Size;
if (held.CapturedAt is { } heldTime) entry["capturedAt"] = heldTime;
else entry.Remove("capturedAt");
if (copy > 0) entry["occurrence"] = copy;
else entry.Remove("occurrence");
renamed = true;
}
renamed |= FoldAlike(pending);
return renamed ? Canonical(project.ToJsonString()) : portableJson;
}
/// <summary>
/// The photo a pending entry names and which copy of it: "sha:&lt;sha-256&gt;#&lt;occurrence&gt;", or
/// "photo:&lt;size&gt;@&lt;capture ticks&gt;#&lt;occurrence&gt;" for a photo not hashed; null for an entry naming no photo.
/// Entries of one key are one photo's positions (<see cref="Fold"/>).
/// </summary>
public static string? PhotoKey(JsonNode? entry)
{
if (entry is not JsonObject e) return null;
var occurrence = e["occurrence"] is JsonValue o && o.TryGetValue<int>(out var n) ? n : 0;
if (e["sha256"] is JsonValue s && s.TryGetValue<string>(out var sha) && sha.Length > 0)
return string.Create(CultureInfo.InvariantCulture, $"sha:{sha.ToLowerInvariant()}#{occurrence}");
var size = e["size"] is JsonValue z && z.TryGetValue<long>(out var bytes) ? bytes : 0;
return e["capturedAt"] is JsonValue c && c.TryGetValue<DateTime>(out var at)
? string.Create(CultureInfo.InvariantCulture, $"photo:{size}@{at.Ticks}#{occurrence}")
: null;
}
/// <summary>
/// Folds <paramref name="entry"/> into <paramref name="into"/>, two pending entries of one photo (saved under two names,
/// alike since): excluded or hero when either is, the keyframes of both (each once), and the members this Chronos does not
/// know of both (those of <paramref name="into"/> where both have one). Nothing either held is dropped.
/// </summary>
public static void Fold(JsonObject into, JsonObject entry)
{
ArgumentNullException.ThrowIfNull(into);
ArgumentNullException.ThrowIfNull(entry);
if (Flag(entry, "excluded")) into["excluded"] = true;
if (Flag(entry, "hero")) into["hero"] = true;
if (entry["keyframes"] is JsonArray { Count: > 0 } keys)
{
if (into["keyframes"] is not JsonArray mine) into["keyframes"] = mine = new JsonArray();
foreach (var key in keys.ToList())
{
if (!mine.Any(k => JsonNode.DeepEquals(k, key))) mine.Add(key?.DeepClone());
}
}
foreach (var (name, value) in entry.ToList())
{
if (!ProjectSettings.PendingMembers.Contains(name) && !into.ContainsKey(name)) into[name] = value?.DeepClone();
}
}
/// <summary>Folds the pending entries naming one photo into the first of them (<see cref="Fold"/>); whether any were.</summary>
private static bool FoldAlike(JsonArray pending)
{
var first = new Dictionary<string, JsonObject>(StringComparer.Ordinal);
var folded = new List<JsonNode>();
foreach (var entry in pending.OfType<JsonObject>())
{
if (PhotoKey(entry) is not { } key) continue;
if (first.TryGetValue(key, out var into))
{
Fold(into, entry);
folded.Add(entry);
}
else
{
first[key] = entry;
}
}
foreach (var entry in folded) pending.Remove(entry);
return folded.Count > 0;
}
private static bool Flag(JsonObject entry, string name) => entry[name] is JsonValue value && value.TryGetValue<bool>(out var set) && set;
/// <summary>
/// Whether two portable texts hold the same choices on the frames of <paramref name="frames"/>: the same text, or the
/// same once their pending frames are named as the frames hold their photos now (<see cref="Rebind"/>), or as the frame
/// each lands on is named, hashed or not (<see cref="Bound"/>): a version saved where a photo was hashed after these
/// frames were copied holds what a working state saved on them does, so it reads neither as a change nor as one to save.
/// </summary>
/// <exception cref="JsonException">A text is not a project object.</exception>
public static bool SameChoices(string portable, string other, FramePhotos frames)
{
ArgumentNullException.ThrowIfNull(portable);
ArgumentNullException.ThrowIfNull(other);
ArgumentNullException.ThrowIfNull(frames);
if (portable == other) return true;
if (frames.Count == 0) return false;
return Rebind(portable, frames) == Rebind(other, frames) || (frames.HasUnhashed && Bound(portable, frames) == Bound(other, frames));
}
/// <summary>
/// The canonical text of a project: read (a newer Chronos's too, its unknown members kept) and written again, its
/// pending frames in a fixed order (by photo) and their capture times as wall-clock values.
/// </summary>
/// <exception cref="JsonException">The text is not a project object.</exception>
public static string Canonical(string json)
{
ArgumentNullException.ThrowIfNull(json);
ProjectSettings settings;
try
{
settings = ProjectSettings.FromJson(json, allowNewer: true);
}
catch (InvalidDataException ex)
{
throw new JsonException(ex.Message, ex);
}
if (settings.PendingFrames is { Count: > 0 } pending)
{
settings = settings with { PendingFrames = [.. pending.Select(Normalized).OrderBy(Key, StringComparer.Ordinal)] };
}
return settings.ToJson();
}
/// <summary>The SHA-256 (lower-case hex) of the UTF-8 bytes of <paramref name="text"/>: a project version's content hash.</summary>
public static string Hash(string text)
{
ArgumentNullException.ThrowIfNull(text);
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
}
/// <summary>Whether <paramref name="hash"/> is the content hash of <paramref name="text"/> (any case).</summary>
public static bool Verifies(string text, string? hash) => hash is { Length: 64 } && string.Equals(Hash(text), hash, StringComparison.OrdinalIgnoreCase);
/// <summary>The settings format (<see cref="ProjectSettings.Version"/>) a project's text declares; 1 when it says none or is not a project.</summary>
public static int FormatOf(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return ProjectSettings.CurrentVersion;
try
{
return JsonNode.Parse(json, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is JsonObject project
&& project["version"] is JsonValue value && value.TryGetValue<int>(out var version) && version > 0
? version
: ProjectSettings.CurrentVersion;
}
catch (Exception ex) when (ex is JsonException or ArgumentException)
{
return ProjectSettings.CurrentVersion;
}
}
/// <summary>
/// A pending frame as the canonical text holds it: its capture time as a wall-clock value, and the frame its keyframes
/// were on left out (0: it is set again when the photo takes its place).
/// </summary>
private static PendingFrame Normalized(PendingFrame frame) => frame with
{
CapturedAt = frame.CapturedAt is { } at ? DateTime.SpecifyKind(at, DateTimeKind.Unspecified) : null,
// Read from a hand-written entry without keyframes, the list is null.
Keyframes = frame.Keyframes is { Count: > 0 } keys ? [.. keys.Select(k => k with { Frame = 0 })] : [],
};
/// <summary>Order of pending frames in the canonical text: by hash, then capture time, size and which copy of the photo.</summary>
private static string Key(PendingFrame frame) => string.Create(CultureInfo.InvariantCulture,
$"{frame.Sha256?.ToLowerInvariant()}|{frame.CapturedAt?.Ticks:D20}|{frame.Size:D20}|{frame.Occurrence:D10}");
/// <summary>A project of a sequence without frames: its positions name nothing.</summary>
private static string? WithoutPositions(string json)
{
if (JsonNode.Parse(json) is not JsonObject project) return null;
var changed = false;
if (project["excludedFrames"] is JsonArray { Count: > 0 } excluded)
{
excluded.Clear();
changed = true;
}
if (project["heroFrame"] is not null)
{
project.Remove("heroFrame");
changed = true;
}
if (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray { Count: > 0 } keys)
{
keys.Clear();
changed = true;
}
return changed ? project.ToJsonString() : null;
}
}
+97 -8
View File
@@ -44,10 +44,20 @@ public enum StackSetting
}
/// <summary>A control point of the time-remap curve: output fraction → source fraction (both 0..1).</summary>
public sealed record CurvePoint(double X, double Y);
public sealed record CurvePoint(double X, double Y)
{
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
/// <summary>Virtual-camera keyframe in normalised coordinates.</summary>
public sealed record CameraKey(int Frame, double CenterX, double CenterY, double Zoom, double Rotation, string Easing = "EaseInOut");
public sealed record CameraKey(int Frame, double CenterX, double CenterY, double Zoom, double Rotation, string Easing = "EaseInOut")
{
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
/// <summary>
/// The frame positions of a project that name a photo this copy of the sequence does not hold: settings taken from a
@@ -78,6 +88,10 @@ public sealed record PendingFrame
[JsonIgnore]
public FramePhoto Photo => new(Sha256, Size, CapturedAt);
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
public sealed record TimingSettings
@@ -91,6 +105,10 @@ public sealed record TimingSettings
public double? FitToSeconds { get; init; }
public IReadOnlyList<CurvePoint> RemapCurve { get; init; } = [new(0, 0), new(1, 1)];
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
public sealed record ExposureSettings
@@ -119,6 +137,10 @@ public sealed record ExposureSettings
/// <remarks>Written even when null: a missing value reads back as the default knee, which would turn "off" on.</remarks>
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public double? HighlightKnee { get; init; } = 0.9;
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
public sealed record MotionSettings
@@ -134,6 +156,10 @@ public sealed record MotionSettings
/// <summary>Path smoothing in frames (Gaussian sigma).</summary>
public Auto<double> StabilizeSmoothing { get; init; } = new();
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
public sealed record CameraSettings
@@ -147,6 +173,10 @@ public sealed record CameraSettings
public double OffsetX { get; init; }
public double OffsetY { get; init; }
public IReadOnlyList<CameraKey> Keyframes { get; init; } = [];
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
public sealed record StackSettings
@@ -155,6 +185,10 @@ public sealed record StackSettings
/// <summary>Window (median/mean) or trail length (star trails) in frames.</summary>
public int Length { get; init; } = 9;
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
/// <summary>Values of an export; null fields take the preset's value (BRIEF §11.4: editing any value makes it "Custom").</summary>
@@ -173,6 +207,10 @@ public sealed record ExportOverrides
public int? Quality { get; init; }
public string? RateControl { get; init; }
public string? Encoder { get; init; }
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
public sealed record ExportSettings
@@ -196,6 +234,10 @@ public sealed record ExportSettings
/// unless chosen, as renders travel on request (BRIEF §14.5).
/// </summary>
public bool SyncToServer { get; init; }
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
/// <summary>
@@ -236,6 +278,20 @@ public sealed record ProjectSettings
[JsonIgnore]
public bool HeroPending => PendingFrames?.Any(p => p.Hero) == true;
/// <summary>
/// Members this Chronos does not know (settings a newer Chronos added, such as filters): kept as they are, so a project
/// read and written again loses nothing (owner review 2, R8).
/// </summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
/// <summary>
/// Written by a newer Chronos (<see cref="Version"/> above <see cref="CurrentVersion"/>), read with
/// <see cref="FromJson(string, bool)"/> allowing it: shown, never edited, as its known values may mean something else there.
/// </summary>
[JsonIgnore]
public bool IsNewerFormat => Version > CurrentVersion;
public string ToJson() => JsonSerializer.Serialize(this, ProjectJson.Default.ProjectSettings);
/// <summary>
@@ -245,7 +301,15 @@ public sealed record ProjectSettings
/// </summary>
/// <exception cref="JsonException">The text is not a JSON object, or repeats a member.</exception>
/// <exception cref="InvalidDataException">The project was written by a newer Chronos.</exception>
public static ProjectSettings FromJson(string json)
public static ProjectSettings FromJson(string json) => FromJson(json, allowNewer: false);
/// <summary>
/// <see cref="FromJson(string)"/>, reading a project of a newer Chronos too when <paramref name="allowNewer"/>: its
/// known values, its unknown members in <see cref="Extra"/>, and <see cref="IsNewerFormat"/> set (open it read-only).
/// </summary>
/// <exception cref="JsonException">The text is not a JSON object, repeats a member, or a known member has another type.</exception>
/// <exception cref="InvalidDataException">The project was written by a newer Chronos and <paramref name="allowNewer"/> is false.</exception>
public static ProjectSettings FromJson(string json, bool allowNewer)
{
var options = new JsonNodeOptions { PropertyNameCaseInsensitive = true };
var merged = JsonNode.Parse(new ProjectSettings().ToJson(), options)!.AsObject();
@@ -266,7 +330,7 @@ public sealed record ProjectSettings
throw new JsonException("A project must be a JSON object.");
}
var settings = JsonSerializer.Deserialize(merged, ProjectJson.Default.ProjectSettings) ?? new ProjectSettings();
if (settings.Version > CurrentVersion)
if (settings.IsNewerFormat && !allowNewer)
throw new InvalidDataException($"project.json version {settings.Version} is newer than this Chronos ({CurrentVersion}).");
return settings;
}
@@ -510,14 +574,21 @@ public sealed record ProjectSettings
return changed;
}
/// <summary>Gives the pending frames whose photo <paramref name="to"/> holds their positions back.</summary>
/// <summary>
/// Gives the pending frames whose photo <paramref name="to"/> holds their positions back. An entry with members this
/// Chronos does not know (a newer one's values of the photo) stays, without its positions: those members are not this
/// Chronos's to drop, and the next portable form parks the positions in it again.
/// </summary>
private static bool PlacePending(JsonObject project, FramePhotos to, List<Parked> pending)
{
var changed = false;
foreach (var parked in pending)
{
if (to.IndexOf(parked.Photo, parked.Occurrence) is not { } at) continue;
parked.Placed = changed = true;
var kept = HasUnknownMembers(parked.Entry);
if (kept && !HoldsPosition(parked.Entry)) continue;
parked.Placed = !kept;
changed = true;
if (Flag(parked.Entry, "excluded"))
{
if (project["excludedFrames"] is not JsonArray positions) project["excludedFrames"] = positions = new JsonArray();
@@ -538,6 +609,12 @@ public sealed record ProjectSettings
keyframes.Add(copy);
}
}
if (kept)
{
parked.Entry["excluded"] = false;
parked.Entry["hero"] = false;
parked.Entry["keyframes"] = new JsonArray();
}
}
if (project["heroFrame"] is null) return changed;
// A hero is chosen: none waits any more, and an entry left with nothing to place goes.
@@ -597,8 +674,20 @@ public sealed record ProjectSettings
private static bool Flag(JsonObject entry, string name) => entry[name] is JsonValue value && value.TryGetValue<bool>(out var set) && set;
/// <summary>A pending entry still has a position to give its photo.</summary>
private static bool Waits(JsonObject entry) => Flag(entry, "excluded") || Flag(entry, "hero") || entry["keyframes"] is JsonArray { Count: > 0 };
/// <summary>The members of a pending entry this Chronos knows: its photo, which copy of it, and the positions on it.</summary>
internal static readonly HashSet<string> PendingMembers = new(StringComparer.OrdinalIgnoreCase)
{
"sha256", "size", "capturedAt", "occurrence", "excluded", "hero", "keyframes",
};
/// <summary>A pending entry has a position to give its photo.</summary>
private static bool HoldsPosition(JsonObject entry) => Flag(entry, "excluded") || Flag(entry, "hero") || entry["keyframes"] is JsonArray { Count: > 0 };
/// <summary>A pending entry holds members this Chronos does not know (written by a newer one).</summary>
private static bool HasUnknownMembers(JsonObject entry) => entry.Any(p => !PendingMembers.Contains(p.Key));
/// <summary>A pending entry still holds something: a position to give its photo, or members that are not this Chronos's to drop.</summary>
private static bool Waits(JsonObject entry) => HoldsPosition(entry) || HasUnknownMembers(entry);
private static bool IsPosition(JsonNode? node, out int position)
{