diff --git a/documentation/content/docs/3d-view.mdx b/documentation/content/docs/3d-view.mdx index 696c2b4..cbfb363 100644 --- a/documentation/content/docs/3d-view.mdx +++ b/documentation/content/docs/3d-view.mdx @@ -81,9 +81,10 @@ model generates it; everyone else gets a cache hit. Configure it in **Settings → 3D Viewer**: - **Inventor version** - which installed release generates viewables, or *Ask each time*. -- **Hide Inventor** / **Run silently** - when MetaReader launches Inventor to generate a viewable, keep - its window hidden and suppress its prompts (both on by default). An Inventor session you already had - open is never touched. +- **Hide Inventor** / **Run silently** - MetaReader generates each viewable in its own dedicated + Inventor instance, which it starts and then shuts down again. These options keep that instance's + window hidden and suppress its prompts (both on by default). An Inventor session you already had open + is never attached to or disturbed. - **Shared cache folder** - a network path so viewables are reused across users; leave empty for a local-only cache under your profile. - **Cached viewables** - **Open** the local cache folder, or **Clear** it to reclaim space. diff --git a/documentation/content/docs/command-line.mdx b/documentation/content/docs/command-line.mdx index 24546e7..1963cdb 100644 --- a/documentation/content/docs/command-line.mdx +++ b/documentation/content/docs/command-line.mdx @@ -24,15 +24,17 @@ dotnet build src/InventorMeta.Cli -c Release ## Commands ```text -invmeta info friendly report (type, iProperties, refs, version) -invmeta states per-model-state iProperties (parts/assemblies) -invmeta json full metadata as JSON -invmeta props every property in every set -invmeta graph recursive reference tree -invmeta tree raw file structure -invmeta thumb [outBase] extract the embedded preview image -invmeta extract dump every stream to disk -invmeta cat hex+ascii dump of one stream +invmeta info friendly report (type, iProperties, refs, version) +invmeta states per-model-state iProperties (parts/assemblies) +invmeta json full metadata as JSON +invmeta props every property in every set +invmeta graph recursive reference tree +invmeta segments RSeStorage segment inventory + damage check +invmeta repair fix a stale segment registry (backs the file up first) +invmeta tree raw file structure +invmeta thumb [outBase] extract the embedded preview image +invmeta extract dump every stream to disk +invmeta cat hex+ascii dump of one stream ``` **STEP files** (`.stp` / `.step`) work with `info`, `states`, `json`, `props` and `graph` - you get @@ -61,6 +63,30 @@ invmeta thumb "Assembly1.iam" preview # -> writes preview.png (or preview.bmp) ``` +## Checking a damaged file + +When Inventor refuses to open a file with an "Error loading segment … in database" message, +`segments` inventories the internal databases and checks their integrity: + +```bash +invmeta segments "Broken.ipt" +``` + +It distinguishes two kinds of damage. A **stale segment registry** is only bookkeeping that drifted +out of sync - no data is lost - and `repair` fixes it in place, writing an untouched backup copy next +to the file first: + +```bash +invmeta repair "Broken.ipt" +# -> patches the registry; original saved as Broken.ipt.pre-repair.bak +``` + +**Destroyed segment data** (runs of zeroed bytes where compressed geometry used to be, typically from +a disk fault or an interrupted copy) is not repairable - the bytes are physically gone. `segments` +reports which segments are affected and how much survives, and `repair` refuses the file rather than +producing one that still won't open. The only fix is to restore an earlier copy from Vault or another +PDM, the OldVersions folder next to the file, or a backup. + ## Automating across many files Because `json` writes to standard output, it drops straight into scripts. For example, export the diff --git a/documentation/content/docs/damaged-files.mdx b/documentation/content/docs/damaged-files.mdx new file mode 100644 index 0000000..4845881 --- /dev/null +++ b/documentation/content/docs/damaged-files.mdx @@ -0,0 +1,67 @@ +--- +title: Damaged Files +description: When Inventor refuses a file with "Error loading segment", MetaReader tells you whether it can be repaired - and repairs the fixable kind in place. +--- + +Sometimes Inventor refuses to open a file and shows a message like **"Error loading segment +PmGraphicsSegment in database"**. The model may be perfectly fine underneath - or parts of it may be +gone. MetaReader reads straight past whatever trips Inventor up, so it can open the file, tell you +**what kind of damage** it has, and, when the damage is the fixable kind, **repair it in place**. + +## The "Damaged file" badge + +Open a file with this kind of damage and a red **Damaged file** badge appears under the document +title. Hover it for the details: which segments are affected, and what exactly is wrong. There are +two very different cases, and the badge tells them apart. + +## Repairable: a stale segment registry + +Inside every Inventor file, a small registry records how many blocks each internal database segment +should have. If some tool rewrote the file's streams without refreshing that registry, the counts no +longer match what's actually stored - and Inventor hard-stops the open with the segment error, even +though **no model data is missing**. Only the bookkeeping drifted. + +This is repairable. When MetaReader sees it, the badge shows a **Repair** button: + +- **Repair** rewrites just the registry counts to match the data that's really there. No geometry, + features or properties are touched. +- Before it writes anything, MetaReader saves an **untouched backup copy** next to the file, named + `yourfile.ipt.pre-repair.bak`. If anything looks wrong afterwards, that copy is your original. +- The first time you use it, MetaReader asks you to confirm you understand that the repair rewrites + the file's internal database - it's a rescue tool, not an everyday action. + +After a successful repair the badge turns into a green **Repaired** chip with an **Open in Inventor** +button, so you can confirm the file opens before you rely on it. + + + A repair edits the file's internal database - a proprietary structure Autodesk gives no supported + way to modify. Treat it as a last resort: prefer restoring a healthy version from Vault or another + PDM, the **OldVersions** folder, or a backup. Always open the repaired file in Inventor and check + it before you continue working with it, and keep the `.pre-repair.bak` copy until you have. + + +## Not repairable: destroyed segment data + +The other case is real data loss. Runs of zeroed bytes sit where compressed geometry used to be - +the signature of a disk fault or an interrupted copy or transfer. Those bytes are physically gone, +the compressed stream can't be re-synchronized past the gap, and Inventor needs every segment intact +to open a file. + +MetaReader detects this too, and is honest about it: **no Repair button appears**, because no repair +could work. The badge names the affected segments and how much still reads, and tells you the only +real fix - **restore the file from a backup** (Vault or another PDM, the OldVersions folder next to +the file, or a file backup). MetaReader never offers a repair that would only produce a file that +still won't open. + +Even for an unrepairable file, everything MetaReader reads from metadata - iProperties, the preview +thumbnail, referenced files, version history - is still available, which is often enough to identify +the file and find the right backup to restore. + +## From the command line + +The [command-line tool](/docs/command-line) makes the same distinction without the app. `invmeta +segments ` inventories the internal databases and flags any damage; `invmeta repair ` +fixes a stale registry in place (writing the same `.pre-repair.bak` backup first) and refuses a file +whose data is destroyed. See [Command line](/docs/command-line#checking-a-damaged-file). + +For what these segments and registries actually are, see [How it works](/docs/how-it-works). diff --git a/documentation/content/docs/index.mdx b/documentation/content/docs/index.mdx index ea4d636..caf1163 100644 --- a/documentation/content/docs/index.mdx +++ b/documentation/content/docs/index.mdx @@ -79,6 +79,7 @@ That's it - no setup, no Inventor. + diff --git a/documentation/content/docs/meta.json b/documentation/content/docs/meta.json index f0d459a..d6ea9d1 100644 --- a/documentation/content/docs/meta.json +++ b/documentation/content/docs/meta.json @@ -9,6 +9,7 @@ "model-states", "references", "file-structure", + "damaged-files", "command-line", "for-developers", "how-it-works", diff --git a/documentation/content/docs/whats-new.mdx b/documentation/content/docs/whats-new.mdx index e7bc634..8113797 100644 --- a/documentation/content/docs/whats-new.mdx +++ b/documentation/content/docs/whats-new.mdx @@ -5,6 +5,35 @@ description: Highlights of each MetaReader release. import { DemoGif } from '@/components/demo-gif'; +## 1.3.0 + +Sharper diagnosis of damaged files, and 3D generation that stays out of your way. + +### Clearer diagnosis of damaged files + +Two very different problems make Inventor refuse to open a file with an "Error loading segment" +message, and MetaReader now tells them apart. A **stale segment registry** is bookkeeping that drifted +out of sync - no data is lost, and MetaReader can **repair it in place** (a backup is written first). +**Destroyed segment data** - runs of zeroed bytes where compressed geometry used to be, the signature +of a disk fault or an interrupted copy - is different: the bytes are physically gone. MetaReader now +detects that case, names the affected segments, and explains that **no repair is possible** - the fix +is to restore the file from a backup (Vault or another PDM, the OldVersions folder, or a file backup). +No repair is offered that could only fail. The `segments` and `repair` [CLI](/docs/command-line) +commands report the same distinction. + +### Isolated, more reliable 3D generation + +When MetaReader generates a viewable with Inventor, it now always starts its **own dedicated Inventor +instance** and shuts it down when finished. It no longer attaches to an Inventor session you already +have open, so generation can't be tripped up by a dialog or an edit in progress on your side - and a +crash or hang during generation can never take your session with it. See [3D viewer](/docs/3d-view). + +### Better logging + +The app records much more about what it's doing - document loads and their timings, damage findings, +each 3D generation step, and any failure with its details - so a problem is far easier to pin down +from the diagnostics log in **Settings → Open log**. + ## 1.2.0 3D everywhere: STEP files open with a 3D view, viewables generate **without Inventor**, and you can diff --git a/documentation/scripts/record-demo.ps1 b/documentation/scripts/record-demo.ps1 index 5dc9749..7c34db5 100644 --- a/documentation/scripts/record-demo.ps1 +++ b/documentation/scripts/record-demo.ps1 @@ -1,11 +1,20 @@ # Records the demo tour and cuts it into documentation GIFs and a promo video. # Builds the app, runs it in --demo-tour mode (a visible, always-on-top window walking the -# features at a human pace, once per theme), records the window region with ffmpeg (gdigrab of -# the composited desktop - a plain window grab renders WebView2 content black), then cuts the -# chapters listed in chapters.json into GIFs (light pass) and an MP4 feature tour (dark pass). +# features at a human pace), records the window region with ffmpeg (gdigrab of the composited +# desktop - a plain window grab renders WebView2 content black), then cuts the chapters listed +# in chapters.json into GIFs and an MP4 feature tour. # -# Requires ffmpeg on PATH (winget install Gyan.FFmpeg). The window sits top-left for ~4 minutes; -# it stays above other windows, but don't drag anything on top of it. +# .\record-demo.ps1 # light pass: docs/what's-new GIFs + the promo video +# .\record-demo.ps1 -Theme dark -VideoOnly # dark pass: ONLY the 1920x1080 Store trailer, +# # leaving the existing (light) GIFs untouched +# +# The window records at its native 1920x1080, so the MP4 is exactly Full HD (the Microsoft Store +# trailer slot requires 1920x1080). Requires ffmpeg on PATH (winget install Gyan.FFmpeg). The +# window sits top-left for ~4 minutes; it stays above other windows, but don't drag anything on top. +param( + [ValidateSet('light', 'dark')] [string]$Theme = 'light', + [switch]$VideoOnly +) $ErrorActionPreference = "Stop" $repo = Resolve-Path "$PSScriptRoot\..\.." @@ -27,7 +36,7 @@ Remove-Item $out -Recurse -Force -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force $out | Out-Null # 1. the tour app writes window-rect.json, then waits for record-ready.flag -$appProc = Start-Process $app -ArgumentList "--demo-tour","`"$out`"","--samples","`"$samples`"","--model","`"$model`"" -PassThru +$appProc = Start-Process $app -ArgumentList "--demo-tour","`"$out`"","--samples","`"$samples`"","--model","`"$model`"","--theme",$Theme -PassThru $rectFile = "$out\window-rect.json" for ($i = 0; $i -lt 60 -and -not (Test-Path $rectFile); $i++) { Start-Sleep -Milliseconds 500 } if (-not (Test-Path $rectFile)) { throw "window-rect.json never appeared" } @@ -65,28 +74,32 @@ if (-not $appProc.HasExited) { Stop-Process -Id $appProc.Id -Force -Confirm:$fal $ch = (Get-Content "$out\chapters.json" | ConvertFrom-Json).chapters $off = 2.5 function Chapter($name, $theme) { $ch | Where-Object { $_.name -eq $name -and $_.theme -eq $theme } } -function Cut($ss, $dur, $w, $fps, $outFile) { - & $ffmpeg -y -v error -ss $ss -t $dur -i $rec -vf "fps=$fps,scale=${w}:-1:flags=lanczos,palettegen=stats_mode=diff" "$out\pal.png" - & $ffmpeg -y -v error -ss $ss -t $dur -i $rec -i "$out\pal.png" -lavfi "fps=$fps,scale=${w}:-1:flags=lanczos[x];[x][1:v]paletteuse=dither=bayer:bayer_scale=4:diff_mode=rectangle" $outFile -} -$appGifDir = "$repo\src\InventorMeta.App\Assets\whatsnew" -function Gif($start, $dur, $name) { - $ss = $start + $off - Cut $ss $dur 820 11 "$gifDir\$name" # docs, inline - Cut $ss $dur 1600 11 "$gifDir\$($name -replace '\.gif$', '-hd.gif')" # docs, lightbox - Cut $ss $dur 1280 10 "$appGifDir\$($name -replace '^demo__', '')" # app what's-new dialog - "{0}: {1:N2} MB (+hd, +app)" -f $name, ((Get-Item "$gifDir\$name").Length / 1MB) + +# GIFs are skipped in -VideoOnly mode, so a dark video pass leaves the (light) docs GIFs untouched. +if (-not $VideoOnly) { + function Cut($ss, $dur, $w, $fps, $outFile) { + & $ffmpeg -y -v error -ss $ss -t $dur -i $rec -vf "fps=$fps,scale=${w}:-1:flags=lanczos,palettegen=stats_mode=diff" "$out\pal.png" + & $ffmpeg -y -v error -ss $ss -t $dur -i $rec -i "$out\pal.png" -lavfi "fps=$fps,scale=${w}:-1:flags=lanczos[x];[x][1:v]paletteuse=dither=bayer:bayer_scale=4:diff_mode=rectangle" $outFile + } + $appGifDir = "$repo\src\InventorMeta.App\Assets\whatsnew" + function Gif($start, $dur, $name) { + $ss = $start + $off + Cut $ss $dur 820 11 "$gifDir\$name" # docs, inline + Cut $ss $dur 1600 11 "$gifDir\$($name -replace '\.gif$', '-hd.gif')" # docs, lightbox + Cut $ss $dur 1280 10 "$appGifDir\$($name -replace '^demo__', '')" # app what's-new dialog + "{0}: {1:N2} MB (+hd, +app)" -f $name, ((Get-Item "$gifDir\$name").Length / 1MB) + } + $refs = Chapter "references" $Theme; $orb = Chapter "viewer-orbit" $Theme + $col = Chapter "coloring" $Theme; $red = Chapter "redlining" $Theme + $tabs = Chapter "tabs" $Theme + Gif ($refs.startMs/1000 + 3.2) (($refs.endMs - $refs.startMs)/1000 - 3.6) "demo__references.gif" + Gif ($tabs.startMs/1000 + 0.2) (($tabs.endMs - $tabs.startMs)/1000 - 0.4) "demo__tabs.gif" + Gif ($orb.startMs/1000) (($col.endMs - $orb.startMs)/1000 - 0.3) "demo__viewer3d.gif" + Gif ($red.startMs/1000 + 0.5) (($red.endMs - $red.startMs)/1000 - 1.0) "demo__redlining.gif" } -$refs = Chapter "references" "light"; $orb = Chapter "viewer-orbit" "light" -$col = Chapter "coloring" "light"; $red = Chapter "redlining" "light" -$tabs = Chapter "tabs" "light" -Gif ($refs.startMs/1000 + 3.2) (($refs.endMs - $refs.startMs)/1000 - 3.6) "demo__references.gif" -Gif ($tabs.startMs/1000 + 0.2) (($tabs.endMs - $tabs.startMs)/1000 - 0.4) "demo__tabs.gif" -Gif ($orb.startMs/1000) (($col.endMs - $orb.startMs)/1000 - 0.3) "demo__viewer3d.gif" -Gif ($red.startMs/1000 + 0.5) (($red.endMs - $red.startMs)/1000 - 1.0) "demo__redlining.gif" -# 5. the full (light) pass becomes the promo / Store video -$h = Chapter "home" "light"; $o = Chapter "outro" "light" +# 5. the full pass becomes the promo / Store video, at the recording's native 1920x1080 +$h = Chapter "home" $Theme; $o = Chapter "outro" $Theme & $ffmpeg -y -v error -ss ($h.startMs/1000 + $off) -t (($o.endMs - $h.startMs)/1000) -i $rec ` -c:v libx264 -preset slow -crf 21 -pix_fmt yuv420p -movflags +faststart "$out\metareader-feature-tour.mp4" "video: $out\metareader-feature-tour.mp4" diff --git a/src/InventorMeta.App/App.xaml.cs b/src/InventorMeta.App/App.xaml.cs index 2dac115..f0ed196 100644 --- a/src/InventorMeta.App/App.xaml.cs +++ b/src/InventorMeta.App/App.xaml.cs @@ -39,6 +39,21 @@ protected override void OnLaunched(LaunchActivatedEventArgs args) Analytics.Init(); Serilog.Log.Information("Inventor MetaReader starting (v{Version})", typeof(App).Assembly.GetName().Version?.ToString() ?? "?"); + Serilog.Log.Information("Environment: {Os}, .NET {Clr}, culture {Culture}, {Cores} cores", + Environment.OSVersion.VersionString, Environment.Version, + System.Globalization.CultureInfo.CurrentUICulture.Name, Environment.ProcessorCount); + + // The file sink writes unbuffered, but the exit line itself still needs a flush - and + // ProcessExit fires no matter which window was closed last. + AppDomain.CurrentDomain.ProcessExit += (_, _) => + { + try + { + Serilog.Log.Information("Inventor MetaReader exiting"); + Serilog.Log.CloseAndFlush(); + } + catch { /* shutting down anyway */ } + }; // Headless docs mode: "--shoot-docs [--samples ] [--model ]" // renders one PNG per view (light + dark) and exits, without ever showing the normal app. @@ -54,6 +69,7 @@ protected override void OnLaunched(LaunchActivatedEventArgs args) int modelIndex = Array.IndexOf(cli, "--model"); string? model = modelIndex >= 0 && modelIndex + 1 < cli.Length ? cli[modelIndex + 1] : null; + Serilog.Log.Information("Mode: --shoot-docs -> {OutDir}", cli[shootIndex + 1]); _ = DocShooter.RunAsync(cli[shootIndex + 1], samples, model); return; } @@ -72,7 +88,14 @@ protected override void OnLaunched(LaunchActivatedEventArgs args) int tourModelIndex = Array.IndexOf(cli, "--model"); string? tourModel = tourModelIndex >= 0 && tourModelIndex + 1 < cli.Length ? cli[tourModelIndex + 1] : null; - _ = DemoTour.RunAsync(cli[tourIndex + 1], tourSamples, tourModel); + int tourThemeIndex = Array.IndexOf(cli, "--theme"); + Microsoft.UI.Xaml.ElementTheme tourTheme = + tourThemeIndex >= 0 && tourThemeIndex + 1 < cli.Length && + string.Equals(cli[tourThemeIndex + 1], "dark", StringComparison.OrdinalIgnoreCase) + ? Microsoft.UI.Xaml.ElementTheme.Dark + : Microsoft.UI.Xaml.ElementTheme.Light; + Serilog.Log.Information("Mode: --demo-tour ({Theme}) -> {OutDir}", tourTheme, cli[tourIndex + 1]); + _ = DemoTour.RunAsync(cli[tourIndex + 1], tourSamples, tourModel, tourTheme); return; } @@ -80,6 +103,7 @@ protected override void OnLaunched(LaunchActivatedEventArgs args) // key, generates the SVF into the store, prints the result to the console, and exits. if (Array.IndexOf(cli, "--gen-svf") >= 0) { + Serilog.Log.Information("Mode: --gen-svf"); SvfTestRunner.Run(cli); return; } diff --git a/src/InventorMeta.App/AppIcons.cs b/src/InventorMeta.App/Common/AppIcons.cs similarity index 94% rename from src/InventorMeta.App/AppIcons.cs rename to src/InventorMeta.App/Common/AppIcons.cs index e2e8c64..00deaeb 100644 --- a/src/InventorMeta.App/AppIcons.cs +++ b/src/InventorMeta.App/Common/AppIcons.cs @@ -2,7 +2,7 @@ using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Media.Imaging; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Common; /// Maps an Inventor document kind to its bundled type icon (Assets\*.png). internal static class AppIcons diff --git a/src/InventorMeta.App/AppInfo.cs b/src/InventorMeta.App/Common/AppInfo.cs similarity index 83% rename from src/InventorMeta.App/AppInfo.cs rename to src/InventorMeta.App/Common/AppInfo.cs index b56774b..e7a9426 100644 --- a/src/InventorMeta.App/AppInfo.cs +++ b/src/InventorMeta.App/Common/AppInfo.cs @@ -1,7 +1,7 @@ using System; using System.Reflection; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Common; /// Central app metadata for the title bar and the About dialog. internal static class AppInfo @@ -30,6 +30,11 @@ public static string Version /// Newest first. public static readonly (string Version, string[] Notes)[] History = [ + ("1.3.0.0", [ + "Damaged files are now diagnosed precisely: MetaReader tells apart a stale segment registry it can repair from destroyed segment data it cannot, and for the latter explains why no repair is possible and what to do instead (restore a backup).", + "3D generation always runs in its own dedicated Inventor instance that is shut down afterwards, so it never disturbs an Inventor session you have open - and is more reliable.", + "More thorough logging throughout the app to make problems easier to diagnose." + ]), ("1.2.0.0", [ "STEP file support (.stp/.step) - header metadata and the 3D model, in the app and the CLI.", "Redlining: draw on the 3D model - freehand, shapes, text and an eraser, organized in layers with per-layer camera poses, saved with the cached viewable.", diff --git a/src/InventorMeta.App/AppLog.cs b/src/InventorMeta.App/Common/AppLog.cs similarity index 97% rename from src/InventorMeta.App/AppLog.cs rename to src/InventorMeta.App/Common/AppLog.cs index 3324b70..df818f4 100644 --- a/src/InventorMeta.App/AppLog.cs +++ b/src/InventorMeta.App/Common/AppLog.cs @@ -4,7 +4,7 @@ using System.Linq; using Serilog; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Common; /// App-wide logging: Serilog writing to a daily rolling file under %LocalAppData%. /// Call once at startup, then log through Serilog's static diff --git a/src/InventorMeta.App/DocCategoryUi.cs b/src/InventorMeta.App/Common/DocCategoryUi.cs similarity index 98% rename from src/InventorMeta.App/DocCategoryUi.cs rename to src/InventorMeta.App/Common/DocCategoryUi.cs index 50938ce..7e4c759 100644 --- a/src/InventorMeta.App/DocCategoryUi.cs +++ b/src/InventorMeta.App/Common/DocCategoryUi.cs @@ -4,7 +4,7 @@ using Microsoft.UI.Xaml.Media; using Windows.UI; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Common; /// Presentation for : a colour + label per /// category, and the legend control shown when hovering the category badge. diff --git a/src/InventorMeta.App/ThemeManager.cs b/src/InventorMeta.App/Common/ThemeManager.cs similarity index 96% rename from src/InventorMeta.App/ThemeManager.cs rename to src/InventorMeta.App/Common/ThemeManager.cs index 35abfa8..62939a9 100644 --- a/src/InventorMeta.App/ThemeManager.cs +++ b/src/InventorMeta.App/Common/ThemeManager.cs @@ -4,7 +4,7 @@ using Microsoft.UI.Xaml; using Windows.UI; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Common; /// Light/dark theme: apply to the window, theme the caption buttons, and persist the choice. internal static class ThemeManager diff --git a/src/InventorMeta.App/DemoTour.cs b/src/InventorMeta.App/DevTools/DemoTour.cs similarity index 98% rename from src/InventorMeta.App/DemoTour.cs rename to src/InventorMeta.App/DevTools/DemoTour.cs index 92c0edd..7f6a1af 100644 --- a/src/InventorMeta.App/DemoTour.cs +++ b/src/InventorMeta.App/DevTools/DemoTour.cs @@ -9,7 +9,7 @@ using Microsoft.UI.Xaml; using Windows.Foundation; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.DevTools; /// /// Scripted feature tour for recording promotional videos and documentation GIFs. Run with @@ -27,7 +27,8 @@ internal static class DemoTour { private sealed record Chapter(string Name, string Theme, long StartMs, long EndMs); - public static async Task RunAsync(string outDir, string? samplesDir, string? modelPath) + public static async Task RunAsync(string outDir, string? samplesDir, string? modelPath, + ElementTheme theme = ElementTheme.Light) { List chapters = []; Stopwatch clock = new(); @@ -49,7 +50,7 @@ public static async Task RunAsync(string outDir, string? samplesDir, string? mod MainWindow w = new(); w.Activate(); w.ShootMove(8, 8); - w.ShootResize(1600, 1000); + w.ShootResize(1920, 1080); // exact Full HD for the Microsoft Store trailer w.ShootTopmost(); await Task.Delay(600); @@ -69,8 +70,8 @@ public static async Task RunAsync(string outDir, string? samplesDir, string? mod clock.Start(); long tourStartEpoch = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - const string t = "light"; // one pass; light matches the docs - ThemeManager.Apply(w, ElementTheme.Light); + string t = theme == ElementTheme.Dark ? "dark" : "light"; + ThemeManager.Apply(w, theme); await Task.Delay(600); // -- home: the welcome screen, the recent list and the sample gallery -------------- @@ -97,7 +98,7 @@ public static async Task RunAsync(string outDir, string? samplesDir, string? mod { Microsoft.UI.Xaml.Controls.ContentDialog? gallery = null; Task pendingGallery = SamplesGallery.ShowAsync(w.Content.XamlRoot, _ => { }, - d => { gallery = d; d.RequestedTheme = ElementTheme.Light; }); + d => { gallery = d; d.RequestedTheme = theme; }); await Task.Delay(4800); gallery?.Hide(); try { await pendingGallery; } catch { /* dismissed */ } @@ -180,7 +181,9 @@ public static async Task RunAsync(string outDir, string? samplesDir, string? mod if (w.CurrentView?.ShootElement("CategoryBadge") is { } badge) { await cursor.MoveToElementAsync(badge, 700); - await Task.Delay(3800); // the tooltip lists all categories + w.CurrentView?.ShootShowCategoryLegend(); // painted cursor can't raise the real hover + await Task.Delay(3800); // the legend lists all categories + w.CurrentView?.ShootHideCategoryLegend(); } if (w.ShootTab(2) is { } partHeader) { await cursor.MoveToElementAsync(partHeader, 650); } w.ShootSelectTabIndex(2); @@ -209,7 +212,7 @@ public static async Task RunAsync(string outDir, string? samplesDir, string? mod w.ShootCaption("Pick your 3D engine: exact Inventor, or the fast built-in converter"); Microsoft.UI.Xaml.Controls.ContentDialog? chooser = null; Task pending = EngineDialogs.ShowChooserAsync( - w.Content.XamlRoot, d => { chooser = d; d.RequestedTheme = ElementTheme.Light; }); + w.Content.XamlRoot, d => { chooser = d; d.RequestedTheme = theme; }); await Task.Delay(1000); // linger on each card so the trade-offs can be read if (chooser?.Content is Microsoft.UI.Xaml.Controls.StackPanel body @@ -387,7 +390,7 @@ await v3.ShootViewer3DScriptAsync( // 2. a second layer for the annotations that follow w.ShootCaption("Organize markup in layers"); await vc.MoveToDomAsync("#redlineLayers .rl-layers-head .rl-layer-btn", 550); // the + - await vc.ClickDomAsync("#redlineLayers .rl-layers-head .rl-layer-btn", 0); + await vc.ClickDomAsync("#redlineLayers .rl-layers-head .rl-layer-btn"); await v3.ShootViewer3DScriptAsync( "(function(){const e=NOP_VIEWER.getExtension('Extrabbit.Redline');e._renameLayer(e._activeId,'Inspection notes');return 'ok';})()"); await Task.Delay(650); diff --git a/src/InventorMeta.App/DocShooter.cs b/src/InventorMeta.App/DevTools/DocShooter.cs similarity index 99% rename from src/InventorMeta.App/DocShooter.cs rename to src/InventorMeta.App/DevTools/DocShooter.cs index 3e2101e..4912cd5 100644 --- a/src/InventorMeta.App/DocShooter.cs +++ b/src/InventorMeta.App/DevTools/DocShooter.cs @@ -10,7 +10,7 @@ using Windows.Graphics.Imaging; using Windows.Storage.Streams; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.DevTools; /// /// Headless documentation snapshotter. Run with diff --git a/src/InventorMeta.App/ShootSupport.cs b/src/InventorMeta.App/DevTools/ShootSupport.cs similarity index 96% rename from src/InventorMeta.App/ShootSupport.cs rename to src/InventorMeta.App/DevTools/ShootSupport.cs index a5812d5..66654e4 100644 --- a/src/InventorMeta.App/ShootSupport.cs +++ b/src/InventorMeta.App/DevTools/ShootSupport.cs @@ -1,6 +1,6 @@ using System.IO; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.DevTools; /// Helpers shared by the two dev-tooling drivers - the documentation snapshotter /// () and the demo-tour recorder (). diff --git a/src/InventorMeta.App/AboutDialog.xaml b/src/InventorMeta.App/Dialogs/AboutDialog.xaml similarity index 98% rename from src/InventorMeta.App/AboutDialog.xaml rename to src/InventorMeta.App/Dialogs/AboutDialog.xaml index d743400..0d3a9af 100644 --- a/src/InventorMeta.App/AboutDialog.xaml +++ b/src/InventorMeta.App/Dialogs/AboutDialog.xaml @@ -1,5 +1,5 @@ First-run opt-in prompt for anonymous product analytics. Opt-in is the preselected /// default (the primary "Yes" button is focused). The choice is persisted via diff --git a/src/InventorMeta.App/EngineDialogs.cs b/src/InventorMeta.App/Dialogs/EngineDialogs.cs similarity index 99% rename from src/InventorMeta.App/EngineDialogs.cs rename to src/InventorMeta.App/Dialogs/EngineDialogs.cs index 8dd2991..92aead2 100644 --- a/src/InventorMeta.App/EngineDialogs.cs +++ b/src/InventorMeta.App/Dialogs/EngineDialogs.cs @@ -6,7 +6,7 @@ using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Media.Imaging; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Dialogs; /// Dialogs around the SVF engine choice: the first-use chooser (Inventor vs the built-in /// best-effort converter) and the one-time notice shown when no Inventor is installed. diff --git a/src/InventorMeta.App/SettingsDialog.cs b/src/InventorMeta.App/Dialogs/SettingsDialog.cs similarity index 99% rename from src/InventorMeta.App/SettingsDialog.cs rename to src/InventorMeta.App/Dialogs/SettingsDialog.cs index aa16037..1b9c41b 100644 --- a/src/InventorMeta.App/SettingsDialog.cs +++ b/src/InventorMeta.App/Dialogs/SettingsDialog.cs @@ -6,7 +6,7 @@ using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Media; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Dialogs; /// The app settings dialog. Currently the 3D viewer: which Inventor generates viewables, /// how that Inventor is launched (hidden / silent), an optional shared (network) cache, and clearing diff --git a/src/InventorMeta.App/WhatsNewDialog.cs b/src/InventorMeta.App/Dialogs/WhatsNewDialog.cs similarity index 91% rename from src/InventorMeta.App/WhatsNewDialog.cs rename to src/InventorMeta.App/Dialogs/WhatsNewDialog.cs index 8783459..6ea8563 100644 --- a/src/InventorMeta.App/WhatsNewDialog.cs +++ b/src/InventorMeta.App/Dialogs/WhatsNewDialog.cs @@ -6,7 +6,7 @@ using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Media.Imaging; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Dialogs; /// /// The "What's new" overlay: highlights of the current release with short demo GIFs. Shown @@ -23,6 +23,26 @@ private sealed record Release(string Version, Section[] Sections); private static readonly Release[] Releases = [ + new("1.3.0", + [ + new("Clearer diagnosis of damaged files", + "MetaReader now tells apart the two kinds of damage that make Inventor refuse a " + + "file. A stale segment registry it can still repair in place; destroyed segment " + + "data (zeroed sectors from a disk fault or an interrupted copy) it cannot - and " + + "it says so plainly, naming the affected segments and pointing you to a backup " + + "instead of offering a repair that could never work.", + null), + new("Isolated, more reliable 3D generation", + "Generating a viewable with Inventor now always runs in its own dedicated Inventor " + + "instance that is shut down when it finishes. It never attaches to - or disturbs - " + + "a session you already have open, which makes generation noticeably more robust.", + null), + new("Better logging", + "The app records much more about what it is doing - loads, timings, damage " + + "findings, generation steps and failures - so a problem is far easier to pin down " + + "from the diagnostics log in Settings.", + null), + ]), new("1.2.0", [ new("STEP files", diff --git a/src/InventorMeta.App/Document/DocumentView.Cards.cs b/src/InventorMeta.App/Document/DocumentView.Cards.cs new file mode 100644 index 0000000..7fc0b44 --- /dev/null +++ b/src/InventorMeta.App/Document/DocumentView.Cards.cs @@ -0,0 +1,332 @@ +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using Microsoft.UI.Text; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Windows.ApplicationModel.DataTransfer; + +namespace ExtrabbitCode.Inventor.MetaReader.App.Document; + +/// The shared card and table toolkit: collapsible cards, click-to-copy rows, +/// property tables, key/value lists and matrices used by every detail tab. +public sealed partial class DocumentView +{ + // sort order for property-set cards: key sets first, internal sets last + private static int SetOrder(string set) => set switch + { + _ when set.Contains("(internal)") => 100, + _ when set.StartsWith("Design Tracking Prop") => 0, + "Inventor User Defined Properties" => 1, + "Custom (User Defined) Properties" => 1, + "Inventor Summary Information" => 2, + "Summary Information" => 2, + "Inventor Document Summary Information" => 3, + "Document Summary Information" => 3, + _ => 50, + }; + + // ---- card / table builders ---- + + /// Wraps a row in a hover area with copy (and optional hide) buttons on the right. + private Border CopyableRow(UIElement content, string copyText, Thickness padding, string? hideKey = null) + { + // Selectable text inside the row captures the pointer for selection, which swallows the + // row's tap - so click-to-copy only worked on a fast click. The row copies the whole value + // anyway, so turn selection off here to make the click reliable. + DisableTextSelection(content); + + Grid grid = new(); + grid.Children.Add(content); + + Button btn = new() + { + Content = new FontIcon { Glyph = "", FontSize = 12 }, + VerticalAlignment = VerticalAlignment.Center, + Padding = new Thickness(7, 3, 7, 3), MinWidth = 0, MinHeight = 0, + CornerRadius = new CornerRadius(4), BorderThickness = new Thickness(0), + Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent) + }; + ToolTipService.SetToolTip(btn, "Copy value"); + bool can = !string.IsNullOrEmpty(copyText); + btn.Click += (_, _) => Copy(copyText); + + // hide + copy live in a right-aligned panel that stays in layout (row never resizes) + StackPanel actions = new() + { + Orientation = Orientation.Horizontal, Spacing = 4, + HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, + Opacity = 0, IsHitTestVisible = false + }; + if (hideKey != null) + { + actions.Children.Add(MakeHideButton(hideKey, "Hide this property")); + } + + if (can) + { + actions.Children.Add(btn); + } + + grid.Children.Add(actions); + + Border row = new() + { + Child = grid, Padding = padding, + Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent) // make the whole row hit-testable + }; + if (can) + { + ToolTipService.SetToolTip(row, "Click to copy"); + } + + bool has = can || hideKey != null; + row.PointerEntered += (_, _) => { if (has) { actions.Opacity = 1; actions.IsHitTestVisible = true; } }; + row.PointerExited += (_, _) => { actions.Opacity = 0; actions.IsHitTestVisible = false; }; + row.Tapped += (_, e) => { if (can) { Copy(copyText); e.Handled = true; } }; + return row; + } + + /// Turns off text selection on every TextBlock within a row so it doesn't intercept + /// the row's copy tap. + private static void DisableTextSelection(UIElement element) + { + switch (element) + { + case TextBlock tb: tb.IsTextSelectionEnabled = false; break; + case Panel panel: foreach (UIElement child in panel.Children) { DisableTextSelection(child); } break; + case Border border when border.Child is { } c: DisableTextSelection(c); break; + } + } + + private void Copy(string text) + { + if (string.IsNullOrEmpty(text)) + { + return; + } + + try + { + DataPackage dp = new(); + dp.SetText(text); + Clipboard.SetContent(dp); + string shown = text.Length > 48 ? text[..48] + "…" : text; + (HostWindow ?? App.MainWindowInstance as MainWindow)?.ShowToast($"Copied “{shown}”"); + } + catch + { + // ignored + } + } + + + /// A rounded, bordered, elevated card with a clickable (collapsible) header and a body. + private Border Card(string title, string? badge, UIElement body, string? hideKey = null) + { + FontIcon chevron = new() + { + Glyph = G(ChevronUp), FontSize = 11, Opacity = 0.6, + VerticalAlignment = VerticalAlignment.Center + }; + StackPanel headerContent = new() { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center }; + headerContent.Children.Add(chevron); + headerContent.Children.Add(new TextBlock + { + Text = title, FontWeight = FontWeights.SemiBold, FontSize = 14, + VerticalAlignment = VerticalAlignment.Center, TextWrapping = TextWrapping.Wrap + }); + if (badge != null) + { + headerContent.Children.Add(new Border + { + Style = (Style)Resources["Badge"], + Child = new TextBlock { Text = badge, Style = (Style)Resources["BadgeText"] } + }); + } + + Grid headerGrid = new(); + headerGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + headerGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + headerGrid.Children.Add(headerContent); + + Button? hideBtn = null; + if (hideKey != null) + { + hideBtn = MakeHideButton(hideKey, "Hide this property set"); + hideBtn.Opacity = 0; + hideBtn.IsHitTestVisible = false; + Grid.SetColumn(hideBtn, 1); + headerGrid.Children.Add(hideBtn); + } + + Border header = new() { Style = (Style)Resources["CardHeaderRow"], Child = headerGrid }; + ToolTipService.SetToolTip(header, "Click to collapse / expand"); + if (hideBtn != null) + { + header.PointerEntered += (_, _) => { hideBtn.Opacity = 1; hideBtn.IsHitTestVisible = true; }; + header.PointerExited += (_, _) => { hideBtn.Opacity = 0; hideBtn.IsHitTestVisible = false; }; + } + + StackPanel stack = new(); + stack.Children.Add(header); + stack.Children.Add(body); + + header.Tapped += (_, _) => + { + bool show = body.Visibility == Visibility.Collapsed; + body.Visibility = show ? Visibility.Visible : Visibility.Collapsed; + chevron.Glyph = G(show ? ChevronUp : ChevronDown); + }; + _collapsibles.Add((body, chevron)); + + Border card = new() { Style = (Style)Resources["DataCard"], Child = stack, Margin = new Thickness(0, 0, 0, 8) }; + card.Shadow = new ThemeShadow(); + card.Translation = new Vector3(0, 0, 8); + return card; + } + + /// A pair of buttons that collapse (up) or expand (down) every card in this view. + private UIElement BuildExpandCollapseAll() => new StackPanel + { + Orientation = Orientation.Horizontal, + Spacing = 6, + HorizontalAlignment = HorizontalAlignment.Right, + Children = + { + ExpandCollapseButton(ChevronUp, "Collapse all", false), + ExpandCollapseButton(ChevronDown, "Expand all", true) + } + }; + + private Button ExpandCollapseButton(int glyph, string tooltip, bool expand) + { + Button b = new() + { + Content = new FontIcon { Glyph = G(glyph), FontSize = 12 }, + Padding = new Thickness(11, 6, 11, 6), MinWidth = 0 + }; + ToolTipService.SetToolTip(b, tooltip); + b.Click += (_, _) => SetAllExpanded(expand); + return b; + } + + /// PID / Name / Value table with divider lines between rows. + private StackPanel PropTable(string setName, IEnumerable<(uint pid, string name, string val)> rows) + { + List<(uint pid, string name, string val)> list = rows + .Where(r => !HideStore.IsHidden(HideStore.PropKey(setName, r.pid))).ToList(); + StackPanel sp = new(); + for (int i = 0; i < list.Count; i++) + { + (uint pid, string name, string val) = list[i]; + Grid g = new(); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(46) }); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(196) }); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + Cell(g, 0, pid.ToString(), 0.45, mono: true); + Cell(g, 1, name, 0.9, semibold: true); + Cell(g, 2, val, 0.8); + sp.Children.Add(CopyableRow(g, val, new Thickness(14, 7, 14, 7), HideStore.PropKey(setName, pid))); + } + return sp; + } + + /// Two-column key / value list (plain rows). + private StackPanel KvList(List<(string k, string v)> rows, double keyWidth) + { + StackPanel sp = new(); + for (int i = 0; i < rows.Count; i++) + { + (string k, string v) = rows[i]; + Grid g = new(); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(keyWidth) }); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + Cell(g, 0, k, 0.55); + Cell(g, 1, v, 0.95, semibold: true); + sp.Children.Add(CopyableRow(g, v, new Thickness(14, 7, 14, 7))); + } + return sp; + } + + /// Per-state comparison matrix: a header strip + zebra rows, active column tinted. + private Grid Matrix(string[] headers, List<(string label, string[] vals)> rows) + { + int cols = headers.Length + 1; + Grid grid = new(); + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(200) }); + for (int c = 0; c < headers.Length; c++) + { + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + } + + // header row + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + Border hdr = new() { Style = (Style)Resources["CardHeaderRow"], CornerRadius = new CornerRadius(0) }; + Grid.SetRow(hdr, 0); Grid.SetColumnSpan(hdr, cols); grid.Children.Add(hdr); + MCell(grid, 0, 0, "Property", true, 0.7); + for (int c = 0; c < headers.Length; c++) + { + MCell(grid, 0, c + 1, headers[c], true, 0.7); + } + + for (int ri = 0; ri < rows.Count; ri++) + { + int r = ri + 1; + (string label, string[] vals) = rows[ri]; + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + MCell(grid, r, 0, label, true, 1.0); + for (int c = 0; c < vals.Length; c++) + { + MCell(grid, r, c + 1, vals[c], false, 0.9); + } + } + return grid; + } + + private static void MCell(Grid g, int row, int col, string text, bool semibold, double opacity) + { + TextBlock t = new() + { + Text = text, Opacity = opacity, FontSize = 12, Margin = new Thickness(14, 7, 14, 7), + TextWrapping = TextWrapping.Wrap, IsTextSelectionEnabled = true, + FontWeight = semibold ? FontWeights.SemiBold : FontWeights.Normal + }; + Grid.SetRow(t, row); Grid.SetColumn(t, col); + g.Children.Add(t); + } + + private static void Cell(Grid g, int col, string text, double opacity, bool semibold = false, bool mono = false) + { + TextBlock t = new() + { + Text = text, Opacity = opacity, FontSize = 12, TextWrapping = TextWrapping.Wrap, + IsTextSelectionEnabled = true, VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(0, 0, 10, 0), + FontWeight = semibold ? FontWeights.SemiBold : FontWeights.Normal + }; + if (mono) + { + t.FontFamily = new FontFamily("Consolas"); + } + + Grid.SetColumn(t, col); + g.Children.Add(t); + } + + private Border KeyRow(string label, string value) + { + Grid g = new(); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(118) }); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + TextBlock l = new() { Text = label, Opacity = 0.6, FontSize = 12, TextWrapping = TextWrapping.Wrap }; + TextBlock v = new() + { Text = value, FontSize = 13, TextWrapping = TextWrapping.Wrap, + IsTextSelectionEnabled = true, Margin = new Thickness(0, 0, 8, 0) }; + Grid.SetColumn(v, 1); + g.Children.Add(l); g.Children.Add(v); + return CopyableRow(g, value, new Thickness(0, 3, 0, 3)); + } + +} diff --git a/src/InventorMeta.App/DocumentView.RefGraph.cs b/src/InventorMeta.App/Document/DocumentView.RefGraph.cs similarity index 99% rename from src/InventorMeta.App/DocumentView.RefGraph.cs rename to src/InventorMeta.App/Document/DocumentView.RefGraph.cs index a3d29d8..bb0fdd1 100644 --- a/src/InventorMeta.App/DocumentView.RefGraph.cs +++ b/src/InventorMeta.App/Document/DocumentView.RefGraph.cs @@ -11,7 +11,7 @@ using Microsoft.UI.Xaml.Media; using Microsoft.Web.WebView2.Core; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Document; /// /// The reference graph, rendered with the bundled vis-network library inside a WebView2: interactive diff --git a/src/InventorMeta.App/Document/DocumentView.References.cs b/src/InventorMeta.App/Document/DocumentView.References.cs new file mode 100644 index 0000000..cfbbb70 --- /dev/null +++ b/src/InventorMeta.App/Document/DocumentView.References.cs @@ -0,0 +1,530 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using Microsoft.UI.Text; +using Microsoft.UI.Windowing; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Input; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Imaging; + +namespace ExtrabbitCode.Inventor.MetaReader.App.Document; + +/// The References tab: the inline canvas node graph (layout, pan/zoom, node boxes) +/// and reference opening. +public sealed partial class DocumentView +{ + // ---- references node graph ----------------------------------------------------- + private int _refGen; + + private void PopulateReferences(InventorDocument doc) + { + RefsRoot.RowDefinitions.Clear(); + RefsRoot.Children.Clear(); + + // version/provenance details - version history first, then schema/template + string[] detailOrder = ["Current Version", "Previous Version", "Next Version", "Last update with", "Last saved by"]; + List<(string, string)> provItems = []; + foreach (string k in detailOrder) + { + if (doc.VersionInfo.TryGetValue(k, out string? v)) { provItems.Add((k, v)); } + } + foreach (KeyValuePair kv in doc.VersionInfo) + { + if (!detailOrder.Contains(kv.Key)) { provItems.Add((kv.Key, kv.Value)); } + } + StackPanel details = KeyValueSection("Version", provItems); + + // Graph fills the top (star); the short version panel docks below it (auto), never scrolling. + RefsRoot.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); + RefsRoot.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + Border graphHost = new(); + Grid.SetRow(graphHost, 0); + RefsRoot.Children.Add(graphHost); + + Border prov = new() + { + BorderThickness = new Thickness(0, 1, 0, 0), + BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(40, 128, 128, 128)), + Padding = new Thickness(14, 10, 14, 12), + Child = details + }; + Grid.SetRow(prov, 1); + RefsRoot.Children.Add(prov); + + if (doc.References.Count == 0) + { + graphHost.Child = GraphInfo("No referenced files."); + return; + } + + int gen = ++_refGen; + _ = BuildAndShowGraphAsync(doc, graphHost, gen); + } + + private async Task BuildAndShowGraphAsync(InventorDocument doc, Border host, int gen) + { + if (doc.References.Count == 0) + { + host.Child = GraphInfo("No referenced files."); + return; + } + + host.Child = GraphInfo("Building reference graph…"); + + RefNode? root = null; + try { root = await Task.Run(() => ReferenceGraph.Build(doc)); } + catch (Exception ex) { Serilog.Log.Error(ex, "Reference graph build failed for {File}", doc.FileName); } + + if (gen != _refGen) + { + return; // a newer load superseded this build + } + + host.Child = root != null ? RenderRefGraphWeb(root, host) : GraphInfo("Couldn't build the reference graph."); + } + + private static TextBlock GraphInfo(string text) => new() + { + Text = text, Opacity = 0.6, Margin = new Thickness(20), + HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center + }; + + private bool _graphFs; + private bool _showThumbs; + private GraphLayout _graphLayout; + + // Set while the reference graph is mounted: exits its fullscreen overlay. Lets the + // node "open" actions drop out of fullscreen before switching to the opened tab. + private Action? _exitGraphFullscreen; + + /// Opens a referenced document in a tab. If the reference graph is currently + /// fullscreen, leave fullscreen first so the newly opened (and selected) tab is visible. + private void OpenReference(string path) + { + Analytics.Capture("reference_opened"); + if (_graphFs) { _exitGraphFullscreen?.Invoke(); } + HostWindow?.OpenDocument(path); + } + + private UIElement RenderRefGraph(RefNode root, Border host) + { + // start with only level 1 visible: root expanded, everything deeper collapsed + ForEachNode(root, n => n.Expanded = n.Depth == 0); + + CompositeTransform xf = new(); + Canvas canvas = new() + { + Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), + RenderTransform = xf, + // pin to the viewport's top-left so the pan/zoom transform's origin is (0,0) + HorizontalAlignment = HorizontalAlignment.Left, + VerticalAlignment = VerticalAlignment.Top + }; + + // Pan/zoom via a render transform on a clipped viewport. We avoid ScrollViewer: its + // ZoomMode + a Canvas hits a WinUI "Layout cycle detected" crash, and it also eats + // the left-drag we want for panning. + Grid viewport = new() { Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent) }; + bool fitted = false; + viewport.SizeChanged += (_, e) => + { + viewport.Clip = new RectangleGeometry { Rect = new Windows.Foundation.Rect(0, 0, e.NewSize.Width, e.NewSize.Height) }; + if (!fitted && e.NewSize.Width > 0 && e.NewSize.Height > 0) + { + fitted = true; + ZoomToFit(viewport, canvas, xf); + } + }; + viewport.Children.Add(canvas); + + LayoutAndDraw(canvas, root); + WirePanZoom(viewport, canvas, xf); + + // floating toolbar (top-right) + StackPanel toolbar = new() + { + Orientation = Orientation.Horizontal, Spacing = 4, + HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top, + Margin = new Thickness(0, 8, 14, 0) + }; + static Button IconBtn(int glyph, string tip) + { + Button b = new() { Content = new FontIcon { Glyph = G(glyph), FontSize = 14 }, + Padding = new Thickness(8, 5, 8, 5), MinWidth = 0 }; + ToolTipService.SetToolTip(b, tip); + return b; + } + + Button fit = IconBtn(0xE9A6, "Fit to view"); + fit.Click += (_, _) => ZoomToFit(viewport, canvas, xf); + Button expandAll = IconBtn(0xE710, "Expand all"); + expandAll.Click += (_, _) => { ForEachNode(root, n => n.Expanded = n.Children.Count > 0); LayoutAndDraw(canvas, root); }; + Button collapseAll = IconBtn(0xE738, "Collapse all"); + collapseAll.Click += (_, _) => { ForEachNode(root, n => n.Expanded = n.Depth == 0); LayoutAndDraw(canvas, root); }; + + // thumbnails toggle: redraw the graph with each node showing its document's preview + ToggleButton thumbs = new() + { + Content = new FontIcon { Glyph = G(0xE8B9), FontSize = 14 }, + Padding = new Thickness(8, 5, 8, 5), MinWidth = 0, IsChecked = _showThumbs + }; + ToolTipService.SetToolTip(thumbs, "Show thumbnails"); + thumbs.Click += (_, _) => + { + _showThumbs = thumbs.IsChecked == true; + LayoutAndDraw(canvas, root); + // re-fit after the relayout settles + DispatcherQueue.TryEnqueue(() => ZoomToFit(viewport, canvas, xf)); + }; + + // Fullscreen: pop the whole viewport (graph + this toolbar) into a window-filling overlay + // and switch the OS window to true fullscreen; the button toggles back, as does Esc. + FontIcon fullIcon = new() { Glyph = G(0xE740), FontSize = 14 }; + Button full = new() { Content = fullIcon, Padding = new Thickness(8, 5, 8, 5), MinWidth = 0 }; + ToolTipService.SetToolTip(full, "Fullscreen"); + Grid? overlay = null; + void SetFullscreen(bool on) + { + MainWindow? win = HostWindow; + if (win is null || on == _graphFs) { return; } + + if (on) + { + host.Child = null; // detach from the References tab + overlay = new Grid(); + overlay.Children.Add(viewport); + win.ShowOverlay(overlay); + win.AppWindow.SetPresenter(AppWindowPresenterKind.FullScreen); + _graphFs = true; + Analytics.Capture("references_fullscreen"); + } + else + { + win.AppWindow.SetPresenter(AppWindowPresenterKind.Default); + overlay?.Children.Remove(viewport); + win.HideOverlay(); + host.Child = viewport; // reattach to the tab + overlay = null; + _graphFs = false; + } + + fullIcon.Glyph = G(_graphFs ? 0xE73F : 0xE740); // BackToWindow / FullScreen + ToolTipService.SetToolTip(full, _graphFs ? "Exit fullscreen" : "Fullscreen"); + fitted = false; // re-fit once the new size settles + full.Focus(FocusState.Programmatic); + } + full.Click += (_, _) => SetFullscreen(!_graphFs); + _exitGraphFullscreen = () => SetFullscreen(false); + KeyboardAccelerator esc = new() { Key = Windows.System.VirtualKey.Escape }; + esc.Invoked += (_, e) => { if (_graphFs) { SetFullscreen(false); e.Handled = true; } }; + full.KeyboardAccelerators.Add(esc); + + toolbar.Children.Add(fit); + toolbar.Children.Add(expandAll); + toolbar.Children.Add(collapseAll); + toolbar.Children.Add(thumbs); + toolbar.Children.Add(full); + viewport.Children.Add(toolbar); + + // Discoverability tip: point at the thumbnails toggle (unless already on). + if (!_showThumbs) + { + TipService.Show(viewport, thumbs, new Tip + { + Id = "refs.thumbnails", + Title = "Did you know?", + Message = "You can show each referenced file's preview thumbnail right in the graph.", + ActionText = "Show thumbnails", + Action = () => + { + thumbs.IsChecked = true; + _showThumbs = true; + LayoutAndDraw(canvas, root); + ZoomToFit(viewport, canvas, xf); + } + }); + } + + return viewport; + } + + /// Scales and centres the graph so all of it fits the viewport (zoom extents). + private static void ZoomToFit(Grid viewport, Canvas canvas, CompositeTransform xf) + { + double vw = viewport.ActualWidth, vh = viewport.ActualHeight, cw = canvas.Width, ch = canvas.Height; + if (vw <= 0 || vh <= 0 || cw <= 0 || ch <= 0) { return; } + + const double margin = 28; + double scale = Math.Clamp(Math.Min((vw - margin) / cw, (vh - margin) / ch), 0.2, 1.0); + xf.ScaleX = xf.ScaleY = scale; + xf.TranslateX = (vw - cw * scale) / 2; + xf.TranslateY = (vh - ch * scale) / 2; + } + + private static void ForEachNode(RefNode n, Action action) + { + action(n); + foreach (RefNode c in n.Children) { ForEachNode(c, action); } + } + + /// Lays out the visible (expanded) part of the tree and (re)draws the canvas. + private void LayoutAndDraw(Canvas canvas, RefNode root) + { + const double colStep = 300, pad = 16; + // bigger nodes when thumbnails are shown so each preview has room + double nodeW = _showThumbs ? 252 : 224; + double nodeH = _showThumbs ? 104 : 56; + double rowStep = _showThumbs ? 120 : 74; + + // tidy left-to-right layout over visible nodes; a collapsed node counts as a leaf + int leaf = 0, maxDepth = 0; + void Assign(RefNode n) + { + maxDepth = Math.Max(maxDepth, n.Depth); + if (!n.Expanded || n.Children.Count == 0) { n.Row = leaf++; return; } + foreach (RefNode c in n.Children) { Assign(c); } + n.Row = (n.Children[0].Row + n.Children[^1].Row) / 2.0; + } + Assign(root); + + List vis = []; + void Collect(RefNode n) { vis.Add(n); if (n.Expanded) { foreach (RefNode c in n.Children) { Collect(c); } } } + Collect(root); + + double X(RefNode n) => pad + n.Depth * colStep; + double Y(RefNode n) => pad + n.Row * rowStep; + + canvas.Children.Clear(); + canvas.Width = pad * 2 + maxDepth * colStep + nodeW; + canvas.Height = pad * 2 + Math.Max(0, leaf - 1) * rowStep + nodeH; + + Brush link = new SolidColorBrush(Windows.UI.Color.FromArgb(150, 130, 130, 130)); + foreach (RefNode n in vis) + { + if (!n.Expanded) { continue; } + foreach (RefNode c in n.Children) + { + double sx = X(n) + nodeW, sy = Y(n) + nodeH / 2, ex = X(c), ey = Y(c) + nodeH / 2; + double dx = (ex - sx) * 0.5; + PathFigure fig = new() { StartPoint = new Windows.Foundation.Point(sx, sy) }; + fig.Segments.Add(new BezierSegment + { + Point1 = new Windows.Foundation.Point(sx + dx, sy), + Point2 = new Windows.Foundation.Point(ex - dx, ey), + Point3 = new Windows.Foundation.Point(ex, ey) + }); + PathGeometry geo = new(); + geo.Figures.Add(fig); + canvas.Children.Add(new Microsoft.UI.Xaml.Shapes.Path { Data = geo, Stroke = link, StrokeThickness = 1.5 }); + } + } + + foreach (RefNode n in vis) + { + Border box = RefNodeBox(n, nodeW, nodeH, canvas, root); + Canvas.SetLeft(box, X(n)); + Canvas.SetTop(box, Y(n)); + canvas.Children.Add(box); + } + } + + private Border RefNodeBox(RefNode n, double w, double h, Canvas canvas, RefNode root) + { + Grid g = new() { ColumnSpacing = 8, Padding = new Thickness(10, 6, 8, 6) }; + g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + + ImageSource? thumb = _showThumbs ? BitmapFromBytes(n.Thumbnail) : null; + FrameworkElement iconEl; + if (thumb != null) + { + iconEl = new Border + { + Width = h - 20, Height = h - 20, CornerRadius = new CornerRadius(4), + VerticalAlignment = VerticalAlignment.Center, + Background = new SolidColorBrush(Windows.UI.Color.FromArgb(28, 128, 128, 128)), + Child = new Image { Source = thumb, Stretch = Stretch.Uniform, Margin = new Thickness(2) } + }; + } + else if (n.IsLinkedFile) + { + iconEl = new FontIcon { Glyph = G(IsImageFile(n.Name) ? 0xE8B9 : 0xE7C3), + FontSize = _showThumbs ? 40 : 22, Width = _showThumbs ? 56 : 30, Opacity = 0.85, + VerticalAlignment = VerticalAlignment.Center }; + } + else + { + double s = _showThumbs ? 48 : 30; + iconEl = new Image { Width = s, Height = s, Source = AppIcons.Bitmap(n.Kind), + VerticalAlignment = VerticalAlignment.Center }; + } + + StackPanel text = new() { VerticalAlignment = VerticalAlignment.Center }; + text.Children.Add(new TextBlock { Text = n.Name, FontWeight = FontWeights.SemiBold, FontSize = 13, + TextTrimming = TextTrimming.CharacterEllipsis }); + // iPart classification (done in the core graph): model-state parts carry the same marker + // but aren't iParts, so they classify as neither. + bool isMember = n.IPart == IPartRole.Member; + bool isFactory = n.IPart == IPartRole.Factory; + + string sub = n.Cyclic ? "↻ already shown above" + : !n.Resolved ? (n.IsLinkedFile ? "linked file - not found" : "file not found") + : n.ReadError ? "unreadable" + : n.IsLinkedFile ? "linked " + Path.GetExtension(n.Name).TrimStart('.').ToLowerInvariant() + : isFactory ? "iPart factory" + : isMember ? "iPart member" + : KindLabel(n.Kind); + TextBlock subtitle = new() { Text = sub, FontSize = 11, Opacity = 0.6, TextTrimming = TextTrimming.CharacterEllipsis }; + if (!n.Resolved) + { + subtitle.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 209, 96, 96)); + subtitle.Opacity = 0.95; + } + else if (isFactory || isMember) + { + subtitle.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 214, 158, 46)); // gold + subtitle.Opacity = 1.0; + subtitle.FontWeight = FontWeights.SemiBold; + } + text.Children.Add(subtitle); + Grid.SetColumn(text, 1); + g.Children.Add(iconEl); + g.Children.Add(text); + + // +/- toggle for nodes that have children + if (n.Children.Count > 0) + { + Button toggle = new() + { + Width = 24, Height = 24, MinWidth = 0, Padding = new Thickness(0), + CornerRadius = new CornerRadius(12), VerticalAlignment = VerticalAlignment.Center, + Content = new FontIcon { Glyph = G(n.Expanded ? 0xE738 : 0xE710), FontSize = 11 } + }; + ToolTipService.SetToolTip(toggle, n.Expanded ? "Collapse" : $"Expand ({n.Children.Count})"); + toggle.Click += (_, _) => { n.Expanded = !n.Expanded; LayoutAndDraw(canvas, root); }; + Grid.SetColumn(toggle, 2); + g.Children.Add(toggle); + } + + Border box = new() { Style = (Style)Resources["DataCard"], Width = w, Height = h, Child = g }; + if (n.Depth == 0) + { + box.BorderBrush = (Brush)Application.Current.Resources["AccentFillColorDefaultBrush"]; + box.BorderThickness = new Thickness(2); + } + else if (isFactory) + { + box.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 214, 158, 46)); // gold + box.BorderThickness = new Thickness(2); + } + ToolTipService.SetToolTip(box, n.Path); + + bool canOpen = n.Resolved && n.Depth > 0 && !n.Cyclic && !n.IsLinkedFile; + if (canOpen) + { + box.Tapped += (_, _) => OpenReference(n.Path); + ToolTipService.SetToolTip(box, n.Path + "\nClick to open · right-click for more"); + } + + if (n.Resolved) + { + box.ContextRequested += (_, e) => + { + MenuFlyout menu = new(); + if (canOpen) + { + MenuFlyoutItem open = new() { Text = "Open in a tab", Icon = new FontIcon { Glyph = G(0xE8E5) } }; + open.Click += (_, _) => OpenReference(n.Path); + menu.Items.Add(open); + } + MenuFlyoutItem reveal = new() { Text = "Show in Explorer", Icon = new FontIcon { Glyph = G(0xEC50) } }; + reveal.Click += (_, _) => RevealInExplorer(n.Path); + menu.Items.Add(reveal); + if (e.TryGetPosition(box, out Windows.Foundation.Point p)) { menu.ShowAt(box, p); } + else { menu.ShowAt(box); } + e.Handled = true; + }; + } + return box; + } + + private static bool IsImageFile(string name) => + Path.GetExtension(name).ToLowerInvariant() is ".png" or ".jpg" or ".jpeg" or ".bmp" or ".tif" or ".tiff" or ".gif"; + + /// Decodes raw image bytes (a document's cached preview) into a usable image source. + private static ImageSource? BitmapFromBytes(byte[]? bytes) + { + if (bytes is not { Length: > 0 }) { return null; } + try + { + BitmapImage bmp = new(); + using MemoryStream ms = new(bytes); + bmp.SetSource(ms.AsRandomAccessStream()); + return bmp; + } + catch { return null; } + } + + /// Left-drag on empty space (or middle-drag anywhere) pans; wheel zooms at the cursor. + private static void WirePanZoom(Grid viewport, Canvas canvas, CompositeTransform xf) + { + bool panning = false; + Windows.Foundation.Point start = default; + double tx0 = 0, ty0 = 0; + + viewport.PointerPressed += (_, e) => + { + Microsoft.UI.Input.PointerPoint pp = e.GetCurrentPoint(viewport); + bool onBackground = ReferenceEquals(e.OriginalSource, canvas) || ReferenceEquals(e.OriginalSource, viewport); + if (!pp.Properties.IsMiddleButtonPressed && !(pp.Properties.IsLeftButtonPressed && onBackground)) + { + return; + } + panning = true; start = pp.Position; tx0 = xf.TranslateX; ty0 = xf.TranslateY; + viewport.CapturePointer(e.Pointer); + }; + viewport.PointerMoved += (_, e) => + { + if (!panning) { return; } + Windows.Foundation.Point p = e.GetCurrentPoint(viewport).Position; + xf.TranslateX = tx0 + (p.X - start.X); + xf.TranslateY = ty0 + (p.Y - start.Y); + }; + void End(object _, Microsoft.UI.Xaml.Input.PointerRoutedEventArgs e) + { + if (panning) { panning = false; viewport.ReleasePointerCapture(e.Pointer); } + } + viewport.PointerReleased += End; + viewport.PointerCanceled += End; + viewport.PointerCaptureLost += (_, _) => panning = false; + + viewport.PointerWheelChanged += (_, e) => + { + Microsoft.UI.Input.PointerPoint pp = e.GetCurrentPoint(viewport); + double factor = pp.Properties.MouseWheelDelta > 0 ? 1.12 : 1 / 1.12; + double scale = Math.Clamp(xf.ScaleX * factor, 0.2, 3.0); + factor = scale / xf.ScaleX; + Windows.Foundation.Point c = pp.Position; + xf.TranslateX = c.X - (c.X - xf.TranslateX) * factor; + xf.TranslateY = c.Y - (c.Y - xf.TranslateY) * factor; + xf.ScaleX = xf.ScaleY = scale; + e.Handled = true; + }; + } + + private static string KindLabel(InventorDocument.DocKind k) => k switch + { + InventorDocument.DocKind.Part => "Part", + InventorDocument.DocKind.Assembly => "Assembly", + InventorDocument.DocKind.Drawing => "Drawing", + InventorDocument.DocKind.Presentation => "Presentation", + InventorDocument.DocKind.Step => "STEP", + _ => "Document" + }; +} diff --git a/src/InventorMeta.App/Document/DocumentView.Repair.cs b/src/InventorMeta.App/Document/DocumentView.Repair.cs new file mode 100644 index 0000000..59e445b --- /dev/null +++ b/src/InventorMeta.App/Document/DocumentView.Repair.cs @@ -0,0 +1,324 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.UI.Text; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; + +namespace ExtrabbitCode.Inventor.MetaReader.App.Document; + +/// The segment-repair flow: the "Damaged file" badge, the one-time risk warning, the +/// in-place repair with backup, and the post-repair "Open in Inventor" shortcut. +public sealed partial class DocumentView +{ + /// True once this view repaired the current file; keeps the "Repaired" chip and its + /// "Open in Inventor" shortcut visible until another file is loaded into the view. + private bool _repairedThisSession; + + /// Shows the "Damaged file" badge when the file carries stale segment summaries + /// (with the repair button - that class is fixable in place) or destroyed segment data + /// (without it - nothing can repair that; the tooltip explains why and points at backups). + /// Right after this view repaired the file, the "Repaired" chip with an Inventor shortcut + /// shows instead. The destroyed-data check decompresses every segment, so it runs in the + /// background and upgrades the badge when it lands. + private void SetDamageBadge(InventorDocument doc) + { + bool repairable = !doc.IsStep && doc.HasRepairableSegmentDamage; + DamagePanel.Visibility = repairable ? Visibility.Visible : Visibility.Collapsed; + RepairButton.Visibility = Visibility.Visible; + RepairedPanel.Visibility = !repairable && _repairedThisSession ? Visibility.Visible : Visibility.Collapsed; + if (repairable) + { + Serilog.Log.Warning("Repairable segment damage in {File}: {Issues}", + doc.FileName, string.Join("; ", doc.SegmentIssues)); + StackPanel tip = new() { Spacing = 4, Padding = new Thickness(2), MaxWidth = 420 }; + tip.Children.Add(new TextBlock + { + Text = "The segment registry disagrees with the data actually stored - Inventor refuses " + + "to open the file (\"the number of objects found in the segment does not match the " + + "segment summary\"):", + TextWrapping = TextWrapping.Wrap + }); + foreach (SegmentRepair.Issue issue in doc.SegmentIssues) + { + string where = issue.Location.Length == 0 ? "" : $" ({issue.Location})"; + tip.Children.Add(new TextBlock + { + Text = $"• {issue.SegmentName}{where}: summary says {issue.SummaryCount:N0} blocks, {issue.ActualCount:N0} are present", + FontWeight = FontWeights.SemiBold + }); + } + tip.Children.Add(new TextBlock + { + Text = "Repair updates the summaries in place - no model data is touched, and an untouched " + + "backup copy is saved next to the file first.", + Opacity = 0.7, TextWrapping = TextWrapping.Wrap + }); + ToolTipService.SetToolTip(DamageBadge, new ToolTip { Content = tip }); + } + + if (!doc.IsStep) + { + _ = UpgradeBadgeForDestroyedDataAsync(doc); + } + } + + /// Runs the deep payload check off the UI thread; when it finds destroyed segment + /// data, the badge switches to the not-repairable presentation: no repair button (a repair + /// cannot bring destroyed bytes back and would fail), a tooltip that explains the damage and + /// says what actually helps - restoring a backup. + private async Task UpgradeBadgeForDestroyedDataAsync(InventorDocument doc) + { + IReadOnlyList damage; + System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew(); + try + { + damage = await Task.Run(() => doc.DataDamage); + } + catch (Exception ex) + { + Serilog.Log.Debug(ex, "Deep segment data check failed for {File}", doc.FileName); + return; // unreadable container -> no verdict, keep the current badge + } + + Serilog.Log.Debug("Deep segment data check for {File}: {Count} damaged segment(s) in {Ms} ms", + doc.FileName, damage.Count, sw.ElapsedMilliseconds); + if (damage.Count == 0 || !ReferenceEquals(Document, doc)) + { + return; // healthy, or the view moved on to another file meanwhile + } + + Serilog.Log.Warning("Destroyed segment data in {File}: {Damage} - not repairable, a backup must be restored", + doc.FileName, string.Join("; ", damage)); + + DamagePanel.Visibility = Visibility.Visible; + RepairButton.Visibility = Visibility.Collapsed; + RepairedPanel.Visibility = Visibility.Collapsed; + + StackPanel tip = new() { Spacing = 4, Padding = new Thickness(2), MaxWidth = 440 }; + tip.Children.Add(new TextBlock + { + Text = "Parts of this file's internal database are destroyed - runs of zeroed bytes sit " + + "where compressed segment data used to be, the typical result of a disk fault or " + + "an interrupted copy:", + TextWrapping = TextWrapping.Wrap + }); + foreach (SegmentDataCheck.Damage d in damage) + { + string where = d.Location.Length == 0 ? "" : $" ({d.Location})"; + string detail = d.ChecksumOnly + ? "content silently altered" + : $"only {FormatSize(d.RecoveredBytes)} of at least {FormatSize(d.ExpectedBytes)} readable"; + tip.Children.Add(new TextBlock + { + Text = $"• {d.SegmentName}{where}: {detail}", + FontWeight = FontWeights.SemiBold + }); + } + tip.Children.Add(new TextBlock + { + Text = "No repair is offered because none can work: the destroyed bytes are physically " + + "gone, the compressed stream cannot be re-synchronized past the damage, and " + + "Inventor needs every segment intact to open a file. Restore an older version " + + "instead - Vault or another PDM, the OldVersions folder next to the file, or a backup.", + Opacity = 0.7, TextWrapping = TextWrapping.Wrap + }); + ToolTipService.SetToolTip(DamageBadge, new ToolTip { Content = tip }); + StatusSink?.Invoke("Segment data is destroyed in this file - not repairable; restore a backup. Hover the badge for details."); + } + + /// Settings key remembering that the user has read and typed away the one-time + /// repair risk warning on this machine. + private const string RepairAckKey = "RepairRiskAcknowledged"; + private const string RepairAckPhrase = "I understand the risk"; + + /// The one-time gate in front of the repair: a prominent warning that the repair + /// rewrites the file's internal database and is a last resort, acknowledged by typing a fixed + /// phrase. Returns true when the user typed it (remembered via ). + private async Task ConfirmRepairRiskOnceAsync() + { + if (AppSettings.GetBool(RepairAckKey, false)) + { + return true; + } + + TextBox ackBox = new() { PlaceholderText = RepairAckPhrase, Margin = new Thickness(0, 6, 0, 0) }; + StackPanel content = new() { Spacing = 10, MaxWidth = 480 }; + content.Children.Add(new StackPanel + { + Orientation = Orientation.Horizontal, Spacing = 10, + Children = + { + new FontIcon + { + Glyph = G(0xE7BA), FontSize = 26, // warning triangle + Foreground = new Microsoft.UI.Xaml.Media.SolidColorBrush(DamageRed), + VerticalAlignment = VerticalAlignment.Center + }, + new TextBlock + { + Text = "This repair rewrites the file's internal database.", + FontWeight = FontWeights.SemiBold, TextWrapping = TextWrapping.Wrap, + VerticalAlignment = VerticalAlignment.Center, MaxWidth = 420 + } + } + }); + content.Children.Add(new TextBlock + { + TextWrapping = TextWrapping.Wrap, + Text = "MetaReader patches the RSeStorage segment registry inside the Inventor file - a " + + "proprietary structure Autodesk offers no supported way to modify. Treat this as a " + + "last resort:\n\n" + + "• First try to restore a healthy version instead - Vault or another PDM, the " + + "OldVersions folder, or a backup.\n" + + "• An untouched backup copy is saved next to the file before every repair. " + + "Keep it until the result is verified.\n" + + "• Always open the repaired file in Autodesk Inventor and check it before you " + + "continue working with it." + }); + content.Children.Add(new TextBlock + { + TextWrapping = TextWrapping.Wrap, Opacity = 0.85, + Text = $"Type \"{RepairAckPhrase}\" to enable the repair. You are only asked once on this computer." + }); + content.Children.Add(ackBox); + + ContentDialog dlg = new() + { + Title = "Read this before repairing", + XamlRoot = XamlRoot, + PrimaryButtonText = "Continue", + CloseButtonText = "Cancel", + DefaultButton = ContentDialogButton.Close, + IsPrimaryButtonEnabled = false, + Content = content, + }; + ackBox.TextChanged += (_, _) => + dlg.IsPrimaryButtonEnabled = string.Equals(ackBox.Text.Trim(), RepairAckPhrase, StringComparison.OrdinalIgnoreCase); + + if (await dlg.ShowAsync() != ContentDialogResult.Primary) + { + return false; + } + + AppSettings.Set(RepairAckKey, "True"); + Analytics.Capture("repair_risk_acknowledged"); + return true; + } + + private async void OnRepairSegments(object sender, RoutedEventArgs e) + { + if (Document == null || !Document.HasRepairableSegmentDamage || !RepairButton.IsEnabled) + { + return; + } + + // Disabled for the whole flow: a queued second click would otherwise open a second + // ContentDialog on this XamlRoot, which WinUI answers with an unhandled COMException. + RepairButton.IsEnabled = false; + try + { + if (!await ConfirmRepairRiskOnceAsync()) + { + return; + } + + string names = string.Join(", ", Document.SegmentIssues.Select(i => i.SegmentName).Distinct()); + ContentDialog dlg = new() + { + Title = "Repair the segment database?", + XamlRoot = XamlRoot, + PrimaryButtonText = "Repair", + CloseButtonText = "Cancel", + DefaultButton = ContentDialogButton.Primary, + Content = new TextBlock + { + Text = $"{Document.SegmentIssues.Count} stale segment summar{(Document.SegmentIssues.Count == 1 ? "y" : "ies")} " + + $"({names}) will be patched in place so Inventor opens the file again.\n\n" + + "No model data is changed. An untouched backup copy is saved next to the file first.", + TextWrapping = TextWrapping.Wrap + }, + }; + if (await dlg.ShowAsync() != ContentDialogResult.Primary) + { + return; + } + + // Repair rescans the file fresh - when someone fixed it since this view loaded, + // nothing is patched, no backup exists, and the UI must not claim otherwise. + Serilog.Log.Information("Repairing segment summaries in {File}", FilePath); + SegmentRepair.RepairResult result = SegmentRepair.Repair(FilePath); + if (result.Repaired.Count == 0) + { + StatusSink?.Invoke("Nothing to repair - the file is already consistent (fixed outside this view?)."); + } + else + { + StatusSink?.Invoke($"Repaired {result.Repaired.Count} segment summar{(result.Repaired.Count == 1 ? "y" : "ies")}; " + + $"backup saved as {Path.GetFileName(result.BackupPath)}."); + Analytics.Capture("segments_repaired", new Dictionary + { + ["segments"] = result.Repaired.Count, + ["doc_kind"] = Document.Kind.ToString(), + }); + _repairedThisSession = true; // Refresh -> SetDamageBadge swaps in the "Repaired" chip + } + Refresh(); + } + catch (Exception ex) + { + Serilog.Log.Error(ex, "Repair failed for {File}", FilePath); + StatusSink?.Invoke("Repair failed: " + ex.Message); + } + finally + { + RepairButton.IsEnabled = true; + } + } + + /// Hands the (just repaired) file to Autodesk Inventor - a running session when one is + /// up, otherwise the preferred release is launched - so the fix can be verified immediately. + private async void OnOpenInInventor(object sender, RoutedEventArgs e) + { + if (HostWindow is not MainWindow win || !OpenInInventorButton.IsEnabled) + { + return; + } + + // Disabled before the first await: ResolveInventorAsync can show the version-chooser + // dialog, and a double-click reaching a second ShowAsync would crash the app. + OpenInInventorButton.IsEnabled = false; + try + { + InventorInstall? inventor = await ResolveInventorAsync(win); + if (inventor == null) + { + StatusSink?.Invoke("No Autodesk Inventor installation was found on this machine."); + return; + } + + StatusSink?.Invoke($"Opening {Path.GetFileName(FilePath)} in {inventor.DisplayName}…"); + string? error = await InventorOpener.OpenAsync(inventor, FilePath); + StatusSink?.Invoke(error == null + ? $"{Path.GetFileName(FilePath)} is open in Inventor." + : "Inventor could not open the file: " + error); + Analytics.Capture("opened_in_inventor", new Dictionary + { + ["after_repair"] = _repairedThisSession, + ["succeeded"] = error == null, + }); + } + catch (Exception ex) + { + Serilog.Log.Error(ex, "Open in Inventor failed for {File}", FilePath); + StatusSink?.Invoke("Could not open the file in Inventor: " + ex.Message); + } + finally + { + OpenInInventorButton.IsEnabled = true; + } + } + +} diff --git a/src/InventorMeta.App/DocumentView.Shoot.cs b/src/InventorMeta.App/Document/DocumentView.Shoot.cs similarity index 93% rename from src/InventorMeta.App/DocumentView.Shoot.cs rename to src/InventorMeta.App/Document/DocumentView.Shoot.cs index 477a7b6..faafba2 100644 --- a/src/InventorMeta.App/DocumentView.Shoot.cs +++ b/src/InventorMeta.App/Document/DocumentView.Shoot.cs @@ -8,7 +8,7 @@ using Windows.Foundation; using Windows.Storage.Streams; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Document; /// Helpers used only by the documentation snapshotter (). public sealed partial class DocumentView @@ -31,6 +31,20 @@ public void ShootSelectTab(string headerPrefix) /// region (e.g. the sidebar card or a single detail panel). public FrameworkElement? ShootElement(string name) => FindName(name) as FrameworkElement; + /// Opens the category badge's hover legend (demo tour). The tour's cursor is painted + /// into the window and never moves the OS pointer, so it can't raise a real hover tooltip - + /// this pops the same legend directly. + internal void ShootShowCategoryLegend() + { + if (_categoryTip != null) { _categoryTip.IsOpen = true; } + } + + /// Closes the category badge legend opened by . + internal void ShootHideCategoryLegend() + { + if (_categoryTip != null) { _categoryTip.IsOpen = false; } + } + /// The header element of a detail tab, so the demo tour can move the cursor onto it /// before switching (snapshotter). internal FrameworkElement? ShootTabHeader(string headerPrefix) => diff --git a/src/InventorMeta.App/Document/DocumentView.Sidebar.cs b/src/InventorMeta.App/Document/DocumentView.Sidebar.cs new file mode 100644 index 0000000..df2cc69 --- /dev/null +++ b/src/InventorMeta.App/Document/DocumentView.Sidebar.cs @@ -0,0 +1,335 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.UI.Text; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Windows.ApplicationModel.DataTransfer; + +namespace ExtrabbitCode.Inventor.MetaReader.App.Document; + +/// The configurable left sidebar: rendering, edit mode, drag-to-reorder and the +/// add/remove property flow. +public sealed partial class DocumentView +{ + // ---- configurable left sidebar ------------------------------------------------- + + private void OnToggleSidebarEdit(object sender, RoutedEventArgs e) + { + _editingSidebar = EditSidebarToggle.IsChecked == true; + RenderSidebar(); + } + + /// Renders the sidebar (thumbnail + chosen properties) per the current SidebarConfig. + private bool _shown3DTip; + + private void RenderSidebar() + { + if (Document == null) + { + return; + } + + bool showThumb = SidebarConfig.ShowThumbnail && !Document.IsStep; + ThumbHost.Visibility = showThumb ? Visibility.Visible : Visibility.Collapsed; + ThumbDivider.Visibility = showThumb ? Visibility.Visible : Visibility.Collapsed; + + // 3D triggers (parts/assemblies): the thumbnail is the primary trigger when shown; the + // command-bar icon is the fallback only when the thumbnail is off. + bool is3D = Document.Kind is InventorDocument.DocKind.Part or InventorDocument.DocKind.Assembly or InventorDocument.DocKind.Step; + View3DButton.Visibility = is3D && !showThumb ? Visibility.Visible : Visibility.Collapsed; + ThreeDHint.Visibility = is3D && showThumb ? Visibility.Visible : Visibility.Collapsed; + + // Discoverability tip (once per loaded doc): STEP uses the bundled OCCT converter; Inventor + // documents still need Inventor to generate a viewable on a cache miss. + if (is3D && !_shown3DTip && (Document.IsStep || InventorInstalls.Detect().Count > 0)) + { + _shown3DTip = true; + TipService.Show((Panel)Content, showThumb ? ThumbHost : View3DButton, new Tip + { + Id = "view.3d", + Title = "See it in 3D", + Message = Document.IsStep + ? "Convert this STEP file locally and open it in the Autodesk viewer." + : showThumb + ? "Click the preview to open this model in the interactive 3D viewer." + : "Open this model in the interactive 3D viewer.", + Glyph = 0xF158, // 3D cube glyph + ActionText = "Open 3D view", + Action = () => _ = OpenViewer3DAsync() + }); + } + + // every property present in the file, keyed for lookup (value may be empty) + Dictionary byKey = new(StringComparer.Ordinal); + foreach (InventorDocument.PropEntry p in Document.Properties) + { + byKey[SidebarConfig.K(p.SetId, p.Pid)] = p; + } + + List keys = SidebarConfig.Keys; + + SidebarEditPanel.Children.Clear(); + if (_editingSidebar) + { + ToggleSwitch thumb = new() { Header = "Show thumbnail", IsOn = showThumb }; + thumb.Toggled += (_, _) => SidebarConfig.ShowThumbnail = thumb.IsOn; + SidebarEditPanel.Children.Add(thumb); + SidebarEditPanel.Children.Add(new TextBlock + { + Text = "Drag to reorder, remove with ✕, or add more below.", + Opacity = 0.6, FontSize = 12, TextWrapping = TextWrapping.Wrap + }); + } + + // Render EVERY configured property so the sidebar layout is identical across files; + // a property that's absent from this file (or blank) simply shows an empty value. + KeyPropsPanel.Children.Clear(); + foreach (string key in keys) + { + (string label, string value) = ResolveRow(key, byKey); + KeyPropsPanel.Children.Add(_editingSidebar + ? EditableKeyRow(key, label, value) + : KeyRow(label, value)); + } + if (keys.Count == 0 && !_editingSidebar) + { + KeyPropsPanel.Children.Add(new TextBlock { Text = "No properties to show", Opacity = 0.5, FontSize = 12 }); + } + + SidebarAddPanel.Children.Clear(); + if (_editingSidebar) + { + SidebarAddPanel.Children.Add(BuildAddPropertyButton(byKey, keys)); + HyperlinkButton reset = new() { Content = "Reset to defaults", Padding = new Thickness(0, 2, 0, 0) }; + reset.Click += (_, _) => SidebarConfig.ResetDefaults(); + SidebarAddPanel.Children.Add(reset); + } + } + + /// Resolves a configured key to its (label, value). Value is empty when the + /// property is absent from this file or blank, keeping the sidebar consistent. + private static (string label, string value) ResolveRow( + string key, IReadOnlyDictionary byKey) + { + if (byKey.TryGetValue(key, out InventorDocument.PropEntry? p)) + { + return (p.Name, p.Display); + } + + (Guid setId, uint pid) = SidebarConfig.Parse(key); + return (InventorProps.Name(setId, pid), ""); + } + + /// A draggable sidebar property row with a remove control (edit mode). + private Border EditableKeyRow(string key, string label, string value) + { + Grid g = new() { ColumnSpacing = 8 }; + g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + + FontIcon grip = new() { Glyph = G(0xE76F), FontSize = 14, Opacity = 0.4, + VerticalAlignment = VerticalAlignment.Center }; + ToolTipService.SetToolTip(grip, "Drag to reorder"); + + StackPanel text = new(); + text.Children.Add(new TextBlock { Text = label, Opacity = 0.6, FontSize = 12, TextWrapping = TextWrapping.Wrap }); + text.Children.Add(new TextBlock { Text = value, FontSize = 13, TextWrapping = TextWrapping.Wrap }); + Grid.SetColumn(text, 1); + + Button remove = MiniButton(0xE711, "Remove", () => RemoveKey(key)); + Grid.SetColumn(remove, 2); + + g.Children.Add(grip); + g.Children.Add(text); + g.Children.Add(remove); + + Border row = new() + { + Padding = new Thickness(0, 4, 0, 4), Child = g, Tag = key, + Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), // hit-testable drop target + CanDrag = true, AllowDrop = true + }; + row.DragStarting += (_, e) => + { + _dragKey = key; + e.Data.RequestedOperation = DataPackageOperation.Move; + e.Data.SetText(key); + }; + row.DragOver += (_, e) => + { + e.AcceptedOperation = _dragKey != null && _dragKey != key + ? DataPackageOperation.Move : DataPackageOperation.None; + }; + row.Drop += (s, e) => + { + bool after = e.GetPosition((UIElement)s).Y > ((FrameworkElement)s).ActualHeight / 2; + ReorderTo(key, after); + }; + return row; + } + + private Button MiniButton(int glyph, string tooltip, Action onClick) + { + Button b = new() + { + Content = new FontIcon { Glyph = G(glyph), FontSize = 12 }, + Padding = new Thickness(6, 4, 6, 4), MinWidth = 0, + Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), BorderThickness = new Thickness(0) + }; + ToolTipService.SetToolTip(b, tooltip); + b.Click += (_, _) => onClick(); + return b; + } + + private Button BuildAddPropertyButton( + IReadOnlyDictionary present, List current) + { + HashSet shownKeys = new(current, StringComparer.Ordinal); + List candidates = present + .Where(kv => !shownKeys.Contains(kv.Key) && kv.Value.Display.Length > 0).Select(kv => kv.Value) + .OrderBy(p => p.Set, StringComparer.OrdinalIgnoreCase) + .ThenBy(p => p.Name, StringComparer.OrdinalIgnoreCase) + .ToList(); + + Button add = new() + { + Content = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = + { + new FontIcon { Glyph = G(0xE710), FontSize = 12 }, new TextBlock { Text = "Add property" } + } } + }; + + // Build the flyout fresh on click so it binds to the current window's XamlRoot. + add.Click += (_, _) => + { + StackPanel menu = new() { Spacing = 1, MinWidth = 280 }; + Flyout flyout = new() { Placement = Microsoft.UI.Xaml.Controls.Primitives.FlyoutPlacementMode.Bottom }; + + if (candidates.Count == 0) + { + menu.Children.Add(new TextBlock { Text = "All available properties are shown", + Opacity = 0.6, FontSize = 12, Margin = new Thickness(4) }); + } + foreach (InventorDocument.PropEntry p in candidates) + { + string key = SidebarConfig.K(p.SetId, p.Pid); + Button row = new() + { + HorizontalAlignment = HorizontalAlignment.Stretch, + HorizontalContentAlignment = HorizontalAlignment.Left, + Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), BorderThickness = new Thickness(0), + Padding = new Thickness(8, 5, 8, 5), + Content = new StackPanel { Children = + { + new TextBlock { Text = p.Name, FontSize = 13 }, + new TextBlock { Text = p.Set + " · " + p.Display, Opacity = 0.55, FontSize = 11, + TextTrimming = TextTrimming.CharacterEllipsis, MaxWidth = 300 } + } } + }; + row.Click += (_, _) => { flyout.Hide(); AddKey(key); }; + menu.Children.Add(row); + } + + flyout.Content = new ScrollViewer { MaxHeight = 360, Content = menu }; + flyout.ShowAt(add); + }; + return add; + } + + private static void AddKey(string key) + { + List keys = SidebarConfig.Keys; + if (!keys.Contains(key)) + { + keys.Add(key); + SidebarConfig.SetKeys(keys); + } + } + + private static void RemoveKey(string key) + { + List keys = SidebarConfig.Keys; + if (keys.Remove(key)) + { + SidebarConfig.SetKeys(keys); + } + } + + /// Moves the dragged key before/after a target key, then persists the new order. + private void ReorderTo(string targetKey, bool after) + { + string? drag = _dragKey; + _dragKey = null; + if (drag == null || drag == targetKey) + { + return; + } + + List keys = SidebarConfig.Keys; + if (!keys.Remove(drag)) + { + return; + } + + int ti = keys.IndexOf(targetKey); + if (ti < 0) + { + return; + } + + keys.Insert(after ? ti + 1 : ti, drag); + SidebarConfig.SetKeys(keys); + } + + private static StackPanel Section(string title, string[] lines) + { + StackPanel sp = new() { Spacing = 4 }; + sp.Children.Add(new TextBlock { Text = title, FontWeight = FontWeights.SemiBold, FontSize = 14 }); + foreach (string l in lines) + { + sp.Children.Add(new TextBlock { Text = l, + FontFamily = new FontFamily("Consolas"), + FontSize = 12, Opacity = 0.85, TextWrapping = TextWrapping.Wrap, IsTextSelectionEnabled = true }); + } + + return sp; + } + + /// A titled label/value grid (one row per field), like Inventor's iProperties + /// "Details" page - long values ellipsize with the full text on hover. + private static StackPanel KeyValueSection(string title, List<(string label, string value)> items) + { + StackPanel sp = new() { Spacing = 8 }; + sp.Children.Add(new TextBlock { Text = title, FontWeight = FontWeights.SemiBold, FontSize = 14 }); + + Grid g = new() { ColumnSpacing = 16, RowSpacing = 5 }; + g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + + for (int i = 0; i < items.Count; i++) + { + g.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + TextBlock lbl = new() { Text = items[i].label, FontSize = 12, Opacity = 0.6, + FontWeight = FontWeights.SemiBold, VerticalAlignment = VerticalAlignment.Center }; + Grid.SetRow(lbl, i); + Grid.SetColumn(lbl, 0); + g.Children.Add(lbl); + + TextBlock val = new() { Text = items[i].value, FontSize = 12, Opacity = 0.95, + TextWrapping = TextWrapping.NoWrap, TextTrimming = TextTrimming.CharacterEllipsis, + IsTextSelectionEnabled = true, VerticalAlignment = VerticalAlignment.Center }; + ToolTipService.SetToolTip(val, items[i].value); + Grid.SetRow(val, i); + Grid.SetColumn(val, 1); + g.Children.Add(val); + } + + sp.Children.Add(g); + return sp; + } + +} diff --git a/src/InventorMeta.App/Document/DocumentView.States.cs b/src/InventorMeta.App/Document/DocumentView.States.cs new file mode 100644 index 0000000..3c7d4af --- /dev/null +++ b/src/InventorMeta.App/Document/DocumentView.States.cs @@ -0,0 +1,151 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Imaging; + +namespace ExtrabbitCode.Inventor.MetaReader.App.Document; + +/// The Model States tab: the per-state property browser with diff matrix and +/// per-state thumbnails. +public sealed partial class DocumentView +{ + private void PopulateStates(InventorDocument doc) + { + StatesPanel.Children.Clear(); + if (!doc.HasModelStates) + { + StatesTab.Visibility = Visibility.Collapsed; + return; + } + StatesTab.Visibility = Visibility.Visible; + List states = doc.ModelStateDetails; + StatesTab.Header = $"Model States ({states.Count})"; + + StatesPanel.Children.Add(new TextBlock + { + Text = "Per-state iProperties, read straight from the file - no need to switch states in Inventor.", + Opacity = 0.7, FontSize = 13, TextWrapping = TextWrapping.Wrap + }); + + // identity of a property = (Set, Pid, Name); value may vary per state + InventorDocument.ModelState? active = states.FirstOrDefault(s => s.IsActive); + bool Has(InventorDocument.ModelState s, (string Set, uint Pid, string Name) id) => + s.Properties.Any(p => p.Set == id.Set && p.Pid == id.Pid && p.Name == id.Name); + string ValueOf(InventorDocument.ModelState s, (string Set, uint Pid, string Name) id) + { + InventorDocument.PropEntry? p = s.Properties.FirstOrDefault(x => x.Set == id.Set && x.Pid == id.Pid && x.Name == id.Name); + if (p != null) + { + return p.Display; + } + + return !s.IsActive && active != null && Has(active, id) ? "(not cached)" : "-"; + } + List<(string Set, uint Pid, string Name)> ids = states.SelectMany(s => s.Properties).Select(p => (p.Set, p.Pid, p.Name)) + .Distinct().OrderBy(i => i.Set).ThenBy(i => i.Pid).ToList(); + bool Meaningful((string Set, uint Pid, string Name) id) => + !id.Set.Contains("(internal)") && + !(id.Set.StartsWith("Design Tracking Properties") && (id.Pid == 21 || id.Pid == 46)) && + !(id.Set.Contains("Summary Information") && id.Pid == 17); // thumbnail blob + List<(string Set, uint Pid, string Name)> allDiffs = ids.Where(id => states.Select(s => ValueOf(s, id)).Distinct().Count() > 1).ToList(); + List<(string Set, uint Pid, string Name)> diffIds = allDiffs.Where(Meaningful).ToList(); + int internalDiffs = allDiffs.Count - diffIds.Count; + + // ---- differences matrix (the headline view) ---- + if (states.Count > 1) + { + string[] headers = states.Select(s => s.Name).ToArray(); + List<(string Name, string[])> rows = diffIds.Select(id => (id.Name, states.Select(s => ValueOf(s, id)).ToArray())).ToList(); + UIElement body = rows.Count > 0 + ? Matrix(headers, rows) + : new TextBlock { Text = "No user-facing properties differ between states.", + Opacity = 0.7, Margin = new Thickness(14, 10, 14, 12), TextWrapping = TextWrapping.Wrap }; + StatesPanel.Children.Add(Card("Differences between states", + rows.Count > 0 ? rows.Count.ToString() : null, body)); + if (internalDiffs > 0) + { + StatesPanel.Children.Add(new TextBlock { + Text = $"+ {internalDiffs} internal/volatile field(s) also differ (revision ids, save timestamps, counters)", + Opacity = 0.5, FontSize = 11, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(4, -4, 0, 0) }); + } + } + + // ---- per-state browser ---- + foreach (InventorDocument.ModelState s in states) + { + StackPanel body = new(); + + // Each state caches its own preview (its geometry can differ) - show it, click to enlarge. + if (s.Thumbnail is { Length: > 0 } thumb) + { + Image img = new() + { + Source = ThumbSource(thumb), Width = 104, Height = 104, + Stretch = Stretch.Uniform, HorizontalAlignment = HorizontalAlignment.Left + }; + ToolTipService.SetToolTip(img, "Click to enlarge"); + img.Tapped += (_, _) => ShowThumbZoom(thumb, s.Name); + body.Children.Add(new Border + { + Child = img, CornerRadius = new CornerRadius(8), Margin = new Thickness(14, 12, 14, 6), + BorderThickness = new Thickness(1), HorizontalAlignment = HorizontalAlignment.Left, + BorderBrush = (Brush)Application.Current.Resources["CardStrokeColorDefaultBrush"] + }); + } + + if (s.Summary.Count > 0) + { + body.Children.Add(KvList(s.Summary.Select(kv => (kv.Key, kv.Value)).ToList(), 150)); + } + + body.Children.Add(new TextBlock { + Text = $"{s.Properties.Count} properties · storage {s.StorageName}", + Opacity = 0.5, FontSize = 11, FontFamily = new FontFamily("Consolas"), + TextWrapping = TextWrapping.Wrap, Margin = new Thickness(14, 8, 14, 12) }); + StatesPanel.Children.Add(Card(s.Name, null, body)); + } + } + + private static BitmapImage ThumbSource(byte[] bytes) + { + BitmapImage bmp = new(); + using MemoryStream ms = new(bytes); + bmp.SetSource(ms.AsRandomAccessStream()); + return bmp; + } + + /// Show a model-state thumbnail enlarged on a dimmed overlay; click anywhere to close. + private void ShowThumbZoom(byte[] bytes, string title) + { + if (HostWindow is not MainWindow win) { return; } + + StackPanel centered = new() + { + Spacing = 10, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center + }; + centered.Children.Add(new TextBlock + { + Text = title, FontSize = 16, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, + Foreground = new SolidColorBrush(Microsoft.UI.Colors.White), HorizontalAlignment = HorizontalAlignment.Center + }); + centered.Children.Add(new Border + { + CornerRadius = new CornerRadius(12), + Child = new Image { Source = ThumbSource(bytes), MaxWidth = 720, MaxHeight = 720, Stretch = Stretch.Uniform } + }); + centered.Children.Add(new TextBlock + { + Text = "Click anywhere to close", FontSize = 12, Opacity = 0.7, + Foreground = new SolidColorBrush(Microsoft.UI.Colors.White), HorizontalAlignment = HorizontalAlignment.Center + }); + + Grid root = new(); + root.Children.Add(centered); + root.Tapped += (_, _) => win.HideOverlay(); + win.ShowOverlay(root, dimmed: true); + } + +} diff --git a/src/InventorMeta.App/Document/DocumentView.Structure.cs b/src/InventorMeta.App/Document/DocumentView.Structure.cs new file mode 100644 index 0000000..99dc6d5 --- /dev/null +++ b/src/InventorMeta.App/Document/DocumentView.Structure.cs @@ -0,0 +1,429 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; + +namespace ExtrabbitCode.Inventor.MetaReader.App.Document; + +/// The File Structure tab: the segment-database card (size bars, block counts, damage +/// chips) above a collapsible storage tree with human annotations, plus the classic plain-text +/// dump behind "Copy as text". +public sealed partial class DocumentView +{ + // --------------------------------------------------------------------------------------- + // File Structure tab: a segment-database card (size bars, block counts, damage chips) above + // a collapsible storage tree with human annotations. "Copy as text" keeps the classic dump + // for support tickets. The damage Inventor only reports as an opaque "Error in reading RSe + // segment" becomes visible right at the streams involved. + // --------------------------------------------------------------------------------------- + + private static readonly Windows.UI.Color DamageRed = Windows.UI.Color.FromArgb(255, 0xC4, 0x2B, 0x1C); + private const int BarDamaged = unchecked((int)0xFFE24B4A), BarHealthy = unchecked((int)0xFF1D9E75); + + private void ClearStructureCards() + { + for (int i = StructurePanel.Children.Count - 1; i >= 0; i--) + { + if (!ReferenceEquals(StructurePanel.Children[i], TreeText)) + { + StructurePanel.Children.RemoveAt(i); + } + } + } + + private void PopulateStructureTree(InventorDocument doc) + { + using CompoundFile cf = new(doc.FilePath); + if (doc.Segments.Count > 0) + { + StructurePanel.Children.Add(BuildSegmentDatabaseCard(doc)); + } + StructurePanel.Children.Add(BuildStorageTreeCard(doc, cf)); + } + + private static SolidColorBrush ArgbBrush(int argb) => new(Windows.UI.Color.FromArgb( + (byte)(argb >> 24), (byte)(argb >> 16), (byte)(argb >> 8), (byte)argb)); + + private SolidColorBrush ErrorText() => new(ActualTheme == ElementTheme.Dark + ? Windows.UI.Color.FromArgb(255, 0xFF, 0x99, 0x8A) : DamageRed); + + private SolidColorBrush OkText() => new(ActualTheme == ElementTheme.Dark + ? Windows.UI.Color.FromArgb(255, 0x6C, 0xCB, 0x5F) : Windows.UI.Color.FromArgb(255, 0x15, 0x80, 0x3D)); + + private static Border DamageChip(string text) => new() + { + CornerRadius = new CornerRadius(9), Padding = new Thickness(8, 1, 8, 2), + Background = new SolidColorBrush(DamageRed), + VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Right, + Child = new TextBlock { Text = text, FontSize = 11, Foreground = new SolidColorBrush(Microsoft.UI.Colors.White) } + }; + + private static string FormatSize(long bytes) => bytes switch + { + < 1024 => $"{bytes} B", + < 1024 * 1024 => $"{bytes / 1024.0:N0} KB", + _ => $"{bytes / (1024.0 * 1024.0):N1} MB", + }; + + /// One row per RSe segment: name, payload-size bar (relative to the largest segment), + /// actual block count and the registry verdict - a red "claims N" chip where the summary is + /// stale, a green "ok" otherwise. + private Border BuildSegmentDatabaseCard(InventorDocument doc) + { + IReadOnlyList segs = doc.Segments; + long total = segs.Sum(s => s.DataSize); + long max = Math.Max(1, segs.Max(s => s.DataSize)); + List memberIssues = doc.SegmentIssues.Where(i => i.Location.Length > 0).ToList(); + int damaged = segs.Count(s => s.HasCountMismatch) + memberIssues.Count; + + StackPanel body = new() { Margin = new Thickness(14, 4, 14, 12) }; + + StackPanel summary = new() { Orientation = Orientation.Horizontal, Spacing = 10, Margin = new Thickness(0, 2, 0, 8) }; + summary.Children.Add(new TextBlock + { + Text = $"{segs.Count} segments · {FormatSize(total)} payload", + Opacity = 0.6, FontSize = 12, VerticalAlignment = VerticalAlignment.Center + }); + if (damaged > 0) + { + summary.Children.Add(DamageChip($"{damaged} damaged")); + } + body.Children.Add(summary); + + body.Children.Add(SegmentGrid( + Dim("segment"), Dim("size"), Dim("blocks", right: true), Dim("registry", right: true), + bottomRule: true)); + + foreach (InventorDocument.Segment s in segs) + { + FrameworkElement registry = s.HasCountMismatch + ? DamageChip($"claims {s.SummaryBlockCount:N0}") + : s.SummaryBlockCount is null + ? new TextBlock { Text = "?", FontSize = 12, Opacity = 0.5, HorizontalAlignment = HorizontalAlignment.Right } + : new TextBlock { Text = "ok", FontSize = 12, Foreground = OkText(), HorizontalAlignment = HorizontalAlignment.Right }; + + Grid row = SegmentGrid( + Mono(s.Name), + SizeBar((double)s.DataSize / max, s.HasCountMismatch), + Mono(s.ActualBlockCount?.ToString("N0") ?? "–", right: true), + registry, + bottomRule: !ReferenceEquals(s, segs[^1]) || memberIssues.Count > 0); + string when = s.Modified is { } dt ? $" · modified {dt:yyyy-MM-dd HH:mm}" : ""; + ToolTipService.SetToolTip(row, + $"{FormatSize(s.DataSize)} payload (B{s.Id}) · {FormatSize(s.MetaSize)} block index (M{s.Id}){when}"); + body.Children.Add(row); + } + + foreach (SegmentRepair.Issue issue in memberIssues) + { + body.Children.Add(new TextBlock + { + Text = $"model-state member {issue.Location}: {issue.SegmentName} registry claims " + + $"{issue.SummaryCount:N0}, {issue.ActualCount:N0} stored", + FontSize = 12, Foreground = ErrorText(), TextWrapping = TextWrapping.Wrap, + Margin = new Thickness(0, 8, 0, 0) + }); + } + + return Card("Segment database", segs.Count.ToString(), body); + } + + private static TextBlock Dim(string text, bool right = false) => new() + { + Text = text, FontSize = 11, Opacity = 0.5, VerticalAlignment = VerticalAlignment.Center, + HorizontalAlignment = right ? HorizontalAlignment.Right : HorizontalAlignment.Left + }; + + private static TextBlock Mono(string text, bool right = false) => new() + { + Text = text, FontSize = 12, FontFamily = new FontFamily("Consolas"), + VerticalAlignment = VerticalAlignment.Center, + HorizontalAlignment = right ? HorizontalAlignment.Right : HorizontalAlignment.Left + }; + + private static Grid SegmentGrid(FrameworkElement name, FrameworkElement bar, FrameworkElement blocks, FrameworkElement registry, bool bottomRule) + { + Grid g = new() { ColumnSpacing = 10, Padding = new Thickness(0, 6, 0, 6) }; + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(165) }); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(78) }); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(118) }); + Grid.SetColumn(bar, 1); Grid.SetColumn(blocks, 2); Grid.SetColumn(registry, 3); + g.Children.Add(name); g.Children.Add(bar); g.Children.Add(blocks); g.Children.Add(registry); + if (bottomRule) + { + g.BorderThickness = new Thickness(0, 0, 0, 1); + g.BorderBrush = (Brush)Application.Current.Resources["DividerStrokeColorDefaultBrush"]; + } + return g; + } + + /// A flat proportional bar: red for a damaged segment, green for a healthy one, on a + /// subtle full-width track. + private static Border SizeBar(double fraction, bool damaged) + { + Grid fillGrid = new(); + fillGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(Math.Max(fraction, 0.006), GridUnitType.Star) }); + fillGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(Math.Max(1 - fraction, 0.0001), GridUnitType.Star) }); + fillGrid.Children.Add(new Border + { + Height = 8, CornerRadius = new CornerRadius(4), + Background = ArgbBrush(damaged ? BarDamaged : BarHealthy) + }); + return new Border + { + Height = 8, CornerRadius = new CornerRadius(4), VerticalAlignment = VerticalAlignment.Center, + Background = (Brush)Application.Current.Resources["ControlFillColorSecondaryBrush"], + Child = fillGrid + }; + } + + // ---- storage tree ---- + + private sealed class StorageNode + { + public CompoundFile.DirEntry? Entry; + public string Name = ""; + public string Path = ""; + public List Children = []; + public int StreamCount; // streams in the whole subtree + } + + private Border BuildStorageTreeCard(InventorDocument doc, CompoundFile cf) + { + Dictionary segsById = new(StringComparer.Ordinal); + foreach (InventorDocument.Segment s in doc.Segments) { segsById[s.Id] = s; } + Dictionary issuesByLocation = doc.SegmentIssues + .GroupBy(i => i.Location, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.Count(), StringComparer.OrdinalIgnoreCase); + + StackPanel body = new() { Margin = new Thickness(14, 4, 14, 12) }; + + Grid info = new() { Margin = new Thickness(0, 2, 0, 6) }; + info.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + info.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + TextBlock containerInfo = new() + { + Text = doc.CfbVersionInfo, Opacity = 0.6, FontSize = 12, VerticalAlignment = VerticalAlignment.Center + }; + ToolTipService.SetToolTip(containerInfo, $"Root CLSID {cf.Directory[0].Clsid}"); + info.Children.Add(containerInfo); + Button copyBtn = new() + { + Padding = new Thickness(8, 3, 8, 4), MinWidth = 0, FontSize = 12, + Content = new StackPanel + { + Orientation = Orientation.Horizontal, Spacing = 5, + Children = + { + new FontIcon { Glyph = G(0xE8C8), FontSize = 12 }, + new TextBlock { Text = "Copy as text", FontSize = 12 } + } + } + }; + ToolTipService.SetToolTip(copyBtn, "Copy the full structure as plain text (for tickets and diffs)"); + // built now, while the container is open - the click must not touch the disk (the file + // may be gone or locked by then) and the copied text should match what the tab shows + string dumpText = BuildStructureText(doc, cf); + copyBtn.Click += (_, _) => Copy(dumpText); + Grid.SetColumn(copyBtn, 1); + info.Children.Add(copyBtn); + body.Children.Add(info); + + StorageNode root = BuildStorageHierarchy(cf); + foreach (StorageNode child in root.Children) + { + RenderStorageNode(body, child, 0, segsById, issuesByLocation); + } + + return Card("Storage tree", root.StreamCount.ToString(), body); + } + + private static StorageNode BuildStorageHierarchy(CompoundFile cf) + { + StorageNode root = new() { Path = "" }; + Dictionary byPath = new(StringComparer.OrdinalIgnoreCase) { [""] = root }; + + foreach (CompoundFile.DirEntry en in cf.Directory.Where(d => d.Type is 1 or 2) + .OrderBy(d => d.Path, StringComparer.OrdinalIgnoreCase)) + { + string[] parts = en.Path.TrimStart('/').Split('/'); + StorageNode parent = root; + string path = ""; + for (int i = 0; i < parts.Length; i++) + { + path += "/" + parts[i]; + if (!byPath.TryGetValue(path, out StorageNode? node)) + { + node = new StorageNode { Name = parts[i], Path = path }; + byPath[path] = node; + parent.Children.Add(node); + } + if (i == parts.Length - 1) { node.Entry = en; } + parent = node; + } + } + + int CountStreams(StorageNode n) + { + n.StreamCount = (n.Entry?.Type == 2 ? 1 : 0) + n.Children.Sum(CountStreams); + return n.StreamCount; + } + CountStreams(root); + return root; + } + + private void RenderStorageNode(StackPanel into, StorageNode node, int depth, + Dictionary segsById, Dictionary issuesByLocation) + { + bool isStorage = node.Entry == null || node.Entry.Type == 1; + StackPanel line = new() + { + Orientation = Orientation.Horizontal, Spacing = 8, + Margin = new Thickness(depth * 18, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center + }; + + if (isStorage) + { + // big generic subtrees (the VBA project, member documents) start folded so the + // interesting streams aren't buried; the document's own RSeStorage stays open + bool collapsed = node.StreamCount > 8 && + !node.Path.Equals("/RSeStorage", StringComparison.OrdinalIgnoreCase); + + FontIcon chevron = new() { Glyph = G(collapsed ? 0xE76C : 0xE70D), FontSize = 10, Opacity = 0.6, VerticalAlignment = VerticalAlignment.Center }; + TextBlock summary = new() + { + Text = $"· {node.StreamCount} stream{(node.StreamCount == 1 ? "" : "s")}", + FontSize = 11, Opacity = 0.5, VerticalAlignment = VerticalAlignment.Center, + Visibility = collapsed ? Visibility.Visible : Visibility.Collapsed + }; + line.Children.Add(chevron); + line.Children.Add(new FontIcon { Glyph = G(0xE8B7), FontSize = 14, Opacity = 0.7, VerticalAlignment = VerticalAlignment.Center }); + line.Children.Add(Mono(node.Name)); + line.Children.Add(summary); + + StackPanel children = new() { Visibility = collapsed ? Visibility.Collapsed : Visibility.Visible }; + foreach (StorageNode child in node.Children) + { + RenderStorageNode(children, child, depth + 1, segsById, issuesByLocation); + } + + Border row = new() + { + Child = line, Padding = new Thickness(2, 3, 2, 3), + Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent) + }; + row.Tapped += (_, _) => + { + bool show = children.Visibility == Visibility.Collapsed; + children.Visibility = show ? Visibility.Visible : Visibility.Collapsed; + chevron.Glyph = G(show ? 0xE70D : 0xE76C); + summary.Visibility = show ? Visibility.Collapsed : Visibility.Visible; + }; + into.Children.Add(row); + into.Children.Add(children); + } + else + { + line.Children.Add(new FontIcon { Glyph = G(0xE7C3), FontSize = 13, Opacity = 0.55, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(18, 0, 0, 0) }); + line.Children.Add(Mono(node.Name)); + line.Children.Add(new TextBlock { Text = FormatSize(node.Entry!.Size), FontSize = 11, Opacity = 0.5, VerticalAlignment = VerticalAlignment.Center }); + (string note, string? chip) = StreamAnnotation(node.Entry, segsById, issuesByLocation); + if (note.Length > 0) + { + line.Children.Add(new TextBlock { Text = note, FontSize = 11, Opacity = 0.65, VerticalAlignment = VerticalAlignment.Center }); + } + if (chip != null) + { + line.Children.Add(DamageChip(chip)); + } + into.Children.Add(new Border { Child = line, Padding = new Thickness(2, 3, 2, 3) }); + } + } + + /// What to say about one stream in the tree: names the segment behind each mangled + /// M/B stream, labels the registries, and hands back a red-chip text where summaries are + /// stale. Member trees (MemberDocs/…/RSeStorage) get their registry chip too. + private static (string Note, string? Chip) StreamAnnotation(CompoundFile.DirEntry en, + Dictionary segsById, Dictionary issuesByLocation) + { + int lastSlash = en.Path.LastIndexOf('/'); + string parent = lastSlash > 0 ? en.Path[..lastSlash] : ""; + bool inRseTree = parent.EndsWith("/RSeStorage", StringComparison.OrdinalIgnoreCase); + if (en.Type != 2 || !inRseTree) + { + return ("", null); + } + + if (en.Name == "RSeSegInfo") + { + // the library owns the Location convention - deriving it here again would let the + // dictionary key and the lookup key drift apart + string location = SegmentRepair.LocationOf(parent); + return issuesByLocation.TryGetValue(location, out int n) && n > 0 + ? ("segment registry", $"{n} stale summar{(n == 1 ? "y" : "ies")}") + : ("segment registry", null); + } + + // named annotations only for the document's own segments (the sidebar list) + if (parent.Equals("/RSeStorage", StringComparison.OrdinalIgnoreCase) && + en.Name.Length > 1 && segsById.TryGetValue(en.Name[1..], out InventorDocument.Segment? seg)) + { + if (en.Name[0] == 'M') + { + return ($"{seg.Name} block index", null); + } + if (en.Name[0] == 'B') + { + string blocks = seg.ActualBlockCount is long n ? $" · {n:N0} blocks" : ""; + return seg.HasCountMismatch + ? ($"{seg.Name} payload{blocks}", $"registry claims {seg.SummaryBlockCount:N0}") + : ($"{seg.Name} payload{blocks}", null); + } + } + return ("", null); + } + + /// The classic plain-text dump (paths, types, sizes plus the segment annotations) - + /// what the tab used to show, kept for tickets, mails and diffs via "Copy as text". Works on + /// the already-loaded document and its open container: no disk access of its own. + private static string BuildStructureText(InventorDocument doc, CompoundFile cf) + { + Dictionary segsById = new(StringComparer.Ordinal); + foreach (InventorDocument.Segment s in doc.Segments) { segsById[s.Id] = s; } + Dictionary issuesByLocation = doc.SegmentIssues + .GroupBy(i => i.Location, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.Count(), StringComparer.OrdinalIgnoreCase); + + StringBuilder sb = new(); + sb.AppendLine($"Root CLSID {cf.Directory[0].Clsid}"); + sb.AppendLine($"Container {doc.CfbVersionInfo}"); + if (doc.HasRepairableSegmentDamage) + { + sb.AppendLine(); + sb.AppendLine("!! Segment database damaged - the registry promises more blocks than the streams hold:"); + foreach (SegmentRepair.Issue i in doc.SegmentIssues) + { + string where = i.Location.Length == 0 ? "" : $" (member {i.Location})"; + sb.AppendLine($"!! {i.SegmentName,-22} registry {i.SummaryCount,10:N0} <> {i.ActualCount:N0} stored{where}"); + } + sb.AppendLine("!! Inventor refuses to open the file over this; the Repair button patches the registry (backup included)."); + } + sb.AppendLine(); + foreach (CompoundFile.DirEntry en in cf.Directory.Where(d => d.Type is 1 or 2 or 5) + .OrderBy(d => d.Path, StringComparer.OrdinalIgnoreCase)) + { + string size = en.Type == 2 ? en.Size.ToString("N0") : ""; + (string note, string? chip) = StreamAnnotation(en, segsById, issuesByLocation); + string line = $"{en.Path,-46}{en.TypeName,-8}{size,12}"; + if (note.Length > 0) { line += " " + note; } + if (chip != null) { line += $" !! {chip}"; } + sb.AppendLine(line); + } + return sb.ToString(); + } + +} diff --git a/src/InventorMeta.App/DocumentView.Viewer3D.cs b/src/InventorMeta.App/Document/DocumentView.Viewer3D.cs similarity index 99% rename from src/InventorMeta.App/DocumentView.Viewer3D.cs rename to src/InventorMeta.App/Document/DocumentView.Viewer3D.cs index d756382..d3629a9 100644 --- a/src/InventorMeta.App/DocumentView.Viewer3D.cs +++ b/src/InventorMeta.App/Document/DocumentView.Viewer3D.cs @@ -10,7 +10,7 @@ using Microsoft.UI.Xaml.Media; using Microsoft.Web.WebView2.Core; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Document; /// /// The 3D viewer: clicking the thumbnail (or the command-bar 3D button) opens a window-filling diff --git a/src/InventorMeta.App/DocumentView.xaml b/src/InventorMeta.App/Document/DocumentView.xaml similarity index 77% rename from src/InventorMeta.App/DocumentView.xaml rename to src/InventorMeta.App/Document/DocumentView.xaml index 3c0ca47..f206dc6 100644 --- a/src/InventorMeta.App/DocumentView.xaml +++ b/src/InventorMeta.App/Document/DocumentView.xaml @@ -1,5 +1,5 @@ @@ -156,6 +156,41 @@ HorizontalAlignment="Left" Visibility="Collapsed"> + + + + + + + + + + + + + + + + + + + + - + + + + + + diff --git a/src/InventorMeta.App/Document/DocumentView.xaml.cs b/src/InventorMeta.App/Document/DocumentView.xaml.cs new file mode 100644 index 0000000..6f6852c --- /dev/null +++ b/src/InventorMeta.App/Document/DocumentView.xaml.cs @@ -0,0 +1,416 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using CommunityToolkit.Mvvm.Messaging; +using Microsoft.UI.Text; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Imaging; +using Windows.Storage; +using Windows.Storage.Pickers; + +namespace ExtrabbitCode.Inventor.MetaReader.App.Document; + +public sealed partial class DocumentView +{ + public string FilePath { get; private set; } = ""; + public InventorDocument? Document { get; private set; } + public string TabTitle => Document?.FileName ?? Path.GetFileName(FilePath); + + /// Status messages after (re)load go here; the host window shows them in its footer. + /// Reassigned when the tab is adopted by another window (tear-out / reattach). + public Action? StatusSink { get; set; } + + /// The window currently hosting this view (may change after a tab tear-out). + private MainWindow? HostWindow => App.GetWindowForElement(this) as MainWindow; + + private readonly List<(UIElement body, FontIcon chevron)> _collapsibles = []; + + public DocumentView() + { + InitializeComponent(); + WireTabHide(PropsTab, "All Properties"); + WireTabHide(StatesTab, "Model States"); + WireTabHide(RefsTab, "References"); + WireTabHide(StructureTab, "File Structure"); + + // The WebView2 reference graph doesn't follow the XAML theme on its own; re-theme it on toggle. + ActualThemeChanged += OnActualThemeChanged; + + // Hide/show state is global; rebuild this view whenever it changes (any tab). + // Static handler => no capture of 'this', so the messenger's weak reference + // lets a closed tab be collected without manual unregistration. + WeakReferenceMessenger.Default.Register(this, + static (recipient, _) => ((DocumentView)recipient).RebuildView()); + + // Sidebar layout is global too, but only the (cheap) sidebar needs re-rendering. + WeakReferenceMessenger.Default.Register(this, + static (recipient, _) => ((DocumentView)recipient).RenderSidebar()); + + // Expand/collapse-all lives in the tab strip footer (shown only for card tabs). + TabStripActions.Children.Add(BuildExpandCollapseAll()); + } + + private void OnDetailTabChanged(object sender, SelectionChangedEventArgs e) + { + bool hasCards = ReferenceEquals(DetailTabs.SelectedItem, PropsTab) + || ReferenceEquals(DetailTabs.SelectedItem, StatesTab); + TabStripActions.Visibility = hasCards ? Visibility.Visible : Visibility.Collapsed; + + if (Document != null && DetailTabs.SelectedItem is TabViewItem { Header: string hdr }) + { + // Strip any "(N)" count suffix (e.g. "Model States (3)") so the tab name groups cleanly. + string tab = hdr.Split('(')[0].Trim(); + Analytics.Capture("detail_tab_viewed", new Dictionary { ["tab"] = tab }); + } + } + + private bool _editingSidebar; + private string? _dragKey; + + private static string G(int code) => ((char)code).ToString(); // Segoe Fluent glyph + private const int ChevronUp = 0xE70E, ChevronDown = 0xE70D, HideGlyph = 0xED1A; + + private void RebuildView() + { + if (Document != null) + { + Populate(Document); + } + } + + /// A small hover "hide" button that hides the item with the given key. + private Button MakeHideButton(string key, string tooltip) + { + Button b = new() + { + Content = new FontIcon { Glyph = G(HideGlyph), FontSize = 12 }, + Padding = new Thickness(6, 3, 6, 3), MinWidth = 0, MinHeight = 0, + CornerRadius = new CornerRadius(4), BorderThickness = new Thickness(0), + Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), + VerticalAlignment = VerticalAlignment.Center + }; + ToolTipService.SetToolTip(b, tooltip); + b.Click += (_, _) => HideStore.Set(key, true); + return b; + } + + private void WireTabHide(TabViewItem tab, string name) + { + // Build the flyout fresh per right-click so it binds to the tab's current XamlRoot + // (the document can move to another window via tab tear-out). + tab.ContextRequested += (_, e) => + { + MenuFlyout mf = new(); + MenuFlyoutItem item = new() { Text = $"Hide “{name}” tab", Icon = new FontIcon { Glyph = G(HideGlyph) } }; + item.Click += (_, _) => HideStore.Set(HideStore.TabKey(name), true); + mf.Items.Add(item); + if (e.TryGetPosition(tab, out Windows.Foundation.Point p)) + { + mf.ShowAt(tab, p); + } + else + { + mf.ShowAt(tab); + } + e.Handled = true; + }; + } + + private void ApplyTabVisibility() + { + bool isStep = Document?.IsStep == true; + PropsTab.Visibility = TabVis("All Properties", true); + StatesTab.Visibility = TabVis("Model States", Document?.HasModelStates == true); + RefsTab.Visibility = TabVis("References", !isStep); + StructureTab.Visibility = TabVis("File Structure", true); + + if (DetailTabs.SelectedItem is TabViewItem sel && sel.Visibility == Visibility.Collapsed) + { + DetailTabs.SelectedItem = DetailTabs.TabItems.OfType() + .FirstOrDefault(t => t.Visibility == Visibility.Visible); + } + + Visibility TabVis(string name, bool applicable) => + applicable && !HideStore.IsHidden(HideStore.TabKey(name)) ? Visibility.Visible : Visibility.Collapsed; + } + + private void RefreshHiddenUi() + { + int count = CollectHidden().Count; + HiddenButton.Visibility = count > 0 ? Visibility.Visible : Visibility.Collapsed; + HiddenCountText.Text = count == 1 ? "1 hidden" : $"{count} hidden"; + } + + /// Builds the hidden-items list fresh on click so it binds to the current + /// window's XamlRoot (the document can move windows via tab tear-out). + private void OnHiddenButtonClick(object sender, RoutedEventArgs e) + { + StackPanel panel = new() { MinWidth = 260, Spacing = 2 }; + panel.Children.Add(new TextBlock + { + Text = "Hidden - click Show to restore", FontWeight = FontWeights.SemiBold, + Margin = new Thickness(4, 2, 4, 8) + }); + + Flyout flyout = new() { Placement = Microsoft.UI.Xaml.Controls.Primitives.FlyoutPlacementMode.Bottom }; + foreach ((string key, string label) in CollectHidden()) + { + Grid row = new() { ColumnSpacing = 10, Padding = new Thickness(4, 2, 4, 2) }; + row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + TextBlock lbl = new() { Text = label, VerticalAlignment = VerticalAlignment.Center, + TextTrimming = TextTrimming.CharacterEllipsis, MaxWidth = 320, FontSize = 12 }; + Button show = new() + { + Padding = new Thickness(8, 2, 8, 2), + Content = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, + Children = { new FontIcon { Glyph = G(0xE7B3), FontSize = 12 }, new TextBlock { Text = "Show" } } } + }; + string k = key; + show.Click += (_, _) => { flyout.Hide(); HideStore.Set(k, false); }; + Grid.SetColumn(show, 1); + row.Children.Add(lbl); + row.Children.Add(show); + panel.Children.Add(row); + } + + flyout.Content = panel; + flyout.ShowAt(HiddenButton); + } + + private List<(string key, string label)> CollectHidden() + { + List<(string, string)> list = []; + if (Document == null) + { + return list; + } + + void Tab(string name, bool applicable) + { + if (applicable && HideStore.IsHidden(HideStore.TabKey(name))) + { + list.Add((HideStore.TabKey(name), "Tab · " + name)); + } + } + Tab("All Properties", true); + Tab("Model States", Document.HasModelStates); + Tab("References", !Document.IsStep); + Tab("File Structure", true); + + foreach (string set in Document.Properties.Select(p => p.Set).Distinct()) + { + if (HideStore.IsHidden(HideStore.SetKey(set))) + { + list.Add((HideStore.SetKey(set), "Set · " + set)); + } + } + + foreach (InventorDocument.PropEntry p in Document.Properties) + { + if (!HideStore.IsHidden(HideStore.SetKey(p.Set)) && HideStore.IsHidden(HideStore.PropKey(p.Set, p.Pid))) + { + list.Add((HideStore.PropKey(p.Set, p.Pid), $"Property · {p.Name} ({p.Set})")); + } + } + return list; + } + + private void SetAllExpanded(bool expanded) + { + foreach ((UIElement body, FontIcon chevron) in _collapsibles) + { + body.Visibility = expanded ? Visibility.Visible : Visibility.Collapsed; + chevron.Glyph = G(expanded ? ChevronUp : ChevronDown); + } + } + + public bool Load(string path) + { + if (!string.Equals(FilePath, path, StringComparison.OrdinalIgnoreCase)) + { + _repairedThisSession = false; // the "Repaired" chip belongs to the previous file + } + FilePath = path; + PathText.Text = path; + _shown3DTip = false; + try + { + long size = new FileInfo(path).Length; + System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew(); + Document = new InventorDocument(path); + Populate(Document); + Serilog.Log.Information( + "Loaded {File} ({Size:N0} B) in {Ms} ms - {Props} properties, {Refs} references, {States} model states, {Segments} segments", + Document.FileName, size, sw.ElapsedMilliseconds, Document.Properties.Count, + Document.References.Count, Document.ModelStateDetails.Count, Document.Segments.Count); + string counts = Document.IsStep + ? $"{Document.Properties.Count} STEP metadata field(s)." + : $"{Document.Properties.Count} properties, {Document.References.Count} reference(s)."; + StatusSink?.Invoke($"Loaded {Document.FileName} - {counts}"); + Analytics.Capture("document_opened", new Dictionary + { + ["doc_kind"] = Document.Kind.ToString(), + ["extension"] = Path.GetExtension(path).ToLowerInvariant(), + ["has_model_states"] = Document.HasModelStates, + ["is_ipart"] = Document.IsIPart, + ["reference_count"] = Document.References.Count, + ["property_count"] = Document.Properties.Count, + }); + return true; + } + catch (Exception ex) + { + Serilog.Log.Error(ex, "Failed to load {File}", path); + StatusSink?.Invoke("Error: " + ex.Message); + return false; + } + } + + public void Refresh() + { + if (string.IsNullOrEmpty(FilePath)) + { + return; + } + + if (!File.Exists(FilePath)) { StatusSink?.Invoke("File no longer exists: " + FilePath); return; } + if (Load(FilePath)) + { + StatusSink?.Invoke($"Refreshed {TabTitle} at {DateTime.Now:HH:mm:ss}."); + } + } + + private void OnRefresh(object sender, RoutedEventArgs e) => Refresh(); + + private void OnShowInExplorer(object sender, RoutedEventArgs e) => RevealInExplorer(FilePath); + + /// Opens File Explorer with the file selected (or its folder if only that exists). + private static void RevealInExplorer(string path) + { + try + { + if (File.Exists(path)) + { + Process.Start(new ProcessStartInfo { FileName = "explorer.exe", Arguments = $"/select,\"{path}\"", UseShellExecute = true }); + } + else if (Directory.Exists(path)) + { + Process.Start(new ProcessStartInfo { FileName = "explorer.exe", Arguments = $"\"{path}\"", UseShellExecute = true }); + } + } + catch { /* best-effort */ } + } + + private async void OnExportJson(object sender, RoutedEventArgs e) + { + if (Document == null) + { + return; + } + + FileSavePicker picker = new(); + Window owner = HostWindow ?? App.MainWindowInstance; + IntPtr hwnd = WinRT.Interop.WindowNative.GetWindowHandle(owner); + WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd); + picker.FileTypeChoices.Add("JSON", new List { ".json" }); + picker.SuggestedFileName = Path.GetFileNameWithoutExtension(Document.FileName) + "_metadata"; + StorageFile? file = await picker.PickSaveFileAsync(); + if (file != null) + { + await FileIO.WriteTextAsync(file, Document.ToJson()); + StatusSink?.Invoke("Exported " + file.Name); + Analytics.Capture("json_exported", new Dictionary { ["doc_kind"] = Document.Kind.ToString() }); + } + } + + private void Populate(InventorDocument doc) + { + FileNameText.Text = doc.FileName; + DocTypeText.Text = doc.DocumentType; + TypeIcon.Source = AppIcons.Bitmap(doc.Kind); + PropsTab.Header = "All Properties"; + StatesTab.Header = "Model States"; + RefsTab.Header = "References"; + StructureTab.Header = doc.IsStep ? "STEP Source" : "File Structure"; + + if (doc.Thumbnail != null) + { + BitmapImage bmp = new(); + using MemoryStream ms = new(doc.Thumbnail); + bmp.SetSource(ms.AsRandomAccessStream()); + ThumbBrush.ImageSource = bmp; + NoThumb.Visibility = Visibility.Collapsed; + } + else + { + ThumbBrush.ImageSource = null; + NoThumb.Visibility = Visibility.Visible; + } + + SetCategoryBadge(doc); + SetDamageBadge(doc); + + RenderSidebar(); // also sets the 3D triggers (button visible only when the thumbnail is off) + + _collapsibles.Clear(); + + PropsPanel.Children.Clear(); + foreach (IGrouping grp in doc.Properties.GroupBy(p => p.Set).OrderBy(g => SetOrder(g.Key))) + { + if (HideStore.IsHidden(HideStore.SetKey(grp.Key))) + { + continue; + } + + StackPanel table = PropTable(grp.Key, grp.OrderBy(x => x.Pid).Select(p => (p.Pid, p.Name, p.Display))); + PropsPanel.Children.Add(Card(grp.Key, grp.Count().ToString(), table, HideStore.SetKey(grp.Key))); + } + + PopulateStates(doc); + + PopulateReferences(doc); + + ClearStructureCards(); + if (doc.IsStep) + { + TreeText.Text = doc.StructureText; + TreeText.Visibility = Visibility.Visible; + } + else + { + TreeText.Visibility = Visibility.Collapsed; + PopulateStructureTree(doc); + } + + ApplyTabVisibility(); + RefreshHiddenUi(); + } + + /// The category badge's hover legend, kept so the demo tour can open it programmatically + /// (its painted cursor never moves the OS pointer, so it can't trigger a real hover). + private ToolTip? _categoryTip; + + /// Colours the category badge for the document's + /// and attaches the legend as its hover tooltip. + private void SetCategoryBadge(InventorDocument doc) + { + (string name, Windows.UI.Color color) = DocCategoryUi.Of(doc.PrimaryCategory); + CategoryBadgeText.Text = name; + CategoryBadge.Background = new Microsoft.UI.Xaml.Media.SolidColorBrush(color); + CategoryBadge.Visibility = Visibility.Visible; + _categoryTip = new ToolTip + { + Content = DocCategoryUi.Legend(doc.PrimaryCategory), + PlacementTarget = CategoryBadge, + Placement = PlacementMode.Bottom + }; + ToolTipService.SetToolTip(CategoryBadge, _categoryTip); + } + +} diff --git a/src/InventorMeta.App/DocumentView.xaml.cs b/src/InventorMeta.App/DocumentView.xaml.cs deleted file mode 100644 index ee64574..0000000 --- a/src/InventorMeta.App/DocumentView.xaml.cs +++ /dev/null @@ -1,1688 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Numerics; -using System.Text; -using System.Threading.Tasks; -using CommunityToolkit.Mvvm.Messaging; -using Microsoft.UI.Text; -using Microsoft.UI.Windowing; -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Controls.Primitives; -using Microsoft.UI.Xaml.Input; -using Microsoft.UI.Xaml.Media; -using Microsoft.UI.Xaml.Media.Imaging; -using Windows.ApplicationModel.DataTransfer; -using Windows.Storage; -using Windows.Storage.Pickers; - -namespace ExtrabbitCode.Inventor.MetaReader.App; - -public sealed partial class DocumentView -{ - public string FilePath { get; private set; } = ""; - public InventorDocument? Document { get; private set; } - public string TabTitle => Document?.FileName ?? Path.GetFileName(FilePath); - - /// Status messages after (re)load go here; the host window shows them in its footer. - /// Reassigned when the tab is adopted by another window (tear-out / reattach). - public Action? StatusSink { get; set; } - - /// The window currently hosting this view (may change after a tab tear-out). - private MainWindow? HostWindow => App.GetWindowForElement(this) as MainWindow; - - private readonly List<(UIElement body, FontIcon chevron)> _collapsibles = []; - - public DocumentView() - { - InitializeComponent(); - WireTabHide(PropsTab, "All Properties"); - WireTabHide(StatesTab, "Model States"); - WireTabHide(RefsTab, "References"); - WireTabHide(StructureTab, "File Structure"); - - // The WebView2 reference graph doesn't follow the XAML theme on its own; re-theme it on toggle. - ActualThemeChanged += OnActualThemeChanged; - - // Hide/show state is global; rebuild this view whenever it changes (any tab). - // Static handler => no capture of 'this', so the messenger's weak reference - // lets a closed tab be collected without manual unregistration. - WeakReferenceMessenger.Default.Register(this, - static (recipient, _) => ((DocumentView)recipient).RebuildView()); - - // Sidebar layout is global too, but only the (cheap) sidebar needs re-rendering. - WeakReferenceMessenger.Default.Register(this, - static (recipient, _) => ((DocumentView)recipient).RenderSidebar()); - - // Expand/collapse-all lives in the tab strip footer (shown only for card tabs). - TabStripActions.Children.Add(BuildExpandCollapseAll()); - } - - private void OnDetailTabChanged(object sender, SelectionChangedEventArgs e) - { - bool hasCards = ReferenceEquals(DetailTabs.SelectedItem, PropsTab) - || ReferenceEquals(DetailTabs.SelectedItem, StatesTab); - TabStripActions.Visibility = hasCards ? Visibility.Visible : Visibility.Collapsed; - - if (Document != null && DetailTabs.SelectedItem is TabViewItem { Header: string hdr }) - { - // Strip any "(N)" count suffix (e.g. "Model States (3)") so the tab name groups cleanly. - string tab = hdr.Split('(')[0].Trim(); - Analytics.Capture("detail_tab_viewed", new Dictionary { ["tab"] = tab }); - } - } - - private bool _editingSidebar; - private string? _dragKey; - - private static string G(int code) => ((char)code).ToString(); // Segoe Fluent glyph - private const int ChevronUp = 0xE70E, ChevronDown = 0xE70D, HideGlyph = 0xED1A; - - private void RebuildView() - { - if (Document != null) - { - Populate(Document); - } - } - - /// A small hover "hide" button that hides the item with the given key. - private Button MakeHideButton(string key, string tooltip) - { - Button b = new() - { - Content = new FontIcon { Glyph = G(HideGlyph), FontSize = 12 }, - Padding = new Thickness(6, 3, 6, 3), MinWidth = 0, MinHeight = 0, - CornerRadius = new CornerRadius(4), BorderThickness = new Thickness(0), - Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), - VerticalAlignment = VerticalAlignment.Center - }; - ToolTipService.SetToolTip(b, tooltip); - b.Click += (_, _) => HideStore.Set(key, true); - return b; - } - - private void WireTabHide(TabViewItem tab, string name) - { - // Build the flyout fresh per right-click so it binds to the tab's current XamlRoot - // (the document can move to another window via tab tear-out). - tab.ContextRequested += (_, e) => - { - MenuFlyout mf = new(); - MenuFlyoutItem item = new() { Text = $"Hide “{name}” tab", Icon = new FontIcon { Glyph = G(HideGlyph) } }; - item.Click += (_, _) => HideStore.Set(HideStore.TabKey(name), true); - mf.Items.Add(item); - if (e.TryGetPosition(tab, out Windows.Foundation.Point p)) - { - mf.ShowAt(tab, p); - } - else - { - mf.ShowAt(tab); - } - e.Handled = true; - }; - } - - private void ApplyTabVisibility() - { - bool isStep = Document?.IsStep == true; - PropsTab.Visibility = TabVis("All Properties", true); - StatesTab.Visibility = TabVis("Model States", Document?.HasModelStates == true); - RefsTab.Visibility = TabVis("References", !isStep); - StructureTab.Visibility = TabVis("File Structure", true); - - if (DetailTabs.SelectedItem is TabViewItem sel && sel.Visibility == Visibility.Collapsed) - { - DetailTabs.SelectedItem = DetailTabs.TabItems.OfType() - .FirstOrDefault(t => t.Visibility == Visibility.Visible); - } - - Visibility TabVis(string name, bool applicable) => - applicable && !HideStore.IsHidden(HideStore.TabKey(name)) ? Visibility.Visible : Visibility.Collapsed; - } - - private void RefreshHiddenUi() - { - int count = CollectHidden().Count; - HiddenButton.Visibility = count > 0 ? Visibility.Visible : Visibility.Collapsed; - HiddenCountText.Text = count == 1 ? "1 hidden" : $"{count} hidden"; - } - - /// Builds the hidden-items list fresh on click so it binds to the current - /// window's XamlRoot (the document can move windows via tab tear-out). - private void OnHiddenButtonClick(object sender, RoutedEventArgs e) - { - StackPanel panel = new() { MinWidth = 260, Spacing = 2 }; - panel.Children.Add(new TextBlock - { - Text = "Hidden - click Show to restore", FontWeight = FontWeights.SemiBold, - Margin = new Thickness(4, 2, 4, 8) - }); - - Flyout flyout = new() { Placement = Microsoft.UI.Xaml.Controls.Primitives.FlyoutPlacementMode.Bottom }; - foreach ((string key, string label) in CollectHidden()) - { - Grid row = new() { ColumnSpacing = 10, Padding = new Thickness(4, 2, 4, 2) }; - row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - TextBlock lbl = new() { Text = label, VerticalAlignment = VerticalAlignment.Center, - TextTrimming = TextTrimming.CharacterEllipsis, MaxWidth = 320, FontSize = 12 }; - Button show = new() - { - Padding = new Thickness(8, 2, 8, 2), - Content = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, - Children = { new FontIcon { Glyph = G(0xE7B3), FontSize = 12 }, new TextBlock { Text = "Show" } } } - }; - string k = key; - show.Click += (_, _) => { flyout.Hide(); HideStore.Set(k, false); }; - Grid.SetColumn(show, 1); - row.Children.Add(lbl); - row.Children.Add(show); - panel.Children.Add(row); - } - - flyout.Content = panel; - flyout.ShowAt(HiddenButton); - } - - private List<(string key, string label)> CollectHidden() - { - List<(string, string)> list = []; - if (Document == null) - { - return list; - } - - void Tab(string name, bool applicable) - { - if (applicable && HideStore.IsHidden(HideStore.TabKey(name))) - { - list.Add((HideStore.TabKey(name), "Tab · " + name)); - } - } - Tab("All Properties", true); - Tab("Model States", Document.HasModelStates); - Tab("References", !Document.IsStep); - Tab("File Structure", true); - - foreach (string set in Document.Properties.Select(p => p.Set).Distinct()) - { - if (HideStore.IsHidden(HideStore.SetKey(set))) - { - list.Add((HideStore.SetKey(set), "Set · " + set)); - } - } - - foreach (InventorDocument.PropEntry p in Document.Properties) - { - if (!HideStore.IsHidden(HideStore.SetKey(p.Set)) && HideStore.IsHidden(HideStore.PropKey(p.Set, p.Pid))) - { - list.Add((HideStore.PropKey(p.Set, p.Pid), $"Property · {p.Name} ({p.Set})")); - } - } - return list; - } - - private void SetAllExpanded(bool expanded) - { - foreach ((UIElement body, FontIcon chevron) in _collapsibles) - { - body.Visibility = expanded ? Visibility.Visible : Visibility.Collapsed; - chevron.Glyph = G(expanded ? ChevronUp : ChevronDown); - } - } - - public bool Load(string path) - { - FilePath = path; - PathText.Text = path; - _shown3DTip = false; - try - { - Document = new InventorDocument(path); - Populate(Document); - string counts = Document.IsStep - ? $"{Document.Properties.Count} STEP metadata field(s)." - : $"{Document.Properties.Count} properties, {Document.References.Count} reference(s)."; - StatusSink?.Invoke($"Loaded {Document.FileName} - {counts}"); - Analytics.Capture("document_opened", new Dictionary - { - ["doc_kind"] = Document.Kind.ToString(), - ["extension"] = Path.GetExtension(path).ToLowerInvariant(), - ["has_model_states"] = Document.HasModelStates, - ["is_ipart"] = Document.IsIPart, - ["reference_count"] = Document.References.Count, - ["property_count"] = Document.Properties.Count, - }); - return true; - } - catch (Exception ex) - { - StatusSink?.Invoke("Error: " + ex.Message); - return false; - } - } - - public void Refresh() - { - if (string.IsNullOrEmpty(FilePath)) - { - return; - } - - if (!File.Exists(FilePath)) { StatusSink?.Invoke("File no longer exists: " + FilePath); return; } - if (Load(FilePath)) - { - StatusSink?.Invoke($"Refreshed {TabTitle} at {DateTime.Now:HH:mm:ss}."); - } - } - - private void OnRefresh(object sender, RoutedEventArgs e) => Refresh(); - - private void OnShowInExplorer(object sender, RoutedEventArgs e) => RevealInExplorer(FilePath); - - /// Opens File Explorer with the file selected (or its folder if only that exists). - private static void RevealInExplorer(string path) - { - try - { - if (File.Exists(path)) - { - Process.Start(new ProcessStartInfo { FileName = "explorer.exe", Arguments = $"/select,\"{path}\"", UseShellExecute = true }); - } - else if (Directory.Exists(path)) - { - Process.Start(new ProcessStartInfo { FileName = "explorer.exe", Arguments = $"\"{path}\"", UseShellExecute = true }); - } - } - catch { /* best-effort */ } - } - - private async void OnExportJson(object sender, RoutedEventArgs e) - { - if (Document == null) - { - return; - } - - FileSavePicker picker = new(); - Window owner = HostWindow ?? App.MainWindowInstance; - IntPtr hwnd = WinRT.Interop.WindowNative.GetWindowHandle(owner); - WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd); - picker.FileTypeChoices.Add("JSON", new List { ".json" }); - picker.SuggestedFileName = Path.GetFileNameWithoutExtension(Document.FileName) + "_metadata"; - StorageFile? file = await picker.PickSaveFileAsync(); - if (file != null) - { - await FileIO.WriteTextAsync(file, Document.ToJson()); - StatusSink?.Invoke("Exported " + file.Name); - Analytics.Capture("json_exported", new Dictionary { ["doc_kind"] = Document.Kind.ToString() }); - } - } - - private void Populate(InventorDocument doc) - { - FileNameText.Text = doc.FileName; - DocTypeText.Text = doc.DocumentType; - TypeIcon.Source = AppIcons.Bitmap(doc.Kind); - PropsTab.Header = "All Properties"; - StatesTab.Header = "Model States"; - RefsTab.Header = "References"; - StructureTab.Header = doc.IsStep ? "STEP Source" : "File Structure"; - - if (doc.Thumbnail != null) - { - BitmapImage bmp = new(); - using MemoryStream ms = new(doc.Thumbnail); - bmp.SetSource(ms.AsRandomAccessStream()); - ThumbBrush.ImageSource = bmp; - NoThumb.Visibility = Visibility.Collapsed; - } - else - { - ThumbBrush.ImageSource = null; - NoThumb.Visibility = Visibility.Visible; - } - - SetCategoryBadge(doc); - - RenderSidebar(); // also sets the 3D triggers (button visible only when the thumbnail is off) - - _collapsibles.Clear(); - - PropsPanel.Children.Clear(); - foreach (IGrouping grp in doc.Properties.GroupBy(p => p.Set).OrderBy(g => SetOrder(g.Key))) - { - if (HideStore.IsHidden(HideStore.SetKey(grp.Key))) - { - continue; - } - - StackPanel table = PropTable(grp.Key, grp.OrderBy(x => x.Pid).Select(p => (p.Pid, p.Name, p.Display))); - PropsPanel.Children.Add(Card(grp.Key, grp.Count().ToString(), table, HideStore.SetKey(grp.Key))); - } - - PopulateStates(doc); - - PopulateReferences(doc); - - if (doc.IsStep) - { - TreeText.Text = doc.StructureText; - } - else - { - using CompoundFile cf = new(doc.FilePath); - StringBuilder sb = new(); - sb.AppendLine($"Root CLSID {cf.Directory[0].Clsid}"); - sb.AppendLine($"Container {doc.CfbVersionInfo}\n"); - foreach (CompoundFile.DirEntry en in cf.Directory.Where(d => d.Type is 1 or 2 or 5) - .OrderBy(d => d.Path, StringComparer.OrdinalIgnoreCase)) - { - string size = en.Type == 2 ? en.Size.ToString("N0") : ""; - sb.AppendLine($"{en.Path,-46}{en.TypeName,-8}{size,12}"); - } - TreeText.Text = sb.ToString(); - } - - ApplyTabVisibility(); - RefreshHiddenUi(); - } - - /// Colours the category badge for the document's - /// and attaches the legend as its hover tooltip. - private void SetCategoryBadge(InventorDocument doc) - { - (string name, Windows.UI.Color color) = DocCategoryUi.Of(doc.PrimaryCategory); - CategoryBadgeText.Text = name; - CategoryBadge.Background = new Microsoft.UI.Xaml.Media.SolidColorBrush(color); - CategoryBadge.Visibility = Visibility.Visible; - ToolTipService.SetToolTip(CategoryBadge, new ToolTip { Content = DocCategoryUi.Legend(doc.PrimaryCategory) }); - } - - private void PopulateStates(InventorDocument doc) - { - StatesPanel.Children.Clear(); - if (!doc.HasModelStates) - { - StatesTab.Visibility = Visibility.Collapsed; - return; - } - StatesTab.Visibility = Visibility.Visible; - List states = doc.ModelStateDetails; - StatesTab.Header = $"Model States ({states.Count})"; - - StatesPanel.Children.Add(new TextBlock - { - Text = "Per-state iProperties, read straight from the file - no need to switch states in Inventor.", - Opacity = 0.7, FontSize = 13, TextWrapping = TextWrapping.Wrap - }); - - // identity of a property = (Set, Pid, Name); value may vary per state - InventorDocument.ModelState? active = states.FirstOrDefault(s => s.IsActive); - bool Has(InventorDocument.ModelState s, (string Set, uint Pid, string Name) id) => - s.Properties.Any(p => p.Set == id.Set && p.Pid == id.Pid && p.Name == id.Name); - string ValueOf(InventorDocument.ModelState s, (string Set, uint Pid, string Name) id) - { - InventorDocument.PropEntry? p = s.Properties.FirstOrDefault(x => x.Set == id.Set && x.Pid == id.Pid && x.Name == id.Name); - if (p != null) - { - return p.Display; - } - - return !s.IsActive && active != null && Has(active, id) ? "(not cached)" : "-"; - } - List<(string Set, uint Pid, string Name)> ids = states.SelectMany(s => s.Properties).Select(p => (p.Set, p.Pid, p.Name)) - .Distinct().OrderBy(i => i.Set).ThenBy(i => i.Pid).ToList(); - bool Meaningful((string Set, uint Pid, string Name) id) => - !id.Set.Contains("(internal)") && - !(id.Set.StartsWith("Design Tracking Properties") && (id.Pid == 21 || id.Pid == 46)) && - !(id.Set.Contains("Summary Information") && id.Pid == 17); // thumbnail blob - List<(string Set, uint Pid, string Name)> allDiffs = ids.Where(id => states.Select(s => ValueOf(s, id)).Distinct().Count() > 1).ToList(); - List<(string Set, uint Pid, string Name)> diffIds = allDiffs.Where(Meaningful).ToList(); - int internalDiffs = allDiffs.Count - diffIds.Count; - - // ---- differences matrix (the headline view) ---- - if (states.Count > 1) - { - string[] headers = states.Select(s => s.Name).ToArray(); - List<(string Name, string[])> rows = diffIds.Select(id => (id.Name, states.Select(s => ValueOf(s, id)).ToArray())).ToList(); - UIElement body = rows.Count > 0 - ? Matrix(headers, rows) - : new TextBlock { Text = "No user-facing properties differ between states.", - Opacity = 0.7, Margin = new Thickness(14, 10, 14, 12), TextWrapping = TextWrapping.Wrap }; - StatesPanel.Children.Add(Card("Differences between states", - rows.Count > 0 ? rows.Count.ToString() : null, body)); - if (internalDiffs > 0) - { - StatesPanel.Children.Add(new TextBlock { - Text = $"+ {internalDiffs} internal/volatile field(s) also differ (revision ids, save timestamps, counters)", - Opacity = 0.5, FontSize = 11, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(4, -4, 0, 0) }); - } - } - - // ---- per-state browser ---- - foreach (InventorDocument.ModelState s in states) - { - StackPanel body = new(); - - // Each state caches its own preview (its geometry can differ) - show it, click to enlarge. - if (s.Thumbnail is { Length: > 0 } thumb) - { - Image img = new() - { - Source = ThumbSource(thumb), Width = 104, Height = 104, - Stretch = Stretch.Uniform, HorizontalAlignment = HorizontalAlignment.Left - }; - ToolTipService.SetToolTip(img, "Click to enlarge"); - img.Tapped += (_, _) => ShowThumbZoom(thumb, s.Name); - body.Children.Add(new Border - { - Child = img, CornerRadius = new CornerRadius(8), Margin = new Thickness(14, 12, 14, 6), - BorderThickness = new Thickness(1), HorizontalAlignment = HorizontalAlignment.Left, - BorderBrush = (Brush)Application.Current.Resources["CardStrokeColorDefaultBrush"] - }); - } - - if (s.Summary.Count > 0) - { - body.Children.Add(KvList(s.Summary.Select(kv => (kv.Key, kv.Value)).ToList(), 150)); - } - - body.Children.Add(new TextBlock { - Text = $"{s.Properties.Count} properties · storage {s.StorageName}", - Opacity = 0.5, FontSize = 11, FontFamily = new FontFamily("Consolas"), - TextWrapping = TextWrapping.Wrap, Margin = new Thickness(14, 8, 14, 12) }); - StatesPanel.Children.Add(Card(s.Name, null, body)); - } - } - - private static BitmapImage ThumbSource(byte[] bytes) - { - BitmapImage bmp = new(); - using MemoryStream ms = new(bytes); - bmp.SetSource(ms.AsRandomAccessStream()); - return bmp; - } - - /// Show a model-state thumbnail enlarged on a dimmed overlay; click anywhere to close. - private void ShowThumbZoom(byte[] bytes, string title) - { - if (HostWindow is not MainWindow win) { return; } - - StackPanel centered = new() - { - Spacing = 10, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center - }; - centered.Children.Add(new TextBlock - { - Text = title, FontSize = 16, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, - Foreground = new SolidColorBrush(Microsoft.UI.Colors.White), HorizontalAlignment = HorizontalAlignment.Center - }); - centered.Children.Add(new Border - { - CornerRadius = new CornerRadius(12), - Child = new Image { Source = ThumbSource(bytes), MaxWidth = 720, MaxHeight = 720, Stretch = Stretch.Uniform } - }); - centered.Children.Add(new TextBlock - { - Text = "Click anywhere to close", FontSize = 12, Opacity = 0.7, - Foreground = new SolidColorBrush(Microsoft.UI.Colors.White), HorizontalAlignment = HorizontalAlignment.Center - }); - - Grid root = new(); - root.Children.Add(centered); - root.Tapped += (_, _) => win.HideOverlay(); - win.ShowOverlay(root, dimmed: true); - } - - // sort order for property-set cards: key sets first, internal sets last - private static int SetOrder(string set) => set switch - { - _ when set.Contains("(internal)") => 100, - _ when set.StartsWith("Design Tracking Prop") => 0, - "Inventor User Defined Properties" => 1, - "Custom (User Defined) Properties" => 1, - "Inventor Summary Information" => 2, - "Summary Information" => 2, - "Inventor Document Summary Information" => 3, - "Document Summary Information" => 3, - _ => 50, - }; - - // ---- card / table builders ---- - - /// Wraps a row in a hover area with copy (and optional hide) buttons on the right. - private Border CopyableRow(UIElement content, string copyText, Thickness padding, string? hideKey = null) - { - // Selectable text inside the row captures the pointer for selection, which swallows the - // row's tap - so click-to-copy only worked on a fast click. The row copies the whole value - // anyway, so turn selection off here to make the click reliable. - DisableTextSelection(content); - - Grid grid = new(); - grid.Children.Add(content); - - Button btn = new() - { - Content = new FontIcon { Glyph = "", FontSize = 12 }, - VerticalAlignment = VerticalAlignment.Center, - Padding = new Thickness(7, 3, 7, 3), MinWidth = 0, MinHeight = 0, - CornerRadius = new CornerRadius(4), BorderThickness = new Thickness(0), - Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent) - }; - ToolTipService.SetToolTip(btn, "Copy value"); - bool can = !string.IsNullOrEmpty(copyText); - btn.Click += (_, _) => Copy(copyText); - - // hide + copy live in a right-aligned panel that stays in layout (row never resizes) - StackPanel actions = new() - { - Orientation = Orientation.Horizontal, Spacing = 4, - HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, - Opacity = 0, IsHitTestVisible = false - }; - if (hideKey != null) - { - actions.Children.Add(MakeHideButton(hideKey, "Hide this property")); - } - - if (can) - { - actions.Children.Add(btn); - } - - grid.Children.Add(actions); - - Border row = new() - { - Child = grid, Padding = padding, - Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent) // make the whole row hit-testable - }; - if (can) - { - ToolTipService.SetToolTip(row, "Click to copy"); - } - - bool has = can || hideKey != null; - row.PointerEntered += (_, _) => { if (has) { actions.Opacity = 1; actions.IsHitTestVisible = true; } }; - row.PointerExited += (_, _) => { actions.Opacity = 0; actions.IsHitTestVisible = false; }; - row.Tapped += (_, e) => { if (can) { Copy(copyText); e.Handled = true; } }; - return row; - } - - /// Turns off text selection on every TextBlock within a row so it doesn't intercept - /// the row's copy tap. - private static void DisableTextSelection(UIElement element) - { - switch (element) - { - case TextBlock tb: tb.IsTextSelectionEnabled = false; break; - case Panel panel: foreach (UIElement child in panel.Children) { DisableTextSelection(child); } break; - case Border border when border.Child is { } c: DisableTextSelection(c); break; - } - } - - private void Copy(string text) - { - if (string.IsNullOrEmpty(text)) - { - return; - } - - try - { - DataPackage dp = new(); - dp.SetText(text); - Clipboard.SetContent(dp); - string shown = text.Length > 48 ? text[..48] + "…" : text; - (HostWindow ?? App.MainWindowInstance as MainWindow)?.ShowToast($"Copied “{shown}”"); - } - catch - { - // ignored - } - } - - - /// A rounded, bordered, elevated card with a clickable (collapsible) header and a body. - private Border Card(string title, string? badge, UIElement body, string? hideKey = null) - { - FontIcon chevron = new() - { - Glyph = G(ChevronUp), FontSize = 11, Opacity = 0.6, - VerticalAlignment = VerticalAlignment.Center - }; - StackPanel headerContent = new() { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center }; - headerContent.Children.Add(chevron); - headerContent.Children.Add(new TextBlock - { - Text = title, FontWeight = FontWeights.SemiBold, FontSize = 14, - VerticalAlignment = VerticalAlignment.Center, TextWrapping = TextWrapping.Wrap - }); - if (badge != null) - { - headerContent.Children.Add(new Border - { - Style = (Style)Resources["Badge"], - Child = new TextBlock { Text = badge, Style = (Style)Resources["BadgeText"] } - }); - } - - Grid headerGrid = new(); - headerGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - headerGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - headerGrid.Children.Add(headerContent); - - Button? hideBtn = null; - if (hideKey != null) - { - hideBtn = MakeHideButton(hideKey, "Hide this property set"); - hideBtn.Opacity = 0; - hideBtn.IsHitTestVisible = false; - Grid.SetColumn(hideBtn, 1); - headerGrid.Children.Add(hideBtn); - } - - Border header = new() { Style = (Style)Resources["CardHeaderRow"], Child = headerGrid }; - ToolTipService.SetToolTip(header, "Click to collapse / expand"); - if (hideBtn != null) - { - header.PointerEntered += (_, _) => { hideBtn.Opacity = 1; hideBtn.IsHitTestVisible = true; }; - header.PointerExited += (_, _) => { hideBtn.Opacity = 0; hideBtn.IsHitTestVisible = false; }; - } - - StackPanel stack = new(); - stack.Children.Add(header); - stack.Children.Add(body); - - header.Tapped += (_, _) => - { - bool show = body.Visibility == Visibility.Collapsed; - body.Visibility = show ? Visibility.Visible : Visibility.Collapsed; - chevron.Glyph = G(show ? ChevronUp : ChevronDown); - }; - _collapsibles.Add((body, chevron)); - - Border card = new() { Style = (Style)Resources["DataCard"], Child = stack, Margin = new Thickness(0, 0, 0, 8) }; - card.Shadow = new ThemeShadow(); - card.Translation = new Vector3(0, 0, 8); - return card; - } - - /// A pair of buttons that collapse (up) or expand (down) every card in this view. - private UIElement BuildExpandCollapseAll() => new StackPanel - { - Orientation = Orientation.Horizontal, - Spacing = 6, - HorizontalAlignment = HorizontalAlignment.Right, - Children = - { - ExpandCollapseButton(ChevronUp, "Collapse all", false), - ExpandCollapseButton(ChevronDown, "Expand all", true) - } - }; - - private Button ExpandCollapseButton(int glyph, string tooltip, bool expand) - { - Button b = new() - { - Content = new FontIcon { Glyph = G(glyph), FontSize = 12 }, - Padding = new Thickness(11, 6, 11, 6), MinWidth = 0 - }; - ToolTipService.SetToolTip(b, tooltip); - b.Click += (_, _) => SetAllExpanded(expand); - return b; - } - - /// PID / Name / Value table with divider lines between rows. - private StackPanel PropTable(string setName, IEnumerable<(uint pid, string name, string val)> rows) - { - List<(uint pid, string name, string val)> list = rows - .Where(r => !HideStore.IsHidden(HideStore.PropKey(setName, r.pid))).ToList(); - StackPanel sp = new(); - for (int i = 0; i < list.Count; i++) - { - (uint pid, string name, string val) = list[i]; - Grid g = new(); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(46) }); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(196) }); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - Cell(g, 0, pid.ToString(), 0.45, mono: true); - Cell(g, 1, name, 0.9, semibold: true); - Cell(g, 2, val, 0.8); - sp.Children.Add(CopyableRow(g, val, new Thickness(14, 7, 14, 7), HideStore.PropKey(setName, pid))); - } - return sp; - } - - /// Two-column key / value list (plain rows). - private StackPanel KvList(List<(string k, string v)> rows, double keyWidth) - { - StackPanel sp = new(); - for (int i = 0; i < rows.Count; i++) - { - (string k, string v) = rows[i]; - Grid g = new(); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(keyWidth) }); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - Cell(g, 0, k, 0.55); - Cell(g, 1, v, 0.95, semibold: true); - sp.Children.Add(CopyableRow(g, v, new Thickness(14, 7, 14, 7))); - } - return sp; - } - - /// Per-state comparison matrix: a header strip + zebra rows, active column tinted. - private Grid Matrix(string[] headers, List<(string label, string[] vals)> rows) - { - int cols = headers.Length + 1; - Grid grid = new(); - grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(200) }); - for (int c = 0; c < headers.Length; c++) - { - grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - } - - // header row - grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - Border hdr = new() { Style = (Style)Resources["CardHeaderRow"], CornerRadius = new CornerRadius(0) }; - Grid.SetRow(hdr, 0); Grid.SetColumnSpan(hdr, cols); grid.Children.Add(hdr); - MCell(grid, 0, 0, "Property", true, 0.7); - for (int c = 0; c < headers.Length; c++) - { - MCell(grid, 0, c + 1, headers[c], true, 0.7); - } - - for (int ri = 0; ri < rows.Count; ri++) - { - int r = ri + 1; - (string label, string[] vals) = rows[ri]; - grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - MCell(grid, r, 0, label, true, 1.0); - for (int c = 0; c < vals.Length; c++) - { - MCell(grid, r, c + 1, vals[c], false, 0.9); - } - } - return grid; - } - - private static void MCell(Grid g, int row, int col, string text, bool semibold, double opacity) - { - TextBlock t = new() - { - Text = text, Opacity = opacity, FontSize = 12, Margin = new Thickness(14, 7, 14, 7), - TextWrapping = TextWrapping.Wrap, IsTextSelectionEnabled = true, - FontWeight = semibold ? FontWeights.SemiBold : FontWeights.Normal - }; - Grid.SetRow(t, row); Grid.SetColumn(t, col); - g.Children.Add(t); - } - - private static void Cell(Grid g, int col, string text, double opacity, bool semibold = false, bool mono = false) - { - TextBlock t = new() - { - Text = text, Opacity = opacity, FontSize = 12, TextWrapping = TextWrapping.Wrap, - IsTextSelectionEnabled = true, VerticalAlignment = VerticalAlignment.Center, - Margin = new Thickness(0, 0, 10, 0), - FontWeight = semibold ? FontWeights.SemiBold : FontWeights.Normal - }; - if (mono) - { - t.FontFamily = new FontFamily("Consolas"); - } - - Grid.SetColumn(t, col); - g.Children.Add(t); - } - - private Border KeyRow(string label, string value) - { - Grid g = new(); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(118) }); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - TextBlock l = new() { Text = label, Opacity = 0.6, FontSize = 12, TextWrapping = TextWrapping.Wrap }; - TextBlock v = new() - { Text = value, FontSize = 13, TextWrapping = TextWrapping.Wrap, - IsTextSelectionEnabled = true, Margin = new Thickness(0, 0, 8, 0) }; - Grid.SetColumn(v, 1); - g.Children.Add(l); g.Children.Add(v); - return CopyableRow(g, value, new Thickness(0, 3, 0, 3)); - } - - // ---- configurable left sidebar ------------------------------------------------- - - private void OnToggleSidebarEdit(object sender, RoutedEventArgs e) - { - _editingSidebar = EditSidebarToggle.IsChecked == true; - RenderSidebar(); - } - - /// Renders the sidebar (thumbnail + chosen properties) per the current SidebarConfig. - private bool _shown3DTip; - - private void RenderSidebar() - { - if (Document == null) - { - return; - } - - bool showThumb = SidebarConfig.ShowThumbnail && !Document.IsStep; - ThumbHost.Visibility = showThumb ? Visibility.Visible : Visibility.Collapsed; - ThumbDivider.Visibility = showThumb ? Visibility.Visible : Visibility.Collapsed; - - // 3D triggers (parts/assemblies): the thumbnail is the primary trigger when shown; the - // command-bar icon is the fallback only when the thumbnail is off. - bool is3D = Document.Kind is InventorDocument.DocKind.Part or InventorDocument.DocKind.Assembly or InventorDocument.DocKind.Step; - View3DButton.Visibility = is3D && !showThumb ? Visibility.Visible : Visibility.Collapsed; - ThreeDHint.Visibility = is3D && showThumb ? Visibility.Visible : Visibility.Collapsed; - - // Discoverability tip (once per loaded doc): STEP uses the bundled OCCT converter; Inventor - // documents still need Inventor to generate a viewable on a cache miss. - if (is3D && !_shown3DTip && (Document.IsStep || InventorInstalls.Detect().Count > 0)) - { - _shown3DTip = true; - TipService.Show((Panel)Content, showThumb ? ThumbHost : View3DButton, new Tip - { - Id = "view.3d", - Title = "See it in 3D", - Message = Document.IsStep - ? "Convert this STEP file locally and open it in the Autodesk viewer." - : showThumb - ? "Click the preview to open this model in the interactive 3D viewer." - : "Open this model in the interactive 3D viewer.", - Glyph = 0xF158, // 3D cube glyph - ActionText = "Open 3D view", - Action = () => _ = OpenViewer3DAsync() - }); - } - - // every property present in the file, keyed for lookup (value may be empty) - Dictionary byKey = new(StringComparer.Ordinal); - foreach (InventorDocument.PropEntry p in Document.Properties) - { - byKey[SidebarConfig.K(p.SetId, p.Pid)] = p; - } - - List keys = SidebarConfig.Keys; - - SidebarEditPanel.Children.Clear(); - if (_editingSidebar) - { - ToggleSwitch thumb = new() { Header = "Show thumbnail", IsOn = showThumb }; - thumb.Toggled += (_, _) => SidebarConfig.ShowThumbnail = thumb.IsOn; - SidebarEditPanel.Children.Add(thumb); - SidebarEditPanel.Children.Add(new TextBlock - { - Text = "Drag to reorder, remove with ✕, or add more below.", - Opacity = 0.6, FontSize = 12, TextWrapping = TextWrapping.Wrap - }); - } - - // Render EVERY configured property so the sidebar layout is identical across files; - // a property that's absent from this file (or blank) simply shows an empty value. - KeyPropsPanel.Children.Clear(); - foreach (string key in keys) - { - (string label, string value) = ResolveRow(key, byKey); - KeyPropsPanel.Children.Add(_editingSidebar - ? EditableKeyRow(key, label, value) - : KeyRow(label, value)); - } - if (keys.Count == 0 && !_editingSidebar) - { - KeyPropsPanel.Children.Add(new TextBlock { Text = "No properties to show", Opacity = 0.5, FontSize = 12 }); - } - - SidebarAddPanel.Children.Clear(); - if (_editingSidebar) - { - SidebarAddPanel.Children.Add(BuildAddPropertyButton(byKey, keys)); - HyperlinkButton reset = new() { Content = "Reset to defaults", Padding = new Thickness(0, 2, 0, 0) }; - reset.Click += (_, _) => SidebarConfig.ResetDefaults(); - SidebarAddPanel.Children.Add(reset); - } - } - - /// Resolves a configured key to its (label, value). Value is empty when the - /// property is absent from this file or blank, keeping the sidebar consistent. - private static (string label, string value) ResolveRow( - string key, IReadOnlyDictionary byKey) - { - if (byKey.TryGetValue(key, out InventorDocument.PropEntry? p)) - { - return (p.Name, p.Display); - } - - (Guid setId, uint pid) = SidebarConfig.Parse(key); - return (InventorProps.Name(setId, pid), ""); - } - - /// A draggable sidebar property row with a remove control (edit mode). - private Border EditableKeyRow(string key, string label, string value) - { - Grid g = new() { ColumnSpacing = 8 }; - g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - - FontIcon grip = new() { Glyph = G(0xE76F), FontSize = 14, Opacity = 0.4, - VerticalAlignment = VerticalAlignment.Center }; - ToolTipService.SetToolTip(grip, "Drag to reorder"); - - StackPanel text = new(); - text.Children.Add(new TextBlock { Text = label, Opacity = 0.6, FontSize = 12, TextWrapping = TextWrapping.Wrap }); - text.Children.Add(new TextBlock { Text = value, FontSize = 13, TextWrapping = TextWrapping.Wrap }); - Grid.SetColumn(text, 1); - - Button remove = MiniButton(0xE711, "Remove", () => RemoveKey(key)); - Grid.SetColumn(remove, 2); - - g.Children.Add(grip); - g.Children.Add(text); - g.Children.Add(remove); - - Border row = new() - { - Padding = new Thickness(0, 4, 0, 4), Child = g, Tag = key, - Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), // hit-testable drop target - CanDrag = true, AllowDrop = true - }; - row.DragStarting += (_, e) => - { - _dragKey = key; - e.Data.RequestedOperation = DataPackageOperation.Move; - e.Data.SetText(key); - }; - row.DragOver += (_, e) => - { - e.AcceptedOperation = _dragKey != null && _dragKey != key - ? DataPackageOperation.Move : DataPackageOperation.None; - }; - row.Drop += (s, e) => - { - bool after = e.GetPosition((UIElement)s).Y > ((FrameworkElement)s).ActualHeight / 2; - ReorderTo(key, after); - }; - return row; - } - - private Button MiniButton(int glyph, string tooltip, Action onClick) - { - Button b = new() - { - Content = new FontIcon { Glyph = G(glyph), FontSize = 12 }, - Padding = new Thickness(6, 4, 6, 4), MinWidth = 0, - Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), BorderThickness = new Thickness(0) - }; - ToolTipService.SetToolTip(b, tooltip); - b.Click += (_, _) => onClick(); - return b; - } - - private Button BuildAddPropertyButton( - IReadOnlyDictionary present, List current) - { - HashSet shownKeys = new(current, StringComparer.Ordinal); - List candidates = present - .Where(kv => !shownKeys.Contains(kv.Key) && kv.Value.Display.Length > 0).Select(kv => kv.Value) - .OrderBy(p => p.Set, StringComparer.OrdinalIgnoreCase) - .ThenBy(p => p.Name, StringComparer.OrdinalIgnoreCase) - .ToList(); - - Button add = new() - { - Content = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = - { - new FontIcon { Glyph = G(0xE710), FontSize = 12 }, new TextBlock { Text = "Add property" } - } } - }; - - // Build the flyout fresh on click so it binds to the current window's XamlRoot. - add.Click += (_, _) => - { - StackPanel menu = new() { Spacing = 1, MinWidth = 280 }; - Flyout flyout = new() { Placement = Microsoft.UI.Xaml.Controls.Primitives.FlyoutPlacementMode.Bottom }; - - if (candidates.Count == 0) - { - menu.Children.Add(new TextBlock { Text = "All available properties are shown", - Opacity = 0.6, FontSize = 12, Margin = new Thickness(4) }); - } - foreach (InventorDocument.PropEntry p in candidates) - { - string key = SidebarConfig.K(p.SetId, p.Pid); - Button row = new() - { - HorizontalAlignment = HorizontalAlignment.Stretch, - HorizontalContentAlignment = HorizontalAlignment.Left, - Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), BorderThickness = new Thickness(0), - Padding = new Thickness(8, 5, 8, 5), - Content = new StackPanel { Children = - { - new TextBlock { Text = p.Name, FontSize = 13 }, - new TextBlock { Text = p.Set + " · " + p.Display, Opacity = 0.55, FontSize = 11, - TextTrimming = TextTrimming.CharacterEllipsis, MaxWidth = 300 } - } } - }; - row.Click += (_, _) => { flyout.Hide(); AddKey(key); }; - menu.Children.Add(row); - } - - flyout.Content = new ScrollViewer { MaxHeight = 360, Content = menu }; - flyout.ShowAt(add); - }; - return add; - } - - private static void AddKey(string key) - { - List keys = SidebarConfig.Keys; - if (!keys.Contains(key)) - { - keys.Add(key); - SidebarConfig.SetKeys(keys); - } - } - - private static void RemoveKey(string key) - { - List keys = SidebarConfig.Keys; - if (keys.Remove(key)) - { - SidebarConfig.SetKeys(keys); - } - } - - /// Moves the dragged key before/after a target key, then persists the new order. - private void ReorderTo(string targetKey, bool after) - { - string? drag = _dragKey; - _dragKey = null; - if (drag == null || drag == targetKey) - { - return; - } - - List keys = SidebarConfig.Keys; - if (!keys.Remove(drag)) - { - return; - } - - int ti = keys.IndexOf(targetKey); - if (ti < 0) - { - return; - } - - keys.Insert(after ? ti + 1 : ti, drag); - SidebarConfig.SetKeys(keys); - } - - private static StackPanel Section(string title, string[] lines) - { - StackPanel sp = new() { Spacing = 4 }; - sp.Children.Add(new TextBlock { Text = title, FontWeight = FontWeights.SemiBold, FontSize = 14 }); - foreach (string l in lines) - { - sp.Children.Add(new TextBlock { Text = l, - FontFamily = new FontFamily("Consolas"), - FontSize = 12, Opacity = 0.85, TextWrapping = TextWrapping.Wrap, IsTextSelectionEnabled = true }); - } - - return sp; - } - - /// A titled label/value grid (one row per field), like Inventor's iProperties - /// "Details" page - long values ellipsize with the full text on hover. - private static StackPanel KeyValueSection(string title, List<(string label, string value)> items) - { - StackPanel sp = new() { Spacing = 8 }; - sp.Children.Add(new TextBlock { Text = title, FontWeight = FontWeights.SemiBold, FontSize = 14 }); - - Grid g = new() { ColumnSpacing = 16, RowSpacing = 5 }; - g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - - for (int i = 0; i < items.Count; i++) - { - g.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - - TextBlock lbl = new() { Text = items[i].label, FontSize = 12, Opacity = 0.6, - FontWeight = FontWeights.SemiBold, VerticalAlignment = VerticalAlignment.Center }; - Grid.SetRow(lbl, i); - Grid.SetColumn(lbl, 0); - g.Children.Add(lbl); - - TextBlock val = new() { Text = items[i].value, FontSize = 12, Opacity = 0.95, - TextWrapping = TextWrapping.NoWrap, TextTrimming = TextTrimming.CharacterEllipsis, - IsTextSelectionEnabled = true, VerticalAlignment = VerticalAlignment.Center }; - ToolTipService.SetToolTip(val, items[i].value); - Grid.SetRow(val, i); - Grid.SetColumn(val, 1); - g.Children.Add(val); - } - - sp.Children.Add(g); - return sp; - } - - // ---- references node graph ----------------------------------------------------- - private int _refGen; - - private void PopulateReferences(InventorDocument doc) - { - RefsRoot.RowDefinitions.Clear(); - RefsRoot.Children.Clear(); - - // version/provenance details - version history first, then schema/template - string[] detailOrder = ["Current Version", "Previous Version", "Next Version", "Last update with", "Last saved by"]; - List<(string, string)> provItems = []; - foreach (string k in detailOrder) - { - if (doc.VersionInfo.TryGetValue(k, out string? v)) { provItems.Add((k, v)); } - } - foreach (KeyValuePair kv in doc.VersionInfo) - { - if (!detailOrder.Contains(kv.Key)) { provItems.Add((kv.Key, kv.Value)); } - } - StackPanel details = KeyValueSection("Version", provItems); - - // Graph fills the top (star); the short version panel docks below it (auto), never scrolling. - RefsRoot.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); - RefsRoot.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - - Border graphHost = new(); - Grid.SetRow(graphHost, 0); - RefsRoot.Children.Add(graphHost); - - Border prov = new() - { - BorderThickness = new Thickness(0, 1, 0, 0), - BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(40, 128, 128, 128)), - Padding = new Thickness(14, 10, 14, 12), - Child = details - }; - Grid.SetRow(prov, 1); - RefsRoot.Children.Add(prov); - - if (doc.References.Count == 0) - { - graphHost.Child = GraphInfo("No referenced files."); - return; - } - - int gen = ++_refGen; - _ = BuildAndShowGraphAsync(doc, graphHost, gen); - } - - private async Task BuildAndShowGraphAsync(InventorDocument doc, Border host, int gen) - { - if (doc.References.Count == 0) - { - host.Child = GraphInfo("No referenced files."); - return; - } - - host.Child = GraphInfo("Building reference graph…"); - - RefNode? root = null; - try { root = await Task.Run(() => ReferenceGraph.Build(doc)); } - catch { /* fall through to error message */ } - - if (gen != _refGen) - { - return; // a newer load superseded this build - } - - host.Child = root != null ? RenderRefGraphWeb(root, host) : GraphInfo("Couldn't build the reference graph."); - } - - private static TextBlock GraphInfo(string text) => new() - { - Text = text, Opacity = 0.6, Margin = new Thickness(20), - HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center - }; - - private bool _graphFs; - private bool _showThumbs; - private GraphLayout _graphLayout; - - // Set while the reference graph is mounted: exits its fullscreen overlay. Lets the - // node "open" actions drop out of fullscreen before switching to the opened tab. - private Action? _exitGraphFullscreen; - - /// Opens a referenced document in a tab. If the reference graph is currently - /// fullscreen, leave fullscreen first so the newly opened (and selected) tab is visible. - private void OpenReference(string path) - { - Analytics.Capture("reference_opened"); - if (_graphFs) { _exitGraphFullscreen?.Invoke(); } - HostWindow?.OpenDocument(path); - } - - private UIElement RenderRefGraph(RefNode root, Border host) - { - // start with only level 1 visible: root expanded, everything deeper collapsed - ForEachNode(root, n => n.Expanded = n.Depth == 0); - - CompositeTransform xf = new(); - Canvas canvas = new() - { - Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), - RenderTransform = xf, - // pin to the viewport's top-left so the pan/zoom transform's origin is (0,0) - HorizontalAlignment = HorizontalAlignment.Left, - VerticalAlignment = VerticalAlignment.Top - }; - - // Pan/zoom via a render transform on a clipped viewport. We avoid ScrollViewer: its - // ZoomMode + a Canvas hits a WinUI "Layout cycle detected" crash, and it also eats - // the left-drag we want for panning. - Grid viewport = new() { Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent) }; - bool fitted = false; - viewport.SizeChanged += (_, e) => - { - viewport.Clip = new RectangleGeometry { Rect = new Windows.Foundation.Rect(0, 0, e.NewSize.Width, e.NewSize.Height) }; - if (!fitted && e.NewSize.Width > 0 && e.NewSize.Height > 0) - { - fitted = true; - ZoomToFit(viewport, canvas, xf); - } - }; - viewport.Children.Add(canvas); - - LayoutAndDraw(canvas, root); - WirePanZoom(viewport, canvas, xf); - - // floating toolbar (top-right) - StackPanel toolbar = new() - { - Orientation = Orientation.Horizontal, Spacing = 4, - HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top, - Margin = new Thickness(0, 8, 14, 0) - }; - static Button IconBtn(int glyph, string tip) - { - Button b = new() { Content = new FontIcon { Glyph = G(glyph), FontSize = 14 }, - Padding = new Thickness(8, 5, 8, 5), MinWidth = 0 }; - ToolTipService.SetToolTip(b, tip); - return b; - } - - Button fit = IconBtn(0xE9A6, "Fit to view"); - fit.Click += (_, _) => ZoomToFit(viewport, canvas, xf); - Button expandAll = IconBtn(0xE710, "Expand all"); - expandAll.Click += (_, _) => { ForEachNode(root, n => n.Expanded = n.Children.Count > 0); LayoutAndDraw(canvas, root); }; - Button collapseAll = IconBtn(0xE738, "Collapse all"); - collapseAll.Click += (_, _) => { ForEachNode(root, n => n.Expanded = n.Depth == 0); LayoutAndDraw(canvas, root); }; - - // thumbnails toggle: redraw the graph with each node showing its document's preview - ToggleButton thumbs = new() - { - Content = new FontIcon { Glyph = G(0xE8B9), FontSize = 14 }, - Padding = new Thickness(8, 5, 8, 5), MinWidth = 0, IsChecked = _showThumbs - }; - ToolTipService.SetToolTip(thumbs, "Show thumbnails"); - thumbs.Click += (_, _) => - { - _showThumbs = thumbs.IsChecked == true; - LayoutAndDraw(canvas, root); - // re-fit after the relayout settles - DispatcherQueue.TryEnqueue(() => ZoomToFit(viewport, canvas, xf)); - }; - - // Fullscreen: pop the whole viewport (graph + this toolbar) into a window-filling overlay - // and switch the OS window to true fullscreen; the button toggles back, as does Esc. - FontIcon fullIcon = new() { Glyph = G(0xE740), FontSize = 14 }; - Button full = new() { Content = fullIcon, Padding = new Thickness(8, 5, 8, 5), MinWidth = 0 }; - ToolTipService.SetToolTip(full, "Fullscreen"); - Grid? overlay = null; - void SetFullscreen(bool on) - { - MainWindow? win = HostWindow; - if (win is null || on == _graphFs) { return; } - - if (on) - { - host.Child = null; // detach from the References tab - overlay = new Grid(); - overlay.Children.Add(viewport); - win.ShowOverlay(overlay); - win.AppWindow.SetPresenter(AppWindowPresenterKind.FullScreen); - _graphFs = true; - Analytics.Capture("references_fullscreen"); - } - else - { - win.AppWindow.SetPresenter(AppWindowPresenterKind.Default); - overlay?.Children.Remove(viewport); - win.HideOverlay(); - host.Child = viewport; // reattach to the tab - overlay = null; - _graphFs = false; - } - - fullIcon.Glyph = G(_graphFs ? 0xE73F : 0xE740); // BackToWindow / FullScreen - ToolTipService.SetToolTip(full, _graphFs ? "Exit fullscreen" : "Fullscreen"); - fitted = false; // re-fit once the new size settles - full.Focus(FocusState.Programmatic); - } - full.Click += (_, _) => SetFullscreen(!_graphFs); - _exitGraphFullscreen = () => SetFullscreen(false); - KeyboardAccelerator esc = new() { Key = Windows.System.VirtualKey.Escape }; - esc.Invoked += (_, e) => { if (_graphFs) { SetFullscreen(false); e.Handled = true; } }; - full.KeyboardAccelerators.Add(esc); - - toolbar.Children.Add(fit); - toolbar.Children.Add(expandAll); - toolbar.Children.Add(collapseAll); - toolbar.Children.Add(thumbs); - toolbar.Children.Add(full); - viewport.Children.Add(toolbar); - - // Discoverability tip: point at the thumbnails toggle (unless already on). - if (!_showThumbs) - { - TipService.Show(viewport, thumbs, new Tip - { - Id = "refs.thumbnails", - Title = "Did you know?", - Message = "You can show each referenced file's preview thumbnail right in the graph.", - ActionText = "Show thumbnails", - Action = () => - { - thumbs.IsChecked = true; - _showThumbs = true; - LayoutAndDraw(canvas, root); - ZoomToFit(viewport, canvas, xf); - } - }); - } - - return viewport; - } - - /// Scales and centres the graph so all of it fits the viewport (zoom extents). - private static void ZoomToFit(Grid viewport, Canvas canvas, CompositeTransform xf) - { - double vw = viewport.ActualWidth, vh = viewport.ActualHeight, cw = canvas.Width, ch = canvas.Height; - if (vw <= 0 || vh <= 0 || cw <= 0 || ch <= 0) { return; } - - const double margin = 28; - double scale = Math.Clamp(Math.Min((vw - margin) / cw, (vh - margin) / ch), 0.2, 1.0); - xf.ScaleX = xf.ScaleY = scale; - xf.TranslateX = (vw - cw * scale) / 2; - xf.TranslateY = (vh - ch * scale) / 2; - } - - private static void ForEachNode(RefNode n, Action action) - { - action(n); - foreach (RefNode c in n.Children) { ForEachNode(c, action); } - } - - /// Lays out the visible (expanded) part of the tree and (re)draws the canvas. - private void LayoutAndDraw(Canvas canvas, RefNode root) - { - const double colStep = 300, pad = 16; - // bigger nodes when thumbnails are shown so each preview has room - double nodeW = _showThumbs ? 252 : 224; - double nodeH = _showThumbs ? 104 : 56; - double rowStep = _showThumbs ? 120 : 74; - - // tidy left-to-right layout over visible nodes; a collapsed node counts as a leaf - int leaf = 0, maxDepth = 0; - void Assign(RefNode n) - { - maxDepth = Math.Max(maxDepth, n.Depth); - if (!n.Expanded || n.Children.Count == 0) { n.Row = leaf++; return; } - foreach (RefNode c in n.Children) { Assign(c); } - n.Row = (n.Children[0].Row + n.Children[^1].Row) / 2.0; - } - Assign(root); - - List vis = []; - void Collect(RefNode n) { vis.Add(n); if (n.Expanded) { foreach (RefNode c in n.Children) { Collect(c); } } } - Collect(root); - - double X(RefNode n) => pad + n.Depth * colStep; - double Y(RefNode n) => pad + n.Row * rowStep; - - canvas.Children.Clear(); - canvas.Width = pad * 2 + maxDepth * colStep + nodeW; - canvas.Height = pad * 2 + Math.Max(0, leaf - 1) * rowStep + nodeH; - - Brush link = new SolidColorBrush(Windows.UI.Color.FromArgb(150, 130, 130, 130)); - foreach (RefNode n in vis) - { - if (!n.Expanded) { continue; } - foreach (RefNode c in n.Children) - { - double sx = X(n) + nodeW, sy = Y(n) + nodeH / 2, ex = X(c), ey = Y(c) + nodeH / 2; - double dx = (ex - sx) * 0.5; - PathFigure fig = new() { StartPoint = new Windows.Foundation.Point(sx, sy) }; - fig.Segments.Add(new BezierSegment - { - Point1 = new Windows.Foundation.Point(sx + dx, sy), - Point2 = new Windows.Foundation.Point(ex - dx, ey), - Point3 = new Windows.Foundation.Point(ex, ey) - }); - PathGeometry geo = new(); - geo.Figures.Add(fig); - canvas.Children.Add(new Microsoft.UI.Xaml.Shapes.Path { Data = geo, Stroke = link, StrokeThickness = 1.5 }); - } - } - - foreach (RefNode n in vis) - { - Border box = RefNodeBox(n, nodeW, nodeH, canvas, root); - Canvas.SetLeft(box, X(n)); - Canvas.SetTop(box, Y(n)); - canvas.Children.Add(box); - } - } - - private Border RefNodeBox(RefNode n, double w, double h, Canvas canvas, RefNode root) - { - Grid g = new() { ColumnSpacing = 8, Padding = new Thickness(10, 6, 8, 6) }; - g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - - ImageSource? thumb = _showThumbs ? BitmapFromBytes(n.Thumbnail) : null; - FrameworkElement iconEl; - if (thumb != null) - { - iconEl = new Border - { - Width = h - 20, Height = h - 20, CornerRadius = new CornerRadius(4), - VerticalAlignment = VerticalAlignment.Center, - Background = new SolidColorBrush(Windows.UI.Color.FromArgb(28, 128, 128, 128)), - Child = new Image { Source = thumb, Stretch = Stretch.Uniform, Margin = new Thickness(2) } - }; - } - else if (n.IsLinkedFile) - { - iconEl = new FontIcon { Glyph = G(IsImageFile(n.Name) ? 0xE8B9 : 0xE7C3), - FontSize = _showThumbs ? 40 : 22, Width = _showThumbs ? 56 : 30, Opacity = 0.85, - VerticalAlignment = VerticalAlignment.Center }; - } - else - { - double s = _showThumbs ? 48 : 30; - iconEl = new Image { Width = s, Height = s, Source = AppIcons.Bitmap(n.Kind), - VerticalAlignment = VerticalAlignment.Center }; - } - - StackPanel text = new() { VerticalAlignment = VerticalAlignment.Center }; - text.Children.Add(new TextBlock { Text = n.Name, FontWeight = FontWeights.SemiBold, FontSize = 13, - TextTrimming = TextTrimming.CharacterEllipsis }); - // iPart classification (done in the core graph): model-state parts carry the same marker - // but aren't iParts, so they classify as neither. - bool isMember = n.IPart == IPartRole.Member; - bool isFactory = n.IPart == IPartRole.Factory; - - string sub = n.Cyclic ? "↻ already shown above" - : !n.Resolved ? (n.IsLinkedFile ? "linked file - not found" : "file not found") - : n.ReadError ? "unreadable" - : n.IsLinkedFile ? "linked " + Path.GetExtension(n.Name).TrimStart('.').ToLowerInvariant() - : isFactory ? "iPart factory" - : isMember ? "iPart member" - : KindLabel(n.Kind); - TextBlock subtitle = new() { Text = sub, FontSize = 11, Opacity = 0.6, TextTrimming = TextTrimming.CharacterEllipsis }; - if (!n.Resolved) - { - subtitle.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 209, 96, 96)); - subtitle.Opacity = 0.95; - } - else if (isFactory || isMember) - { - subtitle.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 214, 158, 46)); // gold - subtitle.Opacity = 1.0; - subtitle.FontWeight = FontWeights.SemiBold; - } - text.Children.Add(subtitle); - Grid.SetColumn(text, 1); - g.Children.Add(iconEl); - g.Children.Add(text); - - // +/- toggle for nodes that have children - if (n.Children.Count > 0) - { - Button toggle = new() - { - Width = 24, Height = 24, MinWidth = 0, Padding = new Thickness(0), - CornerRadius = new CornerRadius(12), VerticalAlignment = VerticalAlignment.Center, - Content = new FontIcon { Glyph = G(n.Expanded ? 0xE738 : 0xE710), FontSize = 11 } - }; - ToolTipService.SetToolTip(toggle, n.Expanded ? "Collapse" : $"Expand ({n.Children.Count})"); - toggle.Click += (_, _) => { n.Expanded = !n.Expanded; LayoutAndDraw(canvas, root); }; - Grid.SetColumn(toggle, 2); - g.Children.Add(toggle); - } - - Border box = new() { Style = (Style)Resources["DataCard"], Width = w, Height = h, Child = g }; - if (n.Depth == 0) - { - box.BorderBrush = (Brush)Application.Current.Resources["AccentFillColorDefaultBrush"]; - box.BorderThickness = new Thickness(2); - } - else if (isFactory) - { - box.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 214, 158, 46)); // gold - box.BorderThickness = new Thickness(2); - } - ToolTipService.SetToolTip(box, n.Path); - - bool canOpen = n.Resolved && n.Depth > 0 && !n.Cyclic && !n.IsLinkedFile; - if (canOpen) - { - box.Tapped += (_, _) => OpenReference(n.Path); - ToolTipService.SetToolTip(box, n.Path + "\nClick to open · right-click for more"); - } - - if (n.Resolved) - { - box.ContextRequested += (_, e) => - { - MenuFlyout menu = new(); - if (canOpen) - { - MenuFlyoutItem open = new() { Text = "Open in a tab", Icon = new FontIcon { Glyph = G(0xE8E5) } }; - open.Click += (_, _) => OpenReference(n.Path); - menu.Items.Add(open); - } - MenuFlyoutItem reveal = new() { Text = "Show in Explorer", Icon = new FontIcon { Glyph = G(0xEC50) } }; - reveal.Click += (_, _) => RevealInExplorer(n.Path); - menu.Items.Add(reveal); - if (e.TryGetPosition(box, out Windows.Foundation.Point p)) { menu.ShowAt(box, p); } - else { menu.ShowAt(box); } - e.Handled = true; - }; - } - return box; - } - - private static bool IsImageFile(string name) => - Path.GetExtension(name).ToLowerInvariant() is ".png" or ".jpg" or ".jpeg" or ".bmp" or ".tif" or ".tiff" or ".gif"; - - /// Decodes raw image bytes (a document's cached preview) into a usable image source. - private static ImageSource? BitmapFromBytes(byte[]? bytes) - { - if (bytes is not { Length: > 0 }) { return null; } - try - { - BitmapImage bmp = new(); - using MemoryStream ms = new(bytes); - bmp.SetSource(ms.AsRandomAccessStream()); - return bmp; - } - catch { return null; } - } - - /// Left-drag on empty space (or middle-drag anywhere) pans; wheel zooms at the cursor. - private static void WirePanZoom(Grid viewport, Canvas canvas, CompositeTransform xf) - { - bool panning = false; - Windows.Foundation.Point start = default; - double tx0 = 0, ty0 = 0; - - viewport.PointerPressed += (_, e) => - { - Microsoft.UI.Input.PointerPoint pp = e.GetCurrentPoint(viewport); - bool onBackground = ReferenceEquals(e.OriginalSource, canvas) || ReferenceEquals(e.OriginalSource, viewport); - if (!pp.Properties.IsMiddleButtonPressed && !(pp.Properties.IsLeftButtonPressed && onBackground)) - { - return; - } - panning = true; start = pp.Position; tx0 = xf.TranslateX; ty0 = xf.TranslateY; - viewport.CapturePointer(e.Pointer); - }; - viewport.PointerMoved += (_, e) => - { - if (!panning) { return; } - Windows.Foundation.Point p = e.GetCurrentPoint(viewport).Position; - xf.TranslateX = tx0 + (p.X - start.X); - xf.TranslateY = ty0 + (p.Y - start.Y); - }; - void End(object _, Microsoft.UI.Xaml.Input.PointerRoutedEventArgs e) - { - if (panning) { panning = false; viewport.ReleasePointerCapture(e.Pointer); } - } - viewport.PointerReleased += End; - viewport.PointerCanceled += End; - viewport.PointerCaptureLost += (_, _) => panning = false; - - viewport.PointerWheelChanged += (_, e) => - { - Microsoft.UI.Input.PointerPoint pp = e.GetCurrentPoint(viewport); - double factor = pp.Properties.MouseWheelDelta > 0 ? 1.12 : 1 / 1.12; - double scale = Math.Clamp(xf.ScaleX * factor, 0.2, 3.0); - factor = scale / xf.ScaleX; - Windows.Foundation.Point c = pp.Position; - xf.TranslateX = c.X - (c.X - xf.TranslateX) * factor; - xf.TranslateY = c.Y - (c.Y - xf.TranslateY) * factor; - xf.ScaleX = xf.ScaleY = scale; - e.Handled = true; - }; - } - - private static string KindLabel(InventorDocument.DocKind k) => k switch - { - InventorDocument.DocKind.Part => "Part", - InventorDocument.DocKind.Assembly => "Assembly", - InventorDocument.DocKind.Drawing => "Drawing", - InventorDocument.DocKind.Presentation => "Presentation", - InventorDocument.DocKind.Step => "STEP", - _ => "Document" - }; -} diff --git a/src/InventorMeta.App/GlobalUsings.cs b/src/InventorMeta.App/GlobalUsings.cs new file mode 100644 index 0000000..85c141a --- /dev/null +++ b/src/InventorMeta.App/GlobalUsings.cs @@ -0,0 +1,16 @@ +// The app's source is organized into feature folders, each with its own namespace. Every type +// name across them is unique, so importing all of them globally lets any file reference any other +// without a per-file using - the same reach the old single flat namespace gave, now with the code +// grouped by feature. Folder-and-namespace collisions (e.g. the Analytics namespace holding an +// Analytics class) resolve to the type at every call site. +global using ExtrabbitCode.Inventor.MetaReader.App; +global using ExtrabbitCode.Inventor.MetaReader.App.Common; +global using ExtrabbitCode.Inventor.MetaReader.App.DevTools; +global using ExtrabbitCode.Inventor.MetaReader.App.Dialogs; +global using ExtrabbitCode.Inventor.MetaReader.App.Document; +global using ExtrabbitCode.Inventor.MetaReader.App.Onboarding; +global using ExtrabbitCode.Inventor.MetaReader.App.Samples; +global using ExtrabbitCode.Inventor.MetaReader.App.Settings; +global using ExtrabbitCode.Inventor.MetaReader.App.Shell; +global using ExtrabbitCode.Inventor.MetaReader.App.Telemetry; +global using ExtrabbitCode.Inventor.MetaReader.App.Viewer3D; diff --git a/src/InventorMeta.App/InventorMeta.App.csproj b/src/InventorMeta.App/InventorMeta.App.csproj index 6c4b51b..190b5c3 100644 --- a/src/InventorMeta.App/InventorMeta.App.csproj +++ b/src/InventorMeta.App/InventorMeta.App.csproj @@ -18,7 +18,7 @@ true win-x64 false - 1.2.0.0 + 1.3.0.0 Assets\appicon.ico diff --git a/src/InventorMeta.App/TipSettings.cs b/src/InventorMeta.App/Onboarding/TipSettings.cs similarity index 95% rename from src/InventorMeta.App/TipSettings.cs rename to src/InventorMeta.App/Onboarding/TipSettings.cs index fd233c0..fdd5003 100644 --- a/src/InventorMeta.App/TipSettings.cs +++ b/src/InventorMeta.App/Onboarding/TipSettings.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Onboarding; /// Persisted state for the in-app tips: a global on/off switch and the set of tips the user /// has turned off with "Don't show again". diff --git a/src/InventorMeta.App/Tips.cs b/src/InventorMeta.App/Onboarding/Tips.cs similarity index 98% rename from src/InventorMeta.App/Tips.cs rename to src/InventorMeta.App/Onboarding/Tips.cs index d168466..04a2611 100644 --- a/src/InventorMeta.App/Tips.cs +++ b/src/InventorMeta.App/Onboarding/Tips.cs @@ -2,7 +2,7 @@ using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Onboarding; /// A single discoverability tip: a short message that points at a control, optionally with /// an action button that performs the very thing it's hinting at. diff --git a/src/InventorMeta.App/SampleFiles.cs b/src/InventorMeta.App/Samples/SampleFiles.cs similarity index 98% rename from src/InventorMeta.App/SampleFiles.cs rename to src/InventorMeta.App/Samples/SampleFiles.cs index 963f05f..7e26be8 100644 --- a/src/InventorMeta.App/SampleFiles.cs +++ b/src/InventorMeta.App/Samples/SampleFiles.cs @@ -3,7 +3,7 @@ using System.IO; using System.Linq; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Samples; /// The sample files shipped with the app. Sample folders are copied out of the (read-only, /// packaged) install folder into a writable user folder when first needed, so the app can open any diff --git a/src/InventorMeta.App/SamplesGallery.cs b/src/InventorMeta.App/Samples/SamplesGallery.cs similarity index 98% rename from src/InventorMeta.App/SamplesGallery.cs rename to src/InventorMeta.App/Samples/SamplesGallery.cs index 55fab01..dbc4547 100644 --- a/src/InventorMeta.App/SamplesGallery.cs +++ b/src/InventorMeta.App/Samples/SamplesGallery.cs @@ -7,7 +7,7 @@ using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Media.Imaging; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Samples; /// The "Try a sample" gallery shown from the start page: a list of bundled sample files, /// each with the capability it demonstrates. Clicking one opens it in a tab; "Open all" opens the diff --git a/src/InventorMeta.App/AppSettings.cs b/src/InventorMeta.App/Settings/AppSettings.cs similarity index 87% rename from src/InventorMeta.App/AppSettings.cs rename to src/InventorMeta.App/Settings/AppSettings.cs index 59bf29d..7199aa1 100644 --- a/src/InventorMeta.App/AppSettings.cs +++ b/src/InventorMeta.App/Settings/AppSettings.cs @@ -3,7 +3,7 @@ using System.IO; using System.Text.Json; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Settings; /// Tiny key/value settings store persisted as JSON in %LocalAppData% (theme, window /// bounds, sidebar layout, 3D-viewer options, …). @@ -69,7 +69,14 @@ private static Dictionary Map() try { File.Delete(LegacyIniPath); } catch { /* leave it */ } } } - catch { /* first run / unreadable */ } + catch (Exception ex) + { + // first run has no file; anything else here means settings silently reset - log it + if (File.Exists(FilePath) || File.Exists(LegacyIniPath)) + { + Serilog.Log.Warning(ex, "Settings could not be read from {File} - continuing with defaults", FilePath); + } + } return _cache; } @@ -105,6 +112,9 @@ private static void Flush() Directory.CreateDirectory(Dir); File.WriteAllText(FilePath, JsonSerializer.Serialize(Map(), JsonOpts)); } - catch { /* best-effort */ } + catch (Exception ex) + { + Serilog.Log.Warning(ex, "Settings could not be saved to {File}", FilePath); + } } } diff --git a/src/InventorMeta.App/HideStore.cs b/src/InventorMeta.App/Settings/HideStore.cs similarity index 97% rename from src/InventorMeta.App/HideStore.cs rename to src/InventorMeta.App/Settings/HideStore.cs index b69cf1c..cac5be4 100644 --- a/src/InventorMeta.App/HideStore.cs +++ b/src/InventorMeta.App/Settings/HideStore.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using CommunityToolkit.Mvvm.Messaging; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Settings; /// Broadcast when any hide/show state changes; views rebuild in response. internal sealed record HideChangedMessage(string Key); diff --git a/src/InventorMeta.App/RecentFiles.cs b/src/InventorMeta.App/Settings/RecentFiles.cs similarity index 96% rename from src/InventorMeta.App/RecentFiles.cs rename to src/InventorMeta.App/Settings/RecentFiles.cs index 9eff786..97cd9d4 100644 --- a/src/InventorMeta.App/RecentFiles.cs +++ b/src/InventorMeta.App/Settings/RecentFiles.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Linq; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Settings; /// The most-recently-opened files, newest first, persisted as a capped list. Paths are joined /// by '|', which is illegal in Windows paths and so is a safe separator. diff --git a/src/InventorMeta.App/SidebarConfig.cs b/src/InventorMeta.App/Settings/SidebarConfig.cs similarity index 98% rename from src/InventorMeta.App/SidebarConfig.cs rename to src/InventorMeta.App/Settings/SidebarConfig.cs index 977e057..d6c38fa 100644 --- a/src/InventorMeta.App/SidebarConfig.cs +++ b/src/InventorMeta.App/Settings/SidebarConfig.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using CommunityToolkit.Mvvm.Messaging; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Settings; /// Broadcast when the left sidebar layout (properties / thumbnail) changes. internal sealed record SidebarConfigChangedMessage; diff --git a/src/InventorMeta.App/MainWindow.Shoot.cs b/src/InventorMeta.App/Shell/MainWindow.Shoot.cs similarity index 99% rename from src/InventorMeta.App/MainWindow.Shoot.cs rename to src/InventorMeta.App/Shell/MainWindow.Shoot.cs index 5d51ecb..ef54268 100644 --- a/src/InventorMeta.App/MainWindow.Shoot.cs +++ b/src/InventorMeta.App/Shell/MainWindow.Shoot.cs @@ -6,7 +6,7 @@ using Windows.Graphics; using Windows.Foundation; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Shell; /// Helpers used only by the documentation snapshotter () and the /// demo tour (). diff --git a/src/InventorMeta.App/MainWindow.xaml b/src/InventorMeta.App/Shell/MainWindow.xaml similarity index 99% rename from src/InventorMeta.App/MainWindow.xaml rename to src/InventorMeta.App/Shell/MainWindow.xaml index bab044b..667feea 100644 --- a/src/InventorMeta.App/MainWindow.xaml +++ b/src/InventorMeta.App/Shell/MainWindow.xaml @@ -1,5 +1,5 @@ diff --git a/src/InventorMeta.App/MainWindow.xaml.cs b/src/InventorMeta.App/Shell/MainWindow.xaml.cs similarity index 95% rename from src/InventorMeta.App/MainWindow.xaml.cs rename to src/InventorMeta.App/Shell/MainWindow.xaml.cs index 0392cf1..073d3cb 100644 --- a/src/InventorMeta.App/MainWindow.xaml.cs +++ b/src/InventorMeta.App/Shell/MainWindow.xaml.cs @@ -13,7 +13,7 @@ using Microsoft.UI.Windowing; using Windows.Graphics; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Shell; public sealed partial class MainWindow { @@ -72,9 +72,18 @@ public MainWindow(bool isPrimary) string[] cli = Environment.GetCommandLineArgs(); DispatcherQueue.TryEnqueue(() => { - foreach (string a in cli.Skip(1).Where(File.Exists)) + foreach (string a in cli.Skip(1)) { - OpenFile(a); + if (File.Exists(a)) + { + OpenFile(a); + } + else + { + // otherwise a mistyped path or a stale shortcut opens an empty window + // with no trace of why + Serilog.Log.Warning("File passed on the command line does not exist: {File}", a); + } } }); @@ -339,6 +348,7 @@ private void OpenFile(string path) private void OnTabClose(TabView sender, TabViewTabCloseRequestedEventArgs args) { if (ReferenceEquals(args.Tab, HomeTab)) { return; } + Serilog.Log.Debug("Closed tab {File}", (args.Tab.Content as DocumentView)?.FilePath); DocTabs.TabItems.Remove(args.Tab); AfterTabRemoved(); } @@ -390,7 +400,14 @@ private void OnTabSelectionChanged(object sender, SelectionChangedEventArgs e) } } - public void SetStatus(string message) => StatusText.Text = message; + /// Status-bar sink for every view in this window. Each message also goes to the app + /// log: the status bar carries the user-visible trace of what happened (loads, exports, + /// repairs, errors), and mirroring it makes the log tell the same story. + public void SetStatus(string message) + { + StatusText.Text = message; + Serilog.Log.Information("status: {Message}", message); + } /// True if any document tab is open (i.e. a tab other than Home). private bool HasDocTabs() => DocTabs.TabItems.OfType().Any(t => !ReferenceEquals(t, HomeTab)); diff --git a/src/InventorMeta.App/Analytics.cs b/src/InventorMeta.App/Telemetry/Analytics.cs similarity index 98% rename from src/InventorMeta.App/Analytics.cs rename to src/InventorMeta.App/Telemetry/Analytics.cs index 956939e..7639fc5 100644 --- a/src/InventorMeta.App/Analytics.cs +++ b/src/InventorMeta.App/Telemetry/Analytics.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; using Serilog; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Telemetry; /// /// Minimal, privacy-respecting product analytics via PostHog (EU). Sends anonymous feature-usage diff --git a/src/InventorMeta.App/AnalyticsConsent.cs b/src/InventorMeta.App/Telemetry/AnalyticsConsent.cs similarity index 96% rename from src/InventorMeta.App/AnalyticsConsent.cs rename to src/InventorMeta.App/Telemetry/AnalyticsConsent.cs index 7699510..500cbfc 100644 --- a/src/InventorMeta.App/AnalyticsConsent.cs +++ b/src/InventorMeta.App/Telemetry/AnalyticsConsent.cs @@ -1,6 +1,6 @@ using System; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Telemetry; /// /// Persisted product-analytics consent. Stores whether the user opted in, whether they've been diff --git a/src/InventorMeta.App/InventorInstalls.cs b/src/InventorMeta.App/Viewer3D/InventorInstalls.cs similarity index 84% rename from src/InventorMeta.App/InventorInstalls.cs rename to src/InventorMeta.App/Viewer3D/InventorInstalls.cs index b114418..bad4a9e 100644 --- a/src/InventorMeta.App/InventorInstalls.cs +++ b/src/InventorMeta.App/Viewer3D/InventorInstalls.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text.RegularExpressions; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Viewer3D; /// An installed Autodesk Inventor release - the year and the Inventor.exe that drives it /// over COM. Every release ships the SVF/collaboration translator add-in used to generate viewables. @@ -36,7 +36,10 @@ public static IReadOnlyList Detect() } } - return byYear.Values.OrderByDescending(i => i.Year).ToList(); + List found = byYear.Values.OrderByDescending(i => i.Year).ToList(); + Serilog.Log.Debug("Inventor installs detected: {Installs}", + found.Count == 0 ? "none" : string.Join(", ", found.Select(i => i.DisplayName))); + return found; } private static IEnumerable SafeDirs(string root, string pattern) diff --git a/src/InventorMeta.App/Viewer3D/InventorOpener.cs b/src/InventorMeta.App/Viewer3D/InventorOpener.cs new file mode 100644 index 0000000..ac52b81 --- /dev/null +++ b/src/InventorMeta.App/Viewer3D/InventorOpener.cs @@ -0,0 +1,58 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; + +namespace ExtrabbitCode.Inventor.MetaReader.App.Viewer3D; + +/// +/// Opens a document in Autodesk Inventor itself - into a running session when one is up (any +/// release), otherwise by launching the given install. Used after a segment repair so the result +/// can be verified immediately in the real application. Late-bound COM on a dedicated STA thread, +/// like ; the session is made visible and brought to the front BEFORE +/// the open, so any prompt Inventor raises (e.g. Resolve Link) is right in front of the user. +/// +internal static class InventorOpener +{ + /// Open in Inventor. Returns null on success, or a + /// user-showable error message. Never closes or hides an Inventor session. + public static Task OpenAsync(InventorInstall inventor, string filePath) + { + TaskCompletionSource tcs = new(); + Thread t = new(() => + { + object? app = null; + using IDisposable? filter = SvfGenerator.OleMessageFilter.Register( + m => Serilog.Log.Information("Open in Inventor: {Step}", m)); + try + { + (app, bool startedByUs) = SvfGenerator.ConnectOrLaunch(inventor); + dynamic inv = app; + inv.Visible = true; + TryFocus((IntPtr)(long)inv.MainFrameHWND); + _ = inv.Documents.Open(filePath, true); + tcs.SetResult(null); + } + catch (Exception ex) + { + Serilog.Log.Warning("Open in Inventor failed (0x{HResult:X8}): {Error}", ex.HResult, ex.Message); + tcs.SetResult(SvfGenerator.FriendlyError(ex)); + } + finally + { + if (app != null) { try { Marshal.ReleaseComObject(app); } catch { /* teardown */ } } + } + }) { IsBackground = true }; + t.SetApartmentState(ApartmentState.STA); + t.Start(); + return tcs.Task; + } + + private static void TryFocus(IntPtr hwnd) + { + try { if (hwnd != IntPtr.Zero) { SetForegroundWindow(hwnd); } } catch { /* focus is best-effort */ } + } + + [DllImport("user32.dll")] + private static extern bool SetForegroundWindow(IntPtr hWnd); +} diff --git a/src/InventorMeta.App/SvfGenerator.cs b/src/InventorMeta.App/Viewer3D/SvfGenerator.cs similarity index 65% rename from src/InventorMeta.App/SvfGenerator.cs rename to src/InventorMeta.App/Viewer3D/SvfGenerator.cs index b94424d..382cc30 100644 --- a/src/InventorMeta.App/SvfGenerator.cs +++ b/src/InventorMeta.App/Viewer3D/SvfGenerator.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; @@ -6,13 +7,19 @@ using System.Runtime.InteropServices; using System.Threading; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Viewer3D; /// /// Generates an SVF viewable for a model by driving Inventor's SVF/collaboration translator add-in /// over COM (the same SaveCopyAs the sample iLogic macro uses). Late-bound so it works against any /// installed Inventor release without a version-specific interop reference. Requires Inventor /// installed; viewing an already-cached SVF does not. +/// +/// Each translation runs in its OWN dedicated Inventor instance that MetaReader starts and then +/// tears down (Quit, with a hard process-kill fallback). It never attaches to - or disturbs - an +/// Inventor session the user already has open: a headless job that borrowed a live session was the +/// main source of flakiness (the user's modal dialogs, in-progress edits and add-ins all +/// interfered), so isolation is deliberate. /// public static class SvfGenerator { @@ -23,12 +30,12 @@ public static class SvfGenerator public sealed record Result(bool Ok, string? BubblePath, string? Error); /// Translates to SVF in using - /// . Long-running (opens the model in Inventor) - call off the UI thread. - /// When is set, an Inventor instance we launch ourselves is kept - /// hidden (a session the user already had open is never touched). When is - /// set, Inventor's dialog prompts are suppressed for the duration. + /// . Long-running (opens the model in a freshly started, dedicated + /// Inventor) - call off the UI thread. The instance is always torn down before returning. When + /// is set, that dedicated instance stays hidden; when + /// is set, its dialog prompts are suppressed. public static Result Generate(InventorInstall inventor, string filePath, string outputBaseDir, - bool hideWhenStarted = true, bool silent = true, Action? log = null) + bool hide = true, bool silent = true, Action? log = null) { void L(string m) => log?.Invoke(m); // Fresh entry each run - the translator creates its own output\ subfolder under here. @@ -36,32 +43,29 @@ public static Result Generate(InventorInstall inventor, string filePath, string Directory.CreateDirectory(outputBaseDir); object? inv = null; - bool startedByUs = false; - bool? prevSilent = null; // previous SilentOperation, restored on a borrowed session + IReadOnlyList ownedPids = []; IDisposable? filter = null; try { - // A running Inventor that's momentarily busy (mid-operation or showing a dialog) rejects - // incoming COM calls; without a message filter that surfaces instantly as - // RPC_E_CALL_REJECTED. The filter retries the busy call instead of failing. + // A busy Inventor (mid-operation or showing a dialog) rejects incoming COM calls; without + // a message filter that surfaces instantly as RPC_E_CALL_REJECTED. The filter retries the + // busy call instead of failing. filter = OleMessageFilter.Register(L); - L("Connecting to Inventor…"); - (inv, startedByUs) = ConnectOrLaunch(inventor); - L(startedByUs ? "Launched a new Inventor instance." : "Attached to a running Inventor instance."); + L("Starting a dedicated Inventor instance…"); + (inv, ownedPids) = LaunchDedicated(inventor, L); dynamic app = inv; - // Suppress Inventor's dialog prompts during the unattended translation; remember the prior - // value so a session the user already had open is restored afterward. + // Suppress Inventor's dialog prompts during the unattended translation. No need to restore + // it - this instance exists only for this run and is killed at the end. if (silent) { - try { prevSilent = (bool)app.SilentOperation; app.SilentOperation = true; L("SilentOperation = true"); } + try { app.SilentOperation = true; L("SilentOperation = true"); } catch { L("Couldn't set SilentOperation."); } } - // Only hide an instance we launched ourselves - never change a running session's visibility. - if (startedByUs && hideWhenStarted) + if (hide) { - try { app.Visible = false; L("Inventor hidden (launched by us)."); } + try { app.Visible = false; L("Inventor hidden."); } catch { L("Couldn't hide Inventor."); } } @@ -136,21 +140,35 @@ public static Result Generate(InventorInstall inventor, string filePath, string } finally { - if (inv != null) + TearDown(inv, ownedPids, L); + filter?.Dispose(); // revoke the message filter last, so it still covers Quit / release above + } + } + + /// Shuts down the dedicated Inventor instance: a graceful Quit first, then - because a + /// headless Inventor sometimes ignores Quit - a hard kill of the exact process(es) this run + /// spawned. Only PIDs identified as ours are killed, so a session the user already had open is + /// never affected. + private static void TearDown(object? inv, IReadOnlyList ownedPids, Action log) + { + if (inv != null) + { + try { ((dynamic)inv).Quit(); log("Inventor Quit requested."); } + catch (Exception ex) { log($"Quit failed ({ex.GetType().Name}); will hard-kill."); } + try { Marshal.FinalReleaseComObject(inv); } catch { /* ignore */ } + } + + foreach (int pid in ownedPids) + { + Process? p; + try { p = Process.GetProcessById(pid); } catch { continue; } // already gone = clean Quit + using (p) { - // Restore dialog suppression on a borrowed session (an instance we started is about to - // quit, so there's nothing to put back). - if (!startedByUs && prevSilent.HasValue) - { - try { ((dynamic)inv).SilentOperation = prevSilent.Value; } catch { /* ignore */ } - } - if (startedByUs) - { - try { ((dynamic)inv).Quit(); } catch { /* leave it running if it refuses */ } - } - try { Marshal.FinalReleaseComObject(inv); } catch { /* ignore */ } + // give a graceful Quit a moment to land before forcing it + if (p.WaitForExit(8000)) { log($"Inventor (pid {pid}) exited."); continue; } + try { p.Kill(entireProcessTree: true); log($"Hard-killed Inventor (pid {pid})."); } + catch (Exception ex) { log($"Couldn't kill Inventor (pid {pid}): {ex.Message}"); } } - filter?.Dispose(); // revoke the message filter last, so it still covers Quit / release above } } @@ -164,18 +182,60 @@ private static void SetValue(object nameValueMap, string name, object value) => private const int RPC_E_SERVERCALL_REJECTED = unchecked((int)0x80010004); /// Turns a COM failure into a message worth showing the user; the raw HRESULT is logged - /// separately for diagnosis. - private static string FriendlyError(Exception ex) => ex.HResult switch + /// separately for diagnosis. (Shared with .) + internal static string FriendlyError(Exception ex) => ex.HResult switch { RPC_E_CALL_REJECTED or RPC_E_SERVERCALL_RETRYLATER or RPC_E_SERVERCALL_REJECTED => - "Inventor was busy and didn't respond in time. Close any open dialog in Inventor (or close " - + "that Inventor session so MetaReader can start its own), then try again.", + "Inventor was busy and didn't respond in time. Close any modal dialog open in Inventor, " + + "then try again.", _ => ex.Message, }; + /// Starts a brand-new, dedicated Inventor instance and returns it together with the OS + /// process id(s) it spawned (for a guaranteed teardown). COM activation ("CreateObject" + /// semantics) hands back a direct reference to our own instance, so - unlike attaching via the + /// running-object table - we never grab, and later quit, a session the user already had open. + /// Verified against Inventor 2024-2027: each activation is a distinct new Inventor.exe, even when + /// other instances are already running. + internal static (object app, IReadOnlyList ownedPids) LaunchDedicated(InventorInstall inventor, Action log) + { + Type? progId = Type.GetTypeFromProgID("Inventor.Application"); + if (progId == null) + { + throw new InvalidOperationException("The Inventor.Application COM class isn't registered on this machine."); + } + + HashSet before = InventorPids(); + object app = Activator.CreateInstance(progId) + ?? throw new InvalidOperationException($"Couldn't start {inventor.DisplayName}."); + + // Identify the process we just spawned so it can be force-killed at the end. It may register a + // moment after CreateInstance returns, so poll briefly. + List owned = []; + for (int i = 0; i < 25 && owned.Count == 0; i++) + { + owned = [.. InventorPids().Except(before)]; + if (owned.Count > 0) { break; } + Thread.Sleep(200); + } + log(owned.Count > 0 + ? $"Started a dedicated Inventor (pid {string.Join(",", owned)})." + : "Started a dedicated Inventor (couldn't identify its process id for a kill fallback)."); + return (app, owned); + } + + /// Process ids of every running Inventor.exe (empty on any failure). + private static HashSet InventorPids() + { + try { return [.. Process.GetProcessesByName("Inventor").Select(p => p.Id)]; } + catch { return []; } + } + /// Uses a running Inventor if one is up; otherwise launches the selected release and - /// waits for it to register as a COM server. - private static (object app, bool startedByUs) ConnectOrLaunch(InventorInstall inventor) + /// waits for it to register as a COM server. Used by to open a file + /// in the user's own session - the SVF generator deliberately does NOT share this and always + /// starts its own isolated instance instead. + internal static (object app, bool startedByUs) ConnectOrLaunch(InventorInstall inventor) { if (TryGetActiveInventor(out object? running)) { return (running!, false); } @@ -224,7 +284,7 @@ private interface IOleMessageFilter [PreserveSig] int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType); } - private sealed class OleMessageFilter : IOleMessageFilter + internal sealed class OleMessageFilter : IOleMessageFilter { private const int SERVERCALL_RETRYLATER = 2; // dwRejectType values private const int SERVERCALL_REJECTED = 1; diff --git a/src/InventorMeta.App/SvfStore.cs b/src/InventorMeta.App/Viewer3D/SvfStore.cs similarity index 92% rename from src/InventorMeta.App/SvfStore.cs rename to src/InventorMeta.App/Viewer3D/SvfStore.cs index 9156b1b..d52fa8c 100644 --- a/src/InventorMeta.App/SvfStore.cs +++ b/src/InventorMeta.App/Viewer3D/SvfStore.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Security.Cryptography; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Viewer3D; /// /// On-disk cache of generated SVF viewables. A model maps to an entry keyed by the SHA-256 of its @@ -86,8 +86,13 @@ public long ClearLocal() { if (Directory.Exists(LocalRoot)) { Directory.Delete(LocalRoot, recursive: true); } } - catch { return 0; } + catch (Exception ex) + { + Serilog.Log.Warning(ex, "Clearing the local SVF cache at {Dir} failed", LocalRoot); + return 0; + } + Serilog.Log.Information("Local SVF cache cleared ({Freed:N0} B at {Dir})", freed, LocalRoot); return freed; } diff --git a/src/InventorMeta.App/SvfTestRunner.cs b/src/InventorMeta.App/Viewer3D/SvfTestRunner.cs similarity index 98% rename from src/InventorMeta.App/SvfTestRunner.cs rename to src/InventorMeta.App/Viewer3D/SvfTestRunner.cs index fb028a7..efeb98f 100644 --- a/src/InventorMeta.App/SvfTestRunner.cs +++ b/src/InventorMeta.App/Viewer3D/SvfTestRunner.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Runtime.InteropServices; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Viewer3D; /// /// Headless diagnostic entry point for the 3D generation chain - no UI yet. Run: diff --git a/src/InventorMeta.App/ViewerLog.cs b/src/InventorMeta.App/Viewer3D/ViewerLog.cs similarity index 87% rename from src/InventorMeta.App/ViewerLog.cs rename to src/InventorMeta.App/Viewer3D/ViewerLog.cs index e7337ca..b824203 100644 --- a/src/InventorMeta.App/ViewerLog.cs +++ b/src/InventorMeta.App/Viewer3D/ViewerLog.cs @@ -1,6 +1,6 @@ using Serilog; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Viewer3D; /// Routes 3D-viewer diagnostics (JS messages and failed fetches) into the app log at Debug /// level. A thin shim over Serilog so the viewer code stays unchanged. diff --git a/src/InventorMeta.App/ViewerSettings.cs b/src/InventorMeta.App/Viewer3D/ViewerSettings.cs similarity index 98% rename from src/InventorMeta.App/ViewerSettings.cs rename to src/InventorMeta.App/Viewer3D/ViewerSettings.cs index 3065c31..6120e5e 100644 --- a/src/InventorMeta.App/ViewerSettings.cs +++ b/src/InventorMeta.App/Viewer3D/ViewerSettings.cs @@ -1,6 +1,6 @@ using System; -namespace ExtrabbitCode.Inventor.MetaReader.App; +namespace ExtrabbitCode.Inventor.MetaReader.App.Viewer3D; /// How the reference graph arranges its nodes. internal enum GraphLayout { LeftRight, TopDown, Network } diff --git a/src/InventorMeta.Cli/Program.cs b/src/InventorMeta.Cli/Program.cs index 6390ab2..cf414af 100644 --- a/src/InventorMeta.Cli/Program.cs +++ b/src/InventorMeta.Cli/Program.cs @@ -17,6 +17,8 @@ Inventor metadata reader - reads .ipt/.iam/.idw/.ipn and .stp/.step without Auto invmeta json full metadata as JSON invmeta props every property in every OLE property set invmeta graph recursive reference tree (resolved on disk) + invmeta segments RSeStorage segment inventory + damage check + invmeta repair fix stale segment summaries (backs the file up first) invmeta tree raw CFB storage/stream tree invmeta thumb [outBase] extract the embedded preview image invmeta extract dump every stream to disk @@ -35,7 +37,7 @@ invmeta cat hex+ascii dump of one stream return 2; } -if (isStep && cmd is "tree" or "cat" or "extract" or "thumb") +if (isStep && cmd is "tree" or "cat" or "extract" or "thumb" or "segments" or "repair") { Console.Error.WriteLine($"'{cmd}' reads the OLE compound file structure; STEP files (.stp/.step) don't have one."); return 2; @@ -49,6 +51,8 @@ invmeta cat hex+ascii dump of one stream case "thumb": Thumb(new InventorDocument(file), args.Length > 2 ? args[2] : Path.GetFileNameWithoutExtension(file) + "_thumb"); break; case "props": if (isStep) { StepProps(new InventorDocument(file)); } else { Props(file); } break; case "graph": Graph(new InventorDocument(file)); break; + case "segments":Segments(new InventorDocument(file)); break; + case "repair": return Repair(file); case "tree": Tree(file); break; case "extract": Extract(file, args[2]); break; case "cat": Cat(file, args[2]); break; @@ -56,6 +60,119 @@ invmeta cat hex+ascii dump of one stream } return 0; +static void Segments(InventorDocument doc) +{ + IReadOnlyList segs = doc.Segments; + if (segs.Count == 0) { Console.WriteLine("No RSeStorage segments found."); return; } + + long total = segs.Sum(s => s.DataSize); + Console.WriteLine($"RSeStorage segments ({segs.Count}, {total:N0} B of payload)\n"); + Console.WriteLine($" {"SEGMENT",-22} {"DATA",13} {"META",10} {"BLOCKS",9} MODIFIED"); + Dictionary destroyed = doc.DataDamage + .Where(d => d.Location.Length == 0) + .ToDictionary(d => d.SegmentName, StringComparer.Ordinal); + foreach (InventorDocument.Segment s in segs) + { + string blocks = s.ActualBlockCount?.ToString("N0") ?? "?"; + string mark = destroyed.ContainsKey(s.Name) ? " !! data destroyed" + : s.HasCountMismatch ? $" !! summary says {s.SummaryBlockCount:N0}" + : s.IsGraphicsCache ? " *graphics cache" : ""; + string when = s.Modified?.ToString("yyyy-MM-dd HH:mm") ?? ""; + Console.WriteLine($" {s.Name,-22} {s.DataSize,13:N0} {s.MetaSize,10:N0} {blocks,9} {when}{mark}"); + } + if (doc.HasDestroyedSegmentData) + { + Console.WriteLine("\n !! destroyed segment data - runs of zeroed bytes sit where compressed payload"); + Console.WriteLine(" used to be (typical of a disk fault or an interrupted copy):"); + foreach (SegmentDataCheck.Damage d in doc.DataDamage) + { + string where = d.Location.Length == 0 ? "" : $" (member {d.Location})"; + string detail = d.ChecksumOnly + ? "content silently altered (checksum mismatch)" + : $"only {d.RecoveredBytes:N0} of at least {d.ExpectedBytes:N0} B readable"; + Console.WriteLine($" {d.SegmentName,-22} {detail}{where}"); + } + Console.WriteLine(" This is NOT repairable: the destroyed bytes are gone, the stream cannot be"); + Console.WriteLine(" re-synchronized past the damage, and Inventor needs every segment intact."); + Console.WriteLine(" Restore the file from a backup (Vault/PDM, OldVersions, or a file backup)."); + } + else if (doc.HasRepairableSegmentDamage) + { + Console.WriteLine("\n !! stale segment summaries - Inventor will refuse to open this file."); + Console.WriteLine(" Run 'invmeta repair' to fix it in place (a backup copy is made first)."); + } + else + { + Console.WriteLine("\n * segment data verified: every payload decompresses cleanly."); + } +} + +static int Repair(string file) +{ + // Destroyed payload data first: nothing can repair that, and reporting "consistent" or + // patching summaries on such a file would only mislead. SegmentRepair.Repair refuses this + // case too; checking here gives the full explanation instead of a one-line error. + IReadOnlyList destroyed; + try + { + destroyed = SegmentDataCheck.FindDamage(file); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) + { + Console.Error.WriteLine($"Repair failed: {ex.Message}"); + return 2; + } + if (destroyed.Count > 0) + { + Console.Error.WriteLine($"{Path.GetFileName(file)} cannot be repaired - segment data is destroyed:"); + foreach (SegmentDataCheck.Damage d in destroyed) + { + string where = d.Location.Length == 0 ? "" : $" (member {d.Location})"; + string detail = d.ChecksumOnly + ? "content silently altered (checksum mismatch)" + : $"only {d.RecoveredBytes:N0} of at least {d.ExpectedBytes:N0} B readable"; + Console.Error.WriteLine($" {d.SegmentName,-22} {detail}{where}"); + } + Console.Error.WriteLine(""" + + Runs of zeroed bytes sit where compressed payload used to be - the signature of a + disk fault or an interrupted copy. The destroyed bytes are physically gone, the + stream cannot be re-synchronized past the damage, and Inventor needs every segment + intact to open a file. Restore the file from a backup instead: Vault or another PDM, + the OldVersions folder next to the file, or a file backup. + """); + return 3; + } + + // Repair scans internally and reports what it actually patched - one scan, and the printed + // list can never disagree with what happened to the file. + SegmentRepair.RepairResult result; + try + { + result = SegmentRepair.Repair(file); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) + { + Console.Error.WriteLine($"Repair failed: {ex.Message}"); + return 2; + } + + if (result.Repaired.Count == 0) + { + Console.WriteLine("Segment summaries are consistent - nothing to repair."); + return 0; + } + + Console.WriteLine($"Repaired stale segment summaries in {Path.GetFileName(file)}:"); + foreach (SegmentRepair.Issue i in result.Repaired) + { + string where = i.Location.Length == 0 ? "" : $" (member {i.Location})"; + Console.WriteLine($" {i.SegmentName,-22} summary {i.SummaryCount,10:N0} -> actual {i.ActualCount:N0}{where}"); + } + Console.WriteLine($"\nBackup of the original: {result.BackupPath}"); + return 0; +} + static void Graph(InventorDocument doc) { RefNode root = ReferenceGraph.Build(doc); diff --git a/src/InventorMeta/Cfb.cs b/src/InventorMeta/Cfb.cs index 6747ce6..bec5a69 100644 --- a/src/InventorMeta/Cfb.cs +++ b/src/InventorMeta/Cfb.cs @@ -237,6 +237,126 @@ public byte[] ReadEntry(DirEntry e) return ReadFatChain(e.StartSector, e.Size); } + /// Overwrite an existing stream's bytes without changing its size. The replacement + /// re-uses the stream's sector chain in place, so the directory, FAT and every other stream + /// stay byte-identical - exactly what a targeted metadata repair needs. Call + /// afterwards to persist the change. + public void OverwriteStreamInPlace(DirEntry e, byte[] data) + { + if (e.Type != 2) + { + throw new InvalidOperationException("Not a stream entry."); + } + + if (data.Length != e.Size) + { + throw new ArgumentException($"Replacement must match the stream size ({e.Size} bytes, got {data.Length})."); + } + + if (e.Size < MiniStreamCutoff) + { + WriteMiniChain(e.StartSector, data); + } + else + { + WriteChain(e.StartSector, data, CheckedSectorOffset, SectorSize, NextFat); + } + } + + /// Write the (patched) container back to disk. The bytes go to a temp sibling first + /// and replace the target atomically, so a crash or full disk mid-write cannot leave the file + /// truncated - it either keeps its old content or has the new one. + public void Save(string path) + { + string tmp = path + ".saving.tmp"; + File.WriteAllBytes(tmp, _data); + try + { + if (File.Exists(path)) + { + File.Replace(tmp, path, null); + } + else + { + File.Move(tmp, path); + } + } + catch + { + try { File.Delete(tmp); } catch { /* best-effort cleanup */ } + throw; + } + } + + private void WriteMiniChain(uint start, byte[] data) + { + // Mini sectors live inside the root entry's regular FAT chain; map each mini sector + // to its file offset through that chain. MiniSectorSize divides SectorSize, so a mini + // sector never straddles two container sectors. + List rootChain = []; + uint rs = Directory[0].StartSector; int guard = 0; + while (rs != ENDOFCHAIN && rs != FREESECT && guard++ < Fat.Length + 4) + { + rootChain.Add(rs); + rs = NextFat(rs); + } + + int FileOffset(uint miniSector) + { + long byteOff = (long)miniSector * MiniSectorSize; + int idx = (int)(byteOff / SectorSize); + if (idx >= rootChain.Count) + { + throw new InvalidDataException("Mini sector beyond the mini-stream container."); + } + + // CheckedSectorOffset refuses corrupt root-chain entries; the mini sector then stays + // inside that validated container sector (MiniSectorSize divides SectorSize). + return CheckedSectorOffset(rootChain[idx]) + (int)(byteOff % SectorSize); + } + + WriteChain(start, data, FileOffset, MiniSectorSize, + s => s < MiniFat.Length ? MiniFat[s] : ENDOFCHAIN); + } + + /// Maps a FAT sector to its file offset like , but refuses + /// (instead of wrapping through the int cast or clamping like the read side) when a corrupt + /// chain entry points into the header or beyond the container - a WRITE there would destroy + /// unrelated container structures. + private int CheckedSectorOffset(uint s) + { + long off = ((long)s + 1) * SectorSize; + if (off < SectorSize || off + SectorSize > _data.Length) + { + throw new InvalidDataException($"Corrupt sector chain: sector {s} maps outside the container; refusing to write."); + } + return (int)off; + } + + private void WriteChain(uint start, byte[] data, Func fileOffset, int sectorSize, Func next) + { + int written = 0; + uint s = start; int guard = 0; + while (s != ENDOFCHAIN && s != FREESECT && written < data.Length && guard++ < _data.Length / sectorSize + 4) + { + int off = fileOffset(s); + int n = Math.Min(sectorSize, data.Length - written); + if (off < SectorSize || off + n > _data.Length) + { + throw new InvalidDataException($"Corrupt sector chain: write at offset {off} would leave the container; refusing."); + } + + Array.Copy(data, written, _data, off, n); + written += n; + s = next(s); + } + + if (written != data.Length) + { + throw new InvalidDataException("Sector chain ended before the replacement data was fully written."); + } + } + // ---- Chain readers ---- private byte[] ReadFatChain(uint start, long size = -1) { diff --git a/src/InventorMeta/InventorDocument.cs b/src/InventorMeta/InventorDocument.cs index 50dde44..741fc91 100644 --- a/src/InventorMeta/InventorDocument.cs +++ b/src/InventorMeta/InventorDocument.cs @@ -78,6 +78,167 @@ public sealed class ModelState private string _primaryName = "[Primary]"; public List References { get; } = []; + /// One segment of the proprietary RSeStorage document database (geometry, graphics cache, + /// browser tree, …). The payload is not decoded, but the segment's identity, size and block-count + /// bookkeeping are readable - enough to inventory the database and spot the classic damage where + /// the registry's block-count summary went stale and Inventor refuses to load the file + /// ("the number of objects found in the segment does not match the segment summary"). + public sealed class Segment + { + public string Name = ""; // segment type, e.g. "PmGraphicsSegment" (read from its metadata stream) + public string Id = ""; // the mangled id shared by the paired data (B) and metadata (M) streams + public long DataSize; // bytes in the B<id> payload stream + public long MetaSize; // bytes in the M<id> metadata stream + public DateTime? Modified; // last-modified time of the payload stream + /// Block count the RSeSegInfo registry claims this segment has; what Inventor + /// expects to find on load. Null when the file's format revision isn't understood. + public long? SummaryBlockCount; + /// Block count actually present, per the segment's own metadata block table. + /// Null when the file's format revision isn't understood. + public long? ActualBlockCount; + /// True when the registry summary disagrees with the blocks actually present - + /// Inventor refuses to open such a file; fixes it. + public bool HasCountMismatch => SummaryBlockCount.HasValue && ActualBlockCount.HasValue && + SummaryBlockCount != ActualBlockCount; + /// The regenerable display-graphics cache - the segment most often found corrupt. + public bool IsGraphicsCache => Name.IndexOf("Graphics", StringComparison.OrdinalIgnoreCase) >= 0; + public override string ToString() => $"{Name} ({DataSize:N0} B)"; + } + + private List? _segments; + + /// The RSeStorage segments (the internal payload databases), largest first. Lets you take + /// stock of what a file carries and flag a damaged segment - useful when Inventor errors with + /// "Error loading segment …", which this tool reads straight past. + public IReadOnlyList Segments => _segments ??= ReadSegments(); + + private IReadOnlyList? _segmentIssues; + + /// Every segment whose registry summary disagrees with its actual block count, across + /// the document's own RSeStorage tree and the trees of embedded model-state members. Empty for + /// a healthy file. Derived from the same single scan that fills - the + /// file is opened and its metadata decompressed once, not per property. + public IReadOnlyList SegmentIssues + { + get + { + if (_segmentIssues == null) + { + _ = Segments; // one scan fills both caches + _segmentIssues ??= []; // unreadable container -> no verdict + } + return _segmentIssues; + } + } + + /// True when at least one segment's registry summary disagrees with its actual block + /// count - the damage that makes Inventor refuse the file and that + /// fixes in place. + public bool HasRepairableSegmentDamage => SegmentIssues.Count > 0; + + private IReadOnlyList? _dataDamage; + + /// Segments whose payload data is physically destroyed (zeroed sectors inside the + /// compressed stream) - the damage class NOTHING can repair, because the bytes are gone and + /// Inventor needs every segment fully intact. Empty for healthy files. First access + /// decompresses every segment payload, so read this off the UI thread for large files. + public IReadOnlyList DataDamage + { + get + { + if (_dataDamage == null) + { + try { _dataDamage = IsStep ? [] : SegmentDataCheck.FindDamage(FilePath); } + catch { _dataDamage = []; } // unreadable container -> no verdict + } + return _dataDamage; + } + } + + /// True when segment payload data is destroyed - see . Do + /// not offer a repair for such a file: the only fix is restoring a backup. + public bool HasDestroyedSegmentData => DataDamage.Count > 0; + + private List ReadSegments() + { + List list = []; + try + { + using CompoundFile cf = new(FilePath); + Dictionary data = new(StringComparer.Ordinal); + Dictionary meta = new(StringComparer.Ordinal); + foreach (CompoundFile.DirEntry e in cf.Directory) + { + // Segment streams are the B<id>/M<id> pairs directly under /RSeStorage. + if (e.Type != 2 || e.Name.Length < 2 || !ParentIs(e.Path, "/RSeStorage")) { continue; } + string id = e.Name[1..]; + if (e.Name[0] == 'B') { data[id] = e; } + else if (e.Name[0] == 'M') { meta[id] = e; } + } + + // One scan serves everything: SegmentIssues (all trees) and the per-segment counts + // here (the document's own tree, joined by the B/M storage id - names can repeat). + List scanned = SegmentRepair.ScanCounts(cf); + _segmentIssues = SegmentRepair.ToIssues(scanned); + Dictionary counts = new(StringComparer.Ordinal); + foreach (SegmentRepair.SegmentCounts c in scanned) + { + if (c.Location.Length == 0 && c.StorageId.Length > 0) + { + counts[c.StorageId] = c; + } + } + + foreach ((string id, CompoundFile.DirEntry b) in data) + { + if (!meta.TryGetValue(id, out CompoundFile.DirEntry? m)) { continue; } + counts.TryGetValue(id, out SegmentRepair.SegmentCounts? c); + // the scan already parsed the name; the legacy scan-for-text fallback covers + // format revisions the strict parser declines + Segment seg = new() + { + Id = id, + Name = c?.Name ?? FirstUtf16String(cf.ReadEntry(m)), + DataSize = b.Size, + MetaSize = m.Size, + Modified = b.Modified is { Year: > 1601 } dt ? dt : null, + ActualBlockCount = c?.Actual, + SummaryBlockCount = c?.Summary, + }; + list.Add(seg); + } + list.Sort((x, y) => y.DataSize.CompareTo(x.DataSize)); + } + catch { /* malformed container -> empty inventory */ } + return list; + } + + private static bool ParentIs(string path, string parent) + { + int i = path.LastIndexOf('/'); + return i >= 0 && string.Equals(path[..i], parent, StringComparison.OrdinalIgnoreCase); + } + + /// A segment's metadata stream opens with its type name as a UTF-16 string (e.g. + /// "PmGraphicsSegment"); return that leading string. + private static string FirstUtf16String(byte[] data) + { + int i = 0; + while (i + 1 < data.Length) + { + if (data[i] is >= 0x20 and < 0x7f && data[i + 1] == 0) + { + int j = i; + StringBuilder sb = new(); + while (j + 1 < data.Length && data[j] is >= 0x20 and < 0x7f && data[j + 1] == 0) { sb.Append((char)data[j]); j += 2; } + if (sb.Length >= 3) { return sb.ToString(); } // skip 1-2 char header bytes before the name + i = j + 2; + } + else { i++; } + } + return ""; + } + private List? _categories; /// Content Center categories this part belongs to (Tube & Pipe, Frame Generator, …), @@ -683,6 +844,7 @@ public string ToJson() categories = Categories.Select(c => new { displayName = c.DisplayName, internalName = c.InternalName, mnemonic = c.Mnemonic }).ToArray(), subsystems = Subsystems.Select(s => new { key = s.Key, displayName = s.DisplayName }).ToArray(), primaryCategory = PrimaryCategory.ToString(), + segments = Segments.Select(s => new { name = s.Name, dataSize = s.DataSize, metaSize = s.MetaSize, isGraphicsCache = s.IsGraphicsCache }).ToArray(), isIPart = IsIPart, hasThumbnail = Thumbnail != null, properties = Properties diff --git a/src/InventorMeta/InventorMeta.csproj b/src/InventorMeta/InventorMeta.csproj index 11a47f4..b1b035a 100644 --- a/src/InventorMeta/InventorMeta.csproj +++ b/src/InventorMeta/InventorMeta.csproj @@ -7,4 +7,7 @@ ExtrabbitCode.Inventor.MetaReader ExtrabbitCode.Inventor.MetaReader + + + diff --git a/src/InventorMeta/SegmentDataCheck.cs b/src/InventorMeta/SegmentDataCheck.cs new file mode 100644 index 0000000..b136688 --- /dev/null +++ b/src/InventorMeta/SegmentDataCheck.cs @@ -0,0 +1,235 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; + +namespace ExtrabbitCode.Inventor.MetaReader; + +/// +/// Detects the second, unrepairable damage class: destroyed segment payload data. +/// +/// Each RSeStorage segment stores its payload in the B<id> stream as ONE compressed blob +/// (an 18-byte header - a fixed 16-byte format id, one version byte, one compression byte +/// (1 = zlib, 2 = zstd) - followed by the compressed image). Files damaged this way carry runs +/// of zeroed 512-byte sectors inside that blob, the classic signature of a disk fault or an +/// interrupted copy. The compressed stream has no resync points, so every byte after the first +/// damaged one is unrecoverable - and Inventor parses the complete decompressed image of every +/// segment when it opens a file (verified experimentally against Inventor 2027: any altered +/// content terminates the load, even inside the regenerable graphics cache - "Error loading +/// segment … in database"). +/// +/// Nothing can repair this: the bytes are physically gone. This check exists so the damage can +/// be NAMED instead of guessed at - which segments, how much survives - and so no repair is +/// offered that would fail. The fix is restoring the file from a backup (Vault or another PDM, +/// the OldVersions folder, or a file backup). Contrast with , which +/// handles the stale-summary class where no payload data is lost. +/// +public static class SegmentDataCheck +{ + /// The 16-byte format id every segment payload blob opens with. + private static ReadOnlySpan BlobMagic => + [0x9E, 0xC2, 0x2B, 0xA4, 0xD4, 0x11, 0xE8, 0x01, 0x60, 0x00, 0x2D, 0xB3, 0xEE, 0x29, 0xFB, 0xB0]; + + /// One segment whose payload data is destroyed. + public sealed class Damage + { + /// Segment type, e.g. "PmGraphicsSegment". + public string SegmentName = ""; + /// Which RSeStorage tree the segment lives in: "" for the document itself, or + /// the member-storage path of an embedded model-state member (same convention as + /// ). + public string Location = ""; + /// Size of the compressed payload stream on disk. + public long CompressedSize; + /// Bytes that still decompress cleanly before the stream breaks. + public long RecoveredBytes; + /// Bytes the segment's own block table promises at minimum (the decompressed + /// image is at least this long, plus internal bookkeeping after the blocks). + public long ExpectedBytes; + /// True for the freak case where the zeroed bytes landed inside stored (raw) + /// compression blocks: the stream still decodes end to end and only the checksum fails. + /// The content silently carries zero-filled holes - just as fatal for Inventor. + public bool ChecksumOnly; + /// Longest run of 0x00 inside the compressed stream - multiple KB here is the + /// zeroed-sector signature. + public long LongestZeroRun; + + public override string ToString() => + $"{SegmentName}: {RecoveredBytes:N0} of >= {ExpectedBytes:N0} B readable"; + } + + /// Scan a document for segments whose payload data is destroyed. Empty for healthy + /// files. Decompresses every segment payload, so this costs real time on big files - call it + /// deliberately, not per property. Parsing is strict: format revisions without the known blob + /// header yield no verdict rather than a false alarm. + public static IReadOnlyList FindDamage(string filePath) + { + using CompoundFile cf = new(filePath); + return Scan(cf); + } + + internal static List Scan(CompoundFile cf) + { + List damage = []; + + // Only claim a wiped header when this file demonstrably uses the known blob format - + // i.e. at least one sibling payload stream carries the magic. Keeps ancient or unknown + // format revisions verdict-free instead of "damaged". + bool fileUsesBlobFormat = cf.Directory.Any(e => + { + if (e.Type != 2 || e.Name.Length < 2 || e.Name[0] != 'B' || !SegmentRepair.IsRSeChild(e.Path)) + { + return false; + } + try + { + byte[] head = cf.ReadEntry(e); + return head.Length >= 18 && head.AsSpan(0, 16).SequenceEqual(BlobMagic); + } + catch { return false; } + }); + + foreach (CompoundFile.DirEntry m in cf.Directory) + { + if (m.Type != 2 || m.Name.Length < 2 || m.Name[0] != 'M' || !SegmentRepair.IsRSeChild(m.Path)) + { + continue; + } + + SegmentRepair.MetaStream? meta; + try { meta = SegmentRepair.ParseMetaStream(cf.ReadEntry(m)); } catch { continue; } + if (meta == null) + { + continue; // unknown metadata revision -> no verdict + } + + string tree = SegmentRepair.ParentPath(m.Path); + string bName = "B" + m.Name[1..]; + CompoundFile.DirEntry? b = cf.Directory.FirstOrDefault(e => + e.Type == 2 && e.Name == bName && + SegmentRepair.ParentPath(e.Path).Equals(tree, StringComparison.OrdinalIgnoreCase)); + if (b == null) + { + continue; + } + + byte[] data; + try { data = cf.ReadEntry(b); } catch { continue; } + + Damage? found = Check(data, meta.BlockBytes, fileUsesBlobFormat); + if (found != null) + { + found.SegmentName = meta.Name; + found.Location = SegmentRepair.LocationOf(tree); + damage.Add(found); + } + } + return damage; + } + + /// Verdict for one payload stream: null when it decompresses cleanly to at least the + /// block-table total (healthy) or when its format isn't the known blob layout (no verdict). + private static Damage? Check(byte[] data, long expectedBytes, bool fileUsesBlobFormat) + { + if (data.Length >= 18 && data.AsSpan(0, 16).SequenceEqual(BlobMagic) && data[17] is 1 or 2) + { + (bool ok, long produced, bool checksumOnly) = Decompress(data); + if (ok && produced >= expectedBytes) + { + return null; + } + + return new Damage + { + CompressedSize = data.Length, + RecoveredBytes = produced, + ExpectedBytes = expectedBytes, + ChecksumOnly = checksumOnly, + LongestZeroRun = LongestZeroRun(data), + }; + } + + // No (readable) blob header. When the rest of the file proves the format, a header that + // was zeroed away is the same sector damage - the whole payload is unreadable. + if (fileUsesBlobFormat && data.Take(Math.Min(data.Length, 18)).All(v => v == 0)) + { + return new Damage + { + CompressedSize = data.Length, + RecoveredBytes = 0, + ExpectedBytes = expectedBytes, + LongestZeroRun = LongestZeroRun(data), + }; + } + + return null; // unknown layout -> no verdict + } + + /// Inflate the blob, counting output only. zlib streams are decoded as bare deflate + /// with the adler32 verified by hand against the trailing 4 bytes - the framework's own + /// trailer validation has proven unreliable, and the checksum is exactly what catches the + /// freak case where zeroed bytes landed inside stored blocks and the structure still decodes. + private static (bool Ok, long Produced, bool ChecksumOnly) Decompress(byte[] data) + { + long produced = 0; + bool clean = false; + uint a = 1, b = 0; // adler32 state + try + { + using MemoryStream src = new(data, data[17] == 1 ? 20 : 18, data.Length - (data[17] == 1 ? 20 : 18)); + using Stream dec = data[17] == 1 + ? new DeflateStream(src, CompressionMode.Decompress) + : new ZstdSharp.DecompressionStream(src); + byte[] buf = new byte[64 * 1024]; + for (int n; (n = dec.Read(buf, 0, buf.Length)) > 0;) + { + produced += n; + if (data[17] == 1) + { + const uint Mod = 65521; + for (int k = 0; k < n; k++) + { + a = (a + buf[k]) % Mod; + b = (b + a) % Mod; + } + } + } + clean = true; + } + catch + { + // fell over inside the damaged region; 'produced' is what decoded before it + } + + if (!clean) + { + return (false, produced, false); + } + + if (data[17] == 1 && data.Length >= 22) + { + // the stream's last 4 bytes are the big-endian adler32 of the decompressed image + uint stored = (uint)((data[^4] << 24) | (data[^3] << 16) | (data[^2] << 8) | data[^1]); + if (stored != (b << 16 | a)) + { + return (false, produced, true); + } + } + return (true, produced, false); + } + + private static long LongestZeroRun(byte[] data) + { + long best = 0, run = 0; + foreach (byte v in data) + { + run = v == 0 ? run + 1 : 0; + if (run > best) + { + best = run; + } + } + return best; + } +} diff --git a/src/InventorMeta/SegmentRepair.cs b/src/InventorMeta/SegmentRepair.cs new file mode 100644 index 0000000..abd0573 --- /dev/null +++ b/src/InventorMeta/SegmentRepair.cs @@ -0,0 +1,440 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Text; + +namespace ExtrabbitCode.Inventor.MetaReader; + +/// +/// Detects and repairs the classic "Error in reading RSe segment - the number of objects found +/// in the segment does not match the segment summary" damage that makes Inventor refuse to open +/// a file MetaReader reads without complaint. +/// +/// Every RSeStorage segment stores its payload as blocks in the B<id> stream, an index over +/// those blocks in the M<id> stream, and a block-count summary in its /RSeStorage/RSeSegInfo +/// entry. On load, Inventor counts the blocks and hard-aborts the open when the RSeSegInfo +/// summary disagrees - a stale summary is all that is wrong with such files (observed after +/// external tooling rewrote the segment streams without refreshing the registry). The repair is +/// a same-size in-place patch of the summary values; no model data is touched, deleted or +/// recompressed, and freshly saved files satisfy summary == actual for every segment. +/// +public static class SegmentRepair +{ + /// One segment whose RSeSegInfo summary disagrees with the blocks actually present. + public sealed class Issue + { + /// Segment type, e.g. "PmGraphicsSegment". + public string SegmentName = ""; + /// Which RSeStorage tree the segment lives in: "" for the document itself, or the + /// member-storage path for an embedded model-state member. + public string Location = ""; + /// Block count the RSeSegInfo registry claims (what Inventor expects to find). + public long SummaryCount; + /// Block count actually present, per the segment's own M-stream block table. + public long ActualCount; + /// Byte offset of the summary u32 inside that tree's RSeSegInfo stream. + internal int PatchOffset; + /// Full path of the RSeSegInfo stream the patch belongs to. + internal string SegInfoPath = ""; + public override string ToString() => $"{SegmentName}: summary {SummaryCount:N0} <> actual {ActualCount:N0}"; + } + + /// Outcome of . + public sealed class RepairResult + { + /// Untouched copy of the file, created next to it before patching + /// (null when there was nothing to repair). + public string? BackupPath; + /// The mismatches that were patched (empty when the file was already consistent). + public IReadOnlyList Repaired = []; + } + + /// Scan a document for segments whose registry summary disagrees with their actual + /// block count. Empty for healthy files; parsing is strict, so unknown format variants yield + /// no issues rather than false alarms. + public static IReadOnlyList FindIssues(string filePath) + { + using CompoundFile cf = new(filePath); + return Scan(cf); + } + + /// Repair every detected mismatch: copy the file to a .pre-repair.bak sibling, then + /// patch the RSeSegInfo summaries in place (same-size write - nothing else in the container + /// moves). Returns the backup path and what was patched; a healthy file is left untouched. + public static RepairResult Repair(string filePath) + { + using CompoundFile cf = new(filePath); + List issues = Scan(cf); + if (issues.Count == 0) + { + return new RepairResult(); + } + + // Refuse to touch files whose payload data is destroyed (zeroed sectors): patching the + // summaries cannot bring the missing bytes back, the file stays unopenable, and a + // "successful repair" would only mislead. Checked before the backup so nothing is left + // behind. The real fix is restoring a backup of the file. + List destroyed = SegmentDataCheck.Scan(cf); + if (destroyed.Count > 0) + { + throw new InvalidDataException( + $"Segment data is destroyed ({string.Join(", ", destroyed.Select(d => d.SegmentName).Distinct())}) - " + + "the payload bytes are physically gone, so no repair can make this file open. " + + "Restore the file from a backup (Vault/PDM, the OldVersions folder, or a file backup)."); + } + + string backup = MakeBackupPath(filePath); + File.Copy(filePath, backup); + try + { + // patch each RSeStorage tree's own registry (the document's, plus any model-state member's) + foreach (IGrouping perTree in issues.GroupBy(i => i.SegInfoPath, StringComparer.OrdinalIgnoreCase)) + { + CompoundFile.DirEntry entry = cf.Directory.First(e => e.Type == 2 && string.Equals(e.Path, perTree.Key, StringComparison.OrdinalIgnoreCase)); + byte[] segInfo = cf.ReadEntry(entry); + foreach (Issue issue in perTree) + { + BitConverter.TryWriteBytes(segInfo.AsSpan(issue.PatchOffset, 4), (uint)issue.ActualCount); + } + cf.OverwriteStreamInPlace(entry, segInfo); + } + cf.Save(filePath); // atomic swap: the file has either its old or its new content + } + catch + { + // the target is untouched on failure (Save is atomic), so the backup has no value - + // don't leave orphaned .bak files behind (File.Copy carries over a ReadOnly attribute, + // which would make the delete fail silently) + try + { + File.SetAttributes(backup, FileAttributes.Normal); + File.Delete(backup); + } + catch { /* best-effort */ } + throw; + } + + return new RepairResult { BackupPath = backup, Repaired = issues }; + } + + /// "file.ipt" -> "file.ipt.pre-repair.bak" (numbered when that already exists). + private static string MakeBackupPath(string filePath) + { + string candidate = filePath + ".pre-repair.bak"; + for (int n = 2; File.Exists(candidate); n++) + { + candidate = $"{filePath}.pre-repair({n}).bak"; + } + return candidate; + } + + // ---- detection ---- + + /// Per-segment block-count bookkeeping: what the segment's own block table holds and, + /// when its registry entry was located, what the RSeSegInfo summary claims. + internal sealed class SegmentCounts + { + public string Name = ""; + public string StorageId = ""; // the mangled id shared by the B/M stream pair + public string Location = ""; // "" = the document's own tree, else the member-storage path + public long Actual; + public long? Summary; + public int PatchOffset = -1; + public string SegInfoPath = ""; + public bool Mismatch => Summary.HasValue && Summary.Value != Actual; + } + + internal static List Scan(CompoundFile cf) => ToIssues(ScanCounts(cf)); + + internal static List ToIssues(IEnumerable counts) + { + List issues = []; + foreach (SegmentCounts c in counts) + { + if (c.Mismatch) + { + issues.Add(new Issue + { + SegmentName = c.Name, + Location = c.Location, + SummaryCount = c.Summary!.Value, + ActualCount = c.Actual, + PatchOffset = c.PatchOffset, + SegInfoPath = c.SegInfoPath, + }); + } + } + return issues; + } + + /// The scope a segment tree belongs to, from the full path of its RSeStorage storage: + /// "" for the document's own tree, else the member-storage path (e.g. "MemberDocs/x2oe…"). + /// The single definition of the Location convention - values and + /// any UI lookup key must both come from here. + public static string LocationOf(string rseStoragePath) => + rseStoragePath.Equals("/RSeStorage", StringComparison.OrdinalIgnoreCase) + ? "" + : rseStoragePath.TrimStart('/').Replace("/RSeStorage", "", StringComparison.OrdinalIgnoreCase); + + internal static List ScanCounts(CompoundFile cf) + { + List counts = []; + + // A document holds one RSeStorage tree of its own, and model-state parts/assemblies embed + // a further complete tree per member under MemberDocs/. Every tree carries its own + // RSeSegInfo registry, and segment names repeat across trees - so each M stream must be + // checked against the registry of exactly its own tree. + foreach (CompoundFile.DirEntry segInfoEntry in cf.Directory) + { + if (segInfoEntry.Type != 2 || segInfoEntry.Name != "RSeSegInfo" || !IsRSeChild(segInfoEntry.Path)) + { + continue; + } + + byte[] segInfo; + try { segInfo = cf.ReadEntry(segInfoEntry); } catch { continue; } + string tree = ParentPath(segInfoEntry.Path); + string location = LocationOf(tree); + + foreach (CompoundFile.DirEntry e in cf.Directory) + { + // segment metadata streams are the M children of this tree's RSeStorage + if (e.Type != 2 || e.Name.Length < 2 || e.Name[0] != 'M' || + !ParentPath(e.Path).Equals(tree, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + try + { + MetaStream? meta = ParseMetaStream(cf.ReadEntry(e)); + if (meta == null) + { + continue; + } + + SegmentCounts c = new() + { + Name = meta.Name, + StorageId = e.Name[1..], + Location = location, + Actual = meta.BlockCount, + SegInfoPath = segInfoEntry.Path, + }; + if (FindSummary(segInfo, meta) is (int offset, long summary)) + { + c.Summary = summary; + c.PatchOffset = offset; + } + counts.Add(c); + } + catch { /* strict parsing: an unreadable segment yields no verdict, not a false alarm */ } + } + } + return counts; + } + + internal static string ParentPath(string path) + { + int i = path.LastIndexOf('/'); + return i > 0 ? path[..i] : ""; + } + + internal static bool IsRSeChild(string path) + { + int i = path.LastIndexOf('/'); + return i > 0 && path.AsSpan(0, i).EndsWith("/RSeStorage", StringComparison.OrdinalIgnoreCase); + } + + internal sealed class MetaStream + { + public string Name = ""; + public byte[] SegmentId = []; + public long BlockCount; + /// Total decompressed bytes of all blocks, per the block-size table (each u32 + /// carries a flag in the high bit; the low 31 bits are the block's byte size). The + /// segment's decompressed payload starts with exactly these bytes. + public long BlockBytes; + } + + /// Parse an M<id> metadata stream far enough to learn the segment's name, its id + /// and how many blocks its block-size table lists ("RSe Meta Stream Version N" header, then a + /// zlib- or zstd-compressed payload whose first table is the block index). Returns null when + /// any byte does not look exactly as expected. + internal static MetaStream? ParseMetaStream(byte[] m) + { + int i = 0; + if (ReadText8(m, ref i) is not string magic || !magic.StartsWith("RSe Meta Stream Version", StringComparison.Ordinal)) + { + return null; + } + + if (i + 2 + 16 > m.Length) + { + return null; + } + + int ver = BitConverter.ToUInt16(m, i); + i += 2 + 16; // version + 8 x u16 + if (ReadText16(m, ref i) is not string name || name.Length == 0 || i + 16 + 12 > m.Length) + { + return null; + } + + byte[] segId = m[i..(i + 16)]; + i += 16 + 12; // segment id + 3 x u32 + if (ver < 7) + { + i += 4; // val1 before the created date + } + + if (ReadText8(m, ref i) == null) + { + return null; + } + + if (ver < 7) + { + i += 4; // val2 before the modified date + } + + if (ReadText8(m, ref i) == null || i + 1 > m.Length) + { + return null; + } + + byte compression = m[i++]; // 1 = zlib, 2 = zstd + byte[] payload; + try + { + using Stream dec = compression switch + { + 1 => new ZLibStream(new MemoryStream(m, i, m.Length - i), CompressionMode.Decompress), + 2 => new ZstdSharp.DecompressionStream(new MemoryStream(m, i, m.Length - i)), + _ => throw new InvalidDataException($"Unknown compression flag {compression}."), + }; + // the block table sits right at the front; 18 header bytes + one u32 per block + using MemoryStream buf = new(); + dec.CopyTo(buf); + payload = buf.ToArray(); + } + catch + { + return null; + } + + if (payload.Length < 22) + { + return null; + } + + long count = BitConverter.ToUInt32(payload, 14); // after 7 x u16 + long trailerOff = 18 + count * 4; + if (trailerOff + 4 > payload.Length) + { + return null; + } + + // the table's own trailer restates its byte size - a strong check that this really is + // the block table of a format revision we understand + if (BitConverter.ToUInt32(payload, (int)trailerOff) != (count + 1) * 4) + { + return null; + } + + long blockBytes = 0; + for (int k = 0; k < count; k++) + { + blockBytes += BitConverter.ToUInt32(payload, 18 + k * 4) & 0x7FFFFFFF; + } + + return new MetaStream { Name = name, SegmentId = segId, BlockCount = count, BlockBytes = blockBytes }; + } + + /// Locate the segment's entry in RSeSegInfo (length-prefixed UTF-16 name, verified + /// by the segment GUID that follows it) and return the offset + value of its block-count + /// summary: entry + name + two GUIDs + value1 + count1 + arr1[0..2] -> arr1[3]. The stepped-over + /// fields are fingerprinted before the offset is trusted, so an unknown layout revision is + /// declined (no verdict) instead of being read - and later patched - at the wrong offset. + internal static (int Offset, long Value)? FindSummary(byte[] segInfo, MetaStream meta) + { + byte[] pattern = BuildNamePattern(meta.Name); + for (int at = Find(segInfo, pattern, 0); at >= 0; at = Find(segInfo, pattern, at + 1)) + { + int idOff = at + pattern.Length; + int summaryOff = idOff + 16 + 16 + 4 + 4 + 12; + if (summaryOff + 4 > segInfo.Length) + { + return null; + } + + if (!segInfo.AsSpan(idOff, 16).SequenceEqual(meta.SegmentId)) + { + continue; + } + + // Layout fingerprint (schema 0x1D-0x1F, observed stable from Inventor 11 through 2027): + // value1 is always 0, count1 is a tiny object count, arr1[0] is always 0. A revision + // that moves these fields fails the fingerprint and gets no verdict. + uint value1 = BitConverter.ToUInt32(segInfo, idOff + 32); + uint count1 = BitConverter.ToUInt32(segInfo, idOff + 36); + uint arr1_0 = BitConverter.ToUInt32(segInfo, idOff + 40); + if (value1 != 0 || count1 > 256 || arr1_0 != 0) + { + return null; + } + + return (summaryOff, BitConverter.ToUInt32(segInfo, summaryOff)); + } + return null; + } + + private static byte[] BuildNamePattern(string name) + { + byte[] pattern = new byte[4 + name.Length * 2]; + BitConverter.TryWriteBytes(pattern.AsSpan(0, 4), (uint)name.Length); + Encoding.Unicode.GetBytes(name, pattern.AsSpan(4)); + return pattern; + } + + private static int Find(byte[] haystack, byte[] needle, int from) => + from > haystack.Length ? -1 : haystack.AsSpan(from).IndexOf(needle) is int rel && rel >= 0 ? from + rel : -1; + + private static string? ReadText8(byte[] b, ref int i) + { + if (i + 4 > b.Length) + { + return null; + } + + int n = (int)BitConverter.ToUInt32(b, i); + if (n < 0 || n > 1024 || i + 4 + n > b.Length) + { + return null; + } + + string s = Encoding.Latin1.GetString(b, i + 4, n); + i += 4 + n; + return s; + } + + private static string? ReadText16(byte[] b, ref int i) + { + if (i + 4 > b.Length) + { + return null; + } + + int n = (int)BitConverter.ToUInt32(b, i); + if (n < 0 || n > 1024 || i + 4 + n * 2 > b.Length) + { + return null; + } + + string s = Encoding.Unicode.GetString(b, i + 4, n * 2); + i += 4 + n * 2; + return s; + } +} diff --git a/tests/InventorMeta.Tests/ContentCategoryTests.cs b/tests/InventorMeta.Tests/ContentCategoryTests.cs index e1dec60..14aa0be 100644 --- a/tests/InventorMeta.Tests/ContentCategoryTests.cs +++ b/tests/InventorMeta.Tests/ContentCategoryTests.cs @@ -1,6 +1,3 @@ -using System; -using System.Linq; - namespace ExtrabbitCode.Inventor.MetaReader.Tests; public class ContentCategoryTests diff --git a/tests/InventorMeta.Tests/DocumentSubsystemTests.cs b/tests/InventorMeta.Tests/DocumentSubsystemTests.cs index a836317..23a25c1 100644 --- a/tests/InventorMeta.Tests/DocumentSubsystemTests.cs +++ b/tests/InventorMeta.Tests/DocumentSubsystemTests.cs @@ -1,5 +1,3 @@ -using System.Linq; - namespace ExtrabbitCode.Inventor.MetaReader.Tests; public class DocumentSubsystemTests diff --git a/tests/InventorMeta.Tests/InventorMeta.Tests.csproj b/tests/InventorMeta.Tests/InventorMeta.Tests.csproj index 773b527..34d5bdb 100644 --- a/tests/InventorMeta.Tests/InventorMeta.Tests.csproj +++ b/tests/InventorMeta.Tests/InventorMeta.Tests.csproj @@ -37,8 +37,8 @@ referenced from a plain test project). --> - - + + diff --git a/tests/InventorMeta.Tests/SegmentDataCheckTests.cs b/tests/InventorMeta.Tests/SegmentDataCheckTests.cs new file mode 100644 index 0000000..f430722 --- /dev/null +++ b/tests/InventorMeta.Tests/SegmentDataCheckTests.cs @@ -0,0 +1,148 @@ +namespace ExtrabbitCode.Inventor.MetaReader.Tests; + +/// +/// The "Error loading segment … in database" damage: runs of zeroed sectors inside a segment's +/// compressed payload stream. Unlike the stale-summary class, the destroyed bytes are physically +/// gone - nothing can repair it, so detection must name it clearly and the repair path must +/// refuse to touch such files. Damage is manufactured at runtime by zeroing bytes inside a +/// healthy sample's payload stream, exactly the shape seen in the wild; no corrupt binary lives +/// in the repo. +/// +public class SegmentDataCheckTests : IDisposable +{ + private readonly string _dir = Directory.CreateTempSubdirectory("segdata-").FullName; + + public void Dispose() => Directory.Delete(_dir, true); + + private string TempCopy(string sample) + { + string path = Path.Combine(_dir, Path.GetFileName(sample)); + File.Copy(Samples.PathOf(sample), path); + return path; + } + + /// Zero bytes of a segment's payload (B) stream, starting + /// at - the zeroed-sector damage seen on real customer files. + /// Deliberately walks the streams itself instead of calling the library under test. + private static void ZeroPayloadBytes(string path, string segmentName, int offset, int length) + { + using CompoundFile cf = new(path); + foreach (CompoundFile.DirEntry m in cf.Directory) + { + if (m.Type != 2 || m.Name.Length < 2 || m.Name[0] != 'M' || + !m.Path.StartsWith("/RSeStorage/", StringComparison.Ordinal)) + { + continue; + } + + // the metadata stream names its segment as a length-prefixed UTF-16 string + byte[] meta = cf.ReadEntry(m); + byte[] pattern = [.. BitConverter.GetBytes((uint)segmentName.Length), .. System.Text.Encoding.Unicode.GetBytes(segmentName)]; + if (meta.AsSpan().IndexOf(pattern) < 0) + { + continue; + } + + CompoundFile.DirEntry b = cf.Directory.Single(e => e.Type == 2 && e.Path == "/RSeStorage/B" + m.Name[1..]); + byte[] data = cf.ReadEntry(b); + Assert.True(offset + length <= data.Length, $"sample's {segmentName} payload is too small for the test damage"); + Array.Clear(data, offset, length); + cf.OverwriteStreamInPlace(b, data); + cf.Save(path); + return; + } + Assert.Fail($"sample has no {segmentName} stream"); + } + + [Fact] + public void HealthySamplesReportNoDataDamage() + { + foreach (string sample in new[] { Samples.Part, Samples.Assembly, Samples.TubeAndPipe, Samples.Cylinder }) + { + InventorDocument doc = Samples.Load(sample); + Assert.False(doc.HasDestroyedSegmentData); + Assert.Empty(doc.DataDamage); + } + } + + [Fact] + public void ZeroedSectorInsideAPayloadIsDetected() + { + string path = TempCopy(Samples.Part); + ZeroPayloadBytes(path, "PmGraphicsSegment", offset: 1024, length: 512); + + InventorDocument doc = new(path); + Assert.True(doc.HasDestroyedSegmentData); + + SegmentDataCheck.Damage d = Assert.Single(doc.DataDamage); + Assert.Equal("PmGraphicsSegment", d.SegmentName); + Assert.Equal("", d.Location); + Assert.True(d.ExpectedBytes > 0); + Assert.True(d.RecoveredBytes < d.ExpectedBytes || d.ChecksumOnly); + Assert.True(d.LongestZeroRun >= 512); + } + + [Fact] + public void ZeroedStreamHeaderIsDetected() + { + // the first sector of the stream wiped - header, compression flag and all (seen in the + // wild: the whole payload is unreadable, not just a stretch of it) + string path = TempCopy(Samples.Part); + ZeroPayloadBytes(path, "PmDCSegment", offset: 0, length: 512); + + InventorDocument doc = new(path); + SegmentDataCheck.Damage d = Assert.Single(doc.DataDamage); + Assert.Equal("PmDCSegment", d.SegmentName); + Assert.Equal(0, d.RecoveredBytes); + } + + [Fact] + public void RepairRefusesADestroyedFileAndLeavesItUntouched() + { + string path = TempCopy(Samples.Part); + // both damage classes at once: a stale summary alone would be repairable, but the + // destroyed payload makes any repair pointless - it must be refused outright + ZeroPayloadBytes(path, "PmGraphicsSegment", offset: 1024, length: 512); + CorruptSummary(path, "PmBRepSegment", 2); + byte[] beforeRepair = File.ReadAllBytes(path); + + InvalidDataException ex = Assert.Throws(() => SegmentRepair.Repair(path)); + Assert.Contains("PmGraphicsSegment", ex.Message); + Assert.Contains("backup", ex.Message); + + Assert.Equal(beforeRepair, File.ReadAllBytes(path)); // nothing was patched + Assert.Empty(Directory.GetFiles(_dir, "*.bak")); // and no backup left behind + } + + [Fact] + public void StaleSummaryAloneIsStillRepairable() + { + // the guard must not get in the way of the class that IS fixable + string path = TempCopy(Samples.Part); + CorruptSummary(path, "PmGraphicsSegment", 3); + + SegmentRepair.RepairResult result = SegmentRepair.Repair(path); + Assert.Single(result.Repaired); + Assert.Empty(SegmentRepair.FindIssues(path)); + } + + /// Same summary-bump helper as SegmentRepairTests - the entry math is deliberately + /// re-implemented rather than borrowed from the library under test. + private static void CorruptSummary(string path, string segmentName, uint delta) + { + using CompoundFile cf = new(path); + CompoundFile.DirEntry entry = cf.Directory.Single(e => e.Type == 2 && e.Path == "/RSeStorage/RSeSegInfo"); + byte[] segInfo = cf.ReadEntry(entry); + + byte[] pattern = [.. BitConverter.GetBytes((uint)segmentName.Length), .. System.Text.Encoding.Unicode.GetBytes(segmentName)]; + int at = segInfo.AsSpan().IndexOf(pattern); + Assert.True(at >= 0, $"sample has no {segmentName} entry"); + + int summaryOff = at + pattern.Length + 32 + 8 + 12; // name, two GUIDs, value1+count1, arr1[0..2] + uint value = BitConverter.ToUInt32(segInfo, summaryOff); + BitConverter.GetBytes(value + delta).CopyTo(segInfo, summaryOff); + + cf.OverwriteStreamInPlace(entry, segInfo); + cf.Save(path); + } +} diff --git a/tests/InventorMeta.Tests/SegmentInventoryTests.cs b/tests/InventorMeta.Tests/SegmentInventoryTests.cs new file mode 100644 index 0000000..4235157 --- /dev/null +++ b/tests/InventorMeta.Tests/SegmentInventoryTests.cs @@ -0,0 +1,27 @@ +namespace ExtrabbitCode.Inventor.MetaReader.Tests; + +public class SegmentInventoryTests +{ + [Fact] + public void ListsRSeStorageSegmentsByNameAndSize() + { + InventorDocument doc = Samples.Load(Samples.Part); // SamplePart.ipt + + Assert.NotEmpty(doc.Segments); + // Every part carries geometry and a (regenerable) graphics cache. + Assert.Contains(doc.Segments, s => s.Name == "PmBRepSegment" && s.DataSize > 0); + Assert.Contains(doc.Segments, s => s.IsGraphicsCache); + + // Reported largest-first, and each has both a data and a metadata stream. + Assert.True(doc.Segments.Zip(doc.Segments.Skip(1)).All(p => p.First.DataSize >= p.Second.DataSize)); + Assert.All(doc.Segments, s => Assert.True(s.DataSize > 0 && s.MetaSize > 0)); + } + + [Fact] + public void GraphicsCacheIsIdentified() + { + InventorDocument doc = Samples.Load(Samples.Part); + InventorDocument.Segment gfx = doc.Segments.Single(s => s.IsGraphicsCache); + Assert.Equal("PmGraphicsSegment", gfx.Name); + } +} diff --git a/tests/InventorMeta.Tests/SegmentRepairTests.cs b/tests/InventorMeta.Tests/SegmentRepairTests.cs new file mode 100644 index 0000000..ebc9d9e --- /dev/null +++ b/tests/InventorMeta.Tests/SegmentRepairTests.cs @@ -0,0 +1,161 @@ +namespace ExtrabbitCode.Inventor.MetaReader.Tests; + +/// +/// The "number of objects found in the segment does not match the segment summary" damage: +/// detection compares each segment's RSeSegInfo block-count summary against its metadata block +/// table; repair patches the summary in place after backing the file up. Damage is manufactured +/// at runtime by bumping a healthy sample's summary the same way the files in the wild are off, +/// so no corrupt binary needs to live in the repo. +/// +public class SegmentRepairTests : IDisposable +{ + private readonly string _dir = Directory.CreateTempSubdirectory("segrepair-").FullName; + + public void Dispose() => Directory.Delete(_dir, true); + + private string TempCopy(string sample) + { + string path = Path.Combine(_dir, Path.GetFileName(sample)); + File.Copy(Samples.PathOf(sample), path); + return path; + } + + /// Bump a segment's block-count summary in the document's own RSeSegInfo - the exact + /// shape of the damage Inventor refuses to load. Deliberately re-implements the entry math + /// instead of calling the library under test. + private static void CorruptSummary(string path, string segmentName, uint delta) + { + using CompoundFile cf = new(path); + CompoundFile.DirEntry entry = cf.Directory.Single(e => e.Type == 2 && e.Path == "/RSeStorage/RSeSegInfo"); + byte[] segInfo = cf.ReadEntry(entry); + + byte[] pattern = [.. BitConverter.GetBytes((uint)segmentName.Length), .. System.Text.Encoding.Unicode.GetBytes(segmentName)]; + int at = segInfo.AsSpan().IndexOf(pattern); + Assert.True(at >= 0, $"sample has no {segmentName} entry"); + + int summaryOff = at + pattern.Length + 32 + 8 + 12; // name, two GUIDs, value1+count1, arr1[0..2] + uint value = BitConverter.ToUInt32(segInfo, summaryOff); + BitConverter.GetBytes(value + delta).CopyTo(segInfo, summaryOff); + + cf.OverwriteStreamInPlace(entry, segInfo); + cf.Save(path); + } + + private static void CorruptGraphicsSummary(string path) => CorruptSummary(path, "PmGraphicsSegment", 3); + + [Fact] + public void HealthySamplesReportNoDamage() + { + foreach (string sample in new[] { Samples.Part, Samples.Assembly, Samples.TubeAndPipe }) + { + InventorDocument doc = Samples.Load(sample); + Assert.False(doc.HasRepairableSegmentDamage); + Assert.Empty(doc.SegmentIssues); + Assert.All(doc.Segments, s => Assert.False(s.HasCountMismatch)); + } + } + + [Fact] + public void BlockCountsAreReadForEverySegment() + { + InventorDocument doc = Samples.Load(Samples.Part); + Assert.NotEmpty(doc.Segments); + Assert.All(doc.Segments, s => + { + Assert.NotNull(s.ActualBlockCount); // the strict M-stream parse understood the format + Assert.NotNull(s.SummaryBlockCount); // and the registry entry was located + Assert.Equal(s.SummaryBlockCount, s.ActualBlockCount); + }); + Assert.True(doc.Segments.Single(s => s.IsGraphicsCache).ActualBlockCount > 0); + } + + [Fact] + public void StaleSummaryIsDetected() + { + string path = TempCopy(Samples.Part); + CorruptGraphicsSummary(path); + + InventorDocument doc = new(path); + Assert.True(doc.HasRepairableSegmentDamage); + + SegmentRepair.Issue issue = Assert.Single(doc.SegmentIssues); + Assert.Equal("PmGraphicsSegment", issue.SegmentName); + Assert.Equal("", issue.Location); + Assert.Equal(issue.ActualCount + 3, issue.SummaryCount); + + InventorDocument.Segment gfx = doc.Segments.Single(s => s.IsGraphicsCache); + Assert.True(gfx.HasCountMismatch); + Assert.Equal(gfx.ActualBlockCount + 3, gfx.SummaryBlockCount); + } + + [Fact] + public void RepairRestoresTheOriginalBytesAndBacksUp() + { + string path = TempCopy(Samples.Part); + byte[] pristine = File.ReadAllBytes(path); + CorruptGraphicsSummary(path); + byte[] corrupted = File.ReadAllBytes(path); + + SegmentRepair.RepairResult result = SegmentRepair.Repair(path); + + // the backup is the untouched (still corrupt) input ... + Assert.NotNull(result.BackupPath); + Assert.Equal(path + ".pre-repair.bak", result.BackupPath); + Assert.Equal(corrupted, File.ReadAllBytes(result.BackupPath!)); + + // ... and the repair puts the summary back to the actual count, i.e. the pristine bytes + Assert.Equal("PmGraphicsSegment", Assert.Single(result.Repaired).SegmentName); + Assert.Equal(pristine, File.ReadAllBytes(path)); + Assert.Empty(SegmentRepair.FindIssues(path)); + } + + /// The signature seen on every damaged customer file so far: PmGraphics, PmDC and + /// PmBRep summaries all stale at once, off by a few counts each. Reproduced here on the free + /// sample (real files can't be committed), detected as three issues and repaired in one go. + [Fact] + public void RealWorldMultiSegmentDamageIsRepairedInOneGo() + { + string path = TempCopy(Samples.Part); + byte[] pristine = File.ReadAllBytes(path); + CorruptSummary(path, "PmGraphicsSegment", 3); + CorruptSummary(path, "PmDCSegment", 4); + CorruptSummary(path, "PmBRepSegment", 4); + + InventorDocument doc = new(path); + Assert.Equal(["PmBRepSegment", "PmDCSegment", "PmGraphicsSegment"], + doc.SegmentIssues.Select(i => i.SegmentName).Order().ToArray()); + + SegmentRepair.RepairResult result = SegmentRepair.Repair(path); + Assert.Equal(3, result.Repaired.Count); + Assert.Equal(pristine, File.ReadAllBytes(path)); + Assert.Empty(SegmentRepair.FindIssues(path)); + } + + [Fact] + public void RepairBackupsNeverOverwriteEachOther() + { + string path = TempCopy(Samples.Part); + CorruptGraphicsSummary(path); + string first = SegmentRepair.Repair(path).BackupPath!; + CorruptGraphicsSummary(path); + string second = SegmentRepair.Repair(path).BackupPath!; + + Assert.NotEqual(first, second); + Assert.True(File.Exists(first)); + Assert.True(File.Exists(second)); + } + + [Fact] + public void HealthyFileIsLeftUntouched() + { + string path = TempCopy(Samples.Part); + byte[] pristine = File.ReadAllBytes(path); + + SegmentRepair.RepairResult result = SegmentRepair.Repair(path); + + Assert.Null(result.BackupPath); + Assert.Empty(result.Repaired); + Assert.Equal(pristine, File.ReadAllBytes(path)); + Assert.Empty(Directory.GetFiles(_dir, "*.bak")); + } +}