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..e339613839 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,33 @@ function resolveUrl(options: GetKvStoreBasedDataSourceOptions) { }; } +async function getOmeLabelSources( + sharedKvStoreContext: SharedKvStoreContext, + url: string, + options: { zarrVersion: 2 | 3 } & Partial, +): Promise { + const labelsGroupUrl = kvstoreEnsureDirectoryPipelineUrl( + joinBaseUrlAndPath(url, "labels"), + ); + try { + const metadata = await getMetadata(sharedKvStoreContext, labelsGroupUrl, { + ...options, + expectedNodeType: "group", + }); + if (metadata === undefined) return undefined; + return parseOmeLabelsGroup( + labelsGroupUrl, + metadata.userAttributes, + 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; + } +} + export class ZarrDataSource implements KvStoreBasedDataSourceProvider { constructor(public zarrVersion: 2 | 3 | undefined = undefined) {} get scheme() { @@ -515,6 +546,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 +562,17 @@ 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, { + ...progressOptions, + zarrVersion: metadata.zarrVersion, + }), + ]); } else { multiscaleInfo = getMultiscaleInfoForSingleArray( kvStoreUrl, @@ -560,6 +594,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/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/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..6beff80ff1 100644 --- a/src/layer/multi_channel_setup.ts +++ b/src/layer/multi_channel_setup.ts @@ -19,19 +19,25 @@ 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, - 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); @@ -168,6 +174,27 @@ function getLayerChannelMetadata( return channels?.[channelIndex]; } +function getRelatedSources(layer: ManagedUserLayer): RelatedDataSource[] { + const loadState = getLoadState(layer); + if (!loadState || loadState.error) return []; + 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 @@ -367,7 +394,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); @@ -384,17 +411,17 @@ 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, ); addedLayer = newLayer; - newChannelLayers.push(newLayer); + newLayers.push(newLayer); } setupLayerPostCreation( addedLayer, @@ -405,26 +432,47 @@ 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); + const relatedSources = getRelatedSources(managedLayer); + for (let i = 0; i < relatedSources.length; i++) { + const relatedSource = relatedSources[i]; + const newLayer = makeLayer( + managedLayer.manager, + `${startingName} labels ${relatedSource.name}`, + { type: relatedSource.suggestedLayerType, source: relatedSource.url }, + ); + managedLayer.manager.add( + newLayer, + 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 // 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, ); } } } - root.display.multiChannelSetupFinished.dispatch(); + root.display.multiChannelSetupFinished.dispatch({ + name: startingName, + toolsJson: getPaletteToolsJson([managedLayer, ...newLayers]), + }); postCreationSetupFunctions.forEach((fn) => fn()); reverseGlobalDimOrderIfNeeded(managedLayer); } 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) { 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; - }), + }, + ), ); }