diff --git a/src/Titano.App/App.xaml.cs b/src/Titano.App/App.xaml.cs
index 842cc69b..52a7fee7 100644
--- a/src/Titano.App/App.xaml.cs
+++ b/src/Titano.App/App.xaml.cs
@@ -15,13 +15,18 @@ namespace Titano.App;
/// then the index and the job engine () off the UI thread. --capture <dir>
/// renders every screen with synthetic data in a throw-away data folder and exits. A file argument is a
/// .titano 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 ().
+/// per data folder: a second launch hands its file to the running one and exits, or, when the running one is closing,
+/// waits for it to exit and starts with the file ().
///
public partial class App : Application
{
+ /// How long a launch waits for a Titano that is closing (it gives its services up to 10 s to stop).
+ private static readonly TimeSpan ClosingWait = TimeSpan.FromSeconds(30);
+
private readonly TaskCompletionSource _started = new(TaskCreationOptions.RunContinuationsAsynchronously);
private FileLogSink? _log;
private SingleInstance? _instance;
+ private bool _windowClosed;
public AppEnvironment Environment { get; private set; } = null!;
public AppSettings Settings { get; private set; } = null!;
@@ -47,11 +52,24 @@ public partial class App : Application
_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;
+ if (SingleInstance.HandOver(Environment.DataDirectory, projectFile is null ? [] : [projectFile]))
+ {
+ Log.Info("app", "Titano already runs on this data folder; arguments handed over");
+ Shutdown();
+ return;
+ }
+ // No answer: the running Titano is closing (it stops listening first). Start once it has exited.
+ _instance = SingleInstance.WaitForTurn(Environment.DataDirectory, ClosingWait);
+ if (_instance is null)
+ {
+ Log.Info("app", "Titano already runs on this data folder and did not answer");
+ Shutdown();
+ return;
+ }
+ Log.Info("app", "The previous Titano on this data folder has exited");
}
+ // From now on: a launch while the window and the index open is kept until the shell can take it.
+ _instance.Listen();
}
Settings = capture ? new AppSettings { Language = "en" } : AppSettings.Load(Environment.SettingsPath);
@@ -82,8 +100,14 @@ public partial class App : Application
_ = ScreenCapture.RunAsync(window, shell, sample!, dir);
return;
}
+ // Closing the main window ends Titano: later launches wait for it instead of handing over a file it cannot open.
+ window.Closed += (_, _) =>
+ {
+ _windowClosed = true;
+ _instance?.StopListening();
+ };
window.Show();
- _instance?.Listen(args => Dispatcher.BeginInvoke(() => OnHandOver(shell, args)));
+ _instance?.Receive(args => Dispatcher.BeginInvoke(() => OnHandOver(shell, args)));
_ = StartAsync(shell, projectFile);
}
@@ -109,6 +133,11 @@ public partial class App : Application
/// A later launch: its window comes to the front here, and its project file opens.
private void OnHandOver(ShellViewModel shell, IReadOnlyList args)
{
+ if (_windowClosed)
+ {
+ Log.Warning("app", "A launch arrived while Titano was closing; its arguments are ignored");
+ return;
+ }
if (MainWindow is { } window)
{
window.Show();
@@ -163,6 +192,8 @@ public partial class App : Application
protected override void OnExit(ExitEventArgs e)
{
+ // The mutex stays until the services have stopped, so a launch now waits for this one to exit.
+ _instance?.StopListening();
SaveSettings();
if (MainWindow?.DataContext is ShellViewModel shell) shell.Dispose();
try
diff --git a/src/Titano.App/Infrastructure/SingleInstance.cs b/src/Titano.App/Infrastructure/SingleInstance.cs
index c689c60b..29e7dcf2 100644
--- a/src/Titano.App/Infrastructure/SingleInstance.cs
+++ b/src/Titano.App/Infrastructure/SingleInstance.cs
@@ -11,8 +11,10 @@ namespace Titano.App.Infrastructure;
///
/// 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 .titano 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.
+/// arguments over a named pipe (current user only), lets the running window come to the front and exits. The running
+/// instance listens from the moment it holds the mutex, keeping what arrives until its window can take it, and stops
+/// listening as soon as it starts closing; a launch that gets no answer waits for it to exit and starts in its place.
+/// Same protocol as the Uploader's, kept per program so neither depends on the other.
///
public sealed partial class SingleInstance : IDisposable
{
@@ -23,6 +25,11 @@ public sealed partial class SingleInstance : IDisposable
private readonly Mutex _mutex;
private readonly string _pipeName;
private readonly CancellationTokenSource _stop = new();
+ private readonly Lock _gate = new();
+ private readonly Queue> _waiting = new();
+ private Action>? _received;
+ private Task? _listening;
+ private bool _disposed;
private SingleInstance(Mutex mutex, string pipeName)
{
@@ -30,15 +37,59 @@ public sealed partial class SingleInstance : IDisposable
_pipeName = pipeName;
}
- /// The instance guard for , or null when another Titano already uses it in this session.
+ ///
+ /// The instance guard for , or null when another Titano already uses it in this
+ /// session (also one running with administrator rights, whose mutex this launch may not even open).
+ ///
public static SingleInstance? TryAcquire(string dataDirectory)
{
- var mutex = new Mutex(initiallyOwned: true, @"Local\Titano.App." + Key(dataDirectory), out var createdNew);
+ Mutex mutex;
+ bool createdNew;
+ try
+ {
+ mutex = new Mutex(initiallyOwned: true, MutexName(dataDirectory), out createdNew);
+ }
+ catch (UnauthorizedAccessException ex)
+ {
+ Log.Info("instance", $"Titano runs with administrator rights on this data folder: {ex.Message}");
+ return null;
+ }
if (createdNew) return new SingleInstance(mutex, PipeName(dataDirectory));
mutex.Dispose();
return null;
}
+ ///
+ /// Waits up to for the Titano running on to exit (while
+ /// it closes it no longer answers hand-overs), then becomes the running instance; null when it still runs, or runs
+ /// with administrator rights.
+ ///
+ public static SingleInstance? WaitForTurn(string dataDirectory, TimeSpan timeout)
+ {
+ Mutex mutex;
+ try
+ {
+ mutex = new Mutex(initiallyOwned: false, MutexName(dataDirectory));
+ }
+ catch (UnauthorizedAccessException ex)
+ {
+ Log.Info("instance", $"Titano runs with administrator rights on this data folder: {ex.Message}");
+ return null;
+ }
+ try
+ {
+ if (mutex.WaitOne(timeout)) return new SingleInstance(mutex, PipeName(dataDirectory));
+ }
+ catch (AbandonedMutexException)
+ {
+ // The other Titano ended without releasing it (it crashed): this thread owns it now.
+ Log.Warning("instance", "The previous Titano ended without closing");
+ return new SingleInstance(mutex, PipeName(dataDirectory));
+ }
+ mutex.Dispose();
+ return null;
+ }
+
///
/// Sends (absolute paths; empty = just show the window) to the Titano running on
/// ; false when it could not be reached.
@@ -62,12 +113,61 @@ public sealed partial class SingleInstance : IDisposable
}
}
- /// Receives messages from later launches; runs on a pool thread.
- public void Listen(Action> received) => _ = ListenAsync(_pipeName, received, _stop.Token);
+ /// Starts receiving messages from later launches; they wait until names who takes them.
+ public void Listen()
+ {
+ lock (_gate)
+ {
+ if (_listening is not null || _disposed) return;
+ _listening = ListenAsync(_pipeName, OnMessage, _stop.Token);
+ }
+ }
+
+ ///
+ /// Hands the messages received so far, then each later one, to , in order; it runs on a
+ /// pool thread.
+ ///
+ public void Receive(Action> received)
+ {
+ lock (_gate)
+ {
+ _received = received;
+ while (_waiting.TryDequeue(out var args)) received(args);
+ }
+ }
+
+ ///
+ /// Stops answering later launches while keeping the mutex: from now on they wait for this instance to exit instead
+ /// of handing over arguments it could no longer open.
+ ///
+ public void StopListening()
+ {
+ Task? listening;
+ lock (_gate)
+ {
+ if (_disposed) return;
+ _stop.Cancel();
+ listening = _listening;
+ }
+ // The pipe closes as the loop ends (cancellation ends it quietly).
+ try
+ {
+ listening?.Wait(TimeSpan.FromSeconds(2));
+ }
+ catch (AggregateException ex)
+ {
+ Log.Warning("instance", "Hand-over listener ended with an error", ex);
+ }
+ }
public void Dispose()
{
- _stop.Cancel();
+ StopListening();
+ lock (_gate)
+ {
+ if (_disposed) return;
+ _disposed = true;
+ }
_mutex.ReleaseMutex();
_mutex.Dispose();
_stop.Dispose();
@@ -86,10 +186,21 @@ public sealed partial class SingleInstance : IDisposable
return [.. lines.Skip(1).Where(l => l.Length > 0)];
}
+ private void OnMessage(IReadOnlyList args)
+ {
+ lock (_gate)
+ {
+ if (_received is null) _waiting.Enqueue(args);
+ else _received(args);
+ }
+ }
+
/// The data folder's identity (case-insensitive, as Windows paths are): a portable copy has its own instance.
private static string Key(string dataDirectory) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetFullPath(dataDirectory).TrimEnd('\\', '/').ToUpperInvariant())))[..16];
+ private static string MutexName(string dataDirectory) => @"Local\Titano.App." + Key(dataDirectory);
+
private static string PipeName(string dataDirectory)
{
using var process = Process.GetCurrentProcess();
@@ -113,9 +224,24 @@ public sealed partial class SingleInstance : IDisposable
{
return;
}
+ catch (UnauthorizedAccessException ex)
+ {
+ // The pipe name belongs to a Titano running with administrator rights: later launches wait instead.
+ Log.Warning("instance", "Hand-over pipe not available", ex);
+ return;
+ }
catch (IOException ex)
{
+ // A pipe of the same name still held by a Titano that is exiting, or a broken connection: try again shortly.
Log.Warning("instance", "Hand-over pipe failed; listening again", ex);
+ try
+ {
+ await Task.Delay(TimeSpan.FromSeconds(1), ct).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ return;
+ }
}
}
}
diff --git a/tests/Titano.App.Tests/Editor/ProjectFilesTests.cs b/tests/Titano.App.Tests/Editor/ProjectFilesTests.cs
index b6d32728..098c017f 100644
--- a/tests/Titano.App.Tests/Editor/ProjectFilesTests.cs
+++ b/tests/Titano.App.Tests/Editor/ProjectFilesTests.cs
@@ -123,15 +123,25 @@ public sealed class ProjectFilesTests(TestContext context)
var first = Assert.NotNull(SingleInstance.TryAcquire(data));
try
{
- var received = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously);
- first.Listen(args => received.TrySetResult(args));
+ first.Listen();
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");
+ // Launches while the first one is still opening its window are kept until the window takes them. The pipe
+ // takes one launch at a time, so once the second hand-over is through, the first one is already waiting.
+ Assert.True(SingleInstance.HandOver(data, [@"D:\Projects\Early.titano"]));
+ Assert.True(SingleInstance.HandOver(data, []));
+ using var received = new System.Collections.Concurrent.BlockingCollection>();
+ first.Receive(received.Add);
+ Assert.True(received.TryTake(out var early, TimeSpan.FromSeconds(10)), "the hand-over that came first is delivered");
+ Assert.SequenceEqual([@"D:\Projects\Early.titano"], early!);
+ Assert.True(received.TryTake(out var show, TimeSpan.FromSeconds(10)), "then the plain launch");
+ Assert.Empty(show!);
+
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);
+ Assert.True(received.TryTake(out var later, TimeSpan.FromSeconds(10)), "the running instance received the hand-over");
+ Assert.SequenceEqual([@"D:\Projects\Roof.titano"], later!);
}
finally
{
@@ -139,6 +149,46 @@ public sealed class ProjectFilesTests(TestContext context)
}
}
+ [Test]
+ public void ALaunchWhileTitanoClosesWaitsForItAndStartsInItsPlace()
+ {
+ var data = context.CreateTempDirectory("closing");
+ var first = Assert.NotNull(SingleInstance.TryAcquire(data));
+ first.Listen();
+ first.Receive(_ => { });
+ // Closing: it no longer answers, but it still holds the data folder until its services have stopped.
+ first.StopListening();
+ Assert.False(SingleInstance.HandOver(data, [@"D:\Projects\Roof.titano"]), "a closing Titano takes no file it could not open");
+ Assert.Null(SingleInstance.TryAcquire(data));
+
+ // The next launch waits (the mutex belongs to a thread, so it waits on its own) and gets its turn once the first exits.
+ var next = Task.Run(() =>
+ {
+ using var instance = SingleInstance.WaitForTurn(data, TimeSpan.FromSeconds(20));
+ return instance is not null;
+ });
+ Assert.False(next.Wait(TimeSpan.FromMilliseconds(300)), "it waits while the first one still runs");
+ first.Dispose();
+ Assert.True(next.Wait(TimeSpan.FromSeconds(20)) && next.Result, "it starts once the first one has exited");
+
+ // Nobody exits in time: the launch gives up.
+ var holder = Assert.NotNull(SingleInstance.TryAcquire(data));
+ try
+ {
+ Assert.False(Task.Run(() => SingleInstance.WaitForTurn(data, TimeSpan.FromMilliseconds(200)) is { } got && Dispose(got)).Result);
+ }
+ finally
+ {
+ holder.Dispose();
+ }
+
+ static bool Dispose(SingleInstance instance)
+ {
+ instance.Dispose();
+ return true;
+ }
+ }
+
/// Dialogs that pick one folder and cancel everything else.
private sealed class FolderDialogs(string folder) : IAppDialogs
{