Files
Chronos/src/Chronos.Core/Project/ProjectBundle.cs
T
Alby96andClaude Opus 5.5 f2b58522b9
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
refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
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>
2026-10-23 12:45:18 +02:00

169 lines
8.9 KiB
C#

using System.Globalization;
using System.Text;
using System.Text.Json;
using Chronos.Core.IO;
using Chronos.Core.Naming;
namespace Chronos.Core.Project;
/// <summary>The archive a project file's sequence lives in: its id, and its name and folder when the file was saved.</summary>
public sealed record BundleArchive(Guid Id, string Name, string? Path);
/// <summary>The sequence a project file applies to: its id, folder (relative to the archive), title and frame count when saved.</summary>
public sealed record BundleSequence(Guid Id, string Folder, string? Title, int Frames);
/// <summary>
/// A <c>.chronos</c> 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:
/// <code>{ "format": "chronos-project", "formatVersion": 1, "saved": …, "archive": { "id", "name", "path" },
/// "sequence": { "id", "folder", "title", "frames" }, "project": { …project.json… } }</code>
/// </summary>
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;
/// <summary>Project settings take a few kilobytes; a larger file is not a project file.</summary>
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);
}
/// <summary>Reads a project file's text.</summary>
/// <exception cref="InvalidDataException">Not a Chronos project file, damaged, or written by a newer Chronos.</exception>
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);
}
}
/// <summary>Reads a project file.</summary>
/// <exception cref="InvalidDataException">Not a Chronos project file (or too large to be one), damaged, or newer.</exception>
/// <exception cref="IOException">The file cannot be read.</exception>
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());
}
/// <summary>Writes the file atomically (temp, flush, rename): an interrupted save never leaves half a file.</summary>
public void Save(string path) => AtomicFile.WriteAllText(path, ToJson());
/// <summary>
/// The settings to give the sequence when the file is opened, the sequence having <paramref name="frameCount"/>
/// frames and <paramref name="current"/> 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.
/// </summary>
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 },
};
/// <summary>A file name for the project of a sequence titled <paramref name="title"/>, valid on every file system.</summary>
public static string FileNameFor(string title) =>
(PathTemplate.SanitizeSegment(title) is { Length: > 0 } name ? name : "Chronos") + Extension;
/// <summary>
/// A path in <paramref name="folder"/> for the project of <paramref name="title"/> that names no existing file
/// ("Harbour sunset.chronos", then "Harbour sunset (2).chronos"…): saving never replaces an earlier project file.
/// </summary>
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;
}