A pull onto a newer Chronos's settings made the editor throw: ProjectHistory.Replace rebased every undo and redo snapshot through ProjectMerge, which refuses to merge a newer format when both sides changed, so any non-empty undo stack broke the reload after a sync that had succeeded. Replace now drops the steps instead when either side (or a step) is of a newer format: the project is shown read-only and undo never brings back values from before the newer settings. The media learnt the home's hashes and conversion aliases only inside a replay, so a status or Save version before that compared a SHA-named base with photo-named media and read a false Modified or saved a version that only re-keyed photos. Now: - ProjectContent.SameChoices also compares the texts as placed on the frames, hashed or not (Bound), so status and commit without a home agree with the base; - a status asked of the home teaches the media its names (written under the lease, or when the lease is free), and so does a checkout of a project already here; - WorkspaceStatus.MediaOutdated reports frames moved at the home, or names the media could not learn yet, and the project menu offers Update media for it (tooltip text updated in en and it). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
293 lines
16 KiB
C#
293 lines
16 KiB
C#
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:<sha-256>#<occurrence>", or
|
|
/// "photo:<size>@<capture ticks>#<occurrence>" 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;
|
|
}
|
|
}
|