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; /// /// 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. /// 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; } /// The instance guard for , or null when another Titano already uses it in this session. 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; } /// /// Sends (absolute paths; empty = just show the window) to the Titano running on /// ; false when it could not be reached. /// public static bool HandOver(string dataDirectory, IReadOnlyList 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; } } /// Receives messages from later launches; runs on a pool thread. public void Listen(Action> received) => _ = ListenAsync(_pipeName, received, _stop.Token); public void Dispose() { _stop.Cancel(); _mutex.ReleaseMutex(); _mutex.Dispose(); _stop.Dispose(); } /// UTF-8: a header line, then one argument per line (paths cannot contain line breaks). public static byte[] Encode(IReadOnlyList args) => Encoding.UTF8.GetBytes(Header + "\n" + string.Join("\n", args.Where(a => !a.Contains('\n', StringComparison.Ordinal)))); /// Arguments of a message, or null when it is not one of ours. public static IReadOnlyList? Decode(ReadOnlySpan 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)]; } /// 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 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> 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); }