diff --git a/CHANGELOG.md b/CHANGELOG.md index 92288cad..90eb6cd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ API between minor releases. ### Added +- CLI and API: `rvtio sheets` lists sheet parameters and filters sheets by them, ported from rvt-prt's `list --params/--where` (Unreleased after 0.1.0). `SheetRecord.Parameters` carries the text and whole-number project/shared parameters of each sheet as display strings (numbers with units stay out until their units are read); Yes/No parameters (`Appears In Sheet List` and project/shared parameters of Yes/No kind, named in `SheetRecord.YesNoParameters`) read as `Yes`/`No`. `rvtio sheets --where NAME=VALUE` (also `!=` and `~` for contains, `*`/`?` wildcards, repeatable, case-insensitive) keeps only matching sheets; on a Yes/No parameter `true/false/1/0` mean `Yes`/`No`, every other field compares literally. A misspelt name or an empty match exits with code 1. `--params` lists each kept sheet's parameters on standard error, `--csv` writes them as CSV, `--json` keeps the default JSON. New API: `SheetFilter.TryParse/Matches`, `SheetCatalog.FromFiltered`. New tests: `SheetFilterTests`. + - CLI and API: `rvtio print [--level ] [--scale ] [--paper A4|A3|A2|A1|A0] [--list-levels]` and `RvtIO.Print.PlanPrinter` render the plan of one level to a PDF page from the decoded model: walls as their stored location line drawn two sides of the stored width apart (`WALL_ATTR_WIDTH_PARAM`; 100 mm when neither the wall nor its type stores one), columns as their bounding-box footprint, and grids clipped to the extent of the level. `--list-levels` prints the levels with a drawable wall or column and their stored elevation; without `--level` the level with the most of them is printed. The page is the smallest landscape A4 to A0 that holds the drawing at the scale (a larger drawing is scaled down to fit), with a frame at the margin and the drawing centred. A wall is cut at the openings of its hosted doors and windows: the cut loop of each insert, transformed to the model, leaves its stretch out, the wall is drawn in the pieces between the openings with a jamb at each cut, and a window gets a light line across the opening. The title (level name and scale) is written with an embedded TrueType font found on the machine (Arial, Segoe UI or Tahoma on Windows, DejaVu Sans on Linux, Arial or Helvetica Neue on macOS), which also makes Cyrillic text real, selectable PDF text; without such a font the page is drawn without a title. Sheets print too: `rvtio print --sheet [--list-sheets]` renders a sheet page from the location curves of the elements the sheet owns (the page border, the title block frame and rules, tables), on the paper the linework spans (snapped to A4-A0 within 8 mm), with the sheet number and name written in a corner; `RvtIO.Print.SheetPrinter` is the API. A level line ends in the marker the reference export uses: a circle with an arrow head at the right of the drawing, the level name above and its height in millimetres below (Roof Line 6000, Level 2 3000, Ceiling 2700, Level 1 0, Level 1 Living Rm. -550, Foundation -800), each height printed once even though the project holds many level elements at the same height; the drawing reserves a label margin on the right. A level line of an elevation ends in a level marker: a white circle with the height in metres (+0.000, +3.000, +6.000), as a Revit elevation notes its levels. diff --git a/README.md b/README.md index a2e66bbd..10f5858d 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ List the sheets and the viewports placed on them: rvtio sheets project.rvt sheets.json ``` -The catalog has the sheet number, name, issue date, by-lines and scale, the viewports of each sheet and the elements each sheet owns. Page size, view placement, the displayed view and 2D content are not decoded; every limit is reported in the catalog itself. See [sheets and viewports](docs/sheets.md). +The catalog has the sheet number, name, issue date, by-lines and scale, the viewports of each sheet and the elements each sheet owns, plus the text and whole-number project/shared parameters of each sheet (`--params`, `--csv`, `--where NAME=VALUE` with `!=`/`~` and `*`/`?` wildcards). Page size, view placement, the displayed view and 2D content are not decoded; every limit is reported in the catalog itself. See [sheets and viewports](docs/sheets.md). Print the plan of a level to PDF — walls with their stored width, column footprints and grids, on the smallest paper that holds the drawing at the scale: diff --git a/docs/public-api.md b/docs/public-api.md index 06f28005..bfe1e91b 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -66,9 +66,10 @@ extension and label helpers carry the ids and names stored in the file format. | Type | Use | |---|---| | `SheetCatalog` | `Extract(document)` (or a `RevitFileInfo`) returns the sheets of the file, the viewports placed on them and the limits of this release: `Sheets`, `Viewports` and `Issues`. Nothing is read from the file again. | -| `SheetRecord` | A sheet: `ElementId`, `Number`, `Name`, `IssueDate`, `Scale`, `DrawnBy`, `DesignedBy`, `CheckedBy`, `ApprovedBy`, `ViewportIds` and `OwnedElementIds`. | +| `SheetRecord` | A sheet: `ElementId`, `Number`, `Name`, `IssueDate`, `Scale`, `DrawnBy`, `DesignedBy`, `CheckedBy`, `ApprovedBy`, `ViewportIds`, `OwnedElementIds`, `Parameters` (text/whole-number project/shared params; Yes/No params read as `Yes`/`No`) and `YesNoParameters` (their names). | | `ViewportRecord` | A placed view: `ElementId`, `SheetId` and `DetailNumber`; `DisplayedViewId` is null until the viewer element is decoded. | | `SheetIssue`, `SheetIssueKind` | What this release does not decode: page size, view placement, displayed view, view content and crop region. | +| `SheetFilter` | A `--where` filter (`NAME=VALUE`, `!=`, `~`, `*`/`?` wildcards; `true`/`false`/`1`/`0` aliases apply only to Yes/No params); `SheetCatalog.FromFiltered` keeps matching sheets. | See [sheets and viewports](sheets.md) for what is decoded, what the limits are and why no page coordinate is exposed yet. diff --git a/docs/sheets.md b/docs/sheets.md index fbefccb2..42870ec0 100644 --- a/docs/sheets.md +++ b/docs/sheets.md @@ -34,6 +34,25 @@ With no output path the JSON goes to standard output; diagnostics go to standard was written, 1 a usage error or an output path that cannot be written, 2 a file that cannot be read, 3 a reader limit that cut a stream (the codes of [the export report](export-report.md)). +Each `SheetRecord` also carries `Parameters`: the text and whole-number project and shared parameters +of the sheet as display strings (numbers with units stay out until their units are read). A Yes/No parameter +(`Appears In Sheet List` and project/shared parameters of Yes/No kind) reads as `Yes`/`No`; its names are also +listed in `SheetRecord.YesNoParameters`. The port follows rvt-prt's `list --params` (Unreleased after 0.1.0). + +```sh +rvtio sheets project.rvt --where "Appears In Sheet List=Yes" --where "Sheet Group=Architectural" +rvtio sheets project.rvt sheets.csv --csv --where "Sheet Name~plan" --where "Sheet Number!=A1*" +rvtio sheets project.rvt --params --where "Drawn By=AB" +``` + +`--where NAME=VALUE` (also `NAME!=VALUE` and `NAME~TEXT` for contains) keeps only the sheets whose parameters +match, as in rvt-prt. `*` stands for any text and `?` for one character; names and values compare +case-insensitively. On a Yes/No parameter `true`, `false`, `1` and `0` mean the same as `Yes`/`No`; +every other field compares literally, so a sheet number `1` never matches `=true`. A parameter a sheet has no +value for is empty. Repeat a filter for several: all must hold. A name no sheet carries stops with the names there +are (exit code 1), as does a filter nothing matches. `--params` lists each kept sheet's parameters on standard +error, `--csv` writes them as CSV (one row per sheet, one column per parameter), `--json` keeps the default JSON. + ## What a sheet is A sheet is an element that carries the `Sheet Number` or `Sheet Name` parameter. The reader creates those parameters @@ -62,6 +81,7 @@ owner, when the stored owner is not a view, or when it is the element itself. | `SheetRecord.DrawnBy`, `DesignedBy`, `CheckedBy`, `ApprovedBy` | the `SHEET_*` by-line parameters | | `SheetRecord.ViewportIds` | the viewports whose sheet is this sheet | | `SheetRecord.OwnedElementIds` | elements whose `OwnerViewId` is this sheet | +| `SheetRecord.Parameters` | text and whole-number project/shared parameters; `SHEET_SCHEDULED` as `Appears In Sheet List` | | `ViewportRecord.SheetId` | the referenced sheet | | `ViewportRecord.DetailNumber` | `Detail Number` parameter (`VIEWPORT_DETAIL_NUMBER`) | diff --git a/src/RvtIO.Cli/Program.cs b/src/RvtIO.Cli/Program.cs index d08857ba..51e0dcae 100644 --- a/src/RvtIO.Cli/Program.cs +++ b/src/RvtIO.Cli/Program.cs @@ -62,8 +62,8 @@ Report options (read the file and print or write a report instead of exporting): --sketch-owner-dump write the closed sketch loops of every sketch-owning element --inspect-batch inspect many ids in one pass (ids: one per line or comma separated) --list-category list the elements of one category - sheets [output.json] [--r22-layout] - write the sheet catalog (sheets, viewports, limits not decoded) as JSON + sheets [output.json] [--r22-layout] [--where FILTER] [--params] [--csv] [--json] + write the sheet catalog (sheets, viewports, parameters, limits not decoded) as JSON print [--level ] [--view ] [--sheet ] [--scale ] [--all-views] [--all-sheets] [--paper A4|A3|A2|A1|A0] [--list-levels] [--list-views] [--list-sheets] diff --git a/src/RvtIO.Cli/SheetsCommand.cs b/src/RvtIO.Cli/SheetsCommand.cs index 7bd3ab9a..164cee3d 100644 --- a/src/RvtIO.Cli/SheetsCommand.cs +++ b/src/RvtIO.Cli/SheetsCommand.cs @@ -6,9 +6,13 @@ namespace RvtIO.Cli; /// -/// rvtio sheets <file.rvt|file.rfa> [output.json] [--r22-layout]: reads a file and writes the sheet catalog of -/// (the sheets, their viewports and what this release does not decode) as JSON to the output -/// path, or to standard output when no path is given. Diagnostics go to standard error. +/// rvtio sheets <file.rvt|file.rfa> [output.json] [--r22-layout] [--where FILTER] [--params] [--csv] [--json]: +/// reads a file and writes the sheet catalog of (the sheets, their viewports and what this +/// release does not decode) as JSON to the output path, or to standard output when no path is given. +/// --where NAME=VALUE (also != and ~ for contains, * and ? wildcards, repeatable) +/// keeps only the sheets whose parameters match, as in rvt-prt's list --where. +/// --params lists each kept sheet's parameters on standard error, --csv writes them as CSV instead of JSON. +/// Diagnostics go to standard error. /// Exit codes: 0 written, 1 usage error or an output path that cannot be written, 2 the file cannot be read, 3 a reader /// limit cut a stream. /// @@ -23,14 +27,46 @@ internal static class SheetsCommand internal static int Run(string[] args, TextWriter output, TextWriter error) { string? file = null, outputPath = null; - bool r22Layout = false; - foreach (string arg in args) + bool r22Layout = false, showParams = false, csv = false; + var whereTexts = new List(); + for (int i = 0; i < args.Length; i++) { + string arg = args[i]; if (arg == "--r22-layout") { r22Layout = true; continue; } + if (arg == "--params") + { + showParams = true; + continue; + } + if (arg == "--csv") + { + csv = true; + continue; + } + if (arg == "--json") + { + // The default output; accepted for rvt-prt compatibility. + continue; + } + if (arg == "--where") + { + if (i + 1 >= args.Length) + { + error.WriteLine("sheets --where needs a filter: NAME=VALUE, NAME!=VALUE or NAME~TEXT. " + Usage); + return RvtExitCodes.Usage; + } + whereTexts.Add(args[++i]); + continue; + } + if (arg.StartsWith("--where=", StringComparison.Ordinal)) + { + whereTexts.Add(arg["--where=".Length..]); + continue; + } if (arg.StartsWith("--", StringComparison.Ordinal)) { error.WriteLine("Unknown option for sheets: " + arg + ". " + Usage); @@ -55,6 +91,18 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) return RvtExitCodes.Usage; } + var filters = new List(); + foreach (string text in whereTexts) + { + var parsed = SheetFilter.TryParse(text, out string? parseError); + if (parsed == null) + { + error.WriteLine(parseError + " " + Usage); + return RvtExitCodes.Usage; + } + filters.Add(parsed); + } + SheetCatalog catalog; try { @@ -72,17 +120,48 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) return RvtExitCodes.LimitExceeded; } - string json = JsonSerializer.Serialize(catalog, Options); + if (filters.Count > 0) + { + // A misspelt name stops with the names there are, as in rvt-prt. + var available = AvailableNames(catalog); + foreach (var filter in filters) + { + if (!available.Contains(filter.Name)) + { + error.WriteLine($"Unknown sheet parameter '{filter.Name}'. Available: {string.Join(", ", available)}."); + return RvtExitCodes.Usage; + } + } + var kept = catalog.Sheets.Where(sheet => filters.All(filter => filter.Matches(sheet))).ToList(); + if (kept.Count == 0) + { + error.WriteLine("[sheets] no sheet matches the --where filters; nothing was written."); + return RvtExitCodes.Usage; + } + catalog = SheetCatalog.FromFiltered(kept, catalog.Viewports.Where(v => kept.Any(s => s.ElementId == v.SheetId)).ToList()); + } + + if (showParams) + { + foreach (var sheet in catalog.Sheets) + { + error.WriteLine($"{sheet.Number ?? "?"} {sheet.Name ?? ""}"); + foreach (var (key, value) in sheet.Parameters) + error.WriteLine($" {key}: {value}"); + } + } + + string payload = csv ? ToCsv(catalog) : JsonSerializer.Serialize(catalog, Options); if (outputPath == null) { - output.WriteLine(json); + output.WriteLine(payload); } else { string temporary = outputPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { - File.WriteAllText(temporary, json + Environment.NewLine, new System.Text.UTF8Encoding(false)); + File.WriteAllText(temporary, payload + Environment.NewLine, new System.Text.UTF8Encoding(false)); File.Move(temporary, outputPath, overwrite: true); } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) @@ -103,5 +182,56 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) return RvtExitCodes.Success; } - private const string Usage = "Usage: rvtio sheets [output.json] [--r22-layout]"; + private static SortedSet AvailableNames(SheetCatalog catalog) + { + var names = new SortedSet(StringComparer.OrdinalIgnoreCase); + foreach (string core in new[] + { + "Sheet Number", "Sheet Name", "Sheet Issue Date", "View Scale", + "Drawn By", "Designed By", "Checked By", "Approved By", "Appears In Sheet List", + "SHEET_NUMBER", "SHEET_NAME", "SHEET_ISSUE_DATE", "VIEW_SCALE", + "SHEET_DRAWN_BY", "SHEET_DESIGNED_BY", "SHEET_CHECKED_BY", "SHEET_APPROVED_BY", + "SHEET_SCHEDULED", + }) + names.Add(core); + foreach (var sheet in catalog.Sheets) + foreach (var key in sheet.Parameters.Keys) + names.Add(key); + return names; + } + + private static string ToCsv(SheetCatalog catalog) + { + var extra = new SortedSet(StringComparer.OrdinalIgnoreCase); + foreach (var sheet in catalog.Sheets) + foreach (var key in sheet.Parameters.Keys) + extra.Add(key); + var lines = new List + { + string.Join(",", new[] { "ElementId", "Number", "Name", "IssueDate", "Scale", "DrawnBy", + "DesignedBy", "CheckedBy", "ApprovedBy" }.Concat(extra).Select(EscapeCsv)), + }; + foreach (var sheet in catalog.Sheets) + { + var fields = new List + { + sheet.ElementId.ToString(), sheet.Number, sheet.Name, sheet.IssueDate, + sheet.Scale?.ToString(), sheet.DrawnBy, sheet.DesignedBy, sheet.CheckedBy, sheet.ApprovedBy, + }; + foreach (string key in extra) + fields.Add(sheet.Parameters.TryGetValue(key, out var value) ? value : null); + lines.Add(string.Join(",", fields.Select(EscapeCsv))); + } + return string.Join(Environment.NewLine, lines); + } + + private static string EscapeCsv(string? field) + { + field ??= string.Empty; + if (field.Contains('"') || field.Contains(',') || field.Contains('\n') || field.Contains('\r')) + return "\"" + field.Replace("\"", "\"\"") + "\""; + return field; + } + + private const string Usage = "Usage: rvtio sheets [output.json] [--r22-layout] [--where FILTER] [--params] [--csv] [--json]"; } diff --git a/src/RvtIO/Sheets/SheetCatalog.cs b/src/RvtIO/Sheets/SheetCatalog.cs index 3b255412..5107b981 100644 --- a/src/RvtIO/Sheets/SheetCatalog.cs +++ b/src/RvtIO/Sheets/SheetCatalog.cs @@ -1,5 +1,6 @@ using RvtIO.BuiltIns; using RvtIO.Model; +using RvtIO.Parsing; namespace RvtIO.Sheets; @@ -46,6 +47,10 @@ private SheetCatalog(IReadOnlyList sheets, IReadOnlyListCreate a catalog from sheets and viewports (used by --where filtering). + public static SheetCatalog FromFiltered(IReadOnlyList sheets, IReadOnlyList viewports) => + new(sheets, viewports); + /// The sheets of the document, ordered by number (empty numbers last) and then by element id. public IReadOnlyList Sheets { get; } @@ -130,6 +135,7 @@ public static SheetCatalog Extract(RevitFileInfo info) var sheets = new List(sheetElements.Count); foreach (var element in sheetElements) { + var (parameters, yesNo) = ExtraParameters(element, info.UserParameters); sheets.Add(new SheetRecord( element.Id, Text(element, BuiltInParameter.SHEET_NUMBER), @@ -141,12 +147,93 @@ public static SheetCatalog Extract(RevitFileInfo info) Text(element, BuiltInParameter.SHEET_CHECKED_BY), Text(element, BuiltInParameter.SHEET_APPROVED_BY), Ordered(viewportsBySheet, element.Id), - Ordered(owned, element.Id))); + Ordered(owned, element.Id), + parameters, + yesNo)); } return new SheetCatalog(sheets, viewports); } + /// + /// The sheet's project and shared parameters as display strings (rvt-prt's list --params): + /// text and whole-number user parameters (positive definition ids) with a value; numbers with units + /// are left out until their units are read. Unset sentinels (HasRevitValue == false) are skipped. + /// Built-in parameters other than the sheet's own fields (such as category or partition ids) are not + /// sheet parameters and stay out. Also returns the display names of the Yes/No parameters among them: + /// a user parameter whose definition is a Yes/No kind, whose Forge spec is boolean, or whose stored + /// value is boolean, reads as Yes/No, as does Appears In Sheet List. + /// + private static (IReadOnlyDictionary Parameters, IReadOnlyCollection YesNo) + ExtraParameters(Element element, UserParameterCatalog? catalog) + { + var result = new SortedDictionary(StringComparer.OrdinalIgnoreCase); + var yesNo = new SortedSet(StringComparer.OrdinalIgnoreCase); + foreach (var parameter in element.Parameters) + { + if (parameter.Definition == null || !parameter.HasRevitValue) continue; + int id = parameter.Definition.Id; + if (id == (int)BuiltInParameter.SHEET_NUMBER + || id == (int)BuiltInParameter.SHEET_NAME + || id == (int)BuiltInParameter.SHEET_ISSUE_DATE + || id == (int)BuiltInParameter.VIEW_SCALE + || id == (int)BuiltInParameter.SHEET_DRAWN_BY + || id == (int)BuiltInParameter.SHEET_DESIGNED_BY + || id == (int)BuiltInParameter.SHEET_CHECKED_BY + || id == (int)BuiltInParameter.SHEET_APPROVED_BY) + continue; + if (id < 0) continue; + string? key = parameter.Definition.Name; + if (string.IsNullOrWhiteSpace(key)) continue; + bool knownYesNo = IsYesNoParameter(parameter, id, catalog); + string? value = DisplayParameterValue(parameter, knownYesNo); + if (value == null) continue; + // First occurrence wins, matching Element.LookupParameter semantics. + if (result.TryAdd(key, value) && knownYesNo) yesNo.Add(key); + } + // "Appears In Sheet List" under its Revit display name for --where compatibility; + // the BIP enum name still resolves through SheetFilter.Lookup. + if (element.LookupParameter(BuiltInParameter.SHEET_SCHEDULED) is { } scheduled + && scheduled.HasRevitValue) + { + string? scheduledText = scheduled.Value switch + { + int scheduledInt => scheduledInt != 0 ? "Yes" : "No", + bool scheduledBool => scheduledBool ? "Yes" : "No", + _ => null, + }; + if (scheduledText != null + && result.TryAdd(SheetFilter.DisplayName(BuiltInParameter.SHEET_SCHEDULED), scheduledText)) + yesNo.Add(SheetFilter.DisplayName(BuiltInParameter.SHEET_SCHEDULED)); + } + return (result, yesNo); + } + + /// True when the parameter is known to be Yes/No: its definition element is a Yes/No kind, + /// its Forge spec is boolean, or its stored value is boolean. + private static bool IsYesNoParameter(Parameter parameter, int id, Parsing.UserParameterCatalog? catalog) + { + if (parameter.Value is bool) return true; + if (parameter.SpecType?.Contains("bool", StringComparison.OrdinalIgnoreCase) == true) return true; + return catalog?.Definitions.TryGetValue(id, out var definition) == true && definition.IsYesNo; + } + + /// Display text for a sheet parameter: strings as stored, integers as numbers, + /// Yes/No parameters as Yes/No. + private static string? DisplayParameterValue(Parameter parameter, bool knownYesNo) + { + if (parameter.Value == null) return null; + if (parameter.Value is bool boolean) return boolean ? "Yes" : "No"; + return parameter.StorageType switch + { + StorageType.String => parameter.Value as string, + StorageType.Integer => parameter.Value is int i + ? knownYesNo ? (i != 0 ? "Yes" : "No") : i.ToString(System.Globalization.CultureInfo.InvariantCulture) + : null, + _ => null, + }; + } + private static IReadOnlyList Ordered(Dictionary> byOwner, int owner) { if (!byOwner.TryGetValue(owner, out var ids) || ids.Count == 0) return []; diff --git a/src/RvtIO/Sheets/SheetFilter.cs b/src/RvtIO/Sheets/SheetFilter.cs new file mode 100644 index 00000000..f86474cc --- /dev/null +++ b/src/RvtIO/Sheets/SheetFilter.cs @@ -0,0 +1,219 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; + +namespace RvtIO.Sheets; + +/// +/// A --where filter over sheets, ported from rvt-prt's sheet-parameter filters: +/// NAME=VALUE (* and ? wildcards), NAME!=VALUE, NAME~TEXT (contains). +/// Names and values compare case-insensitively; on a Yes/No parameter (Appears In Sheet List or +/// one of ) the value reads as Yes/No and the +/// true/false/1/0 spellings match it; every other field compares literally. +/// A sheet without the parameter has an empty value. +/// +public sealed class SheetFilter +{ + private SheetFilter(string name, Operator op, string value) + { + Name = name; + Op = op; + Value = value; + } + + internal enum Operator { Equals, NotEquals, Contains } + + internal string Name { get; } + internal Operator Op { get; } + internal string Value { get; } + + /// Parse one --where filter. Returns null with an error when the text is not a filter. + public static SheetFilter? TryParse(string text, out string? error) + { + error = null; + if (string.IsNullOrWhiteSpace(text)) + { + error = $"Bad filter '{text}': expected NAME=VALUE, NAME!=VALUE or NAME~TEXT."; + return null; + } + // Order matters: != before =. + int notEquals = text.IndexOf("!=", StringComparison.Ordinal); + int contains = text.IndexOf('~'); + int equals = text.IndexOf('='); + string name, value; + Operator op; + if (notEquals >= 0 && (contains < 0 || notEquals < contains) && (equals < 0 || notEquals < equals)) + { + name = text[..notEquals]; + value = text[(notEquals + 2)..]; + op = Operator.NotEquals; + } + else if (contains >= 0 && (equals < 0 || contains < equals)) + { + name = text[..contains]; + value = text[(contains + 1)..]; + op = Operator.Contains; + } + else if (equals >= 0) + { + name = text[..equals]; + value = text[(equals + 1)..]; + op = Operator.Equals; + } + else + { + error = $"Bad filter '{text}': expected NAME=VALUE, NAME!=VALUE or NAME~TEXT."; + return null; + } + name = name.Trim(); + value = value.Trim(); + if (name.Length == 0) + { + error = $"Bad filter '{text}': the parameter name is empty."; + return null; + } + return new SheetFilter(name, op, value); + } + + /// True when the sheet satisfies this filter. + public bool Matches(SheetRecord sheet) + { + string actual = Lookup(sheet, Name) ?? string.Empty; + return Op switch + { + Operator.Contains => actual.Contains(Value, StringComparison.OrdinalIgnoreCase), + Operator.Equals => IsYesNoParameter(sheet, Name) + ? WildcardEquals(actual, Value) + : WildcardLiteralEquals(actual, Value), + Operator.NotEquals => IsYesNoParameter(sheet, Name) + ? !WildcardEquals(actual, Value) + : !WildcardLiteralEquals(actual, Value), + _ => false, + }; + } + + /// True when the named field is a Yes/No parameter: Appears In Sheet List or one of + /// . Only for these do the true/false/1/0 + /// spellings match Yes/No; every other field compares literally. The name compares + /// case-insensitively even when the record was built with a case-sensitive collection. + internal static bool IsYesNoParameter(SheetRecord sheet, string name) => + string.Equals(name, DisplayName(BuiltInParameter.SHEET_SCHEDULED), StringComparison.OrdinalIgnoreCase) + || string.Equals(name, nameof(BuiltInParameter.SHEET_SCHEDULED), StringComparison.OrdinalIgnoreCase) + || sheet.YesNoParameters.Contains(name, StringComparer.OrdinalIgnoreCase); + + /// The value of a named sheet field or parameter, or null when the sheet has no such name. + internal static string? Lookup(SheetRecord sheet, string name) + { + // Core fields by Revit display name and by BIP enum name. + foreach (var (display, bip, get) in CoreFields(sheet)) + { + if (string.Equals(name, display, StringComparison.OrdinalIgnoreCase) + || string.Equals(name, bip, StringComparison.OrdinalIgnoreCase)) + return get(); + } + foreach (var (key, value) in sheet.Parameters) + { + if (string.Equals(name, key, StringComparison.OrdinalIgnoreCase)) + return value; + } + return null; + } + + /// True when every filter names a field the sheet exposes. + public static bool TryValidateNames(IEnumerable filters, SheetRecord sheet, out string? unknown) + { + foreach (var filter in filters) + { + if (Lookup(sheet, filter.Name) == null) + { + unknown = filter.Name; + return false; + } + } + unknown = null; + return true; + } + + private static IEnumerable<(string Display, string Bip, Func Get)> CoreFields(SheetRecord sheet) + { + yield return ("Sheet Number", nameof(BuiltInParameter.SHEET_NUMBER), () => sheet.Number); + yield return ("Sheet Name", nameof(BuiltInParameter.SHEET_NAME), () => sheet.Name); + yield return ("Sheet Issue Date", nameof(BuiltInParameter.SHEET_ISSUE_DATE), () => sheet.IssueDate); + yield return ("View Scale", nameof(BuiltInParameter.VIEW_SCALE), () => sheet.Scale?.ToString()); + yield return ("Drawn By", nameof(BuiltInParameter.SHEET_DRAWN_BY), () => sheet.DrawnBy); + yield return ("Designed By", nameof(BuiltInParameter.SHEET_DESIGNED_BY), () => sheet.DesignedBy); + yield return ("Checked By", nameof(BuiltInParameter.SHEET_CHECKED_BY), () => sheet.CheckedBy); + yield return ("Approved By", nameof(BuiltInParameter.SHEET_APPROVED_BY), () => sheet.ApprovedBy); + if (sheet.Parameters.TryGetValue(DisplayName(BuiltInParameter.SHEET_SCHEDULED), out var scheduled)) + yield return ("Appears In Sheet List", nameof(BuiltInParameter.SHEET_SCHEDULED), () => scheduled); + } + + internal static string DisplayName(BuiltInParameter bip) => bip switch + { + BuiltInParameter.SHEET_NUMBER => "Sheet Number", + BuiltInParameter.SHEET_NAME => "Sheet Name", + BuiltInParameter.SHEET_ISSUE_DATE => "Sheet Issue Date", + BuiltInParameter.VIEW_SCALE => "View Scale", + BuiltInParameter.SHEET_DRAWN_BY => "Drawn By", + BuiltInParameter.SHEET_DESIGNED_BY => "Designed By", + BuiltInParameter.SHEET_CHECKED_BY => "Checked By", + BuiltInParameter.SHEET_APPROVED_BY => "Approved By", + BuiltInParameter.SHEET_SCHEDULED => "Appears In Sheet List", + _ => bip.ToString(), + }; + + /// Normalize a Yes/No spelling to Yes/No; null when the text is neither. + internal static string? NormalizeYesNo(string text) => text.ToUpperInvariant() switch + { + "YES" or "TRUE" or "1" => "Yes", + "NO" or "FALSE" or "0" => "No", + _ => null, + }; + + internal static bool WildcardEquals(string actual, string pattern) + { + string? normalizedPattern = NormalizeYesNo(pattern); + string? normalizedActual = NormalizeYesNo(actual); + if (normalizedPattern != null && normalizedActual != null) + return string.Equals(normalizedActual, normalizedPattern, StringComparison.OrdinalIgnoreCase); + return WildcardLiteralEquals(actual, pattern); + } + + /// Wildcard comparison without Yes/No normalization: an empty pattern matches only an + /// empty value (a sheet without the parameter). + internal static bool WildcardLiteralEquals(string actual, string pattern) + { + if (pattern.Length == 0) + return actual.Length == 0; + return WildcardMatch(actual, pattern); + } + + private static bool WildcardMatch(string text, string pattern) + { + int ti = 0, pi = 0, star = -1, mark = 0; + while (ti < text.Length) + { + if (pi < pattern.Length && (pattern[pi] == '?' || + char.ToUpperInvariant(pattern[pi]) == char.ToUpperInvariant(text[ti]))) + { + ti++; + pi++; + } + else if (pi < pattern.Length && pattern[pi] == '*') + { + star = pi++; + mark = ti; + } + else if (star >= 0) + { + pi = star + 1; + ti = ++mark; + } + else + { + return false; + } + } + while (pi < pattern.Length && pattern[pi] == '*') pi++; + return pi == pattern.Length; + } +} diff --git a/src/RvtIO/Sheets/SheetRecord.cs b/src/RvtIO/Sheets/SheetRecord.cs index e5b8400b..9976d047 100644 --- a/src/RvtIO/Sheets/SheetRecord.cs +++ b/src/RvtIO/Sheets/SheetRecord.cs @@ -16,7 +16,9 @@ internal SheetRecord( string? checkedBy, string? approvedBy, IReadOnlyList viewportIds, - IReadOnlyList ownedElementIds) + IReadOnlyList ownedElementIds, + IReadOnlyDictionary? parameters = null, + IReadOnlyCollection? yesNoParameters = null) { ElementId = elementId; Number = number; @@ -29,6 +31,10 @@ internal SheetRecord( ApprovedBy = approvedBy; ViewportIds = viewportIds; OwnedElementIds = ownedElementIds; + Parameters = parameters ?? new Dictionary(); + // Names compare case-insensitively everywhere else (Lookup, the filter contract), so a plain + // array or list of Yes/No names must not turn case-sensitive here. + YesNoParameters = new HashSet(yesNoParameters ?? [], StringComparer.OrdinalIgnoreCase); } /// The element id of the sheet. @@ -68,4 +74,16 @@ internal SheetRecord( /// view-specific graphics and other content placed on the sheet), ascending. Empty when the file decoded no owner /// view for its content. public IReadOnlyList OwnedElementIds { get; } + + /// The sheet's project and shared parameters as display strings, keyed by display name + /// (the Definition.Name Revit shows). Only text and whole numbers are included; numbers with + /// units are left out until their units are read. A Yes/No parameter reads as Yes/No. + /// The 8 core fields above are not repeated here. + public IReadOnlyDictionary Parameters { get; } + + /// The display names of the entries of (and the + /// Appears In Sheet List value) that are Yes/No parameters. Only for these do the + /// true/false/1/0 spellings match Yes/No; every other + /// field compares literally. + public IReadOnlyCollection YesNoParameters { get; } } diff --git a/tests/RvtIO.Tests/SheetFilterTests.cs b/tests/RvtIO.Tests/SheetFilterTests.cs new file mode 100644 index 00000000..05aba44d --- /dev/null +++ b/tests/RvtIO.Tests/SheetFilterTests.cs @@ -0,0 +1,145 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Sheets; +using Xunit; + +namespace RvtIO.Tests; + +/// Sheet --where filters and extra parameters (ported from rvt-prt's list --params/--where). +public class SheetFilterTests +{ + private static void Add(Element element, BuiltInParameter id, string name, StorageType storage, object value) => + element.Parameters.Add(BipHelpers.MakeBipParam((int)id, name, storage, value)); + + private static Element Sheet(int id, string? number, string? group = null, int scheduled = 1) + { + var sheet = new Element { Id = id, CategoryId = -2003100 }; + Add(sheet, BuiltInParameter.SHEET_NUMBER, "SHEET_NUMBER", StorageType.String, number ?? string.Empty); + Add(sheet, BuiltInParameter.SHEET_NAME, "SHEET_NAME", StorageType.String, "Plan"); + Add(sheet, BuiltInParameter.SHEET_SCHEDULED, "SHEET_SCHEDULED", StorageType.Integer, scheduled); + if (group != null) + sheet.Parameters.Add(BipHelpers.MakeBipParam(9001, "Sheet Group", StorageType.String, group)); + return sheet; + } + + private static SheetRecord Record(Element element) => + SheetCatalog.Extract(new RevitFileInfo { Elements = [element] }).Sheets[0]; + + [Fact] + public void ExtraParameters_HoldProjectParamsAndScheduledAsYesNo() + { + var record = Record(Sheet(100, "A101", "Architectural")); + + Assert.Equal("Architectural", record.Parameters["Sheet Group"]); + Assert.Equal("Yes", record.Parameters["Appears In Sheet List"]); + } + + [Fact] + public void ExtraParameters_SkipsBuiltinNonSheetParams() + { + var sheet = Sheet(100, "A101"); + sheet.Parameters.Add(BipHelpers.MakeBipParam(-1140362, "ELEM_CATEGORY_PARAM", StorageType.Integer, -2003100)); + var record = SheetCatalog.Extract(new RevitFileInfo { Elements = [sheet] }).Sheets[0]; + + Assert.DoesNotContain("ELEM_CATEGORY_PARAM", record.Parameters.Keys); + } + + [Fact] + public void Filter_EqualsSupportsWildcardsCaseInsensitively() + { + var record = Record(Sheet(100, "A101", "Architectural")); + + Assert.True(SheetFilter.TryParse("Sheet Number=A1*", out _)!.Matches(record)); + Assert.True(SheetFilter.TryParse("sheet group=architectural", out _)!.Matches(record)); + Assert.False(SheetFilter.TryParse("Sheet Number=A2*", out _)!.Matches(record)); + } + + [Fact] + public void Filter_NotEqualsAndContains() + { + var record = Record(Sheet(100, "A101", "Architectural")); + + Assert.True(SheetFilter.TryParse("Sheet Number!=A102", out _)!.Matches(record)); + Assert.True(SheetFilter.TryParse("Sheet Group~tect", out _)!.Matches(record)); + Assert.False(SheetFilter.TryParse("Sheet Group~mech", out _)!.Matches(record)); + } + + [Fact] + public void Filter_YesNoAliases() + { + var record = Record(Sheet(100, "A101")); + + Assert.True(SheetFilter.TryParse("Appears In Sheet List=true", out _)!.Matches(record)); + Assert.True(SheetFilter.TryParse("Appears In Sheet List=1", out _)!.Matches(record)); + Assert.False(SheetFilter.TryParse("Appears In Sheet List=No", out _)!.Matches(record)); + } + + [Fact] + public void Filter_YesNoAliasesApplyOnlyToYesNoParameters() + { + // A sheet whose number is "1", name is "true" and text revision is "0": ordinary text fields + // compare literally, so no Yes/No spelling selects them. + var sheet = new Element { Id = 100, CategoryId = -2003100 }; + Add(sheet, BuiltInParameter.SHEET_NUMBER, "SHEET_NUMBER", StorageType.String, "1"); + Add(sheet, BuiltInParameter.SHEET_NAME, "SHEET_NAME", StorageType.String, "true"); + Add(sheet, BuiltInParameter.SHEET_SCHEDULED, "SHEET_SCHEDULED", StorageType.Integer, 0); + sheet.Parameters.Add(BipHelpers.MakeBipParam(9002, "Revision", StorageType.String, "0")); + var record = Record(sheet); + + Assert.False(SheetFilter.TryParse("Sheet Number=true", out _)!.Matches(record)); + Assert.False(SheetFilter.TryParse("Sheet Number=Yes", out _)!.Matches(record)); + Assert.False(SheetFilter.TryParse("Sheet Name=1", out _)!.Matches(record)); + Assert.False(SheetFilter.TryParse("Revision=No", out _)!.Matches(record)); + Assert.True(SheetFilter.TryParse("Sheet Number!=true", out _)!.Matches(record)); + // The Yes/No field itself still takes aliases. + Assert.True(SheetFilter.TryParse("Appears In Sheet List=false", out _)!.Matches(record)); + Assert.True(SheetFilter.TryParse("Appears In Sheet List=0", out _)!.Matches(record)); + } + + [Fact] + public void ExtraParameters_BoolSpecParamReadsYesNoAndMatchesAliases() + { + // A shared Yes/No parameter (boolean Forge spec) with value 1. + var sheet = Sheet(100, "A101"); + var yesNo = BipHelpers.MakeBipParam(9101, "Issued", StorageType.Integer, 1); + yesNo.SpecType = "autodesk.spec:spec.bool-1.0.0"; + sheet.Parameters.Add(yesNo); + sheet.Parameters.Add(BipHelpers.MakeBipParam(9102, "Copies", StorageType.Integer, 1)); + var record = Record(sheet); + + Assert.Equal("Yes", record.Parameters["Issued"]); + Assert.Contains("Issued", record.YesNoParameters); + Assert.Equal("1", record.Parameters["Copies"]); + Assert.DoesNotContain("Copies", record.YesNoParameters); + Assert.True(SheetFilter.TryParse("Issued=true", out _)!.Matches(record)); + Assert.True(SheetFilter.TryParse("Issued=Yes", out _)!.Matches(record)); + Assert.False(SheetFilter.TryParse("Copies=Yes", out _)!.Matches(record)); + Assert.True(SheetFilter.TryParse("Copies=1", out _)!.Matches(record)); + } + + [Fact] + public void Filter_YesNoNameMatchesCaseInsensitivelyWithPlainArray() + { + // The record path: Yes/No names handed over as a plain case-sensitive array still match + // a filter naming the parameter in another case (Lookup already ignores case). + var record = new SheetRecord( + 2, "A2", "Example", null, null, null, null, null, null, + [], [], + new Dictionary { ["Issued"] = "Yes" }, + ["Issued"]); + + Assert.True(SheetFilter.TryParse("Issued=true", out _)!.Matches(record)); + Assert.True(SheetFilter.TryParse("issued=true", out _)!.Matches(record)); + Assert.True(SheetFilter.TryParse("ISSUED=1", out _)!.Matches(record)); + Assert.True(SheetFilter.TryParse("issued=Yes", out _)!.Matches(record)); + Assert.False(SheetFilter.TryParse("issued=No", out _)!.Matches(record)); + } + + [Fact] + public void Filter_BadTextFails() + { + Assert.Null(SheetFilter.TryParse("no-operator-here", out string? error)); + Assert.False(string.IsNullOrWhiteSpace(error)); + } +}