diff --git a/docs/printing.md b/docs/printing.md index d4b43571..f600eb4a 100644 --- a/docs/printing.md +++ b/docs/printing.md @@ -21,8 +21,15 @@ rvtio print project.rvt plan.svg --level 355 --scale 100 rvtio print project.rvt plan.pdf --level "Уровень 1" --scale 200 --paper A3 ``` -`--level` takes the element id or the exact level name (case-insensitive). Without it the level with the most walls and -columns is printed. `--scale` is the view scale denominator: 100 prints 1:100, one model metre to ten millimetres of +`--level` takes the document-local element id, the original 64-bit Revit element id (or `source:` / `native:`), +or the exact level name (case-insensitive). `--view` and `--sheet` accept the same local and 64-bit native ID +selectors as well as view names / sheet numbers. When an element in a Revit 2024+ file was renumbered from a wide +64-bit native ID into a distinct 32-bit document-local ID, `--list-levels`, `--list-views`, and `--list-sheets` keep the +local ID in the first column for compatibility and append `source=` with the lossless decimal 64-bit Revit ID +(the same value exposed by `PlanLevel.SourceElementId`, `PlanView.SourceElementId`, `ElevationView.SourceElementId`, +`PrintableSheet.SourceElementId`, and `ComposedSheet.SourceElementId`). In `--list-views` a plan whose level was +renumbered also appends `level-source=` (`PlanView.SourceLevelId`); the `level ` column is unchanged. +Without `--level`, the level with the most walls and columns is printed. `--scale` is the view scale denominator: 100 prints 1:100, one model metre to ten millimetres of paper. `--paper` takes A4, A3, A2, A1 or A0; without it the smallest landscape paper that holds the drawing at the scale is chosen, and a drawing larger than A0 is scaled down to fit. Exit codes: 0 written, 1 usage error or an unwritable output path (also a level or view that is not printable), 2 the file cannot be read, 3 a reader limit cut a stream, 4 diff --git a/docs/public-api.md b/docs/public-api.md index cf900bef..7fb19d05 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -159,8 +159,8 @@ No compact JSON override is implemented. | 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`, `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. | +| `SheetRecord` | A sheet: `ElementId`, `SourceElementId`, `OwnedElementSourceIds`, `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`, `SourceElementId`, `SheetId`, `SourceSheetId` 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. | @@ -172,16 +172,16 @@ See [sheets and viewports](sheets.md) for what is decoded, what the limits are a |---|---| | `PlanPrinter` | `Levels(document)` lists the printable levels. `Render(document, levelId, scale, options)` returns a `PdfDocument` with the plan of one level, including walls with their stored width, column footprints, and clipped grids. `RenderSvg(document, ...)` returns the same level plan as SVG text. `WriteSvg(document, output, ...)` writes it as UTF-8 to a stream. | | `PlanPrintOptions` | `PaperSize` (null picks the smallest paper that holds the drawing), `MarginMillimetres`, `FallbackWallWidthMillimetres`, `DrawFrame`. | -| `PlanLevel`, `PlanView` | A printable level (id, name, elevation) and a printable plan view (id, name, level, scale). | +| `PlanLevel`, `PlanView` | A printable level (id, name, elevation) and a printable plan view (id, name, level, scale); `SourceElementId` and `PlanView.SourceLevelId` hold renumbered 64-bit Revit ids. | | `ViewPrinter` | `Render(document, viewIds, options)` prints views into one PDF document, one page per view: a plan, an elevation or a section (`PlanPrinter.Views`, `ElevationPrinter.Views`), a 3D view (an isometric massing page) and a rendering (its image page). `OtherViews(document)` lists the 3D views and the renderings. | | `ElevationPrinter` | `Views(document)` lists the elevations and the building sections (North, South, East, West, Section, Stair Section) with their scale; `Collect(document, direction, stairsOnly, planeView)` projects the model faces on the plane of the view when the reader decoded it (a section is cut at that plane: the geometry in front of it is removed and the crossing polygons are clipped) or on the plane of the direction taken from the name; a stair section projects the stairs alone. `DrawContent` writes them. | -| `ElevationView` | An elevation view: id, name, direction (north, south, east, west, section, iso) and scale. | +| `ElevationView` | An elevation view: id, name, direction (north, south, east, west, section, iso), scale and `SourceElementId`. | | `SheetComposer` | `Sheets(document)` lists the numbered sheets with the page their title block spans; `Render(document, sheetId, options)` and `RenderSheets` compose pages: each placed viewport draws its plan at the stored offset and view scale, labelled with the view name and scale, and the sheet's own text notes are written. | | `SheetComposeOptions` | `PaperSize` (null takes the title block extent, snapped to A4-A0), `DrawViewLabels`, `ViewMarginMillimetres`. | -| `ComposedSheet` | A composed sheet: id, number, name, page, placed viewport count, text count. | +| `ComposedSheet` | A composed sheet: id, number, name, page, placed viewport count, text count and `SourceElementId`. | | `SheetPrinter` | `Sheets(document)` lists the sheets with page-sized decoded linework; `Render(document, sheetId, options)` and `RenderSheets` print one page per sheet from the lines the sheet owns, on the paper the linework spans. | | `SheetPrintOptions` | `PaperSize` (null uses the linework extent, snapped to A4-A0), `MarginMillimetres`, `PaperToleranceMillimetres`, `DrawSheetFields`. | -| `PrintableSheet` | A printable sheet: id, number, name, linework extent, curve and text counts. | +| `PrintableSheet` | A printable sheet: id, number, name, linework extent, curve and text counts, and `SourceElementId`. | See [printing a plan](printing.md) for what is drawn, what is not, and the roadmap to sheet printing. diff --git a/docs/sheets.md b/docs/sheets.md index 42870ec0..1b92d438 100644 --- a/docs/sheets.md +++ b/docs/sheets.md @@ -74,6 +74,8 @@ owner, when the stored owner is not a view, or when it is the element itself. | Field | Source | |---|---| +| `SheetRecord.ElementId` | document-local 32-bit element id of the sheet | +| `SheetRecord.SourceElementId` | lossless decimal string of the original 64-bit Revit element ID when the file renumbered it to fit `ElementId` (omitted from JSON when unchanged) | | `SheetRecord.Number` | `Sheet Number` parameter (`SHEET_NUMBER`) | | `SheetRecord.Name` | `Sheet Name` parameter (`SHEET_NAME`) | | `SheetRecord.IssueDate` | `Sheet Issue Date` parameter (`SHEET_ISSUE_DATE`) | @@ -81,10 +83,24 @@ 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.OwnedElementSourceIds` | original 64-bit Revit element IDs, as decimal strings keyed by the local id, of the renumbered entries of `OwnedElementIds` (omitted from JSON when none was; not a CSV column) | | `SheetRecord.Parameters` | text and whole-number project/shared parameters; `SHEET_SCHEDULED` as `Appears In Sheet List` | -| `ViewportRecord.SheetId` | the referenced sheet | +| `ViewportRecord.ElementId` | document-local 32-bit element id of the viewport | +| `ViewportRecord.SourceElementId` | lossless decimal string of the viewport's original 64-bit Revit element ID when renumbered | +| `ViewportRecord.SheetId` | the referenced sheet's document-local 32-bit element id | +| `ViewportRecord.SourceSheetId` | lossless decimal string of the referenced sheet's original 64-bit Revit element ID when renumbered | | `ViewportRecord.DetailNumber` | `Detail Number` parameter (`VIEWPORT_DETAIL_NUMBER`) | +### Local IDs vs. 64-bit Revit element IDs + +Revit 2024 and newer files can assign 64-bit element IDs that exceed 32-bit `int.MaxValue`. When `RvtIO` reads such +a file into a document-local `int` table, each wide element gets a distinct 32-bit local `ElementId` (used for internal +links such as `ViewportIds`, `OwnedElementIds`, and `ViewportRecord.SheetId`), while its original 64-bit Revit ID is +preserved in `SourceElementId` (`ViewportRecord.SourceSheetId` and, for owned elements, +`SheetRecord.OwnedElementSourceIds`) as lossless decimal text so JSON and CSV consumers never lose precision. In CSV +output (`--csv`), the last column, `SourceElementId`, holds the original 64-bit decimal ID when renumbered and is empty +when the ID was unchanged. + Sheets are ordered by number (ordinal, case-insensitive; a sheet without a number keeps document order behind the numbered sheets) and then by element id. Viewports, viewport ids and owned element ids are ordered by id. diff --git a/src/RvtIO.Cli/PrintCommand.cs b/src/RvtIO.Cli/PrintCommand.cs index 00832f57..bdfa03fd 100644 --- a/src/RvtIO.Cli/PrintCommand.cs +++ b/src/RvtIO.Cli/PrintCommand.cs @@ -149,49 +149,17 @@ IReadOnlyList ListedComposed() => whereSheets == null ? composed : composed.Where(sheet => whereSheets.Contains(sheet.SheetId)).ToList(); if (listSheets) { - IReadOnlyList listedComposed = ListedComposed(); - IReadOnlyList listedSheets = ListedSheets(); - if (listedComposed.Count > 0) - { - foreach (ComposedSheet sheet in listedComposed) - output.WriteLine($"{sheet.SheetId}\t{sheet.Number}\t{sheet.Name ?? ""}\t" - + $"{sheet.Page.WidthMillimetres:0}x{sheet.Page.HeightMillimetres:0} mm\t" - + $"{sheet.ViewportCount} views\t{sheet.TextCount} texts"); - } - else - { - foreach (PrintableSheet sheet in listedSheets) - output.WriteLine($"{sheet.SheetId}\t{sheet.Number ?? ""}\t{sheet.Name ?? ""}\t" - + $"{sheet.WidthMillimetres:0}x{sheet.HeightMillimetres:0} mm\t{sheet.CurveCount} curves\t{sheet.TextCount} texts"); - if (listedSheets.Count == 0) error.WriteLine("No sheet with decoded linework was found."); - } + WriteListedSheets(ListedSheets(), ListedComposed(), output, error); return RvtExitCodes.Success; } if (listLevels) { - foreach (PlanLevel level in levels) - { - string elevation = level.ElevationFeet is double feet - ? (feet * 304.8).ToString("0", CultureInfo.InvariantCulture) + " mm" : "elevation not decoded"; - output.WriteLine($"{level.LevelId}\t{level.Name ?? "(unnamed)"}\t{elevation}"); - } + WriteListedLevels(levels, output); if (!listViews) return RvtExitCodes.Success; } if (listViews) { - foreach (PlanView view in views) - output.WriteLine($"{view.ViewId}\t{view.Name}\t1:{view.Scale}\tlevel {view.LevelId}\tplan"); - foreach (ElevationView view in elevations) - output.WriteLine($"{view.ViewId}\t{view.Name}\t1:{view.Scale}\t{view.Direction}\televation"); - foreach (RvtIO.Model.Element other in ViewPrinter.OtherViews(document)) - { - string kind = other.RootClassName == "DBViewRendering" ? "rendering" : "3d"; - int otherScale = other.LookupParameter(RvtIO.BuiltIns.BuiltInParameter.VIEW_SCALE)?.Value is int value - ? value : 0; - output.WriteLine($"{other.Id}\t{other.Name}\t1:{otherScale}\t-\t{kind}"); - } - if (views.Count == 0 && elevations.Count == 0 && ViewPrinter.OtherViews(document).Count == 0) - error.WriteLine("No printable view was found."); + WriteListedViews(document, views, elevations, output, error); return RvtExitCodes.Success; } @@ -283,20 +251,7 @@ IReadOnlyList ListedComposed() => var viewIds = new List(); foreach (string text in viewTexts) { - int? resolved = ResolveView(text, views, elevations); - if (resolved == null) - { - // A 3D view or a rendering is a printable view too. - foreach (RvtIO.Model.Element other in ViewPrinter.OtherViews(document)) - { - if (int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out int otherId) - && otherId == other.Id) - resolved = other.Id; - else if (string.Equals(other.Name, text, StringComparison.OrdinalIgnoreCase)) - resolved = other.Id; - if (resolved != null) break; - } - } + int? resolved = ResolveView(text, views, elevations, ViewPrinter.OtherViews(document), document.RawData); if (resolved == null) { error.WriteLine($"No printable view is named or numbered '{text}'. --list-views shows them."); @@ -351,20 +306,107 @@ IReadOnlyList ListedComposed() => } } - /// The id of the printable view a text names: a plan or an elevation, by id or by exact name. - private static int? ResolveView(string text, IReadOnlyList views, IReadOnlyList elevations) + internal static void WriteListedSheets( + IReadOnlyList listedSheets, + IReadOnlyList listedComposed, + TextWriter output, + TextWriter error) + { + if (listedComposed.Count > 0) + { + foreach (ComposedSheet sheet in listedComposed) + { + string sourceSuffix = sheet.SourceElementId is { } sourceId ? $"\tsource={sourceId}" : ""; + output.WriteLine($"{sheet.SheetId}\t{sheet.Number}\t{sheet.Name ?? ""}\t" + + $"{sheet.Page.WidthMillimetres:0}x{sheet.Page.HeightMillimetres:0} mm\t" + + $"{sheet.ViewportCount} views\t{sheet.TextCount} texts{sourceSuffix}"); + } + } + else + { + foreach (PrintableSheet sheet in listedSheets) + { + string sourceSuffix = sheet.SourceElementId is { } sourceId ? $"\tsource={sourceId}" : ""; + output.WriteLine($"{sheet.SheetId}\t{sheet.Number ?? ""}\t{sheet.Name ?? ""}\t" + + $"{sheet.WidthMillimetres:0}x{sheet.HeightMillimetres:0} mm\t{sheet.CurveCount} curves\t{sheet.TextCount} texts{sourceSuffix}"); + } + if (listedSheets.Count == 0) error.WriteLine("No sheet with decoded linework was found."); + } + } + + internal static void WriteListedLevels(IReadOnlyList levels, TextWriter output) + { + foreach (PlanLevel level in levels) + { + string elevation = level.ElevationFeet is double feet + ? (feet * 304.8).ToString("0", CultureInfo.InvariantCulture) + " mm" : "elevation not decoded"; + string sourceSuffix = level.SourceElementId is { } sourceId ? $"\tsource={sourceId}" : ""; + output.WriteLine($"{level.LevelId}\t{level.Name ?? "(unnamed)"}\t{elevation}{sourceSuffix}"); + } + } + + internal static void WriteListedViews( + RvtDocument document, + IReadOnlyList views, + IReadOnlyList elevations, + TextWriter output, + TextWriter error) + { + foreach (PlanView view in views) + { + // New fields go after the existing ones, which keep their text. + string levelSuffix = view.SourceLevelId is { } sourceLevelId ? $"\tlevel-source={sourceLevelId}" : ""; + string sourceSuffix = view.SourceElementId is { } sourceId ? $"\tsource={sourceId}" : ""; + output.WriteLine($"{view.ViewId}\t{view.Name}\t1:{view.Scale}\tlevel {view.LevelId}\tplan{sourceSuffix}{levelSuffix}"); + } + foreach (ElevationView view in elevations) + { + string sourceSuffix = view.SourceElementId is { } sourceId ? $"\tsource={sourceId}" : ""; + output.WriteLine($"{view.ViewId}\t{view.Name}\t1:{view.Scale}\t{view.Direction}\televation{sourceSuffix}"); + } + IReadOnlyList otherViews = ViewPrinter.OtherViews(document); + foreach (RvtIO.Model.Element other in otherViews) + { + string kind = other.RootClassName == "DBViewRendering" ? "rendering" : "3d"; + int otherScale = other.LookupParameter(RvtIO.BuiltIns.BuiltInParameter.VIEW_SCALE)?.Value is int value + ? value : 0; + string? otherSourceId = RvtIO.Sheets.SheetCatalog.SourceIdText(document.RawData, other.Id, other); + string sourceSuffix = otherSourceId is { } sourceId ? $"\tsource={sourceId}" : ""; + output.WriteLine($"{other.Id}\t{other.Name}\t1:{otherScale}\t-\t{kind}{sourceSuffix}"); + } + if (views.Count == 0 && elevations.Count == 0 && otherViews.Count == 0) + error.WriteLine("No printable view was found."); + } + + /// The id of the printable view a text names: a plan, elevation, 3D view, or rendering, by local id, native 64-bit id, or exact name. + internal static int? ResolveView( + string text, + IReadOnlyList views, + IReadOnlyList elevations, + IReadOnlyList? otherViews = null, + RvtIO.Model.RevitFileInfo? rawData = null) { - bool byId = int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out int id); foreach (PlanView view in views) { - if ((byId && id == view.ViewId) || string.Equals(view.Name, text, StringComparison.OrdinalIgnoreCase)) + if (MatchesId(text, view.ViewId, view.SourceElementId) || string.Equals(view.Name, text, StringComparison.OrdinalIgnoreCase)) return view.ViewId; } foreach (ElevationView view in elevations) { - if ((byId && id == view.ViewId) || string.Equals(view.Name, text, StringComparison.OrdinalIgnoreCase)) + if (MatchesId(text, view.ViewId, view.SourceElementId) || string.Equals(view.Name, text, StringComparison.OrdinalIgnoreCase)) return view.ViewId; } + if (otherViews != null) + { + foreach (RvtIO.Model.Element other in otherViews) + { + string? otherSourceId = rawData != null + ? RvtIO.Sheets.SheetCatalog.SourceIdText(rawData, other.Id, other) + : other.SourceElementId; + if (MatchesId(text, other.Id, otherSourceId) || string.Equals(other.Name, text, StringComparison.OrdinalIgnoreCase)) + return other.Id; + } + } return null; } @@ -400,9 +442,8 @@ internal static ExplicitSheetSelection SelectExplicitSheets( ComposedSheet? composedMatch = null; foreach (ComposedSheet sheet in composed) { - if (int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out int id) && id == sheet.SheetId) - composedMatch = sheet; - else if (string.Equals(sheet.Number, text, StringComparison.OrdinalIgnoreCase)) + if (MatchesId(text, sheet.SheetId, sheet.SourceElementId) + || string.Equals(sheet.Number, text, StringComparison.OrdinalIgnoreCase)) composedMatch = sheet; if (composedMatch != null) break; } @@ -414,9 +455,8 @@ internal static ExplicitSheetSelection SelectExplicitSheets( PrintableSheet? match = null; foreach (PrintableSheet sheet in sheets) { - if (int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out int id) && id == sheet.SheetId) - match = sheet; - else if (string.Equals(sheet.Number, text, StringComparison.OrdinalIgnoreCase)) + if (MatchesId(text, sheet.SheetId, sheet.SourceElementId) + || string.Equals(sheet.Number, text, StringComparison.OrdinalIgnoreCase)) match = sheet; if (match != null) break; } @@ -431,18 +471,43 @@ internal static ExplicitSheetSelection SelectExplicitSheets( return new ExplicitSheetSelection(sheetIds, composedIds, null); } - private static int? ResolveLevelId(string? levelText, IReadOnlyList levels) + internal static int? ResolveLevelId(string? levelText, IReadOnlyList levels) { if (levelText == null) return null; - bool byId = int.TryParse(levelText, NumberStyles.None, CultureInfo.InvariantCulture, out int id); foreach (PlanLevel level in levels) { - if ((byId && id == level.LevelId) || string.Equals(level.Name, levelText, StringComparison.OrdinalIgnoreCase)) + if (MatchesId(levelText, level.LevelId, level.SourceElementId) + || string.Equals(level.Name, levelText, StringComparison.OrdinalIgnoreCase)) return level.LevelId; } return null; } + internal static bool MatchesId(string selector, int localId, string? sourceElementId) + { + const string SourcePrefix = "source:"; + const string NativePrefix = "native:"; + if (selector.StartsWith(SourcePrefix, StringComparison.OrdinalIgnoreCase)) + return MatchesExplicitSource(selector.AsSpan(SourcePrefix.Length), localId, sourceElementId); + if (selector.StartsWith(NativePrefix, StringComparison.OrdinalIgnoreCase)) + return MatchesExplicitSource(selector.AsSpan(NativePrefix.Length), localId, sourceElementId); + + if (!long.TryParse(selector, NumberStyles.None, CultureInfo.InvariantCulture, out long parsed)) + return false; + if (sourceElementId != null && string.Equals(sourceElementId, selector, StringComparison.Ordinal)) + return true; + return parsed <= int.MaxValue && (int)parsed == localId; + } + + private static bool MatchesExplicitSource(ReadOnlySpan idSpan, int localId, string? sourceElementId) + { + if (!long.TryParse(idSpan, NumberStyles.None, CultureInfo.InvariantCulture, out long parsed)) + return false; + return sourceElementId != null + ? long.TryParse(sourceElementId, NumberStyles.None, CultureInfo.InvariantCulture, out long sourceId) && sourceId == parsed + : parsed <= int.MaxValue && (int)parsed == localId; + } + private static int Usage(TextWriter error, string problem) { error.WriteLine(problem); diff --git a/src/RvtIO.Cli/SheetsCommand.cs b/src/RvtIO.Cli/SheetsCommand.cs index 97f73a8a..171334b0 100644 --- a/src/RvtIO.Cli/SheetsCommand.cs +++ b/src/RvtIO.Cli/SheetsCommand.cs @@ -152,7 +152,7 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) } } - string payload = csv ? ToCsv(catalog) : JsonSerializer.Serialize(catalog, Options); + string payload = csv ? ToCsv(catalog) : ToJson(catalog); if (outputPath == null) { output.WriteLine(payload); @@ -183,7 +183,9 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) return RvtExitCodes.Success; } - private static string ToCsv(SheetCatalog catalog) + internal static string ToJson(SheetCatalog catalog) => JsonSerializer.Serialize(catalog, Options); + + internal static string ToCsv(SheetCatalog catalog) { var extra = new SortedSet(StringComparer.OrdinalIgnoreCase); foreach (var sheet in catalog.Sheets) @@ -192,7 +194,7 @@ private static string ToCsv(SheetCatalog catalog) var lines = new List { string.Join(",", new[] { "ElementId", "Number", "Name", "IssueDate", "Scale", "DrawnBy", - "DesignedBy", "CheckedBy", "ApprovedBy" }.Concat(extra).Select(EscapeCsv)), + "DesignedBy", "CheckedBy", "ApprovedBy" }.Concat(extra).Append("SourceElementId").Select(EscapeCsv)), }; foreach (var sheet in catalog.Sheets) { @@ -203,6 +205,7 @@ private static string ToCsv(SheetCatalog catalog) }; foreach (string key in extra) fields.Add(sheet.Parameters.TryGetValue(key, out var value) ? value : null); + fields.Add(sheet.SourceElementId); lines.Add(string.Join(",", fields.Select(EscapeCsv))); } return string.Join(Environment.NewLine, lines); diff --git a/src/RvtIO/Print/ElevationPrinter.cs b/src/RvtIO/Print/ElevationPrinter.cs index b4114fd3..acdc308d 100644 --- a/src/RvtIO/Print/ElevationPrinter.cs +++ b/src/RvtIO/Print/ElevationPrinter.cs @@ -10,7 +10,12 @@ namespace RvtIO.Print; /// The view name. /// The direction the view looks at: north, south, east or west. /// The view scale denominator. -public sealed record ElevationView(int ViewId, string Name, string Direction, int Scale); +public sealed record ElevationView(int ViewId, string Name, string Direction, int Scale) +{ + /// Lossless decimal native 64-bit Revit element ID when the file renumbered it to fit ; null when unchanged. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public string? SourceElementId { get; init; } +} /// /// Prints an elevation from the 3D geometry the reader decodes: every planar face of the model (walls, floors, roofs, @@ -60,7 +65,10 @@ public static IReadOnlyList Views(RvtDocument document) if (section && (scale == 0 || scale < 100) && !name.Contains("stair", StringComparison.OrdinalIgnoreCase) && !(planeDecoded && placed)) continue; - views.Add(new ElevationView(element.Id, name, direction, scale)); + views.Add(new ElevationView(element.Id, name, direction, scale) + { + SourceElementId = RvtIO.Sheets.SheetCatalog.SourceIdText(document.RawData, element.Id, element), + }); } views.Sort((left, right) => string.CompareOrdinal(left.Name, right.Name)); return views; diff --git a/src/RvtIO/Print/PlanPrinter.cs b/src/RvtIO/Print/PlanPrinter.cs index 9c1a09f9..69cac818 100644 --- a/src/RvtIO/Print/PlanPrinter.cs +++ b/src/RvtIO/Print/PlanPrinter.cs @@ -25,7 +25,12 @@ public sealed class PlanPrintOptions /// The element id of the level. /// The level name, when the reader decoded one. /// The stored elevation in feet, null when the reader did not decode it. -public sealed record PlanLevel(int LevelId, string? Name, double? ElevationFeet); +public sealed record PlanLevel(int LevelId, string? Name, double? ElevationFeet) +{ + /// Lossless decimal native 64-bit Revit element ID when the file renumbered it to fit ; null when unchanged. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public string? SourceElementId { get; init; } +} /// A view a plan can be printed for: a named plan view whose name or stored elevation matches a printable /// level. The scale is the view's own view scale. @@ -33,7 +38,16 @@ public sealed record PlanLevel(int LevelId, string? Name, double? ElevationFeet) /// The view name. /// The level the plan of the view is drawn from. /// The view scale denominator, 100 for 1:100. -public sealed record PlanView(int ViewId, string Name, int LevelId, int Scale); +public sealed record PlanView(int ViewId, string Name, int LevelId, int Scale) +{ + /// Lossless decimal native 64-bit Revit element ID when the file renumbered it to fit ; null when unchanged. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public string? SourceElementId { get; init; } + + /// Lossless decimal native 64-bit Revit element ID of the plan's level when renumbered to fit ; null when unchanged. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public string? SourceLevelId { get; init; } +} /// /// Prints plans to PDF pages from the data the reader decodes: walls as their location line with the stored thickness, @@ -83,7 +97,10 @@ public static IReadOnlyList Levels(RvtDocument document) { if (!byId.TryGetValue(levelId, out var level)) continue; double? elevation = level.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is double value ? value : null; - levels.Add(new PlanLevel(levelId, level.Name, elevation)); + levels.Add(new PlanLevel(levelId, level.Name, elevation) + { + SourceElementId = RvtIO.Sheets.SheetCatalog.SourceIdText(document.RawData, levelId, level), + }); } levels.Sort((left, right) => { @@ -108,9 +125,15 @@ public static IReadOnlyList Views(RvtDocument document) if (element.LookupParameter(BuiltInParameter.VIEW_NAME)?.Value is not string name || name.Length == 0) continue; int? levelId = null; + string? sourceLevelId = null; foreach (var level in levels) { - if (string.Equals(level.Name, name, StringComparison.OrdinalIgnoreCase)) { levelId = level.LevelId; break; } + if (string.Equals(level.Name, name, StringComparison.OrdinalIgnoreCase)) + { + levelId = level.LevelId; + sourceLevelId = level.SourceElementId; + break; + } } // The elevation fallback is for a level plan named differently from its level ("Level 1 - Plan"); a site // view, a section or a 3D view shares the level elevation but is not the plan of that level. @@ -122,6 +145,7 @@ public static IReadOnlyList Views(RvtDocument document) if (level.ElevationFeet is double levelElevation && Math.Abs(levelElevation - elevation) < 1e-6) { levelId = level.LevelId; + sourceLevelId = level.SourceElementId; break; } } @@ -131,7 +155,11 @@ public static IReadOnlyList Views(RvtDocument document) // A detail view of a plan is also a DBViewPlan and carries the plan's name; it is drawn at 1:2 to 1:24 and // is not the plan of the level. if (scale < 50) continue; - views.Add(new PlanView(element.Id, name, levelId.Value, scale)); + views.Add(new PlanView(element.Id, name, levelId.Value, scale) + { + SourceElementId = RvtIO.Sheets.SheetCatalog.SourceIdText(document.RawData, element.Id, element), + SourceLevelId = sourceLevelId, + }); } views.Sort((left, right) => { diff --git a/src/RvtIO/Print/SheetComposer.cs b/src/RvtIO/Print/SheetComposer.cs index 42ee628a..215c31ea 100644 --- a/src/RvtIO/Print/SheetComposer.cs +++ b/src/RvtIO/Print/SheetComposer.cs @@ -37,7 +37,12 @@ public sealed class SheetComposeOptions /// The number of placed viewports. /// The number of text notes the sheet owns. public sealed record ComposedSheet(int SheetId, string? Number, string? Name, PdfPageSize Page, int ViewportCount, - int TextCount); + int TextCount) +{ + /// Lossless decimal native 64-bit Revit element ID when the file renumbered it to fit ; null when unchanged. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public string? SourceElementId { get; init; } +} /// /// Composes a sheet page the way Revit prints it: the page is the size the title block spans, every placed viewport @@ -72,7 +77,10 @@ public static IReadOnlyList Sheets(RvtDocument document) sheets.Add(new ComposedSheet(sheet.Id, number, sheet.LookupParameter(BuiltInParameter.SHEET_NAME)?.Value as string, page, viewports.TryGetValue(sheet.Id, out int vp) ? vp : 0, - texts.TryGetValue(sheet.Id, out int tx) ? tx : 0)); + texts.TryGetValue(sheet.Id, out int tx) ? tx : 0) + { + SourceElementId = RvtIO.Sheets.SheetCatalog.SourceIdText(document.RawData, sheet.Id, sheet), + }); } sheets.Sort((left, right) => { diff --git a/src/RvtIO/Print/SheetPrinter.cs b/src/RvtIO/Print/SheetPrinter.cs index 4b603b85..70657f6c 100644 --- a/src/RvtIO/Print/SheetPrinter.cs +++ b/src/RvtIO/Print/SheetPrinter.cs @@ -32,7 +32,12 @@ public sealed class SheetPrintOptions /// The number of location curves of the sheet's own elements. /// The number of text notes of the sheet (their text is not decoded). public sealed record PrintableSheet(int SheetId, string? Number, string? Name, double WidthMillimetres, - double HeightMillimetres, int CurveCount, int TextCount); + double HeightMillimetres, int CurveCount, int TextCount) +{ + /// Lossless decimal native 64-bit Revit element ID when the file renumbered it to fit ; null when unchanged. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public string? SourceElementId { get; init; } +} /// /// Prints a sheet to a PDF page from the linework the reader decodes: the location curves of the elements the sheet @@ -85,7 +90,10 @@ public static IReadOnlyList Sheets(RvtDocument document) if (curves == 0 || maxX - minX < 50 || maxY - minY < 50) continue; sheets.Add(new PrintableSheet(sheet.Id, Text(sheet, BuiltInParameter.SHEET_NUMBER), Text(sheet, BuiltInParameter.SHEET_NAME), - maxX - minX, maxY - minY, curves, texts)); + maxX - minX, maxY - minY, curves, texts) + { + SourceElementId = RvtIO.Sheets.SheetCatalog.SourceIdText(document.RawData, sheet.Id, sheet), + }); continue; void Grow(double[] point) diff --git a/src/RvtIO/Sheets/SheetCatalog.cs b/src/RvtIO/Sheets/SheetCatalog.cs index 5107b981..4b3ef0a9 100644 --- a/src/RvtIO/Sheets/SheetCatalog.cs +++ b/src/RvtIO/Sheets/SheetCatalog.cs @@ -105,16 +105,24 @@ public static SheetCatalog Extract(RevitFileInfo info) foreach (var sheet in sheetElements) sheetIds.Add(sheet.Id); var owned = new Dictionary>(); + var ownedSourceIds = new Dictionary>(); foreach (var element in info.Elements) { if (!Compact.CompactUniverse.IsTableRow(element, info.ElemTableIsExact)) continue; if (element.OwnerViewId is not int owner || !sheetIds.Contains(owner) || owner == element.Id) continue; if (!owned.TryGetValue(owner, out var ids)) owned[owner] = ids = new List(); ids.Add(element.Id); + if (SourceIdText(info, element.Id, element) is not { } sourceId) continue; + if (!ownedSourceIds.TryGetValue(owner, out var sources)) ownedSourceIds[owner] = sources = new Dictionary(); + sources[element.Id] = sourceId; } var viewports = new List(); var viewportsBySheet = new Dictionary>(); + var sheetSourceIds = new Dictionary(); + foreach (var sheet in sheetElements) + if (SourceIdText(info, sheet.Id, sheet) is { } s) + sheetSourceIds[sheet.Id] = s; foreach (var element in info.Elements) { if (!Compact.CompactUniverse.IsTableRow(element, info.ElemTableIsExact)) continue; @@ -126,7 +134,12 @@ public static SheetCatalog Extract(RevitFileInfo info) if (reference != element.Id && sheetIds.Contains(reference)) { sheetId = reference; break; } } if (sheetId == 0) continue; - viewports.Add(new ViewportRecord(element.Id, sheetId, Text(element, BuiltInParameter.VIEWPORT_DETAIL_NUMBER))); + viewports.Add(new ViewportRecord( + element.Id, + sheetId, + Text(element, BuiltInParameter.VIEWPORT_DETAIL_NUMBER), + SourceIdText(info, element.Id, element), + sheetSourceIds.GetValueOrDefault(sheetId))); if (!viewportsBySheet.TryGetValue(sheetId, out var ids)) viewportsBySheet[sheetId] = ids = new List(); ids.Add(element.Id); } @@ -149,12 +162,21 @@ public static SheetCatalog Extract(RevitFileInfo info) Ordered(viewportsBySheet, element.Id), Ordered(owned, element.Id), parameters, - yesNo)); + yesNo, + sheetSourceIds.GetValueOrDefault(element.Id), + ownedSourceIds.GetValueOrDefault(element.Id))); } return new SheetCatalog(sheets, viewports); } + internal static string? SourceIdText(RevitFileInfo info, int localId, Element? element = null) + { + if (element?.SourceElementId is string s) return s; + long sourceId = info.GetSourceElementId(localId); + return sourceId != localId ? sourceId.ToString(System.Globalization.CultureInfo.InvariantCulture) : null; + } + /// /// 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 diff --git a/src/RvtIO/Sheets/SheetRecord.cs b/src/RvtIO/Sheets/SheetRecord.cs index 9976d047..7e76f03c 100644 --- a/src/RvtIO/Sheets/SheetRecord.cs +++ b/src/RvtIO/Sheets/SheetRecord.cs @@ -1,3 +1,5 @@ +using System.Text.Json.Serialization; + namespace RvtIO.Sheets; /// A sheet of the document (the Revit API's ViewSheet) with the data this release decodes: its number, @@ -18,7 +20,9 @@ internal SheetRecord( IReadOnlyList viewportIds, IReadOnlyList ownedElementIds, IReadOnlyDictionary? parameters = null, - IReadOnlyCollection? yesNoParameters = null) + IReadOnlyCollection? yesNoParameters = null, + string? sourceElementId = null, + IReadOnlyDictionary? ownedElementSourceIds = null) { ElementId = elementId; Number = number; @@ -35,11 +39,17 @@ internal SheetRecord( // 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); + SourceElementId = sourceElementId; + OwnedElementSourceIds = ownedElementSourceIds; } - /// The element id of the sheet. + /// The document-local element id of the sheet. public int ElementId { get; } + /// Lossless decimal text of the original 64-bit Revit element ID when the file was renumbered to fit ; null when unchanged. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? SourceElementId { get; } + /// The sheet number (the Sheet Number parameter) as stored, null when it is empty. "???" is a /// value a project stores, not a decode failure. public string? Number { get; } @@ -75,6 +85,11 @@ internal SheetRecord( /// view for its content. public IReadOnlyList OwnedElementIds { get; } + /// The original 64-bit Revit element ID, as lossless decimal text, of each entry of + /// that the file renumbered, keyed by the document-local id; null when none was. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public IReadOnlyDictionary? OwnedElementSourceIds { 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. diff --git a/src/RvtIO/Sheets/ViewportRecord.cs b/src/RvtIO/Sheets/ViewportRecord.cs index 9498d45b..3d7d4b31 100644 --- a/src/RvtIO/Sheets/ViewportRecord.cs +++ b/src/RvtIO/Sheets/ViewportRecord.cs @@ -1,3 +1,5 @@ +using System.Text.Json.Serialization; + namespace RvtIO.Sheets; /// A placed view: a viewport of a sheet (the Revit API's Viewport), as stored in the document. The @@ -6,20 +8,31 @@ namespace RvtIO.Sheets; /// ). public sealed class ViewportRecord { - internal ViewportRecord(int elementId, int sheetId, string? detailNumber) + internal ViewportRecord(int elementId, int sheetId, string? detailNumber, + string? sourceElementId = null, string? sourceSheetId = null) { ElementId = elementId; SheetId = sheetId; DetailNumber = detailNumber; + SourceElementId = sourceElementId; + SourceSheetId = sourceSheetId; } - /// The element id of the viewport. + /// The document-local element id of the viewport. public int ElementId { get; } - /// The element id of the sheet the viewport is placed on, resolved from the elements the viewport + /// Lossless decimal text of the original 64-bit Revit element ID when the file was renumbered to fit ; null when unchanged. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? SourceElementId { get; } + + /// The document-local element id of the sheet the viewport is placed on, resolved from the elements the viewport /// references (the sheet is one of them). public int SheetId { get; } + /// Lossless decimal text of the sheet's original 64-bit Revit element ID when renumbered to fit ; null when unchanged. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? SourceSheetId { get; } + /// The detail number of the viewport (the Detail Number parameter), null when it is empty. public string? DetailNumber { get; } diff --git a/tests/RvtIO.Tests/NativeIdSheetsAndPrintTests.cs b/tests/RvtIO.Tests/NativeIdSheetsAndPrintTests.cs new file mode 100644 index 00000000..7d6bca74 --- /dev/null +++ b/tests/RvtIO.Tests/NativeIdSheetsAndPrintTests.cs @@ -0,0 +1,268 @@ +using System.Text.Json; +using RvtIO.BuiltIns; +using RvtIO.Cli; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Print; +using RvtIO.Sheets; +using Xunit; + +namespace RvtIO.Tests; + +public class NativeIdSheetsAndPrintTests +{ + private const long WideSheetNativeId = 5_000_000_101L; + private const long WideViewportNativeId = 5_000_000_102L; + private const long WideLevelNativeId = 5_000_000_103L; + private const long WidePlanViewNativeId = 5_000_000_104L; + private const long WideElevationViewNativeId = 5_000_000_105L; + private const long WideSheetCurveNativeId = 5_000_000_106L; + + private static RevitFileInfo BuildWideSyntheticProject() + { + var info = new RevitFileInfo(); + + var normalSheet = new Element + { + Id = 10, + CategoryId = -2003100, + Parameters = + [ + BipHelpers.MakeBipParam((int)BuiltInParameter.SHEET_NUMBER, "SHEET_NUMBER", StorageType.String, "A100"), + BipHelpers.MakeBipParam((int)BuiltInParameter.SHEET_NAME, "SHEET_NAME", StorageType.String, "Cover"), + BipHelpers.MakeBipParam((int)BuiltInParameter.VIEW_SCALE, "VIEW_SCALE", StorageType.Integer, 100), + ], + }; + var normalCurve = new Element + { + Id = 11, + SerializedOwnerDbViewId = 10, + Location = new LocationCurve { CurveType = "Line", StartPoint = [0, 0, 0], EndPoint = [1.0, 1.0, 0] }, + }; + + var wideSheet = new Element + { + Id = 201, + NativeId = WideSheetNativeId, + CategoryId = -2003100, + Parameters = + [ + BipHelpers.MakeBipParam((int)BuiltInParameter.SHEET_NUMBER, "SHEET_NUMBER", StorageType.String, "A101"), + BipHelpers.MakeBipParam((int)BuiltInParameter.SHEET_NAME, "SHEET_NAME", StorageType.String, "Ground Plan"), + BipHelpers.MakeBipParam((int)BuiltInParameter.VIEW_SCALE, "VIEW_SCALE", StorageType.Integer, 100), + new Parameter + { + Id = 1000, Definition = new Definition { Id = 1000, Name = "Zone" }, + StorageType = StorageType.String, Value = "North wing", + }, + ], + }; + var wideSheetCurve = new Element + { + Id = 211, + NativeId = WideSheetCurveNativeId, + SerializedOwnerDbViewId = 201, + Location = new LocationCurve { CurveType = "Line", StartPoint = [0, 0, 0], EndPoint = [1.0, 1.0, 0] }, + }; + var wideViewport = new Element + { + Id = 202, + NativeId = WideViewportNativeId, + CategoryId = -2000510, + References = [201], + Parameters = + [ + BipHelpers.MakeBipParam((int)BuiltInParameter.VIEWPORT_DETAIL_NUMBER, "VIEWPORT_DETAIL_NUMBER", StorageType.String, "1"), + ], + }; + + var wideLevel = new Element + { + Id = 203, + NativeId = WideLevelNativeId, + CategoryId = -2000240, + Name = "Level 1", + IsNativeLevel = true, + Parameters = + [ + BipHelpers.MakeBipParam((int)BuiltInParameter.LEVEL_ELEV, "LEVEL_ELEV", StorageType.Double, 0.0), + ], + }; + var wall = new Element + { + Id = 212, + CategoryId = -2000011, + Category = "OST_Walls", + Location = new LocationCurve { CurveType = "Line", StartPoint = [0, 0, 0], EndPoint = [10, 0, 0] }, + Parameters = + [ + BipHelpers.MakeBipParam((int)BuiltInParameter.LEVEL_PARAM, "LEVEL_PARAM", StorageType.ElementId, 203), + ], + }; + var widePlanView = new Element + { + Id = 204, + NativeId = WidePlanViewNativeId, + CategoryId = (int)BuiltInCategory.OST_Views, + NativeRecordClass = 1005, + Name = "Level 1", + Parameters = + [ + BipHelpers.MakeBipParam((int)BuiltInParameter.VIEW_NAME, "VIEW_NAME", StorageType.String, "Level 1"), + BipHelpers.MakeBipParam((int)BuiltInParameter.VIEW_SCALE, "VIEW_SCALE", StorageType.Integer, 100), + ], + }; + var wideElevationView = new Element + { + Id = 205, + NativeId = WideElevationViewNativeId, + CategoryId = (int)BuiltInCategory.OST_Views, + NativeRecordClass = 1016, + Name = "North", + Parameters = + [ + BipHelpers.MakeBipParam((int)BuiltInParameter.VIEW_NAME, "VIEW_NAME", StorageType.String, "North"), + BipHelpers.MakeBipParam((int)BuiltInParameter.VIEW_SCALE, "VIEW_SCALE", StorageType.Integer, 100), + ], + }; + + info.Elements.AddRange([normalSheet, normalCurve, wideSheet, wideSheetCurve, wideViewport, wideLevel, wall, widePlanView, wideElevationView]); + return info; + } + + [Fact] + public void SheetCatalog_And_SheetsCommand_ExposeLosslessSourceElementId_InJsonAndCsv() + { + RevitFileInfo info = BuildWideSyntheticProject(); + SheetCatalog catalog = SheetCatalog.Extract(info); + + SheetRecord normal = Assert.Single(catalog.Sheets, s => s.ElementId == 10); + Assert.Null(normal.SourceElementId); + + SheetRecord wide = Assert.Single(catalog.Sheets, s => s.ElementId == 201); + Assert.Equal("5000000101", wide.SourceElementId); + + ViewportRecord vp = Assert.Single(catalog.Viewports); + Assert.Equal(202, vp.ElementId); + Assert.Equal("5000000102", vp.SourceElementId); + Assert.Equal(201, vp.SheetId); + Assert.Equal("5000000101", vp.SourceSheetId); + + // Owned elements of a sheet map back to Revit too; only the renumbered ones are listed. + Assert.Null(normal.OwnedElementSourceIds); + Assert.Equal("5000000106", Assert.Single(wide.OwnedElementSourceIds!, pair => pair.Key == 211).Value); + + string json = SheetsCommand.ToJson(catalog); + using var parsed = JsonDocument.Parse(json); + var jsonSheets = parsed.RootElement.GetProperty("Sheets").EnumerateArray().ToList(); + Assert.False(jsonSheets[0].TryGetProperty("SourceElementId", out _)); + Assert.Equal(JsonValueKind.String, jsonSheets[1].GetProperty("SourceElementId").ValueKind); + Assert.Equal("5000000101", jsonSheets[1].GetProperty("SourceElementId").GetString()); + + Assert.False(jsonSheets[0].TryGetProperty("OwnedElementSourceIds", out _)); + Assert.Equal("5000000106", jsonSheets[1].GetProperty("OwnedElementSourceIds").GetProperty("211").GetString()); + + var jsonVp = parsed.RootElement.GetProperty("Viewports").EnumerateArray().Single(); + Assert.Equal("5000000102", jsonVp.GetProperty("SourceElementId").GetString()); + Assert.Equal("5000000101", jsonVp.GetProperty("SourceSheetId").GetString()); + + string csv = SheetsCommand.ToCsv(catalog); + string[] lines = csv.Split(Environment.NewLine); + // The new column is last, so the position of every earlier column is unchanged. + Assert.Equal("ElementId,Number,Name,IssueDate,Scale,DrawnBy,DesignedBy,CheckedBy,ApprovedBy,Zone,SourceElementId", lines[0]); + Assert.Equal("10,A100,Cover,,100,,,,,,", lines[1]); + Assert.Equal("201,A101,Ground Plan,,100,,,,,North wing,5000000101", lines[2]); + } + + [Fact] + public void PrintRecords_OmitTheSourceIdFromJson_WhenTheIdWasNotRenumbered() + { + // ComposedSheet is left out: its PdfPageSize.Landscape makes System.Text.Json report a cycle. + object[] unchanged = + [ + new PlanLevel(1, "Level 1", 0), new PlanView(2, "Level 1", 1, 100), new ElevationView(3, "North", "north", 100), + new PrintableSheet(4, "A1", "Cover", 1, 1, 1, 0), + ]; + + foreach (object record in unchanged) + { + string json = JsonSerializer.Serialize(record, record.GetType()); + Assert.DoesNotContain("SourceElementId", json); + Assert.DoesNotContain("SourceLevelId", json); + } + Assert.Contains("\"SourceLevelId\":\"5000000103\"", + JsonSerializer.Serialize(new PlanView(2, "Level 1", 1, 100) { SourceLevelId = "5000000103" })); + } + + [Fact] + public void PrintModels_And_CliListingsAndSelectors_ExposeAndAcceptNative64BitIds() + { + RvtDocument document = RvtDocument.FromInfo(BuildWideSyntheticProject()); + + IReadOnlyList levels = PlanPrinter.Levels(document); + PlanLevel level = Assert.Single(levels); + Assert.Equal(203, level.LevelId); + Assert.Equal("5000000103", level.SourceElementId); + + IReadOnlyList planViews = PlanPrinter.Views(document); + PlanView planView = Assert.Single(planViews); + Assert.Equal(204, planView.ViewId); + Assert.Equal("5000000104", planView.SourceElementId); + Assert.Equal("5000000103", planView.SourceLevelId); + + IReadOnlyList elevations = ElevationPrinter.Views(document); + ElevationView elevation = Assert.Single(elevations); + Assert.Equal(205, elevation.ViewId); + Assert.Equal("5000000105", elevation.SourceElementId); + + IReadOnlyList printableSheets = SheetPrinter.Sheets(document); + PrintableSheet widePrintable = Assert.Single(printableSheets, s => s.SheetId == 201); + Assert.Equal("5000000101", widePrintable.SourceElementId); + Assert.Null(Assert.Single(printableSheets, s => s.SheetId == 10).SourceElementId); + + IReadOnlyList composedSheets = SheetComposer.Sheets(document); + ComposedSheet wideComposed = Assert.Single(composedSheets, s => s.SheetId == 201); + Assert.Equal("5000000101", wideComposed.SourceElementId); + + var sheetsOut = new StringWriter(); + var sheetsErr = new StringWriter(); + PrintCommand.WriteListedSheets(printableSheets, composedSheets, sheetsOut, sheetsErr); + string sheetLines = sheetsOut.ToString(); + string normalSheetLine = sheetLines.Split('\n').First(l => l.StartsWith("10\t", StringComparison.Ordinal)); + Assert.DoesNotContain("source=", normalSheetLine); + string wideSheetLine = sheetLines.Split('\n').First(l => l.StartsWith("201\t", StringComparison.Ordinal)); + Assert.Contains("source=5000000101", wideSheetLine); + + var levelsOut = new StringWriter(); + PrintCommand.WriteListedLevels(levels, levelsOut); + Assert.Contains("203\tLevel 1\t0 mm\tsource=5000000103", levelsOut.ToString()); + + var viewsOut = new StringWriter(); + var viewsErr = new StringWriter(); + PrintCommand.WriteListedViews(document, planViews, elevations, viewsOut, viewsErr); + string viewLines = viewsOut.ToString(); + Assert.Contains("204\tLevel 1\t1:100\tlevel 203\tplan\tsource=5000000104\tlevel-source=5000000103", viewLines); + Assert.Contains("205\tNorth\t1:100\tnorth\televation\tsource=5000000105", viewLines); + + // Selectors accept local 32-bit key, wide 64-bit native ID, explicit prefixes, and numbers/names. + Assert.Equal([201], PrintCommand.SelectExplicitSheets(["201"], printableSheets, composedSheets, null).ComposedIds); + Assert.Equal([201], PrintCommand.SelectExplicitSheets(["5000000101"], printableSheets, composedSheets, null).ComposedIds); + Assert.Equal([201], PrintCommand.SelectExplicitSheets(["source:5000000101"], printableSheets, composedSheets, null).ComposedIds); + Assert.Equal([201], PrintCommand.SelectExplicitSheets(["native:5000000101"], printableSheets, composedSheets, null).ComposedIds); + Assert.Equal([10], PrintCommand.SelectExplicitSheets(["source:10"], printableSheets, composedSheets, null).ComposedIds); + Assert.Equal("source:201", PrintCommand.SelectExplicitSheets(["source:201"], printableSheets, composedSheets, null).Missing); + Assert.Equal("5000000999", PrintCommand.SelectExplicitSheets(["5000000999"], printableSheets, composedSheets, null).Missing); + + Assert.Equal(203, PrintCommand.ResolveLevelId("203", levels)); + Assert.Equal(203, PrintCommand.ResolveLevelId("5000000103", levels)); + Assert.Equal(203, PrintCommand.ResolveLevelId("source:5000000103", levels)); + Assert.Equal(203, PrintCommand.ResolveLevelId("native:5000000103", levels)); + Assert.Null(PrintCommand.ResolveLevelId("source:203", levels)); + + Assert.Equal(204, PrintCommand.ResolveView("5000000104", planViews, elevations)); + Assert.Equal(204, PrintCommand.ResolveView("source:5000000104", planViews, elevations)); + Assert.Equal(205, PrintCommand.ResolveView("5000000105", planViews, elevations)); + Assert.Equal(205, PrintCommand.ResolveView("native:5000000105", planViews, elevations)); + Assert.Null(PrintCommand.ResolveView("source:205", planViews, elevations)); + } +}