using System.Globalization; using System.Text; using Chronos.Core.Archiving; namespace Chronos.Core.Naming; /// A parse problem in a template, with the character position for live validation in the UI. public sealed record TemplateError(int Position, string Code, string? Token); /// /// Folder/file naming templates (BRIEF §7.1). Tokens are written as {name} or {name:format}, where the /// format is passed to the .NET formatter (e.g. {n:0000}, {date:yyyyMMdd}). {{ and }} are literal /// braces. Characters that are illegal in Windows/Linux file names are replaced, never passed through. /// public sealed class PathTemplate { /// Every token the templates understand. Descriptions are localized resources Import.Token.<name>. public static readonly IReadOnlyList Tokens = [ "year", "month", "day", "date", "time", "hm", "session", "sessionstart", "camera", "lens", "iso", "shutter", "aperture", "n", "nsession", "name", "ext", "title", ]; /// The longest text gives: the longest title a sequence takes. public const int MaxTextLength = 200; /// The longest folder level or file name a template gives (), before an appended extension. public const int MaxSegmentLength = 200; private static readonly HashSet TokenSet = new(Tokens, StringComparer.OrdinalIgnoreCase); private static readonly char[] Illegal = ['<', '>', ':', '"', '|', '?', '*', '\\', '/', '\0']; private static readonly HashSet ReservedNames = new(StringComparer.OrdinalIgnoreCase) { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", }; private readonly List _parts; private PathTemplate(string source, List parts, IReadOnlyList errors) { Source = source; _parts = parts; Errors = errors; } public string Source { get; } /// Problems found while parsing; a template with errors still expands best-effort. public IReadOnlyList Errors { get; } public bool IsValid => Errors.Count == 0; /// Whether the template holds (title for {title}), whatever its case or format. public bool Uses(string token) => _parts.Any(p => p.IsToken && string.Equals(p.Text, token, StringComparison.OrdinalIgnoreCase)); /// Parses a template; '/' separates folder levels (only meaningful for folder templates). public static PathTemplate Parse(string template) { ArgumentNullException.ThrowIfNull(template); var parts = new List(); var errors = new List(); var literal = new StringBuilder(); for (var i = 0; i < template.Length; i++) { var c = template[i]; if (c == '{') { if (i + 1 < template.Length && template[i + 1] == '{') { literal.Append('{'); i++; continue; } var close = template.IndexOf('}', i + 1); if (close < 0) { errors.Add(new TemplateError(i, "UnclosedBrace", null)); literal.Append(template, i, template.Length - i); break; } if (literal.Length > 0) { parts.Add(Part.Literal(literal.ToString())); literal.Clear(); } var body = template[(i + 1)..close]; var colon = body.IndexOf(':', StringComparison.Ordinal); var name = (colon < 0 ? body : body[..colon]).Trim(); var format = colon < 0 ? null : body[(colon + 1)..]; if (name.Length == 0) errors.Add(new TemplateError(i, "EmptyToken", null)); else if (!TokenSet.Contains(name)) errors.Add(new TemplateError(i, "UnknownToken", name)); parts.Add(Part.Token(name.ToLowerInvariant(), format)); i = close; } else if (c == '}') { if (i + 1 < template.Length && template[i + 1] == '}') { literal.Append('}'); i++; continue; } errors.Add(new TemplateError(i, "UnopenedBrace", null)); } else { literal.Append(c); } } if (literal.Length > 0) parts.Add(Part.Literal(literal.ToString())); if (template.Trim().Length == 0) errors.Add(new TemplateError(0, "Empty", null)); return new PathTemplate(template, parts, errors); } /// /// Expands to a relative folder path (forward slashes; each segment sanitized). A level archive scans never enter /// (), which a token value such as a title can give, gets a leading _, so every /// sequence filed or moved by a template stays where a scan finds it. /// public string ExpandFolder(NamingContext context) => string.Join('/', Levels(context).Select(s => IsHiddenFolder(s) ? "_" + s : s)); /// Whether a level of the folder this template gives for is one scans never enter, before it is escaped. public bool WritesHiddenFolder(NamingContext context) => Levels(context).Any(IsHiddenFolder); /// /// A folder name archive scans never enter (): one that starts with a dot, or a folder /// the layout keeps for itself (.chronos, originals, proxies, exports), whatever its case. /// public static bool IsHiddenFolder(string name) { ArgumentNullException.ThrowIfNull(name); return name.StartsWith('.') || ArchiveLayout.IsReservedFolder(name); } private IEnumerable Levels(NamingContext context) => Expand(context, allowSeparators: true).Split('/', StringSplitOptions.RemoveEmptyEntries).Select(SanitizeSegment).Where(s => s.Length > 0); /// /// Expands to a file name; the original extension is appended unless the template already ends with {ext}. A name /// longer than is shortened before the .{ext} the template ends with, never through it. /// public string ExpandFile(NamingContext context) { var hasExt = _parts.Count > 0 && _parts[^1] is { IsToken: true, Text: "ext" }; var name = Clean(Expand(context, allowSeparators: false)); var ext = hasExt && context.Extension.Length > 0 ? "." + context.Extension : string.Empty; name = ext.Length > 0 && name.Length > MaxSegmentLength && name.EndsWith(ext, StringComparison.Ordinal) ? Shorten(name[..^ext.Length], MaxSegmentLength - ext.Length) + ext : Shorten(name, MaxSegmentLength); if (name.Length == 0) name = SanitizeSegment(context.OriginalName); if (!hasExt && context.Extension.Length > 0) name += "." + context.Extension; return name; } /// /// Whether every file name the template gives ends with the photo's own extension: the template does not end with /// {ext} (the extension is appended), or ends with .{ext}, which a long name keeps whole /// (). {n}{ext} would drop the dot, and with it the extension every reader of the photo goes by. /// public bool KeepsExtension => _parts is not [.., { IsToken: true, Text: "ext" }] || _parts is [.., { IsToken: false, Text: var before }, { IsToken: true, Text: "ext" }] && before.EndsWith('.'); /// /// Expands to plain text, such as a sequence title: the literals and the token values as they are, since a title may hold /// characters a file name cannot (Paris: night), control characters as spaces, trimmed, no extension; at most /// characters. /// public string ExpandText(NamingContext context) { var text = new StringBuilder(Expand(context, allowSeparators: false, raw: true)); for (var i = 0; i < text.Length; i++) { if (char.IsControl(text[i])) text[i] = ' '; } return Shorten(text.ToString().Trim(), MaxTextLength); } /// At most characters of , a character outside the basic plane never cut in two, trailing spaces trimmed. private static string Shorten(string s, int max) { if (s.Length <= max) return s; var cut = char.IsHighSurrogate(s[max - 1]) ? max - 1 : max; return s[..cut].TrimEnd(); } /// Token values as they are: text, not a path. private string Expand(NamingContext c, bool allowSeparators, bool raw = false) { var inv = CultureInfo.InvariantCulture; var sb = new StringBuilder(); foreach (var part in _parts) { if (!part.IsToken) { sb.Append(allowSeparators ? part.Text.Replace('\\', '/') : part.Text); continue; } var f = part.Format; var value = part.Text switch { "year" => c.CapturedAt.ToString(f ?? "yyyy", inv), "month" => c.CapturedAt.ToString(f ?? "MM", inv), "day" => c.CapturedAt.ToString(f ?? "dd", inv), "date" => c.CapturedAt.ToString(f ?? "yyyy-MM-dd", inv), "time" => c.CapturedAt.ToString(f ?? "HH-mm-ss", inv), "hm" => c.CapturedAt.ToString(f ?? "HH-mm", inv), "sessionstart" => c.SessionStart.ToString(f ?? "yyyy-MM-dd HH-mm", inv), "session" => c.Session.ToString(f ?? "0", inv), "n" => c.Number.ToString(f ?? "0000", inv), "nsession" => c.NumberInSession.ToString(f ?? "0000", inv), "camera" => CameraName(c.CameraMake, c.CameraModel), "lens" => c.Lens ?? string.Empty, "iso" => c.Iso?.ToString(f ?? "0", inv) ?? string.Empty, "shutter" => Shutter(c.ExposureTime), "aperture" => c.FNumber is { } fn ? "f" + fn.ToString(f ?? "0.#", inv) : string.Empty, "name" => c.OriginalName, "ext" => c.Extension, "title" => c.Title ?? string.Empty, _ => string.Empty, }; // Token values never introduce folder levels. sb.Append(raw ? value : value.Replace('/', '-').Replace('\\', '-')); } return sb.ToString(); } /// "Canon EOS R5" from make "Canon" + model "Canon EOS R5"; avoids the duplicated brand most cameras report. public static string CameraName(string? make, string? model) { make = make?.Trim(); model = model?.Trim(); if (string.IsNullOrEmpty(model)) return make ?? string.Empty; if (string.IsNullOrEmpty(make)) return model; var brand = make.Split(' ', StringSplitOptions.RemoveEmptyEntries)[0]; if (brand.Equals("NIKON", StringComparison.OrdinalIgnoreCase)) brand = "Nikon"; if (model.StartsWith(brand, StringComparison.OrdinalIgnoreCase)) return brand + model[brand.Length..]; return brand + " " + model; } /// 1/250 s → "1-250", 2 s → "2s" (file-name safe). public static string Shutter(double? seconds) { if (seconds is not > 0) return string.Empty; var t = seconds.Value; if (t >= 0.3) return t.ToString("0.#", CultureInfo.InvariantCulture) + "s"; return "1-" + Math.Round(1 / t).ToString(CultureInfo.InvariantCulture); } /// /// Replaces characters that are illegal on Windows or Linux and fixes reserved names and trailing dots/spaces; at most /// characters. /// public static string SanitizeSegment(string segment) => Shorten(Clean(segment), MaxSegmentLength); /// without its length limit. private static string Clean(string segment) { var sb = new StringBuilder(segment.Length); foreach (var ch in segment) { if (ch < 32 || Array.IndexOf(Illegal, ch) >= 0) sb.Append('_'); else sb.Append(ch); } var s = sb.ToString().Trim().TrimEnd('.'); while (s.Contains(" ", StringComparison.Ordinal)) s = s.Replace(" ", " ", StringComparison.Ordinal); var stem = s.Split('.')[0]; if (ReservedNames.Contains(stem)) s = "_" + s; if (s is "." or "..") s = "_"; return s; } private readonly record struct Part(bool IsToken, string Text, string? Format) { public static Part Literal(string text) => new(false, text, null); public static Part Token(string name, string? format) => new(true, name, format); } }