using System.Security.Cryptography; using System.Text; namespace Febe.Desktop.Core; /// /// One Febe at a time for a Data folder (spec §12, rule 4): the names of the mutex and of the pipe through which a /// second launch asks the first one to show its window. Derived from the Data folder, so that a second account with /// folders of its own (spec §3) is a second instance; the same folder is the same instance whatever the case of its /// letters. /// public static class InstanceIdentity { /// A short stable name for a Data folder: «Febe-» and 16 hexadecimal digits of SHA-256 of its full path. public static string For(string dataFolder) { ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder); var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(dataFolder)).ToUpperInvariant(); var hash = SHA256.HashData(Encoding.UTF8.GetBytes(full)); return "Febe-" + Convert.ToHexString(hash, 0, 8).ToLowerInvariant(); } /// The named mutex, in the session namespace (one per logged-in user). public static string MutexName(string dataFolder) => @"Local\" + For(dataFolder); /// The named pipe of the first instance (current user only). public static string PipeName(string dataFolder) => For(dataFolder); } /// /// Takes the single-instance guard of a Data folder (on Windows the named mutex and pipe of ) /// for this Febe; null when another Febe already holds it. Disposing the guard gives it back. /// public delegate IDisposable? InstanceGuardFactory(string dataFolder); /// What a second launch asks the running Febe. public enum InstanceRequest { /// Show the window (a normal launch: Start menu, desktop shortcut). Show, /// Nothing visible (a start with the computer while Febe already runs). StayHidden, } /// /// The one-line messages between two launches of Febe, over a pipe that only the current user can open. A message /// carries no path and no secret; anything else than the two known lines is ignored. /// public static class InstanceMessages { private const string Prefix = "FEBE1 "; /// The longest message read (anything longer is not one of ours). public const int MaxLength = 64; /// The message a second launch with these options sends. public static string For(DesktopOptions options) { ArgumentNullException.ThrowIfNull(options); return Format(options.StartHidden ? InstanceRequest.StayHidden : InstanceRequest.Show); } public static string Format(InstanceRequest request) => Prefix + (request == InstanceRequest.StayHidden ? "nascosto" : "mostra"); /// The request in a message; null for anything that is not one of ours. public static InstanceRequest? Parse(string? message) { if (message is null || message.Length > MaxLength) { return null; } return message.Trim() switch { "FEBE1 mostra" => InstanceRequest.Show, "FEBE1 nascosto" => InstanceRequest.StayHidden, _ => null, }; } }