using System.Text;
namespace Febe.Desktop.Core;
///
/// «Avvia Febe all'accensione del computer» (spec §12): a value under HKCU\Software\Microsoft\Windows\CurrentVersion\Run,
/// per user, no administrator rights. Febe then starts with --nascosto: only the icon in the notification area,
/// the window stays closed. Each Febe has its own value: Febe for the usual one (Data folder recorded or
/// default), Febe-… with --dati for one started on a Data folder of its own (a second account), so the
/// switch of one never starts, shows or removes the other.
///
public static class Autostart
{
/// The registry key, under HKEY_CURRENT_USER.
public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
/// The name of the value of the usual Febe.
public const string ValueName = "Febe";
///
/// The name of the value: without a Data folder of its own, otherwise «Febe-» and the
/// identity of the folder (the same as the single-instance guard, so the same folder always has the same value).
///
public static string ValueNameFor(string? fixedDataFolder) =>
fixedDataFolder is null ? ValueName : InstanceIdentity.For(fixedDataFolder);
///
/// The command written in the value: the quoted executable, --nascosto and, for a Febe started with
/// --dati, the same Data folder.
///
public static string Command(string executable, string? fixedDataFolder = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(executable);
if (executable.Contains('"', StringComparison.Ordinal))
{
throw new ArgumentException("Percorso dell'eseguibile non valido.", nameof(executable));
}
if (fixedDataFolder is null)
{
return $"\"{executable}\" --nascosto";
}
if (string.IsNullOrWhiteSpace(fixedDataFolder) || fixedDataFolder.Contains('"', StringComparison.Ordinal))
{
throw new ArgumentException("Percorso della cartella dei dati non valido.", nameof(fixedDataFolder));
}
return $"\"{executable}\" --nascosto --dati {Quote(fixedDataFolder)}";
}
///
/// True when starts this executable on this Data folder:
/// for a Febe started with --dati, none for the usual one. A value left by another copy of Febe, or written
/// for another Data folder, is not ours.
///
public static bool PointsTo(string? value, string executable, string? fixedDataFolder = null)
{
if (string.IsNullOrWhiteSpace(value) || string.IsNullOrWhiteSpace(executable))
{
return false;
}
var arguments = Split(value.Trim());
if (arguments is not [var target, .. var rest] || !SamePath(target, executable))
{
return false;
}
string? dataFolder = null;
for (var i = 0; i < rest.Count; i++)
{
if (string.Equals(rest[i], "--dati", StringComparison.OrdinalIgnoreCase))
{
if (i + 1 >= rest.Count)
{
return false;
}
dataFolder = rest[++i];
}
}
return fixedDataFolder is null ? dataFolder is null : dataFolder is not null && SamePath(dataFolder, fixedDataFolder);
}
///
/// The words of a command line as Windows programs read them: blanks separate, quotes group, backslashes are plain
/// except before a quote (2n backslashes and a quote: n backslashes and a quote that groups; 2n+1: n and a literal
/// quote). Null for an unfinished quote.
///
internal static List? Split(string commandLine)
{
var words = new List();
var word = new StringBuilder();
var inWord = false;
var quoted = false;
for (var i = 0; i < commandLine.Length; i++)
{
var c = commandLine[i];
if (c == '\\')
{
var start = i;
while (i < commandLine.Length && commandLine[i] == '\\')
{
i++;
}
var count = i - start;
if (i < commandLine.Length && commandLine[i] == '"')
{
word.Append('\\', count / 2);
if (count % 2 == 1)
{
word.Append('"');
}
else
{
quoted = !quoted;
}
}
else
{
word.Append('\\', count);
i--;
}
inWord = true;
continue;
}
if (c == '"')
{
quoted = !quoted;
inWord = true;
continue;
}
if (!quoted && char.IsWhiteSpace(c))
{
if (inWord)
{
words.Add(word.ToString());
word.Clear();
inWord = false;
}
continue;
}
word.Append(c);
inWord = true;
}
if (quoted)
{
return null;
}
if (inWord)
{
words.Add(word.ToString());
}
return words;
}
/// A quoted argument: backslashes before the closing quote are doubled ("D:\\" reads back as D:\).
private static string Quote(string argument)
{
var trailing = argument.Length - argument.TrimEnd('\\').Length;
return "\"" + argument + new string('\\', trailing) + "\"";
}
private static bool SamePath(string a, string b) =>
string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase);
private static string Normalize(string path)
{
try
{
return Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return path;
}
}
}