Files
Chronos/src/Titano.App/Infrastructure/SingleInstance.cs
T
Claude 2ffc0268a7 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
2026-10-12 10:29:37 +00:00

127 lines
5.3 KiB
C#

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);
}