using System.Globalization; using System.Text; using System.Text.Json; using Chronos.Core.IO; using Chronos.Core.Naming; namespace Chronos.Core.Project; /// The archive a project file's sequence lives in: its id, and its name and folder when the file was saved. public sealed record BundleArchive(Guid Id, string Name, string? Path); /// The sequence a project file applies to: its id, folder (relative to the archive), title and frame count when saved. public sealed record BundleSequence(Guid Id, string Folder, string? Title, int Frames); /// /// A .chronos project file (BRIEF §18, file associations): which sequence of which archive, and the project /// settings to open it with. The photos stay in the archive; opening the file opens that sequence in the editor with /// these settings. UTF-8 JSON with a format name and version, so a newer file is refused rather than misread: /// { "format": "chronos-project", "formatVersion": 1, "saved": …, "archive": { "id", "name", "path" }, /// "sequence": { "id", "folder", "title", "frames" }, "project": { …project.json… } } /// public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequence, ProjectSettings Project, DateTimeOffset Saved) { public const string Extension = ".chronos"; public const string FormatName = "chronos-project"; public const int CurrentFormatVersion = 1; /// Project settings take a few kilobytes; a larger file is not a project file. public const int MaxBytes = 4 << 20; private static readonly JsonWriterOptions Indented = new() { Indented = true }; public string ToJson() { using var buffer = new MemoryStream(); using (var w = new Utf8JsonWriter(buffer, Indented)) { w.WriteStartObject(); w.WriteString("format", FormatName); w.WriteNumber("formatVersion", CurrentFormatVersion); w.WriteString("saved", Saved); w.WriteStartObject("archive"); w.WriteString("id", Archive.Id); w.WriteString("name", Archive.Name); if (Archive.Path is not null) w.WriteString("path", Archive.Path); w.WriteEndObject(); w.WriteStartObject("sequence"); w.WriteString("id", Sequence.Id); w.WriteString("folder", Sequence.Folder); if (Sequence.Title is not null) w.WriteString("title", Sequence.Title); w.WriteNumber("frames", Sequence.Frames); w.WriteEndObject(); w.WritePropertyName("project"); // The project as project.json holds it, so both are read by the same tolerant reader. using (var project = JsonDocument.Parse(Project.ToJson())) project.RootElement.WriteTo(w); w.WriteEndObject(); } return Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length); } /// Reads a project file's text. /// Not a Chronos project file, damaged, or written by a newer Chronos. public static ProjectBundle Parse(string json) { JsonDocument document; try { document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 64 }); } catch (JsonException ex) { throw new InvalidDataException("The project file is not valid JSON.", ex); } using (document) { var root = document.RootElement; if (root.ValueKind != JsonValueKind.Object || Text(root, "format") != FormatName) throw new InvalidDataException("Not a Chronos project file."); if (!root.TryGetProperty("formatVersion", out var v) || v.ValueKind != JsonValueKind.Number || !v.TryGetInt32(out var version) || version < 1) throw new InvalidDataException("The project file has no valid format version."); if (version > CurrentFormatVersion) throw new InvalidDataException($"The project file uses format {version}, newer than this Chronos ({CurrentFormatVersion})."); var archive = Section(root, "archive"); var sequence = Section(root, "sequence"); var folder = Text(sequence, "folder"); if (string.IsNullOrWhiteSpace(folder)) throw new InvalidDataException("The project file names no sequence folder."); var frames = sequence.TryGetProperty("frames", out var f) && f.ValueKind == JsonValueKind.Number && f.TryGetInt32(out var count) && count >= 0 ? count : 0; if (!root.TryGetProperty("project", out var project) || project.ValueKind != JsonValueKind.Object) throw new InvalidDataException("The project file holds no project settings."); ProjectSettings settings; try { settings = ProjectSettings.FromJson(project.GetRawText()); } catch (JsonException ex) { throw new InvalidDataException("The project settings in the file cannot be read.", ex); } var saved = root.TryGetProperty("saved", out var s) && s.ValueKind == JsonValueKind.String && s.TryGetDateTimeOffset(out var when) ? when : default; return new ProjectBundle( new BundleArchive(Id(archive), Text(archive, "name") ?? string.Empty, Text(archive, "path")), new BundleSequence(Id(sequence), folder, Text(sequence, "title"), frames), settings, saved); } } /// Reads a project file. /// Not a Chronos project file (or too large to be one), damaged, or newer. /// The file cannot be read. public static ProjectBundle Load(string path) { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); if (stream.Length > MaxBytes) throw new InvalidDataException("The file is too large to be a Chronos project file."); using var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true); return Parse(reader.ReadToEnd()); } /// Writes the file atomically (temp, flush, rename): an interrupted save never leaves half a file. public void Save(string path) => AtomicFile.WriteAllText(path, ToJson()); /// /// The settings to give the sequence when the file is opened, the sequence having /// frames and settings: the file's settings, except the frame positions (exclusions, /// hero frame, camera keyframes) when frames were added or removed since the file was saved, as they would now /// point at other frames; the sequence keeps its own. /// public ProjectSettings ProjectFor(ProjectSettings current, int frameCount) => frameCount == Sequence.Frames ? Project : Project with { ExcludedFrames = current.ExcludedFrames, HeroFrame = current.HeroFrame, PendingFrames = current.PendingFrames, Camera = Project.Camera with { Keyframes = current.Camera.Keyframes }, }; /// A file name for the project of a sequence titled , valid on every file system. public static string FileNameFor(string title) => (PathTemplate.SanitizeSegment(title) is { Length: > 0 } name ? name : "Chronos") + Extension; /// /// A path in for the project of that names no existing file /// ("Harbour sunset.chronos", then "Harbour sunset (2).chronos"…): saving never replaces an earlier project file. /// public static string FreePathIn(string folder, string title) { var name = Path.GetFileNameWithoutExtension(FileNameFor(title)); var path = Path.Combine(folder, name + Extension); for (var n = 2; File.Exists(path) || Directory.Exists(path); n++) path = Path.Combine(folder, string.Create(CultureInfo.InvariantCulture, $"{name} ({n}){Extension}")); return path; } private static JsonElement Section(JsonElement root, string name) { if (!root.TryGetProperty(name, out var section) || section.ValueKind != JsonValueKind.Object) throw new InvalidDataException($"The project file has no '{name}' section."); return section; } private static Guid Id(JsonElement section) => section.TryGetProperty("id", out var id) && id.ValueKind == JsonValueKind.String && id.TryGetGuid(out var guid) && guid != Guid.Empty ? guid : throw new InvalidDataException("The project file has a missing or invalid id."); private static string? Text(JsonElement section, string name) => section.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; }