You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Embed CanvasNet formats in SVG <image href> through a new Viewer package and pluggable image sources - #110
SVG diagrams can now embed other CanvasNet formats through <image href>: a rendered OpenSCAD model, a Vega-Lite chart, a nested SVG, a raster picture, or the first page of a PDF, PPTX or VSDX file. Each linked file is rendered at the size it is placed at, so vector sources stay sharp.
The cross-format logic lives in the libraries, not the tool, so in-process users get the same behavior:
Core (DemaConsulting.CanvasNet.ImageSources):
The contracts IImageResolver and IImageSource. A source claims links by file extension or by URI scheme.
ImageSourceRequest and ImageSourceResult, and an immutable ImageSourceSet in which a later source wins.
FolderImageResolver, which does all the shared work:
it accepts relative paths and file: URIs, with the query and fragment stripped first;
it uses the existing file sandbox, and refuses absolute, drive, UNC, .., %00, ::$DATA and symlink escapes;
http and https stay unresolved unless a caller registers a source for them;
it limits depth to 4 and embeds to 64, and detects cycles;
it enforces a decoded-pixel budget (64 MP by default, nested embeds share it, each side clamped to 8192), charged before allocation;
it collects diagnostics and echo output.
RasterImageSource, which reads the picture size from the header before decoding.
Providers in each format package: SvgImageSource, ScadImageSource, VegaLiteImageSource, and Pdf/Pptx/VsdxImageSource for the first page or slide.
SVG:SvgLoadOptions.ImageResolver. It is null by default, which keeps today's behavior: only data: links are drawn.
New package DemaConsulting.CanvasNet.Viewer, the entry point for every CanvasNet format. It offers:
CanvasNetViewer.ImageSources and Extensions;
CreateImageResolver(folder[, extraSources]), where caller sources win, so users can add their own sources (a live camera via a camera:// scheme, for example) or override a built-in one;
Render(path | stream), which returns a ViewerImage, with a MaxDecodedPixels option.
Future formats, such as Mermaid, get registered here.
Tool: it uses Viewer for SVG inputs, rooted at the input file's folder.
The new warnings are svg-image-unresolved and svg-image-too-large. --strict turns them into unsupported-feature errors.
Embedded diagnostics are reported with their origin.
The svg help topic lists the file types that can be linked, with an --example embed. A drift test ties that list to CanvasNetViewer.Extensions. The scad, vega-lite, formats and render help point to it.
Example: an SVG diagram embedding a PNG logo, a .scad bushing (transparent) and a .vl.json chart, rendered at 2×:
Type of Change
Bug fix (non-breaking change which fixes an issue)
New feature (non-breaking change which adds functionality)
Breaking change (fix or feature that would cause existing functionality to not work as expected)
Documentation update
Code quality improvement
Related Issues
User request: put 3D OpenSCAD renders and other CanvasNet outputs into 2D SVG diagrams, and make that composition available to library users, extensible with their own sources.
Pre-Submission Checklist
Before submitting this pull request, ensure you have completed the following:
Build and Test
Code builds successfully and all tests pass: pwsh ./build.ps1 ran 47,979 tests with 0 failed and 33 skipped (symlink tests that need a privilege this host lacks, plus tests that were already skipped). After the final Viewer option: Viewer.Tests 69 passed, 3 skipped.
Code produces zero warnings
Code Quality
New code has appropriate XML documentation comments
Static analyzer warnings have been addressed
Quality Checks
Please run the following checks before submitting:
All linters pass: pwsh ./lint.ps1 passed, along with the Pandoc harness and render-images.ps1 -Check
Testing
Added unit tests for new functionality:
the sandbox, query and fragment handling, and %23
the scheme and extension precedence, a custom made-up extension and an override of a built-in
live frames
depth, count and cycle limits
the pixel budget: a header-only 8192×8192 PNG is refused without decoding, the budget accumulates across embeds, and every provider checks it before allocating
the tool's --strict behavior
the help drift test
Updated existing tests if behavior changed (no existing golden changed)
All tests follow the AAA (Arrange, Act, Assert) pattern
Test coverage is maintained or improved
Documentation
Updated README.md (if applicable)
Updated docs/ documentation (if applicable)
Added code examples for new features (if applicable)
Updated requirements.yaml (if applicable)
Additional Notes
Dispatch is by file name, so a plain .json file with a Vega-Lite $schema cannot be embedded; use .vl.json.
Follow-ups:
Move the tool's whole render pipeline onto Viewer.
Let an embedded diagnostic carry the name of the file that embedded it.
Backlog, pre-existing: a check/open symlink race in SandboxedFileResolver, which Scad include and Vega-Lite data.url already use.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Active moderate and critical findings remain around inconsistent dimension handling and incomplete MaxDecodedPixels accounting, including a path that can permit oversized allocations before refusal.
This pull request adds cross-format image embedding for SVG documents and introduces the DemaConsulting.CanvasNet.Viewer package as a unified, extensible rendering entry point.
Add an explicit, opt-in image resolver to the SVG codec and a shared core
image-source contract (IImageSource, FolderImageResolver, ImageSourceSet,
RasterImageSource) with sandboxed file hrefs, query/fragment handling,
URI-scheme claiming and a per-render decoded-pixel budget. Format packages
ship thin providers (Svg, Scad, VegaLite, Pdf, Pptx, Vsdx) and the new
DemaConsulting.CanvasNet.Viewer package composes them. The canvasnet tool
wires the Viewer for SVG inputs, sandboxed to the input folder, with the
svg-image-unresolved and svg-image-too-large warnings; help topics, user
guides and compliance artifacts updated.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
After #109 the Scad library picks the view (isometric for 3D, top-down for flat 2D, the model's own $vp* variables), so ScadImageSource no longer forces an isometric camera.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Approval is blocked by two moderate findings exposing mutable extension metadata through read-only interfaces, plus a malformed control character in the new documentation.
Built-in sources, ImageSourceSet, FolderImageResolver and ViewerImage no longer
hand out arrays or lists that callers can cast and mutate. Remove a stray
control character from the Scad design doc.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Active critical issues leave the documented pixel and image-count limits unenforced before allocations, with an additional result immutability issue still requiring correction.
No open issues 🎉
4 previously missed issues
In code that hasn't changed since last review
Enforce image-count limits before reading embedded files
_sandbox.Resolve reads and caches the embedded file before CheckLimits runs below. In a stream-backed top-level render the top-level bytes never go through this sandbox, but the constructor still reserves MaxImages + 1 sandbox files for that top-level case; consequently MaxImages = 0 still reads one embedded file (and MaxImages = 1 can read a second) before rejecting it. This violates the documented image/file-count bound and permits unnecessary reads of up to the sandbox file limit. Check the count limit before opening when possible, and distinguish path renders (which consume the extra top-level file slot) from stream renders; add a regression test for MaxImages = 0 with a large embedded file.
Reserve the parent surface before rendering nested images
For a natural-size direct render, PrepareDirect sets reserved to zero, so RenderDirect calls the source before charging the top-level surface. SvgImageSource allocates its output surface before resolving nested <image> elements; those nested images can therefore consume the whole budget, and the resolver only discovers the overage after both the nested surfaces and the parent surface have been allocated (then disposes/throws). This violates the documented pre-allocation pixel cap for CanvasNetViewer.Render(path) without Width/Height. Reserve the natural output before nested rendering (or introduce a two-phase size/reservation contract) so the parent and nested allocations share the live budget.
Check live budget before approving source allocations
RemainingPixels is captured when the request is built, but a source can call request.Resolver.Resolve(...) before it allocates its own surface. Those nested calls consume the resolver's live budget without changing this request's snapshot, so a subsequent EnsureWithinBudget can approve an allocation that is already too large (for example, after a 6,000-pixel nested image, a request with 10,000 reserved and 10,000 remaining can still approve an 18,000-pixel surface). The resolver only notices after the source has allocated and returned it, then disposes it, so the documented before-allocation cap is not enforced for pluggable sources. Make the budget check consult live remaining capacity or provide a reservation/lease for allocations made after nested resolution.
Snapshot caller-owned lists to preserve result immutability
IReadOnlyList<T> does not make the referenced collection immutable. A custom source can assign a mutable List<ImageSourceDiagnostic> (or List<string> to Echo) and mutate it after publishing the result, contradicting this record's documented immutability/thread-sharing guarantee. Copy and wrap these lists when the result is initialized, or otherwise expose immutable snapshots rather than storing caller-owned references.
Sources charge the live budget when they allocate; the resolver charges only
the excess of a returned surface and refunds failed requests. Check the depth
and image-count limits before reading an embedded file, and make
ImageSourceResult lists immutable snapshots.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Review follow-up (632bdf8) for the four "previously missed" items — the pixel budget was redesigned rather than patched:
Live budget (ImageSourceRequest / FolderImageResolver): each resolver owns one live ImageBudget shared by every request, nested ones included. A source calls request.EnsureWithinBudget(w, h) right before each allocation; that charges the live budget at that moment or throws ImageSourceBudgetException (charging nothing). RemainingPixels reads live. After the source returns, the resolver charges only the excess of the returned surface over what the source already charged, refusing and disposing it if that does not fit; a refused or failed request is refunded. There is no snapshot and no up-front reservation any more (ReservedPixels is removed). Regression tests: 6,000-pixel nested + 18,000-pixel parent is refused before the parent allocation; a natural-size direct SVG render whose nested picture exceeds the live remainder is refused before the nested allocation; a non-charging source returning an oversized surface is refused.
Image-count limit before reading: depth and image-count checks now run before the sandbox opens an embedded file (only the cycle check follows the read); the sandbox file limit distinguishes path renders (MaxImages + 1) from stream renders (MaxImages). Test: MaxImages = 0 never reads the embedded file.
ImageSourceResult immutability:Diagnostics and Echo are copied into read-only snapshots on init.
Full build.ps1: 48,645 tests, 0 failed, 0 warnings.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Active correctness and safety issues remain, including undisposed surfaces on resolver failures and an empty-root path that unintentionally broadens the resolver sandbox.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because the change contains critical hidden findings involving an unhandled PDF-rendering resource leak and inconsistent folder sandbox validation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Pull Request
Description
SVG diagrams can now embed other CanvasNet formats through
<image href>: a rendered OpenSCAD model, a Vega-Lite chart, a nested SVG, a raster picture, or the first page of a PDF, PPTX or VSDX file. Each linked file is rendered at the size it is placed at, so vector sources stay sharp.The cross-format logic lives in the libraries, not the tool, so in-process users get the same behavior:
Core (
DemaConsulting.CanvasNet.ImageSources):IImageResolverandIImageSource. A source claims links by file extension or by URI scheme.ImageSourceRequestandImageSourceResult, and an immutableImageSourceSetin which a later source wins.FolderImageResolver, which does all the shared work:file:URIs, with the query and fragment stripped first;..,%00,::$DATAand symlink escapes;RasterImageSource, which reads the picture size from the header before decoding.Providers in each format package:
SvgImageSource,ScadImageSource,VegaLiteImageSource, andPdf/Pptx/VsdxImageSourcefor the first page or slide.SVG:
SvgLoadOptions.ImageResolver. It is null by default, which keeps today's behavior: onlydata:links are drawn.New package
DemaConsulting.CanvasNet.Viewer, the entry point for every CanvasNet format. It offers:CanvasNetViewer.ImageSourcesandExtensions;CreateImageResolver(folder[, extraSources]), where caller sources win, so users can add their own sources (a live camera via acamera://scheme, for example) or override a built-in one;Render(path | stream), which returns aViewerImage, with aMaxDecodedPixelsoption.Future formats, such as Mermaid, get registered here.
Tool: it uses Viewer for SVG inputs, rooted at the input file's folder.
svg-image-unresolvedandsvg-image-too-large.--strictturns them intounsupported-featureerrors.svghelp topic lists the file types that can be linked, with an--example embed. A drift test ties that list toCanvasNetViewer.Extensions. Thescad,vega-lite,formatsandrenderhelp point to it.Example: an SVG diagram embedding a PNG logo, a
.scadbushing (transparent) and a.vl.jsonchart, rendered at 2×:Type of Change
Related Issues
User request: put 3D OpenSCAD renders and other CanvasNet outputs into 2D SVG diagrams, and make that composition available to library users, extensible with their own sources.
Pre-Submission Checklist
Before submitting this pull request, ensure you have completed the following:
Build and Test
pwsh ./build.ps1ran 47,979 tests with 0 failed and 33 skipped (symlink tests that need a privilege this host lacks, plus tests that were already skipped). After the final Viewer option: Viewer.Tests 69 passed, 3 skipped.Code Quality
Quality Checks
Please run the following checks before submitting:
pwsh ./lint.ps1passed, along with the Pandoc harness andrender-images.ps1 -CheckTesting
%23--strictbehaviorDocumentation
Additional Notes
.jsonfile with a Vega-Lite$schemacannot be embedded; use.vl.json.SandboxedFileResolver, which Scad include and Vega-Litedata.urlalready use.