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:
15 files changed
+877
-4
No files matched your search
@@ -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 <dir></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();
|
||||
|
||||
@@ -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}"
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user