using System.Text.Json; using System.Text.Json.Nodes; using Chronos.Core.Project; using Chronos.Testing; namespace Chronos.Core.Tests.Project; /// The portable form of project versions (owner review 2, R8): positions parked by photo, canonical text, a stable hash. public sealed class ProjectContentTests { private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0); private static FramePhoto Photo(int n, bool hashed = true) => new(hashed ? n.ToString("x64", System.Globalization.CultureInfo.InvariantCulture) : null, 1000 + n, Start.AddSeconds(10 * n)); private static FramePhotos Frames(params FramePhoto[] photos) => new(photos.Select((p, i) => (i, p))); private static ProjectSettings Positions(int[] excluded, int? hero, int keyframe) => new() { ExcludedFrames = excluded, HeroFrame = hero, Camera = new CameraSettings { Keyframes = [new CameraKey(keyframe, 0.4, 0.5, 1.2, 0)] }, Exposure = new ExposureSettings { ExposureOffsetEv = 0.5 }, }; [Test] public void ThePortableFormParksEveryPositionByPhotoAndPlacesThemBack() { var frames = Frames(Photo(1), Photo(2), Photo(3), Photo(4), Photo(5)); var settings = Positions([1, 3], 2, 0); var portable = ProjectContent.ToPortable(settings, frames); var parked = ProjectSettings.FromJson(portable); Assert.Empty(parked.ExcludedFrames); Assert.Null(parked.HeroFrame); Assert.Empty(parked.Camera.Keyframes); Assert.Equal(4, parked.PendingFrames!.Count); Assert.Equal(0.5, parked.Exposure.ExposureOffsetEv); var placed = ProjectSettings.FromJson(ProjectContent.Place(portable, frames)); Assert.SequenceEqual([1, 3], placed.ExcludedFrames); Assert.Equal(2, placed.HeroFrame); Assert.Equal(0, Assert.NotNull(placed.Camera.Keyframes.SingleOrDefault()).Frame); Assert.Null(placed.PendingFrames); } [Test] public void PositionsFollowTheirPhotosAcrossInsertionsAndRemovals() { var before = Frames(Photo(1), Photo(2), Photo(3), Photo(4)); var portable = ProjectContent.ToPortable(Positions([1, 3], 2, 0), before); // Two photos inserted before the others, and photo 4 removed: each position names its photo, the one on 4 waits. var after = Frames(Photo(10), Photo(11), Photo(1), Photo(2), Photo(3)); var placed = ProjectSettings.FromJson(ProjectContent.Place(portable, after)); Assert.SequenceEqual([3], placed.ExcludedFrames); Assert.Equal(4, placed.HeroFrame); Assert.Equal(2, placed.Camera.Keyframes.Single().Frame); var waiting = Assert.NotNull(placed.PendingFrames).Single(); Assert.True(waiting.Excluded && waiting.Photo.Matches(Photo(4))); // Photo 4 back: the exclusion takes its place again. var back = ProjectSettings.FromJson(ProjectContent.Place(placed.ToJson(), Frames(Photo(10), Photo(11), Photo(1), Photo(2), Photo(3), Photo(4)))); Assert.SequenceEqual([3, 5], back.ExcludedFrames); Assert.Null(back.PendingFrames); } [Test] public void ACopyOfAPhotoHeldTwiceKeepsItsOwnPosition() { var frames = Frames(Photo(1), Photo(2), Photo(2), Photo(3)); var portable = ProjectContent.ToPortable(new ProjectSettings { ExcludedFrames = [2] }, frames); Assert.Equal(1, ProjectSettings.FromJson(portable).PendingFrames!.Single().Occurrence); var inserted = Frames(Photo(0), Photo(1), Photo(2), Photo(2), Photo(3)); Assert.SequenceEqual([3], ProjectSettings.FromJson(ProjectContent.Place(portable, inserted)).ExcludedFrames); } [Test] public void PhotosNotHashedYetAreMatchedBySizeAndCaptureTime() { var unhashed = Frames(Photo(1, hashed: false), Photo(2, hashed: false), Photo(3, hashed: false)); var portable = ProjectContent.ToPortable(new ProjectSettings { ExcludedFrames = [1] }, unhashed); var parked = ProjectSettings.FromJson(portable).PendingFrames!.Single(); Assert.Null(parked.Sha256); Assert.Equal(Photo(2).Size, parked.Size); // The same photos hashed since, with one inserted before them. var hashed = Frames(Photo(9), Photo(1), Photo(2), Photo(3)); Assert.SequenceEqual([2], ProjectSettings.FromJson(ProjectContent.Place(portable, hashed)).ExcludedFrames); } [Test] public void APhotoParkedOnAnotherEncodingFindsTheFrameHoldingItsReplacement() { // Owner review 2, R7: a conversion replaced photo 2 by 20 and a later one 20 by 21; the undo of another gave 3 back for 30. PhotoAlias[] links = [new(Photo(20).Sha256!, Photo(21).Sha256!), new(Photo(2).Sha256!.ToUpperInvariant(), Photo(20).Sha256!), new(Photo(30).Sha256!, Photo(3).Sha256!)]; var converted = new FramePhotos([(0, Photo(1)), (1, Photo(21)), (2, Photo(3))], links); var portable = ProjectContent.ToPortable(new ProjectSettings { ExcludedFrames = [1], HeroFrame = 2 }, Frames(Photo(1), Photo(2), Photo(30))); var placed = ProjectSettings.FromJson(ProjectContent.Place(portable, converted)); Assert.SequenceEqual([1], placed.ExcludedFrames); Assert.Equal(2, placed.HeroFrame); Assert.Null(placed.PendingFrames); // The links joined in any order, either way: every encoding is the same frame. var reversed = new FramePhotos([(0, Photo(1)), (1, Photo(21)), (2, Photo(3))], links.Reverse().Select(l => new PhotoAlias(l.Replacement, l.Sha256))); foreach (var photos in new[] { converted, reversed }) Assert.SequenceEqual(new int?[] { 1, 1, 1, 2, 2 }, new[] { Photo(2), Photo(20), Photo(21), Photo(3), Photo(30) }.Select(p => photos.IndexOf(p))); Assert.Null(converted.IndexOf(Photo(4))); // Without the links the photos are not there: the positions wait for them. var waiting = ProjectSettings.FromJson(ProjectContent.Place(portable, Frames(Photo(1), Photo(21), Photo(3)))); Assert.Null(waiting.HeroFrame); Assert.Equal(2, waiting.PendingFrames!.Count); } [Test] public void ChoicesSavedOnPhotosAsTheyWereReadAsTheSameOnceRenamed() { // Saved while photo 1 was not hashed and photo 2 not converted yet; since, 1 was hashed and 2 converted into 20. var before = Frames(Photo(1, hashed: false), Photo(2), Photo(3)); var now = new FramePhotos([(0, Photo(1)), (1, Photo(20)), (2, Photo(3))], [new PhotoAlias(Photo(2).Sha256!, Photo(20).Sha256!)]); var saved = ProjectContent.ToPortable(new ProjectSettings { ExcludedFrames = [0, 1] }, before); var current = ProjectContent.ToPortable(new ProjectSettings { ExcludedFrames = [0, 1] }, now); Assert.NotEqual(saved, current); Assert.Equal(current, ProjectContent.Rebind(saved, now)); Assert.True(ProjectContent.SameChoices(saved, current, now)); Assert.False(ProjectContent.SameChoices(saved, ProjectContent.ToPortable(new ProjectSettings { ExcludedFrames = [1] }, now), now)); // Named as the frames hold them already, or held by no frame: the text as it is. Assert.Equal(current, ProjectContent.Rebind(current, now)); Assert.Equal(saved, ProjectContent.Rebind(saved, Frames(Photo(7)))); Assert.False(ProjectContent.SameChoices(saved, current, Frames(Photo(7)))); // A newer Chronos's settings are its own to rename. var newer = """{ "version": 3, "pendingFrames": [ { "size": 1001, "capturedAt": "2026-09-28T18:00:10", "excluded": true } ] }"""; Assert.Equal(newer, ProjectContent.Rebind(newer, now)); } [Test] public void ChoicesSavedWhereAPhotoWasHashedReadAsTheSameOnFramesCopiedBeforeIt() { // A workspace copied photo 1 before its home hashed it; a version the home made since names it by its SHA-256. var copied = Frames(Photo(1, hashed: false), Photo(2), Photo(3)); var home = Frames(Photo(1), Photo(2), Photo(3)); var choices = new ProjectSettings { ExcludedFrames = [0], Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.3, 0.5, 1.2, 0)] } }; var atHome = ProjectContent.ToPortable(choices, home); var here = ProjectContent.ToPortable(choices, copied); Assert.NotEqual(atHome, here); // The same choices on the frames held here: no change to show or to save as a version. Assert.True(ProjectContent.SameChoices(atHome, here, copied)); Assert.True(ProjectContent.SameChoices(here, atHome, copied)); // What is kept keeps the hash the frames do not know yet; a choice of its own still differs. Assert.Equal(atHome, ProjectContent.Rebind(atHome, copied)); Assert.False(ProjectContent.SameChoices(atHome, ProjectContent.ToPortable(new ProjectSettings { ExcludedFrames = [1] }, copied), copied)); Assert.False(ProjectContent.SameChoices(atHome, ProjectContent.ToPortable(choices with { ExcludedFrames = [] }, copied), copied)); // A photo none of the frames holds is compared as it is named. var gone = ProjectContent.ToPortable(choices, Frames(Photo(4))); Assert.False(ProjectContent.SameChoices(gone, ProjectContent.ToPortable(choices, Frames(Photo(4, hashed: false))), copied)); } [Test] public void APhotoOfABurstToldApartByItsOrderKeepsItsPositionOnceHashed() { // A RAW burst of one size without sub-second times: three photos alike but for their SHA-256, told apart by their // order while not hashed (frames 1 to 3); and a photo held twice, two copies of one file (frames 4 and 5). FramePhoto Burst(int n, bool hashed) => new(hashed ? (500 + n).ToString("x64", System.Globalization.CultureInfo.InvariantCulture) : null, 25_000_000, Start); FramePhotos Copy(bool hashed) => new([(0, Photo(1)), (1, Burst(0, hashed)), (2, Burst(1, hashed)), (3, Burst(2, hashed)), (4, Photo(2)), (5, Photo(2))]); var (before, after) = (Copy(hashed: false), Copy(hashed: true)); var choices = new ProjectSettings { ExcludedFrames = [3, 5], HeroFrame = 2, Camera = new CameraSettings { Keyframes = [new CameraKey(1, 0.3, 0.5, 1.2, 0)] } }; var saved = ProjectContent.ToPortable(choices, before); Assert.SequenceEqual([0, 1, 1, 2], ProjectSettings.FromJson(saved).PendingFrames!.Select(p => p.Occurrence).Order()); // Hashed since: each photo of the burst is the only one of its SHA-256, the copy of the photo held twice still the second. var rebound = ProjectContent.Rebind(saved, after); var named = ProjectSettings.FromJson(rebound).PendingFrames!; Assert.True(named.All(p => p.Sha256 is not null)); Assert.SequenceEqual([0, 0, 0, 1], named.Select(p => p.Occurrence).Order()); Assert.Equal(ProjectContent.ToPortable(choices, after), rebound); Assert.True(ProjectContent.SameChoices(saved, ProjectContent.ToPortable(choices, after), after)); var placed = ProjectSettings.FromJson(ProjectContent.Place(rebound, after)); Assert.SequenceEqual([3, 5], placed.ExcludedFrames); Assert.Equal((int?)2, placed.HeroFrame); Assert.Equal(1, placed.Camera.Keyframes.Single().Frame); Assert.Null(placed.PendingFrames); } [Test] public void EntriesOfOnePhotoSavedUnderTwoNamesBecomeOneWithThePositionsOfBoth() { // Photo 2 was converted into 20 (owner review 2, R7). A version holds an exclusion parked on the old encoding, and a hero, a // keyframe and a newer Chronos's rating parked on the new one: each copy named the photo as it held it. var rating = JsonSerializer.SerializeToElement(4); var split = new ProjectSettings { PendingFrames = [ new PendingFrame { Sha256 = Photo(2).Sha256, Size = Photo(2).Size, CapturedAt = Photo(2).CapturedAt, Excluded = true }, new PendingFrame { Sha256 = Photo(20).Sha256, Size = Photo(20).Size, CapturedAt = Photo(2).CapturedAt, Hero = true, Keyframes = [new CameraKey(0, 0.8, 0.5, 1.2, 0)], Extra = new Dictionary { ["rating"] = rating }, }, ], }; var text = ProjectContent.Canonical(split.ToJson()); var now = new FramePhotos([(0, Photo(1)), (1, Photo(20)), (2, Photo(3))], [new PhotoAlias(Photo(2).Sha256!, Photo(20).Sha256!)]); var rebound = ProjectContent.Rebind(text, now); var entry = Assert.NotNull(ProjectSettings.FromJson(rebound).PendingFrames).Single(); Assert.Equal(Photo(20).Sha256, entry.Sha256); Assert.True(entry.Excluded && entry.Hero); Assert.Equal(0.8, entry.Keyframes.Single().CenterX); Assert.Equal(4, entry.Extra!["rating"].GetInt32()); // The same choices as the version made where the frames hold the new encoding. Assert.True(ProjectContent.SameChoices(text, rebound, now)); var placed = ProjectSettings.FromJson(ProjectContent.Place(rebound, now)); Assert.SequenceEqual([1], placed.ExcludedFrames); Assert.Equal((int?)1, placed.HeroFrame); Assert.Equal(1, placed.Camera.Keyframes.Single().Frame); // Two entries already named alike are one too. var twice = ProjectContent.Canonical((split with { PendingFrames = [.. split.PendingFrames!.Select(p => p with { Sha256 = Photo(20).Sha256 })] }).ToJson()); Assert.Equal(rebound, ProjectContent.Rebind(twice, now)); } [Test] public void MembersOfANewerChronosSurviveInsideParametersKeyframesAndCurvePoints() { var waiting = Photo(9).Sha256; var json = $$""" { "version": 1, "timing": { "remapCurve": [ { "x": 0, "y": 0, "handle": 0.25 }, { "x": 1, "y": 1 } ] }, "exposure": { "deflicker": { "isAuto": true, "hasAdvice": true, "autoValue": true, "confidence": 0.8 } }, "camera": { "keyframes": [ { "frame": 1, "centerX": 0.4, "centerY": 0.5, "zoom": 1.2, "rotation": 0, "tilt": 3 } ] }, "pendingFrames": [ { "sha256": "{{waiting}}", "size": 1009, "keyframes": [ { "frame": 0, "centerX": 0.2, "centerY": 0.5, "zoom": 1, "rotation": 0, "tilt": 5 } ] } ] } """; var settings = ProjectSettings.FromJson(json); Assert.Equal(0.8, settings.Exposure.Deflicker.Extra!["confidence"].GetDouble()); Assert.Equal(3, settings.Camera.Keyframes.Single().Extra!["tilt"].GetInt32()); Assert.Equal(0.25, settings.Timing.RemapCurve[0].Extra!["handle"].GetDouble()); // An edit of the parameter or the keyframe keeps them too. Assert.Equal(0.8, settings.Exposure.Deflicker.WithManual(false).Extra!["confidence"].GetDouble()); Assert.Equal(3, (settings.Camera.Keyframes[0] with { Zoom = 2 }).Extra!["tilt"].GetInt32()); var frames = Frames(Photo(1), Photo(2), Photo(3)); var portable = ProjectContent.ToPortable(json, frames); var placed = ProjectContent.Place(portable, frames); foreach (var text in new[] { settings.ToJson(), portable, placed, ProjectContent.Canonical(portable), ProjectContent.Rebind(portable, frames) }) { var node = JsonNode.Parse(text)!; Assert.Equal(0.8, node["exposure"]!["deflicker"]!["confidence"]!.GetValue()); Assert.Equal(0.25, node["timing"]!["remapCurve"]![0]!["handle"]!.GetValue()); var waits = node["pendingFrames"]!.AsArray().Single(p => p!["sha256"]!.GetValue() == waiting)!; Assert.Equal(5, waits["keyframes"]![0]!["tilt"]!.GetValue()); } // The keyframe's member goes where the keyframe goes: parked with its photo, then placed again. var parked = JsonNode.Parse(portable)!["pendingFrames"]!.AsArray().Single(p => p!["sha256"]!.GetValue() == Photo(2).Sha256)!; Assert.Equal(3, parked["keyframes"]![0]!["tilt"]!.GetValue()); Assert.Equal(3, JsonNode.Parse(placed)!["camera"]!["keyframes"]![0]!["tilt"]!.GetValue()); Assert.Equal(portable, ProjectContent.ToPortable(placed, frames)); } [Test] public void AWaitingPhotoKeepsANewerChronosMembersOnceItsPositionsArePlaced() { var frames = Frames(Photo(1), Photo(2), Photo(3)); var portable = ProjectContent.Canonical($$"""{ "pendingFrames": [ { "sha256": "{{Photo(2).Sha256}}", "size": {{Photo(2).Size}}, "excluded": true, "rating": 5 } ] }"""); var placed = ProjectSettings.FromJson(ProjectContent.Place(portable, frames)); Assert.SequenceEqual([1], placed.ExcludedFrames); var kept = Assert.NotNull(placed.PendingFrames).Single(); Assert.False(kept.Excluded || kept.Hero || kept.Keyframes.Count > 0); Assert.Equal(5, kept.Extra!["rating"].GetInt32()); // Parked again, the rating is still the photo's: the same text as before. Assert.Equal(portable, ProjectContent.ToPortable(placed, frames)); // Nothing more to place: the settings stay as they are. Assert.Equal(placed.ToJson(), ProjectContent.Place(placed.ToJson(), frames)); } [Test] public void TheSameSettingsGiveTheSameTextAndHashWhateverTheFrames() { var before = Frames(Photo(1), Photo(2), Photo(3)); var after = Frames(Photo(7), Photo(1), Photo(2), Photo(3)); var first = ProjectContent.ToPortable(Positions([0, 2], 1, 2), before); // The same choices made against frames with one inserted before them: every position one further. var second = ProjectContent.ToPortable(Positions([1, 3], 2, 3), after); Assert.Equal(first, second); Assert.Equal(ProjectContent.Hash(first), ProjectContent.Hash(second)); Assert.Equal(64, ProjectContent.Hash(first).Length); Assert.True(ProjectContent.Verifies(first, ProjectContent.Hash(first).ToUpperInvariant())); Assert.False(ProjectContent.Verifies(first + " ", ProjectContent.Hash(first))); // Pending frames listed in another order, or written by hand with other spacing, read as the same text. var parked = ProjectSettings.FromJson(first); var shuffled = parked with { PendingFrames = [.. parked.PendingFrames!.Reverse()] }; Assert.Equal(first, ProjectContent.Canonical(shuffled.ToJson())); Assert.Equal(first, ProjectContent.Canonical(JsonNode.Parse(first)!.ToJsonString())); Assert.Equal(first, ProjectContent.ToPortable(first, after)); } [Test] public void MembersOfANewerChronosSurviveEveryRoundTrip() { const string json = """ { "version": 1, "filters": { "lut": "teal-orange", "strength": 0.4 }, "exposure": { "exposureOffsetEv": 0.25, "toneCurve": [0, 0.5, 1] }, "camera": { "aspect": { "isAuto": false, "manual": "9:16" }, "lensProfile": "rf-15-35" }, "pendingFrames": [ { "sha256": "abc", "size": 10, "excluded": true, "rating": 5 } ] } """; var settings = ProjectSettings.FromJson(json); Assert.Equal(0.25, settings.Exposure.ExposureOffsetEv); var written = JsonNode.Parse(settings.ToJson())!; Assert.Equal("teal-orange", written["filters"]!["lut"]!.GetValue()); Assert.Equal(3, written["exposure"]!["toneCurve"]!.AsArray().Count); Assert.Equal("rf-15-35", written["camera"]!["lensProfile"]!.GetValue()); Assert.Equal(5, written["pendingFrames"]![0]!["rating"]!.GetValue()); var portable = ProjectContent.ToPortable(json, Frames(Photo(1))); Assert.Contains("teal-orange", portable); Assert.Contains("lensProfile", ProjectContent.Place(portable, Frames(Photo(1)))); Assert.Equal(portable, ProjectContent.Canonical(ProjectSettings.FromJson(portable).ToJson())); } [Test] public void SettingsOfANewerFormatAreReadOnlyAndKeptAsTheyAre() { var newer = """{ "version": 3, "excludedFrames": [1], "exposure": { "exposureOffsetEv": 1.5 }, "grade": { "look": "film" } }"""; Assert.Throws(() => ProjectSettings.FromJson(newer)); var read = ProjectSettings.FromJson(newer, allowNewer: true); Assert.True(read.IsNewerFormat); Assert.Equal(1.5, read.Exposure.ExposureOffsetEv); Assert.Equal(3, ProjectContent.FormatOf(newer)); Assert.Equal(1, ProjectContent.FormatOf("""{ "exposure": {} }""")); // Its positions are a newer Chronos's to translate: only the text is made canonical. var portable = ProjectContent.ToPortable(newer, Frames(Photo(1), Photo(2))); Assert.SequenceEqual([1], ProjectSettings.FromJson(portable, allowNewer: true).ExcludedFrames); Assert.Contains("film", portable); Assert.Equal(portable, ProjectContent.Place(portable, Frames(Photo(2)))); } [Test] public void TextThatIsNoProjectIsRefused() { Assert.Throws(() => ProjectContent.ToPortable("not json", Frames(Photo(1)))); Assert.Throws(() => ProjectContent.Canonical("[1, 2]")); } }