Files
Chronos/src/Chronos.Tools/Commands/XamlLintCommand.cs
T
Alby96andClaude Opus 5.5 188b2c2e55
CI / Build and test (push) Successful in 8m19s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 12m9s
CI / PostgreSQL 16 integration (push) Successful in 7m49s
CI / PostgreSQL 17 integration (push) Successful in 7m19s
CI / Docker image (push) Successful in 46s
Release / Server image (push) Successful in 1m14s
feat(editor): visual crop, rotate/mirror/flip/straighten, colour looks (owner review 1 phase 4) (#26)
Owner review 1 R5 + R6. Camera rotation, mirror, flip, straighten and crop handles locked to the output; an Exposure Look group; Export output size ("proportions win"); settings format 2 with older-node gates. Also fixes project text and hashes differing between Windows and Linux.

Closes #19
Closes #20

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-05 01:09:09 +01:00

112 lines
5.6 KiB
C#

using System.Xml.Linq;
namespace Chronos.Tools.Commands;
/// <summary>
/// BRIEF §20.3 / DESIGN §4: every actionable control carries a tooltip and no visible text is a literal.
/// Elements inside <c>ControlTemplate</c>s are template parts and exempt from the tooltip rule.
/// </summary>
internal sealed class XamlLintCommand : ICommand
{
private static readonly HashSet<string> Actionable = new(StringComparer.Ordinal)
{
"Button", "ToggleButton", "RepeatButton", "Slider", "ComboBox", "CheckBox", "RadioButton", "MenuItem",
"AutoSlider", "IconButton", "SplitButton", "PreviewViewport",
};
private static readonly string[] TextAttributes = ["Content", "Text", "Header", "ToolTip", "Title", "Tag"];
public string Name => "xaml-lint";
public string Summary => "Check tooltips and literal text in all XAML under src/";
public Task<int> RunAsync(string[] args)
{
var root = Args.RepoRoot();
var problems = new List<string>();
var files = Directory.EnumerateFiles(Path.Combine(root, "src"), "*.xaml", SearchOption.AllDirectories)
.Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)
&& !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal))
.ToList();
var documents = files.Select(f => (File: f, Doc: XDocument.Load(f, LoadOptions.SetLineInfo))).ToList();
var valueTypes = ValueResourceTypes(documents.Select(d => d.Doc));
foreach (var (file, doc) in documents)
{
foreach (var el in doc.Descendants())
{
var line = ((System.Xml.IXmlLineInfo)el).LineNumber;
var where = $"{Path.GetRelativePath(root, file)}:{line}";
var name = el.Name.LocalName;
var inTemplate = el.Ancestors().Any(a => a.Name.LocalName is "ControlTemplate" or "Setter" or "Style");
if (Actionable.Contains(name) && !inTemplate && !HasToolTip(el) && !IsExempt(el))
problems.Add($"{where}: <{name}> has no ToolTip");
foreach (var attrName in TextAttributes)
{
var attr = el.Attribute(attrName);
if (attr is null) continue;
var v = attr.Value;
if (v.Length == 0 || v.StartsWith('{')) continue;
if (attrName == "Tag" || (attrName == "Content" && inTemplate)) continue;
if (v.Any(char.IsLetter))
problems.Add($"{where}: literal {attrName}=\"{v}\" on <{name}> (use {{l:Loc …}})");
}
foreach (var attr in el.Attributes())
{
if (ExpectedValueType(name, attr.Name.LocalName) is not { } expected || ResourceKey(attr.Value) is not { } key) continue;
if (valueTypes.TryGetValue(key, out var actual) && actual != expected)
problems.Add($"{where}: {name}.{attr.Name.LocalName} needs a {expected} but resource {key} is a {actual}");
}
// Literal element content such as <TextBlock>Hello</TextBlock> or <Run>Hi</Run>.
if (name is "TextBlock" or "Run" or "Label" or "Button" && !el.HasElements && el.Value.Any(char.IsLetter))
problems.Add($"{where}: literal text in <{name}>");
}
}
foreach (var p in problems) Console.Error.WriteLine(p);
Console.WriteLine($"xaml-lint: {files.Count} file(s), {problems.Count} problem(s)");
return Task.FromResult(problems.Count == 0 ? 0 : 1);
}
/// <summary>Keyed resources of the value types WPF cannot convert into each other at run time (parsing succeeds, loading fails).</summary>
private static Dictionary<string, string> ValueResourceTypes(IEnumerable<XDocument> documents)
{
var types = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var el in documents.SelectMany(d => d.Descendants()))
{
if (el.Name.LocalName is not ("Double" or "GridLength" or "Thickness" or "CornerRadius")) continue;
if (el.Attributes().FirstOrDefault(a => a.Name.LocalName == "Key") is { } key) types[key.Value] = el.Name.LocalName;
}
return types;
}
private static string? ExpectedValueType(string element, string attribute) => attribute switch
{
"Width" when element == "ColumnDefinition" => "GridLength",
"Height" when element == "RowDefinition" => "GridLength",
"Margin" or "Padding" or "BorderThickness" => "Thickness",
"CornerRadius" => "CornerRadius",
"Width" or "Height" or "MinWidth" or "MaxWidth" or "MinHeight" or "MaxHeight" or "FontSize" => "Double",
_ => null,
};
private static string? ResourceKey(string value)
{
var match = System.Text.RegularExpressions.Regex.Match(value, @"^\{(?:Static|Dynamic)Resource\s+(?:ResourceKey=)?([^\s}]+)\s*\}$");
return match.Success ? match.Groups[1].Value : null;
}
private static bool HasToolTip(XElement el) =>
el.Attribute("ToolTip") is not null
|| el.Elements().Any(c => c.Name.LocalName.EndsWith(".ToolTip", StringComparison.Ordinal))
|| el.Attributes().Any(a => a.Name.LocalName == "TipKey");
/// <summary>Opt-out for controls whose tooltip is applied by a style (marked explicitly in XAML).</summary>
private static bool IsExempt(XElement el) =>
el.Attributes().Any(a => a.Name.LocalName == "ToolTipFromStyle" && a.Value == "True");
}