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,633 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Core.Project;
|
||||
|
||||
public enum TimingMode
|
||||
{
|
||||
/// <summary>Every source frame lasts one output frame.</summary>
|
||||
Constant,
|
||||
|
||||
/// <summary>Output time follows capture time (deliberate intervalometer pauses are kept short, gaps preserved).</summary>
|
||||
Adaptive,
|
||||
|
||||
/// <summary>Missing frames in sparse gaps are synthesised from motion.</summary>
|
||||
Interpolated,
|
||||
|
||||
/// <summary>A monotone curve maps output time to source position (speed ramps).</summary>
|
||||
Remapped,
|
||||
}
|
||||
|
||||
public enum RegionMode
|
||||
{
|
||||
Off,
|
||||
Auto,
|
||||
Horizon,
|
||||
Luminance,
|
||||
}
|
||||
|
||||
public enum FlowQualitySetting
|
||||
{
|
||||
Draft,
|
||||
Balanced,
|
||||
Best,
|
||||
}
|
||||
|
||||
public enum StackSetting
|
||||
{
|
||||
None,
|
||||
Median,
|
||||
Mean,
|
||||
StarTrails,
|
||||
}
|
||||
|
||||
/// <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);
|
||||
|
||||
/// <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");
|
||||
|
||||
/// <summary>
|
||||
/// The frame positions of a project that name a photo this copy of the sequence does not hold: settings taken from a
|
||||
/// copy that holds it (BRIEF §14.5). They become positions again when the photo arrives
|
||||
/// (<see cref="ProjectSettings.TranslateFramePositions"/>).
|
||||
/// </summary>
|
||||
public sealed record PendingFrame
|
||||
{
|
||||
public string? Sha256 { get; init; }
|
||||
public long Size { get; init; }
|
||||
public DateTime? CapturedAt { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Which of the frames holding the photo it names, in capture order, when a copy holds the photo more than once
|
||||
/// (<see cref="FramePhotos.Occurrence"/>): 0, the first, is not written.
|
||||
/// </summary>
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
|
||||
public int Occurrence { get; init; }
|
||||
|
||||
/// <summary>The photo is excluded from renders.</summary>
|
||||
public bool Excluded { get; init; }
|
||||
|
||||
/// <summary>The photo is the hero frame, unless another one is chosen before it arrives.</summary>
|
||||
public bool Hero { get; init; }
|
||||
|
||||
/// <summary>Virtual-camera keyframes on the photo; their <see cref="CameraKey.Frame"/> is set when it arrives.</summary>
|
||||
public IReadOnlyList<CameraKey> Keyframes { get; init; } = [];
|
||||
|
||||
[JsonIgnore]
|
||||
public FramePhoto Photo => new(Sha256, Size, CapturedAt);
|
||||
}
|
||||
|
||||
public sealed record TimingSettings
|
||||
{
|
||||
public Auto<TimingMode> Mode { get; init; } = new();
|
||||
|
||||
/// <summary>Output frame rate as "num/den" or an integer (e.g. "24000/1001", "30").</summary>
|
||||
public Auto<string> FrameRate { get; init; } = new();
|
||||
|
||||
/// <summary>When set, the plan is scaled so the video lasts this many seconds.</summary>
|
||||
public double? FitToSeconds { get; init; }
|
||||
|
||||
public IReadOnlyList<CurvePoint> RemapCurve { get; init; } = [new(0, 0), new(1, 1)];
|
||||
}
|
||||
|
||||
public sealed record ExposureSettings
|
||||
{
|
||||
public Auto<bool> Deflicker { get; init; } = new();
|
||||
|
||||
/// <summary>Local-regression window in frames (odd).</summary>
|
||||
public Auto<int> DeflickerWindow { get; init; } = new();
|
||||
|
||||
/// <summary>0..1: share of the flicker removed.</summary>
|
||||
public Auto<double> DeflickerStrength { get; init; } = new();
|
||||
|
||||
public Auto<RegionMode> Regions { get; init; } = new();
|
||||
|
||||
public Auto<bool> HolyGrail { get; init; } = new();
|
||||
|
||||
/// <summary>Transition length in frames for redistributed exposure steps.</summary>
|
||||
public Auto<int> TransitionLength { get; init; } = new();
|
||||
|
||||
public Auto<bool> WhiteBalanceSmoothing { get; init; } = new();
|
||||
|
||||
/// <summary>Global exposure offset in EV applied after correction.</summary>
|
||||
public double ExposureOffsetEv { get; init; }
|
||||
|
||||
/// <summary>Soft highlight knee (linear), null = hard clip at the encoder.</summary>
|
||||
/// <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;
|
||||
}
|
||||
|
||||
public sealed record MotionSettings
|
||||
{
|
||||
public Auto<bool> MotionBlur { get; init; } = new();
|
||||
|
||||
/// <summary>Target shutter angle in degrees (180 = film look).</summary>
|
||||
public Auto<double> TargetShutterAngle { get; init; } = new();
|
||||
|
||||
public Auto<FlowQualitySetting> FlowQuality { get; init; } = new();
|
||||
|
||||
public Auto<bool> Stabilize { get; init; } = new();
|
||||
|
||||
/// <summary>Path smoothing in frames (Gaussian sigma).</summary>
|
||||
public Auto<double> StabilizeSmoothing { get; init; } = new();
|
||||
}
|
||||
|
||||
public sealed record CameraSettings
|
||||
{
|
||||
/// <summary>Normalised crop (0..1) or null for the full frame.</summary>
|
||||
public double[]? Crop { get; init; }
|
||||
|
||||
/// <summary>"source", "16:9", "21:9", "4:3", "3:2", "1:1", "9:16", "4:5" or "w:h".</summary>
|
||||
public Auto<string> Aspect { get; init; } = new();
|
||||
|
||||
public double OffsetX { get; init; }
|
||||
public double OffsetY { get; init; }
|
||||
public IReadOnlyList<CameraKey> Keyframes { get; init; } = [];
|
||||
}
|
||||
|
||||
public sealed record StackSettings
|
||||
{
|
||||
public StackSetting Mode { get; init; } = StackSetting.None;
|
||||
|
||||
/// <summary>Window (median/mean) or trail length (star trails) in frames.</summary>
|
||||
public int Length { get; init; } = 9;
|
||||
}
|
||||
|
||||
/// <summary>Values of an export; null fields take the preset's value (BRIEF §11.4: editing any value makes it "Custom").</summary>
|
||||
public sealed record ExportOverrides
|
||||
{
|
||||
public string? Codec { get; init; }
|
||||
public string? Container { get; init; }
|
||||
public string? Profile { get; init; }
|
||||
public int? BitDepth { get; init; }
|
||||
public int? Width { get; init; }
|
||||
public int? Height { get; init; }
|
||||
public string? FrameRate { get; init; }
|
||||
public long? BitRate { get; init; }
|
||||
public int? GopFrames { get; init; }
|
||||
public int? BFrames { get; init; }
|
||||
public int? Quality { get; init; }
|
||||
public string? RateControl { get; init; }
|
||||
public string? Encoder { get; init; }
|
||||
}
|
||||
|
||||
public sealed record ExportSettings
|
||||
{
|
||||
/// <summary>Id of the selected preset (built-in or user); "custom" when values differ from every preset.</summary>
|
||||
public Auto<string> Preset { get; init; } = new();
|
||||
|
||||
public ExportOverrides Overrides { get; init; } = new();
|
||||
|
||||
/// <summary>Output file name template (tokens: date, title, preset, width, height, fps, codec).</summary>
|
||||
public string NameTemplate { get; init; } = "{date} {title} - {preset}";
|
||||
|
||||
/// <summary>Output folder; null = the sequence's exports folder.</summary>
|
||||
public string? Folder { get; init; }
|
||||
|
||||
/// <summary>Presets queued together by "Render another preset" / batch.</summary>
|
||||
public IReadOnlyList<string> Batch { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Export "Sync": a render made on this PC is sent to the server the sequence is linked to once it is done. Off
|
||||
/// unless chosen, as renders travel on request (BRIEF §14.5).
|
||||
/// </summary>
|
||||
public bool SyncToServer { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The "project" of a sequence (<c>.chronos/project.json</c>, BRIEF §7): every render decision. Originals are
|
||||
/// never modified; all edits live here.
|
||||
/// </summary>
|
||||
public sealed record ProjectSettings
|
||||
{
|
||||
public const int CurrentVersion = 1;
|
||||
|
||||
/// <summary>Layout of a project edited as JSON (<see cref="MoveFramePositions"/>): indented like <see cref="ToJson"/>.</summary>
|
||||
private static readonly JsonSerializerOptions IndentedJson = new() { WriteIndented = true };
|
||||
|
||||
/// <summary>Member names as a project edited as JSON reads them (an older or hand-written file may use any casing).</summary>
|
||||
private static readonly JsonNodeOptions CaseInsensitive = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
public int Version { get; init; } = CurrentVersion;
|
||||
public TimingSettings Timing { get; init; } = new();
|
||||
public ExposureSettings Exposure { get; init; } = new();
|
||||
public MotionSettings Motion { get; init; } = new();
|
||||
public CameraSettings Camera { get; init; } = new();
|
||||
public StackSettings Stack { get; init; } = new();
|
||||
public ExportSettings Export { get; init; } = new();
|
||||
|
||||
/// <summary>Frame indices excluded from renders (positions in capture order; see <see cref="MoveFramePositions"/>).</summary>
|
||||
public IReadOnlyList<int> ExcludedFrames { get; init; } = [];
|
||||
|
||||
/// <summary>Index of the hero frame (sequence thumbnail).</summary>
|
||||
public int? HeroFrame { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Exclusions, hero and keyframes naming photos this copy does not hold yet (settings synced from a copy that holds
|
||||
/// them); null when there are none. They take their place when the photos arrive (<see cref="TranslateFramePositions"/>).
|
||||
/// </summary>
|
||||
public IReadOnlyList<PendingFrame>? PendingFrames { get; init; }
|
||||
|
||||
/// <summary>The hero waits for its photo, so advice does not choose one meanwhile.</summary>
|
||||
[JsonIgnore]
|
||||
public bool HeroPending => PendingFrames?.Any(p => p.Hero) == true;
|
||||
|
||||
public string ToJson() => JsonSerializer.Serialize(this, ProjectJson.Default.ProjectSettings);
|
||||
|
||||
/// <summary>
|
||||
/// Reads a project; members missing from <paramref name="json"/> (an API client's partial settings, an older file)
|
||||
/// keep their defaults. The JSON is laid over the default project first, because generated deserialisation leaves
|
||||
/// missing init-only members null or false rather than at their initial values.
|
||||
/// </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)
|
||||
{
|
||||
var options = new JsonNodeOptions { PropertyNameCaseInsensitive = true };
|
||||
var merged = JsonNode.Parse(new ProjectSettings().ToJson(), options)!.AsObject();
|
||||
switch (JsonNode.Parse(json, options))
|
||||
{
|
||||
case JsonObject given:
|
||||
try
|
||||
{
|
||||
Overlay(merged, given);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
// A parsed object builds its member table on first use and rejects a name given twice (in any casing).
|
||||
throw new JsonException("A project member is given more than once.", ex);
|
||||
}
|
||||
break;
|
||||
case not null:
|
||||
throw new JsonException("A project must be a JSON object.");
|
||||
}
|
||||
var settings = JsonSerializer.Deserialize(merged, ProjectJson.Default.ProjectSettings) ?? new ProjectSettings();
|
||||
if (settings.Version > CurrentVersion)
|
||||
throw new InvalidDataException($"project.json version {settings.Version} is newer than this Chronos ({CurrentVersion}).");
|
||||
return settings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies <paramref name="source"/> into <paramref name="target"/>, merging nested objects. A null keeps a default that
|
||||
/// is an object, a list or a text, since none of those members is nullable; elsewhere it clears a nullable value.
|
||||
/// </summary>
|
||||
private static void Overlay(JsonObject target, JsonObject source)
|
||||
{
|
||||
foreach (var (name, value) in source)
|
||||
{
|
||||
var current = target[name];
|
||||
if (value is JsonObject child && current is JsonObject section) Overlay(section, child);
|
||||
else if (value is not null || !(current is JsonObject or JsonArray || current?.GetValueKind() == JsonValueKind.String))
|
||||
target[name] = value?.DeepClone();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the frame positions of a project — <see cref="ExcludedFrames"/>, <see cref="HeroFrame"/> and the
|
||||
/// virtual-camera <see cref="CameraKey.Frame"/>s — after frames were inserted before them: <paramref name="moves"/> maps
|
||||
/// an old position to the new one, and a position it does not list stays. The JSON is edited in place, so members
|
||||
/// this Chronos does not know survive. Null when nothing moves or <paramref name="json"/> is not a project object.
|
||||
/// </summary>
|
||||
public static string? MoveFramePositions(string json, IReadOnlyDictionary<int, int> moves)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(moves);
|
||||
if (moves.Count == 0 || string.IsNullOrWhiteSpace(json)) return null;
|
||||
try
|
||||
{
|
||||
if (JsonNode.Parse(json, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is not JsonObject project) return null;
|
||||
var moved = false;
|
||||
if (project["excludedFrames"] is JsonArray excluded)
|
||||
{
|
||||
for (var i = 0; i < excluded.Count; i++)
|
||||
{
|
||||
var at = i;
|
||||
moved |= Move(excluded[at], value => excluded[at] = value, moves);
|
||||
}
|
||||
}
|
||||
if (project["heroFrame"] is { } hero) moved |= Move(hero, value => project["heroFrame"] = value, moves);
|
||||
if (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray keyframes)
|
||||
{
|
||||
foreach (var key in keyframes.OfType<JsonObject>())
|
||||
{
|
||||
if (key["frame"] is { } frame) moved |= Move(frame, value => key["frame"] = value, moves);
|
||||
}
|
||||
}
|
||||
return moved ? project.ToJsonString(IndentedJson) : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or ArgumentException)
|
||||
{
|
||||
// Not JSON, or a member given twice (the case-insensitive member table refuses it): not a project to edit.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A project written against the frames <paramref name="before"/> (frame ids, by index) moved to the frames
|
||||
/// <paramref name="after"/> (in index order) the way the archive index moves its own copy when it takes them
|
||||
/// (ProjectPositions in Chronos.Data): while every frame of <paramref name="before"/> is still there, its positions
|
||||
/// move with their frames (<see cref="MoveFramePositions"/>), otherwise they stay; either way pending frames whose
|
||||
/// photos are now there take their place (<see cref="TranslateFramePositions"/>). An editor that read the frames
|
||||
/// before frames were inserted saves its edit in the new order this way. Null when nothing changes.
|
||||
/// </summary>
|
||||
public static string? FollowFrames(string json, IReadOnlyList<Guid> before, IReadOnlyList<Frame> after)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(before);
|
||||
ArgumentNullException.ThrowIfNull(after);
|
||||
var now = new Dictionary<Guid, int>(after.Count);
|
||||
for (var i = 0; i < after.Count; i++) now[after[i].Id] = i;
|
||||
Dictionary<int, int>? moves = [];
|
||||
for (var i = 0; i < before.Count; i++)
|
||||
{
|
||||
if (!now.TryGetValue(before[i], out var index))
|
||||
{
|
||||
moves = null;
|
||||
break;
|
||||
}
|
||||
if (index != i) moves[i] = index;
|
||||
}
|
||||
var moved = moves is null ? null : MoveFramePositions(json, moves);
|
||||
var current = moved ?? json;
|
||||
// Most projects wait for no photo: the frames' photos are gathered only for those that do.
|
||||
var placed = current.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase)
|
||||
? TranslateFramePositions(current, null, new FramePhotos(after.Select((f, i) => (i, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))))
|
||||
: null;
|
||||
return placed ?? moved;
|
||||
}
|
||||
|
||||
private static bool Move(JsonNode? position, Action<JsonNode> replace, IReadOnlyDictionary<int, int> moves)
|
||||
{
|
||||
if (position is not JsonValue value || !value.TryGetValue<int>(out var old) || !moves.TryGetValue(old, out var now) || now == old) return false;
|
||||
replace(JsonValue.Create(now));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a project names frames (exclusions, a hero, camera keyframes or <see cref="PendingFrames"/>); settings
|
||||
/// naming none cross between copies of a sequence as they are. False for text that is not a project object.
|
||||
/// </summary>
|
||||
public static bool NamesFrames(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) return false;
|
||||
try
|
||||
{
|
||||
return JsonNode.Parse(json, CaseInsensitive) is JsonObject project
|
||||
&& (project["excludedFrames"] is JsonArray { Count: > 0 } || project["heroFrame"] is JsonValue || project["pendingFrames"] is JsonArray { Count: > 0 }
|
||||
|| (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray { Count: > 0 }));
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or ArgumentException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Translates the frame positions of a project written against the frames of another copy of the sequence
|
||||
/// (<paramref name="from"/>; a server sequence and a PC's copy hold the same photos, though not always all of them,
|
||||
/// BRIEF §14.5) to the frames of <paramref name="to"/>, by photo: each exclusion, the hero and each camera keyframe
|
||||
/// moves to the frame of <paramref name="to"/> holding its photo, and a position on the n-th frame holding a photo
|
||||
/// <paramref name="from"/> holds more than once to the n-th such frame (<see cref="FramePhotos.Occurrence"/>), so
|
||||
/// duplicates stay apart. One whose photo (or that copy of it) <paramref name="to"/> lacks becomes
|
||||
/// a <see cref="PendingFrame"/>, and pending frames whose photo <paramref name="to"/> holds become positions again; a
|
||||
/// pending hero only while no other hero is chosen (a hero chosen since one was left pending is newer, so that one no
|
||||
/// longer waits even when the chosen one must wait in turn), a pending keyframe only where no keyframe is. With
|
||||
/// <paramref name="from"/> null the positions already name <paramref name="to"/>'s frames and only pending frames are
|
||||
/// placed (photos that arrived). A position naming no frame of <paramref name="from"/> names nothing and goes. Edited
|
||||
/// in place like <see cref="MoveFramePositions"/>; null when nothing changes or <paramref name="json"/> is not a
|
||||
/// project object.
|
||||
/// </summary>
|
||||
public static string? TranslateFramePositions(string json, FramePhotos? from, FramePhotos to)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(to);
|
||||
if (string.IsNullOrWhiteSpace(json)) return null;
|
||||
try
|
||||
{
|
||||
if (JsonNode.Parse(json, CaseInsensitive) is not JsonObject project) return null;
|
||||
var pending = new List<Parked>();
|
||||
var unreadable = new List<JsonNode?>();
|
||||
if (project["pendingFrames"] is JsonArray stored)
|
||||
{
|
||||
foreach (var node in stored)
|
||||
{
|
||||
// An entry naming no photo is not this Chronos's to place: it stays as it is.
|
||||
if (node is JsonObject entry && PhotoOf(entry) is { } photo) pending.Add(new Parked(photo, OccurrenceOf(entry), entry.DeepClone().AsObject()));
|
||||
else unreadable.Add(node?.DeepClone());
|
||||
}
|
||||
}
|
||||
var changed = false;
|
||||
if (project["heroFrame"] is JsonValue && pending.Any(p => Flag(p.Entry, "hero")))
|
||||
{
|
||||
// Checked before the hero itself may be parked below, which leaves no hero chosen.
|
||||
foreach (var parked in pending) parked.Entry["hero"] = false;
|
||||
pending.RemoveAll(p => !Waits(p.Entry));
|
||||
changed = true;
|
||||
}
|
||||
changed |= from is not null && !from.SameAs(to) && TranslatePositions(project, from, to, pending);
|
||||
changed |= PlacePending(project, to, pending);
|
||||
if (!changed) return null;
|
||||
SortPositions(project);
|
||||
var left = pending.Where(p => !p.Placed).Select(p => (JsonNode?)p.Entry).Concat(unreadable).ToArray();
|
||||
if (left.Length == 0) project.Remove("pendingFrames");
|
||||
else project["pendingFrames"] = new JsonArray(left);
|
||||
return project.ToJsonString(IndentedJson);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or ArgumentException or InvalidOperationException)
|
||||
{
|
||||
// Not JSON, a member given twice, or a member of an unexpected kind: not a project to edit.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Moves every position of <paramref name="project"/> from <paramref name="from"/>'s frames to <paramref name="to"/>'s.</summary>
|
||||
private static bool TranslatePositions(JsonObject project, FramePhotos from, FramePhotos to, List<Parked> pending)
|
||||
{
|
||||
var changed = false;
|
||||
if (project["excludedFrames"] is JsonArray excluded)
|
||||
{
|
||||
var kept = new List<JsonNode?>(excluded.Count);
|
||||
foreach (var node in excluded)
|
||||
{
|
||||
if (!IsPosition(node, out var at)) kept.Add(node?.DeepClone());
|
||||
else if (from[at] is not { } photo) changed = true;
|
||||
else if (to.IndexOf(photo, from.Occurrence(at)) is { } now)
|
||||
{
|
||||
kept.Add(JsonValue.Create(now));
|
||||
changed |= now != at;
|
||||
}
|
||||
else
|
||||
{
|
||||
Park(pending, photo, from.Occurrence(at)).Entry["excluded"] = true;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Replace(excluded, kept);
|
||||
}
|
||||
if (project["heroFrame"] is JsonValue hero && hero.TryGetValue<int>(out var heroAt))
|
||||
{
|
||||
var photo = from[heroAt];
|
||||
var now = photo is null ? null : to.IndexOf(photo, from.Occurrence(heroAt));
|
||||
if (photo is not null && now is null) Park(pending, photo, from.Occurrence(heroAt)).Entry["hero"] = true;
|
||||
if (now != heroAt)
|
||||
{
|
||||
project["heroFrame"] = now;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray keyframes)
|
||||
{
|
||||
var kept = new List<JsonNode?>(keyframes.Count);
|
||||
foreach (var node in keyframes)
|
||||
{
|
||||
if (node is not JsonObject key || !IsPosition(key["frame"], out var at))
|
||||
{
|
||||
kept.Add(node?.DeepClone());
|
||||
continue;
|
||||
}
|
||||
var copy = key.DeepClone().AsObject();
|
||||
if (from[at] is not { } photo)
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
else if (to.IndexOf(photo, from.Occurrence(at)) is { } now)
|
||||
{
|
||||
copy["frame"] = now;
|
||||
kept.Add(copy);
|
||||
changed |= now != at;
|
||||
}
|
||||
else
|
||||
{
|
||||
var parked = Park(pending, photo, from.Occurrence(at)).Entry;
|
||||
if (parked["keyframes"] is not JsonArray keys) parked["keyframes"] = keys = new JsonArray();
|
||||
keys.Add(copy);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Replace(keyframes, kept);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>Gives the pending frames whose photo <paramref name="to"/> holds their positions back.</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;
|
||||
if (Flag(parked.Entry, "excluded"))
|
||||
{
|
||||
if (project["excludedFrames"] is not JsonArray positions) project["excludedFrames"] = positions = new JsonArray();
|
||||
if (!positions.Any(n => IsPosition(n, out var p) && p == at)) positions.Add(at);
|
||||
}
|
||||
// A hero chosen since the settings were taken is newer than the one that waited.
|
||||
if (Flag(parked.Entry, "hero") && project["heroFrame"] is null) project["heroFrame"] = at;
|
||||
if (parked.Entry["keyframes"] is JsonArray { Count: > 0 } keys)
|
||||
{
|
||||
if (project["camera"] is not JsonObject camera) project["camera"] = camera = new JsonObject();
|
||||
if (camera["keyframes"] is not JsonArray keyframes) camera["keyframes"] = keyframes = new JsonArray();
|
||||
foreach (var key in keys.OfType<JsonObject>())
|
||||
{
|
||||
// A keyframe set on that frame since is newer.
|
||||
if (keyframes.Any(n => n is JsonObject k && IsPosition(k["frame"], out var f) && f == at)) continue;
|
||||
var copy = key.DeepClone().AsObject();
|
||||
copy["frame"] = at;
|
||||
keyframes.Add(copy);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (project["heroFrame"] is null) return changed;
|
||||
// A hero is chosen: none waits any more, and an entry left with nothing to place goes.
|
||||
foreach (var parked in pending.Where(p => !p.Placed && Flag(p.Entry, "hero")))
|
||||
{
|
||||
parked.Entry["hero"] = false;
|
||||
parked.Placed = !Waits(parked.Entry);
|
||||
changed = true;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>Exclusions in ascending order without repeats and keyframes by frame (values that are no position last, as they were).</summary>
|
||||
private static void SortPositions(JsonObject project)
|
||||
{
|
||||
if (project["excludedFrames"] is JsonArray excluded)
|
||||
{
|
||||
var positions = excluded.Select(n => IsPosition(n, out var p) ? p : (int?)null).OfType<int>().Distinct().Order().Select(p => (JsonNode?)JsonValue.Create(p));
|
||||
Replace(excluded, [.. positions, .. excluded.Where(n => !IsPosition(n, out _)).Select(n => n?.DeepClone())]);
|
||||
}
|
||||
if (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray keyframes)
|
||||
{
|
||||
var sorted = keyframes.Select(n => n?.DeepClone())
|
||||
.OrderBy(n => n is JsonObject key && IsPosition(key["frame"], out var f) ? f : int.MaxValue).ToList();
|
||||
Replace(keyframes, sorted);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The pending entry of <paramref name="photo"/> (the copy of it <paramref name="occurrence"/> names), added when there is none.</summary>
|
||||
private static Parked Park(List<Parked> pending, FramePhoto photo, int occurrence)
|
||||
{
|
||||
if (pending.FirstOrDefault(p => p.Occurrence == occurrence && p.Photo.Matches(photo)) is { } known) return known;
|
||||
var entry = new JsonObject();
|
||||
if (photo.IsHashed) entry["sha256"] = photo.Sha256!.ToLowerInvariant();
|
||||
entry["size"] = photo.Size;
|
||||
if (photo.CapturedAt is { } captured) entry["capturedAt"] = captured;
|
||||
if (occurrence > 0) entry["occurrence"] = occurrence;
|
||||
entry["excluded"] = false;
|
||||
entry["hero"] = false;
|
||||
entry["keyframes"] = new JsonArray();
|
||||
var parked = new Parked(photo, occurrence, entry);
|
||||
pending.Add(parked);
|
||||
return parked;
|
||||
}
|
||||
|
||||
/// <summary>The photo a pending entry names; null when it names none.</summary>
|
||||
private static FramePhoto? PhotoOf(JsonObject entry)
|
||||
{
|
||||
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;
|
||||
return string.IsNullOrEmpty(sha) && (captured is null || size < 0) ? null : new FramePhoto(sha, size, captured);
|
||||
}
|
||||
|
||||
/// <summary>Which copy of its photo a pending entry names; the first when it says nothing (or nothing readable).</summary>
|
||||
private static int OccurrenceOf(JsonObject entry) => entry["occurrence"] is JsonValue o && o.TryGetValue<int>(out var occurrence) && occurrence > 0 ? occurrence : 0;
|
||||
|
||||
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 };
|
||||
|
||||
private static bool IsPosition(JsonNode? node, out int position)
|
||||
{
|
||||
position = 0;
|
||||
return node is JsonValue value && value.TryGetValue(out position);
|
||||
}
|
||||
|
||||
private static void Replace(JsonArray array, IEnumerable<JsonNode?> nodes)
|
||||
{
|
||||
var copy = nodes.ToList();
|
||||
array.Clear();
|
||||
foreach (var node in copy) array.Add(node);
|
||||
}
|
||||
|
||||
/// <summary>A pending entry being edited: its photo (and which copy of it), its JSON, and whether its photo took its place.</summary>
|
||||
private sealed class Parked(FramePhoto photo, int occurrence, JsonObject entry)
|
||||
{
|
||||
public FramePhoto Photo { get; } = photo;
|
||||
public int Occurrence { get; } = occurrence;
|
||||
public JsonObject Entry { get; } = entry;
|
||||
public bool Placed { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
WriteIndented = true,
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
UseStringEnumConverter = true,
|
||||
PropertyNameCaseInsensitive = true)]
|
||||
[JsonSerializable(typeof(ProjectSettings))]
|
||||
internal sealed partial class ProjectJson : JsonSerializerContext;
|
||||
Reference in new issue
Block a user