using System.Text.RegularExpressions; using System.Xml.Linq; using Febe.Tests.Desktop.Support; using Febe.Tests.Web.Support; using Febe.Web.Hosting; namespace Febe.Tests.Web; /// /// Font and icons are Febe's own (decision of 18 November 2026): the system's font, icons drawn in house, no font /// file, no third-party icon set and no reference to the ones used before. /// [TestClass] public sealed partial class InHouseAssetsTests { private const string IconNamespace = "http://www.w3.org/2000/svg"; private static readonly HashSet Shapes = ["path", "line", "polyline", "polygon", "circle", "ellipse", "rect"]; private static readonly HashSet Geometry = ["d", "points", "x", "y", "width", "height", "rx", "ry", "cx", "cy", "r", "x1", "y1", "x2", "y2", "stroke-dasharray", "stroke-dashoffset"]; private static readonly HashSet TextExtensions = [".cs", ".js", ".mjs", ".css", ".html", ".htm", ".json", ".hjson", ".md", ".txt", ".svg", ".xml", ".csproj", ".props", ".targets", ".slnx", ".sh", ".ps1", ".yml", ".yaml", ".nsi", ".config", ".manifest"]; private static readonly HashSet FontExtensions = [".woff", ".woff2", ".ttf", ".otf", ".eot"]; [TestMethod] public void TheInterfaceShipsNoFontFileNoLicenceOfThirdPartyAssetsAndUsesTheSystemFont() { var files = new EmbeddedWwwroot(); foreach (var path in files.Files) { Assert.IsFalse(FontExtensions.Contains(Path.GetExtension(path).ToLowerInvariant()), $"file di caratteri nel programma: {path}"); Assert.IsFalse(Path.GetFileName(path).StartsWith("LICENZA", StringComparison.OrdinalIgnoreCase), $"licenza di terzi nel programma: {path}"); Assert.IsFalse(path.StartsWith("caratteri/", StringComparison.Ordinal), path); } var css = files.ReadText("css/febe.css")!; Assert.DoesNotContain("@font-face", css); Assert.DoesNotContain("url(../caratteri", css); StringAssert.Contains(css, "font-family:var(--carattere)"); var stack = CharacterToken().Match(css); Assert.IsTrue(stack.Success, "il token --carattere c'è"); var families = stack.Groups[1].Value.Split(',', StringSplitOptions.TrimEntries); Assert.AreEqual("system-ui", families[0], "prima il carattere del sistema"); Assert.AreEqual("sans-serif", families[^1], "e in fondo il generico"); // Exactly the stack of the specification (appendix B, «pila dei caratteri di sistema»), nothing more: no name of a // font the Docker image leaves out (Liberation). var specification = File.ReadAllText(Febe.Tests.Desktop.Support.Repository.PathOf("docs", "SPECIFICA.md")); var stated = SpecificationStack().Match(specification); Assert.IsTrue(stated.Success, "la pila dell'appendice B"); Assert.AreEqual(stated.Groups[1].Value, stack.Groups[1].Value.Trim()); Assert.DoesNotContain("Liberation", css); foreach (var page in new[] { "index.html", "accesso.html" }) { var html = files.ReadText(page)!; Assert.DoesNotContain("as=\"font\"", html, page); Assert.DoesNotContain("/caratteri/", html, page); } } [TestMethod] public async Task ThePagesForbidDownloadedFonts() { await using var server = await WebTestServer.StartAsync(); using var response = await server.Client.GetAsync("/"); var policy = string.Join(' ', response.Headers.GetValues("Content-Security-Policy")); StringAssert.Contains(policy, "font-src 'none'"); } [TestMethod] public void EveryIconIsAPlainStrokeDrawingOnTheGridOfTwentyFour() { var files = new EmbeddedWwwroot(); var icons = files.Files.Where(f => f.StartsWith("icone/", StringComparison.Ordinal)).Order(StringComparer.Ordinal).ToList(); Assert.IsGreaterThanOrEqualTo(60, icons.Count, "le icone ci sono"); foreach (var path in icons) { Assert.AreEqual(".svg", Path.GetExtension(path), $"in icone/ solo disegni: {path}"); var document = XDocument.Parse(files.ReadText(path)!, LoadOptions.None); Assert.IsFalse(document.DescendantNodes().OfType().Any(), $"nessun commento (né avvisi di licenza): {path}"); var root = document.Root!; Assert.AreEqual(XName.Get("svg", IconNamespace), root.Name, path); Assert.AreEqual("0 0 24 24", (string?)root.Attribute("viewBox"), path); Assert.IsNull(root.Attribute("class"), path); Assert.AreEqual("none", (string?)root.Attribute("fill"), path); Assert.AreEqual("currentColor", (string?)root.Attribute("stroke"), path); Assert.IsTrue(root.Elements().Any(), $"vuota: {path}"); foreach (var shape in root.Descendants()) { Assert.AreEqual(IconNamespace, shape.Name.NamespaceName, path); Assert.IsTrue(Shapes.Contains(shape.Name.LocalName), $"{path}: elemento «{shape.Name.LocalName}» non ammesso"); Assert.IsFalse(shape.HasElements, $"{path}: forme annidate"); foreach (var attribute in shape.Attributes()) { var name = attribute.Name.LocalName; Assert.IsTrue(Geometry.Contains(name), $"{path}: attributo «{name}» (spessore, colore e riempimento vengono dal foglio di stile)"); var where = $"{path}: <{shape.Name.LocalName} {name}=\"{attribute.Value}\">"; switch (name) { case "d": foreach (var (x, y) in PathPoints(attribute.Value, where)!) { AssertOnGrid(x, where); AssertOnGrid(y, where); } break; case "points": var numbers = Numbers(attribute.Value, where); Assert.IsTrue(numbers.Count >= 4 && numbers.Count % 2 == 0, $"{where}: coppie di coordinate, almeno due punti"); numbers.ForEach(value => AssertOnGrid(value, where)); break; case "stroke-dasharray" or "stroke-dashoffset": Numbers(attribute.Value, where).ForEach(value => Assert.IsTrue(value is >= 0 and <= 100, where)); break; default: AssertOnGrid(Number(attribute.Value, where), where); break; } } } } } [TestMethod] public void TheGridCheckReadsPathsAndPointsAndFindsWhatIsOffTheGrid() { // Absolute and relative commands, repeated arguments, arcs with packed flags, curves, closing. var points = PathPoints("M4.5 12a7.5 7.5 0 0 1 13-5.1l2 2.1M3 3h18v18H3zM6 9c0-2 1-3 3-3s3 1 3 3q2 2 4 0t4 0", "prova"); Assert.IsNotNull(points); Assert.IsTrue(points.Any(p => Math.Abs(p.X - 19.5) < 1e-9 && Math.Abs(p.Y - 9) < 1e-9), "a relative line after a relative arc"); Assert.IsTrue(points.Any(p => p == (21.0, 21.0)), "h and v, then H"); Assert.IsTrue(points.Any(p => p == (20.0, 9.0)), "c, s, q and t"); Assert.IsTrue(points.All(p => p.X is >= 0 and <= 24 && p.Y is >= 0 and <= 24)); Assert.IsTrue(PathPoints("M2 12a10 10 0 1012 0", "prova")!.Any(p => p.Y > 12 + 5), "the arc is followed, not only its ends"); // What the test must refuse: off the grid by an end, by a curve or by an arc that bulges, broken numbers. foreach (var bad in new[] { "M30 30L-5 40", "M2 2l30 0", "M2 12C2 -10 22 -10 22 12", "M2 2a20 20 0 0 1 20 0", "M2 2L3", "M2,x 3", "L2 2", "M2 2a1 1 0 2 1 3 3" }) { var off = PathPoints(bad, bad, failQuietly: true); Assert.IsTrue(off is null || off.Any(p => p.X is < 0 or > 24 || p.Y is < 0 or > 24), $"«{bad}» passerebbe"); } Assert.ThrowsExactly(() => Numbers("0,0 99,x", "prova", failQuietly: true)); CollectionAssert.AreEqual(new[] { 0.5, 0.5, -3.0, 1e-1 }, Numbers("0.5.5-3,1e-1", "prova")); } private static void AssertOnGrid(double value, string where) => Assert.IsTrue(value is >= -1e-6 and <= 24 + 1e-6, $"{where}: {value.ToString(System.Globalization.CultureInfo.InvariantCulture)} fuori dalla griglia 0–24"); private static double Number(string text, string where) { Assert.IsTrue(double.TryParse(text, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var value), $"{where}: «{text}» non è un numero"); return value; } private static List Numbers(string text, string where, bool failQuietly = false) { var numbers = new List(); var at = 0; while (SkipSeparators(text, ref at) < text.Length) { if (ReadNumber(text, ref at) is not { } value) { if (failQuietly) { throw new FormatException(where); } Assert.Fail($"{where}: «{text[at..]}» non è un numero"); } else { numbers.Add(value); } } return numbers; } /// /// Every point the outline of an SVG path goes through (SVG 1.1 §8.3): the ends of each segment, the control points /// of the curves and points along each curve and arc, all made absolute. A path that does not start with a move, /// a command with too few numbers or a number that does not parse fails the test (or gives null with /// ). /// private static List<(double X, double Y)>? PathPoints(string d, string where, bool failQuietly = false) { var points = new List<(double X, double Y)>(); double x = 0, y = 0, startX = 0, startY = 0; var at = 0; var command = '\0'; void Refuse(string why) { if (!failQuietly) { Assert.Fail($"{where}: {why}"); } } while (SkipSeparators(d, ref at) < d.Length) { if (char.IsAsciiLetter(d[at])) { command = d[at++]; if (points.Count == 0 && command is not ('M' or 'm')) { Refuse("il percorso deve cominciare con M"); return null; } if (command is 'Z' or 'z') { (x, y) = (startX, startY); points.Add((x, y)); continue; } } else if (command is '\0' or 'Z' or 'z') { Refuse($"numero senza comando: «{d[at..]}»"); return null; } var relative = char.IsAsciiLetterLower(command); var arguments = char.ToUpperInvariant(command) switch { 'M' or 'L' or 'T' => 2, 'H' or 'V' => 1, 'C' => 6, 'S' or 'Q' => 4, 'A' => 7, _ => -1, }; if (arguments < 0) { Refuse($"comando «{command}» sconosciuto"); return null; } var values = new double[arguments]; for (var i = 0; i < arguments; i++) { SkipSeparators(d, ref at); double? value = char.ToUpperInvariant(command) == 'A' && i is 3 or 4 ? ReadFlag(d, ref at) : ReadNumber(d, ref at); if (value is null) { Refuse($"comando «{command}» con argomenti mancanti o non validi: «{d[at..]}»"); return null; } values[i] = value.Value; } (double X, double Y) Absolute(int index) => relative ? (x + values[index], y + values[index + 1]) : (values[index], values[index + 1]); var from = (X: x, Y: y); switch (char.ToUpperInvariant(command)) { case 'M': (x, y) = Absolute(0); (startX, startY) = (x, y); points.Add((x, y)); command = relative ? 'l' : 'L'; break; case 'L' or 'T': (x, y) = Absolute(0); points.Add((x, y)); break; case 'H': x = relative ? x + values[0] : values[0]; points.Add((x, y)); break; case 'V': y = relative ? y + values[0] : values[0]; points.Add((x, y)); break; case 'C': { var (c1, c2, end) = (Absolute(0), Absolute(2), Absolute(4)); points.AddRange([c1, c2, end]); for (var t = 0.0625; t < 1; t += 0.0625) { var u = 1 - t; points.Add(((u * u * u * from.X) + (3 * u * u * t * c1.X) + (3 * u * t * t * c2.X) + (t * t * t * end.X), (u * u * u * from.Y) + (3 * u * u * t * c1.Y) + (3 * u * t * t * c2.Y) + (t * t * t * end.Y))); } (x, y) = end; break; } case 'S' or 'Q': { var (control, end) = (Absolute(0), Absolute(2)); points.AddRange([control, end]); (x, y) = end; break; } case 'A': { var end = Absolute(5); points.Add(end); points.AddRange(ArcPoints(from, values[0], values[1], values[2], values[3] != 0, values[4] != 0, end)); (x, y) = end; break; } } } if (points.Count == 0) { Refuse("percorso vuoto"); return null; } return points; } /// Points along an elliptical arc, from its end points to its centre as in SVG 1.1 appendix F.6.5. private static IEnumerable<(double X, double Y)> ArcPoints((double X, double Y) from, double rx, double ry, double rotation, bool large, bool sweep, (double X, double Y) to) { rx = Math.Abs(rx); ry = Math.Abs(ry); if (rx == 0 || ry == 0 || from == to) { yield break; } var phi = rotation * Math.PI / 180; var (cos, sin) = (Math.Cos(phi), Math.Sin(phi)); var dx = (from.X - to.X) / 2; var dy = (from.Y - to.Y) / 2; var x1 = (cos * dx) + (sin * dy); var y1 = (-sin * dx) + (cos * dy); var lambda = (x1 * x1 / (rx * rx)) + (y1 * y1 / (ry * ry)); if (lambda > 1) { rx *= Math.Sqrt(lambda); ry *= Math.Sqrt(lambda); } var numerator = (rx * rx * ry * ry) - (rx * rx * y1 * y1) - (ry * ry * x1 * x1); var factor = Math.Sqrt(Math.Max(0, numerator / ((rx * rx * y1 * y1) + (ry * ry * x1 * x1)))) * (large == sweep ? -1 : 1); var cx1 = factor * rx * y1 / ry; var cy1 = -factor * ry * x1 / rx; var cx = (cos * cx1) - (sin * cy1) + ((from.X + to.X) / 2); var cy = (sin * cx1) + (cos * cy1) + ((from.Y + to.Y) / 2); static double Angle(double ux, double uy, double vx, double vy) => Math.Atan2((ux * vy) - (uy * vx), (ux * vx) + (uy * vy)); var start = Angle(1, 0, (x1 - cx1) / rx, (y1 - cy1) / ry); var delta = Angle((x1 - cx1) / rx, (y1 - cy1) / ry, (-x1 - cx1) / rx, (-y1 - cy1) / ry); if (!sweep && delta > 0) { delta -= 2 * Math.PI; } else if (sweep && delta < 0) { delta += 2 * Math.PI; } for (var step = 1; step < 32; step++) { var angle = start + (delta * step / 32); var (ex, ey) = (rx * Math.Cos(angle), ry * Math.Sin(angle)); yield return ((cos * ex) - (sin * ey) + cx, (sin * ex) + (cos * ey) + cy); } } private static int SkipSeparators(string text, ref int at) { while (at < text.Length && (char.IsWhiteSpace(text[at]) || text[at] == ',')) { at++; } return at; } private static double? ReadNumber(string text, ref int at) { var match = SvgNumber().Match(text, at); if (!match.Success || match.Index != at) { return null; } at += match.Length; return double.Parse(match.Value, System.Globalization.CultureInfo.InvariantCulture); } /// An arc flag: one digit, 0 or 1, which may touch the next number («0 01 3 3»). private static double? ReadFlag(string text, ref int at) { if (at < text.Length && text[at] is '0' or '1') { return text[at++] - '0'; } return null; } [TestMethod] public void EveryIconThePagesAskForIsDrawn() { var files = new EmbeddedWwwroot(); var drawn = files.Files.Where(f => f.StartsWith("icone/", StringComparison.Ordinal)) .Select(f => f["icone/".Length..^".svg".Length]).ToHashSet(StringComparer.Ordinal); var asked = new Dictionary(StringComparer.Ordinal); foreach (var path in files.Files.Where(f => f.EndsWith(".js", StringComparison.Ordinal))) { foreach (var name in IconNamesAskedIn(files.ReadText(path)!)) { asked.TryAdd(name, path); } } foreach (var (name, path) in asked) { Assert.Contains(name, drawn, $"{path} chiede l'icona «{name}»"); } // Every form the pages use is read, not only icon('…'): names held in data (icon: '…', a map of icons, the // third argument of label), chosen with a condition, or taken from a list a function returns. One name for each // form, as the pages have them today. foreach (var (name, form) in new[] { ("layout-grid", "icon: '…' (shell.js)"), ("sun", "icon: '…' (settings-general.js)"), ("gauge", "PLAN_ICONS e icon: '…'"), ("trash-2", "icon: '…' (accounts.js)"), ("circle-check", "icon(on ? '…' : '…')"), ("at-sign", "icon(cond ? '…' : '…')"), ("octagon-alert", "[colore, '…'] in outcome"), ("shield-alert", "return ['…', …] di placeholderFor"), ("user-check", "label(testo, '', '…')"), ("hourglass", "icon(a ? '…' : b ? '…' : '…')"), }) { Assert.IsTrue(asked.ContainsKey(name), $"la prova non legge più la forma {form}: manca «{name}»"); } Assert.IsGreaterThan(50, asked.Count, "le pagine usano le icone"); } [TestMethod] public void TheReadingOfTheIconNamesSeesEveryFormAndNotTheConditions() { const string script = """ const MENU = [{ path: '/', icon: 'uno' }, { icon: x ? 'due' : 'tre', label: 'non-icona' }]; const STATE_ICONS = { a: 'quattro', b: 'cinque' }; h('b', icon(s.kind === 'video' ? 'sei' : 'sette', 's'), icon('otto'), label(t('x'), 'ambra', 'nove')); const outcome = { ok: ['verde', 'dieci'], ko: ['rosso', 'undici'] }[k] || ['', 'dodici']; h('td', icon(outcome[1])); function placeholderFor(m) { if (m === 'Off') return ['tredici', t('a'), null]; return ['quattordici', t('b'), 'about:blank']; } const [name, text] = placeholderFor(mode); fill(icon(name, 'l')); """; CollectionAssert.AreEquivalent( new[] { "uno", "due", "tre", "quattro", "cinque", "sei", "sette", "otto", "nove", "dieci", "undici", "dodici", "tredici", "quattordici" }, IconNamesAskedIn(script).Distinct().ToArray(), "not «video» (a condition), not «non-icona», «verde» or «about:blank»"); } /// /// The icon names a script asks for: the literals that reach icon(…) directly or through data. /// /// the first argument of icon(…), the value of icon: … and the third argument of label(…), /// with the literals of a condition left out (those before a ? or after ===); /// the values of an object assigned to a name with ICON in it (PLAN_ICONS); /// icon(v[n]): element n of the lists in const v = …; /// icon(v) with const [.., v, ..] = f(…): that element of the lists f returns. /// /// private static IEnumerable IconNamesAskedIn(string script) { foreach (Match call in IconArgument().Matches(script)) { foreach (var name in NamesIn(FirstArgument(script, call.Index + call.Length))) { yield return name; } } foreach (Match property in IconProperty().Matches(script)) { foreach (var name in NamesIn(FirstArgument(script, property.Index + property.Length))) { yield return name; } } foreach (Match label in LabelIcon().Matches(script)) { yield return label.Groups[1].Value; } foreach (Match map in IconMap().Matches(script)) { foreach (Match value in QuotedValue().Matches(map.Groups["body"].Value)) { yield return value.Groups[1].Value; } } foreach (Match indexed in IndexedIcon().Matches(script)) { var definition = Regex.Match(script, $@"const {Regex.Escape(indexed.Groups["list"].Value)} = (?[^;\n]+)"); var index = int.Parse(indexed.Groups["index"].Value, System.Globalization.CultureInfo.InvariantCulture); foreach (Match list in ListLiteral().Matches(definition.Groups["value"].Value)) { var items = list.Groups["items"].Value.Split(',', StringSplitOptions.TrimEntries); if (index < items.Length && Quoted().Match(items[index]) is { Success: true } item) { yield return item.Groups[1].Value; } } } foreach (Match variable in VariableIcon().Matches(script)) { var name = variable.Groups["name"].Value; foreach (Match destructured in Regex.Matches(script, @"const \[(?[^\]]+)\] = (?\w+)\(")) { var names = destructured.Groups["names"].Value.Split(',', StringSplitOptions.TrimEntries); var position = Array.IndexOf(names, name); if (position < 0) { continue; } var body = Regex.Match(script, $@"function {Regex.Escape(destructured.Groups["function"].Value)}\([^)]*\) \{{(?.*?)\n\s*\}}", RegexOptions.Singleline); foreach (Match returned in Regex.Matches(body.Groups["body"].Value, @"return \[(?[^\]]*)\]")) { var items = returned.Groups["items"].Value.Split(',', StringSplitOptions.TrimEntries); if (position < items.Length && Quoted().Match(items[position]) is { Success: true } item) { yield return item.Groups[1].Value; } } } } } /// The text of an argument or a value from to the comma, parenthesis or brace that ends it. private static string FirstArgument(string script, int start) { var depth = 0; for (var i = start; i < script.Length; i++) { var c = script[i]; if (c is '(' or '[' or '{') { depth++; } else if (c is ')' or ']' or '}' || (c is ',' or ';' or '\n' && depth == 0)) { if (depth == 0) { return script[start..i]; } depth--; } } return script[start..]; } /// The quoted names of an expression, without the operands of a condition. private static IEnumerable NamesIn(string expression) { foreach (Match literal in Quoted().Matches(expression)) { var after = expression[(literal.Index + literal.Length)..].TrimStart(); var before = expression[..literal.Index].TrimEnd(); if (after.StartsWith('?') || before.EndsWith("===", StringComparison.Ordinal) || before.EndsWith("!==", StringComparison.Ordinal)) { continue; } yield return literal.Groups[1].Value; } } [TestMethod] public void NoFileOfTheProgramStillNamesTheFontOrTheIconSetUsedBefore() { var root = Repository.Root(); if (root is null) { Assert.Inconclusive("Il repository non è accanto alle prove."); } var looked = 0; foreach (var folder in new[] { "src", "tools", "installer", "docker", ".gitea", Path.Combine("docs", "guida") }) { var start = Path.Combine(root, folder); if (!Directory.Exists(start)) { continue; } foreach (var file in Directory.EnumerateFiles(start, "*", SearchOption.AllDirectories)) { var relative = Path.GetRelativePath(root, file); var parts = relative.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); if (parts.Contains("bin") || parts.Contains("obj") || parts.Contains("node_modules")) { continue; } Assert.IsFalse(FontExtensions.Contains(Path.GetExtension(file).ToLowerInvariant()), $"file di caratteri: {relative}"); if (!TextExtensions.Contains(Path.GetExtension(file).ToLowerInvariant())) { continue; } looked++; var match = FormerAssets().Match(File.ReadAllText(file)); Assert.IsFalse(match.Success, $"{relative} nomina ancora «{match.Value}»"); } } Assert.IsGreaterThan(100, looked, "i file del programma sono stati letti"); } [GeneratedRegex(@"pila dei caratteri di sistema `([^`]+)`")] private static partial Regex SpecificationStack(); [GeneratedRegex(@"--carattere:([^;]+);")] private static partial Regex CharacterToken(); [GeneratedRegex(@"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?")] private static partial Regex SvgNumber(); [GeneratedRegex(@"(?[^}]*)\}", RegexOptions.IgnoreCase)] private static partial Regex IconMap(); [GeneratedRegex(@":\s*'([a-z0-9-]+)'")] private static partial Regex QuotedValue(); [GeneratedRegex(@"\bicon\((?\w+)\[(?\d)\]\)")] private static partial Regex IndexedIcon(); [GeneratedRegex(@"\bicon\((?[A-Za-z_]\w*)[,)]")] private static partial Regex VariableIcon(); [GeneratedRegex(@"\[(?[^\[\]]*)\]")] private static partial Regex ListLiteral(); [GeneratedRegex(@"'([a-z0-9]+(?:-[a-z0-9]+)*)'")] private static partial Regex Quoted(); // The font and the icon set Febe carried until 18 November 2026. [GeneratedRegex(@"\b(archivo|lucide)\b", RegexOptions.IgnoreCase)] private static partial Regex FormerAssets(); }