@jax-data-science/sci-image-visualizer 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +404 -0
- package/esm2022/index.mjs +52 -0
- package/esm2022/jax-data-science-sci-image-visualizer.mjs +5 -0
- package/esm2022/lib/channel-histogram/channel-histogram.component.mjs +398 -0
- package/esm2022/lib/contracts/capabilities.contract.mjs +32 -0
- package/esm2022/lib/contracts/cell-segmenter.contract.mjs +12 -0
- package/esm2022/lib/contracts/channel-histogram-api.contract.mjs +14 -0
- package/esm2022/lib/contracts/colormap-lut.mjs +95 -0
- package/esm2022/lib/contracts/coordinate-transform.contract.mjs +2 -0
- package/esm2022/lib/contracts/display-types.mjs +8 -0
- package/esm2022/lib/contracts/image.contract.mjs +11 -0
- package/esm2022/lib/contracts/intensity.mjs +28 -0
- package/esm2022/lib/contracts/plot-type.mjs +112 -0
- package/esm2022/lib/contracts/ports/image-state.port.mjs +3 -0
- package/esm2022/lib/contracts/ports/preferences.port.mjs +3 -0
- package/esm2022/lib/contracts/ports/region-io.port.mjs +3 -0
- package/esm2022/lib/contracts/ports/tile-access.port.mjs +3 -0
- package/esm2022/lib/contracts/region-editor-api.contract.mjs +4 -0
- package/esm2022/lib/contracts/region-overlay.contract.mjs +2 -0
- package/esm2022/lib/contracts/region-store.contract.mjs +2 -0
- package/esm2022/lib/contracts/sam.contract.mjs +12 -0
- package/esm2022/lib/contracts/toolbar-config.mjs +8 -0
- package/esm2022/lib/contracts/visualizer.contract.mjs +10 -0
- package/esm2022/lib/contracts/viz-config.mjs +3 -0
- package/esm2022/lib/hex-color-picker/hex-color-picker.component.mjs +260 -0
- package/esm2022/lib/implementations/base-store-visualizer.mjs +76 -0
- package/esm2022/lib/implementations/napari-js/napari-axes-labels.mjs +106 -0
- package/esm2022/lib/implementations/napari-js/napari-region-overlay.mjs +847 -0
- package/esm2022/lib/implementations/napari-js/napari-scale-bar.mjs +92 -0
- package/esm2022/lib/implementations/napari-js/napari-visualizer.service.mjs +2283 -0
- package/esm2022/lib/implementations/napari-js/napari-volume-z-handle.mjs +126 -0
- package/esm2022/lib/implementations/osd/display-pipeline.mjs +143 -0
- package/esm2022/lib/implementations/osd/histogram-sampler.mjs +217 -0
- package/esm2022/lib/implementations/osd/openseadragon-visualizer.service.mjs +1780 -0
- package/esm2022/lib/implementations/osd/osd-coordinate-transform.mjs +25 -0
- package/esm2022/lib/implementations/osd/osd-coords.mjs +53 -0
- package/esm2022/lib/implementations/osd/osd-lib.mjs +20 -0
- package/esm2022/lib/implementations/osd/osd-region-overlay.mjs +1237 -0
- package/esm2022/lib/implementations/osd/osd-scale-bar.mjs +88 -0
- package/esm2022/lib/implementations/osd/slice-cache.mjs +488 -0
- package/esm2022/lib/implementations/osd/tile-client.mjs +29 -0
- package/esm2022/lib/implementations/plotly/plotly-coordinate-transform.mjs +37 -0
- package/esm2022/lib/implementations/plotly/plotly-region-overlay.mjs +31 -0
- package/esm2022/lib/implementations/plotly/plotly-trace-builders.mjs +183 -0
- package/esm2022/lib/implementations/plotly/plotly.service.mjs +2137 -0
- package/esm2022/lib/implementations/simple-slice-access.service.mjs +99 -0
- package/esm2022/lib/models/bezier.mjs +120 -0
- package/esm2022/lib/models/class-preset.mjs +46 -0
- package/esm2022/lib/models/geometry.mjs +198 -0
- package/esm2022/lib/models/region.mjs +166 -0
- package/esm2022/lib/models/shape.mjs +53 -0
- package/esm2022/lib/plot.utilities.mjs +693 -0
- package/esm2022/lib/processing/image-converter.service.mjs +90 -0
- package/esm2022/lib/processing/image-crop.mjs +62 -0
- package/esm2022/lib/processing/processing-image.mjs +50 -0
- package/esm2022/lib/provide-visualization.mjs +63 -0
- package/esm2022/lib/region-editor/mask-raster.mjs +95 -0
- package/esm2022/lib/region-editor/mask-worker.mjs +10 -0
- package/esm2022/lib/region-editor/region-editor.component.mjs +1190 -0
- package/esm2022/lib/region-ops.service.mjs +301 -0
- package/esm2022/lib/render-orchestrator.mjs +87 -0
- package/esm2022/lib/routing-visualizer.service.mjs +533 -0
- package/esm2022/lib/store/class-color.util.mjs +52 -0
- package/esm2022/lib/store/region-store.service.mjs +1029 -0
- package/esm2022/lib/store/visualizer-store.service.mjs +352 -0
- package/esm2022/lib/toolbar/brush/brush-tool.service.mjs +546 -0
- package/esm2022/lib/toolbar/crop/slide-crop.mjs +57 -0
- package/esm2022/lib/toolbar/segmentation/cell-segment-tool.service.mjs +115 -0
- package/esm2022/lib/toolbar/segmentation/cellpose-segmenter.service.mjs +84 -0
- package/esm2022/lib/toolbar/segmentation/onnx-sam-session.mjs +133 -0
- package/esm2022/lib/toolbar/segmentation/ort-runtime-config.mjs +31 -0
- package/esm2022/lib/toolbar/segmentation/sam-model-registry.mjs +108 -0
- package/esm2022/lib/toolbar/segmentation/sam-onnx-core.mjs +159 -0
- package/esm2022/lib/toolbar/segmentation/sam-point-tool.service.mjs +255 -0
- package/esm2022/lib/toolbar/segmentation/sam-prompt.mjs +94 -0
- package/esm2022/lib/toolbar/segmentation/sam-tool.service.mjs +188 -0
- package/esm2022/lib/toolbar/toolbar.component.mjs +311 -0
- package/esm2022/lib/toolbar/vertex-eraser/vertex-eraser-tool.service.mjs +234 -0
- package/esm2022/lib/toolbar/wand/wand-tool.service.mjs +499 -0
- package/esm2022/lib/toolbar/wand/wand.service.mjs +921 -0
- package/esm2022/lib/toolbar/zoom-to-box/zoom-to-box-tool.service.mjs +157 -0
- package/esm2022/lib/visualization.module.mjs +162 -0
- package/esm2022/lib/visualizer.component.mjs +1597 -0
- package/fesm2022/jax-data-science-sci-image-visualizer-mask-worker-uhepXUhM.mjs +12 -0
- package/fesm2022/jax-data-science-sci-image-visualizer-mask-worker-uhepXUhM.mjs.map +1 -0
- package/fesm2022/jax-data-science-sci-image-visualizer-onnx-sam-session-ci1q0xnJ.mjs +327 -0
- package/fesm2022/jax-data-science-sci-image-visualizer-onnx-sam-session-ci1q0xnJ.mjs.map +1 -0
- package/fesm2022/jax-data-science-sci-image-visualizer.mjs +21314 -0
- package/fesm2022/jax-data-science-sci-image-visualizer.mjs.map +1 -0
- package/fesm2022/mask.worker.js +989 -0
- package/fesm2022/onnx-sam.worker.js +202 -0
- package/index.d.ts +39 -0
- package/lib/channel-histogram/channel-histogram.component.d.ts +112 -0
- package/lib/contracts/capabilities.contract.d.ts +30 -0
- package/lib/contracts/cell-segmenter.contract.d.ts +40 -0
- package/lib/contracts/channel-histogram-api.contract.d.ts +98 -0
- package/lib/contracts/colormap-lut.d.ts +21 -0
- package/lib/contracts/coordinate-transform.contract.d.ts +43 -0
- package/lib/contracts/display-types.d.ts +41 -0
- package/lib/contracts/image.contract.d.ts +72 -0
- package/lib/contracts/intensity.d.ts +18 -0
- package/lib/contracts/plot-type.d.ts +108 -0
- package/lib/contracts/ports/image-state.port.d.ts +29 -0
- package/lib/contracts/ports/preferences.port.d.ts +19 -0
- package/lib/contracts/ports/region-io.port.d.ts +29 -0
- package/lib/contracts/ports/tile-access.port.d.ts +27 -0
- package/lib/contracts/region-editor-api.contract.d.ts +83 -0
- package/lib/contracts/region-overlay.contract.d.ts +47 -0
- package/lib/contracts/region-store.contract.d.ts +74 -0
- package/lib/contracts/sam.contract.d.ts +98 -0
- package/lib/contracts/toolbar-config.d.ts +24 -0
- package/lib/contracts/visualizer.contract.d.ts +346 -0
- package/lib/contracts/viz-config.d.ts +25 -0
- package/lib/hex-color-picker/hex-color-picker.component.d.ts +47 -0
- package/lib/implementations/base-store-visualizer.d.ts +71 -0
- package/lib/implementations/napari-js/napari-axes-labels.d.ts +47 -0
- package/lib/implementations/napari-js/napari-region-overlay.d.ts +115 -0
- package/lib/implementations/napari-js/napari-scale-bar.d.ts +31 -0
- package/lib/implementations/napari-js/napari-visualizer.service.d.ts +455 -0
- package/lib/implementations/napari-js/napari-volume-z-handle.d.ts +46 -0
- package/lib/implementations/osd/display-pipeline.d.ts +47 -0
- package/lib/implementations/osd/histogram-sampler.d.ts +85 -0
- package/lib/implementations/osd/openseadragon-visualizer.service.d.ts +476 -0
- package/lib/implementations/osd/osd-coordinate-transform.d.ts +17 -0
- package/lib/implementations/osd/osd-coords.d.ts +16 -0
- package/lib/implementations/osd/osd-lib.d.ts +19 -0
- package/lib/implementations/osd/osd-region-overlay.d.ts +191 -0
- package/lib/implementations/osd/osd-scale-bar.d.ts +17 -0
- package/lib/implementations/osd/slice-cache.d.ts +161 -0
- package/lib/implementations/osd/tile-client.d.ts +32 -0
- package/lib/implementations/plotly/plotly-coordinate-transform.d.ts +19 -0
- package/lib/implementations/plotly/plotly-region-overlay.d.ts +23 -0
- package/lib/implementations/plotly/plotly-trace-builders.d.ts +60 -0
- package/lib/implementations/plotly/plotly.service.d.ts +594 -0
- package/lib/implementations/simple-slice-access.service.d.ts +64 -0
- package/lib/models/bezier.d.ts +59 -0
- package/lib/models/class-preset.d.ts +39 -0
- package/lib/models/geometry.d.ts +66 -0
- package/lib/models/region.d.ts +132 -0
- package/lib/models/shape.d.ts +44 -0
- package/lib/plot.utilities.d.ts +107 -0
- package/lib/processing/image-converter.service.d.ts +28 -0
- package/lib/processing/image-crop.d.ts +18 -0
- package/lib/processing/processing-image.d.ts +17 -0
- package/lib/provide-visualization.d.ts +34 -0
- package/lib/region-editor/mask-raster.d.ts +61 -0
- package/lib/region-editor/mask-worker.d.ts +7 -0
- package/lib/region-editor/region-editor.component.d.ts +305 -0
- package/lib/region-ops.service.d.ts +92 -0
- package/lib/render-orchestrator.d.ts +59 -0
- package/lib/routing-visualizer.service.d.ts +227 -0
- package/lib/store/class-color.util.d.ts +26 -0
- package/lib/store/region-store.service.d.ts +315 -0
- package/lib/store/visualizer-store.service.d.ts +123 -0
- package/lib/toolbar/brush/brush-tool.service.d.ts +143 -0
- package/lib/toolbar/crop/slide-crop.d.ts +30 -0
- package/lib/toolbar/segmentation/cell-segment-tool.service.d.ts +32 -0
- package/lib/toolbar/segmentation/cellpose-segmenter.service.d.ts +39 -0
- package/lib/toolbar/segmentation/onnx-sam-session.d.ts +25 -0
- package/lib/toolbar/segmentation/ort-runtime-config.d.ts +4 -0
- package/lib/toolbar/segmentation/sam-model-registry.d.ts +36 -0
- package/lib/toolbar/segmentation/sam-onnx-core.d.ts +48 -0
- package/lib/toolbar/segmentation/sam-point-tool.service.d.ts +59 -0
- package/lib/toolbar/segmentation/sam-prompt.d.ts +34 -0
- package/lib/toolbar/segmentation/sam-tool.service.d.ts +50 -0
- package/lib/toolbar/toolbar.component.d.ts +167 -0
- package/lib/toolbar/vertex-eraser/vertex-eraser-tool.service.d.ts +64 -0
- package/lib/toolbar/wand/wand-tool.service.d.ts +149 -0
- package/lib/toolbar/wand/wand.service.d.ts +133 -0
- package/lib/toolbar/zoom-to-box/zoom-to-box-tool.service.d.ts +49 -0
- package/lib/visualization.module.d.ts +45 -0
- package/lib/visualizer.component.d.ts +378 -0
- package/package.json +73 -0
- package/src/lib/assets/3d-coordinates.svg +49 -0
- package/src/lib/assets/cells.svg +1 -0
- package/src/lib/assets/click.svg +1 -0
- package/src/lib/assets/colormap-luts.json +1 -0
- package/src/lib/assets/contour.svg +48 -0
- package/src/lib/assets/cube-3d.svg +1 -0
- package/src/lib/assets/edit-selection-white.svg +47 -0
- package/src/lib/assets/heatmap.svg +1 -0
- package/src/lib/assets/icons/colormap-Pastel1.png +0 -0
- package/src/lib/assets/icons/colormap-accent.png +0 -0
- package/src/lib/assets/icons/colormap-afmhot.png +0 -0
- package/src/lib/assets/icons/colormap-autumn.png +0 -0
- package/src/lib/assets/icons/colormap-berlin.png +0 -0
- package/src/lib/assets/icons/colormap-binary.png +0 -0
- package/src/lib/assets/icons/colormap-blackbody.png +0 -0
- package/src/lib/assets/icons/colormap-bluered.png +0 -0
- package/src/lib/assets/icons/colormap-blues.png +0 -0
- package/src/lib/assets/icons/colormap-bone.png +0 -0
- package/src/lib/assets/icons/colormap-brbg.png +0 -0
- package/src/lib/assets/icons/colormap-brg.png +0 -0
- package/src/lib/assets/icons/colormap-bugn.png +0 -0
- package/src/lib/assets/icons/colormap-bupu.png +0 -0
- package/src/lib/assets/icons/colormap-bwr.png +0 -0
- package/src/lib/assets/icons/colormap-cividis.png +0 -0
- package/src/lib/assets/icons/colormap-cmrmap.png +0 -0
- package/src/lib/assets/icons/colormap-cool.png +0 -0
- package/src/lib/assets/icons/colormap-coolwarm.png +0 -0
- package/src/lib/assets/icons/colormap-copper.png +0 -0
- package/src/lib/assets/icons/colormap-cubehelix.png +0 -0
- package/src/lib/assets/icons/colormap-dark2.png +0 -0
- package/src/lib/assets/icons/colormap-earth.png +0 -0
- package/src/lib/assets/icons/colormap-electric.png +0 -0
- package/src/lib/assets/icons/colormap-flag.png +0 -0
- package/src/lib/assets/icons/colormap-gist_earth.png +0 -0
- package/src/lib/assets/icons/colormap-gist_gray.png +0 -0
- package/src/lib/assets/icons/colormap-gist_heat.png +0 -0
- package/src/lib/assets/icons/colormap-gist_ncar.png +0 -0
- package/src/lib/assets/icons/colormap-gist_rainbow.png +0 -0
- package/src/lib/assets/icons/colormap-gist_stern.png +0 -0
- package/src/lib/assets/icons/colormap-gist_yarg.png +0 -0
- package/src/lib/assets/icons/colormap-gnbu.png +0 -0
- package/src/lib/assets/icons/colormap-gnuplot.png +0 -0
- package/src/lib/assets/icons/colormap-gnuplot2.png +0 -0
- package/src/lib/assets/icons/colormap-gray.png +0 -0
- package/src/lib/assets/icons/colormap-greens-inv.png +0 -0
- package/src/lib/assets/icons/colormap-greens.png +0 -0
- package/src/lib/assets/icons/colormap-greys-inv.png +0 -0
- package/src/lib/assets/icons/colormap-greys.png +0 -0
- package/src/lib/assets/icons/colormap-hot.png +0 -0
- package/src/lib/assets/icons/colormap-hsv.png +0 -0
- package/src/lib/assets/icons/colormap-inferno.png +0 -0
- package/src/lib/assets/icons/colormap-jet.png +0 -0
- package/src/lib/assets/icons/colormap-magma.png +0 -0
- package/src/lib/assets/icons/colormap-managua.png +0 -0
- package/src/lib/assets/icons/colormap-nipy_spectral.png +0 -0
- package/src/lib/assets/icons/colormap-ocean.png +0 -0
- package/src/lib/assets/icons/colormap-oranges.png +0 -0
- package/src/lib/assets/icons/colormap-orrd.png +0 -0
- package/src/lib/assets/icons/colormap-pastel2.png +0 -0
- package/src/lib/assets/icons/colormap-picnic.png +0 -0
- package/src/lib/assets/icons/colormap-pink.png +0 -0
- package/src/lib/assets/icons/colormap-piyg.png +0 -0
- package/src/lib/assets/icons/colormap-placeholder.png +0 -0
- package/src/lib/assets/icons/colormap-plasma.png +0 -0
- package/src/lib/assets/icons/colormap-portland.png +0 -0
- package/src/lib/assets/icons/colormap-prgn.png +0 -0
- package/src/lib/assets/icons/colormap-prism.png +0 -0
- package/src/lib/assets/icons/colormap-pubu.png +0 -0
- package/src/lib/assets/icons/colormap-pubugn.png +0 -0
- package/src/lib/assets/icons/colormap-puor.png +0 -0
- package/src/lib/assets/icons/colormap-purd.png +0 -0
- package/src/lib/assets/icons/colormap-purples.png +0 -0
- package/src/lib/assets/icons/colormap-rainbow.png +0 -0
- package/src/lib/assets/icons/colormap-rdbu.png +0 -0
- package/src/lib/assets/icons/colormap-rdgy.png +0 -0
- package/src/lib/assets/icons/colormap-rdpu.png +0 -0
- package/src/lib/assets/icons/colormap-rdylbu.png +0 -0
- package/src/lib/assets/icons/colormap-rdylgn.png +0 -0
- package/src/lib/assets/icons/colormap-reds.png +0 -0
- package/src/lib/assets/icons/colormap-seismic.png +0 -0
- package/src/lib/assets/icons/colormap-set1.png +0 -0
- package/src/lib/assets/icons/colormap-set2.png +0 -0
- package/src/lib/assets/icons/colormap-set3.png +0 -0
- package/src/lib/assets/icons/colormap-spectral.png +0 -0
- package/src/lib/assets/icons/colormap-spring.png +0 -0
- package/src/lib/assets/icons/colormap-summer.png +0 -0
- package/src/lib/assets/icons/colormap-tab10.png +0 -0
- package/src/lib/assets/icons/colormap-tab20.png +0 -0
- package/src/lib/assets/icons/colormap-tab20b.png +0 -0
- package/src/lib/assets/icons/colormap-tab20c.png +0 -0
- package/src/lib/assets/icons/colormap-terrain.png +0 -0
- package/src/lib/assets/icons/colormap-turbo.png +0 -0
- package/src/lib/assets/icons/colormap-twilight.png +0 -0
- package/src/lib/assets/icons/colormap-twilight_shifted.png +0 -0
- package/src/lib/assets/icons/colormap-vanimo.png +0 -0
- package/src/lib/assets/icons/colormap-viridis.png +0 -0
- package/src/lib/assets/icons/colormap-winter.png +0 -0
- package/src/lib/assets/icons/colormap-wistia.png +0 -0
- package/src/lib/assets/icons/colormap-ylgn.png +0 -0
- package/src/lib/assets/icons/colormap-ylgnbu-inv.png +0 -0
- package/src/lib/assets/icons/colormap-ylgnbu.png +0 -0
- package/src/lib/assets/icons/colormap-ylorbr.png +0 -0
- package/src/lib/assets/icons/colormap-ylorrd-inv.png +0 -0
- package/src/lib/assets/icons/colormap-ylorrd.png +0 -0
- package/src/lib/assets/interactive-segmentation-cursor.svg +1 -0
- package/src/lib/assets/invert.svg +1 -0
- package/src/lib/assets/isosurface.svg +7 -0
- package/src/lib/assets/mask.svg +1 -0
- package/src/lib/assets/paintbrush.svg +1 -0
- package/src/lib/assets/picture-segmentation.svg +43 -0
- package/src/lib/assets/polygon-vertices.svg +13 -0
- package/src/lib/assets/polyline.svg +3 -0
- package/src/lib/assets/redo.svg +39 -0
- package/src/lib/assets/region-editor.svg +37 -0
- package/src/lib/assets/region-move.svg +7 -0
- package/src/lib/assets/smooth.svg +56 -0
- package/src/lib/assets/spline-chart.svg +7 -0
- package/src/lib/assets/surface.svg +37 -0
- package/src/lib/assets/test/download-379.svg +1 -0
- package/src/lib/assets/test/download-98.svg +1 -0
- package/src/lib/assets/test/json-1.svg +1 -0
- package/src/lib/assets/test/load-53.svg +1 -0
- package/src/lib/assets/test/mask-44.svg +1 -0
- package/src/lib/assets/test/mask-download-44.svg +15 -0
- package/src/lib/assets/test/mask-save-44.svg +11 -0
- package/src/lib/assets/test/overlay-1.svg +1 -0
- package/src/lib/assets/test/overlay-4.svg +1 -0
- package/src/lib/assets/test/region-26.svg +1 -0
- package/src/lib/assets/test/save-56.svg +1 -0
- package/src/lib/assets/test/upload-43.svg +1 -0
- package/src/lib/assets/to-bezier.svg +15 -0
- package/src/lib/assets/to-polygon.svg +11 -0
- package/src/lib/assets/undo.svg +38 -0
- package/src/lib/assets/vertex-add.svg +12 -0
- package/src/lib/assets/vertex-delete.svg +12 -0
- package/src/lib/assets/wand.svg +54 -0
- package/src/lib/assets/zoom-box.svg +10 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jax-data-science-sci-image-visualizer.mjs","sources":["../../src/lib/contracts/visualizer.contract.ts","../../src/lib/contracts/region-editor-api.contract.ts","../../src/lib/contracts/ports/image-state.port.ts","../../src/lib/contracts/ports/tile-access.port.ts","../../src/lib/contracts/ports/region-io.port.ts","../../src/lib/contracts/ports/preferences.port.ts","../../src/lib/contracts/channel-histogram-api.contract.ts","../../src/lib/contracts/viz-config.ts","../../src/lib/contracts/image.contract.ts","../../src/lib/contracts/plot-type.ts","../../src/lib/contracts/toolbar-config.ts","../../src/lib/contracts/capabilities.contract.ts","../../src/lib/contracts/display-types.ts","../../src/lib/contracts/sam.contract.ts","../../src/lib/toolbar/segmentation/ort-runtime-config.ts","../../src/lib/toolbar/segmentation/cellpose-segmenter.service.ts","../../src/lib/contracts/cell-segmenter.contract.ts","../../src/lib/processing/processing-image.ts","../../src/lib/processing/image-crop.ts","../../src/lib/processing/image-converter.service.ts","../../src/lib/toolbar/segmentation/sam-model-registry.ts","../../src/lib/models/shape.ts","../../src/lib/models/region.ts","../../src/lib/models/class-preset.ts","../../src/lib/models/geometry.ts","../../src/lib/toolbar/wand/wand.service.ts","../../src/lib/region-ops.service.ts","../../src/lib/models/bezier.ts","../../src/lib/plot.utilities.ts","../../src/lib/store/visualizer-store.service.ts","../../src/lib/render-orchestrator.ts","../../src/lib/toolbar/segmentation/sam-prompt.ts","../../src/lib/toolbar/segmentation/sam-tool.service.ts","../../src/lib/toolbar/segmentation/sam-point-tool.service.ts","../../src/lib/toolbar/crop/slide-crop.ts","../../src/lib/toolbar/segmentation/cell-segment-tool.service.ts","../../src/lib/toolbar/toolbar.component.ts","../../src/lib/toolbar/toolbar.component.html","../../src/lib/store/class-color.util.ts","../../src/lib/region-editor/mask-raster.ts","../../src/lib/hex-color-picker/hex-color-picker.component.ts","../../src/lib/hex-color-picker/hex-color-picker.component.html","../../src/lib/region-editor/region-editor.component.ts","../../src/lib/region-editor/region-editor.component.html","../../src/lib/channel-histogram/channel-histogram.component.ts","../../src/lib/channel-histogram/channel-histogram.component.html","../../src/lib/visualizer.component.ts","../../src/lib/visualizer.component.html","../../src/lib/toolbar/wand/wand-tool.service.ts","../../src/lib/toolbar/brush/brush-tool.service.ts","../../src/lib/toolbar/vertex-eraser/vertex-eraser-tool.service.ts","../../src/lib/toolbar/zoom-to-box/zoom-to-box-tool.service.ts","../../src/lib/contracts/intensity.ts","../../src/lib/implementations/plotly/plotly-trace-builders.ts","../../src/lib/implementations/plotly/plotly-region-overlay.ts","../../src/lib/implementations/plotly/plotly-coordinate-transform.ts","../../src/lib/store/region-store.service.ts","../../src/lib/implementations/plotly/plotly.service.ts","../../src/lib/implementations/osd/osd-lib.ts","../../src/lib/implementations/osd/osd-coords.ts","../../src/lib/implementations/osd/osd-region-overlay.ts","../../src/lib/implementations/osd/osd-scale-bar.ts","../../src/lib/implementations/osd/osd-coordinate-transform.ts","../../src/lib/implementations/osd/tile-client.ts","../../src/lib/implementations/osd/slice-cache.ts","../../src/lib/implementations/osd/display-pipeline.ts","../../src/lib/implementations/osd/histogram-sampler.ts","../../src/lib/implementations/base-store-visualizer.ts","../../src/lib/implementations/simple-slice-access.service.ts","../../src/lib/contracts/colormap-lut.ts","../../src/lib/implementations/osd/openseadragon-visualizer.service.ts","../../src/lib/implementations/napari-js/napari-scale-bar.ts","../../src/lib/implementations/napari-js/napari-region-overlay.ts","../../src/lib/implementations/napari-js/napari-axes-labels.ts","../../src/lib/implementations/napari-js/napari-volume-z-handle.ts","../../src/lib/implementations/napari-js/napari-visualizer.service.ts","../../src/lib/routing-visualizer.service.ts","../../src/lib/visualization.module.ts","../../src/lib/provide-visualization.ts","../../src/index.ts","../../src/jax-data-science-sci-image-visualizer.ts"],"sourcesContent":["import { InjectionToken } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { Image } from 'image-js';\n\nimport { IImageInfo, IImageMetadata } from './image.contract';\nimport { Region } from '../models/region';\nimport { PlotType, PlotTypeDescriptor } from './plot-type';\nimport { ViewerCapabilities } from './capabilities.contract';\nimport { IRegionOverlay } from './region-overlay.contract';\nimport { IHistogram } from './channel-histogram-api.contract';\nimport { ColormapNode, IWandOptions, IBrushOptions } from './display-types';\n\n/**\n * Backend-neutral visualization contract. Plotly is one implementation;\n * OpenSeadragon is another (for the image plot type). The abstraction renders\n * data — a raster image OR a scientific plot (heatmap, surface, contour,\n * scatter, line, isosurface) — draws regions on it, and drives on-canvas tools.\n *\n * Split into role interfaces so a consumer can depend only on the slice it\n * uses, then composed into `IVisualizer`.\n *\n * Types are intentionally permissive (`any` where the current Plotly service\n * is untyped) so `PlotlyService` satisfies the contract without a typing\n * rewrite — tightening is a follow-up, not part of standing the interface up.\n */\n\n/** Pixel readback shape returned by `getDisplayedPixelData`. */\nexport interface PixelData {\n width: number;\n height: number;\n channels: number;\n data: Uint8ClampedArray;\n}\n\n/** Intensity sampled along a line ROI (PlotType.LINE over image data). */\nexport interface IntensityProfile {\n /** Distance along the line. In microns when the image carries a physical\n * pixel size (mpp); otherwise in image pixels. See {@link unit}. */\n positions: number[];\n /** Sampled intensity (grayscale value or RGB luminance). */\n values: number[];\n /** Unit of {@link positions}: 'µm' when scaled by the image's mpp, else 'px'. */\n unit?: 'µm' | 'px';\n /** Stable id of the line ROI this profile came from (multi-line support). */\n id?: number;\n /** Colour of the line ROI — the inset trace is drawn in the same colour. */\n color?: string;\n}\n\n/**\n * The render/viewport role: load data, render it (image or plot), and handle\n * zoom, stack navigation, and pixel readback.\n */\nexport interface IDataRenderer {\n load(imageInfo: IImageInfo, zIndex: number): Promise<any>;\n /** `imageLoaded` is the backend-specific handle returned by `load()` —\n * treat it as opaque and pass it straight through. */\n plot(plotDiv: string, imageLoaded: unknown, imageInfo: IImageInfo, screenHeight: number,\n plotType: PlotType, inPlace?: boolean): Promise<boolean>;\n /** @deprecated Plotly-specific re-render; the OSD backend no-ops it. The host\n * re-drives `plot()` from its image stream instead. */\n reloadAndPlot(): void;\n reset(): void;\n relayout(trueImageSize?: number[]): void;\n /** @deprecated Plotly-specific (axis reset); the OSD backend no-ops it. Gate\n * on {@link ViewerCapabilities} before calling. */\n resetAxes(): void;\n /** @deprecated Plotly-specific (autoscale); the OSD backend no-ops it. Gate\n * on {@link ViewerCapabilities} before calling. */\n autoscale(): void;\n zoomIn(): void;\n zoomOut(): void;\n setDragMode(mode: string | false): void;\n /** Show/hide the overview navigator (the minimap). OpenSeadragon only — Plotly\n * no-ops it (it has no navigator). Applied when the viewer is (re)created, and\n * toggled live when one is already mounted. */\n setNavigatorVisible(visible: boolean): void;\n /** Image smoothing (bilinear interpolation). `false` = nearest-neighbour, so\n * zooming past 1:1 shows crisp pixel blocks (pixel-level inspection).\n * OpenSeadragon only — Plotly no-ops it. Applied at viewer creation and live\n * (with a redraw) when one is mounted. */\n setImageSmoothingEnabled(enabled: boolean): void;\n\n setShowStack(showstack: boolean): void;\n setZIndex(zIndex: number): void;\n setStackLoading(stackLoading: boolean): void;\n isStackLoading(): Observable<boolean>;\n getStackLoadingProgress(): Observable<number>;\n /** Cancel any in-flight multi-frame loading (volume-assembly / surface preload) so it stops\n * fetching more frames and clears the loading state. Optional — only backends that stream a\n * z-stack (napari-js WebGPU) do real work here; others no-op. */\n cancelLoading?(): void;\n\n getTrueImageSize(): { width: number; height: number } | null;\n getCurrentImage(): Promise<Image | null>;\n getDisplayedPixelData(): PixelData | null;\n /**\n * The region of the original, full-resolution image that the pixels returned\n * by {@link getDisplayedPixelData} currently cover — `{ x, y, width, height }`\n * in full-image pixel coordinates. When zoomed/panned into a sub-area this is\n * the crop's origin + extent; when zoomed out/panned beyond the edges, the\n * rectangle may extend outside the image bounds (matching the pixel readback\n * canvas). Lets a consumer map displayed-pixel coordinates back to the original\n * image via `origin + displayedPx * (extent / displayedDim)`. \n *\n * Returns `null` when the viewport isn't laid out yet or the backend can't\n * report it — callers should then fall back to the full-image scale (treat\n * the displayed pixels as a downsample of the whole image).\n */\n getDisplayedSourceRect(): { x: number; y: number; width: number; height: number } | null;\n downloadImage(): void;\n\n setPlotType(plotType: PlotType): void;\n /** Set the napari 3D decimate factor (1 = full … 8 = ⅛). Optional — only the napari-js WebGPU\n * backend honors it; changing it re-loads the current 3D plot at the coarser/finer sampling. */\n setResolutionScale?(scale: number): void;\n /** The current napari 3D decimate factor (to initialize the Resolution control). Optional. */\n getResolutionScale?(): number;\n /** @deprecated Use `getSurface3dControls()` — 3D scene controls only exist on\n * a backend that renders 3D plot types; this method silently no-ops on OSD. */\n setSurfaceDragMode(mode: string): void;\n /** @deprecated Use `getSurface3dControls()` — see {@link setSurfaceDragMode}. */\n resetSurfaceCamera(): void;\n\n getAutoscaleEvent(): Observable<any>;\n\n /** Plot types this backend advertises (drives the UI selector). */\n getPlotTypeDescriptors(): PlotTypeDescriptor[];\n\n /** Intensity along the line ROIs; emits the full set as any line is added,\n * moved, or removed (PlotType.LINE). One entry per line ROI. */\n getIntensityProfile$(): Observable<IntensityProfile[]>;\n\n /** Render the floating intensity-profile inset chart into `divId` from the\n * given profiles (one trace per line ROI, coloured to match its line).\n * Owned by the backend so consumers never reach a charting library directly. */\n renderIntensityInset(divId: string, profiles: IntensityProfile[]): void;\n}\n\n/** Region/shape state: CRUD, selection, classification colours, GeoJSON I/O. */\nexport interface IRegionStore {\n setRegions(regions: Region[], showRegionLabel?: boolean, isRegionSaveOn?: boolean,\n fillColor?: string, append?: boolean): void;\n /** Framework-neutral accessor — the canonical way to read current regions. */\n getRegions(): Region[];\n getRegionPolygons(): any[];\n getRegionUpdateEvent(): Observable<any[]>;\n\n setSelectedShapeIndices(indices: number[]): void;\n getSelectedShapeIndices$(): Observable<number[]>;\n /** Select a specific region (by identity), highlighting it on whichever\n * backend is rendering — Plotly sets its active-shape handles, OpenSeadragon\n * highlights the SVG element. No-op if the region isn't in the store. */\n selectRegion(region: Region): void;\n deleteActiveShape(): void;\n\n getShowShapeLabel(): boolean;\n getShapeColor(): string;\n getFillColor(): string;\n getClassificationColors(): Map<string, string>;\n setClassificationColor(label: string, color: string): void;\n\n plotPreviousShapes(): void;\n setPreviousShapes(shapes: any[]): void;\n getPreviousShapes(): any[];\n\n /** Undo the most recent region action (jit-ui#85). Restores the region set to\n * the state before that action; up to a small fixed depth (10) is retained,\n * so it can be invoked up to 10 times in a row. No-op when nothing is left to\n * undo. */\n undo(): void;\n /** Re-apply the most recently undone region action. No-op when there's\n * nothing to redo (any fresh region action clears the redo future). */\n redo(): void;\n /** Synchronous read of {@link getCanUndo$}. */\n canUndo(): boolean;\n /** Synchronous read of {@link getCanRedo$}. */\n canRedo(): boolean;\n /** Emits whether an undo step is currently available — drives the toolbar\n * Undo button's enabled (greyed-out) state. */\n getCanUndo$(): Observable<boolean>;\n /** Emits whether a redo step is currently available — drives the toolbar\n * Redo button's enabled (greyed-out) state. */\n getCanRedo$(): Observable<boolean>;\n /** Clear the undo/redo history (e.g. on image load/switch). */\n resetUndoHistory(): void;\n\n importRegions(geoJsonStr: string): Region[];\n exportRegions(regions: Region[]): void;\n getGeoJsonString(regions: Region[]): string;\n\n /** Begin a per-slice z-stack region session (jit-ui#93). `slices` maps each\n * zero-based slice index to that slice's regions; the store shows `initialZ`\n * live while holding the rest, so scrubbing swaps region sets and edits on a\n * slice persist. `saveLayout` records how the stack persists — `combined`\n * (one z-indexed geojson, single-file z-stack) or `per-slice-file` (folder\n * stack). See {@link setDisplaySlice}, {@link getSliceRegions}. */\n enterStackMode(slices: Map<number, Region[]>, initialZ?: number,\n saveLayout?: 'combined' | 'per-slice-file'): void;\n /** End the per-slice session (single-plane image, or the stack was closed). */\n exitStackMode(): void;\n /** True while a per-slice z-stack session is active. */\n isStackMode(): boolean;\n /** How the current stack persists to disk (jit-ui#93). */\n getStackSaveLayout(): 'combined' | 'per-slice-file';\n /** Swap the live region set to slice `z` (stack mode only), capturing the\n * current slice's edits first. Called on every committed slice scrub. */\n setDisplaySlice(z: number): void;\n /** Every slice's regions for save/export, each tagged with its zero-based\n * {@link Region.z}; the flat set outside stack mode. */\n getSliceRegions(): Region[];\n /** Slices to write on a per-slice-file save (folder stack, jit-ui#93): each\n * slice with regions, plus slices cleared since load (empty, to overwrite).\n * Keyed by zero-based slice index; regions tagged with their z. */\n getStackSaveSlices(): Map<number, Region[]>;\n}\n\n/** On-canvas tool modes (wand, brush, vertex eraser, zoom-to-box). */\nexport interface IToolController {\n setWandMode(active: boolean, options?: IWandOptions): void;\n setWandOptions(options: IWandOptions): void;\n clearActiveWandRegion(): void;\n /** Brush region tool. `size` (matrix-pixel diameter) sizes the painted disc. */\n setBrushMode(active: boolean, options?: IBrushOptions): void;\n setBrushOptions(options: IBrushOptions): void;\n setVertexEraserMode(active: boolean): void;\n setVertexEraserRadius(radius: number): void;\n setZoomToBoxMode(active: boolean): void;\n /** Box-prompted SAM segmentation: segment every rectangle region into masks.\n * Returns the number of mask regions added. (jit-ui#90) */\n segmentRectangles(): Promise<number>;\n /** Cellpose-on-crop: client slide-crop each rectangle and segment cells in it\n * (cellpose-SAM via the host's CELL_SEGMENTER). Returns regions added. */\n segmentRectanglesCellpose(): Promise<number>;\n /** Choose the registered SAM model the segment tools use (jit-ui#90 P1). */\n setSamModel(id: string): void;\n /** Toggle the interactive SAM point-prompt tool (click = +point, Shift = -). */\n setSamPointMode(active: boolean): void;\n /** Finalise / discard the in-progress SAM point object. */\n commitSamPoints(): void;\n clearSamPoints(): void;\n}\n\n/**\n * Controls specific to the ISOSURFACE plot type. Optional and capability-gated\n * (`ViewerFeature.Isosurface`): only a backend that renders isosurfaces exposes\n * it, via `IVisualizer.getIsosurfaceControls()`. Kept off the always-on\n * contract so consumers never call a control that's meaningless for the current\n * plot type / backend.\n */\nexport interface IIsosurfaceControls {\n /** Live-update the isosurface intensity band [isomin, isomax] over 0–255. */\n setIsoRange(isoMin: number, isoMax: number): void;\n}\n\n/**\n * Controls specific to the 3D plot types (SURFACE / SCATTER3D / ISOSURFACE\n * scenes). Capability-gated like {@link IIsosurfaceControls}: only a backend\n * that renders 3D scenes exposes it, via `IVisualizer.getSurface3dControls()` —\n * the deprecated top-level `setSurfaceDragMode`/`resetSurfaceCamera` silently\n * no-op on 2D-only backends.\n */\nexport interface ISurface3dControls {\n /** Switch the 3D scene interaction mode (orbit / turntable / pan / zoom). */\n setSurfaceDragMode(mode: string): void;\n /** Reset the 3D scene camera to its default eye position. */\n resetSurfaceCamera(): void;\n /** Toggle the 3D coordinate-axes / scale gizmo on/off. Optional — only the napari-js WebGPU\n * volume/isosurface backend renders one (jit-ui#102). */\n setAxesVisible?(visible: boolean): void;\n /** Whether the axes gizmo is currently shown (for initializing the toggle UI). Optional. */\n axesVisible?(): boolean;\n /** Render the surface as a wireframe (edges) instead of a filled surface. Optional — only the\n * napari-js WebGPU surface backend supports it (jit-ui#102). */\n setWireframe?(on: boolean): void;\n /** Whether the surface is currently drawn as a wireframe (for initializing the toggle UI). */\n wireframe?(): boolean;\n}\n\n/**\n * Controls specific to the LINE (intensity-profile) plot type. Capability-gated\n * like {@link IIsosurfaceControls}: only a backend that renders the line-ROI /\n * inset exposes it, via `IVisualizer.getIntensityControls()`.\n */\nexport interface IIntensityControls {\n /** Add another line ROI (next bright palette colour) and its inset trace.\n * Returns the created region so the caller can select it on the active\n * backend, or null if no image extent is known yet. */\n addProfileLine(): Region | null;\n}\n\n/** Display options (colormap/LUT, reverse scale, image metadata). */\nexport interface IDisplayOptions {\n getColormap(): Observable<ColormapNode | null>;\n setColormap(colormap: ColormapNode): void;\n getColormapOptions(): ColormapNode[];\n getReverseScale(): Observable<boolean>;\n setReverseScale(reverscale: any): void;\n setImageMeta(imageMeta: IImageMetadata[]): void;\n getImageMeta(): Observable<IImageMetadata[]>;\n}\n\n/**\n * Intensity-profile sampling (PlotType.LINE). The sampling *source* lives in the\n * Plotly backend (it owns pixel readback); OpenSeadragon contributes only the\n * viewport-change signal that drives re-sampling at the current zoom. Each\n * backend implements the part it owns and no-ops the rest — mirroring the\n * deprecated no-op pattern on {@link IDataRenderer} — so the contract is uniform\n * and a consumer can depend on `IVisualizer` alone (no concrete-type reach-in).\n */\nexport interface IIntensitySampling {\n /** Populate the intensity-sampling cache for the current image/slice so the\n * line-ROI profiles have pixel data. Real on Plotly; no-op on OSD. */\n ensureIntensitySampling(imageInfo: IImageInfo, zIndex: number): Promise<void>;\n /** Re-sample the profiles from a fresh crop of the given image-pixel ROI at\n * display resolution. Real on Plotly; no-op on OSD. */\n refreshIntensitySamplingForRoi(x: number, y: number, width: number, height: number,\n zIndex: number): void;\n /** Visible-region changes (image-pixel coords), emitted when the view settles,\n * so the inset can re-sample at the current zoom. Real on OSD; empty on Plotly\n * (its high-def zoom updates the sampling cache inline instead). */\n getViewportChange$(): Observable<{ x: number; y: number; width: number; height: number }>;\n}\n\n/** Composite contract a visualization backend implements. */\nexport interface IVisualizer extends IDataRenderer, IRegionStore, IToolController, IDisplayOptions,\n IIntensitySampling {\n readonly capabilities: ViewerCapabilities;\n /** This backend's region renderer. May be null until a plot is mounted\n * (OpenSeadragon). Drives region draw/select modes uniformly. */\n getRegionOverlay(): IRegionOverlay | null;\n /** Isosurface controls when this backend advertises `ViewerFeature.Isosurface`,\n * else null — so consumers gate on the returned object, not a no-op method. */\n getIsosurfaceControls(): IIsosurfaceControls | null;\n /** Intensity (line-ROI) controls when the backend renders the LINE plot type,\n * else null. */\n getIntensityControls(): IIntensityControls | null;\n /** 3D scene controls when this backend renders 3D plot types, else null —\n * the capability-gated replacement for the deprecated top-level\n * `setSurfaceDragMode`/`resetSurfaceCamera`. */\n getSurface3dControls(): ISurface3dControls | null;\n /** Binned intensity histogram for a channel from the currently-displayed\n * pixels, or null when none are available. Feeds the Channels & Histogram\n * pane. */\n getHistogram(channelIndex: number, bins: number): IHistogram | null;\n /** Async histogram stream — native bit depth for >8-bit images (server), else\n * the 8-bit client histogram. */\n getHistogram$(channelIndex: number, bins: number): Observable<IHistogram | null>;\n /** Export the displayed image, composited with the current display settings,\n * as a publication-ready PNG download. */\n exportComposite(): void;\n /** Export the underlying image data as a data-preserving multi-band TIFF\n * (native bit depth). No-op on backends that can't provide it. */\n exportData(): void;\n unsubscribe(): void;\n}\n\n/**\n * DI token for the active visualization backend. Bind it (`useExisting`) to the\n * `RoutingVisualizerService`, which selects Plotly vs OpenSeadragon per plot\n * type. Consumers — including this library's own `VisualizerComponent` —\n * inject `IVisualizer` through this token rather than the concrete router, so\n * the routing/fallback implementation can change without touching constructors.\n */\nexport const VISUALIZER = new InjectionToken<IVisualizer>('VISUALIZER');\n","import { InjectionToken } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { Region } from '../models/region';\nimport { ClassPreset, PresetSet } from '../models/class-preset';\nimport { IImageMetadata } from './image.contract';\n\n/**\n * Public, implementation-agnostic surface that the Region Editor (an *external*\n * consumer of the visualization package) depends on. It deals only in\n * **annotation** regions — intensity-profile lines (`Region.isProfile()`) are\n * owned by the intensity tool and are filtered out / preserved internally, so\n * the editor never sees or disturbs them.\n *\n * The editor injects this via {@link REGION_EDITOR_API} (bound to the concrete\n * `RoutingVisualizerService` with `useExisting`) instead of importing the\n * service class, so it cannot reach the implementation. This is the boundary\n * that lets `services/visualization` become a library whose only public surface\n * is the contracts.\n *\n * Selection is expressed in terms of {@link Region}s, not array indices — the\n * index space (which includes profile lines) stays internal to the package.\n */\nexport interface IRegionEditorApi {\n // ── display defaults ─────────────────────────────────────────────────\n getShowShapeLabel(): boolean;\n getShapeColor(): string;\n getFillColor(): string;\n\n // ── annotation regions (profile lines excluded & preserved internally) ─\n /** Annotation regions for the current image. Intensity-profile lines are\n * never included. */\n getAnnotationRegions(): Region[];\n /** Replace the annotation regions. Intensity-profile lines in the store are\n * preserved (the editor must not be able to drop them). */\n setAnnotationRegions(regions: Region[], showRegionLabel?: boolean,\n isRegionSaveOn?: boolean, fillColor?: string): void;\n /** Change signal — fires whenever regions change on any backend. */\n getRegionUpdateEvent(): Observable<any[]>;\n\n // ── selection (by region identity; index space stays internal) ────────\n /** The currently-selected annotation regions (profile lines never appear). */\n getSelectedRegions$(): Observable<Region[]>;\n /** Set the selection to these regions. */\n setSelectedRegions(regions: Region[]): void;\n\n // ── classification colours ────────────────────────────────────────────\n getClassificationColors(): Map<string, string>;\n setClassificationColor(label: string, color: string): void;\n\n // ── annotation-class presets (jit-ui#70) ───────────────────────────────\n /** The current per-user preset set (source of truth for region colours). */\n getPresetSet(): PresetSet;\n /** Emits the preset set on every change (BehaviorSubject-backed). */\n getPresetSet$(): Observable<PresetSet>;\n /** Replace the whole preset set (persists per-user). */\n setPresetSet(set: PresetSet): void;\n /** Add or update one class by name (persists). */\n upsertClass(preset: ClassPreset): void;\n /** Remove a class by name (persists). */\n removeClass(name: string): void;\n /** Restore the default preset set (persists). */\n resetPresets(): void;\n\n // ── image metadata (for region areas in µm²) ──────────────────────────\n getImageMeta(): Observable<IImageMetadata[]>;\n\n // ── import / export ────────────────────────────────────────────────────\n importRegions(geoJsonStr: string): Region[];\n getGeoJsonString(regions: Region[]): string;\n\n // ── per-slice z-stacks (jit-ui#93) ──────────────────────────────────────\n /** True while a per-slice z-stack region session is active — the editor then\n * saves/edits regions per displayed slice. */\n isStackMode(): boolean;\n /** How the current stack persists: `combined` = one z-indexed geojson\n * (single-file z-stack, QuPath schema); `per-slice-file` = one geojson per\n * slice-file (folder stack). */\n getStackSaveLayout(): 'combined' | 'per-slice-file';\n /** Every slice's annotation regions (profile lines excluded), each tagged\n * with its zero-based {@link Region.z}, for a combined z-indexed save. */\n getSliceAnnotationRegions(): Region[];\n /** Per-slice annotation regions for a folder-stack (`per-slice-file`) save:\n * zero-based slice index → that slice's annotation regions. Includes\n * now-empty slices loaded non-empty, so their file is overwritten empty. */\n getStackSaveAnnotationSlices(): Map<number, Region[]>;\n /**\n * Full-resolution image size (image-pixel dimensions) used to size an exported\n * region mask. Backend-neutral: prefers the active renderer's reported size\n * and falls back to the image metadata. Returns null when no size is known.\n *\n * The mask itself is rasterized off the main thread (see the Region Editor's\n * mask worker) from the region geometry and this size.\n */\n getMaskImageSize(): { width: number; height: number } | null;\n}\n\n/** DI token the Region Editor injects instead of the concrete service. */\nexport const REGION_EDITOR_API = new InjectionToken<IRegionEditorApi>('REGION_EDITOR_API');\n","import { InjectionToken } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { IImageInfo } from '../image.contract';\n\n/**\n * Host image/loading/zoom state, inverted as a port so the visualization library\n * doesn't import the app's `MainState`/`MainFacade`. The host supplies an adapter\n * that delegates to those. Read methods return the host's live streams; write\n * methods push state back to the host (e.g. loading flags, the updated image).\n */\nexport interface ImageStatePort {\n // ── reads ────────────────────────────────────────────────────────────\n getFilename$(): Observable<string | undefined>;\n isImageCached$(): Observable<boolean>;\n getImageInfo$(): Observable<IImageInfo | null>;\n getImageLoadingMessage$(): Observable<string>;\n getCacheProgress$(): Observable<number | null>;\n getPanelWidth$(): Observable<number>;\n isImageLoading$(): Observable<boolean>;\n isZoom$(): Observable<boolean>;\n\n // ── writes ───────────────────────────────────────────────────────────\n /** Push an updated image descriptor to the host (partial — only set fields). */\n setImageInfo(info: Partial<IImageInfo>): void;\n setImageLoading(loading: boolean): void;\n setImageLoadingMessage(message: string): void;\n setZoom(zoom: boolean): void;\n setImageCached(cached: boolean): void;\n setLoadingError(error: boolean): void;\n /** Register the active diagram/visualization component with the host. */\n setDiagram(diagram: unknown): void;\n}\n\nexport const IMAGE_STATE_PORT = new InjectionToken<ImageStatePort>('IMAGE_STATE_PORT');\n","import { InjectionToken } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { Rectangle } from '../../models/region';\n\n/**\n * File/tile/zoom backend, inverted as a port so the visualization library doesn't\n * import the app's `FilesService` (nor its `ZoomRequest`/`DisplayType` request\n * models). The host supplies an adapter that builds the concrete request from\n * these library-native arguments and the currently-selected file.\n */\nexport interface TileAccessPort {\n /** Base64-encoded info for the currently-selected file (used for `/tile` and\n * `/tiles/info` requests), or null when nothing is selected. Collapses the\n * host's `getSelectedFileInfo()` + `encode(rawData)`. */\n getSelectedInfoB64(): string | null;\n\n /** Server-side crop/zoom of the current image to `roi`; resolves to raw image\n * bytes. `screen` is the on-screen diagram rectangle. The host builds the\n * request (including the selected file) internally. */\n zoomOnRegion(roi: Rectangle, screen: Rectangle, zIndex: number): Observable<ArrayBuffer>;\n\n /** Switch the host's display back to the diagram view (replaces the app's\n * `selectDisplayType(DisplayType.Diagram)`). */\n selectDiagramDisplay(): void;\n\n /** Auth headers (e.g. `Authorization: Bearer …`) for OSD's own tile fetches\n * (its AJAX loader + prefetch bypass Angular's HttpClient interceptor, so the\n * host supplies them). Hides the app's Auth0 dependency from the library. */\n getAuthHeaders(): Promise<Record<string, string>>;\n}\n\nexport const TILE_ACCESS_PORT = new InjectionToken<TileAccessPort>('TILE_ACCESS_PORT');\n","import { InjectionToken } from '@angular/core';\nimport { Observable } from 'rxjs';\n\n/**\n * Region file I/O, inverted as a port so the visualization library's region\n * editor doesn't import the app's `FilesService` (the library performs no backend\n * requests itself). The host supplies an adapter that delegates to its file\n * service; the editor only needs the selected file's name (to derive default ROI\n * filenames), an existence check, and a save. Bound to {@link REGION_IO_PORT}.\n */\nexport interface RegionIoPort {\n /** Name of the currently selected file (e.g. \"image.tif\"), or undefined when\n * none is selected. Used to derive a default ROI filename stem. */\n getSelectedFileName(): string | undefined;\n /** Whether an ROI file named `name` already exists for the selected file. */\n roiFileExists(name: string): Observable<boolean>;\n /** Persist the regions (already serialized to a GeoJSON string) as `filename`. */\n saveGeoJson(geoJsonStr: string, filename: string): Observable<void>;\n /**\n * Persist a folder-stack's regions as one geojson per slice-file (jit-ui#93).\n * Each entry's `z` is the zero-based slice index; the host maps it to that\n * slice-file's sibling `<stem>.geojson` in the same folder. Completes once\n * every slice has been written. (jit-ui#93)\n */\n saveSliceGeoJsons(slices: { z: number; geoJsonStr: string }[]): Observable<void>;\n}\n\nexport const REGION_IO_PORT = new InjectionToken<RegionIoPort>('REGION_IO_PORT');\n","import { InjectionToken } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { PresetSet } from '../../models/class-preset';\n\n/**\n * Port for persisting the per-user annotation-class preset set (jit-ui#70).\n *\n * The library defines the contract; the app supplies an adapter that talks to the\n * jit-service `/api/preferences/annotation-classes` endpoint. The user is keyed\n * server-side from the authenticated JWT, so no user id is passed here.\n *\n * Mirrors `RegionIoPort` / `REGION_IO_PORT`.\n */\nexport interface PreferencesPort {\n /** Load the current user's preset set; resolves to `null` if none has been saved yet. */\n loadPresetSet(): Observable<PresetSet | null>;\n\n /** Persist (upsert) the current user's preset set. */\n savePresetSet(set: PresetSet): Observable<void>;\n}\n\nexport const PREFERENCES_PORT = new InjectionToken<PreferencesPort>('PREFERENCES_PORT');\n","import { InjectionToken } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { IImageMetadata } from './image.contract';\nimport { ColormapNode } from './display-types';\n\n/**\n * Display state for one image channel in the Channels & Histogram pane.\n * `min`/`max` are the display window (contrast/brightness) in raw 0..255 space;\n * `gamma` shapes the transfer curve; `color` is the channel's display tint\n * (used when compositing multiple channels); `visible` toggles it on/off.\n */\nexport interface IChannelState {\n index: number;\n name: string;\n /** Display tint as `#rrggbb`. */\n color: string;\n min: number;\n max: number;\n gamma: number;\n visible: boolean;\n}\n\n/** The standard LUT pseudo-colours (mirrors Fiji's Merge Channels palette) for\n * quick per-channel assignment. */\nexport const LUT_COLORS: ReadonlyArray<{ name: string; color: string }> = [\n { name: 'Red', color: '#ff0000' },\n { name: 'Green', color: '#00ff00' },\n { name: 'Blue', color: '#0000ff' },\n { name: 'Gray', color: '#ffffff' },\n { name: 'Cyan', color: '#00ffff' },\n { name: 'Magenta', color: '#ff00ff' },\n { name: 'Yellow', color: '#ffff00' },\n];\n\n/** A binned intensity histogram for one channel.\n *\n * The 8-bit client path (RGB / 8-bit grayscale, sampled from displayed tiles)\n * leaves the native fields undefined and `bins` span 0..255. The native path\n * (>8-bit images, from the server `/histogram` endpoint) fills `bitDepth`,\n * `rangeMin`/`rangeMax` (the pixel-type span the bins cover) and\n * `observedMin`/`observedMax` (the actual extremes seen), so the dialog can\n * label the window/axis in native units. */\nexport interface IHistogram {\n /** Left edge of each bin (0..255 for the 8-bit path, native units otherwise). */\n bins: number[];\n /** Pixel count per bin, length = bin count. */\n counts: number[];\n /** Largest bin count, for y-axis scaling. */\n max: number;\n /** Native bit depth (8, 16, …) — present only on the native server path. */\n bitDepth?: number;\n /** Pixel-type range the bins span (e.g. 0..65535), native path only. */\n rangeMin?: number;\n rangeMax?: number;\n /** Actual min/max pixel observed (auto-contrast seed), native path only. */\n observedMin?: number;\n observedMax?: number;\n}\n\n/**\n * Public, implementation-agnostic surface the Channels & Histogram pane (an\n * external consumer of the visualization package) depends on. It exposes the\n * per-channel display window/gamma/visibility, an intensity histogram computed\n * from the currently-displayed pixels, and the LUT/colormap controls that used\n * to live in the toolbar. The pane injects this via {@link CHANNEL_HISTOGRAM_API}\n * (bound to the concrete `RoutingVisualizerService` with `useExisting`) so it\n * never reaches the implementation. Every setter live-updates whichever backend\n * (Plotly or OpenSeadragon) is on screen.\n */\nexport interface IChannelHistogramApi {\n // ── channels ──────────────────────────────────────────────────────────\n /** The channels of the current image (1 for grayscale, 3 for RGB). */\n getChannels$(): Observable<IChannelState[]>;\n /** Patch one channel's state (window/gamma/visibility/color); live-updates. */\n setChannelState(index: number, partial: Partial<IChannelState>): void;\n /** Auto-window the given channels by saturating `saturation` (0..1) of pixels\n * at each end of their histogram. */\n autoContrast(indices: number[], saturation: number): void;\n /** Reset the given channels to their derived defaults: full display range\n * (0..255), gamma 1, and the channel's default tint colour. */\n resetContrast(indices: number[]): void;\n\n // ── histogram ─────────────────────────────────────────────────────────\n /** Binned histogram for a channel from the displayed pixels, or null when no\n * image/pixels are available. Synchronous 8-bit path (used by auto-contrast). */\n getHistogram(channelIndex: number, bins: number): IHistogram | null;\n /** Histogram for a channel as an async stream: emits the **native** bit-depth\n * histogram (from the server) for >8-bit images, else the 8-bit client\n * histogram. The dialog uses this so 16-bit stacks get a true distribution. */\n getHistogram$(channelIndex: number, bins: number): Observable<IHistogram | null>;\n\n // ── display options (moved out of the toolbar) ────────────────────────\n getColormap(): Observable<ColormapNode | null>;\n setColormap(colormap: ColormapNode): void;\n getColormapOptions(): ColormapNode[];\n getReverseScale(): Observable<boolean>;\n setReverseScale(reverse: boolean): void;\n getGrayscale$(): Observable<boolean>;\n setGrayscale(on: boolean): void;\n getInvert$(): Observable<boolean>;\n setInvert(on: boolean): void;\n\n // ── image ─────────────────────────────────────────────────────────────\n getImageMeta(): Observable<IImageMetadata[]>;\n\n /** Export the displayed image — composited with the current per-channel\n * pseudo-colours / window / colormap — as a publication-ready PNG download. */\n exportComposite(): void;\n\n /** Export the underlying image data — all (or the visible) channels at native\n * bit depth — as a data-preserving multi-band TIFF download. Server-side, so\n * it keeps true 16-bit values (the PNG composite is an 8-bit figure). Only\n * meaningful for >8-bit images; a no-op on backends that can't provide it. */\n exportData(): void;\n}\n\nexport const CHANNEL_HISTOGRAM_API = new InjectionToken<IChannelHistogramApi>('CHANNEL_HISTOGRAM_API');\n","import { InjectionToken } from '@angular/core';\n\n/**\n * Static configuration the visualization library needs from the host, supplied\n * via DI so the library never imports the app's `environment`.\n */\nexport interface VizConfig {\n /** Base URL of the tile/crop server (`/tile`, `/tiles/info`, zoom). */\n slideCropServer: string;\n /**\n * Optional CSS selector for a host element whose current width the Region\n * Editor dialog should match when it first opens (e.g. the app's right\n * panel). Measured once per open — it does not track later resizes. When\n * absent or the element isn't found, the dialog falls back to a quarter of\n * the page width (25vw).\n */\n regionEditorWidthSelector?: string;\n /**\n * Opt in to the experimental WebGPU **napari-js** backend for the IMAGE plot type\n * (jit-ui#102). When `true`, the router renders images through napari-js with OpenSeadragon\n * as the fallback; when absent/false, OpenSeadragon remains the default. Other plot types\n * are unaffected.\n */\n useNapariRenderer?: boolean;\n}\n\nexport const VIZ_CONFIG = new InjectionToken<VizConfig>('VIZ_CONFIG');\n","/**\n * Library-owned data interfaces for the image the visualization renders.\n *\n * The visualization package must not import the host app's concrete models\n * (`main/models/file-info`), or it can't become a standalone library. These\n * slim interfaces declare only the fields the library reads/writes; the host's\n * `ImageInfo`/`ImageMetadata` classes are pure data holders that satisfy them\n * structurally, so the host keeps passing its own instances unchanged.\n */\n\n/** Per-channel metadata from the server descriptor (issue #76). */\nexport interface IChannelInfo {\n name: string;\n /** Suggested display tint as \"#RRGGBB\". */\n color: string;\n /** Embedded 256-entry display LUT as \"#RRGGBB\" (intensity→color), or\n * null/undefined when the file has no palette for this channel. */\n lut?: string[] | null;\n bitDepth?: number;\n /** Pixel-type minimum (e.g. 0 for unsigned). Native-unit floor of the window. */\n minAllowed?: number;\n /** Pixel-type maximum (e.g. 65535 for unsigned 16-bit). Native-unit ceiling. */\n maxAllowed?: number;\n}\n\n/** Per-series image metadata (physical size + dimensions). */\nexport interface IImageMetadata {\n channelCount: number;\n rgbChannels: number;\n x: number;\n y: number;\n z: number;\n /** Physical pixel size in µm; null/undefined when the format reports none. */\n mppX?: number | null;\n mppY?: number | null;\n /** Per-channel name/color/LUT for multichannel (non-RGB) images, when known. */\n channelInfo?: IChannelInfo[] | null;\n}\n\n/** The image currently being visualized. Field optionality mirrors the host's\n * `ImageInfo` so its instances are assignable to this interface. */\nexport interface IImageInfo {\n isGrayscale: boolean;\n trueImageSize: number[];\n urls: string[];\n /** Optional small-tier URLs (fast blurry placeholder), 1:1 with `urls`. */\n smallUrls?: string[];\n isStack: boolean;\n showStack: boolean;\n scaleRatio: boolean;\n fileName: string;\n roiJsonStr?: string;\n /** Per-slice ROI GeoJSON, aligned 1:1 with `urls`, for a folder stack where\n * each slice is a separate file with its own sibling `<stem>.geojson`\n * (`null` for slices without one). When present, the component applies\n * `roiJsonStrs[z]` for the displayed slice and swaps it on scrub — as\n * opposed to the scalar `roiJsonStr`, which is one ROI set for the whole\n * image (a single file or a server z-stack). (jit-ui#93) */\n roiJsonStrs?: (string | null)[];\n imageMeta: IImageMetadata[];\n /** How the OpenSeadragon backend should source this image.\n * - `true`/absent (default): server-tiled — OSD polls `/tiles/info` for a\n * pyramid and fetches tiles from the slide-crop server (whole-slide path).\n * - `false`: a self-contained, directly-loadable image — `urls[zIndex]` is a\n * complete image (e.g. a `blob:` URL built from a client-side pixel buffer),\n * opened via OSD's single-image source with no tile server. Lets in-memory\n * images (the processing pipeline) use the OSD viewer without a round-trip. */\n tiled?: boolean;\n /** One-shot hint: open the stack on this slice instead of slice 0 (e.g. the\n * host clicked a specific file within a numbered image series). The\n * component consumes and clears this the first time it sees the object, so\n * re-delivering the same ImageInfo (e.g. a plot-type switch) doesn't reset\n * the user's current scrub position. */\n initialZIndex?: number;\n}\n","/**\n * The kind of rendering a viewer backend should produce for the loaded data.\n *\n * Lives in `contracts/` (rather than inside a specific backend) because it is\n * part of the backend-neutral plotting contract: both the Plotly backend and\n * any future backend (e.g. OpenSeadragon) accept a `PlotType` on `plot()`.\n *\n * NOTE: a backend may not support every type — 3D types (`SURFACE`,\n * `SCATTER3D`, `ISOSURFACE`) are gated behind `ViewerFeature.Surface3D` in the\n * capabilities contract, so a 2D-only backend can advertise that it can't\n * render them and the UI can hide the option.\n */\nexport enum PlotType {\n /** Natively-tiled, zoomable raster rendered by OpenSeadragon (the default\n * view for an image). Heatmap remains the Plotly scalar-image rendering. */\n IMAGE = 'image',\n HEATMAP = 'heatmap',\n SURFACE = 'surface',\n CONTOUR = 'contour',\n SCATTER = 'scatter',\n // LINE: reserved/stubbed — intensity profiles are now Region-based (kept for future use)\n LINE = 'line',\n SCATTER3D = 'scatter3d',\n ISOSURFACE = 'isosurface',\n /** WebGPU napari-js renderings (jit-ui#102), selectable alongside the OSD/Plotly types. The 3D\n * types take a runtime decimate factor (Full / ½ / ¼ / ⅛) instead of fixed hi/lo-res variants. */\n NAPARI_IMAGE = 'napari-image',\n NAPARI_VOLUME = 'napari-volume',\n NAPARI_ISOSURFACE = 'napari-isosurface',\n /** WebGPU height-field surface mesh (z = intensity), the napari-js analog of Plotly SURFACE. */\n NAPARI_SURFACE = 'napari-surface',\n /** WebGPU 2D scatter of region centroids (napari-js analog of Plotly SCATTER). */\n NAPARI_SCATTER = 'napari-scatter',\n /** WebGPU 3D scatter of the downsampled voxel cloud (napari-js analog of Plotly SCATTER3D). */\n NAPARI_SCATTER3D = 'napari-scatter3d',\n}\n\n/** How many spatial dimensions a plot type renders in. */\nexport type PlotDimensions = '2d' | '3d';\n\n/**\n * Where a plot type pulls its data from:\n * - `image` — the loaded pixel matrices / z-stack (HEATMAP, SURFACE, …)\n * - `regions` — the drawn/derived regions (SCATTER of region centroids, …)\n */\nexport type PlotDataSource = 'image' | 'regions';\n\n/**\n * Backend-neutral metadata about a plot type. Drives UI affordances (which\n * types are 3D, which need an image stack, how to label them in a dropdown)\n * without any backend's trace-building logic leaking into the contract.\n */\nexport interface PlotTypeDescriptor {\n type: PlotType;\n /** Human-readable label for menus/dropdowns. Shown in **test mode**, where\n * every backend's type is offered, so it carries the backend suffix (e.g.\n * \"Surface (napari · WebGPU)\") to disambiguate same-named modes. */\n label: string;\n /**\n * Label shown in the **default (non-test) selector**, where a single curated\n * mode owns each name — so it drops the backend suffix (e.g. just \"Surface\").\n * A type WITHOUT a `productionLabel` is **test-only**: hidden from the default\n * selector and shown only when the host enables test mode. This is the single\n * knob that curates the default plot-mode list (jax-image-visualization).\n */\n productionLabel?: string;\n /**\n * Icon shown to the left of the label in the plot-type selector. Either a\n * PrimeNG icon class (starts with `pi `, e.g. `pi pi-image`) rendered as a\n * font glyph, or a served SVG asset path (e.g. `assets/plotting/surface.svg`)\n * rendered as an `<img>`. Both are tinted to the toolbar's primary blue.\n */\n icon?: string;\n dimensions: PlotDimensions;\n source: PlotDataSource;\n /** True when the type only makes sense over a multi-frame z-stack. */\n requiresStack?: boolean;\n /** True when the type maps a single scalar intensity per pixel (contour,\n * surface, intensity profile, isosurface) — only meaningful for grayscale.\n * Image/Heatmap render RGB fine; Scatter uses regions. */\n requiresGrayscale?: boolean;\n}\n\n/**\n * Single source of truth for plot-type metadata. LINE is intentionally absent —\n * intensity profiles are now Region-based line ROIs (available in Heatmap/Image\n * mode), so LINE is no longer offered in the selector (the enum member is kept\n * for future use). Hence the `Partial` record.\n */\n// Dropdown order = insertion order: Image (OSD) default at the top, then all Plotly plot modes\n// grouped, then all napari-js WebGPU modes grouped.\n// `productionLabel` marks the curated default-selector set (jit-ui#70 follow-up):\n// - IMAGE / HEATMAP / CONTOUR (2D) and the napari SURFACE / VOLUME / ISOSURFACE\n// (3D) are the modes shown by default, under suffix-free names.\n// - Everything else (all Scatters, NAPARI_IMAGE, and the Plotly SURFACE /\n// ISOSURFACE that the napari versions supersede) is test-only — no\n// `productionLabel`, so it appears only when the host enables test mode.\nexport const PLOT_TYPE_DESCRIPTORS: Partial<Record<PlotType, PlotTypeDescriptor>> = {\n // ── Default ──\n [PlotType.IMAGE]: { type: PlotType.IMAGE, label: 'Image (OSD)', productionLabel: 'Image', icon: 'pi pi-image', dimensions: '2d', source: 'image' },\n // ── Plotly ──\n [PlotType.HEATMAP]: { type: PlotType.HEATMAP, label: 'Heatmap (Plotly)', productionLabel: 'Heatmap', icon: 'assets/plotting/heatmap.svg', dimensions: '2d', source: 'image' },\n [PlotType.CONTOUR]: { type: PlotType.CONTOUR, label: 'Contour (Plotly)', productionLabel: 'Contour', icon: 'assets/plotting/contour.svg', dimensions: '2d', source: 'image', requiresGrayscale: true },\n [PlotType.SCATTER]: { type: PlotType.SCATTER, label: 'Scatter 2D (Plotly)', icon: 'pi pi-chart-scatter', dimensions: '2d', source: 'regions' },\n [PlotType.SURFACE]: { type: PlotType.SURFACE, label: 'Surface (Plotly)', icon: 'assets/plotting/surface.svg', dimensions: '3d', source: 'image', requiresGrayscale: true },\n [PlotType.SCATTER3D]: { type: PlotType.SCATTER3D, label: 'Scatter 3D (Plotly)', icon: 'assets/plotting/3d-coordinates.svg', dimensions: '3d', source: 'image', requiresStack: true, requiresGrayscale: true },\n [PlotType.ISOSURFACE]: { type: PlotType.ISOSURFACE, label: 'Isosurface (Plotly)', icon: 'assets/plotting/isosurface.svg', dimensions: '3d', source: 'image', requiresStack: true, requiresGrayscale: true },\n // ── napari-js WebGPU (jit-ui#102). The 3D types take a runtime decimate factor. ──\n [PlotType.NAPARI_IMAGE]: { type: PlotType.NAPARI_IMAGE, label: 'Image (napari · WebGPU)', icon: 'pi pi-image', dimensions: '2d', source: 'image' },\n [PlotType.NAPARI_SCATTER]: { type: PlotType.NAPARI_SCATTER, label: 'Scatter 2D (napari · WebGPU)', icon: 'pi pi-chart-scatter', dimensions: '2d', source: 'regions' },\n [PlotType.NAPARI_SURFACE]: { type: PlotType.NAPARI_SURFACE, label: 'Surface (napari · WebGPU)', productionLabel: 'Surface', icon: 'assets/plotting/surface.svg', dimensions: '3d', source: 'image', requiresGrayscale: true },\n [PlotType.NAPARI_SCATTER3D]: { type: PlotType.NAPARI_SCATTER3D, label: 'Scatter 3D (napari · WebGPU)', icon: 'assets/plotting/3d-coordinates.svg', dimensions: '3d', source: 'image', requiresStack: true, requiresGrayscale: true },\n [PlotType.NAPARI_VOLUME]: { type: PlotType.NAPARI_VOLUME, label: 'Volume (napari · WebGPU)', productionLabel: 'Volume', icon: 'assets/plotting/cube-3d.svg', dimensions: '3d', source: 'image', requiresStack: true, requiresGrayscale: true },\n [PlotType.NAPARI_ISOSURFACE]: { type: PlotType.NAPARI_ISOSURFACE, label: 'Isosurface (napari · WebGPU)', productionLabel: 'Isosurface', icon: 'assets/plotting/isosurface.svg', dimensions: '3d', source: 'image', requiresStack: true, requiresGrayscale: true },\n};\n\nexport function getPlotTypeDescriptor(type: PlotType): PlotTypeDescriptor | undefined {\n return PLOT_TYPE_DESCRIPTORS[type];\n}\n\nexport function isThreeDimensional(type: PlotType): boolean {\n return PLOT_TYPE_DESCRIPTORS[type]?.dimensions === '3d';\n}\n\n// ── napari-js 3D plot-type predicates ────────────────────────────────────────\n/** napari-js volume. */\nexport function isNapariVolume(type: PlotType): boolean {\n return type === PlotType.NAPARI_VOLUME;\n}\n/** napari-js isosurface. */\nexport function isNapariIsosurface(type: PlotType): boolean {\n return type === PlotType.NAPARI_ISOSURFACE;\n}\n/** napari-js height-field surface mesh. */\nexport function isNapariSurface(type: PlotType): boolean {\n return type === PlotType.NAPARI_SURFACE;\n}\n/** napari-js 2D scatter (region centroids). */\nexport function isNapariScatter(type: PlotType): boolean {\n return type === PlotType.NAPARI_SCATTER;\n}\n/** napari-js 3D scatter (voxel point cloud). */\nexport function isNapariScatter3d(type: PlotType): boolean {\n return type === PlotType.NAPARI_SCATTER3D;\n}\n/** Any napari-js 3D plot type (volume, isosurface, surface, or 3D scatter). Resolution is a runtime\n * decimate factor (Full / ½ / ¼ / ⅛) — see the service's `resolutionScale`. */\nexport function isNapari3d(type: PlotType): boolean {\n return (\n isNapariVolume(type) || isNapariIsosurface(type) || isNapariSurface(type) || isNapariScatter3d(type)\n );\n}\n\n/** Decimate factors offered by the Resolution control (1 = Full … 8 = ⅛). */\nexport const NAPARI_DECIMATE_OPTIONS: { label: string; value: number }[] = [\n { label: 'Full', value: 1 },\n { label: '½', value: 2 },\n { label: '¼', value: 4 },\n { label: '⅛', value: 8 },\n];\n\n/** Default decimate factor: ¼. The caps are set so ¼ is a sensible default resolution while ½ and\n * Full offer 2× and 4× the detail for opt-in high-resolution renders. */\nexport const NAPARI_DEFAULT_DECIMATE = 4;\n","/**\n * Which groups of controls the visualization toolbar shows. All default to `true`\n * (the full toolbar); a consumer embedding `<visualizer>` can hide groups\n * it doesn't want via the `toolbarTools` input — e.g. the processing pipeline shows\n * only the zoom and region tools.\n *\n * Groups not listed here (stack navigation, 3D-scene controls, isosurface band) are\n * already shown only when the image/plot type calls for them, so a single 8-bit\n * image never surfaces them regardless of these flags.\n */\nexport interface ToolbarToolVisibility {\n /** Plot-type selector, intensity-profile line, Channels & Histogram, download,\n * and fit-to-view (autoscale) — everything that isn't a zoom or region tool. */\n specialTools?: boolean;\n /** Zoom drag, zoom box, pan, zoom in, zoom out. */\n zoomTools?: boolean;\n /** Region drawing/editing: select, rectangle, polyline, freeform, polygon vertex\n * editing, wand, vertex eraser, delete, Bézier/polygon conversion. */\n regionTools?: boolean;\n /** The Help button and its dialog. */\n help?: boolean;\n}\n\n/** Full toolbar — the default when no `toolbarTools` is supplied. */\nexport const ALL_TOOLBAR_TOOLS: Required<ToolbarToolVisibility> = {\n specialTools: true,\n zoomTools: true,\n regionTools: true,\n help: true,\n};\n","/**\n * Optional features a viewer backend may or may not support. Consumers query\n * `IImageViewer.capabilities` and degrade gracefully (hide a toolbar item,\n * skip a render path) rather than calling a method that no-ops.\n *\n * The Plotly backend supports the scientific/data features; the OpenSeadragon\n * backend supports `ImageDisplay` (large zoomable image) but not the\n * scalar-data features. The eventual router picks a backend per plot type.\n */\nexport enum ViewerFeature {\n /** Display a raster/tiled image (HEATMAP/RGB image, OSD's strength). */\n ImageDisplay = 'imageDisplay',\n /** 3D scene rendering (SURFACE, SCATTER3D, ISOSURFACE). */\n Surface3D = 'surface3d',\n /** Live colormap/LUT applied to a raw scalar matrix. */\n ScalarColormap = 'scalarColormap',\n /** Read back the displayed pixel matrix (getDisplayedPixelData). */\n PixelReadback = 'pixelReadback',\n /** Server re-fetch of a higher-res crop on zoom (vs native tiling). */\n HighDefZoom = 'highDefZoom',\n /** Per-z-plane slider over an image stack. */\n StackSlider = 'stackSlider',\n /** Live isosurface intensity bounds (isomin/isomax) — see IIsosurfaceControls. */\n Isosurface = 'isosurface',\n}\n\nexport interface ViewerCapabilities {\n has(feature: ViewerFeature): boolean;\n}\n\n/** Build a `ViewerCapabilities` from a fixed feature set. */\nexport function capabilitiesOf(features: Iterable<ViewerFeature>): ViewerCapabilities {\n const set = new Set<ViewerFeature>(features);\n return { has: (f: ViewerFeature) => set.has(f) };\n}\n","/**\n * Publication-critical types that were `any` on the public contracts\n * (refactoring plan, Step 6). Deliberately permissive — every field optional —\n * so existing hosts (which pass PrimeNG `TreeNode`s and plain option objects)\n * keep compiling unchanged while consumers finally get named shapes.\n */\n\n/** A colormap value as Plotly understands it: a built-in scale name (e.g.\n * 'Viridis') or an inline array of `[stop, color]` pairs. */\nexport type ColormapValue = string | Array<[number, string]>;\n\n/** One node of the colormap selector tree (structurally compatible with the\n * PrimeNG `TreeNode`s the host passes): group nodes carry `children`, leaf\n * nodes carry the scale in `data.value` (+ a preview image in `data.src`). */\nexport interface ColormapNode {\n label?: string;\n data?: { value?: ColormapValue; src?: string };\n children?: ColormapNode[];\n}\n\n/** Magic-wand pixel-comparison space. */\nexport type WandType = 'GRAY' | 'RGB' | 'LAB_DISTANCE';\n\n/** Options for the magic-wand tool (QuPath-style). */\nexport interface IWandOptions {\n type?: WandType;\n /** Gaussian sigma applied to the patch before thresholding. */\n sigma?: number;\n /** Higher = stricter (smaller selection) for GRAY/RGB; higher = looser for\n * LAB_DISTANCE — matches QuPath. */\n sensitivity?: number;\n /** Square patch size in pixels (must be odd). */\n patchSize?: number;\n /** When true, skip blur/threshold and flood-fill at exact-match\n * (Cmd/Ctrl-click in QuPath). */\n simpleMode?: boolean;\n}\n\n/** Options for the brush region tool (QuPath-style). */\nexport interface IBrushOptions {\n /** Brush diameter in matrix (image) pixels. */\n size?: number;\n}\n","/**\n * Contracts for the client-side, promptable Segment Anything (SAM) tooling\n * (jit-ui#90). A SAM model is a promptable encoder/decoder ONNX pair: the heavy\n * encoder runs once per image (its embedding is cached), and the light decoder\n * runs per prompt (box/points) to produce a mask.\n *\n * The inference backend is abstracted behind {@link ISamSession} so the tool\n * (SamToolService) is testable with a fake and so different runtimes (an\n * onnxruntime-web session today, a worker-backed one later) can be swapped in.\n */\n\n/** A promptable SAM model: a quantized encoder + decoder ONNX pair. */\nexport interface SamModelDef {\n /** Stable id used by the registry (e.g. 'microsam-vit-b-lm'). */\n id: string;\n /** Human label for a model picker. */\n label: string;\n /** Encoder ONNX URL (image → image embedding). Empty until hosted. */\n encoderUrl: string;\n /** Decoder ONNX URL (embedding + prompts → mask). Empty until hosted. */\n decoderUrl: string;\n /** Decoder I/O family — SAM v1 vs v2/v3 differ in mask output size + names. */\n variant: 'sam1' | 'sam2' | 'sam3';\n /** Encoder input side length (1024 for SAM v1). */\n inputSize: number;\n /** True for microscopy-finetuned checkpoints (micro-sam, pathoSAM). */\n microscopy?: boolean;\n /** Override the onnxruntime-web execution providers for the ENCODER session\n * (decoder is always WASM). Defaults to WebGPU-with-WASM-fallback. Set to\n * `['wasm']` for architectures whose fp16 attention overflows on the WebGPU\n * EP and returns an empty mask (e.g. micro-sam ViT-T's TinyViT encoder),\n * which run correctly — and fast, when small — on WASM. */\n encoderProviders?: string[];\n /** Run inference in-process on the main thread instead of the SAM Web Worker.\n * Only valid for small WASM-only models (e.g. micro-sam ViT-T) where the\n * worker's spawn + second-ORT-runtime + message overhead outweighs its\n * off-thread benefit. WebGPU models ignore this (they must stay in the\n * worker to avoid freezing the tab). */\n inProcess?: boolean;\n}\n\n/** Cached encoder output for one image (reused across every prompt on it). */\nexport interface SamEmbedding {\n /** Flattened embedding tensor, shape `dims`. */\n data: Float32Array;\n /** Embedding tensor dims, e.g. [1, 256, 64, 64]. */\n dims: number[];\n /** `inputSize / max(imageWidth, imageHeight)` — scales prompt coords. */\n scale: number;\n /** Image (matrix) size the embedding was computed for. */\n imageWidth: number;\n imageHeight: number;\n /** Opaque handle to the embedding cached inside the inference Web Worker, when\n * the session runs off-thread. `decode` passes it back so the worker reuses\n * the cached tensor instead of round-tripping the (multi-MB) embedding data;\n * `data` is then an empty placeholder. Absent for in-process/fake sessions. */\n token?: number;\n}\n\n/** A prompt for one object, in image (matrix) pixel coordinates. */\nexport interface SamPrompt {\n /** Box prompt `[x0,y0,x1,y1]` (issue #90's primary affordance). */\n box?: { x0: number; y0: number; x1: number; y1: number };\n /** Point prompts; `label` 1 = positive (include), 0 = negative (exclude). */\n points?: { x: number; y: number; label: 0 | 1 }[];\n}\n\n/** A decoded mask, binary (0/1), at image (matrix) resolution. */\nexport interface SamMaskResult {\n mask: Uint8Array;\n width: number;\n height: number;\n /** Model-predicted IoU quality score for the chosen mask. */\n iou: number;\n}\n\n/**\n * Promptable-SAM inference backend. Lifecycle: `loadModel` once, `embed` once\n * per image, `decode` per prompt.\n */\nexport interface ISamSession {\n /** Load the model; `onProgress` reports encoder-download fraction (0..1). */\n loadModel(model: SamModelDef, onProgress?: (fraction: number) => void): Promise<void>;\n isLoaded(): boolean;\n /** Run the encoder on an RGBA image; returns a cacheable embedding. */\n embed(image: { data: Uint8ClampedArray; width: number; height: number }): Promise<SamEmbedding>;\n /** Run the decoder for one prompt against a cached embedding. */\n decode(embedding: SamEmbedding, prompt: SamPrompt): Promise<SamMaskResult>;\n dispose(): void;\n}\n","/**\n * Shared base URL/path for onnxruntime-web's WASM sidecar files\n * (`ort-wasm-simd-threaded.wasm` / `.jsep.mjs`), used by every ONNX-model tool\n * in the library: SAM (in-process and worker) and Cellpose-SAM.\n *\n * Defaults to `'/assets/ort/'` — a host that serves onnxruntime-web's `dist`\n * WASM files there (as jit-ui does via its `project.json` asset glob) needs no\n * configuration and behaves exactly as before this knob existed. A host that\n * cannot serve them at that path — e.g. a static deployment behind an auth\n * proxy, or one that prefers a CDN — calls {@link setOrtWasmBase} ONCE at app\n * init to point the runtime elsewhere:\n *\n * ```ts\n * // version MUST match the onnxruntime-web the library was built against\n * setOrtWasmBase('https://cdn.jsdelivr.net/npm/onnxruntime-web@1.26.0/dist/');\n * ```\n *\n * Must be set before the first segmentation runs; the value is read at use time\n * by each tool (and passed into the SAM worker via its load message), so a\n * single call at bootstrap covers SAM and Cellpose alike.\n */\nlet ortWasmBase = '/assets/ort/';\n\n/** Override where onnxruntime-web loads its WASM sidecars from. See module docs. */\nexport function setOrtWasmBase(base: string): void {\n ortWasmBase = base;\n}\n\n/** The configured onnxruntime-web WASM base (default `'/assets/ort/'`). */\nexport function getOrtWasmBase(): string {\n return ortWasmBase;\n}\n","import { Injectable } from '@angular/core';\nimport { getOrtWasmBase } from './ort-runtime-config';\n\nimport type { ICellSegmenter, CellSegmentation, CellSegmentProgress } from '../../contracts/cell-segmenter.contract';\nimport type { Cellpose } from 'cellpose-js';\n\n/** Hosted cellpose-SAM ONNX (CPSAM, fp16). Override via {@link setModelUrl}. */\nconst DEFAULT_MODEL_URL =\n 'https://huggingface.co/ballon999/cellpose-sam-onnx/resolve/main/cpsam_fp16.onnx';\n\n/**\n * Default in-library {@link ICellSegmenter} backed by cellpose-js (WebGPU/WASM\n * ONNX) — so the toolbar's automatic **Cellpose** tool works out of the box in\n * any app, with no host wiring (jit-ui#90). `cellpose-js` is a peer dependency\n * and is **lazy-imported** on first use, so apps that never run Cellpose pay\n * nothing for it. A host can still override the {@link CELL_SEGMENTER} token to\n * supply a different implementation.\n *\n * Owns a single shared {@link Cellpose} instance (one model load, one WebGPU\n * session, one worker). {@link getModel} exposes that instance so a host's\n * processing pipeline can reuse it instead of loading the ~588 MB model twice.\n */\n@Injectable({ providedIn: 'root' })\nexport class CellposeSegmenterService implements ICellSegmenter {\n private instance: Cellpose | null = null;\n private loading: Promise<Cellpose> | null = null;\n private modelUrl = DEFAULT_MODEL_URL;\n\n /** Point the segmenter at a different hosted CPSAM ONNX (before first use). */\n setModelUrl(url: string): void {\n this.modelUrl = url;\n }\n\n async segmentCells(\n image: { data: Uint8ClampedArray; width: number; height: number },\n progress?: CellSegmentProgress,\n ): Promise<CellSegmentation> {\n let announcedDownload = false;\n const cp = await this.getModel(\n (loaded, total) => {\n if (total) progress?.onProgress?.(loaded / total);\n if (loaded > 0 && !announcedDownload) {\n announcedDownload = true;\n progress?.onStatus?.('Downloading Cellpose-SAM model…');\n }\n },\n (status) => progress?.onStatus?.(status),\n );\n progress?.onStatus?.('Preprocessing image…');\n const out = await cp.segment(\n { data: image.data, width: image.width, height: image.height, channels: 4 },\n {\n // cellpose-js runs inference in its worker (these fire between tiles) and\n // averaging/dynamics on the main thread; surface both so the toast shows\n // real progress instead of looking stuck.\n onTileProgress: (done, total) => progress?.onStatus?.(\n done < total ? `Running inference (tile ${done}/${total})…` : 'Computing flow dynamics…',\n ),\n },\n );\n return { labels: out.masks, width: out.width, height: out.height, count: out.count };\n }\n\n /**\n * The shared Cellpose instance, lazily created on first use and reused\n * thereafter (deduped across concurrent callers). Exposed so a host pipeline\n * engine can run richer `segment()` options on the same instance. `onProgress`\n * reports raw downloaded/total bytes (`total` is null when unknown); `onStatus`\n * reports worker-init phase strings.\n */\n getModel(\n onProgress?: (loaded: number, total: number | null) => void,\n onStatus?: (status: string) => void,\n ): Promise<Cellpose> {\n if (this.instance) return Promise.resolve(this.instance);\n if (!this.loading) {\n this.loading = (async () => {\n // Lazy: keep cellpose-js + its ORT runtime out of the initial bundle.\n const { Cellpose, configureOrt } = await import('cellpose-js');\n configureOrt({ wasmPaths: getOrtWasmBase() });\n const cp = await Cellpose.fromPretrained(this.modelUrl, {\n preload: true,\n onProgress: ({ loaded, total }) => onProgress?.(loaded, total),\n onStatus: (s) => onStatus?.(s),\n });\n this.instance = cp;\n return cp;\n })();\n }\n return this.loading;\n }\n\n /** Whether the shared model is already loaded (warm). */\n isLoaded(): boolean {\n return this.instance !== null;\n }\n}\n","import { InjectionToken, inject } from '@angular/core';\n\nimport { CellposeSegmenterService } from '../toolbar/segmentation/cellpose-segmenter.service';\n\n/**\n * Result of an automatic cell segmenter: a per-pixel instance label map for the\n * input image (0 = background, 1..count = instances), row-major.\n */\nexport interface CellSegmentation {\n labels: Uint32Array;\n width: number;\n height: number;\n count: number;\n}\n\n/**\n * Port for an automatic (prompt-free) cell segmenter — e.g. cellpose-SAM. The\n * library calls this on a client slide-crop of a drawn box. By default the\n * {@link CELL_SEGMENTER} token resolves to the library's own cellpose-js-backed\n * {@link CellposeSegmenterService} (so the toolbar Cellpose tool works out of the\n * box), but a host can override the token to supply a different implementation\n * (e.g. a server-side segmenter) (jit-ui#90).\n */\n/** Progress/status callbacks for a segmentation run (all optional). */\nexport interface CellSegmentProgress {\n /** Model-download progress, 0..1 (first run only). */\n onProgress?: (fraction: number) => void;\n /** Human-readable phase, e.g. 'Running inference (tile 3/8)…'. */\n onStatus?: (status: string) => void;\n}\n\nexport interface ICellSegmenter {\n /** Segment all cells in an RGBA image into an instance label map. */\n segmentCells(\n image: { data: Uint8ClampedArray; width: number; height: number },\n progress?: CellSegmentProgress,\n ): Promise<CellSegmentation>;\n}\n\n/**\n * DI token for the automatic cell segmenter. Defaults to the in-library\n * {@link CellposeSegmenterService} (cellpose-js, lazy-loaded); override it in the\n * host to swap implementations.\n */\nexport const CELL_SEGMENTER = new InjectionToken<ICellSegmenter>('CELL_SEGMENTER', {\n providedIn: 'root',\n factory: () => inject(CellposeSegmenterService),\n});\n","/**\n * Unified image container used throughout the processing pipeline.\n * Decouples pipeline logic from any specific library's image format.\n */\nexport class ProcessingImage {\n readonly width: number;\n readonly height: number;\n readonly channels: number;\n readonly data: Uint8ClampedArray;\n\n /** Create from browser ImageData. */\n static fromImageData(imageData: ImageData): ProcessingImage {\n return new ProcessingImage(imageData.width, imageData.height, 4,\n new Uint8ClampedArray(imageData.data));\n }\n\n constructor(width: number, height: number, channels: number, data: Uint8ClampedArray) {\n this.width = width;\n this.height = height;\n this.channels = channels;\n this.data = data;\n }\n\n /** Convert to browser-native ImageData (RGBA). */\n toImageData(): ImageData {\n if (this.channels === 4) {\n return new ImageData(this.data, this.width, this.height);\n }\n // Expand grayscale or RGB to RGBA\n const rgba = new Uint8ClampedArray(this.width * this.height * 4);\n for (let i = 0; i < this.width * this.height; i++) {\n if (this.channels === 1) {\n rgba[i * 4] = this.data[i];\n rgba[i * 4 + 1] = this.data[i];\n rgba[i * 4 + 2] = this.data[i];\n } else if (this.channels === 3) {\n rgba[i * 4] = this.data[i * 3];\n rgba[i * 4 + 1] = this.data[i * 3 + 1];\n rgba[i * 4 + 2] = this.data[i * 3 + 2];\n }\n rgba[i * 4 + 3] = 255;\n }\n return new ImageData(rgba, this.width, this.height);\n }\n\n /** Convert to Blob for saving/downloading. */\n async toBlob(mime: string = 'image/png'): Promise<Blob> {\n const canvas = document.createElement('canvas');\n canvas.width = this.width;\n canvas.height = this.height;\n const ctx = canvas.getContext('2d')!;\n ctx.putImageData(this.toImageData(), 0, 0);\n return new Promise((resolve) => {\n canvas.toBlob((blob) => resolve(blob!), mime);\n });\n }\n}\n","import { ProcessingImage } from './processing-image';\n\n/** Crop options in source-image pixels. Out-of-range values are clamped. */\nexport interface CropImageOptions {\n x?: number;\n y?: number;\n width?: number;\n height?: number;\n /** Power-of-two downsample level applied to the crop (0 = full resolution). */\n level?: number;\n}\n\n/** Copy a clamped rectangle of an RGBA source into a fresh, tightly-packed buffer. */\nfunction cropRgba(\n src: Uint8ClampedArray, srcWidth: number, srcHeight: number,\n x: number, y: number, w: number, h: number,\n): { data: Uint8ClampedArray; width: number; height: number } {\n // Clamp the rectangle to the image so bad params snap to the valid region\n // instead of reading out of bounds.\n const x0 = Math.max(0, Math.min(srcWidth - 1, Math.floor(x)));\n const y0 = Math.max(0, Math.min(srcHeight - 1, Math.floor(y)));\n const width = Math.max(1, Math.min(srcWidth - x0, Math.floor(w)));\n const height = Math.max(1, Math.min(srcHeight - y0, Math.floor(h)));\n const out = new Uint8ClampedArray(width * height * 4);\n for (let row = 0; row < height; row++) {\n const srcRow = (y0 + row) * srcWidth + x0;\n const dstRow = row * width;\n for (let col = 0; col < width; col++) {\n const si = (srcRow + col) * 4;\n const di = (dstRow + col) * 4;\n out[di] = src[si] as number;\n out[di + 1] = src[si + 1] as number;\n out[di + 2] = src[si + 2] as number;\n out[di + 3] = src[si + 3] as number;\n }\n }\n return { data: out, width, height };\n}\n\n/** Nearest-neighbour downsample by an integer factor (≥1). factor=1 is a no-op. */\nfunction downsampleRgba(\n src: Uint8ClampedArray, srcWidth: number, srcHeight: number, factor: number,\n): { data: Uint8ClampedArray; width: number; height: number } {\n if (factor <= 1) return { data: src, width: srcWidth, height: srcHeight };\n const width = Math.max(1, Math.floor(srcWidth / factor));\n const height = Math.max(1, Math.floor(srcHeight / factor));\n const out = new Uint8ClampedArray(width * height * 4);\n for (let row = 0; row < height; row++) {\n const sy = Math.min(srcHeight - 1, row * factor);\n for (let col = 0; col < width; col++) {\n const sx = Math.min(srcWidth - 1, col * factor);\n const si = (sy * srcWidth + sx) * 4;\n const di = (row * width + col) * 4;\n out[di] = src[si] as number;\n out[di + 1] = src[si + 1] as number;\n out[di + 2] = src[si + 2] as number;\n out[di + 3] = src[si + 3] as number;\n }\n }\n return { data: out, width, height };\n}\n\n/**\n * Crop a rectangular region out of a {@link ProcessingImage} (browser-side, the\n * counterpart of the JIT server's Slide Crop), optionally downsampling the crop\n * by `2^level`. The rectangle is in source pixels and clamped to the image, so\n * out-of-range values snap to the valid region rather than throwing. Always\n * returns a 4-channel (RGBA) image.\n */\nexport function cropImage(image: ProcessingImage, opts: CropImageOptions = {}): ProcessingImage {\n // Work on RGBA so the crop is channel-count agnostic.\n const src = image.channels === 4 ? image.data : image.toImageData().data;\n const cropped = cropRgba(\n src, image.width, image.height,\n Number(opts.x ?? 0), Number(opts.y ?? 0),\n Number(opts.width ?? image.width), Number(opts.height ?? image.height),\n );\n const level = Math.max(0, Math.floor(Number(opts.level ?? 0)));\n const factor = level > 0 ? 2 ** level : 1;\n const final = downsampleRgba(cropped.data, cropped.width, cropped.height, factor);\n return new ProcessingImage(final.width, final.height, 4, final.data);\n}\n","import { Injectable } from '@angular/core';\nimport { ProcessingImage } from './processing-image';\n\n/**\n * Converts between various image representations. Bridges image-js, browser\n * canvas/image elements, and the neutral {@link ProcessingImage}. Generic image\n * plumbing — no app/pipeline coupling.\n */\n@Injectable({ providedIn: 'root' })\nexport class ImageConverterService {\n /**\n * Convert an image-js Image instance to ProcessingImage.\n * image-js stores pixel data in a typed array with shape (width*height*channels).\n */\n fromImageJs(image: any): ProcessingImage {\n const width = image.width as number;\n const height = image.height as number;\n const channels = image.channels as number;\n\n // image-js data is Uint8Array or Uint16Array; normalize to Uint8ClampedArray\n let data: Uint8ClampedArray;\n if (image.bitDepth > 8) {\n // Normalize 16-bit to 8-bit\n const src = image.data as Uint16Array;\n const max = (1 << image.bitDepth) - 1;\n data = new Uint8ClampedArray(src.length);\n for (let i = 0; i < src.length; i++) {\n data[i] = Math.round((src[i] / max) * 255);\n }\n } else {\n data = new Uint8ClampedArray(image.data);\n }\n\n return new ProcessingImage(width, height, channels, data);\n }\n\n /** Convert from an HTMLCanvasElement. */\n fromCanvas(canvas: HTMLCanvasElement): ProcessingImage {\n const ctx = canvas.getContext('2d')!;\n const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n return ProcessingImage.fromImageData(imageData);\n }\n\n /** Convert from an HTMLImageElement. */\n fromHtmlImage(img: HTMLImageElement): ProcessingImage {\n const canvas = document.createElement('canvas');\n canvas.width = img.naturalWidth;\n canvas.height = img.naturalHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n return this.fromCanvas(canvas);\n }\n\n /** Convert ProcessingImage to a 2D array suitable for Plotly heatmap (grayscale). */\n toPlotlyHeatmapZ(image: ProcessingImage): number[][] {\n const z: number[][] = [];\n for (let y = 0; y < image.height; y++) {\n const row: number[] = [];\n for (let x = 0; x < image.width; x++) {\n const idx = (y * image.width + x) * image.channels;\n row.push(image.data[idx]);\n }\n z.push(row);\n }\n return z;\n }\n\n /** Convert ProcessingImage to Plotly RGB arrays [r[][], g[][], b[][]]. */\n toPlotlyRgbArrays(image: ProcessingImage): { r: number[][]; g: number[][]; b: number[][] } {\n const r: number[][] = [];\n const g: number[][] = [];\n const b: number[][] = [];\n for (let y = 0; y < image.height; y++) {\n const rRow: number[] = [];\n const gRow: number[] = [];\n const bRow: number[] = [];\n for (let x = 0; x < image.width; x++) {\n const idx = (y * image.width + x) * image.channels;\n rRow.push(image.data[idx]);\n gRow.push(image.data[idx + 1]);\n bRow.push(image.data[idx + 2]);\n }\n r.push(rRow);\n g.push(gRow);\n b.push(bRow);\n }\n return { r, g, b };\n }\n}\n","import { SamModelDef } from '../../contracts/sam.contract';\n\n/**\n * Registry of promptable SAM models for the browser segment tool.\n *\n * micro-sam (microscopy-finetuned, promptable) and patho-sam (histopathology-\n * finetuned) are entries; SAM3 slots in here once its quantized ONNX export and\n * a `variant: 'sam3'` decoder path are published. The\n * automatic cellpose-SAM model is intentionally NOT here — it's not promptable\n * and lives in the processing-pipeline's cellpose engine as the automatic tool.\n *\n * `encoderUrl` / `decoderUrl` point at the public HF-hosted ONNX pairs by\n * default, so the segment tools work out of the box in any host (mirroring the\n * cellpose default). A host can repoint them at its own hosting (e.g. a GCS\n * bucket) at runtime via {@link setSamModelUrls}; an empty URL disables a model\n * (the session throws a clear \"not configured\" error). Export/quantization\n * tooling: the sibling `browser-onnx-tools` project; see docs/sam-segmentation-design.md.\n */\nexport const SAM_MODELS: SamModelDef[] = [\n {\n id: 'microsam-vit-t-lm',\n label: 'micro-sam ViT-T',\n encoderUrl: 'https://huggingface.co/Ballon999/microsam-vit-t-lm-onnx/resolve/main/encoder.fp16.onnx',\n decoderUrl: 'https://huggingface.co/Ballon999/microsam-vit-t-lm-onnx/resolve/main/decoder.onnx',\n variant: 'sam1',\n inputSize: 1024,\n microscopy: true,\n // TinyViT's fp16 attention overflows on the onnxruntime-web WebGPU EP and\n // returns an empty mask (\"No masks found\"); it's numerically correct on\n // WASM, and the encoder is tiny (~14 MB) so WASM is plenty fast.\n encoderProviders: ['wasm'],\n // Small enough to run in-process on the main thread — avoids the Web\n // Worker's spawn / second-ORT-runtime / round-trip overhead, which made it\n // noticeably slower to load and segment.\n inProcess: true,\n },\n {\n id: 'microsam-vit-b-lm',\n label: 'micro-sam ViT-B',\n encoderUrl: 'https://huggingface.co/Ballon999/microsam-vit-b-lm-onnx/resolve/main/encoder.fp16.onnx',\n decoderUrl: 'https://huggingface.co/Ballon999/microsam-vit-b-lm-onnx/resolve/main/decoder.onnx',\n variant: 'sam1',\n inputSize: 1024,\n microscopy: true,\n },\n {\n id: 'patho-sam-vit-b',\n label: 'patho-sam ViT-B',\n encoderUrl: 'https://huggingface.co/Ballon999/patho-sam-vit-b-onnx/resolve/main/encoder.fp16.onnx',\n decoderUrl: 'https://huggingface.co/Ballon999/patho-sam-vit-b-onnx/resolve/main/decoder.onnx',\n variant: 'sam1',\n inputSize: 1024,\n microscopy: true,\n },\n {\n id: 'patho-sam-vit-b-int8',\n label: 'patho-sam ViT-B (int8)',\n encoderUrl: 'https://huggingface.co/Ballon999/patho-sam-vit-b-onnx/resolve/main/encoder.int8.onnx',\n decoderUrl: 'https://huggingface.co/Ballon999/patho-sam-vit-b-onnx/resolve/main/decoder.onnx',\n variant: 'sam1',\n inputSize: 1024,\n microscopy: true,\n // int8 dynamic-quantized encoder (~100 MB vs ~180 MB fp16, IoU ~0.99 on the\n // sanity test). onnxruntime-web's WebGPU EP doesn't support int8 matmul, so\n // it runs on WASM — smaller download, slower encode than the fp16 entry.\n encoderProviders: ['wasm'],\n },\n];\n\n/** Initial default model id (overridden at runtime once the host configures a\n * hosted model via {@link setSamModelUrls}). */\nexport const DEFAULT_SAM_MODEL_ID = SAM_MODELS[0].id;\n\n/** The active default — updated when the host configures a model's ONNX URLs,\n * so the tool uses the model that's actually hosted (not just the first entry). */\nlet activeDefaultId = DEFAULT_SAM_MODEL_ID;\n\n/** Look up a model by id; falls back to the active default when id is\n * unknown/absent. */\nexport function getSamModel(id?: string): SamModelDef {\n const wanted = id ?? activeDefaultId;\n return SAM_MODELS.find((m) => m.id === wanted) ?? SAM_MODELS[0];\n}\n\n/** The active default model id (what the tools/picker use when unset). */\nexport function getDefaultSamModelId(): string {\n return activeDefaultId;\n}\n\n/** Set the active default model id (must be a registered model). */\nexport function setDefaultSamModel(id: string): void {\n if (SAM_MODELS.some((m) => m.id === id)) activeDefaultId = id;\n}\n\n/** True when a model has both ONNX URLs configured (i.e. it can actually run). */\nexport function isSamModelReady(model: SamModelDef): boolean {\n return !!model.encoderUrl && !!model.decoderUrl;\n}\n\n/**\n * Point a registered model at its hosted ONNX pair (HF / GCS). Called by the\n * host's composition root once hosting is decided, keeping deployment URLs out\n * of the library.\n */\nexport function setSamModelUrls(id: string, encoderUrl: string, decoderUrl: string): void {\n const m = SAM_MODELS.find((x) => x.id === id);\n if (m) {\n m.encoderUrl = encoderUrl;\n m.decoderUrl = decoderUrl;\n // The configured (hosted) model becomes the active default, so the tools\n // use it rather than the first registry entry (which may be unhosted).\n if (encoderUrl && decoderUrl) activeDefaultId = id;\n }\n}\n","import { Region, Polygon, Rectangle } from './region';\nimport { Datum, Font, Shape, ShapeLabel, ShapeLine, XAxisName, YAxisName } from 'plotly.js-dist-min';\n\nexport class ShapeSelection implements Shape {\n\n /** Stable, unique identity carried alongside the shape so it round-trips\n * through Plotly's relayout untouched. Plotly preserves unknown\n * properties on shape objects, so this survives the same way `legend`\n * and `fileName` already do. */\n id!: number;\n name!: string;\n fillcolor!: string;\n // label takes the form\n // { text: legend, texttemplate: legend, font: { color: '#FFF000' }, textposition: 'top left' }\n // or can be an empty object {} if no label is to be shown\n label!: Partial<ShapeLabel>;\n layer!: 'below' | 'above';\n legendgroup!: string;\n legendgrouptitle!: { text: string; font?: Partial<Font> };\n legendrank!: number;\n line!: Partial<ShapeLine>;\n opacity!: number;\n path!: string;\n showlegend!: boolean;\n templateitemname!: string;\n type!: 'rect' | 'circle' | 'line' | 'path';\n visible!: boolean | 'legendonly';\n x0!: Datum;\n x1!: Datum;\n xanchor!: number | string;\n xref!: 'paper' | XAxisName;\n xsizemode!: 'scaled' | 'pixel';\n y0!: Datum;\n y1!: Datum;\n yanchor!: number | string;\n yref!: 'paper' | YAxisName;\n ysizemode!: 'scaled' | 'pixel';\n editable = true;\n // legend text for the region (used for classes) - value used in label.text and label.texttemplate\n legend!: any;\n // file name of the file for which the region was created\n fileName!: string | undefined;\n // tags an intensity-profile line ROI so it round-trips through Plotly and the\n // region store as a profile (excluded from the Regions tab + exports).\n kind?: 'profile';\n\n /**\n * Returns a Region object based on the shape type.\n */\n public getRegion(): Region {\n const region = new Region();\n region.id = this.id;\n region.name = this.name;\n // The region's colour lives on line.color (see Region.getShape); fillcolor\n // is only set for the active-shape highlight. Restore the class label from\n // legend too. Without these, getRegions() — which the OSD region overlay\n // renders from — returned undefined colour AND label, so OSD drew every\n // region in the default colour with no label (unlike Plotly, which renders\n // its shape array directly).\n region.color = this.line?.color ?? this.fillcolor;\n region.label = this.legend;\n if (this.kind === 'profile') region.kind = 'profile';\n if (this.type === 'rect') {\n region.bounds = new Rectangle();\n region.bounds.x = this.x0 as number;\n region.bounds.y = this.y0 as number;\n region.bounds.width = (this.x1 as number) - (this.x0 as number);\n region.bounds.height = (this.y1 as number) - (this.y0 as number);\n } else if (this.type === 'path') {\n region.bounds = new Polygon();\n const isClosed = this.path.endsWith('Z');\n const spath = isClosed ? this.path.slice(1, -1) : this.path.slice(1); // remove M and optionally Z\n const spoints = spath.split('L');\n region.bounds.npoints = spoints.length;\n region.bounds.xpoints = [];\n region.bounds.ypoints = [];\n region.bounds.coordinates = [];\n region.bounds.closed = isClosed;\n for (const point of spoints) {\n const coords = point.split(',');\n region.bounds.xpoints.push(parseFloat(coords[0]));\n region.bounds.ypoints.push(parseFloat(coords[1]));\n region.bounds.coordinates.push([parseFloat(coords[0]), parseFloat(coords[1])]);\n }\n } else {\n throw new Error(`Unsupported shape type: ${this.type}`);\n }\n return region;\n }\n}\n","import { ShapeSelection } from './shape';\n\nexport class Region {\n\n /** Stable, unique identity for selection and equality. Minted by\n * PlotlyService when a region first enters the system. Never derived\n * from array index — name collisions across delete/add cycles must\n * not break PrimeNG row selection. */\n id!: number;\n name!: string;\n bounds?: Rectangle | Polygon | MultiPolygon | null = null;\n /** profile = an intensity-profile line ROI; rendered/dragged like a region but\n * excluded from the Regions tab and exports. Use `isProfile()` to test it —\n * it's the canonical marker that separates intensity lines (owned by the\n * intensity tool, sampled into the inset) from annotation regions (owned by\n * the Region Editor). Both backends (Plotly, OSD) honour it. */\n kind?: 'profile';\n color?: string; // hex string, e.g. '#RRGGBB' (the historical \"[r, g, b]\" note is stale)\n // class label\n label?: string;\n /** True when the user set this region's colour explicitly (Region Editor Color\n * column). Preset colour resolution (jit-ui#70) skips overridden regions so a\n * manual colour is not clobbered when presets are (re)applied on load/import. */\n colorOverridden?: boolean;\n filename?: string;\n /** Zero-based z-slice this region belongs to within a stack — mirrors\n * QuPath's `geometry.plane.z` (a missing plane / default plane reads back as\n * 0). Used to place/filter ROIs per slice; 0 for a plain single-plane image\n * or a region drawn without a slice context (jit-ui#93). */\n z = 0;\n shapeColor? = '#00FFFF';\n bytesPerPixel = 8;\n /**\n * resolution is the resolution at which the region\n * was found. In order to get it in the full image\n * coordinates it will normally be 0. However if\n * there is a mistake with the resolution it may not\n * be. We return the resolution here in order to be\n * sure what it is. The server may need to be changed\n * to ensure that results regions are always returned\n * at resolution = 0\n */\n resolution = 0;\n cropped = false;\n tileNumber = 0;\n tileCoordinates: number[] | null = null;\n\n /** True for intensity-profile line ROIs (the intensity tool's lines). These are\n * NOT annotation regions: they never appear in the Region Editor and editor\n * operations (select/save/delete) must never touch them. */\n isProfile(): boolean {\n return this.kind === 'profile';\n }\n\n toString() {\n // if shape is rectangle\n if (this.bounds instanceof Rectangle) {\n return `x: ${this.bounds.x}, y: ${this.bounds.y},\n width: ${this.bounds.width}, height: ${this.bounds.height}`;\n } else if (this.bounds instanceof Polygon){\n let path = 'M';\n // display as path\n for (let i = 0; i < this.bounds.npoints; i++) {\n if (i < this.bounds.npoints - 1) {\n path = `${path}${this.bounds.xpoints[i]},${this.bounds.ypoints[i]}L`;\n } else {\n path = `${path}${this.bounds.xpoints[i]},${this.bounds.ypoints[i]}`;\n }\n }\n if (this.bounds.closed !== false) {\n path += 'Z';\n }\n return path;\n }\n return '';\n }\n\n /**\n * Returns a ShapeSelection object that can be used to\n * create a shape in Plotly.\n * @param showRegionLabel\n * @return ShapeSelection\n */\n getShape(showRegionLabel: boolean = true): ShapeSelection {\n const shape = new ShapeSelection();\n shape.id = this.id;\n shape.name = this.name;\n shape.editable = true;\n shape.line = {\n color: this.color ? this.color : this.shapeColor,\n width: 3\n };\n shape.fileName = this.filename;\n if (this.kind === 'profile') shape.kind = 'profile';\n if (showRegionLabel) {\n shape.label = {\n text: `${this.label}`,\n texttemplate: `${this.label}`,\n font: { color: this.color ? this.color : this.shapeColor },\n textposition: 'top left'\n };\n } else {\n shape.label = {};\n }\n shape.legend = this.label;\n\n const bnds = this.bounds;\n if (bnds != undefined) {\n if (this.isRectangle(bnds)) {\n shape.type = 'rect';\n shape.x0 = bnds.x;\n shape.y0 = bnds.y;\n shape.x1 = bnds.x + bnds.width;\n shape.y1 = bnds.y + bnds.height;\n }\n if (this.isPolygon(bnds)) {\n shape.type = 'path';\n let path = 'M';\n for (let i = 0; i < bnds.npoints; i++) {\n if (i < bnds.npoints - 1) {\n path = `${path}${bnds.xpoints[i]},${bnds.ypoints[i]}L`;\n } else {\n path = `${path}${bnds.xpoints[i]},${bnds.ypoints[i]}`;\n }\n }\n if (bnds.closed !== false) {\n path += 'Z';\n }\n shape.path = path;\n }\n }\n return shape;\n }\n\n isRectangle(bnds: any): bnds is Rectangle {\n return 'x' in bnds && 'y' in bnds && 'width' in bnds && 'height' in bnds;\n }\n\n isPolygon(bnds: any): bnds is Polygon {\n return 'npoints' in bnds && 'xpoints' in bnds && 'ypoints' in bnds;\n }\n}\n\nexport class Rectangle {\n x = 0;\n y = 0;\n width = 0;\n height = 0;\n}\n\nexport class Polygon {\n npoints = 0;\n xpoints: number[] = [];\n ypoints: number[] = [];\n coordinates: number[][] = [];\n /** false for open polylines; true (default) for closed polygons */\n closed = true;\n /**\n * When true the vertices are treated as bezier-spline **anchors** and the\n * region is rendered/exported as a smooth curve through them. The vertices\n * stay the editable anchors — toggling this flag is the toBezier\n * (`true`) / toPolygon (`false`), which only add/remove the curve, never move\n * the anchors. GeoJSON keeps the flattened curve as the geometry (so QuPath\n * renders it) plus the anchors + handles + flag in properties (so JIT\n * round-trips the editable bezier).\n */\n bezier = false;\n /**\n * Per-anchor cubic-bezier control-point offsets, **relative** to their anchor\n * (so they translate with it). Present only for bezier regions; initialised\n * from the Catmull-Rom construction (a smooth curve) when bezier is turned on,\n * then individually editable by dragging the handles. `handlesIn[i]` /\n * `handlesOut[i]` are `[dx, dy]` for vertex `i`.\n */\n handlesIn?: number[][];\n handlesOut?: number[][];\n\n /**\n * Interior rings (holes) — jit-ui#85. Each ring is a list of `[x, y]`\n * image-pixel pairs in the SAME closed-polygon convention as the exterior\n * (`coordinates`): no repeated closing point. Present only on closed polygons.\n * A point inside the exterior **and** inside any hole is OUTSIDE the region\n * (even-odd rule). Absent/empty == a solid polygon (the prior behaviour), so\n * every existing region is unaffected.\n */\n holes?: number[][][];\n\n /**\n * Per-hole bézier control-point offsets, parallel to {@link holes} (one entry per ring, each a\n * list of `[dx, dy]` per ring vertex, **relative** to the vertex). Present only when `bezier` is\n * on for a donut — seeded from the Catmull-Rom default and individually editable, exactly like\n * the exterior {@link handlesIn}/{@link handlesOut}. So a donut smoothed to a bézier curves its\n * holes too (jit-ui#102).\n */\n holeHandlesIn?: number[][][];\n holeHandlesOut?: number[][][];\n}\n\n/**\n * A region whose geometry is several disjoint parts — e.g. the result of merging\n * two non-touching regions, or the inverse of a blob (jit-ui#85). Each part is a\n * closed {@link Polygon} that may carry its own holes, so a MultiPolygon\n * represents \"sparse bits, some with donut holes\" as a single region. Maps 1:1\n * onto a GeoJSON `MultiPolygon` (and QuPath's geometry).\n *\n * A single-part MultiPolygon is equivalent to that Polygon; callers should\n * prefer a plain {@link Polygon} for one connected part.\n */\nexport class MultiPolygon {\n /** One or more disjoint closed polygons (each may have holes). */\n polygons: Polygon[] = [];\n}\n\nexport type Bounds = Rectangle | Polygon | {\n x?: number;\n y?: number;\n width?: number;\n height?: number;\n npoints?: number;\n xpoints?: number[];\n ypoints?: number[];\n};\n","/**\n * Preset annotation classes (jit-ui#70).\n *\n * A class is a flat `{ name, color }` pair (v1: no hierarchy, no special-class semantics).\n * The `PresetSet` is the per-user, server-persisted source of truth for region colours;\n * see `class-color.util.ts` for the deterministic colour-resolution engine.\n */\n\nexport type PresetSource = 'user' | 'default' | 'auto';\n\nexport interface ClassPreset {\n /** The class name — matched against `Region.label`. */\n name: string;\n /** Hex colour, `#RRGGBB`. */\n color: string;\n /** Reserved for a future per-class overlay-visibility toggle. */\n visible?: boolean;\n /** Provenance; `'auto'` = added by opt-in fallback promotion. */\n source?: PresetSource;\n}\n\nexport type MatchMode = 'exact' | 'normalized';\n\nexport interface PresetSet {\n /** Ordered list of preset classes. */\n classes: ClassPreset[];\n /** Colours used for classes not in `classes` (assigned deterministically). */\n fallbackPalette: string[];\n /** Opt-in (default false): add an unknown class to `classes` the first time it is seen. */\n autoPromote: boolean;\n /** Label matching against `Region.label` (default `'exact'`). */\n matchMode: MatchMode;\n}\n\n/**\n * Fallback palette for classes not present in the preset set — reasonably distinct hues.\n * Colours are assigned by a stable hash of the class name, so the same unknown class always\n * gets the same colour with no stored state.\n */\nexport const DEFAULT_FALLBACK_PALETTE: string[] = [\n '#6C8EBF', '#82B366', '#B85450', '#9673A6', '#D79B00',\n '#3C948B', '#A64CA6', '#CC6677', '#4477AA', '#228833',\n];\n\n/** Seed classes — mirrors the historical hard-coded `classificationColors` map. */\nconst DEFAULT_CLASSES: ClassPreset[] = [\n { name: 'Fragmented-embryo', color: '#FF8C00', source: 'default' },\n { name: 'Dying-embryo', color: '#FF3333', source: 'default' },\n { name: 'Two-cell-embryo', color: '#33CC66', source: 'default' },\n { name: 'One-cell-embryo', color: '#3399FF', source: 'default' },\n { name: 'Unknown', color: '#888888', source: 'default' },\n { name: 'Tumor', color: '#FF4444', source: 'default' },\n { name: 'Stroma', color: '#44AAFF', source: 'default' },\n { name: 'Immune cells', color: '#FFDD00', source: 'default' },\n { name: 'Necrosis', color: '#AA6633', source: 'default' },\n { name: 'Region', color: '#00FFFF', source: 'default' },\n { name: 'Ignore', color: '#AAAAAA', source: 'default' },\n { name: 'Positive', color: '#00CC44', source: 'default' },\n { name: 'Negative', color: '#CC0000', source: 'default' },\n];\n\n/** A fresh default preset set (deep-copied so callers can mutate safely). */\nexport function defaultPresetSet(): PresetSet {\n return {\n classes: DEFAULT_CLASSES.map((c) => ({ ...c })),\n fallbackPalette: [...DEFAULT_FALLBACK_PALETTE],\n autoPromote: false,\n matchMode: 'exact',\n };\n}\n\n/** True when the set has no usable classes (e.g. the server returned an empty/blank record). */\nexport function isEmptyPresetSet(set: PresetSet | null | undefined): boolean {\n return !set || !Array.isArray(set.classes) || set.classes.length === 0;\n}\n","/**\n * Pure geometry helpers extracted from PlotlyService.\n *\n * No DOM access, no service state, no `this` — every function is testable\n * in isolation. Keep it that way: this module is the dumping ground for\n * shape/mask/SVG-path utilities the wand, vertex eraser, and region editor\n * share. If a helper grows a `this.shapes` reference, it doesn't belong here.\n */\n\n/** A bbox-relative binary mask (1 = filled, 0 = empty). */\nexport interface BBoxMask {\n bx: number;\n by: number;\n bw: number;\n bh: number;\n mask: Uint8Array;\n}\n\n/** Parsed single-subpath polygon vertices. */\nexport interface PolygonVertices {\n xpoints: number[];\n ypoints: number[];\n}\n\n// ── SVG path parsing / building ──────────────────────────────────────\n\n/**\n * Parse a single-subpath `M x,y L x,y ... Z` path into vertex arrays.\n *\n * Returns null for paths we can't safely round-trip (multi-subpath, curves,\n * fewer than three vertices). The wand only adopts shapes it produced or\n * that Plotly's drawclosedpath produces, both of which are single-subpath\n * polygons.\n */\nexport function parseSvgPathPolygon(path: string): PolygonVertices | null {\n if (!path || path[0] !== 'M') return null;\n if (path.indexOf('M', 1) !== -1) return null; // multi-subpath\n const trimmed = path.endsWith('Z') ? path.slice(1, -1) : path.slice(1);\n const segs = trimmed.split('L');\n const xpoints: number[] = [];\n const ypoints: number[] = [];\n for (const seg of segs) {\n const [sx, sy] = seg.split(',');\n const x = parseFloat(sx);\n const y = parseFloat(sy);\n if (!Number.isFinite(x) || !Number.isFinite(y)) return null;\n xpoints.push(x);\n ypoints.push(y);\n }\n if (xpoints.length < 3) return null;\n return { xpoints, ypoints };\n}\n\n/**\n * Build a closed SVG path string `M x,y L x,y L ... Z` from vertex arrays.\n * Returns '' for fewer than three vertices (degenerate).\n */\nexport function polygonToSvgPath(xpoints: number[], ypoints: number[]): string {\n if (xpoints.length < 3) return '';\n let path = 'M';\n for (let i = 0; i < xpoints.length; i++) {\n path += `${xpoints[i]},${ypoints[i]}`;\n path += i < xpoints.length - 1 ? 'L' : 'Z';\n }\n return path;\n}\n\n/**\n * Build an SVG path string from vertex arrays. Closed polygons end with `Z`,\n * open polylines do not. Returns '' for fewer than two vertices (degenerate).\n */\nexport function verticesToSvgPath(xs: number[], ys: number[], closed: boolean): string {\n if (xs.length < 2) return '';\n let path = 'M';\n for (let i = 0; i < xs.length; i++) {\n path += `${xs[i]},${ys[i]}`;\n if (i < xs.length - 1) path += 'L';\n }\n if (closed) path += 'Z';\n return path;\n}\n\n// ── Region equality ──────────────────────────────────────────────────\n\n/**\n * Compare two Plotly shape objects for \"same region\" — used by the wand to\n * avoid appending duplicates when the user pushes the same find result more\n * than once. Polygons compare by SVG path string, rectangles compare by\n * (x0, y0, x1, y1).\n */\nexport function shapesEqual(a: any, b: any): boolean {\n if (a.path && b.path) {\n return a.path === b.path;\n }\n if (\n a.x0 !== undefined && a.y0 !== undefined &&\n a.x1 !== undefined && a.y1 !== undefined &&\n b.x0 !== undefined && b.y0 !== undefined &&\n b.x1 !== undefined && b.y1 !== undefined\n ) {\n return a.x0 === b.x0 &&\n a.y0 === b.y0 &&\n a.x1 === b.x1 &&\n a.y1 === b.y1;\n }\n return false;\n}\n\n// ── BBox-mask operations (used by the wand stroke accumulator) ───────\n\n/** Returns true if the two bbox-relative masks share at least one set pixel. */\nexport function masksOverlap(a: BBoxMask, b: BBoxMask): boolean {\n const ix0 = Math.max(a.bx, b.bx);\n const iy0 = Math.max(a.by, b.by);\n const ix1 = Math.min(a.bx + a.bw, b.bx + b.bw);\n const iy1 = Math.min(a.by + a.bh, b.by + b.bh);\n if (ix0 >= ix1 || iy0 >= iy1) return false;\n for (let y = iy0; y < iy1; y++) {\n const ar = (y - a.by) * a.bw;\n const br = (y - b.by) * b.bw;\n for (let x = ix0; x < ix1; x++) {\n if (a.mask[ar + (x - a.bx)] && b.mask[br + (x - b.bx)]) return true;\n }\n }\n return false;\n}\n\n/**\n * Allocate a fresh accumulator covering both masks and OR them in. The\n * resulting mask's bbox is the smallest rectangle containing both inputs.\n */\nexport function unionMasks(a: BBoxMask, b: BBoxMask): BBoxMask {\n const ux0 = Math.min(a.bx, b.bx);\n const uy0 = Math.min(a.by, b.by);\n const ux1 = Math.max(a.bx + a.bw, b.bx + b.bw);\n const uy1 = Math.max(a.by + a.bh, b.by + b.bh);\n const ubw = ux1 - ux0;\n const ubh = uy1 - uy0;\n const umask = new Uint8Array(ubw * ubh);\n\n const dax = a.bx - ux0;\n const day = a.by - uy0;\n for (let row = 0; row < a.bh; row++) {\n const src = row * a.bw;\n const dst = (row + day) * ubw + dax;\n umask.set(a.mask.subarray(src, src + a.bw), dst);\n }\n const dbx = b.bx - ux0;\n const dby = b.by - uy0;\n for (let row = 0; row < b.bh; row++) {\n const srcRow = row * b.bw;\n const dstRow = (row + dby) * ubw;\n for (let col = 0; col < b.bw; col++) {\n if (b.mask[srcRow + col]) umask[dstRow + (dbx + col)] = 1;\n }\n }\n return { bx: ux0, by: uy0, bw: ubw, bh: ubh, mask: umask };\n}\n\n// ── Ring simplification (Douglas–Peucker) ───────────────────────────────\n\n/** Perpendicular distance from (px,py) to the segment (ax,ay)–(bx,by). */\nfunction perpDistance(px: number, py: number,\n ax: number, ay: number, bx: number, by: number): number {\n const dx = bx - ax, dy = by - ay;\n const len2 = dx * dx + dy * dy;\n if (len2 === 0) return Math.hypot(px - ax, py - ay);\n let t = ((px - ax) * dx + (py - ay) * dy) / len2;\n t = Math.max(0, Math.min(1, t));\n return Math.hypot(px - (ax + t * dx), py - (ay + t * dy));\n}\n\n/**\n * Simplify a closed ring with the Douglas–Peucker algorithm (jit-ui#85):\n * drop every vertex that lies within `epsilon` pixels (the \"altitude\n * threshold\") of the line between its kept neighbours. Anchored at vertex 0\n * (the ring is closed by appending it). Rings of ≤ 3 vertices, or a\n * non-positive epsilon, are returned unchanged. Output keeps the closed-ring\n * convention (no repeated closing point).\n */\nexport function simplifyRing(xs: number[], ys: number[], epsilon: number)\n : { xs: number[]; ys: number[] } {\n const n = xs.length;\n if (n <= 3 || !(epsilon > 0)) return { xs: xs.slice(), ys: ys.slice() };\n\n // Close the ring so both endpoints of the DP run are vertex 0.\n const px = [...xs, xs[0]];\n const py = [...ys, ys[0]];\n const m = px.length;\n const keep = new Array<boolean>(m).fill(false);\n keep[0] = true;\n keep[m - 1] = true;\n\n const stack: Array<[number, number]> = [[0, m - 1]];\n while (stack.length) {\n const [a, b] = stack.pop() as [number, number];\n let maxD = -1, idx = -1;\n for (let i = a + 1; i < b; i++) {\n const d = perpDistance(px[i], py[i], px[a], py[a], px[b], py[b]);\n if (d > maxD) { maxD = d; idx = i; }\n }\n if (maxD > epsilon && idx > a) {\n keep[idx] = true;\n stack.push([a, idx], [idx, b]);\n }\n }\n\n const outX: number[] = [], outY: number[] = [];\n for (let i = 0; i < m - 1; i++) { // drop the duplicated closing vertex\n if (keep[i]) { outX.push(px[i]); outY.push(py[i]); }\n }\n return { xs: outX, ys: outY };\n}\n","import { Injectable } from '@angular/core';\nimport { Polygon } from '../../models/region';\n\nimport { IWandOptions, WandType } from '../../contracts/display-types';\n\n// Canonical wand option/type shapes moved to contracts/display-types (public\n// API surface); re-exported here so existing internal imports keep working.\nexport type { WandType };\nexport type WandOptions = IWandOptions;\n\nexport interface WandImage {\n /**\n * Grayscale: number[][] where data[y][x] is intensity.\n * RGB: [r,g,b][][] where data[y][x] is a 3-tuple.\n */\n data: number[][] | number[][][];\n width: number;\n height: number;\n isGrayscale: boolean;\n}\n\nconst DEFAULT_PATCH_SIZE = 149;\nconst DEFAULT_SIGMA = 4.0;\nconst DEFAULT_SENSITIVITY = 2.0;\n\n/**\n * Wand region-growing tool, modelled after QuPath's WandToolEventHandler.\n *\n * Given an image and a click position, extracts a square patch around the\n * click, optionally blurs it, computes a local threshold, runs a fixed-range\n * flood fill from the centre, closes the resulting mask, and returns the\n * traced contour as a polygon in image coordinates.\n */\n@Injectable({ providedIn: 'root' })\nexport class WandService {\n\n /**\n * @param image full-image pixel matrix (already in memory).\n * @param cx click x in image-pixel coordinates.\n * @param cy click y in image-pixel coordinates.\n * @param options wand parameters; missing fields fall back to defaults.\n * @returns a Polygon in image-pixel coordinates, or null if no region grew.\n */\n computeRegion(image: WandImage, cx: number, cy: number, options: WandOptions = {}): Polygon | null {\n const patch = this.computePatchMask(image, cx, cy, options);\n if (!patch) return null;\n return this.maskToPolygon(patch.mask, patch.size, patch.size, image.width, image.height,\n Math.round(cx) - (patch.size - 1) / 2,\n Math.round(cy) - (patch.size - 1) / 2);\n }\n\n /**\n * Compute the wand's per-click flood-fill mask in patch-local coordinates.\n * Same algorithm as `computeRegion` but stops before contour tracing — useful\n * for accumulating per-tick masks across a brush-style stroke.\n *\n * @returns mask of size W*W (0/1) plus W, or null if patchSize is invalid.\n */\n public computePatchMask(image: WandImage, cx: number, cy: number,\n options: WandOptions = {}): { mask: Uint8Array; size: number } | null {\n const W = options.patchSize ?? DEFAULT_PATCH_SIZE;\n if (W % 2 === 0) {\n throw new Error(`patchSize must be odd, got ${W}`);\n }\n const sigma = options.sigma ?? DEFAULT_SIGMA;\n const sensitivity = options.sensitivity ?? DEFAULT_SENSITIVITY;\n const isGrayscale = image.isGrayscale;\n const type: WandType = options.type ?? (isGrayscale ? 'GRAY' : 'RGB');\n const simple = !!options.simpleMode;\n // extractPatch always interleaves 1 channel for GRAY, 3 for RGB/LAB_DISTANCE.\n const inputChannels = (type === 'GRAY') ? 1 : 3;\n\n let buf = this.extractPatch(image, cx, cy, W, type);\n\n // Flood fill operates on whatever buffer we end up with: the raw patch in\n // simple mode (so multi-channel exact-match), the blurred patch for\n // GRAY/RGB, or the single-channel CIELAB distance map for LAB_DISTANCE.\n let floodChannels: number;\n let threshold: number[];\n\n if (simple) {\n // Skip blur + threshold computation. Flood-fill the raw patch at\n // exact-match per channel — same as QuPath's doSimpleSelection.\n floodChannels = inputChannels;\n threshold = new Array(floodChannels).fill(0);\n } else {\n const blurSigma = Math.max(0.5, sigma);\n buf = this.gaussianBlur(buf, W, inputChannels, blurSigma);\n\n if (type === 'LAB_DISTANCE') {\n // Convert blurred 3-channel patch to a single-channel distance map,\n // then flood-fill on that single channel.\n const distance = this.labDistanceMap(buf, W);\n const max = distance.max > 0 ? distance.max : 1;\n const scaled = new Float32Array(W * W);\n for (let i = 0; i < scaled.length; i++) scaled[i] = distance.values[i] * 255.0 / max;\n buf = scaled;\n floodChannels = 1;\n threshold = [distance.mean * sensitivity * 255.0 / max];\n } else {\n floodChannels = inputChannels;\n threshold = this.perChannelThreshold(buf, W, inputChannels, sensitivity);\n }\n }\n\n const mask = this.floodFill(buf, W, floodChannels, threshold);\n const closed = simple ? mask : this.morphClose(mask, W, 5);\n return { mask: closed, size: W };\n }\n\n /**\n * Standard ray-cast point-in-polygon test. (px, py) and the polygon\n * vertices must be in the same coordinate system.\n */\n public pointInPolygon(px: number, py: number, xpoints: number[], ypoints: number[]): boolean {\n const n = xpoints.length;\n if (n < 3) return false;\n let inside = false;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n const yi = ypoints[i], yj = ypoints[j];\n const xi = xpoints[i], xj = xpoints[j];\n const intersect = ((yi > py) !== (yj > py)) &&\n (px < (xj - xi) * (py - yi) / (yj - yi) + xi);\n if (intersect) inside = !inside;\n }\n return inside;\n }\n\n /**\n * Drop every vertex whose Euclidean distance to (cx, cy) is less than\n * `radius`. Returns trimmed parallel arrays plus how many vertices were\n * removed (so the caller can detect a no-op tick and skip the relayout).\n */\n public dropVerticesWithinRadius(xpoints: number[], ypoints: number[],\n cx: number, cy: number, radius: number)\n : { xpoints: number[]; ypoints: number[]; removed: number } {\n const r2 = radius * radius;\n const xs: number[] = [];\n const ys: number[] = [];\n let removed = 0;\n for (let i = 0; i < xpoints.length; i++) {\n const dx = xpoints[i] - cx;\n const dy = ypoints[i] - cy;\n if (dx * dx + dy * dy < r2) {\n removed++;\n continue;\n }\n xs.push(xpoints[i]);\n ys.push(ypoints[i]);\n }\n return { xpoints: xs, ypoints: ys, removed };\n }\n\n /**\n * Rasterize a closed polygon into a bbox-relative mask suitable as a\n * starting point for a wand stroke accumulator.\n *\n * Returns the bbox origin (clamped to the image) plus the filled mask, or\n * null if the polygon is degenerate or fully outside the image.\n */\n public rasterizePolygon(xpoints: number[], ypoints: number[],\n imageWidth: number, imageHeight: number,\n holes?: number[][][])\n : { bx: number; by: number; bw: number; bh: number; mask: Uint8Array } | null {\n\n const n = xpoints.length;\n if (n < 3) return null;\n\n let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n if (xpoints[i] < minX) minX = xpoints[i];\n if (xpoints[i] > maxX) maxX = xpoints[i];\n if (ypoints[i] < minY) minY = ypoints[i];\n if (ypoints[i] > maxY) maxY = ypoints[i];\n }\n // Rasterize the polygon's FULL extent (not clamped to the viewport), so a region that's\n // partially off the visible/zoomed area keeps its off-screen part when the wand/brush extends\n // it — the coords here are viewport-matrix units and may be negative or exceed the viewport\n // (jit-ui#102). Memory guard: a region that's enormous at the current zoom would allocate a\n // giant mask, so only then fall back to the viewport window (rare; accepts the clip).\n let bx = Math.floor(minX);\n let by = Math.floor(minY);\n let bx1 = Math.ceil(maxX) + 1;\n let by1 = Math.ceil(maxY) + 1;\n if ((bx1 - bx) * (by1 - by) > 4096 * 4096) {\n bx = Math.max(0, bx);\n by = Math.max(0, by);\n bx1 = Math.min(imageWidth, bx1);\n by1 = Math.min(imageHeight, by1);\n }\n const bw = bx1 - bx;\n const bh = by1 - by;\n if (bw <= 0 || bh <= 0) return null;\n\n const mask = new Uint8Array(bw * bh);\n // Scanline ring fill — sample each row at its pixel centre, writing `value`\n // (1 to fill the exterior, 0 to punch a hole back out).\n const fillRing = (rx: number[], ry: number[], value: number) => {\n const m = rx.length;\n if (m < 3) return;\n for (let py = 0; py < bh; py++) {\n const y = by + py + 0.5;\n const xs: number[] = [];\n for (let i = 0, j = m - 1; i < m; j = i++) {\n const yi = ry[i], yj = ry[j];\n if ((yi <= y && yj > y) || (yj <= y && yi > y)) {\n const t = (y - yi) / (yj - yi);\n xs.push(rx[i] + t * (rx[j] - rx[i]));\n }\n }\n xs.sort((a, b) => a - b);\n for (let k = 0; k + 1 < xs.length; k += 2) {\n const xStart = Math.max(0, Math.ceil(xs[k] - bx));\n const xEnd = Math.min(bw - 1, Math.floor(xs[k + 1] - bx));\n for (let x = xStart; x <= xEnd; x++) mask[py * bw + x] = value;\n }\n }\n };\n fillRing(xpoints, ypoints, 1);\n if (holes) {\n for (const ring of holes) {\n fillRing(ring.map(p => p[0]), ring.map(p => p[1]), 0);\n }\n }\n return { bx, by, bw, bh, mask };\n }\n\n /**\n * Point-in-region test that honours interior rings (holes): inside the\n * exterior AND outside every hole (even-odd). Coordinates must share the\n * polygon's frame. With no holes this is exactly {@link pointInPolygon}.\n */\n public pointInPolygonWithHoles(px: number, py: number, xpoints: number[], ypoints: number[],\n holes?: number[][][]): boolean {\n if (!this.pointInPolygon(px, py, xpoints, ypoints)) return false;\n if (holes) {\n for (const ring of holes) {\n if (this.pointInPolygon(px, py, ring.map(p => p[0]), ring.map(p => p[1]))) return false;\n }\n }\n return true;\n }\n\n /**\n * Trace the largest 4-connected blob in `mask` (sized w*h) and return a\n * Polygon translated into image-pixel coordinates via (originX, originY).\n * The traced vertices are NOT clamped to the image bounds: a region drawn while\n * panned/zoomed keeps its true coordinates even where they fall outside the visible\n * window (jit-ui#102). `imageWidth`/`imageHeight` are kept for signature compatibility\n * but no longer used.\n */\n public maskToPolygon(mask: Uint8Array, w: number, h: number,\n _imageWidth: number, _imageHeight: number,\n originX: number, originY: number): Polygon | null {\n const verticesLocal = this.traceContour(mask, w, h);\n if (!verticesLocal || verticesLocal.length < 3) return null;\n const xpoints: number[] = [];\n const ypoints: number[] = [];\n const coordinates: number[][] = [];\n // No viewport clamp: the trace coords (origin + local) are the region's true coords and may\n // lie outside the currently-visible window when it was panned/zoomed (jit-ui#102).\n for (const v of verticesLocal) {\n const ix = Math.round(originX + v.x);\n const iy = Math.round(originY + v.y);\n xpoints.push(ix);\n ypoints.push(iy);\n coordinates.push([ix, iy]);\n }\n const poly = new Polygon();\n poly.npoints = xpoints.length;\n poly.xpoints = xpoints;\n poly.ypoints = ypoints;\n poly.coordinates = coordinates;\n return poly;\n }\n\n /**\n * Trace EVERY 4-connected blob in `mask` (sized w*h) whose area is at least\n * `minSize` pixels, returning one Polygon per blob in image-pixel coordinates\n * (translated via originX/originY, clamped to imageWidth/imageHeight), ordered\n * largest-first. Unlike {@link maskToPolygon} (largest blob only), this lets\n * the brush eraser split a region in two when a stroke cuts through it rather\n * than discarding the smaller piece.\n */\n public maskToPolygons(mask: Uint8Array, w: number, h: number,\n imageWidth: number, imageHeight: number,\n originX: number, originY: number, minSize = 4,\n minHoleSize = minSize): Polygon[] {\n // Label all 4-connected components, recording each one's pixel count.\n const labels = new Int32Array(w * h);\n const sizes: number[] = [0]; // sizes[label]; label 0 unused\n let nextLabel = 0;\n const queue: number[] = [];\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n const idx = y * w + x;\n if (!mask[idx] || labels[idx]) continue;\n nextLabel++;\n labels[idx] = nextLabel;\n let size = 0;\n queue.push(idx);\n while (queue.length) {\n const i = queue.pop() as number;\n size++;\n const px = i % w;\n const py = (i - px) / w;\n if (px > 0) { const j = i - 1;\n if (mask[j] && !labels[j]) { labels[j] = nextLabel; queue.push(j); } }\n if (px < w - 1) { const j = i + 1;\n if (mask[j] && !labels[j]) { labels[j] = nextLabel; queue.push(j); } }\n if (py > 0) { const j = i - w;\n if (mask[j] && !labels[j]) { labels[j] = nextLabel; queue.push(j); } }\n if (py < h - 1) { const j = i + w;\n if (mask[j] && !labels[j]) { labels[j] = nextLabel; queue.push(j); } }\n }\n sizes[nextLabel] = size;\n }\n }\n\n const wanted: number[] = [];\n for (let lbl = 1; lbl <= nextLabel; lbl++) {\n if (sizes[lbl] >= minSize) wanted.push(lbl);\n }\n wanted.sort((a, b) => sizes[b] - sizes[a]); // largest-first\n\n // Interior rings (holes) per foreground label — jit-ui#85.\n const holesByLabel = this.detectHoles(\n mask, labels, w, h, originX, originY, imageWidth, imageHeight, minHoleSize);\n\n const polys: Polygon[] = [];\n const comp = new Uint8Array(w * h);\n for (const lbl of wanted) {\n comp.fill(0);\n for (let i = 0; i < comp.length; i++) comp[i] = labels[i] === lbl ? 1 : 0;\n const verts = this.mooreBoundary(comp, w, h);\n if (!verts || verts.length < 3) continue;\n const xpoints: number[] = [];\n const ypoints: number[] = [];\n const coordinates: number[][] = [];\n // No viewport clamp (jit-ui#102): keep the region's true coords even off the visible window.\n for (const v of verts) {\n const ix = Math.round(originX + v.x);\n const iy = Math.round(originY + v.y);\n xpoints.push(ix);\n ypoints.push(iy);\n coordinates.push([ix, iy]);\n }\n const poly = new Polygon();\n poly.npoints = xpoints.length;\n poly.xpoints = xpoints;\n poly.ypoints = ypoints;\n poly.coordinates = coordinates;\n const holes = holesByLabel.get(lbl);\n if (holes && holes.length) poly.holes = holes;\n polys.push(poly);\n }\n return polys;\n }\n\n /**\n * Find interior rings (holes) of each foreground component in `mask`: a\n * 4-connected run of background (0) pixels that is fully enclosed — i.e. not\n * reachable from the grid border through background — is a hole, attributed to\n * the foreground component that borders it most. Returns `fgLabel → rings`,\n * each ring a list of `[x, y]` image-pixel pairs (same convention as a\n * polygon's `coordinates`). Holes smaller than `minHoleSize` are dropped.\n */\n private detectHoles(mask: Uint8Array, fgLabels: Int32Array, w: number, h: number,\n originX: number, originY: number, imageWidth: number, imageHeight: number,\n minHoleSize: number): Map<number, number[][][]> {\n const result = new Map<number, number[][][]>();\n\n // 1. Flood-fill background reachable from the grid border (\"outside\").\n const outside = new Uint8Array(w * h);\n const stack: number[] = [];\n const seed = (idx: number) => {\n if (!mask[idx] && !outside[idx]) { outside[idx] = 1; stack.push(idx); }\n };\n for (let x = 0; x < w; x++) { seed(x); seed((h - 1) * w + x); }\n for (let y = 0; y < h; y++) { seed(y * w); seed(y * w + w - 1); }\n while (stack.length) {\n const i = stack.pop() as number;\n const px = i % w, py = (i - px) / w;\n if (px > 0) seed(i - 1);\n if (px < w - 1) seed(i + 1);\n if (py > 0) seed(i - w);\n if (py < h - 1) seed(i + w);\n }\n\n // 2. Remaining unvisited background pixels are enclosed holes. BFS each,\n // tally the bordering foreground label, and trace its boundary.\n const visited = new Uint8Array(w * h);\n const holeMask = new Uint8Array(w * h);\n const queue: number[] = [];\n for (let start = 0; start < mask.length; start++) {\n if (mask[start] || outside[start] || visited[start]) continue;\n let size = 0;\n const owners = new Map<number, number>();\n const pixels: number[] = [];\n visited[start] = 1;\n queue.length = 0;\n queue.push(start);\n while (queue.length) {\n const i = queue.pop() as number;\n size++;\n pixels.push(i);\n const px = i % w, py = (i - px) / w;\n const visit = (j: number) => {\n if (mask[j]) {\n const lbl = fgLabels[j];\n if (lbl) owners.set(lbl, (owners.get(lbl) ?? 0) + 1);\n } else if (!outside[j] && !visited[j]) {\n visited[j] = 1;\n queue.push(j);\n }\n };\n if (px > 0) visit(i - 1);\n if (px < w - 1) visit(i + 1);\n if (py > 0) visit(i - w);\n if (py < h - 1) visit(i + w);\n }\n if (size < minHoleSize || owners.size === 0) continue;\n let owner = 0, best = -1;\n owners.forEach((cnt, lbl) => { if (cnt > best) { best = cnt; owner = lbl; } });\n\n holeMask.fill(0);\n for (const i of pixels) holeMask[i] = 1;\n const verts = this.mooreBoundary(holeMask, w, h);\n if (!verts || verts.length < 3) continue;\n const ring: number[][] = [];\n for (const v of verts) {\n const ix = Math.max(0, Math.min(imageWidth - 1, Math.round(originX + v.x)));\n const iy = Math.max(0, Math.min(imageHeight - 1, Math.round(originY + v.y)));\n ring.push([ix, iy]);\n }\n const list = result.get(owner) ?? [];\n list.push(ring);\n result.set(owner, list);\n }\n return result;\n }\n\n /**\n * Trace each instance in an integer label map (0 = background) into a Polygon\n * — used to turn a cellpose-style segmentation into region outlines. Labels\n * with area below `minSize` are skipped. Coords are translated via\n * originX/originY and clamped to imageWidth/imageHeight.\n */\n public labelsToPolygons(labels: Uint32Array, w: number, h: number,\n imageWidth: number, imageHeight: number,\n originX: number, originY: number, minSize = 10): Polygon[] {\n let maxLabel = 0;\n for (let i = 0; i < labels.length; i++) if (labels[i] > maxLabel) maxLabel = labels[i];\n const out: Polygon[] = [];\n const bin = new Uint8Array(w * h);\n for (let lbl = 1; lbl <= maxLabel; lbl++) {\n let any = false;\n for (let i = 0; i < labels.length; i++) {\n const on = labels[i] === lbl; bin[i] = on ? 1 : 0; if (on) any = true;\n }\n if (!any) continue;\n // Reuse the contour tracer; one label is usually a single blob.\n for (const p of this.maskToPolygons(bin, w, h, imageWidth, imageHeight, originX, originY, minSize)) {\n out.push(p);\n }\n }\n return out;\n }\n\n // ── Patch extraction ────────────────────────────────────────────────\n\n private extractPatch(image: WandImage, cx: number, cy: number, W: number, type: WandType): Float32Array {\n const channels = (type === 'GRAY') ? 1 : 3;\n const half = (W - 1) / 2;\n const x0 = Math.round(cx) - half;\n const y0 = Math.round(cy) - half;\n const buf = new Float32Array(W * W * channels);\n\n for (let py = 0; py < W; py++) {\n const iy = y0 + py;\n if (iy < 0 || iy >= image.height) continue;\n const row = image.data[iy];\n if (!row) continue;\n for (let px = 0; px < W; px++) {\n const ix = x0 + px;\n if (ix < 0 || ix >= image.width) continue;\n const dst = (py * W + px) * channels;\n if (image.isGrayscale) {\n const v = row[ix] as number;\n if (channels === 1) {\n buf[dst] = v;\n } else {\n buf[dst] = v;\n buf[dst + 1] = v;\n buf[dst + 2] = v;\n }\n } else {\n const tuple = row[ix] as number[];\n if (channels === 1) {\n // GRAY type forced on RGB image: convert with luminance.\n buf[dst] = 0.299 * tuple[0] + 0.587 * tuple[1] + 0.114 * tuple[2];\n } else {\n buf[dst] = tuple[0];\n buf[dst + 1] = tuple[1];\n buf[dst + 2] = tuple[2];\n }\n }\n }\n }\n return buf;\n }\n\n // ── Gaussian blur (separable) ───────────────────────────────────────\n\n private gaussianBlur(buf: Float32Array, W: number, channels: number, sigma: number): Float32Array {\n const radius = Math.max(1, Math.ceil(sigma * 2));\n const size = radius * 2 + 1;\n const kernel = new Float32Array(size);\n let sum = 0;\n const inv2s2 = 1 / (2 * sigma * sigma);\n for (let i = 0; i < size; i++) {\n const x = i - radius;\n kernel[i] = Math.exp(-x * x * inv2s2);\n sum += kernel[i];\n }\n for (let i = 0; i < size; i++) kernel[i] /= sum;\n\n const horiz = new Float32Array(buf.length);\n // Horizontal pass.\n for (let y = 0; y < W; y++) {\n for (let x = 0; x < W; x++) {\n for (let c = 0; c < channels; c++) {\n let acc = 0;\n for (let k = 0; k < size; k++) {\n let xx = x + k - radius;\n if (xx < 0) xx = 0;\n else if (xx >= W) xx = W - 1;\n acc += kernel[k] * buf[(y * W + xx) * channels + c];\n }\n horiz[(y * W + x) * channels + c] = acc;\n }\n }\n }\n const out = new Float32Array(buf.length);\n // Vertical pass.\n for (let y = 0; y < W; y++) {\n for (let x = 0; x < W; x++) {\n for (let c = 0; c < channels; c++) {\n let acc = 0;\n for (let k = 0; k < size; k++) {\n let yy = y + k - radius;\n if (yy < 0) yy = 0;\n else if (yy >= W) yy = W - 1;\n acc += kernel[k] * horiz[(yy * W + x) * channels + c];\n }\n out[(y * W + x) * channels + c] = acc;\n }\n }\n }\n return out;\n }\n\n // ── Threshold computation ───────────────────────────────────────────\n\n private perChannelThreshold(buf: Float32Array, W: number, channels: number, sensitivity: number): number[] {\n const n = W * W;\n const sums = new Array(channels).fill(0);\n const sqs = new Array(channels).fill(0);\n for (let i = 0; i < n; i++) {\n for (let c = 0; c < channels; c++) {\n const v = buf[i * channels + c];\n sums[c] += v;\n sqs[c] += v * v;\n }\n }\n const scale = sensitivity > 0 ? 1 / sensitivity : 100;\n const threshold = new Array(channels);\n for (let c = 0; c < channels; c++) {\n const mean = sums[c] / n;\n const variance = Math.max(0, sqs[c] / n - mean * mean);\n const stddev = Math.sqrt(variance);\n threshold[c] = stddev * scale;\n }\n return threshold;\n }\n\n private labDistanceMap(buf: Float32Array, W: number): { values: Float32Array; mean: number; max: number } {\n const n = W * W;\n const lab = new Float32Array(n * 3);\n for (let i = 0; i < n; i++) {\n const r = buf[i * 3] / 255;\n const g = buf[i * 3 + 1] / 255;\n const b = buf[i * 3 + 2] / 255;\n const [L, A, B] = srgbToLab(r, g, b);\n lab[i * 3] = L;\n lab[i * 3 + 1] = A;\n lab[i * 3 + 2] = B;\n }\n const mid = Math.floor(n / 2);\n const cL = lab[mid * 3];\n const cA = lab[mid * 3 + 1];\n const cB = lab[mid * 3 + 2];\n\n const values = new Float32Array(n);\n let max = 0;\n let sum = 0;\n for (let i = 0; i < n; i++) {\n const dL = lab[i * 3] - cL;\n const dA = lab[i * 3 + 1] - cA;\n const dB = lab[i * 3 + 2] - cB;\n const d = Math.sqrt(dL * dL + dA * dA + dB * dB);\n values[i] = d;\n if (d > max) max = d;\n sum += d;\n }\n return { values, mean: sum / n, max };\n }\n\n // ── Flood fill ──────────────────────────────────────────────────────\n\n /**\n * Fixed-range scanline flood fill from the patch centre. A neighbour is\n * accepted iff for every channel `|p[c] - seed[c]| <= threshold[c]`.\n */\n private floodFill(buf: Float32Array, W: number, channels: number, threshold: number[]): Uint8Array {\n const mask = new Uint8Array(W * W);\n const seedX = (W - 1) / 2;\n const seedY = (W - 1) / 2;\n const seedIdx = (seedY * W + seedX) * channels;\n const seed = new Array(channels);\n for (let c = 0; c < channels; c++) seed[c] = buf[seedIdx + c];\n\n const accept = (x: number, y: number): boolean => {\n const idx = (y * W + x) * channels;\n for (let c = 0; c < channels; c++) {\n const diff = Math.abs(buf[idx + c] - seed[c]);\n if (diff > threshold[c]) return false;\n }\n return true;\n };\n\n const stack: number[] = [seedX, seedY];\n while (stack.length) {\n const y = stack.pop() as number;\n const x = stack.pop() as number;\n if (x < 0 || x >= W || y < 0 || y >= W) continue;\n if (mask[y * W + x]) continue;\n if (!accept(x, y)) continue;\n\n // Find left edge of run.\n let xl = x;\n while (xl > 0 && !mask[y * W + (xl - 1)] && accept(xl - 1, y)) xl--;\n // Find right edge of run.\n let xr = x;\n while (xr < W - 1 && !mask[y * W + (xr + 1)] && accept(xr + 1, y)) xr++;\n\n for (let xi = xl; xi <= xr; xi++) {\n mask[y * W + xi] = 1;\n }\n // Seed runs above and below.\n if (y > 0) {\n for (let xi = xl; xi <= xr; xi++) {\n if (!mask[(y - 1) * W + xi]) {\n stack.push(xi, y - 1);\n }\n }\n }\n if (y < W - 1) {\n for (let xi = xl; xi <= xr; xi++) {\n if (!mask[(y + 1) * W + xi]) {\n stack.push(xi, y + 1);\n }\n }\n }\n }\n return mask;\n }\n\n // ── Morphological close (dilate then erode) ─────────────────────────\n\n private morphClose(mask: Uint8Array, W: number, kernelSize: number): Uint8Array {\n const r = (kernelSize - 1) / 2;\n const dil = this.dilate(mask, W, r);\n return this.erode(dil, W, r);\n }\n\n private dilate(mask: Uint8Array, W: number, r: number): Uint8Array {\n const out = new Uint8Array(W * W);\n for (let y = 0; y < W; y++) {\n for (let x = 0; x < W; x++) {\n let hit = 0;\n for (let dy = -r; dy <= r && !hit; dy++) {\n const yy = y + dy;\n if (yy < 0 || yy >= W) continue;\n for (let dx = -r; dx <= r; dx++) {\n const xx = x + dx;\n if (xx < 0 || xx >= W) continue;\n if (mask[yy * W + xx]) { hit = 1; break; }\n }\n }\n out[y * W + x] = hit;\n }\n }\n return out;\n }\n\n private erode(mask: Uint8Array, W: number, r: number): Uint8Array {\n const out = new Uint8Array(W * W);\n for (let y = 0; y < W; y++) {\n for (let x = 0; x < W; x++) {\n let all = 1;\n for (let dy = -r; dy <= r && all; dy++) {\n const yy = y + dy;\n if (yy < 0 || yy >= W) { all = 0; break; }\n for (let dx = -r; dx <= r; dx++) {\n const xx = x + dx;\n if (xx < 0 || xx >= W) { all = 0; break; }\n if (!mask[yy * W + xx]) { all = 0; break; }\n }\n }\n out[y * W + x] = all;\n }\n }\n return out;\n }\n\n // ── Contour tracing (Moore-neighbour boundary follow) ───────────────\n\n /**\n * Returns the outer boundary of the largest 4-connected blob in the mask\n * sized w*h.\n */\n private traceContour(mask: Uint8Array, w: number, h: number): { x: number; y: number }[] | null {\n // Find the largest connected component (4-connectivity).\n const labels = new Int32Array(w * h);\n let bestLabel = 0;\n let bestSize = 0;\n let nextLabel = 0;\n const queue: number[] = [];\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n const idx = y * w + x;\n if (!mask[idx] || labels[idx]) continue;\n nextLabel++;\n labels[idx] = nextLabel;\n let size = 0;\n queue.push(idx);\n while (queue.length) {\n const i = queue.pop() as number;\n size++;\n const px = i % w;\n const py = (i - px) / w;\n if (px > 0) { const j = i - 1;\n if (mask[j] && !labels[j]) { labels[j] = nextLabel; queue.push(j); } }\n if (px < w - 1) { const j = i + 1;\n if (mask[j] && !labels[j]) { labels[j] = nextLabel; queue.push(j); } }\n if (py > 0) { const j = i - w;\n if (mask[j] && !labels[j]) { labels[j] = nextLabel; queue.push(j); } }\n if (py < h - 1) { const j = i + w;\n if (mask[j] && !labels[j]) { labels[j] = nextLabel; queue.push(j); } }\n }\n if (size > bestSize) { bestSize = size; bestLabel = nextLabel; }\n }\n }\n if (bestSize === 0) return null;\n\n // Build a single-component mask, then trace its outer boundary using\n // Moore-neighbour following.\n const comp = new Uint8Array(w * h);\n for (let i = 0; i < comp.length; i++) comp[i] = labels[i] === bestLabel ? 1 : 0;\n\n return this.mooreBoundary(comp, w, h);\n }\n\n private mooreBoundary(mask: Uint8Array, w: number, h: number): { x: number; y: number }[] {\n // Find the first foreground pixel in raster order — guaranteed to lie\n // on the boundary.\n let startIdx = -1;\n for (let i = 0; i < mask.length; i++) {\n if (mask[i]) { startIdx = i; break; }\n }\n if (startIdx < 0) return [];\n\n const sx = startIdx % w;\n const sy = (startIdx - sx) / w;\n const points: { x: number; y: number }[] = [{ x: sx, y: sy }];\n\n // Single isolated pixel — emit the pixel's four corner points so callers\n // (which require ≥ 3 vertices to build a polygon) get a valid 1×1 square\n // instead of a degenerate single-vertex contour.\n const singleton = (idx: number): boolean => {\n const x = idx % w;\n const y = (idx - x) / w;\n const at = (xx: number, yy: number) => xx >= 0 && xx < w && yy >= 0 && yy < h && mask[yy * w + xx];\n return !(at(x - 1, y) || at(x + 1, y) || at(x, y - 1) || at(x, y + 1));\n };\n if (singleton(startIdx)) {\n return [\n { x: sx, y: sy },\n { x: sx + 1, y: sy },\n { x: sx + 1, y: sy + 1 },\n { x: sx, y: sy + 1 },\n ];\n }\n\n // 8-connected neighbour offsets in clockwise order starting from West.\n const dx = [-1, -1, 0, 1, 1, 1, 0, -1];\n const dy = [ 0, -1, -1, -1, 0, 1, 1, 1];\n\n let cx = sx, cy = sy;\n // Backtrack direction — start from West (the side we'd be coming from in raster order).\n let prevDir = 0;\n const maxSteps = w * h * 8;\n\n for (let step = 0; step < maxSteps; step++) {\n // Standard Moore-neighbour tracing: search clockwise starting one step\n // after the backtrack direction.\n let found = false;\n for (let k = 1; k <= 8; k++) {\n const dir = (prevDir + k) & 7;\n const nx = cx + dx[dir];\n const ny = cy + dy[dir];\n if (nx < 0 || nx >= w || ny < 0 || ny >= h) continue;\n if (mask[ny * w + nx]) {\n // Backtrack direction is from new pixel back toward previous pixel.\n prevDir = (dir + 4) & 7;\n cx = nx;\n cy = ny;\n points.push({ x: cx, y: cy });\n found = true;\n break;\n }\n }\n if (!found) break;\n if (cx === sx && cy === sy && points.length > 1) {\n points.pop();\n break;\n }\n }\n\n return points;\n }\n}\n\n// ── sRGB → CIELAB (D65) ───────────────────────────────────────────────\n\nfunction srgbToLinear(c: number): number {\n return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);\n}\n\nfunction srgbToLab(r: number, g: number, b: number): [number, number, number] {\n const R = srgbToLinear(r);\n const G = srgbToLinear(g);\n const B = srgbToLinear(b);\n // sRGB → XYZ (D65)\n const X = R * 0.4124564 + G * 0.3575761 + B * 0.1804375;\n const Y = R * 0.2126729 + G * 0.7151522 + B * 0.0721750;\n const Z = R * 0.0193339 + G * 0.1191920 + B * 0.9503041;\n // Reference white (D65)\n const Xn = 0.95047, Yn = 1.0, Zn = 1.08883;\n const fx = labF(X / Xn);\n const fy = labF(Y / Yn);\n const fz = labF(Z / Zn);\n const L = 116 * fy - 16;\n const A = 500 * (fx - fy);\n const Bv = 200 * (fy - fz);\n return [L, A, Bv];\n}\n\nfunction labF(t: number): number {\n const d = 6 / 29;\n return t > d * d * d ? Math.cbrt(t) : t / (3 * d * d) + 4 / 29;\n}\n","import { Injectable } from '@angular/core';\n\nimport { Region, Rectangle, Polygon, MultiPolygon } from './models/region';\nimport { BBoxMask, unionMasks, simplifyRing } from './models/geometry';\nimport { WandService } from './toolbar/wand/wand.service';\n\n/**\n * Pure (DOM-free) region set-operations — merge / inverse / ungroup (jit-ui#85).\n *\n * Raster-based, reusing the wand/brush mask pipeline\n * ({@link WandService.rasterizePolygon} → {@link WandService.maskToPolygons}),\n * so \"select + merge\" yields the same geometry as brushing regions together:\n * one engine, one set of behaviours, holes + multi-part results for free.\n *\n * Every method takes the current regions plus the image dimensions and returns\n * new {@link Region}(s); it never mutates the store. Callers commit the result\n * through the normal region-write path (so undo/redo applies). Coordinates are\n * image pixels throughout.\n */\n@Injectable({ providedIn: 'root' })\nexport class RegionOpsService {\n /**\n * Largest raster (in pixels) a region set-op will allocate on the main thread.\n * Selections whose clipped bbox exceeds this are rasterized at a proportional\n * downscale (then the traced geometry is scaled back), so merge/inverse stay\n * responsive on gigapixel slides. ~16 MP keeps the synchronous contour trace\n * well under a second; the downscale only affects boundary fidelity of very\n * large-extent selections (small selections keep full resolution).\n */\n private static readonly MAX_OP_PIXELS = 16_000_000;\n\n constructor(private wand: WandService) {}\n\n /**\n * Geometric union of `regions` into a single region: a {@link Polygon} when\n * the union is one connected piece, a {@link MultiPolygon} when it stays\n * disjoint, with holes preserved. Returns null when nothing rasterises (e.g.\n * only open polylines were selected).\n */\n merge(regions: Region[], imageWidth: number, imageHeight: number): Region | null {\n // The raster is bounded by the selection's bbox, not the image — but on a\n // whole-slide image a large-extent selection still spans billions of pixels,\n // which freezes (or overflows the typed-array limit) on the main thread.\n // Rasterize at a capped resolution and scale the traced polygons back up.\n const scale = this.opRasterScale(regions, imageWidth, imageHeight);\n const mask = this.unionMask(regions, imageWidth, imageHeight, scale);\n if (!mask) return null;\n const sw = Math.max(1, Math.round(imageWidth * scale));\n const sh = Math.max(1, Math.round(imageHeight * scale));\n let polys = this.wand.maskToPolygons(mask.mask, mask.bw, mask.bh, sw, sh, mask.bx, mask.by, 1, 1);\n if (scale !== 1) polys = polys.map((p) => this.scalePolygon(p, 1 / scale));\n return this.regionFromParts(polys, regions[0]);\n }\n\n /** Downscale factor (≤ 1) keeping the selection's clipped bbox within\n * {@link MAX_OP_PIXELS}; 1 when it already fits. */\n private opRasterScale(regions: Region[], W: number, H: number): number {\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n const scan = (xs: number[], ys: number[]) => {\n for (const x of xs) { if (x < minX) minX = x; if (x > maxX) maxX = x; }\n for (const y of ys) { if (y < minY) minY = y; if (y > maxY) maxY = y; }\n };\n for (const r of regions || []) {\n const b = r?.bounds;\n if (b instanceof Rectangle) scan([b.x, b.x + b.width], [b.y, b.y + b.height]);\n else if (b instanceof Polygon) scan(b.xpoints, b.ypoints);\n else if (b instanceof MultiPolygon) for (const p of b.polygons) scan(p.xpoints, p.ypoints);\n }\n if (!Number.isFinite(minX)) return 1;\n const bw = Math.min(W, maxX) - Math.max(0, minX);\n const bh = Math.min(H, maxY) - Math.max(0, minY);\n const area = bw * bh;\n if (!(area > RegionOpsService.MAX_OP_PIXELS)) return 1;\n return Math.sqrt(RegionOpsService.MAX_OP_PIXELS / area);\n }\n\n /** A copy of `p` with every coordinate (and hole coordinate) multiplied by `s`. */\n private scalePolygon(p: Polygon, s: number): Polygon {\n const poly = new Polygon();\n poly.xpoints = p.xpoints.map((x) => x * s);\n poly.ypoints = p.ypoints.map((y) => y * s);\n poly.npoints = poly.xpoints.length;\n poly.closed = p.closed;\n poly.coordinates = poly.xpoints.map((x, i) => [x, poly.ypoints[i]]);\n if (p.holes) poly.holes = p.holes.map((ring) => ring.map(([x, y]) => [x * s, y * s]));\n return poly;\n }\n\n /**\n * Replace `regions` with their inverse inside the image rectangle: the image\n * minus the selection's union (the former regions become holes). Returns null\n * for a degenerate image or an empty selection.\n *\n * Done *vectorially* so it scales to gigapixel images: the selection is\n * unioned first (raster, bounded by the ROIs' extent — never the whole image),\n * then the result is the image rectangle as the exterior with each union\n * component's outline punched out as a hole. A component's own hole (a donut)\n * becomes a solid island part. Only the image's corner coordinates are used —\n * no full-image buffer is ever allocated.\n */\n inverse(regions: Region[], imageWidth: number, imageHeight: number): Region | null {\n if (imageWidth <= 0 || imageHeight <= 0) return null;\n const merged = this.merge(regions, imageWidth, imageHeight);\n if (!merged) return null;\n const comps: Polygon[] = merged.bounds instanceof MultiPolygon\n ? merged.bounds.polygons\n : merged.bounds instanceof Polygon ? [merged.bounds] : [];\n if (comps.length === 0) return null;\n\n // Image rectangle exterior with every component outline as a hole.\n const rect = this.ringPolygon(\n [0, imageWidth, imageWidth, 0], [0, 0, imageHeight, imageHeight]);\n rect.holes = comps.map((c) => c.xpoints.map((x, i) => [x, c.ypoints[i]]));\n\n // Each component's own hole (donut interior) is *outside* the region, so it\n // stays solid in the inverse — emit it as its own island part.\n const parts: Polygon[] = [rect];\n for (const c of comps) {\n if (c.holes) {\n for (const ring of c.holes) {\n parts.push(this.ringPolygon(ring.map((p) => p[0]), ring.map((p) => p[1])));\n }\n }\n }\n const bounds = parts.length === 1 ? parts[0] : Object.assign(new MultiPolygon(), { polygons: parts });\n return this.makeRegion(bounds, regions[0]);\n }\n\n /** A closed straight-edged Polygon from parallel coord arrays. */\n private ringPolygon(xs: number[], ys: number[]): Polygon {\n const p = new Polygon();\n p.xpoints = xs.slice();\n p.ypoints = ys.slice();\n p.npoints = xs.length;\n p.coordinates = xs.map((x, i) => [x, ys[i]]);\n p.closed = true;\n return p;\n }\n\n /**\n * Split a region into its disjoint parts — one region per {@link MultiPolygon}\n * part. A single connected {@link Polygon}/{@link Rectangle} has nothing to\n * split and is returned unchanged (as a one-element list).\n */\n ungroup(region: Region): Region[] {\n const b = region.bounds;\n if (b instanceof MultiPolygon) {\n return b.polygons\n .filter((p) => p.xpoints.length >= 3)\n .map((p) => this.makeRegion(this.clonePolygon(p), region));\n }\n return [region];\n }\n\n /** True when ungrouping `region` would actually split it (≥2 parts). */\n canUngroup(region: Region): boolean {\n return region.bounds instanceof MultiPolygon && region.bounds.polygons.length > 1;\n }\n\n /**\n * Simplify a region's outline(s) with Douglas–Peucker — drop vertices within\n * `altitudePx` pixels of the line between their kept neighbours. Applies to\n * the exterior and every hole, of a polygon or each part of a MultiPolygon; a\n * ring that would degenerate below a triangle is left at its previous detail\n * (the part/hole is kept, not dropped). Rectangles and open polylines are\n * returned unchanged. Result is always a straight-edged polygon (any Bézier\n * smoothing is dropped, since the anchor set changes).\n */\n simplify(region: Region, altitudePx: number): Region {\n const b = region.bounds;\n if (!(altitudePx > 0)) return region;\n if (b instanceof Polygon && b.closed !== false) {\n return this.makeRegion(this.simplifyPolygon(b, altitudePx), region);\n }\n if (b instanceof MultiPolygon) {\n const mp = new MultiPolygon();\n mp.polygons = b.polygons.map((p) => this.simplifyPolygon(p, altitudePx));\n return this.makeRegion(mp, region);\n }\n return region;\n }\n\n /** Douglas–Peucker the exterior + each hole of one polygon. A ring that\n * collapses below 3 vertices keeps its original points (never degenerates). */\n private simplifyPolygon(p: Polygon, eps: number): Polygon {\n const keepOrSrc = (xs: number[], ys: number[]): { xs: number[]; ys: number[] } => {\n const s = simplifyRing(xs, ys, eps);\n return s.xs.length >= 3 ? s : { xs: xs.slice(), ys: ys.slice() };\n };\n const ext = keepOrSrc(p.xpoints, p.ypoints);\n const poly = new Polygon();\n poly.npoints = ext.xs.length;\n poly.xpoints = ext.xs;\n poly.ypoints = ext.ys;\n poly.coordinates = ext.xs.map((x, i) => [x, ext.ys[i]]);\n poly.closed = true;\n if (p.holes) {\n const holes = p.holes.map((ring) => {\n const s = keepOrSrc(ring.map((q) => q[0]), ring.map((q) => q[1]));\n return s.xs.map((x, i) => [x, s.ys[i]]);\n });\n if (holes.length) poly.holes = holes;\n }\n return poly;\n }\n\n // ── internals ──────────────────────────────────────────────────────────\n\n /** Union of every region's filled mask (exterior minus holes), or null.\n * `scale` (≤ 1) downscales the raster for large selections; coordinates and\n * the clip bounds are scaled to match. */\n private unionMask(regions: Region[], W: number, H: number, scale = 1): BBoxMask | null {\n let acc: BBoxMask | null = null;\n for (const region of regions || []) {\n const m = this.rasterizeRegion(region, W, H, scale);\n if (!m) continue;\n acc = acc ? unionMasks(acc, m) : m;\n }\n return acc;\n }\n\n /** Rasterise any region (rect / closed polygon / multi-polygon, holes punched\n * out) into a bbox mask. Null for open polylines or degenerate geometry.\n * `scale` (≤ 1) shrinks the coordinates and clip bounds for a downscaled raster. */\n private rasterizeRegion(region: Region, W: number, H: number, scale = 1): BBoxMask | null {\n const sw = scale === 1 ? W : Math.max(1, Math.round(W * scale));\n const sh = scale === 1 ? H : Math.max(1, Math.round(H * scale));\n const sc = (arr: number[]) => (scale === 1 ? arr : arr.map((v) => v * scale));\n const scHoles = (holes?: number[][][]) =>\n !holes || scale === 1 ? holes : holes.map((ring) => ring.map(([x, y]) => [x * scale, y * scale]));\n const b = region?.bounds;\n if (b instanceof Rectangle) {\n const xs = [b.x, b.x + b.width, b.x + b.width, b.x];\n const ys = [b.y, b.y, b.y + b.height, b.y + b.height];\n return this.wand.rasterizePolygon(sc(xs), sc(ys), sw, sh);\n }\n if (b instanceof Polygon) {\n if (b.closed === false || b.xpoints.length < 3) return null;\n return this.wand.rasterizePolygon(sc(b.xpoints), sc(b.ypoints), sw, sh, scHoles(b.holes));\n }\n if (b instanceof MultiPolygon) {\n let acc: BBoxMask | null = null;\n for (const part of b.polygons) {\n if (part.xpoints.length < 3) continue;\n const m = this.wand.rasterizePolygon(sc(part.xpoints), sc(part.ypoints), sw, sh, scHoles(part.holes));\n if (m) acc = acc ? unionMasks(acc, m) : m;\n }\n return acc;\n }\n return null;\n }\n\n /** Wrap traced parts as one region (Polygon if single, else MultiPolygon),\n * inheriting colour/label from `proto`. Null when there are no parts. */\n private regionFromParts(polys: Polygon[], proto: Region | undefined): Region | null {\n if (!polys || polys.length === 0) return null;\n if (polys.length === 1) return this.makeRegion(polys[0], proto);\n const mp = new MultiPolygon();\n mp.polygons = polys;\n return this.makeRegion(mp, proto);\n }\n\n private makeRegion(bounds: Polygon | MultiPolygon, proto: Region | undefined): Region {\n const r = new Region();\n r.bounds = bounds;\n r.color = proto?.color;\n r.label = proto?.label ?? 'Region';\n return r;\n }\n\n private clonePolygon(p: Polygon): Polygon {\n const poly = new Polygon();\n poly.npoints = p.npoints;\n poly.xpoints = p.xpoints.slice();\n poly.ypoints = p.ypoints.slice();\n poly.coordinates = p.coordinates.map((c) => c.slice());\n poly.closed = p.closed;\n poly.bezier = p.bezier;\n if (p.holes) poly.holes = p.holes.map((ring) => ring.map((pt) => pt.slice()));\n return poly;\n }\n}\n","/**\n * Bezier-curve helpers (no external dependency).\n *\n * JIT supports true bezier regions: a polygon's vertices are the editable\n * *anchors*, and the smooth curve through them is derived here with the\n * Catmull-Rom construction — the same algorithm paper.js uses in\n * `path.smooth()`. The curve interpolates every anchor and\n * each anchor's two handles are colinear (a smooth tangent).\n *\n * The OSD overlay renders the curve as a true cubic SVG path + draggable handles\n * (see {@link bezierAnchorHandles}); GeoJSON export flattens the *same* cubics\n * into a dense point list (see {@link bezierCurve}) so a viewer without bezier\n * support (e.g. QuPath, which just draws the coordinate list) still shows the\n * smooth shape. Using one algorithm for both keeps what JIT draws identical to\n * what it exports.\n *\n * Pure functions: no DOM, no service state. Coordinates are image pixels.\n */\n\nexport interface CurvePoints {\n xs: number[];\n ys: number[];\n}\n\n/** A vertex's two cubic-bezier control points (absolute coords) plus whether\n * each side has a handle (open-path endpoints have only one). */\nexport interface AnchorHandle {\n in: [number, number];\n out: [number, number];\n hasIn: boolean;\n hasOut: boolean;\n}\n\n/** How many points to sample per cubic segment when flattening for export. */\nconst SAMPLES_PER_SEGMENT = 16;\n\n/**\n * Per-anchor cubic-bezier control points using the Catmull-Rom construction\n * (tension 1: control = anchor ± (next − prev) / 6). Matches paper.js\n * `path.smooth()`: the resulting cubic interpolates every anchor and the two\n * handles of each anchor are colinear. Coordinates are in the input space.\n */\nexport function bezierAnchorHandles(xs: number[], ys: number[], closed: boolean): AnchorHandle[] {\n const n = Math.min(xs.length, ys.length);\n const out: AnchorHandle[] = [];\n for (let i = 0; i < n; i++) {\n const prev = closed ? (i - 1 + n) % n : Math.max(0, i - 1);\n const next = closed ? (i + 1) % n : Math.min(n - 1, i + 1);\n const tx = (xs[next] - xs[prev]) / 6;\n const ty = (ys[next] - ys[prev]) / 6;\n out.push({\n out: [xs[i] + tx, ys[i] + ty],\n in: [xs[i] - tx, ys[i] - ty],\n hasOut: closed || i < n - 1,\n hasIn: closed || i > 0,\n });\n }\n return out;\n}\n\n/** The Catmull-Rom handles as **relative** offsets `[dx, dy]` per anchor — used\n * to initialise a region's editable handles when bezier is turned on. */\nexport function defaultHandleOffsets(xs: number[], ys: number[], closed: boolean):\n { in: number[][]; out: number[][] } {\n const h = bezierAnchorHandles(xs, ys, closed);\n return {\n in: h.map((a, i) => [a.in[0] - xs[i], a.in[1] - ys[i]]),\n out: h.map((a, i) => [a.out[0] - xs[i], a.out[1] - ys[i]]),\n };\n}\n\n/** Absolute handles from stored relative offsets (anchor + offset). */\nexport function handlesFromOffsets(xs: number[], ys: number[],\n inOff: number[][], outOff: number[][], closed: boolean): AnchorHandle[] {\n const n = Math.min(xs.length, ys.length);\n const out: AnchorHandle[] = [];\n for (let i = 0; i < n; i++) {\n out.push({\n in: [xs[i] + (inOff[i]?.[0] ?? 0), ys[i] + (inOff[i]?.[1] ?? 0)],\n out: [xs[i] + (outOff[i]?.[0] ?? 0), ys[i] + (outOff[i]?.[1] ?? 0)],\n hasOut: closed || i < n - 1,\n hasIn: closed || i > 0,\n });\n }\n return out;\n}\n\n/** A region's handles: from its stored (editable) offsets when present, else the\n * Catmull-Rom default. The single source of truth for both rendering and export. */\nexport function resolveHandles(xs: number[], ys: number[], closed: boolean,\n inOff?: number[][], outOff?: number[][]): AnchorHandle[] {\n if (inOff && outOff && inOff.length === xs.length && outOff.length === xs.length) {\n return handlesFromOffsets(xs, ys, inOff, outOff, closed);\n }\n return bezierAnchorHandles(xs, ys, closed);\n}\n\n/**\n * Flatten a cubic bezier (defined by explicit per-anchor handles) into a dense\n * point list by sampling each segment. The curve passes through every anchor; a\n * closed ring returns to its first point.\n */\nexport function bezierCurveFromHandles(xs: number[], ys: number[],\n handles: AnchorHandle[], closed: boolean): CurvePoints {\n const n = Math.min(xs.length, ys.length);\n if (n < 3) return { xs: xs.slice(), ys: ys.slice() };\n\n const outX: number[] = [];\n const outY: number[] = [];\n const segs = closed ? n : n - 1;\n for (let i = 0; i < segs; i++) {\n const j = (i + 1) % n;\n const p0x = xs[i], p0y = ys[i];\n const c1 = handles[i].out, c2 = handles[j].in;\n const p3x = xs[j], p3y = ys[j];\n for (let s = 0; s < SAMPLES_PER_SEGMENT; s++) {\n const t = s / SAMPLES_PER_SEGMENT;\n const u = 1 - t;\n const w0 = u * u * u, w1 = 3 * u * u * t, w2 = 3 * u * t * t, w3 = t * t * t;\n outX.push(w0 * p0x + w1 * c1[0] + w2 * c2[0] + w3 * p3x);\n outY.push(w0 * p0y + w1 * c1[1] + w2 * c2[1] + w3 * p3y);\n }\n }\n if (closed) {\n outX.push(xs[0]); outY.push(ys[0]);\n } else {\n outX.push(xs[n - 1]); outY.push(ys[n - 1]);\n }\n return { xs: outX, ys: outY };\n}\n\n/**\n * Flatten the smooth Catmull-Rom bezier through the anchors (no custom handles).\n * Falls back to the anchors when there are too few to form a curve.\n */\nexport function bezierCurve(xs: number[], ys: number[], closed: boolean): CurvePoints {\n const n = Math.min(xs.length, ys.length);\n if (n < 3) return { xs: xs.slice(), ys: ys.slice() };\n return bezierCurveFromHandles(xs, ys, bezierAnchorHandles(xs, ys, closed), closed);\n}\n","import { Polygon, Rectangle, Region, MultiPolygon } from './models/region';\nimport { ShapeSelection } from './models/shape';\nimport { resolveHandles, bezierCurveFromHandles } from './models/bezier';\nimport { saveAs } from 'file-saver';\n\nexport const COLORMAP_OPTIONS = [\n {\n label: 'Sequential',\n data: null,\n children: [\n { label:'Greys', data: { value: 'GREYS_LUT', src:'assets/plotting/icons/colormap-greys.png' } },\n { label:'Purples', data: { value: 'PURPLES_LUT', src:'assets/plotting/icons/colormap-purples.png' } },\n { label:'Blues', data: { value: 'BLUES_LUT', src:'assets/plotting/icons/colormap-blues.png' } },\n { label:'Greens', data: { value: 'GREENS_LUT', src:'assets/plotting/icons/colormap-greens.png' } },\n { label:'Oranges', data: { value: 'ORANGES_LUT', src:'assets/plotting/icons/colormap-oranges.png' } },\n { label:'Reds', data: { value: 'Reds', src:'assets/plotting/icons/colormap-reds.png' } },\n { label:'YlOrBr', data: { value: 'YLORBR_LUT', src:'assets/plotting/icons/colormap-ylorbr.png' } },\n { label:'YlOrRd', data: { value: 'YLORRD_LUT', src:'assets/plotting/icons/colormap-ylorrd.png' } },\n { label:'OrRd', data: { value: 'ORRD_LUT', src:'assets/plotting/icons/colormap-orrd.png' } },\n { label:'PuRd', data: { value: 'PURD_LUT', src:'assets/plotting/icons/colormap-purd.png' } },\n { label:'RdPu', data: { value: 'RDPU_LUT', src:'assets/plotting/icons/colormap-rdpu.png' } },\n { label:'BuPu', data: { value: 'BUPU_LUT', src:'assets/plotting/icons/colormap-bupu.png' } },\n { label:'GnBu', data: { value: 'GNBU_LUT', src:'assets/plotting/icons/colormap-gnbu.png' } },\n { label:'YlGnBu', data: { value: 'YLGNBU_LUT', src:'assets/plotting/icons/colormap-ylgnbu.png' } },\n { label:'PuBuGn', data: { value: 'PUBUGN_LUT', src:'assets/plotting/icons/colormap-pubugn.png' } },\n { label:'BuGn', data: { value: 'BUGN_LUT', src:'assets/plotting/icons/colormap-bugn.png' } },\n { label:'YlGn', data: { value: 'YLGN_LUT', src:'assets/plotting/icons/colormap-ylgn.png' } },\n { label:'Greys Inv', data: { value: 'Greys', src:'assets/plotting/icons/colormap-greys-inv.png' } },\n { label:'Greens Inv', data: { value: 'Greens', src:'assets/plotting/icons/colormap-greens-inv.png' } },\n { label:'YlOrRd Inv', data: { value: 'YlOrRd', src:'assets/plotting/icons/colormap-ylorrd-inv.png' } },\n { label:'YlGnBu Inv', data: { value: 'YlGnBu', src:'assets/plotting/icons/colormap-ylgnbu-inv.png' } },\n ]\n },\n {\n label: 'Sequential (2)',\n data: null,\n children: [\n { label: 'binary', data: { value: 'BINARY_LUT', src: 'assets/plotting/icons/colormap-binary.png' } },\n { label: 'gist_yarg', data: { value: 'GIST_YARG_LUT', src: 'assets/plotting/icons/colormap-gist_yarg.png' } },\n { label: 'gist_gray', data: { value: 'GIST_GRAY_LUT', src: 'assets/plotting/icons/colormap-gist_gray.png' } },\n { label: 'gray', data: { value: 'GRAY_LUT', src: 'assets/plotting/icons/colormap-gray.png' } },\n { label: 'bone', data: { value: 'BONE_LUT', src: 'assets/plotting/icons/colormap-bone.png' } },\n { label: 'pink', data: { value: 'PINK_LUT', src: 'assets/plotting/icons/colormap-pink.png' } },\n { label: 'spring', data: { value: 'SPRING_LUT', src: 'assets/plotting/icons/colormap-spring.png' } },\n { label: 'summer', data: { value: 'SUMMER_LUT', src: 'assets/plotting/icons/colormap-summer.png' } },\n { label: 'autumn', data: { value: 'AUTUMN_LUT', src: 'assets/plotting/icons/colormap-autumn.png' } },\n { label: 'winter', data: { value: 'WINTER_LUT', src: 'assets/plotting/icons/colormap-winter.png' } },\n { label: 'cool', data: { value: 'COOL_LUT', src: 'assets/plotting/icons/colormap-cool.png' } },\n { label: 'Wistia', data: { value: 'WISTIA_LUT', src: 'assets/plotting/icons/colormap-wistia.png' } },\n { label: 'hot', data: { value: 'HOT_LUT', src: 'assets/plotting/icons/colormap-hot.png' } },\n { label: 'afmhot', data: { value: 'AFMHOT_LUT', src: 'assets/plotting/icons/colormap-afmhot.png' } },\n { label: 'gist_heat', data: { value: 'GIST_HEAT_LUT', src: 'assets/plotting/icons/colormap-gist_heat.png' } },\n { label: 'copper', data: { value: 'COPPER_LUT', src: 'assets/plotting/icons/colormap-copper.png' } },\n { label:'Bluered', data: { value: 'Bluered', src:'assets/plotting/icons/colormap-bluered.png' } },\n\n ]\n },\n {\n label: 'Perceptually Uniform Sequential',\n data: null,\n children: [\n { label:'Viridis', data: { value: 'Viridis', src:'assets/plotting/icons/colormap-viridis.png' } },\n { label: 'Magma', data: { value: 'MAGMA_LUT', src:'assets/plotting/icons/colormap-magma.png' } },\n { label: 'Inferno', data: { value: 'INFERNO_LUT', src:'assets/plotting/icons/colormap-inferno.png' } },\n { label:'Cividis', data: { value: 'Cividis', src:'assets/plotting/icons/colormap-cividis.png' } },\n { label:'Electric', data: { value: 'Electric', src: 'assets/plotting/icons/colormap-electric.png' } },\n { label:'Plasma', data: { value: 'PLASMA_LUT', src:'assets/plotting/icons/colormap-plasma.png' } },\n ]\n },\n {\n label: 'Diverging',\n data: null,\n children: [\n { label:'PiYG', data: { value: 'PIYG_LUT', src:'assets/plotting/icons/colormap-piyg.png' } },\n { label:'PRGn', data: { value: 'PRGN_LUT', src:'assets/plotting/icons/colormap-prgn.png' } },\n { label:'BrBG', data: { value: 'BRBG_LUT', src:'assets/plotting/icons/colormap-brbg.png' } },\n { label:'PuOr', data: { value: 'PUOR_LUT', src:'assets/plotting/icons/colormap-puor.png' } },\n { label:'RdGy', data: { value: 'RDGY_LUT', src:'assets/plotting/icons/colormap-rdgy.png' } },\n { label:'RdBu', data: { value: 'RDBU_LUT', src:'assets/plotting/icons/colormap-rdbu.png' } },\n { label:'RdYlBu', data: { value: 'RDYLBU_LUT', src:'assets/plotting/icons/colormap-rdylbu.png' } },\n { label:'RdYlGn', data: { value: 'RDYLGN_LUT', src:'assets/plotting/icons/colormap-rdylgn.png' } },\n { label:'Spectral', data: { value: 'SPECTRAL_LUT', src:'assets/plotting/icons/colormap-spectral.png' } },\n { label:'coolwarm', data: { value: 'COOLWARM_LUT', src:'assets/plotting/icons/colormap-coolwarm.png' } },\n { label:'bwr', data: { value: 'BWR_LUT', src:'assets/plotting/icons/colormap-bwr.png' } },\n { label:'seismic', data: { value: 'SEISMIC_LUT', src:'assets/plotting/icons/colormap-seismic.png' } },\n { label:'berlin', data: { value: 'BERLIN_LUT', src:'assets/plotting/icons/colormap-berlin.png' } },\n { label:'managua', data: { value: 'MANAGUA_LUT', src:'assets/plotting/icons/colormap-managua.png' } },\n { label:'vanimo', data: { value: 'VANIMO_LUT', src:'assets/plotting/icons/colormap-vanimo.png' } },\n { label:'Picnic', data: { value: 'Picnic', src:'assets/plotting/icons/colormap-picnic.png' } },\n { label:'Portland', data: { value: 'Portland', src:'assets/plotting/icons/colormap-portland.png' } },\n\n ]\n },\n {\n label: 'Cyclic',\n data: null,\n children: [\n { label:'twilight', data: { value: 'TWILIGHT_LUT', src:'assets/plotting/icons/colormap-twilight.png' } },\n { label:'twilight_shifted', data: { value: 'TWILIGHT_SHIFTED_LUT', src:'assets/plotting/icons/colormap-twilight_shifted.png' } },\n { label: 'hsv', data: { value: 'HSV_LUT', src: 'assets/plotting/icons/colormap-hsv.png' } },\n ]\n },\n {\n label: 'Qualitative',\n data: null,\n children: [\n { label:'Pastel1', data: { value: 'PASTEL1_LUT', src:'assets/plotting/icons/colormap-Pastel1.png' } },\n { label:'Pastel2', data: { value: 'PASTEL2_LUT', src:'assets/plotting/icons/colormap-pastel2.png' } },\n { label:'Accent', data: { value: 'ACCENT_LUT', src:'assets/plotting/icons/colormap-accent.png' } },\n { label:'Dark2', data: { value: 'DARK2_LUT', src:'assets/plotting/icons/colormap-dark2.png' } },\n { label:'Set1', data: { value: 'SET1_LUT', src:'assets/plotting/icons/colormap-set1.png' } },\n { label:'Set2', data: { value: 'SET2_LUT', src:'assets/plotting/icons/colormap-set2.png' } },\n { label:'Set3', data: { value: 'SET3_LUT', src: 'assets/plotting/icons/colormap-set3.png' } },\n { label:'tab10', data: { value: 'TAB10_LUT', src:'assets/plotting/icons/colormap-tab10.png' } },\n { label:'tab20', data: { value: 'TAB20_LUT', src:'assets/plotting/icons/colormap-tab20.png' } },\n { label:'tab20b', data: { value: 'TAB20B_LUT', src:'assets/plotting/icons/colormap-tab20b.png' } },\n { label:'tab20c', data: { value: 'TAB20C_LUT', src: 'assets/plotting/icons/colormap-tab20c.png' } }\n ]\n },\n {\n label: 'Miscellaneous',\n data: null,\n children: [\n { label:'flag', data: { value: 'FLAG_LUT', src: 'assets/plotting/icons/colormap-flag.png' } },\n { label:'prism', data: { value: 'PRISM_LUT', src: 'assets/plotting/icons/colormap-prism.png' } },\n { label:'ocean', data: { value: 'OCEAN_LUT', src: 'assets/plotting/icons/colormap-ocean.png' } },\n { label:'gist_earth', data: { value: 'GIST_EARTH_LUT', src: 'assets/plotting/icons/colormap-gist_earth.png' } },\n { label:'terrain', data: { value: 'TERRAIN_LUT', src: 'assets/plotting/icons/colormap-terrain.png' } },\n { label:'gist_stern', data: { value: 'GIST_STERN_LUT', src: 'assets/plotting/icons/colormap-gist_stern.png' } },\n { label:'gnuplot', data: { value: 'GNUPLOT_LUT', src: 'assets/plotting/icons/colormap-gnuplot.png' } },\n { label:'gnuplot2', data: { value: 'GNUPLOT2_LUT', src: 'assets/plotting/icons/colormap-gnuplot2.png' } },\n { label:'CMRmap', data: { value: 'CMRMAP_LUT', src: 'assets/plotting/icons/colormap-cmrmap.png' } },\n { label:'cubehelix', data: { value: 'CUBEHELIX_LUT', src: 'assets/plotting/icons/colormap-cubehelix.png' } },\n { label:'brg', data: { value: 'BRG_LUT', src: 'assets/plotting/icons/colormap-brg.png' } },\n { label:'gist_rainbow', data: { value: 'GIST_RAINBOW_LUT', src: 'assets/plotting/icons/colormap-gist_rainbow.png' } },\n { label:'rainbow', data: { value: 'RAINBOW_LUT', src:'assets/plotting/icons/colormap-rainbow.png' } },\n { label:'jet', data: { value: 'JET_LUT', src:'assets/plotting/icons/colormap-jet.png' } },\n { label:'turbo', data: { value: 'TURBO_LUT', src: 'assets/plotting/icons/colormap-turbo.png' } },\n { label:'nipy_spectral', data: { value: 'NIPY_SPECTRAL_LUT', src: 'assets/plotting/icons/colormap-nipy_spectral.png' } },\n { label:'gist_ncar', data: { value: 'GIST_NCAR_LUT', src: 'assets/plotting/icons/colormap-gist_ncar.png' } },\n { label:'Blackbody', data: { value: 'Blackbody', src:'assets/plotting/icons/colormap-blackbody.png' } },\n ]\n }\n];\n\nexport const CONFIG = {\n displaylogo: false, // Hide the plotly logo\n responsive: true, // Make the plot responsive\n displayModeBar: false,\n scrollZoom: false, // disable mouse scroll zoom\n};\nexport const CONFIG_SURFACE = {\n displaylogo: false, // Hide the plotly logo\n responsive: true, // Make the plot responsive\n displayModeBar: false,\n scrollZoom: true, // 3D scenes orbit/zoom natively on scroll\n};\nexport class PlotUtilities {\n\n /**\n * Rounds all the point coordinates of a path ('M13.54,54.566L35.44,33.3L36.22,89.6Z')\n * becomes 'M14,55L35,33L36,90Z'\n * @param path\n */\n public roundPathCoordinates(path: string) {\n const isClosed = path.endsWith('Z');\n const inner = isClosed ? path.substring(1, path.length - 1) : path.substring(1);\n let roundedPath = 'M';\n const strArray = inner.split('L');\n for (let i = 0; i < strArray.length; i++) {\n const xy = strArray[i].split(',');\n if (i < strArray.length - 1) {\n roundedPath = `${roundedPath}${Math.round(+xy[0])},${Math.round(+xy[1])}L`;\n } else {\n roundedPath = `${roundedPath}${Math.round(+xy[0])},${Math.round(+xy[1])}`;\n }\n }\n return isClosed ? roundedPath + 'Z' : roundedPath;\n }\n\n /**\n * Transform a 1d array into a matrix given a given width\n * @param array Uint8Array\n * @param elementsPerSubArray\n */\n public arrayToMatrix(array: any[] | Uint8Array, elementsPerSubArray: number) {\n const matrix: any[] = [];\n let i, k;\n for (i = 0, k = -1; i < array.length; i++) {\n if (i % elementsPerSubArray === 0) {\n k++;\n matrix[k] = [];\n }\n matrix[k].push(array[i]);\n }\n return matrix;\n }\n\n /**\n * coordinates are of the bottom left and upper right corners of the rectangle, The coordinates\n * are taken given a yAxis that is up side down (as for all images). If Zoom is out of the image boundary,\n * it will return the image size coordinates for the new rectangle.\n * @param coordinates plotly coordinates ([Xaxis.range[0], xAxis.range[1], yAxis.range[0], yaxis.range[1]])\n * @param trueImageSize true image size [0, x, 0, y]\n */\n public getRectangle(coordinates: number[], trueImageSize: number[]) {\n const rect = new Rectangle();\n // check if new image size is bigger than original image size\n if (coordinates[3] < 0) {\n coordinates[3] = 0;\n }\n if (coordinates[1] > trueImageSize[1]) {\n coordinates[1] = trueImageSize[1];\n }\n if (coordinates[2] > trueImageSize[3]) {\n coordinates[2] = trueImageSize[3];\n }\n if (coordinates[0] < 0) {\n coordinates[0] = 0;\n }\n // if coordinates outside of image left/right/top/bottom\n // we set the coordinates to the original image size.\n if (coordinates[1] < 0 || coordinates[0] > trueImageSize[1]\n || coordinates[2] < 0 || coordinates[3] > trueImageSize[3]) {\n coordinates[0] = 0;\n coordinates[1] = trueImageSize[1];\n coordinates[2] = trueImageSize[3];\n coordinates[3] = 0;\n }\n rect.x = Math.floor(coordinates[0]);\n rect.y = Math.floor(coordinates[3]);\n rect.width = Math.floor(coordinates[1] - coordinates[0]);\n rect.height = Math.floor(coordinates[2] - coordinates[3]);\n return rect;\n }\n\n /**\n * given a dom object (found by id), return a Rectangle of the bounding element.\n * @param div\n */\n public getDomRectangle(div: string) {\n const domRect = new Rectangle();\n const appDiv: HTMLElement | null = document.getElementById(div);\n if (appDiv && appDiv.parentNode && appDiv.parentNode.parentElement) {\n const rect = appDiv.parentNode.parentElement.getBoundingClientRect();\n domRect.x = Math.round(rect.x);\n domRect.y = Math.round(rect.y);\n domRect.width = Math.round(rect.width);\n domRect.height = Math.round(rect.height);\n }\n return domRect;\n }\n\n /**\n * snap region to closest pixel in the coordinate (round the coordinates of the region)\n * @param shape\n * @private\n */\n public snapRegion(shape: ShapeSelection) {\n // if region is a polygon\n if (shape.path) {\n shape.path = this.roundPathCoordinates(shape.path);\n } else if (shape.x0 && shape.x1 && shape.y0 && shape.y1) {\n // if region is a rectangle\n if (typeof shape.x0 === 'number') {\n shape.x0 = Math.round(shape.x0);\n }\n if (typeof shape.x1 === 'number') {\n shape.x1 = Math.round(shape.x1);\n }\n if (typeof shape.y0 === 'number') {\n shape.y0 = Math.round(shape.y0);\n }\n if (typeof shape.y1 === 'number') {\n shape.y1 = Math.round(shape.y1);\n }\n }\n return shape;\n }\n\n /**\n * Given a figure (path or rectangle), returns a polygon\n * @param fig\n */\n public getPolygon(fig: any): any {\n const poly: any = new Polygon();\n if (fig.type === 'path') {\n const tempPath = fig.path as string;\n const isClosed = tempPath.endsWith('Z');\n const path = isClosed ? tempPath.substring(1, tempPath.length - 1) : tempPath.substring(1);\n const verts: string[] = path.split('L');\n poly.npoints = verts.length;\n poly.xpoints = [];\n poly.ypoints = [];\n poly.closed = isClosed;\n verts.forEach((pnt: any) => {\n const point = pnt.split(',');\n poly.xpoints.push(Math.round(point[0]));\n poly.ypoints.push(Math.round(point[1]));\n });\n } else if (fig.type === 'rect') {\n poly.npoints = 4;\n poly.xpoints = this.round([fig.x0, fig.x1, fig.x1, fig.x0]);\n poly.ypoints = this.round([fig.y1, fig.y1, fig.y0, fig.y0]);\n } else {\n console.log('Ignoring unrecognised shape in diagram');\n return null;\n }\n return poly;\n }\n\n /**\n * TESTED\n * Rounds a list of numbers\n * @param a\n */\n public round(a: number[]): number[] {\n const b: number[] = [];\n a.forEach((d: number) => b.push(Math.round(d)));\n return b;\n }\n\n /**\n * TESTED\n * Returns true of zoom is the same as image size\n * @param rect Rectangle area\n * @param trueImgSize\n * @return true if rect is out of image size boundary\n */\n public isZoomSameAsImgSize(rect: Rectangle, trueImgSize: number[]) {\n return rect.x === trueImgSize[0] && rect.y === trueImgSize[2]\n && rect.width === trueImgSize[1] && rect.height === trueImgSize[3];\n }\n\n /**\n * Save the json string to a file\n * @param jsonString\n */\n public saveToFile(jsonString: any, baseName?: string) {\n const blob = new Blob([jsonString], { type: 'application/json' });\n const stem = (baseName ?? '').replace(/\\.[^/.]+$/, '').trim() || 'rois';\n saveAs(blob, `${stem}.geojson`);\n }\n\n /**\n * Function that imports ROIs from a geojson object\n * @param geoJsonStr\n * @return Region[]\n */\n public importROIsFromGeoJson(geoJsonStr: string): Region[] {\n const regions: Region[] = [];\n let geoJson: any;\n try {\n geoJson = JSON.parse(geoJsonStr);\n } catch (error) {\n throw new Error('Error parsing json string: ' + error);\n }\n if (!geoJson.features) {\n throw new Error('Invalid GeoJson file: must contain the \\'features\\' key.');\n }\n let idx = 0;\n for (const feature of geoJson.features) {\n const region = new Region();\n region.name = `shape${idx}`;\n idx++;\n // QuPath stores the image plane INSIDE the geometry (a sibling of\n // type/coordinates), not in properties: `geometry.plane = {c,z,t}`, all\n // zero-based, and the key is omitted for the default plane (z=0,t=0). A\n // missing plane therefore reads back as z=0 (jit-ui#93).\n region.z = feature.geometry?.plane?.z ?? 0;\n if (!feature.properties || !feature.properties.classification) {\n // No classification metadata — use a default label and color.\n region.label = 'Cell';\n } else if (!feature.properties.classification.name) {\n // assume classification is a string\n region.label = feature.properties.classification;\n } else {\n // if classification is an object with a name / check color as well\n region.label = feature.properties.classification.name;\n if (feature.properties.classification.color) {\n region.color = this.rgbToHex(\n feature.properties.classification.color[0],\n feature.properties.classification.color[1],\n feature.properties.classification.color[2]\n );\n }\n }\n\n // JIT bezier region: the editable anchors + flag travel in properties\n // (the geometry holds the flattened curve for viewers without bezier\n // support). Reconstruct the editable bezier from the anchors.\n if (feature.properties && feature.properties.isBezier && feature.properties.bezierAnchors) {\n const anchors: number[][] = feature.properties.bezierAnchors;\n const polygon = new Polygon();\n polygon.bezier = true;\n polygon.closed = feature.geometry?.type !== 'LineString';\n polygon.npoints = anchors.length;\n polygon.xpoints = anchors.map(a => a[0]);\n polygon.ypoints = anchors.map(a => a[1]);\n polygon.coordinates = anchors.map(a => [a[0], a[1]]);\n // Restore the edited control handles when present (else they'll fall back\n // to the smooth Catmull-Rom default at render time).\n if (feature.properties.bezierHandlesIn) polygon.handlesIn = feature.properties.bezierHandlesIn;\n if (feature.properties.bezierHandlesOut) polygon.handlesOut = feature.properties.bezierHandlesOut;\n // Restore donut holes + their editable bezier handles (jit-ui#102).\n if (feature.properties.holes) polygon.holes = feature.properties.holes;\n if (feature.properties.holeHandlesIn) polygon.holeHandlesIn = feature.properties.holeHandlesIn;\n if (feature.properties.holeHandlesOut) polygon.holeHandlesOut = feature.properties.holeHandlesOut;\n region.bounds = polygon;\n regions.push(region);\n continue;\n }\n\n const coordinates = feature.geometry.coordinates;\n if (!coordinates) {\n throw new Error('Invalid GeoJson file: must contain the \\'coordinates\\' key.');\n }\n // Multi-part region: GeoJSON MultiPolygon → one Polygon per part, each\n // with its own holes (jit-ui#85).\n if (feature.geometry.type === 'MultiPolygon') {\n const mp = new MultiPolygon();\n mp.polygons = (coordinates as number[][][][])\n .map(rings => this.polygonFromRings(rings))\n .filter(p => p.xpoints.length >= 3);\n region.bounds = mp;\n regions.push(region);\n continue;\n }\n // Open polyline: LineString geometry\n if (feature.geometry.type === 'LineString') {\n const polygon = new Polygon();\n polygon.closed = false;\n polygon.npoints = coordinates.length;\n polygon.xpoints = [];\n polygon.ypoints = [];\n polygon.coordinates = [];\n for (let i = 0; i < coordinates.length; i++) {\n polygon.xpoints.push(coordinates[i][0]);\n polygon.ypoints.push(coordinates[i][1]);\n polygon.coordinates.push([coordinates[i][0], coordinates[i][1]]);\n }\n region.bounds = polygon;\n // Polygon: check if it encodes a rectangle (single ring only — a polygon\n // with holes must never be collapsed to a rectangle).\n } else if (coordinates.length === 1\n && coordinates[0].length === 5\n && JSON.stringify(coordinates[0][0]) === JSON.stringify(coordinates[0][4])\n && coordinates[0][0][0] === coordinates[0][3][0]\n && coordinates[0][0][1] === coordinates[0][1][1]\n && coordinates[0][1][0] === coordinates[0][2][0]\n && coordinates[0][2][1] === coordinates[0][3][1]) {\n const rectangle = new Rectangle();\n rectangle.x = coordinates[0][0][0];\n rectangle.y = coordinates[0][0][1];\n rectangle.width = coordinates[0][2][0] - coordinates[0][0][0];\n rectangle.height = coordinates[0][2][1] - coordinates[0][0][1];\n region.bounds = rectangle;\n\n } else { // polygon is a freeform closed polygon\n const polygon = new Polygon();\n polygon.npoints = coordinates[0].length - 1;\n polygon.xpoints = [];\n polygon.ypoints = [];\n polygon.coordinates = [];\n for (let i = 0; i < coordinates[0].length - 1; i++) {\n polygon.xpoints.push(coordinates[0][i][0]);\n polygon.ypoints.push(coordinates[0][i][1]);\n polygon.coordinates.push([coordinates[0][i][0], coordinates[0][i][1]]);\n }\n // Extra rings are interior holes (GeoJSON Polygon convention) — jit-ui#85.\n const holes = this.ringsToHoles(coordinates.slice(1));\n if (holes.length) polygon.holes = holes;\n region.bounds = polygon;\n }\n regions.push(region);\n }\n return regions;\n }\n\n /**\n * Function that returns a geojson object from a Plotly ROI\n * @param rois\n * @return FeatureCollection<Geometry, GeoJsonProperties>\n */\n public exportROIsToGeoJson(rois: Region[]): string {\n console.log('Exporting ROIs to GeoJson');\n console.log(rois);\n const features: any[] = [];\n for (const roi of rois.filter(r => (r as any).kind !== 'profile')) {\n // QuPath places the image plane inside the geometry (sibling of\n // type/coordinates), zero-based, and omits it for the default plane\n // (z=0,t=0). Emit `plane: {c,z,t}` only for a non-default slice so a\n // single-plane image round-trips byte-identically to QuPath (jit-ui#93).\n const planeProp = (roi.z ?? 0) !== 0 ? { plane: { c: -1, z: roi.z, t: 0 } } : {};\n if (roi.bounds instanceof Rectangle) {\n const rectangle = {\n type: 'Feature',\n properties: {\n classification: {\n name: roi.label ? roi.label : roi.name,\n color: [\n this.hexToRgb(roi?.color)[0],\n this.hexToRgb(roi?.color)[1],\n this.hexToRgb(roi?.color)[2]\n ]\n },\n },\n geometry: {\n type: 'Polygon',\n coordinates: [[\n [roi.bounds.x, roi.bounds.y],\n [roi.bounds.x + roi.bounds.width, roi.bounds.y],\n [roi.bounds.x + roi.bounds.width, roi.bounds.y + roi.bounds.height],\n [roi.bounds.x, roi.bounds.y + roi.bounds.height],\n [roi.bounds.x, roi.bounds.y]\n ]],\n ...planeProp\n }\n };\n features.push(rectangle);\n } else if (roi.bounds instanceof Polygon) {\n const colorRgb = [\n this.hexToRgb(roi?.color)[0],\n this.hexToRgb(roi?.color)[1],\n this.hexToRgb(roi?.color)[2]\n ];\n const closed = roi.bounds.closed !== false;\n const isBezier = roi.bounds.bezier === true;\n // For a bezier region the geometry is the flattened smooth curve,\n // so a viewer without bezier support (QuPath) still renders the curve;\n // the editable anchors + flag ride along in properties for JIT.\n const geomCoords = isBezier\n ? (() => {\n const handles = resolveHandles(roi.bounds.xpoints, roi.bounds.ypoints, closed,\n roi.bounds.handlesIn, roi.bounds.handlesOut);\n const c = bezierCurveFromHandles(roi.bounds.xpoints, roi.bounds.ypoints, handles, closed);\n return c.xs.map((x, i) => [x, c.ys[i]]);\n })()\n : roi.bounds.coordinates;\n const properties: any = {\n classification: {\n name: roi.label ? roi.label : roi.name,\n color: colorRgb\n },\n };\n if (isBezier) {\n properties.isBezier = true;\n properties.bezierAnchors = roi.bounds.coordinates;\n // The editable control handles (relative offsets) travel along so JIT\n // round-trips a hand-edited curve, not just the smooth default.\n if (roi.bounds.handlesIn) properties.bezierHandlesIn = roi.bounds.handlesIn;\n if (roi.bounds.handlesOut) properties.bezierHandlesOut = roi.bounds.handlesOut;\n // Donut bezier: the hole anchors + their editable handles round-trip too (jit-ui#102).\n if (roi.bounds.holes) properties.holes = roi.bounds.holes;\n if (roi.bounds.holeHandlesIn) properties.holeHandlesIn = roi.bounds.holeHandlesIn;\n if (roi.bounds.holeHandlesOut) properties.holeHandlesOut = roi.bounds.holeHandlesOut;\n }\n if (closed) {\n // Close the ring. The flattened bezier curve already returns to its\n // start, so only the straight-polygon path needs the first point\n // repeated.\n const ring = isBezier ? geomCoords : [...geomCoords, geomCoords[0]];\n // Interior rings (holes) follow the exterior as extra GeoJSON rings —\n // standard Polygon-with-holes, which QuPath round-trips (jit-ui#85). For a bezier donut,\n // the hole geometry is the flattened smooth curve too (jit-ui#102).\n const rings: number[][][] = [ring];\n if (roi.bounds.holes) {\n roi.bounds.holes.forEach((hole, hi) => {\n if (hole.length < 3) return;\n if (isBezier) {\n const hxs = hole.map((p) => p[0]);\n const hys = hole.map((p) => p[1]);\n const hh = resolveHandles(\n hxs, hys, true,\n (roi.bounds as Polygon).holeHandlesIn?.[hi],\n (roi.bounds as Polygon).holeHandlesOut?.[hi],\n );\n const c = bezierCurveFromHandles(hxs, hys, hh, true);\n rings.push(c.xs.map((x, i) => [x, c.ys[i]]));\n } else {\n rings.push([...hole, hole[0]]);\n }\n });\n }\n features.push({\n type: 'Feature',\n properties,\n geometry: { type: 'Polygon', coordinates: rings, ...planeProp }\n });\n } else {\n features.push({\n type: 'Feature',\n properties,\n geometry: { type: 'LineString', coordinates: geomCoords, ...planeProp }\n });\n }\n } else if (roi.bounds instanceof MultiPolygon) {\n // Multi-part region → GeoJSON MultiPolygon: one ring-set per part\n // (exterior + holes), each ring closed (jit-ui#85).\n const colorRgb = [\n this.hexToRgb(roi?.color)[0],\n this.hexToRgb(roi?.color)[1],\n this.hexToRgb(roi?.color)[2]\n ];\n const coordinates = roi.bounds.polygons\n .filter(part => part.xpoints.length >= 3)\n .map(part => {\n const ext = part.xpoints.map((x, i) => [x, part.ypoints[i]]);\n const rings: number[][][] = [[...ext, ext[0]]];\n if (part.holes) {\n for (const hole of part.holes) {\n if (hole.length >= 3) rings.push([...hole, hole[0]]);\n }\n }\n return rings;\n });\n features.push({\n type: 'Feature',\n properties: { classification: { name: roi.label ? roi.label : roi.name, color: colorRgb } },\n geometry: { type: 'MultiPolygon', coordinates, ...planeProp }\n });\n }\n }\n const geoJsonData = {\n features: features,\n type: 'FeatureCollection'\n };\n\n return JSON.stringify(geoJsonData);\n }\n\n /**\n * Convert GeoJSON interior rings into the neutral hole representation\n * (`number[][]` per ring, no repeated closing point). Degenerate rings (< 3\n * distinct points) are dropped. jit-ui#85.\n */\n /**\n * Build a closed {@link Polygon} from a GeoJSON ring set: `rings[0]` is the\n * exterior (closing point dropped), `rings[1..]` are interior holes. jit-ui#85.\n */\n private polygonFromRings(rings: number[][][]): Polygon {\n const poly = new Polygon();\n const ext = rings?.[0] ?? [];\n const last = ext.length - 1;\n const closed = ext.length > 1 && ext[0][0] === ext[last][0] && ext[0][1] === ext[last][1];\n const n = closed ? last : ext.length;\n poly.xpoints = []; poly.ypoints = []; poly.coordinates = [];\n for (let i = 0; i < n; i++) {\n poly.xpoints.push(ext[i][0]);\n poly.ypoints.push(ext[i][1]);\n poly.coordinates.push([ext[i][0], ext[i][1]]);\n }\n poly.npoints = poly.xpoints.length;\n poly.closed = true;\n const holes = this.ringsToHoles(rings.slice(1));\n if (holes.length) poly.holes = holes;\n return poly;\n }\n\n private ringsToHoles(rings: number[][][]): number[][][] {\n const holes: number[][][] = [];\n for (const ringIn of rings || []) {\n if (!ringIn || ringIn.length < 3) continue;\n const last = ringIn.length - 1;\n const closed = ringIn[0][0] === ringIn[last][0] && ringIn[0][1] === ringIn[last][1];\n const n = closed ? last : ringIn.length;\n const ring: number[][] = [];\n for (let i = 0; i < n; i++) ring.push([ringIn[i][0], ringIn[i][1]]);\n if (ring.length >= 3) holes.push(ring);\n }\n return holes;\n }\n\n public rgbToHex(r: number, g: number, b: number): string {\n return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);\n }\n\n public hexToRgb(hex: string | undefined): number[] {\n let r: number, g: number, b: number;\n if (hex) {\n const bigint = parseInt(hex.slice(1), 16);\n r = (bigint >> 16) & 255;\n g = (bigint >> 8) & 255;\n b = bigint & 255;\n } else {\n r = 0;\n g = 0;\n b = 0;\n }\n return [r, g, b];\n }\n\n}\n","import { Injectable, Optional, Inject } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport { BehaviorSubject, Observable, Subject } from 'rxjs';\nimport { debounceTime } from 'rxjs/operators';\n\nimport { ClassPreset, PresetSet, defaultPresetSet } from '../models/class-preset';\nimport { PREFERENCES_PORT, PreferencesPort } from '../contracts/ports/preferences.port';\n\nimport { IImageMetadata } from '../contracts/image.contract';\nimport { IChannelState } from '../contracts/channel-histogram-api.contract';\nimport { COLORMAP_OPTIONS } from '../plot.utilities';\n\n/**\n * Backend-neutral store for the **visualization session** — the state that\n * describes *how* the current image is being viewed, independent of which\n * rendering backend (Plotly or OpenSeadragon) is on screen:\n *\n * - the active colormap / LUT and its reverse-scale toggle,\n * - the current image's physical metadata (µm/pixel etc.),\n * - the classification label → colour map,\n * - which on-canvas tool is currently active.\n *\n * Both backends read and write this single instance, so they stay in lock-step\n * regardless of which one is rendering. Previously this state lived inside\n * `PlotlyService`, which forced the OpenSeadragon backend to depend on the\n * Plotly service purely to read the shared colormap; this store removes that\n * coupling — neither backend owns the session state.\n *\n * NOTE: region *geometry* (the drawn shapes / per-image region cache) still\n * lives in `PlotlyService` for now; extracting it into a sibling region store\n * is a separate follow-up.\n */\n@Injectable({ providedIn: 'root' })\nexport class VisualizerStore {\n // ── Colormap / LUT ───────────────────────────────────────────────────\n // Default to inverted greys (dark background → bright signal), which reads as\n // the natural grayscale for these microscopy images.\n private readonly colormap$ = new BehaviorSubject<any>(\n COLORMAP_OPTIONS[0].children.find((c: any) => c.label === 'Greys Inv') ?? COLORMAP_OPTIONS[0].children[0],\n );\n private readonly reverseScale$ = new BehaviorSubject<boolean>(false);\n\n // ── Image metadata (physical pixel size, channels, …) ────────────────\n private readonly imageMeta$ = new BehaviorSubject<IImageMetadata[]>([]);\n\n // ── Channels & histogram display state ───────────────────────────────\n // Per-channel display window/gamma/visibility/colour, derived from the image\n // metadata on load (1 \"Intensity\" channel for grayscale; R/G/B for RGB). The\n // Channels & Histogram pane edits these and both backends recolor live.\n private readonly channelStates$ = new BehaviorSubject<IChannelState[]>([]);\n // The derived defaults (full window, gamma 1, default tint) for the current\n // image, kept so \"Reset\" can restore a channel's window/gamma/colour.\n private defaultChannelStates: IChannelState[] = [];\n // Grayscale display (ignore the channel tints) and inverted background — both\n // global display flags, like the colormap.\n private readonly grayscale$ = new BehaviorSubject<boolean>(false);\n private readonly invert$ = new BehaviorSubject<boolean>(false);\n\n // ── Annotation class presets (jit-ui#70) ─────────────────────────────\n // The per-user, server-persisted source of truth for region colours, seeded\n // from the historical default classes. Loaded/saved via the optional\n // PreferencesPort (app-side adapter → jit-service). getClassificationColors()\n // below stays as a name→colour view for the backends' region renderers.\n private presetSet: PresetSet = defaultPresetSet();\n private readonly presetSet$ = new BehaviorSubject<PresetSet>(this.presetSet);\n private readonly savePresets$ = new Subject<void>();\n private presetsLoaded = false;\n\n // ── Active on-canvas tool ────────────────────────────────────────────\n // Which tool the user has armed (pan, zoom, drawrect, wand, eraser, …) or\n // null when none is active. The single source of truth for tool state across\n // the toolbar and whichever backend's overlay handles the pointer.\n private readonly activeTool$ = new BehaviorSubject<string | null>(null);\n\n // Optional + null defaults so the store can be constructed both via DI and\n // directly (`new VisualizerStore()` in unit tests); the LUT fetch and preset\n // load/save no-op when their dependency is absent.\n constructor(\n @Optional() private readonly http: HttpClient | null = null,\n @Optional() @Inject(PREFERENCES_PORT) private readonly prefsPort: PreferencesPort | null = null,\n ) {\n this.loadColormapLuts();\n this.initPresetPersistence();\n }\n\n /**\n * Resolve the colormap tree's LUT keys (e.g. \"GREYS_LUT\") to their colour\n * arrays from a served JSON asset. The ~630 KB of LUT data lives outside the\n * bundle (as `/assets/plotting/colormap-luts.json`) so it never enters the TS\n * / webpack module graph — that data-in-source was the main driver of the\n * build's >2 GB heap. Named Plotly scales (e.g. \"Viridis\") aren't keys in the\n * JSON, so they're left untouched. The default LUT (\"Greys Inv\" → the Plotly\n * \"Greys\" scale) needs no JSON, so the first render works before this resolves.\n */\n private loadColormapLuts(): void {\n if (!this.http) return;\n this.http.get<Record<string, [number, string][]>>('assets/plotting/colormap-luts.json').subscribe({\n next: (luts) => {\n for (const group of COLORMAP_OPTIONS as any[]) {\n for (const child of group.children ?? []) {\n const key = child?.data?.value;\n if (typeof key === 'string' && luts[key]) child.data.value = luts[key];\n }\n }\n },\n error: () => { /* leave keys unresolved; named scales still work */ },\n });\n }\n\n // ── Preset persistence (jit-ui#70) ───────────────────────────────────\n private initPresetPersistence(): void {\n // Debounced write-back so a burst of edits collapses into one PUT.\n this.savePresets$.pipe(debounceTime(800)).subscribe(() => {\n this.prefsPort?.savePresetSet(this.presetSet).subscribe({ error: () => { /* keep local copy */ } });\n });\n // Load the user's saved set (if any); otherwise keep the seeded defaults.\n this.prefsPort?.loadPresetSet().subscribe({\n next: (set) => {\n if (set && Array.isArray(set.classes) && set.classes.length > 0) {\n this.presetSet = this.normalizePresetSet(set);\n this.presetSet$.next(this.presetSet);\n }\n this.presetsLoaded = true;\n },\n error: () => { this.presetsLoaded = true; },\n });\n }\n\n private normalizePresetSet(set: PresetSet): PresetSet {\n const defaults = defaultPresetSet();\n // Clone the nested arrays/objects so outside callers can't mutate the store's\n // internal state without going through setPresetSet()/upsertClass().\n return {\n classes: Array.isArray(set.classes) ? set.classes.map((c) => ({ ...c })) : [],\n fallbackPalette:\n Array.isArray(set.fallbackPalette) && set.fallbackPalette.length\n ? [...set.fallbackPalette]\n : defaults.fallbackPalette,\n autoPromote: !!set.autoPromote,\n matchMode: set.matchMode === 'normalized' ? 'normalized' : 'exact',\n };\n }\n\n /** Queue a debounced save. No-ops until the initial load resolves (and when no port is bound). */\n private queuePresetSave(): void {\n if (this.presetsLoaded) this.savePresets$.next();\n }\n\n /** Persist the current preset set immediately, bypassing the incremental-edit\n * debounce. Used for explicit bulk actions (Apply / Import / Reset). */\n private savePresetsNow(): void {\n if (this.presetsLoaded) {\n this.prefsPort?.savePresetSet(this.presetSet).subscribe({ error: () => { /* keep local copy */ } });\n }\n }\n\n /** The available colormap options (tree for the LUT dropdown). */\n getColormapOptions(): any {\n return COLORMAP_OPTIONS;\n }\n\n getColormap(): Observable<any> {\n return this.colormap$.asObservable();\n }\n /** Synchronous current value — for render paths that read it while building\n * a frame (e.g. Plotly's colorscale) rather than subscribing. */\n currentColormap(): any {\n return this.colormap$.value;\n }\n setColormap(colormap: any): void {\n this.colormap$.next(colormap);\n }\n\n getReverseScale(): Observable<boolean> {\n return this.reverseScale$.asObservable();\n }\n currentReverseScale(): boolean {\n return this.reverseScale$.value;\n }\n setReverseScale(reverse: boolean): void {\n this.reverseScale$.next(reverse);\n }\n\n getImageMeta(): Observable<IImageMetadata[]> {\n return this.imageMeta$.asObservable();\n }\n\n /**\n * Patch the physical pixel size (µm/pixel) onto the current image meta and\n * re-emit, without touching the derived channels. The OSD tile descriptor\n * (from the server's Bio-Formats `/tiles/info`) is authoritative for scaled\n * images — `imageInfo.imageMeta` often carries no mpp — so the renderer feeds\n * it here once the descriptor loads, letting area/scale consumers (the Region\n * Editor) show µm²/mm² instead of px². No-op when neither axis is positive.\n */\n setPhysicalPixelSize(mppX?: number, mppY?: number): void {\n const hasX = (mppX ?? 0) > 0, hasY = (mppY ?? 0) > 0;\n if (!hasX && !hasY) return;\n const cur = this.imageMeta$.value;\n const meta = (cur && cur.length ? cur : [{} as IImageMetadata]).map((e) => ({ ...e }));\n if (hasX) meta[0].mppX = mppX;\n if (hasY) meta[0].mppY = mppY;\n this.imageMeta$.next(meta);\n }\n setImageMeta(imageMeta: IImageMetadata[]): void {\n this.imageMeta$.next(imageMeta);\n // Re-derive channels only when their structure changes (count), so a re-plot\n // of the same image doesn't clobber the user's window/gamma edits.\n const next = this.deriveChannels(imageMeta);\n // Always refresh the reset baseline to the current image's derived defaults\n // (names/colours can differ even at the same channel count).\n this.defaultChannelStates = next.map((c) => ({ ...c }));\n if (next.length !== this.channelStates$.value.length) {\n this.channelStates$.next(next);\n }\n }\n\n /** Channels for an image:\n * - RGB (rgbChannels ≥ 3) → Red/Green/Blue;\n * - multichannel fluorescence (channelCount > 1) → one channel per band,\n * named/tinted from the server `channelInfo` when present, else a palette;\n * - otherwise a single grayscale \"Intensity\" channel. */\n private deriveChannels(meta: IImageMetadata[]): IChannelState[] {\n const base = { min: 0, max: 255, gamma: 1, visible: true };\n const m = meta?.[0];\n if ((m?.rgbChannels ?? 1) >= 3) {\n return [\n { index: 0, name: 'Red', color: '#ff0000', ...base },\n { index: 1, name: 'Green', color: '#00ff00', ...base },\n { index: 2, name: 'Blue', color: '#0000ff', ...base },\n ];\n }\n const count = m?.channelCount ?? 1;\n if (count > 1) {\n const info = m?.channelInfo;\n // Fallback tints (Fiji-ish) when the server doesn't supply a color.\n const palette = ['#ff0000', '#00ff00', '#0000ff', '#ffffff', '#00ffff', '#ff00ff', '#ffff00'];\n return Array.from({ length: count }, (_, i) => ({\n index: i,\n name: info?.[i]?.name || `Channel ${i + 1}`,\n color: info?.[i]?.color || palette[i % palette.length],\n ...base,\n }));\n }\n return [{ index: 0, name: 'Intensity', color: '#ffffff', ...base }];\n }\n\n // ── Channels & histogram state ───────────────────────────────────────\n getChannelStates(): Observable<IChannelState[]> {\n return this.channelStates$.asObservable();\n }\n currentChannelStates(): IChannelState[] {\n return this.channelStates$.value;\n }\n /** Patch one channel by index (immutable update). */\n setChannelState(index: number, partial: Partial<IChannelState>): void {\n const next = this.channelStates$.value.map((c) =>\n c.index === index ? { ...c, ...partial, index: c.index } : c,\n );\n this.channelStates$.next(next);\n }\n /** Replace all channel states (used by auto/reset). */\n setChannelStates(states: IChannelState[]): void {\n this.channelStates$.next(states);\n }\n /** Reset one channel's display window, gamma AND colour to the values derived\n * for the current image (full 0..255 range, gamma 1, the channel's default\n * tint). Falls back to neutral defaults if no baseline was captured. */\n resetChannelState(index: number): void {\n const def = this.defaultChannelStates.find((c) => c.index === index);\n this.setChannelState(index, {\n min: def?.min ?? 0,\n max: def?.max ?? 255,\n gamma: def?.gamma ?? 1,\n color: def?.color ?? '#ffffff',\n });\n }\n\n getGrayscale(): Observable<boolean> {\n return this.grayscale$.asObservable();\n }\n currentGrayscale(): boolean {\n return this.grayscale$.value;\n }\n setGrayscale(on: boolean): void {\n this.grayscale$.next(on);\n }\n\n getInvert(): Observable<boolean> {\n return this.invert$.asObservable();\n }\n currentInvert(): boolean {\n return this.invert$.value;\n }\n setInvert(on: boolean): void {\n this.invert$.next(on);\n }\n\n /** Name→colour view of the current preset set (compat for backend renderers\n * that still read a Map). */\n getClassificationColors(): Map<string, string> {\n return new Map(this.presetSet.classes.map((c) => [c.name, c.color]));\n }\n /** Upsert a single class colour (used by the editor's per-class colour picker). */\n setClassificationColor(label: string, color: string): void {\n this.upsertClass({ name: label, color });\n }\n\n // ── Annotation-class preset set accessors (jit-ui#70) ────────────────\n getPresetSet(): PresetSet {\n // Defensive copy: callers must not mutate the store's state in place —\n // all changes go through setPresetSet()/upsertClass()/removeClass() so\n // presetSet$ and persistence stay in sync.\n return {\n classes: this.presetSet.classes.map((c) => ({ ...c })),\n fallbackPalette: [...this.presetSet.fallbackPalette],\n autoPromote: this.presetSet.autoPromote,\n matchMode: this.presetSet.matchMode,\n };\n }\n getPresetSet$(): Observable<PresetSet> {\n return this.presetSet$.asObservable();\n }\n setPresetSet(set: PresetSet): void {\n this.presetSet = this.normalizePresetSet(set);\n this.presetSet$.next(this.presetSet);\n this.savePresetsNow(); // explicit bulk apply/import → persist immediately\n }\n /** Add or update a class (keyed by exact stored `name`). */\n upsertClass(preset: ClassPreset): void {\n const classes = [...this.presetSet.classes];\n const i = classes.findIndex((c) => c.name === preset.name);\n if (i >= 0) classes[i] = { ...classes[i], ...preset };\n else classes.push({ ...preset });\n this.presetSet = { ...this.presetSet, classes };\n this.presetSet$.next(this.presetSet);\n this.queuePresetSave();\n }\n removeClass(name: string): void {\n this.presetSet = { ...this.presetSet, classes: this.presetSet.classes.filter((c) => c.name !== name) };\n this.presetSet$.next(this.presetSet);\n this.queuePresetSave();\n }\n resetPresets(): void {\n this.presetSet = defaultPresetSet();\n this.presetSet$.next(this.presetSet);\n this.savePresetsNow(); // explicit reset → persist immediately\n }\n /** Force a (debounced) write-back of the current preset set. */\n persistPresets(): void {\n this.queuePresetSave();\n }\n\n getActiveTool$(): Observable<string | null> {\n return this.activeTool$.asObservable();\n }\n getActiveTool(): string | null {\n return this.activeTool$.value;\n }\n setActiveTool(tool: string | null): void {\n this.activeTool$.next(tool);\n }\n}\n","import { IImageInfo } from './contracts/image.contract';\n\n/**\n * Two-pass (small→large) render sequencing, extracted from\n * VisualizerComponent (refactoring plan, Step 7 — a pure move of the\n * orchestration; the component keeps the UI flags and supplies them through\n * the host callbacks).\n *\n * When the file has small-tier URLs we render the small tier first for a fast\n * blurry preview, release the loading overlay (keeping a translucent\n * \"sharpening\" spinner), then sharpen by re-rendering the canonical large tier\n * in place. Without a small tier it's the original single pass. The large pass\n * retries once after a short delay — the preview endpoint can hit a transient\n * 503 or a lock-contention window, and the second attempt usually lands on\n * fresh pre-gen-cached PNGs.\n */\nexport interface TwoPassRenderHost {\n /** Load + plot one phase (the component owns div/screen/plot-type/z and the\n * newer-click filename guard). `inPlace` updates the existing render so the\n * canvas doesn't blank during the small→large swap. */\n renderPhase(info: IImageInfo, inPlace: boolean): Promise<unknown>;\n /** The small tier is on screen — drop the full loading overlay so the user\n * sees the blurry preview, and show the sharpening spinner. */\n smallShown(): void;\n /** The large render settled (either way) — sharpening spinner off. */\n sharpenSettled(): void;\n /** Rendering finished. `viaSmall` = the overlay was already released by the\n * small tier (so only release the running guard + apply the ROI); otherwise\n * do the full finalize (overlay + running + ROI). */\n finished(viaSmall: boolean, logTag: string): void;\n /** Both large-tier attempts failed; the small tier stays on screen as the\n * fallback. Surface it to the user and release the running guard + ROI. */\n sharpenFailed(err: unknown): void;\n}\n\nexport class RenderOrchestrator {\n constructor(\n private host: TwoPassRenderHost,\n private retryDelayMs = 1000,\n ) {}\n\n /** Run the render: single-pass when `smallInfo` is null, two-pass otherwise. */\n async render(info: IImageInfo, smallInfo: IImageInfo | null): Promise<void> {\n if (!smallInfo) {\n try {\n await this.host.renderPhase(info, false);\n this.host.finished(false, 'finished plotting');\n } catch (err) {\n console.error('Preview failed', err);\n this.host.finished(false, 'plotting aborted');\n }\n return;\n }\n\n let smallReleasedOverlay = false;\n try {\n await this.host.renderPhase(smallInfo, false);\n this.host.smallShown();\n smallReleasedOverlay = true;\n console.log('multi-tier: small tier rendered, starting large');\n } catch (err) {\n // Small-tier render failed (older backend without tier support, transient\n // error, …). Continue with large only; the overlay stays up until it lands.\n console.warn('Small-tier preview failed, falling back to large', err);\n }\n\n try {\n await this.renderLargeWithRetry(info);\n this.host.sharpenSettled();\n if (smallReleasedOverlay) {\n this.host.finished(true, 'multi-tier: large tier rendered, sharpening complete');\n } else {\n this.host.finished(false, 'finished plotting (large only after small fallback)');\n }\n } catch (err) {\n this.host.sharpenSettled();\n console.error('Large-tier preview failed after retry', err);\n this.host.sharpenFailed(err);\n }\n }\n\n /** One retry after a brief delay before giving up on the large tier. */\n private renderLargeWithRetry(info: IImageInfo): Promise<unknown> {\n return this.host.renderPhase(info, true).catch((err) => {\n console.warn('Large-tier preview failed on first try, retrying in 1s', err);\n return new Promise<void>((resolve) => setTimeout(resolve, this.retryDelayMs)).then(() =>\n this.host.renderPhase(info, true),\n );\n });\n }\n}\n\n/**\n * Debounced z-slice scrubbing (extracted with the orchestrator): coalesce the\n * rapid changes a slider drag fires so a slice swap doesn't run on every\n * pixel; the final value lands immediately via {@link commit} (onSlideEnd).\n */\nexport class SliceScrubber {\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n private apply: (z: number) => void,\n private delayMs = 120,\n ) {}\n\n /** Debounced application of z while dragging. */\n scrub(z: number): void {\n this.cancel();\n this.timer = setTimeout(() => {\n this.timer = null;\n this.apply(z);\n }, this.delayMs);\n }\n\n /** Apply z immediately (slide end / keyboard step), dropping any pending scrub. */\n commit(z: number): void {\n this.cancel();\n this.apply(z);\n }\n\n /** Drop a pending scrub without applying (teardown). */\n cancel(): void {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n}\n","import { CachedImageData } from '../wand/wand-tool.service';\nimport { SamPrompt } from '../../contracts/sam.contract';\n\n/**\n * Pure helpers for SAM inference — no DOM, no ORT, no `this` — so they're unit\n * testable. The session uses these to assemble decoder inputs and to convert\n * the cached image frame into the RGBA buffer the encoder preprocesses.\n */\n\n/**\n * Build an RGBA buffer (the encoder's input image) from a cached image frame.\n * Grayscale frames are replicated across R/G/B; RGB tuples are copied through.\n * Out-of-range/missing pixels become opaque black.\n */\nexport function frameToRgba(cached: CachedImageData, frameIndex: number): Uint8ClampedArray {\n const { width, height } = cached;\n const frame = cached.frames[frameIndex] ?? cached.frames[0];\n const rgba = new Uint8ClampedArray(width * height * 4);\n for (let y = 0; y < height; y++) {\n const row = frame?.[y];\n for (let x = 0; x < width; x++) {\n const o = (y * width + x) * 4;\n const px = row?.[x];\n if (px == null) {\n rgba[o + 3] = 255;\n continue;\n }\n if (cached.isGrayscale) {\n const v = px as number;\n rgba[o] = v; rgba[o + 1] = v; rgba[o + 2] = v;\n } else {\n const t = px as number[];\n rgba[o] = t[0]; rgba[o + 1] = t[1]; rgba[o + 2] = t[2];\n }\n rgba[o + 3] = 255;\n }\n }\n return rgba;\n}\n\n/**\n * Assemble the SAM decoder's `point_coords` / `point_labels` from a prompt.\n *\n * Coordinates are scaled into the encoder's resized space (`scale =\n * inputSize / max(imageW, imageH)`). A box is encoded as two points labelled\n * `2` (top-left) and `3` (bottom-right); positive/negative points use `1`/`0`.\n * When there are points but no box, a padding point `[0,0]` labelled `-1` is\n * appended (the decoder expects the box slots padded when absent).\n */\nexport function buildDecoderPrompt(\n prompt: SamPrompt,\n scale: number,\n): { pointCoords: Float32Array; pointLabels: Float32Array; numPoints: number } {\n const coords: number[] = [];\n const labels: number[] = [];\n\n for (const p of prompt.points ?? []) {\n coords.push(p.x * scale, p.y * scale);\n labels.push(p.label);\n }\n\n if (prompt.box) {\n const b = prompt.box;\n coords.push(b.x0 * scale, b.y0 * scale);\n labels.push(2);\n coords.push(b.x1 * scale, b.y1 * scale);\n labels.push(3);\n } else if (labels.length > 0) {\n // Points-only: pad the (absent) box slot.\n coords.push(0, 0);\n labels.push(-1);\n }\n\n return {\n pointCoords: Float32Array.from(coords),\n pointLabels: Float32Array.from(labels),\n numPoints: labels.length,\n };\n}\n\n/**\n * Binarize SAM mask logits (`> threshold`, default 0 per SAM's mask_threshold)\n * into a 0/1 mask the contour tracer (WandService.maskToPolygons) consumes.\n */\nexport function binarizeMask(logits: Float32Array | number[], threshold = 0): Uint8Array {\n const out = new Uint8Array(logits.length);\n for (let i = 0; i < logits.length; i++) out[i] = logits[i] > threshold ? 1 : 0;\n return out;\n}\n\n/** Index of the highest-scoring mask in a multimask decoder output. */\nexport function bestMaskIndex(iouPredictions: Float32Array | number[]): number {\n let best = 0;\n for (let i = 1; i < iouPredictions.length; i++) {\n if (iouPredictions[i] > iouPredictions[best]) best = i;\n }\n return best;\n}\n","import { Injectable } from '@angular/core';\nimport { BehaviorSubject } from 'rxjs';\n\nimport { WandService } from '../wand/wand.service';\nimport { WandToolHost } from '../wand/wand-tool.service';\nimport { frameToRgba } from './sam-prompt';\nimport { getSamModel, isSamModelReady } from './sam-model-registry';\nimport { ISamSession, SamEmbedding, SamModelDef } from '../../contracts/sam.contract';\nimport { Region, Polygon, Rectangle } from '../../models/region';\n\n/** The SAM tool binds to the same host the wand/brush use, so each backend\n * reuses its existing pixel readback + coordinate transform + region store. */\nexport type SamToolHost = WandToolHost;\n\n/**\n * Box-prompted SAM segmentation tool (jit-ui#90, P0). On `segmentBoxes()` it\n * reads every rectangle region, runs the (cached) encoder once for the image,\n * then runs the decoder per box, traces each mask to a polygon (reusing\n * WandService.maskToPolygons) and commits them as regions.\n *\n * Inference is abstracted behind {@link ISamSession}: production uses the\n * onnxruntime-web session (lazy-imported so ORT never loads in unit tests);\n * tests inject a fake via {@link useSession}.\n */\n@Injectable({ providedIn: 'root' })\nexport class SamToolService {\n private host!: SamToolHost;\n private session: ISamSession | null = null;\n private model: SamModelDef = getSamModel();\n\n /** Cached encoder embedding + the key (image identity) it was computed for. */\n private embedding: SamEmbedding | null = null;\n private embeddingKey: string | null = null;\n\n /** Status text + busy flag for a spinner / toast in the host. */\n readonly status$ = new BehaviorSubject<string>('');\n readonly busy$ = new BehaviorSubject<boolean>(false);\n /** Encoder-download progress: -1 = not downloading, 0..1 = downloading. */\n readonly progress$ = new BehaviorSubject<number>(-1);\n\n constructor(private wandService: WandService) {}\n\n /** Bind to the active backend's host (called by the backend, like the wand). */\n bindHost(host: SamToolHost): void {\n this.host = host;\n }\n\n /** Choose the registered model to use; invalidates any cached embedding. */\n setModel(id: string): void {\n const next = getSamModel(id);\n if (next.id === this.model.id) return;\n this.model = next;\n this.invalidateEmbedding();\n // Drop the loaded session so the next run reloads the newly-picked model's\n // ONNX pair — ensureSession() returns the cached session as-is, so without\n // this a model switch would keep running the previous model.\n this.session?.dispose();\n this.session = null;\n }\n\n /** Drop the cached embedding (e.g. after the image/slice changes). */\n invalidateEmbedding(): void {\n this.embedding = null;\n this.embeddingKey = null;\n }\n\n /** Test seam: inject a fake/alternate inference session. */\n useSession(session: ISamSession): void {\n this.session = session;\n }\n\n /**\n * Segment every rectangle region with a box prompt and append the resulting\n * masks as new polygon regions. Returns how many regions were added.\n */\n async segmentBoxes(): Promise<number> {\n if (!this.host) return 0;\n // Re-entrancy guard: a second Segment press while the first run is still\n // downloading/encoding would launch a concurrent model download + GPU\n // encode (and can freeze the tab on a heavy WebGPU ViT-B). Ignore it.\n if (this.busy$.value) return 0;\n const cached = this.host.getCachedImageData();\n if (!cached || cached.frames.length === 0) {\n this.status$.next('No image loaded.');\n return 0;\n }\n\n const regions = this.host.getRegions();\n const rects = regions.filter((r) => r.bounds instanceof Rectangle);\n if (rects.length === 0) {\n this.status$.next('Draw one or more rectangles, then press Segment.');\n return 0;\n }\n\n const rx = cached.ratios[0] || 1;\n const ry = cached.ratios[0] || 1;\n const ox = cached.originX ?? 0;\n const oy = cached.originY ?? 0;\n\n let session: ISamSession;\n try {\n session = await this.ensureSession();\n } catch (err) {\n this.busy$.next(false);\n this.status$.next(err instanceof Error ? err.message : 'SAM model unavailable.');\n return 0;\n }\n\n this.busy$.next(true);\n try {\n // Encode once per image; reuse the embedding across all boxes.\n const key = [\n this.host.getFileName() ?? '',\n this.host.getActiveFrameIndex(),\n `${cached.width}x${cached.height}`,\n `${ox},${oy},${rx}`,\n this.model.id,\n ].join('|');\n if (!this.embedding || this.embeddingKey !== key) {\n this.status$.next('Encoding image…');\n const rgba = frameToRgba(cached, this.host.getActiveFrameIndex());\n this.embedding = await session.embed({ data: rgba, width: cached.width, height: cached.height });\n this.embeddingKey = key;\n }\n\n const masks: Region[] = [];\n const consumed = new Set<Region>(); // prompt rectangles that produced a mask\n let added = 0;\n for (let i = 0; i < rects.length; i++) {\n this.status$.next(`Segmenting ${i + 1}/${rects.length}…`);\n const b = rects[i].bounds as Rectangle;\n // Rectangle is in data coords → convert to image (matrix) coords.\n const box = {\n x0: (b.x - ox) / rx,\n y0: (b.y - oy) / ry,\n x1: (b.x + b.width - ox) / rx,\n y1: (b.y + b.height - oy) / ry,\n };\n const res = await session.decode(this.embedding, { box });\n const polys = this.wandService.maskToPolygons(\n res.mask, res.width, res.height, cached.width, cached.height, 0, 0,\n );\n if (polys.length === 0) continue;\n // Keep the largest connected piece (maskToPolygons returns largest-first).\n const poly = polys[0];\n masks.push(this.makeRegion(\n poly.xpoints.map((x) => ox + x * rx),\n poly.ypoints.map((y) => oy + y * ry),\n rects[i].color, // inherit the prompt rectangle's color\n ));\n consumed.add(rects[i]); // this rectangle is now represented by its mask\n added++;\n }\n\n // Replace each segmented prompt rectangle with its mask region; keep any\n // rectangle that produced no mask (so it can be retried) + other regions.\n const out = regions.filter((r) => !consumed.has(r)).concat(masks);\n this.host.setRegions(out);\n this.status$.next(added > 0 ? `Added ${added} region(s).` : 'No masks found.');\n return added;\n } catch (err) {\n this.status$.next(err instanceof Error ? err.message : 'Segmentation failed.');\n return 0;\n } finally {\n this.busy$.next(false);\n this.progress$.next(-1);\n }\n }\n\n private makeRegion(xData: number[], yData: number[], color?: string): Region {\n const poly = new Polygon();\n poly.npoints = xData.length;\n poly.xpoints = xData;\n poly.ypoints = yData;\n poly.coordinates = xData.map((x, i) => [x, yData[i]]);\n poly.closed = true;\n\n const region = new Region();\n region.bounds = poly;\n // Inherit the source prompt rectangle's color; fall back to the host default.\n region.color = color || this.host.getShapeColor();\n // Default class/annotation name, matching the wand/brush + overlay-drawn regions.\n region.label = 'sam';\n return region;\n }\n\n private async ensureSession(): Promise<ISamSession> {\n if (this.session) return this.session;\n if (!isSamModelReady(this.model)) {\n throw new Error(\n `SAM model \"${this.model.id}\" is not configured yet (no ONNX URLs). ` +\n 'Host it and call setSamModelUrls(), then retry.',\n );\n }\n // Lazy-import so onnxruntime-web is never pulled into unit tests / the\n // initial bundle — only when segmentation actually runs.\n const { OnnxSamSession } = await import('./onnx-sam-session');\n const session = new OnnxSamSession();\n this.progress$.next(0);\n await session.loadModel(this.model, (f) => this.progress$.next(f));\n this.session = session;\n return session;\n }\n}\n","import { Injectable } from '@angular/core';\nimport { BehaviorSubject } from 'rxjs';\n\nimport { WandService } from '../wand/wand.service';\nimport { WandToolHost } from '../wand/wand-tool.service';\nimport { frameToRgba } from './sam-prompt';\nimport { getSamModel, isSamModelReady } from './sam-model-registry';\nimport { ISamSession, SamEmbedding, SamModelDef, SamPrompt } from '../../contracts/sam.contract';\nimport { Region, Polygon } from '../../models/region';\n\n/** Interactive SAM point-prompt tool (jit-ui#90, P1).\n *\n * Each plain (positive) click segments the clicked object as its OWN new region\n * — clicking a second fiber doesn't extend the first into it. Shift/Alt-click\n * adds a negative (exclude) point that refines the CURRENT object, re-running\n * the decoder against the (cached) image embedding and updating its live region.\n * `commit()` (Enter) finalises early; `clear()` (Esc) discards the current\n * prompt + its preview region. Mirrors the wand/brush on-canvas tool pattern and\n * reuses WandService.maskToPolygons + the shared region store.\n *\n * Inference is behind {@link ISamSession} (lazy onnxruntime-web in production,\n * a fake in tests).\n */\n@Injectable({ providedIn: 'root' })\nexport class SamPointToolService {\n private host!: WandToolHost;\n private overlay: HTMLCanvasElement | null = null;\n private session: ISamSession | null = null;\n /** In-flight session load — dedupes a warm-up preload against the first click. */\n private sessionLoad: Promise<ISamSession> | null = null;\n private model: SamModelDef = getSamModel();\n\n private embedding: SamEmbedding | null = null;\n private embeddingKey: string | null = null;\n\n /** Accumulated point prompts, in image (matrix) coords. */\n private points: { x: number; y: number; label: 0 | 1 }[] = [];\n /** Id of the in-progress (preview) region being refined, if committed to store. */\n private regionId: number | null = null;\n\n readonly status$ = new BehaviorSubject<string>('');\n readonly busy$ = new BehaviorSubject<boolean>(false);\n /** Encoder-download progress (0..1) on the first click; -1 when not downloading. */\n readonly progress$ = new BehaviorSubject<number>(-1);\n\n private readonly boundMouseDown: (e: MouseEvent) => void;\n\n constructor(private wandService: WandService) {\n this.boundMouseDown = (e) => { void this.onMouseDown(e); };\n }\n\n bindHost(host: WandToolHost): void { this.host = host; }\n\n setModel(id: string): void {\n const next = getSamModel(id);\n if (next.id === this.model.id) return;\n this.model = next;\n this.embedding = null;\n this.embeddingKey = null;\n // Drop the loaded session so the next run reloads the newly-picked model\n // (ensureSession() returns the cached session as-is otherwise).\n this.session?.dispose();\n this.session = null;\n this.sessionLoad = null;\n }\n\n /** Test seam: inject a fake/alternate session. */\n useSession(session: ISamSession): void { this.session = session; }\n\n setMode(active: boolean): void {\n if (active) {\n this.createOverlay();\n // Warm up the model in the background as soon as the tool is armed, so the\n // first click doesn't pay the (download +) session-build cost on its path.\n this.preload();\n } else {\n this.destroyOverlay();\n }\n }\n\n /** Eagerly load the model in the background (fire-and-forget). Safe to call\n * repeatedly — it dedupes against an in-flight load and an existing session. */\n preload(): void {\n if (this.session || !isSamModelReady(this.model)) return;\n void this.ensureSession().catch(() => undefined);\n }\n\n /** Finalise the current object: keep its region, start fresh next click. */\n commit(): void {\n this.points = [];\n this.regionId = null;\n this.status$.next('');\n }\n\n /** Discard the in-progress prompt + its preview region. */\n clear(): void {\n if (this.regionId != null) {\n const regions = this.host.getRegions().filter((r) => r.id !== this.regionId);\n this.host.setRegions(regions);\n }\n this.points = [];\n this.regionId = null;\n this.status$.next('');\n }\n\n // ── overlay lifecycle (mirrors the wand/brush tools) ────────────────────\n\n private createOverlay(): void {\n const plotEl = this.host?.getOverlayContainer();\n if (!plotEl || this.overlay) return;\n const canvas = document.createElement('canvas');\n Object.assign(canvas.style, {\n position: 'absolute', top: '0', left: '0', width: '100%', height: '100%',\n cursor: 'crosshair', zIndex: '100',\n });\n canvas.width = plotEl.offsetWidth;\n canvas.height = plotEl.offsetHeight;\n plotEl.appendChild(canvas);\n this.overlay = canvas;\n canvas.addEventListener('mousedown', this.boundMouseDown);\n }\n\n private destroyOverlay(): void {\n if (!this.overlay) return;\n this.overlay.removeEventListener('mousedown', this.boundMouseDown);\n this.overlay.remove();\n this.overlay = null;\n this.points = [];\n this.regionId = null;\n }\n\n // ── per-click refinement ────────────────────────────────────────────────\n\n private async onMouseDown(e: MouseEvent): Promise<void> {\n if (e.button !== 0 || !this.overlay) return;\n // Re-entrancy guard: ignore clicks while a previous prompt is still\n // downloading the model / encoding / decoding. Without it, clicking again\n // during the slow first run (e.g. a ~172 MB ViT-B encode on WebGPU) launches\n // concurrent downloads + GPU encodes that can overwhelm the GPU and freeze\n // the tab. Each click is fast once the embedding is cached, so this only\n // drops clicks made while genuinely busy.\n if (this.busy$.value) return;\n const cached = this.host.getCachedImageData();\n if (!cached || cached.frames.length === 0) return;\n const transform = this.host.getCoordinateTransform();\n if (!transform.isReady()) return;\n const { x: dataX, y: dataY } = transform.clientToData(e.clientX, e.clientY);\n if (!Number.isFinite(dataX) || !Number.isFinite(dataY)) return;\n\n const rx = cached.ratios[0] || 1;\n const ry = cached.ratios[0] || 1;\n const ox = cached.originX ?? 0;\n const oy = cached.originY ?? 0;\n // Shift or Alt = negative (exclude) point.\n const label: 0 | 1 = e.shiftKey || e.altKey ? 0 : 1;\n // A plain positive click starts a NEW object: clicking another fiber must\n // segment that fiber on its own, not accumulate with earlier points and\n // grow the in-progress mask into the adjacent object (which would also\n // overwrite a previously-segmented region). Only Shift/Alt (exclude) points\n // refine the current object. This also clears any stale prompt left after a\n // region was deleted, so the next click segments fresh instead of redrawing\n // the old merged mask.\n if (label === 1) {\n this.points = [];\n this.regionId = null;\n }\n this.points.push({ x: (dataX - ox) / rx, y: (dataY - oy) / ry, label });\n\n // Mark busy BEFORE ensureSession: the first click downloads the encoder\n // (~14–172 MB) and builds the session, which is the longest wait — without\n // this the UI showed nothing running until that finished.\n this.busy$.next(true);\n try {\n this.status$.next('Loading SAM model…');\n const session = await this.ensureSession();\n const key = [\n this.host.getFileName() ?? '', this.host.getActiveFrameIndex(),\n `${cached.width}x${cached.height}`, `${ox},${oy},${rx}`, this.model.id,\n ].join('|');\n if (!this.embedding || this.embeddingKey !== key) {\n this.status$.next('Encoding image…');\n const rgba = frameToRgba(cached, this.host.getActiveFrameIndex());\n this.embedding = await session.embed({ data: rgba, width: cached.width, height: cached.height });\n this.embeddingKey = key;\n }\n this.status$.next('Segmenting…');\n const prompt: SamPrompt = { points: this.points.slice() };\n const res = await session.decode(this.embedding, prompt);\n const polys = this.wandService.maskToPolygons(\n res.mask, res.width, res.height, cached.width, cached.height, 0, 0,\n );\n if (polys.length === 0) { this.status$.next('No mask for these points.'); return; }\n const poly = polys[0];\n this.upsertPreview(\n poly.xpoints.map((x) => ox + x * rx),\n poly.ypoints.map((y) => oy + y * ry),\n );\n this.status$.next(\n 'Segmented — click another fiber for a new region, Shift-click to refine, Esc to undo.',\n );\n } catch (err) {\n this.status$.next(err instanceof Error ? err.message : 'SAM model unavailable.');\n } finally {\n this.busy$.next(false);\n this.progress$.next(-1);\n }\n }\n\n /** Replace (or insert) the in-progress preview region in the shared store. */\n private upsertPreview(xData: number[], yData: number[]): void {\n if (xData.length < 3) return;\n const poly = new Polygon();\n poly.npoints = xData.length;\n poly.xpoints = xData;\n poly.ypoints = yData;\n poly.coordinates = xData.map((x, i) => [x, yData[i]]);\n poly.closed = true;\n\n const regions = this.host.getRegions();\n const existing = this.regionId != null ? regions.find((r) => r.id === this.regionId) : null;\n const region = new Region();\n region.bounds = poly;\n region.color = this.host.getShapeColor();\n region.label = 'sam';\n if (existing) {\n region.id = existing.id;\n region.name = existing.name;\n const idx = regions.findIndex((r) => r.id === this.regionId);\n if (idx >= 0) regions[idx] = region; else regions.push(region);\n } else {\n regions.push(region);\n }\n this.host.setRegions(regions);\n this.regionId = region.id ?? this.regionId;\n }\n\n private ensureSession(): Promise<ISamSession> {\n if (this.session) return Promise.resolve(this.session);\n if (this.sessionLoad) return this.sessionLoad;\n if (!isSamModelReady(this.model)) {\n return Promise.reject(new Error(\n `SAM model \"${this.model.id}\" is not configured yet (no ONNX URLs). ` +\n 'Host it and call setSamModelUrls(), then retry.',\n ));\n }\n this.sessionLoad = (async () => {\n try {\n const { OnnxSamSession } = await import('./onnx-sam-session');\n const session = new OnnxSamSession();\n this.progress$.next(0);\n await session.loadModel(this.model, (f) => this.progress$.next(f));\n this.session = session;\n return session;\n } finally {\n this.sessionLoad = null;\n }\n })();\n return this.sessionLoad;\n }\n}\n","import { CachedImageData } from '../wand/wand-tool.service';\n\n/** A client-side crop of the loaded image — the browser equivalent of the JIT\n * server slide-crop, taken from the pixels already in the viewer. */\nexport interface CroppedImage {\n /** RGBA pixels of the crop, row-major. */\n data: Uint8ClampedArray;\n width: number;\n height: number;\n /** Crop origin in image (matrix) coords — lets masks map back to the frame. */\n matrixX0: number;\n matrixY0: number;\n}\n\n/** A box in image *data* coordinates (as stored on a Rectangle region). */\nexport interface DataBox { x0: number; y0: number; x1: number; y1: number; }\n\n/**\n * Browser \"slide crop\": extract the box region (data coords) from a cached image\n * frame as an RGBA image, clamped to the image bounds. Grayscale frames are\n * replicated across R/G/B; RGB tuples are copied through. Returns null when the\n * box is empty/outside the image.\n *\n * The output feeds an automatic segmenter (e.g. cellpose-SAM): run it on the\n * crop, then offset the resulting masks by (matrixX0, matrixY0) to place them\n * back on the full frame.\n */\nexport function cropImageRegion(\n cached: CachedImageData, frameIndex: number, box: DataBox,\n): CroppedImage | null {\n const rx = cached.ratios[0] || 1;\n const ry = cached.ratios[0] || 1;\n const ox = cached.originX ?? 0;\n const oy = cached.originY ?? 0;\n // data -> image (matrix) coords, normalized + clamped to the frame.\n let mx0 = Math.round((Math.min(box.x0, box.x1) - ox) / rx);\n let my0 = Math.round((Math.min(box.y0, box.y1) - oy) / ry);\n let mx1 = Math.round((Math.max(box.x0, box.x1) - ox) / rx);\n let my1 = Math.round((Math.max(box.y0, box.y1) - oy) / ry);\n mx0 = Math.max(0, Math.min(cached.width, mx0));\n my0 = Math.max(0, Math.min(cached.height, my0));\n mx1 = Math.max(0, Math.min(cached.width, mx1));\n my1 = Math.max(0, Math.min(cached.height, my1));\n const cw = mx1 - mx0;\n const ch = my1 - my0;\n if (cw <= 0 || ch <= 0) return null;\n\n const frame = cached.frames[frameIndex] ?? cached.frames[0];\n const data = new Uint8ClampedArray(cw * ch * 4);\n for (let y = 0; y < ch; y++) {\n const row = frame?.[my0 + y];\n for (let x = 0; x < cw; x++) {\n const o = (y * cw + x) * 4;\n const px = row?.[mx0 + x];\n if (px == null) { data[o + 3] = 255; continue; }\n if (cached.isGrayscale) {\n const v = px as number;\n data[o] = v; data[o + 1] = v; data[o + 2] = v;\n } else {\n const t = px as number[];\n data[o] = t[0]; data[o + 1] = t[1]; data[o + 2] = t[2];\n }\n data[o + 3] = 255;\n }\n }\n return { data, width: cw, height: ch, matrixX0: mx0, matrixY0: my0 };\n}\n","import { Injectable } from '@angular/core';\nimport { BehaviorSubject } from 'rxjs';\n\nimport { WandService } from '../wand/wand.service';\nimport { WandToolHost } from '../wand/wand-tool.service';\nimport { cropImageRegion } from '../crop/slide-crop';\nimport { ICellSegmenter } from '../../contracts/cell-segmenter.contract';\nimport { Region, Polygon, Rectangle } from '../../models/region';\n\n/** Yield to the event loop (a macrotask) so the toast can repaint the latest\n * status / animate the spinner before the next main-thread-blocking step. */\nconst tick = (): Promise<void> => new Promise((r) => setTimeout(r, 0));\n\n/**\n * Automatic cell segmentation inside drawn boxes (jit-ui#90). For each rectangle\n * it client slide-crops the box from the loaded image, runs an automatic\n * segmenter (cellpose-SAM, supplied by the host via {@link ICellSegmenter}) on\n * the crop, and turns every cell instance into a region — offset back onto the\n * frame. The prompt rectangle is replaced by its cell regions.\n *\n * This is the complement to the promptable SAM tool: cellpose-SAM can't take a\n * box prompt, so the box just bounds the crop it segments automatically.\n */\n@Injectable({ providedIn: 'root' })\nexport class CellSegmentToolService {\n private host!: WandToolHost;\n\n readonly status$ = new BehaviorSubject<string>('');\n readonly busy$ = new BehaviorSubject<boolean>(false);\n readonly progress$ = new BehaviorSubject<number>(-1);\n\n constructor(private wandService: WandService) {}\n\n bindHost(host: WandToolHost): void { this.host = host; }\n\n /**\n * Crop + cellpose-segment every rectangle; append the cell regions and drop\n * the prompt rectangles that produced cells. Returns the number of regions added.\n */\n async segmentBoxes(segmenter: ICellSegmenter): Promise<number> {\n if (!this.host) return 0;\n const cached = this.host.getCachedImageData();\n if (!cached || cached.frames.length === 0) { this.status$.next('No image loaded.'); return 0; }\n\n const regions = this.host.getRegions();\n const rects = regions.filter((r) => r.bounds instanceof Rectangle);\n if (rects.length === 0) {\n this.status$.next('Draw one or more rectangles, then run Cellpose.');\n return 0;\n }\n\n const rx = cached.ratios[0] || 1;\n const ry = cached.ratios[0] || 1;\n const ox = cached.originX ?? 0;\n const oy = cached.originY ?? 0;\n const frameIdx = this.host.getActiveFrameIndex();\n\n this.busy$.next(true);\n try {\n const masks: Region[] = [];\n const consumed = new Set<Region>();\n let added = 0;\n for (let i = 0; i < rects.length; i++) {\n const b = rects[i].bounds as Rectangle;\n // Prefix each phase with the box index when there's more than one.\n const prefix = rects.length > 1 ? `Box ${i + 1}/${rects.length}: ` : '';\n this.status$.next(`${prefix}Cropping…`);\n await tick(); // let the status paint before the (main-thread) crop\n const crop = cropImageRegion(\n cached, frameIdx, { x0: b.x, y0: b.y, x1: b.x + b.width, y1: b.y + b.height },\n );\n if (!crop) continue;\n const seg = await segmenter.segmentCells(\n { data: crop.data, width: crop.width, height: crop.height },\n { onProgress: (f) => this.progress$.next(f), onStatus: (s) => this.status$.next(prefix + s) },\n );\n this.status$.next(`${prefix}Tracing cells…`);\n await tick(); // paint before the (main-thread) contour tracing\n const polys = this.wandService.labelsToPolygons(\n seg.labels, seg.width, seg.height, seg.width, seg.height, 0, 0,\n );\n if (polys.length === 0) continue;\n for (const poly of polys) {\n // crop-pixel → frame-matrix (offset by crop origin) → data coords.\n const xData = poly.xpoints.map((x) => ox + (crop.matrixX0 + x) * rx);\n const yData = poly.ypoints.map((y) => oy + (crop.matrixY0 + y) * ry);\n masks.push(this.makeRegion(xData, yData, rects[i].color)); // inherit the box's color\n added++;\n }\n consumed.add(rects[i]);\n }\n this.host.setRegions(regions.filter((r) => !consumed.has(r)).concat(masks));\n this.status$.next(added > 0 ? `Added ${added} cell region(s).` : 'No cells found.');\n return added;\n } catch (err) {\n this.status$.next(err instanceof Error ? err.message : 'Cellpose segmentation failed.');\n return 0;\n } finally {\n this.busy$.next(false);\n this.progress$.next(-1);\n }\n }\n\n private makeRegion(xData: number[], yData: number[], color?: string): Region {\n const poly = new Polygon();\n poly.npoints = xData.length;\n poly.xpoints = xData;\n poly.ypoints = yData;\n poly.coordinates = xData.map((x, i) => [x, yData[i]]);\n poly.closed = true;\n const region = new Region();\n region.bounds = poly;\n // Inherit the source box's color; fall back to the host default.\n region.color = color || this.host.getShapeColor();\n region.label = 'cell';\n return region;\n }\n}\n","import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core';\nimport { MenuItem } from 'primeng/api';\n\nimport { IImageInfo } from '../contracts/image.contract';\nimport {\n PlotType,\n PlotTypeDescriptor,\n isNapari3d,\n isNapariIsosurface,\n isNapariSurface,\n isNapariScatter,\n NAPARI_DECIMATE_OPTIONS,\n NAPARI_DEFAULT_DECIMATE,\n} from '../contracts/plot-type';\nimport { ToolbarToolVisibility, ALL_TOOLBAR_TOOLS } from '../contracts/toolbar-config';\n\n/**\n * Presentational toolbar for the plotting viewport.\n *\n * Renders the plot-type selector, colormap/LUT controls, stack navigation,\n * image actions (download / autoscale / pipeline), viewport zoom/pan, the\n * Surface-3D camera controls, and the region-drawing tools — plus the plotting\n * help dialog. It owns no rendering or visualization state: the host\n * (VisualizerComponent) stays the orchestrator, passing state in via `@Input` and\n * handling every action via `@Output`. The same actions are also driven by the\n * diagram's right-click context menu and keyboard shortcuts, so keeping the\n * handlers in the host avoids duplicating that logic.\n */\n@Component({\n // Canonical prefixed selector first; the unprefixed original is kept as an\n // alias for one release (pre-publication back-compat).\n selector: 'plotting-toolbar',\n templateUrl: './toolbar.component.html',\n styleUrls: ['./toolbar.component.scss'],\n})\nexport class ToolbarComponent implements OnChanges {\n /** Current image (gates which control groups are shown). */\n @Input() imageInfo: IImageInfo | undefined;\n /** Plot types the active backend advertises. */\n @Input() plotTypeOptions: PlotTypeDescriptor[] = [];\n @Input() selectedPlotType: PlotType = PlotType.IMAGE;\n /** Isosurface band as a 0–255 slider position (mapped onto the volume's real\n * intensity range by the renderer). Defaults to the full range. */\n @Input() isoRange: number[] = [0, 255];\n @Input() maxIndex = 0;\n @Input() zIndex = 0;\n /** True for any 2D (non Surface-3D) plot type. */\n @Input() isHeatmap = true;\n @Input() activeDragMode: string | null = null;\n @Input() activeSurface3dMode = 'turntable';\n /** Whether the napari 3D axes/scale gizmo is currently shown (drives the toggle's look). */\n @Input() axesVisible = true;\n @Input() wireframeActive = false;\n /** Active napari 3D decimate factor (1 = Full … 8 = ⅛; default ½). */\n @Input() resolutionScale = NAPARI_DEFAULT_DECIMATE;\n /** Decimate-factor options for the Resolution dropdown. */\n readonly decimateOptions = NAPARI_DECIMATE_OPTIONS;\n @Input() wandSensitivity = 2.0;\n @Input() brushSize = 40;\n @Input() vertexEraserRadius = 20;\n /** Whether a region action is available to undo (jit-ui#85). Greys out the\n * Undo button when false (nothing done yet, or all steps already undone). */\n @Input() canUndo = false;\n /** Whether an undone region action is available to redo (jit-ui#85). Greys\n * out the Redo button when false. */\n @Input() canRedo = false;\n @Input() stackOptions: { name: string; val: string }[] =\n [{ name: 'Single image', val: 'false' }, { name: 'Stack', val: 'true' }];\n /** Which toolbar groups to show. Defaults to the full toolbar; the host forwards\n * the consumer's choice (e.g. the pipeline shows only zoom + region tools). */\n @Input() tools: Required<ToolbarToolVisibility> = ALL_TOOLBAR_TOOLS;\n /** Current image-smoothing state (drives the Smoothen toggle button look).\n * `false` = nearest-neighbour (crisp raw pixels), the default. */\n @Input() imageSmoothingEnabled = false;\n /** SAM model picker options + current selection (jit-ui#90 P1). */\n @Input() samModels: { id: string; label: string }[] = [];\n @Input() samModelId = '';\n\n @Output() selectPlotType = new EventEmitter<PlotType>();\n /** Intensity (LINE) mode: add another colored line ROI + inset trace. */\n @Output() addProfileLine = new EventEmitter<void>();\n /** Toggle image smoothing (bilinear) vs nearest-neighbour (crisp pixels). */\n @Output() toggleImageSmoothing = new EventEmitter<void>();\n // PrimeNG slider/inputNumber change events carry optional values, mirrored by\n // the host handlers (which accept `| undefined`).\n @Output() isoRangeChange = new EventEmitter<number[] | undefined>();\n /** Open the Channels & Histogram dialog (brightness/contrast, colormap, …). */\n @Output() openChannelHistogram = new EventEmitter<void>();\n @Output() openRegionEditor = new EventEmitter<void>();\n @Output() selectStackOption = new EventEmitter<{ name: string; val: string }>();\n @Output() zScrub = new EventEmitter<number | undefined>();\n @Output() zSlide = new EventEmitter<number | undefined>();\n @Output() zIndexInput = new EventEmitter<number>();\n @Output() reloadAndPlot = new EventEmitter<void>();\n @Output() downloadImage = new EventEmitter<void>();\n @Output() autoscaleImage = new EventEmitter<void>();\n @Output() toggleDragMode = new EventEmitter<string>();\n @Output() zoomIn = new EventEmitter<void>();\n @Output() zoomOut = new EventEmitter<void>();\n @Output() toggleSurface3dMode = new EventEmitter<string>();\n @Output() resetSurfaceCamera = new EventEmitter<void>();\n /** Toggle the napari 3D coordinate-axes / scale gizmo on/off. */\n @Output() toggleAxes = new EventEmitter<void>();\n /** Toggle the napari surface wireframe (edges) on/off. */\n @Output() toggleWireframe = new EventEmitter<void>();\n /** Change the napari 3D decimate factor (reloads at the new resolution). */\n @Output() selectResolution = new EventEmitter<number>();\n @Output() deleteRegion = new EventEmitter<void>();\n /** Undo the last region action (jit-ui#85). */\n @Output() undoRegion = new EventEmitter<void>();\n /** Redo the last undone region action (jit-ui#85). */\n @Output() redoRegion = new EventEmitter<void>();\n /** Run box-prompted SAM segmentation on the drawn rectangles (jit-ui#90). */\n @Output() segmentRegions = new EventEmitter<void>();\n /** Run cellpose-SAM (auto) inside each drawn rectangle's crop (jit-ui#90). */\n @Output() segmentCellpose = new EventEmitter<void>();\n /** SAM model picker (jit-ui#90 P1). */\n @Output() samModelChange = new EventEmitter<string>();\n @Output() wandSensitivityChange = new EventEmitter<number | undefined>();\n @Output() brushSizeChange = new EventEmitter<number | undefined>();\n @Output() vertexEraserRadiusChange = new EventEmitter<number | undefined>();\n\n /** Sliders' bounds — toolbar UI constants (the values are host-owned). */\n readonly wandSensitivityMin = 0.5;\n readonly wandSensitivityMax = 10.0;\n readonly wandSensitivityStep = 0.1;\n readonly brushSizeMin = 5;\n readonly brushSizeMax = 300;\n readonly brushSizeStep = 5;\n readonly vertexEraserRadiusMin = 5;\n readonly vertexEraserRadiusMax = 300;\n readonly vertexEraserRadiusStep = 5;\n readonly isoValueMin = 0;\n readonly isoValueMax = 255;\n readonly isoValueStep = 1;\n\n displayHelpDialog = false;\n\n /** Model picker for the Segment button's dropdown menu. The active model\n * (`samModelId`) is marked with a check; selecting an item emits\n * `samModelChange` (jit-ui#90 P1).\n *\n * Held as a stable array (rebuilt only when `samModels`/`samModelId` change),\n * NOT a getter: a getter returns a fresh array with new `command` closures on\n * every change-detection tick, which makes the bound `p-menu` overlay rebuild\n * its DOM mid-interaction and swallow the click on a menu item. */\n samMenuItems: MenuItem[] = [];\n\n /** Rebuild the SAM model menu when the model list or active selection\n * changes (keeps the array reference stable across other CD ticks). */\n ngOnChanges(changes: SimpleChanges): void {\n if (changes['samModels'] || changes['samModelId']) {\n this.samMenuItems = this.samModels.map((m) => ({\n label: m.label,\n icon: m.id === this.samModelId ? 'pi pi-check' : 'pi pi-fw',\n command: () => this.samModelChange.emit(m.id),\n }));\n }\n }\n\n /** The Image plot type renders as a natively pan/zoom-able raster, so the\n * generic zoom/pan tools are hidden. */\n get isImageView(): boolean {\n return this.selectedPlotType === PlotType.IMAGE;\n }\n\n /** A plot-type icon is a PrimeNG font glyph (e.g. `pi pi-image`) rather than an\n * SVG asset path — drives which element the selector item template renders. */\n isPiIcon(icon: string | undefined): boolean {\n return !!icon && icon.startsWith('pi ');\n }\n\n /** Backends with a vertex-editing region overlay: OSD Image and napari-js WebGPU image\n * (jit-ui#102). Gates the polygon / add-vertex / delete-vertex / Bézier-convert tools. */\n get supportsRegionVertexTools(): boolean {\n return (\n this.selectedPlotType === PlotType.IMAGE ||\n this.selectedPlotType === PlotType.NAPARI_IMAGE\n );\n }\n\n /** Plot types that scrub a z-stack live (the renderer swaps the slice in place): the OSD Image\n * view, the napari-js WebGPU image, and the napari-js surface — which rebuilds the height field\n * from the picked slice (jit-ui#102). Drives the per-slice slider. */\n get showsLiveSliceScrubber(): boolean {\n return (\n this.selectedPlotType === PlotType.IMAGE ||\n this.selectedPlotType === PlotType.NAPARI_IMAGE ||\n isNapariSurface(this.selectedPlotType) ||\n isNapariScatter(this.selectedPlotType)\n );\n }\n\n /** Any napari-js WebGPU plot type. The single-image/stack toggle + slice-number field are\n * Plotly-only stack controls, so they're hidden for napari (jit-ui#102). */\n get isNapariMode(): boolean {\n return (\n this.selectedPlotType === PlotType.NAPARI_IMAGE ||\n isNapariScatter(this.selectedPlotType) ||\n isNapari3d(this.selectedPlotType)\n );\n }\n\n /** ISOSURFACE (Plotly or napari-js WebGPU, either resolution) shows the isovalue range slider. */\n get isIsosurfaceMode(): boolean {\n return (\n this.selectedPlotType === PlotType.ISOSURFACE || isNapariIsosurface(this.selectedPlotType)\n );\n }\n\n /** The napari-js WebGPU surface — shows the wireframe toggle. */\n get isNapariSurfaceMode(): boolean {\n return isNapariSurface(this.selectedPlotType);\n }\n\n /** Any napari-js WebGPU 3D type (volume/isosurface/surface) — shows the Resolution control. */\n get isNapari3dMode(): boolean {\n return isNapari3d(this.selectedPlotType);\n }\n\n /** Intensity profile lines are Region-based and available in the Heatmap and\n * Image plot types, which show the Intensity tool group. */\n get isIntensityCapable(): boolean {\n return this.selectedPlotType === PlotType.HEATMAP || this.selectedPlotType === PlotType.IMAGE;\n }\n\n showHelp(): void {\n this.displayHelpDialog = true;\n }\n}\n","<p-toolbar>\n <div class=\"p-toolbar-group-start flex-wrap align-items-center gap-1\">\n\n <!-- Host-provided custom toolbar buttons, shown first (e.g. app-specific\n actions the visualization view itself doesn't own). -->\n <ng-content></ng-content>\n\n <!-- Plot type: available for any image (grayscale or RGB). -->\n <ng-container *ngIf=\"imageInfo && tools.specialTools\">\n <span class=\"toolbar-separator\"></span>\n <p-dropdown [options]=\"plotTypeOptions\" optionLabel=\"label\" optionValue=\"type\"\n [(ngModel)]=\"selectedPlotType\" appendTo=\"body\"\n pTooltip=\"Select plot type\" tooltipPosition=\"bottom\"\n [style]=\"{'min-width': '11rem'}\"\n styleClass=\"plotmode-dropdown\" panelStyleClass=\"plotmode-panel\"\n (onChange)=\"selectPlotType.emit($event.value)\">\n <ng-template let-opt pTemplate=\"selectedItem\">\n <span class=\"plotmode-item\" *ngIf=\"opt\">\n <i *ngIf=\"isPiIcon(opt.icon)\" [class]=\"opt.icon\"></i>\n <img *ngIf=\"opt.icon && !isPiIcon(opt.icon)\" class=\"plotmode-icon-img\" [src]=\"opt.icon\" alt=\"\" />\n <span>{{ opt.label }}</span>\n </span>\n </ng-template>\n <ng-template let-opt pTemplate=\"item\">\n <span class=\"plotmode-item\">\n <i *ngIf=\"isPiIcon(opt.icon)\" [class]=\"opt.icon\"></i>\n <img *ngIf=\"opt.icon && !isPiIcon(opt.icon)\" class=\"plotmode-icon-img\" [src]=\"opt.icon\" alt=\"\" />\n <span>{{ opt.label }}</span>\n </span>\n </ng-template>\n </p-dropdown>\n <ng-container *ngIf=\"isIsosurfaceMode\">\n <span class=\"flex align-items-center mx-1 toolbar-text\">Iso</span>\n <p-slider [(ngModel)]=\"isoRange\" [range]=\"true\"\n [min]=\"isoValueMin\" [max]=\"isoValueMax\" [step]=\"isoValueStep\"\n (onChange)=\"isoRangeChange.emit($event.values)\"\n pTooltip=\"Isosurface band (0–255), mapped onto the volume's\n actual intensity range. Surfaces are drawn for voxels whose\n intensity falls in the selected band — narrow it to isolate\n features, widen it to see the whole structure.\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n styleClass=\"wand-sensitivity-slider\"></p-slider>\n <span class=\"flex align-items-center mx-1 toolbar-text wand-sensitivity-value\">\n {{ isoRange[0] }}–{{ isoRange[1] }}</span>\n </ng-container>\n <!-- Intensity tools (Heatmap / Image mode): add another colored line ROI.\n Each added line gets the next bright palette colour and its own inset\n trace; select a line on the image and use the trash tool to remove it\n (and its trace). The lines are Region-based but excluded from the\n Region Editor and exports. -->\n <ng-container *ngIf=\"isIntensityCapable\">\n <span class=\"toolbar-separator\"></span>\n <p-button size=\"small\" [text]=\"true\"\n pTooltip=\"Add an intensity line (new colour). Click a line to select it,\n then use the trash tool to remove it.\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"addProfileLine.emit()\">\n <img src=\"assets/plotting/spline-chart.svg\" class=\"toolbar-icon-dark\" style=\"width: 1rem\"/>\n </p-button>\n </ng-container>\n </ng-container>\n <!-- Channels & Histogram: brightness/contrast, gamma, per-channel display,\n colormap/reverse/invert — opens the floating dialog. -->\n <p-button *ngIf=\"tools.specialTools\" pRipple size=\"small\" [text]=\"true\"\n pTooltip=\"Channels & Histogram (brightness/contrast, colormap)\"\n tooltipPosition=\"bottom\"\n (onClick)=\"openChannelHistogram.emit()\">\n <img src=\"assets/plotting/invert.svg\" class=\"toolbar-icon-dark\" style=\"width: 1rem\"/>\n </p-button>\n\n <!-- Smoothen toggle: bilinear smoothing vs nearest-neighbour raw pixels (Image\n view only — it's an OpenSeadragon drawer setting). Highlighted when smoothing on. -->\n <p-button *ngIf=\"tools.specialTools && isImageView\" size=\"small\"\n [text]=\"!imageSmoothingEnabled\"\n pTooltip=\"Smoothen (turn on image smoothing)\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleImageSmoothing.emit()\">\n <img src=\"assets/plotting/smooth.svg\" style=\"width: 1rem\"\n [class]=\"imageSmoothingEnabled ? 'toolbar-icon-active' : 'toolbar-icon-dark'\"/>\n </p-button>\n\n <!-- Stack controls -->\n <ng-container *ngIf=\"imageInfo?.isStack\">\n <span class=\"toolbar-separator\"></span>\n <!-- Image view: scrub z-slices live (the renderer swaps slices in place). -->\n <ng-container *ngIf=\"showsLiveSliceScrubber\">\n <span class=\"flex align-items-center mx-1 toolbar-text\">Slice</span>\n <p-slider [(ngModel)]=\"zIndex\" [min]=\"0\" [max]=\"maxIndex\"\n (onChange)=\"zScrub.emit($event.value)\" (onSlideEnd)=\"zSlide.emit($event.value)\"\n pTooltip=\"Slice through the stack (← / → keys)\" tooltipPosition=\"bottom\"\n [style]=\"{'width':'16rem'}\" styleClass=\"wand-sensitivity-slider\"></p-slider>\n <span class=\"flex align-items-center mx-1 toolbar-text\">{{zIndex}} of {{maxIndex}}</span>\n </ng-container>\n <!-- Heatmap view: single-image (high-def zoom) vs stack (frame slider). Plotly-only —\n hidden for napari, which has no single/stack toggle or per-frame fetch. -->\n <ng-container *ngIf=\"!showsLiveSliceScrubber && !isNapariMode\">\n <p-button icon=\"pi pi-image\" size=\"small\"\n [text]=\"imageInfo?.showStack\"\n pTooltip=\"Single image mode: enables high-def zoom\" tooltipPosition=\"bottom\"\n (onClick)=\"selectStackOption.emit(stackOptions[0])\">\n </p-button>\n <p-button icon=\"pi pi-images\" size=\"small\"\n [text]=\"!imageInfo?.showStack\"\n pTooltip=\"Stack mode, enables slicing through image frames\" tooltipPosition=\"bottom\"\n (onClick)=\"selectStackOption.emit(stackOptions[1])\">\n </p-button>\n <ng-container *ngIf=\"!imageInfo?.showStack\">\n <span class=\"flex align-items-center mx-1 toolbar-text\">Slice</span>\n <div class=\"p-inputgroup\" style=\"width: auto\">\n <p-inputNumber styleClass=\"w-3rem toolbar-input\"\n\t\t\t\t\tpTooltip=\"View image in stack (⏎)\"\n\t\t\t\t\t[(ngModel)]=\"zIndex\" [min]=\"0\" [max]=\"maxIndex\"\n (onInput)=\"zIndexInput.emit(zIndex)\" (keydown.enter)=\"reloadAndPlot.emit()\"/>\n <p-button icon=\"pi pi-refresh\" size=\"small\" [text]=\"true\" (onClick)=\"reloadAndPlot.emit()\"\n pTooltip=\"Plot this slice\" tooltipPosition=\"bottom\">\n </p-button>\n </div>\n <span class=\"flex align-items-center mx-1 toolbar-text\">of {{maxIndex}}</span>\n </ng-container>\n </ng-container>\n </ng-container>\n\n <!-- Image actions (special tools) -->\n <ng-container *ngIf=\"tools.specialTools\">\n <span class=\"toolbar-separator\"></span>\n <p-button icon=\"pi pi-download\" size=\"small\" [text]=\"true\"\n pTooltip=\"Download image as PNG\" tooltipPosition=\"bottom\"\n (onClick)=\"downloadImage.emit()\">\n </p-button>\n <p-button *ngIf=\"isHeatmap\" icon=\"pi pi-window-maximize\" size=\"small\" [text]=\"true\"\n pTooltip=\"Fit to view\" tooltipPosition=\"bottom\"\n (onClick)=\"autoscaleImage.emit()\">\n </p-button>\n </ng-container>\n\n <!-- Zoom tools. Plotly rubber-band drag-zoom: on OpenSeadragon the box-zoom\n covers this and a bare drag pans natively, so it's hidden in image view. -->\n <ng-container *ngIf=\"isHeatmap && tools.zoomTools\">\n <span class=\"toolbar-separator\"></span>\n <p-button *ngIf=\"!isImageView\" icon=\"pi pi-search\" size=\"small\"\n [text]=\"activeDragMode !== 'zoom'\"\n pTooltip=\"Zoom drag\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('zoom')\">\n </p-button>\n <p-button size=\"small\"\n [text]=\"activeDragMode !== 'zoomToBox'\"\n pTooltip=\"Zoom box (<kbd>b</kbd>)\" [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('zoomToBox')\">\n <img src=\"assets/plotting/zoom-box.svg\"\n [class]=\"activeDragMode === 'zoomToBox' ? 'toolbar-icon-active' : 'toolbar-icon-dark'\"\n style=\"width: 1rem\"/>\n </p-button>\n <p-button icon=\"pi pi-arrows-alt\" size=\"small\"\n [text]=\"activeDragMode !== 'pan'\"\n pTooltip=\"Pan the image (<kbd>p</kbd>)\" [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('pan')\">\n </p-button>\n <p-button icon=\"pi pi-search-plus\" size=\"small\" [text]=\"true\"\n pTooltip=\"Zoom in (<kbd>+</kbd>)\" [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"zoomIn.emit()\">\n </p-button>\n <p-button icon=\"pi pi-search-minus\" size=\"small\" [text]=\"true\"\n pTooltip=\"Zoom out (<kbd>-</kbd>)\" [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"zoomOut.emit()\">\n </p-button>\n </ng-container>\n\n <!-- Surface 3D controls -->\n <ng-container *ngIf=\"!isHeatmap\">\n <span class=\"toolbar-separator\"></span>\n <p-button icon=\"pi pi-search\" size=\"small\"\n [text]=\"activeSurface3dMode !== 'zoom'\"\n pTooltip=\"Zoom\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleSurface3dMode.emit('zoom')\">\n </p-button>\n <p-button icon=\"pi pi-arrows-alt\" size=\"small\"\n [text]=\"activeSurface3dMode !== 'pan'\"\n pTooltip=\"Pan\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleSurface3dMode.emit('pan')\">\n </p-button>\n <p-button icon=\"pi pi-globe\" size=\"small\"\n [text]=\"activeSurface3dMode !== 'orbit'\"\n pTooltip=\"Orbital rotation\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleSurface3dMode.emit('orbit')\">\n </p-button>\n <p-button icon=\"pi pi-sync\" size=\"small\"\n [text]=\"activeSurface3dMode !== 'turntable'\"\n pTooltip=\"Turntable rotation\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleSurface3dMode.emit('turntable')\">\n </p-button>\n <p-button icon=\"pi pi-home\" size=\"small\" [text]=\"true\"\n pTooltip=\"Reset camera to default\" tooltipPosition=\"bottom\"\n (onClick)=\"resetSurfaceCamera.emit()\">\n </p-button>\n <!-- 3D coordinate-axes / scale gizmo toggle (napari-js WebGPU volume/isosurface only).\n `p-button-icon-only` gives the same square sizing as the neighbouring pi-icon buttons\n (the projected <img> doesn't trigger PrimeNG's automatic icon-only sizing). -->\n <p-button size=\"small\" *ngIf=\"isNapariMode\" styleClass=\"p-button-icon-only\"\n [text]=\"!axesVisible\"\n pTooltip=\"Toggle 3D axes / scale\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleAxes.emit()\">\n <img src=\"assets/plotting/3d-coordinates.svg\"\n [class]=\"axesVisible ? 'toolbar-icon-active' : 'toolbar-icon-dark'\"\n style=\"width: 1rem\"/>\n </p-button>\n <!-- Surface wireframe toggle (napari-js WebGPU surface only). -->\n <p-button icon=\"pi pi-share-alt\" size=\"small\" *ngIf=\"isNapariSurfaceMode\"\n [text]=\"!wireframeActive\"\n pTooltip=\"Toggle wireframe\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleWireframe.emit()\">\n </p-button>\n <!-- Resolution (decimate factor) for the napari 3D types — reloads at coarser/finer sampling. -->\n <ng-container *ngIf=\"isNapari3dMode\">\n <span class=\"flex align-items-center mx-1 toolbar-text\">Res</span>\n <p-dropdown [options]=\"decimateOptions\" optionLabel=\"label\" optionValue=\"value\"\n [ngModel]=\"resolutionScale\" appendTo=\"body\"\n pTooltip=\"Resolution (decimate factor)\" tooltipPosition=\"bottom\"\n [style]=\"{'min-width': '6rem'}\"\n (onChange)=\"selectResolution.emit($event.value)\">\n </p-dropdown>\n </ng-container>\n </ng-container>\n\n <ng-container *ngIf=\"isHeatmap && tools.regionTools\">\n <span class=\"toolbar-separator\"></span>\n <!-- Region Editor: opens the editor as a floating dialog (formerly the\n right-panel Regions tab). Sits with the region drawing tools. -->\n <p-button size=\"small\" [text]=\"true\"\n pTooltip=\"Open the Region Editor\" tooltipPosition=\"bottom\"\n (onClick)=\"openRegionEditor.emit()\">\n <img src=\"assets/plotting/region-editor.svg\" class=\"toolbar-icon-dark\" style=\"width: 1rem\"/>\n </p-button>\n <!-- Region drawing tools -->\n <p-button icon=\"pi pi-arrow-up-right\" size=\"small\"\n [text]=\"activeDragMode !== 'select'\"\n pTooltip=\"Selection mode (<kbd>s</kbd>)\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('select')\">\n </p-button>\n <p-button icon=\"pi pi-stop\" size=\"small\"\n [text]=\"activeDragMode !== 'drawrect'\"\n pTooltip=\"Draw a rectangular region (<kbd>r</kbd>)\" [escape]=\"false\"\n tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('drawrect')\">\n </p-button>\n <p-button size=\"small\"\n [text]=\"activeDragMode !== 'drawopenpath'\"\n pTooltip=\"Draw a polyline (<kbd>l</kbd>)\" [escape]=\"false\"\n tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('drawopenpath')\">\n <img src=\"assets/plotting/polyline.svg\"\n [class]=\"activeDragMode === 'drawopenpath' ? 'toolbar-icon-active' : 'toolbar-icon-dark'\"\n style=\"width: 1rem\"/>\n </p-button>\n <p-button icon=\"pi pi-pencil\" size=\"small\"\n [text]=\"activeDragMode !== 'drawclosedpath'\"\n pTooltip=\"Draw a freeform region (<kbd>f</kbd>)\" [escape]=\"false\"\n tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('drawclosedpath')\">\n </p-button>\n <!-- Brush: paint a region by dragging a disc of the given size; the Size\n slider appears while it's active. Hold Shift to erase (subtract). -->\n <p-button size=\"small\"\n [text]=\"activeDragMode !== 'brush'\"\n pTooltip=\"Brush: click and drag to paint a region.\n <br>Hold <kbd>Shift</kbd> while painting to erase from a region.\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('brush')\">\n <img src=\"assets/plotting/paintbrush.svg\"\n [class]=\"activeDragMode === 'brush' ? 'toolbar-icon-active' : 'toolbar-icon-dark'\"\n style=\"width: 1rem\"/>\n </p-button>\n <ng-container *ngIf=\"activeDragMode === 'brush'\">\n <span class=\"flex align-items-center mx-1 toolbar-text\">Size</span>\n <p-slider [(ngModel)]=\"brushSize\"\n [min]=\"brushSizeMin\" [max]=\"brushSizeMax\" [step]=\"brushSizeStep\"\n (onChange)=\"brushSizeChange.emit($event.value)\"\n pTooltip=\"Brush diameter in image pixels.\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n styleClass=\"wand-sensitivity-slider\"></p-slider>\n <span class=\"flex align-items-center mx-1 toolbar-text wand-sensitivity-value\">\n {{ brushSize }}</span>\n </ng-container>\n\n <!-- Vertex editing — backends with a vertex-editing overlay (OSD + napari-js image). -->\n <ng-container *ngIf=\"supportsRegionVertexTools\">\n <p-button size=\"small\"\n [text]=\"activeDragMode !== 'drawpolygon'\"\n pTooltip=\"Polygon: click to place each vertex; click the first point to close\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('drawpolygon')\">\n <img src=\"assets/plotting/polygon-vertices.svg\"\n [class]=\"activeDragMode === 'drawpolygon' ? 'toolbar-icon-active' : 'toolbar-icon-dark'\"\n style=\"width: 1rem\"/>\n </p-button>\n <p-button size=\"small\"\n [text]=\"activeDragMode !== 'addpoint'\"\n pTooltip=\"Add a vertex: click an edge of the selected polygon\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('addpoint')\">\n <img src=\"assets/plotting/vertex-add.svg\"\n [class]=\"activeDragMode === 'addpoint' ? 'toolbar-icon-active' : 'toolbar-icon-dark'\"\n style=\"width: 1rem\"/>\n </p-button>\n <p-button size=\"small\"\n [text]=\"activeDragMode !== 'deletepoint'\"\n pTooltip=\"Delete a vertex: click a vertex of the selected polygon\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('deletepoint')\">\n <img src=\"assets/plotting/vertex-delete.svg\"\n [class]=\"activeDragMode === 'deletepoint' ? 'toolbar-icon-active' : 'toolbar-icon-dark'\"\n style=\"width: 1rem\"/>\n </p-button>\n </ng-container>\n\n <p-button size=\"small\"\n [text]=\"activeDragMode !== 'wand'\"\n pTooltip=\"Wand: click and drag to grow a region by similar pixel values (<kbd>w</kbd>).\n <br>Hold <kbd>Shift</kbd> while clicking or dragging on a region to erase pixels from it.\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('wand')\">\n <img src=\"assets/plotting/wand.svg\"\n [class]=\"activeDragMode === 'wand' ? 'toolbar-icon-active' : 'toolbar-icon-dark'\"\n style=\"width: 1rem\"/>\n </p-button>\n <ng-container *ngIf=\"activeDragMode === 'wand'\">\n <span class=\"flex align-items-center mx-1 toolbar-text\">Sens.</span>\n <p-slider [(ngModel)]=\"wandSensitivity\"\n [min]=\"wandSensitivityMin\" [max]=\"wandSensitivityMax\" [step]=\"wandSensitivityStep\"\n (onChange)=\"wandSensitivityChange.emit($event.value)\"\n pTooltip=\"Higher = stricter (smaller selection); lower = looser.\n Takes effect from the next click/drag tick.\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n styleClass=\"wand-sensitivity-slider\"></p-slider>\n <span class=\"flex align-items-center mx-1 toolbar-text wand-sensitivity-value\">\n {{ wandSensitivity.toFixed(1) }}</span>\n </ng-container>\n <p-button icon=\"pi pi-eraser\" size=\"small\"\n [text]=\"activeDragMode !== 'eraseVertex'\"\n pTooltip=\"Vertex eraser (<kbd>e</kbd>): click or drag to remove polygon vertices inside\n the cursor circle from any region.\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('eraseVertex')\">\n </p-button>\n <ng-container *ngIf=\"activeDragMode === 'eraseVertex'\">\n <span class=\"flex align-items-center mx-1 toolbar-text\">Radius</span>\n <p-slider [(ngModel)]=\"vertexEraserRadius\"\n [min]=\"vertexEraserRadiusMin\" [max]=\"vertexEraserRadiusMax\" [step]=\"vertexEraserRadiusStep\"\n (onChange)=\"vertexEraserRadiusChange.emit($event.value)\"\n pTooltip=\"Eraser radius in image pixels.\n Vertices within this distance of the cursor are removed.\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n styleClass=\"wand-sensitivity-slider\"></p-slider>\n <span class=\"flex align-items-center mx-1 toolbar-text wand-sensitivity-value\">\n {{ vertexEraserRadius }}</span>\n </ng-container>\n <p-button size=\"small\" [text]=\"true\"\n [disabled]=\"!canUndo\"\n pTooltip=\"Undo the last region action (<kbd>Ctrl</kbd>+<kbd>Z</kbd>).\n Up to 10 actions can be undone.\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"undoRegion.emit()\">\n <img src=\"assets/plotting/undo.svg\" class=\"toolbar-icon-dark\" style=\"width: 1rem\"/>\n </p-button>\n <p-button size=\"small\" [text]=\"true\"\n [disabled]=\"!canRedo\"\n pTooltip=\"Redo the last undone region action\n (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> / <kbd>Ctrl</kbd>+<kbd>Y</kbd>).\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"redoRegion.emit()\">\n <img src=\"assets/plotting/redo.svg\" class=\"toolbar-icon-dark\" style=\"width: 1rem\"/>\n </p-button>\n <p-button icon=\"pi pi-trash\" size=\"small\" [text]=\"true\"\n pTooltip=\"Delete selected region (<kbd>Del</kbd>)\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"deleteRegion.emit()\">\n </p-button>\n <!-- SAM (jit-ui#90): box-prompt segment, interactive point prompts, and a\n model picker. -->\n <span class=\"toolbar-separator\"></span>\n <!-- SAM controls grouped: box-prompt Segment, then the point-prompt tool,\n then the model-picker dropdown (the chevron) which governs BOTH tools.\n Falls back to Segment + point with no model picker when none are set. -->\n <span *ngIf=\"samModels.length; else segmentPlain\" class=\"p-buttonset segment-split\">\n <p-button size=\"small\" [text]=\"true\"\n pTooltip=\"Segment the drawn rectangles with SAM (box prompt)\"\n tooltipPosition=\"bottom\"\n (onClick)=\"segmentRegions.emit()\">\n <img src=\"assets/plotting/picture-segmentation.svg\"\n class=\"toolbar-icon-dark\" style=\"width: 1rem\"/>\n </p-button>\n <ng-container [ngTemplateOutlet]=\"samPointBtn\"></ng-container>\n <p-button icon=\"pi pi-chevron-down\" size=\"small\" [text]=\"true\"\n pTooltip=\"Pick the SAM model (used by both segment tools)\"\n tooltipPosition=\"bottom\"\n (onClick)=\"samModelMenu.toggle($event)\">\n </p-button>\n </span>\n <ng-template #segmentPlain>\n <span class=\"p-buttonset segment-split\">\n <p-button size=\"small\" [text]=\"true\"\n pTooltip=\"Segment the drawn rectangles with SAM (box prompt)\"\n tooltipPosition=\"bottom\"\n (onClick)=\"segmentRegions.emit()\">\n <img src=\"assets/plotting/picture-segmentation.svg\"\n class=\"toolbar-icon-dark\" style=\"width: 1rem\"/>\n </p-button>\n <ng-container [ngTemplateOutlet]=\"samPointBtn\"></ng-container>\n </span>\n </ng-template>\n <!-- Point-prompt tool — shared between the models / no-models layouts so it\n always sits just left of the model dropdown. -->\n <ng-template #samPointBtn>\n <p-button size=\"small\"\n [text]=\"activeDragMode !== 'samPoint'\"\n pTooltip=\"SAM point prompts: click a fiber to segment it as a new region;\n Shift/Alt-click to refine (exclude) the current one.<br>Esc undoes it.\"\n [escape]=\"false\" tooltipPosition=\"bottom\"\n (onClick)=\"toggleDragMode.emit('samPoint')\">\n <img src=\"assets/plotting/click.svg\"\n [class]=\"activeDragMode === 'samPoint' ? 'toolbar-icon-active' : 'toolbar-icon-dark'\"\n style=\"width: 1rem\"/>\n </p-button>\n </ng-template>\n <p-menu #samModelMenu [model]=\"samMenuItems\" [popup]=\"true\" appendTo=\"body\"></p-menu>\n <!-- Help: explains the ViT-T vs ViT-B trade-off behind the model picker. -->\n <p-button *ngIf=\"samModels.length\" icon=\"pi pi-info-circle\" size=\"small\" [text]=\"true\"\n pTooltip=\"About the SAM models\" tooltipPosition=\"bottom\"\n (onClick)=\"samModelInfo.toggle($event)\">\n </p-button>\n <p-overlayPanel #samModelInfo appendTo=\"body\" styleClass=\"sam-model-info\">\n <div style=\"max-width: 24rem; line-height: 1.4\">\n <div class=\"font-bold mb-1\">SAM models</div>\n <p class=\"mt-0 mb-2\">\n All are promptable Segment Anything models finetuned for biomedical images. They differ\n in the <i>image encoder</i> (the heavy once-per-image step) and the training domain —\n box and point prompting behave the same.\n </p>\n <div class=\"mb-2\">\n <div class=\"font-bold\">micro-sam ViT-T <span class=\"font-normal\">(default)</span></div>\n <div>Light-microscopy finetuned. TinyViT encoder, ~14 MB, very fast, runs on WASM.\n Good mask quality — best for quick interactive work and many/large objects.</div>\n </div>\n <div class=\"mb-2\">\n <div class=\"font-bold\">micro-sam ViT-B</div>\n <div>Light-microscopy finetuned. ViT-Base encoder, ~172 MB, slower, GPU-accelerated\n (WebGPU). Highest accuracy — when ViT-T misses subtle or overlapping boundaries.</div>\n </div>\n <div class=\"mb-2\">\n <div class=\"font-bold\">patho-sam ViT-B</div>\n <div>Histopathology finetuned (H&E / stained tissue). ViT-Base encoder, GPU-accelerated.\n Use it for pathology slides — it segments tissue/nuclei better than the microscopy models.</div>\n </div>\n <div class=\"mb-2\">\n <div class=\"font-bold\">patho-sam ViT-B (int8)</div>\n <div>Same model, int8-quantized — ~100 MB vs ~180 MB (smaller download). Runs on\n WASM (slower encode than the fp16 version); masks are near-identical. Pick it on slow\n connections.</div>\n </div>\n <div class=\"text-sm\" style=\"opacity: 0.75\">\n The choice applies to both the box and point tools. Each tool loads its own encoder,\n so the first click after switching re-encodes once.\n </div>\n </div>\n </p-overlayPanel>\n <p-button size=\"small\" [text]=\"true\"\n pTooltip=\"Auto-segment cells inside each drawn rectangle (cellpose-SAM, client-side)\"\n tooltipPosition=\"bottom\"\n (onClick)=\"segmentCellpose.emit()\">\n <img src=\"assets/plotting/cells.svg\" class=\"toolbar-icon-dark\" style=\"width: 1rem\"/>\n </p-button>\n </ng-container>\n\n <ng-container *ngIf=\"tools.help\">\n <span class=\"toolbar-separator\"></span>\n\n <!-- Help -->\n <p-button icon=\"pi pi-question-circle\" size=\"small\" [text]=\"true\"\n pTooltip=\"Help\" tooltipPosition=\"bottom\"\n (onClick)=\"showHelp()\">\n </p-button>\n </ng-container>\n\n </div>\n</p-toolbar>\n<p-dialog header=\"Plotting help\" [(visible)]=\"displayHelpDialog\" [modal]=\"true\" [style]=\"{width: '50vw'}\"\n [maximizable]=\"true\" [draggable]=\"false\" [resizable]=\"false\">\n <p>Click a file in the left-hand tree to display it. By default it opens in the\n <b>Image</b> view — a natively tiled, deeply zoomable raster (OpenSeadragon) with a\n navigator minimap and a physical-units scale bar. <b>Click the image to zoom</b> toward\n the clicked point; scroll to zoom and drag to pan. When a stack is open, a slice slider\n (Image view) or image-mode toggle (other views) appears. Regions can also be edited in the\n <b>Region Editor</b>, opened with the\n <img src=\"assets/plotting/region-editor.svg\" width=\"14\" height=\"14\" alt=\"Region Editor\"/>\n toolbar button as a floating dialog. Drag the <i class=\"pi pi-bars\"></i> handle to detach\n this toolbar into a floating window.\n </p>\n\n <h3>Plot-type dropdown</h3>\n <p>\n The <b>plot-type dropdown</b> switches how the file is visualized:\n <b>Image</b>, <b>Contour</b>, <b>Scatter (regions)</b>, <b>Surface (3D)</b>,\n <b>Scatter 3D</b>, and <b>Isosurface (3D)</b>. Scalar and 3D types require a grayscale\n image (the 3D volume types also require a z-stack). The non-image views render with\n Plotly and support \"real zooming\" (a downscaled overview that re-fetches higher\n resolution as you zoom in).\n </p>\n <ul>\n <li>\"<b>Isosurface band</b>\" slider (Isosurface): sets the intensity band the surfaces are\n drawn for, mapped onto the volume's real intensity range.</li>\n <li>\"<b>3D camera</b>\" (Surface / Scatter 3D / Isosurface): zoom <i class=\"pi pi-search\"></i>,\n pan <i class=\"pi pi-arrows-alt\"></i>, orbit <i class=\"pi pi-globe\"></i>,\n turntable <i class=\"pi pi-sync\"></i>, and reset camera <i class=\"pi pi-home\"></i>;\n scroll to zoom the 3D scene.</li>\n </ul>\n\n <h3>Image manipulation tools</h3>\n <ul>\n <li>\"<b>Region Editor</b>\" <img src=\"assets/plotting/region-editor.svg\" width=\"15\" height=\"15\">:\n opens the Region Editor as a floating, draggable dialog — a per-image table of every region\n (class, colour, area) with bulk select/label/colour/delete and GeoJSON import/export. It stays\n in sync with the image, so you can keep it open while drawing.</li>\n <li>\"<b>Intensity profile lines</b>\" <img src=\"assets/plotting/spline-chart.svg\" width=\"15\" height=\"15\">\n (<i>work in progress — not yet stable</i>): adds a coloured line ROI; a floating inset\n chart plots intensity along each line, updates live as you drag it, and re-samples at the\n current zoom resolution. Each added line gets its own colour; select a line and use the\n trash tool <i class=\"pi pi-trash\"></i> to remove it (and its trace).</li>\n <li>\"<b>Channels & Histogram</b>\" <img src=\"assets/plotting/invert.svg\" width=\"15\" height=\"15\">:\n opens a floating dialog for brightness/contrast, gamma, and per-channel display, plus the\n <b>colormap / LUT</b> controls (grayscale only) — a <b>reverse</b> toggle and a colormap\n dropdown (default: inverted greys).</li>\n <li>\"<b>Smoothen</b>\" <img src=\"assets/plotting/smooth.svg\" width=\"15\" height=\"15\">\n (Image view only): the image opens showing <b>raw pixels</b> (nearest-neighbour), so\n zooming in renders crisp blocks for pixel inspection. Toggle this on for bilinear\n smoothing; the icon turns white while smoothing is active.</li>\n </ul>\n\n <h3>Download & view tools</h3>\n <ul>\n <li>\"<b>Download</b>\" <i class=\"pi pi-download\"></i>: download the current image as a PNG.</li>\n <li>\"<b>Fit to view</b>\" / autoscale <i class=\"pi pi-window-maximize\"></i>: resets the image\n to its original dimensions. In stack mode it also resets to single-image mode.</li>\n </ul>\n\n <h3>Zoom tools</h3>\n <ul>\n <li>\"<b>Zoom box</b>\" <img src=\"assets/plotting/zoom-box.svg\" width=\"15\" height=\"15\">\n (<kbd>b</kbd>): drag a box to select an area to zoom into.</li>\n <li>\"<b>Pan</b>\" <i class=\"pi pi-arrows-alt\"></i> (<kbd>p</kbd>): drag to pan the image.</li>\n <li>\"<b>Zoom in</b>\" <i class=\"pi pi-search-plus\"></i> (<kbd>+</kbd>): zoom in one step.</li>\n <li>\"<b>Zoom out</b>\" <i class=\"pi pi-search-minus\"></i> (<kbd>-</kbd>): zoom out one step,\n stopping at the original image dimensions.</li>\n </ul>\n\n <h3>Region tools</h3>\n <p>By default no tool is selected (all greyed-out); selecting a tool highlights it. The\n vertex-editing tools (polygon, add/delete vertex, move, Bézier conversions) are available\n in the <b>Image</b> view only. On a <b>donut</b> (a region with a hole), the inner-ring\n vertices are editable too — drag, add, and delete them just like the outer ring.</p>\n <ul>\n <li>\"<b>Selection</b>\" <i class=\"pi pi-arrow-up-right\"></i> (<kbd>s</kbd>): a neutral mode\n that turns off whatever drawing tool was active (wand, vertex eraser, rectangle, etc.).\n Use it to step out of editing without picking another tool.</li>\n <li>\"<b>Rectangular region</b>\" <i class=\"pi pi-stop\"></i> (<kbd>r</kbd>): click and drag to\n create a rectangular region.</li>\n <li>\"<b>Polyline</b>\" <img src=\"assets/plotting/polyline.svg\" width=\"14\" height=\"14\">\n (<kbd>l</kbd>): draw an open (non-closed) polyline by clicking and dragging. Polylines can\n be edited and exported to GeoJSON as a <code>LineString</code> feature.</li>\n <li>\"<b>Freeform region</b>\" <i class=\"pi pi-pencil\"></i> (<kbd>f</kbd>): click and drag to\n draw a closed freeform polygon.</li>\n <li>\"<b>Brush</b>\" <img src=\"assets/plotting/paintbrush.svg\" width=\"15\" height=\"15\">: click\n and drag to paint a region with a circular brush — the painted stroke is the region.\n A <b>Size</b> slider (brush diameter, in image pixels) appears in the toolbar while the\n brush is active. Hold <kbd>Shift</kbd> while painting to <b>erase</b> (subtract) from a\n region instead. Painting over an existing region extends it; brushing across two regions\n merges them. Painting a closed ring (or shift-erasing an interior pocket) leaves the\n enclosed area empty — a <b>donut</b> (Image view).</li>\n <li>\"<b>Polygon</b>\" <img src=\"assets/plotting/polygon-vertices.svg\" width=\"15\" height=\"15\">:\n click to place each vertex; click the first point to close the polygon.</li>\n <li>\"<b>Add vertex</b>\" <img src=\"assets/plotting/vertex-add.svg\" width=\"15\" height=\"15\">:\n click an edge of the selected polygon to insert a new vertex.</li>\n <li>\"<b>Delete vertex</b>\" <img src=\"assets/plotting/vertex-delete.svg\" width=\"15\" height=\"15\">:\n click a vertex of the selected polygon to remove it.</li>\n <li>\"<b>Move region</b>\" <img src=\"assets/plotting/region-move.svg\" width=\"15\" height=\"15\">:\n drag to move the selected region.</li>\n <li>\"<b>To Bézier</b>\" <img src=\"assets/plotting/to-bezier.svg\" width=\"15\" height=\"15\"> /\n \"<b>To polygon</b>\" <img src=\"assets/plotting/to-polygon.svg\" width=\"15\" height=\"15\">:\n convert the selected region to a smooth Bézier curve, or back to a straight-edged polygon.</li>\n <li>\"<b>Wand</b>\" <img src=\"assets/plotting/wand.svg\" width=\"15\" height=\"15\"> (<kbd>w</kbd>):\n click to grow a region from pixels with similar values around the click point. Hold\n <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> for an exact-match flood fill; drag to keep extending the\n selection while moving; hold <kbd>Shift</kbd> while clicking or dragging on an existing\n region to <b>erase</b> pixels from it. Use the <b>Sens.</b> slider that appears to make the\n wand stricter (higher = smaller selection) or looser. Subsequent clicks keep extending the\n same region; clicking inside an existing region adopts it, and growing into another region\n merges them.</li>\n <li>\"<b>Vertex eraser</b>\" <i class=\"pi pi-eraser\"></i> (<kbd>e</kbd>): click or click-and-drag\n to remove polygon vertices that fall inside the cursor circle from any region, including a\n region's inner rings (donut holes). Use the <b>Radius</b> slider to set the eraser size in\n image pixels. Polygons reduced below 3 vertices (or polylines below 2) are deleted entirely;\n a hole reduced below 3 vertices is removed.</li>\n <li>\"<b>Undo</b>\" <img src=\"assets/plotting/undo.svg\" width=\"15\" height=\"15\">\n (<kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>Z</kbd>): reverts the\n last region action (draw, delete, edit, wand/brush stroke, segmentation, …). Up to the last\n <b>10</b> actions can be undone; the button greys out when there's nothing left to undo.</li>\n <li>\"<b>Redo</b>\" <img src=\"assets/plotting/redo.svg\" width=\"15\" height=\"15\">\n (<kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> or <kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>Y</kbd>):\n re-applies the most recently undone action. Performing a new region action clears what can be redone.</li>\n <li>\"<b>Delete region</b>\" <i class=\"pi pi-trash\"></i> (<kbd>Del</kbd>): deletes the selected\n region. This can also be done from the Region Editor.</li>\n </ul>\n\n <h3>Region actions (right-click the image)</h3>\n <p>Right-click a region — or the current multi-selection — to open the\n \"<b>Selected region(s)</b>\" group at the top of the context menu. These act immediately on\n the selection (they're not drawing modes) and are fully undo/redo-able:</p>\n <ul>\n <li>\"<b>Select all regions</b>\" <i class=\"pi pi-check-square\"></i>: select every region on\n the image (also in the Region Editor toolbar).</li>\n <li>\"<b>Merge / group</b>\": combine 2+ selected regions into one. If the pieces don't touch,\n the result is a single multi-part region (sparse \"bits\").</li>\n <li>\"<b>Ungroup</b>\": split a multi-part region back into one region per piece.</li>\n <li>\"<b>Inverse</b>\": replace the selection with everything <i>outside</i> it — the image\n rectangle with the selected regions punched out as holes. Works at any image size.</li>\n <li>\"<b>Simplify</b>\": reduce a region's vertex count (Douglas–Peucker) by an altitude\n threshold in pixels — pick <b>Light</b> (1 px), <b>Medium</b> (3 px),\n <b>Strong</b> (8 px), or <b>Custom…</b> for a slider. Applies to the exterior and any\n holes (and every part of a multi-part region).</li>\n <li>The Bézier conversions and Delete also live in this group (the right-click equivalents of\n the toolbar / vertex tools above).</li>\n </ul>\n\n <h3>Segmentation tools (SAM & cellpose)</h3>\n <p>AI-assisted segmentation that runs entirely in the browser. The box and point\n tools use a promptable <b>micro-sam</b> model; the cellpose tool auto-detects cells.\n Generated regions inherit the color of the rectangle they came from. The first run\n downloads the model (a progress toast is shown); it's then cached.</p>\n <ul>\n <li>\"<b>Segment</b>\" <img src=\"assets/plotting/picture-segmentation.svg\" width=\"15\" height=\"15\">\n (box prompt): draw one or more <b>Rectangular regions</b> around the objects of interest,\n then click Segment. Each rectangle is replaced by the SAM mask of the object inside it.</li>\n <li>\"<b>Point prompts</b>\" <img src=\"assets/plotting/click.svg\" width=\"15\" height=\"15\">: click directly on an object to\n segment it as a <b>new</b> region. Each click starts a fresh object — clicking another\n object won't grow the previous one. <kbd>Shift</kbd>/<kbd>Alt</kbd>-click adds an\n <i>exclude</i> point that refines the current object; <kbd>Esc</kbd> undoes it,\n <kbd>Enter</kbd> commits it.</li>\n <li>\"<b>Model picker</b>\" <i class=\"pi pi-chevron-down\"></i>: the dropdown attached to the\n Segment button chooses the SAM model — <b>micro-sam ViT-T</b> (default; small, fast) or\n <b>micro-sam ViT-B</b> (larger, highest accuracy) for light microscopy, or\n <b>patho-sam ViT-B</b> for histopathology (H&E / stained tissue). The choice applies to\n <i>both</i> the box and point tools. The <i class=\"pi pi-info-circle\"></i> info button next\n to it explains the trade-off.</li>\n <li>\"<b>Cellpose</b>\" <img src=\"assets/plotting/cells.svg\" width=\"15\" height=\"15\">: draw rectangles, then click Cellpose to\n automatically segment every cell inside each rectangle (client-side cellpose-SAM) — one\n region per detected cell. No clicking on individual cells needed.</li>\n </ul>\n\n <h3>Help</h3>\n <p>\"<b>Help</b>\" <i class=\"pi pi-question-circle\"></i>: opens this dialog.</p>\n\n <h3>Keyboard shortcuts</h3>\n <table class=\"shortcuts-table\">\n <tr><td><kbd>+</kbd> / <kbd>=</kbd></td><td>Zoom in</td></tr>\n <tr><td><kbd>-</kbd></td><td>Zoom out</td></tr>\n <tr><td><kbd>b</kbd></td><td>Toggle zoom box mode</td></tr>\n <tr><td><kbd>p</kbd></td><td>Toggle pan mode</td></tr>\n <tr><td><kbd>f</kbd></td><td>Toggle freeform region drawing</td></tr>\n <tr><td><kbd>l</kbd></td><td>Toggle polyline drawing</td></tr>\n <tr><td><kbd>r</kbd></td><td>Toggle rectangular region drawing</td></tr>\n <tr><td><kbd>w</kbd></td><td>Toggle wand tool</td></tr>\n <tr><td>Wand + <kbd>Shift</kbd></td><td>Erase pixels from the active region</td></tr>\n <tr><td>Wand + <kbd>Ctrl</kbd>/<kbd>Cmd</kbd></td><td>Exact-match flood fill (no smoothing)</td></tr>\n <tr><td><kbd>e</kbd></td><td>Toggle vertex eraser</td></tr>\n <tr><td><kbd>s</kbd></td><td>Selection mode (deactivates drawing tools)</td></tr>\n <tr><td>Point prompt + <kbd>Shift</kbd>/<kbd>Alt</kbd></td><td>Add an exclude point (refine the current object)</td></tr>\n <tr><td><kbd>Enter</kbd></td><td>Commit the current SAM point object</td></tr>\n <tr><td><kbd>Esc</kbd></td><td>Undo the current SAM point object</td></tr>\n <tr><td><kbd>Del</kbd> / <kbd>⌫</kbd></td><td>Delete selected region</td></tr>\n <tr><td><kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>Z</kbd></td><td>Undo the last region action (up to 10)</td></tr>\n <tr><td><kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> / <kbd>Ctrl</kbd>+<kbd>Y</kbd></td><td>Redo the last undone region action</td></tr>\n </table>\n\n <ng-template pTemplate=\"footer\">\n <p-button icon=\"pi pi-check\" (click)=\"displayHelpDialog=false\" label=\"Ok\" styleClass=\"p-button-text\">\n </p-button>\n </ng-template>\n</p-dialog>\n","/**\n * Deterministic colour engine for preset annotation classes (jit-ui#70).\n *\n * Resolution order for a region `label`:\n * 1. a matching preset (exact by default, or normalized if the set's matchMode says so)\n * -> the preset's colour;\n * 2. otherwise a deterministic fallback colour derived from a stable hash of the name,\n * so the same unknown class always gets the same colour with no stored state.\n *\n * These functions are pure (no mutation); opt-in promotion of unknown classes into the\n * set is handled by the store, which owns persistence.\n */\nimport { ClassPreset, PresetSet } from '../models/class-preset';\n\nexport function normalizeLabel(s: string): string {\n return (s ?? '').trim().toLowerCase();\n}\n\n/** Stable, non-negative 32-bit string hash (identical across runs and machines). */\nexport function hashString(s: string): number {\n let h = 0;\n for (let i = 0; i < s.length; i++) {\n h = (Math.imul(31, h) + s.charCodeAt(i)) | 0;\n }\n // Fold to non-negative without the Math.abs(INT_MIN) overflow pitfall.\n return h < 0 ? ~h : h;\n}\n\nfunction hslToHex(hDeg: number, sPct: number, lPct: number): string {\n const s = sPct / 100;\n const l = lPct / 100;\n const k = (n: number) => (n + hDeg / 30) % 12;\n const a = s * Math.min(l, 1 - l);\n const channel = (n: number) => {\n const v = l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));\n return Math.round(255 * v).toString(16).padStart(2, '0');\n };\n return `#${channel(0)}${channel(8)}${channel(4)}`.toUpperCase();\n}\n\n/** Find the preset matching `label` under the set's match mode. */\nexport function findPreset(label: string, set: PresetSet): ClassPreset | undefined {\n if (!label || !set?.classes) return undefined;\n if (set.matchMode === 'normalized') {\n const n = normalizeLabel(label);\n return set.classes.find((c) => normalizeLabel(c.name) === n);\n }\n return set.classes.find((c) => c.name === label);\n}\n\n/**\n * Deterministic fallback colour for an unknown class name: index into the palette by a\n * stable hash of the (normalized) name; if the palette is empty, generate a golden-angle\n * HSL hue. Same name -> same colour, every run.\n */\nexport function fallbackColorFor(label: string, palette: string[]): string {\n const key = normalizeLabel(label);\n if (palette && palette.length > 0) {\n return palette[hashString(key) % palette.length];\n }\n const hue = (hashString(key) * 137.508) % 360;\n return hslToHex(hue, 65, 50);\n}\n\n/** Resolve a colour for `label`: a matching preset's colour, else the deterministic fallback. */\nexport function colorForLabel(label: string, set: PresetSet): string {\n const preset = findPreset(label, set);\n return preset ? preset.color : fallbackColorFor(label, set.fallbackPalette);\n}\n","import { Region, Rectangle, Polygon, MultiPolygon } from '../models/region';\n\n/** A single closed ring (+ optional holes) in image-pixel coordinates. A region\n * rasterizes as the union of its parts. Plain data so it survives a\n * `postMessage` structured clone into the mask worker. */\nexport interface MaskPart {\n xpoints: number[];\n ypoints: number[];\n holes?: number[][][];\n}\n\n/** A bbox-relative binary mask, as returned by `WandService.rasterizePolygon`. */\nexport interface BBoxMask {\n bx: number;\n by: number;\n bw: number;\n bh: number;\n mask: Uint8Array;\n}\n\n/** Polygon-fill function (the wand's scanline rasterizer), injected so this\n * module stays free of Angular/DOM and can run inside a worker. */\nexport type RasterizeFn = (\n xpoints: number[],\n ypoints: number[],\n imageWidth: number,\n imageHeight: number,\n holes?: number[][][],\n) => BBoxMask | null;\n\n/**\n * The largest mask we will allocate, in pixels. A single-channel 8-bit mask is\n * one byte per pixel, so this is also its byte size. Whole-slide level-0 images\n * (e.g. 119040×90112 ≈ 1.07e10 px) blow past both the JS typed-array length cap\n * (~4.29e9) and available memory, so masks for images larger than this are\n * rasterized at a proportionally downscaled resolution. ~100 MP ≈ 100 MB.\n */\nexport const MAX_MASK_PIXELS = 100_000_000;\n\n/** Downscale factor (≤ 1) to keep `width * height` within {@link MAX_MASK_PIXELS}.\n * 1 when the image already fits. */\nexport function maskScaleFor(width: number, height: number): number {\n const total = width * height;\n if (!Number.isFinite(total) || total <= MAX_MASK_PIXELS) return 1;\n return Math.sqrt(MAX_MASK_PIXELS / total);\n}\n\n/** Multiply every coordinate (and hole coordinate) of a region's parts by\n * `scale`, for rasterizing into a downscaled mask. Returns the parts unchanged\n * when `scale` is 1. */\nexport function scaleParts(parts: MaskPart[], scale: number): MaskPart[] {\n if (scale === 1) return parts;\n return parts.map((p) => ({\n xpoints: p.xpoints.map((x) => x * scale),\n ypoints: p.ypoints.map((y) => y * scale),\n holes: p.holes?.map((ring) => ring.map(([x, y]) => [x * scale, y * scale])),\n }));\n}\n\n/** Flatten a region's geometry to plain rings. Rectangles become a 4-point ring;\n * polygons keep their points + holes; multi-polygons expand to one part each. */\nexport function regionToParts(region: Region): MaskPart[] {\n const b = region.bounds;\n if (b instanceof Rectangle) {\n return [{\n xpoints: [b.x, b.x + b.width, b.x + b.width, b.x],\n ypoints: [b.y, b.y, b.y + b.height, b.y + b.height],\n }];\n }\n if (b instanceof Polygon) {\n return [{ xpoints: b.xpoints, ypoints: b.ypoints, holes: b.holes }];\n }\n if (b instanceof MultiPolygon) {\n return b.polygons.map((p) => ({ xpoints: p.xpoints, ypoints: p.ypoints, holes: p.holes }));\n }\n return [];\n}\n\n/** A rasterized label mask plus the PNG bit depth it should be encoded at. */\nexport interface LabelMask {\n data: Uint8Array | Uint16Array;\n /** 8 for ≤255 distinct values, 16 for a multi-class mask with >255 regions. */\n bitDepth: 8 | 16;\n}\n\n/**\n * Rasterize regions (as plain parts) to a full image-size label mask (row-major,\n * `W * H` samples; pixel `(x, y)` at `y * W + x`). Background is 0.\n *\n * - `'binary'` — every region pixel is 255 (standard 8-bit black/white mask:\n * `> 0` = foreground; also directly viewable).\n * - `'multiclass'` — each region gets a distinct 1-based id (its index + 1).\n * Stays 8-bit for ≤255 regions; promotes to 16-bit beyond that. Ids are\n * distinct up to the 16-bit ceiling (65535 regions); a selection larger than\n * that exceeds the PNG's representable range and ids wrap (not a realistic\n * hand-annotation case, but called out so the limit is explicit).\n *\n * Later regions paint over earlier ones where they overlap. `onProgress` is\n * called after each region (1-based) so a caller can drive a progress bar.\n * Returns null when nothing rasterises (no regions, zero/insane size).\n */\nexport function regionsToMask(\n regions: MaskPart[][],\n imageWidth: number,\n imageHeight: number,\n mode: 'binary' | 'multiclass',\n rasterize: RasterizeFn,\n onProgress?: (done: number, total: number) => void,\n): LabelMask | null {\n const W = Math.round(imageWidth);\n const H = Math.round(imageHeight);\n if (!Number.isFinite(W) || !Number.isFinite(H) || W <= 0 || H <= 0 || !regions?.length) {\n return null;\n }\n\n const multiclass = mode === 'multiclass';\n const bitDepth: 8 | 16 = multiclass && regions.length > 255 ? 16 : 8;\n const out: Uint8Array | Uint16Array =\n bitDepth === 16 ? new Uint16Array(W * H) : new Uint8Array(W * H);\n let painted = false;\n for (let i = 0; i < regions.length; i++) {\n // Binary → 255 (viewable, standard). Multi-class → 1-based class id.\n const value = multiclass ? i + 1 : 255;\n for (const part of regions[i]) {\n const m = rasterize(part.xpoints, part.ypoints, W, H, part.holes);\n if (!m) continue;\n painted = true;\n for (let y = 0; y < m.bh; y++) {\n const srcRow = y * m.bw;\n const dstRow = (m.by + y) * W + m.bx;\n for (let x = 0; x < m.bw; x++) {\n if (m.mask[srcRow + x]) out[dstRow + x] = value;\n }\n }\n }\n onProgress?.(i + 1, regions.length);\n }\n return painted ? { data: out, bitDepth } : null;\n}\n","import {\n ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef,\n EventEmitter, HostListener, Input, OnDestroy, Output, Renderer2, ViewChild,\n} from '@angular/core';\n\n@Component({\n // Canonical prefixed selector first; the unprefixed original is kept as an\n // alias for one release (pre-publication back-compat).\n selector: 'hex-color-picker',\n templateUrl: './hex-color-picker.component.html',\n styleUrls: ['./hex-color-picker.component.scss'],\n // OnPush so the always-in-DOM (but hidden) picker panel — a ~130-cell honeycomb\n // grid + sliders — isn't re-checked on every scroll-triggered change detection.\n // Inputs (`color`) and the picker's own events still mark it for check. (jit-ui#70)\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport class HexColorPickerComponent implements OnDestroy {\n\n private static readonly DROPDOWN_WIDTH = 280;\n\n private _color = '#000000';\n\n @Output() colorChange = new EventEmitter<string>();\n\n open = false;\n\n @ViewChild('swatchBtn') swatchBtn!: ElementRef<HTMLButtonElement>;\n @ViewChild('dropdown') dropdownRef!: ElementRef<HTMLDivElement>;\n\n // HSL values\n hue = 0;\n saturation = 100;\n lightness = 50;\n\n // RGB values\n red = 0;\n green = 0;\n blue = 0;\n\n // Honeycomb color palette\n // Honeycomb color palette from w3schools — 7 per side, 13 rows (7→13→7)\n readonly colorRows: string[][] = [\n // Row 1: 7\n ['#003366', '#336699', '#3366CC', '#003399', '#000099', '#0000CC', '#000066'],\n // Row 2: 8\n ['#006666', '#006699', '#0099CC', '#0066CC', '#0033CC', '#0000FF', '#3333FF', '#333399'],\n // Row 3: 9\n ['#669999', '#009999', '#33CCCC', '#00CCFF', '#0099FF', '#0066FF', '#3366FF', '#3333CC', '#666699'],\n // Row 4: 10\n ['#339966', '#00CC99', '#00FFCC', '#00FFFF', '#33CCFF', '#3399FF', '#6699FF', '#6666FF', '#6600FF', '#6600CC'],\n // Row 5: 11\n ['#339933', '#00CC66', '#00FF99', '#66FFCC', '#66FFFF', '#66CCFF', '#99CCFF', '#9999FF', '#9966FF', '#9933FF', '#9900FF'],\n // Row 6: 12\n ['#006600', '#00CC00', '#00FF00', '#66FF99', '#99FFCC', '#CCFFFF', '#CCCCFF', '#CC99FF', '#CC66FF', '#CC33FF', '#CC00FF', '#9900CC'],\n // Row 7: 13 (center)\n ['#003300', '#009933', '#33CC33', '#66FF66', '#99FF99', '#CCFFCC', '#FFFFFF', '#FFCCFF', '#FF99FF', '#FF66FF', '#FF00FF', '#CC00CC', '#660066'],\n // Row 8: 12\n ['#336600', '#009900', '#66FF33', '#99FF66', '#CCFF99', '#FFFFCC', '#FFCCCC', '#FF99CC', '#FF66CC', '#FF33CC', '#CC0099', '#993399'],\n // Row 9: 11\n ['#333300', '#669900', '#99FF33', '#CCFF66', '#FFFF99', '#FFCC99', '#FF9999', '#FF6699', '#FF3399', '#CC3399', '#990099'],\n // Row 10: 10\n ['#666633', '#99CC00', '#CCFF33', '#FFFF66', '#FFCC66', '#FF9966', '#FF6666', '#FF0066', '#CC6699', '#993366'],\n // Row 11: 9\n ['#999966', '#CCCC00', '#FFFF00', '#FFCC00', '#FF9933', '#FF6600', '#FF5050', '#CC0066', '#660033'],\n // Row 12: 8\n ['#996633', '#CC9900', '#FF9900', '#CC6600', '#FF3300', '#FF0000', '#CC0000', '#990033'],\n // Row 13: 7\n ['#663300', '#996600', '#CC3300', '#993300', '#990000', '#800000', '#993333'],\n ];\n\n private normalizeHexColor(val: string): string {\n return val ? val.toUpperCase() : val;\n }\n\n @Input()\n get color(): string {\n return this._color;\n }\n set color(val: string) {\n const normalizedColor = this.normalizeHexColor(val);\n this._color = normalizedColor;\n this.syncFromHex(normalizedColor);\n }\n\n constructor(private elRef: ElementRef, private renderer: Renderer2, private cdr: ChangeDetectorRef) {}\n\n ngOnDestroy() {\n this.removeDropdownFromBody();\n }\n\n toggle() {\n this.open = !this.open;\n if (this.open) {\n // Let Angular render the dropdown, then move it to body\n this.cdr.detectChanges();\n this.appendDropdownToBody();\n } else {\n this.removeDropdownFromBody();\n }\n }\n\n private appendDropdownToBody() {\n const dropdown = this.dropdownRef?.nativeElement;\n if (!dropdown) return;\n const rect = this.swatchBtn.nativeElement.getBoundingClientRect();\n this.renderer.appendChild(document.body, dropdown);\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n const w = HexColorPickerComponent.DROPDOWN_WIDTH;\n // Horizontal: open toward the side with room. When the swatch is on the left\n // half of the viewport, anchor the panel's LEFT edge to it (extend right) so\n // it isn't truncated by the left edge; otherwise anchor its RIGHT edge\n // (extend left). Clamp within the viewport either way.\n let left = rect.left <= vw / 2 ? rect.left : rect.right - w;\n left = Math.max(4, Math.min(left, vw - w - 4));\n // Vertical: below the swatch, flipping above if it would overflow the bottom.\n const h = dropdown.offsetHeight || 0;\n let top = rect.bottom + 4;\n if (h && top + h > vh - 4) top = Math.max(4, rect.top - 4 - h);\n this.renderer.setStyle(dropdown, 'left', left + 'px');\n this.renderer.setStyle(dropdown, 'top', top + 'px');\n }\n\n private removeDropdownFromBody() {\n const dropdown = this.dropdownRef?.nativeElement;\n if (dropdown && dropdown.parentElement === document.body) {\n this.renderer.removeChild(document.body, dropdown);\n }\n }\n\n selectColor(hex: string) {\n this._color = hex;\n this.syncFromHex(hex);\n this.colorChange.emit(hex);\n }\n\n selectAndClose(hex: string) {\n this.selectColor(hex);\n this.close();\n }\n\n close() {\n this.open = false;\n this.removeDropdownFromBody();\n }\n\n onHexInput(value: string) {\n if (/^#[0-9A-Fa-f]{6}$/.test(value)) {\n this.selectColor(value);\n }\n }\n\n onHslChange() {\n const hex = this.hslToHex(this.hue, this.saturation, this.lightness);\n this._color = hex;\n this.syncRgbFromHex(hex);\n this.colorChange.emit(hex);\n }\n\n onRgbChange() {\n const red = Math.max(0, Math.min(255, this.red));\n const green = Math.max(0, Math.min(255, this.green));\n const blue = Math.max(0, Math.min(255, this.blue));\n\n this.red = red;\n this.green = green;\n this.blue = blue;\n\n const hex = this.rgbToHex(red, green, blue);\n this._color = hex;\n this.syncHslFromRgb(red, green, blue);\n this.colorChange.emit(hex);\n }\n\n get hueGradient(): string {\n const stops = [];\n for (let h = 0; h <= 360; h += 30) {\n stops.push(`hsl(${h}, 100%, 50%)`);\n }\n return `linear-gradient(to right, ${stops.join(', ')})`;\n }\n\n get satGradient(): string {\n return `linear-gradient(to right, hsl(${this.hue}, 0%, ${this.lightness}%), hsl(${this.hue}, 100%, ${this.lightness}%))`;\n }\n\n get lightGradient(): string {\n return `linear-gradient(to right, hsl(${this.hue}, ${this.saturation}%, 0%), hsl(${this.hue}, ${this.saturation}%, 50%), hsl(${this.hue}, ${this.saturation}%, 100%))`;\n }\n\n @HostListener('document:click', ['$event'])\n onDocumentClick(event: Event) {\n if (!this.open) return;\n const target = event.target as Node;\n const clickedInside =\n this.elRef.nativeElement.contains(target) || this.dropdownRef?.nativeElement.contains(target);\n if (!clickedInside) {\n this.close();\n }\n }\n\n // --- Color conversion utilities ---\n\n private syncFromHex(hex: string) {\n const rgb = this.hexToRgb(hex);\n if (rgb) {\n this.red = rgb.r;\n this.green = rgb.g;\n this.blue = rgb.b;\n this.syncHslFromRgb(rgb.r, rgb.g, rgb.b);\n }\n }\n\n private syncRgbFromHex(hex: string) {\n const rgb = this.hexToRgb(hex);\n if (rgb) {\n this.red = rgb.r;\n this.green = rgb.g;\n this.blue = rgb.b;\n }\n }\n\n private syncHslFromRgb(r: number, g: number, b: number) {\n const hsl = this.rgbToHsl(r, g, b);\n this.hue = hsl.h;\n this.saturation = hsl.s;\n this.lightness = hsl.l;\n }\n\n private hexToRgb(hex: string): { r: number; g: number; b: number } | null {\n const match = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n return match\n ? {\n r: parseInt(match[1], 16),\n g: parseInt(match[2], 16),\n b: parseInt(match[3], 16),\n }\n : null;\n }\n\n private rgbToHex(r: number, g: number, b: number): string {\n const toHex = (n: number) =>\n Math.max(0, Math.min(255, Math.round(n)))\n .toString(16)\n .padStart(2, '0');\n return `#${toHex(r)}${toHex(g)}${toHex(b)}`.toUpperCase();\n }\n\n private rgbToHsl(r: number, g: number, b: number): { h: number; s: number; l: number } {\n r /= 255;\n g /= 255;\n b /= 255;\n const max = Math.max(r, g, b),\n min = Math.min(r, g, b);\n const l = (max + min) / 2;\n let h = 0,\n s = 0;\n if (max !== min) {\n const d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch (max) {\n case r:\n h = ((g - b) / d + (g < b ? 6 : 0)) / 6;\n break;\n case g:\n h = ((b - r) / d + 2) / 6;\n break;\n case b:\n h = ((r - g) / d + 4) / 6;\n break;\n }\n }\n return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100) };\n }\n\n private hslToHex(h: number, s: number, l: number): string {\n s /= 100;\n l /= 100;\n const a = s * Math.min(l, 1 - l);\n const f = (n: number) => {\n const k = (n + h / 30) % 12;\n const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n return Math.round(255 * color);\n };\n return this.rgbToHex(f(0), f(8), f(4));\n }\n}\n","<div class=\"hex-picker-wrapper\">\n <button #swatchBtn type=\"button\" class=\"hex-picker-swatch\" [style.background]=\"color\"\n (click)=\"toggle()\" [title]=\"color\">\n </button>\n <div #dropdown class=\"hex-picker-dropdown\" [hidden]=\"!open\">\n <!-- Hexagon grid -->\n <div class=\"hex-grid\">\n <div *ngFor=\"let row of colorRows;\"\n class=\"hex-row\">\n <button *ngFor=\"let c of row\"\n type=\"button\"\n class=\"hex-cell\"\n [style.background]=\"c\"\n [class.hex-selected]=\"c === color\"\n [title]=\"c\"\n [attr.aria-label]=\"'Select color ' + c\"\n (click)=\"selectAndClose(c)\">\n </button>\n </div>\n </div>\n\n <!-- Hex input + native picker -->\n <div class=\"hex-picker-footer\">\n <input type=\"text\" class=\"hex-input\" [value]=\"color\"\n (change)=\"onHexInput($any($event.target).value)\"\n maxlength=\"7\" spellcheck=\"false\">\n <input type=\"color\" class=\"native-picker\" [value]=\"color\"\n (input)=\"selectColor($any($event.target).value)\"\n title=\"Open system color picker\">\n </div>\n\n <!-- HSL sliders -->\n <div class=\"slider-section\">\n <div class=\"slider-row\">\n <label>H</label>\n <input type=\"range\" min=\"0\" max=\"360\" [ngModel]=\"hue\"\n (ngModelChange)=\"hue=$event; onHslChange()\"\n class=\"slider slider-hue\" [style.background]=\"hueGradient\">\n <span class=\"slider-value\">{{hue}}</span>\n </div>\n <div class=\"slider-row\">\n <label>S</label>\n <input type=\"range\" min=\"0\" max=\"100\" [ngModel]=\"saturation\"\n (ngModelChange)=\"saturation=$event; onHslChange()\"\n class=\"slider slider-sat\" [style.background]=\"satGradient\">\n <span class=\"slider-value\">{{saturation}}</span>\n </div>\n <div class=\"slider-row\">\n <label>L</label>\n <input type=\"range\" min=\"0\" max=\"100\" [ngModel]=\"lightness\"\n (ngModelChange)=\"lightness=$event; onHslChange()\"\n class=\"slider slider-light\" [style.background]=\"lightGradient\">\n <span class=\"slider-value\">{{lightness}}</span>\n </div>\n </div>\n\n <!-- RGB inputs -->\n <div class=\"rgb-section\">\n <div class=\"rgb-field\">\n <label>R</label>\n <input type=\"number\" min=\"0\" max=\"255\" [ngModel]=\"red\"\n (ngModelChange)=\"red=$event; onRgbChange()\">\n </div>\n <div class=\"rgb-field\">\n <label>G</label>\n <input type=\"number\" min=\"0\" max=\"255\" [ngModel]=\"green\"\n (ngModelChange)=\"green=$event; onRgbChange()\">\n </div>\n <div class=\"rgb-field\">\n <label>B</label>\n <input type=\"number\" min=\"0\" max=\"255\" [ngModel]=\"blue\"\n (ngModelChange)=\"blue=$event; onRgbChange()\">\n </div>\n </div>\n </div>\n</div>\n","import { Component, Inject, OnDestroy, OnInit, ViewChild } from '@angular/core';\nimport { OverlayPanel } from 'primeng/overlaypanel';\nimport { saveAs } from 'file-saver';\nimport { Subject, Subscription } from 'rxjs';\nimport { debounceTime, switchMap } from 'rxjs/operators';\n\nimport { Polygon, Rectangle, Region, MultiPolygon } from '../models/region';\nimport { PresetSet, ClassPreset, defaultPresetSet } from '../models/class-preset';\nimport { colorForLabel } from '../store/class-color.util';\nimport { IImageMetadata } from '../contracts/image.contract';\nimport { ConfirmationService, MessageService } from 'primeng/api';\nimport { IRegionEditorApi, REGION_EDITOR_API } from '../contracts/region-editor-api.contract';\nimport { RegionIoPort, REGION_IO_PORT } from '../contracts/ports/region-io.port';\nimport { regionToParts, scaleParts, maskScaleFor } from './mask-raster';\n\n@Component({\n // Canonical prefixed selector first; the unprefixed original is kept as an\n // alias for one release (pre-publication back-compat).\n selector: 'region-editor',\n templateUrl: './region-editor.component.html',\n styleUrls: ['./region-editor.component.scss'],\n})\nexport class RegionEditorComponent implements OnInit, OnDestroy {\n protected readonly Array = Array;\n\n @ViewChild('op') overlayPanel!: OverlayPanel;\n\n regions: Region[] = [];\n regionsCopy: Region[] = [];\n selectedRegions: Region[] = [];\n showShapeLabel!: boolean;\n shapeColor!: string;\n fillColor!: string;\n displayHelpDialog = false;\n showColorDialog = false;\n /** One colour editor per unique class among the selected regions, shown in the\n * \"edit colour of selected regions\" dialog. Unclassified regions (no label)\n * are grouped under a single entry with an empty `label`. */\n classColorEdits: { label: string; color: string }[] = [];\n labelColors: Map<string, string> = new Map();\n selectedLabelColor = '';\n /** \"Edit class on selected rows\" popup: chosen existing class, and a new-class name. */\n bulkClass = '';\n newBulkClass = '';\n\n // ── annotation-class presets (jit-ui#70) ──\n /** Local mirror of the per-user preset set (chip strip, Class dropdown, dialog). */\n presetSet: PresetSet = defaultPresetSet();\n /** Class applied to newly drawn/added regions and to bulk chip-clicks. */\n activeClass: string | null = null;\n showManageDialog = false;\n /** Working copy edited inside the Manage-classes dialog; committed on Apply/Done. */\n presetDraft: PresetSet | null = null;\n /** class name (match-mode keyed) → number of regions currently using it. */\n classCounts = new Map<string, number>();\n /** Fallback class that a region reverts to when its class is deleted (jit-ui#70). */\n readonly defaultClassName = 'Region';\n /** Classes as shown in the panel: sorted by region count (desc), then name. */\n displayClasses: ClassPreset[] = [];\n readonly matchModeOptions = [\n { label: 'Exact', value: 'exact' },\n { label: 'Normalized', value: 'normalized' },\n ];\n\n paginatorFirst = 0;\n paginatorRows = 10;\n readonly rowsPerPageOptions = [10, 25, 50];\n /** Regions whose Class cell is currently in edit mode.\n * Using object identity as the key avoids needing a unique id field. */\n editingLabelRegions = new Set<any>();\n\n showSaveAsDialog = false;\n saveAsFilename = '';\n saveAsFileExists = false;\n /** True while a GeoJSON persist is serializing/uploading — drives the dialog's\n * progress bar and Cancel button (parity with the Save-mask dialog). */\n saveAsBusy = false;\n private _saveAsCheck$ = new Subject<string>();\n private _saveAsSub?: Subscription;\n /** Handle for the deferred-serialize timer so Cancel/destroy can abort it\n * before it fires (otherwise the upload would still start). */\n private _saveAsTimer?: ReturnType<typeof setTimeout>;\n\n showExportDialog = false;\n exportFilename = '';\n\n showSaveMaskDialog = false;\n saveMaskFilename = '';\n /** Mask type chosen in the Save-mask dialog: a binary foreground/background\n * mask, or a multi-class mask with a distinct id per region. */\n maskMode: 'binary' | 'multiclass' = 'binary';\n /** True while the mask worker is rasterizing/encoding — drives the progress\n * bar and the Cancel button in the dialog. */\n maskBusy = false;\n /** 0–100 rasterization progress; switches to indeterminate during encoding. */\n maskProgress = 0;\n maskEncoding = false;\n private maskWorker?: Worker;\n private pendingMaskFilename = '';\n\n /**\n * PrimeNG p-table multi-selection mode toggle. When true, single-click\n * selects one row (replacing prior); meta/ctrl-click toggles a row in/out\n * of the selection. When false, every click toggles. Default true to\n * match the most common spreadsheet-like UX.\n */\n metaKey = true;\n\n private _updatingFromEditor = false;\n private _suppressSelectionSyncToPlot = false;\n private _regionSub = new Subscription();\n private _selectedIdxSub = new Subscription();\n private _metaSub = new Subscription();\n private _presetSub = new Subscription();\n\n /** Physical pixel size (µm/pixel) of the active image, for region areas in\n * µm². Undefined when the format reports no physical size. */\n private mppX?: number;\n private mppY?: number;\n\n constructor(\n @Inject(REGION_EDITOR_API) private regionApi: IRegionEditorApi,\n public messageService: MessageService,\n private confirmationService: ConfirmationService,\n @Inject(REGION_IO_PORT) private regionIo: RegionIoPort,\n ) {}\n\n /**\n * Deep copy of regions for dirty-tracking (`regionsCopy`). Returns plain-object\n * clones — only structural equality matters here, not prototypes.\n * TODO: replace with `structuredClone` once verified.\n */\n private deepClone<T>(items: T[]): T[] {\n return items.map((item) => {\n if (Array.isArray(item)) {\n return this.deepClone(item) as unknown as T;\n } else if (typeof item === 'object' && item !== null) {\n const cloned: any = {};\n for (const key in item) {\n cloned[key] = this.deepClone([item[key]])[0];\n }\n return cloned;\n }\n return item;\n });\n }\n\n ngOnInit() {\n this.showShapeLabel = this.regionApi.getShowShapeLabel();\n this.shapeColor = this.regionApi.getShapeColor();\n this.fillColor = this.regionApi.getFillColor();\n\n // Annotation-class presets (jit-ui#70): mirror the set for the chip strip,\n // the Class dropdown and the manage dialog. Guarded with optional calls so\n // partial API mocks in tests (which omit the preset methods) don't throw.\n const initialPresets = this.regionApi.getPresetSet?.();\n if (initialPresets) this.presetSet = initialPresets;\n const presets$ = this.regionApi.getPresetSet$?.();\n if (presets$) {\n this._presetSub = presets$.subscribe((set) => {\n if (set) this.presetSet = set;\n this.updateDisplayClasses();\n });\n }\n // Seed from the visualizer's current regions — already scoped to the\n // active image by the per-image cache, and handed back as neutral Region\n // objects (no backend shape format involved).\n // Annotation regions only — intensity-profile lines are owned by the\n // intensity tool and excluded by the contract, so the editor never sees them.\n this.regions = this.applyRegionColors(this.regionApi.getAnnotationRegions());\n this.regionsCopy = this.deepClone(this.regions);\n this.syncClassesFromRegions(this.regions);\n this.recomputeClassCounts();\n\n // The update event is just a change signal; re-read the regions from the\n // visualizer rather than parsing whatever payload it carries.\n this._regionSub = this.regionApi.getRegionUpdateEvent().subscribe(() => {\n if (this._updatingFromEditor) return;\n const updated = this.applyRegionColors(this.regionApi.getAnnotationRegions());\n // preserve selection for regions that still exist (by id, since name\n // is a user-editable display label and may collide)\n const selectedIds = new Set(this.selectedRegions.map((r) => r.id));\n this.regions = updated;\n this.regionsCopy = this.deepClone(this.regions);\n this.selectedRegions = updated.filter((r) => selectedIds.has(r.id));\n this.clampPaginatorFirst();\n this.syncClassesFromRegions(updated);\n this.recomputeClassCounts();\n });\n\n this._saveAsCheck$.pipe(\n debounceTime(400),\n switchMap(name => this.regionIo.roiFileExists(name)),\n ).subscribe({\n next: exists => { this.saveAsFileExists = exists; },\n error: () => { this.saveAsFileExists = false; },\n });\n\n // Physical pixel size of the active image (for region areas in µm²/mm²).\n // Mirror PlotlyService.currentMpp: the calibration may sit on any channel\n // entry, not necessarily [0], so pick the first entry with a positive mppX\n // rather than reading [0] blindly. Fall back to square pixels (mppY = mppX)\n // when only one axis is reported.\n this._metaSub = this.regionApi.getImageMeta().subscribe((meta) => {\n const { mppX, mppY } = this.pickMpp(meta);\n this.mppX = mppX;\n this.mppY = mppY;\n });\n\n this._selectedIdxSub = this.regionApi.getSelectedRegions$().subscribe((selected) => {\n if (this._suppressSelectionSyncToPlot) return;\n // Map the contract's selected regions to the editor's own instances by id.\n const next = selected\n .map((s) => this.regions.find((r) => r.id === s.id))\n .filter((r): r is Region => !!r);\n const same =\n next.length === this.selectedRegions.length &&\n next.every((r, i) => r.id === this.selectedRegions[i]?.id);\n if (!same) this.selectedRegions = next;\n // Scroll the paginator so the most-recently-selected row is visible.\n if (next.length > 0) {\n const lastIdx = this.regions.findIndex((r) => r.id === next[next.length - 1].id);\n if (lastIdx >= 0) {\n const pageStart = Math.floor(lastIdx / this.paginatorRows) * this.paginatorRows;\n if (pageStart !== this.paginatorFirst) this.paginatorFirst = pageStart;\n }\n }\n });\n }\n\n ngOnDestroy() {\n this._regionSub.unsubscribe();\n this._selectedIdxSub.unsubscribe();\n this._metaSub.unsubscribe();\n this._presetSub.unsubscribe();\n if (this._saveAsTimer !== undefined) clearTimeout(this._saveAsTimer);\n this._saveAsSub?.unsubscribe();\n this.teardownMaskWorker();\n }\n\n /**\n * Table → Plot: PrimeNG fires onRowSelect/onRowUnselect after updating\n * `selectedRegions`. Push the selected regions to the contract by identity —\n * the package maps them to its internal index space (which includes the\n * intensity-profile lines the editor never sees).\n */\n onSelectionChanged() {\n this._suppressSelectionSyncToPlot = true;\n try {\n this.regionApi.setSelectedRegions(this.selectedRegions ?? []);\n } finally {\n this._suppressSelectionSyncToPlot = false;\n }\n }\n\n /**\n * Apply classification colours and refresh the label→colour map for regions\n * coming from the visualizer. The visualizer hands back neutral `Region`\n * objects with bounds, colour and label already populated, so the editor no\n * longer parses any backend-specific shape format — it only fills in a\n * fallback colour and rebuilds its local label→colour lookup.\n */\n private applyRegionColors(regions: Region[]): Region[] {\n for (const region of regions) {\n region.color =\n region.color ||\n this.regionApi.getClassificationColors().get(region.label ?? '') ||\n this.shapeColor;\n }\n // Rebuild labelColors: seed from persisted map, then overlay actual region colors\n this.labelColors.clear();\n for (const [label, color] of this.regionApi.getClassificationColors()) {\n this.labelColors.set(label, color);\n }\n for (const region of regions) {\n if (region.label && region.color) {\n this.labelColors.set(region.label, region.color);\n }\n }\n return regions;\n }\n\n /**\n * Push edits from the editor to the diagram in live-edit mode (no save /\n * cancel buttons). The `_updatingFromEditor` guard is still used so the\n * resulting regionUpdateEvent doesn't bounce back as an external change.\n */\n private setRegionsFromEditor(fillColor?: string) {\n this._updatingFromEditor = true;\n // isRegionSaveOn=true so changes commit to the region store (and the per-image\n // cache) immediately. setAnnotationRegions preserves the intensity-profile\n // lines internally, so editor edits never disturb them.\n this.regionApi.setAnnotationRegions(this.regions, this.showShapeLabel, true, fillColor ?? this.fillColor);\n this._updatingFromEditor = false;\n // The editor's own commit is ignored by the region-update subscription (the\n // _updatingFromEditor guard), so refresh here: a class label typed in the\n // Class column gets added to the list, and the panel counts/order stay in\n // sync after any edit. (jit-ui#70)\n this.syncClassesFromRegions(this.regions);\n this.recomputeClassCounts();\n }\n\n /** Set one region's outline colour from the per-row picker and commit live.\n * Remembers it as the label's colour so same-class regions added later match\n * (jit-ui#85 — the Region Editor's per-region Color column). */\n changeRegionColor(region: Region, color: string): void {\n if (!color || region.color === color) return;\n region.color = color;\n region.colorOverridden = true; // explicit per-region colour — preserve it against preset (re)apply (jit-ui#70)\n if (region.label) this.labelColors.set(region.label, color);\n this.setRegionsFromEditor();\n }\n\n addRectangle() {\n const region = new Region();\n region.bounds = new Rectangle();\n region.bounds.width = 512;\n region.bounds.height = 512;\n region.label = this.activeClass ?? 'Region';\n // id and a non-colliding name are minted by the visualizer's setRegions\n this.regions = [...this.regions, region];\n this.setRegionsFromEditor();\n this.regionsCopy = this.deepClone(this.regions);\n }\n\n /**\n * Update the label of the region on enter key pressed (when editing a label cell in the table)\n * @param region\n * @param setRegion\n */\n labelRegionUpdate(region: Region, setRegion = false) {\n if (region.label) {\n // if label doesn't exist\n if (!this.labelColors.has(region.label)) {\n this.labelColors.set(region.label, this.shapeColor);\n }\n }\n // update colors of the regions\n for (const reg of this.regions) {\n if (!reg.color) {\n if (reg.label && this.labelColors.has(reg.label)) {\n reg.color = this.labelColors.get(reg.label);\n }\n }\n }\n // update labels map\n this.labelColors.clear();\n for (const reg of this.regions) {\n if (reg.label && reg.color) {\n this.labelColors.set(reg.label, reg.color);\n }\n }\n if (setRegion) {\n this.setRegionsFromEditor();\n }\n }\n xRectUpdate(region: Region, event: any) {\n const rectangle = region.bounds;\n if (rectangle && rectangle instanceof Rectangle) {\n rectangle.x = event.value;\n this.setRegionsFromEditor();\n }\n }\n yRectUpdate(region: Region, event: any) {\n const rectangle = region.bounds;\n if (rectangle && rectangle instanceof Rectangle) {\n rectangle.y = event.value;\n this.setRegionsFromEditor();\n }\n }\n widthRectUpdate(region: Region, event: any) {\n if (event.value === null || event.value === undefined) return;\n const rectangle = region.bounds;\n if (rectangle && rectangle instanceof Rectangle) {\n const reg = this.regionsCopy.filter((element: Region) => element.id === region.id);\n if (reg.length) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const oldWidth = reg[0].bounds.width;\n const diffWidth = event.value - oldWidth;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n rectangle.x = Math.round(reg[0].bounds.x - diffWidth / 2);\n }\n rectangle.width = event.value;\n this.setRegionsFromEditor();\n this.regionsCopy = this.deepClone(this.regions);\n }\n }\n heightRectUpdate(region: Region, event: any) {\n if (event.value === null || event.value === undefined) return;\n const rectangle = region.bounds;\n if (rectangle && rectangle instanceof Rectangle) {\n const reg = this.regionsCopy.filter((element: Region) => element.id === region.id);\n if (reg.length) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const oldHeight = reg[0].bounds.height;\n const diffHeight = event.value - oldHeight;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n rectangle.y = Math.round(reg[0].bounds.y - diffHeight / 2);\n }\n rectangle.height = event.value;\n this.setRegionsFromEditor();\n this.regionsCopy = this.deepClone(this.regions);\n }\n }\n\n onPageChange(event: { first?: number; rows?: number }) {\n this.paginatorFirst = event.first ?? 0;\n this.paginatorRows = event.rows ?? this.paginatorRows;\n }\n\n /** Select every region in the table (and highlight them on the diagram). */\n selectAllRegions() {\n this.selectedRegions = [...this.regions];\n this.onSelectionChanged();\n }\n\n deleteSelectedRegions() {\n if (this.selectedRegions && this.selectedRegions.length > 0) {\n // Filter by id — object identity isn't reliable across re-parses,\n // and name is a user-editable label that may collide.\n const removed = new Set(this.selectedRegions.map((r) => r.id));\n this.regions = this.regions.filter((r) => !removed.has(r.id));\n this.selectedRegions = [];\n this.clampPaginatorFirst();\n this.setRegionsFromEditor();\n // Sync the cleared selection with the plot's highlight state.\n this.onSelectionChanged();\n }\n }\n\n clearAllRegions() {\n this.confirmationService.confirm({\n key: 'positionDialog',\n message: 'Are you sure you want to delete all regions?',\n accept: () => {\n this.regions = [];\n this.selectedRegions = [];\n this.paginatorFirst = 0;\n this.setRegionsFromEditor();\n this.onSelectionChanged();\n },\n });\n }\n\n addPolygon() {\n const region = new Region();\n region.bounds = new Polygon();\n region.label = this.activeClass ?? 'Region';\n region.bounds.ypoints = [0, 0, 0];\n region.bounds.xpoints = [0, 0, 0];\n region.bounds.coordinates = [\n [0, 0],\n [0, 0],\n [0, 0],\n ];\n region.bounds.npoints = 3;\n this.regions = [...this.regions, region];\n this.setRegionsFromEditor();\n this.regionsCopy = this.deepClone(this.regions);\n }\n deleteRegion(shapeIdx: number) {\n const removed = this.regions[shapeIdx];\n this.regions = this.regions.filter((_, i) => i !== shapeIdx);\n if (removed) {\n this.selectedRegions = this.selectedRegions.filter((r) => r.id !== removed.id);\n }\n this.clampPaginatorFirst();\n this.setRegionsFromEditor();\n // Re-emit the (possibly trimmed) selection so the plot's highlight stays\n // in sync with what's still in the table.\n this.onSelectionChanged();\n }\n\n private clampPaginatorFirst() {\n const maxFirst = Math.max(\n 0,\n Math.floor((this.regions.length - 1) / this.paginatorRows) * this.paginatorRows,\n );\n if (this.paginatorFirst > maxFirst) {\n this.paginatorFirst = maxFirst;\n }\n }\n changeShowShapeLabel(showLabel: boolean) {\n this.setRegionsFromEditor();\n }\n\n isEditingLabel(region: any): boolean {\n return this.editingLabelRegions.has(region);\n }\n\n startEditLabel(region: any, event?: Event): void {\n event?.stopPropagation(); // don't toggle row selection\n this.editingLabelRegions.add(region);\n }\n\n stopEditLabel(region: any, commit: boolean, event?: Event): void {\n event?.stopPropagation();\n this.editingLabelRegions.delete(region);\n if (commit) {\n this.labelRegionUpdate(region, true);\n }\n }\n\n isRectangle(region: Region) {\n return region.bounds instanceof Rectangle;\n }\n\n /**\n * Region area for display: in µm² (or mm²) when the image reports a physical\n * pixel size, otherwise in px². Empty string for degenerate regions.\n */\n regionArea(region: Region): string {\n const px = this.areaInPixels(region);\n if (px <= 0) return '';\n if (this.mppX && this.mppY && this.mppX > 0 && this.mppY > 0) {\n const um2 = px * this.mppX * this.mppY;\n return um2 >= 1e6 ? `${this.fmtArea(um2 / 1e6)} mm²` : `${this.fmtArea(um2)} µm²`;\n }\n return `${this.fmtArea(px)} px²`;\n }\n\n /**\n * Choose the physical pixel size (µm/pixel) for area display from the image\n * meta. The calibration may sit on any channel entry — not necessarily [0] —\n * so pick the first entry with a positive mppX (mirrors\n * PlotlyService.currentMpp). Falls back to square pixels (mppY = mppX) when\n * only one axis is reported, so a scaled image shows µm²/mm² rather than px².\n */\n private pickMpp(meta: IImageMetadata[] | undefined): { mppX?: number; mppY?: number } {\n const m = Array.isArray(meta)\n ? (meta.find((e) => e && (e.mppX ?? 0) > 0) ?? meta[0])\n : undefined;\n const mx = m && (m.mppX ?? 0) > 0 ? (m.mppX as number) : undefined;\n const my = m && (m.mppY ?? 0) > 0 ? (m.mppY as number) : undefined;\n return { mppX: mx, mppY: my ?? mx };\n }\n\n /** Pixel area: width·height for rectangles, shoelace formula for polygons.\n * Interior rings (holes) are subtracted, so a donut reports the annulus area,\n * not the filled exterior (jit-ui#85). */\n private areaInPixels(region: Region): number {\n const b = region.bounds;\n if (b instanceof Rectangle) return Math.abs(b.width * b.height);\n if (b instanceof Polygon) return this.polygonArea(b);\n // Multi-part region: sum each part's (exterior − holes) area (jit-ui#85).\n if (b instanceof MultiPolygon) {\n return b.polygons.reduce((sum, p) => sum + this.polygonArea(p), 0);\n }\n return 0;\n }\n\n /** Polygon area: exterior shoelace minus each interior ring (hole). */\n private polygonArea(p: Polygon): number {\n if ((p.xpoints?.length ?? 0) < 3) return 0;\n let a = this.ringArea(p.xpoints, p.ypoints);\n if (p.holes) {\n for (const ring of p.holes) a -= this.ringArea(ring.map(pt => pt[0]), ring.map(pt => pt[1]));\n }\n return Math.max(0, a);\n }\n\n /** Absolute shoelace area of a single ring. */\n private ringArea(xs: number[], ys: number[]): number {\n const n = xs?.length ?? 0;\n if (n < 3) return 0;\n let a = 0;\n for (let i = 0, j = n - 1; i < n; j = i++) a += (xs[j] + xs[i]) * (ys[j] - ys[i]);\n return Math.abs(a / 2);\n }\n\n private fmtArea(n: number): string {\n return (n >= 1000 ? Math.round(n) : Math.round(n * 100) / 100).toLocaleString();\n }\n\n /**\n * This method rounds all the rectangle regions lengths to multiple of 512\n */\n roundRectangleLengths() {\n for (const region of this.regions) {\n if (region.bounds instanceof Rectangle) {\n const rect = region.bounds;\n rect.height = Math.round(rect.height / 512) * 512;\n rect.width = Math.round(rect.width / 512) * 512;\n }\n }\n this.setRegionsFromEditor();\n }\n\n /**\n * Stop key arrow event propagation\n * @param event\n */\n disableArrowKeys(event: any) {\n if (\n event.key === 'ArrowDown' ||\n event.key === 'Down' ||\n event.key === 'ArrowUp' ||\n event.key === 'Up' ||\n event.key === 'ArrowLeft' ||\n event.key === 'Left' ||\n event.key === 'ArrowRight' ||\n event.key === 'Right'\n ) {\n event.stopPropagation();\n }\n }\n\n changeShapeColor(event: any) {\n this.shapeColor = event.value;\n for (const region of this.regions) {\n if (region.label === this.selectedLabelColor && this.labelColors.has(region.label)) {\n this.labelColors.set(region.label, this.shapeColor);\n region.color = this.shapeColor;\n }\n }\n this.setRegionsFromEditor(this.fillColor);\n }\n\n showHelp() {\n this.displayHelpDialog = true;\n }\n\n /** Open the colour dialog for the currently-selected region(s), building one\n * colour picker per unique class in the selection. Each picker is seeded with\n * the class's current colour (the label→colour map, falling back to the first\n * selected region of that class). */\n openColorDialog() {\n if (!this.selectedRegions?.length) return;\n const seedByLabel = new Map<string, string>();\n for (const region of this.selectedRegions) {\n const label = region.label?.trim() ?? '';\n if (seedByLabel.has(label)) continue;\n seedByLabel.set(\n label,\n (label ? this.labelColors.get(label) : undefined) ?? region.color ?? this.shapeColor,\n );\n }\n this.classColorEdits = [...seedByLabel].map(([label, color]) => ({ label, color }));\n this.showColorDialog = true;\n }\n\n /** Apply each class's chosen colour to the selected regions of that class and\n * commit live. Remembers the colour per class so same-class regions added\n * later match. */\n applyColorToSelected() {\n const colorByLabel = new Map(this.classColorEdits.map((e) => [e.label, e.color]));\n for (const region of this.selectedRegions ?? []) {\n const label = region.label?.trim() ?? '';\n const color = colorByLabel.get(label);\n if (!color) continue;\n region.color = color;\n region.colorOverridden = true; // explicit colour — preserve against preset (re)apply (jit-ui#70)\n if (label) this.labelColors.set(label, color);\n }\n this.setRegionsFromEditor();\n this.showColorDialog = false;\n }\n\n // ── annotation-class presets (jit-ui#70) ─────────────────────────────\n\n /** Resolve the display colour for a class name (preset colour or deterministic fallback). */\n colorForName(name?: string): string {\n return name ? colorForLabel(name, this.presetSet) : this.shapeColor;\n }\n\n /**\n * Ensure every class label present in the loaded regions exists in the preset\n * list, auto-adding any that are missing (using the region's already-resolved\n * colour). This makes classes carried in a loaded/imported GeoJSON show up as\n * chips + Class-dropdown options (a p-dropdown can't display a value that isn't\n * an option) and lets the user manage them. The placeholder 'legend' and empty\n * labels are ignored. (jit-ui#70)\n */\n private syncClassesFromRegions(regions: Region[]): void {\n const normalized = this.presetSet.matchMode === 'normalized';\n const keyOf = (l: string) => (normalized ? l.trim().toLowerCase() : l);\n const known = new Set(this.presetSet.classes.map((c) => keyOf(c.name)));\n const added = new Set<string>();\n for (const r of regions) {\n const label = r.label?.trim();\n if (!label || label === 'legend') continue;\n const k = keyOf(label);\n if (known.has(k) || added.has(k)) continue;\n added.add(k);\n this.regionApi.upsertClass({\n name: label,\n color: r.color || colorForLabel(label, this.presetSet),\n source: 'auto',\n });\n }\n }\n\n // ── Docked Classes panel (jit-ui#70) ─────────────────────────────────\n\n /** Rebuild the per-class region counts shown in the panel. */\n private recomputeClassCounts(): void {\n const normalized = this.presetSet.matchMode === 'normalized';\n const counts = new Map<string, number>();\n for (const r of this.regions) {\n if (!r.label) continue;\n const k = normalized ? r.label.trim().toLowerCase() : r.label;\n counts.set(k, (counts.get(k) ?? 0) + 1);\n }\n this.classCounts = counts;\n this.updateDisplayClasses();\n }\n\n /** Rebuild the panel's display order — most-used classes first, then by name. */\n private updateDisplayClasses(): void {\n this.displayClasses = [...this.presetSet.classes].sort((a, b) => {\n const d = this.classCount(b.name) - this.classCount(a.name);\n return d !== 0 ? d : a.name.localeCompare(b.name);\n });\n }\n\n /** trackBy for the class rows so re-sorting doesn't re-create the pickers. */\n trackByClassName = (_: number, c: ClassPreset): string => c.name;\n\n /** Number of regions currently using a class (keyed by the active match mode). */\n classCount(name: string): number {\n const k = this.presetSet.matchMode === 'normalized' ? name.trim().toLowerCase() : name;\n return this.classCounts.get(k) ?? 0;\n }\n\n /** Recolour a class from its panel swatch and repaint its (non-overridden) regions. */\n setClassColor(name: string, color: string): void {\n if (!color) return;\n this.regionApi.setClassificationColor(name, color);\n this.setRegionsFromEditor();\n }\n\n /** Tooltip for a class's delete button in the panel. */\n deleteClassTooltip(name: string): string {\n const inUse = this.classCount(name) > 0;\n if (name === this.defaultClassName && inUse) return 'The default class cannot be removed while in use';\n return inUse ? 'Remove class — its regions revert to Region' : 'Remove class';\n }\n\n /** Remove a class. Any regions still using it fall back to the default\n * \"Region\" class, so they aren't orphaned (and the class isn't immediately\n * re-added from its regions by syncClassesFromRegions). */\n deleteClass(name: string): void {\n this.reassignRegionsToDefaultClass([name]);\n this.regionApi.removeClass(name);\n if (this.activeClass === name) this.activeClass = null;\n this.setRegionsFromEditor();\n }\n\n /** Regions labelled with any of `removedNames` revert to the default\n * {@link defaultClassName} (\"Region\"): its class colour, override cleared.\n * Skips the default itself so deleting \"Region\" can't self-reassign. (jit-ui#70) */\n private reassignRegionsToDefaultClass(removedNames: string[]): void {\n const norm = this.presetSet.matchMode === 'normalized';\n const keyOf = (s: string) => (norm ? s.trim().toLowerCase() : s);\n const removed = new Set(removedNames.map(keyOf));\n removed.delete(keyOf(this.defaultClassName));\n if (!removed.size) return;\n const color = colorForLabel(this.defaultClassName, this.presetSet);\n for (const r of this.regions) {\n if (r.label && removed.has(keyOf(r.label))) {\n r.label = this.defaultClassName;\n r.colorOverridden = false;\n r.color = color;\n }\n }\n }\n\n /** Stamp a class (and its preset/fallback colour) onto one region from the Class\n * dropdown; choosing a class opts the region back into the preset colour. */\n applyPresetToRegion(region: Region, className: string): void {\n const name = (className ?? '').trim();\n region.label = name;\n region.colorOverridden = false;\n if (name) region.color = colorForLabel(name, this.presetSet);\n this.setRegionsFromEditor();\n }\n\n /** Make a class active (used for new regions) and, if rows are selected, apply\n * it to them in one commit. */\n selectActiveClass(name: string): void {\n this.activeClass = name;\n this.applyClassToSelected(name);\n }\n\n /** Apply a class (label + preset/fallback colour) to the current selection and commit. */\n private applyClassToSelected(name: string): void {\n const selected = this.selectedRegions ?? [];\n if (!selected.length) return;\n for (const r of selected) {\n r.label = name;\n r.colorOverridden = false;\n r.color = colorForLabel(name, this.presetSet);\n }\n this.setRegionsFromEditor();\n }\n\n /** \"Edit class on selected rows\" popup — apply the chosen existing class. */\n applyBulkClass(): void {\n if (!this.bulkClass) return;\n this.applyClassToSelected(this.bulkClass);\n this.overlayPanel?.hide();\n }\n\n /** \"Edit class on selected rows\" popup — add a new class and set it on the selection. */\n addAndApplyBulkClass(): void {\n const name = this.newBulkClass.trim();\n if (!name) return;\n const norm = this.presetSet.matchMode === 'normalized';\n const exists = this.presetSet.classes.some((c) =>\n norm ? c.name.trim().toLowerCase() === name.toLowerCase() : c.name === name,\n );\n if (!exists) {\n this.regionApi.upsertClass({ name, color: colorForLabel(name, this.presetSet), source: 'user' });\n }\n this.applyClassToSelected(name);\n this.bulkClass = name;\n this.newBulkClass = '';\n this.overlayPanel?.hide();\n }\n\n // ── Manage-classes dialog ──\n openManageDialog(): void {\n this.presetDraft = this.clonePresetSet(this.presetSet);\n this.showManageDialog = true;\n }\n private clonePresetSet(s: PresetSet): PresetSet {\n return {\n classes: (s.classes ?? []).map((c) => ({ ...c })),\n fallbackPalette: [...(s.fallbackPalette ?? [])],\n autoPromote: !!s.autoPromote,\n matchMode: s.matchMode === 'normalized' ? 'normalized' : 'exact',\n };\n }\n addPresetClass(): void {\n this.presetDraft?.classes.push({ name: '', color: '#888888', source: 'user' });\n }\n removePresetClass(i: number): void {\n this.presetDraft?.classes.splice(i, 1);\n }\n addFallbackColor(): void {\n this.presetDraft?.fallbackPalette.push('#888888');\n }\n removeFallbackColor(i: number): void {\n this.presetDraft?.fallbackPalette.splice(i, 1);\n }\n /** Commit the draft: drop blank/duplicate names, persist, and recolour\n * non-overridden regions with the updated presets. */\n applyManageDialog(close: boolean): void {\n if (!this.presetDraft) return;\n // De-duplicate using the active match mode's key so normalized mode can't keep\n // both \"Tumor\" and \"tumor\" (which would collide at runtime in findPreset()).\n const norm = this.presetDraft.matchMode === 'normalized';\n const seen = new Set<string>();\n const classes: ClassPreset[] = [];\n for (const c of this.presetDraft.classes) {\n const name = (c.name ?? '').trim();\n const key = norm ? name.toLowerCase() : name;\n if (!name || seen.has(key)) continue;\n seen.add(key);\n classes.push({ ...c, name });\n }\n this.presetDraft.classes = classes;\n // Classes dropped in the dialog: their regions revert to the default \"Region\"\n // class (else syncClassesFromRegions would just re-add them) (jit-ui#70).\n const keyOf = (s: string) => (norm ? s.trim().toLowerCase() : s);\n const kept = new Set(classes.map((c) => keyOf(c.name)));\n const removed = this.presetSet.classes\n .map((c) => c.name)\n .filter((n) => !kept.has(keyOf(n)));\n this.reassignRegionsToDefaultClass(removed);\n this.regionApi.setPresetSet(this.presetDraft);\n this.setRegionsFromEditor(); // recolour existing (non-overridden) regions from the new presets\n if (close) this.showManageDialog = false;\n }\n resetPresetsToDefaults(): void {\n this.regionApi.resetPresets();\n this.presetDraft = this.clonePresetSet(this.regionApi.getPresetSet());\n this.setRegionsFromEditor();\n }\n exportPresets(): void {\n const json = JSON.stringify(this.regionApi.getPresetSet(), null, 2);\n saveAs(new Blob([json], { type: 'application/json' }), 'annotation-classes.json');\n }\n importPresets(event: Event): void {\n const input = event.target as HTMLInputElement;\n const file = input.files?.[0];\n if (!file) return;\n const reader = new FileReader();\n reader.onload = (e: any) => {\n try {\n const set = JSON.parse(e.target.result) as PresetSet;\n this.regionApi.setPresetSet(set);\n this.presetDraft = this.clonePresetSet(this.regionApi.getPresetSet());\n this.setRegionsFromEditor();\n this.messageService.add({ key: 'app-toast', severity: 'success',\n summary: 'Classes imported', detail: 'Annotation classes loaded.' });\n } catch (err) {\n this.messageService.add({ key: 'app-toast', severity: 'error',\n summary: 'Import failed', detail: `${err}` });\n }\n };\n reader.readAsText(file);\n }\n\n importRois(event: Event) {\n const input = event.target as HTMLInputElement;\n const file = input.files?.[0];\n if (!file) return;\n const reader = new FileReader();\n reader.onload = (e: any) => {\n const fileContent = e.target.result;\n try {\n this.regions = this.regionApi.importRegions(fileContent);\n // set label colors\n for (const region of this.regions) {\n this.labelRegionUpdate(region, false);\n }\n this.syncClassesFromRegions(this.regions);\n this.setRegionsFromEditor();\n } catch (event) {\n this.messageService.add({\n severity: 'error',\n summary: 'Error importing the file',\n detail: `${event}`,\n });\n console.error('Error reading the file: ' + event);\n }\n };\n reader.readAsText(file);\n }\n\n /**\n * Regions to serialize on save/export. For a single-file z-stack the store\n * keeps only the current slice live, so pull EVERY slice's annotations (each\n * tagged with its zero-based Region.z) to write one combined z-indexed\n * geojson (jit-ui#93). Otherwise (single-plane image, or a folder stack whose\n * slices save to their own per-slice files) the current set. (jit-ui#93)\n */\n private regionsForSave(): Region[] {\n if (this.regionApi.isStackMode() && this.regionApi.getStackSaveLayout() === 'combined') {\n return this.regionApi.getSliceAnnotationRegions();\n }\n return this.regions;\n }\n\n exportRois() {\n if (!this.regionsForSave().length) return;\n const name = this.regionIo.getSelectedFileName();\n const stem = name ? name.substring(0, name.lastIndexOf('.')) : 'rois';\n this.exportFilename = `${stem}.geojson`;\n this.showExportDialog = true;\n }\n\n confirmExport() {\n const filename = this.exportFilename.trim();\n const regions = this.regionsForSave();\n if (!filename || !regions.length) return;\n this.showExportDialog = false;\n const jsonString = this.regionApi.getGeoJsonString(regions);\n const blob = new Blob([jsonString], { type: 'application/json' });\n saveAs(blob, filename);\n }\n\n /** Open the \"Save mask\" dialog, seeded with `<image-stem>_mask.png`. */\n openSaveMaskDialog() {\n if (!this.regions.length) return;\n const name = this.regionIo.getSelectedFileName();\n // Strip the extension only when there is one; an extension-less name keeps\n // its whole stem (a leading-dot dotfile is treated as having no extension)\n // so we never produce a bare \"_mask.png\".\n const dot = name ? name.lastIndexOf('.') : -1;\n const stem = name ? (dot > 0 ? name.substring(0, dot) : name) : 'regions';\n this.saveMaskFilename = `${stem}_mask.png`;\n this.maskMode = 'binary';\n this.showSaveMaskDialog = true;\n }\n\n /**\n * Rasterize the regions to the chosen mask type and download as a PNG. The\n * heavy work (full-res rasterize + PNG encode) runs in a Web Worker so the UI\n * never freezes on large/whole-slide images and the job can be cancelled\n * (jit-ui#95). The dialog stays open showing a progress bar until done.\n */\n confirmSaveMask() {\n const filename = this.saveMaskFilename.trim();\n if (!filename || !this.regions.length || this.maskBusy) return;\n\n const size = this.regionApi.getMaskImageSize();\n if (!size) {\n this.maskError('No image size is available, so the mask cannot be sized.');\n return;\n }\n\n // Whole-slide images exceed the browser's typed-array/memory limits, so cap\n // the mask to a safe pixel budget and scale the geometry to match.\n const scale = maskScaleFor(size.width, size.height);\n const width = Math.max(1, Math.round(size.width * scale));\n const height = Math.max(1, Math.round(size.height * scale));\n if (scale < 1) {\n this.messageService.add({\n key: 'app-toast',\n severity: 'info',\n summary: 'Mask downscaled',\n detail: `Image too large for a full-resolution mask; saving at ${width}×${height}.`,\n });\n }\n const regions = this.regions.map((r) => scaleParts(regionToParts(r), scale));\n\n this.pendingMaskFilename = filename;\n this.maskBusy = true;\n this.maskEncoding = false;\n this.maskProgress = 0;\n\n const payload = {\n width, height,\n originalWidth: size.width, originalHeight: size.height, scale,\n mode: this.maskMode,\n sourceName: this.regionIo.getSelectedFileName(),\n regions,\n };\n // createMaskWorker() is async (the worker module is imported dynamically so\n // its import.meta never reaches the CommonJS test compile). Wire up once it\n // resolves — unless the user cancelled while it was loading.\n this.createMaskWorker().then((worker) => {\n if (!this.maskBusy) { worker.terminate(); return; }\n this.maskWorker = worker;\n worker.onmessage = ({ data }: MessageEvent) => {\n switch (data?.type) {\n case 'progress':\n this.maskProgress = data.total ? Math.round((data.done / data.total) * 100) : 0;\n break;\n case 'encoding':\n this.maskEncoding = true;\n break;\n case 'done':\n this.finishMask(new Blob([data.png], { type: 'image/png' }));\n break;\n case 'error':\n this.maskError(data.error || 'The mask could not be generated.');\n break;\n }\n };\n worker.onerror = () => this.maskError('The mask worker failed.');\n worker.postMessage(payload);\n }).catch(() => this.maskError('The mask worker failed to start.'));\n }\n\n /** Cancel an in-progress mask export: terminate the worker and reset state. */\n cancelSaveMask() {\n this.teardownMaskWorker();\n this.maskBusy = false;\n this.maskEncoding = false;\n this.maskProgress = 0;\n }\n\n /** Worker factory — async so the worker module (and its `import.meta.url`,\n * which the CommonJS test compile rejects) is loaded via a dynamic import,\n * exactly like the segmentation worker. Overridable in tests. */\n protected async createMaskWorker(): Promise<Worker> {\n const { createMaskWorker } = await import('./mask-worker');\n return createMaskWorker();\n }\n\n private finishMask(blob: Blob) {\n this.teardownMaskWorker();\n this.maskBusy = false;\n this.maskEncoding = false;\n this.showSaveMaskDialog = false;\n saveAs(blob, this.pendingMaskFilename);\n }\n\n private maskError(detail: string) {\n this.teardownMaskWorker();\n this.maskBusy = false;\n this.maskEncoding = false;\n this.messageService.add({\n key: 'app-toast',\n severity: 'error',\n summary: 'Could not create mask',\n detail,\n });\n }\n\n private teardownMaskWorker() {\n this.maskWorker?.terminate();\n this.maskWorker = undefined;\n }\n\n persistRegions() {\n // Folder stack: write each slice's regions back to its own slice-file's\n // sibling geojson — no single-filename prompt (the filenames are the slice\n // files'). (jit-ui#93)\n if (this.regionApi.isStackMode() && this.regionApi.getStackSaveLayout() === 'per-slice-file') {\n this.saveStackSlices();\n return;\n }\n const name = this.regionIo.getSelectedFileName();\n if (!name || !this.regionsForSave().length) return;\n\n this.saveAsFilename = name.substring(0, name.lastIndexOf('.')) + '.geojson';\n this.saveAsFileExists = false;\n this.showSaveAsDialog = true;\n this._saveAsCheck$.next(this.saveAsFilename);\n }\n\n /**\n * Save a folder stack's regions as one geojson per slice-file (jit-ui#93).\n * Groups the store's per-slice regions by slice index and serializes each on\n * the default plane (z=0) — each slice-file is itself one plane, and the\n * loader re-derives the slice index from the file's position in the series.\n * Slices cleared since load are included (empty) so their file is overwritten.\n */\n private saveStackSlices() {\n const bySlice = this.regionApi.getStackSaveAnnotationSlices();\n if (!bySlice.size) return;\n const slices: { z: number; geoJsonStr: string }[] = [];\n for (const [z, regs] of bySlice) {\n const flat = regs.map((r) => Object.assign(new Region(), r, { z: 0 }));\n slices.push({ z, geoJsonStr: this.regionApi.getGeoJsonString(flat) });\n }\n this.saveAsBusy = true;\n this._saveAsSub = this.regionIo.saveSliceGeoJsons(slices).subscribe({\n next: () => {\n this.saveAsBusy = false;\n this.messageService.add({\n key: 'app-toast',\n severity: 'success',\n summary: 'Regions saved',\n detail: `Saved ROIs for ${slices.length} slice${slices.length === 1 ? '' : 's'}`,\n });\n },\n error: (err) => {\n this.saveAsBusy = false;\n this.messageService.add({\n key: 'app-toast',\n severity: 'error',\n summary: 'Error saving regions',\n detail: `${(err as Error)?.message ?? err}`,\n });\n },\n });\n }\n\n checkSaveAsFileExists() {\n this._saveAsCheck$.next(this.saveAsFilename);\n }\n\n confirmSaveAs() {\n if (!this.regionIo.getSelectedFileName()) return;\n\n const filename = this.saveAsFilename.trim();\n if (!filename) return;\n\n const doSave = () => {\n // Keep the dialog open showing an (indeterminate) progress bar while the\n // regions serialize and upload, then close on success. Defer one tick so\n // the bar paints before a large synchronous GeoJSON serialize.\n this.saveAsBusy = true;\n this._saveAsTimer = setTimeout(() => {\n this._saveAsTimer = undefined;\n let geoJsonStr: string;\n try {\n geoJsonStr = this.regionApi.getGeoJsonString(this.regionsForSave());\n } catch (err) {\n this.saveAsBusy = false;\n this.messageService.add({\n key: 'app-toast',\n severity: 'error',\n summary: 'Error saving regions',\n detail: `${(err as Error)?.message ?? err}`,\n });\n return;\n }\n this._saveAsSub = this.regionIo.saveGeoJson(geoJsonStr, filename).subscribe({\n next: () => {\n this.saveAsBusy = false;\n this.showSaveAsDialog = false;\n this.messageService.add({\n key: 'app-toast',\n severity: 'success',\n summary: 'Regions saved',\n detail: `Saved as ${filename}`,\n });\n },\n error: (err) => {\n this.saveAsBusy = false;\n this.messageService.add({\n key: 'app-toast',\n severity: 'error',\n summary: 'Error saving regions',\n detail: `${err.message || err}`,\n });\n },\n });\n });\n };\n\n if (this.saveAsFileExists) {\n this.confirmationService.confirm({\n message: `\"${filename}\" already exists. Do you want to overwrite it?`,\n header: 'Confirm Overwrite',\n icon: 'pi pi-exclamation-triangle',\n accept: doSave,\n });\n } else {\n doSave();\n }\n }\n\n /** Cancel an in-progress GeoJSON persist: abort the deferred serialize and/or\n * the in-flight upload, and reset state. */\n cancelSaveAs() {\n if (this._saveAsTimer !== undefined) {\n clearTimeout(this._saveAsTimer);\n this._saveAsTimer = undefined;\n }\n this._saveAsSub?.unsubscribe();\n this._saveAsSub = undefined;\n this.saveAsBusy = false;\n }\n}\n","\n<p-toolbar styleClass=\"region-toolbar\">\n <div class=\"p-toolbar-group-start align-items-center flex-wrap gap-1\">\n <p-button icon=\"pi pi-tag\" size=\"small\"\n [text]=\"!showShapeLabel\"\n pTooltip=\"Show region labels.\"\n tooltipPosition=\"bottom\"\n (onClick)=\"showShapeLabel = !showShapeLabel; changeShowShapeLabel(showShapeLabel)\">\n </p-button>\n <span class=\"toolbar-separator\"></span>\n <!-- New regions are now created from the diagram toolbar\n (rectangle, polyline, freeform, wand). -->\n <p-button icon=\"pi pi-upload\" size=\"small\" [text]=\"true\" styleClass=\"mr-2\"\n pTooltip=\"Upload and display regions from geojson file.\"\n tooltipPosition=\"bottom\"\n (click)=\"roiFileInput.click()\">\n </p-button>\n <input #roiFileInput type=\"file\" accept=\".geojson,.json\" hidden\n (change)=\"importRois($event); roiFileInput.value = ''\"/>\n <p-button size=\"small\" [text]=\"true\" styleClass=\"mr-2\"\n pTooltip=\"Download regions as geojson file.\"\n tooltipPosition=\"bottom\" icon=\"pi pi-download\"\n (click)=\"exportRois()\">\n </p-button>\n <p-button icon=\"pi pi-save\" size=\"small\" [text]=\"true\" styleClass=\"mr-2\"\n pTooltip=\"Save regions to server.\"\n tooltipPosition=\"bottom\"\n (click)=\"persistRegions()\"\n [disabled]=\"!regions || !regions.length\">\n </p-button>\n <p-button size=\"small\" [text]=\"true\" styleClass=\"mr-2\"\n pTooltip=\"Download mask of the regions as PNG\"\n tooltipPosition=\"bottom\"\n (click)=\"openSaveMaskDialog()\"\n [disabled]=\"!regions || !regions.length\">\n <!-- References the file so Inkscape edits to mask.svg show up directly\n (the lib's assets/** are served at assets/plotting/). The\n toolbar-icon-dark filter recolours the black SVG to the theme blue,\n same as region-editor.svg and the other SVG toolbar icons. -->\n <img src=\"assets/plotting/mask.svg\" class=\"toolbar-icon-dark\"\n style=\"width: 1rem; height: 1rem; vertical-align: middle;\"\n alt=\"Download mask\"/>\n </p-button>\n <p-button label=\"x512\" size=\"small\" [text]=\"true\" styleClass=\"mr-2\"\n pTooltip=\"Round all rectangle regions\n to width and height that are multiple of 512\" tooltipPosition=\"bottom\"\n (click)=\"roundRectangleLengths()\">\n </p-button>\n <p-button icon=\"pi pi-check-square\" size=\"small\" [text]=\"true\" styleClass=\"mr-2\"\n pTooltip=\"Select all regions\" tooltipPosition=\"bottom\"\n (click)=\"selectAllRegions()\"\n [disabled]=\"!regions || !regions.length\">\n </p-button>\n <p-button icon=\"pi pi-tags\" size=\"small\" [text]=\"true\" styleClass=\"mr-2\"\n pTooltip=\"Edit class on selected rows\"\n tooltipPosition=\"bottom\"\n (click)=\"(!selectedRegions || !selectedRegions.length)? op.hide() : op.toggle($event)\"\n [disabled]=\"!selectedRegions || !selectedRegions.length\">\n </p-button>\n <p-button icon=\"pi pi-palette\" size=\"small\" [text]=\"true\" styleClass=\"mr-2\"\n pTooltip=\"Edit colour of selected regions\"\n tooltipPosition=\"bottom\"\n (click)=\"openColorDialog()\"\n [disabled]=\"!selectedRegions || !selectedRegions.length\">\n </p-button>\n <p-overlayPanel #op (onHide)=\"bulkClass=''; newBulkClass=''\">\n <div class=\"flex flex-column gap-2\" style=\"width: 18rem\">\n <span class=\"font-medium text-900\">Set class on {{ selectedRegions?.length || 0 }} selected region(s)</span>\n <!-- Selecting a class applies it immediately (choosing an option closes the\n overlay, so there's no separate Apply button). -->\n <p-dropdown styleClass=\"w-full\" appendTo=\"body\" [options]=\"presetSet.classes\"\n optionLabel=\"name\" optionValue=\"name\" [(ngModel)]=\"bulkClass\"\n placeholder=\"Choose a class…\"\n [filter]=\"presetSet.classes.length > 8\" filterBy=\"name\"\n (onChange)=\"applyBulkClass()\">\n <ng-template let-c pTemplate=\"item\">\n <span class=\"dd-value\"><span class=\"chip-swatch\" [style.background]=\"c.color\"></span>{{ c.name }}</span>\n </ng-template>\n </p-dropdown>\n <div class=\"p-inputgroup\">\n <input type=\"text\" pInputText placeholder=\"…or a new class\" [(ngModel)]=\"newBulkClass\"\n (keydown.enter)=\"addAndApplyBulkClass()\"/>\n <button pButton type=\"button\" icon=\"pi pi-plus\" pTooltip=\"Add class & set it\"\n tooltipPosition=\"bottom\" [disabled]=\"!newBulkClass.trim()\"\n (click)=\"addAndApplyBulkClass()\"></button>\n </div>\n </div>\n </p-overlayPanel>\n <p-button icon=\"pi pi-trash\" size=\"small\" [text]=\"true\" styleClass=\"mr-2\"\n (click)=\"deleteSelectedRegions()\"\n pTooltip=\"Delete selected regions\" tooltipPosition=\"bottom\"\n [disabled]=\"!selectedRegions || !selectedRegions.length\"></p-button>\n <p-button icon=\"pi pi-times-circle\" size=\"small\" [text]=\"true\" styleClass=\"mr-2\"\n (click)=\"clearAllRegions()\"\n pTooltip=\"Delete all regions\" tooltipPosition=\"bottom\"\n [disabled]=\"!regions || !regions.length\"></p-button>\n <p-button icon=\"pi pi-question\" size=\"small\" [text]=\"true\"\n (click)=\"showHelp()\" pTooltip=\"Help\" tooltipPosition=\"bottom\"></p-button>\n </div>\n</p-toolbar>\n\n<!-- Docked \"Classes\" panel (jit-ui#70): the always-visible list of annotation\n classes above the regions table. Click a row to make it the active class\n (new regions inherit it; with rows selected it re-classifies them); recolour\n via the swatch; the badge shows how many regions use the class. \"Manage\"\n opens the full editor (fallback palette, auto-add, matching, import/export). -->\n<div class=\"classes-panel\">\n <div class=\"classes-panel-header\">\n <span class=\"classes-panel-title\">Classes</span>\n <button pButton type=\"button\" icon=\"pi pi-cog\" label=\"Manage\"\n class=\"p-button-sm p-button-text\"\n pTooltip=\"Manage classes — add / remove, palette, matching, import/export\"\n tooltipPosition=\"bottom\" (click)=\"openManageDialog()\"></button>\n </div>\n <div class=\"classes-panel-body\">\n <div *ngFor=\"let c of displayClasses; trackBy: trackByClassName\"\n class=\"class-row\" [class.active]=\"activeClass === c.name\"\n (click)=\"selectActiveClass(c.name)\"\n [pTooltip]=\"selectedRegions?.length\n ? 'Apply “' + c.name + '” to the selected region(s)'\n : 'Set “' + c.name + '” active — new regions use it'\"\n tooltipPosition=\"bottom\">\n <span class=\"row-swatch\" (click)=\"$event.stopPropagation()\">\n <hex-color-picker [color]=\"c.color\" (colorChange)=\"setClassColor(c.name, $event)\"></hex-color-picker>\n </span>\n <span class=\"row-name\">{{ c.name }}</span>\n <span class=\"row-count\" [class.zero]=\"classCount(c.name) === 0\">{{ classCount(c.name) }}</span>\n <button pButton type=\"button\" icon=\"pi pi-trash\"\n class=\"p-button-sm p-button-text p-button-warning row-del\"\n [disabled]=\"c.name === defaultClassName && classCount(c.name) > 0\"\n [pTooltip]=\"deleteClassTooltip(c.name)\"\n tooltipPosition=\"bottom\"\n (click)=\"$event.stopPropagation(); deleteClass(c.name)\"></button>\n </div>\n <div *ngIf=\"!displayClasses.length\" class=\"classes-empty\">\n No classes yet — add one from Manage.\n </div>\n </div>\n</div>\n\n<div class=\"region-editor-content\">\n <p-table #dt [value]=\"regions.slice(paginatorFirst, paginatorFirst + paginatorRows)\"\n [tableStyle]=\"{'width': '100%'}\" [(selection)]=\"selectedRegions\"\n selectionMode=\"multiple\" [metaKeySelection]=\"metaKey\"\n (onRowSelect)=\"onSelectionChanged()\" (onRowUnselect)=\"onSelectionChanged()\"\n [resizableColumns]=\"true\"\n [rowHover]=\"true\" dataKey=\"id\" styleClass=\"p-datatable-sm region-editor-table\"\n [scrollable]=\"true\" scrollHeight=\"100%\">\n <ng-template pTemplate=\"header\">\n <!-- Hide the column header when there are no regions to show. -->\n <tr *ngIf=\"regions.length > 0\">\n <!-- Class column: shrinks to fit \"Region\" by default, grows with longer labels. -->\n <th class=\"class-col-header\" pResizableColumn>Class <p-sortIcon field=\"label\"></p-sortIcon></th>\n <th class=\"surface-col-header\" pResizableColumn>Surface</th>\n <!-- Trash column: just enough for the icon. -->\n <th style=\"width:2rem\"></th>\n </tr>\n </ng-template>\n <ng-template pTemplate=\"body\" let-region let-shapeIdx=\"rowIndex\">\n <tr [pSelectableRow]=\"region\" [pSelectableRowIndex]=\"shapeIdx\">\n <td class=\"class-cell\">\n <ng-container *ngIf=\"!isEditingLabel(region); else editLabelTpl\">\n <span class=\"class-cell-display\">\n <!-- Quick-pick a preset class (its colour follows); the pencil is for\n a free-form name / rename (jit-ui#70). -->\n <p-dropdown class=\"class-dropdown\" appendTo=\"body\"\n [options]=\"presetSet.classes\" optionLabel=\"name\" optionValue=\"name\"\n [ngModel]=\"region.label\" [autoDisplayFirst]=\"false\"\n (onChange)=\"applyPresetToRegion(region, $event.value)\">\n <ng-template pTemplate=\"selectedItem\">\n <span class=\"dd-value\">\n <span class=\"chip-swatch\" [style.background]=\"colorForName(region.label)\"></span>\n <span class=\"class-name\" [pTooltip]=\"region.label\" tooltipPosition=\"bottom\">{{ region.label || '—' }}</span>\n </span>\n </ng-template>\n <ng-template let-c pTemplate=\"item\">\n <span class=\"dd-value\">\n <span class=\"chip-swatch\" [style.background]=\"c.color\"></span>\n <span>{{ c.name }}</span>\n </span>\n </ng-template>\n </p-dropdown>\n <i class=\"pi pi-pencil icon-hover ml-2\"\n pTooltip=\"Rename / free-form label\" tooltipPosition=\"bottom\"\n (click)=\"startEditLabel(region, $event)\"></i>\n </span>\n </ng-container>\n <ng-template #editLabelTpl>\n <span class=\"p-input-icon-right class-cell-edit\">\n <i class=\"pi pi-times icon-hover\"\n pTooltip=\"Close\" tooltipPosition=\"bottom\"\n (click)=\"stopEditLabel(region, false, $event)\"></i>\n <input type=\"text\" pInputText class=\"p-inputtext-sm w-full\"\n [(ngModel)]=\"region.label\"\n (click)=\"$event.stopPropagation()\"\n (keydown.enter)=\"stopEditLabel(region, true, $event)\"\n (keydown.escape)=\"stopEditLabel(region, false, $event)\"/>\n </span>\n </ng-template>\n </td>\n <!-- Surface area (µm²/mm² when the image is scaled, else px²). -->\n <td class=\"surface-cell\">{{ regionArea(region) || '—' }}</td>\n <td>\n <button pButton pRipple icon=\"pi pi-trash\"\n\t\t\t\t\t\t\tclass=\"p-button-sm p-button-rounded p-button-text p-button-warning\"\n (click)=\"deleteRegion(paginatorFirst + shapeIdx)\"></button>\n </td>\n </tr>\n </ng-template>\n </p-table>\n</div>\n\n<p-paginator *ngIf=\"regions.length > 0\"\n [rows]=\"paginatorRows\" [totalRecords]=\"regions.length\"\n [first]=\"paginatorFirst\"\n [rowsPerPageOptions]=\"rowsPerPageOptions\"\n [showCurrentPageReport]=\"true\"\n currentPageReportTemplate=\"{first} to {last} of {totalRecords}\"\n (onPageChange)=\"onPageChange($event)\"\n styleClass=\"region-editor-paginator\">\n</p-paginator>\n\n<!-- Live-edit mode: no Save/Cancel — every edit commits immediately to the\n active image's region cache. -->\n\n\n<p-confirmDialog #cd [style]=\"{width: '24rem', height: '14rem'}\" key=\"positionDialog\"\n [baseZIndex]=\"10000\" rejectButtonStyleClass=\"p-button-outlined\">\n <ng-template pTemplate=\"footer\">\n <button type=\"button\" pButton icon=\"pi pi-check\" label=\"Yes\" (click)=\"cd.accept()\"></button>\n <button type=\"button\" class=\"p-button-outlined\" pButton icon=\"pi pi-times\" label=\"No\"\n (click)=\"cd.reject()\"></button>\n </ng-template>\n</p-confirmDialog>\n\n<p-dialog header=\"Save Regions As\" [(visible)]=\"showSaveAsDialog\" [modal]=\"true\" appendTo=\"body\"\n [style]=\"{width: '30rem'}\" [draggable]=\"false\" [resizable]=\"false\"\n [closable]=\"!saveAsBusy\" [closeOnEscape]=\"!saveAsBusy\">\n <!-- Idle: filename + overwrite warning. -->\n <div *ngIf=\"!saveAsBusy\" class=\"flex flex-column gap-3 pt-2\">\n <label for=\"geojson-filename\" class=\"font-medium\">GeoJSON filename</label>\n <input id=\"geojson-filename\" type=\"text\" pInputText\n [(ngModel)]=\"saveAsFilename\"\n (ngModelChange)=\"checkSaveAsFileExists()\"\n class=\"w-full\" />\n <small *ngIf=\"saveAsFileExists\" class=\"p-error\">\n <i class=\"pi pi-exclamation-triangle mr-1\"></i>\n This file already exists and will be overwritten.\n </small>\n </div>\n\n <!-- Busy: progress while regions serialize + upload. -->\n <div *ngIf=\"saveAsBusy\" class=\"flex flex-column gap-3 pt-2\">\n <span>Saving regions…</span>\n <p-progressBar mode=\"indeterminate\" [style]=\"{height: '0.75rem'}\"></p-progressBar>\n </div>\n\n <ng-template pTemplate=\"footer\">\n <p-button *ngIf=\"!saveAsBusy\" label=\"Cancel\" icon=\"pi pi-times\" [text]=\"true\"\n (onClick)=\"showSaveAsDialog = false\"></p-button>\n <p-button *ngIf=\"!saveAsBusy\" label=\"Save\" icon=\"pi pi-save\"\n [disabled]=\"!saveAsFilename || !saveAsFilename.trim()\"\n (onClick)=\"confirmSaveAs()\"></p-button>\n <p-button *ngIf=\"saveAsBusy\" label=\"Cancel\" icon=\"pi pi-times\" [text]=\"true\"\n (onClick)=\"cancelSaveAs()\"></p-button>\n </ng-template>\n</p-dialog>\n\n<p-dialog header=\"Export Regions\" [(visible)]=\"showExportDialog\" [modal]=\"true\" appendTo=\"body\"\n [style]=\"{width: '30rem'}\" [draggable]=\"false\" [resizable]=\"false\">\n <div class=\"flex flex-column gap-3 pt-2\">\n <label for=\"export-filename\" class=\"font-medium\">GeoJSON filename</label>\n <input id=\"export-filename\" type=\"text\" pInputText\n [(ngModel)]=\"exportFilename\"\n class=\"w-full\" />\n </div>\n <ng-template pTemplate=\"footer\">\n <p-button label=\"Cancel\" icon=\"pi pi-times\" [text]=\"true\"\n (onClick)=\"showExportDialog = false\"></p-button>\n <p-button label=\"Export\" icon=\"pi pi-download\"\n [disabled]=\"!exportFilename || !exportFilename.trim()\"\n (onClick)=\"confirmExport()\"></p-button>\n </ng-template>\n</p-dialog>\n\n<p-dialog header=\"Save Mask\" [(visible)]=\"showSaveMaskDialog\" [modal]=\"true\" appendTo=\"body\"\n [style]=\"{width: '30rem'}\" [draggable]=\"false\" [resizable]=\"false\"\n [closable]=\"!maskBusy\" [closeOnEscape]=\"!maskBusy\">\n <!-- Idle: filename + mask-type form. -->\n <div *ngIf=\"!maskBusy\" class=\"flex flex-column gap-3 pt-2\">\n <label for=\"mask-filename\" class=\"font-medium\">Mask filename</label>\n <input id=\"mask-filename\" type=\"text\" pInputText\n [(ngModel)]=\"saveMaskFilename\"\n class=\"w-full\" />\n <span class=\"font-medium\">Mask type</span>\n <div class=\"flex align-items-center gap-2\">\n <p-radioButton inputId=\"mask-binary\" name=\"maskMode\" value=\"binary\"\n [(ngModel)]=\"maskMode\"></p-radioButton>\n <label for=\"mask-binary\">Binary <span class=\"text-color-secondary\">(regions 1, background 0)</span></label>\n </div>\n <div class=\"flex align-items-center gap-2\">\n <p-radioButton inputId=\"mask-multiclass\" name=\"maskMode\" value=\"multiclass\"\n [(ngModel)]=\"maskMode\"></p-radioButton>\n <label for=\"mask-multiclass\">Multi-class <span class=\"text-color-secondary\">(unique id per region, background 0)</span></label>\n </div>\n </div>\n\n <!-- Busy: progress while the worker rasterizes + encodes the PNG. -->\n <div *ngIf=\"maskBusy\" class=\"flex flex-column gap-3 pt-2\">\n <span>{{ maskEncoding ? 'Encoding PNG…' : 'Rasterizing regions…' }}</span>\n <p-progressBar [mode]=\"maskEncoding ? 'indeterminate' : 'determinate'\"\n [value]=\"maskProgress\"\n [style]=\"{height: '0.75rem'}\"></p-progressBar>\n </div>\n\n <ng-template pTemplate=\"footer\">\n <p-button *ngIf=\"!maskBusy\" label=\"Cancel\" icon=\"pi pi-times\" [text]=\"true\"\n (onClick)=\"showSaveMaskDialog = false\"></p-button>\n <p-button *ngIf=\"!maskBusy\" label=\"Download\" icon=\"pi pi-download\"\n [disabled]=\"!saveMaskFilename || !saveMaskFilename.trim()\"\n (onClick)=\"confirmSaveMask()\"></p-button>\n <p-button *ngIf=\"maskBusy\" label=\"Cancel\" icon=\"pi pi-times\" [text]=\"true\"\n (onClick)=\"cancelSaveMask()\"></p-button>\n </ng-template>\n</p-dialog>\n\n<p-dialog header=\"Region colour\" [(visible)]=\"showColorDialog\" [modal]=\"false\" appendTo=\"body\"\n [style]=\"{width: '24rem'}\" [draggable]=\"true\" [resizable]=\"false\">\n <div class=\"flex flex-column gap-3 pt-2\">\n <span>Outline colour per class for the\n <b>{{ selectedRegions?.length || 0 }}</b> selected region(s):</span>\n <div *ngFor=\"let edit of classColorEdits; let i = index\"\n class=\"flex align-items-center gap-3\">\n <span class=\"font-medium flex-1\">{{ edit.label || 'Unclassified' }}</span>\n <hex-color-picker [color]=\"edit.color\"\n (colorChange)=\"classColorEdits[i].color = $event\"></hex-color-picker>\n </div>\n </div>\n <ng-template pTemplate=\"footer\">\n <p-button label=\"Cancel\" icon=\"pi pi-times\" [text]=\"true\" (onClick)=\"showColorDialog = false\">\n </p-button>\n <p-button label=\"Apply\" icon=\"pi pi-check\" (onClick)=\"applyColorToSelected()\">\n </p-button>\n </ng-template>\n</p-dialog>\n\n<!-- Manage annotation classes (jit-ui#70): CRUD + fallback palette + matching/auto-add\n settings + reset/import/export. Edits a working copy, committed on Apply/Done. -->\n<p-dialog header=\"Manage annotation classes\" [(visible)]=\"showManageDialog\" [modal]=\"true\" appendTo=\"body\"\n [style]=\"{width: '34rem'}\" [draggable]=\"true\" [resizable]=\"false\">\n <div *ngIf=\"presetDraft\" class=\"manage-dialog flex flex-column gap-3 pt-2\">\n <div class=\"manage-classes flex flex-column gap-2\">\n <div *ngFor=\"let c of presetDraft.classes; let i = index\"\n class=\"manage-class-row flex align-items-center gap-2\">\n <hex-color-picker [color]=\"c.color\" (colorChange)=\"c.color = $event\"></hex-color-picker>\n <input type=\"text\" pInputText class=\"p-inputtext-sm flex-1\"\n [(ngModel)]=\"c.name\" placeholder=\"Class name\"/>\n <button pButton type=\"button\" icon=\"pi pi-trash\"\n class=\"p-button-sm p-button-text p-button-warning\"\n pTooltip=\"Remove class\" tooltipPosition=\"bottom\"\n (click)=\"removePresetClass(i)\"></button>\n </div>\n <button pButton type=\"button\" icon=\"pi pi-plus\" label=\"Add class\"\n class=\"p-button-sm p-button-text align-self-start\" (click)=\"addPresetClass()\"></button>\n </div>\n\n <div class=\"manage-section flex flex-column gap-2\">\n <span class=\"section-title font-medium\">Fallback palette\n <small class=\"text-color-secondary\">— colours for classes not listed</small></span>\n <div class=\"fallback-palette flex align-items-center flex-wrap gap-2\">\n <span *ngFor=\"let col of presetDraft.fallbackPalette; let i = index\"\n class=\"fallback-swatch flex align-items-center\">\n <hex-color-picker [color]=\"col\" (colorChange)=\"presetDraft.fallbackPalette[i] = $event\"></hex-color-picker>\n <i class=\"pi pi-times icon-hover ml-1\" pTooltip=\"Remove\" tooltipPosition=\"bottom\"\n (click)=\"removeFallbackColor(i)\"></i>\n </span>\n <button pButton type=\"button\" icon=\"pi pi-plus\"\n class=\"p-button-sm p-button-text\" pTooltip=\"Add fallback colour\"\n tooltipPosition=\"bottom\" (click)=\"addFallbackColor()\"></button>\n </div>\n </div>\n\n <div class=\"flex align-items-center gap-2\">\n <p-checkbox [(ngModel)]=\"presetDraft.autoPromote\" [binary]=\"true\" inputId=\"autoPromote\"></p-checkbox>\n <label for=\"autoPromote\">Auto-add detected classes to this list as they appear</label>\n </div>\n\n <div class=\"flex align-items-center gap-3\">\n <span class=\"font-medium\">Label matching</span>\n <p-selectButton [options]=\"matchModeOptions\" [(ngModel)]=\"presetDraft.matchMode\"\n optionLabel=\"label\" optionValue=\"value\"></p-selectButton>\n </div>\n </div>\n\n <ng-template pTemplate=\"footer\">\n <div class=\"manage-footer flex align-items-center flex-wrap gap-2 w-full\">\n <span class=\"flex align-items-center flex-wrap gap-1\">\n <p-button label=\"Reset\" icon=\"pi pi-refresh\" [text]=\"true\"\n (onClick)=\"resetPresetsToDefaults()\"></p-button>\n <p-button label=\"Import\" icon=\"pi pi-upload\" [text]=\"true\"\n (onClick)=\"presetFileInput.click()\"></p-button>\n <input #presetFileInput type=\"file\" accept=\".json,application/json\" hidden\n (change)=\"importPresets($event); presetFileInput.value = ''\"/>\n <p-button label=\"Export\" icon=\"pi pi-download\" [text]=\"true\"\n (onClick)=\"exportPresets()\"></p-button>\n </span>\n <span class=\"flex-1\"></span>\n <!-- Apply persists to the server and closes; it replaces the old Apply+Done pair. -->\n <p-button label=\"Apply\" icon=\"pi pi-check\" (onClick)=\"applyManageDialog(true)\"></p-button>\n </div>\n </ng-template>\n</p-dialog>\n\n<p-dialog header=\"Region editor help\" [(visible)]=\"displayHelpDialog\" [style]=\"{width: '50vw'}\"\n [maximizable]=\"true\" [draggable]=\"true\" appendTo=\"body\">\n <p>\n The Region Editor lists every region drawn on the currently displayed image.\n Open it with the\n <img src=\"assets/plotting/region-editor.svg\" width=\"14\" height=\"14\" alt=\"Region Editor\"/>\n button in the diagram toolbar: it opens as a floating dialog you can drag,\n resize, and leave open while you draw on the image.\n Regions are tracked <b>per image</b>: switching to another image hides\n these and shows that image's regions; switching back restores them.\n Edits in the table apply <b>live</b> to the diagram — there is no save or\n cancel.\n </p>\n\n <h3>Creating regions</h3>\n <p>\n Use the diagram toolbar tools to draw new regions:\n <i class=\"pi pi-stop\"></i> rectangle,\n <object data=\"assets/icons/polyline.svg\" width=\"14\" height=\"14\"></object> polyline,\n <i class=\"pi pi-pencil\"></i> freeform path, brush, or\n <object data=\"assets/icons/wand.svg\" width=\"14\" height=\"14\"></object> wand.\n Anything you draw appears immediately in the table, with the class name\n \"<b>Region</b>\" by default.\n </p>\n\n <h3>The table columns</h3>\n <ul>\n <li><b>Class</b> — the region's class. Pick a class from the dropdown (its\n colour follows), or use the <i class=\"pi pi-pencil\"></i> for a free-form name.</li>\n <li><b>Surface</b> — the region's area, in µm²/mm² when the image carries a\n physical pixel size, otherwise in px². Holes (donuts) and multi-part\n regions are accounted for.</li>\n <li>The trash icon at the end of a row deletes that one region.</li>\n <li>Use \"<b>x512</b>\" to round all rectangle widths/heights to the\n nearest multiple of 512.</li>\n </ul>\n <p>Region geometry is edited on the diagram itself (drag vertices, the vertex\n tools, brush/wand, and the right-click region actions), not in this table.</p>\n\n <h3>Selecting rows</h3>\n <ul>\n <li>Click a row to select it. The corresponding region is highlighted in the\n diagram (Plotly shows its edit handles; the OpenSeadragon image view\n highlights it and shows its handles in select mode).</li>\n <li><kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+click to add or remove a row from the\n selection. <kbd>Shift</kbd>+click to extend the selection in a range.</li>\n <li>Selecting a region in the diagram highlights the matching row in the\n table.</li>\n <li>Clicks on the colour picker, the trash icon, or the active class-edit\n input do not change the selection — that's standard PrimeNG behaviour.</li>\n </ul>\n\n <h3>Bulk actions on the selected rows</h3>\n <ul>\n <li><i class=\"pi pi-check-square\"></i> Select every region in the table at once (also a\n right-click action on the image).</li>\n <li><i class=\"pi pi-tags\"></i> Edit the label on every selected row at once.</li>\n <li><i class=\"pi pi-trash\"></i> Delete every selected region — both from\n the table and the diagram.</li>\n <li><i class=\"pi pi-times-circle\"></i> Delete every region on this image.</li>\n </ul>\n\n <h3>Annotation classes & colours (presets)</h3>\n <p>\n Preset a class once — a <b>name</b> and a <b>colour</b> — and every region with\n that class name is drawn in that colour, <b>including regions loaded from a\n GeoJSON later</b>. The preset colour is the source of truth: on load it\n <b>overrides the colour stored in the file</b>, so a given annotation type always\n looks the same across images and sessions.\n </p>\n <p>Set up your classes in the annotation-class manager —\n <i class=\"pi pi-cog\"></i> <b>Manage</b>:</p>\n <ol>\n <li><b>Add class</b>, then type the class <b>name exactly as it appears in your\n data</b> (e.g. <code>Tumor</code>) and pick its <b>colour</b> from the swatch.\n Repeat for each class.</li>\n <li>Optionally: edit the <b>fallback palette</b> (colours given to classes that\n aren't in your list), toggle <b>auto-add</b> (adds unmatched classes found on\n load), and choose <b>exact</b> vs. <b>normalized</b> name matching — normalized\n ignores case and surrounding spaces, so <code>tumor</code> matches\n <code>Tumor</code>.</li>\n <li><b>Apply.</b> Presets are saved <b>per user</b> on the server, so they follow\n you across images and sessions. You can also <b>reset to defaults</b> or\n <b>import / export</b> the set as JSON to share it.</li>\n </ol>\n <p>\n Next time you open or <i class=\"pi pi-upload\"></i> import a GeoJSON whose regions\n carry those class names, each region is shown in its preset colour automatically —\n no re-colouring needed. A class that isn't in your list instead gets a stable\n colour from the fallback palette.\n </p>\n <p>Day to day:</p>\n <ul>\n <li>The <b>class strip</b> above the table lists your presets with their colours.\n Click a class to make it <b>active</b> (new regions inherit it); with rows\n selected, clicking a class re-classifies them.</li>\n <li>The <b>Class</b> column dropdown re-classifies one region to a preset (its\n colour follows), or use the <i class=\"pi pi-pencil\"></i> for a free-form name.</li>\n <li>Recolour a class from its swatch (class strip or Manage) and every region of\n that class updates at once.</li>\n <li>Deleting a class reassigns its regions to the default <b>Region</b> class.</li>\n <li>A colour you set on a <b>single</b> region (<i class=\"pi pi-palette\"></i>\n Selected regions) is kept and is not overridden by its class.</li>\n </ul>\n\n <h3>Region actions (right-click the diagram)</h3>\n <p>Right-click a region — or the current multi-selection — on the diagram for\n the \"Selected region(s)\" actions:</p>\n <ul>\n <li><b>Merge / group</b> — combine 2+ selected regions into one (it may end\n up multi-part if the pieces don't touch).</li>\n <li><b>Ungroup</b> — split a multi-part region back into separate regions.</li>\n <li><b>Inverse</b> — replace the selection with everything outside it (the\n regions become holes in the image rectangle).</li>\n <li><b>Simplify</b> — reduce the vertex count (Douglas–Peucker) by a pixel\n threshold; pick a preset or a custom value.</li>\n <li><b>Convert to Bézier / to polygon</b> and <b>Delete</b>.</li>\n </ul>\n\n <h3>Display options</h3>\n <ul>\n <li><i class=\"pi pi-tag\"></i> Toggle showing class labels on every\n region in the diagram (slower with many regions).</li>\n </ul>\n\n <h3>Import / export</h3>\n <ul>\n <li><i class=\"pi pi-upload\"></i> Import regions from a GeoJSON file.</li>\n <li><i class=\"pi pi-download\"></i> Export the current image's regions to\n a GeoJSON file. (The per-image cache is in-memory only — exporting is\n how you persist regions across sessions.)</li>\n </ul>\n\n <ng-template pTemplate=\"footer\">\n <p-button icon=\"pi pi-check\" (click)=\"displayHelpDialog=false\" label=\"Ok\" styleClass=\"p-button-text\">\n </p-button>\n </ng-template>\n</p-dialog>\n\n","import {\n Component, EventEmitter, Inject, Input, OnDestroy, OnInit, Output,\n} from '@angular/core';\nimport { Subscription } from 'rxjs';\nimport { TreeNode } from 'primeng/api';\nimport * as Plotly from 'plotly.js-dist-min';\n\nimport {\n CHANNEL_HISTOGRAM_API, IChannelHistogramApi, IChannelState, IHistogram, LUT_COLORS,\n} from '../contracts/channel-histogram-api.contract';\n\n/**\n * Channels & Histogram pane: a non-modal, resizable, draggable dialog for\n * brightness/contrast (per-channel display window), gamma, channel\n * visibility/colour, the intensity histogram, and the colormap/reverse/invert\n * controls (moved here from the toolbar). Every edit flows through\n * {@link CHANNEL_HISTOGRAM_API} into the shared store, and both rendering\n * backends recolor the displayed image live. The pane depends only on the\n * contract, never the concrete visualizer.\n */\n@Component({\n // Canonical prefixed selector first; the unprefixed original is kept as an\n // alias for one release (pre-publication back-compat).\n selector: 'channel-histogram',\n templateUrl: './channel-histogram.component.html',\n styleUrls: ['./channel-histogram.component.scss'],\n})\nexport class ChannelHistogramComponent implements OnInit, OnDestroy {\n /** Dialog visibility, two-way bound so the host (toolbar button) can open it. */\n @Input() visible = false;\n @Output() visibleChange = new EventEmitter<boolean>();\n\n readonly histogramDiv = 'channel-histogram-plot';\n readonly lutColors = LUT_COLORS;\n\n channels: IChannelState[] = [];\n selected: IChannelState | null = null;\n invert = false;\n logScale = false;\n /** Bounded retries while the (async) histogram sampling resolves. */\n private histRetries = 0;\n /** The selected channel's current histogram. Native bit depth (with\n * observed/range fields) for >8-bit images, else the 8-bit client histogram.\n * Drives the plot, the native window labels, and the export-button gate. */\n hist: IHistogram | null = null;\n private histSub?: Subscription;\n /** Which window control is being adjusted right now — drives a small\n * non-blocking activity spinner next to that slider, since the image recolor\n * isn't instant on large stacks. Cleared a short moment after movement stops\n * (the recolor isn't directly observable, so this is a trailing heuristic). */\n activeAdjust: 'min' | 'max' | 'gamma' | null = null;\n private adjustTimer?: ReturnType<typeof setTimeout>;\n\n colormapOptions: any;\n selectedColormap: any;\n\n private subs = new Subscription();\n /** Keeps the Plotly histogram sized to the (resizable) dialog body. */\n private resizeObserver?: ResizeObserver;\n\n constructor(@Inject(CHANNEL_HISTOGRAM_API) private api: IChannelHistogramApi) {}\n\n /** Per-channel pseudo-colour only applies when there's more than one channel\n * (RGB / fluorescence). A single grayscale channel uses the colormap instead. */\n get multichannel(): boolean {\n return this.channels.length > 1;\n }\n\n ngOnInit(): void {\n this.colormapOptions = this.api.getColormapOptions();\n this.subs.add(this.api.getColormap().subscribe((cm) => (this.selectedColormap = cm)));\n this.subs.add(this.api.getInvert$().subscribe((i) => (this.invert = !!i)));\n this.subs.add(\n this.api.getChannels$().subscribe((channels) => {\n this.channels = channels ?? [];\n // Keep the selected row (by index) or default to the first channel.\n const keepIdx = this.selected?.index ?? 0;\n this.selected = this.channels.find((c) => c.index === keepIdx) ?? this.channels[0] ?? null;\n if (this.visible) this.updateMarkers();\n }),\n );\n // The histogram is of the source pixels — it changes with the image/slice,\n // not with window edits — so reload it when the image metadata changes.\n this.subs.add(this.api.getImageMeta().subscribe(() => { if (this.visible) this.loadHistogram(); }));\n }\n\n ngOnDestroy(): void {\n this.subs.unsubscribe();\n this.histSub?.unsubscribe();\n clearTimeout(this.adjustTimer);\n this.teardownResize();\n try { Plotly.purge(this.histogramDiv); } catch { /* never rendered */ }\n }\n\n onVisibleChange(v: boolean): void {\n this.visible = v;\n this.visibleChange.emit(v);\n if (!v) this.teardownResize();\n }\n\n /** p-dialog (onShow): the plot div now exists, so draw the histogram and keep\n * it sized to the dialog (which is resizable) via a ResizeObserver. */\n onShow(): void {\n this.histRetries = 0;\n requestAnimationFrame(() => {\n this.loadHistogram();\n const el = document.getElementById(this.histogramDiv);\n if (el && !this.resizeObserver && typeof ResizeObserver !== 'undefined') {\n this.resizeObserver = new ResizeObserver(() => {\n try { (Plotly as any).Plots.resize(el); } catch { /* not rendered */ }\n });\n this.resizeObserver.observe(el);\n }\n });\n }\n\n private teardownResize(): void {\n this.resizeObserver?.disconnect();\n this.resizeObserver = undefined;\n }\n\n selectChannel(ch: IChannelState): void {\n this.selected = ch;\n this.histRetries = 0;\n this.loadHistogram();\n }\n\n // ── per-channel edits (live) ─────────────────────────────────────────\n // PrimeNG slider/inputNumber events carry `number | string | null`, so the\n // handlers accept `any` and coerce. Values arrive in NATIVE units (the slider\n // is labelled natively for 16-bit); we map them back to the store's 8-bit\n // display window via the channel's observed range (identity for 8-bit images,\n // so their behaviour is unchanged).\n onMinChange(value: any): void {\n if (!this.selected) return;\n const min = this.toDisp(value);\n const max = Math.max(min, this.selected.max);\n this.api.setChannelState(this.selected.index, { min, max });\n this.markBusy('min');\n this.updateMarkers();\n }\n onMaxChange(value: any): void {\n if (!this.selected) return;\n const max = this.toDisp(value);\n const min = Math.min(max, this.selected.min);\n this.api.setChannelState(this.selected.index, { min, max });\n this.markBusy('max');\n this.updateMarkers();\n }\n onGammaChange(value: any): void {\n if (!this.selected) return;\n const g = Number(value);\n if (isNaN(g)) return;\n this.api.setChannelState(this.selected.index, { gamma: g });\n this.markBusy('gamma');\n }\n\n /** Flag a control as actively adjusting so its spinner shows; auto-clears a\n * short moment after the last change (kept alive while the user keeps\n * dragging, since each change resets the timer). */\n private markBusy(which: 'min' | 'max' | 'gamma'): void {\n this.activeAdjust = which;\n clearTimeout(this.adjustTimer);\n this.adjustTimer = setTimeout(() => { this.activeAdjust = null; }, 500);\n }\n onVisibleToggle(ch: IChannelState, value: boolean): void {\n this.api.setChannelState(ch.index, { visible: value });\n }\n onColorChange(ch: IChannelState, color: string): void {\n this.api.setChannelState(ch.index, { color });\n // The histogram bars are drawn in the selected channel's colour — redraw\n // when that channel's colour changes.\n if (this.selected && ch.index === this.selected.index) {\n this.selected.color = color;\n this.renderHistogram();\n }\n }\n\n // ── display options ──────────────────────────────────────────────────\n onColormap(node: TreeNode): void {\n if (node && !node.children) this.api.setColormap(node);\n }\n onInvert(value: boolean): void {\n this.invert = value;\n this.api.setInvert(value);\n }\n toggleLog(value: boolean): void {\n this.logScale = value;\n this.renderHistogram();\n }\n\n /** Quick-assign a preset LUT colour to a channel (Fiji palette). */\n setPreset(ch: IChannelState, color: string): void {\n this.onColorChange(ch, color);\n }\n\n /** Export the displayed composite as a publication-ready PNG (8-bit figure). */\n exportComposite(): void {\n this.api.exportComposite();\n }\n\n /** Export the underlying data as a true-16-bit multi-band TIFF (server-side). */\n exportData(): void {\n this.api.exportData();\n }\n\n // ── native bit-depth helpers ─────────────────────────────────────────\n /** True when the current channel histogram is native >8-bit (16-bit etc.):\n * gates the native slider labelling and the 16-bit TIFF export button. */\n get is16bit(): boolean {\n return (this.hist?.bitDepth ?? 8) > 8;\n }\n /** The native value range the 8-bit display window maps onto — the observed\n * pixel extremes for a native histogram, else plain 0..255 (so 8-bit images\n * pass through unchanged). The 8-bit tile is server-stretched across this\n * range, so it's the best client-side native↔display mapping. */\n private obsRange(): { min: number; max: number } {\n const h = this.hist;\n if (h && (h.bitDepth ?? 8) > 8 && (h.observedMax ?? 0) > (h.observedMin ?? 0)) {\n return { min: h.observedMin as number, max: h.observedMax as number };\n }\n return { min: 0, max: 255 };\n }\n /** 8-bit display value (0..255) → native units. */\n private toNative(disp: number): number {\n const o = this.obsRange();\n return Math.round(o.min + (disp / 255) * (o.max - o.min));\n }\n /** Native units → clamped 8-bit display value (0..255). */\n private toDisp(value: any): number {\n const v = Number(value);\n if (v == null || isNaN(v)) return 0;\n const o = this.obsRange();\n const span = o.max - o.min || 1;\n const d = Math.round(255 * (v - o.min) / span);\n return d < 0 ? 0 : d > 255 ? 255 : d;\n }\n /** Selected channel window endpoints in native units (for the sliders). */\n get minNative(): number { return this.selected ? this.toNative(this.selected.min) : 0; }\n get maxNative(): number { return this.selected ? this.toNative(this.selected.max) : 0; }\n /** Native slider bounds + step (256 display steps across the native range). */\n get sliderMin(): number { return this.obsRange().min; }\n get sliderMax(): number { return this.obsRange().max; }\n get sliderStep(): number {\n const r = this.obsRange();\n return this.is16bit ? Math.max(1, Math.round((r.max - r.min) / 255)) : 1;\n }\n\n // ── auto / reset ─────────────────────────────────────────────────────\n auto(): void {\n if (!this.selected) return;\n // Native path: saturate the true distribution, then map the native window\n // back to the 8-bit store. 8-bit path keeps the existing client auto-window.\n if (this.is16bit && this.hist) {\n const [nmin, nmax] = this.autoWindow(this.hist, 0.001);\n if (nmax > nmin) {\n this.api.setChannelState(this.selected.index, { min: this.toDisp(nmin), max: this.toDisp(nmax) });\n this.updateMarkers();\n }\n return;\n }\n this.api.autoContrast([this.selected.index], 0.001);\n }\n reset(): void {\n if (this.selected) this.api.resetContrast([this.selected.index]);\n }\n\n /** Saturation-based auto-window over a (native or 8-bit) histogram: pick\n * [min,max] so ~`saturation` of pixels clip at each end, dropping a dominant\n * first/last bin (background/padding). Returns native bin values. */\n private autoWindow(h: IHistogram, saturation: number): [number, number] {\n const counts = h.counts.slice();\n const n = counts.length;\n if (n === 0) return [this.sliderMin, this.sliderMax];\n if (n > 2 && counts[0] > counts[1]) counts[0] = 0;\n if (n > 2 && counts[n - 1] > counts[n - 2]) counts[n - 1] = 0;\n let total = 0;\n for (const c of counts) total += c;\n if (total <= 0) return [this.sliderMin, this.sliderMax];\n const target = total * Math.max(0, Math.min(0.5, saturation));\n let acc = 0;\n let min = h.bins[0];\n for (let i = 0; i < n; i++) { acc += counts[i]; if (acc > target) { min = h.bins[i]; break; } }\n acc = 0;\n let max = h.bins[n - 1];\n for (let i = n - 1; i >= 0; i--) { acc += counts[i]; if (acc > target) { max = h.bins[i]; break; } }\n return [min, max];\n }\n\n // ── histogram rendering ──────────────────────────────────────────────\n /** Fetch the selected channel's histogram (native for 16-bit, else 8-bit) and\n * (re)draw it. Async — the native path hits the server; the 8-bit path may be\n * null until tile sampling resolves, so we retry a few times. */\n private loadHistogram(): void {\n if (!this.selected) return;\n this.histSub?.unsubscribe();\n this.histSub = this.api.getHistogram$(this.selected.index, 256).subscribe((h) => {\n if (!h) {\n // Not ready (async sampling / file still caching) — retry a few times.\n if (this.visible && this.histRetries < 10) {\n this.histRetries++;\n setTimeout(() => this.loadHistogram(), 400);\n } else {\n this.hist = null;\n this.renderHistogram();\n }\n return;\n }\n this.histRetries = 0;\n this.hist = h;\n this.renderHistogram();\n });\n }\n\n private renderHistogram(): void {\n const el = document.getElementById(this.histogramDiv);\n if (!el || !this.selected) return;\n const h = this.hist;\n if (!h) {\n try { Plotly.purge(el); } catch { /* ignore */ }\n el.setAttribute('data-empty', 'true');\n return;\n }\n el.removeAttribute('data-empty');\n const y = this.logScale ? h.counts.map((c) => (c > 0 ? Math.log10(c) : 0)) : h.counts;\n const trace = {\n x: h.bins,\n y,\n type: 'bar',\n marker: { color: this.selected.color || '#4fa3ff' },\n hoverinfo: 'x+y',\n };\n Plotly.react(el, [trace] as any, this.histogramLayout(), {\n displayModeBar: false, responsive: true,\n } as any);\n }\n\n /** Move only the min/max marker lines (cheap) without recomputing counts. */\n private updateMarkers(): void {\n const el = document.getElementById(this.histogramDiv);\n if (!el || !this.selected || el.getAttribute('data-empty') === 'true') return;\n try {\n Plotly.relayout(el, { shapes: this.markerShapes() } as any);\n } catch { /* not rendered yet */ }\n }\n\n private markerShapes(): any[] {\n const c = this.selected;\n if (!c) return [];\n // Markers sit in the same (native) coordinate space as the histogram axis.\n const line = (x: number, color: string) => ({\n type: 'line', x0: x, x1: x, yref: 'paper', y0: 0, y1: 1,\n line: { color, width: 1, dash: 'dot' },\n });\n return [line(this.toNative(c.min), '#00e0ff'), line(this.toNative(c.max), '#ff7a7a')];\n }\n\n private histogramLayout(): any {\n return {\n margin: { t: 6, r: 8, b: 24, l: 44 },\n bargap: 0,\n xaxis: { range: [this.sliderMin, this.sliderMax], zeroline: false, color: '#ccc', fixedrange: true },\n yaxis: {\n title: this.logScale ? 'log₁₀ count' : 'count',\n zeroline: false, color: '#ccc', fixedrange: true,\n },\n paper_bgcolor: 'rgba(30,30,30,0.95)',\n plot_bgcolor: 'rgba(30,30,30,0.95)',\n font: { color: '#ddd', size: 10 },\n shapes: this.markerShapes(),\n showlegend: false,\n };\n }\n}\n","<p-dialog header=\"Channels & Histogram\"\n [visible]=\"visible\" (visibleChange)=\"onVisibleChange($event)\"\n [modal]=\"false\" [resizable]=\"true\" [draggable]=\"true\"\n [style]=\"{ width: '30rem' }\"\n [breakpoints]=\"{ '960px': '90vw' }\"\n styleClass=\"channel-histogram-dialog\"\n (onShow)=\"onShow()\">\n\n <div class=\"ch-body\">\n\n <!-- Channels -->\n <p-table [value]=\"channels\" selectionMode=\"single\" [(selection)]=\"selected\"\n dataKey=\"index\" (onRowSelect)=\"selectChannel($event.data)\"\n styleClass=\"ch-table p-datatable-sm\">\n <ng-template pTemplate=\"header\">\n <tr>\n <th style=\"width: 2.5rem\"></th>\n <th>Channel</th>\n <th style=\"width: 3.5rem; text-align: center\">Show</th>\n </tr>\n </ng-template>\n <ng-template pTemplate=\"body\" let-ch>\n <tr [pSelectableRow]=\"ch\">\n <td>\n <hex-color-picker *ngIf=\"multichannel\" [color]=\"ch.color\"\n (colorChange)=\"onColorChange(ch, $event)\"></hex-color-picker>\n </td>\n <td>{{ ch.name }}</td>\n <td style=\"text-align: center\">\n <p-checkbox [binary]=\"true\" [ngModel]=\"ch.visible\"\n (onChange)=\"onVisibleToggle(ch, $event.checked)\"></p-checkbox>\n </td>\n </tr>\n </ng-template>\n </p-table>\n\n <!-- Pseudo-color presets for the selected channel (multichannel only;\n grayscale uses the colormap below). -->\n <div class=\"ch-presets\" *ngIf=\"multichannel && selected\">\n <span class=\"ch-presets-lbl\">{{ selected.name }} LUT</span>\n <button *ngFor=\"let p of lutColors\" type=\"button\" class=\"ch-preset\"\n [style.background]=\"p.color\" [pTooltip]=\"p.name\" tooltipPosition=\"top\"\n (click)=\"setPreset(selected, p.color)\"></button>\n </div>\n\n <!-- Histogram -->\n <div class=\"ch-hist-head\">\n <span>Histogram{{ selected ? ' — ' + selected.name : '' }}</span>\n <p-checkbox [binary]=\"true\" [(ngModel)]=\"logScale\"\n (onChange)=\"toggleLog($event.checked)\" label=\"Log\"></p-checkbox>\n </div>\n <div [id]=\"histogramDiv\" class=\"ch-hist-plot\"></div>\n\n <!-- Display window / gamma -->\n <div class=\"ch-sliders\" *ngIf=\"selected\">\n <!-- Window endpoints are shown/edited in NATIVE units (0..255 for 8-bit,\n the channel's observed native range for 16-bit). One-way bound to the\n native getters; the handlers map back to the 8-bit display window. -->\n <div class=\"ch-row\">\n <span class=\"ch-lbl\">Min</span>\n <p-slider [ngModel]=\"minNative\" [min]=\"sliderMin\" [max]=\"sliderMax\" [step]=\"sliderStep\"\n (onChange)=\"onMinChange($event.value)\" styleClass=\"ch-slider\"></p-slider>\n <p-inputNumber [ngModel]=\"minNative\" [min]=\"sliderMin\" [max]=\"sliderMax\" [showButtons]=\"false\"\n (onInput)=\"onMinChange($event.value)\" styleClass=\"ch-num\"></p-inputNumber>\n <span class=\"ch-busy\"><i *ngIf=\"activeAdjust === 'min'\" class=\"pi pi-spin pi-spinner\"\n aria-label=\"updating\"></i></span>\n </div>\n <div class=\"ch-row\">\n <span class=\"ch-lbl\">Max</span>\n <p-slider [ngModel]=\"maxNative\" [min]=\"sliderMin\" [max]=\"sliderMax\" [step]=\"sliderStep\"\n (onChange)=\"onMaxChange($event.value)\" styleClass=\"ch-slider\"></p-slider>\n <p-inputNumber [ngModel]=\"maxNative\" [min]=\"sliderMin\" [max]=\"sliderMax\" [showButtons]=\"false\"\n (onInput)=\"onMaxChange($event.value)\" styleClass=\"ch-num\"></p-inputNumber>\n <span class=\"ch-busy\"><i *ngIf=\"activeAdjust === 'max'\" class=\"pi pi-spin pi-spinner\"\n aria-label=\"updating\"></i></span>\n </div>\n <div class=\"ch-row\">\n <span class=\"ch-lbl\">Gamma</span>\n <p-slider [(ngModel)]=\"selected.gamma\" [min]=\"0.1\" [max]=\"5\" [step]=\"0.01\"\n (onChange)=\"onGammaChange($event.value)\" styleClass=\"ch-slider\"></p-slider>\n <p-inputNumber [(ngModel)]=\"selected.gamma\" [min]=\"0.1\" [max]=\"5\" [minFractionDigits]=\"2\"\n [maxFractionDigits]=\"2\" [showButtons]=\"false\"\n (onInput)=\"onGammaChange($event.value)\" styleClass=\"ch-num\"></p-inputNumber>\n <span class=\"ch-busy\"><i *ngIf=\"activeAdjust === 'gamma'\" class=\"pi pi-spin pi-spinner\"\n aria-label=\"updating\"></i></span>\n </div>\n <div class=\"ch-btns\">\n <p-button label=\"Auto\" size=\"small\" (onClick)=\"auto()\"></p-button>\n <p-button label=\"Reset\" size=\"small\" [text]=\"true\" (onClick)=\"reset()\"></p-button>\n </div>\n </div>\n\n <!-- LUT / colormap controls. The colormap maps single-channel intensity →\n colour, so it only applies to grayscale; RGB/multichannel use the\n per-channel pseudo-colour presets above. -->\n <div class=\"ch-display\">\n <p-treeSelect *ngIf=\"!multichannel\"\n [options]=\"colormapOptions\" [(ngModel)]=\"selectedColormap\"\n [selectionMode]=\"'single'\" placeholder=\"Colormap\" [scrollHeight]=\"'300px'\"\n pTooltip=\"Color Lookup Tables\" tooltipPosition=\"bottom\"\n (onNodeSelect)=\"onColormap($event.node)\">\n <ng-template let-node pTemplate=\"default\">\n <div class=\"flex align-items-center gap-2\">\n <img *ngIf=\"!node.children\" [src]=\"node.data?.src\" class=\"colormap\" />\n <div>{{ node.label }}</div>\n </div>\n </ng-template>\n </p-treeSelect>\n <p-checkbox [binary]=\"true\" [(ngModel)]=\"invert\"\n (onChange)=\"onInvert($event.checked)\" label=\"Invert\"></p-checkbox>\n </div>\n\n <!-- Exports: an 8-bit publication composite (always), plus a true-16-bit\n data-preserving TIFF when the image carries >8-bit pixels. -->\n <div class=\"ch-export\">\n <p-button label=\"Export composite (PNG)\" icon=\"pi pi-download\" size=\"small\"\n (onClick)=\"exportComposite()\"></p-button>\n <p-button *ngIf=\"is16bit\" label=\"Export 16-bit TIFF\" icon=\"pi pi-download\" size=\"small\"\n [outlined]=\"true\" pTooltip=\"Data-preserving multi-band TIFF (visible channels, native bit depth)\"\n tooltipPosition=\"top\" (onClick)=\"exportData()\"></p-button>\n </div>\n\n </div>\n</p-dialog>\n","import { ChangeDetectorRef, Component, AfterViewInit, EventEmitter, HostListener, Inject, Input, NgZone, OnChanges, OnDestroy, OnInit, Optional, Output, SimpleChanges, ViewChild } from '@angular/core';\n\nimport { BehaviorSubject, Subject, Subscription } from 'rxjs';\nimport { takeUntil } from 'rxjs/operators';\n\nimport { MenuItem, MessageService, TreeNode } from 'primeng/api';\nimport { ContextMenu } from 'primeng/contextmenu';\nimport { IImageInfo } from './contracts/image.contract';\nimport { ImageStatePort, IMAGE_STATE_PORT } from './contracts/ports/image-state.port';\nimport { Polygon, Rectangle, MultiPolygon, Region } from './models/region';\nimport { RegionOpsService } from './region-ops.service';\nimport { VisualizerStore } from './store/visualizer-store.service';\nimport { RenderOrchestrator, SliceScrubber } from './render-orchestrator';\nimport {\n PlotType,\n PlotTypeDescriptor,\n isNapari3d,\n NAPARI_DEFAULT_DECIMATE,\n} from './contracts/plot-type';\nimport { ViewerFeature } from './contracts/capabilities.contract';\nimport { IntensityProfile, IVisualizer, VISUALIZER } from './contracts/visualizer.contract';\nimport { SAM_MODELS, getDefaultSamModelId, isSamModelReady } from './toolbar/segmentation/sam-model-registry';\nimport { SamToolService } from './toolbar/segmentation/sam-tool.service';\nimport { SamPointToolService } from './toolbar/segmentation/sam-point-tool.service';\nimport { CellSegmentToolService } from './toolbar/segmentation/cell-segment-tool.service';\nimport { RegionToolMode } from './contracts/region-overlay.contract';\nimport { ToolbarToolVisibility, ALL_TOOLBAR_TOOLS } from './contracts/toolbar-config';\nimport { VIZ_CONFIG, VizConfig } from './contracts/viz-config';\n\n/** Per-instance plot-div id source. The mount element's id must be unique so two\n * live viewers (e.g. the main diagram + a modal preview) don't collide on the\n * same DOM id — `getElementById` would otherwise return whichever came first.\n * Styling hangs off the `.viz-plot` class instead of the id. */\nlet plotInstanceSeq = 0;\n\n@Component({\n // Canonical prefixed selector first; the unprefixed original is kept as an\n // alias for one release (pre-publication back-compat).\n selector: 'visualizer',\n templateUrl: './visualizer.component.html',\n styleUrls: ['./visualizer.component.scss'],\n})\nexport class VisualizerComponent implements OnInit, OnChanges, AfterViewInit, OnDestroy {\n /** Per-instance toast key. MessageService is a global singleton, so two live\n * `<visualizer>` instances (main viewer + pipeline-dialog preview) sharing\n * one key would each render the same message — a duplicate toast. A unique\n * key per instance scopes the toast to the component that raised it. */\n private static nextToastId = 0;\n\n @Output()\n isStackEvent = new EventEmitter(false);\n @Output()\n isGrayscaleEvent = new EventEmitter(false);\n\n /** Which toolbar groups to show. A partial override merges over the full set,\n * so `{ specialTools: false }` hides only that group. Defaults to everything. */\n @Input()\n set toolbarTools(v: ToolbarToolVisibility | undefined) {\n this._toolbarTools = { ...ALL_TOOLBAR_TOOLS, ...(v ?? {}) };\n }\n\n get toolbarTools(): Required<ToolbarToolVisibility> {\n return this._toolbarTools;\n }\n private _toolbarTools: Required<ToolbarToolVisibility> = ALL_TOOLBAR_TOOLS;\n\n /** Expose test-only plot modes in the selector (e.g. the napari `Image`\n * mode, otherwise hidden). The host app sets this from a `?test=1` URL\n * toggle. Off by default, so production users never see them. */\n @Input()\n testMode = false;\n\n /** Image-smoothing state for the toolbar's Smoothen toggle (OSD only).\n * Defaults to `false` so OSD shows raw pixels (nearest-neighbour). */\n imageSmoothingEnabled = false;\n loadingMessage = 'Loading image...';\n zoom = false;\n fileName: string | undefined;\n private loadedFileName: string | undefined;\n imageInfo: IImageInfo | undefined;\n\n private unsub = new Subject<void>();\n private previewSubscription = new Subscription();\n\n public stackLoading = false;\n public imgLoading = false;\n public loadingPercentage = 0;\n // Non-null (0..100) while jit-service is copying the source file into the\n // local cache PVC on first click. When set, the loading overlay swaps the\n // spinner for a determinate progress bar with a \"Caching image\" message.\n public cacheProgress: number | null = null;\n // True between the small-tier render landing and the large-tier render\n // landing in the multi-tier rendering path. The template uses this to\n // overlay a translucent spinner on top of the blurry small-tier image so\n // the user doesn't mistake it for the final preview.\n public sharpening = false;\n /** A jit-service cache copy is actively in progress (determinate 0..99). Drives the cache\n * progress bar independently of `imgLoading` so the bar can't be dropped — or masked by the\n * \"Sharpening preview...\" overlay — mid-download if the loading flag flips early. */\n get isCaching(): boolean {\n return this.cacheProgress !== null && this.cacheProgress < 100;\n }\n private running = false;\n public zIndex = 0;\n public maxIndex = 0;\n\n @ViewChild('cm') contextMenu!: ContextMenu;\n contextMenuItems: MenuItem[] = [];\n\n activeDragMode: string | null = null;\n\n /** Whether a region action is available to undo (jit-ui#85). Mirrors the\n * shared RegionStore's history depth; drives the toolbar Undo button. */\n canUndoRegion = false;\n /** Whether an undone region action is available to redo (jit-ui#85). */\n canRedoRegion = false;\n\n /** Custom-threshold Simplify dialog (jit-ui#85). */\n displaySimplifyDialog = false;\n simplifyThreshold = 3;\n /** Current region selection (array indices) — mirrored from the store so the\n * context-menu region actions can read it synchronously (jit-ui#85). */\n private selectedIndices: number[] = [];\n\n /** Wand sensitivity — higher = stricter (smaller selection). Matches QuPath default. */\n wandSensitivity = 2.0;\n /** Brush diameter in image-pixel coordinates (drives the painted disc size). */\n brushSize = 40;\n /** SAM model picker options + current selection (jit-ui#90 P1). Only models\n * with a hosted ONNX pair (configured via setSamModelUrls at app init) are\n * offered, so the picker can't select a model that can't run. */\n samModels = SAM_MODELS.filter(isSamModelReady).map((m) => ({ id: m.id, label: m.label }));\n samModelId = getDefaultSamModelId();\n /** SAM download/segment toast state (bound by the `sam` p-toast template). */\n samStatus = '';\n samProgress = 0; // 0..100, encoder download\n samDownloading = false;\n samBusy = false; // any SAM work in flight (drives the indeterminate spinner)\n /** Whether the shared `sam` toast is currently shown (avoids stacking it on\n * every point click, which re-runs inference). */\n private samToastShown = false;\n\n readonly samToastKey = `sam-${VisualizerComponent.nextToastId++}`;\n /** Subscriptions to the point tool's live feeds (status/busy/download). */\n private samPointSub = new Subscription();\n /** Vertex eraser radius in image-pixel coordinates. */\n vertexEraserRadius = 20;\n\n colormapsOptions!: any;\n reversescale = false;\n selectedColormap!: any;\n /** Channels & Histogram dialog visibility (opened from the toolbar). */\n showChannelHistogram = false;\n /** Region Editor dialog visibility (opened from the toolbar). */\n showRegionEditor = false;\n /** Region Editor dialog width. On open it is set to the configured host\n * element's current width, or — when no selector is configured / the element\n * isn't found — to a quarter of the page (see openRegionEditor). */\n regionEditorWidth = '25vw';\n stackOptions = [\n { name: 'Single image', val: 'false' },\n { name: 'Stack', val: 'true' },\n ];\n selectedStackOption: { name: string; val: string } | undefined = this.stackOptions[0];\n readonly plotDivName = `viz-plot-${plotInstanceSeq++}`;\n plotType = PlotType.IMAGE;\n isHeatmap = true;\n activeSurface3dMode = 'turntable';\n /** Whether the napari 3D coordinate-axes / scale gizmo is shown (volume/isosurface). */\n axesVisible = true;\n wireframeActive = false;\n /** napari 3D decimate factor (1 = Full … 8 = ⅛; default ½); changing it re-plots. */\n resolutionScale = NAPARI_DEFAULT_DECIMATE;\n\n /** Plot types the active backend advertises (3D gated by capability). */\n plotTypeOptions: PlotTypeDescriptor[] = [];\n selectedPlotType: PlotType = PlotType.IMAGE;\n\n /** Floating intensity-profile inset (LINE mode). */\n readonly intensityInsetDiv = 'intensity-inset-plot';\n profilePanelPos = { x: 20, y: 70 };\n private profilePanelDragging = false;\n private profilePanelStart = { mx: 0, my: 0, x: 0, y: 0 };\n\n /** Toolbar docking: docked across the top by default; dragging its handle\n * detaches it into a floating, movable window (frees the top row for the\n * visualization). */\n toolbarFloating = false;\n toolbarPos = { x: 8, y: 8 };\n private toolbarDragging = false;\n private toolbarStart = { mx: 0, my: 0, x: 0, y: 0 };\n private latestProfiles: IntensityProfile[] = [];\n /** Drives the intensity inset panel's visibility — true whenever any\n * intensity-profile line exists (independent of the current plot type). */\n hasProfiles = false;\n private intensityProfileSub?: Subscription;\n private viewportChangeSub?: Subscription;\n private profileDragMoveListener?: (e: MouseEvent) => void;\n private profileDragUpListener?: () => void;\n private profileResizeListener?: () => void;\n\n /** LINE plot type shows the image + draggable line ROI + intensity inset. */\n get isProfileMode(): boolean {\n return this.selectedPlotType === PlotType.LINE;\n }\n\n /** True for the Image plot type, which renders as a natively pan/zoom-able\n * raster — so the backend-agnostic zoom/pan toolbar tools are hidden. The\n * component drives this off the plot type, not the active backend. */\n get isImageView(): boolean {\n return this.selectedPlotType === PlotType.IMAGE;\n }\n\n /** Isosurface band as a 0–255 slider position, mapped onto the volume's real\n * intensity range by the renderer. Defaults to the full range. */\n isoRange: number[] = [0, 255];\n\n plotWidthSubscription?: Subscription;\n imageLoadingSubscription?: Subscription;\n imgLoadingMessageSubscription?: Subscription;\n isZoomSubscription?: Subscription;\n filenameSubscription?: Subscription;\n autoscaleSubscription?: Subscription;\n\n private plotContextMenuListener?: (e: MouseEvent) => void;\n private keydownListener?: (e: KeyboardEvent) => void;\n private wheelListener?: (e: WheelEvent) => void;\n\n /** Debounced z-slice scrubbing (see SliceScrubber — refactoring plan Step 7). */\n private readonly scrubber = new SliceScrubber((z) => {\n this.plotService.setZIndex(z);\n // In a per-slice z-stack session the store swaps the live region set to this\n // slice (preserving edits made on the previous one); outside stack mode this\n // just records the slice, leaving single-plane regions untouched (jit-ui#93).\n this.plotService.setDisplaySlice(z);\n });\n\n constructor(\n @Inject(IMAGE_STATE_PORT) private state: ImageStatePort,\n @Inject(VISUALIZER) public plotService: IVisualizer,\n public messageService: MessageService,\n private ngZone: NgZone,\n private cdr: ChangeDetectorRef,\n private session: VisualizerStore,\n private samTool: SamToolService,\n private cellSegmentTool: CellSegmentToolService,\n private samPointTool: SamPointToolService,\n private regionOps: RegionOpsService,\n @Optional() @Inject(VIZ_CONFIG) private vizConfig?: VizConfig,\n ) {\n this.colormapsOptions = plotService.getColormapOptions();\n this.computePlotTypeOptions();\n }\n\n /**\n * Plot types offered in the selector for the current image:\n * - Outside **test mode**, only the curated default set (descriptors with a\n * `productionLabel`) is offered, shown under suffix-free names — Image,\n * Heatmap, Contour and the napari Surface / Volume / Isosurface. Test mode\n * exposes every backend's type under its full (backend-suffixed) label.\n * - 3D types hidden when the backend can't render a 3D scene.\n * - stack-only types (volume, isosurface) hidden unless the file is a stack —\n * a volume needs multiple z-slices.\n * - scalar-intensity types (contour, surface, isosurface) hidden for RGB\n * images — they map a single intensity per pixel. Image and Heatmap render\n * any image.\n */\n private computePlotTypeOptions() {\n const caps = this.plotService.capabilities;\n const isStack = !!this.imageInfo?.isStack;\n const isGrayscale = !!this.imageInfo?.isGrayscale;\n this.plotTypeOptions = this.plotService.getPlotTypeDescriptors()\n .filter((d) => {\n // Outside test mode, only the curated set (those with a productionLabel)\n // is offered; test mode exposes every backend's type.\n if (!this.testMode && !d.productionLabel) return false;\n if (d.dimensions === '3d' && !caps.has(ViewerFeature.Surface3D)) return false;\n if (d.requiresStack && !isStack) return false;\n if (d.requiresGrayscale && !isGrayscale) return false;\n return true;\n })\n // Default selector shows the suffix-free productionLabel; test mode keeps\n // the full backend-suffixed label so same-named modes stay distinguishable.\n .map((d) => (this.testMode ? d : { ...d, label: d.productionLabel! }));\n }\n\n ngOnChanges(changes: SimpleChanges): void {\n // The constructor computes the options with testMode still at its default;\n // recompute once the host binds it (and on any later change) so the selector\n // reflects test mode immediately, without waiting for an image to (re)load.\n if (changes['testMode']) {\n this.computePlotTypeOptions();\n // If test mode is turned off while a test-only type (e.g. NAPARI_IMAGE) is\n // active, that type is no longer offered — fall back to Image.\n this.reconcileSelectedPlotType();\n }\n }\n\n /** If the active plot type is no longer in the offered options (e.g. test mode\n * turned off while a test-only type was active, or a scalar type carried onto\n * an RGB image), fall back to the default 2D Image view. */\n private reconcileSelectedPlotType(): void {\n if (!this.plotTypeOptions.some((d) => d.type === this.selectedPlotType)) {\n this.selectedPlotType = PlotType.IMAGE;\n this.plotType = PlotType.IMAGE;\n this.isHeatmap = true;\n this.plotService.setPlotType(PlotType.IMAGE);\n }\n }\n\n ngOnInit(): void {\n this.state.setDiagram(this);\n this.selectedColormap =\n this.colormapsOptions[0].children.find((c: any) => c.label === 'Greys Inv') ??\n this.colormapsOptions[0].children[0];\n this.stackOptions = [\n { name: 'Single image', val: 'false' },\n { name: 'Stack', val: 'true' },\n ];\n this.selectedStackOption = this.stackOptions[0];\n this.autoscaleSubscription = this.plotService.getAutoscaleEvent().subscribe(() => {\n // reset the image mode to single image\n this.selectedStackOption = { name: 'Single image', val: 'false' };\n this.activeDragMode = null;\n this.session.setActiveTool(null);\n });\n this.imageLoadingSubscription = this.state.isImageLoading$().subscribe((isImageLoading) => {\n this.imgLoading = isImageLoading;\n });\n // Undo availability (jit-ui#85): the shared RegionStore emits whenever its\n // history depth changes; greys out the toolbar Undo button accordingly.\n this.plotService\n .getCanUndo$()\n .pipe(takeUntil(this.unsub))\n .subscribe((canUndo) => {\n this.canUndoRegion = canUndo;\n this.cdr.detectChanges();\n });\n this.plotService\n .getCanRedo$()\n .pipe(takeUntil(this.unsub))\n .subscribe((canRedo) => {\n this.canRedoRegion = canRedo;\n this.cdr.detectChanges();\n });\n // Mirror the region selection so the right-click action group (jit-ui#85)\n // can read it synchronously when the menu is built.\n this.plotService\n .getSelectedShapeIndices$()\n .pipe(takeUntil(this.unsub))\n .subscribe((indices) => {\n this.selectedIndices = indices || [];\n });\n // Interactive point-prompt segmentation runs inside the renderer on each\n // click; surface its live status + download progress in the shared `sam`\n // toast so the user sees it working (the first click pulls the encoder).\n this.samPointSub.add(\n this.samPointTool.progress$.subscribe((f) => {\n this.samDownloading = f >= 0 && f < 1;\n if (f >= 0) this.samProgress = Math.min(100, Math.round(f * 100));\n this.cdr.detectChanges();\n }),\n );\n this.samPointSub.add(\n this.samPointTool.status$.subscribe((m) => {\n this.samStatus = m;\n this.cdr.detectChanges();\n }),\n );\n this.samPointSub.add(\n this.samPointTool.busy$.subscribe((busy) => {\n this.samBusy = busy;\n if (busy) this.showSamToast('SAM point segmentation');\n this.cdr.detectChanges();\n }),\n );\n this.plotService.getStackLoadingProgress().subscribe((loadingProgress) => {\n this.loadingPercentage = loadingProgress;\n });\n this.plotService.isStackLoading().subscribe((stackLoading) => {\n this.stackLoading = stackLoading;\n });\n this.plotWidthSubscription = this.state.getPanelWidth$().subscribe(() => {\n this.plotService.relayout();\n // The intensity inset is a separate Plotly chart in a floating panel; reflow\n // it to its current size when the canvas resizes, else it keeps the stale\n // size and blanks out. Defer a tick so the panel layout has settled.\n if (this.hasProfiles) {\n setTimeout(() => this.renderIntensityInset(), 0);\n }\n });\n this.imgLoadingMessageSubscription = this.state.getImageLoadingMessage$().subscribe((message) => {\n this.loadingMessage = message;\n });\n this.state\n .getCacheProgress$()\n .pipe(takeUntil(this.unsub))\n .subscribe((progress) => {\n this.cacheProgress = progress;\n });\n this.isZoomSubscription = this.state.isZoom$().subscribe((zoom) => {\n this.zoom = zoom;\n });\n this.filenameSubscription = this.state.getFilename$().subscribe((filename) => {\n if (filename) {\n this.fileName = filename;\n }\n });\n this.plotService.getColormap().subscribe((colormap) => {\n this.selectedColormap = colormap;\n });\n this.plotService.getReverseScale().subscribe((reversescale) => {\n this.reversescale = reversescale;\n });\n this.intensityProfileSub = this.plotService.getIntensityProfile$().subscribe((profiles) => {\n this.latestProfiles = profiles;\n this.hasProfiles = profiles.length > 0;\n // The panel div is behind *ngIf=\"hasProfiles\". detectChanges() materializes\n // it synchronously (the subscription may fire outside Angular's zone — e.g.\n // from an OSD drag — so CD wouldn't run on its own). Then render on the next\n // animation frame, AFTER the browser lays the panel out: a synchronous draw\n // hits a zero-size container on first create and Plotly keeps that size, so\n // the inset stays blank and live updates redraw into the same zero box.\n this.cdr.detectChanges();\n requestAnimationFrame(() => this.renderIntensityInset());\n });\n // When the OSD view settles at a new zoom/pan, re-sample the intensity lines\n // from a crop of the visible region so the inset reflects the zoom-level\n // resolution (Plotly's own high-def zoom updates the sampling cache inline).\n this.viewportChangeSub = this.plotService.getViewportChange$().subscribe((roi) => {\n if (this.hasProfiles && this.isImageView) {\n this.plotService.refreshIntensitySamplingForRoi(roi.x, roi.y, roi.width, roi.height, this.zIndex);\n }\n });\n this.previewSubscription = this.state.getImageInfo$().subscribe({\n next: (imgInfo) => {\n if (imgInfo) {\n this.imageInfo = imgInfo;\n // Stack-only plot types (isosurface, scatter3d) depend on whether this\n // file is a stack — recompute the selector options.\n this.computePlotTypeOptions();\n // If the active plot type isn't valid for this image (e.g. a scalar\n // type like Contour carried over to an RGB image), fall back to Image.\n this.reconcileSelectedPlotType();\n // reset stack options selection\n this.selectedStackOption = imgInfo.showStack ? this.stackOptions[1] : this.stackOptions[0];\n\n this.isGrayscaleEvent.emit(this.imageInfo.isGrayscale);\n this.isStackEvent.emit(this.imageInfo.isStack);\n // Reset to the default 2D Image view when a different image is\n // selected while a 3D type is active.\n if (!this.isHeatmap && imgInfo.fileName !== this.loadedFileName) {\n this.isHeatmap = true;\n this.plotType = PlotType.IMAGE;\n this.selectedPlotType = PlotType.IMAGE;\n this.plotService.setPlotType(this.plotType);\n this.activeSurface3dMode = 'turntable';\n }\n this.loadedFileName = imgInfo.fileName;\n this.plotService.setImageMeta(this.imageInfo.imageMeta);\n const urls = imgInfo.urls;\n if (!this.running) {\n // image size — measure the plot div directly so the toolbar height is excluded\n const plotDiv: HTMLElement | null = document.getElementById(this.plotDivName);\n const screenHeight = plotDiv?.offsetHeight || 500;\n if (urls) {\n this.plotService.reset();\n this.stackLoading = imgInfo.isStack && imgInfo.showStack;\n // set max index of stack — computed before updateZIndex so a\n // fresh stack (shorter or longer than whatever was previously\n // loaded) clamps against ITS bounds, not the stale ones.\n // One URL per slice (0-indexed), so the last reachable index is\n // length-1 — earlier `length-2` dropped the final slice.\n this.maxIndex = urls.length > 1 ? urls.length - 1 : 0;\n // One-shot hint: jump straight to a specific slice (e.g. the\n // file the user actually clicked within a numbered series).\n // Consumed immediately so redelivering the same ImageInfo later\n // (a plot-type switch, reloadAndPlot) doesn't reset the user's\n // current scrub position back to it.\n if (imgInfo.initialZIndex !== undefined) {\n this.zIndex = imgInfo.initialZIndex;\n imgInfo.initialZIndex = undefined;\n }\n // make sure the zindex is within bounds\n this.updateZIndex(urls);\n this.running = true;\n // Multi-tier rendering (small blurry tier first, then sharpen in\n // place) — sequencing lives in RenderOrchestrator; this component\n // supplies the phase render and owns the UI flags via callbacks.\n // 3D plot types render single-pass: the in-place large pass doesn't\n // rebuild a 3D gl-mesh isosurface, so the sharpen step blanked it.\n const hasSmallTier =\n this.isHeatmap &&\n (imgInfo.smallUrls?.length ?? 0) === urls.length &&\n (imgInfo.smallUrls?.length ?? 0) > 0;\n const smallImgInfo = hasSmallTier ? { ...imgInfo, urls: imgInfo.smallUrls as string[] } : null;\n\n // Enter per-slice stack mode with the given slice→regions map and\n // seed the \"previous shapes\" from the now-live slice. enterStackMode\n // makes zIndex's slice live and resets undo (jit-ui#93).\n const enterStack = (\n slices: Map<number, Region[]>,\n layout: 'combined' | 'per-slice-file',\n ) => {\n this.plotService.enterStackMode(slices, this.zIndex, layout);\n const shapes = this.plotService\n .getRegions()\n .map((region) => region.getShape(this.plotService.getShowShapeLabel()));\n this.plotService.setPreviousShapes(shapes);\n };\n\n const applyRoi = () => {\n // Folder stack: a stack of self-contained per-slice files\n // (tiled === false; see loadSeriesAsStack). Each slice-file may\n // carry its own sibling \"<stem>.geojson\" (roiJsonStrs[z]), but a\n // fresh folder with none yet leaves roiJsonStrs undefined — key\n // off `tiled === false`, NOT roiJsonStrs, so an unannotated\n // folder stack still enters the per-slice-file layout (and saves\n // back one geojson per slice-file) rather than falling through to\n // the single-file combined path (jit-ui#93).\n if (imgInfo.isStack && imgInfo.tiled === false) {\n const perSlice = imgInfo.roiJsonStrs;\n const sliceCount = imgInfo.urls?.length ?? perSlice?.length ?? 0;\n const slices = new Map<number, Region[]>();\n for (let z = 0; z < sliceCount; z++) {\n const json = perSlice?.[z] ?? null;\n slices.set(z, json ? this.plotService.importRegions(json) : []);\n }\n enterStack(slices, 'per-slice-file');\n return;\n }\n // Single-file z-stack: one sibling geojson holding every slice's\n // regions indexed by QuPath's geometry.plane.z. Enter per-slice\n // mode (saving back one combined z-indexed geojson) when the\n // geojson actually carries slice indices, or when there's nothing\n // yet to author against. A legacy geojson whose regions are all on\n // the default plane stays global (shown on every slice) so\n // existing single-plane annotations aren't confined to slice 0.\n const roiJson = imgInfo.roiJsonStr;\n if (imgInfo.isStack) {\n const regions = roiJson ? this.plotService.importRegions(roiJson) : [];\n const hasSliceInfo = regions.some((r) => (r.z ?? 0) !== 0);\n if (!roiJson || hasSliceInfo) {\n const slices = new Map<number, Region[]>();\n for (const r of regions) {\n const z = r.z ?? 0;\n const bucket = slices.get(z);\n if (bucket) bucket.push(r);\n else slices.set(z, [r]);\n }\n enterStack(slices, 'combined');\n return;\n }\n }\n // Single-plane image (or a legacy global z-stack geojson): one\n // region set for the whole image.\n if (roiJson) {\n const regions = this.plotService.importRegions(roiJson);\n this.plotService.setRegions(regions);\n const shapes = regions.map((region) =>\n region.getShape(this.plotService.getShowShapeLabel()),\n );\n this.plotService.setPreviousShapes(shapes);\n }\n // Loading an image's saved ROIs is not a user edit — start the\n // undo history fresh so the first undo can't wipe them (jit-ui#85).\n this.plotService.resetUndoHistory();\n };\n let overlayReleased = false;\n const releaseOverlay = () => {\n if (overlayReleased) return;\n overlayReleased = true;\n if (imgInfo.isStack && imgInfo.showStack) this.stackLoading = false;\n this.state.setImageLoading(false);\n };\n\n new RenderOrchestrator({\n // inPlace=true updates the existing render instead of rebuilding\n // it, so the canvas doesn't blank during the small→large swap.\n renderPhase: (phaseInfo, inPlace) =>\n this.plotService.load(phaseInfo, this.zIndex).then((loadedImage) => {\n // Guard against a newer click reaching us mid-render.\n if (phaseInfo.fileName !== loadedImage.filename) return null;\n return this.plotService.plot(\n this.plotDivName,\n loadedImage,\n phaseInfo,\n screenHeight,\n this.plotType,\n inPlace,\n );\n }),\n smallShown: () => {\n // If the file is still being cached/prepared server-side, keep the full\n // cache-progress overlay up instead of dropping to the translucent \"Sharpening\n // preview...\" spinner over a blank canvas (a large uncached image renders its\n // small preview before its tiles exist). finished() releases the overlay once\n // the real render lands.\n if (this.isCaching) return;\n // Small tier on screen — drop the full overlay but keep a translucent spinner so\n // the blurry render isn't mistaken for the final image.\n releaseOverlay();\n this.sharpening = true;\n },\n sharpenSettled: () => {\n this.sharpening = false;\n },\n finished: (_viaSmall, logTag) => {\n // Idempotent — releases now if smallShown deferred it (caching) or was skipped.\n releaseOverlay();\n this.running = false;\n applyRoi();\n console.log(logTag);\n },\n sharpenFailed: (err: any) => {\n // The small tier stays on screen as the fallback — tell the\n // user the sharper version isn't coming.\n const msg = err?.error?.message || err?.message || err?.statusText || String(err);\n this.messageService.add({\n key: 'center-toast',\n severity: 'warn',\n summary: 'Preview not sharpened',\n detail: `The full-resolution preview did not load (${msg}). The low-resolution preview is still shown. Try clicking the image again.`,\n });\n this.running = false;\n applyRoi();\n },\n }).render(imgInfo, smallImgInfo);\n }\n }\n }\n },\n error: (err) => {\n const msg = err?.error?.message || err?.message || err?.statusText || String(err);\n console.error('Error occured when getting image info', err);\n this.messageService.add({\n key: 'center-toast',\n sticky: true,\n severity: 'error',\n summary: 'An error occured',\n detail: `The following error occured while getting image info: ${msg}.\n Please try to open the image again through the file navigator.`,\n });\n this.stackLoading = false;\n this.state.setImageLoading(false);\n this.running = false;\n this.plotService.reset();\n },\n });\n }\n\n ngAfterViewInit() {\n this.plotContextMenuListener = (event: MouseEvent) => {\n const plotEl = document.getElementById(this.plotDivName);\n if (!plotEl?.contains(event.target as Node)) return;\n event.preventDefault();\n event.stopImmediatePropagation();\n this.ngZone.run(() => {\n this.contextMenuItems = this.buildContextMenuItems();\n this.cdr.detectChanges();\n this.contextMenu.show(event);\n });\n };\n window.addEventListener('contextmenu', this.plotContextMenuListener, true);\n\n this.keydownListener = (event: KeyboardEvent) => {\n const target = event.target as HTMLElement;\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) return;\n // SAM point mode: Enter commits the object, Esc clears the prompt.\n if (this.activeDragMode === 'samPoint' && (event.key === 'Enter' || event.key === 'Escape')) {\n this.ngZone.run(() => {\n if (event.key === 'Enter') this.plotService.commitSamPoints();\n else this.plotService.clearSamPoints();\n this.hideSamToast(); // prompt resolved → dismiss the status toast\n });\n return;\n }\n // Region history (jit-ui#85): Ctrl/Cmd+Z undoes; Ctrl/Cmd+Shift+Z or\n // Ctrl/Cmd+Y redoes.\n if (event.ctrlKey || event.metaKey) {\n const k = event.key.toLowerCase();\n if (k === 'z' && !event.shiftKey) {\n event.preventDefault();\n this.ngZone.run(() => this.undoRegion());\n return;\n }\n if ((k === 'z' && event.shiftKey) || k === 'y') {\n event.preventDefault();\n this.ngZone.run(() => this.redoRegion());\n return;\n }\n }\n if (event.key === 'Delete' || event.key === 'Backspace' || event.key === 'd' || event.key === 'D') {\n this.ngZone.run(() => this.deleteRegion());\n } else if (event.key === '+' || event.key === '=') {\n this.ngZone.run(() => this.zoomIn());\n } else if (event.key === '-' || event.key === '_') {\n this.ngZone.run(() => this.zoomOut());\n } else if (event.key === 'p') {\n this.ngZone.run(() => this.toggleDragMode('pan'));\n } else if (event.key === 'b') {\n this.ngZone.run(() => this.toggleDragMode('zoomToBox'));\n } else if (event.key === 'r') {\n this.ngZone.run(() => this.toggleDragMode('drawrect'));\n } else if (event.key === 'f') {\n this.ngZone.run(() => this.toggleDragMode('drawclosedpath'));\n } else if (event.key === 'w') {\n this.ngZone.run(() => this.toggleDragMode('wand'));\n } else if (event.key === 'e') {\n this.ngZone.run(() => this.toggleDragMode('eraseVertex'));\n } else if (event.key === 's') {\n this.ngZone.run(() => this.toggleDragMode('select'));\n } else if (event.key === 'l') {\n this.ngZone.run(() => this.toggleDragMode('drawopenpath'));\n }\n };\n window.addEventListener('keydown', this.keydownListener);\n\n this.wheelListener = (event: WheelEvent) => {\n const plotEl = document.getElementById(this.plotDivName);\n if (!plotEl?.contains(event.target as Node)) return;\n // The Image view handles scroll-zoom natively (it respects the scroll\n // delta). Intercepting here would fire a fixed zoom step per wheel\n // event — far too sensitive — so let the renderer own it.\n if (this.isImageView) return;\n // 3D plot types (surface, scatter3d, isosurface) render in a Plotly scene\n // that orbits/zooms natively on scroll. The 2D step-zoom doesn't apply and\n // would throw (no xaxis on a scene), so let Plotly handle the wheel.\n if (!this.isHeatmap) return;\n event.preventDefault();\n event.stopImmediatePropagation();\n if (event.deltaY < 0) {\n this.ngZone.run(() => this.zoomIn());\n } else if (event.deltaY > 0) {\n this.ngZone.run(() => this.zoomOut());\n }\n };\n window.addEventListener('wheel', this.wheelListener, { capture: true, passive: false });\n\n // Drag handling for the floating intensity-profile panel.\n this.profileDragMoveListener = (e: MouseEvent) => {\n if (this.profilePanelDragging) {\n this.ngZone.run(() => {\n this.profilePanelPos = {\n x: this.profilePanelStart.x + (e.clientX - this.profilePanelStart.mx),\n y: this.profilePanelStart.y + (e.clientY - this.profilePanelStart.my),\n };\n });\n } else if (this.toolbarDragging) {\n this.ngZone.run(() => {\n this.toolbarPos = {\n x: this.toolbarStart.x + (e.clientX - this.toolbarStart.mx),\n y: this.toolbarStart.y + (e.clientY - this.toolbarStart.my),\n };\n });\n }\n };\n this.profileDragUpListener = () => {\n this.profilePanelDragging = false;\n this.toolbarDragging = false;\n };\n window.addEventListener('mousemove', this.profileDragMoveListener);\n window.addEventListener('mouseup', this.profileDragUpListener);\n\n // On any window resize, reflow the intensity inset to its (fixed) panel size\n // on the next frame, once layout has settled. Without this the inset can be\n // left at a stale/zero size by a mid-reflow resize and stop showing.\n this.profileResizeListener = () => {\n if (!this.hasProfiles) return;\n requestAnimationFrame(() => this.renderIntensityInset());\n };\n window.addEventListener('resize', this.profileResizeListener);\n }\n\n onProfilePanelDragStart(e: MouseEvent) {\n this.profilePanelDragging = true;\n this.profilePanelStart = {\n mx: e.clientX,\n my: e.clientY,\n x: this.profilePanelPos.x,\n y: this.profilePanelPos.y,\n };\n e.preventDefault();\n }\n\n /** Grab the toolbar handle: detach it into a floating window (if still docked)\n * and start dragging. */\n onToolbarDragStart(e: MouseEvent) {\n if (!this.toolbarFloating) {\n this.toolbarFloating = true;\n this.toolbarPos = { x: 8, y: 8 };\n }\n this.toolbarDragging = true;\n this.toolbarStart = {\n mx: e.clientX,\n my: e.clientY,\n x: this.toolbarPos.x,\n y: this.toolbarPos.y,\n };\n e.preventDefault();\n }\n\n /** Snap the floating toolbar back to its docked position across the top. */\n dockToolbar() {\n this.toolbarFloating = false;\n }\n\n /** Render the intensity inset chart from the latest profile data. The actual\n * charting is owned by the visualizer service — the component just decides\n * when (profile mode + a fresh profile). */\n private renderIntensityInset(): void {\n if (!this.hasProfiles) return;\n this.plotService.renderIntensityInset(this.intensityInsetDiv, this.latestProfiles);\n }\n\n /** Toolbar \"Intensity\" group: add another line ROI (next bright colour). */\n async addProfileLine(): Promise<void> {\n // Park the floating inset near the plot's top-right when the first line is\n // added (it's position:fixed, so use viewport coords from the plot rect).\n if (!this.hasProfiles) {\n const rect = document.getElementById(this.plotDivName)?.getBoundingClientRect();\n this.profilePanelPos = rect\n ? { x: Math.max(10, rect.right - 300), y: rect.top + 10 }\n : { x: 20, y: 70 };\n }\n // Image (OSD) mode: Plotly never rendered, so it has no pixel cache / extent.\n // Load the current slice's frames for sampling + line placement first.\n if (this.isImageView && this.imageInfo) {\n await this.plotService.ensureIntensitySampling(this.imageInfo, this.zIndex);\n }\n const region = this.plotService.getIntensityControls()?.addProfileLine();\n // Auto-select the new line on the active backend (Plotly handles / OSD\n // highlight) so it's ready to move or delete immediately.\n if (region) {\n this.plotService.selectRegion(region);\n // OSD only draws a selected region's handles in an edit mode, so a line in\n // 'none' mode looks unselected. Switch to 'select' so the new line shows\n // its endpoint handles and can be dragged/deleted right away.\n if (this.isImageView && this.activeDragMode !== 'select') {\n this.toggleDragMode('select');\n }\n }\n }\n\n ngOnDestroy() {\n this.scrubber.cancel();\n this.samPointSub.unsubscribe();\n if (this.plotContextMenuListener) {\n window.removeEventListener('contextmenu', this.plotContextMenuListener, true);\n }\n if (this.keydownListener) {\n window.removeEventListener('keydown', this.keydownListener);\n }\n if (this.wheelListener) {\n window.removeEventListener('wheel', this.wheelListener, true);\n }\n if (this.profileDragMoveListener) {\n window.removeEventListener('mousemove', this.profileDragMoveListener);\n }\n if (this.profileDragUpListener) {\n window.removeEventListener('mouseup', this.profileDragUpListener);\n }\n if (this.profileResizeListener) {\n window.removeEventListener('resize', this.profileResizeListener);\n }\n if (this.intensityProfileSub) {\n this.intensityProfileSub.unsubscribe();\n }\n if (this.viewportChangeSub) {\n this.viewportChangeSub.unsubscribe();\n }\n this.unsub.next();\n this.unsub.complete();\n if (this.previewSubscription) {\n this.previewSubscription.unsubscribe();\n }\n if (this.plotWidthSubscription) {\n this.plotWidthSubscription.unsubscribe();\n }\n if (this.imageLoadingSubscription) {\n this.imageLoadingSubscription.unsubscribe();\n }\n if (this.imgLoadingMessageSubscription) {\n this.imgLoadingMessageSubscription.unsubscribe();\n }\n if (this.isZoomSubscription) {\n this.isZoomSubscription.unsubscribe();\n }\n if (this.autoscaleSubscription) {\n this.autoscaleSubscription.unsubscribe();\n }\n if (this.filenameSubscription) {\n this.filenameSubscription.unsubscribe();\n }\n this.plotService.unsubscribe();\n }\n\n public hasRegions(): boolean {\n // Use the contract's framework-neutral region accessor, not the raw\n // Plotly-shaped getShapes() — the component only needs to know whether any\n // region exists, and must not depend on a backend's wire format.\n return this.plotService.getRegions().length > 0;\n }\n\n /**\n * This method is called in mainFacade.configRequest() - DO NOT DELETE\n */\n public getRegionPolygons(): Polygon[] {\n return this.plotService.getRegionPolygons();\n }\n\n /**\n * Select the color scale type: called by the color scale select button\n * @param event\n */\n toggleReverseScale() {\n this.reversescale = !this.reversescale;\n this.plotService.setReverseScale(this.reversescale);\n }\n\n /**\n * Select a color map: called by the color map dropdown button\n * @param colormapNode\n */\n selectColormap(colormapNode: TreeNode) {\n if (!colormapNode.children) {\n this.plotService.setColormap(colormapNode);\n }\n }\n\n /** Open the Channels & Histogram dialog (toolbar button). */\n openChannelHistogram() {\n this.showChannelHistogram = true;\n }\n\n /** Open the Region Editor dialog (toolbar button). The editor stays linked to\n * this plotting instance through the root RegionStore singleton, so it works\n * the same as the former right-panel Regions tab. */\n openRegionEditor() {\n // Size the dialog to match the host's configured element (e.g. the app's\n // right panel) at open time. Measured once — it intentionally does not\n // track later browser/split resizes. Falls back to a quarter of the page\n // when no selector is configured or the element isn't present.\n const selector = this.vizConfig?.regionEditorWidthSelector;\n const width = selector\n ? document.querySelector<HTMLElement>(selector)?.getBoundingClientRect().width\n : undefined;\n this.regionEditorWidth = width && width > 0 ? `${Math.round(width)}px` : '25vw';\n this.showRegionEditor = true;\n }\n\n /**\n * Called by the stack/single image dropdown button\n * @param showstack\n */\n selectStackOption(selectedStackOption: any) {\n const showstack = selectedStackOption.val === 'true';\n this.selectedStackOption = selectedStackOption;\n console.log('selected stack option' + JSON.stringify(this.selectedStackOption));\n this.stackLoading = showstack;\n this.state.setImageLoading(!showstack);\n // Stack mode is always a 2D heatmap — reset surface mode if active\n if (!this.isHeatmap) {\n this.isHeatmap = true;\n this.plotType = PlotType.HEATMAP;\n this.selectedPlotType = PlotType.HEATMAP;\n this.plotService.setPlotType(this.plotType);\n }\n this.plotService.setShowStack(showstack);\n }\n\n updateZIndex(urls?: string[]) {\n if (this.zIndex > this.maxIndex) {\n this.zIndex = this.maxIndex;\n }\n if (this.zIndex < 0) {\n this.zIndex = 0;\n }\n if (urls) {\n if (this.zIndex > urls?.length) {\n this.zIndex = 0;\n this.maxIndex = urls.length - 1;\n }\n }\n this.plotService.setZIndex(this.zIndex);\n }\n\n /**\n * Live z-slice scrub for the Image view: the renderer swaps the displayed\n * slice in place (no re-mount), so dragging the slider steps through the\n * stack the same way the heatmap frame slider does.\n */\n onZSlide(z: number | undefined) {\n if (z === undefined) return;\n this.zIndex = z;\n this.scrubber.commit(z);\n // Keep the intensity inset in sync with the displayed slice (Image/OSD mode,\n // where the profile sampler is fed from the loaded preview frames).\n if (this.hasProfiles && this.isImageView && this.imageInfo) {\n this.plotService.ensureIntensitySampling(this.imageInfo, z);\n }\n }\n\n /**\n * Live (debounced) scrub while dragging the Image-view z-slider: update the\n * slice as the user drags, but coalesce rapid changes so we don't fire a\n * slice swap on every pixel. The final value also lands via onZSlide (onSlideEnd).\n */\n onZScrub(z: number | undefined) {\n if (z === undefined) return;\n this.zIndex = z;\n this.scrubber.scrub(z);\n }\n\n /**\n * Keyboard stack navigation: ←/→ step the z-slice in the Image view, the same\n * way the slider does. Only active for a loaded stack in Image view, and\n * ignored while a form field is focused so typing isn't hijacked. Up/Down are\n * left to OpenSeadragon (panning).\n */\n @HostListener('window:keydown', ['$event'])\n onKeydown(e: KeyboardEvent): void {\n if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;\n if (!this.imageInfo?.isStack || !this.isImageView) return;\n const t = e.target as HTMLElement | null;\n if (t && (/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName) || t.isContentEditable)) return;\n // The slice slider handles arrows natively when focused (also a +1 step) —\n // skip here so we don't double-step it.\n if (t && (t.getAttribute('role') === 'slider' || t.closest('.p-slider'))) return;\n e.preventDefault();\n this.stepSlice(e.key === 'ArrowRight' ? 1 : -1);\n }\n\n /** Move the displayed slice by `delta`, clamped to the stack bounds. */\n stepSlice(delta: number): void {\n const next = Math.min(this.maxIndex, Math.max(0, this.zIndex + delta));\n if (next === this.zIndex) return;\n this.onZSlide(next);\n }\n\n reloadAndPlot() {\n this.state.setImageLoading(true);\n // Re-drive the render pipeline from the current image info (the source of\n // truth, with real urls/fileName). Don't use plotService.reloadAndPlot():\n // that rebuilds the info from the renderer's internal state, which can be\n // stale (e.g. after switching plot type Image -> Heatmap) and re-emit\n // empty/old urls, failing to hand the div over to the new renderer.\n if (this.imageInfo) {\n this.state.setImageInfo(this.imageInfo);\n } else {\n this.plotService.reloadAndPlot();\n }\n }\n cancelLoading() {\n // Stop any in-flight frame streaming (napari-js volume/surface preload) so the fetch loops\n // actually abort — clearing the flag alone only routed to Plotly and left napari fetching.\n this.plotService.cancelLoading?.();\n this.stackLoading = false;\n this.imgLoading = false;\n this.state.setImageLoading(false);\n this.zIndex = 0;\n this.plotService.setZIndex(this.zIndex);\n this.running = false;\n this.plotService.setStackLoading(false);\n }\n\n downloadImage() {\n this.plotService.downloadImage();\n }\n\n autoscaleImage() {\n this.plotService.autoscale();\n }\n\n /** Toolbar pixel/smooth toggle: flip smoothing and apply to the active backend. */\n onToggleImageSmoothing(): void {\n this.imageSmoothingEnabled = !this.imageSmoothingEnabled;\n this.plotService.setImageSmoothingEnabled(this.imageSmoothingEnabled);\n }\n\n resetAxes() {\n this.plotService.resetAxes();\n }\n\n toggleDragMode(mode: string) {\n // Toggle off if the same mode is re-selected.\n this.activeDragMode = this.activeDragMode === mode ? null : mode;\n const active = this.activeDragMode;\n // Record the armed tool in the shared session store.\n this.session.setActiveTool(active);\n\n // Region draw/select run through the renderer's region overlay.\n this.plotService\n .getRegionOverlay()\n ?.setMode(this.isRegionMode(active) ? (active as RegionToolMode) : 'none');\n\n // Viewport drag modes (pan/box-zoom). Region modes own the drag mode via\n // the overlay, so don't also set one here.\n if (!this.isRegionMode(active)) {\n const viewportDrag = active === 'pan' || active === 'zoom';\n this.plotService.setDragMode(viewportDrag ? active : false);\n }\n\n // On-canvas tool overlays.\n this.plotService.setZoomToBoxMode(active === 'zoomToBox');\n this.plotService.setWandMode(active === 'wand', { sensitivity: this.wandSensitivity });\n this.plotService.setBrushMode(active === 'brush', { size: this.brushSize });\n this.plotService.setSamPointMode(active === 'samPoint');\n // Leaving point mode dismisses any lingering status toast.\n if (active !== 'samPoint') this.hideSamToast();\n this.plotService.setVertexEraserMode(active === 'eraseVertex');\n if (active === 'eraseVertex') {\n this.plotService.setVertexEraserRadius(this.vertexEraserRadius);\n }\n }\n\n /** Region draw/select/edit modes routed through the region overlay. The\n * The vertex tools (drawpolygon/addpoint/deletepoint/move) are\n * handled by the OpenSeadragon overlay; Plotly's overlay maps them to no-op. */\n private isRegionMode(mode: string | null): boolean {\n return (\n mode === 'drawrect' ||\n mode === 'drawclosedpath' ||\n mode === 'drawopenpath' ||\n mode === 'select' ||\n mode === 'drawpolygon' ||\n mode === 'addpoint' ||\n mode === 'deletepoint' ||\n mode === 'move'\n );\n }\n\n /** Live-update the isosurface as the range slider moves. The control is only\n * available when the active backend renders isosurfaces (ISOSURFACE mode). */\n onIsoRangeChange(values: number[] | undefined) {\n if (!values || values.length < 2) return;\n this.isoRange = values;\n this.plotService.getIsosurfaceControls()?.setIsoRange(values[0], values[1]);\n }\n\n onWandSensitivityChange(value: number | undefined) {\n if (value === undefined || !Number.isFinite(value)) return;\n this.wandSensitivity = value;\n this.plotService.setWandOptions({ sensitivity: value });\n }\n\n onBrushSizeChange(value: number | undefined) {\n if (value === undefined || !Number.isFinite(value)) return;\n this.brushSize = value;\n this.plotService.setBrushOptions({ size: value });\n }\n\n onVertexEraserRadiusChange(value: number | undefined) {\n if (value === undefined || !Number.isFinite(value)) return;\n this.vertexEraserRadius = value;\n this.plotService.setVertexEraserRadius(value);\n }\n\n zoomIn() {\n this.plotService.zoomIn();\n }\n\n zoomOut() {\n this.plotService.zoomOut();\n }\n\n deleteRegion() {\n this.plotService.deleteActiveShape();\n }\n\n /** Undo the most recent region action (jit-ui#85). Up to 10 steps back. */\n undoRegion() {\n this.plotService.undo();\n }\n\n /** Redo the most recently undone region action (jit-ui#85). */\n redoRegion() {\n this.plotService.redo();\n }\n\n // ── Region set-operations on the current selection (jit-ui#85) ──────────\n\n /** The currently-selected regions (live store instances). */\n private get selectedRegions(): Region[] {\n const all = this.plotService.getRegions();\n return this.selectedIndices\n .map((i) => all[i])\n .filter((r): r is Region => !!r);\n }\n\n /** Regions eligible for set-ops: closed areas (rect / closed polygon /\n * multi-polygon), excluding intensity-profile lines. */\n private opEligible(regions: Region[]): Region[] {\n return regions.filter((r) => r.kind !== 'profile' && (\n r.bounds instanceof Rectangle ||\n r.bounds instanceof MultiPolygon ||\n (r.bounds instanceof Polygon && r.bounds.closed !== false)\n ));\n }\n\n /** Image pixel dimensions for the raster ops; falls back to the selection's\n * extent when the image size isn't known (keeps clamping sane). */\n private opImageDims(regions: Region[]): { w: number; h: number } {\n let [w, h] = this.imageInfo?.trueImageSize ?? [0, 0];\n if (!(w > 0) || !(h > 0)) {\n let maxX = 0, maxY = 0;\n const scan = (xs: number[], ys: number[]) => {\n for (const x of xs) maxX = Math.max(maxX, x);\n for (const y of ys) maxY = Math.max(maxY, y);\n };\n for (const r of regions) {\n const b = r.bounds;\n if (b instanceof Rectangle) scan([b.x + b.width], [b.y + b.height]);\n else if (b instanceof Polygon) scan(b.xpoints, b.ypoints);\n else if (b instanceof MultiPolygon) for (const p of b.polygons) scan(p.xpoints, p.ypoints);\n }\n w = Math.max(w, Math.ceil(maxX) + 2);\n h = Math.max(h, Math.ceil(maxY) + 2);\n }\n return { w, h };\n }\n\n /** True when ≥2 eligible regions are selected (Merge available). */\n get canMergeRegions(): boolean { return this.opEligible(this.selectedRegions).length >= 2; }\n /** True when any selected region is multi-part (Ungroup available). */\n get canUngroupRegions(): boolean { return this.selectedRegions.some((r) => this.regionOps.canUngroup(r)); }\n /** True when ≥1 eligible region is selected (Inverse / Simplify available). */\n get hasEligibleSelection(): boolean { return this.opEligible(this.selectedRegions).length >= 1; }\n\n /** Select every region on the image (excludes intensity-profile lines). */\n selectAllRegions(): void {\n const all = this.plotService.getRegions();\n const indices: number[] = [];\n all.forEach((r, i) => { if (r.kind !== 'profile') indices.push(i); });\n this.plotService.setSelectedShapeIndices(indices);\n }\n\n /** Merge the selected regions into a single (possibly multi-part) region. */\n mergeRegions(): void {\n const sel = this.opEligible(this.selectedRegions);\n if (sel.length < 2) return;\n const { w, h } = this.opImageDims(sel);\n const merged = this.regionOps.merge(sel, w, h);\n if (merged) this.replaceRegions(sel, [merged]);\n }\n\n /** Split each selected multi-part region into one region per part. */\n ungroupRegions(): void {\n const sel = this.selectedRegions.filter((r) => this.regionOps.canUngroup(r));\n if (sel.length === 0) return;\n const results: Region[] = [];\n for (const r of sel) results.push(...this.regionOps.ungroup(r));\n this.replaceRegions(sel, results);\n }\n\n /** Replace the selection with its inverse inside the image rectangle. */\n inverseRegions(): void {\n const sel = this.opEligible(this.selectedRegions);\n if (sel.length === 0) return;\n const { w, h } = this.opImageDims(sel);\n const inv = this.regionOps.inverse(sel, w, h);\n if (!inv) {\n this.messageService.add({\n severity: 'warn', summary: 'Inverse',\n detail: 'Nothing to invert — select one or more closed regions first.',\n });\n return;\n }\n this.replaceRegions(sel, [inv]);\n }\n\n /** Douglas–Peucker simplify each selected region by `thresholdPx`. */\n simplifyRegions(thresholdPx: number): void {\n const sel = this.opEligible(this.selectedRegions);\n if (sel.length === 0) return;\n this.replaceRegions(sel, sel.map((r) => this.regionOps.simplify(r, thresholdPx)));\n this.displaySimplifyDialog = false;\n }\n\n /** Open the custom-threshold simplify dialog. */\n openSimplifyDialog(): void { this.displaySimplifyDialog = true; }\n\n /**\n * Commit a set-op: drop the `remove` regions, append `add`, and select the\n * results. Goes through setRegions so it's undo-tracked and re-rendered;\n * profile lines and unselected regions are preserved.\n */\n private replaceRegions(remove: Region[], add: Region[]): void {\n if (add.length === 0) return;\n const removeSet = new Set(remove);\n const kept = this.plotService.getRegions().filter((r) => !removeSet.has(r));\n this.plotService.setRegions([...kept, ...add]); // mints ids on `add`, records undo\n const stored = this.plotService.getRegions();\n const sel = add.map((r) => stored.indexOf(r)).filter((i) => i >= 0);\n this.plotService.setSelectedShapeIndices(sel);\n }\n\n /** Box-prompted SAM segmentation of the drawn rectangles (jit-ui#90). A sticky\n * `sam` toast shows live status + a download progress bar (first run pulls the\n * encoder, ~170 MB); it stays open until the run finishes (bar hits 100%). */\n async segmentRegions() {\n await this.runSegmentWithToast('SAM', this.samTool, () => this.plotService.segmentRectangles());\n }\n\n /** Auto-segment cells inside each drawn rectangle with cellpose-SAM, client-side\n * (jit-ui#90). Each box is cropped (browser slide-crop) then run through the\n * cellpose-js model; the same sticky `sam` toast + progress bar is reused. */\n async segmentCellpose() {\n await this.runSegmentWithToast('Cellpose', this.cellSegmentTool, () =>\n this.plotService.segmentRectanglesCellpose(),\n );\n }\n\n /** Shared driver for the box-prompt segment tools: wires the tool's status +\n * download progress into the sticky `sam` toast, runs `op`, and reports the\n * region count. Keeps the toast open until the run settles (bar hits 100%). */\n private async runSegmentWithToast(\n label: string,\n tool: { status$: BehaviorSubject<string>; progress$: BehaviorSubject<number> },\n op: () => Promise<number>,\n ) {\n this.samStatus = 'Starting…';\n this.samProgress = 0;\n this.samDownloading = false;\n this.samBusy = true;\n const psub = tool.progress$.subscribe((f) => {\n this.samDownloading = f >= 0 && f < 1;\n if (f >= 0) this.samProgress = Math.min(100, Math.round(f * 100));\n this.cdr.detectChanges();\n });\n const ssub = tool.status$.subscribe((m) => {\n if (m) {\n this.samStatus = m;\n this.cdr.detectChanges();\n }\n });\n this.showSamToast(label);\n try {\n const n = await op();\n this.messageService.add({\n severity: n > 0 ? 'success' : 'warn',\n summary: label,\n detail: tool.status$.value || (n > 0 ? `Added ${n} region(s).` : 'No regions added.'),\n });\n } catch (e) {\n this.messageService.add({ severity: 'error', summary: `${label} failed`, detail: String(e) });\n } finally {\n psub.unsubscribe();\n ssub.unsubscribe();\n this.hideSamToast();\n }\n }\n\n /** Show the shared sticky `sam` toast once (idempotent — re-adding would stack\n * a new toast on every point click). */\n private showSamToast(summary: string): void {\n if (this.samToastShown) return;\n this.samToastShown = true;\n this.messageService.add({ key: this.samToastKey, sticky: true, severity: 'info', summary });\n }\n\n /** Dismiss the shared `sam` toast and reset its progress/spinner state. */\n private hideSamToast(): void {\n this.samToastShown = false;\n this.samBusy = false;\n this.samDownloading = false;\n this.samProgress = 0;\n this.messageService.clear(this.samToastKey);\n this.cdr.detectChanges();\n }\n\n /** Pick the SAM model the segment tools use (jit-ui#90 P1). */\n onSamModelChange(id: string) {\n this.samModelId = id;\n this.plotService.setSamModel(id);\n }\n\n /** Convert the selected region to a smooth bezier curve. */\n toBezierRegion() {\n this.plotService.getRegionOverlay()?.setSelectedBezier(true);\n }\n\n /** Convert the selected region back to a straight-edged polygon. */\n toPolygonRegion() {\n this.plotService.getRegionOverlay()?.setSelectedBezier(false);\n }\n\n /**\n * Immediate region actions on the current selection (jit-ui#85): merge,\n * ungroup, inverse, simplify, the Bézier conversions, and delete — the\n * one-shot geometry transforms, grouped apart from the tool/mode toggles and\n * shown only when something is selected. Each item is gated on what the\n * selection supports.\n */\n private buildRegionActionItems(): MenuItem[] {\n const all = this.plotService.getRegions();\n const selectable = all.filter((r) => r.kind !== 'profile');\n if (selectable.length === 0) return [];\n const items: MenuItem[] = [];\n\n // Select all — available whenever the image has regions, regardless of the\n // current selection.\n items.push({\n label: 'Select all regions', icon: 'pi pi-check-square',\n command: () => this.selectAllRegions(),\n });\n\n const selAll = this.selectedRegions;\n if (selAll.length === 0) return items;\n const eligible = this.opEligible(selAll);\n\n if (eligible.length >= 2) {\n items.push({ label: 'Merge / group', icon: 'pi pi-link', command: () => this.mergeRegions() });\n }\n if (selAll.some((r) => this.regionOps.canUngroup(r))) {\n items.push({ label: 'Ungroup', icon: 'pi pi-sitemap', command: () => this.ungroupRegions() });\n }\n if (eligible.length >= 1) {\n items.push(\n { label: 'Inverse', icon: 'pi pi-clone', command: () => this.inverseRegions() },\n {\n label: 'Simplify', icon: 'pi pi-chart-line',\n items: [\n { label: 'Light (1 px)', command: () => this.simplifyRegions(1) },\n { label: 'Medium (3 px)', command: () => this.simplifyRegions(3) },\n { label: 'Strong (8 px)', command: () => this.simplifyRegions(8) },\n { separator: true },\n { label: 'Custom…', command: () => this.openSimplifyDialog() },\n ],\n },\n );\n }\n // Bézier conversions are vertex-level edits — Image (OpenSeadragon) view\n // only — gated on the selection's current form.\n if (this.selectedPlotType === PlotType.IMAGE) {\n const hasStraight = selAll.some((r) =>\n (r.bounds instanceof Polygon && !r.bounds.bezier) || r.bounds instanceof Rectangle);\n const hasBezier = selAll.some((r) => r.bounds instanceof Polygon && r.bounds.bezier);\n if (hasStraight) {\n items.push({ label: 'Convert to Bézier', icon: 'to-bezier-icon', command: () => this.toBezierRegion() });\n }\n if (hasBezier) {\n items.push({ label: 'Convert to polygon', icon: 'to-polygon-icon', command: () => this.toPolygonRegion() });\n }\n }\n items.push({ label: 'Delete region', icon: 'pi pi-trash', command: () => this.deleteRegion() });\n return items;\n }\n\n private buildContextMenuItems(): MenuItem[] {\n const active = this.activeDragMode;\n const activeClass = 'context-menu-active';\n const items: MenuItem[] = [];\n // Selected-region actions lead the menu (separated from the tool toggles).\n if (this.isHeatmap) {\n const actions = this.buildRegionActionItems();\n if (actions.length) items.push(...actions, { separator: true });\n }\n if (this.isHeatmap) {\n items.push(\n { label: 'Autoscale', icon: 'pi pi-window-maximize', command: () => this.autoscaleImage() },\n { separator: true },\n );\n // 'Zoom selection' is Plotly's rubber-band zoom; it doesn't apply to the\n // OpenSeadragon-backed Image view (use 'Zoom to box' there instead).\n if (!this.isImageView) {\n items.push({\n label: 'Zoom selection',\n icon: 'pi pi-search',\n styleClass: active === 'zoom' ? activeClass : '',\n command: () => this.toggleDragMode('zoom'),\n });\n }\n items.push({\n label: 'Zoom to box',\n icon: 'zoom-box-off-icon',\n styleClass: active === 'zoomToBox' ? activeClass : '',\n command: () => this.toggleDragMode('zoomToBox'),\n });\n }\n if (this.isHeatmap) {\n items.push({\n label: 'Pan',\n icon: 'pi pi-arrows-alt',\n styleClass: active === 'pan' ? activeClass : '',\n command: () => this.toggleDragMode('pan'),\n });\n } else {\n const s3d = this.activeSurface3dMode;\n items.push(\n {\n label: 'Zoom',\n icon: 'pi pi-search',\n styleClass: s3d === 'zoom' ? activeClass : '',\n command: () => this.toggleSurface3dMode('zoom'),\n },\n {\n label: 'Pan',\n icon: 'pi pi-arrows-alt',\n styleClass: s3d === 'pan' ? activeClass : '',\n command: () => this.toggleSurface3dMode('pan'),\n },\n {\n label: 'Orbital rotation',\n icon: 'pi pi-globe',\n styleClass: s3d === 'orbit' ? activeClass : '',\n command: () => this.toggleSurface3dMode('orbit'),\n },\n {\n label: 'Turntable rotation',\n icon: 'pi pi-sync',\n styleClass: s3d === 'turntable' ? activeClass : '',\n command: () => this.toggleSurface3dMode('turntable'),\n },\n { separator: true },\n { label: 'Reset camera', icon: 'pi pi-home', command: () => this.resetSurfaceCamera() },\n );\n }\n if (this.isHeatmap) {\n items.push(\n { label: 'Zoom in', icon: 'pi pi-search-plus', command: () => this.zoomIn() },\n { label: 'Zoom out', icon: 'pi pi-search-minus', command: () => this.zoomOut() },\n { separator: true },\n {\n label: 'Select',\n icon: 'pi pi-arrow-up-right',\n styleClass: active === 'select' ? activeClass : '',\n command: () => this.toggleDragMode('select'),\n },\n {\n label: 'Freeform',\n icon: 'pi pi-pencil',\n styleClass: active === 'drawclosedpath' ? activeClass : '',\n command: () => this.toggleDragMode('drawclosedpath'),\n },\n {\n label: 'Brush',\n icon: 'brush-icon',\n styleClass: active === 'brush' ? activeClass : '',\n command: () => this.toggleDragMode('brush'),\n },\n {\n label: 'Polyline',\n icon: 'polyline-icon',\n styleClass: active === 'drawopenpath' ? activeClass : '',\n command: () => this.toggleDragMode('drawopenpath'),\n },\n {\n label: 'Rectangle',\n icon: 'pi pi-stop',\n styleClass: active === 'drawrect' ? activeClass : '',\n command: () => this.toggleDragMode('drawrect'),\n },\n {\n label: 'Wand',\n icon: 'wand-icon',\n styleClass: active === 'wand' ? activeClass : '',\n command: () => this.toggleDragMode('wand'),\n },\n {\n label: 'Vertex eraser',\n icon: 'pi pi-eraser',\n styleClass: active === 'eraseVertex' ? activeClass : '',\n command: () => this.toggleDragMode('eraseVertex'),\n },\n );\n // Vertex editing runs on the OpenSeadragon overlay, which\n // backs the Image plot type. Hidden for other 2D types (Plotly), where\n // these modes are no-ops.\n if (this.selectedPlotType === PlotType.IMAGE) {\n items.push(\n {\n label: 'Polygon (click vertices)',\n icon: 'polygon-vertices-icon',\n styleClass: active === 'drawpolygon' ? activeClass : '',\n command: () => this.toggleDragMode('drawpolygon'),\n },\n {\n label: 'Add vertex',\n icon: 'vertex-add-icon',\n styleClass: active === 'addpoint' ? activeClass : '',\n command: () => this.toggleDragMode('addpoint'),\n },\n {\n label: 'Delete vertex',\n icon: 'vertex-delete-icon',\n styleClass: active === 'deletepoint' ? activeClass : '',\n command: () => this.toggleDragMode('deletepoint'),\n },\n );\n }\n // Bézier conversions + Delete are immediate selection *actions*, now in the\n // \"Selected region(s)\" group at the top (see buildRegionActionItems).\n }\n return items;\n }\n\n toggleSurface3dMode(mode: string) {\n this.activeSurface3dMode = mode;\n this.plotService.setSurfaceDragMode(mode);\n }\n\n resetSurfaceCamera() {\n this.plotService.resetSurfaceCamera();\n }\n\n /** Toggle the napari 3D coordinate-axes / scale gizmo (volume/isosurface). No-op on backends\n * that don't render one (the control method is optional). */\n toggleAxes() {\n this.axesVisible = !this.axesVisible;\n this.plotService.getSurface3dControls()?.setAxesVisible?.(this.axesVisible);\n }\n\n /** Toggle the napari surface wireframe (edges vs filled). No-op on backends without a surface. */\n toggleWireframe() {\n this.wireframeActive = !this.wireframeActive;\n this.plotService.getSurface3dControls()?.setWireframe?.(this.wireframeActive);\n }\n\n /** Change the napari 3D decimate factor. Decimation changes the fetched/assembled data, so this\n * re-plots the current 3D type at the new resolution (unlike axes/wireframe, which are live). */\n selectResolution(scale: number) {\n if (scale === this.resolutionScale) return;\n this.resolutionScale = scale;\n this.plotService.setResolutionScale?.(scale);\n this.reloadAndPlot();\n }\n\n /**\n * Switch the active plot type (heatmap, surface, contour, scatter, line,\n * scatter3d, isosurface). Keeps `isHeatmap` as the 2D-vs-3D flag the rest of\n * the toolbar/context-menu logic relies on, deactivates 2D-only tools when\n * moving to a 3D type, then re-plots.\n */\n onSelectPlotType(type: PlotType) {\n this.plotType = type;\n this.selectedPlotType = type;\n const descriptor = this.plotTypeOptions.find((d) => d.type === type);\n const is3d = descriptor?.dimensions === '3d';\n this.isHeatmap = !is3d;\n this.plotService.setPlotType(type);\n // Switching plot type cancels the active tool — not every type supports the\n // same tools (line/scatter charts and 3D scenes have no box zoom or region\n // drawing), so leaving a tool armed would misbehave on the new plot.\n this.deactivateActiveTool();\n if (is3d) {\n this.activeSurface3dMode = 'turntable';\n }\n // napari-js volume/isosurface assemble their own 3D texture from the slice endpoint, so\n // they take the normal re-plot path — NOT Plotly's stack-frame loader (whose \"Loading\n // frames\" overlay would never clear, since Plotly isn't the active backend) (jit-ui#102).\n const isNapari = type === PlotType.NAPARI_IMAGE || isNapari3d(type);\n if (descriptor?.requiresStack && !isNapari) {\n // Volume types (isosurface, scatter3d) need the whole z-stack loaded as a\n // 3D array, and they always render on Plotly. Drive the stack reload\n // directly through the image-info stream rather than the active renderer's\n // setShowStack: when OpenSeadragon owns the Image view its setShowStack is\n // a no-op, so the reload never fired and the loader spun forever. We arm\n // Plotly's stack-loading flag (keeps its frame-fetch loop alive) and\n // re-emit the image info with showStack on so the pipeline reloads on\n // Plotly regardless of which backend was on screen.\n this.selectedStackOption = this.stackOptions[1];\n this.stackLoading = true;\n this.plotService.setStackLoading(true);\n if (this.imageInfo) {\n this.imageInfo.showStack = true;\n this.state.setImageInfo(this.imageInfo);\n }\n return;\n }\n this.reloadAndPlot();\n }\n\n /** Deactivate whatever tool is armed and clear every tool mode. */\n private deactivateActiveTool() {\n this.activeDragMode = null;\n this.session.setActiveTool(null);\n this.plotService.getRegionOverlay()?.setMode('none');\n this.plotService.setDragMode(false);\n this.plotService.setZoomToBoxMode(false);\n this.plotService.setWandMode(false);\n this.plotService.setBrushMode(false);\n this.plotService.setSamPointMode(false);\n this.plotService.setVertexEraserMode(false);\n }\n}\n\n","<!-- SAM toast: live status + encoder-download progress bar (jit-ui#90). Sticky\n while a segment runs; stays open until the bar reaches 100% and the run ends. -->\n<p-toast [key]=\"samToastKey\" position=\"bottom-right\">\n <ng-template let-message pTemplate=\"message\">\n <div style=\"flex: 1; min-width: 16rem\">\n <div class=\"font-bold mb-1\">{{ message.summary }}</div>\n <div>{{ samStatus || message.detail }}</div>\n <p-progressBar *ngIf=\"samDownloading\" [value]=\"samProgress\" styleClass=\"mt-2 sam-progress\"></p-progressBar>\n <p-progressBar *ngIf=\"samBusy && !samDownloading\" mode=\"indeterminate\" styleClass=\"mt-2\"\n [style]=\"{ height: '4px' }\"></p-progressBar>\n </div>\n </ng-template>\n</p-toast>\n\n<!-- Toolbar dock: docked across the top by default; drag the handle to detach\n it into a floating, movable window (frees the top row for the image). -->\n<div class=\"toolbar-dock\" [class.floating]=\"toolbarFloating\"\n [style.left.px]=\"toolbarFloating ? toolbarPos.x : null\"\n [style.top.px]=\"toolbarFloating ? toolbarPos.y : null\">\n <div class=\"toolbar-drag-handle\" (mousedown)=\"onToolbarDragStart($event)\"\n pTooltip=\"Drag to float the toolbar\" tooltipPosition=\"bottom\">\n <i class=\"pi pi-bars\"></i>\n </div>\n<plotting-toolbar\n [imageInfo]=\"imageInfo\"\n [plotTypeOptions]=\"plotTypeOptions\"\n [selectedPlotType]=\"selectedPlotType\"\n [isoRange]=\"isoRange\"\n [maxIndex]=\"maxIndex\"\n [zIndex]=\"zIndex\"\n [isHeatmap]=\"isHeatmap\"\n [activeDragMode]=\"activeDragMode\"\n [activeSurface3dMode]=\"activeSurface3dMode\"\n [axesVisible]=\"axesVisible\"\n [wireframeActive]=\"wireframeActive\"\n [resolutionScale]=\"resolutionScale\"\n [wandSensitivity]=\"wandSensitivity\"\n [brushSize]=\"brushSize\"\n [samModels]=\"samModels\"\n [samModelId]=\"samModelId\"\n [vertexEraserRadius]=\"vertexEraserRadius\"\n [canUndo]=\"canUndoRegion\"\n [canRedo]=\"canRedoRegion\"\n [stackOptions]=\"stackOptions\"\n [tools]=\"toolbarTools\"\n [imageSmoothingEnabled]=\"imageSmoothingEnabled\"\n (selectPlotType)=\"onSelectPlotType($event)\"\n (toggleImageSmoothing)=\"onToggleImageSmoothing()\"\n (addProfileLine)=\"addProfileLine()\"\n (isoRangeChange)=\"onIsoRangeChange($event)\"\n (openChannelHistogram)=\"openChannelHistogram()\"\n (openRegionEditor)=\"openRegionEditor()\"\n (selectStackOption)=\"selectStackOption($event)\"\n (zScrub)=\"onZScrub($event)\"\n (zSlide)=\"onZSlide($event)\"\n (zIndexInput)=\"zIndex = $event; updateZIndex()\"\n (reloadAndPlot)=\"reloadAndPlot()\"\n (downloadImage)=\"downloadImage()\"\n (autoscaleImage)=\"autoscaleImage()\"\n (toggleDragMode)=\"toggleDragMode($event)\"\n (zoomIn)=\"zoomIn()\"\n (zoomOut)=\"zoomOut()\"\n (toggleSurface3dMode)=\"toggleSurface3dMode($event)\"\n (resetSurfaceCamera)=\"resetSurfaceCamera()\"\n (toggleAxes)=\"toggleAxes()\"\n (toggleWireframe)=\"toggleWireframe()\"\n (selectResolution)=\"selectResolution($event)\"\n (deleteRegion)=\"deleteRegion()\"\n (undoRegion)=\"undoRegion()\"\n (redoRegion)=\"redoRegion()\"\n (segmentRegions)=\"segmentRegions()\"\n (segmentCellpose)=\"segmentCellpose()\"\n (samModelChange)=\"onSamModelChange($event)\"\n (wandSensitivityChange)=\"onWandSensitivityChange($event)\"\n (brushSizeChange)=\"onBrushSizeChange($event)\"\n (vertexEraserRadiusChange)=\"onVertexEraserRadiusChange($event)\">\n <!-- Host-projected custom toolbar buttons, forwarded into the toolbar. -->\n <ng-content></ng-content>\n</plotting-toolbar>\n <p-button *ngIf=\"toolbarFloating\" class=\"toolbar-dock-btn\" icon=\"pi pi-thumbtack\" size=\"small\" [text]=\"true\"\n pTooltip=\"Dock to top\" tooltipPosition=\"bottom\" (onClick)=\"dockToolbar()\">\n </p-button>\n</div>\n\n<p-contextMenu #cm [model]=\"contextMenuItems\" appendTo=\"body\"></p-contextMenu>\n<!-- No `h-full` here: PrimeFlex's height:100% !important made #plot as tall as\n the whole host, so under the docked toolbar its bottom toolbar-height strip\n (incl. the OSD scale bar at bottom-left) was clipped by the host's\n overflow:hidden. The component stylesheet sizes it (.viz-plot { flex: 1 }). -->\n<div class=\"w-full relative viz-plot\" [id]=\"plotDivName\">\n <div *ngIf=\"imgLoading || stackLoading || isCaching\" id=\"overlay\">\n <!-- Determinate stack/volume progress takes precedence: while it's active show ONLY the\n progress bar + \"Loading frames...\", not the generic spinner/\"Loading image...\" on top of\n it (both were rendering at once for napari volume/isosurface loads). -->\n <ng-container *ngIf=\"stackLoading; else imgLoadingTpl\">\n <p-progressBar class=\"progress\" [value]=\"loadingPercentage\"></p-progressBar>\n <span class=\"text-loading\">Loading frames...</span>\n </ng-container>\n <ng-template #imgLoadingTpl>\n <!-- Cache-copy progress is shown whenever a cache download is active (isCaching), independent\n of `imgLoading`, so it's never dropped/masked mid-download. -->\n <ng-container *ngIf=\"isCaching; else spinnerLoading\">\n <!-- Stage-aware message comes from CacheProgressService updating\n imageLoadingMessage$ (\"Caching image...\" during the GCS download,\n then \"Generating preview...\" during per-slice thumbnail gen). Once the\n download hits 100% the remaining work (server preview/tile generation)\n has no determinate progress, so fall through to the spinner template\n rather than parking a full bar under \"Loading image...\". -->\n <p-progressBar class=\"progress\" [value]=\"cacheProgress\"></p-progressBar>\n <span class=\"text-loading\">{{loadingMessage}}</span>\n </ng-container>\n <ng-template #spinnerLoading>\n <div *ngIf=\"imgLoading\" class=\"spinner\"></div>\n <span *ngIf=\"imgLoading && !zoom\" class=\"text-loading\">{{loadingMessage}}</span>\n <span *ngIf=\"imgLoading && zoom\" class=\"zoom-text-loading\">{{loadingMessage}}</span>\n </ng-template>\n </ng-template>\n <p-button *ngIf=\"stackLoading || imgLoading\" class=\"cancel-loading \" label=\"Cancel\"\n (onClick)=\"cancelLoading()\">\n </p-button>\n </div>\n <!-- Translucent \"sharpening\" overlay shown after the small-tier preview is\n on screen while the large-tier render is still loading in the\n background. Lets the user see the blurry image underneath but makes\n it clear something is still loading so they don't mistake the\n low-res render for the final image. -->\n <div *ngIf=\"sharpening && !imgLoading && !stackLoading && !isCaching\" id=\"sharpening-overlay\">\n <div class=\"spinner\"></div>\n <span class=\"text-loading\">Sharpening preview...</span>\n </div>\n\n</div>\n\n<!-- Floating, draggable intensity-profile inset. Shown in LINE mode; the chart\n updates live as the line ROI on the image is moved. Kept OUTSIDE #plot and\n positioned fixed so it floats over the whole page (not clipped to the\n diagram/canvas area). -->\n<div *ngIf=\"hasProfiles\" class=\"intensity-panel\"\n [style.left.px]=\"profilePanelPos.x\" [style.top.px]=\"profilePanelPos.y\">\n <div class=\"intensity-panel-header\" (mousedown)=\"onProfilePanelDragStart($event)\">\n <span>Intensity profile</span>\n <i class=\"pi pi-arrows-alt\"></i>\n </div>\n <div [id]=\"intensityInsetDiv\" class=\"intensity-panel-plot\"></div>\n</div>\n\n<!-- Channels & Histogram: non-modal floating dialog opened from the toolbar. -->\n<channel-histogram [(visible)]=\"showChannelHistogram\"></channel-histogram>\n\n<!-- Region Editor: non-modal, draggable, resizable floating dialog opened from\n the toolbar (formerly the right-panel Regions tab). Modeless so regions can\n still be drawn/selected on the plot while it's open; stays linked to this\n plotting instance via the root RegionStore singleton. Opens over the right\n side of the view. -->\n<p-dialog header=\"Region Editor\" [(visible)]=\"showRegionEditor\"\n [modal]=\"false\" [resizable]=\"true\" [draggable]=\"true\"\n [maximizable]=\"true\" appendTo=\"body\" position=\"right\"\n [style]=\"{ width: regionEditorWidth, height: '85vh' }\"\n [contentStyle]=\"{ overflow: 'auto' }\">\n <region-editor></region-editor>\n</p-dialog>\n\n<!-- Simplify (Douglas–Peucker): custom px-threshold picker for the selected\n region(s), opened from the right-click \"Simplify ▸ Custom…\" action. -->\n<p-dialog header=\"Simplify region(s)\" [(visible)]=\"displaySimplifyDialog\" [modal]=\"true\"\n [style]=\"{width: '22rem'}\" [draggable]=\"false\" [resizable]=\"false\">\n <div class=\"flex flex-column gap-2\">\n <span>Altitude threshold: <b>{{ simplifyThreshold }} px</b></span>\n <p-slider [(ngModel)]=\"simplifyThreshold\" [min]=\"1\" [max]=\"20\" [step]=\"1\"></p-slider>\n <small>Vertices within this distance of the line between their neighbours are removed.</small>\n </div>\n <ng-template pTemplate=\"footer\">\n <p-button label=\"Cancel\" [text]=\"true\" (onClick)=\"displaySimplifyDialog = false\"></p-button>\n <p-button label=\"Apply\" icon=\"pi pi-check\" (onClick)=\"simplifyRegions(simplifyThreshold)\"></p-button>\n </ng-template>\n</p-dialog>\n\n","import { Injectable } from '@angular/core';\n\nimport { WandImage, WandOptions, WandService } from './wand.service';\nimport { BBoxMask, masksOverlap, unionMasks } from '../../models/geometry';\nimport { IViewportHost, IRegionDataHost } from '../../contracts/coordinate-transform.contract';\nimport { Region, Polygon } from '../../models/region';\n\n/**\n * The pixel data and frame state PlotlyService caches for sampling. Returned\n * by `WandToolHost.getCachedImageData()`.\n */\nexport interface CachedImageData {\n /** 2-D matrices, one per stack frame (length 1 for non-stack images). */\n frames: any[];\n /** Image-pixel width of each frame matrix. */\n width: number;\n /** Image-pixel height of each frame matrix. */\n height: number;\n /**\n * Plot-data-coords-per-image-pixel along x (and y — they're the same\n * for heatmap and image traces).\n */\n ratios: number[];\n /** Whether each frame is a 2-D scalar matrix (true) or 3-channel RGB (false). */\n isGrayscale: boolean;\n /**\n * Data-coords of matrix pixel (0,0). Lets the matrix be a *crop* of the data\n * space rather than starting at the origin — e.g. the OSD backend samples the\n * currently rendered viewport, so when zoomed in the matrix covers only the\n * visible sub-region at screen resolution. Defaults to 0 (full-frame matrix,\n * as Plotly provides). matrixIndex = (data - origin) / ratio.\n */\n originX?: number;\n originY?: number;\n}\n\n/**\n * The collaboration interface the wand tool needs from PlotlyService.\n *\n * Keeping it explicit makes the dependency one-way: WandToolService never\n * imports PlotlyService directly. PlotlyService satisfies this interface\n * structurally and binds itself via `bindHost(this)`.\n */\nexport interface WandToolHost extends IViewportHost, IRegionDataHost {\n /** Pixel data for sampling. null when no image is loaded yet. */\n getCachedImageData(): CachedImageData | null;\n /** Index of the currently visible frame in a stack (0 for non-stack). */\n getActiveFrameIndex(): number;\n\n /** Current image's filename — stamped onto new shapes for filtering. */\n getFileName(): string | undefined;\n /** Default stroke colour for new shapes. */\n getShapeColor(): string;\n}\n\n/**\n * The wand drawing tool. Owns its own canvas overlay, mouse handlers, and\n * stroke accumulator. Reads/writes the shape list via the WandToolHost\n * interface so it stays decoupled from PlotlyService internals.\n *\n * Lifecycle: PlotlyService injects this service, calls `bindHost(this)` once\n * during its own construction, then calls `setMode(true | false, options)` to\n * activate/deactivate the tool.\n */\n@Injectable({ providedIn: 'root' })\nexport class WandToolService {\n // ── Tool state ──────────────────────────────────────────────────────\n\n private host!: WandToolHost;\n private overlay: HTMLCanvasElement | null = null;\n private active = false;\n /**\n * Accumulated wand region. Every per-tick patch mask is OR'd into `mask`\n * over a bbox that grows with the stroke, so the region keeps expanding\n * as the user drags. The accumulator persists across mouseup/mousedown so\n * that subsequent strokes extend the *same* region — matching QuPath's\n * brush behaviour where the active annotation stays editable until the\n * user switches tool.\n */\n private stroke: BBoxMask | null = null;\n /** Id of the region this wand stroke is editing (null = a fresh region). */\n private strokeRegionId: number | null = null;\n /** Readback ratio/origin signature the active stroke's matrix coords are tied to; a change\n * (zoom/pan) invalidates the stroke so it isn't re-committed at a different scale (jit-ui#102). */\n private strokeRatioSig: string | null = null;\n private dragging = false;\n private options: WandOptions = {};\n\n private readonly boundMouseDown: (e: MouseEvent) => void;\n private readonly boundMouseMove: (e: MouseEvent) => void;\n private readonly boundMouseUp: (e: MouseEvent) => void;\n\n constructor(private wandService: WandService) {\n this.boundMouseDown = (e) => this.onMouseDown(e);\n this.boundMouseMove = (e) => this.onMouseMove(e);\n this.boundMouseUp = (e) => this.onMouseUp(e);\n }\n\n /** Wire the tool to its host. Must be called once before `setMode(true)`. */\n bindHost(host: WandToolHost) {\n this.host = host;\n }\n\n // ── Public API ──────────────────────────────────────────────────────\n\n /** Toggle the wand on/off. */\n setMode(active: boolean, options: WandOptions = {}) {\n this.active = active;\n this.options = options;\n if (active) {\n this.createOverlay();\n } else {\n this.destroyOverlay();\n }\n }\n\n /** Merge new options (e.g. live sensitivity slider updates). */\n setOptions(options: WandOptions) {\n this.options = { ...this.options, ...options };\n }\n\n /** Drop the active wand region so the next click starts a new one. */\n clearActiveRegion() {\n this.resetStroke();\n }\n\n // ── Overlay lifecycle ───────────────────────────────────────────────\n\n private createOverlay() {\n const plotEl = this.host.getOverlayContainer();\n if (!plotEl || this.overlay) return;\n\n const canvas = document.createElement('canvas');\n canvas.style.position = 'absolute';\n canvas.style.top = '0';\n canvas.style.left = '0';\n canvas.style.width = '100%';\n canvas.style.height = '100%';\n canvas.style.cursor = 'crosshair';\n canvas.style.zIndex = '100';\n canvas.width = plotEl.offsetWidth;\n canvas.height = plotEl.offsetHeight;\n\n plotEl.appendChild(canvas);\n this.overlay = canvas;\n\n canvas.addEventListener('mousedown', this.boundMouseDown);\n canvas.addEventListener('mousemove', this.boundMouseMove);\n canvas.addEventListener('mouseup', this.boundMouseUp);\n canvas.addEventListener('mouseleave', this.boundMouseUp);\n }\n\n private destroyOverlay() {\n if (!this.overlay) return;\n this.overlay.removeEventListener('mousedown', this.boundMouseDown);\n this.overlay.removeEventListener('mousemove', this.boundMouseMove);\n this.overlay.removeEventListener('mouseup', this.boundMouseUp);\n this.overlay.removeEventListener('mouseleave', this.boundMouseUp);\n this.overlay.remove();\n this.overlay = null;\n this.resetStroke();\n }\n\n private onMouseDown(e: MouseEvent) {\n if (e.button !== 0) return;\n this.dragging = true;\n this.applyAtClient(e, true);\n }\n\n private onMouseMove(e: MouseEvent) {\n if (!this.dragging) return;\n if ((e.buttons & 1) === 0) {\n this.dragging = false;\n return;\n }\n this.applyAtClient(e, false);\n }\n\n private onMouseUp(_: MouseEvent) {\n // Stop accumulating from this drag, but keep the region alive so the\n // next mousedown extends it instead of starting fresh.\n this.dragging = false;\n }\n\n private resetStroke() {\n this.stroke = null;\n this.strokeRegionId = null;\n this.dragging = false;\n }\n\n // ── Per-tick stroke logic ───────────────────────────────────────────\n\n /**\n * Sample the cached image at the click location, OR (or AND-NOT) the\n * wand's per-tick patch mask into the active region's bbox-relative mask,\n * re-trace the boundary, and update the in-progress shape — matching\n * QuPath's additive brush/wand behaviour. Shift = erase. Cmd/Ctrl =\n * exact-match flood fill.\n */\n private applyAtClient(e: MouseEvent, isStart = false) {\n if (!this.overlay) return;\n const cached = this.host.getCachedImageData();\n if (!cached || cached.frames.length === 0) return;\n\n // The current regions (neutral model). Mutated locally across this tick and\n // committed once via host.setRegions().\n const regions = this.host.getRegions();\n\n const transform = this.host.getCoordinateTransform();\n if (!transform.isReady()) return;\n const { x: dataX, y: dataY } = transform.clientToData(e.clientX, e.clientY);\n if (!Number.isFinite(dataX) || !Number.isFinite(dataY)) return;\n\n // ratios = [xRatio, yRatio] from both backends. Use the X ratio for the\n // column and the Y ratio for the row: they differ when the pixel aspect\n // isn't 1:1 (e.g. a non-square OSD viewport), and reusing ratios[0] for\n // both would distort the sampled region vertically. Fall back to the X\n // ratio if only one was supplied.\n const rx = cached.ratios[0] || 1;\n const ry = cached.ratios[1] || cached.ratios[0] || 1;\n const ox = cached.originX ?? 0;\n const oy = cached.originY ?? 0;\n // The stroke accumulator is in matrix (viewport-pixel) coordinates tied to the readback's\n // ratio/origin. If the view changed (zoom/pan) since the stroke was built, those coords no\n // longer mean the same thing — re-committing would rescale the region by the zoom factor\n // (jit-ui#102). Drop the stale stroke so a fresh one is built at the current view.\n const sig = `${rx},${ry},${ox},${oy}`;\n if (this.stroke && this.strokeRatioSig !== sig) {\n this.stroke = null;\n this.strokeRegionId = null;\n }\n this.strokeRatioSig = sig;\n const matrixX = (dataX - ox) / rx;\n const matrixY = (dataY - oy) / ry;\n if (matrixX < 0 || matrixX >= cached.width) return;\n if (matrixY < 0 || matrixY >= cached.height) return;\n\n const frameIdx = this.host.getActiveFrameIndex();\n const frame = cached.frames[frameIdx] ?? cached.frames[0];\n\n const wandImage: WandImage = {\n data: frame,\n width: cached.width,\n height: cached.height,\n isGrayscale: cached.isGrayscale,\n };\n // Shift = erase (subtract pixels from an existing region).\n // Cmd/Ctrl alone = simple flood fill (no smoothing/threshold).\n const erase = e.shiftKey;\n const opts: WandOptions = {\n ...this.options,\n simpleMode: this.options.simpleMode || ((e.metaKey || e.ctrlKey) && !erase),\n };\n\n // If this is the first tick of a new drag and the click is NOT inside the\n // current accumulator and NOT inside any existing path-shape, drop the old\n // stroke so a brand-new region starts here. Without this, the accumulator\n // bbox grows to span both areas and `maskToPolygon` keeps only the largest\n // connected blob — making the new click appear to do nothing.\n if (isStart && !erase && this.stroke && !this.pointInStroke(matrixX, matrixY)) {\n // Will fall through to tryAdoptShapeAt below; if that also misses, a\n // fresh stroke is created from the patch.\n this.stroke = null;\n this.strokeRegionId = null;\n }\n\n const patch = this.wandService.computePatchMask(wandImage, matrixX, matrixY, opts);\n if (!patch) return;\n\n const W = patch.size;\n const half = (W - 1) / 2;\n const px0 = Math.round(matrixX) - half;\n const py0 = Math.round(matrixY) - half;\n const px1 = px0 + W;\n const py1 = py0 + W;\n\n // If there's no active wand region, see if the click landed on an\n // existing path-shape — adopt it so this stroke extends (or erases\n // from) it instead of creating a new region.\n if (!this.stroke) {\n this.tryAdoptShapeAt(regions, matrixX, matrixY, rx, ry, cached);\n }\n\n // Erasing requires an existing region. Shift-clicking empty space is a\n // no-op — we don't create a region only to immediately delete from it.\n if (erase && !this.stroke) return;\n\n // Grow the region's accumulated mask only when adding. Erasing never\n // expands the region beyond its current bbox.\n if (!this.stroke) {\n const bx = Math.max(0, px0);\n const by = Math.max(0, py0);\n const bx1 = Math.min(cached.width, px1);\n const by1 = Math.min(cached.height, py1);\n const bw = Math.max(0, bx1 - bx);\n const bh = Math.max(0, by1 - by);\n if (bw === 0 || bh === 0) return;\n this.stroke = { bx, by, bw, bh, mask: new Uint8Array(bw * bh) };\n } else if (!erase) {\n // Don't clamp the accumulator to the viewport: an adopted region may extend off-screen, and\n // clamping here would discard its off-screen part when the stroke grows (jit-ui#102).\n const bx = Math.min(this.stroke.bx, px0);\n const by = Math.min(this.stroke.by, py0);\n const bx1 = Math.max(this.stroke.bx + this.stroke.bw, px1);\n const by1 = Math.max(this.stroke.by + this.stroke.bh, py1);\n const bw = bx1 - bx;\n const bh = by1 - by;\n if (bw !== this.stroke.bw || bh !== this.stroke.bh || bx !== this.stroke.bx || by !== this.stroke.by) {\n // Reallocate the larger mask and copy the previous mask into it.\n const next = new Uint8Array(bw * bh);\n const dx = this.stroke.bx - bx;\n const dy = this.stroke.by - by;\n for (let row = 0; row < this.stroke.bh; row++) {\n const srcOff = row * this.stroke.bw;\n const dstOff = (row + dy) * bw + dx;\n next.set(this.stroke.mask.subarray(srcOff, srcOff + this.stroke.bw), dstOff);\n }\n this.stroke = { bx, by, bw, bh, mask: next };\n }\n }\n\n // Apply the patch: OR (add) or AND-NOT (erase).\n const stroke = this.stroke;\n for (let py = 0; py < W; py++) {\n const iy = py0 + py;\n const my = iy - stroke.by;\n if (my < 0 || my >= stroke.bh) continue;\n const srcRow = py * W;\n const dstRow = my * stroke.bw;\n for (let px = 0; px < W; px++) {\n if (!patch.mask[srcRow + px]) continue;\n const ix = px0 + px;\n const mx = ix - stroke.bx;\n if (mx < 0 || mx >= stroke.bw) continue;\n if (erase) stroke.mask[dstRow + mx] = 0;\n else stroke.mask[dstRow + mx] = 1;\n }\n }\n\n if (!erase) {\n // If the grown stroke now overlaps another path-shape, fold those\n // shapes into this one and drop them — matching QuPath's\n // merge-on-touch behaviour.\n this.mergeOverlappingShapes(regions, rx, ry, cached);\n }\n\n // Trace the union boundary in image-pixel coords.\n const stroke2 = this.stroke!;\n const poly = this.wandService.maskToPolygon(\n stroke2.mask,\n stroke2.bw,\n stroke2.bh,\n cached.width,\n cached.height,\n stroke2.bx,\n stroke2.by,\n );\n\n if (!poly) {\n // Erased to nothing — remove the shape entirely.\n if (erase) this.dropActiveShape(regions);\n return;\n }\n\n // Convert from matrix coords back to plot data coords.\n const xPlot = poly.xpoints.map((x) => ox + x * rx);\n const yPlot = poly.ypoints.map((y) => oy + y * ry);\n\n this.commitStroke(regions, xPlot, yPlot);\n }\n\n /** True if (matrixX, matrixY) lies inside the current stroke accumulator. */\n private pointInStroke(matrixX: number, matrixY: number): boolean {\n const s = this.stroke;\n if (!s) return false;\n const mx = Math.floor(matrixX) - s.bx;\n const my = Math.floor(matrixY) - s.by;\n if (mx < 0 || my < 0 || mx >= s.bw || my >= s.bh) return false;\n return s.mask[my * s.bw + mx] === 1;\n }\n\n /**\n * Remove the region referenced by `strokeRegionId` from the region list and\n * reset the active stroke — used when an erase stroke deletes every pixel.\n */\n private dropActiveShape(regions: Region[]) {\n if (this.strokeRegionId != null) {\n const idx = regions.findIndex((r) => r.id === this.strokeRegionId);\n if (idx >= 0) {\n regions.splice(idx, 1);\n this.host.setRegions(regions);\n }\n }\n this.stroke = null;\n this.strokeRegionId = null;\n }\n\n /**\n * Whether a region can be faithfully rasterized into the wand stroke at the current view\n * resolution (rx/ry = data units per matrix pixel). Editing rasterizes the region to the\n * viewport grid and re-traces it, so a region whose matrix-space bbox exceeds the rasterizer's\n * cap would be clipped/down-quantized and come back rescaled/corrupted (jit-ui#102) — e.g. a\n * whole-slide annotation while zoomed out. Skip adopt/merge for those: leave them untouched and\n * only edit them near native zoom.\n */\n private fitsForEdit(\n verts: { xpoints: number[]; ypoints: number[] },\n rx: number,\n ry: number,\n ): boolean {\n const xs = verts.xpoints;\n const ys = verts.ypoints;\n let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;\n for (let i = 0; i < xs.length; i++) {\n if (xs[i] < minX) minX = xs[i];\n if (xs[i] > maxX) maxX = xs[i];\n if (ys[i] < minY) minY = ys[i];\n if (ys[i] > maxY) maxY = ys[i];\n }\n const w = (maxX - minX) / (rx || 1);\n const h = (maxY - minY) / (ry || 1);\n return w > 0 && h > 0 && w * h <= 4096 * 4096;\n }\n\n /** A region's closed-polygon vertices (image/data coords), or null when it\n * isn't a fillable closed polygon (rectangles, open polylines). */\n private regionVerts(\n region: Region,\n ): { xpoints: number[]; ypoints: number[]; holes?: number[][][] } | null {\n const b = region?.bounds;\n if (b instanceof Polygon && b.closed !== false && b.xpoints.length >= 3) {\n return { xpoints: b.xpoints, ypoints: b.ypoints, holes: b.holes };\n }\n return null;\n }\n\n /** Convert a region's hole rings from image/data coords into matrix coords so\n * they line up with the stroke accumulator (jit-ui#85). */\n private holesToMatrix(\n holes: number[][][] | undefined, ox: number, oy: number, rx: number, ry: number,\n ): number[][][] | undefined {\n return holes?.map((ring) => ring.map(([x, y]) => [(x - ox) / rx, (y - oy) / ry]));\n }\n\n /**\n * If (matrixX, matrixY) falls inside an existing region, rasterize it into\n * the wand stroke accumulator so subsequent wand input extends it rather than\n * starting a new region.\n */\n private tryAdoptShapeAt(\n regions: Region[],\n matrixX: number,\n matrixY: number,\n rx: number,\n ry: number,\n cached: CachedImageData,\n ): boolean {\n if (!regions || regions.length === 0) return false;\n\n // Most-recently-added regions are on top — check them first.\n for (let i = regions.length - 1; i >= 0; i--) {\n const verts = this.regionVerts(regions[i]);\n if (!verts) continue;\n // Too large to rasterize at this zoom → don't adopt it (editing would rescale/corrupt it).\n if (!this.fitsForEdit(verts, rx, ry)) continue;\n\n const ox = cached.originX ?? 0;\n const oy = cached.originY ?? 0;\n const xs = verts.xpoints.map((x) => (x - ox) / rx);\n const ys = verts.ypoints.map((y) => (y - oy) / ry);\n const holes = this.holesToMatrix(verts.holes, ox, oy, rx, ry);\n\n // Clicking inside a hole must NOT adopt the donut (it's empty there).\n if (!this.wandService.pointInPolygonWithHoles(matrixX, matrixY, xs, ys, holes)) continue;\n\n const raster = this.wandService.rasterizePolygon(xs, ys, cached.width, cached.height, holes);\n if (!raster) continue;\n\n this.stroke = raster;\n this.strokeRegionId = regions[i].id ?? null;\n return true;\n }\n return false;\n }\n\n /**\n * Iterate every region; if its rasterized mask overlaps the wand stroke mask\n * by at least one pixel, OR it into the stroke and remove it from the list.\n * Called every tick so chained merges resolve. If the wand has no region id\n * yet, the merged region's id is adopted so the merged region replaces it.\n */\n private mergeOverlappingShapes(regions: Region[], rx: number, ry: number, cached: CachedImageData) {\n if (!this.stroke) return;\n let didMerge = true;\n while (didMerge) {\n didMerge = false;\n for (let i = regions.length - 1; i >= 0; i--) {\n const region = regions[i];\n if (region.id != null && region.id === this.strokeRegionId) continue;\n\n const verts = this.regionVerts(region);\n if (!verts) continue;\n // Too large to rasterize at this zoom → don't merge it (would rescale/corrupt it).\n if (!this.fitsForEdit(verts, rx, ry)) continue;\n\n const ox = cached.originX ?? 0;\n const oy = cached.originY ?? 0;\n const xs = verts.xpoints.map((x) => (x - ox) / rx);\n const ys = verts.ypoints.map((y) => (y - oy) / ry);\n\n // Quick bbox reject before rasterizing.\n let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;\n for (let k = 0; k < xs.length; k++) {\n if (xs[k] < minX) minX = xs[k];\n if (xs[k] > maxX) maxX = xs[k];\n if (ys[k] < minY) minY = ys[k];\n if (ys[k] > maxY) maxY = ys[k];\n }\n const wx0 = this.stroke.bx, wy0 = this.stroke.by;\n const wx1 = wx0 + this.stroke.bw, wy1 = wy0 + this.stroke.bh;\n if (maxX < wx0 || minX > wx1 || maxY < wy0 || minY > wy1) continue;\n\n const holes = this.holesToMatrix(verts.holes, ox, oy, rx, ry);\n const raster = this.wandService.rasterizePolygon(xs, ys, cached.width, cached.height, holes);\n if (!raster) continue;\n\n if (!masksOverlap(this.stroke, raster)) continue;\n\n this.stroke = unionMasks(this.stroke, raster);\n\n if (this.strokeRegionId == null) {\n this.strokeRegionId = region.id ?? null;\n }\n regions.splice(i, 1);\n didMerge = true;\n break;\n }\n }\n }\n\n /**\n * Commit the in-progress polygon as a region — a new region on the first tick\n * of a stroke, or an in-place replacement of the active region on later ticks\n * — then ask the host to render. The store mints an id on the first commit,\n * which we adopt so subsequent ticks replace the same region.\n */\n private commitStroke(regions: Region[], xPlot: number[], yPlot: number[]) {\n if (xPlot.length < 3) return;\n\n const existing = this.strokeRegionId != null\n ? regions.find((r) => r.id === this.strokeRegionId) : null;\n\n const poly = new Polygon();\n poly.npoints = xPlot.length;\n poly.xpoints = xPlot;\n poly.ypoints = yPlot;\n poly.coordinates = xPlot.map((x, i) => [x, yPlot[i]]);\n poly.closed = true;\n\n const region = new Region();\n region.bounds = poly;\n region.color = this.host.getShapeColor();\n if (existing) {\n // Preserve identity + class label across the stroke's drag ticks.\n region.id = existing.id;\n region.name = existing.name;\n }\n // Default class/annotation name, matching the overlay-drawn regions and the\n // Region Editor's \"Add\" actions so a wand region isn't left unlabeled.\n region.label = existing?.label ?? 'Region';\n\n if (this.strokeRegionId == null) {\n regions.push(region);\n } else {\n const idx = regions.findIndex((r) => r.id === this.strokeRegionId);\n if (idx >= 0) regions[idx] = region;\n else regions.push(region);\n }\n\n this.host.setRegions(regions);\n // The store assigns an id on the first commit — adopt it.\n this.strokeRegionId = region.id ?? this.strokeRegionId;\n }\n}\n","import { Injectable } from '@angular/core';\n\nimport { WandService } from '../wand/wand.service';\nimport { CachedImageData, WandToolHost } from '../wand/wand-tool.service';\nimport { BBoxMask, masksOverlap, unionMasks } from '../../models/geometry';\nimport { Region, Polygon } from '../../models/region';\n\n/** Brush parameters. `size` is the brush *diameter* in matrix (image) pixels. */\nexport interface BrushOptions {\n size?: number;\n}\n\n/** Default brush diameter (matrix pixels) if none is supplied. */\nconst DEFAULT_BRUSH_SIZE = 40;\n\n/**\n * The brush host is identical to the wand's — both need the cached-image\n * coordinate frame, the overlay container, the coordinate transform, and\n * read/write access to the shared region list. The brush ignores the wand's\n * pixel values (it paints a geometric disc rather than flood-filling by colour),\n * so reusing {@link WandToolHost} lets each backend bind the same host object.\n */\nexport type BrushToolHost = WandToolHost;\n\n/**\n * QuPath-style brush tool. Painting a stroke unions a disc of the configured\n * size into the active region as the cursor drags; holding <kbd>Shift</kbd>\n * subtracts instead (eraser brush), matching the wand's modifier. The stroke is\n * accumulated as a bbox-relative mask (exactly like {@link WandToolService}) so\n * the brush inherits the wand's adopt-existing-region and merge-on-touch\n * behaviour, then the union boundary is traced back into a polygon Region.\n *\n * No pixel sampling and no cursor indicator: the painted stroke itself shows the\n * brush size. The overlay canvas only captures the pointer.\n *\n * Lifecycle mirrors the wand: a backend binds its host once, then toggles the\n * tool with `setMode(true | false, options)`.\n *\n * Holes / donuts (jit-ui#85): brushing a ring that encloses an unpainted area\n * keeps the enclosed hole — {@link WandService.maskToPolygons} traces interior\n * rings into {@link Polygon.holes}, which adopt/merge preserve (the re-rasterize\n * punches the holes back out). The OpenSeadragon overlay renders them with\n * even-odd fill and GeoJSON round-trips them as extra Polygon rings. The Plotly\n * (Heatmap) backend currently renders the filled exterior only.\n */\n@Injectable({ providedIn: 'root' })\nexport class BrushToolService {\n private host!: BrushToolHost;\n private overlay: HTMLCanvasElement | null = null;\n private active = false;\n\n /**\n * Accumulated brush region (bbox-relative mask). Persists across mouseup so a\n * subsequent stroke extends the *same* region until the user switches tool —\n * matching QuPath, and the wand.\n */\n private stroke: BBoxMask | null = null;\n /** Id of the region this stroke is editing (null = a fresh region). For an\n * erase that splits the region, this tracks the largest resulting piece. */\n private strokeRegionId: number | null = null;\n /** Readback ratio/origin signature the active stroke is tied to; a change (zoom/pan) invalidates\n * it so it isn't re-committed at a different scale (jit-ui#102). */\n private strokeRatioSig: string | null = null;\n /** Ids of the extra regions produced when an erase stroke splits a region\n * into disconnected pieces — reused across drag ticks so the split pieces\n * keep stable identities instead of being recreated each tick. */\n private strokeExtraIds: number[] = [];\n /** Previous cursor position (matrix coords) within the current drag, so fast\n * drags paint a continuous stroke rather than disconnected dabs. */\n private lastMatrix: { x: number; y: number } | null = null;\n private dragging = false;\n private size = DEFAULT_BRUSH_SIZE;\n\n private readonly boundMouseDown: (e: MouseEvent) => void;\n private readonly boundMouseMove: (e: MouseEvent) => void;\n private readonly boundMouseUp: (e: MouseEvent) => void;\n\n constructor(private wandService: WandService) {\n this.boundMouseDown = (e) => this.onMouseDown(e);\n this.boundMouseMove = (e) => this.onMouseMove(e);\n this.boundMouseUp = (e) => this.onMouseUp(e);\n }\n\n /** Wire the tool to its host. Must be called once before `setMode(true)`. */\n bindHost(host: BrushToolHost) {\n this.host = host;\n }\n\n // ── Public API ──────────────────────────────────────────────────────\n\n /** Toggle the brush on/off. */\n setMode(active: boolean, options: BrushOptions = {}) {\n this.active = active;\n if (options.size != null) this.setSize(options.size);\n if (active) {\n this.createOverlay();\n } else {\n this.destroyOverlay();\n }\n }\n\n /** Live-update the brush size (matrix-pixel diameter). */\n setSize(size: number) {\n if (!Number.isFinite(size) || size <= 0) return;\n this.size = size;\n }\n\n /** Drop the active brush region so the next stroke starts a new one. */\n clearActiveRegion() {\n this.resetStroke();\n }\n\n // ── Overlay lifecycle ───────────────────────────────────────────────\n\n private createOverlay() {\n const plotEl = this.host.getOverlayContainer();\n if (!plotEl || this.overlay) return;\n\n const canvas = document.createElement('canvas');\n canvas.style.position = 'absolute';\n canvas.style.top = '0';\n canvas.style.left = '0';\n canvas.style.width = '100%';\n canvas.style.height = '100%';\n canvas.style.cursor = 'crosshair';\n canvas.style.zIndex = '100';\n canvas.width = plotEl.offsetWidth;\n canvas.height = plotEl.offsetHeight;\n\n plotEl.appendChild(canvas);\n this.overlay = canvas;\n\n canvas.addEventListener('mousedown', this.boundMouseDown);\n canvas.addEventListener('mousemove', this.boundMouseMove);\n canvas.addEventListener('mouseup', this.boundMouseUp);\n canvas.addEventListener('mouseleave', this.boundMouseUp);\n }\n\n private destroyOverlay() {\n if (!this.overlay) return;\n this.overlay.removeEventListener('mousedown', this.boundMouseDown);\n this.overlay.removeEventListener('mousemove', this.boundMouseMove);\n this.overlay.removeEventListener('mouseup', this.boundMouseUp);\n this.overlay.removeEventListener('mouseleave', this.boundMouseUp);\n this.overlay.remove();\n this.overlay = null;\n this.resetStroke();\n }\n\n private onMouseDown(e: MouseEvent) {\n if (e.button !== 0) return;\n this.dragging = true;\n this.lastMatrix = null; // first stamp of this drag is a single dab\n this.applyAtClient(e, true);\n }\n\n private onMouseMove(e: MouseEvent) {\n if (!this.dragging) return;\n if ((e.buttons & 1) === 0) {\n this.dragging = false;\n return;\n }\n this.applyAtClient(e, false);\n }\n\n private onMouseUp(_: MouseEvent) {\n // Stop accumulating from this drag, but keep the region alive so the next\n // mousedown extends it. Clear lastMatrix so the next drag starts a dab.\n this.dragging = false;\n this.lastMatrix = null;\n }\n\n private resetStroke() {\n this.stroke = null;\n this.strokeRegionId = null;\n this.strokeExtraIds = [];\n this.lastMatrix = null;\n this.dragging = false;\n }\n\n // ── Per-tick stroke logic ───────────────────────────────────────────\n\n /**\n * Paint (or erase) a disc — or a swept line of discs since the previous\n * tick — into the active region's accumulator mask, re-trace the boundary,\n * and commit the updated Region. Shift = erase.\n */\n private applyAtClient(e: MouseEvent, isStart: boolean) {\n if (!this.overlay) return;\n const cached = this.host.getCachedImageData();\n if (!cached || cached.frames.length === 0) return;\n\n const regions = this.host.getRegions();\n\n const transform = this.host.getCoordinateTransform();\n if (!transform.isReady()) return;\n const { x: dataX, y: dataY } = transform.clientToData(e.clientX, e.clientY);\n if (!Number.isFinite(dataX) || !Number.isFinite(dataY)) return;\n\n // Heatmap/image traces use ratios[0] for both dx and dy.\n const rx = cached.ratios[0] || 1;\n const ry = cached.ratios[0] || 1;\n const ox = cached.originX ?? 0;\n const oy = cached.originY ?? 0;\n // Drop a stroke built at a different view (zoom/pan): its matrix coords are tied to the old\n // ratio/origin, and re-committing would rescale the region by the zoom factor (jit-ui#102).\n const sig = `${rx},${ry},${ox},${oy}`;\n if (this.stroke && this.strokeRatioSig !== sig) {\n this.stroke = null;\n this.strokeRegionId = null;\n }\n this.strokeRatioSig = sig;\n const matrixX = (dataX - ox) / rx;\n const matrixY = (dataY - oy) / ry;\n if (matrixX < 0 || matrixX >= cached.width) return;\n if (matrixY < 0 || matrixY >= cached.height) return;\n\n const erase = e.shiftKey;\n const radius = Math.max(0.5, this.size / 2);\n\n // Start of a fresh drag that isn't inside the current accumulator: drop the\n // old stroke so a brand-new region starts here (mirrors the wand).\n if (isStart && !erase && this.stroke && !this.pointInStroke(matrixX, matrixY)) {\n this.stroke = null;\n this.strokeRegionId = null;\n }\n\n // If there's no active region, adopt an existing shape under the cursor so\n // the stroke extends (or erases from) it instead of creating a new region.\n if (!this.stroke) {\n this.tryAdoptShapeAt(regions, matrixX, matrixY, rx, ry, cached);\n }\n\n // Erasing requires an existing region — shift on empty space is a no-op.\n if (erase && !this.stroke) {\n this.lastMatrix = { x: matrixX, y: matrixY };\n return;\n }\n\n // Stamp the disc, sweeping from the previous point for a continuous stroke.\n if (isStart || !this.lastMatrix) {\n this.stampDisc(matrixX, matrixY, radius, erase, cached);\n } else {\n const dx = matrixX - this.lastMatrix.x;\n const dy = matrixY - this.lastMatrix.y;\n const dist = Math.hypot(dx, dy);\n const step = Math.max(1, radius / 2);\n const n = Math.max(1, Math.ceil(dist / step));\n for (let i = 1; i <= n; i++) {\n const t = i / n;\n this.stampDisc(this.lastMatrix.x + dx * t, this.lastMatrix.y + dy * t, radius, erase, cached);\n }\n }\n this.lastMatrix = { x: matrixX, y: matrixY };\n\n if (!this.stroke) return;\n\n if (!erase) {\n // Growing into another shape folds it into this stroke (merge-on-touch).\n this.mergeOverlappingShapes(regions, rx, ry, cached);\n }\n\n const stroke = this.stroke;\n // Trace every connected piece: an erase that cuts through the region splits\n // it into two, and both must survive (the larger keeps the region identity).\n const polys = this.wandService.maskToPolygons(\n stroke.mask, stroke.bw, stroke.bh, cached.width, cached.height, stroke.bx, stroke.by,\n );\n if (polys.length === 0) {\n // Erased to nothing — remove the shape(s) entirely.\n if (erase) this.dropActiveShape(regions);\n return;\n }\n\n const components = polys.map((poly) => ({\n xPlot: poly.xpoints.map((x) => ox + x * rx),\n yPlot: poly.ypoints.map((y) => oy + y * ry),\n // Carry traced interior rings (holes) back to plot coords so the donut\n // survives the commit (jit-ui#85).\n holes: poly.holes?.map((ring) => ring.map(([x, y]) => [ox + x * rx, oy + y * ry])),\n }));\n this.commitComponents(regions, components);\n }\n\n /**\n * OR (add) or AND-NOT (erase) a filled disc of `radius` matrix-pixels centred\n * at (cx, cy) into the accumulator, growing its bbox to fit when adding.\n */\n private stampDisc(cx: number, cy: number, radius: number, erase: boolean, cached: CachedImageData) {\n const px0 = Math.floor(cx - radius);\n const py0 = Math.floor(cy - radius);\n const px1 = Math.ceil(cx + radius) + 1;\n const py1 = Math.ceil(cy + radius) + 1;\n\n if (!erase) {\n if (!this.ensureStrokeCovers(px0, py0, px1, py1, cached)) return;\n }\n const s = this.stroke;\n if (!s) return; // erasing with no active region\n\n const r2 = radius * radius;\n const iy0 = Math.max(s.by, py0);\n const iy1 = Math.min(s.by + s.bh, py1);\n const ix0 = Math.max(s.bx, px0);\n const ix1 = Math.min(s.bx + s.bw, px1);\n for (let iy = iy0; iy < iy1; iy++) {\n const dy = iy + 0.5 - cy;\n const row = (iy - s.by) * s.bw;\n for (let ix = ix0; ix < ix1; ix++) {\n const dx = ix + 0.5 - cx;\n if (dx * dx + dy * dy > r2) continue;\n s.mask[row + (ix - s.bx)] = erase ? 0 : 1;\n }\n }\n }\n\n /**\n * Ensure the accumulator's bbox covers [px0,py0,px1,py1) (clamped to the\n * image), allocating/copying a larger mask when it must grow. Returns false if\n * the requested box is empty after clamping.\n */\n private ensureStrokeCovers(\n px0: number, py0: number, px1: number, py1: number, cached: CachedImageData,\n ): boolean {\n const bx = Math.max(0, px0);\n const by = Math.max(0, py0);\n const bx1 = Math.min(cached.width, px1);\n const by1 = Math.min(cached.height, py1);\n const bw = bx1 - bx;\n const bh = by1 - by;\n if (bw <= 0 || bh <= 0) return false;\n\n if (!this.stroke) {\n this.stroke = { bx, by, bw, bh, mask: new Uint8Array(bw * bh) };\n return true;\n }\n const s = this.stroke;\n const nbx = Math.min(s.bx, bx);\n const nby = Math.min(s.by, by);\n const nbx1 = Math.max(s.bx + s.bw, bx1);\n const nby1 = Math.max(s.by + s.bh, by1);\n const nbw = nbx1 - nbx;\n const nbh = nby1 - nby;\n if (nbw === s.bw && nbh === s.bh && nbx === s.bx && nby === s.by) return true;\n\n const next = new Uint8Array(nbw * nbh);\n const dx = s.bx - nbx;\n const dy = s.by - nby;\n for (let row = 0; row < s.bh; row++) {\n const srcOff = row * s.bw;\n const dstOff = (row + dy) * nbw + dx;\n next.set(s.mask.subarray(srcOff, srcOff + s.bw), dstOff);\n }\n this.stroke = { bx: nbx, by: nby, bw: nbw, bh: nbh, mask: next };\n return true;\n }\n\n /** True if (matrixX, matrixY) lies inside the current stroke accumulator. */\n private pointInStroke(matrixX: number, matrixY: number): boolean {\n const s = this.stroke;\n if (!s) return false;\n const mx = Math.floor(matrixX) - s.bx;\n const my = Math.floor(matrixY) - s.by;\n if (mx < 0 || my < 0 || mx >= s.bw || my >= s.bh) return false;\n return s.mask[my * s.bw + mx] === 1;\n }\n\n /**\n * Remove the region(s) referenced by the stroke and reset it — used when an\n * erase stroke deletes every pixel.\n */\n private dropActiveShape(regions: Region[]) {\n const ids = [this.strokeRegionId, ...this.strokeExtraIds].filter((id): id is number => id != null);\n let changed = false;\n for (const id of ids) {\n const idx = regions.findIndex((r) => r.id === id);\n if (idx >= 0) { regions.splice(idx, 1); changed = true; }\n }\n if (changed) this.host.setRegions(regions);\n this.stroke = null;\n this.strokeRegionId = null;\n this.strokeExtraIds = [];\n }\n\n /** A region's closed-polygon vertices (image/data coords), or null when it\n * isn't a fillable closed polygon (rectangles, open polylines). */\n private regionVerts(\n region: Region,\n ): { xpoints: number[]; ypoints: number[]; holes?: number[][][] } | null {\n const b = region?.bounds;\n if (b instanceof Polygon && b.closed !== false && b.xpoints.length >= 3) {\n return { xpoints: b.xpoints, ypoints: b.ypoints, holes: b.holes };\n }\n return null;\n }\n\n /** Whether a region can be faithfully rasterized at this zoom (rx/ry = data units per matrix px).\n * Editing rasterizes + re-traces the region, so one whose matrix-space bbox exceeds the\n * rasterizer cap would come back rescaled/corrupted (e.g. a whole-slide annotation while zoomed\n * out) — skip adopt/merge for those and only edit them near native zoom (jit-ui#102). */\n private fitsForEdit(verts: { xpoints: number[]; ypoints: number[] }, rx: number, ry: number): boolean {\n const xs = verts.xpoints;\n const ys = verts.ypoints;\n let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;\n for (let i = 0; i < xs.length; i++) {\n if (xs[i] < minX) minX = xs[i];\n if (xs[i] > maxX) maxX = xs[i];\n if (ys[i] < minY) minY = ys[i];\n if (ys[i] > maxY) maxY = ys[i];\n }\n const w = (maxX - minX) / (rx || 1);\n const h = (maxY - minY) / (ry || 1);\n return w > 0 && h > 0 && w * h <= 4096 * 4096;\n }\n\n /** Convert a region's hole rings from image/data coords into matrix coords so\n * they line up with the stroke accumulator (jit-ui#85). */\n private holesToMatrix(\n holes: number[][][] | undefined, ox: number, oy: number, rx: number, ry: number,\n ): number[][][] | undefined {\n return holes?.map((ring) => ring.map(([x, y]) => [(x - ox) / rx, (y - oy) / ry]));\n }\n\n /**\n * If (matrixX, matrixY) falls inside an existing region, rasterize it into the\n * stroke accumulator so subsequent brush input extends it rather than starting\n * a new region.\n */\n private tryAdoptShapeAt(\n regions: Region[],\n matrixX: number,\n matrixY: number,\n rx: number,\n ry: number,\n cached: CachedImageData,\n ): boolean {\n if (!regions || regions.length === 0) return false;\n // Most-recently-added regions are on top — check them first.\n for (let i = regions.length - 1; i >= 0; i--) {\n const verts = this.regionVerts(regions[i]);\n if (!verts) continue;\n if (!this.fitsForEdit(verts, rx, ry)) continue; // too large at this zoom → don't adopt\n\n const ox = cached.originX ?? 0;\n const oy = cached.originY ?? 0;\n const xs = verts.xpoints.map((x) => (x - ox) / rx);\n const ys = verts.ypoints.map((y) => (y - oy) / ry);\n const holes = this.holesToMatrix(verts.holes, ox, oy, rx, ry);\n\n // Clicking inside a hole must NOT adopt the donut (it's empty there).\n if (!this.wandService.pointInPolygonWithHoles(matrixX, matrixY, xs, ys, holes)) continue;\n\n const raster = this.wandService.rasterizePolygon(xs, ys, cached.width, cached.height, holes);\n if (!raster) continue;\n\n this.stroke = raster;\n this.strokeRegionId = regions[i].id ?? null;\n return true;\n }\n return false;\n }\n\n /**\n * Fold every region whose rasterized mask overlaps the stroke mask into the\n * stroke and remove it from the list, so brushing across regions merges them.\n */\n private mergeOverlappingShapes(regions: Region[], rx: number, ry: number, cached: CachedImageData) {\n if (!this.stroke) return;\n let didMerge = true;\n while (didMerge) {\n didMerge = false;\n for (let i = regions.length - 1; i >= 0; i--) {\n const region = regions[i];\n if (region.id != null && region.id === this.strokeRegionId) continue;\n\n const verts = this.regionVerts(region);\n if (!verts) continue;\n if (!this.fitsForEdit(verts, rx, ry)) continue; // too large at this zoom → don't merge\n\n const ox = cached.originX ?? 0;\n const oy = cached.originY ?? 0;\n const xs = verts.xpoints.map((x) => (x - ox) / rx);\n const ys = verts.ypoints.map((y) => (y - oy) / ry);\n\n // Quick bbox reject before rasterizing.\n let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;\n for (let k = 0; k < xs.length; k++) {\n if (xs[k] < minX) minX = xs[k];\n if (xs[k] > maxX) maxX = xs[k];\n if (ys[k] < minY) minY = ys[k];\n if (ys[k] > maxY) maxY = ys[k];\n }\n const wx0 = this.stroke.bx, wy0 = this.stroke.by;\n const wx1 = wx0 + this.stroke.bw, wy1 = wy0 + this.stroke.bh;\n if (maxX < wx0 || minX > wx1 || maxY < wy0 || minY > wy1) continue;\n\n const holes = this.holesToMatrix(verts.holes, ox, oy, rx, ry);\n const raster = this.wandService.rasterizePolygon(xs, ys, cached.width, cached.height, holes);\n if (!raster) continue;\n if (!masksOverlap(this.stroke, raster)) continue;\n\n this.stroke = unionMasks(this.stroke, raster);\n if (this.strokeRegionId == null) {\n this.strokeRegionId = region.id ?? null;\n }\n regions.splice(i, 1);\n didMerge = true;\n break;\n }\n }\n }\n\n /**\n * Commit the stroke's connected pieces as regions — the largest keeps the\n * stroke's region identity, additional pieces (from an erase that split the\n * region) become their own regions tracked in `strokeExtraIds` so they keep\n * stable identities across drag ticks. The store mints ids on commit, which\n * we read back so subsequent ticks replace the same regions.\n */\n private commitComponents(\n regions: Region[],\n components: { xPlot: number[]; yPlot: number[]; holes?: number[][][] }[],\n ) {\n const valid = components.filter((c) => c.xPlot.length >= 3);\n if (valid.length === 0) return;\n\n const prevExtraIds = this.strokeExtraIds;\n // Drop previously-tracked extras that no longer have a matching piece (the\n // component count shrank, e.g. an add stroke bridged a gap).\n const reuseCount = Math.max(0, valid.length - 1);\n for (let k = reuseCount; k < prevExtraIds.length; k++) {\n const idx = regions.findIndex((r) => r.id === prevExtraIds[k]);\n if (idx >= 0) regions.splice(idx, 1);\n }\n\n const primary = this.upsertComponent(regions, this.strokeRegionId, valid[0]);\n const extras: Region[] = [];\n for (let i = 1; i < valid.length; i++) {\n extras.push(this.upsertComponent(regions, prevExtraIds[i - 1] ?? null, valid[i]));\n }\n\n this.host.setRegions(regions);\n // Ids are minted during setRegions — read them back for the next tick.\n this.strokeRegionId = primary.id ?? this.strokeRegionId;\n this.strokeExtraIds = extras\n .map((r) => r.id)\n .filter((id): id is number => id != null);\n }\n\n /**\n * Build a Region for one component and insert it into `regions`: replace the\n * region with `id` in place if it exists, otherwise append a new one. Returns\n * the Region instance (its id is minted later by the store when new).\n */\n private upsertComponent(\n regions: Region[], id: number | null,\n c: { xPlot: number[]; yPlot: number[]; holes?: number[][][] },\n ): Region {\n const existing = id != null ? regions.find((r) => r.id === id) : null;\n\n const poly = new Polygon();\n poly.npoints = c.xPlot.length;\n poly.xpoints = c.xPlot;\n poly.ypoints = c.yPlot;\n poly.coordinates = c.xPlot.map((x, i) => [x, c.yPlot[i]]);\n poly.closed = true;\n if (c.holes && c.holes.length) poly.holes = c.holes;\n\n const region = new Region();\n region.bounds = poly;\n region.color = this.host.getShapeColor();\n if (existing) {\n region.id = existing.id;\n region.name = existing.name;\n }\n // Default class/annotation name, matching the overlay-drawn regions and the\n // wand so a brush region isn't left unlabeled.\n region.label = existing?.label ?? 'Region';\n\n if (existing) {\n const idx = regions.findIndex((r) => r.id === id);\n if (idx >= 0) regions[idx] = region;\n else regions.push(region);\n } else {\n regions.push(region);\n }\n return region;\n }\n}\n","import { Injectable } from '@angular/core';\n\nimport { WandService } from '../wand/wand.service';\nimport { IViewportHost, IRegionDataHost } from '../../contracts/coordinate-transform.contract';\nimport { Region, Polygon } from '../../models/region';\n\n/**\n * Collaboration interface the vertex eraser needs from its host backend.\n *\n * Extends {@link IViewportHost} for coordinate conversion + overlay attachment,\n * so the eraser is backend-agnostic (Plotly and OpenSeadragon both satisfy it).\n */\nexport interface VertexEraserToolHost extends IViewportHost, IRegionDataHost {\n /**\n * Drop the wand's in-progress stroke. Called after the eraser modifies\n * regions — the wand's accumulator may now reference stale vertices.\n */\n invalidateWandRegion(): void;\n /**\n * Data-coords-per-image-pixel ratio (== cachedImageRatios[0] || 1). Used to\n * convert between matrix coordinates (the eraser's native space) and the\n * backend's data coordinates.\n */\n getCachedImageRatio(): number;\n}\n\n/**\n * Vertex eraser. A custom canvas overlay that, on click/drag, removes any\n * polygon vertex within `radius` matrix-pixels of the cursor from every\n * `type: 'path'` shape on the plot. Polygons that fall below 3 vertices\n * (or polylines below 2) are removed entirely.\n *\n * The cursor is rendered as a dashed-red circle on the overlay so the user\n * can see the active radius while moving.\n */\n@Injectable({ providedIn: 'root' })\nexport class VertexEraserToolService {\n\n private host!: VertexEraserToolHost;\n private overlay: HTMLCanvasElement | null = null;\n private dragging = false;\n /** Eraser radius in image-pixel (matrix) coordinates. */\n private radius = 20;\n private cursor: { x: number; y: number } | null = null;\n\n private readonly boundMouseDown: (e: MouseEvent) => void;\n private readonly boundMouseMove: (e: MouseEvent) => void;\n private readonly boundMouseUp: (e: MouseEvent) => void;\n\n constructor(private wandService: WandService) {\n this.boundMouseDown = (e) => this.onMouseDown(e);\n this.boundMouseMove = (e) => this.onMouseMove(e);\n this.boundMouseUp = (e) => this.onMouseUp(e);\n }\n\n bindHost(host: VertexEraserToolHost) {\n this.host = host;\n }\n\n // ── Public API ──────────────────────────────────────────────────────\n\n setMode(active: boolean) {\n if (active) {\n this.createOverlay();\n } else {\n this.destroyOverlay();\n }\n }\n\n /** Set eraser radius in matrix-pixel (image pixel) coordinates. */\n setRadius(radius: number) {\n if (!Number.isFinite(radius) || radius <= 0) return;\n this.radius = radius;\n this.drawCursor();\n }\n\n // ── Overlay lifecycle ───────────────────────────────────────────────\n\n private createOverlay() {\n const plotEl = this.host.getOverlayContainer();\n if (!plotEl || this.overlay) return;\n\n const canvas = document.createElement('canvas');\n canvas.style.position = 'absolute';\n canvas.style.top = '0';\n canvas.style.left = '0';\n canvas.style.width = '100%';\n canvas.style.height = '100%';\n canvas.style.cursor = 'crosshair';\n canvas.style.zIndex = '100';\n canvas.width = plotEl.offsetWidth;\n canvas.height = plotEl.offsetHeight;\n\n plotEl.appendChild(canvas);\n this.overlay = canvas;\n\n canvas.addEventListener('mousedown', this.boundMouseDown);\n canvas.addEventListener('mousemove', this.boundMouseMove);\n canvas.addEventListener('mouseup', this.boundMouseUp);\n canvas.addEventListener('mouseleave', this.boundMouseUp);\n }\n\n private destroyOverlay() {\n if (!this.overlay) return;\n this.overlay.removeEventListener('mousedown', this.boundMouseDown);\n this.overlay.removeEventListener('mousemove', this.boundMouseMove);\n this.overlay.removeEventListener('mouseup', this.boundMouseUp);\n this.overlay.removeEventListener('mouseleave', this.boundMouseUp);\n this.overlay.remove();\n this.overlay = null;\n this.dragging = false;\n this.cursor = null;\n }\n\n // ── Mouse handlers ──────────────────────────────────────────────────\n\n private onMouseDown(e: MouseEvent) {\n if (e.button !== 0) return;\n this.dragging = true;\n this.updateCursor(e);\n this.applyAtClient(e);\n }\n\n private onMouseMove(e: MouseEvent) {\n this.updateCursor(e);\n if (!this.dragging) {\n this.drawCursor();\n return;\n }\n if ((e.buttons & 1) === 0) {\n this.dragging = false;\n this.drawCursor();\n return;\n }\n this.applyAtClient(e);\n this.drawCursor();\n }\n\n private onMouseUp(_: MouseEvent) {\n this.dragging = false;\n }\n\n private updateCursor(e: MouseEvent) {\n if (!this.overlay) return;\n const rect = this.overlay.getBoundingClientRect();\n this.cursor = { x: e.clientX - rect.left, y: e.clientY - rect.top };\n }\n\n /** Draw the eraser radius circle at the current cursor position. */\n private drawCursor() {\n if (!this.overlay) return;\n const ctx = this.overlay.getContext('2d');\n if (!ctx) return;\n ctx.clearRect(0, 0, this.overlay.width, this.overlay.height);\n if (!this.cursor) return;\n const transform = this.host.getCoordinateTransform();\n if (!transform.isReady()) return;\n // Convert matrix-pixel radius to screen-pixel radius via the data scale.\n const rx = this.host.getCachedImageRatio();\n const screenRadius = transform.dataLengthToScreen(this.radius * rx);\n if (!Number.isFinite(screenRadius) || screenRadius <= 0) return;\n ctx.save();\n ctx.strokeStyle = 'rgba(255, 80, 80, 0.9)';\n ctx.lineWidth = 1.5;\n ctx.setLineDash([4, 3]);\n ctx.beginPath();\n ctx.arc(this.cursor.x, this.cursor.y, screenRadius, 0, Math.PI * 2);\n ctx.stroke();\n ctx.restore();\n }\n\n // ── Per-tick erase logic ────────────────────────────────────────────\n\n /**\n * Drop every vertex of every path-shape that lies within the eraser's\n * radius of the cursor. Polygons reduced below 3 vertices (or polylines\n * below 2) are removed entirely.\n */\n private applyAtClient(e: MouseEvent) {\n if (!this.overlay) return;\n const regions = this.host.getRegions();\n if (!regions || regions.length === 0) return;\n\n const transform = this.host.getCoordinateTransform();\n if (!transform.isReady()) return;\n const { x: dataX, y: dataY } = transform.clientToData(e.clientX, e.clientY);\n if (!Number.isFinite(dataX) || !Number.isFinite(dataY)) return;\n const rx = this.host.getCachedImageRatio();\n const cmx = dataX / rx;\n const cmy = dataY / rx;\n\n let anyChange = false;\n for (let i = regions.length - 1; i >= 0; i--) {\n const region = regions[i];\n const b = region?.bounds;\n if (!(b instanceof Polygon) || b.xpoints.length === 0) continue;\n const closed = b.closed !== false;\n const xs = b.xpoints.map(x => x / rx);\n const ys = b.ypoints.map(y => y / rx);\n\n const result = this.wandService.dropVerticesWithinRadius(xs, ys, cmx, cmy, this.radius);\n\n // Erase vertices on interior rings (a donut's inner outline) too, and drop\n // a hole that degenerates below a triangle (jit-ui#85).\n let holesChanged = false;\n let newHoles: number[][][] | undefined;\n if (b.holes) {\n newHoles = [];\n for (const ring of b.holes) {\n const hr = this.wandService.dropVerticesWithinRadius(\n ring.map(p => p[0] / rx), ring.map(p => p[1] / rx), cmx, cmy, this.radius);\n if (hr.removed === 0) {\n newHoles.push(ring); // untouched — keep as-is\n } else {\n holesChanged = true;\n if (hr.xpoints.length >= 3) {\n newHoles.push(hr.xpoints.map((x, k) => [x * rx, hr.ypoints[k] * rx]));\n } // else: hole collapsed — drop it\n }\n }\n if (newHoles.length === 0) newHoles = undefined;\n }\n\n if (result.removed === 0 && !holesChanged) continue;\n\n anyChange = true;\n const minVerts = closed ? 3 : 2;\n if (result.xpoints.length < minVerts) {\n // Region became degenerate — remove it.\n regions.splice(i, 1);\n continue;\n }\n\n // Rebuild the polygon in image/data coords. Drop any stored bezier\n // handles (the anchor count changed) — they re-derive from the new anchors.\n const xPlot = result.xpoints.map(x => x * rx);\n const yPlot = result.ypoints.map(y => y * rx);\n const poly = new Polygon();\n poly.npoints = xPlot.length;\n poly.xpoints = xPlot;\n poly.ypoints = yPlot;\n poly.coordinates = xPlot.map((x, k) => [x, yPlot[k]]);\n poly.closed = closed;\n poly.bezier = b.bezier;\n if (newHoles && newHoles.length) poly.holes = newHoles;\n\n const nr = new Region();\n nr.id = region.id;\n nr.name = region.name;\n nr.label = region.label;\n nr.color = region.color;\n nr.bounds = poly;\n regions[i] = nr;\n }\n\n if (!anyChange) return;\n // The wand's stroke mask becomes stale once we trim vertices off any\n // region — drop it so the next wand interaction re-adopts or restarts.\n this.host.invalidateWandRegion();\n this.host.setRegions(regions);\n }\n}\n","import { Injectable } from '@angular/core';\n\n/**\n * Collaboration interface the zoom-to-box tool needs from PlotlyService.\n */\nexport interface ZoomToBoxToolHost {\n /** DOM id of the plot element the overlay canvas attaches to. */\n getPlotDiv(): string;\n /**\n * Convert an overlay-pixel point (relative to the plot element's top-left)\n * into the backend's data coordinates — Plotly axis data for Plotly,\n * image-pixel coords for OpenSeadragon. Keeps the tool backend-agnostic.\n */\n pixelToData(px: number, py: number): { x: number; y: number };\n /**\n * Apply the user-selected zoom rectangle, ordered `[xMin, xMax, yMax, yMin]`.\n * The host decides what that means: Plotly does a high-def re-fetch / axis\n * relayout, OpenSeadragon fits the viewport to the image rectangle.\n */\n applyZoomToBox(coordinates: number[]): void;\n}\n\n/**\n * Custom canvas overlay for click-and-drag rectangular zoom. Plotly's\n * built-in `dragmode: 'zoom'` works on heatmap/image traces too, but it\n * doesn't drive the high-def zoom pipeline — this overlay does, by handing\n * the selected coordinates back to the host.\n */\n@Injectable({ providedIn: 'root' })\nexport class ZoomToBoxToolService {\n\n private host!: ZoomToBoxToolHost;\n private overlay: HTMLCanvasElement | null = null;\n private startPx: { x: number; y: number } | null = null;\n\n private readonly boundMouseDown: (e: MouseEvent) => void;\n private readonly boundMouseMove: (e: MouseEvent) => void;\n private readonly boundMouseUp: (e: MouseEvent) => void;\n\n constructor() {\n this.boundMouseDown = (e) => this.onMouseDown(e);\n this.boundMouseMove = (e) => this.onMouseMove(e);\n this.boundMouseUp = (e) => this.onMouseUp(e);\n }\n\n bindHost(host: ZoomToBoxToolHost) {\n this.host = host;\n }\n\n setMode(active: boolean) {\n if (active) {\n this.createOverlay();\n } else {\n this.destroyOverlay();\n }\n }\n\n // ── Overlay lifecycle ───────────────────────────────────────────────\n\n private createOverlay() {\n const plotEl = document.getElementById(this.host.getPlotDiv());\n if (!plotEl || this.overlay) return;\n\n const canvas = document.createElement('canvas');\n canvas.style.position = 'absolute';\n canvas.style.top = '0';\n canvas.style.left = '0';\n canvas.style.width = '100%';\n canvas.style.height = '100%';\n canvas.style.cursor = 'crosshair';\n canvas.style.zIndex = '100';\n canvas.width = plotEl.offsetWidth;\n canvas.height = plotEl.offsetHeight;\n\n plotEl.appendChild(canvas);\n this.overlay = canvas;\n\n canvas.addEventListener('mousedown', this.boundMouseDown);\n canvas.addEventListener('mousemove', this.boundMouseMove);\n canvas.addEventListener('mouseup', this.boundMouseUp);\n canvas.addEventListener('mouseleave', this.boundMouseUp);\n }\n\n private destroyOverlay() {\n if (!this.overlay) return;\n this.overlay.removeEventListener('mousedown', this.boundMouseDown);\n this.overlay.removeEventListener('mousemove', this.boundMouseMove);\n this.overlay.removeEventListener('mouseup', this.boundMouseUp);\n this.overlay.removeEventListener('mouseleave', this.boundMouseUp);\n this.overlay.remove();\n this.overlay = null;\n this.startPx = null;\n }\n\n // ── Mouse handlers ──────────────────────────────────────────────────\n\n private onMouseDown(e: MouseEvent) {\n const rect = this.overlay!.getBoundingClientRect();\n this.startPx = { x: e.clientX - rect.left, y: e.clientY - rect.top };\n }\n\n private onMouseMove(e: MouseEvent) {\n if (!this.startPx || !this.overlay) return;\n const rect = this.overlay.getBoundingClientRect();\n this.drawSelection(\n this.startPx.x, this.startPx.y,\n e.clientX - rect.left, e.clientY - rect.top\n );\n }\n\n private onMouseUp(e: MouseEvent) {\n if (!this.startPx || !this.overlay) return;\n const rect = this.overlay.getBoundingClientRect();\n const endX = e.clientX - rect.left;\n const endY = e.clientY - rect.top;\n\n // Ignore tiny drags (accidental clicks).\n if (Math.abs(endX - this.startPx.x) < 5 || Math.abs(endY - this.startPx.y) < 5) {\n this.startPx = null;\n this.clearCanvas();\n return;\n }\n\n // Convert overlay-pixel → data coordinates via the active backend's host.\n const d0 = this.host.pixelToData(this.startPx.x, this.startPx.y);\n const d1 = this.host.pixelToData(endX, endY);\n\n const coordinates = [\n Math.min(d0.x, d1.x), Math.max(d0.x, d1.x),\n Math.max(d0.y, d1.y), Math.min(d0.y, d1.y),\n ];\n\n this.startPx = null;\n this.clearCanvas();\n\n this.host.applyZoomToBox(coordinates);\n }\n\n // ── Selection rectangle drawing ─────────────────────────────────────\n\n private drawSelection(x0: number, y0: number, x1: number, y1: number) {\n const canvas = this.overlay!;\n const ctx = canvas.getContext('2d')!;\n\n const left = Math.min(x0, x1);\n const top = Math.min(y0, y1);\n const w = Math.abs(x1 - x0);\n const h = Math.abs(y1 - y0);\n\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n // Semi-transparent overlay covering everything outside the selection.\n ctx.save();\n ctx.fillStyle = 'rgba(0, 0, 0, 0.35)';\n ctx.beginPath();\n // Outer rectangle (full canvas).\n ctx.rect(0, 0, canvas.width, canvas.height);\n // Inner rectangle (selection cutout) — wound counter-clockwise to create a hole.\n ctx.moveTo(left, top);\n ctx.lineTo(left, top + h);\n ctx.lineTo(left + w, top + h);\n ctx.lineTo(left + w, top);\n ctx.closePath();\n ctx.fill('evenodd');\n ctx.restore();\n\n // Corner notches.\n const notchLen = Math.min(16, w / 4, h / 4);\n ctx.save();\n ctx.strokeStyle = 'rgba(255, 255, 255, 0.9)';\n ctx.lineWidth = 2;\n ctx.beginPath();\n // Top-left.\n ctx.moveTo(left, top + notchLen);\n ctx.lineTo(left, top);\n ctx.lineTo(left + notchLen, top);\n // Top-right.\n ctx.moveTo(left + w - notchLen, top);\n ctx.lineTo(left + w, top);\n ctx.lineTo(left + w, top + notchLen);\n // Bottom-right.\n ctx.moveTo(left + w, top + h - notchLen);\n ctx.lineTo(left + w, top + h);\n ctx.lineTo(left + w - notchLen, top + h);\n // Bottom-left.\n ctx.moveTo(left + notchLen, top + h);\n ctx.lineTo(left, top + h);\n ctx.lineTo(left, top + h - notchLen);\n ctx.stroke();\n ctx.restore();\n }\n\n private clearCanvas() {\n if (!this.overlay) return;\n const ctx = this.overlay.getContext('2d');\n if (ctx) ctx.clearRect(0, 0, this.overlay.width, this.overlay.height);\n }\n}\n","import { IHistogram } from './channel-histogram-api.contract';\n\n/**\n * Shared intensity helpers (refactoring plan, Step 5). The two backends use\n * two DIFFERENT scalar projections by design — do not unify them:\n * - Plotly projects `[r,g,b]` frame cells with ITU-R BT.601 luminance (matches\n * what its heatmap has always rendered);\n * - the OSD tile path takes the max of the decoded RGBA channels (single-band\n * tiles encode gray as r=g=b, so max is exact; it also tolerates tinted\n * pixels).\n */\n\n/** ITU-R BT.601 luminance for an RGB pixel (Plotly's scalar projection). */\nexport function bt601Luminance(r: number, g: number, b: number): number {\n return 0.299 * r + 0.587 * g + 0.114 * b;\n}\n\n/** Max of the three channels (the OSD tile path's scalar projection).\n * NOTE: the per-pixel recolor loop in `osd/display-pipeline.ts` keeps this\n * inlined on purpose — it runs ~262k times per tile. */\nexport function maxRgb(r: number, g: number, b: number): number {\n return r >= g ? (r >= b ? r : b) : g >= b ? g : b;\n}\n\n/** Wrap 256 raw bin counts as an IHistogram (0..255 left edges + max). */\nexport function histogram256(counts: number[]): IHistogram {\n return {\n bins: Array.from({ length: 256 }, (_, i) => i),\n counts,\n max: counts.reduce((m, c) => (c > m ? c : m), 0),\n };\n}\n","import { PlotType } from '../../contracts/plot-type';\nimport { bt601Luminance } from '../../contracts/intensity';\n\n/**\n * Pluggable Plotly trace builders for the plot types added on top of the\n * original HEATMAP / SURFACE / RGB-image renderers.\n *\n * DESIGN / EXTRACTION ALIGNMENT\n * -----------------------------\n * Every function here is **pure** — it takes a `TraceBuildInput` and returns\n * Plotly trace dicts. There is no Angular, no RxJS, no host-state coupling\n * (`MainState`, `FilesService`, …). That keeps the module relocatable into the\n * future `@jax-data-science/image-visualization` library core (see the\n * `sketch/jit-plotting-extraction` SOW) without port surgery.\n *\n * Layout building stays in `PlotlyService` (it needs live service state such\n * as screen height, scale ratio and the current shapes); only TRACE building\n * is pluggable here. To add a new plot type: write a builder, register it in\n * `PLOTLY_PLOT_TYPE_IMPLS`, and add a descriptor in `contracts/plot-type.ts`.\n *\n * The original HEATMAP/SURFACE/RGB types intentionally keep their dedicated\n * renderers in `PlotlyService` (they are also reused by the high-def zoom\n * re-fetch path), so they are NOT registered here.\n */\n\n/** Normalised input for a trace builder. Frames are per-z-plane matrices:\n * grayscale cells are scalars, RGB cells are `[r, g, b]`. */\nexport interface TraceBuildInput {\n frames: any[];\n width: number;\n height: number;\n /** [xRatio, yRatio] — data units per pixel. */\n ratios: number[];\n /** [x0, x1, y0, y1] — true image extent in data units. */\n trueImageSize: number[];\n isGrayscale: boolean;\n /** Plotly colorscale value (e.g. from the active colormap). */\n colorscale: any;\n reversescale: boolean;\n /** Region polygons in data coords, for region-sourced plots (SCATTER). */\n regions: { xpoints: number[]; ypoints: number[] }[];\n /** Default marker/line colour for derived (non-image-LUT) traces. */\n shapeColor: string;\n /** ISOSURFACE intensity bounds (0–255): surfaces are drawn for values in\n * [isoMin, isoMax], mapped straight onto Plotly's isomin/isomax. */\n isoMin: number;\n isoMax: number;\n}\n\nexport type TraceBuilder = (input: TraceBuildInput) => any[];\n\nexport type PlotLayoutKind = '2d-image' | '2d-overlay' | '2d-chart' | '3d-volume';\n\nexport interface PlotlyPlotTypeImpl {\n buildTraces: TraceBuilder;\n /** Which layout `PlotlyService` should build for this type. */\n layoutKind: PlotLayoutKind;\n /** True for scene-based (3D) traces — picks the 3D Plotly config. */\n threeD: boolean;\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────\n\n/** Scalar value of a frame cell: `[r, g, b]` → BT.601 luminance, scalar as-is. */\nfunction luminance(cell: any): number {\n if (Array.isArray(cell)) {\n return bt601Luminance(cell[0], cell[1], cell[2]);\n }\n return cell as number;\n}\n\n/** Project a frame to a scalar matrix (RGB → luminance, grayscale → as-is). */\nfunction toScalarFrame(frame: any[], isGrayscale: boolean): number[][] {\n if (isGrayscale) return frame as number[][];\n return frame.map((row: any[]) => row.map(luminance));\n}\n\n/** Even stride that keeps an axis under `maxSamples` sample points. */\nfunction strideFor(length: number, maxSamples: number): number {\n return Math.max(1, Math.ceil(length / maxSamples));\n}\n\n// ── builders ─────────────────────────────────────────────────────────────\n\n/** Max cells per axis the contour grid is downsampled to. The heatmap trace can\n * raster the full preview cheaply, but contour runs CPU marching-squares over\n * every cell, so a full-resolution preview (~1000²) costs seconds. Contours\n * interpolate, so a coarser grid looks the same while rendering near-instantly. */\nconst CONTOUR_MAX_SAMPLES = 400;\n\n/** Every `sx`-th column / `sy`-th row of a scalar matrix. */\nfunction downsampleMatrix(matrix: number[][], sx: number, sy: number): number[][] {\n if (sx <= 1 && sy <= 1) return matrix;\n const out: number[][] = [];\n for (let r = 0; r < matrix.length; r += sy) {\n const row = matrix[r];\n if (sx <= 1) { out.push(row); continue; }\n const sampled: number[] = [];\n for (let c = 0; c < row.length; c += sx) sampled.push(row[c]);\n out.push(sampled);\n }\n return out;\n}\n\n/** CONTOUR — per-frame iso-contours over a downsampled scalar matrix. Mirrors\n * the heatmap trace geometry (x0/dx/y0/dy) so it lines up with the image axes;\n * the stride scales dx/dy so the coarser grid still spans the true extent. */\nfunction buildContourTraces(input: TraceBuildInput): any[] {\n const [x0, , y0] = [input.trueImageSize[0], input.trueImageSize[1], input.trueImageSize[2]];\n return input.frames.map((frame, index) => {\n const scalar = toScalarFrame(frame, input.isGrayscale);\n const height = scalar.length;\n const width = height > 0 ? scalar[0].length : 0;\n const sx = strideFor(width, CONTOUR_MAX_SAMPLES);\n const sy = strideFor(height, CONTOUR_MAX_SAMPLES);\n return {\n x0,\n dx: input.ratios[0] * sx,\n y0,\n dy: input.ratios[0] * sy,\n z: downsampleMatrix(scalar, sx, sy),\n type: 'contour',\n hoverinfo: 'none',\n colorscale: input.colorscale,\n reversescale: input.reversescale,\n contours: { coloring: 'heatmap' },\n // Cap the level count so it doesn't scale with the (now coarser) grid.\n ncontours: 15,\n name: `Slice ${index + 1}`,\n visible: index === 0,\n };\n });\n}\n\n/** SCATTER — region centroids as labelled markers (region-sourced). */\nfunction buildScatterTraces(input: TraceBuildInput): any[] {\n const xs: number[] = [];\n const ys: number[] = [];\n const text: string[] = [];\n input.regions.forEach((poly, i) => {\n const n = poly.xpoints.length;\n if (n === 0) return;\n const cx = poly.xpoints.reduce((a, b) => a + b, 0) / n;\n const cy = poly.ypoints.reduce((a, b) => a + b, 0) / n;\n xs.push(cx);\n ys.push(cy);\n text.push(`R${i + 1}`);\n });\n return [{\n x: xs,\n y: ys,\n text,\n type: 'scatter',\n mode: 'markers+text',\n textposition: 'top center',\n marker: { size: 10, color: input.shapeColor, line: { color: '#000', width: 1 } },\n name: 'Region centroids',\n }];\n}\n\n/**\n * Collect a downsampled regular grid of voxels across the z-stack.\n * Returns parallel flat arrays suitable for both scatter3d and isosurface.\n * A single-frame image is thickened to two z-planes so 3D traces render.\n */\nfunction sampleVolume(input: TraceBuildInput, maxXY: number, maxZ: number) {\n let frames = input.frames.map(f => toScalarFrame(f, input.isGrayscale));\n if (frames.length < 2) frames = [frames[0] || [], frames[0] || []];\n\n const height = frames[0].length;\n const width = height > 0 ? frames[0][0].length : 0;\n const sx = strideFor(width, maxXY);\n const sy = strideFor(height, maxXY);\n const sz = strideFor(frames.length, maxZ);\n\n const x: number[] = [];\n const y: number[] = [];\n const z: number[] = [];\n const value: number[] = [];\n for (let zi = 0; zi < frames.length; zi += sz) {\n for (let yi = 0; yi < height; yi += sy) {\n const rowArr = frames[zi][yi] || [];\n for (let xi = 0; xi < width; xi += sx) {\n x.push(xi * input.ratios[0]);\n y.push(yi * input.ratios[0]);\n z.push(zi);\n value.push(rowArr[xi]);\n }\n }\n }\n return { x, y, z, value };\n}\n\n/** SCATTER3D — downsampled voxels as intensity-coloured 3D markers. */\nfunction buildScatter3dTraces(input: TraceBuildInput): any[] {\n const { x, y, z, value } = sampleVolume(input, 48, 40);\n return [{\n type: 'scatter3d',\n mode: 'markers',\n x, y, z,\n marker: {\n size: 2,\n color: value,\n colorscale: input.colorscale,\n reversescale: input.reversescale,\n opacity: 0.8,\n },\n name: 'Voxels',\n }];\n}\n\n/** ISOSURFACE — iso-intensity surfaces over the downsampled volume grid.\n * isomin/isomax come straight from the toolbar range slider (0–255). */\nfunction buildIsosurfaceTraces(input: TraceBuildInput): any[] {\n const { x, y, z, value } = sampleVolume(input, 40, 40);\n // The caller (PlotlyService) maps the 0–255 slider onto the volume's real\n // intensity range before this runs, so the band always sits inside the data.\n // We only guard ordering here.\n const isoMin = Math.min(input.isoMin, input.isoMax);\n const isoMax = Math.max(input.isoMin, input.isoMax);\n return [{\n type: 'isosurface',\n x, y, z, value,\n isomin: isoMin,\n isomax: isoMax,\n // A few nested levels (not just the two band extremes): even if an extreme\n // grazes the data edge and draws nothing, an interior level still renders,\n // so the volume is never silently empty.\n surface: { count: 3 },\n colorscale: input.colorscale,\n reversescale: input.reversescale,\n opacity: 0.6,\n caps: { x: { show: false }, y: { show: false }, z: { show: false } },\n name: 'Isosurface',\n }];\n}\n\n/** Registry of the pluggable (non-original) plot types. */\nexport const PLOTLY_PLOT_TYPE_IMPLS: Partial<Record<PlotType, PlotlyPlotTypeImpl>> = {\n [PlotType.CONTOUR]: { buildTraces: buildContourTraces, layoutKind: '2d-image', threeD: false },\n [PlotType.SCATTER]: { buildTraces: buildScatterTraces, layoutKind: '2d-overlay', threeD: false },\n [PlotType.SCATTER3D]: { buildTraces: buildScatter3dTraces, layoutKind: '3d-volume', threeD: true },\n [PlotType.ISOSURFACE]: { buildTraces: buildIsosurfaceTraces, layoutKind: '3d-volume', threeD: true },\n};\n\nexport function getPlotTypeImpl(type: PlotType): PlotlyPlotTypeImpl | undefined {\n return PLOTLY_PLOT_TYPE_IMPLS[type];\n}\n","import { PlotlyService } from './plotly.service';\nimport { IRegionOverlay, RegionToolMode } from '../../contracts/region-overlay.contract';\n\n/**\n * Plotly implementation of {@link IRegionOverlay}.\n *\n * Plotly renders region shapes natively in its plot layout and edits them via\n * its own drag modes, so this adapter is thin: it maps the neutral\n * {@link RegionToolMode} onto Plotly drag modes and lets Plotly draw. `redraw`\n * is a no-op because Plotly re-renders its shapes itself on relayout.\n *\n * It is the symmetric counterpart to {@link OsdRegionOverlay}: both render the\n * same shared `IRegionStore`, each onto its own backend's canvas.\n */\nexport class PlotlyRegionOverlay implements IRegionOverlay {\n\n constructor(private plotly: PlotlyService) {}\n\n setMode(mode: RegionToolMode): void {\n // 'select' is a neutral mode for Plotly (no drag mode); region selection is\n // driven by the table / active-shape sampling, so just clear the drag mode.\n const dragMode =\n mode === 'drawrect' ? 'drawrect' :\n mode === 'drawclosedpath' ? 'drawclosedpath' :\n mode === 'drawopenpath' ? 'drawopenpath' :\n false;\n this.plotly.setDragMode(dragMode);\n }\n\n redraw(): void { /* Plotly re-renders its shapes natively on relayout */ }\n\n /** Bezier regions are an OpenSeadragon-only feature (Plotly has no native\n * curved-shape rendering), so this is a no-op here. */\n setSelectedBezier(_bezier: boolean): void { /* OSD-only */ }\n\n destroy(): void { /* nothing to tear down — shapes live in the Plotly layout */ }\n}\n","import { ICoordinateTransform } from '../../contracts/coordinate-transform.contract';\n\n/**\n * Plotly implementation of {@link ICoordinateTransform}. Wraps the axis objects\n * on the plot's `_fullLayout`. This is the exact math the wand / vertex-eraser\n * used inline before they were decoupled — lifted here verbatim so Plotly\n * behaviour is unchanged.\n */\nexport class PlotlyCoordinateTransform implements ICoordinateTransform {\n\n constructor(\n private getGraphDiv: () => any,\n private getContainer: () => HTMLElement | null,\n ) {}\n\n private axes(): { xaxis: any; yaxis: any } {\n const layout = this.getGraphDiv()?._fullLayout;\n return { xaxis: layout?.xaxis, yaxis: layout?.yaxis };\n }\n\n isReady(): boolean {\n const { xaxis, yaxis } = this.axes();\n return !!(xaxis && yaxis);\n }\n\n clientToData(clientX: number, clientY: number): { x: number; y: number } {\n const { xaxis, yaxis } = this.axes();\n const rect = this.getContainer()?.getBoundingClientRect();\n if (!xaxis || !yaxis || !rect) return { x: NaN, y: NaN };\n return {\n x: xaxis.p2d(clientX - rect.left - xaxis._offset),\n y: yaxis.p2d(clientY - rect.top - yaxis._offset),\n };\n }\n\n dataLengthToScreen(dataLength: number): number {\n const { xaxis } = this.axes();\n if (!xaxis) return 0;\n return Math.abs(xaxis.l2p(dataLength) - xaxis.l2p(0));\n }\n}\n","import { Injectable } from '@angular/core';\nimport { BehaviorSubject, Observable, Subject } from 'rxjs';\n\nimport { IImageInfo } from '../contracts/image.contract';\nimport { Region, Rectangle, Polygon, MultiPolygon } from '../models/region';\nimport { PlotUtilities } from '../plot.utilities';\nimport { VisualizerStore } from './visualizer-store.service';\nimport { defaultHandleOffsets } from '../models/bezier';\nimport { IRegionStore } from '../contracts/visualizer.contract';\nimport { IRegionEditApi } from '../contracts/region-store.contract';\nimport { findPreset, fallbackColorFor } from './class-color.util';\n\n/**\n * Backend-neutral region store — the single source of truth for region state.\n *\n * Holds the neutral {@link Region} model (never a backend's own shape\n * representation), keyed per image so regions persist as the user switches\n * files and survive a Plotly⇄OpenSeadragon backend switch (both backends read\n * and write *this* store, so no migration is needed). Backends own *rendering*\n * and react to {@link getRegionUpdateEvent}; this service owns *state* and the\n * editing operations.\n *\n * Implements:\n * - {@link IRegionStore} — the cross-backend CRUD/selection/colour contract\n * every consumer (Region Editor, segmentation, etc.) already uses.\n * - {@link IRegionEditApi} — Region-native geometry edits (move/resize, and\n * add/delete/move vertex) the OSD overlay drives.\n *\n * Classification colours live in {@link VisualizerStore} (shared by both\n * backends); GeoJSON import/export and the closed-polygon projection reuse the\n * neutral {@link PlotUtilities} helpers. All coordinates are image pixels.\n */\n@Injectable({ providedIn: 'root' })\nexport class RegionStore implements IRegionStore, IRegionEditApi {\n\n private static readonly UNDO_LIMIT = 10;\n private static readonly UNDO_COALESCE_MS = 250;\n\n /** Per-image region cache. `regions` is always a snapshot of the entry for\n * `currentImageKey`. */\n private regionsByImageKey = new Map<string, Region[]>();\n private currentImageKey: string | undefined;\n /** The current image's regions — the live, edited array. */\n private regions: Region[] = [];\n /** Last saved snapshot, restorable via plotPreviousShapes(). */\n private previousRegions: Region[] = [];\n\n /**\n * Undo/redo history (jit-ui#85): up to {@link UNDO_LIMIT} snapshots of the\n * region set, each a deep clone captured immediately *before* a\n * region-editing action. {@link undo} pops the newest off `undoStack`, pushes\n * the current state onto `redoStack`, and restores it — so it can be invoked\n * up to {@link UNDO_LIMIT} times in a row. {@link redo} is the mirror. Any new\n * region action clears `redoStack` (the redo future is no longer reachable).\n *\n * A continuous gesture (a wand/brush/vertex drag commits to the store many\n * times) is coalesced into a single entry: the first commit of a burst\n * captures the pre-burst state and every commit within\n * {@link UNDO_COALESCE_MS} of the previous one is folded into it. History\n * never crosses an image load/switch — {@link resetUndoHistory} clears it.\n */\n private undoStack: Region[][] = [];\n private redoStack: Region[][] = [];\n /** True while a coalescing burst is open (further commits fold into it). */\n private undoBurstOpen = false;\n private undoBurstTimer: ReturnType<typeof setTimeout> | null = null;\n /** True while restoring a snapshot, so the restore records no new history. */\n private restoringUndo = false;\n private readonly canUndo$ = new BehaviorSubject<boolean>(false);\n private readonly canRedo$ = new BehaviorSubject<boolean>(false);\n\n /** Monotonic id source — ids never repeat within the service lifetime, so\n * selection stays correct across delete/add cycles even when names collide. */\n private nextId = 1;\n\n private showShapeLabel = false;\n private shapeColor = '#00FFFF';\n private fillColor = '#ff00ff';\n private isRegionSavedOn = true;\n\n /**\n * Per-slice region support for z-stacks (jit-ui#93). While {@link stackMode}\n * is on (a z-stack is loaded), the live `regions` array always holds ONE\n * slice — the {@link currentSliceZ} slice — so the on-canvas overlays, the\n * selection projection, and the Regions table keep working unchanged\n * (they all read {@link getRegions}). The other slices live in\n * {@link regionsBySlice}; {@link setDisplaySlice} swaps the live set on scrub\n * and {@link getSliceRegions} flattens every slice (each tagged with its\n * zero-based {@link Region.z}) for save/export. Off by default (stackMode\n * false, z 0), so single-plane images are completely unaffected.\n */\n private regionsBySlice = new Map<number, Region[]>();\n private stackMode = false;\n private currentSliceZ = 0;\n /** How a stack's regions round-trip to disk (jit-ui#93): `combined` writes one\n * z-indexed geojson (single-file z-stack, QuPath schema); `per-slice-file`\n * writes one geojson per slice-file (a folder of numbered images). */\n private stackSaveLayout: 'combined' | 'per-slice-file' = 'combined';\n /** Slices that were loaded with regions (jit-ui#93). A per-slice-file save\n * re-writes these even when now empty, so clearing a slice's regions and\n * saving removes its previously-saved geojson (writes an empty one). */\n private stackInitialNonEmpty = new Set<number>();\n\n /** Selection is tracked by region *id* internally (stable across edits) and\n * projected to array indices on the IRegionStore boundary. */\n private selectedIds: number[] = [];\n private readonly selectedIndices$ = new BehaviorSubject<number[]>([]);\n private readonly regionUpdate$ = new Subject<Region[]>();\n /** Non-coalesced sibling of regionUpdate$: fires on every change even during a\n * batched drag, so live consumers (intensity inset) update per frame. */\n private readonly regionLiveEdit$ = new Subject<Region[]>();\n\n /** Emit coalescing for live drags (see IRegionEditApi.beginBatch). */\n private batchDepth = 0;\n private pendingEmit = false;\n\n private readonly plotUtilities = new PlotUtilities();\n\n constructor(private store: VisualizerStore) {}\n\n // ── IRegionStore: CRUD ─────────────────────────────────────────────────\n\n /**\n * Replace (or, with `append`, add to) the current image's regions. Mints ids\n * and default names, applies stored classification colours, and emits. When\n * `isRegionSaveOn` is false the regions are shown transiently (emitted) but\n * not stored — mirrors the previous Plotly behaviour.\n */\n setRegions(regions: Region[], showRegionLabel?: boolean, isRegionSaveOn?: boolean,\n fillColor?: string, append: boolean = false): void {\n if (showRegionLabel === undefined) showRegionLabel = this.showShapeLabel;\n if (isRegionSaveOn === undefined) isRegionSaveOn = this.isRegionSavedOn;\n if (fillColor === undefined) fillColor = this.fillColor;\n\n for (const region of regions) {\n if (region.id == null) region.id = this.nextId++;\n if (region.name == null) region.name = `shape${region.id}`;\n }\n this.applyClassificationColors(regions);\n\n this.isRegionSavedOn = isRegionSaveOn;\n if (isRegionSaveOn) {\n this.recordUndoSnapshot();\n this.showShapeLabel = showRegionLabel;\n this.fillColor = fillColor;\n if (append) {\n // Reject by id collision (already tracked) or geometry equality (same\n // coordinates) — the find button can push the same region repeatedly.\n const added = regions.filter(r =>\n !this.regions.some(existing => existing.id === r.id || this.regionsEqual(existing, r)));\n this.regions = this.regions.concat(added);\n } else {\n this.regions = regions.slice();\n }\n this.syncCache();\n this.emitSelection();\n this.emit();\n } else {\n // Transient display only — don't touch stored state.\n this.regionUpdate$.next(regions.slice());\n }\n }\n\n /** The canonical accessor: current image's regions (live instances). */\n getRegions(): Region[] {\n return this.regions.slice();\n }\n\n // ── Per-slice regions for z-stacks (jit-ui#93) ─────────────────────────\n\n /** True while a z-stack is loaded and the store holds regions per slice. */\n isStackMode(): boolean { return this.stackMode; }\n\n /** The current display slice (zero-based). */\n getDisplaySlice(): number { return this.currentSliceZ; }\n\n /** How the current stack persists to disk (jit-ui#93): `combined` = one\n * z-indexed geojson (single-file z-stack); `per-slice-file` = one geojson per\n * slice-file (folder stack). Meaningless outside stack mode. */\n getStackSaveLayout(): 'combined' | 'per-slice-file' { return this.stackSaveLayout; }\n\n /**\n * Enter per-slice stack mode. `slices` maps each zero-based slice index to\n * the regions imported for that slice; the store makes `initialZ`'s slice the\n * live set, so the overlays / selection / Regions table are unchanged (they\n * still read {@link getRegions}). Freshly-created regions are tagged with the\n * current slice so they persist on it, and {@link getSliceRegions} returns\n * every slice for save/export. Ids/names/classification colours are minted\n * exactly as {@link setRegions} does.\n */\n enterStackMode(slices: Map<number, Region[]>, initialZ = 0,\n saveLayout: 'combined' | 'per-slice-file' = 'combined'): void {\n this.stackMode = true;\n this.stackSaveLayout = saveLayout;\n this.currentSliceZ = initialZ || 0;\n this.regionsBySlice = new Map<number, Region[]>();\n this.stackInitialNonEmpty = new Set<number>();\n for (const [z, regs] of slices) {\n const normalized = this.normalizeSlice(regs || [], z);\n this.regionsBySlice.set(z, normalized);\n if (normalized.length) this.stackInitialNonEmpty.add(z);\n }\n this.regions = (this.regionsBySlice.get(this.currentSliceZ) ?? []).slice();\n this.previousRegions = this.regions.slice();\n this.selectedIds = [];\n this.syncCache();\n this.resetUndoHistory();\n this.emitSelection();\n this.emit();\n }\n\n /** Leave stack mode (single-plane image, or the stack was closed). */\n exitStackMode(): void {\n if (!this.stackMode) return;\n this.stackMode = false;\n this.currentSliceZ = 0;\n this.regionsBySlice = new Map<number, Region[]>();\n this.stackInitialNonEmpty = new Set<number>();\n }\n\n /**\n * Show a different slice: capture the current slice's (possibly edited)\n * regions back into the per-slice store, then load the target slice's regions\n * as the live set and emit. Undo never crosses a slice. Outside stack mode\n * this only records the requested slice index (a no-op otherwise: single-plane\n * regions stay on the default plane — addRegion tags Region.z only in stack\n * mode, so the recorded index is unused until a stack is entered). (jit-ui#93)\n */\n setDisplaySlice(z: number): void {\n const next = z || 0;\n if (!this.stackMode) { this.currentSliceZ = next; return; }\n if (this.currentSliceZ === next) return;\n this.regionsBySlice.set(this.currentSliceZ, this.regions.slice());\n this.currentSliceZ = next;\n this.regions = (this.regionsBySlice.get(next) ?? []).slice();\n this.previousRegions = this.regions.slice();\n this.selectedIds = [];\n this.syncCache();\n this.resetUndoHistory();\n this.emitSelection();\n this.emit();\n }\n\n /**\n * Every slice's regions for save/export, each tagged with its zero-based\n * slice index in {@link Region.z}. Captures the current slice's live edits\n * first. Returns the flat single-plane set when not in stack mode. (jit-ui#93)\n */\n getSliceRegions(): Region[] {\n if (!this.stackMode) return this.regions.slice();\n this.regionsBySlice.set(this.currentSliceZ, this.regions.slice());\n const out: Region[] = [];\n const zs = Array.from(this.regionsBySlice.keys()).sort((a, b) => a - b);\n for (const z of zs) {\n for (const r of this.regionsBySlice.get(z) as Region[]) {\n r.z = z;\n out.push(r);\n }\n }\n return out;\n }\n\n /**\n * Slices to write on a per-slice-file save (folder stack, jit-ui#93): every\n * slice that currently has regions, PLUS slices that were loaded non-empty but\n * are now empty (so their file is re-written empty, clearing a slice whose\n * regions the user deleted). Each returned region is tagged with its z, and\n * the current live slice is captured first. Empty outside stack mode.\n */\n getStackSaveSlices(): Map<number, Region[]> {\n const out = new Map<number, Region[]>();\n if (!this.stackMode) return out;\n this.regionsBySlice.set(this.currentSliceZ, this.regions.slice());\n const zs = new Set<number>(this.stackInitialNonEmpty);\n for (const [z, regs] of this.regionsBySlice) if (regs.length) zs.add(z);\n for (const z of Array.from(zs).sort((a, b) => a - b)) {\n const regs = (this.regionsBySlice.get(z) ?? []).map((r) => { r.z = z; return r; });\n out.set(z, regs);\n }\n return out;\n }\n\n /** Mint ids/names + apply classification colours + tag the slice index, as\n * {@link setRegions} does, for regions entering the per-slice store. */\n private normalizeSlice(regions: Region[], z: number): Region[] {\n for (const region of regions) {\n if (region.id == null) region.id = this.nextId++;\n if (region.name == null) region.name = `shape${region.id}`;\n region.z = z;\n }\n this.applyClassificationColors(regions);\n return regions.slice();\n }\n\n /**\n * Closed polygons projected for image-processing consumers (segmentation,\n * trace builders). Open polylines are annotation-only and excluded. Reuses\n * the neutral PlotUtilities projection so output matches the previous path.\n */\n getRegionPolygons(): any[] {\n const ret: any[] = [];\n for (const region of this.regions) {\n const poly: any = this.plotUtilities.getPolygon({ ...region.getShape(this.showShapeLabel) });\n if (poly == null || poly.closed === false) continue;\n ret.push(poly);\n }\n return ret;\n }\n\n getRegionUpdateEvent(): Observable<any[]> {\n return this.regionUpdate$.asObservable();\n }\n\n /** Live (non-coalesced) region-change stream — fires per frame during a drag.\n * Used by the intensity-profile inset so it tracks line ROIs live. */\n getRegionLiveEdit$(): Observable<Region[]> {\n return this.regionLiveEdit$.asObservable();\n }\n\n // ── IRegionStore: selection ────────────────────────────────────────────\n\n /** Select regions by array index (or [] to clear). Stored internally by id\n * so the selection survives subsequent edits/reorders. */\n setSelectedShapeIndices(indices: number[]): void {\n const ids: number[] = [];\n const seen = new Set<number>();\n for (const i of indices || []) {\n if (!Number.isFinite(i) || i < 0 || i >= this.regions.length) continue;\n const id = this.regions[i].id;\n if (!seen.has(id)) { seen.add(id); ids.push(id); }\n }\n this.selectedIds = ids;\n this.emitSelection();\n }\n\n /** Select a single region by identity (id). Backends call this from their\n * `selectRegion()`; the OSD overlay + region editor highlight off the\n * resulting selection emit. No-op if the region isn't in the store. */\n selectRegion(region: Region): void {\n if (region?.id == null || this.indexOfId(region.id) < 0) return;\n this.selectedIds = [region.id];\n this.emitSelection();\n }\n\n getSelectedShapeIndices$(): Observable<number[]> {\n return this.selectedIndices$.asObservable();\n }\n\n /** Synchronous current selection (array indices) — for callers that need to\n * read the selection without subscribing. */\n getSelectedShapeIndices(): number[] {\n return this.selectedIndices$.value;\n }\n\n /** Delete the currently selected regions and clear the selection. */\n deleteActiveShape(): void {\n if (this.selectedIds.length === 0) return;\n this.recordUndoSnapshot();\n const ids = new Set(this.selectedIds);\n this.regions = this.regions.filter(r => !ids.has(r.id));\n this.selectedIds = [];\n this.syncCache();\n this.emitSelection();\n this.emit();\n }\n\n // ── IRegionStore: colours / labels ─────────────────────────────────────\n\n getShowShapeLabel(): boolean { return this.showShapeLabel; }\n getShapeColor(): string { return this.shapeColor; }\n getFillColor(): string { return this.fillColor; }\n\n /** Convenience setters (not on the contract) for toolbar wiring. */\n setShowShapeLabel(show: boolean): void { this.showShapeLabel = show; }\n setShapeColor(color: string): void { this.shapeColor = color; }\n setFillColor(color: string): void { this.fillColor = color; }\n\n getClassificationColors(): Map<string, string> { return this.store.getClassificationColors(); }\n setClassificationColor(label: string, color: string): void { this.store.setClassificationColor(label, color); }\n\n // ── IRegionStore: previous-shapes buffer ───────────────────────────────\n\n /** Re-show the last saved snapshot (transient — does not alter stored state). */\n plotPreviousShapes(): void {\n this.regionUpdate$.next(this.previousRegions.slice());\n }\n setPreviousShapes(shapes: any[]): void { this.previousRegions = (shapes as Region[]).slice(); }\n getPreviousShapes(): any[] { return this.previousRegions.slice(); }\n\n // ── IRegionStore: undo / redo (jit-ui#85) ──────────────────────────────\n\n /** Emits whether an undo step is currently available — drives the toolbar\n * Undo button's enabled state (greyed out when false). */\n getCanUndo$(): Observable<boolean> {\n return this.canUndo$.asObservable();\n }\n\n /** Emits whether a redo step is currently available — drives the toolbar\n * Redo button's enabled state. */\n getCanRedo$(): Observable<boolean> {\n return this.canRedo$.asObservable();\n }\n\n /** Synchronous read of {@link getCanUndo$} — true when at least one region\n * action can be undone. */\n canUndo(): boolean {\n return this.undoStack.length > 0;\n }\n\n /** Synchronous read of {@link getCanRedo$} — true when an undone action can\n * be re-applied. */\n canRedo(): boolean {\n return this.redoStack.length > 0;\n }\n\n /**\n * Undo the most recent region action, restoring the region set to its state\n * just before that action and pushing the current state onto the redo stack.\n * Up to {@link UNDO_LIMIT} steps are retained, so this can be called up to\n * {@link UNDO_LIMIT} times in a row before the history empties. No-op when\n * nothing is left to undo.\n */\n undo(): void {\n if (this.undoStack.length === 0) return;\n const snapshot = this.undoStack.pop() as Region[];\n // Stash the current (post-action) state so redo can re-apply it.\n this.redoStack.push(this.cloneRegions(this.regions));\n if (this.redoStack.length > RegionStore.UNDO_LIMIT) this.redoStack.shift();\n this.restoreSnapshot(snapshot);\n }\n\n /**\n * Redo the action most recently undone, restoring the region set to the state\n * it had before that undo and pushing the current state back onto the undo\n * stack. No-op when there's nothing to redo (the redo stack is cleared by any\n * fresh region action).\n */\n redo(): void {\n if (this.redoStack.length === 0) return;\n const snapshot = this.redoStack.pop() as Region[];\n this.undoStack.push(this.cloneRegions(this.regions));\n if (this.undoStack.length > RegionStore.UNDO_LIMIT) this.undoStack.shift();\n this.restoreSnapshot(snapshot);\n }\n\n /** Discard the undo/redo history (e.g. on image load/switch — history never\n * crosses images). */\n resetUndoHistory(): void {\n this.undoStack = [];\n this.redoStack = [];\n this.closeUndoBurst();\n if (this.canUndo$.value) this.canUndo$.next(false);\n if (this.canRedo$.value) this.canRedo$.next(false);\n }\n\n /** Make `snapshot` the live region set and notify both backends. Shared by\n * {@link undo} and {@link redo}; the snapshot is already a detached deep\n * clone, so it becomes the live array directly. */\n private restoreSnapshot(snapshot: Region[]): void {\n // Close any open coalescing burst so the next edit starts a fresh entry,\n // and flag the restore so it doesn't record itself back into the history.\n this.closeUndoBurst();\n this.restoringUndo = true;\n this.regions = snapshot;\n // Drop any selected ids the restored set no longer contains.\n this.selectedIds = this.selectedIds.filter(id => this.indexOfId(id) >= 0);\n this.syncCache();\n this.emitSelection();\n this.restoringUndo = false;\n this.emitUndoState();\n // Notify the live + coalesced streams so whichever backend is on screen\n // re-renders from the restored store state.\n this.regionLiveEdit$.next(this.regions.slice());\n this.regionUpdate$.next(this.getRegions());\n }\n\n /**\n * Capture the pre-action region set into the bounded undo history. Called at\n * the top of every mutating operation, *before* it changes `regions`, so the\n * snapshot is the state to return to. Rapid commits from one gesture coalesce\n * into a single entry (see {@link undoStack}). A fresh action also abandons\n * any redo future.\n */\n private recordUndoSnapshot(): void {\n if (this.restoringUndo) return;\n const startsBurst = !this.undoBurstOpen;\n this.armUndoBurst();\n if (!startsBurst) return; // mid-burst — keep first snapshot\n this.undoStack.push(this.cloneRegions(this.regions));\n if (this.undoStack.length > RegionStore.UNDO_LIMIT) this.undoStack.shift();\n this.redoStack = []; // a new edit invalidates redo\n this.emitUndoState();\n }\n\n /** Push the current can-undo / can-redo availability to subscribers. */\n private emitUndoState(): void {\n const canUndo = this.undoStack.length > 0;\n const canRedo = this.redoStack.length > 0;\n if (this.canUndo$.value !== canUndo) this.canUndo$.next(canUndo);\n if (this.canRedo$.value !== canRedo) this.canRedo$.next(canRedo);\n }\n\n /** (Re)arm the idle timer that closes the current coalescing burst. */\n private armUndoBurst(): void {\n this.undoBurstOpen = true;\n if (this.undoBurstTimer) clearTimeout(this.undoBurstTimer);\n this.undoBurstTimer = setTimeout(() => {\n this.undoBurstOpen = false;\n this.undoBurstTimer = null;\n }, RegionStore.UNDO_COALESCE_MS);\n }\n\n private closeUndoBurst(): void {\n this.undoBurstOpen = false;\n if (this.undoBurstTimer) { clearTimeout(this.undoBurstTimer); this.undoBurstTimer = null; }\n }\n\n private cloneRegions(regions: Region[]): Region[] {\n return regions.map(r => this.cloneRegion(r));\n }\n\n /** Deep clone a region so an in-place geometry edit can't mutate a stored\n * history snapshot (bounds are cloned via {@link cloneBounds}). */\n private cloneRegion(r: Region): Region {\n const c = new Region();\n Object.assign(c, r);\n c.bounds = r.bounds ? this.cloneBounds(r.bounds) : r.bounds;\n if (Array.isArray(r.tileCoordinates)) c.tileCoordinates = r.tileCoordinates.slice();\n return c;\n }\n\n // ── IRegionStore: GeoJSON I/O (neutral helpers) ────────────────────────\n\n importRegions(geoJsonStr: string): Region[] {\n return this.plotUtilities.importROIsFromGeoJson(geoJsonStr);\n }\n exportRegions(regions: Region[]): void {\n this.plotUtilities.saveToFile(this.plotUtilities.exportROIsToGeoJson(regions));\n }\n getGeoJsonString(regions: Region[]): string {\n return this.plotUtilities.exportROIsToGeoJson(regions);\n }\n\n // ── IRegionEditApi: structural edits ───────────────────────────────────\n\n addRegion(region: Region): number {\n this.recordUndoSnapshot();\n if (region.id == null) region.id = this.nextId++;\n if (region.name == null) region.name = `shape${region.id}`;\n // A region drawn on a stack belongs to the slice currently displayed, so\n // it saves/reloads on that slice (jit-ui#93). No-op for single-plane images\n // (currentSliceZ stays 0).\n if (this.stackMode) region.z = this.currentSliceZ;\n this.applyClassificationColors([region]);\n this.regions.push(region);\n this.selectedIds = [region.id];\n this.syncCache();\n this.emitSelection();\n this.emit();\n return region.id;\n }\n\n removeRegion(id: number): void {\n const idx = this.indexOfId(id);\n if (idx < 0) return;\n this.recordUndoSnapshot();\n this.regions.splice(idx, 1);\n this.selectedIds = this.selectedIds.filter(s => s !== id);\n this.syncCache();\n this.emitSelection();\n this.emit();\n }\n\n updateBounds(id: number, bounds: Rectangle | Polygon | MultiPolygon): void {\n const r = this.findById(id);\n if (!r) return;\n this.recordUndoSnapshot();\n r.bounds = this.cloneBounds(bounds);\n this.syncCache();\n this.emit();\n }\n\n moveRegion(id: number, dx: number, dy: number): void {\n const r = this.findById(id);\n if (!r || !r.bounds) return;\n this.recordUndoSnapshot();\n const b = r.bounds;\n if (b instanceof Rectangle) {\n b.x += dx;\n b.y += dy;\n } else if (b instanceof Polygon) {\n this.translatePolygon(b, dx, dy);\n } else if (b instanceof MultiPolygon) {\n // Translate every part (and its holes) together (jit-ui#85).\n for (const part of b.polygons) this.translatePolygon(part, dx, dy);\n }\n this.syncCache();\n this.emit();\n }\n\n /** Translate a polygon's vertices and any holes in place by (dx, dy). */\n private translatePolygon(p: Polygon, dx: number, dy: number): void {\n p.xpoints = p.xpoints.map(x => x + dx);\n p.ypoints = p.ypoints.map(y => y + dy);\n p.coordinates = p.xpoints.map((x, i) => [x, p.ypoints[i]]);\n if (p.holes) p.holes = p.holes.map(ring => ring.map(([x, y]) => [x + dx, y + dy]));\n }\n\n // ── IRegionEditApi: vertex edits (polygons only) ───────────────────────\n\n moveVertex(id: number, index: number, x: number, y: number): void {\n const poly = this.polygonOf(id);\n if (!poly || index < 0 || index >= poly.xpoints.length) return;\n this.recordUndoSnapshot();\n poly.xpoints[index] = x;\n poly.ypoints[index] = y;\n poly.coordinates[index] = [x, y];\n this.syncCache();\n this.emit();\n }\n\n /** Move a vertex on a polygon's interior ring (hole) — jit-ui#85. */\n moveHoleVertex(id: number, holeIndex: number, index: number, x: number, y: number): void {\n const poly = this.polygonOf(id);\n if (!poly || !poly.holes || holeIndex < 0 || holeIndex >= poly.holes.length) return;\n const ring = poly.holes[holeIndex];\n if (index < 0 || index >= ring.length) return;\n this.recordUndoSnapshot();\n ring[index] = [x, y];\n this.syncCache();\n this.emit();\n }\n\n /** Insert a vertex on a polygon's interior ring (hole), after `segIndex`\n * (the edge's start vertex). No-op for an out-of-range hole — jit-ui#85. */\n addHoleVertex(id: number, holeIndex: number, segIndex: number, x: number, y: number): void {\n const poly = this.polygonOf(id);\n if (!poly || !poly.holes || holeIndex < 0 || holeIndex >= poly.holes.length) return;\n const ring = poly.holes[holeIndex];\n this.recordUndoSnapshot();\n const at = Math.max(0, Math.min(segIndex + 1, ring.length));\n ring.splice(at, 0, [x, y]);\n if (poly.bezier) this.seedHoleHandles(poly); // keep hole handles aligned to the ring\n this.syncCache();\n this.emit();\n }\n\n /** Delete the vertex at `index` on a polygon's interior ring (hole). Removing\n * it below 3 vertices drops the whole hole (a ring with < 3 points bounds no\n * area) — jit-ui#85. */\n deleteHoleVertex(id: number, holeIndex: number, index: number): void {\n const poly = this.polygonOf(id);\n if (!poly || !poly.holes || holeIndex < 0 || holeIndex >= poly.holes.length) return;\n const ring = poly.holes[holeIndex];\n if (index < 0 || index >= ring.length) return;\n this.recordUndoSnapshot();\n if (ring.length <= 3) {\n poly.holes.splice(holeIndex, 1);\n if (poly.holes.length === 0) poly.holes = undefined;\n } else {\n ring.splice(index, 1);\n }\n if (poly.bezier) this.seedHoleHandles(poly); // keep hole handles aligned to the ring(s)\n this.syncCache();\n this.emit();\n }\n\n addVertex(id: number, segIndex: number, x: number, y: number): void {\n const poly = this.polygonOf(id);\n if (!poly) return;\n this.recordUndoSnapshot();\n // Insert after segIndex (the start vertex of the edge). Clamp to range.\n const at = Math.max(0, Math.min(segIndex + 1, poly.xpoints.length));\n poly.xpoints.splice(at, 0, x);\n poly.ypoints.splice(at, 0, y);\n poly.coordinates = poly.xpoints.map((xx, i) => [xx, poly.ypoints[i]]);\n poly.npoints = poly.xpoints.length;\n // Give the new vertex smooth handles from its neighbours; keep the others'\n // (possibly hand-edited) handles intact.\n if (poly.bezier && poly.handlesIn && poly.handlesOut) {\n const n = poly.xpoints.length;\n const closed = poly.closed !== false;\n const prev = closed ? (at - 1 + n) % n : Math.max(0, at - 1);\n const next = closed ? (at + 1) % n : Math.min(n - 1, at + 1);\n const tx = (poly.xpoints[next] - poly.xpoints[prev]) / 6;\n const ty = (poly.ypoints[next] - poly.ypoints[prev]) / 6;\n poly.handlesIn.splice(at, 0, [-tx, -ty]);\n poly.handlesOut.splice(at, 0, [tx, ty]);\n }\n this.syncCache();\n this.emit();\n }\n\n deleteVertex(id: number, index: number): void {\n const poly = this.polygonOf(id);\n if (!poly || index < 0 || index >= poly.xpoints.length) return;\n const min = poly.closed === false ? 2 : 3;\n if (poly.xpoints.length <= min) return; // refuse to degenerate the polygon\n this.recordUndoSnapshot();\n poly.xpoints.splice(index, 1);\n poly.ypoints.splice(index, 1);\n poly.coordinates = poly.xpoints.map((xx, i) => [xx, poly.ypoints[i]]);\n poly.npoints = poly.xpoints.length;\n if (poly.bezier && poly.handlesIn && poly.handlesOut) {\n poly.handlesIn.splice(index, 1);\n poly.handlesOut.splice(index, 1);\n }\n this.syncCache();\n this.emit();\n }\n\n setBezier(id: number, bezier: boolean): void {\n const r = this.findById(id);\n if (!r || !r.bounds) return;\n if (r.bounds instanceof Polygon) {\n if (r.bounds.bezier === bezier) return;\n this.recordUndoSnapshot();\n this.applyBezier(r.bounds, bezier);\n } else if (r.bounds instanceof Rectangle && bezier) {\n this.recordUndoSnapshot();\n // Smoothing a rectangle: convert it to a 4-anchor closed polygon first.\n const b = r.bounds;\n const xs = [b.x, b.x + b.width, b.x + b.width, b.x];\n const ys = [b.y, b.y, b.y + b.height, b.y + b.height];\n const poly = new Polygon();\n poly.npoints = 4;\n poly.xpoints = xs;\n poly.ypoints = ys;\n poly.coordinates = xs.map((x, i) => [x, ys[i]]);\n poly.closed = true;\n this.applyBezier(poly, true);\n r.bounds = poly;\n } else {\n return; // bezier=false on a rectangle: nothing to do\n }\n this.syncCache();\n this.emit();\n }\n\n /** Turn bezier on (and seed editable handles from the smooth default) or off\n * (and drop the handles). */\n private applyBezier(poly: Polygon, bezier: boolean): void {\n poly.bezier = bezier;\n if (bezier) {\n const off = defaultHandleOffsets(poly.xpoints, poly.ypoints, poly.closed !== false);\n poly.handlesIn = off.in;\n poly.handlesOut = off.out;\n this.seedHoleHandles(poly); // smooth the holes too (donut → bezier curves the holes)\n } else {\n poly.handlesIn = undefined;\n poly.handlesOut = undefined;\n poly.holeHandlesIn = undefined;\n poly.holeHandlesOut = undefined;\n }\n }\n\n /** (Re)seed per-hole bezier handles from the Catmull-Rom default, parallel to `poly.holes`. */\n private seedHoleHandles(poly: Polygon): void {\n if (!poly.holes || !poly.holes.length) {\n poly.holeHandlesIn = undefined;\n poly.holeHandlesOut = undefined;\n return;\n }\n const ins: number[][][] = [];\n const outs: number[][][] = [];\n for (const ring of poly.holes) {\n const off = defaultHandleOffsets(\n ring.map((p) => p[0]),\n ring.map((p) => p[1]),\n true,\n );\n ins.push(off.in);\n outs.push(off.out);\n }\n poly.holeHandlesIn = ins;\n poly.holeHandlesOut = outs;\n }\n\n /** Drag a bezier control point on a hole ring vertex (donut bezier editing). */\n moveHoleBezierHandle(\n id: number,\n holeIndex: number,\n index: number,\n side: 'in' | 'out',\n x: number,\n y: number,\n ): void {\n const poly = this.polygonOf(id);\n if (!poly || !poly.bezier || !poly.holes || holeIndex < 0 || holeIndex >= poly.holes.length) {\n return;\n }\n const ring = poly.holes[holeIndex];\n if (index < 0 || index >= ring.length) return;\n this.recordUndoSnapshot();\n if (!poly.holeHandlesIn || !poly.holeHandlesOut) this.seedHoleHandles(poly);\n const offset = [x - ring[index][0], y - ring[index][1]];\n if (side === 'in') poly.holeHandlesIn![holeIndex][index] = offset;\n else poly.holeHandlesOut![holeIndex][index] = offset;\n this.syncCache();\n this.emit();\n }\n\n moveBezierHandle(id: number, index: number, side: 'in' | 'out', x: number, y: number): void {\n const poly = this.polygonOf(id);\n if (!poly || !poly.bezier || index < 0 || index >= poly.xpoints.length) return;\n this.recordUndoSnapshot();\n if (!poly.handlesIn || !poly.handlesOut) {\n const off = defaultHandleOffsets(poly.xpoints, poly.ypoints, poly.closed !== false);\n poly.handlesIn = off.in;\n poly.handlesOut = off.out;\n }\n const offset = [x - poly.xpoints[index], y - poly.ypoints[index]];\n if (side === 'in') poly.handlesIn[index] = offset;\n else poly.handlesOut[index] = offset;\n this.syncCache();\n this.emit();\n }\n\n beginBatch(): void { this.batchDepth++; }\n endBatch(): void {\n if (this.batchDepth > 0) this.batchDepth--;\n if (this.batchDepth === 0 && this.pendingEmit) {\n this.pendingEmit = false;\n this.regionUpdate$.next(this.getRegions());\n }\n }\n\n // ── per-image lifecycle ────────────────────────────────────────────────\n\n /**\n * Switch the active image: snapshot the outgoing regions, restore the\n * incoming image's (or [] if none), clear selection, and notify. Idempotent\n * for the same image (so repeated replots of one image keep its regions).\n */\n setActiveImage(imageInfo: IImageInfo): void {\n const newKey = this.deriveImageKey(imageInfo);\n if (this.currentImageKey === newKey) return;\n // Switching images ends any per-slice stack session (jit-ui#93); the loader\n // re-enters stack mode afterwards if the new image is itself a z-stack.\n this.exitStackMode();\n if (this.currentImageKey) {\n this.regionsByImageKey.set(this.currentImageKey, this.regions.slice());\n }\n this.currentImageKey = newKey;\n this.regions = (newKey && this.regionsByImageKey.get(newKey))\n ? (this.regionsByImageKey.get(newKey) as Region[]).slice()\n : [];\n this.previousRegions = this.regions.slice();\n this.selectedIds = [];\n // Undo never crosses an image switch.\n this.resetUndoHistory();\n this.emitSelection();\n this.regionUpdate$.next(this.getRegions());\n }\n\n /** Drop the entire per-image cache (logout / project switch). */\n clearRegionsByImageKey(): void {\n this.regionsByImageKey.clear();\n this.currentImageKey = undefined;\n this.regions = [];\n this.selectedIds = [];\n this.resetUndoHistory();\n }\n\n // ── internals ──────────────────────────────────────────────────────────\n\n private deriveImageKey(imageInfo: IImageInfo | undefined): string | undefined {\n if (!imageInfo) return undefined;\n if (imageInfo.urls && imageInfo.urls.length > 0 && imageInfo.urls[0]) {\n return imageInfo.urls[0];\n }\n return imageInfo.fileName || undefined;\n }\n\n /**\n * Resolve each region's colour from the annotation-class preset set (jit-ui#70).\n * The presets are the source of truth for colour — this **overrides any colour\n * embedded in the GeoJSON** (which the YOLO worker writes today). A matching\n * preset gives the class colour; an unknown class gets a deterministic fallback\n * colour (and, only when `autoPromote` is on, is added to the editable list).\n * Regions the user explicitly recoloured (`colorOverridden`) are left untouched.\n */\n private applyClassificationColors(regions: Region[]): void {\n const set = this.store.getPresetSet();\n const keyOf = (label: string) =>\n set.matchMode === 'normalized' ? label.trim().toLowerCase() : label;\n const known = new Set(set.classes.map((c) => keyOf(c.name)));\n for (const region of regions) {\n if (!region.label || region.colorOverridden) continue;\n const preset = findPreset(region.label, set);\n if (preset) {\n region.color = preset.color;\n continue;\n }\n const color = fallbackColorFor(region.label, set.fallbackPalette);\n region.color = color;\n if (set.autoPromote && !known.has(keyOf(region.label))) {\n known.add(keyOf(region.label));\n // In normalized mode, trim the promoted name so leading/trailing\n // whitespace doesn't create invisible duplicates or odd display names.\n const name = set.matchMode === 'normalized' ? region.label.trim() : region.label;\n this.store.upsertClass({ name, color, source: 'auto' });\n }\n }\n }\n\n private syncCache(): void {\n if (this.currentImageKey) {\n this.regionsByImageKey.set(this.currentImageKey, this.regions.slice());\n }\n }\n\n private emit(): void {\n // Live-edit listeners (e.g. the intensity-profile inset) react on EVERY\n // change — including per-frame during a batched drag — so they track the\n // region live. The main regionUpdate$ stays coalesced during a batch (fires\n // once on endBatch) to keep heavier consumers (Regions tab) calm.\n this.regionLiveEdit$.next(this.regions.slice());\n if (this.batchDepth > 0) { this.pendingEmit = true; return; }\n this.regionUpdate$.next(this.getRegions());\n }\n\n /** Project selected ids to current array indices, pruning ids that no longer\n * exist, and emit if the index set changed. */\n private emitSelection(): void {\n const indices: number[] = [];\n const liveIds: number[] = [];\n for (const id of this.selectedIds) {\n const idx = this.indexOfId(id);\n if (idx >= 0) { indices.push(idx); liveIds.push(id); }\n }\n this.selectedIds = liveIds;\n if (!this.indicesEqual(this.selectedIndices$.value, indices)) {\n this.selectedIndices$.next(indices);\n }\n }\n\n private indicesEqual(a: number[], b: number[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n }\n\n private findById(id: number): Region | undefined {\n return this.regions.find(r => r.id === id);\n }\n\n private indexOfId(id: number): number {\n return this.regions.findIndex(r => r.id === id);\n }\n\n /** The region's bounds as a Polygon, or undefined if it isn't a polygon. */\n private polygonOf(id: number): Polygon | undefined {\n const r = this.findById(id);\n return r && r.bounds instanceof Polygon ? r.bounds : undefined;\n }\n\n private clonePolygon(p: Polygon): Polygon {\n const poly = new Polygon();\n poly.npoints = p.npoints;\n poly.xpoints = p.xpoints.slice();\n poly.ypoints = p.ypoints.slice();\n poly.coordinates = p.coordinates.map(c => c.slice());\n poly.closed = p.closed;\n poly.bezier = p.bezier;\n if (p.handlesIn) poly.handlesIn = p.handlesIn.map(o => o.slice());\n if (p.handlesOut) poly.handlesOut = p.handlesOut.map(o => o.slice());\n if (p.holes) poly.holes = p.holes.map(ring => ring.map(pt => pt.slice()));\n if (p.holeHandlesIn) poly.holeHandlesIn = p.holeHandlesIn.map(r => r.map(o => o.slice()));\n if (p.holeHandlesOut) poly.holeHandlesOut = p.holeHandlesOut.map(r => r.map(o => o.slice()));\n return poly;\n }\n\n private cloneBounds(bounds: Rectangle | Polygon | MultiPolygon): Rectangle | Polygon | MultiPolygon {\n if (bounds instanceof Rectangle) {\n const rect = new Rectangle();\n rect.x = bounds.x; rect.y = bounds.y; rect.width = bounds.width; rect.height = bounds.height;\n return rect;\n }\n if (bounds instanceof MultiPolygon) {\n const mp = new MultiPolygon();\n mp.polygons = bounds.polygons.map(p => this.clonePolygon(p));\n return mp;\n }\n return this.clonePolygon(bounds);\n }\n\n private regionsEqual(a: Region, b: Region): boolean {\n const ba = a.bounds, bb = b.bounds;\n if (ba instanceof Rectangle && bb instanceof Rectangle) {\n return ba.x === bb.x && ba.y === bb.y && ba.width === bb.width && ba.height === bb.height;\n }\n if (ba instanceof MultiPolygon && bb instanceof MultiPolygon) {\n if (ba.polygons.length !== bb.polygons.length) return false;\n for (let i = 0; i < ba.polygons.length; i++) {\n if (!this.polygonsEqual(ba.polygons[i], bb.polygons[i])) return false;\n }\n return true;\n }\n if (ba instanceof Polygon && bb instanceof Polygon) {\n return this.polygonsEqual(ba, bb);\n }\n return false;\n }\n\n private polygonsEqual(pa: Polygon, pb: Polygon): boolean {\n if ((pa.closed !== false) !== (pb.closed !== false)) return false;\n if (pa.xpoints.length !== pb.xpoints.length) return false;\n for (let i = 0; i < pa.xpoints.length; i++) {\n if (pa.xpoints[i] !== pb.xpoints[i] || pa.ypoints[i] !== pb.ypoints[i]) return false;\n }\n return this.holesEqual(pa.holes, pb.holes);\n }\n\n /** Compare two polygons' interior-ring (hole) sets for the dedupe path. */\n private holesEqual(a: number[][][] | undefined, b: number[][][] | undefined): boolean {\n const na = a?.length ?? 0, nb = b?.length ?? 0;\n if (na !== nb) return false;\n for (let h = 0; h < na; h++) {\n const ra = (a as number[][][])[h], rb = (b as number[][][])[h];\n if (ra.length !== rb.length) return false;\n for (let i = 0; i < ra.length; i++) {\n if (ra[i][0] !== rb[i][0] || ra[i][1] !== rb[i][1]) return false;\n }\n }\n return true;\n }\n}\n","import { Injectable, Inject, Optional } from '@angular/core';\n\nimport * as Plotly from 'plotly.js-dist-min';\nimport { Image } from 'image-js';\nimport { HttpClient } from '@angular/common/http';\nimport { firstValueFrom } from 'rxjs';\n\nimport { Polygon, Rectangle, Region } from '../../models/region';\nimport { Buffer } from 'buffer';\nimport { IImageInfo, IImageMetadata } from '../../contracts/image.contract';\nimport { TileAccessPort, TILE_ACCESS_PORT } from '../../contracts/ports/tile-access.port';\nimport { ImageStatePort, IMAGE_STATE_PORT } from '../../contracts/ports/image-state.port';\nimport { BehaviorSubject, EMPTY, Observable, Subject, Subscription, combineLatest, of } from 'rxjs';\nimport { MessageService } from 'primeng/api';\nimport { ShapeSelection } from '../../models/shape';\nimport { CONFIG, CONFIG_SURFACE, PlotUtilities } from '../../plot.utilities';\nimport { WandService, WandOptions } from '../../toolbar/wand/wand.service';\nimport { CachedImageData, WandToolService, WandToolHost } from '../../toolbar/wand/wand-tool.service';\nimport { BrushToolService, BrushOptions } from '../../toolbar/brush/brush-tool.service';\nimport { SamToolService } from '../../toolbar/segmentation/sam-tool.service';\nimport { SamPointToolService } from '../../toolbar/segmentation/sam-point-tool.service';\nimport { CellSegmentToolService } from '../../toolbar/segmentation/cell-segment-tool.service';\nimport { ICellSegmenter, CELL_SEGMENTER } from '../../contracts/cell-segmenter.contract';\nimport { VertexEraserToolService, VertexEraserToolHost } from '../../toolbar/vertex-eraser/vertex-eraser-tool.service';\nimport { ZoomToBoxToolService } from '../../toolbar/zoom-to-box/zoom-to-box-tool.service';\nimport {\n parseSvgPathPolygon,\n verticesToSvgPath,\n} from '../../models/geometry';\nimport { PlotType, PLOT_TYPE_DESCRIPTORS, PlotTypeDescriptor } from '../../contracts/plot-type';\nimport {\n PLOTLY_PLOT_TYPE_IMPLS,\n PlotlyPlotTypeImpl,\n TraceBuildInput,\n} from './plotly-trace-builders';\nimport { IVisualizer, IntensityProfile, IIsosurfaceControls, IIntensityControls } from '../../contracts/visualizer.contract';\nimport { IHistogram } from '../../contracts/channel-histogram-api.contract';\nimport { bt601Luminance, histogram256 } from '../../contracts/intensity';\nimport { ViewerCapabilities, ViewerFeature, capabilitiesOf } from '../../contracts/capabilities.contract';\nimport { IRegionOverlay } from '../../contracts/region-overlay.contract';\nimport { PlotlyRegionOverlay } from './plotly-region-overlay';\nimport { ICoordinateTransform } from '../../contracts/coordinate-transform.contract';\nimport { PlotlyCoordinateTransform } from './plotly-coordinate-transform';\nimport { VisualizerStore } from '../../store/visualizer-store.service';\nimport { RegionStore } from '../../store/region-store.service';\n\n// Re-exported so existing consumers can keep importing PlotType from this\n// module while it physically lives in the backend-neutral contracts/ dir.\n// TODO(plotting-abstraction): once all consumers import from\n// './contracts/plot-type' directly, drop this re-export.\nexport { PlotType } from '../../contracts/plot-type';\n\n\n(window as any).Buffer = Buffer;\n\n@Injectable({\n providedIn: 'root'\n})\nexport class PlotlyService implements IVisualizer {\n\n /**\n * Plotly is the full-featured data backend: it supports every feature,\n * including 3D scenes, live scalar colormaps, pixel readback and the\n * server-side high-def zoom re-fetch. (OpenSeadragon's stub advertises only\n * image display.)\n */\n readonly capabilities: ViewerCapabilities = capabilitiesOf([\n ViewerFeature.ImageDisplay,\n ViewerFeature.Surface3D,\n ViewerFeature.ScalarColormap,\n ViewerFeature.PixelReadback,\n ViewerFeature.HighDefZoom,\n ViewerFeature.StackSlider,\n ViewerFeature.Isosurface,\n ]);\n\n private shapes: any[] = [];\n private previousShapes: ShapeSelection[] = [];\n private isRegionSavedOn = true;\n private imageLength!: number;\n private screenHeight!: number;\n private plotDiv!: string;\n private isRealZoom = true;\n private scaleratio = true;\n private trueImgSize!: number[];\n private zoomCoordinates: number[] = [];\n private fileName!: string | undefined;\n\n private dragMode!: string;\n // Region data (the list + per-image cache), selection, id minting, the region\n // update event and the shape colour/label prefs now live in the shared\n // RegionStore (injected as `this.regionStore`) — the single source of truth\n // both backends delegate to. `this.shapes` below is kept as Plotly's *render\n // projection* of those regions (the dict array Plotly.relayout consumes) and\n // is mirrored into the store on every write. Colormap, reverse-scale, image\n // metadata and classification colours live in the shared VisualizerStore\n // (injected as `this.store`).\n private urls!: string[];\n imageInfo!: IImageInfo;\n private plotUtilities = new PlotUtilities();\n private plotType!: PlotType;\n\n private onPlotMouseDown: (() => void) | null = null;\n\n // The per-image region cache (regionsByImageKey/currentImageKey) now lives in\n // the shared RegionStore; setActiveImage() delegates to it and re-projects\n // `this.shapes` from the store afterwards.\n\n /** Pixel data cached for wand sampling. data[zIndex] is a 2-D matrix. */\n private cachedImageFrames?: any[];\n private cachedImageWidth = 0;\n private cachedImageHeight = 0;\n private cachedImageRatios: number[] = [1, 1];\n private cachedIsGrayscale = false;\n /** Data-space coordinate of the cached frame's pixel (0,0). [0,0] for the full\n * image; a crop's top-left when zoomed (so the intensity profile samples the\n * zoom-level pixels at the right offset/resolution). */\n private cachedFrameOrigin: [number, number] = [0, 0];\n /** Last visible image-pixel rectangle from the active backend's viewport (set by\n * the OSD viewport-change hook via refreshIntensitySamplingForRoi). New profile lines are\n * placed within it so they land on-screen when zoomed in; null → use full image. */\n private lastVisibleRoi: { x: number; y: number; width: number; height: number } | null = null;\n\n /** events */\n private onRelayoutEvent: any;\n\n private stackLoading$ = new BehaviorSubject<boolean>(false);\n private stackLoadingProgress$ = new BehaviorSubject<number>(0);\n // current index of image in stack (if stack), 0 if single image\n private zIndex = new BehaviorSubject<number>(0);\n private autoscaleEvent = new Subject<any>();\n // The region update event and selection stream are owned by the shared\n // RegionStore; getRegionUpdateEvent()/getSelectedShapeIndices$() delegate to\n // it so every consumer (and the OSD backend) sees one stream.\n /** Bright, well-separated colours cycled as the user adds profile-line ROIs.\n * The matching inset trace is drawn in the same colour. */\n private readonly PROFILE_PALETTE = [\n '#FFD400', // yellow\n '#00E5FF', // cyan\n '#FF2D95', // magenta\n '#39FF14', // green\n '#FF9500', // orange\n '#7C4DFF', // violet\n '#FF3B30', // red\n '#18FFFF', // aqua\n ];\n /** Palette cursor for profile lines (never reset on delete, so colours keep\n * cycling across the session). */\n private profileColorSeq = 0;\n private intensityProfile$ = new Subject<IntensityProfile[]>();\n /** ISOSURFACE band as a 0–255 slider position, mapped onto the volume's real\n * intensity range at render time (see mapIsoBand). Defaults to the full range\n * so the first render shows the whole structure regardless of how bright or\n * dark the volume is; the user then narrows the band to isolate intensities. */\n private isoMin = 0;\n private isoMax = 255;\n /** Actual intensity range of the volume on screen ([min,max] over the loaded\n * frames). The slider spans 0–255, but a given stack often occupies only a\n * sub-range, so we clamp the iso band into this range (with a small margin)\n * to guarantee non-degenerate surfaces — both on first render and on live\n * slider moves. Null until an isosurface volume has been measured. */\n private isoDataRange: [number, number] | null = null;\n // Id minting and the selection index stream are owned by the shared\n // RegionStore. Selection still drives Plotly's `_activeShapeIndex` (so a\n // single shape gets the edit handles) — see setSelectedShapeIndices().\n private imageCached = false;\n private imageCachedSubscription: Subscription;\n private filenameSubscription: Subscription;\n /** Drives the intensity inset off region adds/drags/deletes (both backends). */\n private regionUpdateSubscription?: Subscription;\n /** Live (per-frame, non-coalesced) region edits — so the inset tracks an OSD\n * line ROI live during a drag (OSD batches regionUpdate$ until release). */\n private regionLiveEditSubscription?: Subscription;\n private channelSub?: Subscription;\n\n private wandHost!: WandToolHost;\n private eraserHost!: VertexEraserToolHost;\n /** This backend's region renderer (lazily created in getRegionOverlay). */\n private regionOverlay?: IRegionOverlay;\n private readonly coordinateTransform: ICoordinateTransform =\n new PlotlyCoordinateTransform(\n () => document.getElementById(this.plotDiv),\n () => this.getOverlayContainer());\n\n constructor(@Inject(TILE_ACCESS_PORT) private tiles: TileAccessPort,\n @Inject(IMAGE_STATE_PORT) private state: ImageStatePort,\n public messageService: MessageService, private http: HttpClient,\n private wandService: WandService,\n private wandTool: WandToolService,\n private brushTool: BrushToolService,\n private samTool: SamToolService,\n private samPointTool: SamPointToolService,\n private cellSegmentTool: CellSegmentToolService,\n @Optional() @Inject(CELL_SEGMENTER) private cellSegmenter: ICellSegmenter | null,\n private vertexEraserTool: VertexEraserToolService,\n private zoomToBoxTool: ZoomToBoxToolService,\n private store: VisualizerStore,\n private regionStore: RegionStore) {\n // relayout event router\n this.onRelayoutEvent = (event: any) => { this.relayoutEventHandler(event); };\n\n // Tool services read/mutate our state via small *Host interfaces. Stored\n // so we can re-bind them to ourselves whenever a Plotly tool is activated\n // (the OpenSeadragon backend re-binds the same singleton tools to itself).\n this.wandHost = {\n getRegions: () => this.regionStore.getRegions(),\n setRegions: (regions) => this.setRegions(regions),\n getCachedImageData: () => this.getCachedImageData(),\n getActiveFrameIndex: () => this.activeFrameIndex(),\n getOverlayContainer: () => this.getOverlayContainer(),\n getCoordinateTransform: () => this.getCoordinateTransform(),\n getFileName: () => this.fileName,\n getShapeColor: () => this.regionStore.getShapeColor(),\n };\n this.eraserHost = {\n getRegions: () => this.regionStore.getRegions(),\n setRegions: (regions) => this.setRegions(regions),\n invalidateWandRegion: () => this.wandTool.clearActiveRegion(),\n getOverlayContainer: () => this.getOverlayContainer(),\n getCoordinateTransform: () => this.getCoordinateTransform(),\n getCachedImageRatio: () => this.cachedImageRatios[0] || 1,\n };\n this.wandTool.bindHost(this.wandHost);\n // The brush reuses the wand host (same coordinate frame + region access).\n this.brushTool.bindHost(this.wandHost);\n this.vertexEraserTool.bindHost(this.eraserHost);\n this.bindZoomToBoxHost();\n\n this.imageCachedSubscription = this.state.isImageCached$().subscribe(imageCached => {\n this.imageCached = imageCached;\n });\n this.filenameSubscription = this.state.getFilename$().subscribe(filename => {\n this.fileName = filename;\n });\n // Live recolor from the Channels & Histogram pane: restyle the display window (zmin/zmax for\n // a heatmap, cmin/cmax for isosurface/surface), the colorscale (colormap), and reverse/invert\n // when the channel state OR the colormap changes. (Gamma is applied by the OSD image view; the\n // Plotly colorscale window covers the common contrast case.)\n this.channelSub = combineLatest([\n this.store.getChannelStates(),\n this.store.getReverseScale(),\n this.store.getInvert(),\n this.store.getColormap(),\n ]).subscribe(([channels, rev, inv]) => this.applyChannelDisplay(channels, rev, inv));\n // Profile lines are store regions; any region change (add/drag/delete, on\n // either backend) should refresh the inset traces. The live-edit stream\n // fires per frame during a drag (OSD coalesces regionUpdate$ until release),\n // so the inset tracks an OSD line ROI live as it's moved.\n this.regionUpdateSubscription = this.regionStore.getRegionUpdateEvent().subscribe(() => {\n this.emitProfiles();\n });\n this.regionLiveEditSubscription = this.regionStore.getRegionLiveEdit$().subscribe(() => {\n this.emitProfiles();\n });\n }\n\n getTrueImageSize(): { width: number; height: number } | null {\n if (!this.trueImgSize) return null;\n return {\n width: this.trueImgSize[1] - this.trueImgSize[0],\n height: this.trueImgSize[3] - this.trueImgSize[2],\n };\n }\n\n /**\n * Load image\n * @param imageInfo\n * @param zIndex index of the image to load\n * @return an object with data and ratio keys\n */\n public async load(imageInfo: IImageInfo, zIndex: number) {\n const urls = imageInfo.urls;\n // use zIndex provided if any, 0 otherwise\n let imageUrl;\n if (zIndex) {\n imageUrl = urls[zIndex];\n } else {\n imageUrl = urls[0];\n }\n const isGrayscale = imageInfo.isGrayscale;\n const image = await this.loadImage(imageUrl);\n const xRatio = imageInfo.trueImageSize[0] / image.width;\n const yRatio = imageInfo.trueImageSize[1] / image.height;\n\n const trueImageSize = [];\n // [x0, x1, y0, y1]\n trueImageSize[0] = 0;\n trueImageSize[1] = imageInfo.trueImageSize[0];\n trueImageSize[2] = 0;\n trueImageSize[3] = imageInfo.trueImageSize[1];\n this.trueImgSize = trueImageSize;\n this.fileName = imageInfo.fileName;\n if (imageInfo.isStack && imageInfo.showStack) {\n const images: any[] = [];\n this.stackLoadingProgress$.next(0);\n // One URL per slice — load them all (earlier `length-1` dropped the last).\n for (let i = 0; i < urls.length; i++) {\n console.log(`image stack ${i}`);\n // do not keep with loading if filename is different (a new file has been selected)\n // or if the stackLoading value is set to false\n if (this.fileName === imageInfo.fileName && this.stackLoading$.value) {\n const image = await this.loadImage(urls[i]);\n if (isGrayscale) {\n const grey = image.grey();\n const imgData = this.plotUtilities.arrayToMatrix(Array.from(grey.data), image.width);\n images.push(imgData);\n } else {\n const rgbData = image.getPixelsArray();\n const rgbMatrix = this.plotUtilities.arrayToMatrix(rgbData, image.width);\n images.push(rgbMatrix);\n }\n this.stackLoadingProgress$.next(Math.round((i * 100) / urls.length));\n } else {\n // break stack loading\n break;\n }\n }\n // reset stackLoading progress to 0\n this.stackLoadingProgress$.next(0);\n return { data: images, ratios: [xRatio, yRatio],\n sizes: [image.width, image.height],\n filename: imageInfo.fileName };\n } else {\n let imageData;\n if (isGrayscale) {\n const grey = image.grey();\n imageData = this.plotUtilities.arrayToMatrix(Array.from(grey.data), image.width);\n } else {\n const rgbData = image.getPixelsArray();\n imageData = this.plotUtilities.arrayToMatrix(rgbData, image.width);\n }\n return { data: [imageData],\n ratios: [xRatio, yRatio],\n sizes: [image.width, image.height],\n filename: imageInfo.fileName };\n }\n }\n\n /**\n *\n * @param plotDiv\n * @param imageLoaded object with data, ratios and sizes key\n * @param imageInfo ImageInfo object\n * @param screenHeight size of the available screen height\n * @param plotType type of plotting\n */\n /**\n * @param inPlace when true, updates the existing plot via Plotly.react\n * instead of Plotly.purge + Plotly.newPlot. Used by the multi-tier\n * diagram swap (small → large) so the canvas doesn't briefly blank\n * between phases.\n */\n public plot(plotDiv: string, imageLoaded: any, imageInfo: IImageInfo, screenHeight: number,\n plotType: PlotType, inPlace: boolean = false) {\n const trueImageSize: number[] = [];\n this.zoomCoordinates = [];\n // [x0, x1, y0, y1]\n trueImageSize[0] = 0;\n trueImageSize[1] = imageInfo.trueImageSize[0];\n trueImageSize[2] = 0;\n trueImageSize[3] = imageInfo.trueImageSize[1];\n // Save the current image's regions and pull in any cached regions for the\n // image we're about to display, before Plotly.newPlot reads `this.shapes`.\n this.setActiveImage(imageInfo);\n this.imageInfo = imageInfo;\n this.plotType = plotType;\n // Cache pixel matrices so the wand tool can sample them.\n this.cachedImageFrames = imageLoaded.data;\n this.cachedImageWidth = imageLoaded.sizes[0];\n this.cachedImageHeight = imageLoaded.sizes[1];\n this.cachedImageRatios = imageLoaded.ratios;\n this.cachedFrameOrigin = [0, 0]; // full image — reset any prior zoom-crop origin\n this.cachedIsGrayscale = !!imageInfo.isGrayscale;\n\n // Pluggable plot types (contour, scatter, scatter3d, isosurface) render\n // through the trace-builder registry. The original HEATMAP/SURFACE/RGB-image\n // renderers keep their dedicated paths below (also reused by the high-def\n // zoom re-fetch). Intensity profiles are no longer a plot type — they're\n // Region-based line ROIs, available in HEATMAP/IMAGE mode.\n const impl = PLOTLY_PLOT_TYPE_IMPLS[plotType];\n if (impl) {\n this.imageInfo.isGrayscale = !!imageInfo.isGrayscale;\n return this.plotViaRegistry(\n plotDiv, impl, this.buildTraceInput(imageInfo, imageLoaded, trueImageSize),\n screenHeight, inPlace);\n }\n\n if (imageInfo.isGrayscale) {\n if (plotType === PlotType.SURFACE) {\n return this.plotSurface(plotDiv, imageInfo.urls, imageLoaded.data, trueImageSize,\n imageLoaded.ratios, screenHeight, inPlace);\n }\n return this.plotHeatmap(plotDiv, imageInfo.urls, imageLoaded.data, trueImageSize,\n imageLoaded.ratios, screenHeight, inPlace);\n }\n return this.plotRGBHeatmap(plotDiv, imageInfo.urls, imageLoaded.data, trueImageSize,\n imageLoaded.ratios, imageLoaded.sizes[0], imageLoaded.sizes[1], screenHeight, inPlace);\n }\n\n /**\n * Function used to plot a grayscale heatmap\n * @param plotDiv\n * @param urls\n * @param images\n * @param trueImgSize array containing the following : [x0, x1, y0, y1]\n * @param ratios\n * @param screenHeight\n * @return Promise true when plotting is finished\n */\n private plotHeatmap(plotDiv: string, urls: string[], images: any[], trueImgSize: number[],\n ratios: number[], screenHeight: number, inPlace: boolean = false): Promise<boolean> {\n if (!inPlace) Plotly.purge(plotDiv);\n this.plotDiv = plotDiv;\n this.imageLength = images.length;\n this.urls = urls;\n this.screenHeight = screenHeight;\n // plot\n const traces: { z: any; type: string; name: string; visible: boolean; }[] = [];\n images.forEach((dataset, index) => {\n const trace = {\n x0: trueImgSize[0],\n dx: ratios[0],\n y0: trueImgSize[2],\n dy: ratios[0],\n z: dataset,\n type: 'heatmap',\n // We remove the tooltip annotation for performances reasons\n // text: dataset.map((row: any[], i: any) => row.map((item, j) => {\n // return `x: ${+(j * ratios[0]).toFixed(2)}<br>y: ${+(i * ratios[0]).toFixed(2)}<br>value: ${item}`})),\n hoverinfo: 'none',\n colorscale: this.store.currentColormap().data.value,\n reversescale: this.store.currentReverseScale(),\n name: `Slice ${index + 1}`,\n visible: index === 0\n };\n traces.push(trace);\n });\n const render = inPlace ? Plotly.react : Plotly.newPlot;\n return (render as any)(plotDiv, traces as any,\n this.getHeatmapLayout([trueImgSize[0], trueImgSize[1]], [trueImgSize[3],\n trueImgSize[2]]), CONFIG as any).then(() => {\n // handle the relayout event for zoom / rois and the click event\n this.setEvents(plotDiv, true, screenHeight);\n return true;\n });\n }\n\n /**\n * Function used to plot a grayscale surface\n * @param plotDiv\n * @param urls\n * @param images\n * @param trueImgSize array containing the following : [x0, x1, y0, y1]\n * @param ratios\n * @param screenHeight\n * @return Promise true when plotting is finished\n */\n private plotSurface(plotDiv: string, urls: string[], images: any[], trueImgSize: number[],\n ratios: number[], screenHeight: number, inPlace: boolean = false): Promise<boolean> {\n if (!inPlace) Plotly.purge(plotDiv);\n this.plotDiv = plotDiv;\n this.imageLength = images.length;\n this.urls = urls;\n this.screenHeight = screenHeight;\n // plot\n const traces: { z: any; type: string; }[] = [];\n images.forEach((dataset, index) => {\n const trace = {\n z: dataset,\n type: 'surface',\n // hoverinfo: 'none',\n colorscale: this.store.currentColormap().data.value,\n reversescale: this.store.currentReverseScale(),\n // name: `Slice ${index + 1}`,\n // visible: index === 0\n };\n traces.push(trace);\n });\n const xrange = [trueImgSize[0], trueImgSize[1]];\n const yrange = [trueImgSize[2], trueImgSize[3]];\n const render = inPlace ? Plotly.react : Plotly.newPlot;\n return (render as any)(plotDiv, traces as any,\n this.getSurfaceLayout(xrange, yrange, 0.4), CONFIG_SURFACE as any).then(() => {\n // handle the relayout event for zoom / rois and the click event\n this.setEvents(plotDiv, true, screenHeight);\n return true;\n });\n }\n\n /**\n * Function used to plot an RGB heatmap\n * @param plotDiv\n * @param urls\n * @param images\n * @param trueImgSize\n * @param width\n * @param height\n * @param ratios\n * @param screenHeight\n * @return Promise\n */\n private plotRGBHeatmap(plotDiv: string, urls: string[], images: any[], trueImgSize: number[],\n ratios: number[], width: number, height: number,\n screenHeight: number, inPlace: boolean = false): Promise<boolean> {\n // Plotly.react updates in place; Plotly.purge + Plotly.newPlot blanks\n // the canvas for ~100ms which makes the multi-tier small→large swap\n // look like a regression to \"loading\" before the sharper version\n // appears.\n if (!inPlace) Plotly.purge(plotDiv);\n this.plotDiv = plotDiv;\n this.imageLength = images.length;\n this.urls = urls;\n this.screenHeight = screenHeight;\n\n // as autorange is set to false, and not reversed we need to set the yrange correcly here\n const layout = this.getHeatmapLayout([trueImgSize[0], trueImgSize[1]],\n [trueImgSize[3], trueImgSize[2]]);\n const traces: { z: any; type: string; name: string; visible: boolean; }[] = [];\n images.forEach((dataset, index) => {\n const trace = {\n x0: trueImgSize[0],\n dx: ratios[0],\n y0: trueImgSize[2],\n dy: ratios[0],\n x: Array.from(Array(width).keys()),\n y: Array.from(Array(height).keys()),\n z: dataset,\n // text: dataset.map((row: any[], i: any) => row.map((item, j) => {\n // return `x: ${+(j * ratios[0]).toFixed(2)}<br>y: ${+(i * ratios[0]).toFixed(2)}<br>value: ${item}`})),\n hoverinfo: 'none',\n type: 'image',\n name: `Slice ${index + 1}`,\n visible: index === 0\n };\n traces.push(trace);\n });\n const render = inPlace ? Plotly.react : Plotly.newPlot;\n return (render as any)(plotDiv, traces as any, layout, CONFIG as any).then(() => {\n // handle the relayout event\n this.setEvents(plotDiv, false, screenHeight);\n return true;\n });\n }\n\n /**\n * Assemble the normalised input the pluggable trace builders consume.\n * Pure data only — no Plotly handles — so the builders stay backend-neutral.\n */\n private buildTraceInput(imageInfo: IImageInfo, imageLoaded: any,\n trueImageSize: number[]): TraceBuildInput {\n // Measure the volume's real intensity range so the iso band can be clamped\n // into it (the slider is a fixed 0–255 but a stack may occupy only part of\n // that, which would otherwise leave the surfaces with nothing to cross).\n if (this.plotType === PlotType.ISOSURFACE) {\n this.isoDataRange = this.measureIntensityRange(imageLoaded.data, !!imageInfo.isGrayscale);\n }\n const [isoMin, isoMax] = this.mapIsoBand(this.isoMin, this.isoMax);\n return {\n frames: imageLoaded.data,\n width: imageLoaded.sizes[0],\n height: imageLoaded.sizes[1],\n ratios: imageLoaded.ratios,\n trueImageSize,\n isGrayscale: !!imageInfo.isGrayscale,\n colorscale: this.store.currentColormap().data.value,\n reversescale: this.store.currentReverseScale(),\n regions: this.getRegionPolygons(),\n shapeColor: this.regionStore.getShapeColor(),\n isoMin,\n isoMax,\n };\n }\n\n /** Min/max intensity over every voxel of the loaded frames (RGB → luminance),\n * used to keep the iso band inside the data. Returns null for empty input. */\n private measureIntensityRange(frames: any[], isGrayscale: boolean): [number, number] | null {\n let min = Infinity, max = -Infinity;\n for (const frame of frames || []) {\n for (const row of frame || []) {\n for (const cell of row || []) {\n const v = isGrayscale ? cell\n : 0.299 * cell[0] + 0.587 * cell[1] + 0.114 * cell[2];\n if (!Number.isFinite(v)) continue;\n if (v < min) min = v;\n if (v > max) max = v;\n }\n }\n }\n return (Number.isFinite(min) && Number.isFinite(max) && max > min) ? [min, max] : null;\n }\n\n /** Map the 0–255 slider band onto the volume's actual intensity range. The\n * slider is fixed 0–255, but a stack often occupies only a narrow sub-range\n * (e.g. this EDOF volume is ~2–50 with structure near 6–10). Mapping spreads\n * the data across the whole slider so every intensity is easy to reach and\n * the band always lands inside the data — a small inset keeps the extreme\n * surfaces off the exact data edges, which are degenerate and draw nothing. */\n private mapIsoBand(isoMin: number, isoMax: number): [number, number] {\n let lo = Math.min(isoMin, isoMax);\n let hi = Math.max(isoMin, isoMax);\n if (this.isoDataRange) {\n const [vMin, vMax] = this.isoDataRange;\n const span = vMax - vMin;\n const pad = 0.03 * span;\n const usable = span - 2 * pad;\n const SLIDER_MAX = 255; // toolbar slider domain (isoValueMax)\n lo = vMin + pad + (lo / SLIDER_MAX) * usable;\n hi = vMin + pad + (hi / SLIDER_MAX) * usable;\n if (lo > hi) { const t = lo; lo = hi; hi = t; }\n }\n return [lo, hi];\n }\n\n /**\n * Update the isosurface intensity bounds. When isosurface is on screen this\n * restyles `isomin`/`isomax` in place for a live update (no volume rebuild).\n * Slider values are mapped onto the volume's real range so the surfaces always\n * have data to cross (matching the initial render).\n */\n public setIsoRange(isoMin: number, isoMax: number): void {\n this.isoMin = isoMin;\n this.isoMax = isoMax;\n if (this.plotType === PlotType.ISOSURFACE && this.plotDiv) {\n const [lo, hi] = this.mapIsoBand(isoMin, isoMax);\n try {\n Plotly.restyle(this.plotDiv, { isomin: [lo], isomax: [hi] } as any);\n } catch { /* plot not ready */ }\n }\n }\n\n /** Plotly renders isosurfaces, so it exposes the isosurface controls (itself). */\n public getIsosurfaceControls(): IIsosurfaceControls | null { return this; }\n\n /**\n * Render a registry-backed plot type: build its traces from the input, pick\n * the matching layout, render, and wire the usual relayout/click events.\n * Mirrors the structure of the dedicated heatmap/surface renderers.\n */\n private plotViaRegistry(plotDiv: string, impl: PlotlyPlotTypeImpl, input: TraceBuildInput,\n screenHeight: number, inPlace: boolean = false): Promise<boolean> {\n if (!inPlace) Plotly.purge(plotDiv);\n this.plotDiv = plotDiv;\n this.imageLength = input.frames.length;\n this.urls = this.imageInfo?.urls ?? this.urls;\n this.screenHeight = screenHeight;\n\n const traces = impl.buildTraces(input);\n const [x0, x1, y0, y1] = input.trueImageSize;\n let layout: any;\n switch (impl.layoutKind) {\n case '3d-volume':\n layout = this.getVolumeLayout();\n break;\n case '2d-chart':\n layout = this.getChartLayout();\n break;\n case '2d-overlay':\n layout = this.getOverlayLayout([x0, x1], [y1, y0]); // reversed y like the image\n break;\n default: // '2d-image'\n layout = this.getHeatmapLayout([x0, x1], [y1, y0]);\n }\n const config = impl.threeD ? CONFIG_SURFACE : CONFIG;\n const render = inPlace ? Plotly.react : Plotly.newPlot;\n return (render as any)(plotDiv, traces as any, layout, config as any).then(() => {\n this.setEvents(plotDiv, input.isGrayscale, screenHeight);\n return true;\n });\n }\n\n /** Plain 2D chart axes (intensity profile / line plots). */\n private getChartLayout(): any {\n return {\n margin: { t: 30, b: 45, l: 60, r: 20 },\n height: this.screenHeight,\n autosize: true,\n xaxis: { title: 'Position (px)' },\n yaxis: { title: 'Intensity' },\n dragmode: false,\n };\n }\n\n /** Image-aligned 2D axes without the z-plane slider (region scatter). */\n private getOverlayLayout(xRange: number[], yRange: number[]): any {\n return {\n xaxis: { constrain: 'range', constraintoward: 'center', side: 'top', ticks: '', range: xRange },\n yaxis: {\n constrain: 'range', constraintoward: 'center', range: yRange, ticks: '',\n ticksuffix: ' ', autorange: false, scaleanchor: this.scaleratio ? 'x' : false,\n },\n margin: { t: 30, b: 5, l: 55, r: 5 },\n height: this.screenHeight,\n autosize: true,\n shapes: this.currentRenderShapes(this.regionStore.getShowShapeLabel()),\n dragmode: this.dragMode ? this.dragMode : false,\n };\n }\n\n /** 3D scene for volumetric plot types (scatter3d, isosurface). */\n private getVolumeLayout(): any {\n return {\n margin: { t: 0, b: 0, l: 0, r: 0 },\n height: this.screenHeight,\n autosize: true,\n scene: {\n xaxis: { title: 'X' },\n yaxis: { title: 'Y' },\n zaxis: { title: 'Z-plane' },\n // 'cube' (not 'data'): a z-stack has far fewer planes than X/Y pixels,\n // so 'data' squashes the volume into a near-flat slab that reads as\n // empty edge-on. A cube gives the z dimension real height so the\n // isosurface/voxels are actually visible.\n aspectmode: 'cube',\n },\n };\n }\n\n /** Plot types this backend advertises (drives the UI selector). */\n public getPlotTypeDescriptors(): PlotTypeDescriptor[] {\n return Object.values(PLOT_TYPE_DESCRIPTORS).filter((d): d is PlotTypeDescriptor => !!d);\n }\n\n /** This backend's region renderer. Plotly draws shapes natively, so the\n * overlay is a thin adapter over this service's drag modes. */\n public getRegionOverlay(): IRegionOverlay {\n if (!this.regionOverlay) this.regionOverlay = new PlotlyRegionOverlay(this);\n return this.regionOverlay;\n }\n\n // ── Intensity profile (Region-based line ROIs) ──────────────────────\n\n /** Emits the full set of intensity profiles (one per profile-line region)\n * whenever a profile line is added, moved, or removed. */\n public getIntensityProfile$(): Observable<IntensityProfile[]> {\n return this.intensityProfile$.asObservable();\n }\n\n /** Plotly renders the line ROIs + inset, so it exposes the intensity controls. */\n public getIntensityControls(): IIntensityControls | null { return this; }\n\n /**\n * Render the floating intensity-profile inset chart into `divId` — one line\n * trace per ROI, each drawn in its ROI's colour. Kept here (not in the diagram\n * component) so the consumer never touches Plotly directly.\n */\n public renderIntensityInset(divId: string, profiles: IntensityProfile[]): void {\n const el = document.getElementById(divId);\n if (!el) return;\n const traces = (profiles ?? []).map((p, i) => ({\n x: p.positions,\n y: p.values,\n type: 'scatter',\n mode: 'lines',\n line: { color: p.color ?? '#FFD400', width: 2 },\n name: `Line ${i + 1}`,\n hoverinfo: 'x+y',\n }));\n // X axis is in microns when the image carries a physical pixel size (mpp),\n // otherwise in pixels — driven by the unit the sampler tagged on the profile.\n const unit = (profiles ?? []).find(p => p.unit)?.unit ?? 'px';\n const xTitle = unit === 'µm' ? 'Position (µm)' : 'Position (px)';\n Plotly.react(el, traces as any, {\n margin: { t: 6, r: 8, b: 38, l: 40 },\n xaxis: { title: xTitle, zeroline: false, color: '#ddd' },\n yaxis: { title: 'Intensity', zeroline: false, color: '#ddd' },\n showlegend: false,\n paper_bgcolor: 'rgba(25,25,25,0.9)',\n plot_bgcolor: 'rgba(25,25,25,0.9)',\n font: { color: '#eee', size: 10 },\n } as any, { displayModeBar: false, responsive: true } as any);\n }\n\n /**\n * Region shapes (filtered/redrawn for the current file). The profile-line ROIs\n * are ordinary store regions (tagged `kind: 'profile'`), so they are already\n * part of `this.shapes` — no separate append is needed.\n */\n private currentRenderShapes(showLabel = this.regionStore.getShowShapeLabel()): any[] {\n return this.shapesToRedraw(showLabel);\n }\n\n /**\n * IIntensityControls: add another intensity-profile line as a neutral Region\n * (tagged `kind: 'profile'`). It is a horizontal open 2-point polyline spanning\n * the image width, staggered vertically so successive lines stay distinct, in\n * the next bright palette colour. Added to the shared store so both backends\n * (Plotly + OpenSeadragon) render and drag it; excluded from the Regions tab\n * and exports by its kind.\n */\n public addProfileLine(): Region | null {\n if (!this.trueImgSize) return null;\n const count = this.getProfileRegions().length;\n const imgX0 = this.trueImgSize[0], imgX1 = this.trueImgSize[1];\n const imgTop = this.trueImgSize[2], imgBottom = this.trueImgSize[3];\n\n // Place the line within the currently VISIBLE image area, so when zoomed in it\n // lands on-screen instead of spanning the whole (mostly off-screen) image, at\n // 2/3 of the visible width and horizontally centred. Falls back to the full\n // image when no viewport ROI is known (Plotly heatmap) or a stale ROI no longer\n // overlaps the image.\n const roi = this.lastVisibleRoi;\n const overlaps = !!roi && roi.width > 0 && roi.height > 0\n && roi.x < imgX1 && roi.x + roi.width > imgX0\n && roi.y < imgBottom && roi.y + roi.height > imgTop;\n const x0v = overlaps ? Math.max(imgX0, roi!.x) : imgX0;\n const x1v = overlaps ? Math.min(imgX1, roi!.x + roi!.width) : imgX1;\n const topV = overlaps ? Math.max(imgTop, roi!.y) : imgTop;\n const bottomV = overlaps ? Math.min(imgBottom, roi!.y + roi!.height) : imgBottom;\n\n const cx = (x0v + x1v) / 2;\n const half = ((x1v - x0v) * (2 / 3)) / 2; // line spans 2/3 of the visible width\n const x0 = cx - half, x1 = cx + half;\n\n const bandH = bottomV - topV;\n const midY = (topV + bottomV) / 2;\n // Stagger successive lines across the visible band so they stay distinct.\n const y = Math.min(bottomV, Math.max(topV, midY + count * bandH * 0.12));\n\n const poly = new Polygon();\n poly.npoints = 2;\n poly.xpoints = [x0, x1];\n poly.ypoints = [y, y];\n poly.coordinates = [[x0, y], [x1, y]];\n poly.closed = false;\n\n const region = new Region();\n region.bounds = poly;\n region.kind = 'profile';\n region.color = this.PROFILE_PALETTE[this.profileColorSeq++ % this.PROFILE_PALETTE.length];\n // Leave region.label undefined so applyClassificationColors won't recolor it.\n\n this.regionStore.addRegion(region);\n\n // If a Plotly plot is on screen, re-render shapes so the new line appears.\n // (The OSD overlay renders automatically via its region-update subscription.)\n if (this.plotDiv) {\n this.syncShapesFromStore();\n try {\n Plotly.relayout(this.plotDiv, { shapes: this.currentRenderShapes() } as any);\n } catch { /* div not a Plotly plot (OSD owns it) */ }\n }\n return region;\n }\n\n /** The profile-line ROIs currently in the store (kind === 'profile'). */\n private getProfileRegions(): Region[] {\n return this.regionStore.getRegions().filter(r => (r as any).kind === 'profile');\n }\n\n /** Recompute and broadcast a profile for every profile-line region (id + colour\n * tagged so the inset trace matches its line). */\n private emitProfiles(): void {\n this.intensityProfile$.next(this.getProfileRegions().map(r => ({\n ...this.computeIntensityProfileForRegion(r),\n id: r.id,\n color: r.color,\n })));\n }\n\n /**\n * Sample the intensity profile for a profile-line region: extract its two\n * polygon endpoints and reuse the shared `computeIntensityProfile` sampling.\n */\n private computeIntensityProfileForRegion(region: Region): IntensityProfile {\n // Duck-typed (not `instanceof Polygon`): after a drag round-trips through the\n // store the bounds can be a plain object, so match on the point arrays.\n const poly: any = region.bounds;\n if (!poly || !Array.isArray(poly.xpoints) || !Array.isArray(poly.ypoints) ||\n poly.xpoints.length < 2 || poly.ypoints.length < 2) {\n return { positions: [], values: [] };\n }\n return this.computeIntensityProfile({\n x0: poly.xpoints[0], y0: poly.ypoints[0],\n x1: poly.xpoints[1], y1: poly.ypoints[1],\n });\n }\n\n /**\n * Supply pixel frames for intensity sampling (used by the OSD/image backend,\n * whose cached frames may be empty). Optionally also sets the data/pixel ratios.\n */\n public setSamplingFrames(frames: any[], ratios: number[], origin: [number, number] = [0, 0]): void {\n this.cachedImageFrames = frames;\n if (ratios) this.cachedImageRatios = ratios;\n this.cachedFrameOrigin = origin;\n }\n\n /**\n * Populate the sampling cache for the intensity profiles when OpenSeadragon is\n * the active backend (the Image plot type). In OSD mode Plotly never rendered,\n * so `cachedImageFrames`/`trueImgSize` are unset — fetch the current slice's\n * preview (the same pixels the heatmap would sample) so the line ROIs have\n * pixel data and a placement extent. Re-emits the profiles once loaded.\n */\n public async ensureIntensitySampling(imageInfo: IImageInfo, zIndex: number): Promise<void> {\n if (!imageInfo?.urls?.length) return;\n // Sample just the displayed slice (showStack off → single frame); `load`\n // also sets `this.trueImgSize`, which addProfileLine needs for placement.\n const single = { ...imageInfo, showStack: false } as IImageInfo;\n const loaded = await this.load(single, zIndex || 0);\n this.cachedImageFrames = loaded.data;\n this.cachedImageRatios = loaded.ratios;\n this.cachedImageWidth = loaded.sizes?.[0] ?? this.cachedImageWidth;\n this.cachedImageHeight = loaded.sizes?.[1] ?? this.cachedImageHeight;\n this.cachedFrameOrigin = [0, 0]; // full preview\n this.cachedIsGrayscale = !!imageInfo.isGrayscale;\n this.emitProfiles();\n }\n\n /**\n * {@link IIntensitySampling} stub — the viewport-change signal is OpenSeadragon's\n * (it re-samples on OSD zoom/pan). Plotly's own high-def zoom updates the\n * sampling cache inline, so it never emits here; returns EMPTY so a uniform\n * `IVisualizer` consumer can subscribe regardless of the active backend.\n */\n public getViewportChange$(): Observable<{ x: number; y: number; width: number; height: number }> {\n return EMPTY;\n }\n\n /**\n * Re-fetch the given image-pixel ROI at the display resolution and use it as\n * the intensity-sampling source, so the profile reflects the data at the\n * current zoom level. Shared by both backends: the OSD viewport-change hook\n * calls it on zoom/pan; Plotly's own high-def zoom (triggerZoom) updates the\n * same cache inline. `roi` is in full-image pixel coordinates.\n */\n public refreshIntensitySamplingForRoi(x: number, y: number, width: number, height: number,\n zIndex: number): void {\n if (width <= 0 || height <= 0) return;\n // Remember the visible region so a new profile line is placed inside it.\n this.lastVisibleRoi = { x, y, width, height };\n const roi = new Rectangle();\n roi.x = Math.round(x); roi.y = Math.round(y);\n roi.width = Math.round(width); roi.height = Math.round(height);\n const screen = this.plotUtilities.getDomRectangle('diagram');\n // Snapshot the filename so a response that arrives after the user switched\n // files is dropped (the request carried the file selected at call time).\n const reqName = this.fileName;\n this.tiles.zoomOnRegion(roi, screen, zIndex || 0).subscribe({\n next: (zoomData) => {\n Image.load(Buffer.from(new Uint8Array(zoomData))).then((image: any) => {\n if (this.fileName !== reqName) return;\n const isGray = !!this.imageInfo?.isGrayscale;\n const frame = isGray\n ? this.plotUtilities.arrayToMatrix(image.grey().data, image.width)\n : this.plotUtilities.arrayToMatrix(image.getPixelsArray(), image.width);\n this.setSamplingFrames([frame], [roi.width / image.width, roi.height / image.height],\n [roi.x, roi.y]);\n this.emitProfiles();\n });\n },\n error: () => { /* keep the previous sampling frame on a failed crop fetch */ },\n });\n }\n\n /**\n * Sample the active frame's intensity (grayscale value or RGB luminance)\n * along the line ROI. Returns distance-along-line positions and values.\n */\n private computeIntensityProfile(line: any): IntensityProfile {\n const empty: IntensityProfile = { positions: [], values: [] };\n if (!this.cachedImageFrames?.length || !line) return empty;\n const frame = this.cachedImageFrames[this.activeFrameIndex()] ?? this.cachedImageFrames[0];\n if (!frame?.length) return empty;\n const rx = this.cachedImageRatios[0] || 1;\n const ry = this.cachedImageRatios[1] || rx;\n const [ox, oy] = this.cachedFrameOrigin;\n const x0 = +line.x0, y0 = +line.y0, x1 = +line.x1, y1 = +line.y1;\n const dxData = x1 - x0, dyData = y1 - y0;\n // Scale the along-line distance by the physical pixel size (microns/pixel)\n // when the image carries one — anisotropic mppX/mppY are applied per axis so\n // diagonal lines measure the true physical length. Falls back to pixels.\n const { mppX, mppY } = this.currentMpp();\n const useMicrons = mppX != null;\n const lenData = useMicrons\n ? Math.hypot(dxData * mppX, dyData * (mppY ?? mppX))\n : Math.hypot(dxData, dyData);\n const lenPx = Math.hypot(dxData / rx, dyData / ry);\n const n = Math.max(2, Math.round(lenPx));\n const h = frame.length;\n const w = frame[0].length;\n const positions: number[] = [];\n const values: number[] = [];\n for (let i = 0; i < n; i++) {\n const t = i / (n - 1);\n // Map data coords to the cached frame's pixel grid, offset by the frame's\n // origin (non-zero when the frame is a zoomed crop).\n const px = Math.round((x0 + t * dxData - ox) / rx);\n const py = Math.round((y0 + t * dyData - oy) / ry);\n let v = 0;\n if (px >= 0 && px < w && py >= 0 && py < h) {\n const cell = frame[py][px];\n v = Array.isArray(cell) ? (0.299 * cell[0] + 0.587 * cell[1] + 0.114 * cell[2]) : cell;\n }\n positions.push(t * lenData);\n values.push(v);\n }\n return { positions, values, unit: useMicrons ? 'µm' : 'px' };\n }\n\n /** Physical pixel size (microns/pixel) for the current image, if known.\n * mpp is constant across frames/channels, so the first metadata entry that\n * carries a positive mppX wins. Returns nulls when the image is unscaled. */\n private currentMpp(): { mppX: number | null; mppY: number | null } {\n const meta = this.imageInfo?.imageMeta;\n const m = Array.isArray(meta)\n ? (meta.find(e => e && (e.mppX ?? 0) > 0) ?? meta[0])\n : undefined;\n const mppX = m && (m.mppX ?? 0) > 0 ? (m.mppX as number) : null;\n const mppY = m && (m.mppY ?? 0) > 0 ? (m.mppY as number) : null;\n return { mppX, mppY };\n }\n\n /**\n * autoscale the plot\n */\n public autoscale() {\n if (this.plotDiv) {\n this.zoomCoordinates = [];\n Plotly.relayout(this.plotDiv, {\n 'xaxis.autorange': true,\n 'yaxis.autorange': false }\n );\n }\n }\n\n /**\n * relayout the plot\n */\n public relayout(trueImageSize?: number[]) {\n let imgSize;\n if (trueImageSize) {\n imgSize = trueImageSize;\n } else {\n imgSize = this.trueImgSize;\n }\n if (this.plotDiv) {\n // Refresh height from current DOM so panel resizes are reflected\n const plotEl = document.getElementById(this.plotDiv);\n if (plotEl?.offsetHeight) {\n this.screenHeight = plotEl.offsetHeight;\n }\n try {\n if (this.zoomCoordinates.length > 0) {\n Plotly.relayout(this.plotDiv, this.getHeatmapLayout(\n [this.zoomCoordinates[0], this.zoomCoordinates[1]],\n [this.zoomCoordinates[2], this.zoomCoordinates[3]])); // reverse the y range\n } else {\n // as autorange is set to false, and not reversed we need to set the yrange correcly here\n Plotly.relayout(this.plotDiv, this.getHeatmapLayout(\n [imgSize[0], imgSize[1]], [imgSize[3], imgSize[2]]));\n }\n } catch (err: any) {\n const msg = err?.error?.message || err?.message || err?.statusText || String(err);\n console.error('Error occured', err);\n this.messageService.add({ key: 'center-toast', sticky: true, severity:'error', summary:'An error occured', detail:`The following\n error occured: ${msg}. Please try to open the image again through the\n file navigator.` });\n // TODO correctly clear the plot\n this.reset();\n }\n }\n }\n\n private setEvents(plotDiv: string, isGrayscale: boolean, screenHeight: number) {\n this.imageInfo.isGrayscale = isGrayscale;\n this.screenHeight = screenHeight;\n const plot: any = document.getElementById(plotDiv);\n if (plot) {\n // unbind previous event\n plot.removeEventListener('plotly_relayout', this.onRelayoutEvent);\n // bind new event\n plot.on('plotly_relayout', this.onRelayoutEvent);\n\n // Clicking on a shape activates it but Plotly doesn't fire a dedicated\n // event — sample _activeShapeIndex on the next microtask so subscribers\n // (Region Editor) can mirror the selection.\n plot.removeEventListener('mousedown', this.onPlotMouseDown);\n this.onPlotMouseDown = () => setTimeout(() => this.maybeEmitActiveShapeIndex(), 0);\n plot.addEventListener('mousedown', this.onPlotMouseDown);\n }\n }\n\n private relayoutEventHandler(event: any) {\n if (Object.keys(event).includes('dragmode')) {\n this.dragMode = event.dragmode;\n }\n // when relayout event occurs\n // update the region selection udpdates\n const keys = Object.keys(event);\n let shapesModified = false;\n keys.forEach((key: any) => {\n if (typeof key === 'string' && key.startsWith('shapes[')) {\n const shapeNumber = +key.split('[')[1].split(']')[0];\n const shapeChange = key.split('.')[1];\n if (this.shapes && this.shapes[shapeNumber]) {\n if (shapeChange === 'path') {\n this.shapes[shapeNumber][shapeChange] = this.plotUtilities.roundPathCoordinates(event[key]);\n } else {\n this.shapes[shapeNumber][shapeChange] = Math.round(+event[key]);\n }\n shapesModified = true;\n }\n }\n });\n if (shapesModified) {\n // Mirror the in-place edit into the shared store (syncs its cache + emits).\n this.commitShapesToStore();\n }\n // manage high def zoom (not if we are showing a stack)\n if (keys.length === 4 && this.isRealZoom) {\n const coordinates: any[] = [];\n keys.forEach(key => {\n if (key.startsWith('xaxis.range[')) {\n coordinates.push(event[key]);\n }\n if (key.startsWith('yaxis.range[')) {\n coordinates.push(event[key]);\n }\n });\n this.zoomCoordinates = coordinates;\n if (!this.imageInfo.showStack) {\n this.triggerZoom(coordinates);\n }\n }\n // when shape is created\n if (keys.length === 1 && 'shapes' in event) {\n this.shapes = event.shapes as any[];\n for (let i = 0; i < this.shapes.length; i++) {\n // A freshly Plotly-drawn shape has no id yet — give it a label object\n // (when labels are on) before the store mints id + default name.\n const isNew = this.shapes[i].id == null;\n this.shapes[i].fileName = this.fileName;\n this.shapes[i] = this.plotUtilities.snapRegion(this.shapes[i]);\n if (isNew && this.regionStore.getShowShapeLabel()) {\n this.shapes[i].label = { text: this.shapes[i].label,\n texttemplate: this.shapes[i].label,\n font: { color: this.regionStore.getShapeColor() },\n textposition: 'top left'\n };\n }\n }\n // Mint ids/names in the store, write them back onto the dicts, and emit.\n this.commitShapesToStore();\n if (this.isRegionSavedOn) {\n this.previousShapes = this.shapes.slice();\n }\n }\n // if autoscale\n if (keys.includes('xaxis.autorange') && keys.includes('yaxis.autorange')) {\n // trigger an autoscale event to reset the selected image mode dropdown\n this.autoscaleEvent.next('an autoscale has happened');\n // select display type to trigger a new plotting update with all the necessary plotting parameters set\n this.tiles.selectDiagramDisplay();\n }\n // if showstack or aspectratio event\n if (event.showstack !== undefined || event.aspectratio !== undefined) {\n // Set new image info to trigger a plot update\n this.setImageInfo(event.showstack, event.aspectratio);\n }\n\n // Plotly may have updated the active shape index as part of the relayout\n // (e.g. clicking a shape's edit handle, or finishing a draw) — surface\n // that change to the Region Editor.\n this.maybeEmitActiveShapeIndex();\n }\n\n public reloadAndPlot() {\n this.setImageInfo();\n }\n\n\n // ── Tool delegations ────────────────────────────────────────────────\n\n public setWandMode(active: boolean, options: WandOptions = {}) {\n // Re-bind to ourselves in case the OSD backend last used these singletons.\n if (active) this.wandTool.bindHost(this.wandHost);\n this.wandTool.setMode(active, options);\n }\n\n public setWandOptions(options: WandOptions) {\n this.wandTool.setOptions(options);\n }\n\n public clearActiveWandRegion() {\n this.wandTool.clearActiveRegion();\n }\n\n public setBrushMode(active: boolean, options: BrushOptions = {}) {\n // Re-bind to ourselves in case the OSD backend last used this singleton.\n if (active) this.brushTool.bindHost(this.wandHost);\n this.brushTool.setMode(active, options);\n }\n\n public setBrushOptions(options: BrushOptions) {\n if (options.size != null) this.brushTool.setSize(options.size);\n }\n\n public setVertexEraserMode(active: boolean) {\n if (active) this.vertexEraserTool.bindHost(this.eraserHost);\n this.vertexEraserTool.setMode(active);\n }\n\n public setVertexEraserRadius(radius: number) {\n this.vertexEraserTool.setRadius(radius);\n }\n\n public setZoomToBoxMode(active: boolean) {\n // The zoom-to-box tool is a root singleton shared with the OSD backend,\n // which rebinds it to its own host on activation. Rebind to ours when we\n // activate so a prior OSD zoom-to-box doesn't leave the singleton pointing\n // at OSD's coordinate/zoom handlers (which would break box-zoom on heatmaps).\n if (active) this.bindZoomToBoxHost();\n this.zoomToBoxTool.setMode(active);\n }\n\n /** Bind the shared zoom-to-box tool to this (Plotly) backend's host. */\n private bindZoomToBoxHost() {\n this.zoomToBoxTool.bindHost({\n getPlotDiv: () => this.plotDiv,\n pixelToData: (px, py) => this.zoomBoxPixelToData(px, py),\n applyZoomToBox: (coords) => this.applyZoomToBox(coords),\n });\n }\n\n /** Box-prompted SAM: segment the drawn rectangles. The SAM tool reuses the\n * wand host (cached frame + coordinate transform + region store). */\n public segmentRectangles(): Promise<number> {\n this.samTool.bindHost(this.wandHost);\n return this.samTool.segmentBoxes();\n }\n public segmentRectanglesCellpose(): Promise<number> {\n if (!this.cellSegmenter) return Promise.resolve(0);\n this.cellSegmentTool.bindHost(this.wandHost);\n return this.cellSegmentTool.segmentBoxes(this.cellSegmenter);\n }\n public setSamModel(id: string): void {\n this.samTool.setModel(id);\n this.samPointTool.setModel(id);\n }\n public setSamPointMode(active: boolean): void {\n if (active) this.samPointTool.bindHost(this.wandHost);\n this.samPointTool.setMode(active);\n }\n public commitSamPoints(): void { this.samPointTool.commit(); }\n public clearSamPoints(): void { this.samPointTool.clear(); }\n\n /**\n * Tool-host callback: apply the zoom-to-box selection. Stack mode does a\n * pure axis-range relayout; non-stack mode goes through the high-def\n * triggerZoom pipeline so the image is re-fetched at the new resolution.\n */\n /** Overlay-pixel -> Plotly data coords via the axis objects (subtracting the\n * plot margin offset). The zoom-to-box tool calls this through its host. */\n private zoomBoxPixelToData(px: number, py: number): { x: number; y: number } {\n const gd: any = document.getElementById(this.plotDiv);\n const xaxis = gd._fullLayout.xaxis;\n const yaxis = gd._fullLayout.yaxis;\n return { x: xaxis.p2d(px - xaxis._offset), y: yaxis.p2d(py - yaxis._offset) };\n }\n\n private applyZoomToBox(coordinates: number[]) {\n this.zoomCoordinates = coordinates;\n if (this.imageInfo?.showStack) {\n Plotly.relayout(this.plotDiv, {\n 'xaxis.range[0]': coordinates[0],\n 'xaxis.range[1]': coordinates[1],\n 'yaxis.range[0]': coordinates[2],\n 'yaxis.range[1]': coordinates[3],\n } as any);\n } else {\n this.triggerZoom(coordinates);\n }\n }\n\n // ── IViewportHost implementation (for the on-canvas tools) ──────────\n\n /** The plot element the tool canvas overlays attach to. */\n public getOverlayContainer(): HTMLElement | null {\n return this.plotDiv ? document.getElementById(this.plotDiv) : null;\n }\n\n /** Plotly coordinate transform (screen <-> data via the axis objects). */\n public getCoordinateTransform(): ICoordinateTransform {\n return this.coordinateTransform;\n }\n\n // ── WandToolHost implementation ─────────────────────────────────────\n\n /** Pixel data the wand needs for sampling. null = no image loaded. */\n private getCachedImageData(): CachedImageData | null {\n if (!this.cachedImageFrames || this.cachedImageFrames.length === 0) return null;\n return {\n frames: this.cachedImageFrames,\n width: this.cachedImageWidth,\n height: this.cachedImageHeight,\n ratios: this.cachedImageRatios,\n isGrayscale: this.cachedIsGrayscale,\n };\n }\n\n // ── shared-store sync helpers ──────────────────────────────────────────\n //\n // `this.shapes` is Plotly's own representation (the dict array Plotly.relayout\n // consumes). The shared RegionStore is the single source of truth, holding the\n // neutral Region model. These helpers bridge the two: writes mirror\n // `this.shapes` INTO the store; image switches/external changes project the\n // store back OUT to `this.shapes`.\n\n /** Build Plotly shape dicts from the store's regions (the render projection). */\n private regionsToShapeDicts(): any[] {\n const showLabel = this.regionStore.getShowShapeLabel();\n return this.regionStore.getRegions().map(r => {\n r.filename = this.fileName;\n return { ...r.getShape(showLabel) };\n });\n }\n\n /** Rebuild the dict working-set from the store (after an image switch, or when\n * regions changed while another backend was rendering). */\n private syncShapesFromStore(): void {\n this.shapes = this.regionsToShapeDicts();\n }\n\n /**\n * Make the shared store authoritative for the current dict working-set: convert\n * `this.shapes` to neutral regions and replace the store's list (the store\n * mints ids, applies class colours, syncs its per-image cache and emits the\n * region-update event). Store-minted ids are written back onto the dicts so the\n * two representations stay aligned. Profile-line ROIs are ordinary regions\n * (tagged `kind: 'profile'`) and round-trip through here too.\n */\n private commitShapesToStore(): void {\n const regions = this.shapes\n .map(s => Object.assign(new ShapeSelection(), s).getRegion());\n this.regionStore.setRegions(regions, this.regionStore.getShowShapeLabel(), true,\n this.regionStore.getFillColor(), false);\n const stored = this.regionStore.getRegions();\n for (let i = 0; i < this.shapes.length && i < stored.length; i++) {\n if (this.shapes[i].id == null) this.shapes[i].id = stored[i].id;\n if (this.shapes[i].name == null) this.shapes[i].name = stored[i].name;\n }\n }\n\n /**\n * Push the current `this.shapes` to Plotly, mirror them into the shared store\n * (which syncs its cache + emits the region-update event), and refresh the\n * local previous-shapes buffer. The wand/eraser tools call this after mutating\n * the shapes array directly.\n */\n public applyShapesChange() {\n if (this.isRegionSavedOn) {\n this.previousShapes = this.shapes.slice();\n }\n this.commitShapesToStore();\n if (this.plotDiv) {\n const dictArray = this.shapes.map(s => ({ ...s }));\n try {\n Plotly.relayout(this.plotDiv, this.shapesRelayout(dictArray) as any);\n } catch { /* div owned by another backend (OSD) — its overlay renders shapes */ }\n }\n }\n\n /** Active frame index in the cached image stack. */\n private activeFrameIndex(): number {\n if (!this.cachedImageFrames || this.cachedImageFrames.length <= 1) return 0;\n const gd: any = document.getElementById(this.plotDiv);\n const sliderActive = gd?._fullLayout?.sliders?.[0]?.active;\n if (typeof sliderActive === 'number') return sliderActive;\n return this.zIndex.value || 0;\n }\n\n /** Capability-gated 3D scene controls (Plotly renders the 3D plot types). */\n getSurface3dControls() {\n return {\n setSurfaceDragMode: (mode: string) => this.setSurfaceDragMode(mode),\n resetSurfaceCamera: () => this.resetSurfaceCamera(),\n };\n }\n\n public setSurfaceDragMode(mode: string) {\n if (this.plotDiv) {\n Plotly.relayout(this.plotDiv, { 'scene.dragmode': mode } as any);\n }\n }\n\n public resetSurfaceCamera() {\n if (this.plotDiv) {\n Plotly.relayout(this.plotDiv, { 'scene.camera': {} } as any);\n }\n }\n\n private triggerZoom(coordinates: number[]) {\n if (coordinates.length === 0 || !this.trueImgSize) return;\n this.zoomCoordinates = coordinates;\n const rect = this.plotUtilities.getRectangle(coordinates, this.trueImgSize);\n if (this.plotUtilities.isZoomSameAsImgSize(rect, this.trueImgSize)) {\n this.autoscale();\n return;\n }\n // A brief \"Caching image...\" message for uncached files (large files take a\n // moment to cache); just a spinner otherwise.\n this.state.setImageLoadingMessage(this.imageCached ? '' : 'Caching image...');\n const screen = this.plotUtilities.getDomRectangle('diagram');\n const imageSize: any[] = [];\n imageSize[0] = rect.x;\n imageSize[1] = rect.x + rect.width;\n imageSize[2] = rect.y;\n imageSize[3] = rect.y + rect.height;\n // Snapshot the filename so a response that arrives after the user switched\n // files is dropped (the request carried the file selected at call time).\n const reqName = this.fileName;\n this.state.setImageLoading(true);\n this.state.setZoom(true);\n this.tiles.zoomOnRegion(rect, screen, this.zIndex.value).subscribe({ next: zoomData => {\n const uint8Array = new Uint8Array(zoomData);\n const buffer = Buffer.from(uint8Array);\n Image.load(buffer).then((image: any) => {\n const xRatio = rect.width / image.width;\n const yRatio = rect.height / image.height;\n if (this.fileName === reqName) {\n const isGray = this.imageInfo.isGrayscale;\n const frame = isGray\n ? this.plotUtilities.arrayToMatrix(image.grey().data, image.width)\n : this.plotUtilities.arrayToMatrix(image.getPixelsArray(), image.width);\n // Also sample the intensity profiles from this high-def crop so the\n // inset reflects the zoom-level resolution (origin = crop top-left).\n this.setSamplingFrames([frame], [xRatio, yRatio], [imageSize[0], imageSize[2]]);\n this.emitProfiles();\n // Re-render the high-def crop in the SAME plot type the user is\n // viewing. Without this the zoom re-fetch always fell back to a\n // heatmap, so zooming in contour (or any registry type) reverted\n // to heatmap.\n const impl = PLOTLY_PLOT_TYPE_IMPLS[this.plotType];\n const renderPromise = impl\n ? this.plotViaRegistry(this.plotDiv, impl,\n this.buildTraceInput(this.imageInfo, {\n data: [frame], ratios: [xRatio, yRatio],\n sizes: [image.width, image.height], filename: reqName,\n }, imageSize), this.screenHeight)\n : (isGray\n ? this.plotHeatmap(this.plotDiv, this.urls, [frame], imageSize, [xRatio, yRatio],\n this.screenHeight)\n : this.plotRGBHeatmap(this.plotDiv, this.urls, [frame], imageSize, [xRatio, yRatio],\n image.width, image.height, this.screenHeight));\n // plotViaRegistry already applies the type's own layout/range for\n // non-image layouts (chart/overlay); only re-apply the heatmap\n // range for the image-aligned paths.\n const reapplyRange = !impl || impl.layoutKind === '2d-image';\n renderPromise.then(() => {\n this.state.setImageCached(true);\n this.state.setImageLoading(false);\n image = null;\n if (reapplyRange) this.relayout(imageSize);\n });\n }\n });\n }, error: err => {\n const msg = err?.error?.message || err?.message || err?.statusText || String(err);\n console.error('Error occured when zooming', err);\n this.messageService.add({ key: 'center-toast', sticky: true, severity:'error', summary:'An error occured',\n detail:`The following error occured while zooming: ${msg}.\n Please try to open the image again through the file navigator and\n zoom on the selected area once more.` });\n this.state.setLoadingError(true);\n this.state.setImageLoading(false);\n }, complete: () => {\n console.log('zooming complete');\n } });\n }\n\n public setPlotType(plotType: PlotType) {\n this.plotType = plotType;\n }\n\n private setImageInfo(showStack?: boolean, scaleratio?: boolean) {\n // Build a partial image descriptor and push it to the host via the port.\n const imgInfo: Partial<IImageInfo> = {\n isGrayscale: this.imageInfo.isGrayscale,\n trueImageSize: [this.trueImgSize[1], this.trueImgSize[3]],\n urls: this.urls,\n isStack: this.urls.length > 1,\n scaleRatio: scaleratio !== undefined ? scaleratio : this.scaleratio,\n };\n if (showStack !== undefined) imgInfo.showStack = showStack;\n if (this.fileName) imgInfo.fileName = this.fileName;\n this.state.setImageInfo(imgInfo);\n }\n\n public getShapes() {\n return this.shapes;\n }\n\n /**\n * Framework-neutral view of the current regions — delegates to the shared\n * RegionStore (the single source of truth). The canonical accessor on the\n * `IVisualizer` contract; consumers should prefer this over `getShapes()`\n * (which exposes Plotly-shaped dicts).\n */\n public getRegions(): Region[] {\n return this.regionStore.getRegions();\n }\n\n /**\n * Switch the active image. The shared RegionStore owns the per-image region\n * cache (snapshot outgoing / restore incoming / clear selection / emit); we\n * delegate to it, then re-project the store's regions into Plotly's dict\n * working-set. Re-projecting unconditionally (even when the store no-ops for\n * the same image) means Plotly also picks up regions another backend (OSD)\n * added while it was off-screen. Called from `plot()` and from the router\n * before any backend renders.\n */\n public setActiveImage(imageInfo: IImageInfo) {\n this.regionStore.setActiveImage(imageInfo);\n this.syncShapesFromStore();\n this.previousShapes = this.shapes.slice();\n }\n\n /** Test/dev hook — drop the entire per-image cache (logout / project switch). */\n public clearRegionsByImageKey() {\n this.regionStore.clearRegionsByImageKey();\n }\n\n /**\n * Get all the selected regions as polygons. Open polylines (closed === false)\n * are excluded — they're annotation-only and cannot be used as filled regions\n * for image processing. Delegates to the shared store.\n */\n public getRegionPolygons(): any[] {\n return this.regionStore.getRegionPolygons();\n }\n\n isRectangle(bnds: any): bnds is Rectangle {\n return 'x' in bnds && 'y' in bnds && 'width' in bnds && 'height' in bnds;\n }\n\n isPolygon(bnds: any): bnds is Polygon {\n return 'npoints' in bnds && 'xpoints' in bnds && 'ypoints' in bnds;\n }\n\n /**\n * Set plot regions. Delegates the state change to the shared RegionStore\n * (id/name minting, classification colours, append de-duplication, per-image\n * cache and the region-update event all live there), then re-projects the\n * store's regions into Plotly's dict working-set and renders.\n *\n * When `isRegionSaveOn` is false the regions are shown transiently — rendered\n * without altering the stored working-set (preserves the prior behaviour).\n */\n public setRegions(regions: Region[], showRegionLabel?: boolean,\n isRegionSaveOn?: boolean, fillColor?: string,\n append: boolean = false) {\n const showLabel = showRegionLabel === undefined ? this.regionStore.getShowShapeLabel() : showRegionLabel;\n const save = isRegionSaveOn === undefined ? this.isRegionSavedOn : isRegionSaveOn;\n\n this.regionStore.setRegions(regions, showRegionLabel, isRegionSaveOn, fillColor, append);\n this.isRegionSavedOn = save;\n\n if (save) {\n // Re-project the authoritative regions into Plotly's working-set and render.\n this.syncShapesFromStore();\n this.renderShapes();\n } else {\n // Transient display only — render the passed regions, don't touch the\n // working-set (and the store didn't store them either).\n const dicts = regions.map(r => { r.filename = this.fileName; return { ...r.getShape(showLabel) }; });\n try {\n Plotly.relayout(this.plotDiv, this.shapesRelayout(dicts) as any);\n } catch { /* div owned by another backend (OSD) — its overlay renders shapes */ }\n }\n }\n\n /** The shapes-relayout payload: region shapes (profile-line ROIs included, as\n * they are ordinary regions) plus the active-shape fill colour. */\n private shapesRelayout(shapeDicts: any[]): any {\n return {\n shapes: shapeDicts,\n activeshape: { fillcolor: this.regionStore.getFillColor() },\n };\n }\n\n /** Push the current dict working-set to Plotly (no-op when another backend\n * owns the div). */\n private renderShapes(): void {\n if (!this.plotDiv) return;\n const dictArray = this.shapes.map(s => ({ ...s }));\n try {\n Plotly.relayout(this.plotDiv, this.shapesRelayout(dictArray) as any);\n } catch { /* div owned by another backend (OSD) — its overlay renders shapes */ }\n }\n\n getShowShapeLabel() {\n return this.regionStore.getShowShapeLabel();\n }\n\n /**\n * Set previous saved shapes\n */\n public plotPreviousShapes() {\n // convert to dict so that plotly recognises the shapes\n const dictArray = this.previousShapes.map(s => ({ ...s }));\n try {\n Plotly.relayout(this.plotDiv, { shapes: dictArray });\n } catch { /* div owned by another backend (OSD) */ }\n }\n\n setPreviousShapes(shapes: ShapeSelection[]) {\n this.previousShapes = shapes;\n }\n\n getPreviousShapes() {\n return this.previousShapes;\n }\n\n // Undo (jit-ui#85): region history lives in the shared RegionStore, so the\n // active backend's overlay re-renders off its regionUpdate$ on restore.\n public undo(): void { this.regionStore.undo(); }\n public redo(): void { this.regionStore.redo(); }\n public canUndo(): boolean { return this.regionStore.canUndo(); }\n public canRedo(): boolean { return this.regionStore.canRedo(); }\n public getCanUndo$(): Observable<boolean> { return this.regionStore.getCanUndo$(); }\n public getCanRedo$(): Observable<boolean> { return this.regionStore.getCanRedo$(); }\n public resetUndoHistory(): void { this.regionStore.resetUndoHistory(); }\n\n // ── Per-slice z-stack regions → RegionStore (jit-ui#93) ──────────────────\n public enterStackMode(slices: Map<number, Region[]>, initialZ?: number,\n saveLayout?: 'combined' | 'per-slice-file'): void {\n this.regionStore.enterStackMode(slices, initialZ, saveLayout);\n }\n public exitStackMode(): void { this.regionStore.exitStackMode(); }\n public isStackMode(): boolean { return this.regionStore.isStackMode(); }\n public getStackSaveLayout(): 'combined' | 'per-slice-file' {\n return this.regionStore.getStackSaveLayout();\n }\n public setDisplaySlice(z: number): void { this.regionStore.setDisplaySlice(z); }\n public getSliceRegions(): Region[] { return this.regionStore.getSliceRegions(); }\n public getStackSaveSlices(): Map<number, Region[]> { return this.regionStore.getStackSaveSlices(); }\n\n private getHeatmapLayout(xRange: number[], yRange: number[]): any {\n return {\n xaxis: {\n constrain: 'range',\n constraintoward: 'center',\n side: 'top',\n ticks: '',\n range: xRange\n },\n yaxis: {\n constrain: 'range',\n constraintoward: 'center',\n range: yRange,\n ticks: '',\n ticksuffix: ' ',\n\t\t\t\t// set autorange to false so that plotly does not overwrite the range for the y axis\n\t\t\t\tautorange: false,\n scaleanchor: this.scaleratio ? 'x' : false\n },\n margin: { t: 30, b: 5, l: 55, r: 5 },\n height: this.screenHeight,\n sliders: [{\n pad: { t: 50 },\n currentvalue: {\n visible: true,\n prefix: 'Z-plane:',\n xanchor: 'right',\n },\n steps: this.getSteps()\n }],\n autosize: true,\n shapes: this.currentRenderShapes(this.regionStore.getShowShapeLabel()),\n activeshape: { fillcolor: this.regionStore.getFillColor() },\n dragmode: this.dragMode ? this.dragMode : false,\n newshape: { line: { color: this.regionStore.getShapeColor(), width: 3 } }\n };\n }\n\n private shapesToRedraw(showLabel: boolean) {\n const shapesToRedraw: ShapeSelection[] = [];\n for (const shape of this.shapes) {\n if (JSON.stringify(shape.fileName) === JSON.stringify(this.fileName)) {\n // Set label\n if (showLabel) {\n shape.label = {\n text: `${shape.legend}`,\n texttemplate: `${shape.legend}`,\n textposition: 'top left',\n font: { color: `${shape.line.color}` }\n };\n } else {\n shape.label = {};\n }\n shapesToRedraw.push(shape);\n }\n }\n // convert to dict so that plotly recognises the shapes\n return shapesToRedraw.map(s => ({ ...s }));\n }\n /**\n * Unused (will be used when surface plot is added)\n * @param xRange\n * @param yRange\n * @param zRatio\n * @private\n */\n private getSurfaceLayout(xRange: number[], yRange: number[], zRatio: number): any {\n return {\n margin: { t: 0, b: 0, l: 0, r: 0 },\n scene: {\n xaxis: {\n gridcolor: 'rgb(255, 255, 255)',\n zerolinecolor: 'rgb(255, 255, 255)',\n showbackground: true,\n backgroundcolor: 'rgb(230, 230,230)',\n // range: xRange\n },\n yaxis: {\n gridcolor: 'rgb(255, 255, 255)',\n zerolinecolor: 'rgb(255, 255, 255)',\n showbackground: true,\n backgroundcolor: 'rgb(230, 230, 230)',\n // autorange: 'reversed',\n // range: yRange,\n // scaleanchor: 'x'\n },\n zaxis: {\n gridcolor: 'rgb(255, 255, 255)',\n zerolinecolor: 'rgb(255, 255, 255)',\n showbackground: true,\n backgroundcolor: 'rgb(230, 230,230)'\n },\n aspectratio: { x: 1, y: 1, z: zRatio },\n aspectmode: 'manual',\n sliders: [{\n pad: { t: 50 },\n currentvalue: {\n visible: true,\n prefix: 'Z-plane:',\n xanchor: 'right',\n },\n steps: this.getSteps()\n }],\n }\n };\n }\n\n private getSteps() {\n const steps = [];\n for (let i = 0; i < this.imageLength; i++) {\n steps.push({\n label: i + 1,\n method: 'restyle',\n args: ['visible', Array(this.imageLength).fill(false).fill(true, i, i + 1)],\n });\n }\n return steps;\n }\n\n /**\n * Fetch an image via Angular HttpClient so that auth interceptors (Bearer token)\n * are applied, then decode it with image-js. This avoids raw browser fetch()\n * calls that bypass the interceptor chain and fail behind an OAuth2 proxy.\n */\n private async loadImage(url: string): Promise<Image> {\n const buffer = await firstValueFrom(\n this.http.get(url, { responseType: 'arraybuffer' })\n );\n return Image.load(Buffer.from(buffer));\n }\n\n /**\n * Get the currently displayed image as an image-js Image instance.\n * Used by the processing pipeline to obtain the input image.\n */\n public async getCurrentImage(): Promise<Image | null> {\n if (!this.imageInfo || !this.imageInfo.urls || this.imageInfo.urls.length === 0) {\n return null;\n }\n const zIdx = this.zIndex.value || 0;\n const url = this.imageInfo.urls[zIdx] || this.imageInfo.urls[0];\n return this.loadImage(url);\n }\n\n /**\n * Get the currently displayed plot pixel data as a flat Uint8ClampedArray.\n * This captures whatever is actually rendered — including zoomed regions.\n * Returns { width, height, channels, data } or null if no plot is displayed.\n */\n public getDisplayedPixelData(): { width: number; height: number; channels: number;\n data: Uint8ClampedArray } | null {\n if (!this.plotDiv) return null;\n const gd: any = document.getElementById(this.plotDiv);\n if (!gd?.data || gd.data.length === 0) return null;\n\n // Find the visible trace\n const frameIdx = this.activeFrameIndex();\n const trace = gd.data[frameIdx] || gd.data[0];\n if (!trace || !trace.z) return null;\n\n const zData: any[][] = trace.z;\n const height = zData.length;\n if (height === 0) return null;\n const width = zData[0].length;\n\n if (trace.type === 'image') {\n // RGB image: z[row][col] = [r, g, b] or [r, g, b, a]\n const sample = zData[0][0];\n const channels = Array.isArray(sample) ? sample.length : 3;\n const data = new Uint8ClampedArray(width * height * channels);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const pixel = zData[y][x];\n const offset = (y * width + x) * channels;\n for (let c = 0; c < channels; c++) {\n data[offset + c] = pixel[c];\n }\n }\n }\n return { width, height, channels, data };\n } else {\n // Heatmap (grayscale): z[row][col] = scalar value\n const data = new Uint8ClampedArray(width * height);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n data[y * width + x] = Math.round(zData[y][x]);\n }\n }\n return { width, height, channels: 1, data };\n }\n }\n\n /**\n * Region of the original image that the displayed `z` grid covers, in\n * full-image pixel coords. On a server zoom (`triggerZoom`) the trace `z` is\n * replaced with the high-def crop and the axes are relaid out to the crop's\n * original-image bounds (`imageSize`), so the live axis ranges ARE that\n * rectangle; when the whole image is in view the ranges span `trueImgSize`.\n * Reading the ranges therefore yields the crop origin + extent without\n * tracking zoom state separately. Falls back to the full image, then `null`.\n */\n public getDisplayedSourceRect(): { x: number; y: number; width: number; height: number } | null {\n const gd: any = this.plotDiv ? document.getElementById(this.plotDiv) : null;\n const xr: number[] | undefined = gd?._fullLayout?.xaxis?.range;\n const yr: number[] | undefined = gd?._fullLayout?.yaxis?.range;\n if (xr && yr) {\n const x0 = Math.min(xr[0], xr[1]);\n const y0 = Math.min(yr[0], yr[1]); // y axis is reversed for image layouts\n return { x: x0, y: y0, width: Math.abs(xr[1] - xr[0]), height: Math.abs(yr[1] - yr[0]) };\n }\n if (!this.trueImgSize) return null;\n return {\n x: this.trueImgSize[0],\n y: this.trueImgSize[2],\n width: this.trueImgSize[1] - this.trueImgSize[0],\n height: this.trueImgSize[3] - this.trueImgSize[2],\n };\n }\n\n public reset() {\n if (this.plotDiv) {\n Plotly.newPlot(this.plotDiv, [],\n this.getHeatmapLayout([0, 100], [100, 0]), CONFIG as any);\n }\n }\n\n /**\n * Fully remove Plotly's DOM from the plot div (axes included). Used when\n * handing the div to another backend (OpenSeadragon) — unlike `reset()`,\n * which re-renders an empty plot and would leave the Plotly axes showing.\n */\n public purgePlot() {\n if (this.plotDiv) {\n Plotly.purge(this.plotDiv);\n }\n }\n\n /** Export the heatmap as a PNG (the rendered plot already reflects the active\n * colormap/window). The full-res tile composite is OSD's job. */\n public exportComposite(): void {\n this.downloadImage();\n }\n\n public downloadImage() {\n if (this.plotDiv) {\n (Plotly as any).downloadImage(this.plotDiv, { format: 'png', filename: this.fileName || 'image' });\n }\n }\n\n public resetAxes() {\n this.zoomCoordinates = [];\n this.relayout();\n }\n\n public setDragMode(mode: string | false) {\n this.dragMode = mode ? (mode as string) : '';\n if (!this.plotDiv) return;\n // Only relayout a LIVE Plotly graph. When another backend (OSD / napari-js) owns the view the\n // div id is still set but has no Plotly plot attached, and Plotly.relayout throws\n // (\"can't access property _guiEditing, n is undefined\"). That throw aborted the caller\n // (deactivateActiveTool → onSelectPlotType) before the re-plot ran, wedging the plot type\n // (e.g. stuck switching napari volume ↔ isosurface). Guard on `_fullLayout` like the zoom\n // helpers do so it safely no-ops when Plotly isn't the active renderer.\n const gd = document.getElementById(this.plotDiv) as unknown as { _fullLayout?: unknown } | null;\n if (!gd?._fullLayout) return;\n Plotly.relayout(this.plotDiv, { dragmode: mode } as any);\n }\n\n /** {@link IDataRenderer} stub — Plotly has no overview navigator (it's an\n * OpenSeadragon feature), so toggling it is a no-op here. */\n public setNavigatorVisible(_visible: boolean): void {\n /* no-op: navigator is OpenSeadragon-only */\n }\n\n /** {@link IDataRenderer} stub — image smoothing is an OpenSeadragon canvas-drawer\n * setting; the Plotly image/heatmap traces don't expose it, so it's a no-op. */\n public setImageSmoothingEnabled(_enabled: boolean): void {\n /* no-op: smoothing toggle is OpenSeadragon-only */\n }\n\n public zoomIn() {\n if (!this.plotDiv) return;\n const gd: any = document.getElementById(this.plotDiv);\n if (!gd?._fullLayout) return;\n const xl = gd._fullLayout.xaxis;\n const yl = gd._fullLayout.yaxis;\n // 3D scenes have no 2D xaxis/yaxis (they live under `scene`); the step-zoom\n // is meaningless there and would throw on `xl.range`. Plotly's scene handles\n // scroll-zoom natively, so just bail.\n if (!xl?.range || !yl?.range) return;\n const xc = (xl.range[0] + xl.range[1]) / 2;\n const yc = (yl.range[0] + yl.range[1]) / 2;\n const dx = (xl.range[1] - xl.range[0]) / 1.3;\n const dy = (yl.range[1] - yl.range[0]) / 1.3;\n const x0 = xc - dx / 2, x1 = xc + dx / 2;\n const y0 = yc - dy / 2, y1 = yc + dy / 2;\n this.zoomCoordinates = [x0, x1, y0, y1];\n Plotly.relayout(this.plotDiv, {\n 'xaxis.range[0]': x0, 'xaxis.range[1]': x1,\n 'yaxis.range[0]': y0, 'yaxis.range[1]': y1\n } as any);\n }\n\n /**\n * Delete every currently selected shape. Falls back to the single\n * `_activeShapeIndex` when no multi-selection is active (covers the case\n * where Plotly clicked a shape without going through the table).\n */\n public deleteActiveShape() {\n // Note: no `plotDiv` guard — when OpenSeadragon is the renderer, Plotly\n // never plotted (plotDiv is unset), but deletion only needs the shape list\n // + the current selection; the Plotly relayout below is guarded.\n const gd: any = this.plotDiv ? document.getElementById(this.plotDiv) : null;\n\n // Resolve what to delete: the store's selection, else the shape Plotly\n // tracks as clicked (when the user clicked a shape without going through the\n // Region Editor table).\n if (this.regionStore.getSelectedShapeIndices().length === 0) {\n const activeIndex: number = gd?._fullLayout?._activeShapeIndex;\n if (activeIndex === undefined || activeIndex < 0) return;\n this.regionStore.setSelectedShapeIndices([activeIndex]);\n }\n // The store removes the selected regions, clears the selection, syncs its\n // cache and emits the region-update event.\n this.regionStore.deleteActiveShape();\n\n // Re-project the remaining regions and render on the Plotly plot (a no-op,\n // caught, when another backend owns the div — its overlay re-renders via\n // the store's update event).\n if (gd?._fullLayout) gd._fullLayout._activeShapeIndex = -1;\n this.syncShapesFromStore();\n const dictArray = this.shapes.map(s => ({ ...s }));\n try {\n Plotly.relayout(this.plotDiv, { shapes: dictArray } as any).then(() => {\n if (gd?._fullLayout) (Plotly as any).redraw(gd);\n }, () => { /* div not a Plotly plot */ });\n } catch { /* div owned by another backend */ }\n }\n\n public zoomOut() {\n if (!this.plotDiv) return;\n const gd: any = document.getElementById(this.plotDiv);\n if (!gd?._fullLayout) return;\n const xl = gd._fullLayout.xaxis;\n const yl = gd._fullLayout.yaxis;\n // 3D scenes have no 2D xaxis/yaxis — see zoomIn().\n if (!xl?.range || !yl?.range) return;\n const xc = (xl.range[0] + xl.range[1]) / 2;\n const yc = (yl.range[0] + yl.range[1]) / 2;\n const dx = (xl.range[1] - xl.range[0]) * 1.3;\n const dy = (yl.range[1] - yl.range[0]) * 1.3;\n const x0 = xc - dx / 2, x1 = xc + dx / 2;\n const y0 = yc - dy / 2, y1 = yc + dy / 2;\n this.zoomCoordinates = [x0, x1, y0, y1];\n Plotly.relayout(this.plotDiv, {\n 'xaxis.range[0]': x0, 'xaxis.range[1]': x1,\n 'yaxis.range[0]': y0, 'yaxis.range[1]': y1\n } as any);\n }\n\n public isStackLoading$(): Observable<boolean> {\n return this.stackLoading$.asObservable();\n }\n public setStackLoading(stackLoading: boolean) {\n this.stackLoading$.next(stackLoading);\n }\n public getStackLoadingProgress$(): Observable<number> {\n return this.stackLoadingProgress$.asObservable();\n }\n\n // Colormap / reverse-scale / image metadata state lives in the shared\n // VisualizerStore; these delegate, keeping only the Plotly-specific live\n // restyle as render glue.\n getColormapOptions() {\n return this.store.getColormapOptions();\n }\n setColormap(colormap: any) {\n this.store.setColormap(colormap);\n try {\n Plotly.restyle(this.plotDiv, { 'colorscale': [colormap.data.value] });\n } catch { /* div owned by another backend (OSD) — it recolors via the LUT */ }\n }\n getColormap() {\n return this.store.getColormap();\n }\n\n setReverseScale(reverscale: any) {\n this.store.setReverseScale(reverscale);\n try {\n Plotly.restyle(this.plotDiv, { 'reversescale': reverscale });\n } catch { /* div owned by another backend (OSD) — it recolors via the LUT */ }\n }\n\n getReverseScale() {\n return this.store.getReverseScale();\n }\n\n setImageMeta(imageMeta: IImageMetadata[]) {\n this.store.setImageMeta(imageMeta);\n }\n\n getImageMeta() {\n return this.store.getImageMeta();\n }\n\n setShowStack(showstack: boolean) {\n if (!showstack) {\n this.zIndex.next(0);\n }\n this.imageInfo.showStack = showstack;\n this.stackLoading$.next(showstack);\n Plotly.relayout(this.plotDiv, { 'showstack': showstack } as any);\n }\n\n getAutoscaleEvent() {\n return this.autoscaleEvent.asObservable();\n }\n\n getRegionUpdateEvent() {\n return this.regionStore.getRegionUpdateEvent();\n }\n\n /**\n * Stream of the indices of currently selected regions — owned by the shared\n * RegionStore so the selection is consistent across backends and the Region\n * Editor table. Empty = nothing selected.\n */\n getSelectedShapeIndices$(): Observable<number[]> {\n return this.regionStore.getSelectedShapeIndices$();\n }\n\n /**\n * Programmatically select regions (or clear with []). The shared store owns\n * the selection state (validates/dedupes/emits); here we additionally point\n * Plotly's `_activeShapeIndex` at the last selected shape so it gets the edit\n * handles. No visual change to non-active shapes — Plotly's own active-shape\n * rendering is the only highlight.\n */\n public setSelectedShapeIndices(indices: number[]) {\n const valid = (indices || [])\n .filter(i => Number.isFinite(i) && i >= 0 && i < this.shapes.length);\n const seen = new Set<number>();\n const cleaned: number[] = [];\n for (const i of valid) {\n if (!seen.has(i)) { seen.add(i); cleaned.push(i); }\n }\n if (this.plotDiv) {\n const gd: any = document.getElementById(this.plotDiv);\n if (gd?._fullLayout) {\n gd._fullLayout._activeShapeIndex = cleaned.length > 0 ? cleaned[cleaned.length - 1] : -1;\n try { (Plotly as any).redraw(gd); } catch { /* noop in tests */ }\n }\n }\n this.regionStore.setSelectedShapeIndices(cleaned);\n }\n\n /**\n * Select a specific region (IRegionStore.selectRegion). Sets the shared store\n * selection by identity and points Plotly's active-shape at the matching\n * rendered shape so its edit handles appear.\n */\n public selectRegion(region: Region): void {\n this.regionStore.selectRegion(region);\n if (this.plotDiv) {\n const idx = this.shapes.findIndex(s => s.id === region?.id);\n const gd: any = document.getElementById(this.plotDiv);\n if (gd?._fullLayout && idx >= 0) {\n gd._fullLayout._activeShapeIndex = idx;\n try { (Plotly as any).redraw(gd); } catch { /* noop in tests */ }\n }\n }\n }\n\n /**\n * Read Plotly's `_activeShapeIndex` and push it as the selection. Called from\n * the relayout handler and the post-click tick — Plotly doesn't fire a\n * dedicated active-shape event for clicks, so we sample. The store no-ops if\n * the selection is unchanged.\n */\n private maybeEmitActiveShapeIndex() {\n if (!this.plotDiv) return;\n const gd: any = document.getElementById(this.plotDiv);\n const raw = gd?._fullLayout?._activeShapeIndex;\n const idx = (typeof raw === 'number' && raw >= 0 && raw < this.shapes.length) ? raw : -1;\n this.regionStore.setSelectedShapeIndices(idx >= 0 ? [idx] : []);\n }\n setZIndex(zIndex: number) {\n this.zIndex.next(zIndex);\n }\n\n getShapeColor() {\n return this.regionStore.getShapeColor();\n }\n getFillColor() {\n return this.regionStore.getFillColor();\n }\n\n getClassificationColors(): Map<string, string> {\n return this.store.getClassificationColors();\n }\n\n setClassificationColor(label: string, color: string) {\n this.store.setClassificationColor(label, color);\n }\n\n /**\n * Unsubscribe Subscriptions\n */\n unsubscribe() {\n if (this.imageCachedSubscription) {\n this.imageCachedSubscription.unsubscribe();\n }\n if (this.filenameSubscription) {\n this.filenameSubscription.unsubscribe();\n }\n if (this.regionUpdateSubscription) {\n this.regionUpdateSubscription.unsubscribe();\n }\n if (this.regionLiveEditSubscription) {\n this.regionLiveEditSubscription.unsubscribe();\n }\n if (this.channelSub) {\n this.channelSub.unsubscribe();\n }\n }\n\n /** Live-apply the channel display window (zmin/zmax) + reverse/invert to the\n * heatmap. No-op when no Plotly plot is mounted (OSD owns the div). */\n private applyChannelDisplay(channels: any[], rev: boolean, inv: boolean): void {\n if (!this.plotDiv) return;\n const ch = channels?.[0];\n const colorscale = this.store.currentColormap()?.data?.value;\n // reverse-scale and invert each flip the ramp; both together cancel.\n const update: any = { reversescale: rev !== inv };\n if (colorscale != null) update.colorscale = colorscale; // live colormap recolor\n if (ch) {\n // Surface/isosurface/scatter3d colour-map via cmin/cmax; heatmap/contour via zmin/zmax.\n const threeD =\n this.plotType === PlotType.ISOSURFACE ||\n this.plotType === PlotType.SURFACE ||\n this.plotType === PlotType.SCATTER3D;\n if (threeD) {\n update.cmin = ch.min;\n update.cmax = ch.max;\n update.cauto = false;\n } else {\n update.zmin = ch.min;\n update.zmax = ch.max;\n update.zauto = false;\n }\n }\n try {\n Plotly.restyle(this.plotDiv, update);\n } catch {\n /* not a colour-mapped trace, or OSD owns the div */\n }\n }\n\n /** Binned intensity histogram for a channel from the cached source frames\n * (raw, pre-LUT). Grayscale cells are numbers; RGB cells are [r,g,b]. */\n getHistogram(channelIndex: number, _bins: number): IHistogram | null {\n const frames = this.cachedImageFrames;\n if (!frames?.length) return null;\n const frame = frames[this.activeFrameIndex()] ?? frames[0];\n if (!frame?.length) return null;\n const counts = new Array(256).fill(0);\n for (const row of frame) {\n if (!row) continue;\n for (const cell of row) {\n let v: number;\n if (Array.isArray(cell)) {\n v = channelIndex >= 0 && channelIndex < cell.length\n ? cell[channelIndex]\n : Math.round(bt601Luminance(cell[0], cell[1], cell[2]));\n } else {\n v = cell;\n }\n v = v | 0;\n if (v < 0) v = 0; else if (v > 255) v = 255;\n counts[v]++;\n }\n }\n return histogram256(counts);\n }\n\n /** Async histogram stream — Plotly renders heatmap frame data (already in\n * memory, 8-bit luminance), so this just wraps the synchronous 8-bit\n * histogram. Native 16-bit histograms only apply to the OSD tile path. */\n getHistogram$(channelIndex: number, bins: number): Observable<IHistogram | null> {\n return of(this.getHistogram(channelIndex, bins));\n }\n\n /** Data export (16-bit TIFF) is an OSD-tile-path feature backed by the server.\n * Plotly renders heatmaps from frame data, so there's nothing to export here. */\n exportData(): void {\n console.warn('[plotly] 16-bit data export is not available for the heatmap backend.');\n }\n\n importRegions(geoJsonStr: string): Region[] {\n return this.plotUtilities.importROIsFromGeoJson(geoJsonStr);\n }\n\n exportRegions(regions: Region[]) {\n const jsonString = this.plotUtilities.exportROIsToGeoJson(regions);\n this.plotUtilities.saveToFile(jsonString, this.fileName);\n }\n\n getGeoJsonString(regions: Region[]): string {\n return this.plotUtilities.exportROIsToGeoJson(regions);\n }\n\n getStackLoadingProgress() {\n return this.getStackLoadingProgress$();\n }\n\n isStackLoading() {\n return this.isStackLoading$();\n }\n\n}\n","import * as OpenSeadragon from 'openseadragon';\n\n/**\n * The real OpenSeadragon object, normalized for the packaged (FESM) build.\n *\n * OpenSeadragon ships as plain CommonJS (`module.exports = OpenSeadragon`, no\n * `__esModule` flag). Bundled into this library's FESM and re-bundled by a\n * consuming app, `import * as OpenSeadragon` resolves to a synthesized ES\n * namespace whose only reliable slot is `.default` (the real `module.exports`).\n * The factory itself and every static member (Viewer, Point, Rect, TileSource, …)\n * live on that object, NOT on the namespace — so `OpenSeadragon(...)` or\n * `new OpenSeadragon.Point()` against the namespace fail once packaged\n * (\"is not a function\" / \"not a constructor\"). Normalize ONCE here and import\n * { OSD } wherever a runtime VALUE is needed; import the `openseadragon` namespace\n * directly only for its TYPES (e.g. `OpenSeadragon.Viewer`).\n *\n * (plotly.js-dist-min needs no equivalent: it sets `__esModule`, so webpack gives\n * it real named exports and plain member access works.)\n */\nexport const OSD: typeof OpenSeadragon =\n (OpenSeadragon as any).default ?? OpenSeadragon;\n","import { OSD } from './osd-lib';\n\n/**\n * Coordinate conversions between screen (viewer-element) pixels, the OSD viewport,\n * and image (data) pixels.\n *\n * With the stack-slice cache the world holds several tiled images at once, which\n * makes the `Viewport.*` image conversions ambiguous — OpenSeadragon logs\n * \"not accurate with multi-image; use TiledImage.* instead\". All slices share the\n * same dimensions and placement, so we route the image<->viewport step through a\n * single reference tiled image (world item 0) and keep the viewport<->element\n * step on the viewport (which is unambiguous). Falls back to the viewport methods\n * when the world is empty.\n */\nconst osd: any = OSD;\n\n/** Reference tiled image for image<->viewport conversions (any slice works since\n * they share geometry). */\nfunction refItem(viewer: any): any | null {\n return viewer?.world?.getItemCount?.() > 0 ? viewer.world.getItemAt(0) : null;\n}\n\n/** Viewer-element pixel -> image (data) coordinates. */\nexport function elementToImage(viewer: any, x: number, y: number): { x: number; y: number } {\n const vp = viewer.viewport;\n const pt = new osd.Point(x, y);\n const item = refItem(viewer);\n const img = item\n ? item.viewportToImageCoordinates(vp.viewerElementToViewportCoordinates(pt))\n : vp.viewerElementToImageCoordinates(pt);\n return { x: img.x, y: img.y };\n}\n\n/** Image (data) coordinates -> viewer-element pixel point. */\nexport function imageToElement(viewer: any, x: number, y: number): { x: number; y: number } {\n const vp = viewer.viewport;\n const pt = new osd.Point(x, y);\n const item = refItem(viewer);\n const p = item\n ? vp.viewportToViewerElementCoordinates(item.imageToViewportCoordinates(pt))\n : vp.imageToViewerElementCoordinates(pt);\n return { x: p.x, y: p.y };\n}\n\n/** Image-space rectangle -> viewport rectangle (for fitBounds). */\nexport function imageRectToViewport(viewer: any, x: number, y: number, w: number, h: number): any {\n const rect = new osd.Rect(x, y, w, h);\n const item = refItem(viewer);\n return item ? item.imageToViewportRectangle(rect) : viewer.viewport.imageToViewportRectangle(rect);\n}\n\n/** Viewport rectangle -> image (data) rectangle. Routes through world item 0 so\n * it stays accurate when the world holds multiple images (stack slices /\n * per-channel layers); falls back to the viewport when the world is empty. */\nexport function viewportRectToImage(viewer: any, vpRect: any): any {\n const item = refItem(viewer);\n return item ? item.viewportToImageRectangle(vpRect) : viewer.viewport.viewportToImageRectangle(vpRect);\n}\n","import { OSD } from './osd-lib';\nimport { Subscription } from 'rxjs';\n\nimport { Region, Rectangle, Polygon, MultiPolygon } from '../../models/region';\nimport { resolveHandles } from '../../models/bezier';\nimport { IRegionStore } from '../../contracts/visualizer.contract';\nimport { IRegionEditApi } from '../../contracts/region-store.contract';\nimport { IRegionOverlay, RegionToolMode } from '../../contracts/region-overlay.contract';\nimport { elementToImage, imageToElement } from './osd-coords';\n\n/**\n * The shared region store as the overlay needs it: the cross-backend\n * {@link IRegionStore} (read regions, selection, colours) plus the Region-native\n * {@link IRegionEditApi} (add/move/resize/vertex edits). The shared RegionStore\n * satisfies both. The overlay edits through these typed operations on the\n * neutral Region model — it never touches a backend's own shape representation\n * (e.g. Plotly's `x0/y0/x1/y1` / `M…L…Z` dicts).\n */\nexport type RegionEditStore = IRegionStore & IRegionEditApi;\n\nconst SVGNS = 'http://www.w3.org/2000/svg';\n\n/** Move/resize zones on the selected rectangle. */\ntype EditZone = 'move' | 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw';\nconst ZONE_CURSOR: Record<EditZone, string> = {\n move: 'move', n: 'ns-resize', s: 'ns-resize', e: 'ew-resize', w: 'ew-resize',\n ne: 'nesw-resize', sw: 'nesw-resize', nw: 'nwse-resize', se: 'nwse-resize',\n};\n/** Screen-pixel tolerance for grabbing an edge/corner handle. */\nconst EDIT_TOL = 8;\n/** Wheel zoom step per scroll tick — mirrors the viewer's `zoomPerScroll`. */\nconst ZOOM_PER_SCROLL = 1.1;\n\n/**\n * OpenSeadragon implementation of {@link IRegionOverlay}.\n *\n * - Renders the store's regions (rect/polygon) in image-pixel space, kept\n * aligned on every pan/zoom via the OSD viewport API.\n * - Draws new rectangle and polygon regions (committed to the shared store).\n * - Click-to-select in 'select' mode.\n *\n * Reads/writes the shared {@link IRegionStore}, so regions stay in sync with the\n * Region Editor and the Plotly backend. The wand, vertex-eraser and zoom-to-box\n * tools are NOT handled here — they're owned by OpenSeadragonVisualizerService\n * (which binds them to OSD via the shared coordinate transform + viewport pixel\n * readback), the same singleton tool services the Plotly backend uses.\n */\nexport class OsdRegionOverlay implements IRegionOverlay {\n\n private readonly svg: SVGSVGElement;\n private readonly subs = new Subscription();\n private readonly osd: any = OSD;\n\n private selected: number[] = [];\n private mode: RegionToolMode = 'none';\n\n private tracker: any;\n private rectStart: { x: number; y: number } | null = null; // image coords\n private rectCurrent: { x: number; y: number } | null = null;\n private polyPoints: { x: number; y: number }[] = []; // image coords\n /** True while dragging a freehand path (freeform / polyline). */\n private freehandDragging = false;\n /** True while placing a click-to-add polygon ('drawpolygon' mode). */\n private drawingPolygon = false;\n /** Last element-pixel point appended, to thin the freehand path. */\n private lastFreehandPx: { x: number; y: number } | null = null;\n /**\n * In-progress edit of the selected region:\n * - kind 'bounds' — rectangle resize/move or whole-region move (uses `zone`);\n * - kind 'vertex' — dragging a single polygon vertex (uses `vertexIndex`).\n */\n private edit: {\n kind: 'bounds' | 'vertex' | 'handle';\n zone: EditZone;\n vertexIndex: number;\n /** Which ring the dragged vertex belongs to: -1 = exterior, else a hole\n * index into `Polygon.holes` (jit-ui#85). */\n ring: number;\n handleSide: 'in' | 'out';\n id: number;\n startImg: { x: number; y: number };\n orig: any;\n } | null = null;\n private editDragged = false;\n /** Rubber-band (marquee) multi-select in 'select' mode: press on empty space\n * and drag to select every region the band intersects. Image coords. */\n private bandStart: { x: number; y: number } | null = null;\n private bandCurrent: { x: number; y: number } | null = null;\n private bandDragged = false;\n\n private readonly redrawHandler = () => this.redraw();\n\n constructor(private viewer: any, private store: RegionEditStore) {\n this.svg = document.createElementNS(SVGNS, 'svg') as SVGSVGElement;\n Object.assign(this.svg.style, {\n position: 'absolute', left: '0', top: '0', width: '100%', height: '100%',\n pointerEvents: 'none', // OSD handles navigation unless we're drawing\n });\n this.viewer.canvas.appendChild(this.svg);\n\n this.viewer.addHandler('update-viewport', this.redrawHandler);\n this.viewer.addHandler('animation', this.redrawHandler);\n this.viewer.addHandler('resize', this.redrawHandler);\n this.viewer.addHandler('rotate', this.redrawHandler);\n // Keep wheel-zoom alive while a tool has mouse-nav disabled (see handler).\n (this.viewer.element as HTMLElement | undefined)\n ?.addEventListener('wheel', this.wheelZoomHandler, { passive: false });\n\n this.tracker = new this.osd.MouseTracker({\n element: this.viewer.canvas,\n pressHandler: (e: any) => this.onPress(e),\n dragHandler: (e: any) => this.onDrag(e),\n releaseHandler: (e: any) => this.onRelease(e),\n clickHandler: (e: any) => this.onClick(e),\n moveHandler: (e: any) => this.onMove(e),\n });\n this.tracker.setTracking(false);\n\n this.subs.add(this.store.getRegionUpdateEvent().subscribe(this.redrawHandler));\n this.subs.add(this.store.getSelectedShapeIndices$().subscribe(idx => {\n this.selected = idx || [];\n this.redraw();\n }));\n\n this.redraw();\n }\n\n /** Switch drawing/selection mode; toggles OSD navigation accordingly. */\n setMode(mode: RegionToolMode): void {\n this.mode = mode;\n this.resetInProgress();\n // Any active region tool takes over the pointer — OSD pan/zoom is disabled\n // so dragging draws (and clicks select) instead of panning. With no tool,\n // OSD navigates normally.\n this.viewer.setMouseNavEnabled(mode === 'none');\n this.tracker.setTracking(mode !== 'none');\n this.updateCursor(false);\n this.redraw();\n }\n\n /** Drive OSD zoom from the wheel while any tool owns the pointer.\n *\n * OSD's native scroll-zoom is part of mouse-nav, so `setMouseNavEnabled(false)`\n * (used by every region tool and by the wand/brush/eraser/SAM tools) disables\n * it. The covering-canvas tools also sit above the OSD canvas and swallow the\n * wheel outright. This listener is bound once to the viewer element — an\n * ancestor of both the OSD canvas and the tool overlays — and forwards the\n * wheel to a cursor-centred zoom whenever mouse-nav is off. When nav is on (no\n * tool active) it does nothing and OSD zooms natively. (jit-ui#94) */\n private readonly wheelZoomHandler = (e: WheelEvent) => {\n const vp = this.viewer?.viewport;\n const el = this.viewer?.element as HTMLElement | undefined;\n // Nav on → no tool active → let OSD handle scroll-zoom natively.\n if (!vp || !el || e.deltaY === 0 || this.viewer.isMouseNavEnabled()) return;\n e.preventDefault();\n const rect = el.getBoundingClientRect();\n const refPoint = vp.pointFromPixel(new this.osd.Point(e.clientX - rect.left, e.clientY - rect.top));\n vp.zoomBy(e.deltaY < 0 ? ZOOM_PER_SCROLL : 1 / ZOOM_PER_SCROLL, refPoint);\n vp.applyConstraints();\n };\n\n /** Cursor feedback per mode (crosshair while drawing; pointer over a region\n * in select mode). */\n private updateCursor(overRegion: boolean): void {\n const canvas = this.viewer.canvas as HTMLElement;\n if (this.mode === 'drawrect' || this.mode === 'drawclosedpath' || this.mode === 'drawopenpath'\n || this.mode === 'drawpolygon' || this.mode === 'addpoint' || this.mode === 'deletepoint') {\n canvas.style.cursor = 'crosshair';\n } else if (this.mode === 'move') {\n canvas.style.cursor = 'move';\n } else if (this.mode === 'select') {\n canvas.style.cursor = overRegion ? 'pointer' : 'default';\n } else {\n canvas.style.cursor = ''; // OSD default (grab)\n }\n }\n\n /** Whether the selected region's vertices/handles should be drawn. Shown\n * whenever a region is selected — including `none` (display) mode and while\n * another tool (wand, brush, SAM…) is active — so a selection always reveals\n * its vertices. Suppressed only while actively drawing a brand-new shape,\n * where stray handles would be noise. */\n private get showsSelectedVertices(): boolean {\n return this.mode !== 'drawrect' && this.mode !== 'drawpolygon'\n && this.mode !== 'drawclosedpath' && this.mode !== 'drawopenpath';\n }\n\n destroy(): void {\n this.subs.unsubscribe();\n (this.viewer.element as HTMLElement | undefined)\n ?.removeEventListener('wheel', this.wheelZoomHandler);\n this.viewer.removeHandler('update-viewport', this.redrawHandler);\n this.viewer.removeHandler('animation', this.redrawHandler);\n this.viewer.removeHandler('resize', this.redrawHandler);\n this.viewer.removeHandler('rotate', this.redrawHandler);\n if (this.tracker) this.tracker.destroy();\n if (this.svg.parentNode) this.svg.parentNode.removeChild(this.svg);\n }\n\n // ── coordinate helpers ───────────────────────────────────────────────\n /** Image-pixel point -> element pixel point. */\n private toPx(imgX: number, imgY: number): { x: number; y: number } {\n return imageToElement(this.viewer, imgX, imgY);\n }\n /** Element pixel point (from a MouseTracker event) -> image-pixel point. */\n private toImage(pos: any): { x: number; y: number } {\n const p = elementToImage(this.viewer, pos.x, pos.y);\n return { x: Math.round(p.x), y: Math.round(p.y) };\n }\n\n // ── rendering ────────────────────────────────────────────────────────\n redraw(): void {\n while (this.svg.firstChild) this.svg.removeChild(this.svg.firstChild);\n\n const regions = this.store.getRegions();\n regions.forEach((r, i) => {\n const el = this.buildRegionEl(r, this.selected.includes(i));\n if (el) this.svg.appendChild(el);\n });\n\n // Handles on the selected polygon, so the user can grab/insert/delete\n // vertices. Bezier regions also get their cubic\n // control handles (tangent lines + control points), mirroring paper.js's\n // fullySelected rendering.\n if (this.showsSelectedVertices) {\n const sel = this.selectedRegionInfo();\n const b = sel?.region.bounds;\n // Handles/vertices take the region's own colour (not the global shape\n // colour) so they match the shape they belong to.\n const color = sel ? sel.region.color || this.store.getShapeColor() : '';\n if (b instanceof Polygon) {\n if (b.bezier) {\n this.drawBezierHandles(b, color);\n } else {\n for (let i = 0; i < b.xpoints.length; i++) {\n const q = this.toPx(b.xpoints[i], b.ypoints[i]);\n this.svg.appendChild(this.vertexMarker(q.x, q.y, false, color));\n }\n // Interior-ring (hole) vertices too, so a donut's inner outline shows\n // its vertices when selected (jit-ui#85).\n if (b.holes) {\n for (const ring of b.holes) {\n for (const [hx, hy] of ring) {\n const q = this.toPx(hx, hy);\n this.svg.appendChild(this.vertexMarker(q.x, q.y, false, color));\n }\n }\n }\n }\n } else if (b instanceof Rectangle) {\n // The four corners as grab/resize handles.\n const corners: [number, number][] = [\n [b.x, b.y], [b.x + b.width, b.y],\n [b.x + b.width, b.y + b.height], [b.x, b.y + b.height],\n ];\n for (const [cx, cy] of corners) {\n const q = this.toPx(cx, cy);\n this.svg.appendChild(this.vertexMarker(q.x, q.y, false, color));\n }\n }\n }\n\n // Rubber-band (marquee) selection preview.\n if (this.mode === 'select' && this.bandStart && this.bandCurrent) {\n this.svg.appendChild(this.selectionBand(this.bandStart, this.bandCurrent));\n }\n\n // In-progress drawing preview.\n if (this.mode === 'drawrect' && this.rectStart && this.rectCurrent) {\n this.svg.appendChild(this.rectPreview(this.rectStart, this.rectCurrent));\n }\n if ((this.mode === 'drawclosedpath' || this.mode === 'drawopenpath') && this.polyPoints.length) {\n this.svg.appendChild(this.polyPreview(this.polyPoints));\n }\n // Click-to-place polygon preview: the polyline so far + a marker on the\n // first vertex (click it to close).\n if (this.mode === 'drawpolygon' && this.polyPoints.length) {\n this.svg.appendChild(this.polyPreview(this.polyPoints));\n const f = this.toPx(this.polyPoints[0].x, this.polyPoints[0].y);\n this.svg.appendChild(this.vertexMarker(f.x, f.y, true));\n }\n }\n\n /** A small vertex handle (filled for an emphasised marker, hollow otherwise).\n * Colour defaults to the global shape colour (used by the in-progress draw\n * preview); selected-region handles pass the region's own colour. */\n private vertexMarker(x: number, y: number, emphasised: boolean,\n color: string = this.store.getShapeColor()): SVGElement {\n const c = document.createElementNS(SVGNS, 'circle');\n c.setAttribute('cx', `${x}`);\n c.setAttribute('cy', `${y}`);\n c.setAttribute('r', emphasised ? '5' : '4');\n c.setAttribute('fill', emphasised ? color : '#ffffff');\n c.setAttribute('stroke', color);\n c.setAttribute('stroke-width', '2');\n return c;\n }\n\n private buildRegionEl(region: Region, selected: boolean): SVGElement | null {\n const color = region.color || this.store.getShapeColor();\n const bounds = region.bounds;\n let pts: { x: number; y: number }[] | null = null;\n let closed = true;\n let el: SVGElement | null = null;\n\n if (bounds instanceof MultiPolygon) {\n // Multi-part region (jit-ui#85): one even-odd <path> with every part's\n // exterior plus its holes. All parts' vertices drive the label bbox.\n const parts = bounds.polygons.filter((p) => (p.xpoints?.length ?? 0) >= 3);\n if (parts.length === 0) return null;\n pts = [];\n let d = '';\n for (const part of parts) {\n const ext = part.xpoints.map((x, i) => ({ x, y: part.ypoints[i] }));\n pts.push(...ext);\n d += (d ? ' ' : '') + this.straightPathD(ext, true);\n if (part.holes) {\n for (const ring of part.holes) {\n d += ' ' + this.straightPathD(ring.map(([x, y]) => ({ x, y })), true);\n }\n }\n }\n el = document.createElementNS(SVGNS, 'path');\n el.setAttribute('d', d);\n el.setAttribute('fill-rule', 'evenodd');\n } else if (bounds instanceof Rectangle) {\n pts = [\n { x: bounds.x, y: bounds.y },\n { x: bounds.x + bounds.width, y: bounds.y },\n { x: bounds.x + bounds.width, y: bounds.y + bounds.height },\n { x: bounds.x, y: bounds.y + bounds.height },\n ];\n } else if (bounds instanceof Polygon) {\n closed = bounds.closed !== false;\n // The anchors drive the label bbox and (for non-bezier) the rendered shape.\n pts = bounds.xpoints.map((x, i) => ({ x, y: bounds.ypoints[i] }));\n }\n if (!pts || pts.length === 0) return null;\n\n if (!el) {\n // Bezier regions render as a true cubic-bezier path through the anchors\n // (paper.js-equivalent smooth curve); everything else as a straight\n // polygon/polyline.\n const isBezier = bounds instanceof Polygon && bounds.bezier && pts.length >= 2;\n // Interior rings (holes) — punch through with even-odd fill (jit-ui#85).\n const holes = (closed && bounds instanceof Polygon && bounds.holes?.length)\n ? bounds.holes : null;\n if (isBezier || holes) {\n el = document.createElementNS(SVGNS, 'path');\n // Exterior subpath (smooth for bezier, straight otherwise) followed by a\n // straight subpath per hole.\n let d = isBezier ? this.bezierPathD(bounds as Polygon) : this.straightPathD(pts, closed);\n if (holes) {\n const poly = bounds as Polygon;\n holes.forEach((ring, hi) => {\n const xs = ring.map((p) => p[0]);\n const ys = ring.map((p) => p[1]);\n // When the donut is a bezier, smooth its holes too (jit-ui#102) — using stored hole\n // handles when present, else the Catmull-Rom default (via resolveHandles).\n d +=\n ' ' +\n (isBezier\n ? this.ringBezierPathD(xs, ys, poly.holeHandlesIn?.[hi], poly.holeHandlesOut?.[hi], true)\n : this.straightPathD(ring.map(([x, y]) => ({ x, y })), true));\n });\n el.setAttribute('fill-rule', 'evenodd');\n }\n el.setAttribute('d', d);\n } else {\n el = document.createElementNS(SVGNS, closed ? 'polygon' : 'polyline');\n el.setAttribute('points', pts.map(p => { const q = this.toPx(p.x, p.y); return `${q.x},${q.y}`; }).join(' '));\n }\n }\n el.setAttribute('fill', selected ? this.rgba(color, 0.35) : 'none');\n el.setAttribute('stroke', color);\n el.setAttribute('stroke-width', selected ? '4' : '2');\n\n // The class label (legend), shown when the Region Editor's \"show labels\" is\n // on — mirrors Plotly's per-shape label (top-left, drawn in the region's\n // colour). Without this OSD showed regions with no label even though Plotly\n // did. region.label is restored from the shape's legend in getRegion().\n const label = region.label;\n if (this.store.getShowShapeLabel() && label != null && `${label}`.length > 0) {\n const g = document.createElementNS(SVGNS, 'g');\n g.appendChild(el);\n const minX = Math.min(...pts.map(p => p.x));\n const minY = Math.min(...pts.map(p => p.y));\n const q = this.toPx(minX, minY);\n const text = document.createElementNS(SVGNS, 'text');\n text.setAttribute('x', `${q.x}`);\n text.setAttribute('y', `${q.y - 4}`); // just above the top-left corner\n text.setAttribute('fill', color);\n text.setAttribute('font-size', '13');\n text.setAttribute('font-family', 'sans-serif');\n // Dark halo so the label stays legible over both bright and dark tiles.\n text.setAttribute('paint-order', 'stroke');\n text.setAttribute('stroke', 'rgba(0,0,0,0.65)');\n text.setAttribute('stroke-width', '2');\n text.textContent = `${label}`;\n g.appendChild(text);\n return g;\n }\n return el;\n }\n\n /** Marquee rectangle for rubber-band multi-select (dashed outline + faint fill). */\n private selectionBand(a: { x: number; y: number }, b: { x: number; y: number }): SVGElement {\n const corners = [\n { x: a.x, y: a.y }, { x: b.x, y: a.y }, { x: b.x, y: b.y }, { x: a.x, y: b.y },\n ];\n const el = document.createElementNS(SVGNS, 'polygon');\n el.setAttribute('points', corners.map(p => { const q = this.toPx(p.x, p.y); return `${q.x},${q.y}`; }).join(' '));\n el.setAttribute('fill', 'rgba(120,170,255,0.15)');\n el.setAttribute('stroke', '#4a90e2');\n el.setAttribute('stroke-dasharray', '4 3');\n el.setAttribute('stroke-width', '1');\n return el;\n }\n\n private rectPreview(a: { x: number; y: number }, b: { x: number; y: number }): SVGElement {\n const corners = [\n { x: a.x, y: a.y }, { x: b.x, y: a.y }, { x: b.x, y: b.y }, { x: a.x, y: b.y },\n ];\n const el = document.createElementNS(SVGNS, 'polygon');\n el.setAttribute('points', corners.map(p => { const q = this.toPx(p.x, p.y); return `${q.x},${q.y}`; }).join(' '));\n el.setAttribute('fill', 'none');\n el.setAttribute('stroke', this.store.getShapeColor());\n el.setAttribute('stroke-dasharray', '4 3');\n el.setAttribute('stroke-width', '2');\n return el;\n }\n\n private polyPreview(pts: { x: number; y: number }[]): SVGElement {\n const el = document.createElementNS(SVGNS, 'polyline');\n el.setAttribute('points', pts.map(p => { const q = this.toPx(p.x, p.y); return `${q.x},${q.y}`; }).join(' '));\n el.setAttribute('fill', 'none');\n el.setAttribute('stroke', this.store.getShapeColor());\n el.setAttribute('stroke-dasharray', '4 3');\n el.setAttribute('stroke-width', '2');\n return el;\n }\n\n /** SVG path `d` (element-pixel coords) for a straight-edged ring/polyline. */\n private straightPathD(pts: { x: number; y: number }[], closed: boolean): string {\n if (pts.length < 2) return '';\n let d = '';\n pts.forEach((p, i) => {\n const q = this.toPx(p.x, p.y);\n d += (i === 0 ? 'M ' : ' L ') + `${q.x},${q.y}`;\n });\n if (closed) d += ' Z';\n return d;\n }\n\n /** SVG path `d` (element-pixel coords) for the smooth cubic bezier through a\n * polygon's anchors — the paper.js-equivalent curve. */\n private bezierPathD(poly: Polygon): string {\n const closed = poly.closed !== false;\n return this.ringBezierPathD(poly.xpoints, poly.ypoints, poly.handlesIn, poly.handlesOut, closed);\n }\n\n /** SVG cubic-bezier path `d` (element px) for any ring (exterior or hole). Uses the stored\n * per-vertex handle offsets when present, else the Catmull-Rom default (resolveHandles). */\n private ringBezierPathD(\n xs: number[], ys: number[], inOff: number[][] | undefined, outOff: number[][] | undefined, closed: boolean,\n ): string {\n const n = Math.min(xs.length, ys.length);\n if (n < 2) return '';\n const h = resolveHandles(xs, ys, closed, inOff, outOff);\n const px = (x: number, y: number) => { const q = this.toPx(x, y); return `${q.x},${q.y}`; };\n let d = `M ${px(xs[0], ys[0])}`;\n const segs = closed ? n : n - 1;\n for (let i = 0; i < segs; i++) {\n const j = (i + 1) % n;\n const c1 = h[i].out;\n const c2 = h[j].in;\n d += ` C ${px(c1[0], c1[1])} ${px(c2[0], c2[1])} ${px(xs[j], ys[j])}`;\n }\n if (closed) d += ' Z';\n return d;\n }\n\n /**\n * Draw the bezier editing handles for the selected region, paper.js-style:\n * each anchor as a small square, with tangent lines out to its two control\n * points (drawn as small circles).\n */\n private drawBezierHandles(poly: Polygon, color: string): void {\n const xs = poly.xpoints;\n const ys = poly.ypoints;\n const drawRing = (rxs: number[], rys: number[], inOff: number[][] | undefined,\n outOff: number[][] | undefined, closed: boolean): void => {\n const h = resolveHandles(rxs, rys, closed, inOff, outOff);\n for (let i = 0; i < rxs.length; i++) {\n const a = this.toPx(rxs[i], rys[i]);\n if (h[i].hasIn) this.drawHandle(a, this.toPx(h[i].in[0], h[i].in[1]), color);\n if (h[i].hasOut) this.drawHandle(a, this.toPx(h[i].out[0], h[i].out[1]), color);\n this.svg.appendChild(this.anchorSquare(a.x, a.y, color));\n }\n };\n drawRing(xs, ys, poly.handlesIn, poly.handlesOut, poly.closed !== false);\n // Donut hole rings get their own editable bezier handles (jit-ui#102).\n if (poly.holes && poly.holeHandlesIn && poly.holeHandlesOut) {\n poly.holes.forEach((ring, hi) => {\n const inOff = poly.holeHandlesIn![hi];\n const outOff = poly.holeHandlesOut![hi];\n if (inOff && outOff) drawRing(ring.map((p) => p[0]), ring.map((p) => p[1]), inOff, outOff, true);\n });\n }\n }\n\n /** A tangent line from an anchor to a control point, with a circle at the end. */\n private drawHandle(anchor: { x: number; y: number }, ctrl: { x: number; y: number }, color: string): void {\n const line = document.createElementNS(SVGNS, 'line');\n line.setAttribute('x1', `${anchor.x}`); line.setAttribute('y1', `${anchor.y}`);\n line.setAttribute('x2', `${ctrl.x}`); line.setAttribute('y2', `${ctrl.y}`);\n line.setAttribute('stroke', color);\n line.setAttribute('stroke-width', '1');\n this.svg.appendChild(line);\n const c = document.createElementNS(SVGNS, 'circle');\n c.setAttribute('cx', `${ctrl.x}`); c.setAttribute('cy', `${ctrl.y}`);\n c.setAttribute('r', '3');\n c.setAttribute('fill', color);\n this.svg.appendChild(c);\n }\n\n /** A filled-white anchor square (the editable vertex). */\n private anchorSquare(x: number, y: number, color: string): SVGElement {\n const r = 3.5;\n const rect = document.createElementNS(SVGNS, 'rect');\n rect.setAttribute('x', `${x - r}`); rect.setAttribute('y', `${y - r}`);\n rect.setAttribute('width', `${2 * r}`); rect.setAttribute('height', `${2 * r}`);\n rect.setAttribute('fill', '#ffffff');\n rect.setAttribute('stroke', color);\n rect.setAttribute('stroke-width', '2');\n return rect;\n }\n\n private rgba(color: string, alpha: number): string {\n // Accept #rrggbb; fall back to the color as-is for named/rgb values.\n if (/^#([0-9a-f]{6})$/i.test(color)) {\n const r = parseInt(color.slice(1, 3), 16);\n const g = parseInt(color.slice(3, 5), 16);\n const b = parseInt(color.slice(5, 7), 16);\n return `rgba(${r},${g},${b},${alpha})`;\n }\n return color;\n }\n\n // ── interaction ──────────────────────────────────────────────────────\n private get isFreehand(): boolean {\n return this.mode === 'drawclosedpath' || this.mode === 'drawopenpath';\n }\n\n private onPress(e: any): void {\n if (this.mode === 'drawrect') {\n this.rectStart = this.toImage(e.position);\n this.rectCurrent = this.rectStart;\n return;\n }\n if (this.isFreehand) {\n // Freehand draw (matches Plotly drawclosedpath/drawopenpath): press to\n // start, drag to trace, release to commit.\n this.freehandDragging = true;\n this.polyPoints = [this.toImage(e.position)];\n this.lastFreehandPx = { x: e.position.x, y: e.position.y };\n return;\n }\n if (this.mode === 'move') {\n // Whole-region drag ('move' mode): press inside the selected region\n // to translate it, ignoring vertices/edges.\n const sel = this.selectedRegionInfo();\n if (sel && this.containsPoint(sel.region, this.toImage(e.position))) {\n this.startEdit('bounds', 'move', -1, sel.region, this.toImage(e.position));\n }\n return;\n }\n if (this.mode === 'select') {\n // A bezier control handle takes top priority (it sits off the anchor).\n const hh = this.hitBezierHandle(e.position);\n if (hh) {\n const region = this.store.getRegions()[this.selected[this.selected.length - 1]];\n this.startEdit('handle', 'move', hh.index, region, this.toImage(e.position), hh.side, hh.ring);\n return;\n }\n // Then dragging a single polygon vertex (over body-move/resize) —\n // 'select' grabs the nearest segment first.\n const vh = this.hitVertex(e.position);\n if (vh) {\n const region = this.store.getRegions()[this.selected[this.selected.length - 1]];\n this.startEdit('vertex', 'move', vh.index, region, this.toImage(e.position), 'out', vh.ring);\n return;\n }\n // Otherwise start a move/resize when pressing the selected region's\n // body/handles.\n const ez = this.editZoneAt(e.position);\n if (ez) {\n this.startEdit('bounds', ez.zone, -1, this.store.getRegions()[ez.index], this.toImage(e.position));\n return;\n }\n // Press on empty space / a non-selected region: begin a rubber-band\n // multi-select. A plain click (no drag) falls through to onClick, which\n // single-selects or clears.\n this.bandStart = this.toImage(e.position);\n this.bandCurrent = this.bandStart;\n this.bandDragged = false;\n }\n }\n\n /** Begin an edit gesture (move/resize or single-vertex drag) and open a store\n * batch so the live drag emits once on release. */\n private startEdit(kind: 'bounds' | 'vertex' | 'handle', zone: EditZone, vertexIndex: number,\n region: Region, startImg: { x: number; y: number },\n handleSide: 'in' | 'out' = 'out', ring = -1): void {\n this.edit = {\n kind, zone, vertexIndex, ring, handleSide, id: region.id,\n startImg, orig: kind === 'bounds' ? this.snapshot(region) : null,\n };\n this.editDragged = false;\n this.store.beginBatch();\n }\n\n private onDrag(e: any): void {\n if (this.mode === 'drawrect' && this.rectStart) {\n this.rectCurrent = this.toImage(e.position);\n this.redraw();\n return;\n }\n if (this.freehandDragging && this.isFreehand) {\n // Thin the path: only sample once the cursor has moved a few screen px.\n const last = this.lastFreehandPx;\n if (!last || Math.hypot(e.position.x - last.x, e.position.y - last.y) >= 4) {\n this.polyPoints.push(this.toImage(e.position));\n this.lastFreehandPx = { x: e.position.x, y: e.position.y };\n this.redraw();\n }\n return;\n }\n if (this.edit) {\n this.editDragged = true;\n this.applyEdit(this.toImage(e.position));\n return;\n }\n if (this.bandStart) {\n this.bandCurrent = this.toImage(e.position);\n this.bandDragged = true;\n this.redraw();\n }\n }\n\n private onRelease(e: any): void {\n if (this.mode === 'drawrect' && this.rectStart) {\n const end = this.toImage(e.position);\n const x = Math.min(this.rectStart.x, end.x);\n const y = Math.min(this.rectStart.y, end.y);\n const w = Math.abs(end.x - this.rectStart.x);\n const h = Math.abs(end.y - this.rectStart.y);\n this.rectStart = this.rectCurrent = null;\n if (w > 2 && h > 2) this.commitRectangle(x, y, w, h);\n return;\n }\n if (this.freehandDragging) {\n this.freehandDragging = false;\n this.lastFreehandPx = null;\n // Closed = freeform (drawclosedpath); open = polyline (drawopenpath).\n this.commitPolygon(this.mode === 'drawclosedpath');\n return;\n }\n // Move/resize already applied live; flush the coalesced edits + end the\n // gesture (keep selection).\n if (this.edit) {\n this.store.endBatch();\n this.edit = null;\n return;\n }\n // Finish a rubber-band selection: select every region the band intersects.\n if (this.bandStart) {\n const start = this.bandStart;\n const end = this.bandCurrent ?? start;\n this.bandStart = this.bandCurrent = null;\n const x0 = Math.min(start.x, end.x), y0 = Math.min(start.y, end.y);\n const x1 = Math.max(start.x, end.x), y1 = Math.max(start.y, end.y);\n // Only a real drag selects; a click-sized band falls through to onClick.\n if (this.bandDragged && (x1 - x0 > 2 || y1 - y0 > 2)) {\n this.store.setSelectedShapeIndices(this.regionsInRect(x0, y0, x1, y1));\n }\n this.redraw();\n }\n }\n\n private onClick(e: any): void {\n if (this.mode === 'select') {\n // A move/resize/vertex drag or a rubber-band drag also ends with a click\n // event — don't treat it as a re-selection.\n if (this.editDragged) { this.editDragged = false; return; }\n if (this.bandDragged) { this.bandDragged = false; return; }\n // Shift (or Cmd/Ctrl) toggles the clicked region in/out of the current\n // selection; a plain click replaces it.\n const oe = e.originalEvent;\n const additive = !!oe && (oe.shiftKey || oe.metaKey || oe.ctrlKey);\n this.selectAt(this.toImage(e.position), additive);\n return;\n }\n if (this.mode === 'drawpolygon') {\n this.onDrawPolygonClick(e);\n return;\n }\n if (this.mode === 'addpoint') {\n // Insert a vertex on the clicked edge — exterior or an interior ring.\n const sel = this.selectedRegionInfo();\n const edge = sel ? this.hitEdge(e.position, sel.region) : null;\n if (sel && edge) {\n if (edge.ring < 0) this.store.addVertex(sel.region.id, edge.segIndex, edge.x, edge.y);\n else this.store.addHoleVertex(sel.region.id, edge.ring, edge.segIndex, edge.x, edge.y);\n }\n return;\n }\n if (this.mode === 'deletepoint') {\n // Remove the clicked vertex — exterior or an interior ring (jit-ui#85).\n const vh = this.hitVertex(e.position);\n if (vh) {\n if (vh.ring < 0) this.store.deleteVertex(vh.id, vh.index);\n else this.store.deleteHoleVertex(vh.id, vh.ring, vh.index);\n }\n return;\n }\n }\n\n /**\n * Click-to-place polygon ('drawpolygon'): the first click starts the\n * polygon, each subsequent click adds a vertex, and clicking near the first\n * vertex (with at least 3 placed) closes and commits it.\n */\n private onDrawPolygonClick(e: any): void {\n const pt = this.toImage(e.position);\n if (!this.drawingPolygon) {\n this.polyPoints = [pt];\n this.drawingPolygon = true;\n this.redraw();\n return;\n }\n const first = this.toPx(this.polyPoints[0].x, this.polyPoints[0].y);\n const onFirst = Math.hypot(e.position.x - first.x, e.position.y - first.y) <= EDIT_TOL;\n if (onFirst && this.polyPoints.length >= 3) {\n this.commitPolygon(true); // closes + resets in-progress (incl. drawingPolygon)\n return;\n }\n this.polyPoints.push(pt);\n this.redraw();\n }\n\n /**\n * Hover feedback in select mode: move/resize cursors over the selected\n * region's body/edges/corners, a pointer over any other region.\n */\n private onMove(e: any): void {\n if (this.mode !== 'select') return;\n // A grabbable bezier control handle or vertex of the selected polygon takes\n // priority.\n if (this.hitBezierHandle(e.position) || this.hitVertex(e.position)) {\n (this.viewer.canvas as HTMLElement).style.cursor = 'pointer';\n return;\n }\n const ez = this.editZoneAt(e.position);\n if (ez) {\n (this.viewer.canvas as HTMLElement).style.cursor = ZONE_CURSOR[ez.zone];\n return;\n }\n this.updateCursor(this.regionIndexAt(this.toImage(e.position)) >= 0);\n }\n\n /**\n * The move/resize zone under the cursor for the currently-selected region\n * (rectangles get edge/corner handles + body; polygons get body-move only),\n * or null if the cursor isn't over the selected region.\n */\n private editZoneAt(position: { x: number; y: number }): { zone: EditZone; index: number } | null {\n if (this.selected.length === 0) return null;\n const index = this.selected[this.selected.length - 1];\n const region = this.store.getRegions()[index];\n if (!region) return null;\n const b = region.bounds;\n if (b instanceof Rectangle) {\n const a = this.toPx(b.x, b.y);\n const c = this.toPx(b.x + b.width, b.y + b.height);\n const zone = this.rectZone(position.x, position.y,\n Math.min(a.x, c.x), Math.min(a.y, c.y), Math.max(a.x, c.x), Math.max(a.y, c.y));\n return zone ? { zone, index } : null;\n }\n if (b instanceof Polygon || b instanceof MultiPolygon) {\n // Polygons + multi-part regions support whole-region move (no resize zones).\n return this.containsPoint(region, this.toImage(position)) ? { zone: 'move', index } : null;\n }\n return null;\n }\n\n /** The currently-selected region (the last one selected), or null. */\n private selectedRegionInfo(): { region: Region; index: number } | null {\n if (this.selected.length === 0) return null;\n const index = this.selected[this.selected.length - 1];\n const region = this.store.getRegions()[index];\n return region ? { region, index } : null;\n }\n\n /** The vertex of the selected polygon under the cursor (screen-pixel\n * tolerance), or null. Rectangles have no editable vertices. */\n private hitVertex(position: { x: number; y: number }): { id: number; ring: number; index: number } | null {\n const sel = this.selectedRegionInfo();\n if (!sel || !(sel.region.bounds instanceof Polygon)) return null;\n const b = sel.region.bounds;\n for (let i = 0; i < b.xpoints.length; i++) {\n const q = this.toPx(b.xpoints[i], b.ypoints[i]);\n if (Math.hypot(position.x - q.x, position.y - q.y) <= EDIT_TOL) {\n return { id: sel.region.id, ring: -1, index: i };\n }\n }\n // Interior-ring (hole) vertices are draggable too (jit-ui#85).\n if (b.holes) {\n for (let h = 0; h < b.holes.length; h++) {\n const ring = b.holes[h];\n for (let i = 0; i < ring.length; i++) {\n const q = this.toPx(ring[i][0], ring[i][1]);\n if (Math.hypot(position.x - q.x, position.y - q.y) <= EDIT_TOL) {\n return { id: sel.region.id, ring: h, index: i };\n }\n }\n }\n }\n return null;\n }\n\n /** The bezier control handle of the selected region under the cursor (which\n * anchor, and whether the in- or out-handle), or null. */\n private hitBezierHandle(\n position: { x: number; y: number },\n ): { id: number; index: number; side: 'in' | 'out'; ring: number } | null {\n const sel = this.selectedRegionInfo();\n if (!sel || !(sel.region.bounds instanceof Polygon) || !sel.region.bounds.bezier) return null;\n const b = sel.region.bounds;\n // Test one ring's control handles; returns the matched vertex/side or null.\n const testRing = (\n xs: number[], ys: number[], inOff: number[][] | undefined, outOff: number[][] | undefined,\n closed: boolean, ring: number,\n ): { id: number; index: number; side: 'in' | 'out'; ring: number } | null => {\n const h = resolveHandles(xs, ys, closed, inOff, outOff);\n for (let i = 0; i < h.length; i++) {\n if (h[i].hasOut) {\n const q = this.toPx(h[i].out[0], h[i].out[1]);\n if (Math.hypot(position.x - q.x, position.y - q.y) <= EDIT_TOL) {\n return { id: sel.region.id, index: i, side: 'out', ring };\n }\n }\n if (h[i].hasIn) {\n const q = this.toPx(h[i].in[0], h[i].in[1]);\n if (Math.hypot(position.x - q.x, position.y - q.y) <= EDIT_TOL) {\n return { id: sel.region.id, index: i, side: 'in', ring };\n }\n }\n }\n return null;\n };\n const ext = testRing(b.xpoints, b.ypoints, b.handlesIn, b.handlesOut, b.closed !== false, -1);\n if (ext) return ext;\n // Donut hole rings (jit-ui#102): their own bezier control handles.\n if (b.holes && b.holeHandlesIn && b.holeHandlesOut) {\n for (let hi = 0; hi < b.holes.length; hi++) {\n const ring = b.holes[hi];\n const hit = testRing(\n ring.map((p) => p[0]), ring.map((p) => p[1]),\n b.holeHandlesIn[hi], b.holeHandlesOut[hi], true, hi,\n );\n if (hit) return hit;\n }\n }\n return null;\n }\n\n /** The edge of `region`'s polygon nearest the cursor (within tolerance), with\n * the clicked point in image coords as the insertion position, or null. */\n private hitEdge(position: { x: number; y: number }, region: Region):\n { ring: number; segIndex: number; x: number; y: number } | null {\n if (!(region.bounds instanceof Polygon)) return null;\n const b = region.bounds;\n let best = -1, bestRing = -1, bestDist = Infinity;\n // Nearest edge across the exterior (ring -1) and every interior ring (hole).\n const scan = (xs: number[], ys: number[], ring: number, closed: boolean) => {\n const n = xs.length;\n const segCount = closed ? n : n - 1; // closed wraps the last->first edge\n for (let i = 0; i < segCount; i++) {\n const j = (i + 1) % n;\n const a = this.toPx(xs[i], ys[i]);\n const c = this.toPx(xs[j], ys[j]);\n const d = this.distToSegmentPx(position, a, c);\n if (d < bestDist) { bestDist = d; best = i; bestRing = ring; }\n }\n };\n scan(b.xpoints, b.ypoints, -1, b.closed !== false);\n if (b.holes) {\n b.holes.forEach((r, h) => scan(r.map(p => p[0]), r.map(p => p[1]), h, true));\n }\n if (best < 0 || bestDist > EDIT_TOL) return null;\n const img = this.toImage(position);\n return { ring: bestRing, segIndex: best, x: img.x, y: img.y };\n }\n\n /** Classify a screen point against a screen-space rectangle into a zone. */\n private rectZone(px: number, py: number, x0: number, y0: number, x1: number, y1: number): EditZone | null {\n const t = EDIT_TOL;\n if (px < x0 - t || px > x1 + t || py < y0 - t || py > y1 + t) return null;\n const left = Math.abs(px - x0) <= t, right = Math.abs(px - x1) <= t;\n const top = Math.abs(py - y0) <= t, bottom = Math.abs(py - y1) <= t;\n if (top && left) return 'nw';\n if (top && right) return 'ne';\n if (bottom && left) return 'sw';\n if (bottom && right) return 'se';\n if (left) return 'w';\n if (right) return 'e';\n if (top) return 'n';\n if (bottom) return 's';\n if (px > x0 && px < x1 && py > y0 && py < y1) return 'move';\n return null;\n }\n\n /** Snapshot the selected region's geometry at the start of an edit. */\n private snapshot(region: Region): any {\n const b = region.bounds;\n if (b instanceof Rectangle) return { kind: 'rect', x: b.x, y: b.y, w: b.width, h: b.height };\n if (b instanceof Polygon) {\n return {\n kind: 'poly', xs: b.xpoints.slice(), ys: b.ypoints.slice(), closed: b.closed !== false,\n bezier: b.bezier,\n inOff: b.handlesIn?.map(o => o.slice()),\n outOff: b.handlesOut?.map(o => o.slice()),\n holes: b.holes?.map(ring => ring.map(pt => pt.slice())),\n };\n }\n if (b instanceof MultiPolygon) {\n return {\n kind: 'multi',\n polygons: b.polygons.map((p) => ({\n xs: p.xpoints.slice(), ys: p.ypoints.slice(), closed: p.closed !== false,\n holes: p.holes?.map(ring => ring.map(pt => pt.slice())),\n })),\n };\n }\n return { kind: 'rect', x: 0, y: 0, w: 0, h: 0 };\n }\n\n /**\n * Apply the in-progress move/resize to the region, live, through the\n * Region-native edit API. Recomputed absolutely from the gesture-start\n * snapshot (`orig`) + the total delta, so each frame is idempotent.\n */\n private applyEdit(curImg: { x: number; y: number }): void {\n if (!this.edit) return;\n\n if (this.edit.kind === 'vertex') {\n // Drag a single vertex to the cursor (absolute — idempotent). Route to the\n // exterior or the matching interior ring (hole) — jit-ui#85.\n if (this.edit.ring < 0) {\n this.store.moveVertex(this.edit.id, this.edit.vertexIndex, curImg.x, curImg.y);\n } else {\n this.store.moveHoleVertex(this.edit.id, this.edit.ring, this.edit.vertexIndex, curImg.x, curImg.y);\n }\n this.redraw();\n return;\n }\n\n if (this.edit.kind === 'handle') {\n // Drag a bezier control handle to the cursor — exterior (ring -1) or a donut hole ring.\n if (this.edit.ring < 0) {\n this.store.moveBezierHandle(this.edit.id, this.edit.vertexIndex, this.edit.handleSide, curImg.x, curImg.y);\n } else {\n this.store.moveHoleBezierHandle(\n this.edit.id, this.edit.ring, this.edit.vertexIndex, this.edit.handleSide, curImg.x, curImg.y,\n );\n }\n this.redraw();\n return;\n }\n\n const dx = curImg.x - this.edit.startImg.x;\n const dy = curImg.y - this.edit.startImg.y;\n\n const o = this.edit.orig;\n if (o.kind === 'rect') {\n let x0 = o.x, y0 = o.y, x1 = o.x + o.w, y1 = o.y + o.h;\n switch (this.edit.zone) {\n case 'move': x0 += dx; x1 += dx; y0 += dy; y1 += dy; break;\n case 'w': x0 += dx; break;\n case 'e': x1 += dx; break;\n case 'n': y0 += dy; break;\n case 's': y1 += dy; break;\n case 'nw': x0 += dx; y0 += dy; break;\n case 'ne': x1 += dx; y0 += dy; break;\n case 'sw': x0 += dx; y1 += dy; break;\n case 'se': x1 += dx; y1 += dy; break;\n }\n const rect = new Rectangle();\n rect.x = Math.round(Math.min(x0, x1));\n rect.y = Math.round(Math.min(y0, y1));\n rect.width = Math.round(Math.abs(x1 - x0));\n rect.height = Math.round(Math.abs(y1 - y0));\n this.store.updateBounds(this.edit.id, rect);\n } else if (o.kind === 'multi') {\n // Multi-part region: translate every part (and its holes) by the delta.\n const mp = new MultiPolygon();\n mp.polygons = o.polygons.map((pp: any) => {\n const xs = pp.xs.map((x: number) => Math.round(x + dx));\n const ys = pp.ys.map((y: number) => Math.round(y + dy));\n const poly = new Polygon();\n poly.npoints = xs.length;\n poly.xpoints = xs;\n poly.ypoints = ys;\n poly.coordinates = xs.map((x: number, i: number) => [x, ys[i]]);\n poly.closed = pp.closed;\n if (pp.holes) {\n poly.holes = pp.holes.map((ring: number[][]) =>\n ring.map(([x, y]: number[]) => [Math.round(x + dx), Math.round(y + dy)]));\n }\n return poly;\n });\n this.store.updateBounds(this.edit.id, mp);\n } else {\n // Polygon: translate every vertex (the only polygon edit zone is 'move').\n // Bezier flag + handle offsets are relative, so they carry over unchanged.\n const xs = o.xs.map((x: number) => Math.round(x + dx));\n const ys = o.ys.map((y: number) => Math.round(y + dy));\n const poly = new Polygon();\n poly.npoints = xs.length;\n poly.xpoints = xs;\n poly.ypoints = ys;\n poly.coordinates = xs.map((x: number, i: number) => [x, ys[i]]);\n poly.closed = o.closed;\n poly.bezier = o.bezier;\n if (o.inOff) poly.handlesIn = o.inOff.map((off: number[]) => off.slice());\n if (o.outOff) poly.handlesOut = o.outOff.map((off: number[]) => off.slice());\n // Translate interior rings (holes) with the exterior (jit-ui#85).\n if (o.holes) {\n poly.holes = o.holes.map((ring: number[][]) =>\n ring.map(([x, y]: number[]) => [Math.round(x + dx), Math.round(y + dy)]));\n }\n this.store.updateBounds(this.edit.id, poly);\n }\n this.redraw();\n }\n\n private selectAt(pt: { x: number; y: number }, additive = false): void {\n const idx = this.regionIndexAt(pt);\n if (additive) {\n // Shift-click on empty space keeps the current selection.\n if (idx < 0) return;\n // `this.selected` mirrors the store's current selection (kept in sync via\n // the subscription), so it's the source of truth without a sync getter.\n const cur = this.selected.slice();\n const at = cur.indexOf(idx);\n if (at >= 0) cur.splice(at, 1); // toggle off\n else cur.push(idx); // toggle on\n this.store.setSelectedShapeIndices(cur);\n return;\n }\n this.store.setSelectedShapeIndices(idx >= 0 ? [idx] : []);\n }\n\n /** Indices of every region whose bounding box intersects the image-space\n * rectangle [x0,y0]–[x1,y1] (rubber-band multi-select). */\n private regionsInRect(x0: number, y0: number, x1: number, y1: number): number[] {\n const out: number[] = [];\n this.store.getRegions().forEach((r, i) => {\n const bb = this.regionBBox(r);\n if (bb && bb.x0 <= x1 && bb.x1 >= x0 && bb.y0 <= y1 && bb.y1 >= y0) out.push(i);\n });\n return out;\n }\n\n /** Axis-aligned bounding box of a region in image coords, or null if empty. */\n private regionBBox(r: Region): { x0: number; y0: number; x1: number; y1: number } | null {\n const b = r.bounds;\n if (b instanceof Rectangle) {\n return { x0: b.x, y0: b.y, x1: b.x + b.width, y1: b.y + b.height };\n }\n if (b instanceof Polygon && b.xpoints.length) {\n return {\n x0: Math.min(...b.xpoints), y0: Math.min(...b.ypoints),\n x1: Math.max(...b.xpoints), y1: Math.max(...b.ypoints),\n };\n }\n if (b instanceof MultiPolygon) {\n let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;\n for (const p of b.polygons) {\n for (let i = 0; i < p.xpoints.length; i++) {\n if (p.xpoints[i] < x0) x0 = p.xpoints[i];\n if (p.xpoints[i] > x1) x1 = p.xpoints[i];\n if (p.ypoints[i] < y0) y0 = p.ypoints[i];\n if (p.ypoints[i] > y1) y1 = p.ypoints[i];\n }\n }\n return x1 >= x0 ? { x0, y0, x1, y1 } : null;\n }\n return null;\n }\n\n /** Index of the topmost region under a point, or -1. */\n private regionIndexAt(pt: { x: number; y: number }): number {\n const regions = this.store.getRegions();\n for (let i = regions.length - 1; i >= 0; i--) {\n if (this.containsPoint(regions[i], pt)) return i;\n }\n return -1;\n }\n\n private containsPoint(region: Region, pt: { x: number; y: number }): boolean {\n const b = region.bounds;\n if (b instanceof Rectangle) {\n return pt.x >= b.x && pt.x <= b.x + b.width && pt.y >= b.y && pt.y <= b.y + b.height;\n }\n // Multi-part region: inside any part (exterior minus that part's holes).\n if (b instanceof MultiPolygon) {\n return b.polygons.some((p) => this.closedPolygonContains(p, pt));\n }\n if (b instanceof Polygon) {\n if (b.closed !== false) return this.closedPolygonContains(b, pt);\n // Open polyline: no interior — select when the click lands near the line.\n // Tolerance is in screen pixels so it stays clickable at any zoom.\n const xs = b.xpoints, ys = b.ypoints, n = xs.length, tolPx = 6;\n const here = this.toPx(pt.x, pt.y);\n for (let i = 0; i + 1 < n; i++) {\n const a = this.toPx(xs[i], ys[i]);\n const c = this.toPx(xs[i + 1], ys[i + 1]);\n if (this.distToSegmentPx(here, a, c) <= tolPx) return true;\n }\n return false;\n }\n return false;\n }\n\n /** Point-in-closed-polygon (image coords) honouring interior rings (holes):\n * inside the exterior AND outside every hole (even-odd). */\n private closedPolygonContains(b: Polygon, pt: { x: number; y: number }): boolean {\n const inRing = (rxs: number[], rys: number[]): boolean => {\n let hit = false;\n for (let i = 0, j = rxs.length - 1; i < rxs.length; j = i++) {\n const intersect = ((rys[i] > pt.y) !== (rys[j] > pt.y))\n && (pt.x < ((rxs[j] - rxs[i]) * (pt.y - rys[i])) / (rys[j] - rys[i]) + rxs[i]);\n if (intersect) hit = !hit;\n }\n return hit;\n };\n if (!inRing(b.xpoints, b.ypoints)) return false;\n if (b.holes) {\n for (const ring of b.holes) {\n if (inRing(ring.map(p => p[0]), ring.map(p => p[1]))) return false;\n }\n }\n return true;\n }\n\n /** Shortest distance from point p to segment a–b, all in screen pixels. */\n private distToSegmentPx(\n p: { x: number; y: number }, a: { x: number; y: number }, b: { x: number; y: number },\n ): number {\n const dx = b.x - a.x, dy = b.y - a.y;\n const len2 = dx * dx + dy * dy;\n if (len2 === 0) return Math.hypot(p.x - a.x, p.y - a.y);\n let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2;\n t = Math.max(0, Math.min(1, t));\n return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));\n }\n\n private resetInProgress(): void {\n this.rectStart = this.rectCurrent = null;\n this.polyPoints = [];\n this.freehandDragging = false;\n this.drawingPolygon = false;\n this.lastFreehandPx = null;\n // Close any open edit batch (e.g. a mode switch mid-drag) so the store's\n // emit coalescing doesn't get stuck.\n if (this.edit) {\n this.store.endBatch();\n this.edit = null;\n }\n }\n\n // ── commit to the store ──────────────────────────────────────────────\n private commitRectangle(x: number, y: number, w: number, h: number): void {\n const region = new Region();\n const rect = new Rectangle();\n rect.x = x; rect.y = y; rect.width = w; rect.height = h;\n region.bounds = rect;\n region.color = this.store.getShapeColor();\n this.commitRegion(region);\n }\n\n private commitPolygon(closed: boolean): void {\n if (this.polyPoints.length < (closed ? 3 : 2)) { this.resetInProgress(); return; }\n const region = new Region();\n const poly = new Polygon();\n poly.npoints = this.polyPoints.length;\n poly.xpoints = this.polyPoints.map(p => p.x);\n poly.ypoints = this.polyPoints.map(p => p.y);\n poly.coordinates = this.polyPoints.map(p => [p.x, p.y]);\n poly.closed = closed;\n region.bounds = poly;\n region.color = this.store.getShapeColor();\n this.resetInProgress();\n this.commitRegion(region);\n }\n\n /**\n * Add a freshly-drawn region to the shared store and redraw immediately. The\n * store mints the id, selects the new region (so it renders solid/highlighted\n * rather than as a dashed in-progress shape) and emits the full region list to\n * the Region Editor — we still redraw locally rather than relying solely on\n * the store's update event, which can be swallowed when Plotly isn't active.\n */\n private commitRegion(region: Region): void {\n // Default class/annotation name, matching the Plotly backend and the Region\n // Editor's \"Add\" actions so a freshly drawn region isn't unlabeled.\n if (region.label == null) region.label = 'Region';\n this.store.addRegion(region);\n this.redraw();\n }\n\n /**\n * Convert the selected region(s) to/from a bezier curve (toBezier = true /\n * toPolygon = false). One-shot; the anchors are unchanged,\n * only the smooth-curve rendering is toggled.\n */\n setSelectedBezier(bezier: boolean): void {\n const regions = this.store.getRegions();\n for (const idx of this.selected) {\n const region = regions[idx];\n if (region) this.store.setBezier(region.id, bezier);\n }\n this.redraw();\n }\n}\n","import { OSD } from './osd-lib';\n\n/** Round up to a \"nice\" 1/2/5 × 10ⁿ value for scale-bar lengths. */\nfunction niceLength(x: number): number {\n if (x <= 0) return 1;\n const base = Math.pow(10, Math.floor(Math.log10(x)));\n const f = x / base;\n const nice = f < 1.5 ? 1 : f < 3.5 ? 2 : f < 7.5 ? 5 : 10;\n return nice * base;\n}\n\n/**\n * Format a length given in micrometres, picking the unit that suits its\n * magnitude. The value is always µm internally (jit-service normalises whatever\n * unit Bio-Formats reports — nm/µm/mm/cm/inch — to µm), so this adapts the\n * displayed unit to the image's actual scale rather than assuming microns.\n */\nfunction formatUm(um: number): string {\n const trim = (n: number) => (n % 1 === 0 ? `${n}` : n.toFixed(1));\n if (um >= 1e6) return `${trim(um / 1e6)} m`;\n if (um >= 1e4) return `${trim(um / 1e4)} cm`;\n if (um >= 1e3) return `${trim(um / 1e3)} mm`;\n if (um >= 1) return `${trim(um)} µm`;\n return `${trim(um * 1000)} nm`;\n}\n\n/**\n * A physical scale bar drawn over an OpenSeadragon viewer. Recomputes on every\n * pan/zoom from the viewport's image→screen scale and the image's µm/pixel\n * (`mppX`, from Bio-Formats). Hidden when the image has no physical pixel size.\n */\nexport class OsdScaleBar {\n private readonly osd: any = OSD;\n private readonly bar: HTMLDivElement;\n private readonly line: HTMLDivElement;\n private readonly label: HTMLSpanElement;\n private readonly redrawHandler = () => this.update();\n\n constructor(private viewer: any, private mppX: number) {\n this.bar = document.createElement('div');\n Object.assign(this.bar.style, {\n position: 'absolute', left: '12px', bottom: '12px', zIndex: '30',\n pointerEvents: 'none', color: '#fff', font: '11px sans-serif',\n textShadow: '0 0 3px #000', textAlign: 'center', userSelect: 'none',\n } as CSSStyleDeclaration);\n this.label = document.createElement('span');\n this.line = document.createElement('div');\n Object.assign(this.line.style, {\n height: '4px', marginTop: '2px', background: 'rgba(255,255,255,0.9)',\n borderLeft: '1px solid #fff', borderRight: '1px solid #fff',\n boxShadow: '0 0 3px #000',\n } as CSSStyleDeclaration);\n this.bar.appendChild(this.label);\n this.bar.appendChild(this.line);\n this.viewer.canvas.appendChild(this.bar);\n\n this.viewer.addHandler('update-viewport', this.redrawHandler);\n this.viewer.addHandler('animation', this.redrawHandler);\n this.viewer.addHandler('resize', this.redrawHandler);\n this.update();\n }\n\n private update(): void {\n if (!(this.mppX > 0) || !this.viewer.viewport || this.viewer.world?.getItemCount() === 0) {\n this.bar.style.display = 'none';\n return;\n }\n const vp = this.viewer.viewport;\n const a = vp.imageToViewerElementCoordinates(new this.osd.Point(0, 0));\n const b = vp.imageToViewerElementCoordinates(new this.osd.Point(1, 0));\n const pxPerImagePx = Math.abs(b.x - a.x); // screen px per image px\n if (!(pxPerImagePx > 0)) { this.bar.style.display = 'none'; return; }\n\n const umPerScreenPx = this.mppX / pxPerImagePx;\n const niceUm = niceLength(120 * umPerScreenPx); // target ~120px bar\n this.bar.style.display = '';\n this.line.style.width = `${Math.round(niceUm / umPerScreenPx)}px`;\n this.label.textContent = formatUm(niceUm);\n }\n\n destroy(): void {\n this.viewer.removeHandler('update-viewport', this.redrawHandler);\n this.viewer.removeHandler('animation', this.redrawHandler);\n this.viewer.removeHandler('resize', this.redrawHandler);\n if (this.bar.parentNode) this.bar.parentNode.removeChild(this.bar);\n }\n}\n","import { ICoordinateTransform } from '../../contracts/coordinate-transform.contract';\nimport { elementToImage, imageToElement } from './osd-coords';\n\n/**\n * OpenSeadragon implementation of {@link ICoordinateTransform}. \"Data coords\"\n * here are image-pixel coordinates (OSD's native shape space), obtained from the\n * viewport API. This is the reason the tools can run over OSD at all: the\n * viewport gives a clean screen<->image mapping that holds across pan/zoom.\n */\nexport class OsdCoordinateTransform implements ICoordinateTransform {\n\n constructor(private viewer: any) {}\n\n isReady(): boolean {\n return !!this.viewer?.viewport && this.viewer.world?.getItemCount() > 0;\n }\n\n clientToData(clientX: number, clientY: number): { x: number; y: number } {\n const rect = this.viewer.canvas.getBoundingClientRect();\n return elementToImage(this.viewer, clientX - rect.left, clientY - rect.top);\n }\n\n dataLengthToScreen(dataLength: number): number {\n const a = imageToElement(this.viewer, 0, 0);\n const b = imageToElement(this.viewer, dataLength, 0);\n return Math.abs(b.x - a.x);\n }\n}\n","import { HttpClient } from '@angular/common/http';\nimport { firstValueFrom } from 'rxjs';\nimport { timeout } from 'rxjs/operators';\n\n/**\n * Single source of truth for jit-service `/tile` access from the OSD backend\n * (refactoring plan, Step 2). Before this module the tile URL was string-built\n * in four places and the fetch→decode pipeline copy-pasted in three — every\n * query-param change had to be repeated per site.\n *\n * Error handling is deliberately left to the CALL SITES: these helpers\n * propagate failures so each caller keeps its own tagged catch\n * (`[viz:histogram]`, `[viz:window]`, `[viz:export]`) and its own\n * skip/fallback semantics.\n */\n\n/** Tile coordinates for one `/tile` request. `channel == null` (or omitted)\n * requests the server-composited tile; an index (including 0) requests that\n * single channel as grayscale. */\nexport interface TileCoords {\n res: number;\n col: number;\n row: number;\n z: number;\n tileSize: number;\n channel?: number | null;\n}\n\n/** Build the `/tile` request URL — the one place its query shape lives. */\nexport function buildTileUrl(api: string, infoB64: string, c: TileCoords): string {\n const ch = c.channel == null ? '' : `&channel=${c.channel}`;\n return `${api}tile?info=${infoB64}&res=${c.res}&col=${c.col}&row=${c.row}&z=${c.z}&tileSize=${c.tileSize}${ch}`;\n}\n\n/** Fetch a tile PNG and decode it to an ImageBitmap. The caller owns the\n * bitmap (call `close()` when done). Throws on network/decode failure. */\nexport async function fetchTileBitmap(http: HttpClient, url: string, timeoutMs: number): Promise<ImageBitmap> {\n const blob = await firstValueFrom(http.get(url, { responseType: 'blob' }).pipe(timeout(timeoutMs)));\n return createImageBitmap(blob);\n}\n\n/** Fetch a tile and read its pixels back as RGBA ImageData (via an offscreen\n * canvas). Returns null only when a 2d context can't be created; throws on\n * network/decode failure (the caller's tagged catch handles it). */\nexport async function fetchTileRgba(\n http: HttpClient, url: string, timeoutMs: number,\n): Promise<ImageData | null> {\n const bmp = await fetchTileBitmap(http, url, timeoutMs);\n const cv = document.createElement('canvas');\n cv.width = bmp.width;\n cv.height = bmp.height;\n const ctx = cv.getContext('2d', { willReadFrequently: true });\n if (!ctx) return null;\n ctx.drawImage(bmp, 0, 0);\n bmp.close?.();\n return ctx.getImageData(0, 0, cv.width, cv.height);\n}\n","import { OSD } from './osd-lib';\n\n/**\n * Stack-slice cache for the OpenSeadragon backend (refactoring plan, Step 3 —\n * a pure move of the cache cluster out of the visualizer service).\n *\n * Scrubbing the z-slider used to viewer.open() a fresh tile source per slice,\n * which destroys the current tiled image (and its decoded+recolored tiles), so\n * revisiting a slice re-fetched everything. Instead we keep each visited slice\n * as its own tiled image in the world and just toggle opacity — a revisited\n * slice is instant (no network, no re-decode, no re-recolor). Bounded by an\n * LRU so deep stacks don't grow without limit. Multichannel slices cache one\n * TiledImage per channel (additively composited); composite slices cache one.\n * A background loader pre-fills the rest of the stack, one slice at a time,\n * yielding to the visible slice so on-screen tiles always win the connection.\n */\n\n/** What the cache needs from the visualizer service. All accessors are live\n * (called at use time, never captured) so the cache always sees the current\n * viewer/descriptor/z — matching the field reads it replaced. */\nexport interface SliceCacheHost {\n /** The mounted viewer, or null. */\n viewer(): any | null;\n /** True when a viewer, descriptor and infoB64 are all present. */\n hasImage(): boolean;\n /** Stack depth (descriptor.z, 1 for single images). */\n sliceCount(): number;\n /** The currently displayed z-slice. */\n currentZ(): number;\n /** Per-channel rendering (multichannel fluorescence) vs composite. */\n isMultiChannel(): boolean;\n /** Channel count for a multichannel group add. */\n channelCount(): number;\n /** Channel visibility (drives group reveal opacity). */\n channelVisible(c: number): boolean;\n /** Tile source for slice z (optionally one channel). */\n buildTileSource(z: number, channel?: number): any;\n /** A composite slice landed in the world — the service samples its window. */\n onCompositeSliceAdded(z: number): void;\n}\n\nexport class SliceCache {\n /** z-slice → its TiledImage in the viewer world (composite path). */\n private sliceItems = new Map<number, any>();\n /** Multichannel per-slice cache: z → the N channel TiledImages for that slice\n * (additively composited by OSD; index = channel). Only the active slice's\n * visible channels have opacity > 0. */\n private channelSliceItems = new Map<number, any[]>();\n /** Cached multichannel slices whose tiles were tinted before the latest\n * display change; re-tinted lazily when next revealed by z-scrub. */\n private staleSlices = new Set<number>();\n /** Most-recently-shown z last; drives LRU eviction. */\n private sliceLru: number[] = [];\n /** z-slices whose tiled image is being added (dedupe rapid scrubbing). */\n private slicesLoading = new Set<number>();\n /** Bumped whenever the loaded image changes; in-flight background slice adds\n * captured under an older token are dropped (cancelled image switch). */\n private sliceLoadToken = 0;\n /** The slice the background loader is currently waiting on (its tiles are\n * still streaming): addTiledImage 'success' fires on add, not on tile load,\n * so we gate the next slice on getFullyLoaded(). */\n private bgLoadingZ: number | null = null;\n /** When bgLoadingZ started loading — a fallback so a slow/stuck slice can't\n * stall the whole background pass forever. */\n private bgLoadingSince = 0;\n /** Slices the background loader has already attempted (no tight retry loop). */\n private bgAttempted = new Set<number>();\n /** Max cached slice tiled images kept resident before LRU eviction. */\n private maxCachedSlices = 8;\n /** Upper bound on resident slices, regardless of stack depth (memory guard). */\n private readonly MAX_CACHED_SLICES_CAP = 64;\n /** Fit-view tile budget above which background preloading is skipped: a huge\n * no-pyramid stack would preload every slice at full resolution and\n * flood/timeout. Normal stacks stay below it and KEEP the flicker-free\n * pre-cache. */\n private readonly MAX_PREFETCH_FIT_TILES = 256;\n /** True only for stacks too large to background-preload. */\n private skipSlicePrefetch = false;\n private prefetchTimer: any = null;\n\n constructor(private host: SliceCacheHost) {}\n\n // ── configuration (per image, from plot()) ────────────────────────────\n\n /** Size the cache for the loaded image: keep the whole stack resident\n * (capped) so the background loader fills every slice without evicting\n * itself; skip preloading entirely when even the coarsest level's tile\n * grid is too large (its slices only exist at full resolution). */\n configure(stackDepth: number, coarseFitTiles: number): void {\n this.skipSlicePrefetch = coarseFitTiles > this.MAX_PREFETCH_FIT_TILES;\n this.maxCachedSlices =\n stackDepth > 1 ? Math.min(this.MAX_CACHED_SLICES_CAP, stackDepth) : 1;\n }\n\n /** Current LRU cap (the viewer sizes its tile cache from it). */\n maxSlices(): number {\n return this.maxCachedSlices;\n }\n\n /** Drop the per-channel groups (on a fresh plot). */\n clearChannelGroups(): void {\n this.channelSliceItems.clear();\n }\n\n /** Seed the cache with the just-opened composite slice (world item 0), so\n * scrubbing back to it later is an instant opacity toggle, not a re-open. */\n seedComposite(z: number, item: any): void {\n this.sliceItems.set(z, item);\n this.touchSliceLru(z);\n }\n\n // ── slice display (setZIndex's cache work) ────────────────────────────\n\n /** Show slice z: reveal it instantly when cached (re-tinting a stale\n * multichannel group), otherwise add it once. The current slice stays\n * visible until the new one is in — no white-flicker. */\n showSlice(z: number): void {\n if (this.host.isMultiChannel()) {\n const group = this.channelSliceItems.get(z);\n if (group && group.length && group.some((it) => it && this.sliceInWorld(it))) {\n this.revealChannelSlice(z);\n // If a display change happened while this slice was cached, its tiles\n // hold a stale tint — re-apply now (it's the visible slice, so the\n // brief restore flash is acceptable, like a fresh load).\n if (this.staleSlices.delete(z)) this.invalidateSlice(z);\n this.touchSliceLru(z);\n this.schedulePrefetch();\n } else if (!this.slicesLoading.has(z)) {\n this.addChannelSlice(z);\n }\n return;\n }\n const cached = this.sliceItems.get(z);\n if (cached && this.sliceInWorld(cached)) {\n // Instant: reveal the cached slice, hide the others — no fetch/decode.\n this.showOnlySlice(z);\n this.touchSliceLru(z);\n this.schedulePrefetch();\n return;\n }\n if (this.slicesLoading.has(z)) return; // already being added; success reveals it\n this.addSlice(z);\n }\n\n /** Add a never-seen slice as a hidden tiled image, then reveal it once loaded\n * (composite path; multichannel routes to addChannelSlice). */\n private addSlice(z: number): void {\n if (!this.host.hasImage()) return;\n if (this.host.isMultiChannel()) {\n this.addChannelSlice(z);\n return;\n }\n this.slicesLoading.add(z);\n // Tag this add to the current image; if the user switches images before it\n // resolves, the stale callback is dropped (the add belongs to the old stack).\n const token = this.sliceLoadToken;\n const ts = this.host.buildTileSource(z);\n try {\n // addTiledImage lives on the Viewer (it queues the add into the world).\n this.host.viewer().addTiledImage({\n tileSource: ts,\n x: 0,\n y: 0,\n width: 1, // match the primary image's normalized placement\n opacity: 0,\n // Load tiles even though it's hidden — this is what lets the background\n // loader fill every slice's cache so scrubbing gets progressively smoother.\n preload: true,\n success: (e: any) => {\n const item = e?.item;\n if (token !== this.sliceLoadToken) {\n // Image switched while this was adding — drop the orphan so it stops\n // loading instead of streaming tiles for the abandoned stack.\n if (item) {\n try { this.host.viewer()?.world?.removeItem(item); } catch { /* gone */ }\n }\n return;\n }\n this.slicesLoading.delete(z);\n if (!item) return;\n this.sliceItems.set(z, item);\n this.touchSliceLru(z);\n this.host.onCompositeSliceAdded(z);\n // Only reveal if the user is still on this slice (fast scrubbing may\n // have moved on — leave it cached/hidden for a later revisit).\n if (z === this.host.currentZ()) {\n this.showOnlySlice(z);\n this.schedulePrefetch();\n }\n this.evictSliceLru();\n },\n error: () => {\n if (token === this.sliceLoadToken) this.slicesLoading.delete(z);\n },\n });\n } catch (err) {\n this.slicesLoading.delete(z);\n console.warn('[OSD] failed to add z-slice', err);\n }\n }\n\n /**\n * Add slice z's channel group: one additively-composited ('lighter' = Fiji\n * \"Composite\") TiledImage per channel, hidden (opacity 0) until revealed.\n * Each is preloaded so the background loader can pre-fill every slice.\n * Cached so a revisit is an instant opacity toggle — no re-fetch, no\n * white-flicker. Mirrors addSlice for the composite path.\n */\n addChannelSlice(z: number): void {\n if (!this.host.hasImage()) return;\n if (this.channelSliceItems.has(z) || this.slicesLoading.has(z)) return;\n this.slicesLoading.add(z);\n const token = this.sliceLoadToken;\n const n = this.host.channelCount();\n const group: any[] = new Array(n);\n let settled = 0;\n const onSettled = () => {\n if (++settled < n) return;\n if (token !== this.sliceLoadToken) return; // image switched mid-add\n this.slicesLoading.delete(z);\n this.channelSliceItems.set(z, group);\n this.staleSlices.delete(z); // freshly tinted at the current display state\n this.touchSliceLru(z);\n if (z === this.host.currentZ()) {\n this.revealChannelSlice(z); // tiles may still be decoding; opacity is set now\n this.schedulePrefetch();\n }\n this.evictSliceLru();\n };\n for (let c = 0; c < n; c++) {\n try {\n this.host.viewer().addTiledImage({\n tileSource: this.host.buildTileSource(z, c),\n x: 0, y: 0, width: 1,\n opacity: 0, // revealed by revealChannelSlice once the group is in\n compositeOperation: 'lighter',\n preload: true,\n success: (e: any) => {\n const item = e?.item;\n if (token !== this.sliceLoadToken) {\n if (item) { try { this.host.viewer()?.world?.removeItem(item); } catch { /* gone */ } }\n return;\n }\n if (item) group[c] = item;\n onSettled();\n },\n error: () => onSettled(),\n });\n } catch (err) {\n console.warn('[OSD] failed to add channel slice image', z, c, err);\n onSettled();\n }\n }\n }\n\n /** Reveal slice z's channel group (each visible channel → opacity 1) and\n * hide every other cached slice's group. Instant; no fetch/decode. */\n revealChannelSlice(z: number): void {\n for (const [zz, group] of this.channelSliceItems) {\n const active = zz === z;\n group.forEach((it, c) => {\n if (!it) return;\n const visible = this.host.channelVisible(c);\n try { it.setOpacity(active && visible ? 1 : 0); } catch { /* gone */ }\n });\n }\n }\n\n /** Show the given composite slice (opacity 1) and hide all other cached slices. */\n private showOnlySlice(z: number): void {\n for (const [zz, item] of this.sliceItems) {\n try { item.setOpacity(zz === z ? 1 : 0); } catch { /* item gone */ }\n }\n }\n\n // ── display invalidation (multichannel) ───────────────────────────────\n\n /** Re-tint after a display change: invalidate ONLY the visible slice's\n * channel images — invalidating the whole world would re-process every\n * hidden/preloaded slice's tiles (hundreds), flooding OSD and wasting work\n * on tiles that aren't on screen. The other cached slices are marked stale\n * and re-tinted lazily when revealed. */\n invalidateChannelDisplay(z: number): void {\n this.invalidateSlice(z);\n this.staleSlices.clear();\n for (const zz of this.channelSliceItems.keys()) {\n if (zz !== z) this.staleSlices.add(zz);\n }\n }\n\n /** Invalidate (restore + re-recolor) just the channel images of one cached\n * slice. A shared timestamp batches the per-image invalidations into one\n * processing pass (OSD dedupes tiles already stamped at >= tStamp). */\n private invalidateSlice(z: number): void {\n const group = this.channelSliceItems.get(z) ?? [];\n if (!group.length) return;\n const osd: any = OSD;\n const tStamp = typeof osd.now === 'function' ? osd.now() : Date.now();\n for (const it of group) {\n if (it && typeof it.requestInvalidate === 'function') {\n try { it.requestInvalidate(true, false, tStamp); } catch { /* gone */ }\n }\n }\n }\n\n // ── background stack preloading ───────────────────────────────────────\n\n /** Debounce so a burst of viewport/slice events coalesces, then advance the\n * background stack loader by one slice. */\n schedulePrefetch(): void {\n if (this.skipSlicePrefetch) return;\n if (this.prefetchTimer) clearTimeout(this.prefetchTimer);\n this.prefetchTimer = setTimeout(() => this.loadNextBackgroundSlice(), 200);\n }\n\n /**\n * Background-load the whole stack: add each not-yet-cached slice as a\n * hidden, preloaded tiled image, one at a time, working outward from the\n * current slice — and never blocking the visible slice (it yields while the\n * current view is still streaming tiles; only one slice is in flight at a\n * time so the on-screen tiles always win the connection).\n */\n private loadNextBackgroundSlice(): void {\n this.prefetchTimer = null;\n if (!this.host.hasImage()) return;\n const sliceCount = this.host.sliceCount();\n if (sliceCount <= 1) return; // not a stack — nothing to preload\n // Yield to the visible slice while it's still streaming tiles.\n if (this.sliceTilesLoading(this.host.currentZ())) {\n this.schedulePrefetch();\n return;\n }\n // Gate on the in-flight slice's TILES finishing — addTiledImage's success\n // fires on add, not on tile load, so without this we'd add the whole stack\n // at once and flood the connection. A time fallback prevents a stuck slice\n // from stalling the pass.\n if (this.bgLoadingZ != null) {\n const adding = this.slicesLoading.has(this.bgLoadingZ);\n const tilesLoading = this.sliceTilesLoading(this.bgLoadingZ);\n const timedOut = Date.now() - this.bgLoadingSince > 8000;\n if ((adding || tilesLoading) && !timedOut) {\n this.schedulePrefetch();\n return;\n }\n this.bgLoadingZ = null; // that slice's tiles are in (or gave up) — advance\n }\n const next = this.nearestUncachedSlice(sliceCount);\n if (next == null) return; // whole stack cached — done\n this.bgLoadingZ = next;\n this.bgLoadingSince = Date.now();\n this.bgAttempted.add(next);\n this.addSlice(next); // hidden + preload (added with opacity 0; not revealed)\n this.schedulePrefetch(); // poll until its tiles load, then advance\n }\n\n /** The not-yet-cached slice closest to the current one (load nearest first),\n * skipping any already attempted so a failed/slow one isn't retried in a loop. */\n private nearestUncachedSlice(sliceCount: number): number | null {\n const cur = this.host.currentZ();\n for (let d = 0; d < sliceCount; d++) {\n const candidates = d === 0 ? [cur] : [cur - d, cur + d];\n for (const z of candidates) {\n if (\n z >= 0 && z < sliceCount &&\n !this.sliceCacheHas(z) && !this.slicesLoading.has(z) && !this.bgAttempted.has(z)\n ) {\n return z;\n }\n }\n }\n return null;\n }\n\n /**\n * Stop background stack preloading and invalidate any in-flight slice add.\n * Called when a different image is selected so the previous stack stops\n * loading immediately instead of finishing in the background.\n */\n cancelBackgroundLoad(): void {\n if (this.prefetchTimer) {\n clearTimeout(this.prefetchTimer);\n this.prefetchTimer = null;\n }\n this.slicesLoading.clear();\n this.bgLoadingZ = null;\n this.bgAttempted.clear();\n this.sliceLoadToken++; // drop pending addTiledImage callbacks from the old image\n // Abort in-flight background tiles immediately by dropping the hidden\n // preloaded slices (removeItem cancels their pending tile loads). Keep the\n // visible slice so the current view doesn't blank before the next plot.\n this.dropHiddenSlices();\n }\n\n /** Remove every cached slice except the currently displayed one, aborting\n * their in-flight tile requests. */\n private dropHiddenSlices(): void {\n const v = this.host.viewer();\n if (!v) return;\n const cur = this.host.currentZ();\n for (const [z, item] of [...this.sliceItems]) {\n if (z === cur) continue;\n this.sliceItems.delete(z);\n try { v.world.removeItem(item); } catch { /* already gone */ }\n }\n for (const [z, group] of [...this.channelSliceItems]) {\n if (z === cur) continue;\n this.channelSliceItems.delete(z);\n for (const it of group) { if (it) { try { v.world.removeItem(it); } catch { /* gone */ } } }\n }\n this.sliceLru = this.sliceCacheHas(cur) ? [cur] : [];\n }\n\n // ── cache bookkeeping ─────────────────────────────────────────────────\n\n /** Whether slice z is in the active cache (composite single image, or the\n * multichannel per-channel group). */\n private sliceCacheHas(z: number): boolean {\n return this.host.isMultiChannel() ? this.channelSliceItems.has(z) : this.sliceItems.has(z);\n }\n\n /** The cached TiledImage(s) for slice z (0–1 for composite, N for multichannel). */\n private sliceGroup(z: number): any[] {\n if (this.host.isMultiChannel()) return this.channelSliceItems.get(z) ?? [];\n const it = this.sliceItems.get(z);\n return it ? [it] : [];\n }\n\n /** Whether slice z's tiles are still streaming (any cached image not fully loaded). */\n private sliceTilesLoading(z: number): boolean {\n const g = this.sliceGroup(z);\n if (!g.length) return false;\n return g.some((it) => it && typeof it.getFullyLoaded === 'function' && !it.getFullyLoaded());\n }\n\n /** Remove slice z's cached image(s) from the world and the active cache. */\n private removeCachedSlice(z: number): void {\n const v = this.host.viewer();\n if (this.host.isMultiChannel()) {\n const group = this.channelSliceItems.get(z);\n this.channelSliceItems.delete(z);\n if (group && v) for (const it of group) { if (it) { try { v.world.removeItem(it); } catch { /* gone */ } } }\n } else {\n const item = this.sliceItems.get(z);\n this.sliceItems.delete(z);\n if (item && v) { try { v.world.removeItem(item); } catch { /* gone */ } }\n }\n }\n\n /** Is the tiled image still in the world (not evicted)? */\n private sliceInWorld(item: any): boolean {\n try {\n return this.host.viewer().world.getIndexOfItem(item) >= 0;\n } catch {\n return false;\n }\n }\n\n /** Mark z as most-recently-used. */\n private touchSliceLru(z: number): void {\n const i = this.sliceLru.indexOf(z);\n if (i >= 0) this.sliceLru.splice(i, 1);\n this.sliceLru.push(z);\n }\n\n /** Drop the least-recently-used cached slices beyond the cap (never the\n * current one), removing their tiled images so memory stays bounded. */\n private evictSliceLru(): void {\n while (this.sliceLru.length > this.maxCachedSlices) {\n const cur = this.host.currentZ();\n const idx = this.sliceLru.findIndex((z) => z !== cur);\n if (idx < 0) break;\n const z = this.sliceLru.splice(idx, 1)[0];\n this.removeCachedSlice(z);\n }\n }\n\n /** Clear the cache (on teardown / image switch). */\n reset(): void {\n this.sliceItems.clear();\n this.channelSliceItems.clear();\n this.staleSlices.clear();\n this.sliceLru = [];\n this.slicesLoading.clear();\n this.bgLoadingZ = null;\n this.bgAttempted.clear();\n }\n}\n","import { IChannelState } from '../../contracts/channel-histogram-api.contract';\nimport { Rgb } from '../../contracts/colormap-lut';\n\n/**\n * The OSD pixel display pipeline (refactoring plan, Step 4 — a pure move of\n * the recolor math out of the visualizer service). Stateless: every call reads\n * the current display state through the host closures, exactly like the moved\n * code read the service's fields. Shared by tile recoloring and the composite\n * export so they stay identical.\n */\nexport interface DisplayPipelineHost {\n /** Grayscale image (colormap LUT path) vs RGB/multichannel (additive tint). */\n isGrayscale(): boolean;\n /** 256-entry colormap LUT (grayscale path); null while options resolve. */\n colorLut(): Rgb[] | null;\n /** Latest per-channel display state from the store. */\n channelStates(): IChannelState[];\n /** Inverted background (white = zero). */\n invertBg(): boolean;\n}\n\nexport class DisplayPipeline {\n constructor(private host: DisplayPipelineHost) {}\n\n /**\n * Apply the current display pipeline to an RGBA buffer in place; returns\n * whether any opaque pixel was written.\n * - Grayscale: intensity → window + gamma + invert → colormap LUT.\n * - RGB/multichannel: additive pseudo-colour merge — each visible channel's\n * windowed intensity is tinted by its assigned colour and summed (Fiji\n * \"Merge Channels\"). Defaults (R=red, G=green, B=blue) are the identity.\n */\n applyToRgba(d: Uint8ClampedArray): boolean {\n let changed = false;\n const channelStates = this.host.channelStates();\n const invertBg = this.host.invertBg();\n if (this.host.isGrayscale()) {\n const lut = this.host.colorLut();\n if (!lut) return false;\n const ch = channelStates[0];\n const wMin = ch ? ch.min : 0;\n const wSpan = ch && ch.max > ch.min ? ch.max - ch.min : 255;\n const invGamma = ch && ch.gamma > 0 ? 1 / ch.gamma : 1;\n // Precompute raw(0..255) -> final RGB once (256 window+gamma+invert+colormap\n // evaluations) and map each pixel by table lookup — a Math.pow per pixel\n // (~262k/tile) made the window/gamma sliders crawl on large stacks.\n const rL = new Uint8ClampedArray(256);\n const gL = new Uint8ClampedArray(256);\n const bL = new Uint8ClampedArray(256);\n for (let raw = 0; raw < 256; raw++) {\n let t = (raw - wMin) / wSpan;\n t = t < 0 ? 0 : t > 1 ? 1 : t;\n if (invGamma !== 1) t = Math.pow(t, invGamma);\n let v = Math.round(t * 255);\n if (invertBg) v = 255 - v;\n const c = lut[v];\n rL[raw] = c[0];\n gL[raw] = c[1];\n bL[raw] = c[2];\n }\n for (let i = 0; i < d.length; i += 4) {\n if (d[i + 3] === 0) continue;\n // maxRgb (contracts/intensity) inlined on purpose: this loop runs\n // ~262k times per tile on every recolor.\n const raw =\n d[i] >= d[i + 1] ? (d[i] >= d[i + 2] ? d[i] : d[i + 2]) : d[i + 1] >= d[i + 2] ? d[i + 1] : d[i + 2];\n d[i] = rL[raw];\n d[i + 1] = gL[raw];\n d[i + 2] = bL[raw];\n changed = true;\n }\n } else {\n const chans = [channelStates[0], channelStates[1], channelStates[2]];\n const tints = chans.map((c) => this.tint01(c));\n for (let i = 0; i < d.length; i += 4) {\n if (d[i + 3] === 0) continue;\n let oR = 0, oG = 0, oB = 0;\n for (let k = 0; k < 3; k++) {\n const c = chans[k];\n if (c && !c.visible) continue;\n const v = this.channelIntensity(d[i + k], c);\n const tint = tints[k];\n oR += v * tint[0];\n oG += v * tint[1];\n oB += v * tint[2];\n }\n if (oR > 255) oR = 255;\n if (oG > 255) oG = 255;\n if (oB > 255) oB = 255;\n if (invertBg) { oR = 255 - oR; oG = 255 - oG; oB = 255 - oB; }\n d[i] = oR;\n d[i + 1] = oG;\n d[i + 2] = oB;\n changed = true;\n }\n }\n return changed;\n }\n\n /** Precomputed lum(0..255) → tinted-RGB lookup for a channel's window/gamma/\n * colour. Building it costs 256 channelIntensity() calls; using it makes a\n * full-tile recolor ~262k array lookups instead of ~262k Math.pow() calls. */\n channelRgbLut(st?: IChannelState): { r: Uint8ClampedArray; g: Uint8ClampedArray; b: Uint8ClampedArray } {\n const r = new Uint8ClampedArray(256);\n const g = new Uint8ClampedArray(256);\n const b = new Uint8ClampedArray(256);\n const [tr, tg, tb] = this.tint01(st);\n for (let lum = 0; lum < 256; lum++) {\n const v = this.channelIntensity(lum, st);\n r[lum] = v * tr;\n g[lum] = v * tg;\n b[lum] = v * tb;\n }\n return { r, g, b };\n }\n\n /** Windowed + gamma intensity (0..255) for a channel, ignoring tint/invert. */\n channelIntensity(val: number, c?: IChannelState): number {\n if (!c) return val;\n const span = c.max > c.min ? c.max - c.min : 0;\n if (!span) return 0;\n let t = (val - c.min) / span;\n t = t < 0 ? 0 : t > 1 ? 1 : t;\n if (c.gamma > 0 && c.gamma !== 1) t = Math.pow(t, 1 / c.gamma);\n return t * 255;\n }\n\n /** A channel's pseudo-colour tint as [r,g,b] in 0..1 (default white). */\n tint01(c?: IChannelState): [number, number, number] {\n const m = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(c?.color ?? '');\n return m ? [parseInt(m[1], 16) / 255, parseInt(m[2], 16) / 255, parseInt(m[3], 16) / 255] : [1, 1, 1];\n }\n\n /** True when any RGB channel is windowed/hidden/gamma'd/re-tinted or the\n * background is inverted — otherwise the tile passes through unchanged. */\n rgbNeedsRecolor(): boolean {\n if (this.host.invertBg()) return true;\n const defaults = ['#ff0000', '#00ff00', '#0000ff'];\n const channelStates = this.host.channelStates();\n for (let k = 0; k < 3; k++) {\n const c = channelStates[k];\n if (\n c && (!c.visible || c.min !== 0 || c.max !== 255 || c.gamma !== 1 ||\n (c.color || '').toLowerCase() !== defaults[k])\n ) {\n return true;\n }\n }\n return false;\n }\n}\n","import { HttpClient } from '@angular/common/http';\nimport { Observable, firstValueFrom, from, of } from 'rxjs';\nimport { timeout } from 'rxjs/operators';\n\nimport { IHistogram } from '../../contracts/channel-histogram-api.contract';\nimport { buildTileUrl, fetchTileRgba } from './tile-client';\nimport { histogram256, maxRgb } from '../../contracts/intensity';\n\n/**\n * Histogram + auto-window sampling for the OSD backend (refactoring plan,\n * Step 4 — a pure move out of the visualizer service). Owns the per-slice\n * 8-bit histograms (sampled from displayed tiles) and the native-bit-depth\n * histograms (fetched from the server `/histogram` endpoint). Read-only with\n * respect to the tile/display pipeline.\n */\n\n/** The descriptor fields the samplers read (structurally satisfied by the\n * service's TileDescriptor). */\nexport interface SampledDescriptor {\n width: number;\n height: number;\n tileSize: number;\n channels?: number;\n levels?: Array<{ width: number; height: number }>;\n}\n\nexport interface HistogramSamplerHost {\n /** Real Bio-Formats levels (per-channel tiles exist only there). */\n realLevels(): number;\n /** Channel count for the multichannel sampler. */\n channelCount(d: SampledDescriptor): number;\n /** Grayscale (intensity histogram + auto-window) vs RGB (R/G/B histograms). */\n isGrayscale(): boolean;\n /** Histograms landed — nudge the pane to re-read (its retry window may have\n * lapsed). */\n onChannelHistogramsSampled(): void;\n /** A grayscale auto-window was measured from full-res tiles — seed the\n * Intensity channel (or re-invalidate if the user already windowed). */\n onGrayWindowSampled(min: number, max: number): void;\n}\n\nexport class HistogramSampler {\n /** 256-bin intensity histogram per z-slice, from sampled tiles. */\n private sliceHistograms = new Map<number, IHistogram[]>();\n /** Native-bit-depth histograms from `/histogram`, keyed `${z}|${channel}`. */\n private nativeHistograms = new Map<string, IHistogram>();\n /** Per-app-load cache-buster for `/histogram` — the server marks the\n * response cacheable for 24h, and a hard refresh can't bust a post-load\n * XHR. A token stable within a session but new on each full load keeps the\n * in-session dedup (via `nativeHistograms`) while always reflecting the\n * live backend after a reload. */\n private readonly histCacheBuster = Date.now();\n\n constructor(\n private http: HttpClient,\n private api: string,\n private host: HistogramSamplerHost,\n ) {}\n\n /** The sampled histogram for one channel of slice z, or null until the\n * async sampling resolves (or if it was skipped). */\n get(z: number, channelIndex: number): IHistogram | null {\n return this.sliceHistograms.get(z)?.[channelIndex] ?? null;\n }\n\n /** Drop everything (teardown / image switch). */\n clear(): void {\n this.sliceHistograms.clear();\n this.nativeHistograms.clear();\n }\n\n /**\n * Per-channel intensity histograms for multichannel images: sample each\n * channel's single-band tiles at the coarsest real level and bin the\n * luminance. Fire-and-forget.\n */\n async computeMultiChannelHistograms(d: SampledDescriptor, infoB64: string, z: number): Promise<void> {\n try {\n const t = d.tileSize;\n // Sample the COARSEST real level (per-channel tiles exist only at real\n // resolutions; the coarsest is small enough to bin even for whole-slides).\n const res = Math.max(0, this.host.realLevels() - 1);\n const lvl = d.levels?.[res];\n const lw = lvl?.width ?? d.width;\n const lh = lvl?.height ?? d.height;\n const cols = Math.max(1, Math.ceil(lw / t));\n const rows = Math.max(1, Math.ceil(lh / t));\n if (cols * rows > 64) return; // even the coarsest real level is too big\n const nCh = this.host.channelCount(d);\n if (nCh < 1) return;\n const counts: number[][] = Array.from({ length: nCh }, () => new Array(256).fill(0));\n const jobs: Array<Promise<void>> = [];\n for (let row = 0; row < rows; row++) {\n for (let col = 0; col < cols; col++) {\n for (let c = 0; c < nCh; c++) {\n const url = buildTileUrl(this.api, infoB64, { res, col, row, z, tileSize: t, channel: c });\n jobs.push(\n (async () => {\n try {\n const img = await fetchTileRgba(this.http, url, 20000);\n if (!img) return;\n const data = img.data;\n const cc = counts[c];\n for (let i = 0; i < data.length; i += 4) {\n if (data[i + 3] === 0) continue;\n cc[maxRgb(data[i], data[i + 1], data[i + 2])]++;\n }\n } catch (err) {\n // Skip this tile — the histogram is just missing its counts.\n console.warn('[viz:histogram] channel tile sample failed, skipping', url, err);\n }\n })(),\n );\n }\n }\n }\n await Promise.all(jobs);\n this.sliceHistograms.set(z, counts.map((c) => histogram256(c)));\n this.host.onChannelHistogramsSampled();\n } catch (err) {\n // Leave histograms unset (the pane shows empty) — but say why.\n console.warn('[viz:histogram] multichannel histogram sampling failed', err);\n }\n }\n\n /**\n * Compute a per-image intensity window [min,max] for grayscale auto-ranging,\n * mirroring the heatmap's auto-stretch. Two constraints force the sampling\n * strategy:\n * - The window MUST be in the same value space as the displayed tiles: the\n * `/preview` endpoint is server-normalized while `/tile` serves raw\n * un-normalized 8-bit — a window from the preview wouldn't match.\n * - It must read FULL-RESOLUTION tiles, not a downsampled overview:\n * averaging sparse low values (label masks) toward 0 wipes the signal.\n * So we sample the full-res level across the whole image — bounded to 64\n * tiles (a huge grayscale image samples the coarsest overview for histograms\n * only). Fire-and-forget; failures leave the window unset (identity 0..255).\n */\n async computeImageWindow(d: SampledDescriptor, infoB64: string, z: number): Promise<void> {\n const gray = this.host.isGrayscale();\n try {\n const t = d.tileSize;\n // Sample full-resolution when the grid is small (accurate for the grayscale\n // auto-window); otherwise sample the coarsest overview just for histograms\n // (whole-slide images). RGB only needs the histograms, not an auto-window.\n let res = 0;\n let cols = Math.max(1, Math.ceil(d.width / t));\n let rows = Math.max(1, Math.ceil(d.height / t));\n let fullRes = true;\n if (cols * rows > 64) {\n res = Math.max(0, (d.levels?.length ?? 1) - 1);\n const lvl = d.levels?.[res];\n cols = Math.max(1, Math.ceil((lvl?.width ?? d.width) / t));\n rows = Math.max(1, Math.ceil((lvl?.height ?? d.height) / t));\n fullRes = false;\n if (cols * rows > 36) return; // even the coarsest is too big — give up\n }\n const coords: Array<[number, number]> = [];\n for (let row = 0; row < rows; row++) {\n for (let col = 0; col < cols; col++) coords.push([col, row]);\n }\n let min = 255;\n let max = 0;\n const cR = new Array(256).fill(0);\n const cG = gray ? null : new Array(256).fill(0);\n const cB = gray ? null : new Array(256).fill(0);\n await Promise.all(\n coords.map(async ([col, row]) => {\n const url = buildTileUrl(this.api, infoB64, { res, col, row, z, tileSize: t });\n try {\n const img = await fetchTileRgba(this.http, url, 20000);\n if (!img) return;\n const data = img.data;\n for (let i = 0; i < data.length; i += 4) {\n if (data[i + 3] === 0) continue; // skip transparent padding\n if (gray) {\n const v = maxRgb(data[i], data[i + 1], data[i + 2]);\n if (v < min) min = v;\n if (v > max) max = v;\n cR[v]++;\n } else {\n cR[data[i]]++;\n cG![data[i + 1]]++;\n cB![data[i + 2]]++;\n }\n }\n } catch (err) {\n // Skip this tile — window/histogram just lose its samples.\n console.warn('[viz:window] tile sample failed, skipping', url, err);\n }\n }),\n );\n // Cache per-channel histograms: grayscale → [intensity]; RGB → [R, G, B].\n this.sliceHistograms.set(\n z, gray ? [histogram256(cR)] : [histogram256(cR), histogram256(cG!), histogram256(cB!)],\n );\n // Grayscale auto-window — only from full-res samples (coarsest averaging\n // is inaccurate); the host seeds the channel or re-invalidates.\n if (gray && fullRes && max > min && (min > 0 || max < 255)) {\n this.host.onGrayWindowSampled(min, max);\n }\n } catch (err) {\n console.warn('[viz:window] per-image window compute failed — using identity 0..255', err);\n }\n }\n\n /**\n * Native-bit-depth histogram for >8-bit images, from the server `/histogram`\n * endpoint (the 8-bit canvas tiles can't carry 16-bit values). Cached per\n * slice+channel for the session.\n */\n native$(infoB64: string, z: number, channel: number, bins: number): Observable<IHistogram | null> {\n const key = `${z}|${channel}`;\n const cached = this.nativeHistograms.get(key);\n if (cached) return of(cached);\n return from(this.fetchNative(infoB64, z, channel, bins, key));\n }\n\n /** Fetch + cache one channel's native histogram from `GET /histogram`. */\n private async fetchNative(\n infoB64: string, z: number, channel: number, bins: number, key: string,\n ): Promise<IHistogram | null> {\n const url = `${this.api}histogram?info=${infoB64}&channel=${channel}&z=${z}&bins=${bins}&_=${this.histCacheBuster}`;\n try {\n // HttpClient calls get auth via the Angular interceptor (unlike OSD's own\n // ajax tile loader, which needs authHeaders) — mirror the other fetches.\n const hi = await firstValueFrom(\n this.http\n .get<{\n bitDepth: number; rangeMin: number; rangeMax: number;\n observedMin: number; observedMax: number; binWidth: number; counts: number[];\n }>(url)\n .pipe(timeout(45000)),\n );\n if (!hi || !hi.counts) return null;\n const out: IHistogram = {\n // Native bin left-edges: rangeMin + i*binWidth.\n bins: hi.counts.map((_, i) => hi.rangeMin + i * hi.binWidth),\n counts: hi.counts,\n max: hi.counts.reduce((m, c) => (c > m ? c : m), 0),\n bitDepth: hi.bitDepth,\n rangeMin: hi.rangeMin,\n rangeMax: hi.rangeMax,\n observedMin: hi.observedMin,\n observedMax: hi.observedMax,\n };\n this.nativeHistograms.set(key, out);\n return out;\n } catch (err) {\n // 202 (still caching) or a transient error → null; the pane retries.\n console.warn('[viz:histogram] native histogram fetch failed', err);\n return null;\n }\n }\n}\n","import { Observable } from 'rxjs';\n\nimport { IDisplayOptions, IRegionStore } from '../contracts/visualizer.contract';\nimport { Region } from '../models/region';\nimport { ColormapNode } from '../contracts/display-types';\nimport { IImageMetadata } from '../contracts/image.contract';\nimport { RegionStore } from '../store/region-store.service';\nimport { VisualizerStore } from '../store/visualizer-store.service';\n\n/**\n * Shared store-delegation base for the OpenSeadragon and napari-js\n * `IVisualizer` backends. The entire `IRegionStore` and `IDisplayOptions`\n * surfaces (plus the two classification-colour members) are pure forwarders to\n * the shared `RegionStore` / `VisualizerStore` in BOTH backends — so they live\n * here once, as a single source of truth, rather than being copied per backend.\n * (This is the \"cross-backend behaviour that isn't rendering belongs in a\n * shared abstraction\" convention from CLAUDE.md; the extraction closes\n * SHARED-BACKEND-REFACTOR.md.)\n *\n * Backend-specific members — `load`/`plot`/`reset`/zoom/`setZIndex`/readback,\n * the region OVERLAY, tool wiring, histograms, scale bar, tiling, colormap LUT\n * application — deliberately stay in each subclass.\n *\n * NOT `@Injectable`: an abstract base doesn't participate in Angular DI. Each\n * subclass stays `@Injectable`, declares its own injected dependencies\n * (including the two stores), and passes them to `super(...)`. Plotly is\n * intentionally not a subclass — it has its own region model.\n */\nexport abstract class BaseStoreVisualizer implements IRegionStore, IDisplayOptions {\n protected constructor(\n protected readonly regionStore: RegionStore,\n protected readonly store: VisualizerStore,\n ) {}\n\n // ── IRegionStore → shared RegionStore ────────────────────────────────────\n setRegions(regions: Region[], showRegionLabel?: boolean, isRegionSaveOn?: boolean,\n fillColor?: string, append?: boolean): void {\n this.regionStore.setRegions(regions, showRegionLabel, isRegionSaveOn, fillColor, append);\n }\n getRegions(): Region[] { return this.regionStore.getRegions(); }\n getRegionPolygons(): any[] { return this.regionStore.getRegionPolygons(); }\n getRegionUpdateEvent(): Observable<any[]> { return this.regionStore.getRegionUpdateEvent(); }\n setSelectedShapeIndices(indices: number[]): void { this.regionStore.setSelectedShapeIndices(indices); }\n getSelectedShapeIndices$(): Observable<number[]> { return this.regionStore.getSelectedShapeIndices$(); }\n selectRegion(region: Region): void { this.regionStore.selectRegion(region); }\n deleteActiveShape(): void { this.regionStore.deleteActiveShape(); }\n getShowShapeLabel(): boolean { return this.regionStore.getShowShapeLabel(); }\n getShapeColor(): string { return this.regionStore.getShapeColor(); }\n getFillColor(): string { return this.regionStore.getFillColor(); }\n plotPreviousShapes(): void { this.regionStore.plotPreviousShapes(); }\n setPreviousShapes(shapes: any[]): void { this.regionStore.setPreviousShapes(shapes); }\n getPreviousShapes(): any[] { return this.regionStore.getPreviousShapes(); }\n undo(): void { this.regionStore.undo(); }\n redo(): void { this.regionStore.redo(); }\n canUndo(): boolean { return this.regionStore.canUndo(); }\n canRedo(): boolean { return this.regionStore.canRedo(); }\n getCanUndo$(): Observable<boolean> { return this.regionStore.getCanUndo$(); }\n getCanRedo$(): Observable<boolean> { return this.regionStore.getCanRedo$(); }\n resetUndoHistory(): void { this.regionStore.resetUndoHistory(); }\n importRegions(geoJsonStr: string): Region[] { return this.regionStore.importRegions(geoJsonStr); }\n exportRegions(regions: Region[]): void { this.regionStore.exportRegions(regions); }\n getGeoJsonString(regions: Region[]): string { return this.regionStore.getGeoJsonString(regions); }\n\n // ── Per-slice z-stack regions → RegionStore (jit-ui#93) ──────────────────\n enterStackMode(slices: Map<number, Region[]>, initialZ?: number,\n saveLayout?: 'combined' | 'per-slice-file'): void {\n this.regionStore.enterStackMode(slices, initialZ, saveLayout);\n }\n exitStackMode(): void { this.regionStore.exitStackMode(); }\n isStackMode(): boolean { return this.regionStore.isStackMode(); }\n getStackSaveLayout(): 'combined' | 'per-slice-file' { return this.regionStore.getStackSaveLayout(); }\n setDisplaySlice(z: number): void { this.regionStore.setDisplaySlice(z); }\n getSliceRegions(): Region[] { return this.regionStore.getSliceRegions(); }\n getStackSaveSlices(): Map<number, Region[]> { return this.regionStore.getStackSaveSlices(); }\n\n // ── Classification colours → shared VisualizerStore ──────────────────────\n getClassificationColors(): Map<string, string> { return this.store.getClassificationColors(); }\n setClassificationColor(label: string, color: string): void {\n this.store.setClassificationColor(label, color);\n }\n\n // ── IDisplayOptions → shared VisualizerStore ─────────────────────────────\n getColormap(): Observable<ColormapNode | null> { return this.store.getColormap(); }\n setColormap(colormap: ColormapNode): void { this.store.setColormap(colormap); }\n getColormapOptions(): ColormapNode[] { return this.store.getColormapOptions(); }\n getReverseScale(): Observable<boolean> { return this.store.getReverseScale(); }\n setReverseScale(reverscale: any): void { this.store.setReverseScale(reverscale); }\n setImageMeta(imageMeta: IImageMetadata[]): void { this.store.setImageMeta(imageMeta); }\n getImageMeta(): Observable<IImageMetadata[]> { return this.store.getImageMeta(); }\n}\n","import { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport { firstValueFrom } from 'rxjs';\n\nimport { IImageInfo } from '../contracts/image.contract';\n\n/**\n * Shared access to a \"simple\" (`IImageInfo.tiled === false`) stack — a\n * self-contained per-slice-URL image, as opposed to one server-tiled file\n * with an internal z dimension (the tile-pyramid case each backend already\n * handles on its own, since the tiling protocol itself IS backend-specific).\n * A numbered image series assembled client-side from separate files (the\n * jit-ui folder-stack feature) is the current producer of this shape.\n *\n * Every backend that can render a 2D image (OSD, napari-js) needs the exact\n * same three things for this case — detect it, resolve `urls[z]`, and fetch\n * that URL with the app's auth applied — so they live here once instead of\n * being reimplemented per backend. Plotly needs no equivalent: its `load()`\n * already fetches `urls[i]` generically for every plot type, with no\n * tile-server concept to route around.\n *\n * Fetches go through Angular's `HttpClient` so the app's auth interceptor\n * (Bearer token) applies — a raw `fetch()`/`<img src>` bypasses it and, behind\n * an OAuth2-proxied deployment, gets redirected to the login page and then\n * CORS-fails. Mirrors `PlotlyService.loadImage`, the reference\n * implementation this generalizes for the other backends.\n */\n@Injectable({ providedIn: 'root' })\nexport class SimpleSliceAccessService {\n /** raw slice URL → already-fetched blob: URL, so a backend that opens a\n * URL (OSD) doesn't repeat the auth round-trip revisiting a slice (scrub\n * back, the small→large tier re-fetch). Shared across backends: switching\n * plot types on the same file (e.g. Image → Volume) reuses entries. */\n private readonly blobUrls = new Map<string, string>();\n private currentFileName: string | undefined;\n\n constructor(private http: HttpClient) {}\n\n /** True when `imageInfo` is a self-contained per-slice-URL stack with no\n * server tile pyramid to route to. */\n isSimple(imageInfo: IImageInfo | null | undefined): boolean {\n return imageInfo?.tiled === false;\n }\n\n /** The URL for slice `z` of a simple stack (falls back to slice 0 if `z`\n * is out of range or unset). */\n urlFor(imageInfo: IImageInfo, z: number): string | undefined {\n return imageInfo.urls?.[z] ?? imageInfo.urls?.[0];\n }\n\n /** Call once per backend `load()` so the blob cache is evicted when a\n * genuinely different file is selected — not on every phase/z-scrub of\n * the SAME file, and not wrongly evicted by a second backend loading the\n * same file for a different plot type. */\n noteActiveFile(fileName: string | undefined): void {\n if (fileName && this.currentFileName && fileName !== this.currentFileName) {\n this.revokeAll();\n }\n this.currentFileName = fileName;\n }\n\n /** Fetch a slice's own URL and hand back a blob: URL — for backends (OSD)\n * that open a URL rather than decode bytes directly. A true in-memory\n * blob:/data: URL (the processing-pipeline's original tiled:false use\n * case) is already self-contained and returned as-is, no fetch/cache. */\n async fetchAsBlobUrl(rawUrl: string): Promise<string> {\n if (rawUrl.startsWith('blob:') || rawUrl.startsWith('data:')) return rawUrl;\n const cached = this.blobUrls.get(rawUrl);\n if (cached) return cached;\n const blob = await firstValueFrom(this.http.get(rawUrl, { responseType: 'blob' }));\n const blobUrl = URL.createObjectURL(blob);\n this.blobUrls.set(rawUrl, blobUrl);\n return blobUrl;\n }\n\n /** Fetch a slice's own URL and decode it as an `ImageBitmap` — for\n * backends (napari-js) that upload pixels directly rather than opening a\n * URL. Not cached (ImageBitmaps are consumed once and closed by the\n * caller); the underlying HTTP response may still hit the browser cache.\n *\n * A self-contained blob:/data: URL (e.g. the processing-pipeline's\n * in-memory preview, which also emits `tiled:false`) needs no auth and\n * isn't a server URL to route through the interceptor — read it directly\n * via the browser. Only real server URLs go through HttpClient so the auth\n * interceptor applies. Mirrors {@link fetchAsBlobUrl}'s blob:/data: branch. */\n async fetchAsBitmap(rawUrl: string): Promise<ImageBitmap> {\n const blob = rawUrl.startsWith('blob:') || rawUrl.startsWith('data:')\n ? await (await fetch(rawUrl)).blob()\n : await firstValueFrom(this.http.get(rawUrl, { responseType: 'blob' }));\n return createImageBitmap(blob);\n }\n\n private revokeAll(): void {\n for (const url of this.blobUrls.values()) URL.revokeObjectURL(url);\n this.blobUrls.clear();\n }\n}\n","/**\n * Colormap → RGB lookup-table builder.\n *\n * Lets a non-Plotly backend (OpenSeadragon) recolor grayscale pixels with the\n * exact same colormaps the Plotly heatmap uses. The input is a colormap value\n * straight from `COLORMAP_OPTIONS` (see plot.utilities) — the same value handed\n * to Plotly's `colorscale` — so the two surfaces stay in lock-step.\n *\n * A colormap value is either:\n * - an array of `[stop, color]` pairs (the matplotlib `*_LUT` constants), or\n * - a Plotly built-in scale *name* string (e.g. 'Viridis', 'Reds').\n * `color` may be `'rgb(r, g, b)'` or `'#rrggbb'`/`'#rgb'`.\n */\n\nexport type Rgb = [number, number, number];\ntype Stop = [number, string];\n\n/**\n * Plotly's built-in named colorscales (copied verbatim from plotly.js\n * `components/colorscale/scales.js`), for the `COLORMAP_OPTIONS` entries whose\n * `value` is a name string rather than an inline LUT array.\n */\nconst BUILTIN_SCALES: Record<string, Stop[]> = {\n Greys: [[0, 'rgb(0,0,0)'], [1, 'rgb(255,255,255)']],\n YlGnBu: [[0, 'rgb(8,29,88)'], [0.125, 'rgb(37,52,148)'], [0.25, 'rgb(34,94,168)'], [0.375, 'rgb(29,145,192)'], [0.5, 'rgb(65,182,196)'], [0.625, 'rgb(127,205,187)'], [0.75, 'rgb(199,233,180)'], [0.875, 'rgb(237,248,217)'], [1, 'rgb(255,255,217)']],\n Greens: [[0, 'rgb(0,68,27)'], [0.125, 'rgb(0,109,44)'], [0.25, 'rgb(35,139,69)'], [0.375, 'rgb(65,171,93)'], [0.5, 'rgb(116,196,118)'], [0.625, 'rgb(161,217,155)'], [0.75, 'rgb(199,233,192)'], [0.875, 'rgb(229,245,224)'], [1, 'rgb(247,252,245)']],\n YlOrRd: [[0, 'rgb(128,0,38)'], [0.125, 'rgb(189,0,38)'], [0.25, 'rgb(227,26,28)'], [0.375, 'rgb(252,78,42)'], [0.5, 'rgb(253,141,60)'], [0.625, 'rgb(254,178,76)'], [0.75, 'rgb(254,217,118)'], [0.875, 'rgb(255,237,160)'], [1, 'rgb(255,255,204)']],\n Bluered: [[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']],\n RdBu: [[0, 'rgb(5,10,172)'], [0.35, 'rgb(106,137,247)'], [0.5, 'rgb(190,190,190)'], [0.6, 'rgb(220,170,132)'], [0.7, 'rgb(230,145,90)'], [1, 'rgb(178,10,28)']],\n Reds: [[0, 'rgb(220,220,220)'], [0.2, 'rgb(245,195,157)'], [0.4, 'rgb(245,160,105)'], [1, 'rgb(178,10,28)']],\n Blues: [[0, 'rgb(5,10,172)'], [0.35, 'rgb(40,60,190)'], [0.5, 'rgb(70,100,245)'], [0.6, 'rgb(90,120,245)'], [0.7, 'rgb(106,137,247)'], [1, 'rgb(220,220,220)']],\n Picnic: [[0, 'rgb(0,0,255)'], [0.1, 'rgb(51,153,255)'], [0.2, 'rgb(102,204,255)'], [0.3, 'rgb(153,204,255)'], [0.4, 'rgb(204,204,255)'], [0.5, 'rgb(255,255,255)'], [0.6, 'rgb(255,204,255)'], [0.7, 'rgb(255,153,255)'], [0.8, 'rgb(255,102,204)'], [0.9, 'rgb(255,102,102)'], [1, 'rgb(255,0,0)']],\n Rainbow: [[0, 'rgb(150,0,90)'], [0.125, 'rgb(0,0,200)'], [0.25, 'rgb(0,25,255)'], [0.375, 'rgb(0,152,255)'], [0.5, 'rgb(44,255,150)'], [0.625, 'rgb(151,255,0)'], [0.75, 'rgb(255,234,0)'], [0.875, 'rgb(255,111,0)'], [1, 'rgb(255,0,0)']],\n Portland: [[0, 'rgb(12,51,131)'], [0.25, 'rgb(10,136,186)'], [0.5, 'rgb(242,211,56)'], [0.75, 'rgb(242,143,56)'], [1, 'rgb(217,30,30)']],\n Jet: [[0, 'rgb(0,0,131)'], [0.125, 'rgb(0,60,170)'], [0.375, 'rgb(5,255,255)'], [0.625, 'rgb(255,255,0)'], [0.875, 'rgb(250,0,0)'], [1, 'rgb(128,0,0)']],\n Hot: [[0, 'rgb(0,0,0)'], [0.3, 'rgb(230,0,0)'], [0.6, 'rgb(255,210,0)'], [1, 'rgb(255,255,255)']],\n Blackbody: [[0, 'rgb(0,0,0)'], [0.2, 'rgb(230,0,0)'], [0.4, 'rgb(230,210,0)'], [0.7, 'rgb(255,255,255)'], [1, 'rgb(160,200,255)']],\n Earth: [[0, 'rgb(0,0,130)'], [0.1, 'rgb(0,180,180)'], [0.2, 'rgb(40,210,40)'], [0.4, 'rgb(230,230,50)'], [0.6, 'rgb(120,70,20)'], [1, 'rgb(255,255,255)']],\n Electric: [[0, 'rgb(0,0,0)'], [0.15, 'rgb(30,0,100)'], [0.4, 'rgb(120,0,100)'], [0.6, 'rgb(160,90,0)'], [0.8, 'rgb(230,200,0)'], [1, 'rgb(255,250,220)']],\n Viridis: [[0, '#440154'], [0.06274509803921569, '#48186a'], [0.12549019607843137, '#472d7b'], [0.18823529411764706, '#424086'], [0.25098039215686274, '#3b528b'], [0.3137254901960784, '#33638d'], [0.3764705882352941, '#2c728e'], [0.4392156862745098, '#26828e'], [0.5019607843137255, '#21918c'], [0.5647058823529412, '#1fa088'], [0.6274509803921569, '#28ae80'], [0.6901960784313725, '#3fbc73'], [0.7529411764705882, '#5ec962'], [0.8156862745098039, '#84d44b'], [0.8784313725490196, '#addc30'], [0.9411764705882353, '#d8e219'], [1, '#fde725']],\n Cividis: [[0, 'rgb(0,32,76)'], [0.058824, 'rgb(0,42,102)'], [0.117647, 'rgb(0,52,110)'], [0.176471, 'rgb(39,63,108)'], [0.235294, 'rgb(60,74,107)'], [0.294118, 'rgb(76,85,107)'], [0.352941, 'rgb(91,95,109)'], [0.411765, 'rgb(104,106,112)'], [0.470588, 'rgb(117,117,117)'], [0.529412, 'rgb(131,129,120)'], [0.588235, 'rgb(146,140,120)'], [0.647059, 'rgb(161,152,118)'], [0.705882, 'rgb(176,165,114)'], [0.764706, 'rgb(192,177,109)'], [0.823529, 'rgb(209,191,102)'], [0.882353, 'rgb(225,204,92)'], [0.941176, 'rgb(243,219,79)'], [1, 'rgb(255,233,69)']],\n};\n\n/** Parse a Plotly colorscale color (`rgb(r,g,b)` or `#rrggbb`/`#rgb`) to RGB. */\nfunction parseColor(c: string): Rgb {\n const s = (c || '').trim();\n const hex = s.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);\n if (hex) {\n let h = hex[1];\n if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];\n return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];\n }\n const rgb = s.match(/rgba?\\(([^)]+)\\)/i);\n if (rgb) {\n const p = rgb[1].split(',').map((v) => parseFloat(v.trim()));\n return [Math.round(p[0]) || 0, Math.round(p[1]) || 0, Math.round(p[2]) || 0];\n }\n return [0, 0, 0];\n}\n\n/**\n * Build a 256-entry RGB lookup table from a `COLORMAP_OPTIONS` value, indexed by\n * grayscale value 0–255. Returns null if the value can't be resolved to a scale.\n * @param value array of `[stop, color]` pairs, or a Plotly built-in name string\n * @param reverse mirror the scale (matches Plotly's `reversescale`)\n */\nexport function buildColormapLut(value: unknown, reverse = false): Rgb[] | null {\n let scale: Stop[] | null = null;\n if (Array.isArray(value)) scale = value as Stop[];\n else if (typeof value === 'string') scale = BUILTIN_SCALES[value] ?? null;\n if (!scale || scale.length < 2) return null;\n\n // Normalise + sort the control points.\n const stops = scale\n .map((s) => [Number(s[0]), parseColor(String(s[1]))] as [number, Rgb])\n .sort((a, b) => a[0] - b[0]);\n\n const lut: Rgb[] = new Array(256);\n for (let i = 0; i < 256; i++) {\n const t = i / 255;\n // Find the bracketing control points for t.\n let k = 0;\n while (k < stops.length - 2 && stops[k + 1][0] < t) k++;\n const [t0, c0] = stops[k];\n const [t1, c1] = stops[k + 1];\n const span = t1 - t0 || 1;\n const f = Math.max(0, Math.min(1, (t - t0) / span));\n lut[i] = [\n Math.round(c0[0] + (c1[0] - c0[0]) * f),\n Math.round(c0[1] + (c1[1] - c0[1]) * f),\n Math.round(c0[2] + (c1[2] - c0[2]) * f),\n ];\n }\n if (reverse) lut.reverse();\n return lut;\n}\n","import { Injectable, Inject, Optional } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport { BehaviorSubject, Observable, Subject, Subscription, combineLatest, firstValueFrom, of } from 'rxjs';\nimport { timeout } from 'rxjs/operators';\nimport { Image } from 'image-js';\nimport * as OpenSeadragon from 'openseadragon';\nimport { OSD } from './osd-lib';\n\n\nimport { VisualizerStore } from '../../store/visualizer-store.service';\nimport { RegionStore } from '../../store/region-store.service';\nimport { IImageInfo } from '../../contracts/image.contract';\nimport { TileAccessPort, TILE_ACCESS_PORT } from '../../contracts/ports/tile-access.port';\nimport { VizConfig, VIZ_CONFIG } from '../../contracts/viz-config';\nimport { PlotType, PLOT_TYPE_DESCRIPTORS, PlotTypeDescriptor } from '../../contracts/plot-type';\nimport { IVisualizer, PixelData, IntensityProfile, IIsosurfaceControls, IIntensityControls, ISurface3dControls } from '../../contracts/visualizer.contract';\nimport { ViewerCapabilities, ViewerFeature, capabilitiesOf } from '../../contracts/capabilities.contract';\nimport { OsdRegionOverlay } from './osd-region-overlay';\nimport { OsdScaleBar } from './osd-scale-bar';\nimport { IRegionOverlay, RegionToolMode } from '../../contracts/region-overlay.contract';\nimport { ICoordinateTransform } from '../../contracts/coordinate-transform.contract';\nimport { OsdCoordinateTransform } from './osd-coordinate-transform';\nimport { elementToImage, imageRectToViewport, viewportRectToImage } from './osd-coords';\nimport { buildTileUrl, fetchTileBitmap } from './tile-client';\nimport { SliceCache } from './slice-cache';\nimport { DisplayPipeline } from './display-pipeline';\nimport { HistogramSampler } from './histogram-sampler';\nimport { BaseStoreVisualizer } from '../base-store-visualizer';\nimport { SimpleSliceAccessService } from '../simple-slice-access.service';\nimport { CachedImageData, WandToolService, WandToolHost } from '../../toolbar/wand/wand-tool.service';\nimport { BrushToolService, BrushOptions } from '../../toolbar/brush/brush-tool.service';\nimport { SamToolService } from '../../toolbar/segmentation/sam-tool.service';\nimport { SamPointToolService } from '../../toolbar/segmentation/sam-point-tool.service';\nimport { CellSegmentToolService } from '../../toolbar/segmentation/cell-segment-tool.service';\nimport { ICellSegmenter, CELL_SEGMENTER } from '../../contracts/cell-segmenter.contract';\nimport { VertexEraserToolService, VertexEraserToolHost } from '../../toolbar/vertex-eraser/vertex-eraser-tool.service';\nimport { ZoomToBoxToolService, ZoomToBoxToolHost } from '../../toolbar/zoom-to-box/zoom-to-box-tool.service';\nimport { WandOptions } from '../../toolbar/wand/wand.service';\nimport { buildColormapLut, Rgb } from '../../contracts/colormap-lut';\nimport { IChannelState, IHistogram } from '../../contracts/channel-histogram-api.contract';\nimport { saveAs } from 'file-saver';\n\n/**\n * Quiet OpenSeadragon's \"[Viewport.*] is not accurate with multi-image\" advisories.\n * A multichannel image is composited from one TiledImage per channel — a legitimate\n * multi-image world — and OSD logs that advisory (at error level) from its own\n * navigator/overview rendering on every animation frame, flooding the console. Our\n * own image<->viewport conversions already route through world item 0 (see\n * osd-coords), so the remaining advisories are OSD-internal and only affect the\n * minimap's box accuracy (cosmetic). This wraps OSD's logger in a Proxy that drops\n * only that one message string and forwards every other log untouched. Idempotent.\n */\nfunction silenceOsdMultiImageAdvisory(): void {\n const osd: any = OSD as any;\n if (osd.__multiImageFilterInstalled) return;\n const base: any = (osd.console && typeof osd.console.error === 'function')\n ? osd.console\n : (typeof console !== 'undefined' ? console : null);\n if (!base) return;\n const isAdvisory = (a: unknown) =>\n typeof a === 'string' && a.indexOf('not accurate with multi-image') !== -1;\n osd.console = new Proxy(base, {\n get(target: any, prop: string) {\n const orig = target[prop];\n if ((prop === 'error' || prop === 'warn') && typeof orig === 'function') {\n return (...args: any[]) => { if (isAdvisory(args[0])) return; orig.apply(target, args); };\n }\n return typeof orig === 'function' ? orig.bind(target) : orig;\n },\n });\n osd.__multiImageFilterInstalled = true;\n}\n\n/** One pyramid level from `GET /tiles/info`. */\ninterface TileLevel { res: number; width: number; height: number; }\n\n/** Tile-source descriptor returned by `GET /tiles/info`. */\ninterface TileDescriptor {\n width: number;\n height: number;\n tileSize: number;\n z: number;\n channels: number;\n /** True only for genuine multi-channel composites (indexed/LUT-bearing\n * fluorescence stacks) the client should split into per-channel layers. The\n * server sets it; an RGB photo read as separated planes has channels>1 but\n * multichannel=false, so it stays a single composite tile source. */\n multichannel?: boolean;\n /** Real Bio-Formats resolution levels at the front of `levels`; the remaining\n * levels are synthetic composited overviews (no per-channel tiles). */\n realLevels?: number;\n /** Per-channel metadata (name/color/bitDepth/min-maxAllowed) for native 16-bit\n * windowing + histogram; null for plain 8-bit/RGB sources. */\n channelInfo?: Array<{\n name?: string; color?: string; bitDepth?: number; minAllowed?: number; maxAllowed?: number;\n }> | null;\n levels: TileLevel[];\n /** Physical pixel size in µm (0 when the format doesn't report it). */\n mppX?: number;\n mppY?: number;\n}\n\n/** What `load()` hands to `plot()`. */\ninterface OsdLoaded {\n descriptor: TileDescriptor | null;\n infoB64: string;\n z: number;\n /** Mirrors the loaded image's filename — the diagram's render pipeline\n * guards on `loaded.filename === phaseInfo.fileName` before calling plot(). */\n filename: string | undefined;\n /** Simple (non-tiled) image: `plot()` opens {@link url} directly via OSD's\n * single-image source — no tile pyramid, no server. Set when the image\n * carries `tiled === false` (see {@link IImageInfo.tiled}). */\n simple?: boolean;\n /** The directly-loadable image URL (`blob:`/`data:`/`http`) for simple mode. */\n url?: string;\n}\n\n/**\n * OpenSeadragon visualization backend.\n *\n * Renders the *image* plot type as a natively-tiled, zoomable raster, backed by\n * the jit-service tile endpoints (`GET /tiles/info` + `GET /tile`, which reuse\n * the Bio-Formats ROI renderer). Plotly keeps the scientific/data plot types\n * (scalar heatmap, surface, contour, scatter, line, scatter3d, isosurface) —\n * hence this backend advertises only `ImageDisplay`.\n *\n * Wired: load → descriptor, plot → mount viewer with a custom tile source,\n * zoom/pan → viewport API. NOT wired yet (follow-ups): region overlays + tools\n * (a positioned canvas/SVG overlay or Annotorious), pixel readback, and the\n * per-tile LUT/contrast params. Not registered in DI providers — `PlotlyService`\n * is still the only active backend; this proves the contract supports a second\n * implementation against real endpoints.\n */\n@Injectable({ providedIn: 'root' })\nexport class OpenSeadragonVisualizerService extends BaseStoreVisualizer implements IVisualizer {\n /** OSD's strength is displaying a large zoomable image — nothing else here. */\n readonly capabilities: ViewerCapabilities = capabilitiesOf([ViewerFeature.ImageDisplay]);\n\n private readonly api: string;\n private viewer: OpenSeadragon.Viewer | null = null;\n private overlay: IRegionOverlay | null = null;\n private scaleBar: OsdScaleBar | null = null;\n private descriptor: TileDescriptor | null = null;\n /** Base64 RawFileInfo + current z-slice, kept so setZIndex can rebuild the\n * tile source and swap slices live (stack navigation). */\n private infoB64 = '';\n private currentZ = 0;\n /** True while the current image is \"simple\" (tiled:false — self-contained\n * per-slice URLs, no tile server; e.g. a numbered image series assembled\n * client-side into a stack). setZIndex swaps the single-image source for\n * the new slice's URL instead of updating a tiled z-param. */\n private simpleMode = false;\n /** urls[] for the current simple-mode image, so setZIndex can look up the\n * slice being scrubbed to (via {@link SimpleSliceAccessService.urlFor}).\n * Unused (and left stale, harmlessly) in tiled mode. */\n private simpleUrls: string[] = [];\n /** preview blob URL → full-res upscaled blob URL (see toFullResUrl), so\n * re-visiting a simple-mode slice doesn't re-upscale. Revoked on file change. */\n private readonly simpleFullResUrls = new Map<string, string>();\n /** Skip the full-res upscale above this longest-side dimension — a folder\n * stack is per-file previews (well under this); this only guards against an\n * accidental enormous canvas allocation. */\n private readonly SIMPLE_UPSCALE_MAX_DIM = 8192;\n private coordTransform: ICoordinateTransform | null = null;\n private wandHost!: WandToolHost;\n private eraserHost!: VertexEraserToolHost;\n /** Wand sampling matrix read back from the rendered viewport; cached until\n * the viewport changes (see readbackViewport). */\n private viewportPixels: CachedImageData | null = null;\n /** The DOM id of the element OSD is mounted in (shared with Plotly); the\n * on-canvas tools attach their overlays here. */\n private plotDiv = '';\n /** Current file name, tagged onto wand-created shapes. */\n private currentFileName: string | undefined;\n /** 256-entry RGB LUT for the active colormap, applied to grayscale tiles via\n * the tile-invalidated pixel pipeline (mirrors Plotly's heatmap colorscale).\n * Null while options resolve; recoloring is skipped until it's built. */\n private colorLut: Rgb[] | null = null;\n /** Only grayscale images get a colormap (RGB tiles pass through untouched). */\n private isGrayscaleImage = false;\n private colormapSub: Subscription | null = null;\n /** Latest per-channel display state (window/gamma/visibility) from the store,\n * read synchronously by recolorTile. Channel 0 drives grayscale windowing;\n * R/G/B (indices 0-2) drive RGB per-channel windowing. */\n private channelStates: IChannelState[] = [];\n /** True for multichannel fluorescence (channelCount > 1, not RGB): tiles are\n * composited client-side from per-channel single-band fetches (see\n * recolorMultiChannelTile) rather than recolored in place. */\n private isMultiChannel = false;\n /** Count of real Bio-Formats resolution levels (per-channel tiles exist only\n * here). For multichannel images the tile source is built from these alone so\n * every displayed tile supports a per-channel fetch. */\n private realLevels = 0;\n /** Inverted background (white = zero): inverts the display value before the\n * LUT (grayscale) / per channel (RGB). */\n private invertBg = false;\n /** Bearer token for OSD's own tile fetches (HttpClient calls get it via the\n * interceptor; OSD's loader does not, so we pass it as an ajax header). */\n private authHeaders: Record<string, string> = {};\n /** Whether the overview navigator (minimap) is shown. Read at viewer creation;\n * a consumer that doesn't want it (e.g. a small embedded preview) sets it off\n * via {@link setNavigatorVisible} before the first render. */\n private navigatorVisible = true;\n /** Image smoothing (bilinear). `false` → nearest-neighbour, so zoomed-in pixels\n * render as crisp blocks (pixel inspection). Defaults to `false` so the image\n * opens showing raw pixels. Read at viewer creation; toggled via\n * {@link setImageSmoothingEnabled}. */\n private smoothingEnabled = false;\n\n /** Overall deadline for the /tiles/info poll loop. An uncached whole-slide\n * image (e.g. .ndpi) is cached server-side first (GCS->PVC), which can take\n * several minutes — we poll (short requests; the cache-progress overlay\n * shows the wait) until it's ready. Generous because each poll is cheap; on\n * expiry the render pipeline gives up and the router falls back to Plotly. */\n private readonly tilesInfoTimeoutMs = 600000; // 10 min\n\n /** Per-channel fit-view tile budget (tiles at the coarsest real level × channels).\n * Above it, a multichannel image renders server-composited instead of per-channel\n * — its full-res reads (it has no overview pyramid) would be too many × N channels.\n * 64 (e.g. a 4x4 single-FOV z-stack × 4ch) stays per-channel; a whole-slide\n * (hundreds–thousands) falls back. */\n private readonly MAX_MULTICHANNEL_FIT_TILES = 256;\n\n /** Pixel display pipeline (window/gamma/invert/colormap + additive tint) —\n * shared by tile recoloring and the composite export so they stay identical\n * (see DisplayPipeline). Host closures read the service's live fields. */\n private readonly display = new DisplayPipeline({\n isGrayscale: () => this.isGrayscaleImage,\n colorLut: () => this.colorLut,\n channelStates: () => this.channelStates,\n invertBg: () => this.invertBg,\n });\n\n /** Histogram + auto-window sampling (see HistogramSampler). Constructed in\n * the ctor body because it captures the resolved API base URL. */\n private sampler!: HistogramSampler;\n\n /** Stack-slice cache + background preloader (see SliceCache — refactoring\n * plan Step 3). The host accessors are live closures, so the cache always\n * reads the service's current viewer/descriptor/z — exactly the fields the\n * moved code used to read directly. */\n private readonly cache = new SliceCache({\n viewer: () => this.viewer,\n hasImage: () => !!(this.viewer && this.descriptor && this.infoB64),\n sliceCount: () => this.descriptor?.z ?? 1,\n currentZ: () => this.currentZ,\n isMultiChannel: () => this.isMultiChannel,\n channelCount: () => Math.max(1, this.channelStates.length || (this.descriptor?.channels ?? 1)),\n channelVisible: (c: number) => this.channelStates[c]?.visible !== false,\n buildTileSource: (z: number, channel?: number) =>\n this.buildTileSource(this.descriptor!, this.infoB64, z, channel),\n onCompositeSliceAdded: (z: number) => this.sampler.computeImageWindow(this.descriptor!, this.infoB64, z),\n });\n\n constructor(\n private http: HttpClient,\n @Inject(TILE_ACCESS_PORT) private tiles: TileAccessPort,\n private wandTool: WandToolService,\n private brushTool: BrushToolService,\n private samTool: SamToolService,\n private samPointTool: SamPointToolService,\n private cellSegmentTool: CellSegmentToolService,\n @Optional() @Inject(CELL_SEGMENTER) private cellSegmenter: ICellSegmenter | null,\n private eraserTool: VertexEraserToolService,\n private zoomToBoxTool: ZoomToBoxToolService,\n store: VisualizerStore,\n regionStore: RegionStore,\n private simpleStack: SimpleSliceAccessService,\n @Inject(VIZ_CONFIG) config: VizConfig,\n ) {\n super(regionStore, store);\n this.api = config.slideCropServer;\n this.sampler = new HistogramSampler(this.http, this.api, {\n realLevels: () => this.realLevels,\n channelCount: (d) => this.channelStates.length || (d.channels ?? 1),\n isGrayscale: () => this.isGrayscaleImage,\n // Nudge the channel-states stream so the pane re-reads getHistogram now,\n // in case its bounded retry window already lapsed.\n onChannelHistogramsSampled: () => this.store.setChannelStates(this.store.currentChannelStates()),\n onGrayWindowSampled: (min, max) => this.seedGrayWindow(min, max),\n });\n this.ensureColormapSubscription();\n }\n\n private readonly stackLoading$ = new BehaviorSubject<boolean>(false);\n private readonly stackLoadingProgress$ = new BehaviorSubject<number>(0);\n private readonly autoscaleEvent$ = new Subject<any>();\n /** Visible image region (full-image pixel coords) emitted when the view\n * settles, so the intensity inset can re-sample at the current zoom level. */\n private readonly viewportChange$ = new Subject<{ x: number; y: number; width: number; height: number }>();\n // Region state (regions, selection, the update event) lives in the shared\n // RegionStore; the IRegionStore methods below delegate to it.\n private readonly intensityProfile$ = new Subject<IntensityProfile[]>();\n // Image metadata and classification colours live in the shared VisualizerStore.\n\n /**\n * Subscribe to the shared VisualizerStore colormap/reverse so OSD recolors in\n * lock-step with Plotly. Idempotent and self-healing: this service is a root\n * singleton, but `unsubscribe()` (called on VisualizerComponent destroy)\n * tears the subscription down — and the constructor never runs again. So\n * `plot()` calls this to re-establish it after a component teardown/recreate\n * (e.g. switching images), otherwise colormap changes would be silently\n * dropped on every image after the first switch.\n */\n private ensureColormapSubscription(): void {\n if (this.colormapSub) return;\n // Colormap/reverse live in the shared VisualizerStore — the single source\n // of truth for both backends. Rebuild the LUT and re-run the pixel pipeline\n // whenever either changes, so OSD recolors in lock-step with Plotly.\n // Colormap/reverse + per-channel window/gamma/visibility + invert all live in\n // the shared VisualizerStore. Rebuild the LUT and re-run the pixel pipeline\n // whenever any of them changes, so the Channels & Histogram pane updates the\n // image live and OSD stays in lock-step with Plotly.\n this.colormapSub = combineLatest([\n this.store.getColormap(),\n this.store.getReverseScale(),\n this.store.getChannelStates(),\n this.store.getInvert(),\n ]).subscribe(([cm, rev, channels, invert]) => {\n this.colorLut = buildColormapLut(cm?.data?.value, !!rev);\n this.channelStates = channels;\n this.invertBg = !!invert;\n // Multichannel: each channel is its own TiledImage — visibility is the\n // image's opacity (window/gamma/colour are applied by recolorChannelTile\n // on the invalidate below). Re-applying the current slice's reveal picks up\n // the new per-channel visibility (cached slices stay hidden).\n if (this.isMultiChannel) {\n this.cache.revealChannelSlice(this.currentZ);\n }\n // requestInvalidate(true) restores each tile to its original data before\n // re-running recolorTile, so a change always maps afresh (no compounding).\n // RGB now recolors too (per-channel window/visibility), so don't gate on\n // grayscale.\n this.invalidateDisplay();\n });\n }\n\n /** Seed the Intensity channel with a measured auto-window while it's still\n * at full range (never clobber the user's manual window); if the user\n * already windowed, just re-invalidate so painted tiles pick the LUT up. */\n private seedGrayWindow(min: number, max: number): void {\n const ch0 = this.store.currentChannelStates()[0];\n if (ch0 && ch0.min === 0 && ch0.max === 255) {\n this.store.setChannelState(0, { min, max });\n } else if (this.viewer && this.colorLut) {\n try {\n (this.viewer as any).world.requestInvalidate(true);\n } catch {\n /* no-op */\n }\n try {\n (this.viewer as any).navigator?.world?.requestInvalidate(true);\n } catch {\n /* no-op */\n }\n }\n }\n\n // ── IDataRenderer ────────────────────────────────────────────────────\n\n /**\n * Fetch the tile-source descriptor for the selected file. The `info` param is\n * the base64 RawFileInfo the rest of the API uses; the GET goes through the\n * auth interceptor (Bearer). We also grab a token here for OSD's own tile\n * fetches (its loader bypasses HttpClient).\n */\n async load(imageInfo: IImageInfo, zIndex: number): Promise<OsdLoaded> {\n const filename = imageInfo?.fileName;\n // A different image was selected — stop the previous stack's background\n // loading immediately rather than letting it finish behind the new image.\n if (filename && this.currentFileName && filename !== this.currentFileName) {\n this.cache.cancelBackgroundLoad();\n this.revokeSimpleFullResUrls();\n }\n this.simpleStack.noteActiveFile(filename);\n // Simple (in-memory / non-tiled) image: skip the tile server entirely — no\n // getSelectedInfoB64, no /tiles/info poll. `urls[zIndex]` is a complete image\n // OSD opens via its single-image source (see plot()).\n if (this.simpleStack.isSimple(imageInfo)) {\n return this.loadSimple(imageInfo, zIndex);\n }\n const infoB64 = this.tiles.getSelectedInfoB64();\n if (!infoB64) return { descriptor: null, infoB64: '', z: zIndex || 0, filename };\n\n try {\n this.authHeaders = await this.tiles.getAuthHeaders();\n } catch {\n this.authHeaders = {}; // fall back to cookie auth (ajaxWithCredentials)\n }\n // Poll /tiles/info: the backend returns 202 while the source file is still\n // being cached (GCS->PVC) — it kicks the download off in the background, so\n // each request is short (no long-held connection to trip ingress/proxy or\n // client timeouts), and 200 with the descriptor once it's ready. The\n // cache-progress overlay shows progress during the wait. We give up after\n // tilesInfoTimeoutMs so the render pipeline never hangs (the router then\n // falls back to Plotly for this image).\n const url = `${this.api}tiles/info?info=${infoB64}`;\n const deadline = Date.now() + this.tilesInfoTimeoutMs;\n for (;;) {\n if (Date.now() > deadline) {\n throw new Error('tiles/info not ready before deadline — file still caching');\n }\n try {\n const resp = await firstValueFrom(\n this.http.get<TileDescriptor>(url, { observe: 'response' }).pipe(timeout(45000)),\n );\n if (resp.status === 200 && resp.body) {\n this.descriptor = resp.body;\n return { descriptor: resp.body, infoB64, z: zIndex || 0, filename };\n }\n // 202 Accepted (or empty body) → still caching; fall through and re-poll.\n } catch (err) {\n // Tolerate transient failures WHILE the file is being prepared: a slow\n // metadata read on a multi-GB file (IFD walk), a 5xx mid-pipeline, a\n // proxy hiccup. A single bad poll must NOT drop us to Plotly — a large\n // image always passes through this busy window, so bailing here is why\n // it \"always ends up on Plotly\". Keep polling until ready or deadline.\n console.warn('[OSD] tiles/info poll retry', err);\n }\n await new Promise((r) => setTimeout(r, 1500));\n }\n }\n\n /** Build the `plot()` payload for a simple (tiled:false) image: a single-level\n * descriptor sized from `trueImageSize`, plus the directly-loadable URL —\n * resolved and fetched via {@link SimpleSliceAccessService} (shared with\n * napari-js; see its docs for why this can't be a raw `fetch()`/`<img>`). */\n private async loadSimple(imageInfo: IImageInfo, zIndex: number): Promise<OsdLoaded> {\n const z = zIndex || 0;\n const filename = imageInfo?.fileName;\n this.authHeaders = {};\n const [width, height] = imageInfo.trueImageSize ?? [0, 0];\n const rawUrl = this.simpleStack.urlFor(imageInfo, z);\n let url: string | undefined;\n if (rawUrl) {\n try {\n const previewUrl = await this.simpleStack.fetchAsBlobUrl(rawUrl);\n // Upscale the (downscaled) preview to full resolution so OSD's world\n // matches the full-res ROI coordinate space — see toFullResUrl.\n url = await this.toFullResUrl(previewUrl, width, height);\n } catch (err) {\n console.warn('[OSD] simple-mode slice fetch failed', err);\n }\n }\n // No loadable URL (empty urls[] or the fetch failed): signal \"couldn't\n // load\" with a null descriptor — same as the tiled path when there's no\n // selected-file info — so plot() returns false (its `if (!d)` guard) and\n // the router can fall back, instead of mounting an <img> with an undefined\n // src that throws at runtime.\n if (!url) {\n console.warn('[OSD] simple-mode slice has no loadable URL; skipping OSD render', rawUrl);\n return { descriptor: null, infoB64: '', z, filename };\n }\n const meta = imageInfo.imageMeta?.[0];\n const descriptor: TileDescriptor = {\n width,\n height,\n tileSize: 0, // unused: simple mode never calls buildTileSource\n z: 1, // single frame\n channels: meta?.rgbChannels ?? (imageInfo.isGrayscale ? 1 : 3),\n multichannel: false,\n realLevels: 1,\n levels: [{ res: 0, width, height }],\n mppX: meta?.mppX ?? 0,\n mppY: meta?.mppY ?? 0,\n };\n return {\n descriptor,\n infoB64: '',\n z,\n filename,\n simple: true,\n url,\n };\n }\n\n /**\n * OSD's `{type:'image'}` source sizes its coordinate world to the image's\n * NATURAL pixels. A folder-stack slice is a server `/preview` whose pixel size\n * needn't match the full-resolution image — it may be downscaled (large\n * images) OR larger than the dimensions `/metadata` reports. Either way OSD's\n * world would differ from the full-res ROI coordinate space (QuPath geojson,\n * in level-0 pixels): a smaller preview renders ROIs oversized, a larger one\n * renders them undersized/offset. Resample the preview to EXACTLY the\n * full-resolution dimensions (blurry but positionally exact — scaling up or\n * down as needed) so OSD's world matches the ROI coordinate space, while still\n * using OSD's reliable single-image renderer. Cached per preview URL (revoked\n * on file change); a no-op when the preview is already exactly full-res (small\n * images, in-memory pipeline blobs), when the dims are unknown, or when\n * they're implausibly large (guards against an enormous canvas). (jit-ui#93)\n */\n private async toFullResUrl(previewUrl: string, width: number, height: number): Promise<string> {\n if (!width || !height || Math.max(width, height) > this.SIMPLE_UPSCALE_MAX_DIM) return previewUrl;\n const cached = this.simpleFullResUrls.get(previewUrl);\n if (cached) return cached;\n let img: HTMLImageElement;\n try {\n img = await this.loadImageEl(previewUrl);\n } catch {\n return previewUrl; // couldn't decode — let OSD try the URL as-is\n }\n // Already the exact full-res world — no resample needed. (A preview that is\n // larger OR smaller than full-res must still be resized so OSD's world ==\n // the ROI coordinate space; only an exact match is skippable.)\n if (img.naturalWidth === width && img.naturalHeight === height) return previewUrl;\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext('2d');\n if (!ctx) return previewUrl;\n ctx.drawImage(img, 0, 0, width, height); // scale preview (up or down) to full-res\n const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve));\n if (!blob) return previewUrl;\n const fullResUrl = URL.createObjectURL(blob);\n this.simpleFullResUrls.set(previewUrl, fullResUrl);\n return fullResUrl;\n }\n\n /** Load a URL into an HTMLImageElement (resolves once decoded). Uses\n * document.createElement rather than `new Image()` because this file's\n * `Image` import is image-js's decoder, not the DOM element. */\n private loadImageEl(url: string): Promise<HTMLImageElement> {\n return new Promise((resolve, reject) => {\n const img = document.createElement('img');\n img.onload = () => resolve(img);\n img.onerror = (e) => reject(e);\n img.src = url;\n });\n }\n\n private revokeSimpleFullResUrls(): void {\n for (const u of this.simpleFullResUrls.values()) URL.revokeObjectURL(u);\n this.simpleFullResUrls.clear();\n }\n\n /** Mount the viewer with a custom tile source pointing at `GET /tile`. */\n plot(\n plotDiv: string,\n imageLoaded: any,\n imageInfo: IImageInfo,\n _screenHeight: number,\n _plotType: PlotType,\n inPlace?: boolean,\n ): Promise<boolean> {\n const loaded = imageLoaded as OsdLoaded;\n const d = loaded?.descriptor;\n if (!d) return Promise.resolve(false);\n // Re-establish the colormap subscription if a prior component teardown\n // (unsubscribe()) tore it down — this service is a root singleton, so the\n // constructor won't run again to recreate it.\n this.ensureColormapSubscription();\n // OSD tiles natively, so the in-place (large) pass is normally a no-op\n // once mounted — the tile pyramid IS the full resolution regardless of\n // which ImageInfo tier requested it. Simple mode has no pyramid to fall\n // back on: it displays literally whatever URL was last opened, so\n // without this swap the small tier's 128px placeholder would stay on\n // screen forever (pixelated, never \"sharpening\" like the tiled path).\n if (inPlace && this.viewer) {\n if (loaded.simple && loaded.url) {\n // Also refresh simpleUrls to THIS phase's (large-tier) urls[] — it was\n // set from the small tier's 128px urls on the initial mount below,\n // which never runs again for the in-place pass. Without this,\n // setZIndex's later slider scrubs would keep reading the small\n // tier's low-res URLs forever, even though the initial slice was\n // correctly swapped to full resolution here.\n this.simpleUrls = imageInfo?.urls ?? this.simpleUrls;\n this.viewer.open({ type: 'image', url: loaded.url } as any);\n }\n return Promise.resolve(true);\n }\n this.plotDiv = plotDiv;\n this.currentFileName = imageInfo?.fileName;\n this.descriptor = d;\n this.infoB64 = loaded.infoB64;\n this.currentZ = loaded.z;\n this.simpleMode = !!loaded.simple;\n this.simpleUrls = loaded.simple ? (imageInfo?.urls ?? []) : [];\n // The descriptor's physical pixel size (server Bio-Formats `/tiles/info`) is\n // authoritative — push it into the shared meta so the Region Editor reports\n // areas in µm²/mm², matching the scale bar built from `d.mppX` below.\n this.store.setPhysicalPixelSize(d.mppX, d.mppY);\n // Use the SAME grayscale flag the colormap dropdown / Plotly use\n // (imageInfo.isGrayscale ← rgbChannels === 1). The descriptor's `channels`\n // (channelCount) diverges from rgbChannels for stacks, which left grayscale\n // stacks un-recolored even though the colormap selector was shown.\n this.isGrayscaleImage = !!imageInfo?.isGrayscale;\n // Simple (non-tiled, in-memory) image: no pyramid, no per-channel tiles, and\n // no server-side intensity sampling — OSD's single-image source decodes\n // urls[z] directly. Skip the whole tiled-setup path below.\n const simple = !!loaded.simple;\n if (simple) {\n this.realLevels = 1;\n this.isMultiChannel = false;\n this.cache.clearChannelGroups();\n this.destroyViewer();\n } else {\n // Multichannel fluorescence (indexed/LUT-bearing stacks) composite client-side\n // from per-channel tiles. Trust the server's explicit `multichannel` flag — the\n // old `channels>1 && grayscale` heuristic also matched RGB photos Bio-Formats\n // reads as separated planes (channels>1, rgbChannels==1), splitting them into N\n // per-channel TiledImages that flooded the tile endpoint and hung on load.\n this.realLevels = d.realLevels ?? d.levels.length;\n // Tiles to cover the whole image at the coarsest REAL Bio-Formats level (the\n // smallest level that has real, per-channel-fetchable tiles — synthetic overview\n // levels are server-composited only). A pyramidal image's coarsest real level is\n // tiny (few tiles); a flat/no-pyramid image's is the full-res grid (many tiles).\n const coarse = d.levels[this.realLevels - 1] ?? d.levels[d.levels.length - 1];\n const coarseW = coarse ? Math.ceil(coarse.width / d.tileSize) : 1;\n const coarseH = coarse ? Math.ceil(coarse.height / d.tileSize) : 1;\n const coarseTiles = coarseW * coarseH;\n this.isMultiChannel = !!d.multichannel;\n if (this.isMultiChannel) {\n // Per-channel rendering can only use the REAL levels, so OSD requests the\n // coarsest real level's whole tile grid × N channels at fit. When that's large\n // (a whole-slide), it's too many (often slow, pyramid-less) full-res reads —\n // fall back to the single server-composited source (which keeps the fast\n // synthetic overviews). A small single-FOV z-stack stays per-channel. Size in\n // BYTES isn't the signal — tile count is.\n const fitTiles = coarseTiles * Math.max(1, d.channels ?? 1);\n if (fitTiles > this.MAX_MULTICHANNEL_FIT_TILES) {\n this.isMultiChannel = false;\n console.warn(\n '[OSD] multichannel composite too large for per-channel rendering: ' +\n `${coarseW}x${coarseH} tiles x ${d.channels} channels = ${fitTiles} at the coarsest ` +\n `real level (> ${this.MAX_MULTICHANNEL_FIT_TILES}); rendering server-composited for speed.`,\n );\n }\n }\n this.cache.clearChannelGroups();\n // Auto-range grayscale tiles to the image's actual intensity span (like the\n // heatmap), sampling the coarsest tile level so the window matches the raw\n // tile values. Fire-and-forget: it re-invalidates once the window is known;\n // tiles paint unwindowed until then. (Multichannel windows are per-channel,\n // defaulting to full range; the user auto/edits each channel.)\n if (this.isMultiChannel) {\n this.sampler.computeMultiChannelHistograms(d, loaded.infoB64, loaded.z);\n } else {\n this.sampler.computeImageWindow(d, loaded.infoB64, loaded.z);\n }\n this.destroyViewer();\n // Size the slice cache for this image: LRU cap to hold the whole stack\n // (capped) and skip background preloading for stacks too large to preload\n // (would flood full-res reads). Normal stacks keep the flicker-free pre-cache.\n this.cache.configure(d.z ?? 1, coarseTiles);\n }\n\n // Simple mode: OSD's single-image source decodes the URL (blob:/data:/http)\n // directly — no pyramid, no server. Tiled mode: the custom server-backed tile\n // source (multichannel opens on channel 0; the open handler then swaps in this\n // slice's per-channel group and the background loader pre-fills the rest).\n const tileSource = simple\n ? { type: 'image', url: loaded.url }\n : this.buildTileSource(d, loaded.infoB64, loaded.z, this.isMultiChannel ? 0 : undefined);\n silenceOsdMultiImageAdvisory();\n this.viewer = (OSD as any)({\n id: plotDiv,\n // Simple-mode z-scrub calls viewer.open() again per slice (see\n // setZIndex) — without this it resets to the home zoom/pan on every\n // slice change. Tiled mode never re-opens (it toggles pre-added\n // TiledImages' opacity instead), so this is a no-op there.\n preserveViewport: true,\n // Use the 2D canvas drawer, not WebGL: creating/destroying a viewer on\n // each engine toggle / image load churns WebGL contexts (browsers cap\n // how many exist at once), which surfaces as \"WebGL context was lost\"\n // and blank tiles. The canvas drawer has no such limit.\n drawer: 'canvas',\n showNavigationControl: false, // avoids needing the icon-image assets\n // Overview thumbnail with the current-viewport rectangle, bottom-right.\n showNavigator: this.navigatorVisible,\n // Nearest-neighbour when off → crisp pixels on zoom-in (pixel inspection).\n imageSmoothingEnabled: this.smoothingEnabled,\n navigatorPosition: 'BOTTOM_RIGHT',\n navigatorSizeRatio: 0.16,\n navigatorAutoFade: false,\n navigatorBackground: 'rgba(0,0,0,0.5)',\n loadTilesWithAjax: true,\n ajaxWithCredentials: true, // cookie auth (oauth2-proxy)\n ajaxHeaders: this.authHeaders, // bearer auth (Auth0), when available\n crossOriginPolicy: 'Anonymous',\n // Gentler zoom: the default (1.2) feels fast and big jumps cross several\n // pyramid levels at once, firing a burst of tile requests.\n zoomPerScroll: 1.1,\n // Click-to-zoom toward the clicked point (OpenSeadragon's default demo\n // behaviour). Only applies when no region tool is active — an active tool\n // disables OSD mouse-nav so clicks draw/select instead of zooming.\n gestureSettingsMouse: { clickToZoom: true, scrollToZoom: true },\n // Zoom limits (jit-ui#94). Default minZoomImageRatio (0.9) stops you from\n // zooming the image smaller than ~home; drop it so the image can be shrunk\n // freely (effectively no minimum). Default maxZoomPixelRatio (1.1) caps\n // zoom-in at ~1 screen px per image px; raise it so you can zoom in to\n // inspect individual pixels (paired with imageSmoothingEnabled=false for\n // crisp nearest-neighbour blocks).\n minZoomImageRatio: 0.01,\n maxZoomPixelRatio: 20,\n // Wait for the view to settle before pulling new tiles (less churn).\n immediateRender: false,\n animationTime: 0.4,\n // Release memory aggressively: cap the tile cache so tiles outside the\n // current view (e.g. the coarser levels left behind after zooming in) are\n // evicted instead of accumulating. Large whole-slide tiles — doubled when\n // the colormap pipeline keeps a recolored copy — make an unbounded cache\n // costly. Tunable; lower = less memory, more re-fetch on pan-back.\n // Stacks keep many slices resident (the whole stack is background-loaded),\n // so they get a much larger tile budget — otherwise switching slices evicts\n // each other's tiles and scrubbing back re-fetches. Scaled to the resident\n // slice count; single images keep the lean default.\n maxImageCacheCount: (d.z ?? 1) > 1 ? Math.min(2400, Math.max(600, this.cache.maxSlices() * 40)) : 150,\n });\n\n return new Promise<boolean>((resolve) => {\n // Always settle: if OSD never emits open/open-failed (a bad tile source,\n // a viewer torn down mid-open), the render pipeline must not hang — a hang\n // leaves imageLoading=true, sticking the spinner and the 500ms\n // cache-progress poll forever (NS_BINDING_ABORTED storm).\n let settled = false;\n const done = (ok: boolean) => {\n if (!settled) {\n settled = true;\n resolve(ok);\n }\n };\n this.viewer!.addOnceHandler('open', () => {\n // Region overlay reads/writes the shared RegionStore, so regions stay\n // in sync with Plotly and the Region Editor. Recreate it per open() so\n // it binds to the freshly-opened viewer's canvas/MouseTracker.\n this.overlay?.destroy();\n this.overlay = new OsdRegionOverlay(this.viewer as any, this.regionStore);\n this.coordTransform = new OsdCoordinateTransform(this.viewer as any);\n this.scaleBar = new OsdScaleBar(this.viewer as any, d.mppX ?? 0);\n this.buildToolHosts();\n // Simple mode is a single, self-contained image — no slice cache to seed.\n if (simple) {\n /* nothing to cache: one frame, no pyramid */\n } else if (this.isMultiChannel) {\n // Drop the single opened (channel-0) image and add this slice's channel\n // group to the per-slice cache. The shared background loader / LRU then\n // pre-fills the other slices' channel groups so z-scrub is flicker-free.\n try {\n const it0 = (this.viewer as any).world?.getItemAt?.(0);\n if (it0) (this.viewer as any).world.removeItem(it0);\n } catch { /* nothing to remove */ }\n this.cache.addChannelSlice(this.currentZ);\n } else {\n // Seed the slice cache with the just-opened slice (world item 0), so\n // scrubbing back to it later is an instant opacity toggle, not a re-open.\n const firstItem = (this.viewer as any).world?.getItemAt?.(0);\n if (firstItem) this.cache.seedComposite(this.currentZ, firstItem);\n }\n // The wand samples the *rendered viewport*, so its pixel matrix is only\n // valid for the current view — drop it whenever the viewport changes.\n this.viewer!.addHandler('viewport-change', () => {\n this.viewportPixels = null;\n });\n // Grayscale tiles get the active colormap via the pixel pipeline. The\n // handler runs per tile on load (and on requestInvalidate); recoloring\n // is a no-op for RGB images or before the LUT resolves.\n // (isGrayscaleImage is set from imageInfo.isGrayscale in plot() above.)\n this.viewer!.addHandler('tile-invalidated', (event: any) => this.recolorTile(event));\n // The overview navigator is a separate mini-viewer with its own tiles,\n // so it doesn't receive the main viewer's tile-invalidated events. Apply\n // the same recolor pipeline to it so the minimap tracks the main image's\n // colormap/LUT instead of staying grayscale.\n const nav = (this.viewer as any).navigator;\n nav?.addHandler('tile-invalidated', (event: any) => this.recolorTile(event));\n if ((this.isGrayscaleImage && this.colorLut) || this.isMultiChannel) {\n try {\n (this.viewer as any).world.requestInvalidate(true);\n } catch {\n /* no-op */\n }\n try {\n nav?.world?.requestInvalidate(true);\n } catch {\n /* no-op */\n }\n }\n // Prefetch adjacent z-slices once the view settles (and on each settle,\n // so it tracks the current viewport as the user pans/zooms). Simple mode\n // has a single frame, so there's nothing to prefetch.\n if (!simple) this.viewer!.addHandler('animation-finish', () => this.cache.schedulePrefetch());\n // Tell listeners (the intensity inset) the visible image region whenever\n // the view settles, so they can re-sample at the current zoom resolution.\n this.viewer!.addHandler('animation-finish', () => this.emitViewportChange());\n // Chrome compositor bug: after an OSD zoom the docked toolbar (a sibling of\n // #plot in the <visualizer> host) is left laid-out-but-unpainted and\n // vanishes — confirmed via DevTools (DOM intact, region simply not painted).\n // CSS (z-index / isolation / contain) and DOM-reparenting don't fix it; a\n // repaint reliably does. Nudge it each animation frame (so it never visibly\n // drops) and on settle. The synchronous display toggle re-rasters with no\n // visible gone-frame and no layout shift.\n this.viewer!.addHandler('animation', () => this.nudgeToolbarRepaint());\n this.viewer!.addHandler('animation-finish', () => this.nudgeToolbarRepaint());\n if (!simple) this.cache.schedulePrefetch();\n // Force fit-to-view as the split/flex layout settles. A tall\n // non-pyramidal image can otherwise open zoomed-in (image width filling\n // the viewer), making OSD demand slow full-res res=0 tiles for the\n // centre instead of the fast coarse overview → white canvas. goHome\n // fits the whole image so OSD selects the coarse synthetic level. Retry\n // across a few frames because the container may not have its final size\n // on the first frame after 'open'.\n const refit = () => {\n try {\n this.viewer?.viewport.goHome(true);\n // The navigator was sized in the Viewer constructor — BEFORE the\n // layout settled — so its element can carry a stale (even\n // wrong-aspect) size that floats the visible minimap above the\n // corner. Re-size it from the settled container.\n this.resizeNavigator();\n } catch {\n /* torn down */\n }\n };\n requestAnimationFrame(refit);\n setTimeout(refit, 150);\n setTimeout(refit, 400);\n // The timed retries above miss the case where the container is STILL\n // zero-size at 400ms — which happens when the render starts while the\n // file viewer is mid-switch from the folder view to the diagram (e.g.\n // \"Load as Stack\" from a folder, with no image open first). Because\n // preserveViewport suppresses OSD's own open-time fit, the image would\n // then be left un-fitted at the top-left (\"a tile\"). A one-shot\n // ResizeObserver fits the instant the container first has a real size,\n // regardless of when the render began (jit-ui#106).\n this.fitWhenContainerSized(document.getElementById(plotDiv), refit);\n // Keep the navigator sized to the container as the panel resizes.\n this.viewer!.addHandler('resize', () => this.resizeNavigator());\n done(true);\n });\n this.viewer!.addOnceHandler('open-failed', (e: any) => {\n console.warn('[OSD] open-failed', e?.message ?? e);\n done(false);\n });\n setTimeout(() => {\n if (!settled) console.warn('[OSD] viewer open timed out');\n done(false);\n }, 8000);\n this.viewer!.open(tileSource as any);\n });\n }\n\n /**\n * Fit-to-home once `el` first has a non-zero size. If it's already sized we\n * rely on the timed refits the caller scheduled; otherwise a one-shot\n * ResizeObserver runs `refit` the moment the container is laid out (then\n * disconnects), so the initial fit doesn't depend on the render's start time\n * relative to the diagram container's layout. No-op without a container or\n * ResizeObserver (the timed refits remain the fallback). One-shot + only\n * attached on a fresh mount, so slice-scrub re-opens keep the user's zoom.\n */\n private fitWhenContainerSized(el: HTMLElement | null, refit: () => void): void {\n if (!el || typeof ResizeObserver === 'undefined') return;\n if (el.clientWidth > 0 && el.clientHeight > 0) return; // already sized — timed refits suffice\n const ro = new ResizeObserver(() => {\n if (el.clientWidth > 0 && el.clientHeight > 0) {\n ro.disconnect();\n refit();\n }\n });\n ro.observe(el);\n // Safety net: stop observing even if it never gains a size.\n setTimeout(() => ro.disconnect(), 5000);\n }\n\n /**\n * Custom tile source built from the descriptor. OSD numbers levels\n * coarsest-first; the backend numbers resolutions full-res-first, so\n * `res = (levels-1) - osdLevel`. Overriding getLevelScale/getNumTiles lets us\n * honour Bio-Formats' actual per-level dimensions (not assume power-of-two).\n */\n private buildTileSource(d: TileDescriptor, infoB64: string, z: number, channel?: number): any {\n // Multichannel images composite from per-channel tiles, which only exist at\n // real Bio-Formats resolutions — so drive OSD off the real levels alone and\n // skip the synthetic (server-composited) overviews. Every displayed tile is\n // then per-channel-fetchable at any zoom.\n const levels = this.isMultiChannel ? d.levels.slice(0, this.realLevels) : d.levels;\n const n = levels.length;\n const t = d.tileSize;\n const base = this.api;\n\n // OSD level i (0 = coarsest) <-> backend resolution (n-1-i) (res 0 = full).\n // The backend pyramid is NOT necessarily power-of-two, so we drive OSD off\n // the backend's real per-level dimensions. We override ONLY getLevelScale:\n // OSD derives getNumTiles, getTileBounds AND its per-zoom level selection\n // from getLevelScale, so they all stay consistent — requesting exactly the\n // tiles each resolution actually has (no out-of-range 400s, no flood).\n const resForLevel = (level: number) => n - 1 - level;\n const ts: any = new (OSD as any).TileSource({\n width: d.width,\n height: d.height,\n tileSize: t,\n tileOverlap: 0,\n minLevel: 0,\n maxLevel: n - 1,\n });\n ts.getLevelScale = (level: number) => {\n const lvl = levels[resForLevel(level)];\n return lvl ? lvl.width / d.width : 1;\n };\n // Drive the tile COUNT off each level's own (independently-rounded) dimensions,\n // not OSD's default `ceil(scale * fullDimension / tileSize)`. Synthetic AND real\n // Bio-Formats levels aren't exact proportional scales of the full image, so\n // `scale * fullHeight` can round up to one more row (or column) than the level\n // actually has — OSD then requests an out-of-range tile that the server 400s\n // (\"Tile (col,row) out of range\"). Using the level's real w/h matches the\n // server's own bounds check exactly.\n const Point = (OSD as any).Point;\n ts.getNumTiles = (level: number) => {\n const lvl = levels[resForLevel(level)];\n if (!lvl) return new Point(0, 0);\n return new Point(Math.ceil(lvl.width / t), Math.ceil(lvl.height / t));\n };\n ts.getTileUrl = (level: number, x: number, y: number) =>\n buildTileUrl(base, infoB64, { res: resForLevel(level), col: x, row: y, z, tileSize: t, channel });\n return ts;\n }\n\n /** Re-apply the display pipeline (window/gamma/colour/invert) after a state change.\n * Multichannel invalidates ONLY the visible slice's channel images — invalidating\n * the whole world would re-process every hidden/preloaded slice's tiles (hundreds),\n * flooding OSD with \"[CacheRecord] … InvalidStateError\" and wasting work on tiles\n * that aren't on screen. The other cached slices are marked stale and re-tinted\n * lazily when revealed. Composite/grayscale invalidate the world as before. */\n private invalidateDisplay(): void {\n const v: any = this.viewer;\n if (!v) return;\n if (this.isMultiChannel) {\n this.cache.invalidateChannelDisplay(this.currentZ);\n return;\n }\n try { v.world.requestInvalidate(true); } catch { /* no-op */ }\n try { v.navigator?.world?.requestInvalidate(true); } catch { /* no-op */ }\n }\n\n private destroyViewer(): void {\n this.cache.cancelBackgroundLoad();\n // Tear down any active tool overlays (shared singletons).\n this.wandTool.setMode(false);\n this.brushTool.setMode(false);\n this.samPointTool.setMode(false);\n this.eraserTool.setMode(false);\n if (this.overlay) {\n this.overlay.destroy();\n this.overlay = null;\n }\n if (this.scaleBar) {\n this.scaleBar.destroy();\n this.scaleBar = null;\n }\n if (this.viewer) {\n this.viewer.destroy();\n this.viewer = null;\n }\n this.coordTransform = null;\n this.cache.reset();\n this.sampler.clear();\n }\n\n /** This backend's region renderer (the SVG overlay), once a plot is mounted. */\n getRegionOverlay(): IRegionOverlay | null {\n return this.overlay;\n }\n\n /** OSD renders only the image type — no isosurface, so no controls. */\n getIsosurfaceControls(): IIsosurfaceControls | null {\n return null;\n }\n\n /** OSD renders only the image type — no 3D scenes, so no controls. */\n getSurface3dControls(): ISurface3dControls | null {\n return null;\n }\n\n /** OSD renders only the image type — no LINE intensity ROIs, so no controls. */\n getIntensityControls(): IIntensityControls | null {\n return null;\n }\n\n private toOverlayMode(mode: string | false): RegionToolMode {\n switch (mode) {\n case 'drawrect':\n return 'drawrect';\n case 'drawclosedpath':\n return 'drawclosedpath';\n case 'drawopenpath':\n return 'drawopenpath';\n case 'drawpolygon':\n return 'drawpolygon';\n case 'addpoint':\n return 'addpoint';\n case 'deletepoint':\n return 'deletepoint';\n case 'move':\n return 'move';\n case 'select':\n return 'select';\n default:\n return 'none';\n }\n }\n\n reloadAndPlot(): void {\n /* host re-drives plot() via the image-info stream */\n }\n reset(): void {\n this.destroyViewer();\n }\n relayout(_trueImageSize?: number[]): void {\n const vp = this.viewer?.viewport;\n if (!vp) return;\n // Keep the user's current view across a container/split resize instead of\n // snapping home. Viewport bounds are image-relative (image width = 1), so\n // they're independent of the container's pixel size — capture the visible\n // region now and re-fit it once the new size has settled. OSD's autoResize\n // fires asynchronously and the angular-split transition animates the width\n // over a few hundred ms, so restore on the next frame and again after the\n // transition completes.\n const bounds = vp.getBounds(true);\n const restore = () => {\n try {\n this.viewer?.viewport.fitBounds(bounds, true);\n this.viewer?.viewport.applyConstraints(true);\n } catch {\n /* viewer torn down */\n }\n };\n requestAnimationFrame(restore);\n setTimeout(restore, 350);\n }\n resetAxes(): void {\n this.viewer?.viewport.goHome();\n }\n autoscale(): void {\n this.viewer?.viewport.goHome();\n this.autoscaleEvent$.next('autoscale');\n }\n zoomIn(): void {\n this.viewer?.viewport.zoomBy(1.3);\n this.viewer?.viewport.applyConstraints();\n }\n zoomOut(): void {\n this.viewer?.viewport.zoomBy(1 / 1.3);\n this.viewer?.viewport.applyConstraints();\n }\n setDragMode(mode: string | false): void {\n // Rectangle/polygon drawing run on the SVG overlay; wand/eraser/zoom-box\n // (custom Plotly overlays) are routed to Plotly by the router and aren't\n // handled here yet.\n this.overlay?.setMode(this.toOverlayMode(mode));\n }\n\n setShowStack(_showstack: boolean): void {\n /* OSD navigates the stack via the z-slider -> setZIndex */\n }\n\n /** Show/hide the overview navigator. Stored for the next viewer creation, and\n * applied live when a viewer is already mounted (hides/reveals its element —\n * the navigator instance itself only exists when created with showNavigator). */\n setNavigatorVisible(visible: boolean): void {\n this.navigatorVisible = visible;\n const navEl: HTMLElement | undefined = (this.viewer as any)?.navigator?.element;\n if (navEl) navEl.style.display = visible ? '' : 'none';\n }\n\n /** Toggle bilinear smoothing vs nearest-neighbour (crisp pixels). Stored for the\n * next viewer creation, and applied live (with a redraw) to a mounted viewer. */\n setImageSmoothingEnabled(enabled: boolean): void {\n this.smoothingEnabled = enabled;\n const drawer: any = (this.viewer as any)?.drawer;\n if (drawer?.setImageSmoothingEnabled) {\n drawer.setImageSmoothingEnabled(enabled);\n this.viewer?.forceRedraw();\n }\n }\n\n /**\n * Swap the displayed z-slice live. Slices are kept as separate tiled images in\n * the world, so switching is just an opacity toggle: a previously-visited slice\n * shows instantly (its decoded + recolored tiles are still resident), and a\n * never-seen slice is added once. The region overlay, coordinate transform,\n * scale bar, colormap pipeline and current zoom/pan all persist — the x/y\n * geometry is identical across slices.\n *\n * Simple mode (tiled:false — a numbered image series assembled client-side,\n * each slice its own complete image with no shared tile server) has no\n * pyramid to toggle opacity on, so it re-opens the viewer on the new\n * slice's URL instead. preserveViewport (viewer option, see plot()) keeps\n * the current zoom/pan across that reopen.\n */\n setZIndex(zIndex: number): void {\n const z = zIndex || 0;\n if (z === this.currentZ) return;\n if (!this.viewer) return;\n if (this.simpleMode) {\n const rawUrl = this.simpleUrls[z] ?? this.simpleUrls[0];\n if (!rawUrl) return;\n this.currentZ = z;\n this.viewportPixels = null;\n // Fetched via SimpleSliceAccessService (auth interceptor applies) then\n // upscaled to full-res (same as the initial load — see toFullResUrl) so\n // the world stays full-res across slices and ROIs keep aligning. Guard\n // against a newer scrub landing first.\n this.simpleStack.fetchAsBlobUrl(rawUrl)\n .then((previewUrl) =>\n this.toFullResUrl(previewUrl, this.descriptor?.width ?? 0, this.descriptor?.height ?? 0),\n )\n .then((url) => {\n if (this.currentZ !== z || !this.viewer) return;\n this.viewer.addOnceHandler('open-failed', (e: any) => {\n console.warn('[OSD] slice re-open failed', e?.message ?? e);\n });\n this.viewer.open({ type: 'image', url } as any);\n })\n .catch((err) => console.warn('[OSD] slice fetch failed', err));\n return;\n }\n if (!this.descriptor || !this.infoB64) return;\n this.currentZ = z;\n this.viewportPixels = null; // wand readback is slice-specific\n this.cache.showSlice(z);\n if (this.isMultiChannel) {\n this.sampler.computeMultiChannelHistograms(this.descriptor, this.infoB64, z);\n }\n }\n\n setStackLoading(stackLoading: boolean): void {\n this.stackLoading$.next(stackLoading);\n }\n isStackLoading(): Observable<boolean> {\n return this.stackLoading$.asObservable();\n }\n getStackLoadingProgress(): Observable<number> {\n return this.stackLoadingProgress$.asObservable();\n }\n\n getTrueImageSize(): { width: number; height: number } | null {\n return this.descriptor ? { width: this.descriptor.width, height: this.descriptor.height } : null;\n }\n getCurrentImage(): Promise<Image | null> {\n return Promise.resolve(null);\n }\n\n /**\n * The currently displayed pixels — the rendered viewport (what the user sees,\n * including the current zoom and any colormap recolor), as RGBA. Feeds the\n * processing-pipeline dialog's \"use current view\". Returns null until tiles\n * are drawn.\n */\n getDisplayedPixelData(): PixelData | null {\n const canvas: HTMLCanvasElement | undefined = (this.viewer as any)?.drawer?.canvas;\n if (!canvas || !canvas.width || !canvas.height) return null;\n const ctx = canvas.getContext('2d', { willReadFrequently: true });\n if (!ctx) return null;\n const { width, height } = canvas;\n const img = ctx.getImageData(0, 0, width, height);\n return { width, height, channels: 4, data: img.data };\n }\n\n /**\n * Image-pixel rectangle the drawer canvas (what {@link getDisplayedPixelData}\n * reads) currently covers. Unlike {@link emitViewportChange}, this is NOT\n * clamped to the image bounds: the canvas maps 1:1 to the viewport rectangle,\n * so leaving it unclamped keeps `canvasPx -> imagePx` an exact affine map\n * (clamping would skew coordinates near the image edges). Routed through world\n * item 0 (see {@link viewportRectToImage}) for multi-layer accuracy.\n */\n getDisplayedSourceRect(): { x: number; y: number; width: number; height: number } | null {\n const vp: any = this.viewer?.viewport;\n if (!vp || !this.descriptor) return null;\n try {\n const r = viewportRectToImage(this.viewer, vp.getBounds(true));\n return { x: r.x, y: r.y, width: r.width, height: r.height };\n } catch {\n return null;\n }\n }\n\n downloadImage(): void {\n // Snapshot the currently rendered OSD view as a PNG (WYSIWYG) — the parallel\n // to Plotly's downloadImage. OSD uses the 2D canvas drawer and bakes the\n // active display settings (window / gamma / colormap / per-channel colours /\n // invert) into the tiles via the recolor pipeline, so the drawer canvas\n // already reflects exactly what's on screen at the current zoom/pan. The\n // full-resolution stitched export lives in exportComposite() (Channels &\n // Histogram dialog).\n const canvas: HTMLCanvasElement | undefined = (this.viewer as any)?.drawer?.canvas;\n if (!canvas || !canvas.width || !canvas.height) return;\n const stem = (this.currentFileName || 'image').replace(/\\.[^.]+$/, '');\n canvas.toBlob((blob) => {\n if (blob) saveAs(blob, `${stem}.png`);\n }, 'image/png');\n }\n\n setPlotType(_plotType: PlotType): void {\n /* OSD only renders the image type */\n }\n setSurfaceDragMode(_mode: string): void {\n /* 3D not supported by OSD */\n }\n resetSurfaceCamera(): void {\n /* 3D not supported by OSD */\n }\n\n getAutoscaleEvent(): Observable<any> {\n return this.autoscaleEvent$.asObservable();\n }\n\n /** Visible image region (full-image pixel coords), emitted when the view\n * settles. The intensity inset re-samples this region at the zoom resolution. */\n getViewportChange$(): Observable<{ x: number; y: number; width: number; height: number }> {\n return this.viewportChange$.asObservable();\n }\n\n /** {@link IIntensitySampling} stub — intensity sampling lives in the Plotly\n * backend (it owns pixel readback). OSD feeds it only via getViewportChange$;\n * the sampling-cache priming itself is a no-op here. */\n async ensureIntensitySampling(_imageInfo: IImageInfo, _zIndex: number): Promise<void> {\n /* no-op: Plotly owns intensity sampling (see IIntensitySampling) */\n }\n\n /** {@link IIntensitySampling} stub — see {@link ensureIntensitySampling}. */\n refreshIntensitySamplingForRoi(_x: number, _y: number, _width: number, _height: number,\n _zIndex: number): void {\n /* no-op: Plotly owns intensity sampling (see IIntensitySampling) */\n }\n\n /** Compute the current viewport's image-pixel rectangle (clamped to the image)\n * and broadcast it. */\n private emitViewportChange(): void {\n const vp: any = this.viewer?.viewport;\n if (!vp || !this.descriptor) return;\n try {\n // Route through world item 0 (osd-coords): vp.viewportToImageRectangle is\n // inaccurate and warns when the world holds multiple images (per-channel\n // multichannel layers), which fed the intensity inset a wrong ROI.\n const r = viewportRectToImage(this.viewer, vp.getBounds(true));\n const iw = this.descriptor.width, ih = this.descriptor.height;\n const x = Math.max(0, Math.min(iw, r.x));\n const y = Math.max(0, Math.min(ih, r.y));\n const width = Math.max(1, Math.min(iw - x, r.width));\n const height = Math.max(1, Math.min(ih - y, r.height));\n this.viewportChange$.next({ x, y, width, height });\n } catch {\n /* viewport not ready */\n }\n }\n\n /** OSD targets the image display; the scalar/3D plot types belong to Plotly. */\n getPlotTypeDescriptors(): PlotTypeDescriptor[] {\n return [PLOT_TYPE_DESCRIPTORS[PlotType.HEATMAP]!];\n }\n\n getIntensityProfile$(): Observable<IntensityProfile[]> {\n return this.intensityProfile$.asObservable();\n }\n /** OSD only renders the image type; the LINE intensity inset is Plotly-only. */\n renderIntensityInset(_divId: string, _profiles: IntensityProfile[]): void {\n /* no LINE mode on OSD */\n }\n\n // ── IRegionStore + classification colours ────────────────────────────\n // Inherited from BaseStoreVisualizer — pure delegations to the shared\n // RegionStore / VisualizerStore (identical to napari-js). The OSD region\n // overlay (constructed in plot()) reads/writes that same store, so regions\n // stay in sync with Plotly and the Region Editor; OSD renders them as an SVG\n // overlay rather than carrying Plotly shape dicts.\n\n // ── IToolController ──────────────────────────────────────────────────\n // Wand + vertex eraser run over OSD via ICoordinateTransform. They share the\n // singleton tool services with Plotly, so we re-bind to our hosts on activate.\n setWandMode(active: boolean, options?: any): void {\n if (!active) {\n this.wandTool.setMode(false);\n return;\n }\n // Take the pointer from OSD so the drag draws instead of panning. (Nav is\n // re-enabled when the region overlay returns to 'none' on tool switch.)\n this.viewer?.setMouseNavEnabled(false);\n // The wand samples the rendered viewport — read back lazily on first use.\n this.viewportPixels = null;\n this.wandTool.bindHost(this.wandHost);\n this.wandTool.setMode(true, (options ?? {}) as WandOptions);\n }\n setWandOptions(options: any): void {\n this.wandTool.setOptions(options as WandOptions);\n }\n clearActiveWandRegion(): void {\n this.wandTool.clearActiveRegion();\n }\n setBrushMode(active: boolean, options?: any): void {\n if (!active) {\n this.brushTool.setMode(false);\n return;\n }\n // Take the pointer from OSD so the drag paints instead of panning.\n this.viewer?.setMouseNavEnabled(false);\n // The brush works in the rendered-viewport coordinate frame — read it back\n // lazily on first use, like the wand. It shares the wand's host.\n this.viewportPixels = null;\n this.brushTool.bindHost(this.wandHost);\n this.brushTool.setMode(true, (options ?? {}) as BrushOptions);\n }\n setBrushOptions(options: any): void {\n this.brushTool.setSize((options as BrushOptions)?.size ?? 0);\n }\n setVertexEraserMode(active: boolean): void {\n if (active) {\n this.viewer?.setMouseNavEnabled(false); // tool takes the pointer\n this.viewportPixels = null;\n this.eraserTool.bindHost(this.eraserHost);\n }\n this.eraserTool.setMode(active);\n }\n setVertexEraserRadius(radius: number): void {\n this.eraserTool.setRadius(radius);\n }\n setZoomToBoxMode(active: boolean): void {\n if (active) {\n this.viewer?.setMouseNavEnabled(false); // the box drag must not pan\n this.zoomToBoxTool.bindHost(this.zoomBoxHost());\n }\n this.zoomToBoxTool.setMode(active);\n if (!active) this.viewer?.setMouseNavEnabled(true);\n }\n /** Box-prompted SAM: segment the drawn rectangles. The SAM tool reuses the\n * wand host (viewport readback + coordinate transform + region store). */\n segmentRectangles(): Promise<number> {\n this.viewportPixels = null; // segment against the current viewport readback\n this.samTool.bindHost(this.wandHost);\n return this.samTool.segmentBoxes();\n }\n segmentRectanglesCellpose(): Promise<number> {\n if (!this.cellSegmenter) return Promise.resolve(0);\n this.viewportPixels = null; // crop against the current viewport readback\n this.cellSegmentTool.bindHost(this.wandHost);\n return this.cellSegmentTool.segmentBoxes(this.cellSegmenter);\n }\n setSamModel(id: string): void {\n this.samTool.setModel(id);\n this.samPointTool.setModel(id);\n }\n setSamPointMode(active: boolean): void {\n if (active) {\n this.viewer?.setMouseNavEnabled(false); // clicks add points, don't pan\n this.viewportPixels = null;\n this.samPointTool.bindHost(this.wandHost);\n }\n this.samPointTool.setMode(active);\n }\n commitSamPoints(): void { this.samPointTool.commit(); }\n clearSamPoints(): void { this.samPointTool.clear(); }\n\n /** Build the wand/eraser host objects bound to this backend. Both tools run\n * over OSD via the shared coordinate transform + a viewport pixel readback,\n * and read/write regions directly on the shared RegionStore (neutral model). */\n private buildToolHosts(): void {\n this.wandHost = {\n getRegions: () => this.regionStore.getRegions(),\n setRegions: (regions) => this.regionStore.setRegions(regions),\n getCachedImageData: () => this.readbackViewport(),\n getActiveFrameIndex: () => this.currentZ,\n getOverlayContainer: () => this.getOverlayContainer(),\n getCoordinateTransform: () => this.coordTransform as ICoordinateTransform,\n getFileName: () => this.currentFileName,\n getShapeColor: () => this.regionStore.getShapeColor(),\n };\n this.eraserHost = {\n getRegions: () => this.regionStore.getRegions(),\n setRegions: (regions) => this.regionStore.setRegions(regions),\n invalidateWandRegion: () => this.wandTool.clearActiveRegion(),\n getOverlayContainer: () => this.getOverlayContainer(),\n getCoordinateTransform: () => this.coordTransform as ICoordinateTransform,\n getCachedImageRatio: () => this.readbackViewport()?.ratios[0] ?? 1,\n };\n }\n\n /** The element the on-canvas tool overlays attach to (OSD is mounted here). */\n private getOverlayContainer(): HTMLElement | null {\n return this.plotDiv ? document.getElementById(this.plotDiv) : null;\n }\n\n /** Size the navigator from the CURRENT container (navigatorSizeRatio of the\n * viewer element) and keep it pinned to the corner. OSD computes the size\n * once in the Viewer constructor — before the host flex layout settles —\n * and never corrects it, leaving a stale-size element whose visible minimap\n * floats above the bottom-right corner. */\n private resizeNavigator(): void {\n const v: any = this.viewer;\n const nav = v?.navigator;\n const el: HTMLElement | undefined = v?.element;\n if (!nav?.element || !el?.clientWidth || !el?.clientHeight) return;\n const w = Math.round(el.clientWidth * 0.16);\n const h = Math.round(el.clientHeight * 0.16);\n if (nav.element.style.width !== `${w}px` || nav.element.style.height !== `${h}px`) {\n try {\n nav.setWidth(w);\n nav.setHeight(h);\n } catch { /* navigator torn down */ }\n }\n // Normalize OSD's control-corner stack so the minimap sits flush in the\n // corner, inset 12px to line up with the scale bar:\n // - the inline-block wrapper carries line-box struts and can retain stale\n // sizing → make it a tight block;\n // - anything else OSD left in the corner would stack below the navigator\n // and float it up → hide it;\n // - inset the corner itself (bottom/right 12px), keeping the element in\n // normal flow.\n const wrapper = nav.element.parentElement as HTMLElement | null;\n const corner = wrapper?.parentElement as HTMLElement | null;\n if (wrapper && corner) {\n wrapper.style.display = 'block';\n wrapper.style.lineHeight = '0';\n wrapper.style.fontSize = '0';\n // The wrapper keeps the navigator's stale pre-settle height as an\n // explicit size (the nav was 0.16x the UNSETTLED container at creation),\n // leaving an empty band under the resized minimap — measured live:\n // navH=87 inside wrapH=167. Force it to hug its content.\n wrapper.style.height = 'auto';\n wrapper.style.width = 'auto';\n for (const child of Array.from(corner.children) as HTMLElement[]) {\n if (child !== wrapper) child.style.display = 'none';\n }\n for (const child of Array.from(wrapper.children) as HTMLElement[]) {\n if (child !== nav.element) child.style.display = 'none';\n }\n corner.style.bottom = '12px';\n corner.style.right = '12px';\n }\n Object.assign(nav.element.style, { position: 'relative', top: '', left: '', bottom: '', right: '', margin: '0' });\n // TODO(debug): remove after verification\n const ner = nav.element.getBoundingClientRect();\n const wr = wrapper?.getBoundingClientRect();\n const cr = corner?.getBoundingClientRect();\n const per = el.getBoundingClientRect();\n console.warn(`[viz:nav] navBottom=${Math.round(ner.bottom)} wrapBottom=${Math.round(wr?.bottom ?? -1)} ` +\n `cornerBottom=${Math.round(cr?.bottom ?? -1)} plotBottom=${Math.round(per.bottom)} ` +\n `navH=${Math.round(ner.height)} wrapH=${Math.round(wr?.height ?? -1)} cornerH=${Math.round(cr?.height ?? -1)}`);\n }\n\n /** Force the docked toolbar to repaint after an OSD zoom. Chrome leaves it\n * laid-out-but-unpainted (the canvas's compositing churn strands the toolbar's\n * raster). A synchronous display toggle re-rasters it with no visible gone-frame\n * and no layout shift. Located via the DOM since this service doesn't own the\n * toolbar; a no-op when there's no toolbar (e.g. embedded without one). */\n private nudgeToolbarRepaint(): void {\n const plotEl = this.plotDiv ? document.getElementById(this.plotDiv) : null;\n const dock = plotEl?.closest('visualization')?.querySelector<HTMLElement>('.toolbar-dock');\n if (!dock) return;\n const prev = dock.style.display;\n dock.style.display = 'none';\n void dock.offsetHeight; // reflow so the toggle re-rasters on the next paint\n dock.style.display = prev;\n }\n\n /** Host for the (shared) zoom-to-box tool: convert overlay pixels to image\n * coords via the viewport, and fit the viewport to the chosen rectangle. */\n private zoomBoxHost(): ZoomToBoxToolHost {\n return {\n getPlotDiv: () => this.plotDiv,\n pixelToData: (px: number, py: number) => elementToImage(this.viewer, px, py),\n applyZoomToBox: (coords: number[]) => this.applyZoomToBox(coords),\n };\n }\n\n /** Fit the OSD viewport to an image-space rectangle (coords ordered\n * [xMin, xMax, yMax, yMin]). */\n private applyZoomToBox(coordinates: number[]): void {\n if (!this.viewer || coordinates.length < 4) return;\n const [a, b, c, d] = coordinates;\n const x = Math.min(a, b);\n const w = Math.abs(b - a);\n const y = Math.min(c, d);\n const h = Math.abs(c - d);\n if (w <= 0 || h <= 0) return;\n const rect = imageRectToViewport(this.viewer, x, y, w, h);\n this.viewer.viewport.fitBounds(rect, false);\n }\n\n /**\n * Read back the *currently rendered* OSD canvas as the wand's pixel matrix.\n * The matrix covers only the visible viewport at screen resolution, so when\n * the user is zoomed into a sub-region the wand samples that region's detail\n * (rather than the whole image at preview resolution). `originX/originY` and\n * `ratios` map image coords <-> readback-pixel coords for the wand's\n * data/ratio/origin model. Cached until the viewport changes.\n */\n private readbackViewport(): CachedImageData | null {\n if (this.viewportPixels) return this.viewportPixels;\n const viewer = this.viewer as any;\n const canvas: HTMLCanvasElement | undefined = viewer?.drawer?.canvas;\n const vp = viewer?.viewport;\n if (!canvas || !canvas.width || !canvas.height || !vp) return null;\n const ctx = canvas.getContext('2d', { willReadFrequently: true });\n if (!ctx) return null;\n\n const w = canvas.width; // device pixels\n const h = canvas.height;\n const data = ctx.getImageData(0, 0, w, h).data; // RGBA, row-major\n // Build the [y][x] = [r,g,b] matrix the wand expects for RGB frames.\n const matrix: number[][][] = new Array(h);\n for (let y = 0; y < h; y++) {\n const row: number[][] = new Array(w);\n const base = y * w * 4;\n for (let x = 0; x < w; x++) {\n const o = base + x * 4;\n row[x] = [data[o], data[o + 1], data[o + 2]];\n }\n matrix[y] = row;\n }\n\n // Image-coord span the readback covers (CSS px in, image coords out). Route\n // through world item 0 (osd-coords) so it stays accurate — and quiet — when\n // the world holds multiple images (per-channel multichannel layers).\n const elW = canvas.clientWidth || w;\n const elH = canvas.clientHeight || h;\n const tl = elementToImage(this.viewer, 0, 0);\n const br = elementToImage(this.viewer, elW, elH);\n const ratioX = (br.x - tl.x) / w; // image px per readback px\n const ratioY = (br.y - tl.y) / h;\n\n this.viewportPixels = {\n frames: [matrix],\n width: w,\n height: h,\n ratios: [ratioX, ratioY],\n isGrayscale: false, // canvas readback is always RGBA\n originX: tl.x,\n originY: tl.y,\n };\n return this.viewportPixels;\n }\n\n /**\n * Recolor a grayscale tile through the active colormap LUT, using OSD's\n * tile-invalidated pixel pipeline (OSD 5+/6). Maps each pixel's grayscale\n * value (r==g==b) to the LUT's RGB. No-op for RGB images or until the LUT is\n * built. Handler is async — OSD awaits it (raiseEventAwaiting).\n */\n private async recolorTile(event: any): Promise<void> {\n if (this.isMultiChannel) {\n await this.recolorChannelTile(event);\n return;\n }\n const gray = this.isGrayscaleImage;\n if (gray) {\n if (!this.colorLut) return;\n } else if (!this.display.rgbNeedsRecolor()) {\n return; // RGB at default (all visible, full window, γ=1, no invert) → passthrough\n }\n\n // Read the tile's pixels. Prefer the rendering context, but some tile caches\n // (ajax PNG blobs) convert to an *empty* context2d — recoloring that would\n // blank the tile (white canvas). So if the context has no opaque pixels, draw\n // the tile's own bitmap/image and recolor that instead. We never write back\n // unless we actually recolored something, so a tile is never blanked.\n let ctx: CanvasRenderingContext2D | null = null;\n try {\n ctx = await event.getData('context2d');\n } catch {\n /* try bitmap below */\n }\n let img: ImageData | null = null;\n if (ctx && ctx.canvas && ctx.canvas.width && ctx.canvas.height) {\n try {\n img = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);\n } catch {\n img = null;\n }\n }\n if (!img || !this.hasOpaque(img.data)) {\n // Fall back to the tile's decoded image/bitmap.\n let src: any = null;\n try {\n src = await event.getData('imageBitmap');\n } catch {\n /* none */\n }\n if (!src || !src.width) {\n try {\n src = await event.getData('image');\n } catch {\n /* none */\n }\n }\n if (!src || !src.width) return; // can't get pixels — leave the tile untouched\n const c = document.createElement('canvas');\n c.width = src.width;\n c.height = src.height;\n ctx = c.getContext('2d', { willReadFrequently: true });\n if (!ctx) return;\n ctx.drawImage(src, 0, 0);\n img = ctx.getImageData(0, 0, c.width, c.height);\n }\n\n if (!this.display.applyToRgba(img.data) || !ctx) return; // nothing opaque\n ctx.putImageData(img, 0, 0);\n // The tile's cache can be evicted between the awaits above and here (slice\n // change / invalidation), making setData throw a DOMException on a dead\n // canvas. Swallow it — the tile is gone, so there's nothing to recolor.\n try { await event.setData(ctx, 'context2d'); } catch { /* tile evicted */ }\n }\n\n /**\n * Tint a single channel's tile in place. Each channel is its own OpenSeadragon\n * TiledImage (a single-band grayscale tile); OSD composites the N images\n * additively ('lighter') in its drawer — so this just maps the tile's intensity\n * through the channel's window/gamma and its pseudo-colour. Synchronous (no\n * cross-tile fetch) → no race, no seams. Channel is parsed from the tile URL.\n */\n private async recolorChannelTile(event: any): Promise<void> {\n const tile = event?.tile;\n const url: string = (tile && (typeof tile.getUrl === 'function' ? tile.getUrl() : tile.url)) || '';\n const m = /[?&]channel=(\\d+)/.exec(url);\n const ch = m ? parseInt(m[1], 10) : 0;\n const st = this.channelStates[ch];\n\n let ctx: CanvasRenderingContext2D | null = null;\n try { ctx = await event.getData('context2d'); } catch { /* fallback below */ }\n let img: ImageData | null = null;\n if (ctx && ctx.canvas && ctx.canvas.width && ctx.canvas.height) {\n try { img = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height); } catch { img = null; }\n }\n if (!img || !this.hasOpaque(img.data)) {\n let src: any = null;\n try { src = await event.getData('imageBitmap'); } catch { /* none */ }\n if (!src || !src.width) { try { src = await event.getData('image'); } catch { /* none */ } }\n if (!src || !src.width) return;\n const c = document.createElement('canvas');\n c.width = src.width; c.height = src.height;\n ctx = c.getContext('2d', { willReadFrequently: true });\n if (!ctx) return;\n ctx.drawImage(src, 0, 0);\n img = ctx.getImageData(0, 0, c.width, c.height);\n }\n if (!ctx) return;\n\n // Precompute lum(0..255) → tinted RGB once, then map each pixel by lookup —\n // the channel tile is single-band, so this turns ~262k per-pixel\n // channelIntensity() (with Math.pow for gamma) calls into 256 — the difference\n // between a snappy and a sluggish slider on a 4-channel stack.\n const { r: rL, g: gL, b: bL } = this.display.channelRgbLut(st);\n const d = img.data;\n let changed = false;\n for (let i = 0; i < d.length; i += 4) {\n if (d[i + 3] === 0) continue;\n const r = d[i], g = d[i + 1], b = d[i + 2];\n const lum = r >= g ? (r >= b ? r : b) : g >= b ? g : b; // single-band → max\n d[i] = rL[lum];\n d[i + 1] = gL[lum];\n d[i + 2] = bL[lum];\n changed = true;\n }\n if (!changed) return;\n ctx.putImageData(img, 0, 0);\n // See recolorTile: the tile cache can die between the awaits and here.\n try { await event.setData(ctx, 'context2d'); } catch { /* tile evicted */ }\n }\n\n /** Per-channel histogram for the Channels & Histogram pane, from the current\n * slice's sampled tiles (grayscale → channel 0; RGB → R/G/B). Null until the\n * async sampling resolves or if it was skipped. */\n getHistogram(channelIndex: number, _bins: number): IHistogram | null {\n return this.sampler.get(this.currentZ, channelIndex);\n }\n\n /** Native bit depth of a channel from the tile descriptor (8 when unknown). */\n private channelBitDepth(channelIndex: number): number {\n return this.descriptor?.channelInfo?.[channelIndex]?.bitDepth ?? 8;\n }\n\n /**\n * Async histogram for the Channels & Histogram pane. For >8-bit images it\n * fetches the **native** distribution from the server `/histogram` endpoint\n * (the 8-bit canvas tiles can't carry 16-bit values) and caches it per\n * slice+channel; for 8-bit/RGB it returns the existing client-sampled 8-bit\n * histogram. Read-only — it never touches the tile/display pipeline.\n */\n getHistogram$(channelIndex: number, bins: number): Observable<IHistogram | null> {\n if (this.channelBitDepth(channelIndex) <= 8 || !this.infoB64) {\n return of(this.getHistogram(channelIndex, bins));\n }\n return this.sampler.native$(this.infoB64, this.currentZ, channelIndex, bins);\n }\n\n /**\n * Export the underlying image data as a data-preserving multi-band TIFF at\n * native bit depth via `GET /export/tiff` (the server reads the raw 16-bit\n * planes — the client never sees them). Sends only the visible channels; the\n * existing 8-bit composite PNG export is unaffected.\n */\n async exportData(): Promise<void> {\n if (!this.infoB64) return;\n const visible = this.channelStates.filter((c) => c.visible).map((c) => c.index);\n const all = this.channelStates.length;\n // Omit `channels` when every channel is visible (server default = all).\n const chParam =\n visible.length && visible.length < all ? `&channels=${visible.join(',')}` : '';\n const url = `${this.api}export/tiff?info=${this.infoB64}&z=${this.currentZ}${chParam}`;\n const stem = (this.currentFileName || 'image').replace(/\\.[^.]+$/, '');\n try {\n const resp = await firstValueFrom(\n this.http\n .get(url, { observe: 'response', responseType: 'blob' })\n .pipe(timeout(600000)), // large exports stream slowly; generous deadline\n );\n if (resp.status === 202) {\n console.warn('[OSD] 16-bit export: file still caching — try again shortly.');\n return;\n }\n const blob = resp.body;\n if (blob) saveAs(blob, `${stem}_16bit.ome.tif`);\n } catch (err) {\n console.warn('[OSD] 16-bit TIFF export failed', err);\n }\n }\n\n /**\n * Export the current slice as a publication-ready PNG composited with the\n * active display settings (window / gamma / colormap or per-channel pseudo-\n * colours / invert). Picks the largest pyramid level under a pixel cap (the\n * coarser overview for huge whole-slides), fetches that level's tile grid,\n * stitches it into one canvas, runs the shared display pipeline, and saves it.\n */\n async exportComposite(): Promise<void> {\n const desc = this.descriptor;\n const levels = desc?.levels ?? [];\n if (!desc || !this.infoB64 || !levels.length) return;\n const CAP = 32_000_000; // ~32 MP — bounds memory for whole-slide images\n let res = levels.length - 1; // coarsest fallback\n for (let i = 0; i < levels.length; i++) {\n if (levels[i].width * levels[i].height <= CAP) { res = i; break; }\n }\n const lw = levels[res].width;\n const lh = levels[res].height;\n const t = desc.tileSize;\n const cols = Math.max(1, Math.ceil(lw / t));\n const rows = Math.max(1, Math.ceil(lh / t));\n const canvas = document.createElement('canvas');\n canvas.width = lw;\n canvas.height = lh;\n const ctx = canvas.getContext('2d', { willReadFrequently: true });\n if (!ctx) return;\n const z = this.currentZ;\n const jobs: Promise<void>[] = [];\n for (let row = 0; row < rows; row++) {\n for (let col = 0; col < cols; col++) {\n const url = buildTileUrl(this.api, this.infoB64, { res, col, row, z, tileSize: t });\n jobs.push(\n (async () => {\n try {\n const bmp = await fetchTileBitmap(this.http, url, 30000);\n ctx.drawImage(bmp, col * t, row * t);\n bmp.close?.();\n } catch (err) {\n // Skip a failed tile — the exported composite has a gap there.\n console.warn('[viz:export] composite tile fetch failed, skipping', url, err);\n }\n })(),\n );\n }\n }\n await Promise.all(jobs);\n try {\n const imageData = ctx.getImageData(0, 0, lw, lh);\n if (this.display.applyToRgba(imageData.data)) ctx.putImageData(imageData, 0, 0);\n } catch (err) {\n // Keep the un-recolored composite if readback fails — but say why.\n console.warn('[viz:export] composite recolor readback failed — exporting raw tiles', err);\n }\n const stem = (this.currentFileName || 'image').replace(/\\.[^.]+$/, '');\n canvas.toBlob((blob) => {\n if (blob) saveAs(blob, `${stem}_composite.png`);\n }, 'image/png');\n }\n\n /** True if any pixel in the RGBA buffer is non-transparent. */\n private hasOpaque(d: Uint8ClampedArray): boolean {\n for (let i = 3; i < d.length; i += 4) {\n if (d[i] !== 0) return true;\n }\n return false;\n }\n\n // ── IDisplayOptions ──────────────────────────────────────────────────\n // Inherited from BaseStoreVisualizer — pure delegations to the shared\n // VisualizerStore, so OSD and Plotly stay in lock-step. OSD applies the\n // colormap to grayscale tiles via the LUT reactively (see the constructor's\n // colormap subscription), not in setColormap.\n\n // ── IVisualizer ──────────────────────────────────────────────────────\n unsubscribe(): void {\n this.colormapSub?.unsubscribe();\n this.colormapSub = null;\n this.destroyViewer();\n }\n}\n","/**\n * Physical scale bar for the napari-js WebGPU image view (jit-ui#102), mirroring the OSD\n * backend's {@link OsdScaleBar}. napari keeps layers at pixel scale, so the camera's `zoom`\n * (CSS px per world unit) is exactly screen px per image pixel; combined with the image's\n * µm/pixel (`mppX`, from Bio-Formats `/tiles/info`) that gives a real-world bar length.\n * Recomputes on every camera change and host resize. Hidden when the image has no physical size.\n */\n\n/** Round up to a \"nice\" 1/2/5 × 10ⁿ value for scale-bar lengths. */\nfunction niceLength(x: number): number {\n if (x <= 0) return 1;\n const base = Math.pow(10, Math.floor(Math.log10(x)));\n const f = x / base;\n const nice = f < 1.5 ? 1 : f < 3.5 ? 2 : f < 7.5 ? 5 : 10;\n return nice * base;\n}\n\n/** Format a length given in micrometres, picking the unit that suits its magnitude (jit-service\n * normalises whatever unit Bio-Formats reports to µm). */\nexport function formatUm(um: number): string {\n const trim = (n: number): string => (n % 1 === 0 ? `${n}` : n.toFixed(1));\n if (um >= 1e6) return `${trim(um / 1e6)} m`;\n if (um >= 1e4) return `${trim(um / 1e4)} cm`;\n if (um >= 1e3) return `${trim(um / 1e3)} mm`;\n if (um >= 1) return `${trim(um)} µm`;\n return `${trim(um * 1000)} nm`;\n}\n\n/** The slice of the napari Camera the scale bar reads (zoom = CSS px per world/image pixel). */\ninterface ScaleBarCamera {\n readonly zoom: number;\n readonly changed: { connect(listener: () => void): () => void };\n}\n\nexport class NapariScaleBar {\n private readonly bar: HTMLDivElement;\n private readonly line: HTMLDivElement;\n private readonly label: HTMLSpanElement;\n private readonly disconnectCamera: () => void;\n private readonly resizeObserver?: ResizeObserver;\n\n constructor(\n private readonly host: HTMLElement,\n private readonly camera: ScaleBarCamera,\n private readonly mppX: number,\n ) {\n // The bar is absolutely positioned within the host, so the host must establish a containing\n // block (the plot host is often statically positioned).\n if (getComputedStyle(host).position === 'static') host.style.position = 'relative';\n\n this.bar = document.createElement('div');\n Object.assign(this.bar.style, {\n position: 'absolute',\n left: '12px',\n bottom: '12px',\n zIndex: '30',\n pointerEvents: 'none',\n color: '#fff',\n font: '11px sans-serif',\n textShadow: '0 0 3px #000',\n textAlign: 'center',\n userSelect: 'none',\n } as Partial<CSSStyleDeclaration>);\n this.label = document.createElement('span');\n this.line = document.createElement('div');\n Object.assign(this.line.style, {\n height: '4px',\n marginTop: '2px',\n background: 'rgba(255,255,255,0.9)',\n borderLeft: '1px solid #fff',\n borderRight: '1px solid #fff',\n boxShadow: '0 0 3px #000',\n } as Partial<CSSStyleDeclaration>);\n this.bar.appendChild(this.label);\n this.bar.appendChild(this.line);\n this.host.appendChild(this.bar);\n\n this.disconnectCamera = this.camera.changed.connect(() => this.update());\n if (typeof ResizeObserver !== 'undefined') {\n this.resizeObserver = new ResizeObserver(() => this.update());\n this.resizeObserver.observe(this.host);\n }\n this.update();\n }\n\n private update(): void {\n const pxPerImagePx = this.camera.zoom; // CSS screen px per image pixel\n if (!(this.mppX > 0) || !(pxPerImagePx > 0)) {\n this.bar.style.display = 'none';\n return;\n }\n const umPerScreenPx = this.mppX / pxPerImagePx;\n const niceUm = niceLength(120 * umPerScreenPx); // target ~120px bar\n this.bar.style.display = '';\n this.line.style.width = `${Math.round(niceUm / umPerScreenPx)}px`;\n this.label.textContent = formatUm(niceUm);\n }\n\n destroy(): void {\n this.disconnectCamera();\n this.resizeObserver?.disconnect();\n if (this.bar.parentNode) this.bar.parentNode.removeChild(this.bar);\n }\n}\n","import { Subscription } from 'rxjs';\n\nimport { IRegionOverlay, RegionToolMode } from '../../contracts/region-overlay.contract';\nimport { Region, Rectangle, Polygon } from '../../models/region';\nimport { RegionStore } from '../../store/region-store.service';\n\nconst SVG_NS = 'http://www.w3.org/2000/svg';\n/** Min drag (image px) before a freehand path records another point. */\nconst FREEHAND_STEP = 2;\n/** Click-distance (screen px) within which a polygon click snaps closed onto the first vertex. */\nconst CLOSE_SNAP_PX = 10;\n/** Screen-px hit radius for grabbing a vertex / rectangle corner handle. */\nconst HANDLE_HIT_PX = 9;\n/** Rendered handle size (screen px). */\nconst HANDLE_SIZE = 7;\n\n/** The slice of the napari Viewer the overlay needs (coord transforms + control gating). */\ninterface OverlayViewer {\n canvasToWorld(clientX: number, clientY: number): [number, number];\n worldToCanvas(worldX: number, worldY: number): [number, number];\n setControlsEnabled(enabled: boolean): void;\n readonly camera: { readonly changed: { connect(listener: () => void): () => void } };\n}\n\n/**\n * SVG region overlay for the napari-js WebGPU image view (jit-ui#102), mirroring the OSD backend's\n * {@link OsdRegionOverlay} but driven by napari's `canvasToWorld`/`worldToCanvas` transforms.\n * Vector shapes are drawn in an absolutely-positioned `<svg>` over the canvas (no need to push\n * them through WebGPU). It writes completed shapes to the shared {@link RegionStore} (so save /\n * undo / export work identically to OSD) and re-renders from the store on every camera move,\n * region change, and selection change.\n *\n * Supports (jit-ui#102): rectangle / polygon / freehand path drawing, click-select and rubber-band\n * marquee select, pan/zoom gating via `setControlsEnabled`, body move, vertex move/add/delete,\n * bezier handle editing, and donut holes (including hole vertex + hole-bezier-handle editing) —\n * full parity with {@link OsdRegionOverlay}.\n */\nexport class NapariRegionOverlay implements IRegionOverlay {\n private readonly svg: SVGSVGElement;\n private readonly subs = new Subscription();\n private readonly disconnectCamera: () => void;\n\n private mode: RegionToolMode = 'none';\n private selected: number[] = [];\n\n /** In-progress drawing state (image-space). */\n private draftRect: { x0: number; y0: number; x1: number; y1: number } | null = null;\n /** In-progress rubber-band selection marquee (select mode), image-space. */\n private marquee: { x0: number; y0: number; x1: number; y1: number } | null = null;\n /** Dedicated marquee rect element, updated directly during the drag (no full region redraw). */\n private marqueeEl: SVGRectElement | null = null;\n private draftPath: Array<[number, number]> | null = null; // freehand or click polygon\n private drawing = false; // pointer is down for rect / freehand\n\n /** In-progress manipulation (select/move modes): dragging a body, a polygon vertex, or a\n * rectangle corner. `anchor` is the fixed opposite corner for a rectangle resize. */\n private edit: {\n kind: 'body' | 'vertex' | 'corner' | 'bezier' | 'holevertex' | 'holebezier';\n id: number;\n vertexIndex?: number;\n holeIndex?: number;\n side?: 'in' | 'out';\n anchor?: [number, number];\n last: [number, number];\n } | null = null;\n\n constructor(\n private readonly host: HTMLElement,\n private readonly viewer: OverlayViewer,\n private readonly store: RegionStore,\n ) {\n if (getComputedStyle(host).position === 'static') host.style.position = 'relative';\n this.svg = document.createElementNS(SVG_NS, 'svg');\n Object.assign(this.svg.style, {\n position: 'absolute',\n inset: '0',\n width: '100%',\n height: '100%',\n zIndex: '20',\n pointerEvents: 'none', // until a tool activates\n touchAction: 'none',\n } as Partial<CSSStyleDeclaration>);\n this.host.appendChild(this.svg);\n\n this.svg.addEventListener('pointerdown', this.onPointerDown);\n this.svg.addEventListener('pointermove', this.onPointerMove);\n this.svg.addEventListener('pointerup', this.onPointerUp);\n this.svg.addEventListener('dblclick', this.onDblClick);\n\n this.subs.add(this.store.getRegionUpdateEvent().subscribe(() => this.redraw()));\n this.subs.add(\n this.store.getSelectedShapeIndices$().subscribe((idx) => {\n this.selected = idx ?? [];\n this.redraw();\n }),\n );\n this.disconnectCamera = this.viewer.camera.changed.connect(() => this.redraw());\n this.redraw();\n }\n\n // ── IRegionOverlay ────────────────────────────────────────────────────────\n setMode(mode: RegionToolMode): void {\n this.mode = mode;\n this.draftRect = null;\n this.draftPath = null;\n this.marquee = null;\n this.clearMarqueeEl();\n this.drawing = false;\n // The overlay owns pointer/navigation gating: while a tool is active it captures the pointer\n // and the napari camera controls are disabled; 'none' hands the pointer back for pan/zoom.\n const active = mode !== 'none';\n this.viewer.setControlsEnabled(!active);\n this.svg.style.pointerEvents = active ? 'auto' : 'none';\n this.svg.style.cursor = active ? 'crosshair' : 'default';\n this.redraw();\n }\n\n setSelectedBezier(bezier: boolean): void {\n const sel = this.selectedRegion();\n if (sel?.id != null) this.store.setBezier(sel.id, bezier);\n }\n\n destroy(): void {\n this.svg.removeEventListener('pointerdown', this.onPointerDown);\n this.svg.removeEventListener('pointermove', this.onPointerMove);\n this.svg.removeEventListener('pointerup', this.onPointerUp);\n this.svg.removeEventListener('dblclick', this.onDblClick);\n this.disconnectCamera();\n this.subs.unsubscribe();\n if (this.svg.parentNode) this.svg.parentNode.removeChild(this.svg);\n }\n\n // ── coordinate transforms ─────────────────────────────────────────────────\n /** Pointer client coords → rounded image coords. */\n private toImage(clientX: number, clientY: number): [number, number] {\n const [wx, wy] = this.viewer.canvasToWorld(clientX, clientY);\n return [Math.round(wx), Math.round(wy)];\n }\n\n /** Image coords → SVG-local px (the svg overlays the canvas at the same client rect). */\n private toLocal(imgX: number, imgY: number): [number, number] {\n const [cx, cy] = this.viewer.worldToCanvas(imgX, imgY);\n const r = this.svg.getBoundingClientRect();\n return [cx - r.left, cy - r.top];\n }\n\n // ── pointer handlers ──────────────────────────────────────────────────────\n private readonly onPointerDown = (e: PointerEvent): void => {\n if (this.mode === 'none') return;\n e.preventDefault();\n const [ix, iy] = this.toImage(e.clientX, e.clientY);\n if (this.mode === 'drawrect') {\n this.draftRect = { x0: ix, y0: iy, x1: ix, y1: iy };\n this.drawing = true;\n this.svg.setPointerCapture(e.pointerId);\n } else if (this.mode === 'drawclosedpath' || this.mode === 'drawopenpath') {\n this.draftPath = [[ix, iy]];\n this.drawing = true;\n this.svg.setPointerCapture(e.pointerId);\n } else if (this.mode === 'drawpolygon') {\n this.handlePolygonClick(ix, iy, e.clientX, e.clientY);\n } else if (this.mode === 'select' || this.mode === 'move') {\n this.beginManipulation(ix, iy, e);\n } else if (this.mode === 'addpoint') {\n this.handleAddPoint(ix, iy);\n } else if (this.mode === 'deletepoint') {\n this.handleDeletePoint(ix, iy);\n }\n this.redraw();\n };\n\n private readonly onPointerMove = (e: PointerEvent): void => {\n const [ix, iy] = this.toImage(e.clientX, e.clientY);\n if (this.marquee) {\n this.marquee.x1 = ix;\n this.marquee.y1 = iy;\n this.updateMarqueeEl(); // update just the marquee rect — NOT a full region redraw\n return;\n }\n if (this.edit) {\n this.applyManipulation(ix, iy);\n this.redraw();\n return;\n }\n if (!this.drawing) return;\n if (this.draftRect) {\n this.draftRect.x1 = ix;\n this.draftRect.y1 = iy;\n } else if (this.draftPath) {\n const last = this.draftPath[this.draftPath.length - 1];\n if (Math.abs(ix - last[0]) >= FREEHAND_STEP || Math.abs(iy - last[1]) >= FREEHAND_STEP) {\n this.draftPath.push([ix, iy]);\n }\n }\n this.redraw();\n };\n\n private readonly onPointerUp = (e: PointerEvent): void => {\n if (this.marquee) {\n const m = this.marquee;\n this.marquee = null;\n this.clearMarqueeEl();\n try {\n this.svg.releasePointerCapture(e.pointerId);\n } catch {\n /* already released */\n }\n this.finishMarquee(m); // setSelectedShapeIndices → one redraw via the selection subscription\n return;\n }\n if (this.edit) {\n this.store.endBatch();\n this.edit = null;\n try {\n this.svg.releasePointerCapture(e.pointerId);\n } catch {\n /* already released */\n }\n this.redraw();\n return;\n }\n if (!this.drawing) return;\n this.drawing = false;\n try {\n this.svg.releasePointerCapture(e.pointerId);\n } catch {\n /* capture may already be released */\n }\n if (this.draftRect) {\n const { x0, y0, x1, y1 } = this.draftRect;\n const x = Math.min(x0, x1);\n const y = Math.min(y0, y1);\n const w = Math.abs(x1 - x0);\n const h = Math.abs(y1 - y0);\n this.draftRect = null;\n if (w >= 2 && h >= 2) this.commitRectangle(x, y, w, h);\n } else if (this.draftPath) {\n const pts = this.draftPath;\n this.draftPath = null;\n const closed = this.mode === 'drawclosedpath';\n if (pts.length >= (closed ? 3 : 2)) this.commitPolygon(pts, closed);\n }\n this.redraw();\n };\n\n /** Click-to-place polygon: add a vertex, or close when clicking near the first one. */\n private handlePolygonClick(ix: number, iy: number, clientX: number, clientY: number): void {\n if (!this.draftPath) {\n this.draftPath = [[ix, iy]];\n return;\n }\n const [fx, fy] = this.toLocal(this.draftPath[0][0], this.draftPath[0][1]);\n const r = this.svg.getBoundingClientRect();\n const near =\n Math.hypot(clientX - r.left - fx, clientY - r.top - fy) <= CLOSE_SNAP_PX &&\n this.draftPath.length >= 3;\n if (near) {\n const pts = this.draftPath;\n this.draftPath = null;\n this.commitPolygon(pts, true);\n } else {\n this.draftPath.push([ix, iy]);\n }\n }\n\n private readonly onDblClick = (e: MouseEvent): void => {\n if (this.mode !== 'drawpolygon' || !this.draftPath) return;\n e.preventDefault();\n const pts = this.draftPath;\n this.draftPath = null;\n if (pts.length >= 3) this.commitPolygon(pts, true);\n this.redraw();\n };\n\n /** The currently-selected region (single selection), or null. */\n private selectedRegion(): Region | null {\n const regions = this.store.getRegions();\n const i = this.selected[0];\n return i != null && i >= 0 && i < regions.length ? regions[i] : null;\n }\n\n /** Screen distance (px) between a client point and an image coord. */\n private screenDist(clientX: number, clientY: number, imgX: number, imgY: number): number {\n const [lx, ly] = this.toLocal(imgX, imgY);\n const r = this.svg.getBoundingClientRect();\n return Math.hypot(clientX - r.left - lx, clientY - r.top - ly);\n }\n\n /**\n * Start a select/move interaction: grab a handle (rectangle corner) or vertex of the already-\n * selected region first; otherwise select the topmost region under the cursor and drag its body.\n */\n private beginManipulation(ix: number, iy: number, e: PointerEvent): void {\n const sel = this.selectedRegion();\n if (sel?.bounds) {\n const grab = this.hitHandle(sel, e.clientX, e.clientY);\n if (grab) {\n this.store.beginBatch();\n this.edit = { ...grab, id: sel.id, last: [ix, iy] };\n this.svg.setPointerCapture(e.pointerId);\n return;\n }\n }\n // Hit-test bodies, topmost first (last drawn renders on top).\n const regions = this.store.getRegions();\n for (let i = regions.length - 1; i >= 0; i--) {\n if (this.hitTest(regions[i], ix, iy)) {\n this.store.selectRegion(regions[i]);\n this.store.beginBatch();\n this.edit = { kind: 'body', id: regions[i].id, last: [ix, iy] };\n this.svg.setPointerCapture(e.pointerId);\n return;\n }\n }\n // Empty space: in select mode start a rubber-band marquee (selects the regions it covers on\n // release); in move mode just clear the selection.\n if (this.mode === 'select') {\n this.marquee = { x0: ix, y0: iy, x1: ix, y1: iy };\n this.updateMarqueeEl();\n this.svg.setPointerCapture(e.pointerId);\n } else {\n this.store.setSelectedShapeIndices([]);\n }\n }\n\n /** Create/update the marquee rect element directly (avoids a full region redraw per move). */\n private updateMarqueeEl(): void {\n if (!this.marquee) return;\n if (!this.marqueeEl || !this.marqueeEl.parentNode) {\n this.marqueeEl = document.createElementNS(SVG_NS, 'rect');\n this.marqueeEl.setAttribute('stroke', '#4da3ff');\n this.marqueeEl.setAttribute('stroke-width', '1');\n this.marqueeEl.setAttribute('stroke-dasharray', '4 3');\n this.marqueeEl.setAttribute('fill', '#4da3ff');\n this.marqueeEl.setAttribute('fill-opacity', '0.12');\n this.marqueeEl.setAttribute('vector-effect', 'non-scaling-stroke');\n this.svg.appendChild(this.marqueeEl);\n }\n const { x0, y0, x1, y1 } = this.marquee;\n const [lx, ly] = this.toLocal(Math.min(x0, x1), Math.min(y0, y1));\n const [rx, ry] = this.toLocal(Math.max(x0, x1), Math.max(y0, y1));\n this.marqueeEl.setAttribute('x', `${lx}`);\n this.marqueeEl.setAttribute('y', `${ly}`);\n this.marqueeEl.setAttribute('width', `${Math.abs(rx - lx)}`);\n this.marqueeEl.setAttribute('height', `${Math.abs(ry - ly)}`);\n }\n\n /** Remove the marquee element from the SVG. */\n private clearMarqueeEl(): void {\n if (this.marqueeEl?.parentNode) this.marqueeEl.parentNode.removeChild(this.marqueeEl);\n this.marqueeEl = null;\n }\n\n /** Test whether a client point grabs a rectangle corner or a polygon vertex of `region`. */\n private hitHandle(\n region: Region,\n clientX: number,\n clientY: number,\n ):\n | { kind: 'corner'; anchor: [number, number] }\n | { kind: 'vertex'; vertexIndex: number }\n | { kind: 'bezier'; vertexIndex: number; side: 'in' | 'out' }\n | { kind: 'holevertex'; holeIndex: number; vertexIndex: number }\n | { kind: 'holebezier'; holeIndex: number; vertexIndex: number; side: 'in' | 'out' }\n | null {\n const b = region.bounds;\n if (!b) return null;\n if ('width' in b && 'x' in b) {\n const r = b as Rectangle;\n const corners: Array<[number, number, [number, number]]> = [\n [r.x, r.y, [r.x + r.width, r.y + r.height]],\n [r.x + r.width, r.y, [r.x, r.y + r.height]],\n [r.x, r.y + r.height, [r.x + r.width, r.y]],\n [r.x + r.width, r.y + r.height, [r.x, r.y]],\n ];\n for (const [cx, cy, anchor] of corners) {\n if (this.screenDist(clientX, clientY, cx, cy) <= HANDLE_HIT_PX) return { kind: 'corner', anchor };\n }\n } else if ('npoints' in b) {\n const p = b as Polygon;\n // Bezier control points first (they sit off the anchors), so they're grabbable.\n if (p.bezier && p.handlesIn?.length === p.npoints && p.handlesOut?.length === p.npoints) {\n for (let i = 0; i < p.npoints; i++) {\n const out = p.handlesOut[i];\n const inn = p.handlesIn[i];\n if (this.screenDist(clientX, clientY, p.xpoints[i] + out[0], p.ypoints[i] + out[1]) <= HANDLE_HIT_PX) {\n return { kind: 'bezier', vertexIndex: i, side: 'out' };\n }\n if (this.screenDist(clientX, clientY, p.xpoints[i] + inn[0], p.ypoints[i] + inn[1]) <= HANDLE_HIT_PX) {\n return { kind: 'bezier', vertexIndex: i, side: 'in' };\n }\n }\n }\n for (let i = 0; i < p.npoints; i++) {\n if (this.screenDist(clientX, clientY, p.xpoints[i], p.ypoints[i]) <= HANDLE_HIT_PX) {\n return { kind: 'vertex', vertexIndex: i };\n }\n }\n // Hole (donut) ring: bezier control points first, then the vertices.\n const holes = p.holes ?? [];\n const holeBezier = !!(p.bezier && p.holeHandlesIn && p.holeHandlesOut);\n for (let hi = 0; hi < holes.length; hi++) {\n const ring = holes[hi];\n if (holeBezier && p.holeHandlesIn![hi] && p.holeHandlesOut![hi]) {\n for (let vi = 0; vi < ring.length; vi++) {\n const out = p.holeHandlesOut![hi][vi] ?? [0, 0];\n const inn = p.holeHandlesIn![hi][vi] ?? [0, 0];\n if (this.screenDist(clientX, clientY, ring[vi][0] + out[0], ring[vi][1] + out[1]) <= HANDLE_HIT_PX) {\n return { kind: 'holebezier', holeIndex: hi, vertexIndex: vi, side: 'out' };\n }\n if (this.screenDist(clientX, clientY, ring[vi][0] + inn[0], ring[vi][1] + inn[1]) <= HANDLE_HIT_PX) {\n return { kind: 'holebezier', holeIndex: hi, vertexIndex: vi, side: 'in' };\n }\n }\n }\n for (let vi = 0; vi < ring.length; vi++) {\n if (this.screenDist(clientX, clientY, ring[vi][0], ring[vi][1]) <= HANDLE_HIT_PX) {\n return { kind: 'holevertex', holeIndex: hi, vertexIndex: vi };\n }\n }\n }\n }\n return null;\n }\n\n /** Apply the live drag for the active manipulation (image coords `ix,iy`). */\n private applyManipulation(ix: number, iy: number): void {\n if (!this.edit) return;\n if (this.edit.kind === 'body') {\n const [lx, ly] = this.edit.last;\n this.store.moveRegion(this.edit.id, ix - lx, iy - ly);\n this.edit.last = [ix, iy];\n } else if (this.edit.kind === 'vertex' && this.edit.vertexIndex != null) {\n this.store.moveVertex(this.edit.id, this.edit.vertexIndex, ix, iy);\n } else if (this.edit.kind === 'corner' && this.edit.anchor) {\n const [ax, ay] = this.edit.anchor;\n const rect = new Rectangle();\n rect.x = Math.min(ax, ix);\n rect.y = Math.min(ay, iy);\n rect.width = Math.abs(ix - ax);\n rect.height = Math.abs(iy - ay);\n this.store.updateBounds(this.edit.id, rect);\n } else if (this.edit.kind === 'bezier' && this.edit.vertexIndex != null && this.edit.side) {\n this.store.moveBezierHandle(this.edit.id, this.edit.vertexIndex, this.edit.side, ix, iy);\n } else if (\n this.edit.kind === 'holevertex' &&\n this.edit.holeIndex != null &&\n this.edit.vertexIndex != null\n ) {\n this.store.moveHoleVertex(this.edit.id, this.edit.holeIndex, this.edit.vertexIndex, ix, iy);\n } else if (\n this.edit.kind === 'holebezier' &&\n this.edit.holeIndex != null &&\n this.edit.vertexIndex != null &&\n this.edit.side\n ) {\n this.store.moveHoleBezierHandle(\n this.edit.id,\n this.edit.holeIndex,\n this.edit.vertexIndex,\n this.edit.side,\n ix,\n iy,\n );\n }\n }\n\n /** addpoint mode: insert a vertex on the selected polygon's nearest edge at the click. */\n private handleAddPoint(ix: number, iy: number): void {\n const sel = this.selectedRegion();\n const b = sel?.bounds;\n if (!sel || !b || !('npoints' in b)) return;\n const p = b as Polygon;\n let bestSeg = 0;\n let bestD = Infinity;\n const segs = p.closed === false ? p.npoints - 1 : p.npoints;\n for (let s = 0; s < segs; s++) {\n const j = (s + 1) % p.npoints;\n const d = this.pointSegDist(ix, iy, p.xpoints[s], p.ypoints[s], p.xpoints[j], p.ypoints[j]);\n if (d < bestD) {\n bestD = d;\n bestSeg = s;\n }\n }\n this.store.addVertex(sel.id, bestSeg, ix, iy);\n }\n\n /** deletepoint mode: remove the selected polygon's vertex nearest the click. */\n private handleDeletePoint(ix: number, iy: number): void {\n const sel = this.selectedRegion();\n const b = sel?.bounds;\n if (!sel || !b || !('npoints' in b)) return;\n const p = b as Polygon;\n let best = -1;\n let bestD = Infinity;\n for (let i = 0; i < p.npoints; i++) {\n const d = Math.hypot(p.xpoints[i] - ix, p.ypoints[i] - iy);\n if (d < bestD) {\n bestD = d;\n best = i;\n }\n }\n if (best >= 0) this.store.deleteVertex(sel.id, best);\n }\n\n /** Distance from point (px,py) to segment (ax,ay)-(bx,by), in image units. */\n private pointSegDist(\n px: number,\n py: number,\n ax: number,\n ay: number,\n bx: number,\n by: number,\n ): number {\n const dx = bx - ax;\n const dy = by - ay;\n const len2 = dx * dx + dy * dy || 1;\n let t = ((px - ax) * dx + (py - ay) * dy) / len2;\n t = Math.max(0, Math.min(1, t));\n return Math.hypot(px - (ax + t * dx), py - (ay + t * dy));\n }\n\n /** Finalize a rubber-band marquee: select every region whose bounding box it overlaps (a tiny\n * marquee is treated as a click on empty space → clear the selection). */\n private finishMarquee(m: { x0: number; y0: number; x1: number; y1: number }): void {\n const x0 = Math.min(m.x0, m.x1);\n const x1 = Math.max(m.x0, m.x1);\n const y0 = Math.min(m.y0, m.y1);\n const y1 = Math.max(m.y0, m.y1);\n if (x1 - x0 < 3 && y1 - y0 < 3) {\n this.store.setSelectedShapeIndices([]);\n return;\n }\n const indices: number[] = [];\n this.store.getRegions().forEach((r, i) => {\n if (r.isProfile?.()) return;\n const bb = this.regionBBox(r);\n if (bb && bb.x0 <= x1 && bb.x1 >= x0 && bb.y0 <= y1 && bb.y1 >= y0) indices.push(i);\n });\n this.store.setSelectedShapeIndices(indices);\n }\n\n /** A region's bounding box in image coords (rectangle, polygon, or multipolygon), or null. */\n private regionBBox(\n region: Region,\n ): { x0: number; y0: number; x1: number; y1: number } | null {\n const b = region.bounds;\n if (!b) return null;\n if ('width' in b && 'x' in b) {\n const r = b as Rectangle;\n return { x0: r.x, y0: r.y, x1: r.x + r.width, y1: r.y + r.height };\n }\n const acc = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity };\n const addRing = (xs: number[], ys: number[]): void => {\n for (let i = 0; i < xs.length; i++) {\n if (xs[i] < acc.x0) acc.x0 = xs[i];\n if (xs[i] > acc.x1) acc.x1 = xs[i];\n if (ys[i] < acc.y0) acc.y0 = ys[i];\n if (ys[i] > acc.y1) acc.y1 = ys[i];\n }\n };\n if ('npoints' in b) {\n const p = b as Polygon;\n addRing(p.xpoints, p.ypoints);\n } else if ('polygons' in b) {\n for (const p of (b as { polygons: Polygon[] }).polygons) addRing(p.xpoints, p.ypoints);\n } else {\n return null;\n }\n return isFinite(acc.x0) ? acc : null;\n }\n\n // ── shape commit ──────────────────────────────────────────────────────────\n private commitRectangle(x: number, y: number, width: number, height: number): void {\n const rect = new Rectangle();\n rect.x = x;\n rect.y = y;\n rect.width = width;\n rect.height = height;\n const region = new Region();\n region.bounds = rect;\n region.color = this.store.getShapeColor();\n this.store.addRegion(region);\n }\n\n private commitPolygon(points: Array<[number, number]>, closed: boolean): void {\n const poly = new Polygon();\n poly.npoints = points.length;\n poly.xpoints = points.map((p) => p[0]);\n poly.ypoints = points.map((p) => p[1]);\n poly.coordinates = points.map((p) => [p[0], p[1]]);\n poly.closed = closed;\n const region = new Region();\n region.bounds = poly;\n region.color = this.store.getShapeColor();\n region.label = 'Region';\n this.store.addRegion(region);\n }\n\n // ── rendering ─────────────────────────────────────────────────────────────\n private hitTest(region: Region, x: number, y: number): boolean {\n const b = region.bounds;\n if (!b) return false;\n if ('width' in b && 'x' in b) {\n const r = b as Rectangle;\n return x >= r.x && x <= r.x + r.width && y >= r.y && y <= r.y + r.height;\n }\n if ('npoints' in b) {\n const p = b as Polygon;\n let inside = false;\n for (let i = 0, j = p.npoints - 1; i < p.npoints; j = i++) {\n const xi = p.xpoints[i];\n const yi = p.ypoints[i];\n const xj = p.xpoints[j];\n const yj = p.ypoints[j];\n if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;\n }\n return inside;\n }\n return false;\n }\n\n redraw(): void {\n while (this.svg.firstChild) this.svg.removeChild(this.svg.firstChild);\n const regions = this.store.getRegions();\n regions.forEach((region, i) => {\n if (region.isProfile?.()) return;\n const isSel = this.selected.includes(i);\n const el = this.buildRegionEl(region, isSel);\n if (el) this.svg.appendChild(el);\n this.drawLabel(region);\n if (isSel) this.drawHandles(region);\n });\n this.drawDraft();\n }\n\n /** Draw a region's classification label at its top-left, when labels are enabled (matches OSD). */\n private drawLabel(region: Region): void {\n if (!this.store.getShowShapeLabel() || region.isProfile?.()) return;\n const label = region.label;\n const b = region.bounds;\n if (!label || !b) return;\n let ix: number;\n let iy: number;\n if ('width' in b && 'x' in b) {\n ix = (b as Rectangle).x;\n iy = (b as Rectangle).y;\n } else if ('npoints' in b) {\n const p = b as Polygon;\n ix = p.xpoints.reduce((m, x) => Math.min(m, x), Infinity);\n iy = p.ypoints.reduce((m, y) => Math.min(m, y), Infinity);\n } else {\n return;\n }\n const [lx, ly] = this.toLocal(ix, iy);\n const text = document.createElementNS(SVG_NS, 'text');\n text.setAttribute('x', `${lx}`);\n text.setAttribute('y', `${ly - 4}`);\n text.setAttribute('fill', '#fff');\n text.setAttribute('stroke', '#000');\n text.setAttribute('stroke-width', '3');\n text.setAttribute('paint-order', 'stroke');\n text.setAttribute('font', '12px sans-serif');\n text.setAttribute('pointer-events', 'none');\n text.textContent = label;\n this.svg.appendChild(text);\n }\n\n /** Draw grab handles for the selected region: rectangle corners or polygon vertices. */\n private drawHandles(region: Region): void {\n const b = region.bounds;\n if (!b) return;\n const stroke = region.color || this.store.getShapeColor() || '#00ffff';\n const handle = (imgX: number, imgY: number): void => {\n const [lx, ly] = this.toLocal(imgX, imgY);\n const el = document.createElementNS(SVG_NS, 'rect');\n el.setAttribute('x', `${lx - HANDLE_SIZE / 2}`);\n el.setAttribute('y', `${ly - HANDLE_SIZE / 2}`);\n el.setAttribute('width', `${HANDLE_SIZE}`);\n el.setAttribute('height', `${HANDLE_SIZE}`);\n el.setAttribute('fill', '#fff');\n el.setAttribute('stroke', stroke);\n el.setAttribute('stroke-width', '1.5');\n this.svg.appendChild(el);\n };\n if ('width' in b && 'x' in b) {\n const r = b as Rectangle;\n handle(r.x, r.y);\n handle(r.x + r.width, r.y);\n handle(r.x, r.y + r.height);\n handle(r.x + r.width, r.y + r.height);\n } else if ('npoints' in b) {\n const p = b as Polygon;\n const isBezier = p.bezier && p.handlesIn?.length === p.npoints && p.handlesOut?.length === p.npoints;\n for (let i = 0; i < p.npoints; i++) handle(p.xpoints[i], p.ypoints[i]);\n for (const ring of p.holes ?? []) for (const [hx, hy] of ring) handle(hx, hy);\n // Bezier regions also expose their tangent control points (circles) joined to the anchor\n // by a thin line, matching the OSD overlay's editable bezier handles.\n if (isBezier) {\n const hIn = p.handlesIn as number[][];\n const hOut = p.handlesOut as number[][];\n for (let i = 0; i < p.npoints; i++) {\n this.drawBezierHandle(p.xpoints[i], p.ypoints[i], hOut[i], stroke);\n this.drawBezierHandle(p.xpoints[i], p.ypoints[i], hIn[i], stroke);\n }\n }\n // Donut hole bezier control handles.\n if (p.bezier && p.holeHandlesIn && p.holeHandlesOut) {\n (p.holes ?? []).forEach((ring, hi) => {\n const hIn = p.holeHandlesIn![hi];\n const hOut = p.holeHandlesOut![hi];\n if (!hIn || !hOut) return;\n ring.forEach(([hx, hy], vi) => {\n this.drawBezierHandle(hx, hy, hOut[vi], stroke);\n this.drawBezierHandle(hx, hy, hIn[vi], stroke);\n });\n });\n }\n }\n }\n\n /** Draw one bezier control point (anchor + handle offset) as a small circle connected to its\n * anchor by a tangent line. `handle` is the [dx,dy] offset from the anchor in image space. */\n private drawBezierHandle(ax: number, ay: number, handle: number[], stroke: string): void {\n if (!handle || (handle[0] === 0 && handle[1] === 0)) return;\n const [alx, aly] = this.toLocal(ax, ay);\n const [hlx, hly] = this.toLocal(ax + handle[0], ay + handle[1]);\n const line = document.createElementNS(SVG_NS, 'line');\n line.setAttribute('x1', `${alx}`);\n line.setAttribute('y1', `${aly}`);\n line.setAttribute('x2', `${hlx}`);\n line.setAttribute('y2', `${hly}`);\n line.setAttribute('stroke', stroke);\n line.setAttribute('stroke-width', '1');\n line.setAttribute('stroke-opacity', '0.7');\n this.svg.appendChild(line);\n const dot = document.createElementNS(SVG_NS, 'circle');\n dot.setAttribute('cx', `${hlx}`);\n dot.setAttribute('cy', `${hly}`);\n dot.setAttribute('r', `${HANDLE_SIZE / 2}`);\n dot.setAttribute('fill', stroke);\n dot.setAttribute('stroke', '#fff');\n dot.setAttribute('stroke-width', '1');\n this.svg.appendChild(dot);\n }\n\n private buildRegionEl(region: Region, isSelected: boolean): SVGElement | null {\n const b = region.bounds;\n if (!b) return null;\n const stroke = region.color || this.store.getShapeColor() || '#00ffff';\n if ('width' in b && 'x' in b) {\n const r = b as Rectangle;\n const [lx, ly] = this.toLocal(r.x, r.y);\n const [rx, ry] = this.toLocal(r.x + r.width, r.y + r.height);\n const el = document.createElementNS(SVG_NS, 'rect');\n el.setAttribute('x', `${Math.min(lx, rx)}`);\n el.setAttribute('y', `${Math.min(ly, ry)}`);\n el.setAttribute('width', `${Math.abs(rx - lx)}`);\n el.setAttribute('height', `${Math.abs(ry - ly)}`);\n this.style(el, stroke, isSelected);\n return el;\n }\n if ('npoints' in b) {\n const p = b as Polygon;\n const isBezier =\n !!p.bezier && p.handlesIn?.length === p.npoints && p.handlesOut?.length === p.npoints;\n const hasHoles = !!(p.holes && p.holes.length);\n // Bezier or donut (holes) → a single <path>; holes use even-odd fill so they punch through.\n if (isBezier || hasHoles) {\n const el = document.createElementNS(SVG_NS, 'path');\n el.setAttribute('d', this.polygonPathData(p, isBezier));\n if (hasHoles) el.setAttribute('fill-rule', 'evenodd');\n this.style(el, stroke, isSelected);\n return el;\n }\n const pts = p.xpoints\n .map((_, i) => this.toLocal(p.xpoints[i], p.ypoints[i]).join(','))\n .join(' ');\n const el = document.createElementNS(SVG_NS, p.closed === false ? 'polyline' : 'polygon');\n el.setAttribute('points', pts);\n this.style(el, stroke, isSelected);\n return el;\n }\n return null;\n }\n\n /** Path data for a polygon: the exterior ring (bezier or straight) plus any holes (bezier when\n * the donut carries hole handles, else straight) as sub-paths — even-odd fill cuts them out. */\n private polygonPathData(p: Polygon, isBezier: boolean): string {\n let d = isBezier\n ? this.ringBezierPath(p.xpoints, p.ypoints, p.handlesIn!, p.handlesOut!, p.closed !== false)\n : this.straightPath(p.xpoints, p.ypoints, p.closed !== false);\n const holeBezier = !!(p.bezier && p.holeHandlesIn && p.holeHandlesOut);\n (p.holes ?? []).forEach((ring, hi) => {\n if (ring.length < 3) return;\n const xs = ring.map((pt) => pt[0]);\n const ys = ring.map((pt) => pt[1]);\n if (holeBezier && p.holeHandlesIn![hi] && p.holeHandlesOut![hi]) {\n d += ' ' + this.ringBezierPath(xs, ys, p.holeHandlesIn![hi], p.holeHandlesOut![hi], true);\n } else {\n d += ' ' + this.straightPath(xs, ys, true);\n }\n });\n return d;\n }\n\n /** SVG path data for a straight ring/polyline in image coords (closed appends `Z`). */\n private straightPath(xs: number[], ys: number[], closed: boolean): string {\n let d = '';\n for (let i = 0; i < xs.length; i++) {\n const [lx, ly] = this.toLocal(xs[i], ys[i]);\n d += (i === 0 ? 'M' : ' L') + ` ${lx},${ly}`;\n }\n return closed ? d + ' Z' : d;\n }\n\n /** SVG cubic-bezier path data for any ring (exterior or hole): anchors joined by cubic segments\n * whose control points are `anchor + handleOut` (leaving) and `nextAnchor + handleIn` (arriving),\n * in image space. Used for both the exterior and (donut) hole rings. */\n private ringBezierPath(\n xs: number[],\n ys: number[],\n hIn: number[][],\n hOut: number[][],\n closed: boolean,\n ): string {\n const n = xs.length;\n const anchor = (i: number): [number, number] => this.toLocal(xs[i], ys[i]);\n const ctrlOut = (i: number): [number, number] =>\n this.toLocal(xs[i] + (hOut[i]?.[0] ?? 0), ys[i] + (hOut[i]?.[1] ?? 0));\n const ctrlIn = (i: number): [number, number] =>\n this.toLocal(xs[i] + (hIn[i]?.[0] ?? 0), ys[i] + (hIn[i]?.[1] ?? 0));\n const [sx, sy] = anchor(0);\n let d = `M ${sx},${sy}`;\n const segments = closed ? n : n - 1;\n for (let s = 0; s < segments; s++) {\n const i = s;\n const j = (s + 1) % n;\n const [c1x, c1y] = ctrlOut(i);\n const [c2x, c2y] = ctrlIn(j);\n const [ex, ey] = anchor(j);\n d += ` C ${c1x},${c1y} ${c2x},${c2y} ${ex},${ey}`;\n }\n if (closed) d += ' Z';\n return d;\n }\n\n private style(el: SVGElement, stroke: string, isSelected: boolean): void {\n el.setAttribute('stroke', stroke);\n el.setAttribute('stroke-width', isSelected ? '4' : '2');\n el.setAttribute('fill', isSelected ? stroke : 'none');\n el.setAttribute('fill-opacity', isSelected ? '0.35' : '0');\n el.setAttribute('vector-effect', 'non-scaling-stroke');\n }\n\n /** Draw the in-progress rectangle / path preview. */\n private drawDraft(): void {\n if (this.draftRect) {\n const { x0, y0, x1, y1 } = this.draftRect;\n const [lx, ly] = this.toLocal(Math.min(x0, x1), Math.min(y0, y1));\n const [rx, ry] = this.toLocal(Math.max(x0, x1), Math.max(y0, y1));\n const el = document.createElementNS(SVG_NS, 'rect');\n el.setAttribute('x', `${lx}`);\n el.setAttribute('y', `${ly}`);\n el.setAttribute('width', `${Math.abs(rx - lx)}`);\n el.setAttribute('height', `${Math.abs(ry - ly)}`);\n this.styleDraft(el);\n this.svg.appendChild(el);\n }\n if (this.draftPath && this.draftPath.length) {\n const pts = this.draftPath.map(([x, y]) => this.toLocal(x, y).join(',')).join(' ');\n const el = document.createElementNS(SVG_NS, 'polyline');\n el.setAttribute('points', pts);\n this.styleDraft(el);\n this.svg.appendChild(el);\n }\n }\n\n private styleDraft(el: SVGElement): void {\n el.setAttribute('stroke', this.store.getShapeColor() || '#00ffff');\n el.setAttribute('stroke-width', '2');\n el.setAttribute('stroke-dasharray', '4 3');\n el.setAttribute('fill', 'none');\n el.setAttribute('vector-effect', 'non-scaling-stroke');\n }\n}\n","/**\n * DOM text labels for the napari-js 3D axes gizmo (jit-ui#102). The {@link AxesLayer} draws the\n * axis lines/ticks/box in WebGPU; this overlay adds the crisp X/Y/Z + scale text on top, projected\n * with the 3D camera's view-projection so each label tracks its anchor as the volume orbits.\n * Mirrors the {@link NapariScaleBar} overlay pattern (absolute-positioned over the host, updated on\n * every `camera3d.changed`). Falls back to pixel/slice counts when no physical µm/pixel is known.\n */\n\n/** One axis label: a world-space anchor (the axis end, in the volume's centred box), the text to\n * show, and its colour (matching the WebGPU axis colour). */\nexport interface AxisLabelSpec {\n anchor: [number, number, number];\n text: string;\n color: string;\n}\n\n/** The slice of napari's Camera3D this overlay reads. `viewProjection` is column-major (gl-matrix). */\nexport interface AxesLabelCamera3D {\n viewProjection(vw: number, vh: number): ArrayLike<number>;\n readonly changed: { connect(listener: () => void): () => void };\n}\n\n/**\n * Project a world point through a column-major 4×4 MVP to CSS-pixel screen coordinates.\n * Returns `visible: false` when the point is at/behind the camera (w ≤ 0). Pure — unit-tested.\n */\nexport function projectPoint(\n mvp: ArrayLike<number>,\n p: [number, number, number],\n vw: number,\n vh: number,\n): { x: number; y: number; visible: boolean } {\n const [x, y, z] = p;\n // Column-major: clip[r] = Σ_c M[c*4+r] * v[c].\n const cx = mvp[0] * x + mvp[4] * y + mvp[8] * z + mvp[12];\n const cy = mvp[1] * x + mvp[5] * y + mvp[9] * z + mvp[13];\n const cw = mvp[3] * x + mvp[7] * y + mvp[11] * z + mvp[15];\n if (cw <= 0) return { x: 0, y: 0, visible: false };\n const ndcX = cx / cw;\n const ndcY = cy / cw;\n return {\n x: (ndcX * 0.5 + 0.5) * vw,\n y: (0.5 - ndcY * 0.5) * vh,\n visible: true,\n };\n}\n\nexport class NapariAxesLabels {\n private readonly els: HTMLSpanElement[] = [];\n private readonly disconnectCamera: () => void;\n private readonly resizeObserver?: ResizeObserver;\n private visible = true;\n\n constructor(\n private readonly host: HTMLElement,\n private readonly camera3d: AxesLabelCamera3D,\n private readonly labels: AxisLabelSpec[],\n ) {\n if (getComputedStyle(host).position === 'static') host.style.position = 'relative';\n for (const spec of labels) {\n const el = document.createElement('span');\n Object.assign(el.style, {\n position: 'absolute',\n zIndex: '30',\n pointerEvents: 'none',\n font: '11px sans-serif',\n fontWeight: '600',\n color: spec.color,\n textShadow: '0 0 3px #000, 0 0 3px #000',\n whiteSpace: 'nowrap',\n transform: 'translate(-50%, -50%)',\n userSelect: 'none',\n } as Partial<CSSStyleDeclaration>);\n el.textContent = spec.text;\n this.host.appendChild(el);\n this.els.push(el);\n }\n this.disconnectCamera = this.camera3d.changed.connect(() => this.update());\n if (typeof ResizeObserver !== 'undefined') {\n this.resizeObserver = new ResizeObserver(() => this.update());\n this.resizeObserver.observe(this.host);\n }\n this.update();\n }\n\n setVisible(visible: boolean): void {\n this.visible = visible;\n this.update();\n }\n\n /** Replace the label anchors/text in place (same count) and reproject — lets a host move the\n * labels when the box geometry changes live (e.g. a Z-height gizmo restretching the volume)\n * without tearing down and recreating the DOM elements (which would flicker). */\n updateAnchors(labels: AxisLabelSpec[]): void {\n for (let i = 0; i < this.labels.length && i < labels.length; i++) {\n this.labels[i] = labels[i];\n if (labels[i].text !== this.els[i].textContent) this.els[i].textContent = labels[i].text;\n }\n this.update();\n }\n\n private update(): void {\n const vw = this.host.clientWidth;\n const vh = this.host.clientHeight;\n if (!this.visible || vw <= 0 || vh <= 0) {\n for (const el of this.els) el.style.display = 'none';\n return;\n }\n const mvp = this.camera3d.viewProjection(vw, vh);\n this.labels.forEach((spec, i) => {\n const el = this.els[i];\n const s = projectPoint(mvp, spec.anchor, vw, vh);\n if (!s.visible) {\n el.style.display = 'none';\n return;\n }\n el.style.display = '';\n el.style.left = `${s.x}px`;\n el.style.top = `${s.y}px`;\n });\n }\n\n destroy(): void {\n this.disconnectCamera();\n this.resizeObserver?.disconnect();\n for (const el of this.els) el.parentNode?.removeChild(el);\n this.els.length = 0;\n }\n}\n","/**\n * Draggable Z-height handle for the napari-js WebGPU volume (jit-ui#102). A small DOM grip is drawn\n * over the 3D canvas at the projected top-face centre of the volume box (reusing the axes-label\n * {@link projectPoint} projection, so it tracks the box as the volume orbits). Dragging it up makes\n * the volume taller, down makes it flatter — the host maps the drag to a Z-scale factor and\n * restretches the volume + axes live (only the model matrix changes; the voxel texture is untouched).\n *\n * Direct-manipulation counterpart of {@link NapariAxesLabels}: both are absolute-positioned overlays\n * updated on every `camera3d.changed`, but this one accepts pointer input.\n */\nimport { AxesLabelCamera3D, projectPoint } from './napari-axes-labels';\n\nexport interface VolumeZHandleOptions {\n /** Current top-face-centre world point (the box is centred at the origin, so `[0, 0, +halfZ]`). */\n topAnchor: () => [number, number, number];\n /** The current Z-scale factor (1 = the volume's default proportions). */\n getScale: () => number;\n /** Apply a new Z-scale factor — the host restretches the volume + axes and repositions overlays. */\n setScale: (scale: number) => void;\n /** Vertical drag (px) for one doubling/halving of the Z height. Larger = less sensitive. */\n pixelsPerDouble?: number;\n /** Clamp for the Z-scale factor. */\n minScale?: number;\n maxScale?: number;\n}\n\nconst DEFAULTS = { pixelsPerDouble: 180, minScale: 0.1, maxScale: 10 };\n\nexport class NapariVolumeZHandle {\n private readonly el: HTMLDivElement;\n private readonly disconnectCamera: () => void;\n private readonly resizeObserver?: ResizeObserver;\n private readonly opts: Required<VolumeZHandleOptions>;\n private visible = true;\n private dragging = false;\n private startY = 0;\n private startScale = 1;\n\n constructor(\n private readonly host: HTMLElement,\n private readonly camera3d: AxesLabelCamera3D,\n opts: VolumeZHandleOptions,\n ) {\n this.opts = { ...DEFAULTS, ...opts };\n if (getComputedStyle(host).position === 'static') host.style.position = 'relative';\n\n this.el = document.createElement('div');\n Object.assign(this.el.style, {\n position: 'absolute',\n zIndex: '31',\n width: '22px',\n height: '22px',\n marginLeft: '-11px',\n marginTop: '-11px',\n borderRadius: '50%',\n background: 'rgba(102,140,255,0.85)', // matches the Z axis colour (#668cff)\n border: '1.5px solid #fff',\n boxShadow: '0 0 4px rgba(0,0,0,0.6)',\n color: '#fff',\n font: '13px sans-serif',\n lineHeight: '20px',\n textAlign: 'center',\n cursor: 'ns-resize',\n touchAction: 'none',\n userSelect: 'none',\n } as Partial<CSSStyleDeclaration>);\n this.el.textContent = '↕';\n this.el.title = 'Drag to change the volume height (Z). Double-click to reset.';\n this.host.appendChild(this.el);\n\n this.el.addEventListener('pointerdown', this.onPointerDown);\n this.el.addEventListener('pointermove', this.onPointerMove);\n this.el.addEventListener('pointerup', this.onPointerUp);\n this.el.addEventListener('pointercancel', this.onPointerUp);\n this.el.addEventListener('dblclick', this.onDoubleClick);\n\n this.disconnectCamera = this.camera3d.changed.connect(() => this.reposition());\n if (typeof ResizeObserver !== 'undefined') {\n this.resizeObserver = new ResizeObserver(() => this.reposition());\n this.resizeObserver.observe(this.host);\n }\n this.reposition();\n }\n\n setVisible(visible: boolean): void {\n this.visible = visible;\n this.reposition();\n }\n\n /** Reproject the handle to the current top-face anchor. Called on camera move, resize, and after\n * the host applies a new scale (so the grip follows the growing/shrinking box). */\n reposition(): void {\n const vw = this.host.clientWidth;\n const vh = this.host.clientHeight;\n if (!this.visible || vw <= 0 || vh <= 0) {\n this.el.style.display = 'none';\n return;\n }\n const mvp = this.camera3d.viewProjection(vw, vh);\n const s = projectPoint(mvp, this.opts.topAnchor(), vw, vh);\n if (!s.visible) {\n this.el.style.display = 'none';\n return;\n }\n this.el.style.display = '';\n this.el.style.left = `${s.x}px`;\n this.el.style.top = `${s.y}px`;\n }\n\n private readonly onPointerDown = (e: PointerEvent): void => {\n e.preventDefault();\n e.stopPropagation();\n this.dragging = true;\n this.startY = e.clientY;\n this.startScale = this.opts.getScale();\n this.el.setPointerCapture?.(e.pointerId);\n };\n\n private readonly onPointerMove = (e: PointerEvent): void => {\n if (!this.dragging) return;\n e.preventDefault();\n e.stopPropagation();\n // Up (negative dy) → taller. Exponential so each `pixelsPerDouble` px doubles/halves the height.\n const dy = e.clientY - this.startY;\n const factor = Math.pow(2, -dy / this.opts.pixelsPerDouble);\n const next = Math.min(\n this.opts.maxScale,\n Math.max(this.opts.minScale, this.startScale * factor),\n );\n this.opts.setScale(next);\n this.reposition();\n };\n\n private readonly onPointerUp = (e: PointerEvent): void => {\n if (!this.dragging) return;\n this.dragging = false;\n if (this.el.hasPointerCapture?.(e.pointerId)) this.el.releasePointerCapture?.(e.pointerId);\n };\n\n private readonly onDoubleClick = (e: MouseEvent): void => {\n e.preventDefault();\n e.stopPropagation();\n this.opts.setScale(1);\n this.reposition();\n };\n\n destroy(): void {\n this.disconnectCamera();\n this.resizeObserver?.disconnect();\n this.el.removeEventListener('pointerdown', this.onPointerDown);\n this.el.removeEventListener('pointermove', this.onPointerMove);\n this.el.removeEventListener('pointerup', this.onPointerUp);\n this.el.removeEventListener('pointercancel', this.onPointerUp);\n this.el.removeEventListener('dblclick', this.onDoubleClick);\n this.el.parentNode?.removeChild(this.el);\n }\n}\n","import { Inject, Injectable, Optional } from '@angular/core';\nimport { Observable, BehaviorSubject, Subject, Subscription, combineLatest, from, of } from 'rxjs';\nimport { Image } from 'image-js';\nimport { saveAs } from 'file-saver';\nimport {\n Viewer,\n histogramScalar,\n colormapFromLut,\n tintColormap,\n reverseColormap,\n heightField,\n MultiChannelImageView,\n MultiChannelVolumeView,\n} from 'napari-js';\nimport type {\n AxesLayer,\n SurfaceLayer,\n PointsLayer,\n Points3DLayer,\n TiledSource,\n TileKey,\n PixelChunk,\n ChannelView,\n VolumeChannel,\n Colormap,\n} from 'napari-js';\n\nimport { IImageInfo } from '../../contracts/image.contract';\nimport { IChannelState } from '../../contracts/channel-histogram-api.contract';\nimport { buildColormapLut, Rgb } from '../../contracts/colormap-lut';\nimport {\n PlotType,\n PlotTypeDescriptor,\n PLOT_TYPE_DESCRIPTORS,\n isNapari3d,\n isNapariIsosurface,\n isNapariSurface,\n isNapariScatter,\n isNapariScatter3d,\n NAPARI_DEFAULT_DECIMATE,\n} from '../../contracts/plot-type';\nimport {\n IVisualizer,\n PixelData,\n IntensityProfile,\n IIsosurfaceControls,\n IIntensityControls,\n ISurface3dControls,\n} from '../../contracts/visualizer.contract';\nimport {\n ViewerCapabilities,\n ViewerFeature,\n capabilitiesOf,\n} from '../../contracts/capabilities.contract';\nimport { IRegionOverlay } from '../../contracts/region-overlay.contract';\nimport { IHistogram } from '../../contracts/channel-histogram-api.contract';\nimport { ColormapNode, IWandOptions, IBrushOptions } from '../../contracts/display-types';\nimport { VIZ_CONFIG, VizConfig } from '../../contracts/viz-config';\nimport { TILE_ACCESS_PORT, TileAccessPort } from '../../contracts/ports/tile-access.port';\nimport { BaseStoreVisualizer } from '../base-store-visualizer';\nimport { SimpleSliceAccessService } from '../simple-slice-access.service';\nimport { VisualizerStore } from '../../store/visualizer-store.service';\nimport { RegionStore } from '../../store/region-store.service';\nimport { NapariScaleBar, formatUm } from './napari-scale-bar';\nimport { NapariRegionOverlay } from './napari-region-overlay';\nimport { NapariAxesLabels, AxisLabelSpec } from './napari-axes-labels';\nimport { NapariVolumeZHandle } from './napari-volume-z-handle';\nimport {\n ICoordinateTransform,\n} from '../../contracts/coordinate-transform.contract';\nimport { WandToolService, WandToolHost, CachedImageData } from '../../toolbar/wand/wand-tool.service';\nimport { WandOptions } from '../../toolbar/wand/wand.service';\nimport { BrushToolService, BrushOptions } from '../../toolbar/brush/brush-tool.service';\nimport {\n VertexEraserToolService,\n VertexEraserToolHost,\n} from '../../toolbar/vertex-eraser/vertex-eraser-tool.service';\nimport {\n ZoomToBoxToolService,\n ZoomToBoxToolHost,\n} from '../../toolbar/zoom-to-box/zoom-to-box-tool.service';\nimport { SamToolService } from '../../toolbar/segmentation/sam-tool.service';\nimport { SamPointToolService } from '../../toolbar/segmentation/sam-point-tool.service';\nimport { CellSegmentToolService } from '../../toolbar/segmentation/cell-segment-tool.service';\nimport { ICellSegmenter, CELL_SEGMENTER } from '../../contracts/cell-segmenter.contract';\n\n/** ICoordinateTransform over the napari camera: pointer client coords ↔ image/world coords. */\nclass NapariCoordinateTransform implements ICoordinateTransform {\n constructor(\n private readonly viewer: {\n canvasToWorld(clientX: number, clientY: number): [number, number];\n readonly camera: { zoom: number };\n },\n private readonly ready: () => boolean,\n ) {}\n clientToData(clientX: number, clientY: number): { x: number; y: number } {\n const [x, y] = this.viewer.canvasToWorld(clientX, clientY);\n return { x, y };\n }\n dataLengthToScreen(dataLength: number): number {\n return dataLength * this.viewer.camera.zoom; // CSS px per world unit\n }\n isReady(): boolean {\n return this.ready();\n }\n}\n\n/** Opaque handle from {@link NapariVisualizerService.load}, passed back to plot(). */\ninterface NapariLoaded {\n imageInfo: IImageInfo;\n z: number;\n /** Must match `IImageInfo.fileName` — the render orchestrator drops the result if the\n * handle's `filename` doesn't match the requested image (guards against stale clicks). */\n filename: string;\n}\n\nconst VOLUME_MAX_SLICE = 1024; // \"Full\" in-plane cap; the default ¼ load uses 256\n/** Reference in-plane world size (long side) for the volume/axes box, in arbitrary world units.\n * The box is anchored to this reference regardless of the chosen decimate factor, so changing the\n * resolution changes DETAIL, not the volume's proportions (Z no longer appears to shrink when the\n * in-plane sampling grows). Set to the DEFAULT decimate's in-plane cap so the default view is\n * unchanged; higher/lower resolutions keep that same shape. See {@link mountVolume}. */\nconst VOLUME_WORLD_INPLANE_REF = VOLUME_MAX_SLICE / NAPARI_DEFAULT_DECIMATE;\n/** Max concurrent slice fetches when assembling a volume — keeps the connection pool busy\n * without flooding it (browsers cap ~6/host) on a deep stack. */\nconst VOLUME_FETCH_CONCURRENCY = 8;\n\n/** Volume/isosurface sampling for a decimate factor `scale` (1 = Full 1024, 2 = ½ 512, 4 = ¼ 256\n * default, 8 = ⅛ 128): the in-plane cap halves each step; slices stay un-subsampled until ⅛, then\n * subsample. */\nfunction volumeResolutionFor(scale: number): { maxSlice: number; sliceStep: number } {\n const s = Math.max(1, Math.round(scale));\n return {\n maxSlice: Math.max(8, Math.round(VOLUME_MAX_SLICE / s)),\n sliceStep: Math.max(1, Math.floor(s / 4)),\n };\n}\n/** Fully-normalized intensity height as a fraction of the in-plane extent — matches the Plotly\n * SURFACE z-aspect (~0.4) so the relief isn't exaggerated. */\nconst SURFACE_Z_ASPECT = 0.4;\n/** \"Full\" mesh grid cap; the decimate factor divides it (default ¼ → 220, ½ → 440, Full → 880). */\nconst SURFACE_MAX_GRID = 880;\n/** Coefficient scaling the pyramid tile budget with the target resolution — a higher target pulls a\n * finer pyramid level (more real detail). Shared by the surface plane fetch + volume assembly. */\nconst STITCH_BUDGET_COEFF = 16;\n/** Surface mesh target grid for a decimate factor `scale`: the grid cap shrinks by `scale` (every\n * slice is kept — the z-slider needs them all). The source is fetched at a matching resolution. */\nfunction surfaceResolutionFor(scale: number): { maxGrid: number } {\n const s = Math.max(1, Math.round(scale));\n return { maxGrid: Math.max(16, Math.round(SURFACE_MAX_GRID / s)) };\n}\n\n/** 3D scatter: in-plane cap for the assembled voxel grid, and the max number of points emitted\n * (the grid is flat-strided down to this) — keeps the billboard count interactive. */\nconst SCATTER3D_MAX_XY = 64;\nconst SCATTER3D_MAX_POINTS = 150000;\n\nconst TILE_SIZE = 512; // server tile edge (matches the OSD backend)\n/** Max tiles stitched for one displayed slice (512px tiles → up to ~6144² at full res). Beyond\n * this we step to a coarser pyramid level so a large image stays tractable. */\nconst MAX_STITCH_TILES = 144;\n/** WebGPU default `maxTextureDimension2D` — a stitched slice's longest side must fit a texture. */\nconst MAX_TEXTURE_DIM = 8192;\n/** Concurrent tile requests per stitched slice. Firing a whole grid at once (hundreds of requests\n * for a large level) overwhelmed the tile server (504s); a small pool keeps the pipe full without\n * flooding it — and slice-level workers already run several stitches in parallel on top of this. */\nconst TILE_FETCH_CONCURRENCY = 6;\n/** How long to poll `/tiles/info` (202 while the server caches the source) before falling back to\n * a single tile. Generous like the OSD backend — a cold whole-slide can take minutes to cache. */\nconst DESCRIPTOR_TIMEOUT_MS = 120000;\n\n/** Default per-channel tints (Fiji-style) when the store/descriptor offers no colour. */\nconst DEFAULT_TINTS = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff', '#ffffff'];\n\n/** Default tint for a channel index, cycling the Fiji palette. */\nfunction tintFor(channel: number): string {\n return DEFAULT_TINTS[channel % DEFAULT_TINTS.length];\n}\n\n/** One pyramid level from `GET /tiles/info` (res 0 = full resolution). */\ninterface TileLevel {\n res: number;\n width: number;\n height: number;\n}\n\n/** Subset of the `/tiles/info` descriptor this backend reads (tile grid, channels, scale). */\ninterface TileDescriptor {\n width: number;\n height: number;\n tileSize: number;\n z: number;\n channels: number;\n multichannel?: boolean;\n /** Real Bio-Formats levels at the front of `levels`; per-channel tiles exist only there. */\n realLevels?: number;\n channelInfo?: Array<{\n name?: string;\n color?: string;\n bitDepth?: number;\n minAllowed?: number;\n maxAllowed?: number;\n }> | null;\n levels: TileLevel[];\n mppX?: number;\n mppY?: number;\n}\n\n/**\n * A WebGPU image backend built on the published `napari-js` library — the POC engine for\n * jit-ui#102 (a browser-based napari shipped as a JS library, swapping image plotting with\n * OpenSeadragon and 3D slicing/isosurfaces with Plotly).\n *\n * Render strategy: rather than re-implement the server's tile/pyramid protocol (which OSD\n * already handles), this backend renders the **complete per-slice image URLs the app already\n * produces** (`IImageInfo.urls`) — `urls[z]` for the 2D image, and the full `urls` stack\n * assembled into a downsampled volume for the 3D types. Region state and display options\n * delegate to the shared {@link RegionStore} / {@link VisualizerStore}, exactly as OSD does.\n *\n * Follow-ups (jit-ui#102): native-resolution pyramidal tiling, on-canvas tools, region\n * overlay rendering, per-channel histograms, TIFF export.\n */\n@Injectable({ providedIn: 'root' })\nexport class NapariVisualizerService extends BaseStoreVisualizer implements IVisualizer {\n readonly capabilities: ViewerCapabilities = capabilitiesOf([\n ViewerFeature.ImageDisplay,\n ViewerFeature.StackSlider,\n ViewerFeature.PixelReadback,\n ViewerFeature.Surface3D,\n ViewerFeature.Isosurface,\n ]);\n\n private readonly api: string;\n\n private viewer: Viewer | null = null;\n private canvas: HTMLCanvasElement | null = null;\n private host: HTMLElement | null = null;\n private loaded: NapariLoaded | null = null;\n private lastPixels: PixelData | null = null;\n private currentPlotType: PlotType = PlotType.NAPARI_IMAGE;\n /** napari-js high-level view owning the 3D volume layers (one additive tinted layer per channel\n * for multichannel, or a single grayscale volume). Null in 2D. */\n private volumeView: MultiChannelVolumeView | null = null;\n /** True when the volume is composited from per-channel layers (vs a single grayscale volume). */\n private volumeMultichannel = false;\n /** napari-js height-field surface mesh (NAPARI_SURFACE plot type; null otherwise). Built from a\n * single grayscale slice by {@link buildSurface} via napari-js's `heightField` + `addSurface`. */\n private surfaceLayer: SurfaceLayer | null = null;\n /** Which band the surface samples (a channel index for multichannel, else the composite). */\n private surfaceChannel: number | undefined = undefined;\n /** Pre-loaded per-slice luminance planes (already decimated to the surface grid), keyed by z,\n * so the stack slider rebuilds the surface instantly. Filled by {@link preloadSurfacePlanes}. */\n private readonly surfacePlanes = new Map<\n number,\n { data: Uint8Array; width: number; height: number }\n >();\n /** In-plane grid cap for the active surface load (full grid ÷ the decimate factor). */\n private surfaceMaxGrid = SURFACE_MAX_GRID;\n /** Contrast window [min,max] the current surface mesh was built with. A change reshapes the\n * mesh (pixel height = intensity within [min,max]), so it triggers a geometry rebuild. */\n private surfaceWindow: [number, number] | null = null;\n /** Persisted wireframe choice for the surface (re-applied when a new surface mounts). */\n private surfaceWireframe = false;\n /** napari-js 2D scatter points (region centroids) + its region-change subscription. */\n private scatter2dPoints: PointsLayer | null = null;\n private scatterRegionSub: Subscription | null = null;\n /** napari-js 3D scatter (voxel point cloud). */\n private scatter3dLayer: Points3DLayer | null = null;\n /** Monotonic load generation. Bumped by {@link reset} and {@link cancelLoading}; the frame-loading\n * loops (volume assembly, surface preload) capture it and bail when it changes, so a Cancel (or a\n * new plot) actually stops fetching frames instead of running to completion in the background. */\n private loadToken = 0;\n /** Decimate factor for the napari 3D types (1 = Full, 2 = ½ default, 4 = ¼, 8 = ⅛). Applied when a\n * volume/isosurface/surface (re)loads; changing it needs a re-plot (it changes fetched data). */\n private resolutionScale = NAPARI_DEFAULT_DECIMATE;\n /** 3D coordinate-axes / scale gizmo for the volume/isosurface view (null in 2D). */\n private axesLayer: AxesLayer | null = null;\n /** DOM X/Y/Z + scale labels tracking the 3D axes gizmo (null in 2D). */\n private axesLabels: NapariAxesLabels | null = null;\n /** Draggable Z-height grip over the volume (null unless a volume/isosurface is mounted). */\n private zHandle: NapariVolumeZHandle | null = null;\n /** User Z-height factor for the volume (1 = the volume's natural proportions); driven by the\n * in-view drag handle. Reset per mount. */\n private volumeZScale = 1;\n /** Volume world box at `volumeZScale = 1` (base) + the sampled voxel depth — enough to recompute\n * the Z-axis voxel scale, axes depth, and overlay anchors as the handle stretches Z. */\n private volumeWorldBase: { width: number; height: number; depth: number } | null = null;\n private volumeSampledDepth = 1;\n /** Persisted axes on/off choice, re-applied when a new volume mounts. Defaults on. */\n private axesVisible = true;\n private volumeDims: { width: number; height: number; depth: number } | null = null;\n /** Assembled uint8 volume data per channel (key = channel index), kept for the volume intensity\n * histogram. Key 0 holds the grayscale/composite volume in the single-channel case. */\n private readonly volumeChannelData = new Map<number, Uint8Array>();\n private imageW = 0;\n private imageH = 0;\n /** Monotonic slice-request id so a slow out-of-order slice fetch can't clobber a newer one. */\n private sliceReq = 0;\n /** Cached `/tiles/info` pyramid descriptor + the infoB64 it was fetched for. */\n private descriptor: TileDescriptor | null = null;\n private descriptorKey: string | null = null;\n\n /** How the current 2D image is composited (drives histogram + state application). */\n private imageMode: 'grayscale' | 'multichannel' | 'rgb' = 'rgb';\n /** napari-js high-level view that owns the per-channel layer set (build + live display\n * updates) for the current {@link imageMode}. Rebuilt on each (re)render. */\n private channelView: MultiChannelImageView | null = null;\n /** Live subscription applying channel-state / colormap changes to the layers. */\n private displaySub: Subscription | null = null;\n /** Latest grayscale colormap selection from the store (applied to the single gray layer). */\n private currentColormap: ColormapNode | null = null;\n private currentReverse = false;\n /** Latest invert toggle from the store (flips intensity before the colormap, like OSD). */\n private invertEnabled = false;\n /** Physical scale bar overlay for the 2D image (null when 3D or the image has no µm/pixel). */\n private scaleBar: NapariScaleBar | null = null;\n /** SVG region-drawing overlay for the 2D image (null until a 2D image is plotted). */\n private regionOverlay: NapariRegionOverlay | null = null;\n /** Pixel-tool plumbing: the plot div id, coord transform, and bound tool hosts. */\n private plotDivId = '';\n private coordTransform: ICoordinateTransform | null = null;\n private wandHost: WandToolHost | null = null;\n private eraserHost: VertexEraserToolHost | null = null;\n /** Cached CachedImageData built from the last readback (rebuilt when lastPixels changes). */\n private cachedImage: CachedImageData | null = null;\n private cachedImageSource: PixelData | null = null;\n /** Visible world rect captured AT the last readback — must pair with `lastPixels` so the pixel\n * tools' ratios/origin match the matrix's camera (using the live rect after a pan/zoom would\n * mis-scale the region). */\n private lastPixelsRect: { x: number; y: number; width: number; height: number } | null = null;\n /** Image smoothing (bilinear) vs nearest-neighbour (crisp pixels, the default). */\n private imageSmoothing = false;\n /** True when the 2D image is rendered via pyramidal TiledSources (descriptor available). */\n private tiled = false;\n /** Debounced readback timer + camera-change unsubscribe (keep lastPixels current for tools). */\n private readbackTimer: ReturnType<typeof setTimeout> | null = null;\n private cameraReadbackOff: (() => void) | null = null;\n /** Coarse per-channel luminance sample (keyed by channel index) for the histogram in tiled mode,\n * where the layers have no full in-memory pixels. Refreshed on plot + slice change. */\n private readonly histSamples = new Map<number, Uint8Array>();\n /** Native-bit-depth histograms from `/histogram`, keyed `${z}|${channel}` (>8-bit images). */\n private readonly nativeHistograms = new Map<string, IHistogram>();\n\n private readonly stackLoading$ = new BehaviorSubject<boolean>(false);\n private readonly stackLoadingProgress$ = new BehaviorSubject<number>(0);\n private readonly autoscaleEvent$ = new Subject<unknown>();\n private readonly intensityProfile$ = new Subject<IntensityProfile[]>();\n private readonly viewportChange$ = new Subject<{\n x: number;\n y: number;\n width: number;\n height: number;\n }>();\n\n constructor(\n @Inject(TILE_ACCESS_PORT) private readonly tiles: TileAccessPort,\n store: VisualizerStore,\n regionStore: RegionStore,\n private readonly wandTool: WandToolService,\n private readonly brushTool: BrushToolService,\n private readonly eraserTool: VertexEraserToolService,\n private readonly zoomToBoxTool: ZoomToBoxToolService,\n private readonly samTool: SamToolService,\n private readonly samPointTool: SamPointToolService,\n private readonly cellSegmentTool: CellSegmentToolService,\n @Optional() @Inject(CELL_SEGMENTER) private readonly cellSegmenter: ICellSegmenter | null,\n private readonly simpleStack: SimpleSliceAccessService,\n @Inject(VIZ_CONFIG) config: VizConfig,\n ) {\n super(regionStore, store);\n this.api = config.slideCropServer;\n }\n\n /**\n * Fetch + cache the server pyramid descriptor (`GET /tiles/info`): the REAL per-level tile grid,\n * tile size, channel metadata and physical pixel size. The backend returns 202 while the source\n * is still caching, so we poll briefly. Cached per `infoB64`; returns null if it never becomes\n * ready (callers fall back to a single-tile fetch). This is the authoritative grid — guessing\n * level dims from `trueImageSize` overshoots the real grid and the server 400s out-of-range tiles.\n */\n private async ensureDescriptor(): Promise<TileDescriptor | null> {\n // Self-contained multi-slice stack (no tile server — e.g. a numbered image\n // series assembled client-side, each slice a different file): there is no\n // single server-tiled pyramid to describe. Returning null routes every\n // caller (2D image, volume, surface) to their stitched/single-fetch\n // fallback, which — via fetchSlice's own SimpleSliceAccessService branch —\n // correctly fetches each slice's own URL instead of one fixed file's tile\n // pyramid.\n if (this.simpleStack.isSimple(this.loaded?.imageInfo)) return null;\n const infoB64 = this.tiles.getSelectedInfoB64();\n if (!infoB64) return null;\n if (this.descriptor && this.descriptorKey === infoB64) return this.descriptor;\n const headers = await this.tiles\n .getAuthHeaders()\n .catch(() => ({}) as Record<string, string>);\n const url = `${this.api}tiles/info?info=${infoB64}`;\n const deadline = Date.now() + DESCRIPTOR_TIMEOUT_MS;\n for (;;) {\n try {\n const resp = await fetch(url, { headers });\n if (resp.status === 200) {\n const body = (await resp.json()) as TileDescriptor;\n if (body?.levels?.length) {\n this.descriptor = body;\n this.descriptorKey = infoB64;\n return body;\n }\n }\n // 202 (still caching) or empty body → re-poll until the deadline.\n } catch (err) {\n console.warn('[napari-js] tiles/info poll retry', err);\n }\n if (Date.now() > deadline) {\n console.warn('[napari-js] tiles/info not ready; falling back to single-tile fetch');\n return null;\n }\n await new Promise((r) => setTimeout(r, 1200));\n }\n }\n\n /**\n * Fetch a COMPLETE rendered slice as an `ImageBitmap` by stitching the server's REAL tile grid\n * (from `/tiles/info`) — not just the top-left tile, which only ever showed a large image's\n * corner. Picks the finest pyramid level whose grid fits `budgetTiles` and whose longest side is\n * within the GPU texture limit, fetches that grid concurrently, and stitches it into one canvas.\n *\n * `channel` selects a single band as grayscale (real levels only); omit for the server composite.\n * `budgetTiles` caps the grid: the 2D view uses the full budget for detail; the 3D volume passes\n * 1 for a cheap overview tile per slice (it downsamples to {@link VOLUME_MAX_SLICE}). Falls back\n * to a single `col=0,row=0` tile when no descriptor is available (small/simple images, volumes).\n */\n private async fetchSlice(\n z: number,\n channel?: number,\n budgetTiles: number = MAX_STITCH_TILES,\n /** When a specific channel has no pyramid level within `budgetTiles`, drop to the server\n * COMPOSITE overview instead of stitching the huge per-channel level. Only safe when the caller\n * wants a single decimated plane (the surface height): for a multichannel VOLUME every channel\n * would then fetch the same composite and the channels would collapse into one, so volume\n * assembly leaves this `false` to keep each band distinct. */\n allowCompositeFallback = false,\n ): Promise<ImageBitmap> {\n // Self-contained multi-slice stack (tiled:false): `z` indexes a completely\n // different file's own preview URL, not an internal slice of one server-\n // tiled file — resolved and fetched via SimpleSliceAccessService (shared\n // with OSD; see its docs for why this can't be a bare fetch()) instead of\n // building a /tile?info=...&z= request against whichever single file\n // getSelectedInfoB64() points at (which would 400/mismatch for any z\n // beyond that one file's own extent).\n const info = this.loaded?.imageInfo;\n if (this.simpleStack.isSimple(info)) {\n const url = this.simpleStack.urlFor(info as IImageInfo, z);\n if (!url) throw new Error(`[napari-js] no URL for slice ${z}`);\n return this.simpleStack.fetchAsBitmap(url);\n }\n const infoB64 = this.tiles.getSelectedInfoB64();\n if (!infoB64) throw new Error('[napari-js] no selected image info (getSelectedInfoB64 null)');\n const headers = await this.tiles\n .getAuthHeaders()\n .catch(() => ({}) as Record<string, string>);\n const desc = await this.ensureDescriptor();\n\n // The requested band; may be dropped to the composite (undefined) below when the channel has no\n // pyramid level small enough to stitch within budget.\n let effectiveChannel = channel;\n const fetchTile = async (\n res: number,\n col: number,\n row: number,\n t: number,\n ): Promise<ImageBitmap> => {\n const ch = effectiveChannel == null ? '' : `&channel=${effectiveChannel}`;\n const url = `${this.api}tile?info=${infoB64}&res=${res}&col=${col}&row=${row}&z=${z}&tileSize=${t}${ch}`;\n const resp = await fetch(url, { headers });\n if (!resp.ok) {\n throw new Error(`[napari-js] slice fetch failed: ${resp.status} (${col}/${row} res ${res})`);\n }\n return createImageBitmap(await resp.blob());\n };\n\n // No descriptor → single top-left tile (legacy fallback; correct for small/simple images).\n if (!desc || !desc.levels?.length) return fetchTile(0, 0, 0, TILE_SIZE);\n\n const t = desc.tileSize || TILE_SIZE;\n // Per-channel tiles exist ONLY at REAL Bio-Formats levels (the front of `levels`); the server\n // composite exists at every level, including the small overviews.\n const perChannelLevels = desc.realLevels ?? desc.levels.length;\n const usable =\n channel == null ? desc.levels : desc.levels.slice(0, Math.max(1, perChannelLevels));\n\n // Finest level whose stitched grid fits BOTH the tile budget and the GPU texture limit; if none\n // fits, the coarsest available (fits=false).\n const tilesFor = (lvl: TileLevel): number =>\n Math.max(1, Math.ceil(lvl.width / t)) * Math.max(1, Math.ceil(lvl.height / t));\n const pick = (levels: TileLevel[]): { lvl: TileLevel; fits: boolean } => {\n let c = levels[0];\n for (const lvl of levels) {\n c = lvl;\n if (tilesFor(lvl) <= budgetTiles && Math.max(lvl.width, lvl.height) <= MAX_TEXTURE_DIM) {\n return { lvl, fits: true };\n }\n }\n return { lvl: c, fits: false };\n };\n\n let sel = pick(usable);\n // A specific channel only has tiles at the (few, large) real levels. When none of them fit the\n // budget — e.g. the coarsest real level is still 14982×18670 → ~1100 full-res tiles — stitching\n // it per slice floods the server (504s) and stalls the load. The composite pyramid has small\n // overview levels, so fetch the composite instead and derive luminance from it. Every caller here\n // (surface height, volume assembly, readback) downscales the plane anyway, so a composite-derived\n // plane is the right trade for one that actually loads. Only kicks in when the channel can't fit.\n if (allowCompositeFallback && !sel.fits && channel != null && desc.levels.length > perChannelLevels) {\n const composite = pick(desc.levels);\n if (composite.fits || tilesFor(composite.lvl) < tilesFor(sel.lvl)) {\n effectiveChannel = undefined;\n sel = composite;\n console.warn(\n `[napari-js] channel ${channel} has no pyramid level within the ${budgetTiles}-tile ` +\n `budget; using the composite overview (res ${sel.lvl.res}, ${sel.lvl.width}×` +\n `${sel.lvl.height}) for this plane.`,\n );\n }\n }\n const chosen = sel.lvl;\n const cols = Math.max(1, Math.ceil(chosen.width / t));\n const rows = Math.max(1, Math.ceil(chosen.height / t));\n if (!sel.fits && budgetTiles === MAX_STITCH_TILES) {\n console.warn(\n `[napari-js] full resolution exceeds the ${budgetTiles}-tile/${MAX_TEXTURE_DIM}px budget; ` +\n `displaying overview level res ${chosen.res} (${chosen.width}×${chosen.height}).`,\n );\n }\n\n if (cols === 1 && rows === 1) return fetchTile(chosen.res, 0, 0, t);\n\n // Stitch into one level-sized canvas. Fetch the grid with BOUNDED concurrency: firing every tile\n // at once (a big grid = hundreds of requests) overwhelmed the tile server (504s). Edge tiles are\n // narrower/shorter; drawImage places each at its grid offset so partial tiles line up.\n const coords: Array<{ col: number; row: number }> = [];\n for (let row = 0; row < rows; row++) {\n for (let col = 0; col < cols; col++) coords.push({ col, row });\n }\n const tiles: Array<{ col: number; row: number; bmp: ImageBitmap }> = [];\n const stitchWorker = async (): Promise<void> => {\n for (;;) {\n const job = coords.shift();\n if (!job) return;\n const bmp = await fetchTile(chosen.res, job.col, job.row, t);\n tiles.push({ col: job.col, row: job.row, bmp });\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(TILE_FETCH_CONCURRENCY, coords.length) }, () => stitchWorker()),\n );\n\n let canvas: HTMLCanvasElement | OffscreenCanvas;\n if (typeof OffscreenCanvas !== 'undefined') {\n canvas = new OffscreenCanvas(chosen.width, chosen.height);\n } else {\n canvas = document.createElement('canvas');\n canvas.width = chosen.width;\n canvas.height = chosen.height;\n }\n const ctx = canvas.getContext('2d') as\n | CanvasRenderingContext2D\n | OffscreenCanvasRenderingContext2D\n | null;\n if (!ctx) throw new Error('[napari-js] slice stitch: 2D context unavailable');\n for (const { col, row, bmp } of tiles) {\n ctx.drawImage(bmp, col * t, row * t);\n bmp.close?.();\n }\n\n // Safety net: if the chosen level still exceeds the GPU texture limit (e.g. a multichannel\n // image whose coarsest REAL level is huge — overview levels are composite-only), downscale the\n // stitched canvas to fit so the WebGPU texture upload can't fail.\n const longest = Math.max(chosen.width, chosen.height);\n if (longest > MAX_TEXTURE_DIM) {\n const scale = MAX_TEXTURE_DIM / longest;\n const outW = Math.max(1, Math.floor(chosen.width * scale));\n const outH = Math.max(1, Math.floor(chosen.height * scale));\n console.warn(\n `[napari-js] stitched level ${chosen.width}×${chosen.height} exceeds the ` +\n `${MAX_TEXTURE_DIM}px texture limit; downscaling to ${outW}×${outH}.`,\n );\n let out: HTMLCanvasElement | OffscreenCanvas;\n if (typeof OffscreenCanvas !== 'undefined') {\n out = new OffscreenCanvas(outW, outH);\n } else {\n out = document.createElement('canvas');\n out.width = outW;\n out.height = outH;\n }\n const octx = out.getContext('2d') as\n | CanvasRenderingContext2D\n | OffscreenCanvasRenderingContext2D\n | null;\n if (!octx) throw new Error('[napari-js] slice downscale: 2D context unavailable');\n octx.drawImage(canvas as unknown as CanvasImageSource, 0, 0, outW, outH);\n return createImageBitmap(out as unknown as ImageBitmapSource);\n }\n return createImageBitmap(canvas as unknown as ImageBitmapSource);\n }\n\n // ── IDataRenderer: load / render / viewport ───────────────────────────────\n async load(imageInfo: IImageInfo, zIndex: number): Promise<NapariLoaded> {\n // Keeps SimpleSliceAccessService's blob cache in sync even when the user\n // switches backends (e.g. OSD Image → napari Volume) on the same file —\n // whichever backend loads a genuinely different file first evicts it.\n this.simpleStack.noteActiveFile(imageInfo.fileName);\n this.loaded = { imageInfo, z: zIndex, filename: imageInfo.fileName };\n return this.loaded;\n }\n\n async plot(\n plotDiv: string,\n imageLoaded: unknown,\n imageInfo: IImageInfo,\n screenHeight: number,\n plotType: PlotType,\n _inPlace?: boolean,\n ): Promise<boolean> {\n const host = document.getElementById(plotDiv);\n if (!host) {\n console.error(`[napari-js] plot target #${plotDiv} not found`);\n return false;\n }\n this.reset();\n this.host = host;\n this.plotDivId = plotDiv;\n this.currentPlotType = plotType;\n\n const canvas = document.createElement('canvas');\n canvas.style.display = 'block';\n canvas.style.width = '100%';\n canvas.style.height = screenHeight ? `${screenHeight}px` : '100%';\n host.appendChild(canvas);\n this.canvas = canvas;\n\n const info = (imageLoaded as NapariLoaded)?.imageInfo ?? imageInfo;\n const z = (imageLoaded as NapariLoaded)?.z ?? 0;\n\n try {\n const viewer = new Viewer({ canvas, background: { r: 0.07, g: 0.07, b: 0.09, a: 1 } });\n this.viewer = viewer;\n await viewer.ready;\n\n if (isNapariScatter(plotType)) {\n await this.mountScatter(viewer, z);\n } else if (isNapariScatter3d(plotType)) {\n await this.mountScatter3d(viewer, info);\n } else if (isNapariSurface(plotType)) {\n await this.mountSurface(viewer);\n } else if (isNapari3d(plotType)) {\n await this.mountVolume(viewer, info, plotType);\n } else {\n await this.renderImage(z);\n this.fitCameraSoon();\n this.subscribeDisplayState();\n this.installScaleBar();\n this.regionOverlay = new NapariRegionOverlay(host, viewer, this.regionStore);\n this.buildToolHosts();\n // Keep the pixel-tool readback (lastPixels) current as the view pans/zooms and tiled\n // levels load, so wand/brush/SAM sample the actually-displayed image (jit-ui#102).\n this.cameraReadbackOff = viewer.camera.changed.connect(() => this.armReadback());\n }\n this.scheduleReadback();\n return true;\n } catch (err) {\n console.error('[napari-js] plot failed:', err);\n return false;\n }\n }\n\n // ── Channels: per-channel composite, LUT, native histograms (jit-ui#102) ──────────────────\n\n /** The grayscale display colormap from the store selection (+reverse), defaulting to gray.\n * Maps the jit-ui store colormap node to a napari `Colormap` via the library's LUT factory;\n * the multichannel tint ramps are built inside {@link MultiChannelImageView} from each\n * channel's hex colour. */\n private grayscaleColormap(): Colormap | string {\n const value = (this.currentColormap as { data?: { value?: unknown } } | null)?.data?.value;\n const lut = value != null ? buildColormapLut(value, this.currentReverse) : null;\n if (lut) return colormapFromLut('gray-cmap', lut);\n return this.currentReverse\n ? colormapFromLut('gray-rev', [[255, 255, 255], [0, 0, 0]] as Rgb[])\n : 'gray';\n }\n\n /** Fetch a stitched slice and read it back as a single-channel uint8 plane. `channel` selects a\n * band (multichannel); omit it for the grayscale composite (all overview levels available, so a\n * large image picks a fitting downscaled level rather than only the full-res real level). */\n private async fetchChannelData(\n z: number,\n channel?: number,\n budgetTiles?: number,\n ): Promise<{ data: Uint8Array; width: number; height: number }> {\n const bmp = await this.fetchSlice(z, channel, budgetTiles);\n return this.bitmapToLuminance(bmp);\n }\n\n /** Decode an `ImageBitmap` (server bands are grayscale, R=G=B) to a single-channel uint8 plane.\n * `maxSide` caps the longest side (downscaling on the canvas draw) — used to keep pre-loaded\n * surface slice planes small. */\n private bitmapToLuminance(\n bmp: ImageBitmap,\n maxSide?: number,\n ): { data: Uint8Array; width: number; height: number } {\n const scale = maxSide ? Math.min(1, maxSide / Math.max(bmp.width, bmp.height, 1)) : 1;\n const w = Math.max(1, Math.round(bmp.width * scale));\n const h = Math.max(1, Math.round(bmp.height * scale));\n let canvas: HTMLCanvasElement | OffscreenCanvas;\n if (typeof OffscreenCanvas !== 'undefined') {\n canvas = new OffscreenCanvas(w, h);\n } else {\n canvas = document.createElement('canvas');\n canvas.width = w;\n canvas.height = h;\n }\n const ctx = canvas.getContext('2d') as\n | CanvasRenderingContext2D\n | OffscreenCanvasRenderingContext2D\n | null;\n if (!ctx) throw new Error('[napari-js] channel readback: 2D context unavailable');\n // Scale the WHOLE bitmap into the (possibly smaller) target canvas — drawing at natural size\n // would crop to the top-left w×h corner when downscaling a large slice (maxSide < bmp size).\n ctx.drawImage(bmp, 0, 0, w, h);\n bmp.close?.();\n const rgba = ctx.getImageData(0, 0, w, h).data;\n const data = new Uint8Array(w * h);\n for (let i = 0; i < w * h; i++) data[i] = rgba[i * 4];\n return { data, width: w, height: h };\n }\n\n /**\n * Render the 2D image for slice `z`. With a server pyramid descriptor we use a pyramidal\n * {@link TiledSource} per layer so the view refines to higher resolution on zoom (like OSD) and\n * sits naturally in full-resolution coordinates; without one we fall back to the single-level\n * stitch. Three display modes either way: multichannel additive tint, grayscale colormap, RGB.\n */\n private async renderImage(z: number, token?: number): Promise<void> {\n const v = this.viewer;\n if (!v) return;\n const desc = await this.ensureDescriptor();\n if (desc && desc.levels?.length) {\n if (token != null && token !== this.sliceReq) return;\n await this.renderImageTiled(z, desc);\n return;\n }\n return this.renderImageStitched(z, token);\n }\n\n /** Single-level stitch fallback (no descriptor): the pre-tiling path. */\n private async renderImageStitched(z: number, token?: number): Promise<void> {\n const v = this.viewer;\n if (!v) return;\n const desc = await this.ensureDescriptor();\n const states = this.store.currentChannelStates();\n const channelCount = desc?.channels ?? (states.length || 1);\n const multichannel = !!desc?.multichannel && channelCount > 1;\n\n // 1) Fetch all pixel data BEFORE touching the viewer, so a superseded scrub can bail without\n // having torn down the visible layers (avoids flicker / out-of-order layer state).\n let mode: 'grayscale' | 'multichannel' | 'rgb';\n let planes: Array<{ data: Uint8Array; width: number; height: number }> = [];\n let bitmap: ImageBitmap | null = null;\n if (multichannel) {\n mode = 'multichannel';\n planes = await Promise.all(\n Array.from({ length: channelCount }, (_, c) => this.fetchChannelData(z, c)),\n );\n } else if (channelCount === 1) {\n mode = 'grayscale';\n // Composite fetch (no channel) → all overview levels usable, so a large grayscale image\n // selects a fitting downscaled level instead of the full-res real level (texture limit).\n planes = [await this.fetchChannelData(z)];\n } else {\n mode = 'rgb';\n bitmap = await this.fetchSlice(z);\n }\n\n // 2) Commit — unless a newer scrub superseded us or the viewer was torn down.\n if ((token != null && token !== this.sliceReq) || this.viewer !== v) {\n bitmap?.close?.();\n return;\n }\n\n // The displayed texture may be a downscaled pyramid level; scale the layer into FULL-RESOLUTION\n // world coordinates (level-0 pixels) so the camera, readback and — critically — pre-saved\n // regions (stored in full-res coords, e.g. ndpi) all line up regardless of which level is shown.\n // This mirrors OSD, whose coordinate system is always level 0.\n const texW = mode === 'rgb' ? (bitmap as ImageBitmap).width : planes[0]?.width ?? 0;\n const texH = mode === 'rgb' ? (bitmap as ImageBitmap).height : planes[0]?.height ?? 0;\n const fullW = desc?.width || texW || 1;\n const fullH = desc?.height || texH || 1;\n const scale: [number, number] = [texW ? fullW / texW : 1, texH ? fullH / texH : 1];\n\n this.imageMode = mode;\n const interpolation: 'linear' | 'nearest' = this.imageSmoothing ? 'linear' : 'nearest';\n this.channelView = new MultiChannelImageView(v);\n if (mode === 'multichannel') {\n const views: ChannelView[] = planes.map((d, c) => {\n const st = states.find((s) => s.index === c);\n const color = st?.color ?? desc?.channelInfo?.[c]?.color ?? tintFor(c);\n return {\n source: { kind: 'typed', width: d.width, height: d.height, channels: 1, dtype: 'uint8', data: d.data },\n tint: color,\n name: st?.name ?? `ch${c}`,\n contrastLimits: [st?.min ?? 0, st?.max ?? 255],\n gamma: st?.gamma ?? 1,\n visible: st?.visible ?? true,\n invert: this.invertEnabled,\n scale,\n };\n });\n this.channelView.render('multichannel', views, { interpolation });\n } else if (mode === 'grayscale') {\n const d = planes[0];\n const st = states[0];\n this.channelView.render(\n 'grayscale',\n [\n {\n source: { kind: 'typed', width: d.width, height: d.height, channels: 1, dtype: 'uint8', data: d.data },\n colormap: this.grayscaleColormap(),\n contrastLimits: [st?.min ?? 0, st?.max ?? 255],\n gamma: st?.gamma ?? 1,\n invert: this.invertEnabled,\n scale,\n },\n ],\n { interpolation },\n );\n } else {\n this.channelView.render('rgb', [{ source: bitmap as ImageBitmap, scale }], { interpolation });\n }\n this.imageW = fullW;\n this.imageH = fullH;\n }\n\n /**\n * Render the 2D image with pyramidal {@link TiledSource}s — the view refines to higher resolution\n * as you zoom in (the visual fetches the level whose texels ≈ screen pixels) and sits in full-res\n * coordinates so regions align. Same three modes as the stitch path. Per-channel layers use the\n * REAL pyramid levels (per-channel tiles only exist there); the composite uses all levels.\n */\n private async renderImageTiled(z: number, desc: TileDescriptor): Promise<void> {\n const v = this.viewer;\n if (!v) return;\n const states = this.store.currentChannelStates();\n const channelCount = desc.channels ?? (states.length || 1);\n const multichannel = !!desc.multichannel && channelCount > 1;\n const interpolation: 'linear' | 'nearest' = this.imageSmoothing ? 'linear' : 'nearest';\n\n this.tiled = true;\n this.channelView = new MultiChannelImageView(v);\n\n if (multichannel) {\n this.imageMode = 'multichannel';\n const views: ChannelView[] = [];\n for (let c = 0; c < channelCount; c++) {\n const st = states.find((s) => s.index === c);\n const color = st?.color ?? desc.channelInfo?.[c]?.color ?? tintFor(c);\n views.push({\n source: this.buildTiledSource(desc, c, 1),\n tint: color,\n name: st?.name ?? `ch${c}`,\n contrastLimits: [st?.min ?? 0, st?.max ?? 255],\n gamma: st?.gamma ?? 1,\n visible: st?.visible ?? true,\n invert: this.invertEnabled,\n });\n }\n this.channelView.render('multichannel', views, { interpolation });\n } else if (channelCount === 1) {\n this.imageMode = 'grayscale';\n const st = states[0];\n this.channelView.render(\n 'grayscale',\n [\n {\n source: this.buildTiledSource(desc, undefined, 1),\n colormap: this.grayscaleColormap(),\n contrastLimits: [st?.min ?? 0, st?.max ?? 255],\n gamma: st?.gamma ?? 1,\n invert: this.invertEnabled,\n },\n ],\n { interpolation },\n );\n } else {\n this.imageMode = 'rgb';\n this.channelView.render('rgb', [{ source: this.buildTiledSource(desc, undefined, 4) }], {\n interpolation,\n });\n }\n this.imageW = desc.width;\n this.imageH = desc.height;\n // Await on the initial render so getHistogram/autoContrast have data immediately; slice changes\n // refresh fire-and-forget (the histogram pane retries).\n await this.refreshHistogramSamples(z, desc);\n }\n\n /** Build a pyramidal TiledSource backed by the server `/tile` endpoint. `channel` selects a band\n * (grayscale luminance, real levels only); omit it for the composite (RGBA, all levels). */\n private buildTiledSource(\n desc: TileDescriptor,\n channel: number | undefined,\n channels: 1 | 4,\n ): TiledSource {\n const infoB64 = this.tiles.getSelectedInfoB64() ?? '';\n // Per-channel tiles exist only at REAL Bio-Formats levels; the composite exists at all levels.\n const usable =\n channel == null\n ? desc.levels\n : desc.levels.slice(0, Math.max(1, desc.realLevels ?? desc.levels.length));\n const levelScales = usable.map((l) => desc.width / Math.max(1, l.width)); // level-0 px per level px\n const tileSize = desc.tileSize || TILE_SIZE;\n const ch = channel == null ? '' : `&channel=${channel}`;\n const api = this.api;\n return {\n kind: 'tiled',\n width: desc.width,\n height: desc.height,\n tileSize,\n levels: usable.length,\n levelScales,\n depth: Math.max(1, desc.z || 1),\n channels,\n dtype: 'uint8',\n fetchTile: async (key: TileKey): Promise<PixelChunk> => {\n const res = usable[key.level]?.res ?? key.level;\n const url = `${api}tile?info=${infoB64}&res=${res}&col=${key.col}&row=${key.row}&z=${key.z}&tileSize=${tileSize}${ch}`;\n const headers = await this.tiles\n .getAuthHeaders()\n .catch(() => ({}) as Record<string, string>);\n const resp = await fetch(url, { headers });\n if (!resp.ok) {\n throw new Error(`[napari-js] tile ${key.level}/${key.col}/${key.row} → ${resp.status}`);\n }\n const bmp = await createImageBitmap(await resp.blob());\n if (channels === 4) return { width: bmp.width, height: bmp.height, data: bmp };\n return this.bitmapToLuminance(bmp);\n },\n };\n }\n\n /** (Re)fetch a coarse per-channel luminance sample for the histogram (tiled mode has no full\n * in-memory pixels). One cheap overview tile per channel; cached by channel index. */\n private async refreshHistogramSamples(z: number, desc: TileDescriptor): Promise<void> {\n this.histSamples.clear();\n if (this.imageMode === 'rgb') return; // RGB uses the displayed-pixel readback (rgbHistogram)\n const channelCount = this.imageMode === 'multichannel' ? desc.channels ?? 1 : 1;\n for (let c = 0; c < channelCount; c++) {\n try {\n const ch = this.imageMode === 'multichannel' ? c : undefined;\n const d = await this.fetchChannelData(z, ch, 1); // budget 1 → coarsest single tile\n this.histSamples.set(c, d.data);\n } catch {\n /* leave this channel's sample unset */\n }\n }\n }\n\n /** Subscribe channel states + grayscale colormap → live-apply to the rendered layers (no\n * re-fetch; only z changes re-fetch). Replaces any prior subscription. */\n private subscribeDisplayState(): void {\n this.displaySub?.unsubscribe();\n this.displaySub = combineLatest([\n this.store.getChannelStates(),\n this.store.getColormap(),\n this.store.getReverseScale(),\n this.store.getInvert(),\n ]).subscribe(([channels, colormap, reverse, invert]) => {\n this.currentColormap = (colormap as ColormapNode) ?? null;\n this.currentReverse = reverse;\n this.invertEnabled = invert;\n this.applyDisplayState(channels);\n });\n }\n\n /** Subscribe the store colormap (+reverse), invert, and channel state → the volume/isosurface\n * transfer function: colour (channel tint or selected colormap), the intensity **window\n * (min/max → contrastLimits)** and **gamma**, mirroring the grayscale image's display controls\n * so the histogram pane drives the 3D render. Replaces any prior subscription. */\n private subscribeVolumeDisplayState(): void {\n this.displaySub?.unsubscribe();\n this.displaySub = combineLatest([\n this.store.getColormap(),\n this.store.getReverseScale(),\n this.store.getInvert(),\n this.store.getChannelStates(),\n ]).subscribe(([colormap, reverse, invert, channels]) => {\n this.currentColormap = (colormap as ColormapNode) ?? null;\n this.currentReverse = reverse;\n this.invertEnabled = invert;\n const view = this.volumeView;\n if (!view) return;\n if (this.volumeMultichannel) {\n // Each channel's layer is tinted by its colour and gets its own window/gamma/visibility.\n view.layers.forEach((_, c) => {\n const st = channels.find((s) => s.index === c);\n view.updateChannel(c, {\n colormap: this.channelTintColormap(st?.color ?? '#ffffff'),\n ...(st\n ? {\n contrastLimits: [st.min, st.max] as [number, number],\n gamma: st.gamma,\n visible: st.visible,\n }\n : {}),\n });\n });\n } else {\n const st = channels[0];\n view.updateChannel(0, {\n colormap: this.volumeColormap(st),\n ...(st ? { contrastLimits: [st.min, st.max] as [number, number], gamma: st.gamma } : {}),\n });\n }\n });\n }\n\n /** A channel's tint colormap (black→colour) with reverse-scale / invert applied by flipping. */\n private channelTintColormap(color: string): Colormap | string {\n let cmap: Colormap | string = tintColormap(color);\n if (this.currentReverse) cmap = reverseColormap(cmap);\n if (this.invertEnabled) cmap = reverseColormap(cmap);\n return cmap;\n }\n\n /**\n * Colour map for the volume/isosurface. A real colormap selection (viridis/magma/…) wins;\n * otherwise the channel's colour tints it (so the channel-dialog colour swatch recolors the 3D\n * render). Reverse-scale and invert each flip the ramp — the `VolumeLayer` has no per-layer\n * invert, so both are emulated by reversing the colormap.\n */\n private volumeColormap(st: IChannelState | undefined): Colormap | string {\n const node = this.currentColormap as { label?: string; data?: { value?: unknown } } | null;\n // A colored colormap (viridis/magma/…) drives the volume; the default grayscale family\n // (gray / Greys / Greys Inv) yields to the channel's colour so the dialog colour swatch\n // recolors the 3D render.\n const label = (node?.label ?? '').toLowerCase();\n const grayFamily = label === '' || label.includes('grey') || label.includes('gray');\n const value = node?.data?.value;\n const lut = !grayFamily && value != null ? buildColormapLut(value, false) : null;\n let cmap: Colormap | string = lut\n ? colormapFromLut('vol-cmap', lut)\n : tintColormap(st?.color ?? '#ffffff');\n // Reverse-scale and invert each flip the ramp (the VolumeLayer has no per-layer invert).\n if (this.currentReverse) cmap = reverseColormap(cmap);\n if (this.invertEnabled) cmap = reverseColormap(cmap);\n return cmap;\n }\n\n /** Apply the current channel states / colormap to the live layers (no re-fetch), delegating the\n * per-channel layer mutations to the {@link MultiChannelImageView}. */\n private applyDisplayState(channels: IChannelState[]): void {\n const view = this.channelView;\n if (!this.viewer || !view) return;\n if (this.imageMode === 'multichannel') {\n view.layers.forEach((_, c) => {\n const st = channels.find((s) => s.index === c);\n if (!st) return;\n view.updateChannel(c, {\n tint: st.color,\n contrastLimits: [st.min, st.max],\n gamma: st.gamma,\n visible: st.visible,\n invert: this.invertEnabled,\n });\n });\n } else if (this.imageMode === 'grayscale') {\n const st = channels[0];\n view.updateChannel(0, {\n colormap: this.grayscaleColormap(),\n invert: this.invertEnabled,\n ...(st ? { contrastLimits: [st.min, st.max] as [number, number], gamma: st.gamma } : {}),\n });\n }\n }\n\n /** (Re)install the physical scale bar over the 2D image, sized from the image's µm/pixel\n * (`/tiles/info` mppX, falling back to the image metadata). No-op without a physical size. */\n private installScaleBar(): void {\n this.scaleBar?.destroy();\n this.scaleBar = null;\n const mppX = this.descriptor?.mppX || this.loaded?.imageInfo.imageMeta?.[0]?.mppX || 0;\n if (this.viewer && this.host && mppX > 0) {\n this.scaleBar = new NapariScaleBar(this.host, this.viewer.camera, mppX);\n }\n }\n\n /** Convert a napari-js `Histogram` (bin count + min/max) to the pane's `IHistogram` (bin edges). */\n private toIHistogram(h: { counts: Uint32Array; bins: number; min: number; max: number }): IHistogram {\n const span = h.max - h.min || 1;\n const bins = Array.from({ length: h.bins }, (_, i) => h.min + (i * span) / h.bins);\n const counts = Array.from(h.counts);\n return { bins, counts, max: counts.reduce((m, c) => (c > m ? c : m), 0) };\n }\n\n /**\n * Mount the 3D volume/isosurface. A multichannel image becomes one additive, tinted\n * {@link VolumeLayer} per channel (so each channel's colour composites into the render); a\n * grayscale/composite image uses a single volume. Adds the axes gizmo + labels and wires the\n * display-state subscription. The caller owns `viewer.ready`.\n */\n private async mountVolume(\n viewer: Viewer,\n info: IImageInfo | undefined,\n plotType: PlotType,\n ): Promise<void> {\n const token = this.loadToken; // bail before rendering if a Cancel / new plot bumps this\n const desc = await this.ensureDescriptor();\n const channelCount = desc?.channels ?? 1;\n const multichannel = !!desc?.multichannel && channelCount > 1;\n const res = volumeResolutionFor(this.resolutionScale);\n const rendering: 'iso' | 'mip' = isNapariIsosurface(plotType) ? 'iso' : 'mip';\n const states = this.store.currentChannelStates();\n\n this.volumeChannelData.clear();\n this.volumeMultichannel = multichannel;\n this.imageMode = multichannel ? 'multichannel' : 'grayscale';\n const view = new MultiChannelVolumeView(viewer);\n this.volumeView = view;\n\n // Assemble per-channel scalar volumes from the server tiles (jit-specific); the napari-js view\n // owns the layer orchestration (one additive tinted volume per channel, or a single grayscale\n // volume). The adapter computes each channel's colormap (incl. invert/reverse flips).\n let dims: { width: number; height: number; depth: number } | null = null;\n const channels: VolumeChannel[] = [];\n this.stackLoading$.next(true);\n this.stackLoadingProgress$.next(0);\n try {\n if (multichannel) {\n for (let c = 0; c < channelCount; c++) {\n const vol = await this.assembleVolume(info, res, c);\n if (!vol) continue;\n dims = vol;\n this.volumeChannelData.set(c, vol.data);\n const st = states.find((s) => s.index === c);\n const color = st?.color ?? desc?.channelInfo?.[c]?.color ?? tintFor(c);\n channels.push({\n data: vol.data,\n width: vol.width,\n height: vol.height,\n depth: vol.depth,\n colormap: this.channelTintColormap(color),\n contrastLimits: [st?.min ?? 0, st?.max ?? 255],\n gamma: st?.gamma ?? 1,\n visible: st?.visible ?? true,\n });\n }\n } else {\n const vol = await this.assembleVolume(info, res);\n if (vol) {\n dims = vol;\n this.volumeChannelData.set(0, vol.data);\n const st = states[0];\n channels.push({\n data: vol.data,\n width: vol.width,\n height: vol.height,\n depth: vol.depth,\n colormap: this.volumeColormap(st),\n contrastLimits: [st?.min ?? 0, st?.max ?? 255],\n gamma: st?.gamma ?? 1,\n });\n }\n }\n } finally {\n this.stackLoading$.next(false);\n this.stackLoadingProgress$.next(0);\n }\n\n if (!dims || !channels.length || this.loadToken !== token) return; // cancelled → don't render\n\n // Resolution-invariant world box. Sizing the box by the sampled voxel counts made higher\n // in-plane resolution grow X/Y while the depth stayed the (constant) slice count — so Z appeared\n // to shrink at higher resolution. Instead anchor the in-plane long side to a fixed reference and\n // let Z span the full slice count; the box shape is then identical at every decimate factor. The\n // per-axis `voxelSize` (napari `scale`) maps the sampled grid onto that fixed world box.\n const fullW = this.descriptor?.width ?? dims.width;\n const fullH = this.descriptor?.height ?? dims.height;\n const fullD =\n this.loaded?.imageInfo.imageMeta?.[0]?.z || this.loaded?.imageInfo.urls?.length || dims.depth;\n const fullLong = Math.max(1, fullW, fullH);\n const world = {\n width: (fullW * VOLUME_WORLD_INPLANE_REF) / fullLong,\n height: (fullH * VOLUME_WORLD_INPLANE_REF) / fullLong,\n depth: fullD,\n };\n // Base box (Z-scale = 1) + the sampled depth drive the live Z-height handle below; the persisted\n // `volumeZScale` (user drag) applies on top so changing resolution keeps the chosen height.\n this.volumeWorldBase = world;\n this.volumeSampledDepth = Math.max(1, dims.depth);\n const worldZ = world.depth * this.volumeZScale;\n const voxelSize: [number, number, number] = [\n world.width / dims.width,\n world.height / dims.height,\n worldZ / this.volumeSampledDepth,\n ];\n for (const ch of channels) ch.voxelSize = voxelSize;\n\n view.render(multichannel ? 'multichannel' : 'grayscale', channels, { rendering });\n this.imageW = dims.width;\n this.imageH = dims.height;\n this.volumeDims = dims;\n\n // 3D coordinate-axes / scale gizmo + labels, sharing the volume's world box so the gizmo tracks\n // the rendered proportions. Physical scale text still comes from the FULL image extent.\n const mppX = this.descriptor?.mppX || this.loaded?.imageInfo.imageMeta?.[0]?.mppX || 0;\n this.axesLayer = viewer.addAxes(world.width, world.height, worldZ, { visible: this.axesVisible });\n if (this.host) {\n this.axesLabels = new NapariAxesLabels(\n this.host,\n viewer.camera3d,\n this.buildAxesLabels({ width: world.width, height: world.height, depth: worldZ }, mppX),\n );\n this.axesLabels.setVisible(this.axesVisible);\n // In-view drag handle at the TOP END OF THE Z AXIS (the box's min-XY corner, where the blue\n // \"Z\" axis + label live), so it reads as the Z-height control. Floated a little past the axis\n // tip (×1.12) so the grip clears the \"Z · …\" label. Drag ↕ to restretch Z live.\n this.zHandle = new NapariVolumeZHandle(this.host, viewer.camera3d, {\n topAnchor: () => [\n -this.volumeWorldBase!.width / 2,\n -this.volumeWorldBase!.height / 2,\n ((this.volumeWorldBase!.depth * this.volumeZScale) / 2) * 1.12,\n ],\n getScale: () => this.volumeZScale,\n setScale: (s) => this.setVolumeZScale(s),\n });\n }\n this.subscribeVolumeDisplayState();\n }\n\n /**\n * Restretch the volume's Z height live (driven by the in-view {@link NapariVolumeZHandle}). Only\n * the per-axis `voxelSize` / axes depth change — the voxel textures are untouched — so dragging is\n * smooth. `factor` is relative to the volume's natural proportions (1). Persists across re-mounts\n * (resolution changes) so the chosen height sticks.\n */\n private setVolumeZScale(factor: number): void {\n this.volumeZScale = Math.min(10, Math.max(0.1, factor));\n const base = this.volumeWorldBase;\n if (!base || !this.volumeView) return;\n const worldZ = base.depth * this.volumeZScale;\n const vsZ = worldZ / this.volumeSampledDepth;\n for (const layer of this.volumeView.layers) {\n const [sx, sy] = layer.voxelSize;\n layer.voxelSize = [sx, sy, vsZ];\n }\n if (this.axesLayer) this.axesLayer.depth = worldZ;\n const mppX = this.descriptor?.mppX || this.loaded?.imageInfo.imageMeta?.[0]?.mppX || 0;\n this.axesLabels?.updateAnchors(\n this.buildAxesLabels({ width: base.width, height: base.height, depth: worldZ }, mppX),\n );\n this.zHandle?.reposition();\n this.viewer?.requestRender();\n }\n\n /** Build the X/Y/Z axis-end label specs for the 3D gizmo. Anchors are in the volume's centred\n * world box (matching the AxesLayer geometry); the scale text reflects the FULL image extent —\n * physical µm when µm/pixel is known, else pixel (X/Y) / slice (Z) counts. */\n private buildAxesLabels(\n vol: { width: number; height: number; depth: number },\n mppX: number,\n ): AxisLabelSpec[] {\n const hx = vol.width / 2;\n const hy = vol.height / 2;\n const hz = vol.depth / 2;\n const descW = this.descriptor?.width ?? vol.width;\n const descH = this.descriptor?.height ?? vol.height;\n const slices =\n this.loaded?.imageInfo.imageMeta?.[0]?.z || this.loaded?.imageInfo.urls?.length || vol.depth;\n const len = (px: number): string => (mppX > 0 ? formatUm(px * mppX) : `${px} px`);\n return [\n { anchor: [hx, -hy, -hz], text: `X · ${len(descW)}`, color: '#ed4545' },\n { anchor: [-hx, hy, -hz], text: `Y · ${len(descH)}`, color: '#4dd959' },\n { anchor: [-hx, -hy, hz], text: `Z · ${slices} px`, color: '#668cff' },\n ];\n }\n\n /**\n * Assemble a downsampled uint8 volume (luminance) from the per-slice tile endpoint. Slices are\n * fetched with bounded concurrency (keeps the connection pool full without flooding it on a deep\n * stack) and read into the volume as each arrives, driving {@link stackLoadingProgress$} so the\n * host shows a determinate progress bar instead of a bare spinner.\n */\n private async assembleVolume(\n info: IImageInfo | undefined,\n opts: { maxSlice?: number; sliceStep?: number } = {},\n channel?: number,\n ): Promise<{ data: Uint8Array; width: number; height: number; depth: number } | null> {\n const token = this.loadToken; // bail if a Cancel / new plot bumps this while we fetch\n const fullDepth = info?.imageMeta?.[0]?.z || info?.urls?.length || 1;\n if (fullDepth < 1) {\n console.warn('[napari-js] no slices to assemble a volume');\n return null;\n }\n const step = Math.max(1, Math.floor(opts.sliceStep ?? 1));\n const maxSlice = opts.maxSlice ?? VOLUME_MAX_SLICE;\n // Source-slice indices sampled into the volume (every `step`th plane → low-res is faster).\n const zIndices: number[] = [];\n for (let z = 0; z < fullDepth; z += step) zIndices.push(z);\n const depth = zIndices.length;\n\n this.stackLoadingProgress$.next(0);\n try {\n // Fetch each slice at a pyramid level matching `maxSlice` (budget scales with the decimate\n // factor), so a higher factor pulls a finer level → more real in-plane detail; then downsample\n // to `maxSlice`. `channel` selects a band (multichannel volume); omit for the grayscale\n // composite. The caller owns the stackLoading flag (multichannel assembles channels in turn).\n const budget = this.tileBudgetFor(maxSlice);\n const first = await this.fetchSlice(zIndices[0], channel, budget);\n const scale = Math.min(1, maxSlice / Math.max(first.width, first.height, 1));\n const width = Math.max(1, Math.round(first.width * scale));\n const height = Math.max(1, Math.round(first.height * scale));\n const data = new Uint8Array(width * height * depth);\n\n let canvas: HTMLCanvasElement | OffscreenCanvas;\n if (typeof OffscreenCanvas !== 'undefined') {\n canvas = new OffscreenCanvas(width, height);\n } else {\n canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n }\n const ctx = canvas.getContext('2d') as\n | CanvasRenderingContext2D\n | OffscreenCanvasRenderingContext2D\n | null;\n if (!ctx) throw new Error('napari-js volume assembly: 2D context unavailable');\n\n // Read one fetched slice bitmap into the volume plane `z` (luminance). Synchronous between\n // awaits, so the shared 2D context is safe to reuse across the concurrent fetch workers.\n let done = 0;\n const readSlice = (z: number, bmp: ImageBitmap): void => {\n ctx.clearRect(0, 0, width, height);\n ctx.drawImage(bmp, 0, 0, width, height);\n const rgba = ctx.getImageData(0, 0, width, height).data;\n const base = z * width * height;\n for (let i = 0; i < width * height; i++) {\n data[base + i] =\n (rgba[i * 4] * 0.299 + rgba[i * 4 + 1] * 0.587 + rgba[i * 4 + 2] * 0.114) | 0;\n }\n bmp.close?.();\n done++;\n this.stackLoadingProgress$.next(Math.round((done / depth) * 100));\n };\n\n readSlice(0, first);\n\n // Remaining planes via a small pool of workers draining a shared queue. Each plane `p`\n // maps to source slice `zIndices[p]` (subsampled for low-res).\n const pending: number[] = [];\n for (let p = 1; p < depth; p++) pending.push(p);\n const worker = async (): Promise<void> => {\n for (;;) {\n const p = pending.shift();\n if (p === undefined || this.loadToken !== token) return;\n readSlice(p, await this.fetchSlice(zIndices[p], channel, budget));\n }\n };\n const poolSize = Math.min(VOLUME_FETCH_CONCURRENCY, Math.max(1, depth - 1));\n await Promise.all(Array.from({ length: poolSize }, () => worker()));\n\n if (this.loadToken !== token) return null; // cancelled → don't render a partial volume\n return { data, width, height, depth };\n } finally {\n this.stackLoadingProgress$.next(0);\n }\n }\n\n /**\n * Mount the NAPARI_SCATTER 2D scatter: the slice image with a points layer at each region's\n * centroid (napari-js analog of Plotly's region-centroid scatter). Rebuilds the points live as\n * regions change.\n */\n private async mountScatter(viewer: Viewer, z: number): Promise<void> {\n await this.renderImage(z);\n this.fitCameraSoon();\n this.subscribeDisplayState();\n this.installScaleBar();\n this.rebuildScatterPoints();\n this.scatterRegionSub = this.regionStore\n .getRegionUpdateEvent()\n .subscribe(() => this.rebuildScatterPoints());\n this.scheduleReadback();\n }\n\n /** (Re)build the 2D scatter's point layer at the current region centroids. */\n private rebuildScatterPoints(): void {\n const v = this.viewer;\n if (!v) return;\n if (this.scatter2dPoints) {\n v.layers.remove(this.scatter2dPoints);\n this.scatter2dPoints = null;\n }\n const centroids = this.regionCentroids();\n if (centroids.length === 0) return;\n this.scatter2dPoints = v.addPoints(centroids, {\n size: 12,\n faceColor: [1, 0.85, 0.2, 1],\n borderColor: [0, 0, 0, 1],\n borderWidth: 2,\n });\n }\n\n /** Region centroids as flat `[x, y, …]` data coords (rectangle / polygon / multipolygon). */\n private regionCentroids(): Float32Array {\n const out: number[] = [];\n const polyCentroid = (xs: number[], ys: number[]): void => {\n const n = xs.length;\n if (n === 0) return;\n let cx = 0;\n let cy = 0;\n for (let i = 0; i < n; i++) {\n cx += xs[i];\n cy += ys[i];\n }\n out.push(cx / n, cy / n);\n };\n for (const r of this.regionStore.getRegions()) {\n const b = r.bounds as\n | { x: number; y: number; width: number; height: number }\n | { xpoints: number[]; ypoints: number[] }\n | { polygons: { xpoints: number[]; ypoints: number[] }[] }\n | null\n | undefined;\n if (!b) continue;\n if ('width' in b && 'x' in b) {\n out.push(b.x + b.width / 2, b.y + b.height / 2);\n } else if ('xpoints' in b) {\n polyCentroid(b.xpoints, b.ypoints);\n } else if ('polygons' in b) {\n for (const p of b.polygons) polyCentroid(p.xpoints, p.ypoints);\n }\n }\n return new Float32Array(out);\n }\n\n /**\n * Mount the NAPARI_SCATTER3D 3D scatter: the downsampled voxel grid as a 3D point cloud colored\n * by intensity (napari-js analog of Plotly's voxel scatter3d). Assembles a coarse volume, then\n * emits a flat-strided sample of voxels (capped at {@link SCATTER3D_MAX_POINTS}) via `addPoints3D`.\n */\n private async mountScatter3d(viewer: Viewer, info: IImageInfo | undefined): Promise<void> {\n this.imageMode = 'grayscale';\n this.volumeMultichannel = false;\n const res = volumeResolutionFor(this.resolutionScale);\n this.stackLoading$.next(true);\n this.stackLoadingProgress$.next(0);\n let vol: { data: Uint8Array; width: number; height: number; depth: number } | null = null;\n try {\n vol = await this.assembleVolume(info, {\n maxSlice: Math.min(res.maxSlice, SCATTER3D_MAX_XY),\n sliceStep: res.sliceStep,\n });\n } finally {\n this.stackLoading$.next(false);\n this.stackLoadingProgress$.next(0);\n }\n if (!vol || this.viewer !== viewer) return;\n\n const { data, width, height, depth } = vol;\n const zScale = Math.max(width, height) / Math.max(1, depth); // ≈ cubic aspect\n const total = width * height * depth;\n const stride = Math.max(1, Math.ceil(total / SCATTER3D_MAX_POINTS));\n const pos: number[] = [];\n const val: number[] = [];\n for (let i = 0; i < total; i += stride) {\n const x = i % width;\n const y = Math.floor(i / width) % height;\n const zi = Math.floor(i / (width * height));\n pos.push(x, y, zi * zScale);\n val.push(data[i]);\n }\n\n const st = this.store.currentChannelStates()[0];\n this.scatter3dLayer = viewer.addPoints3D(new Float32Array(pos), new Float32Array(val), {\n colormap: this.volumeColormap(st),\n contrastLimits: [st?.min ?? 0, st?.max ?? 255],\n size: 3,\n });\n this.imageW = width;\n this.imageH = height;\n this.volumeDims = { width, height, depth };\n // Feed the intensity histogram from the assembled volume (key 0).\n this.volumeChannelData.clear();\n this.volumeChannelData.set(0, data);\n this.subscribeScatter3dDisplayState();\n this.scheduleReadback();\n }\n\n /** Store colormap / reverse / invert / channel window → the 3D scatter's colormap + contrast. */\n private subscribeScatter3dDisplayState(): void {\n this.displaySub?.unsubscribe();\n this.displaySub = combineLatest([\n this.store.getColormap(),\n this.store.getReverseScale(),\n this.store.getInvert(),\n this.store.getChannelStates(),\n ]).subscribe(([colormap, reverse, invert, channels]) => {\n this.currentColormap = (colormap as ColormapNode) ?? null;\n this.currentReverse = reverse;\n this.invertEnabled = invert;\n const layer = this.scatter3dLayer;\n if (!layer) return;\n const st = channels[0];\n layer.colormap = this.volumeColormap(st);\n if (st) layer.contrastLimits = [st.min, st.max];\n this.viewer?.requestRender();\n });\n }\n\n /**\n * Mount the NAPARI_SURFACE height-field surface. A height field is single-scalar, so for a\n * multichannel image the surface follows ONE band — the first visible channel (fallback 0) —\n * coloured by that channel's window/colormap (like the Plotly SURFACE, which is grayscale-only).\n * Pre-loads every slice's height data with a progress bar (as the volume does) so the stack\n * slider re-slices instantly, then builds the mesh for the current slice. All mesh + GPU work\n * lives in napari-js (`heightField` + `Viewer.addSurface`); this backend supplies scalar slices.\n */\n private async mountSurface(viewer: Viewer): Promise<void> {\n const desc = await this.ensureDescriptor();\n const multichannel = !!desc?.multichannel && (desc?.channels ?? 1) > 1;\n const states = this.store.currentChannelStates();\n this.surfaceChannel = multichannel ? states.find((s) => s.visible)?.index ?? 0 : undefined;\n this.surfaceMaxGrid = surfaceResolutionFor(this.resolutionScale).maxGrid;\n this.imageMode = 'grayscale';\n this.volumeMultichannel = false;\n await this.preloadSurfacePlanes(viewer);\n if (this.viewer !== viewer) return;\n await this.buildSurface(viewer, this.loaded?.z ?? 0);\n this.installSurfaceAxes(viewer);\n // Subscribe after the first build so display-state edits target a live layer.\n this.subscribeSurfaceDisplayState();\n }\n\n /** Add the 3D axes gizmo + DOM labels around the (origin-centered) surface mesh, matching the\n * volume/isosurface. Installed once per mount; the box tracks the mesh bounds, X/Y show the\n * physical (or pixel) extent, and Z is the intensity/height axis. */\n private installSurfaceAxes(viewer: Viewer): void {\n if (!this.surfaceLayer) return;\n const b = this.surfaceLayer.bounds();\n const boxW = Math.max(1, b.max[0] - b.min[0]);\n const boxH = Math.max(1, b.max[1] - b.min[1]);\n const boxD = Math.max(1, b.max[2] - b.min[2]);\n const mppX = this.descriptor?.mppX || this.loaded?.imageInfo.imageMeta?.[0]?.mppX || 0;\n const voxel = mppX > 0 ? (mppX * (this.descriptor?.width ?? this.imageW)) / Math.max(1, this.imageW) : 1;\n this.axesLayer = viewer.addAxes(boxW, boxH, boxD, {\n voxelSize: [voxel, voxel, 1],\n visible: this.axesVisible,\n });\n if (this.host) {\n this.axesLabels = new NapariAxesLabels(\n this.host,\n viewer.camera3d,\n this.buildSurfaceAxesLabels(boxW, boxH, boxD, mppX),\n );\n this.axesLabels.setVisible(this.axesVisible);\n }\n }\n\n /** X/Y/Z end-labels for the surface gizmo: X/Y are the physical (µm) or pixel extent of the FULL\n * image; Z is the intensity/height axis. Anchors are in the centered box (matching AxesLayer). */\n private buildSurfaceAxesLabels(\n boxW: number,\n boxH: number,\n boxD: number,\n mppX: number,\n ): AxisLabelSpec[] {\n const hx = boxW / 2;\n const hy = boxH / 2;\n const hz = boxD / 2;\n const descW = this.descriptor?.width ?? this.imageW;\n const descH = this.descriptor?.height ?? this.imageH;\n const len = (px: number): string => (mppX > 0 ? formatUm(px * mppX) : `${px} px`);\n return [\n { anchor: [hx, -hy, -hz], text: `X · ${len(descW)}`, color: '#ed4545' },\n { anchor: [-hx, hy, -hz], text: `Y · ${len(descH)}`, color: '#4dd959' },\n { anchor: [-hx, -hy, hz], text: 'Z · intensity', color: '#668cff' },\n ];\n }\n\n /**\n * Pre-fetch every stack slice's luminance plane (decimated to the surface grid) into\n * {@link surfacePlanes}, driving {@link stackLoadingProgress$} — the same load-with-progress UX\n * as the volume, but keeping one 2D plane per slice rather than packing a 3D volume. Bounded\n * concurrency keeps the connection pool busy without flooding it on a deep stack.\n */\n private async preloadSurfacePlanes(viewer: Viewer): Promise<void> {\n const token = this.loadToken; // bail if a Cancel / new plot bumps this while we fetch\n const info = this.loaded?.imageInfo;\n const depth = info?.imageMeta?.[0]?.z || info?.urls?.length || 1;\n const { maxGrid } = surfaceResolutionFor(this.resolutionScale);\n this.surfacePlanes.clear();\n this.stackLoading$.next(true);\n this.stackLoadingProgress$.next(0);\n try {\n const pending: number[] = [];\n for (let z = 0; z < depth; z++) pending.push(z);\n let done = 0;\n const worker = async (): Promise<void> => {\n for (;;) {\n const z = pending.shift();\n if (z === undefined || this.viewer !== viewer || this.loadToken !== token) return;\n try {\n this.surfacePlanes.set(z, await this.fetchSurfacePlane(z, maxGrid));\n } catch (err) {\n console.warn(`[napari-js] surface slice ${z} preload failed`, err);\n }\n done++;\n this.stackLoadingProgress$.next(Math.round((done / depth) * 100));\n }\n };\n const pool = Math.min(VOLUME_FETCH_CONCURRENCY, Math.max(1, depth));\n await Promise.all(Array.from({ length: pool }, () => worker()));\n } finally {\n this.stackLoading$.next(false);\n this.stackLoadingProgress$.next(0);\n }\n }\n\n /**\n * Fetch slice `z` as a single WHOLE-image luminance plane (decimated to `maxGrid`). Prefers the\n * app's complete per-slice image (`smallUrls`/`urls`, exactly like the Plotly surface) so the\n * surface always covers the FULL slice — the tile-pyramid `fetchSlice` path would fall back to a\n * single top-left tile (a corner) for self-contained / non-`/tiles/info` images. Falls back to\n * stitching the tile grid only when no complete-image URL is available.\n */\n /** Tile budget to stitch a whole slice at ~`targetPx` resolution from the pyramid: a higher target\n * pulls a FINER pyramid level (more real detail). Shared by the surface plane fetch and the volume\n * assembly so both scale their in-plane resolution with the decimate factor. */\n private tileBudgetFor(targetPx: number): number {\n const tileSize = this.descriptor?.tileSize || TILE_SIZE;\n return Math.min(\n MAX_STITCH_TILES,\n Math.max(1, Math.round((targetPx / tileSize) ** 2 * STITCH_BUDGET_COEFF)),\n );\n }\n\n private async fetchSurfacePlane(\n z: number,\n maxGrid: number,\n ): Promise<{ data: Uint8Array; width: number; height: number }> {\n const info = this.loaded?.imageInfo;\n const desc = await this.ensureDescriptor();\n let plane: { data: Uint8Array; width: number; height: number } | null = null;\n\n // Preferred: stitch the WHOLE slice from the server pyramid at a resolution driven by the\n // decimate factor — a higher target grid pulls a FINER pyramid level (more real detail). With a\n // descriptor, fetchSlice stitches the whole chosen level (never a corner), then we downscale to\n // the grid. This is what makes \"Full\" actually higher-res than \"½\", not just a fixed preview.\n if (desc?.levels?.length) {\n const budget = this.tileBudgetFor(maxGrid);\n // The surface is a single decimated plane, so the composite fallback is acceptable when the\n // channel has no small pyramid level (keeps it fast); a multichannel VOLUME must not do this.\n plane = this.bitmapToLuminance(\n await this.fetchSlice(z, this.surfaceChannel, budget, true),\n maxGrid,\n );\n }\n\n // Fallback (no pyramid): the app's COMPLETE per-slice image (urls[z], not the small blurry\n // thumbnail) — whole slice, avoids a corner tile. Capped at the image's own resolution.\n if (!plane) {\n const url = info?.urls?.[z] ?? info?.smallUrls?.[z];\n if (url) {\n try {\n const headers = await this.tiles\n .getAuthHeaders()\n .catch(() => ({}) as Record<string, string>);\n const resp = await fetch(url, { headers });\n if (resp.ok) {\n plane = this.bitmapToLuminance(await createImageBitmap(await resp.blob()), maxGrid);\n }\n } catch (err) {\n console.warn(`[napari-js] surface url fetch failed for z=${z}`, err);\n }\n }\n }\n\n // Last resort (no pyramid and no complete image): a single tile.\n if (!plane) {\n plane = this.bitmapToLuminance(\n await this.fetchSlice(z, this.surfaceChannel, this.tileBudgetFor(maxGrid), true),\n maxGrid,\n );\n }\n return plane;\n }\n\n /** The channel state driving the surface: the chosen band for multichannel (matched by index),\n * else the single grayscale channel. */\n private surfaceState(channels: IChannelState[]): IChannelState | undefined {\n if (this.surfaceChannel == null) return channels[0];\n return channels.find((s) => s.index === this.surfaceChannel) ?? channels[0];\n }\n\n /**\n * (Re)build the surface mesh for slice `z` from the pre-loaded plane cache (instant — this is\n * what the stack slider calls); a slice missing from the cache is fetched on demand. napari-js's\n * pure `heightField` builds the triangle grid (z = normalized intensity), then `addSurface`\n * renders it. The slice plane also feeds the intensity histogram (key 0).\n */\n private async buildSurface(viewer: Viewer, z: number): Promise<void> {\n let plane = this.surfacePlanes.get(z);\n if (!plane) {\n this.stackLoading$.next(true);\n try {\n plane = await this.fetchSurfacePlane(z, this.surfaceMaxGrid);\n this.surfacePlanes.set(z, plane);\n } catch (err) {\n console.error('[napari-js] surface slice fetch failed:', err);\n } finally {\n this.stackLoading$.next(false);\n }\n }\n if (!plane || plane.width < 2 || plane.height < 2 || this.viewer !== viewer) return;\n\n const st = this.surfaceState(this.store.currentChannelStates());\n const win: [number, number] = [st?.min ?? 0, st?.max ?? 255];\n this.surfaceWindow = win;\n // Height AND colour are normalized by the same contrast window, so changing min/max reshapes the\n // surface (a pixel's height = its intensity within [min,max]). Center it for the axes gizmo. The\n // plane is already decimated to the grid cap → stride 1.\n const zScale = SURFACE_Z_ASPECT * Math.max(plane.width, plane.height);\n const { vertices, faces, values } = heightField(plane.data, plane.width, plane.height, {\n zScale,\n zLimits: win,\n center: true,\n });\n\n // Preserve the orbit camera across a re-slice / window rebuild — only the first mount frames, so\n // stepping the stack or changing the window keeps the current zoom/pan/orientation.\n const cam = viewer.camera3d;\n const preserveCamera = this.surfaceLayer != null;\n const savedTarget = cam.target;\n const savedDistance = cam.distance;\n if (this.surfaceLayer) {\n viewer.layers.remove(this.surfaceLayer);\n this.surfaceLayer = null;\n }\n this.surfaceLayer = viewer.addSurface(vertices, faces, values, {\n colormap: this.volumeColormap(st),\n contrastLimits: win,\n gamma: st?.gamma ?? 1,\n wireframe: this.surfaceWireframe,\n });\n if (preserveCamera) {\n cam.target = savedTarget;\n cam.distance = savedDistance;\n }\n\n this.imageW = plane.width;\n this.imageH = plane.height;\n this.volumeDims = { width: plane.width, height: plane.height, depth: Math.max(1, Math.round(zScale)) };\n // Reuse the volume intensity-histogram path: the slice's scalar plane is the histogram source.\n this.volumeChannelData.clear();\n this.volumeChannelData.set(0, plane.data);\n this.scheduleReadback();\n }\n\n /** Subscribe the store colormap / reverse / invert / channel window → the surface, so histogram\n * & channel-dialog edits update it live without a re-fetch. **min/max reshapes the surface's\n * height** (a pixel's height = its intensity within [min,max]), so a window change rebuilds the\n * mesh geometry (from the cached slice); colour-only edits (colormap/LUT, gamma, reverse, invert)\n * just update the layer's uniforms. */\n private subscribeSurfaceDisplayState(): void {\n this.displaySub?.unsubscribe();\n this.displaySub = combineLatest([\n this.store.getColormap(),\n this.store.getReverseScale(),\n this.store.getInvert(),\n this.store.getChannelStates(),\n ]).subscribe(([colormap, reverse, invert, channels]) => {\n this.currentColormap = (colormap as ColormapNode) ?? null;\n this.currentReverse = reverse;\n this.invertEnabled = invert;\n const layer = this.surfaceLayer;\n if (!layer || !this.viewer) return;\n const st = this.surfaceState(channels);\n const win: [number, number] = [st?.min ?? 0, st?.max ?? 255];\n const windowChanged =\n !this.surfaceWindow || win[0] !== this.surfaceWindow[0] || win[1] !== this.surfaceWindow[1];\n if (windowChanged) {\n // Height follows the contrast window → rebuild the mesh for the new [min,max] (camera kept).\n void this.buildSurface(this.viewer, this.loaded?.z ?? 0).catch((err) =>\n console.error('[napari-js] surface window rebuild failed:', err),\n );\n return;\n }\n // Colour-only change: update uniforms in place, no geometry rebuild.\n layer.colormap = this.volumeColormap(st);\n if (st) {\n layer.contrastLimits = win;\n layer.gamma = st.gamma;\n }\n this.viewer.requestRender();\n });\n }\n\n private fitCameraSoon(): void {\n const run = (): void => {\n if (this.viewer && this.canvas && this.imageW > 0 && this.imageH > 0) {\n this.viewer.camera.fit(\n this.imageW,\n this.imageH,\n this.canvas.clientWidth || this.imageW,\n this.canvas.clientHeight || this.imageH,\n );\n }\n };\n if (typeof requestAnimationFrame === 'function') requestAnimationFrame(run);\n else run();\n }\n\n /** @deprecated Plotly-specific; host re-drives plot() from its image stream. */\n reloadAndPlot(): void {\n /* no-op */\n }\n\n reset(): void {\n this.loadToken++; // invalidate any in-flight frame loading from the previous plot\n this.displaySub?.unsubscribe();\n this.displaySub = null;\n this.scaleBar?.destroy();\n this.scaleBar = null;\n this.regionOverlay?.destroy();\n this.regionOverlay = null;\n this.axesLabels?.destroy();\n this.axesLabels = null;\n this.zHandle?.destroy();\n this.zHandle = null;\n this.volumeWorldBase = null;\n this.cachedImage = null;\n this.cachedImageSource = null;\n this.lastPixelsRect = null;\n this.nativeHistograms.clear();\n this.tiled = false;\n this.histSamples.clear();\n if (this.readbackTimer != null) {\n clearTimeout(this.readbackTimer);\n this.readbackTimer = null;\n }\n this.cameraReadbackOff?.();\n this.cameraReadbackOff = null;\n this.channelView = null;\n this.viewer?.dispose();\n this.viewer = null;\n if (this.canvas && this.host?.contains(this.canvas)) this.host.removeChild(this.canvas);\n this.canvas = null;\n this.lastPixels = null;\n this.volumeView = null;\n this.volumeMultichannel = false;\n this.surfaceLayer = null;\n this.surfaceChannel = undefined;\n this.surfacePlanes.clear();\n this.surfaceWindow = null;\n this.scatterRegionSub?.unsubscribe();\n this.scatterRegionSub = null;\n this.scatter2dPoints = null;\n this.scatter3dLayer = null;\n this.axesLayer = null;\n this.volumeDims = null;\n this.volumeChannelData.clear();\n }\n\n relayout(_trueImageSize?: number[]): void {\n this.viewer?.requestRender();\n }\n\n /** @deprecated Plotly-specific axis reset. */\n resetAxes(): void {\n this.fitCameraSoon();\n }\n\n /** @deprecated Plotly-specific autoscale. */\n autoscale(): void {\n this.fitCameraSoon();\n this.autoscaleEvent$.next(undefined);\n }\n\n zoomIn(): void {\n if (this.viewer) this.viewer.camera.zoom = this.viewer.camera.zoom * 1.3;\n }\n\n zoomOut(): void {\n if (this.viewer) this.viewer.camera.zoom = this.viewer.camera.zoom / 1.3;\n }\n\n setDragMode(_mode: string | false): void {\n // No-op: pan and zoom are always the napari camera's default gestures, and pan/zoom gating for\n // drawing is owned by the region overlay's setMode (setControlsEnabled). Toggling controls here\n // would fight that — the host calls setDragMode(false) alongside overlay.setMode(<tool>).\n }\n\n setNavigatorVisible(_visible: boolean): void {\n /* napari-js has no minimap; no-op */\n }\n\n setImageSmoothingEnabled(enabled: boolean): void {\n this.imageSmoothing = enabled;\n // Apply live to the rendered image layers; baked into the next render too.\n this.channelView?.setInterpolation(enabled ? 'linear' : 'nearest');\n }\n\n setShowStack(_showstack: boolean): void {\n /* stack navigated via setZIndex */\n }\n\n setZIndex(zIndex: number): void {\n if (this.loaded) this.loaded.z = zIndex;\n const v = this.viewer;\n if (!v) return;\n // Surface: one slice → one mesh, so re-build the height field for the new slice.\n if (this.surfaceLayer) {\n void this.buildSurface(v, zIndex).catch((err) =>\n console.error('[napari-js] setZIndex surface failed:', err),\n );\n return;\n }\n // Volume / isosurface: step the volume's z plane in place.\n if (this.volumeView) {\n v.dims.z = zIndex;\n this.scheduleReadback();\n return;\n }\n // Tiled 2D image: just move the dims plane — the tiled visual fetches the new slice's tiles\n // (cached per z), no layer rebuild. Refresh the coarse histogram sample for the new slice.\n if (this.tiled) {\n v.dims.z = zIndex;\n if (this.descriptor) void this.refreshHistogramSamples(zIndex, this.descriptor);\n this.scheduleReadback();\n return;\n }\n // 2D image (stitch fallback): re-render the slice (re-fetches per-channel / composite). Branch\n // of a volume layer (not currentPlotType, which could be stale and silently no-op the swap).\n // The token lets renderImage drop a superseded scrub so a slow older slice can't clobber a newer one.\n const req = ++this.sliceReq;\n void this.renderImage(zIndex, req)\n .then(() => {\n if (req === this.sliceReq) this.scheduleReadback();\n })\n .catch((err) => console.error('[napari-js] setZIndex slice failed:', err));\n }\n\n setStackLoading(stackLoading: boolean): void {\n this.stackLoading$.next(stackLoading);\n }\n\n /** Cancel in-flight frame loading: bump the load generation so the volume-assembly / surface\n * preload workers stop fetching more frames, and clear the loading flag + progress. */\n cancelLoading(): void {\n this.loadToken++;\n this.stackLoading$.next(false);\n this.stackLoadingProgress$.next(0);\n }\n\n isStackLoading(): Observable<boolean> {\n return this.stackLoading$.asObservable();\n }\n\n getStackLoadingProgress(): Observable<number> {\n return this.stackLoadingProgress$.asObservable();\n }\n\n getTrueImageSize(): { width: number; height: number } | null {\n return this.imageW > 0 && this.imageH > 0 ? { width: this.imageW, height: this.imageH } : null;\n }\n\n getCurrentImage(): Promise<Image | null> {\n return Promise.resolve(null);\n }\n\n getDisplayedPixelData(): PixelData | null {\n return this.lastPixels;\n }\n\n getDisplayedSourceRect(): { x: number; y: number; width: number; height: number } | null {\n const v = this.viewer;\n const size = this.getTrueImageSize();\n if (!v || !size) return null;\n const r = v.visibleWorldRect();\n const x = Math.max(0, r.x);\n const y = Math.max(0, r.y);\n return {\n x,\n y,\n width: Math.min(size.width, r.x + r.width) - x,\n height: Math.min(size.height, r.y + r.height) - y,\n };\n }\n\n downloadImage(): void {\n void this.exportComposite();\n }\n\n setPlotType(plotType: PlotType): void {\n this.currentPlotType = plotType;\n }\n\n /** Map a Plotly-style 3D drag mode onto napari-js's camera drag mode. */\n setSurfaceDragMode(mode: string): void {\n if (!this.viewer) return;\n const m = mode === 'pan' ? 'pan' : mode === 'zoom' ? 'zoom' : 'rotate'; // orbit/turntable → rotate\n this.viewer.setCameraDragMode(m);\n }\n\n /** Re-frame the 3D camera on the current 3D layer. A surface mesh sits in the positive octant\n * (not centred), so frame it by its own bounds; a volume/isosurface uses its centred box. */\n resetSurfaceCamera(): void {\n if (!this.viewer) return;\n const meshLayer = this.surfaceLayer ?? this.scatter3dLayer;\n if (meshLayer) {\n const b = meshLayer.bounds();\n this.viewer.camera3d.target = b.center;\n this.viewer.camera3d.distance = Math.max(b.radius * 2.5, 1e-3);\n this.viewer.requestRender();\n return;\n }\n const d = this.volumeDims;\n if (d) this.viewer.camera3d.frame(d.width, d.height, d.depth);\n }\n\n getAutoscaleEvent(): Observable<unknown> {\n return this.autoscaleEvent$.asObservable();\n }\n\n getPlotTypeDescriptors(): PlotTypeDescriptor[] {\n // The WebGPU napari-js options, offered alongside (not replacing) the OSD/Plotly types.\n return [\n PLOT_TYPE_DESCRIPTORS[PlotType.NAPARI_IMAGE]!,\n PLOT_TYPE_DESCRIPTORS[PlotType.NAPARI_SCATTER]!,\n PLOT_TYPE_DESCRIPTORS[PlotType.NAPARI_SURFACE]!,\n PLOT_TYPE_DESCRIPTORS[PlotType.NAPARI_SCATTER3D]!,\n PLOT_TYPE_DESCRIPTORS[PlotType.NAPARI_VOLUME]!,\n PLOT_TYPE_DESCRIPTORS[PlotType.NAPARI_ISOSURFACE]!,\n ];\n }\n\n /** The napari 3D decimate factor (1 = full … 8 = ⅛). Read by the toolbar to init the control. */\n getResolutionScale(): number {\n return this.resolutionScale;\n }\n\n /** Set the decimate factor for the napari 3D types. Takes effect on the next (re)load — the host\n * re-plots after calling this, since decimation changes the fetched/assembled data. */\n setResolutionScale(scale: number): void {\n this.resolutionScale = Math.max(1, Math.round(scale));\n }\n\n getIntensityProfile$(): Observable<IntensityProfile[]> {\n return this.intensityProfile$.asObservable();\n }\n\n renderIntensityInset(_divId: string, _profiles: IntensityProfile[]): void {\n /* Plotly owns the intensity inset */\n }\n\n /** Read the displayed composite into `lastPixels` (the pixel-tools' source) + emit the clamped\n * visible region. A fresh PixelData object means cachedImageData() rebuilds automatically. */\n private async runReadback(): Promise<void> {\n const v = this.viewer;\n if (!v) return;\n try {\n const px = await v.readDisplayedPixels();\n if (this.viewer !== v) return;\n const rect = v.visibleWorldRect(); // capture WITH the pixels (same camera)\n this.lastPixels = px;\n this.lastPixelsRect = rect;\n const size = this.getTrueImageSize();\n if (size && rect) {\n const x = Math.max(0, Math.min(size.width, rect.x));\n const y = Math.max(0, Math.min(size.height, rect.y));\n const width = Math.max(1, Math.min(size.width - x, rect.width));\n const height = Math.max(1, Math.min(size.height - y, rect.height));\n this.viewportChange$.next({ x, y, width, height });\n }\n } catch {\n /* readback unavailable */\n }\n }\n\n private scheduleReadback(): void {\n if (!this.viewer) return;\n if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => void this.runReadback());\n else setTimeout(() => void this.runReadback(), 0);\n }\n\n /** Debounced readback — armed on camera changes so `lastPixels` tracks the current view after a\n * pan/zoom settles (and after tiled levels finish loading), which the on-canvas pixel tools\n * (wand/brush/SAM) read synchronously. Coalesces rapid changes. */\n private armReadback(delayMs = 250): void {\n if (this.readbackTimer != null) clearTimeout(this.readbackTimer);\n this.readbackTimer = setTimeout(() => {\n this.readbackTimer = null;\n void this.runReadback();\n }, delayMs);\n }\n\n // ── IRegionStore + classification colours ──────────────────────────────────\n // Inherited from BaseStoreVisualizer — pure delegations to the shared\n // RegionStore / VisualizerStore (identical to the OSD backend).\n\n // ── Pixel tools: reuse the shared, backend-agnostic tool services with a napari host ───────\n\n /** Build the coordinate transform + tool hosts for the current viewer (called from plot()). The\n * pixel tools read displayed pixels synchronously from the last readback and convert pointer\n * coords via the napari camera, exactly mirroring the OSD host. */\n private buildToolHosts(): void {\n if (!this.viewer) return;\n this.coordTransform = new NapariCoordinateTransform(\n this.viewer,\n () => !!this.viewer && this.imageW > 0,\n );\n const regions = this.regionStore;\n this.wandHost = {\n getRegions: () => regions.getRegions(),\n setRegions: (r) => regions.setRegions(r),\n getCachedImageData: () => this.cachedImageData(),\n getActiveFrameIndex: () => this.loaded?.z ?? 0,\n getOverlayContainer: () => this.host,\n getCoordinateTransform: () => this.coordTransform as ICoordinateTransform,\n getFileName: () => this.loaded?.filename,\n getShapeColor: () => regions.getShapeColor(),\n };\n this.eraserHost = {\n getRegions: () => regions.getRegions(),\n setRegions: (r) => regions.setRegions(r),\n invalidateWandRegion: () => this.wandTool.clearActiveRegion(),\n getOverlayContainer: () => this.host,\n getCoordinateTransform: () => this.coordTransform as ICoordinateTransform,\n getCachedImageRatio: () => this.cachedImageData()?.ratios[0] ?? 1,\n };\n }\n\n private zoomBoxHost(): ZoomToBoxToolHost {\n return {\n getPlotDiv: () => this.plotDivId,\n pixelToData: (px, py) => {\n const rect = this.host?.getBoundingClientRect();\n if (!this.viewer || !rect) return { x: 0, y: 0 };\n const [x, y] = this.viewer.canvasToWorld(rect.left + px, rect.top + py);\n return { x, y };\n },\n applyZoomToBox: (coords) => this.applyZoomToBox(coords),\n };\n }\n\n /** Zoom/pan the camera to fit a data-space rectangle `[xMin, xMax, yMax, yMin]`. */\n private applyZoomToBox(coordinates: number[]): void {\n const v = this.viewer;\n if (!v || !this.canvas || coordinates.length < 4) return;\n const [xMin, xMax, yA, yB] = coordinates;\n const x0 = Math.min(xMin, xMax);\n const x1 = Math.max(xMin, xMax);\n const y0 = Math.min(yA, yB);\n const y1 = Math.max(yA, yB);\n const w = Math.max(1, x1 - x0);\n const h = Math.max(1, y1 - y0);\n const vw = this.canvas.clientWidth || w;\n const vh = this.canvas.clientHeight || h;\n v.camera.center = [(x0 + x1) / 2, (y0 + y1) / 2];\n v.camera.zoom = Math.min(vw / w, vh / h);\n v.requestRender();\n }\n\n /** Build CachedImageData from the most recent readback (RGBA device pixels → [y][x]=[r,g,b]),\n * with ratios/origin mapping image coords ↔ readback pixels. Cached until the readback changes. */\n private cachedImageData(): CachedImageData | null {\n const px = this.lastPixels;\n if (!px || !this.viewer) return null;\n if (this.cachedImage && this.cachedImageSource === px) return this.cachedImage;\n const w = px.width;\n const h = px.height;\n const data = px.data;\n const matrix: number[][][] = new Array(h);\n for (let y = 0; y < h; y++) {\n const row: number[][] = new Array(w);\n const base = y * w * 4;\n for (let x = 0; x < w; x++) {\n const o = base + x * 4;\n row[x] = [data[o], data[o + 1], data[o + 2]];\n }\n matrix[y] = row;\n }\n // Use the rect captured WITH this readback (not the live one) so ratios/origin match the\n // matrix's camera — otherwise a pan/zoom since the readback mis-scales the traced region.\n const rect = this.lastPixelsRect ?? this.viewer.visibleWorldRect();\n this.cachedImage = {\n frames: [matrix],\n width: w,\n height: h,\n ratios: [rect.width / w, rect.height / h],\n isGrayscale: false,\n originX: rect.x,\n originY: rect.y,\n };\n this.cachedImageSource = px;\n return this.cachedImage;\n }\n\n // ── IToolController ────────────────────────────────────────────────────────\n // Control gating: a tool that ACTIVATES disables the camera controls; deactivation is a no-op\n // because the host always calls the region overlay's setMode FIRST in each toggle (which sets\n // the baseline enabled/disabled), so re-enabling here would fight a freshly-activated draw mode.\n setWandMode(active: boolean, options?: IWandOptions): void {\n if (!this.viewer) return; // no plot yet → nothing to drive\n if (!active) {\n this.wandTool.setMode(false);\n return;\n }\n this.viewer?.setControlsEnabled(false);\n this.cachedImageSource = null;\n this.armReadback(0);\n if (this.wandHost) this.wandTool.bindHost(this.wandHost);\n this.wandTool.setMode(true, (options ?? {}) as unknown as WandOptions);\n }\n setWandOptions(options: IWandOptions): void {\n this.wandTool.setOptions((options ?? {}) as unknown as WandOptions);\n }\n clearActiveWandRegion(): void {\n this.wandTool.clearActiveRegion();\n }\n setBrushMode(active: boolean, options?: IBrushOptions): void {\n if (!this.viewer) return;\n if (!active) {\n this.brushTool.setMode(false);\n return;\n }\n this.viewer?.setControlsEnabled(false);\n this.cachedImageSource = null;\n this.armReadback(0);\n if (this.wandHost) this.brushTool.bindHost(this.wandHost);\n this.brushTool.setMode(true, (options ?? {}) as unknown as BrushOptions);\n }\n setBrushOptions(options: IBrushOptions): void {\n if (options?.size != null) this.brushTool.setSize(options.size);\n }\n setVertexEraserMode(active: boolean): void {\n if (!this.viewer) return;\n if (active) {\n this.viewer?.setControlsEnabled(false);\n this.cachedImageSource = null;\n if (this.eraserHost) this.eraserTool.bindHost(this.eraserHost);\n }\n this.eraserTool.setMode(active);\n }\n setVertexEraserRadius(radius: number): void {\n this.eraserTool.setRadius(radius);\n }\n setZoomToBoxMode(active: boolean): void {\n if (!this.viewer) return;\n if (active) {\n this.viewer?.setControlsEnabled(false);\n this.zoomToBoxTool.bindHost(this.zoomBoxHost());\n }\n this.zoomToBoxTool.setMode(active);\n }\n // SAM / cellpose — server round-trips that read the drawn rectangles + displayed pixels through\n // the same wand host (rectangles from the RegionStore, image from the readback).\n async segmentRectangles(): Promise<number> {\n if (!this.viewer || !this.wandHost) return 0;\n await this.runReadback(); // the SAM embedding samples the currently-displayed image\n this.cachedImageSource = null;\n this.samTool.bindHost(this.wandHost);\n return this.samTool.segmentBoxes();\n }\n async segmentRectanglesCellpose(): Promise<number> {\n if (!this.viewer || !this.wandHost || !this.cellSegmenter) return 0;\n await this.runReadback();\n this.cachedImageSource = null;\n this.cellSegmentTool.bindHost(this.wandHost);\n return this.cellSegmentTool.segmentBoxes(this.cellSegmenter);\n }\n setSamModel(id: string): void {\n this.samTool.setModel(id);\n this.samPointTool.setModel(id);\n }\n setSamPointMode(active: boolean): void {\n if (!this.viewer) return;\n if (active) {\n this.viewer?.setControlsEnabled(false);\n this.cachedImageSource = null;\n this.armReadback(0); // refresh the readback the click's embedding will sample\n if (this.wandHost) this.samPointTool.bindHost(this.wandHost);\n }\n this.samPointTool.setMode(active);\n }\n commitSamPoints(): void {\n this.samPointTool.commit();\n }\n clearSamPoints(): void {\n this.samPointTool.clear();\n }\n\n // ── IDisplayOptions ───────────────────────────────────────────────────────\n // Inherited from BaseStoreVisualizer — pure delegations to the shared\n // VisualizerStore (identical to the OSD backend).\n\n // ── IIntensitySampling: Plotly owns sampling; emit viewport changes ───────\n ensureIntensitySampling(_imageInfo: IImageInfo, _zIndex: number): Promise<void> {\n return Promise.resolve();\n }\n refreshIntensitySamplingForRoi(\n _x: number,\n _y: number,\n _width: number,\n _height: number,\n _zIndex: number,\n ): void {}\n getViewportChange$(): Observable<{ x: number; y: number; width: number; height: number }> {\n return this.viewportChange$.asObservable();\n }\n\n // ── IVisualizer composite members ─────────────────────────────────────────\n getRegionOverlay(): IRegionOverlay | null {\n return this.regionOverlay;\n }\n getIsosurfaceControls(): IIsosurfaceControls | null {\n if (!this.volumeView) return null;\n return {\n setIsoRange: (isoMin: number, isoMax: number): void => {\n // Apply to every channel's volume layer.\n for (const layer of this.volumeView?.layers ?? []) {\n layer.contrastLimits = [isoMin, isoMax];\n layer.rendering = 'iso';\n layer.isoThreshold = 0.5;\n }\n this.viewer?.requestRender();\n },\n };\n }\n getIntensityControls(): IIntensityControls | null {\n return null;\n }\n getSurface3dControls(): ISurface3dControls | null {\n if (!this.volumeView && !this.surfaceLayer && !this.scatter3dLayer) return null;\n return {\n setSurfaceDragMode: (mode: string): void => this.setSurfaceDragMode(mode),\n resetSurfaceCamera: (): void => this.resetSurfaceCamera(),\n setAxesVisible: (visible: boolean): void => {\n this.axesVisible = visible;\n this.axesLabels?.setVisible(visible);\n if (this.axesLayer) {\n this.axesLayer.visible = visible;\n this.viewer?.requestRender();\n }\n },\n axesVisible: (): boolean => this.axesVisible,\n // Surface wireframe (napari-js surface only) — a live layer property, no rebuild needed.\n setWireframe: (on: boolean): void => {\n this.surfaceWireframe = on;\n if (this.surfaceLayer) {\n this.surfaceLayer.wireframe = on;\n this.viewer?.requestRender();\n }\n },\n wireframe: (): boolean => this.surfaceWireframe,\n };\n }\n getHistogram(channelIndex: number, bins: number): IHistogram | null {\n const v = this.viewer;\n if (!v) return null;\n // Volume / isosurface: intensity histogram of the assembled (downsampled) uint8 volume for the\n // requested channel (multichannel) or the single grayscale volume (key 0).\n if (this.volumeChannelData.size) {\n const data = this.volumeChannelData.get(channelIndex) ?? this.volumeChannelData.get(0);\n return data ? this.toIHistogram(histogramScalar(data, bins, 0, 255)) : null;\n }\n // Tiled mode has no full in-memory pixels → use the coarse per-channel sample (RGB: readback).\n if (this.tiled) {\n if (this.imageMode === 'rgb') return this.rgbHistogram(channelIndex, bins);\n const sample = this.histSamples.get(this.imageMode === 'grayscale' ? 0 : channelIndex);\n return sample ? this.toIHistogram(histogramScalar(sample, bins, 0, 255)) : null;\n }\n // Grayscale/multichannel (stitch): native per-channel histogram straight from the in-memory\n // scalar layer (no GPU readback). RGB: bin the displayed pixels' R/G/B byte (8-bit client path).\n const layer = this.channelView?.layers[this.imageMode === 'grayscale' ? 0 : channelIndex];\n if (layer) {\n const h = v.layerHistogram(layer, bins);\n if (h) return this.toIHistogram(h);\n }\n if (this.imageMode === 'rgb') return this.rgbHistogram(channelIndex, bins);\n return null;\n }\n getHistogram$(channelIndex: number, bins: number): Observable<IHistogram | null> {\n // >8-bit channels: fetch the true native distribution from the server (the displayed pixels\n // are 8-bit, so the client histogram would be clipped). 8-bit channels use the client path.\n const bitDepth = this.descriptor?.channelInfo?.[channelIndex]?.bitDepth ?? 8;\n if (bitDepth > 8) {\n const z = this.loaded?.z ?? 0;\n const key = `${z}|${channelIndex}`;\n const cached = this.nativeHistograms.get(key);\n if (cached) return of(cached);\n return from(this.fetchNativeHistogram(channelIndex, bins, z, key));\n }\n return of(this.getHistogram(channelIndex, bins));\n }\n\n /** Fetch + cache one channel's native-bit-depth histogram from `GET /histogram` (>8-bit). */\n private async fetchNativeHistogram(\n channel: number,\n bins: number,\n z: number,\n key: string,\n ): Promise<IHistogram | null> {\n const infoB64 = this.tiles.getSelectedInfoB64();\n if (!infoB64) return null;\n const headers = await this.tiles\n .getAuthHeaders()\n .catch(() => ({}) as Record<string, string>);\n const url = `${this.api}histogram?info=${infoB64}&channel=${channel}&z=${z}&bins=${bins}`;\n try {\n const resp = await fetch(url, { headers });\n if (!resp.ok) return null; // 202 (still caching) or transient → null; the pane retries\n const hi = (await resp.json()) as {\n bitDepth: number;\n rangeMin: number;\n rangeMax: number;\n observedMin: number;\n observedMax: number;\n binWidth: number;\n counts: number[];\n };\n if (!hi?.counts) return null;\n const out: IHistogram = {\n bins: hi.counts.map((_, i) => hi.rangeMin + i * hi.binWidth),\n counts: hi.counts,\n max: hi.counts.reduce((m, c) => (c > m ? c : m), 0),\n bitDepth: hi.bitDepth,\n rangeMin: hi.rangeMin,\n rangeMax: hi.rangeMax,\n observedMin: hi.observedMin,\n observedMax: hi.observedMax,\n };\n this.nativeHistograms.set(key, out);\n return out;\n } catch (err) {\n console.warn('[napari-js] native histogram fetch failed', err);\n return null;\n }\n }\n\n /** Per-channel histogram of the displayed RGB composite (R/G/B byte), from the last readback. */\n private rgbHistogram(channelIndex: number, bins: number): IHistogram | null {\n const px = this.lastPixels;\n if (!px) return null;\n const band = Math.max(0, Math.min(2, channelIndex));\n const n = Math.max(1, Math.min(256, Math.floor(bins) || 256));\n const counts = new Array(n).fill(0);\n const data = px.data;\n for (let i = 0; i < data.length; i += 4) {\n if (data[i + 3] === 0) continue; // skip transparent padding\n counts[Math.min(n - 1, (data[i + band] * n) >> 8)]++;\n }\n const binsArr = Array.from({ length: n }, (_, i) => (i * 256) / n);\n return { bins: binsArr, counts, max: counts.reduce((m, c) => (c > m ? c : m), 0) };\n }\n exportComposite(): void {\n const v = this.viewer;\n if (!v) return;\n void v.screenshot().then((blob) => {\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = 'napari-js.png';\n a.click();\n URL.revokeObjectURL(url);\n });\n }\n /** Native-bit-depth (16/32-bit) multi-band TIFF export via the server `/export/tiff` endpoint —\n * the displayed PNG is an 8-bit figure, this preserves the true pixel values. Visible channels\n * only (omitted when all are visible → server default). Mirrors the OSD backend. */\n async exportData(): Promise<void> {\n const infoB64 = this.tiles.getSelectedInfoB64();\n if (!infoB64) return;\n const states = this.store.currentChannelStates();\n const visible = states.filter((c) => c.visible).map((c) => c.index);\n const chParam =\n visible.length && visible.length < states.length ? `&channels=${visible.join(',')}` : '';\n const z = this.loaded?.z ?? 0;\n const url = `${this.api}export/tiff?info=${infoB64}&z=${z}${chParam}`;\n const stem = (this.loaded?.filename || 'image').replace(/\\.[^.]+$/, '');\n const headers = await this.tiles\n .getAuthHeaders()\n .catch(() => ({}) as Record<string, string>);\n try {\n const resp = await fetch(url, { headers });\n if (resp.status === 202) {\n console.warn('[napari-js] 16-bit export: file still caching — try again shortly.');\n return;\n }\n if (!resp.ok) throw new Error(`status ${resp.status}`);\n saveAs(await resp.blob(), `${stem}_16bit.ome.tif`);\n } catch (err) {\n console.warn('[napari-js] 16-bit TIFF export failed', err);\n }\n }\n unsubscribe(): void {\n this.reset();\n }\n}\n","import { Inject, Injectable } from '@angular/core';\nimport { Observable, combineLatest } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { Image } from 'image-js';\n\nimport { IImageInfo, IImageMetadata } from './contracts/image.contract';\nimport { Region } from './models/region';\nimport { ClassPreset, PresetSet } from './models/class-preset';\nimport { PlotlyService } from './implementations/plotly/plotly.service';\nimport { OpenSeadragonVisualizerService } from './implementations/osd/openseadragon-visualizer.service';\nimport { PlotType, PlotTypeDescriptor, isNapari3d, isNapariScatter } from './contracts/plot-type';\nimport { IVisualizer, PixelData, IntensityProfile, IIsosurfaceControls, IIntensityControls, ISurface3dControls } from './contracts/visualizer.contract';\nimport { ViewerCapabilities } from './contracts/capabilities.contract';\nimport { IRegionOverlay } from './contracts/region-overlay.contract';\nimport { IRegionEditorApi } from './contracts/region-editor-api.contract';\nimport { IChannelHistogramApi, IChannelState, IHistogram } from './contracts/channel-histogram-api.contract';\nimport { VisualizerStore } from './store/visualizer-store.service';\nimport { NapariVisualizerService } from './implementations/napari-js/napari-visualizer.service';\nimport { VIZ_CONFIG, VizConfig } from './contracts/viz-config';\n\n/**\n * Backend selector. Routes per plot type:\n * - the **Image** plot type renders through OpenSeadragon — a natively-tiled,\n * zoomable raster backed by the jit-service tile endpoints. It's the default\n * view and supports the region overlay/tools and (for grayscale) the\n * colormap, applied client-side via the tile pixel pipeline.\n * - every other plot type (heatmap, surface, contour, scatter, line,\n * scatter3d, isosurface) renders through Plotly.\n *\n * Only the **render + viewport** path is routed. Region state, display options\n * (colormap/LUT), and the long-lived observables always live in Plotly (the\n * shared store) so both backends stay in sync; OSD reads them to drive its own\n * overlay and tile recoloring.\n *\n * The Image type renders through OpenSeadragon; a failed OSD load falls back to\n * Plotly for that image only (see `osdFellBack`) so it still renders.\n */\n/** Intensity-profile line ROIs are owned by the intensity tool, not the editor.\n * Package-internal predicate (property-based so it also matches plain objects\n * after a drag round-trip). */\nfunction isProfileRegion(r: any): boolean {\n return r?.kind === 'profile';\n}\n\n/** Saturation-based auto-window: pick [min,max] so ~`saturation` of pixels clip\n * at each end of the histogram. A dominant first/last bin (unscanned padding /\n * clipped background) is dropped so it doesn't skew the range. */\nfunction autoWindowFromHistogram(h: IHistogram, saturation: number): [number, number] {\n const counts = h.counts.slice();\n const n = counts.length;\n if (n === 0) return [0, 255];\n if (n > 2 && counts[0] > counts[1]) counts[0] = 0;\n if (n > 2 && counts[n - 1] > counts[n - 2]) counts[n - 1] = 0;\n let total = 0;\n for (const c of counts) total += c;\n if (total <= 0) return [0, 255];\n const target = total * Math.max(0, Math.min(0.5, saturation));\n let acc = 0;\n let min = h.bins[0];\n for (let i = 0; i < n; i++) {\n acc += counts[i];\n if (acc > target) { min = h.bins[i]; break; }\n }\n acc = 0;\n let max = h.bins[n - 1];\n for (let i = n - 1; i >= 0; i--) {\n acc += counts[i];\n if (acc > target) { max = h.bins[i]; break; }\n }\n return [min, max];\n}\n\n@Injectable({ providedIn: 'root' })\nexport class RoutingVisualizerService implements IVisualizer, IRegionEditorApi, IChannelHistogramApi {\n\n private currentPlotType: PlotType = PlotType.IMAGE;\n private lastRendered: IVisualizer | null = null;\n /** OSD failed for the *current* render cycle (e.g. a fresh file still caching\n * past the deadline) → fall back to Plotly for this image only. Reset by\n * reset() at the start of every render cycle, so the next file — or a\n * re-select once the file is cached — retries OSD. (Was a permanent flag,\n * which left the whole session stuck on Plotly after one slow load.) */\n private osdFellBack = false;\n /** napari-js failed for the current render cycle → fall back to OSD (then Plotly).\n * Reset by reset() at the start of every cycle, like {@link osdFellBack}. */\n private napariFellBack = false;\n\n constructor(private plotly: PlotlyService,\n private osd: OpenSeadragonVisualizerService,\n private napari: NapariVisualizerService,\n private store: VisualizerStore,\n @Inject(VIZ_CONFIG) private config: VizConfig) {}\n\n private isImageType(t: PlotType): boolean {\n return t === PlotType.IMAGE;\n }\n\n /** The 2D napari types (image + region-centroid scatter) — a 2D fallback chain (OSD, then Plotly). */\n private isNapariImageType(t: PlotType): boolean {\n return t === PlotType.NAPARI_IMAGE || isNapariScatter(t);\n }\n\n /** The 3D napari types (volume/isosurface, either resolution) — no 2D fallback exists (OSD is\n * image-only), so they fall straight to Plotly. */\n private isNapari3dType(t: PlotType): boolean {\n return isNapari3d(t);\n }\n\n /**\n * Backend to attempt for the current plot type this render. The fallback chains below are\n * mirrored exactly by {@link load} so the handle `plot()` receives always comes from the\n * backend `plot()` selects (no load/plot backend mismatch):\n * - 2D image (explicit `NAPARI_IMAGE`, or `IMAGE` with the WebGPU opt-in): napari-js → OSD → Plotly.\n * - plain `IMAGE` (no opt-in): OSD → Plotly.\n * - 3D napari (`NAPARI_VOLUME`/`NAPARI_ISOSURFACE`): napari-js → Plotly (OSD can't render 3D).\n */\n private imageBackend(): IVisualizer {\n const t = this.currentPlotType;\n // 2D image with a napari-js attempt (explicit napari image, or opt-in on the Image type).\n if (this.isNapariImageType(t) || (this.isImageType(t) && this.config.useNapariRenderer)) {\n if (!this.napariFellBack) return this.napari;\n if (!this.osdFellBack) return this.osd;\n return this.plotly;\n }\n // Plain Image type (no napari opt-in): OSD, then Plotly.\n if (this.isImageType(t)) {\n return this.osdFellBack ? this.plotly : this.osd;\n }\n // 3D napari types: napari-js, with Plotly as the only viable fallback.\n if (this.isNapari3dType(t)) {\n return this.napariFellBack ? this.plotly : this.napari;\n }\n return this.plotly;\n }\n\n /** Backend currently on screen — what ongoing zoom/tool/region ops act on. */\n private renderer(): IVisualizer {\n return this.lastRendered ?? this.plotly;\n }\n\n // System capabilities are Plotly's (the full-featured backend) so the UI\n // keeps offering every plot type regardless of which one is on screen.\n get capabilities(): ViewerCapabilities { return this.plotly.capabilities; }\n\n // ── render / viewport → active renderer ──────────────────────────────\n async load(imageInfo: IImageInfo, zIndex: number): Promise<any> {\n const backend = this.imageBackend();\n if (backend === this.napari) {\n try {\n return await this.napari.load(imageInfo, zIndex);\n } catch (err) {\n this.napariFellBack = true;\n // Mirror imageBackend()'s fallback so load + plot pick the same backend:\n // - 3D napari types have no 2D fallback → straight to Plotly.\n // - 2D image → OSD, then Plotly.\n if (this.isNapari3dType(this.currentPlotType)) {\n console.warn('[visualizer] napari-js load failed — falling back to Plotly.', err);\n return this.plotly.load(imageInfo, zIndex);\n }\n console.warn('[visualizer] napari-js load failed — falling back to OpenSeadragon.', err);\n return this.loadViaOsdThenPlotly(imageInfo, zIndex);\n }\n }\n if (backend === this.osd) {\n return this.loadViaOsdThenPlotly(imageInfo, zIndex);\n }\n return this.plotly.load(imageInfo, zIndex);\n }\n\n /** Try OSD; on failure fall back to Plotly for this image (not permanent — see reset()). */\n private async loadViaOsdThenPlotly(imageInfo: IImageInfo, zIndex: number): Promise<any> {\n try {\n return await this.osd.load(imageInfo, zIndex);\n } catch (err) {\n console.warn('[visualizer] OpenSeadragon load failed — falling back to Plotly for this image.', err);\n this.osdFellBack = true;\n return this.plotly.load(imageInfo, zIndex);\n }\n }\n plot(plotDiv: string, imageLoaded: any, imageInfo: IImageInfo, screenHeight: number,\n plotType: PlotType, inPlace?: boolean): Promise<boolean> {\n this.currentPlotType = plotType;\n // Apply the per-image region cache (snapshot old regions, restore the new\n // image's, clear selection) for whichever backend renders — Plotly does\n // this inside its own plot(), but OSD doesn't, so drive it here. Idempotent\n // for the same image, so it's safe to call on every (re)plot.\n this.plotly.setActiveImage(imageInfo);\n const next = this.imageBackend();\n // Both backends share the same div — tear down the outgoing one on switch.\n // Plotly must be *purged* (not reset, which re-draws empty axes) before OSD\n // takes the div.\n if (this.lastRendered && this.lastRendered !== next) {\n if (this.lastRendered === this.plotly) this.plotly.purgePlot();\n else this.lastRendered.reset();\n }\n this.lastRendered = next;\n return next.plot(plotDiv, imageLoaded, imageInfo, screenHeight, plotType, inPlace);\n }\n reloadAndPlot(): void { this.plotly.reloadAndPlot(); }\n reset(): void {\n // Start of a render cycle: re-enable napari-js/OSD attempts (clear any prior\n // per-image fallback) and tear down whatever's on screen.\n this.osdFellBack = false;\n this.napariFellBack = false;\n this.renderer().reset();\n }\n relayout(trueImageSize?: number[]): void { this.renderer().relayout(trueImageSize); }\n resetAxes(): void { this.renderer().resetAxes(); }\n autoscale(): void { this.renderer().autoscale(); }\n zoomIn(): void { this.renderer().zoomIn(); }\n zoomOut(): void { this.renderer().zoomOut(); }\n setDragMode(mode: string | false): void { this.renderer().setDragMode(mode); }\n // Set on both backends (not just the active renderer): consumers call this\n // before the first render, when `renderer()` is still the Plotly default, so\n // OSD must receive the flag to honour it at viewer creation.\n setNavigatorVisible(visible: boolean): void {\n this.osd.setNavigatorVisible(visible);\n this.plotly.setNavigatorVisible(visible);\n }\n // Set on both backends (see setNavigatorVisible): consumers may set it before\n // the first render, when the active renderer is still Plotly.\n setImageSmoothingEnabled(enabled: boolean): void {\n this.osd.setImageSmoothingEnabled(enabled);\n this.plotly.setImageSmoothingEnabled(enabled);\n }\n setShowStack(showstack: boolean): void { this.renderer().setShowStack(showstack); }\n setZIndex(zIndex: number): void { this.renderer().setZIndex(zIndex); }\n getTrueImageSize(): { width: number; height: number } | null { return this.renderer().getTrueImageSize(); }\n getCurrentImage(): Promise<Image | null> { return this.renderer().getCurrentImage(); }\n getDisplayedPixelData(): PixelData | null { return this.renderer().getDisplayedPixelData(); }\n getDisplayedSourceRect(): { x: number; y: number; width: number; height: number } | null {\n return this.renderer().getDisplayedSourceRect();\n }\n downloadImage(): void { this.renderer().downloadImage(); }\n exportComposite(): void { this.renderer().exportComposite(); }\n\n setPlotType(plotType: PlotType): void {\n this.currentPlotType = plotType;\n this.plotly.setPlotType(plotType);\n }\n setSurfaceDragMode(mode: string): void { this.renderer().setSurfaceDragMode(mode); }\n resetSurfaceCamera(): void { this.renderer().resetSurfaceCamera(); }\n setResolutionScale(scale: number): void { this.renderer().setResolutionScale?.(scale); }\n getResolutionScale(): number { return this.renderer().getResolutionScale?.() ?? 1; }\n getPlotTypeDescriptors(): PlotTypeDescriptor[] {\n // Plotly enumerates the full PLOT_TYPE_DESCRIPTORS map, which already includes the\n // napari-js WebGPU types (jit-ui#102) — so this single source covers them (no duplicates).\n return this.plotly.getPlotTypeDescriptors();\n }\n\n // ── long-lived observables + stack flags ──────────────────────────────────\n setStackLoading(b: boolean): void { this.plotly.setStackLoading(b); }\n // Cancel in-flight loading on every backend — the user's Cancel shouldn't depend on which one is\n // active. Only backends that stream frames (napari-js) do real work; the rest no-op. The concrete\n // backend classes don't all declare the optional contract method, so call it via IVisualizer.\n cancelLoading(): void {\n for (const backend of [this.plotly, this.osd, this.napari] as IVisualizer[]) {\n backend.cancelLoading?.();\n }\n }\n // Loading state is surfaced from whichever backend is doing the work: OSD and napari-js (volume\n // assembly) drive their own subjects, so merge all three into one stable stream the host\n // subscribes to once. (Previously hardcoded to Plotly, so napari/OSD progress never showed.)\n isStackLoading(): Observable<boolean> {\n return combineLatest([\n this.plotly.isStackLoading(),\n this.osd.isStackLoading(),\n this.napari.isStackLoading(),\n ]).pipe(map((flags) => flags.some(Boolean)));\n }\n getStackLoadingProgress(): Observable<number> {\n // Report the progress of whichever backend is ACTIVELY loading (max across active ones). A plain\n // merge let an idle backend's stale value win the stream on a re-load — leaving the bar below the\n // active backend's real progress (e.g. stuck ~⅓ while the % read 100). Gating by the loading flag\n // ignores idle backends, so the bar tracks the one doing the work and reaches 100%.\n const track = (v: IVisualizer): Observable<[number, boolean]> =>\n combineLatest([v.getStackLoadingProgress(), v.isStackLoading()]);\n return combineLatest([track(this.plotly), track(this.osd), track(this.napari)]).pipe(\n map((pairs) => {\n const active = pairs.filter(([, loading]) => loading).map(([p]) => p);\n return active.length ? Math.max(...active) : 0;\n }),\n );\n }\n getAutoscaleEvent(): Observable<any> { return this.plotly.getAutoscaleEvent(); }\n getIntensityProfile$(): Observable<IntensityProfile[]> { return this.plotly.getIntensityProfile$(); }\n // The intensity inset is a Plotly LINE chart — render it through Plotly, which\n // owns the profile stream regardless of which backend draws the main image.\n renderIntensityInset(divId: string, profiles: IntensityProfile[]): void {\n this.plotly.renderIntensityInset(divId, profiles); }\n\n // ── regions → active renderer ────────────────────────────────────────\n // Region *state* lives in the shared RegionStore; both backends implement\n // IRegionStore by delegating to it. We route through the active renderer\n // (not hardcoded Plotly) so the backend on screen also *renders* the change:\n // Plotly relayouts its shapes, OpenSeadragon's overlay redraws from the store\n // update event. Either way the same store is the single source of truth.\n setRegions(regions: Region[], showRegionLabel?: boolean, isRegionSaveOn?: boolean,\n fillColor?: string, append?: boolean): void {\n this.renderer().setRegions(regions, showRegionLabel, isRegionSaveOn, fillColor, append);\n }\n getRegions(): Region[] { return this.renderer().getRegions(); }\n getRegionPolygons(): any[] { return this.renderer().getRegionPolygons(); }\n getRegionUpdateEvent(): Observable<any[]> { return this.renderer().getRegionUpdateEvent(); }\n setSelectedShapeIndices(indices: number[]): void { this.renderer().setSelectedShapeIndices(indices); }\n selectRegion(region: Region): void { this.renderer().selectRegion(region); }\n getSelectedShapeIndices$(): Observable<number[]> { return this.renderer().getSelectedShapeIndices$(); }\n deleteActiveShape(): void { this.renderer().deleteActiveShape(); }\n getShowShapeLabel(): boolean { return this.renderer().getShowShapeLabel(); }\n getShapeColor(): string { return this.renderer().getShapeColor(); }\n getFillColor(): string { return this.renderer().getFillColor(); }\n getClassificationColors(): Map<string, string> { return this.renderer().getClassificationColors(); }\n setClassificationColor(label: string, color: string): void {\n this.renderer().setClassificationColor(label, color); }\n // Annotation-class presets live in the shared VisualizerStore (backend-neutral\n // session state), so route straight to it rather than through renderer(). (jit-ui#70)\n getPresetSet(): PresetSet { return this.store.getPresetSet(); }\n getPresetSet$(): Observable<PresetSet> { return this.store.getPresetSet$(); }\n setPresetSet(set: PresetSet): void { this.store.setPresetSet(set); }\n upsertClass(preset: ClassPreset): void { this.store.upsertClass(preset); }\n removeClass(name: string): void { this.store.removeClass(name); }\n resetPresets(): void { this.store.resetPresets(); }\n plotPreviousShapes(): void { this.renderer().plotPreviousShapes(); }\n setPreviousShapes(shapes: any[]): void { this.renderer().setPreviousShapes(shapes); }\n getPreviousShapes(): any[] { return this.renderer().getPreviousShapes(); }\n // Undo state is owned by the shared RegionStore (same instance for both\n // backends), so routing through the active renderer is safe and stable.\n undo(): void { this.renderer().undo(); }\n redo(): void { this.renderer().redo(); }\n canUndo(): boolean { return this.renderer().canUndo(); }\n canRedo(): boolean { return this.renderer().canRedo(); }\n getCanUndo$(): Observable<boolean> { return this.renderer().getCanUndo$(); }\n getCanRedo$(): Observable<boolean> { return this.renderer().getCanRedo$(); }\n resetUndoHistory(): void { this.renderer().resetUndoHistory(); }\n importRegions(geoJsonStr: string): Region[] { return this.renderer().importRegions(geoJsonStr); }\n exportRegions(regions: Region[]): void { this.renderer().exportRegions(regions); }\n getGeoJsonString(regions: Region[]): string { return this.renderer().getGeoJsonString(regions); }\n\n // ── Per-slice z-stack regions (jit-ui#93) — the RegionStore is shared across\n // backends, so routing to the active renderer hits the same store. ──────\n enterStackMode(slices: Map<number, Region[]>, initialZ?: number,\n saveLayout?: 'combined' | 'per-slice-file'): void {\n this.renderer().enterStackMode(slices, initialZ, saveLayout);\n }\n exitStackMode(): void { this.renderer().exitStackMode(); }\n isStackMode(): boolean { return this.renderer().isStackMode(); }\n getStackSaveLayout(): 'combined' | 'per-slice-file' { return this.renderer().getStackSaveLayout(); }\n setDisplaySlice(z: number): void { this.renderer().setDisplaySlice(z); }\n getSliceRegions(): Region[] { return this.renderer().getSliceRegions(); }\n getStackSaveSlices(): Map<number, Region[]> { return this.renderer().getStackSaveSlices(); }\n /** All slices' ANNOTATION regions for a z-stack save (jit-ui#93), each tagged\n * with its zero-based Region.z; profile lines excluded. Flat annotation set\n * outside stack mode. */\n getSliceAnnotationRegions(): Region[] {\n return this.renderer().getSliceRegions().filter((r) => !isProfileRegion(r));\n }\n /** Per-slice annotation regions to write on a folder-stack save (jit-ui#93):\n * slice index → that slice's annotation regions (profile lines excluded),\n * including now-empty slices that were loaded non-empty (so they overwrite). */\n getStackSaveAnnotationSlices(): Map<number, Region[]> {\n const out = new Map<number, Region[]>();\n for (const [z, regs] of this.renderer().getStackSaveSlices()) {\n out.set(z, regs.filter((r) => !isProfileRegion(r)));\n }\n return out;\n }\n\n /** Authoritative full-resolution image size for mask export. Prefers the\n * active renderer's reported size, falling back to the image metadata (x/y\n * are the full-res pixel dimensions used across the app). Rejects non-finite\n * or non-positive sizes — the Plotly bounds can yield NaN before a plot is\n * fully laid out, which would otherwise crash mask creation. */\n getMaskImageSize(): { width: number; height: number } | null {\n const valid = (s: { width: number; height: number } | null | undefined) =>\n s && Number.isFinite(s.width) && Number.isFinite(s.height) &&\n s.width >= 1 && s.height >= 1\n ? { width: Math.round(s.width), height: Math.round(s.height) }\n : null;\n\n const fromRenderer = valid(this.getTrueImageSize());\n if (fromRenderer) return fromRenderer;\n\n let meta: IImageMetadata[] = [];\n this.getImageMeta().subscribe((m) => (meta = m)).unsubscribe();\n const m0 = meta?.[0];\n return m0 ? valid({ width: m0.x, height: m0.y }) : null;\n }\n\n // ── IRegionEditorApi: annotation-only surface for the Region Editor ───\n // Intensity-profile lines (kind='profile') belong to the intensity tool, not\n // the editor. These methods give external consumers an annotation-only view\n // and guarantee profile lines are preserved. Routing (not the store) owns this\n // so writes/selection go through renderer() and the active backend re-renders\n // (Plotly relayouts its shapes in setRegions; it doesn't on regionUpdate$).\n\n getAnnotationRegions(): Region[] {\n return this.renderer().getRegions().filter((r) => !isProfileRegion(r));\n }\n setAnnotationRegions(regions: Region[], showRegionLabel?: boolean,\n isRegionSaveOn?: boolean, fillColor?: string): void {\n // Re-append the store's profile lines so an editor save/delete can't drop\n // them, then route through setRegions so the active backend re-renders.\n const profiles = this.renderer().getRegions().filter((r) => isProfileRegion(r));\n const annotations = (regions || []).filter((r) => !isProfileRegion(r));\n this.setRegions([...annotations, ...profiles], showRegionLabel, isRegionSaveOn, fillColor, false);\n }\n getSelectedRegions$(): Observable<Region[]> {\n // Map the internal index-based selection to the selected annotation regions.\n return this.getSelectedShapeIndices$().pipe(\n map((idxs) => {\n const regs = this.renderer().getRegions();\n return idxs\n .map((i) => regs[i])\n .filter((r): r is Region => !!r && !isProfileRegion(r));\n }),\n );\n }\n setSelectedRegions(regions: Region[]): void {\n const regs = this.renderer().getRegions();\n const indices = (regions || [])\n .map((r) => regs.findIndex((x) => x.id === r.id))\n .filter((i) => i >= 0);\n this.setSelectedShapeIndices(indices);\n }\n\n // ── tools → active renderer (run on either backend) ─────────────────\n // The wand, vertex eraser and zoom-to-box are implemented on both backends\n // via ICoordinateTransform (+ a viewport pixel readback for the wand), so they\n // follow the active renderer.\n setWandMode(active: boolean, options?: any): void { this.renderer().setWandMode(active, options); }\n setWandOptions(options: any): void { this.renderer().setWandOptions(options); }\n clearActiveWandRegion(): void { this.renderer().clearActiveWandRegion(); }\n setBrushMode(active: boolean, options?: any): void { this.renderer().setBrushMode(active, options); }\n setBrushOptions(options: any): void { this.renderer().setBrushOptions(options); }\n setVertexEraserMode(active: boolean): void { this.renderer().setVertexEraserMode(active); }\n setVertexEraserRadius(radius: number): void { this.renderer().setVertexEraserRadius(radius); }\n setZoomToBoxMode(active: boolean): void { this.renderer().setZoomToBoxMode(active); }\n segmentRectangles(): Promise<number> { return this.renderer().segmentRectangles(); }\n segmentRectanglesCellpose(): Promise<number> { return this.renderer().segmentRectanglesCellpose(); }\n setSamModel(id: string): void { this.renderer().setSamModel(id); }\n setSamPointMode(active: boolean): void { this.renderer().setSamPointMode(active); }\n commitSamPoints(): void { this.renderer().commitSamPoints(); }\n clearSamPoints(): void { this.renderer().clearSamPoints(); }\n\n // ── display options ──────────────────────────────────────────────────\n // State lives in the shared VisualizerStore — reads go straight to it.\n // The two SETTERS still route through Plotly because its implementations\n // carry render glue beyond the store write (a live Plotly.restyle of\n // colorscale/reversescale on the mounted heatmap); OSD recolors via its own\n // store subscription either way.\n getColormap(): Observable<any> { return this.store.getColormap(); }\n setColormap(colormap: any): void { this.plotly.setColormap(colormap); }\n getColormapOptions(): any { return this.store.getColormapOptions(); }\n getReverseScale(): Observable<boolean> { return this.store.getReverseScale(); }\n setReverseScale(reverscale: any): void { this.plotly.setReverseScale(reverscale); }\n setImageMeta(imageMeta: IImageMetadata[]): void { this.store.setImageMeta(imageMeta); }\n getImageMeta(): Observable<IImageMetadata[]> { return this.store.getImageMeta(); }\n\n // ── IChannelHistogramApi: Channels & Histogram pane surface ───────────\n // Channel/grayscale/invert state lives in the shared VisualizerStore; both\n // backends subscribe and recolor live, so setters just write the store. The\n // histogram comes from whichever backend is on screen (its native pixels).\n getHistogram(channelIndex: number, bins: number): IHistogram | null {\n return this.renderer().getHistogram(channelIndex, bins);\n }\n getHistogram$(channelIndex: number, bins: number): Observable<IHistogram | null> {\n return this.renderer().getHistogram$(channelIndex, bins);\n }\n /** Export the underlying data (16-bit multi-band TIFF) via the active backend. */\n exportData(): void { this.renderer().exportData(); }\n getChannels$(): Observable<IChannelState[]> { return this.store.getChannelStates(); }\n setChannelState(index: number, partial: Partial<IChannelState>): void {\n this.store.setChannelState(index, partial);\n }\n resetContrast(indices: number[]): void {\n // Full reset: window (0..255), gamma (1) AND the channel's default tint.\n for (const i of indices) this.store.resetChannelState(i);\n }\n /** Auto-window each channel by saturating `saturation` (0..1) of pixels at each\n * end of its histogram (skipping outlier first/last bins). */\n autoContrast(indices: number[], saturation: number): void {\n for (const i of indices) {\n const h = this.renderer().getHistogram(i, 256);\n if (!h) continue;\n const [min, max] = autoWindowFromHistogram(h, saturation);\n if (max > min) this.store.setChannelState(i, { min, max });\n }\n }\n getGrayscale$(): Observable<boolean> { return this.store.getGrayscale(); }\n setGrayscale(on: boolean): void { this.store.setGrayscale(on); }\n getInvert$(): Observable<boolean> { return this.store.getInvert(); }\n setInvert(on: boolean): void { this.store.setInvert(on); }\n\n /**\n * The active backend's region overlay. Falls back to Plotly's when the active backend\n * (OSD or napari-js) is selected but a plot isn't mounted yet, so callers always get a\n * usable overlay.\n */\n getRegionOverlay(): IRegionOverlay {\n const r = this.renderer();\n if (r === this.osd) {\n return this.osd.getRegionOverlay() ?? this.plotly.getRegionOverlay();\n }\n if (r === this.napari) {\n return this.napari.getRegionOverlay() ?? this.plotly.getRegionOverlay();\n }\n return this.plotly.getRegionOverlay();\n }\n\n /**\n * Isosurface controls when available — always Plotly's, since the isosurface\n * plot type renders on Plotly (OSD only handles the image type).\n */\n getIsosurfaceControls(): IIsosurfaceControls | null { return this.renderer().getIsosurfaceControls(); }\n\n /** 3D scene controls — always Plotly's, since the 3D plot types render on\n * Plotly (OSD only handles the image type). */\n getSurface3dControls(): ISurface3dControls | null { return this.renderer().getSurface3dControls(); }\n\n /** Intensity (line-ROI) controls — always Plotly's, since the line profiles\n * render their inset on Plotly regardless of which backend draws the image. */\n getIntensityControls(): IIntensityControls | null { return this.plotly.getIntensityControls(); }\n\n /** Load pixel frames for intensity sampling when OpenSeadragon owns the image\n * (it doesn't feed Plotly's frame cache). No-op needed when Plotly renders. */\n ensureIntensitySampling(imageInfo: IImageInfo, zIndex: number): Promise<void> {\n return this.plotly.ensureIntensitySampling(imageInfo, zIndex);\n }\n\n /** Visible-region changes from the OpenSeadragon viewer (image-pixel coords),\n * so the intensity inset can re-sample at the current zoom level. Plotly's own\n * high-def zoom updates the sampling cache inline, so only OSD feeds this. */\n getViewportChange$(): Observable<{ x: number; y: number; width: number; height: number }> {\n return this.osd.getViewportChange$();\n }\n\n /** Re-sample the intensity profiles from a fresh crop of the given image-pixel\n * ROI at display resolution (sampling always lives in Plotly). */\n refreshIntensitySamplingForRoi(x: number, y: number, width: number, height: number, zIndex: number): void {\n this.plotly.refreshIntensitySamplingForRoi(x, y, width, height, zIndex);\n }\n\n unsubscribe(): void {\n this.plotly.unsubscribe();\n this.osd.unsubscribe();\n }\n}\n","import { NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { FormsModule } from '@angular/forms';\n\nimport { ToolbarModule } from 'primeng/toolbar';\nimport { ButtonModule } from 'primeng/button';\nimport { MenuModule } from 'primeng/menu';\nimport { DropdownModule } from 'primeng/dropdown';\nimport { SliderModule } from 'primeng/slider';\nimport { TreeSelectModule } from 'primeng/treeselect';\nimport { InputNumberModule } from 'primeng/inputnumber';\nimport { DialogModule } from 'primeng/dialog';\nimport { ContextMenuModule } from 'primeng/contextmenu';\nimport { ProgressBarModule } from 'primeng/progressbar';\nimport { ToastModule } from 'primeng/toast';\nimport { TooltipModule } from 'primeng/tooltip';\nimport { RippleModule } from 'primeng/ripple';\nimport { TableModule } from 'primeng/table';\nimport { PaginatorModule } from 'primeng/paginator';\nimport { OverlayPanelModule } from 'primeng/overlaypanel';\nimport { ConfirmDialogModule } from 'primeng/confirmdialog';\nimport { InputTextModule } from 'primeng/inputtext';\nimport { CheckboxModule } from 'primeng/checkbox';\nimport { RadioButtonModule } from 'primeng/radiobutton';\nimport { SelectButtonModule } from 'primeng/selectbutton';\n\nimport { VisualizerComponent } from './visualizer.component';\nimport { ToolbarComponent } from './toolbar/toolbar.component';\nimport { RegionEditorComponent } from './region-editor/region-editor.component';\nimport { HexColorPickerComponent } from './hex-color-picker/hex-color-picker.component';\nimport { ChannelHistogramComponent } from './channel-histogram/channel-histogram.component';\nimport { RoutingVisualizerService } from './routing-visualizer.service';\nimport { VISUALIZER } from './contracts/visualizer.contract';\nimport { REGION_EDITOR_API } from './contracts/region-editor-api.contract';\nimport { CHANNEL_HISTOGRAM_API } from './contracts/channel-histogram-api.contract';\n\n/**\n * Self-contained plotting UI: the {@link VisualizerComponent} (plot surface\n * + render orchestration), its {@link ToolbarComponent}, and the\n * {@link RegionEditorComponent} (the Regions tab table/editor). Consumers embed\n * `<visualizer>` / `<region-editor>` and need know nothing about the toolbar,\n * the rendering backends, or region file I/O (supplied via the REGION_IO_PORT).\n *\n * Also exports {@link HexColorPickerComponent} (`<hex-color-picker>`) as a\n * standalone reusable picker (`[color]` in, `(colorChange)` out) so consuming\n * apps can use it on its own, the same way as the visualizer and region editor.\n */\n@NgModule({\n declarations: [\n VisualizerComponent,\n ToolbarComponent,\n RegionEditorComponent,\n HexColorPickerComponent,\n ChannelHistogramComponent,\n ],\n imports: [\n CommonModule,\n FormsModule,\n ToolbarModule,\n ButtonModule,\n MenuModule,\n DropdownModule,\n SliderModule,\n TreeSelectModule,\n InputNumberModule,\n DialogModule,\n ContextMenuModule,\n ProgressBarModule,\n ToastModule,\n TooltipModule,\n RippleModule,\n TableModule,\n PaginatorModule,\n OverlayPanelModule,\n ConfirmDialogModule,\n InputTextModule,\n CheckboxModule,\n RadioButtonModule,\n SelectButtonModule,\n ],\n exports: [VisualizerComponent, RegionEditorComponent, HexColorPickerComponent, ChannelHistogramComponent],\n providers: [\n // Internal backend wiring. All three host-facing contracts are served by the\n // RoutingVisualizerService (the Plotly/OpenSeadragon selector), so consumers\n // depend only on the tokens and never the concrete router. Owned by the\n // library so importing VisualizationModule is enough — the host supplies only\n // the *ports* (IMAGE_STATE_PORT / TILE_ACCESS_PORT / REGION_IO_PORT) and\n // VIZ_CONFIG, which are app-specific. A consumer needing an isolated instance\n // (e.g. a modal that mustn't share region/image state) re-provides this same\n // set at component scope, which shadows these defaults for its subtree.\n { provide: VISUALIZER, useExisting: RoutingVisualizerService },\n { provide: REGION_EDITOR_API, useExisting: RoutingVisualizerService },\n { provide: CHANNEL_HISTOGRAM_API, useExisting: RoutingVisualizerService },\n ],\n})\nexport class VisualizationModule {}\n","import { Provider } from '@angular/core';\n\nimport { RoutingVisualizerService } from './routing-visualizer.service';\nimport { PlotlyService } from './implementations/plotly/plotly.service';\nimport { OpenSeadragonVisualizerService } from './implementations/osd/openseadragon-visualizer.service';\nimport { NapariVisualizerService } from './implementations/napari-js/napari-visualizer.service';\nimport { VisualizerStore } from './store/visualizer-store.service';\nimport { RegionStore } from './store/region-store.service';\nimport { WandToolService } from './toolbar/wand/wand-tool.service';\nimport { VertexEraserToolService } from './toolbar/vertex-eraser/vertex-eraser-tool.service';\nimport { ZoomToBoxToolService } from './toolbar/zoom-to-box/zoom-to-box-tool.service';\nimport { VISUALIZER } from './contracts/visualizer.contract';\nimport { REGION_EDITOR_API } from './contracts/region-editor-api.contract';\nimport { CHANNEL_HISTOGRAM_API } from './contracts/channel-histogram-api.contract';\n\n/**\n * A self-contained, isolated visualization backend chain for a component subtree.\n *\n * The chain services are `providedIn: 'root'` singletons, so by default the whole\n * app shares one viewer's state (regions, image, channels, render handles) — which\n * is correct for the single main viewer. A consumer that needs a SECOND, independent\n * viewer (e.g. a modal that mounts `<visualizer>` over the live main view\n * and must not clobber its regions/image) drops this into its component `providers`:\n *\n * ```ts\n * @Component({\n * ...,\n * providers: [\n * ...provideVisualization(), // isolated chain instance\n * // plus the host ports + config for THIS viewer:\n * { provide: IMAGE_STATE_PORT, useClass: MyImageStateAdapter },\n * { provide: TILE_ACCESS_PORT, useClass: MyTileAccessAdapter },\n * { provide: REGION_IO_PORT, useClass: MyRegionIoAdapter },\n * { provide: VIZ_CONFIG, useValue: { slideCropServer: '' } },\n * ],\n * })\n * ```\n *\n * Component-scoped providers shadow the root singletons for that subtree, so the\n * embedded viewer gets its own router/Plotly/OSD/stores/tools while the rest of the\n * app keeps the default root instance.\n *\n * Lists EVERY stateful service in the chain. Stateless collaborators (HttpClient,\n * MessageService, WandService) deliberately resolve to root — they hold no\n * per-viewer state, so sharing them is correct and keeps this list minimal. When a\n * new stateful service joins the rendering chain, add it here too.\n */\nexport function provideVisualization(): Provider[] {\n return [\n RoutingVisualizerService,\n PlotlyService,\n OpenSeadragonVisualizerService,\n NapariVisualizerService,\n VisualizerStore,\n RegionStore,\n WandToolService,\n VertexEraserToolService,\n ZoomToBoxToolService,\n // The three host-facing contracts are all served by the router — bound here at\n // the SAME (component) scope so they resolve to the isolated instance, not root.\n { provide: VISUALIZER, useExisting: RoutingVisualizerService },\n { provide: REGION_EDITOR_API, useExisting: RoutingVisualizerService },\n { provide: CHANNEL_HISTOGRAM_API, useExisting: RoutingVisualizerService },\n ];\n}\n","/**\n * Public API of the jax-image-visualization library. External consumers import\n * ONLY from here (`@jax-data-science/sci-image-visualizer`); everything else under `lib/` is\n * internal. The surface is contracts + tokens + neutral models + the Angular\n * module, plus the routing service the host's composition root binds the tokens\n * to (`useExisting`).\n */\n\n// ── Contracts & DI tokens ────────────────────────────────────────────────\nexport * from './lib/contracts/visualizer.contract';\nexport * from './lib/contracts/region-editor-api.contract';\nexport * from './lib/contracts/ports/image-state.port';\nexport * from './lib/contracts/ports/tile-access.port';\nexport * from './lib/contracts/ports/region-io.port';\nexport * from './lib/contracts/ports/preferences.port';\nexport * from './lib/contracts/channel-histogram-api.contract';\nexport * from './lib/contracts/viz-config';\nexport * from './lib/contracts/image.contract';\nexport * from './lib/contracts/plot-type';\nexport * from './lib/contracts/toolbar-config';\nexport * from './lib/contracts/capabilities.contract';\nexport * from './lib/contracts/region-overlay.contract';\nexport * from './lib/contracts/display-types';\nexport * from './lib/contracts/sam.contract';\nexport * from './lib/contracts/cell-segmenter.contract';\nexport { CellposeSegmenterService } from './lib/toolbar/segmentation/cellpose-segmenter.service';\n\n// ── Generic client-side image utilities (shared with the host's pipeline) ──\nexport { ProcessingImage } from './lib/processing/processing-image';\nexport { cropImage, CropImageOptions } from './lib/processing/image-crop';\nexport { ImageConverterService } from './lib/processing/image-converter.service';\n\n// ── SAM model registry (host configures hosted ONNX URLs once available) ──\nexport {\n SAM_MODELS, DEFAULT_SAM_MODEL_ID, getSamModel, isSamModelReady, setSamModelUrls,\n setDefaultSamModel, getDefaultSamModelId,\n} from './lib/toolbar/segmentation/sam-model-registry';\n\n// ── onnxruntime-web WASM location (host overrides once, at app init) ───────\nexport { setOrtWasmBase, getOrtWasmBase } from './lib/toolbar/segmentation/ort-runtime-config';\n\n// ── Neutral data models ──────────────────────────────────────────────────\nexport * from './lib/models/region';\nexport * from './lib/models/class-preset';\nexport { ShapeSelection } from './lib/models/shape';\n\n// ── Angular module + composition-root service ────────────────────────────\nexport { VisualizationModule } from './lib/visualization.module';\nexport { RoutingVisualizerService } from './lib/routing-visualizer.service';\n// Provider factory for an isolated, component-scoped viewer instance (e.g. a\n// modal that must not share the main viewer's region/image state).\nexport { provideVisualization } from './lib/provide-visualization';\n\n// ── Public components (exported by VisualizationModule) ───────────────────\n// ng-packagr requires module-exported components to be reachable from the\n// entry point so consumers get their types; these are the embeddable elements\n// (`<visualizer>`, `<region-editor>`, `<hex-color-picker>`).\nexport { VisualizerComponent } from './lib/visualizer.component';\nexport { RegionEditorComponent } from './lib/region-editor/region-editor.component';\nexport { HexColorPickerComponent } from './lib/hex-color-picker/hex-color-picker.component';\nexport { ChannelHistogramComponent } from './lib/channel-histogram/channel-histogram.component';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":["i1.WandService","i1","i4","i2","i3","i6","i7","i8","i9","i10","i11","i12","i19.HexColorPickerComponent","i5","i12.HexColorPickerComponent","i13","i14","i15","i16.ToolbarComponent","i17.RegionEditorComponent","i18.ChannelHistogramComponent","i1.VisualizerStore","i9.VertexEraserToolService","i10.ZoomToBoxToolService","i11.VisualizerStore","i12.RegionStore","niceLength","formatUm","i2.WandToolService","i3.BrushToolService","i4.SamToolService","i5.SamPointToolService","i6.CellSegmentToolService","i2.RegionStore","i3.WandToolService","i4.BrushToolService","i5.VertexEraserToolService","i6.ZoomToBoxToolService","i7.SamToolService","i8.SamPointToolService","i9.CellSegmentToolService"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqWA;;;;;;AAMG;MACU,UAAU,GAAG,IAAI,cAAc,CAAc,YAAY;;AC5QtE;MACa,iBAAiB,GAAG,IAAI,cAAc,CAAmB,mBAAmB;;MChE5E,gBAAgB,GAAG,IAAI,cAAc,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