feat(app): .titano project files that open their sequence with its settings

Setup registered .titano with Titano.exe "%1", but nothing wrote such a file
and Titano ignored the argument (BRIEF §18).

- Core ProjectBundle: versioned UTF-8 JSON ("titano-project", format 1) with
  the archive (id, name, path), the sequence (id, folder, title, frame
  count) and the project settings as project.json holds them; newer or
  foreign files are refused, frame positions apply only to the frames they
  were saved for, saving never replaces an earlier file.
- Data ProjectBundles: the file for a sequence of the index, and the sequence
  a file names (by id, else the same folder of the same archive).
- Editor: "Save project file" on the Export tab (sequences of this PC's
  archives); opening a file shows its sequence and applies the settings as
  one undo step with an Undo toast, or says in one sentence why not (not in
  the library, unreadable, a job runs).
- Titano.exe opens its file argument once the index is open and runs once
  per data folder: a later launch hands its file over a current-user named
  pipe, lets the running window come to the front and exits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 10:29:37 +00:00
1 parent 4f6bbfba5d
commit 2ffc0268a7
15 files changed
+877 -4

No files matched your search

+9
View File
@@ -184,6 +184,15 @@
<data name="Editor.Preview.Unreadable" xml:space="preserve"><value>This frame cannot be read.</value></data>
<data name="Editor.Preview.Vectors" xml:space="preserve"><value>Vectors</value></data>
<data name="Editor.Preview.Wipe" xml:space="preserve"><value>original | corrected</value></data>
<data name="Editor.ProjectFile.Applied" xml:space="preserve"><value>Project file applied</value></data>
<data name="Editor.ProjectFile.Locked" xml:space="preserve"><value>The project file’s settings were not applied.</value><comment>long</comment></data>
<data name="Editor.ProjectFile.NotFound" xml:space="preserve"><value>The sequence of this project file is not in the library.</value><comment>long</comment></data>
<data name="Editor.ProjectFile.Retry" xml:space="preserve"><value>Retry</value></data>
<data name="Editor.ProjectFile.Save" xml:space="preserve"><value>Save project file</value></data>
<data name="Editor.ProjectFile.Saved" xml:space="preserve"><value>Project file saved</value></data>
<data name="Editor.ProjectFile.Title" xml:space="preserve"><value>Project file folder</value></data>
<data name="Editor.ProjectFile.Undo" xml:space="preserve"><value>Undo</value></data>
<data name="Editor.ProjectFile.Unreadable" xml:space="preserve"><value>This file is not a Titano project or cannot be read.</value><comment>long</comment></data>
<data name="Editor.Proxies.Failed" xml:space="preserve"><value>Proxies not received</value></data>
<data name="Editor.Proxies.Fetching" xml:space="preserve"><value>Getting the proxies</value></data>
<data name="Editor.Regions.Auto" xml:space="preserve"><value>Auto</value></data>
+4
View File
@@ -210,6 +210,10 @@
<data name="Tooltips.Editor.Preview.ShotData" xml:space="preserve"><value>Show or hide the shot data</value></data>
<data name="Tooltips.Editor.Preview.Vectors" xml:space="preserve"><value>Overlay the motion to the next frame measured by the engine</value></data>
<data name="Tooltips.Editor.Preview.View" xml:space="preserve"><value>Drag the line to compare · drag to pan · wheel zooms · double-click 1:1</value></data>
<data name="Tooltips.Editor.ProjectFile.Remote" xml:space="preserve"><value>Project files are for sequences in an archive on this PC</value></data>
<data name="Tooltips.Editor.ProjectFile.Retry" xml:space="preserve"><value>Apply the project file’s settings again</value></data>
<data name="Tooltips.Editor.ProjectFile.Save" xml:space="preserve"><value>Save a .titano file that opens this sequence with these settings when double-clicked</value></data>
<data name="Tooltips.Editor.ProjectFile.Undo" xml:space="preserve"><value>Bring back the settings the sequence had before the file was opened · Ctrl+Z</value></data>
<data name="Tooltips.Editor.ReadOnly" xml:space="preserve"><value>Your account can look at this server sequence but not change it</value></data>
<data name="Tooltips.Editor.Remote" xml:space="preserve"><value>Edited with proxies on this PC; changes are saved on {0} and analyses and renders run there</value></data>
<data name="Tooltips.Editor.RemoteReadOnly" xml:space="preserve"><value>Shown from {0}; your account can look at this sequence but not change it</value></data>
+9
View File
@@ -173,6 +173,15 @@
<data name="Editor.Preview.Unreadable" xml:space="preserve"><value>Questo fotogramma non si può leggere.</value></data>
<data name="Editor.Preview.Vectors" xml:space="preserve"><value>Vettori</value></data>
<data name="Editor.Preview.Wipe" xml:space="preserve"><value>originale | corretto</value></data>
<data name="Editor.ProjectFile.Applied" xml:space="preserve"><value>File di progetto applicato</value></data>
<data name="Editor.ProjectFile.Locked" xml:space="preserve"><value>Le impostazioni del file di progetto non sono state applicate.</value><comment>long</comment></data>
<data name="Editor.ProjectFile.NotFound" xml:space="preserve"><value>La sequenza di questo file di progetto non è nella libreria.</value><comment>long</comment></data>
<data name="Editor.ProjectFile.Retry" xml:space="preserve"><value>Riprova</value></data>
<data name="Editor.ProjectFile.Save" xml:space="preserve"><value>Salva file progetto</value></data>
<data name="Editor.ProjectFile.Saved" xml:space="preserve"><value>File di progetto salvato</value></data>
<data name="Editor.ProjectFile.Title" xml:space="preserve"><value>Cartella file progetto</value></data>
<data name="Editor.ProjectFile.Undo" xml:space="preserve"><value>Annulla</value></data>
<data name="Editor.ProjectFile.Unreadable" xml:space="preserve"><value>Questo file non è un progetto Titano o non si può leggere.</value><comment>long</comment></data>
<data name="Editor.Proxies.Failed" xml:space="preserve"><value>Proxy non ricevuti</value></data>
<data name="Editor.Proxies.Fetching" xml:space="preserve"><value>Scaricamento dei proxy</value></data>
<data name="Editor.Regions.Auto" xml:space="preserve"><value>Auto</value></data>
+4
View File
@@ -210,6 +210,10 @@
<data name="Tooltips.Editor.Preview.ShotData" xml:space="preserve"><value>Mostra o nasconde i dati di scatto</value></data>
<data name="Tooltips.Editor.Preview.Vectors" xml:space="preserve"><value>Sovrappone il movimento verso il fotogramma successivo misurato dal motore</value></data>
<data name="Tooltips.Editor.Preview.View" xml:space="preserve"><value>Trascina la linea per confrontare · trascina per spostare · la rotellina ingrandisce · doppio clic 1:1</value></data>
<data name="Tooltips.Editor.ProjectFile.Remote" xml:space="preserve"><value>I file di progetto sono per le sequenze di un archivio su questo PC</value></data>
<data name="Tooltips.Editor.ProjectFile.Retry" xml:space="preserve"><value>Applica di nuovo le impostazioni del file di progetto</value></data>
<data name="Tooltips.Editor.ProjectFile.Save" xml:space="preserve"><value>Salva un file .titano che, con un doppio clic, apre questa sequenza con queste impostazioni</value></data>
<data name="Tooltips.Editor.ProjectFile.Undo" xml:space="preserve"><value>Ripristina le impostazioni che la sequenza aveva prima di aprire il file · Ctrl+Z</value></data>
<data name="Tooltips.Editor.ReadOnly" xml:space="preserve"><value>Il tuo account può vedere questa sequenza del server ma non modificarla</value></data>
<data name="Tooltips.Editor.Remote" xml:space="preserve"><value>Modificata con i proxy su questo PC; le modifiche si salvano su {0} e analisi e render vengono eseguiti lì</value></data>
<data name="Tooltips.Editor.RemoteReadOnly" xml:space="preserve"><value>Mostrata da {0}; il tuo account può vedere questa sequenza ma non modificarla</value></data>
+72 -4
View File
@@ -1,6 +1,7 @@
using System.Windows;
using System.Windows.Threading;
using Titano.App.DesignTime;
using Titano.App.Editor;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
@@ -12,11 +13,15 @@ namespace Titano.App;
/// <summary>
/// Titano desktop client. Local mode starts here: settings and language before the first window, then the window,
/// then the index and the job engine (<see cref="AppServices"/>) off the UI thread. <c>--capture &lt;dir&gt;</c>
/// renders every screen with synthetic data in a throw-away data folder and exits.
/// renders every screen with synthetic data in a throw-away data folder and exits. A file argument is a
/// <c>.titano</c> project file (Explorer passes it on a double-click) opened once the index is open. One Titano runs
/// per data folder: a second launch hands its file to the running one and exits (<see cref="SingleInstance"/>).
/// </summary>
public partial class App : Application
{
private readonly TaskCompletionSource _started = new(TaskCreationOptions.RunContinuationsAsynchronously);
private FileLogSink? _log;
private SingleInstance? _instance;
public AppEnvironment Environment { get; private set; } = null!;
public AppSettings Settings { get; private set; } = null!;
@@ -36,6 +41,19 @@ public partial class App : Application
Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log);
Log.Info("app", $"Titano {AppServices.VersionText} starting; data at {Environment.DataDirectory}");
var projectFile = capture ? null : ProjectFileArgument(e.Args);
if (!capture)
{
_instance = SingleInstance.TryAcquire(Environment.DataDirectory);
if (_instance is null)
{
var handed = SingleInstance.HandOver(Environment.DataDirectory, projectFile is null ? [] : [projectFile]);
Log.Info("app", handed ? "Titano already runs on this data folder; arguments handed over" : "Titano already runs on this data folder");
Shutdown();
return;
}
}
Settings = capture ? new AppSettings { Language = "en" } : AppSettings.Load(Environment.SettingsPath);
UiLanguage.Apply(Settings.Language);
ThemeManager.Initialize(this, capture ? AppTheme.Dark : Settings.Theme);
@@ -65,11 +83,12 @@ public partial class App : Application
return;
}
window.Show();
_ = StartAsync(shell);
_instance?.Listen(args => Dispatcher.BeginInvoke(() => OnHandOver(shell, args)));
_ = StartAsync(shell, projectFile);
}
/// <summary>Opens the index and the job engine after the window is visible, then fills the screens.</summary>
private async Task StartAsync(ShellViewModel shell)
/// <summary>Opens the index and the job engine after the window is visible, fills the screens, then opens the project file given.</summary>
private async Task StartAsync(ShellViewModel shell, string? projectFile)
{
try
{
@@ -80,10 +99,58 @@ public partial class App : Application
{
shell.ReportError(ex);
}
finally
{
_started.TrySetResult();
}
if (projectFile is not null) await OpenProjectFileAsync(shell, projectFile);
}
/// <summary>A later launch: its window comes to the front here, and its project file opens.</summary>
private void OnHandOver(ShellViewModel shell, IReadOnlyList<string> args)
{
if (MainWindow is { } window)
{
window.Show();
if (window.WindowState == WindowState.Minimized) window.WindowState = WindowState.Normal;
window.Activate();
}
if (ProjectFileArgument(args) is { } projectFile) _ = OpenProjectFileAsync(shell, projectFile);
}
/// <summary>Opens a project file once the index is open; failures become the usual one-sentence toast.</summary>
private async Task OpenProjectFileAsync(ShellViewModel shell, string path)
{
await _started.Task;
try
{
await new ProjectFiles(shell).OpenAsync(path);
}
catch (Exception ex)
{
shell.ReportError(ex);
}
}
/// <summary>The first argument that is not an option, as a full path (the hand-over crosses working folders).</summary>
private static string? ProjectFileArgument(IReadOnlyList<string> args)
{
if (args.FirstOrDefault(a => !a.StartsWith("--", StringComparison.Ordinal) && a.Length > 0) is not { } file) return null;
try
{
return System.IO.Path.GetFullPath(file);
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or System.IO.PathTooLongException)
{
Log.Warning("app", $"Ignoring argument '{file}'", ex);
return null;
}
}
public void SaveSettings()
{
// A launch that handed over to the running Titano exits before loading any settings.
if (Settings is null) return;
try
{
Settings.Save(Environment.SettingsPath);
@@ -108,6 +175,7 @@ public partial class App : Application
{
Log.Warning("app", "Services stopped with an error", ex);
}
_instance?.Dispose();
Log.Info("app", "Titano exiting");
_log?.Dispose();
if (Environment.IsCapture) Environment.DeleteCaptureData();
+3
View File
@@ -293,6 +293,9 @@
<TextBlock Text="{Binding HistoryText}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
ToolTip="{Binding HistoryText}" />
</DockPanel>
<!-- A .titano project file that opens this sequence with these settings (BRIEF §18). -->
<Button Style="{StaticResource Button.Link}" HorizontalAlignment="Left" Margin="0,8,0,0" Content="{l:Loc Editor.ProjectFile.Save}"
Command="{Binding SaveProjectCommand}" ToolTip="{Binding SaveProjectToolTip}" ToolTipService.ShowOnDisabled="True" />
<!-- This PC's settings kept by "Save both" (sync conflicts): the newest, or another from the menu, becomes the project as one undo step. -->
<v:SplitButton Margin="0,8,0,0" HorizontalAlignment="Left" Content="{Binding RestoreText}" Command="{Binding RestoreCommand}"
ItemsSource="{Binding SavedCopies}" DisplayMemberPath="Label" SelectedItem="{Binding SelectedCopy}" ToolTip="{Binding RestoreToolTip}"
+9
View File
@@ -139,6 +139,7 @@ public sealed class ExportTab : EditorTab
HistoryCommand = new RelayCommand(OpenHistory);
RevealLastCommand = new RelayCommand(() => ShellActions.Reveal(Editor.Session.Content.Renders[0].OutputPath), () => CanReveal);
_restore = new AsyncRelayCommand(RestoreAsync, () => !Editor.IsLocked && SelectedCopy is not null);
SaveProjectCommand = new AsyncRelayCommand(() => new ProjectFiles(Editor.Shell).SaveAsync(Editor.Session), () => !Editor.IsRemote);
ResetFrameRateCommand = new RelayCommand(() => EditOverrides(o => o with { FrameRate = null }));
Width = new EditableField(string.Empty, ValidateSize, v => EditOverrides(o => o with { Width = ParseSize(v) }), () => Loc.L("Tooltips.Editor.Export.Width"));
Height = new EditableField(string.Empty, ValidateSize, v => EditOverrides(o => o with { Height = ParseSize(v) }), () => Loc.L("Tooltips.Editor.Export.Height"));
@@ -178,6 +179,14 @@ public sealed class ExportTab : EditorTab
/// <summary>The newest render is a file on this PC (a server's renders stay on the server).</summary>
public bool CanReveal => Editor.Session.Content.Renders is [{ OutputPath.Length: > 0 }, ..];
/// <summary>
/// Saves a <c>.titano</c> project file of this sequence and its settings (BRIEF §18); a server sequence has no
/// archive on this PC for the file to name.
/// </summary>
public ICommand SaveProjectCommand { get; }
public string SaveProjectToolTip => Editor.IsRemote ? Loc.L("Tooltips.Editor.ProjectFile.Remote") : Loc.L("Tooltips.Editor.ProjectFile.Save");
// ---- Export "Sync" (Export.html, next to Save to) ----
/// <summary>Send each render made on this PC to the server the sequence is linked to; remembered in the project.</summary>
+92
View File
@@ -0,0 +1,92 @@
using System.IO;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Core.Project;
using Titano.Data.Processing;
namespace Titano.App.Editor;
/// <summary>
/// <c>.titano</c> project files (BRIEF §18): the editor saves one for the open sequence of this PC's archive, and
/// opening one (a double-click, which Windows passes to Titano.exe) opens its sequence in the editor and gives it the
/// file's settings as one undoable step.
/// </summary>
public sealed class ProjectFiles(ShellViewModel shell)
{
/// <summary>Asks for a folder and saves the session's sequence and current settings there; never replaces a file.</summary>
public async Task SaveAsync(EditorSession session)
{
if (session.IsRemote) return;
if (shell.Services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
if (shell.Services.Dialogs.PickFolder(Loc.L("Editor.ProjectFile.Title")) is not { } folder) return;
var bundle = await ProjectBundles.CreateAsync(db, session.Content.Sequence.Id, session.Project, session.Content.Count);
var path = await Task.Run(() =>
{
var free = ProjectBundle.FreePathIn(folder, bundle.Sequence.Title ?? session.Content.Sequence.DisplayTitle);
bundle.Save(free);
return free;
});
Log.Info("project", $"Project file '{path}' saved for sequence {bundle.Sequence.Id}");
shell.Notify(Loc.L("Editor.ProjectFile.Saved"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"),
() => ShellActions.Reveal(path));
}
/// <summary>
/// Opens the project file at <paramref name="path"/>: its sequence in the editor (found by id, else by archive and
/// folder), then the file's settings as one undo step. Says in one sentence why when the file cannot be read, its
/// sequence is not in the library, or the sequence cannot take the settings now.
/// </summary>
public async Task OpenAsync(string path)
{
ProjectBundle bundle;
try
{
bundle = await Task.Run(() => ProjectBundle.Load(path));
}
catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException)
{
Log.Warning("project", $"Project file '{path}' not opened", ex);
shell.Notify(Loc.L("Editor.ProjectFile.Unreadable"), Path.GetFileName(path), Loc.L("Common.OpenLogs"), Loc.L("Tooltips.Common.OpenLogs"),
() => ShellActions.Reveal(shell.Services.Environment.LogDirectory), isError: true);
return;
}
if (shell.Services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
if (await ProjectBundles.ResolveAsync(db, bundle) is not { } sequence)
{
Log.Info("project", $"Project file '{path}': sequence {bundle.Sequence.Id} ('{bundle.Sequence.Folder}' in archive {bundle.Archive.Id}) not in the index");
shell.Notify(Loc.L("Editor.ProjectFile.NotFound"), bundle.Sequence.Title ?? Path.GetFileName(path), Loc.L("Shell.Nav.Archive"),
Loc.L("Tooltips.Nav.Archive"), () => shell.Navigate(SectionKey.Archive), isError: true);
return;
}
// Not opened: the editor said why, or kept the open sequence's edit the user chose not to discard.
if (await shell.Sequence.ShowAsync(sequence.Id) is not { } editor) return;
Apply(editor, bundle);
}
/// <summary>Gives the open sequence the file's settings, unless the editor cannot change them now (a job runs, read-only).</summary>
private void Apply(EditorViewModel editor, ProjectBundle bundle)
{
var session = editor.Session;
var settings = bundle.ProjectFor(session.Project, session.Content.Count);
if (settings.ToJson() == session.Project.ToJson()) return;
if (editor.IsLocked)
{
shell.Notify(Loc.L("Editor.ProjectFile.Locked"), editor.LockedToolTip, Loc.L("Editor.ProjectFile.Retry"), Loc.L("Tooltips.Editor.ProjectFile.Retry"),
() =>
{
// Still the same editor: the file's settings, laid over the project as it is then.
if (ReferenceEquals(shell.Sequence.Editor, editor)) Apply(editor, bundle);
}, isError: true);
return;
}
var before = session.Project;
if (!session.Edit(_ => settings)) return;
session.EndEditRun();
var restore = new ProjectRestore(session, before, session.Project);
Log.Info("project", $"Project file settings applied to sequence {session.Content.Sequence.Id}");
shell.Notify(Loc.L("Editor.ProjectFile.Applied"), session.Content.Sequence.DisplayTitle, Loc.L("Editor.ProjectFile.Undo"),
Loc.L("Tooltips.Editor.ProjectFile.Undo"), () => restore.Undo());
}
}
@@ -0,0 +1,126 @@
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Titano.Core.Diagnostics;
namespace Titano.App.Infrastructure;
/// <summary>
/// One Titano per data folder in a Windows session (two would share one index and job engine): a named mutex marks
/// the running instance, and a later launch (a double-clicked <c>.titano</c> file, the Start menu) hands its file
/// arguments over a named pipe (current user only), lets the running window come to the front and exits. Same
/// protocol as the Uploader's, kept per program so neither depends on the other.
/// </summary>
public sealed partial class SingleInstance : IDisposable
{
private const string Header = "TITANO/1";
private const int MaxMessageBytes = 1 << 20;
private const int AnyProcess = -1;
private readonly Mutex _mutex;
private readonly string _pipeName;
private readonly CancellationTokenSource _stop = new();
private SingleInstance(Mutex mutex, string pipeName)
{
_mutex = mutex;
_pipeName = pipeName;
}
/// <summary>The instance guard for <paramref name="dataDirectory"/>, or null when another Titano already uses it in this session.</summary>
public static SingleInstance? TryAcquire(string dataDirectory)
{
var mutex = new Mutex(initiallyOwned: true, @"Local\Titano.App." + Key(dataDirectory), out var createdNew);
if (createdNew) return new SingleInstance(mutex, PipeName(dataDirectory));
mutex.Dispose();
return null;
}
/// <summary>
/// Sends <paramref name="args"/> (absolute paths; empty = just show the window) to the Titano running on
/// <paramref name="dataDirectory"/>; false when it could not be reached.
/// </summary>
public static bool HandOver(string dataDirectory, IReadOnlyList<string> args)
{
// This launch came from the user, so it may give the running window the right to come to the front.
AllowSetForegroundWindow(AnyProcess);
try
{
using var pipe = new NamedPipeClientStream(".", PipeName(dataDirectory), PipeDirection.Out, PipeOptions.CurrentUserOnly);
pipe.Connect(3000);
pipe.Write(Encode(args));
pipe.Flush();
return true;
}
catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException)
{
Log.Warning("instance", "Could not reach the running Titano", ex);
return false;
}
}
/// <summary>Receives messages from later launches; <paramref name="received"/> runs on a pool thread.</summary>
public void Listen(Action<IReadOnlyList<string>> received) => _ = ListenAsync(_pipeName, received, _stop.Token);
public void Dispose()
{
_stop.Cancel();
_mutex.ReleaseMutex();
_mutex.Dispose();
_stop.Dispose();
}
/// <summary>UTF-8: a header line, then one argument per line (paths cannot contain line breaks).</summary>
public static byte[] Encode(IReadOnlyList<string> args) =>
Encoding.UTF8.GetBytes(Header + "\n" + string.Join("\n", args.Where(a => !a.Contains('\n', StringComparison.Ordinal))));
/// <summary>Arguments of a message, or null when it is not one of ours.</summary>
public static IReadOnlyList<string>? Decode(ReadOnlySpan<byte> message)
{
if (message.Length > MaxMessageBytes) return null;
var lines = Encoding.UTF8.GetString(message).Split('\n');
if (lines[0] != Header) return null;
return [.. lines.Skip(1).Where(l => l.Length > 0)];
}
/// <summary>The data folder's identity (case-insensitive, as Windows paths are): a portable copy has its own instance.</summary>
private static string Key(string dataDirectory) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetFullPath(dataDirectory).TrimEnd('\\', '/').ToUpperInvariant())))[..16];
private static string PipeName(string dataDirectory)
{
using var process = Process.GetCurrentProcess();
return $"Titano.App.{process.SessionId}.{Environment.UserName}.{Key(dataDirectory)}";
}
private static async Task ListenAsync(string pipeName, Action<IReadOnlyList<string>> received, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await using var pipe = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
await pipe.WaitForConnectionAsync(ct).ConfigureAwait(false);
using var buffer = new MemoryStream();
await pipe.CopyToAsync(buffer, ct).ConfigureAwait(false);
if (Decode(buffer.GetBuffer().AsSpan(0, (int)buffer.Length)) is { } args) received(args);
}
catch (OperationCanceledException)
{
return;
}
catch (IOException ex)
{
Log.Warning("instance", "Hand-over pipe failed; listening again", ex);
}
}
}
[LibraryImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool AllowSetForegroundWindow(int processId);
}
@@ -75,6 +75,20 @@ public sealed class SequenceViewModel : SectionViewModel
return _switch;
}
/// <summary>
/// Shows <paramref name="sequenceId"/> in the editor, as the Library does, and returns its editor once open; null
/// when it did not open (the reason was reported, or the open sequence's unsaved edit was kept) or waits for its
/// proxies.
/// </summary>
public async Task<EditorViewModel?> ShowAsync(Guid sequenceId)
{
Shell.OpenSequence(sequenceId);
// Already chosen and shown but not open (an earlier open failed): opening it again is what is asked now.
if (_openId != sequenceId && _switch.IsCompleted) _ = OpenAsync(sequenceId);
await Settled(_switch);
return _openId == sequenceId ? Editor : null;
}
/// <summary>
/// Fetches the proxies of server sequence <paramref name="remoteId"/> into this PC's cache (a download job, shown in
/// the job bar and on the Jobs screen) and opens it in the editor once they are here, if it is still the sequence
+167
View File
@@ -0,0 +1,167 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
using Titano.Core.IO;
using Titano.Core.Naming;
namespace Titano.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>.titano</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": "titano-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 = ".titano";
public const string FormatName = "titano-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 Titano project file, damaged, or written by a newer Titano.</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 Titano 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 Titano ({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 Titano 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 Titano 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,
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 : "Titano") + Extension;
/// <summary>
/// A path in <paramref name="folder"/> for the project of <paramref name="title"/> that names no existing file
/// ("Harbour sunset.titano", then "Harbour sunset (2).titano"…): 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;
}
@@ -0,0 +1,42 @@
using Titano.Core.Model;
using Titano.Core.Project;
namespace Titano.Data.Processing;
/// <summary>
/// <c>.titano</c> project files (BRIEF §18) against this index: the file for a sequence of one of its archives, and
/// the sequence a file names.
/// </summary>
public static class ProjectBundles
{
/// <summary>
/// The project file of <paramref name="sequenceId"/> with <paramref name="project"/> (the editor's current
/// settings), whose frame positions refer to <paramref name="frames"/> frames.
/// </summary>
/// <exception cref="InvalidOperationException">The sequence is not in the index.</exception>
public static async Task<ProjectBundle> CreateAsync(TitanoDatabase db, Guid sequenceId, ProjectSettings project, int frames,
CancellationToken cancellationToken = default)
{
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new InvalidOperationException($"Sequence {sequenceId} is not in the index.");
var archive = await db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false);
return new ProjectBundle(
new BundleArchive(sequence.ArchiveId, archive?.Name ?? string.Empty, archive?.RootPath),
new BundleSequence(sequence.Id, sequence.Folder, sequence.DisplayTitle, frames),
project,
DateTimeOffset.UtcNow);
}
/// <summary>
/// The sequence <paramref name="bundle"/> names: by its id, else the sequence in the same folder of the same
/// archive (an index rebuilt elsewhere, or a folder adopted again, gives it a new id). Null when this index has
/// neither: the archive is not added here, or the sequence was deleted.
/// </summary>
public static async Task<Sequence?> ResolveAsync(TitanoDatabase db, ProjectBundle bundle, CancellationToken cancellationToken = default)
{
if (await db.Sequences.GetAsync(bundle.Sequence.Id, cancellationToken).ConfigureAwait(false) is { } byId) return byId;
var locations = await db.Sequences.ListLocationsAsync(bundle.Archive.Id, cancellationToken).ConfigureAwait(false);
var match = locations.FirstOrDefault(l => string.Equals(l.Folder, bundle.Sequence.Folder, StringComparison.OrdinalIgnoreCase));
return match is null ? null : await db.Sequences.GetAsync(match.Id, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,157 @@
using System.IO;
using System.Windows;
using Titano.App.DesignTime;
using Titano.App.Editor;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.App.Tests.Windows;
using Titano.Core.Localization;
using Titano.Core.Project;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Theming;
namespace Titano.App.Tests.Editor;
/// <summary>
/// <c>.titano</c> project files (BRIEF §18) in the real main window on the editor sample: the editor saves one, and
/// opening one shows its sequence with the file's settings as one undo step, or says in one sentence why not.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class ProjectFilesTests(TestContext context)
{
[Test]
public Task AProjectFileSavesAndOpensItsSequenceWithItsSettings() => ScreenHost.RunAsync(async () =>
{
var folder = context.CreateTempDirectory("project-files");
var environment = AppEnvironment.ForCapture();
UiLanguage.Apply("en");
ThemeManager.Apply(AppTheme.Dark);
var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new FolderDialogs(folder));
var sample = SampleData.Configure(services);
var shell = new ShellViewModel(services);
var toasts = new List<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
var window = new MainWindow(shell)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
Width = 1200,
Height = 788,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
try
{
await sample.OpenEmptyAsync();
await shell.StartAsync();
var id = await sample.FillEditorAsync();
var files = new ProjectFiles(shell);
// Saved under the sequence's title, never over an earlier file.
var editor = Assert.NotNull(await shell.Sequence.ShowAsync(id));
await files.SaveAsync(editor.Session);
await files.SaveAsync(editor.Session);
var path = Path.Combine(folder, "Harbour sunset.titano");
Assert.FileExists(path);
Assert.FileExists(Path.Combine(folder, "Harbour sunset (2).titano"));
Assert.Equal(Loc.L("Editor.ProjectFile.Saved"), toasts[^1].Title);
var bundle = ProjectBundle.Load(path);
Assert.Equal(id, bundle.Sequence.Id);
Assert.Equal(editor.FrameCount, bundle.Sequence.Frames);
Assert.Equal(editor.Session.Project.ToJson(), bundle.Project.ToJson());
// Opening it with other settings shows the sequence with them, as one step Undo takes back.
var before = editor.Session.Project;
bundle.ExposureOffset(0.7).Save(path);
await files.OpenAsync(path);
Assert.Same(editor, shell.Sequence.Editor);
Assert.Equal(0.7, editor.Session.Project.Exposure.ExposureOffsetEv);
var applied = toasts[^1];
Assert.Equal(Loc.L("Editor.ProjectFile.Applied"), applied.Title);
Assert.False(applied.IsError);
applied.ActionCommand!.Execute(null);
Assert.Equal(before.ToJson(), editor.Session.Project.ToJson());
// A sequence this library does not have, and a file that is not a project: one sentence each.
var elsewhere = bundle with
{
Archive = bundle.Archive with { Id = Guid.CreateVersion7() },
Sequence = bundle.Sequence with { Id = Guid.CreateVersion7(), Folder = "2026/elsewhere" },
};
var missing = Path.Combine(folder, "Elsewhere.titano");
elsewhere.Save(missing);
await files.OpenAsync(missing);
Assert.Equal(Loc.L("Editor.ProjectFile.NotFound"), toasts[^1].Title);
Assert.True(toasts[^1].IsError);
var text = Path.Combine(folder, "notes.titano");
await File.WriteAllTextAsync(text, "not a project");
await files.OpenAsync(text);
Assert.Equal(Loc.L("Editor.ProjectFile.Unreadable"), toasts[^1].Title);
Assert.True(toasts[^1].IsError);
Assert.Same(editor, shell.Sequence.Editor, "the open sequence stays");
await editor.Session.FlushAsync();
}
finally
{
window.Close();
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
environment.DeleteCaptureData();
}
});
[Test]
public void AHandOverMessageRoundTrips()
{
string[] args = [@"C:\Users\me\Desktop\Harbour sunset.titano"];
Assert.SequenceEqual(args, SingleInstance.Decode(SingleInstance.Encode(args))!);
Assert.Empty(SingleInstance.Decode(SingleInstance.Encode([]))!);
Assert.Null(SingleInstance.Decode("TITANO-UPLOADER/1\nE:\\"u8));
}
[Test]
public void ASecondLaunchOnTheSameDataFolderHandsItsFileToTheFirst()
{
var data = context.CreateTempDirectory("instance");
var first = Assert.NotNull(SingleInstance.TryAcquire(data));
try
{
var received = new TaskCompletionSource<IReadOnlyList<string>>(TaskCreationOptions.RunContinuationsAsynchronously);
first.Listen(args => received.TrySetResult(args));
Assert.Null(SingleInstance.TryAcquire(data), "one Titano per data folder");
using (var other = SingleInstance.TryAcquire(context.CreateTempDirectory("other-copy")))
Assert.NotNull(other, "a portable copy with its own data folder runs on its own");
Assert.True(SingleInstance.HandOver(data, [@"D:\Projects\Roof.titano"]));
Assert.True(received.Task.Wait(TimeSpan.FromSeconds(10)), "the running instance received the hand-over");
Assert.SequenceEqual([@"D:\Projects\Roof.titano"], received.Task.Result);
}
finally
{
first.Dispose();
}
}
/// <summary>Dialogs that pick one folder and cancel everything else.</summary>
private sealed class FolderDialogs(string folder) : IAppDialogs
{
public string? PickFolder(string title, string? initialFolder = null) => folder;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request) => false;
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
}
internal static class ProjectBundleTestExtensions
{
/// <summary>The same file with another exposure offset.</summary>
public static ProjectBundle ExposureOffset(this ProjectBundle bundle, double ev) =>
bundle with { Project = bundle.Project with { Exposure = bundle.Project.Exposure with { ExposureOffsetEv = ev } } };
}
@@ -0,0 +1,104 @@
using Titano.Core.Project;
using Titano.Testing;
namespace Titano.Core.Tests.Project;
/// <summary>The <c>.titano</c> project file (BRIEF §18): a sequence reference plus the settings to open it with.</summary>
public sealed class ProjectBundleTests(TestContext context)
{
private static readonly Guid ArchiveId = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
private static readonly Guid SequenceId = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a02");
[Test]
public void ARoundTripKeepsTheReferenceAndTheSettings()
{
var bundle = Sample();
var path = Path.Combine(context.CreateTempDirectory("bundle"), ProjectBundle.FileNameFor("Harbour sunset"));
bundle.Save(path);
var back = ProjectBundle.Load(path);
Assert.Equal(bundle.Archive, back.Archive);
Assert.Equal(bundle.Sequence, back.Sequence);
Assert.Equal(bundle.Saved, back.Saved);
Assert.Equal(bundle.Project.ToJson(), back.Project.ToJson());
Assert.Equal(0.8, back.Project.Exposure.DeflickerStrength.Resolve(1.0));
Assert.SequenceEqual([3, 7], back.Project.ExcludedFrames);
var json = File.ReadAllText(path);
Assert.Contains("\"format\": \"titano-project\"", json);
Assert.Contains("\"formatVersion\": 1", json);
}
[Test]
public void OtherFilesAreRefusedAsNotProjectFiles()
{
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse("not json"));
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse("[1, 2]"));
// The archive's own meta files are JSON too, but not project files.
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse("""{ "schemaVersion": 1, "id": "0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01" }"""));
var json = Sample().ToJson();
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace("\"formatVersion\": 1", "\"formatVersion\": 2", StringComparison.Ordinal)));
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace(SequenceId.ToString(), "not-a-guid", StringComparison.Ordinal)));
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace("\"version\": 1", "\"version\": 99", StringComparison.Ordinal)));
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace("\"folder\"", "\"place\"", StringComparison.Ordinal)));
}
[Test]
public void AFileTooLargeToBeAProjectIsNotRead()
{
var path = Path.Combine(context.CreateTempDirectory("bundle"), "huge.titano");
using (var stream = File.Create(path)) stream.SetLength(ProjectBundle.MaxBytes + 1L);
Assert.Throws<InvalidDataException>(() => ProjectBundle.Load(path));
}
[Test]
public void FramePositionsApplyOnlyToTheFramesTheyWereSavedFor()
{
var bundle = Sample();
var current = new ProjectSettings
{
ExcludedFrames = [1],
HeroFrame = 2,
Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 1, 0)] },
};
Assert.Same(bundle.Project, bundle.ProjectFor(current, frameCount: 3600));
var changed = bundle.ProjectFor(current, frameCount: 3610);
Assert.SequenceEqual([1], changed.ExcludedFrames);
Assert.Equal(2, changed.HeroFrame);
Assert.Same(current.Camera.Keyframes, changed.Camera.Keyframes);
// Everything else comes from the file.
Assert.Equal(0.8, changed.Exposure.DeflickerStrength.Resolve(1.0));
Assert.Equal(bundle.Project.Camera.Crop, changed.Camera.Crop);
}
[Theory]
[Case("Harbour sunset", "Harbour sunset.titano")]
[Case("Roof: 12/03 \"storm\"?", "Roof_ 12_03 _storm__.titano")]
[Case("CON", "_CON.titano")]
[Case(" ", "Titano.titano")]
public void TheFileNameComesFromTheTitle(string title, string expected) => Assert.Equal(expected, ProjectBundle.FileNameFor(title));
[Test]
public void SavingNeverReplacesAnEarlierProjectFile()
{
var folder = context.CreateTempDirectory("bundle");
Assert.Equal(Path.Combine(folder, "Harbour sunset.titano"), ProjectBundle.FreePathIn(folder, "Harbour sunset"));
File.WriteAllText(Path.Combine(folder, "Harbour sunset.titano"), "{}");
Directory.CreateDirectory(Path.Combine(folder, "Harbour sunset (2).titano"));
Assert.Equal(Path.Combine(folder, "Harbour sunset (3).titano"), ProjectBundle.FreePathIn(folder, "Harbour sunset"));
}
private static ProjectBundle Sample() => new(
new BundleArchive(ArchiveId, "Main archive", @"D:\Timelapse"),
new BundleSequence(SequenceId, "2026/2026-09-28 Harbour sunset", "Harbour sunset", 3600),
new ProjectSettings
{
Exposure = new ExposureSettings { DeflickerStrength = new Auto<double>().WithManual(0.8) },
Camera = new CameraSettings { Crop = [0.1, 0.1, 0.9, 0.9], Keyframes = [new CameraKey(120, 0.4, 0.5, 1.2, 0)] },
ExcludedFrames = [3, 7],
HeroFrame = 1800,
},
new DateTimeOffset(2026, 10, 12, 9, 30, 0, TimeSpan.Zero));
}
@@ -0,0 +1,65 @@
using Titano.Core.Project;
using Titano.Data.Processing;
using Titano.Data.Tests.Infrastructure;
using Titano.Testing;
namespace Titano.Data.Tests.Processing;
/// <summary>A <c>.titano</c> project file names a sequence of this index, found again by id or by its folder (BRIEF §18).</summary>
public abstract class ProjectBundlesTests(TestContext context) : RepositoryTest(context)
{
[Test]
public async Task TheFileNamesTheSequenceAndItsArchive()
{
var db = await OpenTitanoAsync();
var archive = TestData.Archive("Main");
await db.Archives.UpsertAsync(archive, Ct);
var sequence = TestData.Sequence(archive.Id, title: "Harbour sunset");
await db.Sequences.UpsertAsync(sequence, Ct);
var project = new ProjectSettings { ExcludedFrames = [2] };
var bundle = await ProjectBundles.CreateAsync(db, sequence.Id, project, frames: 120, Ct);
Assert.Equal(new BundleArchive(archive.Id, "Main", archive.RootPath), bundle.Archive);
Assert.Equal(new BundleSequence(sequence.Id, sequence.Folder, "Harbour sunset", 120), bundle.Sequence);
Assert.Same(project, bundle.Project);
Assert.Equal(sequence.Id, (await ProjectBundles.ResolveAsync(db, ProjectBundle.Parse(bundle.ToJson()), Ct))!.Id);
await Assert.ThrowsAsync<InvalidOperationException>(() => ProjectBundles.CreateAsync(db, Guid.CreateVersion7(), project, 0, Ct));
}
[Test]
public async Task ASequenceWithANewIdIsFoundByItsFolderInTheSameArchive()
{
var db = await OpenTitanoAsync();
var archive = TestData.Archive("Main");
var other = TestData.Archive("Other");
await db.Archives.UpsertAsync(archive, Ct);
await db.Archives.UpsertAsync(other, Ct);
var adoptedAgain = TestData.Sequence(archive.Id) with { Folder = "2026/2026-09-28 Harbour" };
var elsewhere = TestData.Sequence(other.Id) with { Folder = "2026/2026-09-28 Roof" };
await db.Sequences.UpsertAsync(adoptedAgain, Ct);
await db.Sequences.UpsertAsync(elsewhere, Ct);
var bundle = Bundle(archive.Id, Guid.CreateVersion7(), "2026/2026-09-28 HARBOUR");
Assert.Equal(adoptedAgain.Id, (await ProjectBundles.ResolveAsync(db, bundle, Ct))!.Id);
// A folder of another archive, an unknown folder or an archive this index does not have: not found.
Assert.Null(await ProjectBundles.ResolveAsync(db, Bundle(archive.Id, Guid.CreateVersion7(), "2026/2026-09-28 Roof"), Ct));
Assert.Null(await ProjectBundles.ResolveAsync(db, Bundle(archive.Id, Guid.CreateVersion7(), "2025/missing"), Ct));
Assert.Null(await ProjectBundles.ResolveAsync(db, Bundle(Guid.CreateVersion7(), Guid.CreateVersion7(), "2026/2026-09-28 Harbour"), Ct));
}
private static ProjectBundle Bundle(Guid archiveId, Guid sequenceId, string folder) =>
new(new BundleArchive(archiveId, "Main", null), new BundleSequence(sequenceId, folder, "Harbour", 10), new ProjectSettings(), TestData.Now);
}
public sealed class SqliteProjectBundlesTests(TestContext context) : ProjectBundlesTests(context)
{
protected override Backend Backend => Backend.SqliteMemory;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresProjectBundlesTests(TestContext context) : ProjectBundlesTests(context)
{
protected override Backend Backend => Backend.Postgres;
}