feat(editor): visual crop, rotate/mirror/flip/straighten, colour looks (owner review 1 phase 4) (#26)
CI / Build and test (push) Successful in 8m19s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 12m9s
CI / PostgreSQL 16 integration (push) Successful in 7m49s
CI / PostgreSQL 17 integration (push) Successful in 7m19s
CI / Docker image (push) Successful in 46s
Release / Server image (push) Successful in 1m14s

Owner review 1 R5 + R6. Camera rotation, mirror, flip, straighten and crop handles locked to the output; an Exposure Look group; Export output size ("proportions win"); settings format 2 with older-node gates. Also fixes project text and hashes differing between Windows and Linux.

Closes #19
Closes #20

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 #26.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-05 01:09:09 +01:00
1 parent db389a54f2
commit 188b2c2e55
355 files changed
+10549 -1061

No files matched your search

@@ -2,6 +2,8 @@ using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Video;
using Chronos.Data.Jobs;
using Chronos.Protocol;
@@ -32,8 +34,11 @@ internal sealed class ManagedRenderJobHandler(RenderJobHandler render, Processin
try
{
parameters = ProcessingJobs.ReadParameters(job.ParametersJson);
// Most jobs are decided by the main codec, before the export is read.
if (Produces(parameters.Codec) && RenderJobHandler.Targets(ProcessingJobs.ReadExport(parameters.PresetJson), parameters.PresetName).All(t => Produces(t.Export)))
// Most jobs are decided by the main codec, before the export is read. The job's own output is checked at the size the
// job names (the server's: the chosen proportions fitted in a fixed-size preset, owner review 1, phase 4).
if (Produces(parameters.Codec) && RenderJobHandler.Targets(ProcessingJobs.ReadExport(parameters.PresetJson), parameters.PresetName)
.Select((t, i) => i == 0 && t.Export is { Width: > 0, Height: > 0 } ? Produces(t.Export, parameters.Width, parameters.Height) : Produces(t.Export))
.All(produced => produced))
return true;
}
catch (Exception ex) when (ex is not OperationCanceledException)
@@ -55,7 +60,7 @@ internal sealed class ManagedRenderJobHandler(RenderJobHandler render, Processin
}
public Task RunAsync(JobContext context) =>
render.RunAsync(context, target => Produces(target.Export) ? target : Fallback(context, target));
render.RunAsync(context, (target, project) => Produces(target.Export, project) ? target : Fallback(context, target));
/// <summary>The output as MJPEG in AVI with the managed preset's quality, at the size and frame rate asked for.</summary>
private static ExportTarget Fallback(JobContext context, ExportTarget target)
@@ -83,6 +88,21 @@ internal sealed class ManagedRenderJobHandler(RenderJobHandler render, Processin
private bool Produces(string codec) =>
_capabilities.Any(c => string.Equals(ProcessingJobs.CodecName(c.Codec), codec, StringComparison.OrdinalIgnoreCase));
private bool Produces(ResolvedExport export) =>
_capabilities.Any(c => c.Codec == export.Codec && export.Width <= c.MaxWidth && export.Height <= c.MaxHeight);
/// <summary>A managed encoder writes <paramref name="export"/> at the preset's size (a free-size preset is not checked by size).</summary>
private bool Produces(ResolvedExport export) => Produces(export, export.Width, export.Height);
/// <summary>
/// A managed encoder writes <paramref name="export"/> at the size <paramref name="project"/> gives it: a fixed-size preset
/// adapted to the chosen proportions (<see cref="RenderSize"/>, 4K at 9:16 = 2160×3840).
/// </summary>
private bool Produces(ResolvedExport export, ProjectSettings project)
{
if (export is not { Width: > 0, Height: > 0 }) return Produces(export);
// A fixed-size preset's output does not depend on the source's size.
var (width, height) = RenderSize.Of(project.Camera, export, export.Width, export.Height);
return Produces(export, width, height);
}
private bool Produces(ResolvedExport export, int width, int height) =>
_capabilities.Any(c => c.Codec == export.Codec && EncoderSelector.Takes(c, width, height));
}
@@ -30,10 +30,13 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
{
public JobKind Kind => JobKind.Render;
public Task RunAsync(JobContext context) => RunAsync(context, target => target);
public Task RunAsync(JobContext context) => RunAsync(context, (target, _) => target);
/// <summary>Runs the job with each output still to render passed through <paramref name="adapt"/> (the server's managed stand-ins).</summary>
internal async Task RunAsync(JobContext context, Func<ExportTarget, ExportTarget> adapt)
/// <summary>
/// Runs the job with each output still to render passed through <paramref name="adapt"/> with the settings rendered (the
/// server's managed stand-ins, which look at the size those settings give the output).
/// </summary>
internal async Task RunAsync(JobContext context, Func<ExportTarget, ProjectSettings, ExportTarget> adapt)
{
var cancellation = context.Cancellation;
var (parameters, export) = ProcessingJobs.ReadRender(context.Job.ParametersJson);
@@ -72,7 +75,7 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
Discard(output, keepOutput: recorded.Any(r => r.OutputPath == Stored(paths, output)));
names.Release(output); // free again for the entry's new attempt
}
var targets = all.Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).Select(t => (t.i, adapt(t.t))).ToList();
var targets = all.Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).Select(t => (t.i, adapt(t.t, project))).ToList();
if (targets.Count == 0) return;
var companions = await GprCompanions.FindAsync(db, archive, frames.Frames, cancellation).ConfigureAwait(false);
@@ -154,7 +157,7 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
|| await db.Projects.GetVersionAsync(versionId, cancellationToken).ConfigureAwait(false) is not { } version
|| (project is { } named && version.ProjectId != named)
|| await db.Projects.GetAsync(version.ProjectId, cancellationToken).ConfigureAwait(false) is not { } of || of.SequenceId != sequence.Id
|| (parameters.SettingsJson is { } embedded && !ProjectContent.Verifies(embedded, version.ContentHash)))
|| (parameters.SettingsJson is { } embedded && !ProjectContent.MatchesHash(embedded, version.ContentHash)))
return (project, null);
return (version.ProjectId, versionId);
}
+83 -11
View File
@@ -5,6 +5,7 @@ using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Video;
using Chronos.Data.Archiving.Jobs;
using Chronos.Protocol;
@@ -28,15 +29,17 @@ public static class ProcessingJobs
/// <summary>
/// <see cref="JobKind.Render"/> of one sequence. <paramref name="export"/> (preset, overrides, name template,
/// folder, batch) replaces the project's export section; <paramref name="project"/> embeds the settings to render,
/// null renders the sequence's current project. <paramref name="sourceWidth"/>×<paramref name="sourceHeight"/>
/// stands in for a preset without a fixed size, so render nodes can match the job by resolution.
/// null renders the sequence's current project. <paramref name="sourceWidth"/>×<paramref name="sourceHeight"/> (the
/// frames' Exif-oriented size) gives the output size of the settings rendered (<see cref="RenderSize"/>; the sequence's
/// own when <paramref name="project"/> is null), so render nodes can match the job by resolution, and the settings
/// format the render needs (<see cref="RenderRules.RequiredFormat"/>).
/// </summary>
public static ArchiveJobRequest Render(Sequence sequence, ExportSettings export, int sourceWidth, int sourceHeight, ProjectSettings? project = null,
bool useProxies = false)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(export);
var parameters = Parameters(export, sourceWidth, sourceHeight, project?.ToJson(), useProxies);
var parameters = Parameters(export, sourceWidth, sourceHeight, project?.ToJson(), useProxies, project ?? ReadSettings(sequence.SettingsJson));
return new ArchiveJobRequest(JobKind.Render, [sequence.Id], RenderLabel(sequence.DisplayTitle, parameters.PresetName),
JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters), JobPriority.User);
}
@@ -80,20 +83,22 @@ public static class ProcessingJobs
/// <summary>
/// A posted render job as one job per preset, as <see cref="RenderEach"/> makes them (a render node uploads one file
/// per job): the job itself when it has no batch; otherwise its own preset, then each batch preset with its own values,
/// all with the job's project and proxy choice. <paramref name="sourceWidth"/>×<paramref name="sourceHeight"/> stands in
/// for a batch preset without a fixed size.
/// all with the job's project and proxy choice. <paramref name="sourceWidth"/>×<paramref name="sourceHeight"/> (the
/// frames' Exif-oriented size) stands in for a batch preset without a fixed size. With the <paramref name="settings"/>
/// the job renders, every job gets the output size and the settings format its render needs (<see cref="Routed"/>);
/// without them, the job keeps the size it was posted with and each batch preset its preset's.
/// </summary>
/// <exception cref="InvalidDataException">The preset JSON is not an export section.</exception>
public static IReadOnlyList<RenderJobParameters> Split(RenderJobParameters parameters, int sourceWidth, int sourceHeight)
public static IReadOnlyList<RenderJobParameters> Split(RenderJobParameters parameters, int sourceWidth, int sourceHeight, ProjectSettings? settings = null)
{
ArgumentNullException.ThrowIfNull(parameters);
var export = ReadExport(parameters.PresetJson);
var batch = BatchPresets(export).ToList();
if (batch.Count == 0) return [parameters];
var own = batch.Count == 0 ? parameters : parameters with { PresetJson = JsonSerializer.Serialize(export with { Batch = [] }, ProcessingJson.Default.ExportSettings) };
return
[
parameters with { PresetJson = JsonSerializer.Serialize(export with { Batch = [] }, ProcessingJson.Default.ExportSettings) },
.. batch.Select(id => Parameters(BatchExport(export, id), sourceWidth, sourceHeight, parameters.SettingsJson, parameters.UseProxies) with
settings is null ? own : Routed(own, settings, sourceWidth, sourceHeight),
.. batch.Select(id => Parameters(BatchExport(export, id), sourceWidth, sourceHeight, parameters.SettingsJson, parameters.UseProxies, settings) with
{
ProjectId = parameters.ProjectId,
ProjectVersionId = parameters.ProjectVersionId,
@@ -101,6 +106,59 @@ public static class ProcessingJobs
];
}
/// <summary>
/// A render job's parameters with the output size and the settings format a render of <paramref name="settings"/> needs
/// (owner review 1, phase 4: the chosen proportions win over a fixed-size preset, a quarter turn swaps a source-sized
/// output). The size comes from the job's preset, as the render does: never from the size the job was posted with,
/// which a newer client already adapted to the settings of the moment (a long edge kept for 1:1 cannot be adapted back
/// to 16:9 once the sequence's settings change). Other presets are sized on the source. The format is at least the one
/// the job was posted with.
/// </summary>
/// <exception cref="InvalidDataException">The preset JSON is not an export section.</exception>
public static RenderJobParameters Routed(RenderJobParameters parameters, ProjectSettings settings, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(parameters);
ArgumentNullException.ThrowIfNull(settings);
var resolved = ExportResolver.Resolve(ReadExport(parameters.PresetJson));
var (width, height) = Size(settings, resolved, sourceWidth, sourceHeight) ?? (parameters.Width, parameters.Height);
return parameters with
{
Width = width,
Height = height,
RequiredSettingsFormat = int.Max(parameters.RequiredSettingsFormat, RequiredFormat(settings, resolved, sourceWidth, sourceHeight)),
};
}
/// <summary>
/// The settings format a render of <paramref name="settings"/> with <paramref name="export"/> and each of its batch
/// presets needs (the highest <see cref="RenderRules.RequiredFormat"/> of them): what a server or a render node must read
/// to render it as this Chronos would.
/// </summary>
public static int RequiredFormat(ProjectSettings settings, ExportSettings export, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(export);
return BatchPresets(export).Select(id => ExportResolver.Resolve(BatchExport(export, id))).Prepend(ExportResolver.Resolve(export))
.Max(resolved => RequiredFormat(settings, resolved, sourceWidth, sourceHeight));
}
/// <summary>
/// Project settings read for their output size and format, a newer Chronos's too (its format stands); null when there
/// are none or the text is not a project.
/// </summary>
public static ProjectSettings? ReadSettings(string? settingsJson)
{
if (string.IsNullOrWhiteSpace(settingsJson)) return null;
try
{
return ProjectSettings.FromJson(settingsJson, allowNewer: true);
}
catch (JsonException)
{
return null;
}
}
/// <summary>
/// One <see cref="Render"/> job per preset of <paramref name="export"/>: its preset, then each batch preset with its
/// own values. For a server: a render node uploads one file per job, so a batch must not travel as one job.
@@ -128,13 +186,27 @@ public static class ProcessingJobs
internal static ExportSettings BatchExport(ExportSettings export, string presetId) =>
new() { Preset = new Auto<string>().WithManual(presetId), NameTemplate = export.NameTemplate, Folder = export.Folder };
private static RenderJobParameters Parameters(ExportSettings export, int sourceWidth, int sourceHeight, string? settingsJson, bool useProxies)
/// <param name="settings">The settings rendered, for the output size and the format (else read from <paramref name="settingsJson"/>); unknown, the preset's size.</param>
private static RenderJobParameters Parameters(ExportSettings export, int sourceWidth, int sourceHeight, string? settingsJson, bool useProxies,
ProjectSettings? settings = null)
{
var resolved = ExportResolver.Resolve(export);
settings ??= ReadSettings(settingsJson);
var (width, height) = (settings is null ? null : Size(settings, resolved, sourceWidth, sourceHeight))
?? (resolved.Width > 0 ? resolved.Width : sourceWidth, resolved.Height > 0 ? resolved.Height : sourceHeight);
var format = settings is null ? ProjectSettings.BaseVersion : RequiredFormat(settings, resolved, sourceWidth, sourceHeight);
return new RenderJobParameters(PresetName(resolved), JsonSerializer.Serialize(export, ProcessingJson.Default.ExportSettings), CodecName(resolved.Codec),
resolved.Width > 0 ? resolved.Width : sourceWidth, resolved.Height > 0 ? resolved.Height : sourceHeight, useProxies, settingsJson);
width, height, useProxies, settingsJson, RequiredSettingsFormat: format);
}
/// <summary>The output size of <paramref name="settings"/> with <paramref name="export"/> (<see cref="RenderSize.Of"/>); null without a source size.</summary>
private static (int Width, int Height)? Size(ProjectSettings settings, ResolvedExport export, int sourceWidth, int sourceHeight) =>
sourceWidth > 0 && sourceHeight > 0 ? RenderSize.Of(settings.Camera, export, sourceWidth, sourceHeight) : null;
/// <summary><see cref="RenderRules.RequiredFormat"/>; without a source size, the format the settings are written in.</summary>
private static int RequiredFormat(ProjectSettings settings, ResolvedExport export, int sourceWidth, int sourceHeight) =>
sourceWidth > 0 && sourceHeight > 0 ? RenderRules.RequiredFormat(settings, export, sourceWidth, sourceHeight) : settings.WrittenFormat;
/// <summary>Codec name in job parameters and render-node capabilities ("h264", "hevc", "mjpeg", "pngsequence"…).</summary>
public static string CodecName(VideoCodec codec) => codec.ToString().ToLowerInvariant();
+10 -1
View File
@@ -1,6 +1,7 @@
using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
@@ -22,7 +23,10 @@ internal sealed class ProjectStore(ChronosDatabase db, SequenceWriter writer)
public static ProjectSettings Read(Sequence sequence, SequencePaths folder) =>
Parse(sequence.SettingsJson ?? (File.Exists(folder.ProjectPath) ? AtomicFile.ReadAllText(folder.ProjectPath) : null));
/// <exception cref="InvalidDataException">The settings are not valid JSON or come from a newer Chronos.</exception>
/// <exception cref="InvalidDataException">
/// The settings are not valid JSON, or come from a newer Chronos (<c>Errors.Render.NewerSettings</c>, which a render's
/// job shows as its error).
/// </exception>
public static ProjectSettings Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings();
@@ -34,6 +38,11 @@ internal sealed class ProjectStore(ChronosDatabase db, SequenceWriter writer)
{
throw new InvalidDataException(ex.Message, ex);
}
catch (InvalidDataException ex)
{
// A settings format above this Chronos's (owner review 1, phase 4: a server, a node or a desktop that is older).
throw new InvalidDataException(Loc.L("Errors.Render.NewerSettings"), ex);
}
}
/// <summary>Applies <paramref name="edit"/> to the settings in force and stores the result when it differs; false when nothing changed.</summary>
@@ -7,6 +7,7 @@ using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Video;
using Chronos.Data.Archiving;
@@ -117,10 +118,11 @@ public sealed class RenderNodeClient : IAsyncDisposable
/// <summary>Registers this node (again) and returns its id.</summary>
public async Task<Guid> RegisterAsync(CancellationToken cancellationToken)
{
// Each encoder carries its own limit; the node-wide one (for servers that read only that) is the largest offered.
// Each encoder carries its own limit; the node-wide one (for servers that read only that) is the largest offered. The
// settings format the node reads keeps it from jobs it would render otherwise than asked (owner review 1, phase 4).
var encoders = Encoders;
var request = new RegisterNodeRequest(_options.ClientName, encoders, encoders.Select(e => e.MaxWidth).DefaultIfEmpty().Max(),
encoders.Select(e => e.MaxHeight).DefaultIfEmpty().Max());
encoders.Select(e => e.MaxHeight).DefaultIfEmpty().Max(), ProjectSettings.CurrentVersion);
var node = await _client.RegisterNodeAsync(request, cancellationToken).ConfigureAwait(false);
_nodeId = node.Id;
return node.Id;
@@ -137,9 +137,9 @@ internal sealed class SequenceAnalyser(ChronosDatabase db, ProcessingOptions opt
}
try
{
// The frame rate follows the user's "fit to N seconds" when one is set (BRIEF §10.3).
// The frame rate follows the user's "fit to N seconds" when one is set (BRIEF §10.3), the aspect the camera's turns.
changed = await projects.UpdateLockedAsync(paths, sequence,
settings => Advisor.Apply(settings, Advisor.Recommend(light, report, context with { TargetDurationSeconds = settings.Timing.FitToSeconds })),
settings => Advisor.Apply(settings, Advisor.Recommend(light, report, context.ForCamera(settings.Camera) with { TargetDurationSeconds = settings.Timing.FitToSeconds })),
cancellationToken).ConfigureAwait(false);
}
catch (InvalidDataException ex)
@@ -76,6 +76,12 @@ public interface IProjectHome
/// then. Null from a home that keeps none: the frames are read every time.
/// </summary>
Task<string?> FramesStampAsync(CancellationToken cancellationToken) => Task.FromResult<string?>(null);
/// <summary>
/// The highest project settings format the home stores and renders (owner review 1, phase 4); a version of a higher one
/// is not pushed to it (an older server refuses it, 422 <c>newer_format</c>). This PC's archive reads what this Chronos does.
/// </summary>
int SettingsFormat => ProjectSettings.CurrentVersion;
}
/// <summary>A sequence of this PC's archive as its projects' home: the archive's <see cref="ProjectService"/>.</summary>
+67
View File
@@ -82,6 +82,7 @@ public static class ProjectMerge
}
var merged = MergeNode(b, o, t, string.Empty, conflicts, choice) as JsonObject ?? new JsonObject();
OneHero(merged, o, t, conflicts, choice);
OneFraming(merged, b, o, t, conflicts, choice);
return new ProjectMergeResult(FromKeyed(merged), conflicts);
}
@@ -179,6 +180,72 @@ public static class ProjectMerge
other is null ? null : (theirs[PendingPath] as JsonObject)?[other]?.ToJsonString()));
}
/// <summary>The camera members that turn or mirror the view frame (owner review 1, R6).</summary>
private static readonly string[] OrientationMembers = ["rotate", "mirror", "flip"];
/// <summary>The camera members placed in the view frame (normalised there), which a turn or a mirror moves with it (<c>OrientationEdit</c>).</summary>
private static readonly string[] FramingMembers = ["crop", "keyframes", "offsetX", "offsetY", "aspect"];
private const string KeyframesMember = "keyframes";
/// <summary>
/// A turn or a mirror on one side and a framing on the other (a crop, keyframes, offsets, an aspect; keyframes of
/// photos that wait) are one value (owner review 1, phase 4): the framing was placed in a view frame the other side
/// turned, and a turn of a project without a crop changes nothing but the orientation, so member by member the merge
/// would apply a crop meant for the unturned frame to the turned one. One conflict at the orientation member the turning
/// side changed (camera.rotate, .mirror or .flip) replaces the conflicts of the framing, and the side it is settled for
/// gives the orientation and the framing together. Both sides turning are the orientation members' own conflicts.
/// </summary>
private static void OneFraming(JsonObject merged, JsonObject basis, JsonObject ours, JsonObject theirs, List<SettingsDifference> conflicts,
IReadOnlySet<string> takeTheirs)
{
var (b, o, t) = (CameraOf(basis), CameraOf(ours), CameraOf(theirs));
var oursTurned = Differs(b, o, OrientationMembers);
if (oursTurned == Differs(b, t, OrientationMembers)) return;
var (turned, framed, framedProject) = oursTurned ? (o, t, theirs) : (t, o, ours);
if (!Differs(b, framed, FramingMembers) && !PendingKeysDiffer(basis, framedProject)) return;
var member = OrientationMembers.First(m => !JsonNode.DeepEquals(b?[m], turned?[m]));
var path = "camera." + member;
conflicts.RemoveAll(c => IsFraming(c.Path));
conflicts.Add(new SettingsDifference(path, o?[member]?.ToJsonString(), t?[member]?.ToJsonString()));
var side = takeTheirs.Contains(path) ? theirs : ours;
var chosen = CameraOf(side);
if (merged["camera"] is not JsonObject camera) merged["camera"] = camera = new JsonObject();
foreach (var name in OrientationMembers.Concat(FramingMembers))
{
if (chosen?[name] is { } value) camera[name] = value.DeepClone();
else camera.Remove(name);
}
if (merged[PendingPath] is not JsonObject pending || side[PendingPath] is not JsonObject sidePending) return;
foreach (var (key, entry) in pending)
{
// An entry the chosen side does not hold keeps what the merge gave it.
if (entry is not JsonObject target || sidePending[key] is not JsonObject source) continue;
if (source[KeyframesMember] is { } keys) target[KeyframesMember] = keys.DeepClone();
else target.Remove(KeyframesMember);
}
}
private static JsonObject? CameraOf(JsonObject project) => project["camera"] as JsonObject;
private static bool Differs(JsonObject? basis, JsonObject? side, string[] members) => members.Any(m => !JsonNode.DeepEquals(basis?[m], side?[m]));
/// <summary>The keyframes of a photo that waits differ from the basis's (keyed pending frames, <see cref="Keyed"/>).</summary>
private static bool PendingKeysDiffer(JsonObject basis, JsonObject side)
{
var (b, s) = (basis[PendingPath] as JsonObject, side[PendingPath] as JsonObject);
var keys = (b?.Select(p => p.Key) ?? []).Union(s?.Select(p => p.Key) ?? []);
return keys.Any(key => !JsonNode.DeepEquals(b?[key]?[KeyframesMember], s?[key]?[KeyframesMember]));
}
/// <summary>A conflict's path among the framing members (or below them), or a waiting photo's keyframes.</summary>
private static bool IsFraming(string path) =>
FramingMembers.Any(m => Under(path, "camera." + m))
|| (path.StartsWith(PendingPath + ".", StringComparison.Ordinal) && path.Contains("." + KeyframesMember, StringComparison.Ordinal));
private static bool Under(string path, string member) =>
path == member || (path.StartsWith(member, StringComparison.Ordinal) && path.Length > member.Length && path[member.Length] == '.');
private static string? HeroOf(JsonObject project) =>
project[PendingPath] is JsonObject pending ? pending.FirstOrDefault(p => p.Value is JsonObject entry && Flag(entry, "hero")).Key : null;
@@ -27,15 +27,20 @@ public sealed class ServerProjectHome : IProjectHome
private const int MaxPage = 200;
/// <param name="serverName">The server's name as its <c>server/info</c> gives it, for the project file; the address's host when null.</param>
public ServerProjectHome(ChronosClient client, Guid sequenceId, string? serverName = null)
/// <param name="settingsFormat">The settings format its <c>server/info</c> announces (<see cref="ServerInfo.SettingsFormat"/>); null, an older server's 1.</param>
public ServerProjectHome(ChronosClient client, Guid sequenceId, string? serverName = null, int? settingsFormat = null)
{
ArgumentNullException.ThrowIfNull(client);
Client = client;
SequenceId = sequenceId;
Server = SyncService.ServerKey(client.BaseAddress);
ServerName = string.IsNullOrWhiteSpace(serverName) ? client.BaseAddress.Host : serverName.Trim();
SettingsFormat = settingsFormat is > 0 and var format ? format : ProjectSettings.BaseVersion;
}
/// <summary>The highest settings format the server reads (owner review 1, phase 4); 1 for an older server, which does not announce it.</summary>
public int SettingsFormat { get; }
public ChronosClient Client { get; }
/// <summary>The server's sequence.</summary>
+30
View File
@@ -85,8 +85,21 @@ public interface ISyncRemote : IDisposable
/// <summary>The sequence's deep-analysis report (<c>analysis.json</c>); null when it was never deep-analysed, or the remote has no such call.</summary>
Task<string?> GetAnalysisReportAsync(Guid sequenceId, CancellationToken cancellationToken) => Task.FromResult<string?>(null);
/// <summary>
/// The highest project settings format the server reads (<see cref="ServerInfo.SettingsFormat"/>; 1 for an older server,
/// which announces none). Settings that need more are never sent to it (owner review 1, phase 4): it would store them and
/// then fail every render of them. A remote that cannot say reads this Chronos's.
/// </summary>
Task<int> SettingsFormatAsync(CancellationToken cancellationToken) => Task.FromResult(Core.Project.ProjectSettings.CurrentVersion);
}
/// <summary>
/// Settings that need a newer settings format than the server reads (an older Chronos Server; owner review 1, phase 4): kept
/// on this PC, nothing sent. Its message is the sentence the sync row shows.
/// </summary>
public sealed class ServerFormatException(string message) : IOException(message);
/// <summary>Where sync jobs find their server connection.</summary>
public interface ISyncConnector
{
@@ -107,6 +120,23 @@ public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient) : I
private const int SequencePage = 500;
private const int FramePage = 1000;
/// <summary>How long the server's announced settings format is taken as it was read (an update of the server restarts it).</summary>
private static readonly TimeSpan FormatAge = TimeSpan.FromMinutes(1);
private KnownFormat? _format;
public async Task<int> SettingsFormatAsync(CancellationToken cancellationToken)
{
if (Volatile.Read(ref _format) is { } known && System.Diagnostics.Stopwatch.GetElapsedTime(known.Read) < FormatAge) return known.Format;
var info = await client.GetInfoAsync(cancellationToken).ConfigureAwait(false);
var format = info.SettingsFormat is > 0 and var announced ? announced : Core.Project.ProjectSettings.BaseVersion;
Volatile.Write(ref _format, new KnownFormat(format, System.Diagnostics.Stopwatch.GetTimestamp()));
return format;
}
/// <summary>The settings format the server announced, and when it was read (a <see cref="System.Diagnostics.Stopwatch"/> timestamp).</summary>
private sealed record KnownFormat(int Format, long Read);
public string Server { get; } = SyncService.ServerKey(client.BaseAddress);
public async Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken)
+12
View File
@@ -267,6 +267,17 @@ public static class SyncRules
}
}
/// <summary>
/// The project's "version" while both sides are of a format this Chronos writes (owner review 1, phase 4): it follows the
/// other members (format 2 only while a turn or a look is set), so it is no difference of its own; one of a newer Chronos
/// still is.
/// </summary>
private static bool Derived(string name, JsonNode? a, JsonNode? b) =>
name == "version" && FormatOf(a) <= ProjectSettings.CurrentVersion && FormatOf(b) <= ProjectSettings.CurrentVersion;
private static int FormatOf(JsonNode? value) =>
value is null ? ProjectSettings.BaseVersion : value is JsonValue v && v.TryGetValue<int>(out var format) ? format : int.MaxValue;
private static void Collect(JsonNode? a, JsonNode? b, string path, List<SettingsDifference> differences, int max)
{
if (differences.Count >= max) return;
@@ -276,6 +287,7 @@ public static class SyncRules
{
left.TryGetPropertyValue(name, out var x);
right.TryGetPropertyValue(name, out var y);
if (path.Length == 0 && Derived(name, x, y)) continue;
Collect(x, y, path.Length == 0 ? name : path + "." + name, differences, max);
if (differences.Count >= max) return;
}
+4
View File
@@ -664,6 +664,10 @@ public sealed class SyncService
{
var positions = Positions(remote, local, manifest);
if (await positions.ToServerAsync(local.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } translated) return null;
// Settings an older server cannot read (owner review 1, phase 4: a turn, a mirror, a look) stay here, the sync row
// saying why: the server would store them and then fail every render of them.
if (ProjectContent.FormatOf(translated.SettingsJson) > await remote.SettingsFormatAsync(cancellationToken).ConfigureAwait(false))
throw new ServerFormatException(Loc.L("Tooltips.Server.NeedsNewerServer"));
var frames = ProjectSettings.NamesFrames(translated.Local.SettingsJson) ? positions.ServerFrames : (int?)null;
return (SyncPayload.Of(translated.Local) with { SettingsJson = translated.SettingsJson }).ToRequest(expected, frames);
}
@@ -167,7 +167,7 @@ internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveServi
else if (named is not null) portable = version?.SettingsJson ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderVersion"));
else portable = versions.Count > 0 ? versions[^1].SettingsJson : ProjectContent.ToPortable(bundle.Project, media.Photos);
// Recorded only for the settings it holds (a version is never named for settings it did not render).
Guid? versionId = version is not null && ProjectContent.Verifies(portable, version.ContentHash) ? version.Id : null;
Guid? versionId = version is not null && ProjectContent.MatchesHash(portable, version.ContentHash) ? version.Id : null;
var settings = portable.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase) ? Place(portable, media.Photos) : portable;
var placed = ProjectStore.Parse(settings);
var excluded = placed.ExcludedFrames.ToHashSet();
@@ -217,7 +217,10 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
if (entry.SettingsHash is { Length: > 0 } hash)
{
var history = await home.HistoryAsync(projectId, null, ReplayedLookBack, ct).ConfigureAwait(false);
same = history.FirstOrDefault(v => string.Equals(v.ContentHash, hash, StringComparison.OrdinalIgnoreCase));
// Of the same content whatever its line ends: a version stored by a Windows build before every build wrote LF
// holds the CRLF text and its hash.
same = history.FirstOrDefault(v => string.Equals(v.ContentHash, hash, StringComparison.OrdinalIgnoreCase)
|| (v.SettingsJson is { Length: > 0 } text && ProjectContent.MatchesHash(text, hash)));
}
if (same is not null)
{
+40 -4
View File
@@ -68,6 +68,12 @@ public sealed record WorkspaceStatus(WorkspaceState State, bool Modified, int Ah
/// <summary>Version files after the base that cannot be read or do not follow from it (<see cref="WorkspaceState.Damaged"/>).</summary>
public int Damaged { get; init; }
/// <summary>
/// The highest settings format among the local versions not sent yet (0 when there are none): a home that reads an older
/// one (<see cref="IProjectHome.SettingsFormat"/>, an older Chronos Server) is sent none of them (owner review 1, phase 4).
/// </summary>
public int UnpushedFormat { get; init; }
}
/// <summary>What a push, pull or resolve did: the versions it stored at the home and those it took from there, and where it left the project.</summary>
@@ -112,6 +118,12 @@ public sealed record WorkspaceSession(WorkspaceProject Project, ProjectBundle Bu
public sealed class WorkspaceSyncException(PushOutcome outcome, string message) : IOException(message)
{
public PushOutcome Outcome { get; } = outcome;
/// <summary>
/// The home reads an older settings format than a version to send needs (an older Chronos Server; owner review 1, phase
/// 4): nothing was sent, the versions wait here until the home is updated.
/// </summary>
public bool HomeReadsOlderFormat { get; init; }
}
/// <summary>
@@ -286,6 +298,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var diverged = false;
var locals = Unpushed(project, bundle);
EnsureChained(project, bundle, locals);
EnsureHomeReads(home, locals, $"project {projectId}");
foreach (var local in locals)
{
var result = await home.PushAsync(projectId, local, cancellationToken).ConfigureAwait(false);
@@ -1041,6 +1054,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
private async Task<List<ProjectVersion>> SendToCopyAsync(WorkspaceProject project, IProjectHome home, SequenceProject copy, WorkspaceSaveBoth pending,
IReadOnlyList<ProjectVersion> locals, CancellationToken cancellationToken)
{
EnsureHomeReads(home, locals, $"project '{copy.Name}'");
var ids = pending.Moves.ToDictionary(m => m.LocalId, m => m.CopyVersionId);
var (parentId, parentNumber) = (pending.CopyBaseId, pending.CopyBaseNumber);
var pushed = new List<ProjectVersion>(locals.Count);
@@ -1085,6 +1099,26 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
/// <summary>The home answered a save-both's copy moved under it (<see cref="PushOutcome.Diverged"/>).</summary>
private sealed class CopyMovedException() : Exception("The copy moved at the home.");
/// <summary>
/// Nothing is sent to a home that reads an older settings format than one of <paramref name="locals"/> is written in (an
/// older Chronos Server would refuse it, IProjectHome.SettingsFormat): the push stops before the first version, so the
/// home never holds half of the chain.
/// </summary>
/// <exception cref="WorkspaceSyncException"><see cref="WorkspaceSyncException.HomeReadsOlderFormat"/>.</exception>
private static void EnsureHomeReads(IProjectHome home, IReadOnlyList<ProjectVersion> locals, string target)
{
if (FormatOf(locals) is var needed && needed <= home.SettingsFormat) return;
throw new WorkspaceSyncException(PushOutcome.NewerFormat,
$"The versions of {target} need settings format {needed}, and the home reads {home.SettingsFormat}: nothing was sent (update the server).")
{
HomeReadsOlderFormat = true,
};
}
/// <summary>The highest settings format of <paramref name="versions"/>; 0 when there are none.</summary>
private static int FormatOf(IReadOnlyList<ProjectVersion> versions) =>
versions.Count == 0 ? 0 : versions.Max(v => int.Max(v.SettingsFormat, ProjectContent.FormatOf(v.SettingsJson)));
/// <summary>A push the home refused for good: too large for a version, or refused otherwise (<see cref="WorkspaceSyncException.Outcome"/> says why).</summary>
private static WorkspaceSyncException Refused(PushOutcome outcome, ProjectVersion local, string target) => outcome switch
{
@@ -1099,7 +1133,6 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var workspace = bundle.Workspace!;
var media = project.ReadMedia();
var portable = Portable(bundle.Project, media) ?? throw MediaMissing(project.ProjectId);
var hash = ProjectContent.Hash(portable);
var versions = project.Versions();
var locals = Unpushed(versions, bundle);
// Saved after a gap, the new version would hang from the versions before it and the ones after it would be left out.
@@ -1107,7 +1140,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var (tipId, tipNumber, tipHash) = locals.Count > 0
? (locals[^1].Id, locals[^1].Number, locals[^1].ContentHash)
: (workspace.Base?.VersionId, workspace.Base?.Number ?? 0, workspace.Base?.ContentHash);
if (hash == tipHash || SameAsTip(versions, bundle, locals, portable, media)) return null;
// The tip's hash may be of the text with CRLF (saved by a Windows build before every build wrote LF).
if (ProjectContent.MatchesHash(portable, tipHash) || SameAsTip(versions, bundle, locals, portable, media)) return null;
var sync = project.ReadSync();
// A restore taken back since (Undo, Ctrl+Z) no longer shows in the working state: that version is no restore.
var restoredFrom = sync.RestoredFrom is { } restored && StillRestores(project, restored, Tip(project, bundle, locals), portable, media?.Photos ?? NoFrames)
@@ -1195,7 +1229,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
}
var tipHash = locals.Count > 0 ? locals[^1].ContentHash : workspace.Base?.ContentHash;
var modified = !bundle.IsReadOnly && (Portable(bundle.Project, media) is not { } portable
|| (ProjectContent.Hash(portable) != tipHash && !SameAsTip(versions, bundle, locals, portable, media)));
|| (!ProjectContent.MatchesHash(portable, tipHash) && !SameAsTip(versions, bundle, locals, portable, media)));
var behind = head is not null && head.Id != workspace.Base?.VersionId ? Math.Max(1, head.Number - (workspace.Base?.Number ?? 0)) : 0;
// A local commit the home stored although its answer was lost reads as behind by the commits it holds: they are ours.
if (head is not null && locals.Any(v => v.Id == head.Id)) behind = 0;
@@ -1216,6 +1250,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
{
MediaOutdated = outdated,
Damaged = damaged,
UnpushedFormat = FormatOf(locals),
};
}
@@ -1444,7 +1479,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
if (project.Versions().FirstOrDefault(v => v.Id == restoredId) is not { } restored) return true;
var then = ProjectContent.Rebind(restored.SettingsJson, photos);
var before = parent is null ? ProjectContent.ToPortable(new ProjectSettings(), photos) : ProjectContent.Rebind(parent.SettingsJson, photos);
if (then == before) return false;
// The same choices are no different, whatever line ends either was stored with (a CRLF version of an older Windows build).
if (ProjectContent.SameChoices(then, before, photos)) return false;
var now = ProjectContent.Rebind(portable, photos);
var merge = ProjectMerge.MergeWithConflicts(ProjectMerge.Read(before), ProjectMerge.Read(now), ProjectMerge.Read(then));
return merge.Conflicts.Count == 0 && ProjectContent.Canonical(merge.Merged.ToJson()) == ProjectContent.Canonical(now);