From e859457da476b8f84c49faa6e0b0cd7dc436b602 Mon Sep 17 00:00:00 2001 From: Sean Martin Date: Tue, 3 Nov 2026 00:13:26 +0100 Subject: [PATCH 1/6] feat: add labels as related data source and auto open Supports 0.5 and 0.4, each label image becomes a seg in auto --- src/datasource/index.ts | 9 ++++++ src/datasource/zarr/frontend.ts | 52 +++++++++++++++++++++++++----- src/datasource/zarr/ome.spec.ts | 40 ++++++++++++++++++++++- src/datasource/zarr/ome.ts | 22 +++++++++++++ src/layer/annotation/index.ts | 7 +++++ src/layer/image/index.ts | 6 ++++ src/layer/index.ts | 7 +++++ src/layer/multi_channel_setup.ts | 54 +++++++++++++++++++++++++++----- src/layer/segmentation/index.ts | 6 ++++ src/layer/single_mesh/index.ts | 6 ++++ 10 files changed, 194 insertions(+), 15 deletions(-) diff --git a/src/datasource/index.ts b/src/datasource/index.ts index 38d2332bc5..c4bef34e69 100644 --- a/src/datasource/index.ts +++ b/src/datasource/index.ts @@ -38,6 +38,7 @@ import { parseUrlSuffix, splitPipelineUrl, } from "#src/kvstore/url.js"; +import type { LayerTypeName } from "#src/layer/index.js"; import type { MeshSource, MultiscaleMeshSource } from "#src/mesh/frontend.js"; import type { SegmentPropertyMap } from "#src/segmentation_display_state/property_map.js"; import type { SegmentationGraphSource } from "#src/segmentation_graph/source.js"; @@ -189,6 +190,13 @@ export interface SingleChannelMetadata { coefficient?: number; } +// Another data source that belongs with this one, unlike a subsource, which is part of it. +export interface RelatedDataSource { + readonly name: string; + readonly url: string; + readonly suggestedLayerType: LayerTypeName; +} + export interface DataSource { subsources: DataSubsourceEntry[]; modelTransform: CoordinateSpaceTransform; @@ -196,6 +204,7 @@ export interface DataSource { state?: Trackable; canonicalUrl?: string; channelMetadata?: ChannelMetadata; + relatedSources?: RelatedDataSource[]; } export interface DataSourceRedirect { diff --git a/src/datasource/zarr/frontend.ts b/src/datasource/zarr/frontend.ts index 9197cdebe5..b7d5dde8d3 100644 --- a/src/datasource/zarr/frontend.ts +++ b/src/datasource/zarr/frontend.ts @@ -29,6 +29,7 @@ import type { DataSource, GetKvStoreBasedDataSourceOptions, KvStoreBasedDataSourceProvider, + RelatedDataSource, } from "#src/datasource/index.js"; import { getKvStorePathCompletions } from "#src/datasource/kvstore_completions.js"; import { VolumeChunkSourceParameters } from "#src/datasource/zarr/base.js"; @@ -50,7 +51,10 @@ import { parseV3Metadata, } from "#src/datasource/zarr/metadata/parse.js"; import type { OmeMultiscaleMetadata } from "#src/datasource/zarr/ome.js"; -import { parseOmeMetadata } from "#src/datasource/zarr/ome.js"; +import { + parseOmeLabelsGroup, + parseOmeMetadata, +} from "#src/datasource/zarr/ome.js"; import type { AutoDetectRegistry } from "#src/kvstore/auto_detect.js"; import { simpleFilePresenceAutoDetectDirectorySpec } from "#src/kvstore/auto_detect.js"; import { WithSharedKvStoreContext } from "#src/kvstore/chunk_source_frontend.js"; @@ -474,6 +478,34 @@ function resolveUrl(options: GetKvStoreBasedDataSourceOptions) { }; } +async function getOmeLabelSources( + sharedKvStoreContext: SharedKvStoreContext, + imageUrl: string, + zarrVersion: 2 | 3, + options: Partial, +): Promise { + const labelsGroupUrl = kvstoreEnsureDirectoryPipelineUrl( + joinBaseUrlAndPath(imageUrl, "labels"), + ); + try { + const metadata = await getMetadata(sharedKvStoreContext, labelsGroupUrl, { + ...options, + zarrVersion, + expectedNodeType: "group", + }); + if (metadata === undefined) return undefined; + return parseOmeLabelsGroup( + labelsGroupUrl, + metadata.userAttributes, + zarrVersion, + ); + } catch (error) { + // A bad labels group must not stop the image from opening. + console.warn(`Ignoring OME labels group ${labelsGroupUrl}:`, error); + return undefined; + } +} + export class ZarrDataSource implements KvStoreBasedDataSourceProvider { constructor(public zarrVersion: 2 | 3 | undefined = undefined) {} get scheme() { @@ -515,6 +547,7 @@ export class ZarrDataSource implements KvStoreBasedDataSourceProvider { explicitDimensionSeparator: dimensionSeparator, }); let channelMetadata: ChannelMetadata | undefined; + let relatedSources: RelatedDataSource[] | undefined; if (metadata === undefined) { throw new Error("No zarr metadata found"); } @@ -530,15 +563,19 @@ export class ZarrDataSource implements KvStoreBasedDataSourceProvider { throw new Error("Neither array nor OME multiscale metadata found"); } channelMetadata = omeMetadata.channels; - multiscaleInfo = await resolveOmeMultiscale( - sharedKvStoreContext, - omeMetadata.multiscale, - { + [multiscaleInfo, relatedSources] = await Promise.all([ + resolveOmeMultiscale(sharedKvStoreContext, omeMetadata.multiscale, { ...progressOptions, zarrVersion: metadata.zarrVersion, explicitDimensionSeparator: dimensionSeparator, - }, - ); + }), + getOmeLabelSources( + sharedKvStoreContext, + kvStoreUrl, + metadata.zarrVersion, + progressOptions, + ), + ]); } else { multiscaleInfo = getMultiscaleInfoForSingleArray( kvStoreUrl, @@ -560,6 +597,7 @@ export class ZarrDataSource implements KvStoreBasedDataSourceProvider { canonicalUrl: `${kvStoreUrl}|zarr${metadata.zarrVersion}:`, modelTransform, channelMetadata, + relatedSources, subsources: [ { id: "default", diff --git a/src/datasource/zarr/ome.spec.ts b/src/datasource/zarr/ome.spec.ts index 88fff870a9..6a90ebb9b3 100644 --- a/src/datasource/zarr/ome.spec.ts +++ b/src/datasource/zarr/ome.spec.ts @@ -15,7 +15,10 @@ */ import { describe, it, expect } from "vitest"; -import { parseOmeMetadata } from "#src/datasource/zarr/ome.js"; +import { + parseOmeLabelsGroup, + parseOmeMetadata, +} from "#src/datasource/zarr/ome.js"; import { createIdentity } from "#src/util/matrix.js"; const intrinsicCoordinateSystem = { @@ -1417,3 +1420,38 @@ it("should handle anisotropic scales with rotations for 0.6 (issue #952)", () => // Column 4 - [0, 0, 0, 1] expect(baseTransform.slice(12)).toEqual(new Float64Array([0, 0, 0, 1])); }); + +describe("OME-Zarr labels group", () => { + it("lists the label images of a 0.5 labels group as segmentation sources", () => { + const attrs = { + ome: { version: "0.5", labels: ["cells", "nuclei/v2"] }, + }; + expect( + parseOmeLabelsGroup("http://host/image.zarr/labels/", attrs, 3), + ).toEqual([ + { + name: "cells", + url: "http://host/image.zarr/labels/cells/|zarr3:", + suggestedLayerType: "segmentation", + }, + { + name: "nuclei/v2", + url: "http://host/image.zarr/labels/nuclei/v2/|zarr3:", + suggestedLayerType: "segmentation", + }, + ]); + }); + + it("lists the label images of a 0.4 labels group as segmentation sources", () => { + const attrs = { labels: ["cells"] }; + expect( + parseOmeLabelsGroup("http://host/image.zarr/labels/", attrs, 2), + ).toEqual([ + { + name: "cells", + url: "http://host/image.zarr/labels/cells/|zarr2:", + suggestedLayerType: "segmentation", + }, + ]); + }); +}); diff --git a/src/datasource/zarr/ome.ts b/src/datasource/zarr/ome.ts index 4cc7261db6..cc6ff09518 100644 --- a/src/datasource/zarr/ome.ts +++ b/src/datasource/zarr/ome.ts @@ -19,6 +19,7 @@ import { makeCoordinateSpace } from "#src/coordinate_transform.js"; import type { SingleChannelMetadata, ChannelMetadata, + RelatedDataSource, } from "#src/datasource/index.js"; import { joinBaseUrlAndPath, @@ -38,6 +39,7 @@ import { verifyObject, verifyObjectProperty, verifyOptionalObjectProperty, + verifyStringArray, verifyString, } from "#src/util/json.js"; import { clampToInterval } from "#src/util/lerp.js"; @@ -830,6 +832,26 @@ function parseOmeMultiscale( } } +export function parseOmeLabelsGroup( + labelsGroupUrl: string, + attrs: unknown, + zarrVersion: 2 | 3, +): RelatedDataSource[] | undefined { + verifyObject(attrs); + const metadata = + verifyOptionalObjectProperty(attrs, "ome", verifyObject) ?? attrs; + const paths = verifyOptionalObjectProperty( + metadata, + "labels", + verifyStringArray, + ); + return paths?.map((path) => ({ + name: path, + url: `${kvstoreEnsureDirectoryPipelineUrl(joinBaseUrlAndPath(labelsGroupUrl, path))}|zarr${zarrVersion}:`, + suggestedLayerType: "segmentation", + })); +} + export function parseOmeMetadata( url: string, attrs: any, diff --git a/src/layer/annotation/index.ts b/src/layer/annotation/index.ts index 55c1a33463..9705d140ae 100644 --- a/src/layer/annotation/index.ts +++ b/src/layer/annotation/index.ts @@ -952,6 +952,13 @@ for (const control of Object.values(LAYER_CONTROLS)) { registerLayerControl(AnnotationUserLayer, control); } +declare module "#src/layer/index.js" { + interface RegisteredLayerTypes { + annotation: AnnotationUserLayer; + pointAnnotation: AnnotationUserLayer; + } +} + registerLayerType(AnnotationUserLayer); registerLayerType(AnnotationUserLayer, "pointAnnotation"); diff --git a/src/layer/image/index.ts b/src/layer/image/index.ts index b58b7cbaa0..30bc93e2c3 100644 --- a/src/layer/image/index.ts +++ b/src/layer/image/index.ts @@ -598,6 +598,12 @@ class ShaderCodeOverlay extends Overlay { } } +declare module "#src/layer/index.js" { + interface RegisteredLayerTypes { + image: ImageUserLayer; + } +} + registerLayerType(ImageUserLayer); registerVolumeLayerType(VolumeType.IMAGE, ImageUserLayer); // Use ImageUserLayer as a fallback layer type if there is a `volume` subsource. diff --git a/src/layer/index.ts b/src/layer/index.ts index fad0e1400e..6e65e78362 100644 --- a/src/layer/index.ts +++ b/src/layer/index.ts @@ -2355,6 +2355,13 @@ export class LayerSubsetSpecification extends LayerListSpecification { export type UserLayerConstructor = typeof UserLayer & AnyConstructor; +export interface RegisteredLayerTypes { + new: NewUserLayer; + auto: AutoUserLayer; +} + +export type LayerTypeName = keyof RegisteredLayerTypes; + export const layerTypes = new Map(); const volumeLayerTypes = new Map(); export interface LayerTypeGuess { diff --git a/src/layer/multi_channel_setup.ts b/src/layer/multi_channel_setup.ts index 032d1ee063..ebdc28d313 100644 --- a/src/layer/multi_channel_setup.ts +++ b/src/layer/multi_channel_setup.ts @@ -19,7 +19,10 @@ import { makeCoordinateSpace, permuteCoordinateSpace, } from "#src/coordinate_transform.js"; -import type { SingleChannelMetadata } from "#src/datasource/index.js"; +import type { + RelatedDataSource, + SingleChannelMetadata, +} from "#src/datasource/index.js"; import type { ImageUserLayer } from "#src/layer/image/index.js"; import { type LayerListSpecification, @@ -168,6 +171,33 @@ function getLayerChannelMetadata( return channels?.[channelIndex]; } +function getRelatedSources(layer: ManagedUserLayer): RelatedDataSource[] { + const loadState = getLoadState(layer); + if (!loadState || loadState.error) return []; + return loadState.dataSource.relatedSources ?? []; +} + +function makeRelatedLayers( + managedLayer: ManagedUserLayer, + makeLayer: MakeLayerFn, + startingName: string, + insertionIndex: number | undefined, +): ManagedUserLayer[] { + return getRelatedSources(managedLayer).map((relatedSource, relatedIndex) => { + const newLayer = makeLayer( + managedLayer.manager, + `${startingName} ${relatedSource.name}`, + { type: relatedSource.suggestedLayerType, source: relatedSource.url }, + ); + managedLayer.manager.add( + newLayer, + insertionIndex === undefined ? undefined : insertionIndex + relatedIndex, + ); + newLayer.setArchived(relatedIndex > 3); + return newLayer; + }); +} + function checkLayerInputMetadataForErrors(layer: ManagedUserLayer): boolean { // If all the ranges are the same and the colors are black, then we can // assume that the input metadata is not set up correctly @@ -367,7 +397,7 @@ export function createImageLayerAsMultiChannel( "Input omera metadata is not set up correctly. Colors are either missing or all close to black, and all ranges are the same or missing. Using default values for display purposes.", ); } - const newChannelLayers: ManagedUserLayer[] = []; + const newLayers: ManagedUserLayer[] = []; for (let i = 0; i < totalLocalChannels; i++) { const channelMetadata = getLayerChannelMetadata(managedLayer, i); const { localPosition, chanName } = getAdjustedLocalPositionAndName(i); @@ -394,7 +424,7 @@ export function createImageLayerAsMultiChannel( parentIndex !== -1 ? parentIndex + i : undefined, ); addedLayer = newLayer; - newChannelLayers.push(newLayer); + newLayers.push(newLayer); } setupLayerPostCreation( addedLayer, @@ -405,20 +435,30 @@ export function createImageLayerAsMultiChannel( ignoreInputMetadata, ); } - // Propagate new channel layers to all layer group subsets that contain the original managed layer + const parentIndex = + managedLayer.manager.layerManager.managedLayers.indexOf(managedLayer); + newLayers.push( + ...makeRelatedLayers( + managedLayer, + makeLayer, + startingName, + parentIndex !== -1 ? parentIndex + totalLocalChannels : undefined, + ), + ); + // Propagate new layers to all layer group subsets that contain the original managed layer // The initial manager.add() above only adds to the layer's own manager and its owner // Update other subsets referencing the original layer const { root } = managedLayer.manager; - if (newChannelLayers.length > 0) { + if (newLayers.length > 0) { for (const subset of root.subsets) { // Skip the subset that is the current manager if (subset === managedLayer.manager) continue; const subsetIndex = subset.layerManager.managedLayers.indexOf(managedLayer); if (subsetIndex === -1) continue; - for (let j = 0; j < newChannelLayers.length; j++) { + for (let j = 0; j < newLayers.length; j++) { subset.layerManager.addManagedLayer( - newChannelLayers[j].addRef(), + newLayers[j].addRef(), subsetIndex + 1 + j, ); } diff --git a/src/layer/segmentation/index.ts b/src/layer/segmentation/index.ts index 8fc24b8fd4..ef8bd718ab 100644 --- a/src/layer/segmentation/index.ts +++ b/src/layer/segmentation/index.ts @@ -1394,6 +1394,12 @@ export class SegmentationUserLayer extends Base { registerLayerControls(SegmentationUserLayer); +declare module "#src/layer/index.js" { + interface RegisteredLayerTypes { + segmentation: SegmentationUserLayer; + } +} + registerLayerType(SegmentationUserLayer); registerVolumeLayerType(VolumeType.SEGMENTATION, SegmentationUserLayer); registerLayerTypeDetector((subsource) => { diff --git a/src/layer/single_mesh/index.ts b/src/layer/single_mesh/index.ts index cbd65286a4..2f4d5c3bac 100644 --- a/src/layer/single_mesh/index.ts +++ b/src/layer/single_mesh/index.ts @@ -268,6 +268,12 @@ class ShaderCodeOverlay extends Overlay { } } +declare module "#src/layer/index.js" { + interface RegisteredLayerTypes { + mesh: SingleMeshUserLayer; + } +} + registerLayerType(SingleMeshUserLayer); registerLayerTypeDetector((subsource) => { if (subsource.singleMesh !== undefined) { From 7a2ac91db595e590ff384f0830fe91a145ac60aa Mon Sep 17 00:00:00 2001 From: Sean Martin Date: Tue, 3 Nov 2026 13:33:28 +0100 Subject: [PATCH 2/6] refactor: simplify make layers for ref --- src/layer/multi_channel_setup.ts | 48 +++++++++++--------------------- 1 file changed, 17 insertions(+), 31 deletions(-) diff --git a/src/layer/multi_channel_setup.ts b/src/layer/multi_channel_setup.ts index ebdc28d313..2cf9ceb0f5 100644 --- a/src/layer/multi_channel_setup.ts +++ b/src/layer/multi_channel_setup.ts @@ -177,27 +177,6 @@ function getRelatedSources(layer: ManagedUserLayer): RelatedDataSource[] { return loadState.dataSource.relatedSources ?? []; } -function makeRelatedLayers( - managedLayer: ManagedUserLayer, - makeLayer: MakeLayerFn, - startingName: string, - insertionIndex: number | undefined, -): ManagedUserLayer[] { - return getRelatedSources(managedLayer).map((relatedSource, relatedIndex) => { - const newLayer = makeLayer( - managedLayer.manager, - `${startingName} ${relatedSource.name}`, - { type: relatedSource.suggestedLayerType, source: relatedSource.url }, - ); - managedLayer.manager.add( - newLayer, - insertionIndex === undefined ? undefined : insertionIndex + relatedIndex, - ); - newLayer.setArchived(relatedIndex > 3); - return newLayer; - }); -} - function checkLayerInputMetadataForErrors(layer: ManagedUserLayer): boolean { // If all the ranges are the same and the colors are black, then we can // assume that the input metadata is not set up correctly @@ -414,11 +393,11 @@ export function createImageLayerAsMultiChannel( changeLayerName(managedLayer, name); managedLayer.localPosition.value = new Float32Array(localPosition); } + const parentIndex = + managedLayer.manager.layerManager.managedLayers.indexOf(managedLayer); if (i !== 0) { const thisSpec = { ...spec, localPosition }; const newLayer = makeLayer(managedLayer.manager, name, thisSpec); - const parentIndex = - managedLayer.manager.layerManager.managedLayers.indexOf(managedLayer); managedLayer.manager.add( newLayer, parentIndex !== -1 ? parentIndex + i : undefined, @@ -437,14 +416,21 @@ export function createImageLayerAsMultiChannel( } const parentIndex = managedLayer.manager.layerManager.managedLayers.indexOf(managedLayer); - newLayers.push( - ...makeRelatedLayers( - managedLayer, - makeLayer, - startingName, - parentIndex !== -1 ? parentIndex + totalLocalChannels : undefined, - ), - ); + const relatedSources = getRelatedSources(managedLayer); + for (let i = 0; i < relatedSources.length; i++) { + const relatedSource = relatedSources[i]; + const newLayer = makeLayer( + managedLayer.manager, + `${startingName} ${relatedSource.name}`, + { type: relatedSource.suggestedLayerType, source: relatedSource.url }, + ); + managedLayer.manager.add( + newLayer, + parentIndex !== -1 ? parentIndex + totalLocalChannels + i : undefined, + ); + newLayer.setArchived(i > 3); + } + // Propagate new layers to all layer group subsets that contain the original managed layer // The initial manager.add() above only adds to the layer's own manager and its owner // Update other subsets referencing the original layer From 6fea12a4e97bdfcb125b7d8dd2efb7e232bfe55c Mon Sep 17 00:00:00 2001 From: Sean Martin Date: Tue, 3 Nov 2026 13:34:45 +0100 Subject: [PATCH 3/6] feat: put labels in the name --- src/layer/multi_channel_setup.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/layer/multi_channel_setup.ts b/src/layer/multi_channel_setup.ts index 2cf9ceb0f5..edda7d2a41 100644 --- a/src/layer/multi_channel_setup.ts +++ b/src/layer/multi_channel_setup.ts @@ -421,7 +421,7 @@ export function createImageLayerAsMultiChannel( const relatedSource = relatedSources[i]; const newLayer = makeLayer( managedLayer.manager, - `${startingName} ${relatedSource.name}`, + `${startingName} labels ${relatedSource.name}`, { type: relatedSource.suggestedLayerType, source: relatedSource.url }, ); managedLayer.manager.add( From 3657fd32c8e3692ee6e96d360e93922be23935f7 Mon Sep 17 00:00:00 2001 From: Sean Martin Date: Tue, 3 Nov 2026 15:21:01 +0100 Subject: [PATCH 4/6] fix: don't warn in frontend.ts on abort --- src/datasource/zarr/frontend.ts | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/src/datasource/zarr/frontend.ts b/src/datasource/zarr/frontend.ts index b7d5dde8d3..e339613839 100644 --- a/src/datasource/zarr/frontend.ts +++ b/src/datasource/zarr/frontend.ts @@ -480,26 +480,25 @@ function resolveUrl(options: GetKvStoreBasedDataSourceOptions) { async function getOmeLabelSources( sharedKvStoreContext: SharedKvStoreContext, - imageUrl: string, - zarrVersion: 2 | 3, - options: Partial, + url: string, + options: { zarrVersion: 2 | 3 } & Partial, ): Promise { const labelsGroupUrl = kvstoreEnsureDirectoryPipelineUrl( - joinBaseUrlAndPath(imageUrl, "labels"), + joinBaseUrlAndPath(url, "labels"), ); try { const metadata = await getMetadata(sharedKvStoreContext, labelsGroupUrl, { ...options, - zarrVersion, expectedNodeType: "group", }); if (metadata === undefined) return undefined; return parseOmeLabelsGroup( labelsGroupUrl, metadata.userAttributes, - zarrVersion, + options.zarrVersion, ); } catch (error) { + if (error instanceof Error && error.name === "AbortError") throw error; // A bad labels group must not stop the image from opening. console.warn(`Ignoring OME labels group ${labelsGroupUrl}:`, error); return undefined; @@ -569,12 +568,10 @@ export class ZarrDataSource implements KvStoreBasedDataSourceProvider { zarrVersion: metadata.zarrVersion, explicitDimensionSeparator: dimensionSeparator, }), - getOmeLabelSources( - sharedKvStoreContext, - kvStoreUrl, - metadata.zarrVersion, - progressOptions, - ), + getOmeLabelSources(sharedKvStoreContext, kvStoreUrl, { + ...progressOptions, + zarrVersion: metadata.zarrVersion, + }), ]); } else { multiscaleInfo = getMultiscaleInfoForSingleArray( From ff43db6c6f06ed0bf83111b466965e9c5c750fad Mon Sep 17 00:00:00 2001 From: Sean Martin Date: Tue, 3 Nov 2026 15:41:51 +0100 Subject: [PATCH 5/6] fix: propagate labels to other groups --- src/layer/multi_channel_setup.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/layer/multi_channel_setup.ts b/src/layer/multi_channel_setup.ts index edda7d2a41..a13da5e37f 100644 --- a/src/layer/multi_channel_setup.ts +++ b/src/layer/multi_channel_setup.ts @@ -429,6 +429,7 @@ export function createImageLayerAsMultiChannel( parentIndex !== -1 ? parentIndex + totalLocalChannels + i : undefined, ); newLayer.setArchived(i > 3); + newLayers.push(newLayer); } // Propagate new layers to all layer group subsets that contain the original managed layer From 349c8c0d7340f5604c650c0208ed30e1029255e6 Mon Sep 17 00:00:00 2001 From: Sean Martin Date: Tue, 3 Nov 2026 15:53:19 +0100 Subject: [PATCH 6/6] feat: make controls in palette explicit --- src/display_context.ts | 10 ++++++++-- src/layer/multi_channel_setup.ts | 31 ++++++++++++++++++++++++++----- src/ui/tool_palette.ts | 32 ++++++++++++++------------------ 3 files changed, 48 insertions(+), 25 deletions(-) diff --git a/src/display_context.ts b/src/display_context.ts index b15d64a68f..73e5edaa37 100644 --- a/src/display_context.ts +++ b/src/display_context.ts @@ -24,7 +24,7 @@ import { RefCounted } from "#src/util/disposable.js"; import { FramerateMonitor } from "#src/util/framerate.js"; import type { mat4 } from "#src/util/geom.js"; import { parseFixedLengthArray, verifyFloat01 } from "#src/util/json.js"; -import { NullarySignal } from "#src/util/signal.js"; +import { NullarySignal, Signal } from "#src/util/signal.js"; import { TrackableScreenshotMode, ScreenshotMode, @@ -428,6 +428,12 @@ interface PanelMonitorState { addedToResizeObserver?: boolean; } +export interface MultiChannelSetup { + readonly name: string; + // Palette JSON of the tools for the layers that the setup created. + readonly toolsJson: readonly object[]; +} + export class DisplayContext extends RefCounted implements FrameNumberCounter { canvas = document.createElement("canvas"); gl: GL; @@ -435,7 +441,7 @@ export class DisplayContext extends RefCounted implements FrameNumberCounter { updateFinished = new NullarySignal(); continuousCameraMotionStarted = new NullarySignal(); continuousCameraMotionFinished = new NullarySignal(); - multiChannelSetupFinished = new NullarySignal(); + multiChannelSetupFinished = new Signal<(setup: MultiChannelSetup) => void>(); changed = this.updateFinished; panels = new Set(); canvasRect: DOMRect | undefined; diff --git a/src/layer/multi_channel_setup.ts b/src/layer/multi_channel_setup.ts index a13da5e37f..6beff80ff1 100644 --- a/src/layer/multi_channel_setup.ts +++ b/src/layer/multi_channel_setup.ts @@ -24,17 +24,20 @@ import type { SingleChannelMetadata, } from "#src/datasource/index.js"; import type { ImageUserLayer } from "#src/layer/image/index.js"; -import { - type LayerListSpecification, - type ManagedUserLayer, - type UserLayer, +import type { + LayerListSpecification, + LayerTypeName, + ManagedUserLayer, + UserLayer, } from "#src/layer/index.js"; +import { SELECTED_ALPHA_JSON_KEY } from "#src/layer/segmentation/json_keys.js"; import { BLEND_MODES } from "#src/trackable_blend.js"; import { arraysEqual } from "#src/util/array.js"; import type { Borrowed } from "#src/util/disposable.js"; import type { vec3 } from "#src/util/geom.js"; import { dataTypeIntervalEqual, defaultDataTypeRange } from "#src/util/lerp.js"; import type { ShaderImageInvlerpControl } from "#src/webgl/shader_ui_controls.js"; +import { SHADER_CONTROL_TOOL_ID } from "#src/widget/shader_controls.js"; function changeLayerName(managedLayer: ManagedUserLayer, newName: string) { newName = managedLayer.manager.root.layerManager.getUniqueLayerName(newName); @@ -177,6 +180,21 @@ function getRelatedSources(layer: ManagedUserLayer): RelatedDataSource[] { return loadState.dataSource.relatedSources ?? []; } +function getPaletteToolsJson(layers: readonly ManagedUserLayer[]): object[] { + const toolsByLayerType: Partial> = { + image: [ + { type: SHADER_CONTROL_TOOL_ID, control: "contrast" }, + { type: SHADER_CONTROL_TOOL_ID, control: "color" }, + ], + segmentation: [{ type: SELECTED_ALPHA_JSON_KEY }], + }; + return layers.flatMap((layer) => + (toolsByLayerType[layer.layer?.type as LayerTypeName] ?? []).map( + (toolJson) => ({ layer: layer.name, ...toolJson }), + ), + ); +} + function checkLayerInputMetadataForErrors(layer: ManagedUserLayer): boolean { // If all the ranges are the same and the colors are black, then we can // assume that the input metadata is not set up correctly @@ -451,7 +469,10 @@ export function createImageLayerAsMultiChannel( } } } - root.display.multiChannelSetupFinished.dispatch(); + root.display.multiChannelSetupFinished.dispatch({ + name: startingName, + toolsJson: getPaletteToolsJson([managedLayer, ...newLayers]), + }); postCreationSetupFunctions.forEach((fn) => fn()); reverseGlobalDimOrderIfNeeded(managedLayer); } diff --git a/src/ui/tool_palette.ts b/src/ui/tool_palette.ts index a3f41fd054..467cce1f0a 100644 --- a/src/ui/tool_palette.ts +++ b/src/ui/tool_palette.ts @@ -1079,25 +1079,21 @@ export class MultiToolPaletteManager extends RefCounted { this.registerDisposer(this.state.changedShallow.add(debouncedUpdatePanels)); this.updatePanels(); this.registerDisposer( - this.sidePanelManager.display.multiChannelSetupFinished.add(() => { - // Check for the canned shader control palette - const shaderControlPalette = CANNED_PALETTES[2]; - const existingPalettes = this.state.palettes; - for (const palette of existingPalettes) { - if (palette.query.value === shaderControlPalette.query) { - return; + this.sidePanelManager.display.multiChannelSetupFinished.add( + ({ name, toolsJson }) => { + const palette = this.state.addNew({ + name: `${name} controls`, + location: { + ...DEFAULT_TOOL_PALETTE_PANEL_LOCATION, + side: "left", + row: 0, + }, + }); + for (const toolJson of toolsJson) { + palette.tools.insert(toolJson); } - } - const newPalette = this.state.addNew({ - name: shaderControlPalette.name, - location: { - ...DEFAULT_TOOL_PALETTE_PANEL_LOCATION, - side: "left", - row: 0, - }, - }); - newPalette.query.value = shaderControlPalette.query; - }), + }, + ), ); }