Compare commits

..
Author SHA1 Message Date
ohif-bot f0e2f64397 chore(version): Update package versions to 3.13.0-beta.121 [skip ci] 2026-07-10 22:54:59 +00:00
Alireza 43226d9191 fix(app): appearance modal provider scope, worklist preview persistence, and tag browser label overflow (#6136)
- Insert ServiceProvidersManager providers ahead of the dialog/modal
  providers in App.tsx: modal content renders as a sibling of the
  provider's children, so contexts registered via the manager (e.g.
  ActiveThemeProvider) were out of scope and the appearance modal
  crashed with 'useActiveTheme must be used within an ActiveThemeProvider'.
- Persist the worklist preview panel open/closed state in
  sessionStorage so it survives navigating into a study and back.
- Keep the DICOM tag browser instance number label on one line:
  the words truncate, the (n of total) digits never clip.
2026-07-10 18:52:06 -04:00
ohif-bot dc9df56be4 chore(version): Update package versions to 3.13.0-beta.120 [skip ci] 2026-07-10 21:08:34 +00:00
Alireza 9c76afa075 feat(segmentation): replace One Click Segment with ClickSegmentTool (#6135)
* feat(segmentation): replace One Click Segment with ClickSegmentTool

Wire OHIF to ClickSegmentTool from Cornerstone3D (#2780), rename the
toolbox button to Click to Segment, and enable it only on PET (PT)
viewports.

* chore(deps): bump @cornerstonejs packages to 5.4.13

Pick up ClickSegmentTool from the published Cornerstone3D release so
OHIF installs the tool from npm without a local CS3D link.
2026-07-10 17:05:26 -04:00
ohif-bot 6d8a275171 chore(version): Update package versions to 3.13.0-beta.119 [skip ci] 2026-07-10 19:38:19 +00:00
Alireza 1eee3e6119 fix(MetadataProvider): Correctly assign imageId for multiframe images and remove unused frame information retrieval method (#5965) 2026-07-10 15:35:09 -04:00
ohif-bot 2c54616136 chore(version): Update package versions to 3.13.0-beta.118 [skip ci] 2026-07-10 17:34:50 +00:00
Alireza 9329dd5b55 test(core): use fake timers in Queue unit tests to stop CI flakes (#6134)
The Queue tests measured real setTimeout wall-clock time and asserted
elapsed < 2 * threshold. On busy CI runners a 2400ms timer can take
longer than 4800ms to fire, failing the assertion intermittently (seen
in downstream validation runs). Switch to jest's modern fake timers so
elapsed is exactly the timeout delay: the tests are deterministic and
no longer spend ~5 seconds of real time waiting.
2026-07-10 13:31:42 -04:00
ohif-bot 75105ced04 chore(version): Update package versions to 3.13.0-beta.117 [skip ci] 2026-07-10 16:46:10 +00:00
Bill Wallace b266c0a86a feat: Add extensibility for tmtv and segmentation modes (#6128)
* feat: Add extensibility for tmtv and segmentation modes

* Fixes for ordering issues on laod

* Remove unnecessary reference lookup

* Chane side panel timing to fix tests

* PR comments - change how mode definitions get created

* Improvements to mode customizations

* Start organizing customizations

* Misc fixes for a customization demo page

* Security fixes

* PR requested changes to naming
2026-07-10 12:43:17 -04:00
ohif-bot f79055f98e chore(version): Update package versions to 3.13.0-beta.116 [skip ci] 2026-07-10 12:19:06 +00:00
Bill WallaceandClaude Fable 5 6b6761088b fix: Several new worklist issues (#6130)
* fix: Several new worklist issues

* refactor: Export a single OnStudyDoubleClick type from the StudyList barrel

Addresses PR review feedback: the double-click handler signature was
written out in both TableProps and the WorkList customization cast,
so the two could drift apart.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: Run worklist study double-click as a command, registrable by modes

- Modes can now export getCommandsModule on their definition; appInit
  registers it (via the new ExtensionManager.registerCommandsModule)
  before the mode is instantiated, in a new 'WORKLIST' commands context,
  so the commands are available on the worklist before any mode route
  is entered.
- The workList.onStudyDoubleClick customization is now a command run
  input (name/options) instead of a bare function, defaulting to the
  new launchDefaultMode command, which launches the default workflow
  falling back to the first applicable one. commandOptions.workflowId
  overrides it to a specific mode.
- Duplicate mode ids are now skipped before running their modeFactory
  rather than after.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 08:16:16 -04:00
dbb8b1526e feat: Add support for labelmap seg images in any supported tsuid (also for compressed bitmap) (#5806)
* feat: Update to use pnpm (#6031) [simulated squash-merge]

* feat: load DICOM SEG images via imageLoader

* feat: load DICOM SEG images via imageLoader

* PR review fixes

* Test fragment of compressed multiframes

* fix: Removed dependencies incorrectly

* Update frame as a targetted change to avoid stripping remaining params

* lock

* Update test to agree with the missing representation branch

* test(contour): contour color change coverage (#6042)

* test(contour): contour interactions delete segment (#6069)

---------

Co-authored-by: Bill Wallace <wayfarer3130@gmail.com>

* chore(version): Update package versions to 3.13.0-beta.98 [skip ci]

* feat(testing): OHIF Test Agent Skills (#5993)

* chore(version): Update package versions to 3.13.0-beta.99 [skip ci]

* test(contour): Add the ContourSegmentToggleLock.spec.ts test file to test contour locking (#6072)

* chore(version): Update package versions to 3.13.0-beta.100 [skip ci]

* chore(testing): Flock lock for playwright tests; Pin node version for OHIF; add more workers (#6099)

* update Cypress apt deps for Ubuntu Noble (drop libgconf-2-4, libasound2→libasound2t64)

* chore(version): Update package versions to 3.13.0-beta.101 [skip ci]

* Debug fixes

* perf(seg): pass explicit frame decode concurrency (16) to SEG loader

Pass an explicit concurrency value (SEG_FRAME_DECODE_CONCURRENCY = 16) into
createFromDicomSegImageId rather than relying on the adapter default, so the
SEG frame fetch/decode parallelism is set at the call site and is ready to
become configurable.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(behaviours): add behaviours section + multiframe Part 10 prefetch proposal

Start a "Behaviours" docs section for documenting how the system and UI behave
end-to-end (observed behaviours, design proposals, and failure modes), with an
index README and a Docusaurus category.

First entry is the proposal for loading a multiframe SEG as a single Part 10
instance: prefetch the whole instance (gated by loadMultiframeAsPart10RaceTimeMs),
parse it with dcmjs (handling multipart/related vs raw DICOM), and register the
per-frame compressed pixels into the Cornerstone3D core image cache (the single
uniform frame registry) so the per-frame load path is served locally while the
standard decode path is unchanged. Best-effort: falls back to per-frame fetches
on any failure.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Pre-cache the image data using a full part10 file for performance

* Add customizations to specify type of segmentation save

* Add clearcache of the cacheData

* Bump @cornerstonejs/* pins 5.1.3 -> 5.4.10 to match libs/@cornerstonejs base

libs/@cornerstonejs (fix/use-imageLoader-for-seg) is based on the released
cs3d 5.4.10 (merge-base with origin/main is the 5.4.10 version bump), so pin
OHIF to that release. The local branch changes still reach the app via the
cs3d:link symlinks; these pins keep the lockfile/npm fallback aligned.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Fix seg OOM

* fix: file meta garbage element, bogus NumberOfFrames, unguarded source-map-loader

- dicomWriter: drop the naturalized meta.TransferSyntaxUID assignment that
  dcmjs wrote as a garbage (0000,0000) element into every saved file's meta
  group (download / clipboard / local wadouri blob / local store); keep the
  hex 00020010 assignment, which is required for string-form _meta fallbacks.
- registerNaturalizedDatasetForLocalWadouri: keep the computed frame count
  local so single-frame IODs (SR, RTSTRUCT) no longer gain a bogus
  NumberOfFrames element in their serialized form.
- rsbuild.config: resolve source-map-loader opportunistically (it is not a
  project dependency; the rule only serves the gitignored cs3d-link
  workflow) so fresh clones no longer crash at config load.
- Regression tests for both writer fixes (mutation-checked).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* PR review comment fixes

* Update versions

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: diattamo <mmddiatta@gmail.com>
Co-authored-by: ohif-bot <danny.ri.brown+ohif-bot@gmail.com>
Co-authored-by: Joe Boccanfuso <109477394+jbocce@users.noreply.github.com>
2026-07-09 20:54:23 -04:00
138 changed files with 5861 additions and 1659 deletions

No files matched your search

+27
View File
@@ -244,6 +244,32 @@ also supports a number of commands that can be found in their respective
\* - For more information on different builds, check out our [Deploy
Docs][deployment-docs]
### Which config each command uses
The dev server and the production build select a different default
[configuration file][config-file] when `APP_CONFIG` is not set explicitly:
| Command | Default config | Data sources | `?customization=` |
| ------------------------------- | -------------------- | ------------ | ----------------- |
| `dev`, `dev:fast`, `start` | `config/dev.js` | Full set | Enabled |
| `build` | `config/default.js` | One demo source | Disabled |
- **`config/dev.js`** is the full-featured local-development config: every data
source is enabled, the `?customization=` URL feature is turned on (via
`customizationUrlPrefixes`), and it is kept at parity with the public demo
(`config/netlify.js`) so customizations behave locally the same way they do on
the demo.
- **`config/netlify.js`** is the public demo / Netlify deploy config
(`build:viewer:ci`), with the same full data-source set and `?customization=`
enabled.
- **`config/default.js`** is a locked-down baseline and is now **only** the
default for a plain production build (`build` with no `APP_CONFIG`): a single
read-only demo data source and `?customization=` off.
Any explicit `APP_CONFIG` overrides the default, e.g.
`APP_CONFIG=config/default.js pnpm run dev` or
`APP_CONFIG=config/netlify.js pnpm run build`.
## Project
The OHIF Medical Image Viewing Platform is maintained as a
@@ -371,6 +397,7 @@ MIT © [OHIF](https://github.com/OHIF)
[ohif-architecture]: https://docs.ohif.org/architecture/index.html
[ohif-extensions]: https://docs.ohif.org/architecture/index.html
[deployment-docs]: https://docs.ohif.org/deployment/
[config-file]: https://docs.ohif.org/configuration/configurationFiles
[react-url]: https://reactjs.org/
[pwa-url]: https://developers.google.com/web/progressive-web-apps/
[ohif-viewer-url]: https://www.npmjs.com/package/@ohif/app
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone-dicom-pmap",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "DICOM Parametric Map read workflow",
"author": "OHIF",
"license": "MIT",
@@ -41,8 +41,8 @@
},
"dependencies": {
"@babel/runtime": "7.29.7",
"@cornerstonejs/adapters": "5.1.3",
"@cornerstonejs/core": "5.1.3",
"@cornerstonejs/adapters": "5.4.13",
"@cornerstonejs/core": "5.4.13",
"@kitware/vtk.js": "35.5.3"
},
"devDependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone-dicom-rt",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "DICOM RT read workflow",
"author": "OHIF",
"license": "MIT",
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone-dicom-seg",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "DICOM SEG read workflow",
"author": "OHIF",
"license": "MIT",
@@ -41,8 +41,8 @@
},
"dependencies": {
"@babel/runtime": "7.29.7",
"@cornerstonejs/adapters": "5.1.3",
"@cornerstonejs/core": "5.1.3",
"@cornerstonejs/adapters": "5.4.13",
"@cornerstonejs/core": "5.4.13",
"@kitware/vtk.js": "35.5.3"
},
"devDependencies": {
@@ -6,6 +6,7 @@ import { adaptersRT, adaptersSEG } from '@cornerstonejs/adapters';
import { createReportDialogPrompt, useUIStateStore } from '@ohif/extension-default';
import PROMPT_RESPONSES from '../../default/src/utils/_shared/PROMPT_RESPONSES';
import { getSegmentationSaveOptions } from './utils/segmentationConfig';
const getTargetViewport = ({ viewportId, viewportGridService }) => {
const { viewports, activeViewportId } = viewportGridService.getState();
@@ -34,7 +35,7 @@ const commandsModule = ({
extensionManager,
commandsManager,
}: Types.Extensions.ExtensionParams): Types.Extensions.CommandsModule => {
const { segmentationService, displaySetService, viewportGridService } =
const { segmentationService, displaySetService, viewportGridService, customizationService } =
servicesManager.services as AppTypes.Services;
const actions = {
@@ -88,13 +89,37 @@ const commandsModule = ({
* @returns Returns the generated segmentation data.
*/
generateSegmentation: ({ segmentationId, options = {} }) => {
// `dataSource` (a data source name) is consumed here to resolve the store
// overrides; it must not be forwarded to the adapter's generateSegmentation.
const { dataSource: dataSourceName, ...generateOptions } = options;
const segmentation = cornerstoneToolsSegmentation.state.getSegmentation(segmentationId);
const predecessorImageId = options.predecessorImageId ?? segmentation.predecessorImageId;
const predecessorImageId =
generateOptions.predecessorImageId ?? segmentation.predecessorImageId;
// A data source may override the app-wide `segmentation.store.*` defaults
// via `configuration.segmentation.store` (different back ends support
// different SEG encodings). Use the named target data source when storing,
// otherwise the active one (e.g. download).
const dataSourceDefinition = dataSourceName
? extensionManager.getDataSourceDefinition(dataSourceName)
: extensionManager.getActiveDataSourceDefinition();
const dataSourceStoreOverride = dataSourceDefinition?.configuration?.segmentation?.store;
const { imageIds } = segmentation.representationData.Labelmap;
const segImages = imageIds.map(imageId => cache.getImage(imageId));
const referencedImages = segImages.map(image => cache.getImage(image.referencedImageId));
const referencedImages = segImages.map((segImage, sliceIndex) => {
const referencedImage = cache.getImage(segImage.referencedImageId);
if (!referencedImage) {
throw new Error(
`Referenced source image not in cache for segmentation slice ${sliceIndex} ` +
`(referencedImageId: ${segImage.referencedImageId}). Ensure the referenced series is fully loaded before storing.`
);
}
return referencedImage;
});
const labelmaps2D = [];
@@ -173,7 +198,8 @@ const commandsModule = ({
const generatedSegmentation = generateSegmentation(referencedImages, labelmap3D, metaData, {
predecessorImageId,
...options,
...getSegmentationSaveOptions(customizationService, dataSourceStoreOverride),
...generateOptions,
});
return generatedSegmentation;
@@ -257,6 +283,8 @@ const commandsModule = ({
const args = {
segmentationId,
options: {
// Resolve store overrides against the data source we are storing into.
dataSource: dataSourceName,
SeriesDescription: series ? undefined : reportName || label || 'Contour Series',
SeriesNumber: series ? undefined : 1 + priorSeriesNumber,
predecessorImageId: series,
@@ -289,6 +317,8 @@ const commandsModule = ({
generateContour: async args => {
const { segmentationId, options } = args;
// `dataSource` is only used by the SEG store path; keep it out of the RTSS options.
const { dataSource: _dataSource, ...contourOptions } = options ?? {};
const segmentations = segmentationService.getSegmentation(segmentationId);
// inject colors to the segmentIndex
@@ -301,10 +331,11 @@ const commandsModule = ({
Number(segmentIndex)
);
});
const predecessorImageId = options?.predecessorImageId ?? segmentations.predecessorImageId;
const predecessorImageId =
contourOptions.predecessorImageId ?? segmentations.predecessorImageId;
const dataset = await generateRTSSFromRepresentation(segmentations, {
predecessorImageId,
...options,
...contourOptions,
});
return { dataset };
},
@@ -0,0 +1,29 @@
import {
DEFAULT_SEG_STORE_MODE,
DEFAULT_SEG_STORE_TRANSFER_SYNTAX_UID,
type SegmentationMode,
} from '../utils/segmentationConfig';
export type SegmentLabelCustomization = {
enabledByDefault?: boolean;
labelColor?: number[];
hoverTimeout?: number;
background?: string;
};
export type SegmentationStoreCustomization = {
defaultMode?: SegmentationMode;
transferSyntaxUID?: string;
};
/** Extension-registered defaults: Label Map SEG + RLE Lossless. */
const segmentationCustomization = {
'segmentation.store.defaultMode': DEFAULT_SEG_STORE_MODE,
'segmentation.store.transferSyntaxUID': DEFAULT_SEG_STORE_TRANSFER_SYNTAX_UID,
'segmentation.segmentLabel': {
enabledByDefault: false,
hoverTimeout: 1,
} satisfies SegmentLabelCustomization,
};
export default segmentationCustomization;
@@ -0,0 +1,10 @@
import segmentationCustomization from './customizations/segmentationCustomization';
export default function getCustomizationModule() {
return [
{
name: 'default',
value: segmentationCustomization,
},
];
}
@@ -1,16 +1,237 @@
import { utils, Types as OhifTypes } from '@ohif/core';
import { utils, Types as OhifTypes, DicomMetadataStore, classes, log } from '@ohif/core';
import i18n from '@ohif/i18n';
import { metaData, eventTarget } from '@cornerstonejs/core';
import { metaData, eventTarget, utilities as csUtils } from '@cornerstonejs/core';
import { CONSTANTS, segmentation as cstSegmentation } from '@cornerstonejs/tools';
import { adaptersSEG, Enums } from '@cornerstonejs/adapters';
import { SOPClassHandlerId } from './id';
import { dicomlabToRGB } from './utils/dicomlabToRGB';
import { getSegmentationParserType } from './utils/segmentationConfig';
import {
getFrameIndexFromImageId,
isLocalSchemeImageId,
stripFrameFromImageId,
} from './utils/segLocalImageIds';
const sopClassUids = ['1.2.840.10008.5.1.4.1.1.66.4', '1.2.840.10008.5.1.4.1.1.66.7'];
const LABELMAP_SEG_SOP_CLASS_UID = '1.2.840.10008.5.1.4.1.1.66.7';
const loadPromises = {};
const SEG_LOAD_LOG_PREFIX = '[SEG load]';
// Max number of SEG frames fetched/decoded concurrently by the segmentation
// loader. Hard-coded to 16 for now; intended to become configurable (and to
// pair with the full-instance prefetch capability) in a follow-up.
const SEG_FRAME_DECODE_CONCURRENCY = 16;
function _normalizeImageId(imageId: string | string[] | undefined): string | undefined {
if (imageId == null) {
return undefined;
}
return Array.isArray(imageId) ? imageId[0] : imageId;
}
/**
* Expands a WADO-RS frame imageId (…/frames/1) into one imageId per frame.
* Multiframe SEG is stored as separate /frames/N resources on the server.
*/
function getFrameImageIds(segImageId: string, numberOfFrames: number): string[] {
const frameMatch = segImageId.match(/(.*\/frames\/)(\d+)(.*)$/);
if (!frameMatch || numberOfFrames <= 1) {
return [segImageId];
}
const prefix = frameMatch[1];
const suffix = frameMatch[3] || '';
const frameImageIds: string[] = [];
for (let frameNumber = 1; frameNumber <= numberOfFrames; frameNumber++) {
frameImageIds.push(`${prefix}${frameNumber}${suffix}`);
}
return frameImageIds;
}
function _getSegNumberOfFrames(instance: Record<string, unknown>): number {
const fromTag = Number(instance.NumberOfFrames);
if (fromTag > 0) {
return fromTag;
}
const perFrame = instance.PerFrameFunctionalGroupsSequence;
if (Array.isArray(perFrame) && perFrame.length > 0) {
return perFrame.length;
}
return 1;
}
function _ensureSegImageIdMetadataRegistered(
imageId: string | undefined,
instance: Record<string, unknown>
): void {
if (!imageId) {
return;
}
const metadataProvider = classes.MetadataProvider;
const StudyInstanceUID = instance.StudyInstanceUID as string | undefined;
const SeriesInstanceUID = instance.SeriesInstanceUID as string | undefined;
const SOPInstanceUID = (instance.SOPInstanceUID || instance.SopInstanceUID) as
| string
| undefined;
if (!StudyInstanceUID || !SeriesInstanceUID || !SOPInstanceUID) {
return;
}
metadataProvider.addImageIdToUIDs(imageId, {
StudyInstanceUID,
SeriesInstanceUID,
SOPInstanceUID,
frameNumber: getFrameIndexFromImageId(imageId),
});
}
/** Ensures metadataProvider.get('instance', imageId) resolves for frame-qualified local SEG ids. */
function _ensureSegInstanceMetadataAvailable(
imageId: string | undefined,
instance: Record<string, unknown>
): void {
if (!imageId) {
return;
}
_ensureSegImageIdMetadataRegistered(imageId, instance);
if (metaData.get('instance', imageId)) {
return;
}
const StudyInstanceUID = instance.StudyInstanceUID as string | undefined;
const SeriesInstanceUID = instance.SeriesInstanceUID as string | undefined;
const SOPInstanceUID = (instance.SOPInstanceUID || instance.SopInstanceUID) as
| string
| undefined;
const storedInstance =
StudyInstanceUID && SeriesInstanceUID && SOPInstanceUID
? DicomMetadataStore.getInstance(StudyInstanceUID, SeriesInstanceUID, SOPInstanceUID)
: undefined;
classes.MetadataProvider.addCustomMetadata(
imageId,
'instance',
storedInstance || instance
);
}
function _getSegDataSource(extensionManager, instance: Record<string, unknown>) {
const StudyInstanceUID = instance.StudyInstanceUID as string | undefined;
const SeriesInstanceUID = instance.SeriesInstanceUID as string | undefined;
const SOPInstanceUID = (instance.SOPInstanceUID || instance.SopInstanceUID) as
| string
| undefined;
let localUrl: string | undefined;
if (StudyInstanceUID && SeriesInstanceUID && SOPInstanceUID) {
const storedInstance = DicomMetadataStore.getInstance(
StudyInstanceUID,
SeriesInstanceUID,
SOPInstanceUID
);
localUrl = storedInstance?.url as string | undefined;
}
localUrl = localUrl || (instance.url as string | undefined);
if (localUrl && isLocalSchemeImageId(localUrl)) {
const dicomLocal = extensionManager.getDataSources('dicomlocal');
if (dicomLocal?.[0]) {
return dicomLocal[0];
}
}
return extensionManager.getActiveDataSource()[0];
}
function _getSegImageIdFromInstance(
instance: Record<string, unknown>,
dataSource: { getImageIdsForInstance?: (args: { instance: unknown; frame?: number }) => unknown }
): string | undefined {
const numberOfFrames = _getSegNumberOfFrames(instance);
const frame = numberOfFrames > 1 ? 1 : undefined;
return _normalizeImageId(
dataSource.getImageIdsForInstance?.({ instance, frame }) as string | string[] | undefined
);
}
function _resolveFrameImageIds(
segImageIdStr: string,
instance: Record<string, unknown>,
dataSource: { getImageIdsForInstance?: (args: { instance: unknown; frame?: number }) => unknown }
): string[] {
const numberOfFrames = _getSegNumberOfFrames(instance);
const fromFrameUrl = getFrameImageIds(segImageIdStr, numberOfFrames);
if (fromFrameUrl.length > 1) {
return fromFrameUrl;
}
if (numberOfFrames <= 1) {
return [segImageIdStr];
}
const frameImageIds: string[] = [];
for (let frame = 1; frame <= numberOfFrames; frame++) {
const frameImageId = _normalizeImageId(
dataSource.getImageIdsForInstance?.({ instance, frame }) as string | string[] | undefined
);
if (frameImageId) {
frameImageIds.push(frameImageId);
}
}
return frameImageIds.length ? frameImageIds : [segImageIdStr];
}
function _logSegImageIds({
segDisplaySet,
segImageIdStr,
frameImageIds,
referencedImageIds,
}: {
segDisplaySet: AppTypes.DisplaySet;
segImageIdStr: string;
frameImageIds: string[];
referencedImageIds: string[];
}) {
const instance = segDisplaySet.instance as Record<string, unknown>;
const numberOfFrames = Number(instance?.NumberOfFrames) || 1;
log.debug(SEG_LOAD_LOG_PREFIX, 'Loading SEG pixel data', {
SOPInstanceUID: segDisplaySet.SOPInstanceUID,
SeriesInstanceUID: segDisplaySet.SeriesInstanceUID,
SOPClassUID: segDisplaySet.SOPClassUID,
NumberOfFrames: numberOfFrames,
segmentCount: Object.keys(segDisplaySet.segments || {}).length,
referencedDisplaySetInstanceUID: segDisplaySet.referencedDisplaySetInstanceUID,
referencedImageIdCount: referencedImageIds.length,
referencedImageIds,
segImageIdForMetadata: segImageIdStr,
frameImageIds,
loadSegFramesIndividually: frameImageIds.length > 1,
});
}
function _getDisplaySetsFromSeries(
instances,
servicesManager: AppTypes.ServicesManager,
@@ -171,6 +392,11 @@ function _load(
});
});
// Expose the in-flight load promise so observers (e.g. the viewport service
// waiting to attach the representation) can react to a load failure without
// re-invoking load().
segDisplaySet.loadingPromise = loadPromises[SOPInstanceUID];
return loadPromises[SOPInstanceUID];
}
@@ -178,16 +404,18 @@ async function _loadSegments({
extensionManager,
servicesManager,
segDisplaySet,
headers,
}: withAppTypes) {
const utilityModule = extensionManager.getModuleEntry(
'@ohif/extension-cornerstone.utilityModule.common'
);
}: withAppTypes<{ segDisplaySet: AppTypes.DisplaySet }>) {
const { segmentationService, uiNotificationService, customizationService } =
servicesManager.services;
const instance = segDisplaySet.instance as Record<string, unknown>;
const dataSource = _getSegDataSource(extensionManager, instance);
const segImageIdStr = _getSegImageIdFromInstance(instance, dataSource);
const { segmentationService, uiNotificationService } = servicesManager.services;
const { dicomLoaderService } = utilityModule.exports;
const arrayBuffer = await dicomLoaderService.findDicomDataPromise(segDisplaySet, null, headers);
if (!segImageIdStr) {
throw new Error(
'Could not get imageId for SEG instance (no local wadouri url and getImageIdsForInstance returned nothing).'
);
}
const referencedDisplaySet = servicesManager.services.displaySetService.getDisplaySetByUID(
segDisplaySet.referencedDisplaySetInstanceUID
@@ -197,31 +425,114 @@ async function _loadSegments({
throw new Error('referencedDisplaySet is missing for SEG');
}
// Prefer cached stack imageIds (multiframe SEG fix #4890), then data source expansion.
let { imageIds } = referencedDisplaySet;
if (!imageIds) {
// try images
const { images } = referencedDisplaySet;
imageIds = images.map(image => image.imageId);
if (!imageIds?.length) {
imageIds = dataSource.getImageIdsForDisplaySet?.(referencedDisplaySet);
}
// Todo: what should be defaults here
if (!imageIds?.length) {
imageIds = (referencedDisplaySet as { images?: { imageId: string }[] }).images?.map(
(img: { imageId: string }) => img.imageId
);
}
if (!imageIds?.length) {
throw new Error('referencedDisplaySet has no imageIds');
}
(segDisplaySet as AppTypes.DisplaySet & { referencedImageIds?: string[] }).referencedImageIds =
imageIds;
if (!referencedDisplaySet.imageIds?.length) {
referencedDisplaySet.imageIds = imageIds;
}
const frameImageIds = _resolveFrameImageIds(
segImageIdStr,
segDisplaySet.instance as Record<string, unknown>,
dataSource
);
const segImageIdForMetadata = isLocalSchemeImageId(segImageIdStr)
? stripFrameFromImageId(segImageIdStr)
: segImageIdStr;
_logSegImageIds({
segDisplaySet,
segImageIdStr: segImageIdForMetadata,
frameImageIds,
referencedImageIds: imageIds,
});
_ensureSegInstanceMetadataAvailable(segImageIdForMetadata, instance);
frameImageIds.forEach(id => _ensureSegInstanceMetadataAvailable(id, instance));
const tolerance = 0.001;
eventTarget.addEventListener(Enums.Events.SEGMENTATION_LOAD_PROGRESS, evt => {
const onProgress = evt => {
const { percentComplete } = evt.detail;
segmentationService._broadcastEvent(segmentationService.EVENTS.SEGMENT_LOADING_COMPLETE, {
percentComplete,
});
});
};
eventTarget.addEventListener(Enums.Events.SEGMENTATION_LOAD_PROGRESS, onProgress);
const results = await adaptersSEG.Cornerstone3D.Segmentation.createFromDICOMSegBuffer(
imageIds,
arrayBuffer,
{ metadataProvider: metaData, tolerance }
);
// Fetch the whole SEG instance as a single Part 10 object and register its
// per-frame compressed pixels into the Cornerstone3D frame registry, so the
// per-frame loads below are served locally instead of one network request
// per frame: SEG frames are so small and numerous that one bulk fetch beats
// hundreds of tiny requests. Enabled by default; per-frame loading is the
// exception (loadMultiframeAsPart10: false in the data source config, or the
// cornerstone.segmentation.loadMultiframeAsPart10 customization). The
// prefetch is awaited until it completes OR fails — deliberately no timeout:
// a failed/unsupported instance fetch resolves quickly and falls back to
// per-frame, while a slow large fetch is still the fastest way to all frames.
const loadMultiframeAsPart10 =
(dataSource?.getConfig?.()?.loadMultiframeAsPart10 as boolean | undefined) ??
(customizationService?.getCustomization?.(
'cornerstone.segmentation.loadMultiframeAsPart10'
) as boolean | undefined) ??
true;
let prefetch;
if (loadMultiframeAsPart10) {
prefetch = dataSource.retrieve?.prefetchInstanceFrames?.({
instance,
imageId: segImageIdForMetadata,
});
if (prefetch?.done) {
await prefetch.done;
}
}
let results;
try {
results = await adaptersSEG.Cornerstone3D.Segmentation.createFromDicomSegImageId(
imageIds,
segImageIdForMetadata,
{
metadataProvider: metaData,
tolerance,
parserType: getSegmentationParserType(
segDisplaySet.SOPClassUID,
customizationService
),
frameImageIds,
concurrency: SEG_FRAME_DECODE_CONCURRENCY,
}
);
} finally {
eventTarget.removeEventListener(Enums.Events.SEGMENTATION_LOAD_PROGRESS, onProgress);
prefetch?.cancel?.();
}
let usedRecommendedDisplayCIELabValue = true;
results.segMetadata.data.forEach((data, i) => {
const resultsTyped = results as {
segMetadata: { data: { rgba?: number[]; RecommendedDisplayCIELabValue?: number[] }[] };
};
resultsTyped.segMetadata.data.forEach((data, i) => {
if (i > 0) {
data.rgba = data.RecommendedDisplayCIELabValue;
@@ -246,6 +557,17 @@ async function _loadSegments({
}
Object.assign(segDisplaySet, results);
const labelMapImageIds = (results as { labelMapImages?: { imageId: string }[][] })
.labelMapImages?.flat()
.map(image => image.imageId);
log.debug(SEG_LOAD_LOG_PREFIX, 'SEG parse complete', {
SOPInstanceUID: segDisplaySet.SOPInstanceUID,
labelMapImageCount: labelMapImageIds?.length ?? 0,
labelMapImageIds,
segmentIndices: Object.keys(segDisplaySet.segments || {}),
});
}
function _segmentationExists(segDisplaySet) {
@@ -4,6 +4,7 @@ import React from 'react';
import getSopClassHandlerModule from './getSopClassHandlerModule';
import getHangingProtocolModule from './getHangingProtocolModule';
import getCommandsModule from './commandsModule';
import getCustomizationModule from './getCustomizationModule';
import { getToolbarModule } from './getToolbarModule';
const Component = React.lazy(() => {
@@ -28,6 +29,7 @@ const extension = {
*/
id,
getCommandsModule,
getCustomizationModule,
getToolbarModule,
getViewportModule({ servicesManager, extensionManager, commandsManager }) {
const ExtendedOHIFCornerstoneSEGViewport = props => {
@@ -0,0 +1,32 @@
export function isLocalSchemeImageId(imageId: string): boolean {
return /^(wadouri:|dicomfile:|dicomweb:)/.test(imageId);
}
export function stripFrameFromImageId(imageId: string): string {
const queryIndex = imageId.indexOf('?');
if (queryIndex === -1) {
return imageId;
}
const basePath = imageId.slice(0, queryIndex);
const rebuiltQuery = imageId
.slice(queryIndex + 1)
.split('&')
.filter(param => param.split('=')[0] !== 'frame')
.join('&');
return rebuiltQuery ? `${basePath}?${rebuiltQuery}` : basePath;
}
export function appendFrameToImageId(baseImageId: string, frame: number): string {
const withoutFrame = stripFrameFromImageId(baseImageId);
const separator = withoutFrame.includes('?') ? '&' : '?';
return `${withoutFrame}${separator}frame=${frame}`;
}
export function getFrameIndexFromImageId(imageId: string): number {
const frameMatch = imageId.match(/(?:&|\?)frame=(\d+)/);
return frameMatch ? Number(frameMatch[1]) : 1;
}
@@ -0,0 +1,100 @@
export const LABELMAP_SEG_SOP_CLASS_UID = '1.2.840.10008.5.1.4.1.1.66.7';
export const BITMAP_SEG_SOP_CLASS_UID = '1.2.840.10008.5.1.4.1.1.66.4';
/** RLE Lossless — OHIF default SEG store transfer syntax. */
export const DEFAULT_SEG_STORE_TRANSFER_SYNTAX_UID = '1.2.840.10008.1.2.5';
/** OHIF default SEG store mode (Label Map Segmentation SOP Class). */
export const DEFAULT_SEG_STORE_MODE = 'labelmap' as const;
export type SegmentationMode = 'labelmap' | 'bitmap';
/**
* Per-data-source overrides for the SEG store defaults. A data source may set
* these under `configuration.segmentation.store` to override the values coming
* from the `segmentation.store.*` customizations. Different back ends support
* different SEG encodings, so the data source is allowed to win over the
* app-wide customization default.
*/
export type SegmentationStoreOverride = {
defaultMode?: SegmentationMode;
transferSyntaxUID?: string;
};
type SegmentationCustomizationReader = {
getCustomization: (customizationId: string) => unknown;
};
function getStoreDefaultMode(
customizationService?: SegmentationCustomizationReader,
override?: SegmentationStoreOverride
): SegmentationMode {
const mode =
override?.defaultMode ??
(customizationService?.getCustomization('segmentation.store.defaultMode') as
| SegmentationMode
| undefined) ??
DEFAULT_SEG_STORE_MODE;
return mode === 'bitmap' ? 'bitmap' : 'labelmap';
}
function getStoreTransferSyntaxUID(
customizationService?: SegmentationCustomizationReader,
override?: SegmentationStoreOverride
): string {
return (
override?.transferSyntaxUID ??
(customizationService?.getCustomization(
'segmentation.store.transferSyntaxUID'
) as string | undefined) ??
DEFAULT_SEG_STORE_TRANSFER_SYNTAX_UID
);
}
/**
* Resolves the parser type for loading a DICOM SEG instance.
* Uses the instance SOP Class UID when it is a known SEG class; otherwise falls back to store defaultMode.
*/
export function getSegmentationParserType(
sopClassUID: string | undefined,
customizationService?: SegmentationCustomizationReader
): SegmentationMode {
if (sopClassUID === LABELMAP_SEG_SOP_CLASS_UID) {
return 'labelmap';
}
if (sopClassUID === BITMAP_SEG_SOP_CLASS_UID) {
return 'bitmap';
}
return getStoreDefaultMode(customizationService);
}
/**
* Options passed to @cornerstonejs/adapters generateSegmentation when exporting or storing SEG.
*
* Defaults to **Label Map + RLE Lossless**. Customizations (or per-data-source
* `configuration.segmentation.store`) are only needed to opt into bitmap and/or
* uncompressed Explicit VR Little Endian.
*/
export function getSegmentationSaveOptions(
customizationService?: SegmentationCustomizationReader,
override?: SegmentationStoreOverride
): {
sopClassUID: string;
transferSyntaxUID: string;
transferSyntaxUid: string;
} {
const defaultMode = getStoreDefaultMode(customizationService, override);
const sopClassUID =
defaultMode === 'bitmap' ? BITMAP_SEG_SOP_CLASS_UID : LABELMAP_SEG_SOP_CLASS_UID;
const transferSyntaxUID = getStoreTransferSyntaxUID(
customizationService,
override
);
return {
sopClassUID,
transferSyntaxUID,
transferSyntaxUid: transferSyntaxUID,
};
}
@@ -95,10 +95,13 @@ function OHIFCornerstoneSEGViewport(props: withAppTypes) {
};
const getCornerstoneViewport = useCallback(() => {
// Stack uses the referenced series (data[0]); SEG is applied as an overlay (data[1]).
// Passing only the SEG display set leaves the stack with derived labelmap imageIds,
// which are not displayable without the underlying grayscale series.
return (
<OHIFCornerstoneViewport
{...props}
displaySets={[segDisplaySet]}
displaySets={[referencedDisplaySet, segDisplaySet]}
viewportOptions={{
viewportType: viewportOptions.viewportType,
toolGroupId: toolGroupId,
@@ -111,7 +114,14 @@ function OHIFCornerstoneSEGViewport(props: withAppTypes) {
}}
/>
);
}, [viewportId, segDisplaySet, toolGroupId, props, viewportOptions]);
}, [
viewportId,
segDisplaySet,
referencedDisplaySet,
toolGroupId,
props,
viewportOptions,
]);
useEffect(() => {
if (segIsLoading) {
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone-dicom-sr",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "OHIF extension for an SR Cornerstone Viewport",
"author": "OHIF",
"license": "MIT",
@@ -32,7 +32,7 @@
"@ohif/core": "workspace:*",
"@ohif/extension-cornerstone": "workspace:*",
"@ohif/ui": "workspace:*",
"dcmjs": "0.49.4",
"dcmjs": "0.52.0",
"dicom-parser": "1.8.21",
"hammerjs": "2.0.8",
"prop-types": "15.8.1",
@@ -40,9 +40,9 @@
},
"dependencies": {
"@babel/runtime": "7.29.7",
"@cornerstonejs/adapters": "5.1.3",
"@cornerstonejs/core": "5.1.3",
"@cornerstonejs/tools": "5.1.3",
"@cornerstonejs/adapters": "5.4.13",
"@cornerstonejs/core": "5.4.13",
"@cornerstonejs/tools": "5.4.13",
"classnames": "2.5.1"
},
"devDependencies": {
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone-dynamic-volume",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "OHIF extension for 4D volumes data",
"author": "OHIF",
"license": "MIT",
@@ -37,7 +37,7 @@
"@ohif/extension-default": "workspace:*",
"@ohif/i18n": "workspace:*",
"@ohif/ui": "workspace:*",
"dcmjs": "0.49.4",
"dcmjs": "0.52.0",
"dicom-parser": "1.8.21",
"hammerjs": "2.0.8",
"prop-types": "15.8.1",
@@ -45,8 +45,8 @@
},
"dependencies": {
"@babel/runtime": "7.29.7",
"@cornerstonejs/core": "5.1.3",
"@cornerstonejs/tools": "5.1.3",
"@cornerstonejs/core": "5.4.13",
"@cornerstonejs/tools": "5.4.13",
"classnames": "2.5.1"
},
"devDependencies": {
+10 -10
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "OHIF extension for Cornerstone",
"author": "OHIF",
"license": "MIT",
@@ -38,11 +38,11 @@
"@cornerstonejs/codec-libjpeg-turbo-8bit": "1.2.2",
"@cornerstonejs/codec-openjpeg": "1.3.0",
"@cornerstonejs/codec-openjph": "2.4.7",
"@cornerstonejs/dicom-image-loader": "5.1.3",
"@cornerstonejs/dicom-image-loader": "5.4.13",
"@ohif/core": "workspace:*",
"@ohif/extension-default": "workspace:*",
"@ohif/ui": "workspace:*",
"dcmjs": "0.49.4",
"dcmjs": "0.52.0",
"dicom-parser": "1.8.21",
"hammerjs": "2.0.8",
"prop-types": "15.8.1",
@@ -52,13 +52,13 @@
},
"dependencies": {
"@babel/runtime": "7.29.7",
"@cornerstonejs/adapters": "5.1.3",
"@cornerstonejs/ai": "5.1.3",
"@cornerstonejs/core": "5.1.3",
"@cornerstonejs/labelmap-interpolation": "5.1.3",
"@cornerstonejs/metadata": "5.1.3",
"@cornerstonejs/polymorphic-segmentation": "5.1.3",
"@cornerstonejs/tools": "5.1.3",
"@cornerstonejs/adapters": "5.4.13",
"@cornerstonejs/ai": "5.4.13",
"@cornerstonejs/core": "5.4.13",
"@cornerstonejs/labelmap-interpolation": "5.4.13",
"@cornerstonejs/metadata": "5.4.13",
"@cornerstonejs/polymorphic-segmentation": "5.4.13",
"@cornerstonejs/tools": "5.4.13",
"@icr/polyseg-wasm": "0.4.0",
"@itk-wasm/morphological-contour-interpolation": "1.1.0",
"@kitware/vtk.js": "35.5.3",
@@ -350,7 +350,10 @@ function _getInstanceNumberFromVolume(
const imageId = imageIds[imageIndex];
if (!imageId) {
return {};
// No image at this index (e.g. a single-image volume scrolled out of
// range). Return undefined so the overlay falls back to the slice count
// instead of rendering an empty object as "[object Object]".
return;
}
const { instanceNumber } = metaData.get('generalImageModule', imageId) || {};
+9 -2
View File
@@ -1982,8 +1982,15 @@ function commandsModule({
* Use it before initializing the toolGroup with the tools.
*/
initializeSegmentLabelTool: ({ tools }) => {
const appConfig = extensionManager.appConfig;
const segmentLabelConfig = appConfig.segmentation?.segmentLabel;
const { customizationService } = servicesManager.services;
const segmentLabelConfig = customizationService.getCustomization(
'segmentation.segmentLabel'
) as {
enabledByDefault?: boolean;
labelColor?: number[];
hoverTimeout?: number;
background?: string;
};
if (segmentLabelConfig?.enabledByDefault) {
const activeTools = tools?.active ?? [];
@@ -1,8 +1,11 @@
import type { Button } from '@ohif/core/types';
import { ViewportGridService } from '@ohif/core';
import { ViewportGridService, ToolbarService } from '@ohif/core';
import i18n from 'i18next';
import { MIN_SEGMENTATION_DRAWING_RADIUS, MAX_SEGMENTATION_DRAWING_RADIUS } from './constants';
const { TOOLBAR_SECTIONS } = ToolbarService;
export const MIN_SEGMENTATION_DRAWING_RADIUS = 0.5;
export const MAX_SEGMENTATION_DRAWING_RADIUS = 99.5;
const setToolActiveToolbar = {
commandName: 'setToolActiveToolbar',
@@ -20,155 +23,16 @@ const callbacks = (toolName: string) => [
},
];
export const toolbarButtons: Button[] = [
{
id: 'AdvancedRenderingControls',
uiType: 'ohif.advancedRenderingControls',
props: {
buttonSection: true,
},
},
{
id: 'modalityLoadBadge',
uiType: 'ohif.modalityLoadBadge',
props: {
icon: 'Status',
label: i18n.t('Buttons:Status'),
tooltip: i18n.t('Buttons:Status'),
evaluate: {
name: 'evaluate.modalityLoadBadge',
hideWhenDisabled: true,
},
},
},
{
id: 'navigationComponent',
uiType: 'ohif.navigationComponent',
props: {
icon: 'Navigation',
label: i18n.t('Buttons:Navigation'),
tooltip: i18n.t('Buttons:Navigate between segments/measurements and manage their visibility'),
evaluate: {
name: 'evaluate.navigationComponent',
hideWhenDisabled: true,
},
},
},
{
id: 'trackingStatus',
uiType: 'ohif.trackingStatus',
props: {
icon: 'TrackingStatus',
label: i18n.t('Buttons:Tracking Status'),
tooltip: i18n.t('Buttons:View and manage tracking status of measurements and annotations'),
evaluate: {
name: 'evaluate.trackingStatus',
hideWhenDisabled: true,
},
},
},
{
id: 'dataOverlayMenu',
uiType: 'ohif.dataOverlayMenu',
props: {
icon: 'ViewportViews',
label: i18n.t('Buttons:Data Overlay'),
tooltip: i18n.t(
'Buttons:Configure data overlay options and manage foreground/background display sets'
),
evaluate: 'evaluate.dataOverlayMenu',
},
},
{
id: 'orientationMenu',
uiType: 'ohif.orientationMenu',
props: {
icon: 'OrientationSwitch',
label: i18n.t('Buttons:Orientation'),
tooltip: i18n.t(
'Buttons:Change viewport orientation between axial, sagittal, coronal and reformat planes'
),
evaluate: {
name: 'evaluate.orientationMenu',
// hideWhenDisabled: true,
},
},
},
{
id: 'windowLevelMenuEmbedded',
uiType: 'ohif.windowLevelMenuEmbedded',
props: {
icon: 'WindowLevel',
label: i18n.t('Buttons:Window Level'),
tooltip: i18n.t('Buttons:Adjust window/level presets and customize image contrast settings'),
evaluate: {
name: 'evaluate.windowLevelMenuEmbedded',
hideWhenDisabled: true,
},
},
},
{
id: 'windowLevelMenu',
uiType: 'ohif.windowLevelMenu',
props: {
icon: 'WindowLevel',
label: i18n.t('Buttons:Window Level'),
tooltip: i18n.t('Buttons:Adjust window/level presets and customize image contrast settings'),
evaluate: 'evaluate.windowLevelMenu',
},
},
{
id: 'voiManualControlMenu',
uiType: 'ohif.voiManualControlMenu',
props: {
icon: 'WindowLevelAdvanced',
label: i18n.t('Buttons:Advanced Window Level'),
tooltip: i18n.t('Buttons:Advanced window/level settings with manual controls and presets'),
evaluate: 'evaluate.voiManualControlMenu',
},
},
{
id: 'thresholdMenu',
uiType: 'ohif.thresholdMenu',
props: {
icon: 'Threshold',
label: i18n.t('Buttons:Threshold'),
tooltip: i18n.t('Buttons:Image threshold settings'),
evaluate: {
name: 'evaluate.thresholdMenu',
hideWhenDisabled: true,
},
},
},
{
id: 'opacityMenu',
uiType: 'ohif.opacityMenu',
props: {
icon: 'Opacity',
label: i18n.t('Buttons:Opacity'),
tooltip: i18n.t('Buttons:Image opacity settings'),
evaluate: {
name: 'evaluate.opacityMenu',
hideWhenDisabled: true,
},
},
},
{
id: 'Colorbar',
uiType: 'ohif.colorbar',
props: {
type: 'tool',
label: i18n.t('Buttons:Colorbar'),
},
},
// sections
{
id: 'MoreTools',
uiType: 'ohif.toolButtonList',
props: {
buttonSection: true,
},
},
/**
* Segmentation editing toolbar buttons: the toolbox section containers plus
* the labelmap / contour editing tools and utilities. These complement the
* general buttons in `cornerstone.toolbarButtons`; together they are the
* default button set for the segmentation mode, and modes such as basic /
* longitudinal can pull them in via a customization (see
* `segmentationEditing.jsonc`).
*/
const segmentationToolbarButtons: Button[] = [
// section containers for the nested toolboxes and toolbars
{
id: 'BrushTools',
uiType: 'ohif.toolBoxButtonGroup',
@@ -176,7 +40,6 @@ export const toolbarButtons: Button[] = [
buttonSection: true,
},
},
// Section containers for the nested toolboxes and toolbars.
{
id: 'LabelMapUtilities',
uiType: 'ohif.Toolbar',
@@ -206,215 +69,6 @@ export const toolbarButtons: Button[] = [
},
},
// tool defs
{
id: 'Zoom',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-zoom',
label: i18n.t('Buttons:Zoom'),
commands: setToolActiveToolbar,
evaluate: 'evaluate.cornerstoneTool',
},
},
{
id: 'WindowLevel',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-window-level',
label: i18n.t('Buttons:Window Level'),
commands: setToolActiveToolbar,
evaluate: 'evaluate.cornerstoneTool',
},
},
{
id: 'Pan',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-move',
label: i18n.t('Buttons:Pan'),
commands: setToolActiveToolbar,
evaluate: 'evaluate.cornerstoneTool',
},
},
{
id: 'TrackballRotate',
uiType: 'ohif.toolButton',
props: {
type: 'tool',
icon: 'tool-3d-rotate',
label: i18n.t('Buttons:3D Rotate'),
commands: setToolActiveToolbar,
evaluate: {
name: 'evaluate.cornerstoneTool',
disabledText: i18n.t('Buttons:Select a 3D viewport to enable this tool'),
},
},
},
{
id: 'Capture',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-capture',
label: i18n.t('Buttons:Capture'),
commands: 'showDownloadViewportModal',
evaluate: [
'evaluate.action',
{
name: 'evaluate.viewport.supported',
unsupportedViewportTypes: ['video', 'wholeSlide'],
},
],
},
},
{
id: 'Layout',
uiType: 'ohif.layoutSelector',
props: {
rows: 3,
columns: 4,
evaluate: 'evaluate.action',
commands: 'setViewportGridLayout',
},
},
{
id: 'Crosshairs',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-crosshair',
label: i18n.t('Buttons:Crosshairs'),
commands: {
commandName: 'setToolActiveToolbar',
commandOptions: {
toolGroupIds: ['mpr'],
},
},
evaluate: {
name: 'evaluate.cornerstoneTool',
disabledText: i18n.t('Buttons:Select an MPR viewport to enable this tool'),
},
},
},
{
id: 'Reset',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-reset',
label: i18n.t('Buttons:Reset View'),
tooltip: i18n.t('Buttons:Reset View'),
commands: 'resetViewport',
evaluate: 'evaluate.action',
},
},
{
id: 'rotate-right',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-rotate-right',
label: i18n.t('Buttons:Rotate Right'),
tooltip: i18n.t('Buttons:Rotate +90'),
commands: 'rotateViewportCW',
evaluate: 'evaluate.action',
},
},
{
id: 'flipHorizontal',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-flip-horizontal',
label: i18n.t('Buttons:Flip Horizontal'),
tooltip: i18n.t('Buttons:Flip Horizontally'),
commands: 'flipViewportHorizontal',
evaluate: [
'evaluate.viewportProperties.toggle',
{
name: 'evaluate.viewport.supported',
unsupportedViewportTypes: ['volume3d'],
},
],
},
},
{
id: 'ReferenceLines',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-referenceLines',
label: i18n.t('Buttons:Reference Lines'),
tooltip: i18n.t('Buttons:Show Reference Lines'),
commands: 'toggleEnabledDisabledToolbar',
evaluate: 'evaluate.cornerstoneTool.toggle',
},
},
{
id: 'ImageOverlayViewer',
uiType: 'ohif.toolButton',
props: {
icon: 'toggle-dicom-overlay',
label: i18n.t('Buttons:Image Overlay'),
tooltip: i18n.t('Buttons:Toggle Image Overlay'),
commands: 'toggleEnabledDisabledToolbar',
evaluate: 'evaluate.cornerstoneTool.toggle',
},
},
{
id: 'StackScroll',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-stack-scroll',
label: i18n.t('Buttons:Stack Scroll'),
tooltip: i18n.t('Buttons:Stack Scroll'),
commands: setToolActiveToolbar,
evaluate: 'evaluate.cornerstoneTool',
},
},
{
id: 'invert',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-invert',
label: i18n.t('Buttons:Invert'),
tooltip: i18n.t('Buttons:Invert Colors'),
commands: 'invertViewport',
evaluate: 'evaluate.viewportProperties.toggle',
},
},
{
id: 'Cine',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-cine',
label: i18n.t('Buttons:Cine'),
tooltip: i18n.t('Buttons:Cine'),
commands: 'toggleCine',
evaluate: [
'evaluate.cine',
{
name: 'evaluate.viewport.supported',
unsupportedViewportTypes: ['volume3d'],
},
],
},
},
{
id: 'Magnify',
uiType: 'ohif.toolButton',
props: {
icon: 'tool-magnify',
label: i18n.t('Buttons:Zoom-in'),
tooltip: i18n.t('Buttons:Zoom-in'),
commands: setToolActiveToolbar,
evaluate: 'evaluate.cornerstoneTool',
},
},
{
id: 'TagBrowser',
uiType: 'ohif.toolButton',
props: {
icon: 'dicom-tag-browser',
label: i18n.t('Buttons:Dicom Tag Browser'),
tooltip: i18n.t('Buttons:Dicom Tag Browser'),
commands: 'openDICOMTagViewer',
},
},
{
id: 'PlanarFreehandContourSegmentationTool',
uiType: 'ohif.toolBoxButton',
@@ -559,7 +213,11 @@ export const toolbarButtons: Button[] = [
value: 'CatmullRomSplineROI',
label: i18n.t('Buttons:Catmull Rom Spline'),
},
{ id: 'LinearSplineROI', value: 'LinearSplineROI', label: i18n.t('Buttons:Linear Spline') },
{
id: 'LinearSplineROI',
value: 'LinearSplineROI',
label: i18n.t('Buttons:Linear Spline'),
},
{ id: 'BSplineROI', value: 'BSplineROI', label: i18n.t('Buttons:B-Spline') },
],
commands: {
@@ -763,18 +421,23 @@ export const toolbarButtons: Button[] = [
},
},
{
id: 'RegionSegmentPlus',
id: 'ClickSegment',
uiType: 'ohif.toolBoxButton',
props: {
icon: 'icon-tool-click-segment',
label: i18n.t('Buttons:One Click Segment'),
label: i18n.t('Buttons:Click to Segment'),
tooltip: i18n.t(
'Buttons:Detects segmentable regions with one click. Hover for visual feedback—click when a plus sign appears to auto-segment the lesion.'
'Buttons:PET only. Click-to-segment lesions with no configuration. Hover for visual feedback—click when a plus sign appears to segment the lesion.'
),
evaluate: [
{
name: 'evaluate.modality.supported',
supportedModalities: ['PT'],
disabledText: i18n.t('Buttons:Tool not available for this modality'),
},
{
name: 'evaluate.cornerstone.segmentation',
toolNames: ['RegionSegmentPlus'],
toolNames: ['ClickSegment'],
disabledText: i18n.t('Buttons:Create new segmentation to enable this tool.'),
},
{
@@ -1195,4 +858,106 @@ export const toolbarButtons: Button[] = [
},
];
export default toolbarButtons;
/**
* The toolbox / utilities section wiring for segmentation editing. These are
* the sections rendered by the `panelSegmentationWithTools*` panels, so any
* mode that shows those panels can merge this block into its toolbar sections.
*/
export const segmentationToolboxSections: Record<string, string[]> = {
[TOOLBAR_SECTIONS.labelMapSegmentationToolbox]: ['LabelMapTools'],
[TOOLBAR_SECTIONS.contourSegmentationToolbox]: ['ContourTools'],
[TOOLBAR_SECTIONS.labelMapSegmentationUtilities]: ['LabelMapUtilities'],
[TOOLBAR_SECTIONS.contourSegmentationUtilities]: ['ContourUtilities'],
LabelMapTools: [
'LabelmapSlicePropagation',
'BrushTools',
'MarkerLabelmap',
'ClickSegment',
'Shapes',
'LabelMapEditWithContour',
],
ContourTools: [
'PlanarFreehandContourSegmentationTool',
'SculptorTool',
'SplineContourSegmentationTool',
'LivewireContourSegmentationTool',
],
LabelMapUtilities: ['InterpolateLabelmap', 'SegmentBidirectional'],
ContourUtilities: ['LogicalContourOperations', 'SimplifyContours', 'SmoothContours'],
BrushTools: ['Brush', 'Eraser', 'Threshold'],
};
/**
* The segmentation mode's main toolbar layout (primary bar and viewport
* action corners). Kept separate from the toolbox wiring above so other modes
* can adopt segmentation editing without adopting this mode layout.
*/
export const segmentationModeToolbarSections: Record<string, string[]> = {
[TOOLBAR_SECTIONS.primary]: [
'WindowLevel',
'Pan',
'Zoom',
'TrackballRotate',
'Capture',
'Layout',
'Crosshairs',
'MoreTools',
],
[TOOLBAR_SECTIONS.viewportActionMenu.topLeft]: ['orientationMenu', 'dataOverlayMenu'],
[TOOLBAR_SECTIONS.viewportActionMenu.bottomMiddle]: ['AdvancedRenderingControls'],
AdvancedRenderingControls: [
'windowLevelMenuEmbedded',
'voiManualControlMenu',
'Colorbar',
'opacityMenu',
'thresholdMenu',
],
[TOOLBAR_SECTIONS.viewportActionMenu.topRight]: [
'modalityLoadBadge',
'trackingStatus',
'navigationComponent',
],
[TOOLBAR_SECTIONS.viewportActionMenu.bottomLeft]: ['windowLevelMenu'],
MoreTools: [
'Reset',
'rotate-right',
'flipHorizontal',
'ReferenceLines',
'ImageOverlayViewer',
'StackScroll',
'invert',
'Cine',
'Magnify',
'TagBrowser',
],
};
/**
* Segmentation capability packs registered (at default scope) by the
* cornerstone extension. These are pure "what can exist" packs and carry no
* mode identity:
* - `cornerstone.segmentationToolbarButtons` – segmentation editing button definitions
* - `cornerstone.segmentationToolbarSections` – toolbox/utilities section wiring
* - `cornerstone.segmentationModeToolbarSections` – a reusable segmentation-mode toolbar layout
*
* Modes compose these by name in their own `toolbarButtons` /
* `toolbarSections` instance arrays; `?customization=` modules extend the
* result through the `mode` phase.
*/
const segmentationToolbarCustomization = {
'cornerstone.segmentationToolbarButtons': segmentationToolbarButtons,
'cornerstone.segmentationToolbarSections': segmentationToolboxSections,
'cornerstone.segmentationModeToolbarSections': segmentationModeToolbarSections,
};
export { segmentationToolbarButtons };
export default segmentationToolbarCustomization;
@@ -0,0 +1,204 @@
import { toolNames } from '../initCornerstoneTools';
import {
MIN_SEGMENTATION_DRAWING_RADIUS,
MAX_SEGMENTATION_DRAWING_RADIUS,
} from './segmentationToolbarCustomization';
/**
* Reusable tool group "capability blocks", registered as default
* customizations so modes and `?customization=` JSON modules can add them to
* a tool group by name via a mode's `toolGroupAdditions` customization, e.g.
*
* "mode": {
* "basic": {
* "toolGroupAdditions": {
* "default": { "$push": [{ "$reference": "cornerstone.segmentationTools" }] }
* }
* }
* }
*
* Each block is a `{ active/passive/enabled/disabled }` object suitable for
* `toolGroupService.addToolsToToolGroup`.
*/
function getToolGroupToolsCustomization({ commandsManager }) {
const brushInstances = [
{
toolName: 'CircularBrush',
parentTool: 'Brush',
configuration: {
activeStrategy: 'FILL_INSIDE_CIRCLE',
minRadius: MIN_SEGMENTATION_DRAWING_RADIUS,
maxRadius: MAX_SEGMENTATION_DRAWING_RADIUS,
},
},
{
toolName: 'CircularEraser',
parentTool: 'Brush',
configuration: {
activeStrategy: 'ERASE_INSIDE_CIRCLE',
minRadius: MIN_SEGMENTATION_DRAWING_RADIUS,
maxRadius: MAX_SEGMENTATION_DRAWING_RADIUS,
},
},
{
toolName: 'SphereBrush',
parentTool: 'Brush',
configuration: {
activeStrategy: 'FILL_INSIDE_SPHERE',
minRadius: MIN_SEGMENTATION_DRAWING_RADIUS,
maxRadius: MAX_SEGMENTATION_DRAWING_RADIUS,
},
},
{
toolName: 'SphereEraser',
parentTool: 'Brush',
configuration: {
activeStrategy: 'ERASE_INSIDE_SPHERE',
minRadius: MIN_SEGMENTATION_DRAWING_RADIUS,
maxRadius: MAX_SEGMENTATION_DRAWING_RADIUS,
},
},
{
toolName: 'ThresholdCircularBrush',
parentTool: 'Brush',
configuration: {
activeStrategy: 'THRESHOLD_INSIDE_CIRCLE',
minRadius: MIN_SEGMENTATION_DRAWING_RADIUS,
maxRadius: MAX_SEGMENTATION_DRAWING_RADIUS,
},
},
{
toolName: 'ThresholdSphereBrush',
parentTool: 'Brush',
configuration: {
activeStrategy: 'THRESHOLD_INSIDE_SPHERE',
minRadius: MIN_SEGMENTATION_DRAWING_RADIUS,
maxRadius: MAX_SEGMENTATION_DRAWING_RADIUS,
},
},
{
toolName: 'ThresholdCircularBrushDynamic',
parentTool: 'Brush',
configuration: {
activeStrategy: 'THRESHOLD_INSIDE_CIRCLE',
minRadius: MIN_SEGMENTATION_DRAWING_RADIUS,
maxRadius: MAX_SEGMENTATION_DRAWING_RADIUS,
threshold: {
isDynamic: true,
dynamicRadius: 3,
},
},
},
{
toolName: 'ThresholdSphereBrushDynamic',
parentTool: 'Brush',
configuration: {
activeStrategy: 'THRESHOLD_INSIDE_SPHERE',
minRadius: MIN_SEGMENTATION_DRAWING_RADIUS,
maxRadius: MAX_SEGMENTATION_DRAWING_RADIUS,
threshold: {
isDynamic: true,
dynamicRadius: 3,
},
},
},
];
const splineInstances = [
{
toolName: 'CatmullRomSplineROI',
parentTool: toolNames.SplineContourSegmentation,
configuration: {
spline: {
type: 'CATMULLROM',
enableTwoPointPreview: true,
},
},
},
{
toolName: 'LinearSplineROI',
parentTool: toolNames.SplineContourSegmentation,
configuration: {
spline: {
type: 'LINEAR',
enableTwoPointPreview: true,
},
},
},
{
toolName: 'BSplineROI',
parentTool: toolNames.SplineContourSegmentation,
configuration: {
spline: {
type: 'BSPLINE',
enableTwoPointPreview: true,
},
},
},
];
return {
/**
* The segmentation editing tools (labelmap brushes/scissors and contour
* segmentation tools), matching the buttons in
* `cornerstone.segmentationToolbarButtons`.
*/
'cornerstone.segmentationTools': {
passive: [
...brushInstances,
{ toolName: toolNames.LabelmapSlicePropagation },
{ toolName: toolNames.MarkerLabelmap },
{ toolName: toolNames.ClickSegment },
{ toolName: toolNames.LabelMapEditWithContourTool },
{ toolName: toolNames.SegmentSelect },
{ toolName: toolNames.CircleScissors },
{ toolName: toolNames.RectangleScissors },
{ toolName: toolNames.SphereScissors },
{ toolName: toolNames.LivewireContourSegmentation },
{ toolName: toolNames.SculptorTool },
...splineInstances,
],
},
/**
* The measurement/annotation tools, matching the `MeasurementTools`
* buttons in `cornerstone.toolbarButtons`. Useful for adding annotations
* to modes (such as segmentation) whose tool groups omit them.
*/
'cornerstone.annotationTools': {
passive: [
{ toolName: toolNames.Length },
{
toolName: toolNames.ArrowAnnotate,
configuration: {
getTextCallback: (callback, eventDetails) => {
commandsManager.runCommand('arrowTextCallback', {
callback,
eventDetails,
});
},
changeTextCallback: (data, eventDetails, callback) => {
commandsManager.runCommand('arrowTextCallback', {
callback,
data,
eventDetails,
});
},
},
},
{ toolName: toolNames.Bidirectional },
{ toolName: toolNames.Probe },
{ toolName: toolNames.DragProbe },
{ toolName: toolNames.EllipticalROI },
{ toolName: toolNames.CircleROI },
{ toolName: toolNames.RectangleROI },
{ toolName: toolNames.Angle },
{ toolName: toolNames.CobbAngle },
{ toolName: toolNames.SplineROI },
{ toolName: toolNames.LivewireContour },
],
},
};
}
export default getToolGroupToolsCustomization;
@@ -784,12 +784,16 @@ export const toolbarSections = {
};
/**
* Customizations registered (at default scope) by the cornerstone extension:
* - `cornerstone.toolbarButtons` – the default toolbar button definitions
* - `cornerstone.toolbarSections` – the default toolbar layout (section -> button ids)
* Capability packs registered (at default scope) by the cornerstone extension:
* - `cornerstone.toolbarButtons` – the general toolbar button definitions
* - `cornerstone.toolbarSections` – the general toolbar layout (section -> button ids)
*
* Modes read these by name in `onModeEnter`; URL `?customization=` modules can
* extend them with immutability-helper commands (e.g. `$push` a new button).
* These are pure "what can exist" packs — they carry no mode identity. Modes
* compose them with `{ $reference }` markers in their own `toolbarButtons` /
* `toolbarSections` instance arrays, which the mode route seeds into the Mode
* customization scope on enter; URL `?customization=` modules extend the result
* through the `mode` phase (e.g.
* `mode.basic.toolbarButtons: { $push: [{ $reference: '...' }] }`).
*/
const toolbarButtonsCustomization = {
'cornerstone.toolbarButtons': toolbarButtons,
@@ -9,6 +9,8 @@ import colorbarCustomization from './customizations/colorbarCustomization';
import modalityColorMapCustomization from './customizations/modalityColorMapCustomization';
import windowLevelPresetsCustomization from './customizations/windowLevelPresetsCustomization';
import toolbarButtonsCustomization from './customizations/toolbarButtonsCustomization';
import segmentationToolbarCustomization from './customizations/segmentationToolbarCustomization';
import getToolGroupToolsCustomization from './customizations/toolGroupToolsCustomization';
import miscCustomization from './customizations/miscCustomization';
import captureViewportModalCustomization from './customizations/captureViewportModalCustomization';
import viewportDownloadWarningCustomization from './customizations/viewportDownloadWarningCustomization';
@@ -34,6 +36,8 @@ function getCustomizationModule({ commandsManager, servicesManager, extensionMan
...modalityColorMapCustomization,
...windowLevelPresetsCustomization,
...toolbarButtonsCustomization,
...segmentationToolbarCustomization,
...getToolGroupToolsCustomization({ commandsManager }),
...miscCustomization,
...captureViewportModalCustomization,
...viewportDownloadWarningCustomization,
+6
View File
@@ -7,6 +7,7 @@ import {
imageRetrievalPoolManager,
} from '@cornerstonejs/core';
import { Enums as cs3DToolsEnums } from '@cornerstonejs/tools';
import { utilities as csMetadataUtilities } from '@cornerstonejs/metadata';
import { Types } from '@ohif/core';
import Enums from './enums';
@@ -169,6 +170,11 @@ const cornerstoneExtension: Types.Extensions.Extension = {
imageRetrievalPoolManager.clearRequestStack(type);
});
// Release the typed metadata registry (NATURALIZED instances registered via
// prefetchPart10Instance hold full compressed Part 10 buffers that live
// outside the size-capped cornerstone image cache)
csMetadataUtilities.clearCacheData();
cineService.setIsCineEnabled(false);
enabledElementReset();
@@ -40,7 +40,7 @@ import {
OrientationMarkerTool,
WindowLevelRegionTool,
SegmentSelectTool,
RegionSegmentPlusTool,
ClickSegmentTool,
SegmentLabelTool,
LivewireContourSegmentationTool,
SculptorTool,
@@ -114,7 +114,7 @@ export default function initCornerstoneTools(configuration = {}) {
addTool(SegmentLabelTool);
addTool(LabelmapSlicePropagationTool);
addTool(MarkerLabelmapTool);
addTool(RegionSegmentPlusTool);
addTool(ClickSegmentTool);
addTool(LivewireContourSegmentationTool);
addTool(SculptorTool);
addTool(SplineContourSegmentationTool);
@@ -178,7 +178,7 @@ const toolNames = {
SegmentLabel: SegmentLabelTool.toolName,
LabelmapSlicePropagation: LabelmapSlicePropagationTool.toolName,
MarkerLabelmap: MarkerLabelmapTool.toolName,
RegionSegmentPlus: RegionSegmentPlusTool.toolName,
ClickSegment: ClickSegmentTool.toolName,
LivewireContourSegmentation: LivewireContourSegmentationTool.toolName,
SculptorTool: SculptorTool.toolName,
SplineContourSegmentation: SplineContourSegmentationTool.toolName,
@@ -1799,6 +1799,10 @@ describe('SegmentationService', () => {
const segmentationId = 'segmentationId';
const segmentationData = {
segmentationId,
representation: {
type: csToolsEnums.SegmentationRepresentations.Labelmap,
data: {},
},
config: {
label: 'Segmentation 1',
},
@@ -302,7 +302,15 @@ class SegmentationService extends PubSubService {
}
): Promise<void> {
const segmentation = this.getSegmentation(segmentationId);
if (segmentation && !segmentation.predecessorImageId && predecessorImageId) {
if (!segmentation) {
console.warn(
`addSegmentationRepresentation: segmentation "${segmentationId}" is not in state yet`
);
return;
}
if (!segmentation.predecessorImageId && predecessorImageId) {
segmentation.predecessorImageId = predecessorImageId;
}
const csViewport = this.getAndValidateViewport(viewportId);
@@ -488,10 +496,22 @@ class SegmentationService extends PubSubService {
throw new Error('No instances were provided for the referenced display set of the SEG');
}
const imageIds = images.map(image => image.imageId);
// Use the same imageIds as SEG parse (_loadSegments stores these on segDisplaySet).
const imageIds =
segDisplaySet.referencedImageIds ||
(referencedDisplaySet.imageIds as string[] | undefined) ||
images.map(image => image.imageId);
if (!imageIds?.length) {
throw new Error('referencedDisplaySet has no imageIds for SEG');
}
const derivedImages = labelMapImages?.flat();
const derivedImageIds = derivedImages.map(image => image.imageId);
// Note: instance runtime props (frameNumber, imageId, url, ...) are
// intentionally non-enumerable, so this spread deliberately does NOT copy
// them — frameNumber must not be carried onto these derived image entries.
// Read such props off the original instance, never off a copy.
segDisplaySet.images = derivedImages.map(image => ({
...image,
...metaData.get('instance', image.referencedImageId),
@@ -572,11 +592,6 @@ class SegmentationService extends PubSubService {
const colorLUTIndex = addColorLUT(colorLUT);
this._segmentationIdToColorLUTIndexMap.set(segmentationId, colorLUTIndex);
this._broadcastEvent(EVENTS.SEGMENTATION_LOADING_COMPLETE, {
segmentationId,
segDisplaySet,
});
const seg: cstTypes.SegmentationPublicInput = {
segmentationId,
representation: {
@@ -596,8 +611,18 @@ class SegmentationService extends PubSubService {
segDisplaySet.isLoaded = true;
// Add the segmentation to cornerstone state BEFORE broadcasting that loading is
// complete. Subscribers (e.g. CornerstoneViewportService) react synchronously and
// call addSegmentationRepresentation, which now early-returns when the segmentation
// is not yet in cornerstone state. Broadcasting first would make that guard always
// fire on initial load, silently preventing the representation from being attached.
this.addOrUpdateSegmentation(seg);
this._broadcastEvent(EVENTS.SEGMENTATION_LOADING_COMPLETE, {
segmentationId,
segDisplaySet,
});
return segmentationId;
}
@@ -772,9 +797,16 @@ class SegmentationService extends PubSubService {
if (existingSegmentation) {
// Update the existing segmentation
this.updateSegmentationInSource(segmentationId, data as Partial<cstTypes.Segmentation>);
} else {
} else if (
'representation' in data &&
(data as cstTypes.SegmentationPublicInput).representation
) {
// Add a new segmentation
this.addSegmentationToSource(data as cstTypes.SegmentationPublicInput);
} else {
console.warn(
`addOrUpdateSegmentation: skipping add for ${segmentationId} — missing representation`
);
}
}
@@ -1596,7 +1628,13 @@ class SegmentationService extends PubSubService {
private determineViewportAndSegmentationType(csViewport, segmentation) {
const isVolumeViewport = isVolumeViewportType(csViewport);
const isVolumeSegmentation = 'volumeId' in segmentation.representationData[LABELMAP];
const labelmapData = segmentation?.representationData?.[LABELMAP];
if (!labelmapData) {
return { isVolumeViewport, isVolumeSegmentation: false };
}
const isVolumeSegmentation = 'volumeId' in labelmapData;
return { isVolumeViewport, isVolumeSegmentation };
}
@@ -1294,24 +1294,122 @@ class CornerstoneViewportService extends PubSubService implements IViewportServi
? csToolsEnums.SegmentationRepresentations.Labelmap
: csToolsEnums.SegmentationRepresentations.Contour;
const { predecessorImageId } = displaySet;
const segmentationRepresentationPromise = segmentationService.addSegmentationRepresentation(
viewport.id,
{
segmentationId,
predecessorImageId,
type: representationType,
config: {
blendMode:
viewport?.getBlendMode?.() === 1
? BlendModes.LABELMAP_EDGE_PROJECTION_BLEND
: undefined,
},
const applyRepresentation = () => {
const { predecessorImageId } = displaySet;
const segmentationRepresentationPromise =
segmentationService.addSegmentationRepresentation(viewport.id, {
segmentationId,
predecessorImageId,
type: representationType,
config: {
blendMode:
viewport?.getBlendMode?.() === 1
? BlendModes.LABELMAP_EDGE_PROJECTION_BLEND
: undefined,
},
});
this.storePresentation({ viewportId: viewport.id });
return segmentationRepresentationPromise;
};
// SEG overlay is registered during stack setup, but cornerstone segmentation state
// is created in displaySet.load() (async). Wait until it exists before adding representation.
if (displaySet.Modality === 'SEG') {
if (segmentationService.getSegmentation(segmentationId)) {
return applyRepresentation();
}
);
// store the segmentation presentation id in the viewport info
this.storePresentation({ viewportId: viewport.id });
return segmentationRepresentationPromise;
// Bound the wait so a failed/aborted SEG load (where SEGMENTATION_LOADING_COMPLETE
// never fires) cannot leave this promise — and the viewport setup awaiting it —
// hanging indefinitely.
const SEG_LOADING_TIMEOUT_MS = 120000;
return new Promise<void>(resolve => {
let settled = false;
let timeoutId;
// Final resolution — extra calls are harmless (resolve is a no-op after
// the first), which lets the timeout stay armed while a representation
// apply is in flight and still bound it.
const finish = () => {
clearTimeout(timeoutId);
resolve();
};
// Give up without applying (load failure / timeout before the event).
const settleWithoutApply = () => {
settled = true;
unsubscribe();
finish();
};
const { unsubscribe } = segmentationService.subscribe(
segmentationService.EVENTS.SEGMENTATION_LOADING_COMPLETE,
async (evt: { segDisplaySet?: OhifTypes.DisplaySet }) => {
if (settled || evt.segDisplaySet?.displaySetInstanceUID !== segmentationId) {
return;
}
// Dedupe immediately, but resolve only after the representation is
// applied: awaiters continue into rotation/flip/render and broadcast
// VIEWPORT_DATA_CHANGED (hanging-protocol callbacks, toolbar, e2e
// readiness), which must not observe a viewport whose overlay
// doesn't exist yet. applyRepresentation can be genuinely async
// (stack→volume viewport conversion). The timeout is deliberately
// NOT cleared here — a hung apply stays bounded.
settled = true;
unsubscribe();
try {
await applyRepresentation();
} catch (error) {
console.warn(
`Failed to apply segmentation representation for "${segmentationId}":`,
error
);
} finally {
finish();
}
}
);
// Stop waiting immediately if the SEG load itself fails — otherwise the
// loading-complete event never fires and we would idle until the timeout.
const loadingPromise = (displaySet as { loadingPromise?: Promise<unknown> })
.loadingPromise;
loadingPromise?.catch(error => {
if (settled) {
return;
}
console.warn(
`Segmentation "${segmentationId}" failed to load; skipping representation setup.`,
error
);
settleWithoutApply();
});
timeoutId = setTimeout(() => {
if (settled) {
// The load completed but applyRepresentation is hung — resolve so
// viewport setup is never blocked past the bound (best-effort
// semantics; the apply may still land later).
console.warn(
`Timed out applying segmentation representation for "${segmentationId}"; resolving viewport readiness anyway.`
);
resolve();
return;
}
console.warn(
`Timed out waiting for segmentation "${segmentationId}" to load; skipping representation setup.`
);
settleWithoutApply();
}, SEG_LOADING_TIMEOUT_MS);
});
}
return applyRepresentation();
}
private async _addOverlayRepresentations(
@@ -53,10 +53,14 @@ export function setupSegmentationDataModifiedHandler({
});
if (!isUnsubscribed && updatedSegmentation) {
segmentationService.addOrUpdateSegmentation({
segmentationId,
segments: updatedSegmentation.segments,
});
const existingSegmentation = segmentationService.getSegmentation(segmentationId);
if (existingSegmentation) {
segmentationService.addOrUpdateSegmentation({
segmentationId,
segments: updatedSegmentation.segments,
});
}
}
},
1000
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-default",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "Common/default features and functionality for basic image viewing",
"author": "OHIF Core Team",
"license": "MIT",
@@ -31,7 +31,7 @@
"peerDependencies": {
"@ohif/core": "workspace:*",
"@ohif/i18n": "workspace:*",
"dcmjs": "0.49.4",
"dcmjs": "0.52.0",
"dicomweb-client": "0.10.4",
"prop-types": "15.8.1",
"react": "18.3.1",
@@ -48,6 +48,7 @@
"react-color": "2.19.3"
},
"devDependencies": {
"cross-env": "7.0.3",
"webpack-merge": "5.10.0"
},
"keywords": [
@@ -1,6 +1,11 @@
import { DicomMetadataStore, IWebApiDataSource, utils } from '@ohif/core';
import OHIF from '@ohif/core';
import dcmjs from 'dcmjs';
import {
datasetToDicomBlob,
makeExistingPropertiesNonEnumerable,
setNonEnumerableInstanceProperty,
} from '../utils/dicomWriter';
import { appendFrameQueryToImageId } from '../utils/appendFrameQueryToImageId';
const metadataProvider = OHIF.classes.MetadataProvider;
const { EVENTS } = DicomMetadataStore;
@@ -152,14 +157,15 @@ function createDicomLocalApi(dicomLocalConfig) {
SOPInstanceUID,
} = instance;
instance.imageId = imageId;
setNonEnumerableInstanceProperty(instance, 'imageId', imageId);
makeExistingPropertiesNonEnumerable(instance);
// Add imageId specific mapping to this data as the URL isn't necessarily WADO-URI.
metadataProvider.addImageIdToUIDs(imageId, {
StudyInstanceUID,
SeriesInstanceUID,
SOPInstanceUID,
frameIndex: isMultiframe ? index : 1,
frameNumber: isMultiframe ? index + 1 : 1,
});
});
@@ -174,7 +180,7 @@ function createDicomLocalApi(dicomLocalConfig) {
},
store: {
dicom: naturalizedReport => {
const reportBlob = dcmjs.data.datasetToBlob(naturalizedReport);
const reportBlob = datasetToDicomBlob(naturalizedReport);
//Create a URL for the binary.
var objectUrl = URL.createObjectURL(reportBlob);
@@ -211,9 +217,6 @@ function createDicomLocalApi(dicomLocalConfig) {
getImageIdsForInstance({ instance, frame }) {
// Important: Never use instance.imageId because it might be multiframe,
// which would make it an invalid imageId.
// if (instance.imageId) {
// return instance.imageId;
// }
const { StudyInstanceUID, SeriesInstanceUID } = instance;
const SOPInstanceUID = instance.SOPInstanceUID || instance.SopInstanceUID;
@@ -223,13 +226,20 @@ function createDicomLocalApi(dicomLocalConfig) {
SOPInstanceUID
);
let imageId = storedInstance.url;
const baseImageId = storedInstance?.url || instance.url;
if (frame !== undefined) {
imageId += `&frame=${frame}`;
if (!baseImageId) {
return;
}
return imageId;
const numberOfFrames = Number(storedInstance?.NumberOfFrames || instance.NumberOfFrames) || 1;
if (numberOfFrames > 1) {
const frameNumber = frame !== undefined ? frame : 1;
return appendFrameQueryToImageId(baseImageId, frameNumber);
}
return baseImageId;
},
deleteStudyMetadataPromise() {
console.log('deleteStudyMetadataPromise not implemented');
@@ -165,8 +165,11 @@ const DicomTagBrowser = ({
</div>
{shouldShowInstanceList && (
<div className="mx-auto mt-0.5 flex w-1/4 flex-col">
<span className="text-muted-foreground flex h-6 items-center pb-2 text-base">
Instance Number ({instanceNumber} of {activeDisplaySet?.images?.length})
<span className="text-muted-foreground flex h-6 min-w-0 items-center whitespace-nowrap pb-2 text-base">
<span className="truncate">Instance Number</span>
<span className="shrink-0">
&nbsp;({instanceNumber} of {activeDisplaySet?.images?.length})
</span>
</span>
<Slider
value={[instanceNumber]}
@@ -12,11 +12,17 @@ import dcm4cheeReject from './dcm4cheeReject.js';
import getImageId from './utils/getImageId.js';
import dcmjs from 'dcmjs';
import dicomImageLoader from '@cornerstonejs/dicom-image-loader';
import { retrieveStudyMetadata, deleteStudyMetadataPromise } from './retrieveStudyMetadata.js';
import StaticWadoClient from './utils/StaticWadoClient';
import getDirectURL from '../utils/getDirectURL';
import { fixBulkDataURI } from './utils/fixBulkDataURI';
import { HeadersInterface } from '@ohif/core/src/types/RequestHeaders';
import {
getDatasetTransferSyntaxUID,
setNonEnumerableInstanceProperty,
writeDicomDictToPart10Buffer,
} from '../utils/dicomWriter';
import { getGetThumbnailSrc, ThumbnailContext } from './retrieveThumbnail';
import { getRenderedURL } from './retrieveRendered';
@@ -26,7 +32,6 @@ const { naturalizeDataset, denaturalizeDataset } = DicomMetaDictionary;
const ImplementationClassUID = '2.25.270695996825855179949881587723571202391.2.0.0';
const ImplementationVersionName = 'OHIF-3.11.0';
const EXPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2.1';
const metadataProvider = classes.MetadataProvider;
@@ -308,6 +313,86 @@ function createDicomWebApi(dicomWebConfig: DicomWebConfig, servicesManager) {
*/
getWadoDicomWebClient: () => wadoDicomWebClient,
/**
* Best-effort prefetch of a whole multiframe instance as a single Part 10
* object, registered into the Cornerstone3D NATURALIZED frame registry so
* subsequent per-frame image loads are served locally instead of issuing
* one network request per frame (see the "Behaviours" doc
* segmentation-multiframe-part10-prefetch).
*
* Whether to use it at all is the caller's policy (the SEG handler
* resolves the `loadMultiframeAsPart10` config/customization, defaulting
* it on — per-frame loading is the explicit opt-out there).
* Never throws into the caller — on any failure it resolves `done` to
* `false` and the normal per-frame load path is used.
*
* @returns `{ done: Promise<boolean>, cancel: () => void }`.
*/
prefetchInstanceFrames: ({ instance, imageId }) => {
const noop = { done: Promise.resolve(false), cancel: () => {} };
if (!instance || !imageId) {
return noop;
}
const StudyInstanceUID = instance.StudyInstanceUID;
const SeriesInstanceUID = instance.SeriesInstanceUID;
const SOPInstanceUID = instance.SOPInstanceUID || instance.SopInstanceUID;
if (!StudyInstanceUID || !SeriesInstanceUID || !SOPInstanceUID) {
return noop;
}
let cancelled = false;
// Lazy resolver: dicomweb-client.retrieveInstance returns the Part 10
// instance as an ArrayBuffer, unwrapping multipart/related transparently
// (and returning the raw object for single-part responses).
const resolvePart10 = async () => {
wadoDicomWebClient.headers = getAuthorizationHeader();
const result = await wadoDicomWebClient.retrieveInstance({
studyInstanceUID: StudyInstanceUID,
seriesInstanceUID: SeriesInstanceUID,
sopInstanceUID: SOPInstanceUID,
});
if (cancelled) {
throw new Error('prefetchInstanceFrames cancelled');
}
if (result instanceof ArrayBuffer) {
return result;
}
if (Array.isArray(result) && result[0] instanceof ArrayBuffer) {
return result[0];
}
if (result && (result as { buffer?: ArrayBuffer }).buffer instanceof ArrayBuffer) {
return (result as ArrayBufferView).buffer as ArrayBuffer;
}
throw new Error('Unexpected retrieveInstance result for instance prefetch');
};
const done = (async () => {
try {
await dicomImageLoader.prefetchPart10Instance(imageId, resolvePart10);
return !cancelled;
} catch (error) {
console.warn(
'[prefetchInstanceFrames] full-instance prefetch failed; falling back to per-frame loads',
error
);
return false;
}
})();
return {
done,
cancel: () => {
cancelled = true;
},
};
},
bulkDataURI: async ({ StudyInstanceUID, BulkDataURI }) => {
qidoDicomWebClient.headers = getAuthorizationHeader();
const options = {
@@ -372,7 +457,7 @@ function createDicomWebApi(dicomWebConfig: DicomWebConfig, servicesManager) {
FileMetaInformationVersion: dataset._meta?.FileMetaInformationVersion?.Value,
MediaStorageSOPClassUID: dataset.SOPClassUID,
MediaStorageSOPInstanceUID: dataset.SOPInstanceUID,
TransferSyntaxUID: EXPLICIT_VR_LITTLE_ENDIAN,
TransferSyntaxUID: getDatasetTransferSyntaxUID(dataset),
ImplementationClassUID,
ImplementationVersionName,
};
@@ -384,7 +469,7 @@ function createDicomWebApi(dicomWebConfig: DicomWebConfig, servicesManager) {
effectiveDicomDict = defaultDicomDict;
}
const part10Buffer = effectiveDicomDict.write();
const part10Buffer = writeDicomDictToPart10Buffer(effectiveDicomDict);
const options = {
datasets: [part10Buffer],
@@ -445,9 +530,9 @@ function createDicomWebApi(dicomWebConfig: DicomWebConfig, servicesManager) {
instance,
});
instance.imageId = imageId;
instance.wadoRoot = dicomWebConfig.wadoRoot;
instance.wadoUri = dicomWebConfig.wadoUri;
setNonEnumerableInstanceProperty(instance, 'imageId', imageId);
setNonEnumerableInstanceProperty(instance, 'wadoRoot', dicomWebConfig.wadoRoot);
setNonEnumerableInstanceProperty(instance, 'wadoUri', dicomWebConfig.wadoUri);
metadataProvider.addImageIdToUIDs(imageId, {
StudyInstanceUID,
@@ -544,8 +629,8 @@ function createDicomWebApi(dicomWebConfig: DicomWebConfig, servicesManager) {
// Adding instanceMetadata to OHIF MetadataProvider
naturalizedInstances.forEach(instance => {
instance.wadoRoot = dicomWebConfig.wadoRoot;
instance.wadoUri = dicomWebConfig.wadoUri;
setNonEnumerableInstanceProperty(instance, 'wadoRoot', dicomWebConfig.wadoRoot);
setNonEnumerableInstanceProperty(instance, 'wadoUri', dicomWebConfig.wadoUri);
const { StudyInstanceUID, SeriesInstanceUID, SOPInstanceUID } = instance;
const numberOfFrames = instance.NumberOfFrames || 1;
@@ -571,7 +656,7 @@ function createDicomWebApi(dicomWebConfig: DicomWebConfig, servicesManager) {
const imageId = implementation.getImageIdsForInstance({
instance,
});
instance.imageId = imageId;
setNonEnumerableInstanceProperty(instance, 'imageId', imageId);
});
DicomMetadataStore.addInstances(naturalizedInstances, madeInClient);
+49 -9
View File
@@ -1,5 +1,6 @@
import { Types, DicomMetadataStore, utils } from '@ohif/core';
import dcmjs from 'dcmjs';
import { datasetToDicomBlob, setNonEnumerableInstanceProperty } from './utils/dicomWriter';
import { registerNaturalizedDatasetsForLocalWadouri } from './utils/registerNaturalizedDatasetForLocalWadouri';
const { downloadBlob } = utils;
@@ -784,11 +785,12 @@ const commandsModule = ({
if (dataSource === 'download') {
return async dicom => {
const instances = Array.isArray(dicom) ? dicom : [dicom];
registerNaturalizedDatasetsForLocalWadouri(instances);
DicomMetadataStore.addInstances(instances, true);
if (instances.length !== 1) {
throw new Error('Download only supports a single DICOM instance');
}
const reportBlob = dcmjs.data.datasetToBlob(instances[0]);
const reportBlob = datasetToDicomBlob(instances[0]);
downloadBlob(reportBlob, { filename: defaultFileName || 'dicom.dcm' });
};
}
@@ -796,14 +798,15 @@ const commandsModule = ({
if (dataSource === 'copyToClipboard') {
return async dicom => {
const instances = Array.isArray(dicom) ? dicom : [dicom];
registerNaturalizedDatasetsForLocalWadouri(instances);
DicomMetadataStore.addInstances(instances, true);
if (instances.length !== 1) {
throw new Error('Copy to clipboard only supports a single DICOM instance');
}
const reportBlob = dcmjs.data.datasetToBlob(instances[0]);
const reportBlob = datasetToDicomBlob(instances[0]);
const type = defaultContentType || 'application/dicom';
await navigator.clipboard.write([
new ClipboardItem({ [type]: new Blob([reportBlob], { type }) }),
new ClipboardItem({ [type]: reportBlob }),
]);
};
}
@@ -817,12 +820,18 @@ const commandsModule = ({
return async (dicom, { dicomDict } = {}) => {
const instances = Array.isArray(dicom) ? dicom : [dicom];
const config = resolvedDataSource.getConfig?.();
if (config?.wadoRoot) {
instances.forEach(instance => {
instance.wadoRoot = config.wadoRoot;
});
// Always keep an in-memory wadouri copy so DICOM can be read without re-fetching.
registerNaturalizedDatasetsForLocalWadouri(instances);
if (dataSource !== 'dicomlocal') {
const config = resolvedDataSource.getConfig?.();
if (config?.wadoRoot) {
instances.forEach(instance => {
setNonEnumerableInstanceProperty(instance, 'wadoRoot', config.wadoRoot);
});
}
}
DicomMetadataStore.addInstances(instances, true);
for (const instance of instances) {
await resolvedDataSource.store.dicom(instance, null, dicomDict);
@@ -833,6 +842,33 @@ const commandsModule = ({
}
};
},
/**
* Launches a workflow (mode) for a study from the worklist. This is the
* default `workList.onStudyDoubleClick` command.
*
* @param study - the StudyRow the action applies to
* @param workflows - the workflows applicable to the study, in menu order;
* each has `id`, `displayName`, `isDefault` and `launchWithStudy(study)`
* @param defaultWorkflow - the user's default workflow when it applies to
* the study
* @param workflowId - command option to force a specific workflow (mode id)
* instead of the default/first applicable one
*/
launchDefaultMode: ({ study, workflows = [], defaultWorkflow, workflowId }) => {
const workflow = workflowId
? workflows.find(w => w.id === workflowId)
: (defaultWorkflow ?? workflows[0]);
if (!workflow) {
console.warn(
workflowId
? `launchDefaultMode: workflow '${workflowId}' is not applicable to the study`
: 'launchDefaultMode: no workflow is applicable to the study'
);
return;
}
workflow.launchWithStudy(study);
},
};
const definitions = {
@@ -862,6 +898,10 @@ const commandsModule = ({
addDisplaySetAsLayer: actions.addDisplaySetAsLayer,
removeDisplaySetLayer: actions.removeDisplaySetLayer,
createStoreFunction: actions.createStoreFunction,
launchDefaultMode: {
commandFn: actions.launchDefaultMode,
context: 'WORKLIST',
},
};
return {
@@ -10,6 +10,18 @@ type DataSource = {
placeHolder: string;
};
/** Radix Select item value for "Create new series" (state remains null). */
const NEW_SERIES_SELECT_VALUE = '__new_series_id__';
type SeriesOption = {
optionKey: string;
selectValue: string;
value: string | null;
seriesNumber: number;
description: string | null;
label: string;
};
type ReportDialogProps = {
dataSources: DataSource[];
modality?: string;
@@ -46,20 +58,32 @@ function ReportDialog({
const [selectedSeries, setSelectedSeries] = useState<string | null>(predecessorImageId || null);
const [reportName, setReportName] = useState('');
const seriesOptions = useMemo(() => {
const seriesOptions = useMemo((): SeriesOption[] => {
const displaySetsMap = displaySetService.getDisplaySetCache();
const displaySets = Array.from(displaySetsMap.values());
const options = displaySets
.filter(ds => ds.Modality === modality)
.map(ds => ({
value: ds.predecessorImageId || ds.SeriesInstanceUID,
seriesNumber: isFinite(ds.SeriesNumber) ? ds.SeriesNumber : minSeriesNumber,
description: ds.SeriesDescription,
label: `${ds.SeriesDescription} ${ds.SeriesDate}/${ds.SeriesTime} ${ds.SeriesNumber}`,
}));
.map(ds => {
const value = ds.predecessorImageId || ds.SeriesInstanceUID;
const selectValue = value || ds.displaySetInstanceUID;
return {
optionKey: `series-${ds.displaySetInstanceUID}`,
selectValue,
value: value || null,
seriesNumber: isFinite(ds.SeriesNumber) ? ds.SeriesNumber : minSeriesNumber,
description: ds.SeriesDescription,
label: `${ds.SeriesDescription} ${ds.SeriesDate}/${ds.SeriesTime} ${ds.SeriesNumber}`,
};
})
.filter(
option =>
option.selectValue && option.selectValue !== NEW_SERIES_SELECT_VALUE
);
return [
{
optionKey: NEW_SERIES_SELECT_VALUE,
selectValue: NEW_SERIES_SELECT_VALUE,
value: null,
description: null,
seriesNumber: minSeriesNumber,
@@ -67,7 +91,17 @@ function ReportDialog({
},
...options,
];
}, [displaySetService, modality]);
}, [displaySetService, modality, minSeriesNumber]);
const handleSeriesChange = useCallback(
(selectValue: string) => {
const option = seriesOptions.find(o => o.selectValue === selectValue);
setSelectedSeries(
selectValue === NEW_SERIES_SELECT_VALUE ? null : (option?.value ?? selectValue)
);
},
[seriesOptions]
);
useEffect(() => {
const seriesOption = seriesOptions.find(s => s.value === selectedSeries);
@@ -115,6 +149,11 @@ function ReportDialog({
const showDataSourceSelect = dataSources?.length > 1;
const showDownloadButton = enableDownload;
const selectedSeriesSelectValue =
selectedSeries == null
? NEW_SERIES_SELECT_VALUE
: (seriesOptions.find(o => o.value === selectedSeries)?.selectValue ??
selectedSeries);
return (
<div className="text-foreground flex min-w-[400px] max-w-md flex-col">
@@ -146,8 +185,8 @@ function ReportDialog({
<div className={showDataSourceSelect ? 'mt-1 w-1/2' : 'mt-1 w-full'}>
<div className="mb-1 pl-1 text-base">Series</div>
<Select
value={selectedSeries}
onValueChange={setSelectedSeries}
value={selectedSeriesSelectValue}
onValueChange={handleSeriesChange}
>
<SelectTrigger>
<SelectValue placeholder="Select a series" />
@@ -155,8 +194,8 @@ function ReportDialog({
<SelectContent>
{seriesOptions.map(series => (
<SelectItem
key={series.value}
value={series.value}
key={series.optionKey}
value={series.selectValue}
>
{series.label}
</SelectItem>
@@ -172,8 +211,8 @@ function ReportDialog({
<div className="w-1/3">
<div className="mb-1 pl-1 text-base">Series</div>
<Select
value={selectedSeries}
onValueChange={setSelectedSeries}
value={selectedSeriesSelectValue}
onValueChange={handleSeriesChange}
>
<SelectTrigger>
<SelectValue placeholder="Select a series" />
@@ -181,8 +220,8 @@ function ReportDialog({
<SelectContent>
{seriesOptions.map(series => (
<SelectItem
key={series.value}
value={series.value}
key={series.optionKey}
value={series.selectValue}
>
{series.label}
</SelectItem>
@@ -67,6 +67,29 @@ import { StudyList } from '@ohif/ui-next';
* `<StudyList.PreviewContainer>` layout is used.
* Currently only applies when `workList.variant` is `'default'`.
*
* - `workList.onStudyDoubleClick`: command run input (default:
* `{ commandName: 'launchDefaultMode' }`)
* The command(s) run when a study row is double-clicked (the row is selected
* first). Accepts anything `commandsManager.run` does: a command name string,
* `{ commandName, commandOptions, context }`, an array of those, or a plain
* function. At call time these are merged into the command options (a plain
* function receives them as its single argument):
* - `study`: the double-clicked `StudyRow`.
* - `workflows`: the workflows applicable to the study, in the same order as
* the row's Launch Workflow menu. Each has `id`, `displayName`,
* `isDefault`, and `launchWithStudy(study)`.
* - `defaultWorkflow`: the user's default workflow when it applies to the
* study, else `undefined`.
* The default `launchDefaultMode` command launches `defaultWorkflow`,
* falling back to the first applicable workflow. Override the options to
* always launch a specific mode:
* `{ commandName: 'launchDefaultMode', commandOptions: { workflowId: 'segmentation' } }`.
* Modes can contribute their own commands for this via a `getCommandsModule`
* export on the mode definition, registered at app init in the 'WORKLIST'
* context — before any mode route is entered. When set to a falsy value the
* built-in StudyList.Table double-click behavior applies.
* Currently only applies when `workList.variant` is `'default'`.
*
* - `workList.settingsMenuItems`: `(defaults) => SettingsMenuItem[]` (default: identity)
* Builds the items in the WorkList settings popover. Receives the default
* items (`about`, `userPreferences`, and `logout` when OIDC is configured)
@@ -82,6 +105,7 @@ export default function getWorkListCustomization() {
'workList.previewSeriesView': 'all',
'workList.columns': StudyList.defaultColumns,
'workList.renderPreviewContent': undefined,
'workList.onStudyDoubleClick': { commandName: 'launchDefaultMode' },
'workList.settingsMenuItems': (defaults: unknown) => defaults,
};
}
@@ -14,14 +14,13 @@ const DYNAMIC_VOLUME_LOADER_SCHEME = 'cornerstoneStreamingDynamicImageVolume';
const sopClassHandlerName = 'stack';
let appContext = {};
const getDynamicVolumeInfo = instances => {
const getDynamicVolumeInfo = imageIds => {
const { extensionManager } = appContext;
if (!extensionManager) {
throw new Error('extensionManager is not available');
}
const imageIds = instances.map(({ imageId }) => imageId);
const volumeLoaderUtility = extensionManager.getModuleEntry(
'@ohif/extension-cornerstone.utilityModule.volumeLoader'
);
@@ -34,8 +33,8 @@ const isMultiFrame = instance => {
return instance.NumberOfFrames > 1;
};
function getDisplaySetInfo(instances) {
const dynamicVolumeInfo = getDynamicVolumeInfo(instances);
function getDisplaySetInfo(instances, imageIds) {
const dynamicVolumeInfo = getDynamicVolumeInfo(imageIds);
const { isDynamicVolume, timePoints } = dynamicVolumeInfo;
let displaySetInfo;
@@ -82,12 +81,13 @@ const makeDisplaySet = (instances, index) => {
const imageSet = new ImageSet(instances);
const { extensionManager } = appContext;
const dataSource = extensionManager.getActiveDataSource()[0];
const imageIds = dataSource.getImageIdsForDisplaySet(imageSet);
const {
isDynamicVolume,
value: isReconstructable,
averageSpacingBetweenFrames,
dynamicVolumeInfo,
} = getDisplaySetInfo(instances);
} = getDisplaySetInfo(instances, imageIds);
const volumeLoaderSchema = isDynamicVolume
? DYNAMIC_VOLUME_LOADER_SCHEME
@@ -124,7 +124,6 @@ const makeDisplaySet = (instances, index) => {
FrameOfReferenceUID: instance.FrameOfReferenceUID,
});
const imageIds = dataSource.getImageIdsForDisplaySet(imageSet);
let imageId = imageIds[Math.floor(imageIds.length / 2)];
let thumbnailInstance = instances[Math.floor(instances.length / 2)];
if (isDynamicVolume) {
@@ -0,0 +1,74 @@
jest.mock('./getDisplaySetMessages', () => jest.fn(() => ({ addMessage: jest.fn() })));
jest.mock('./getDisplaySetsFromUnsupportedSeries', () => jest.fn());
import getSopClassHandlerModule from './getSopClassHandlerModule';
const makeInstance = () => ({
imageId: 'dicomfile:blob://local-multiframe',
url: 'dicomfile:blob://local-multiframe',
NumberOfFrames: 4,
Rows: 2,
Columns: 2,
PixelSpacing: [1, 1],
SliceThickness: 1,
ImageOrientationPatient: [1, 0, 0, 0, 1, 0],
ImagePositionPatient: [0, 0, 0],
FrameOfReferenceUID: 'frame-of-reference',
StudyInstanceUID: 'study',
SeriesInstanceUID: 'series',
SOPInstanceUID: 'sop',
SOPClassUID: '1.2.840.10008.5.1.4.1.1.2.1',
Modality: 'CT',
SeriesDescription: 'Local multiframe CT',
SeriesNumber: 1,
});
describe('getSopClassHandlerModule', () => {
it('checks dynamic volume grouping with generated multiframe imageIds', () => {
const frameImageIds = [
'dicomfile:blob://local-multiframe&frame=1',
'dicomfile:blob://local-multiframe&frame=2',
'dicomfile:blob://local-multiframe&frame=3',
'dicomfile:blob://local-multiframe&frame=4',
];
const getDynamicVolumeInfo = jest.fn(() => ({
isDynamicVolume: false,
timePoints: [frameImageIds],
splittingTag: null,
}));
const dataSource = {
getImageIdsForDisplaySet: jest.fn(() => frameImageIds),
retrieve: {
getGetThumbnailSrc: jest.fn(),
},
};
const customizationService = {
getCustomization: jest.fn(() => ({
sortFunctions: {},
defaultSortFunctionName: 'default',
})),
};
const appContext = {
appConfig: {},
extensionManager: {
getActiveDataSource: jest.fn(() => [dataSource]),
getModuleEntry: jest.fn(() => ({
exports: {
getDynamicVolumeInfo,
},
})),
},
servicesManager: {
services: {
customizationService,
},
},
};
const stackHandler = getSopClassHandlerModule(appContext)[0];
stackHandler.getDisplaySetsFromSeries([makeInstance()]);
expect(getDynamicVolumeInfo).toHaveBeenCalledWith(frameImageIds);
});
});
+4
View File
@@ -27,6 +27,7 @@ import { useHangingProtocolStageIndexStore } from './stores/useHangingProtocolSt
import { useToggleHangingProtocolStore } from './stores/useToggleHangingProtocolStore';
import { useToggleOneUpViewportGridStore } from './stores/useToggleOneUpViewportGridStore';
import { callInputDialogAutoComplete, callInputDialog } from './utils/callInputDialog';
import { releaseLocalWadouriRegistrations } from './utils/registerNaturalizedDatasetForLocalWadouri';
import colorPickerDialog from './utils/colorPickerDialog';
import promptSaveReport from './utils/promptSaveReport';
@@ -52,6 +53,9 @@ const defaultExtension: Types.Extensions.Extension = {
useHangingProtocolStageIndexStore.getState().clearHangingProtocolStageIndexMap();
useToggleHangingProtocolStore.getState().clearToggleHangingProtocol();
useViewportsByPositionStore.getState().clearViewportsByPosition();
// Free the Part 10 Blobs (and any parsed copies) retained for locally
// generated instances (SEG etc.) registered with the wadouri loader.
releaseLocalWadouriRegistrations();
},
getDataSourcesModule,
getViewportModule,
@@ -0,0 +1,9 @@
/**
* Appends ?frame= or &frame= to a local/wadouri imageId.
*/
export function appendFrameQueryToImageId(baseImageId, frame) {
const withoutFrame = baseImageId.split('&frame=')[0].split('?frame=')[0];
const separator = withoutFrame.includes('?') ? '&' : '?';
return `${withoutFrame}${separator}frame=${frame}`;
}
@@ -0,0 +1,228 @@
import { TextEncoder, TextDecoder } from 'util';
import dcmjs from 'dcmjs';
import {
DICOM_WRITE_OPTIONS,
datasetToDicomPart10Buffer,
writeDicomDictToPart10Buffer,
} from './dicomWriter';
// jsdom does not expose TextEncoder/TextDecoder, which dcmjs's buffer streams need.
if (typeof (global as { TextEncoder?: unknown }).TextEncoder === 'undefined') {
(global as { TextEncoder?: unknown }).TextEncoder = TextEncoder;
}
if (typeof (global as { TextDecoder?: unknown }).TextDecoder === 'undefined') {
(global as { TextDecoder?: unknown }).TextDecoder = TextDecoder;
}
const RLE_LOSSLESS = '1.2.840.10008.1.2.5';
const EXPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2.1';
const IMPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2';
const PIXEL_DATA_TAG = '7FE00010';
// Use frames larger than dcmjs's 20KB fragment size so that, if a frame were
// ever split, we'd see more than one fragment per frame.
const FRAME_BYTES = 30000;
function makeDicomDict(transferSyntaxUID, vr, pixelDataValue) {
const dict = new dcmjs.data.DicomDict({
'00020010': { vr: 'UI', Value: [transferSyntaxUID] },
'00020002': { vr: 'UI', Value: ['1.2.840.10008.5.1.4.1.1.66.4'] },
'00020003': { vr: 'UI', Value: ['1.2.3.4.5'] },
});
dict.upsertTag(PIXEL_DATA_TAG, vr, pixelDataValue);
return dict;
}
/**
* Locates the PixelData element in a Part-10 buffer and, when it is encapsulated,
* walks the encapsulated items (Basic Offset Table + fragments).
*/
function inspectPixelData(arrayBuffer) {
const dv = new DataView(arrayBuffer);
// Skip the 128-byte preamble + "DICM", then read the file-meta group length
// from (0002,0000) UL to find where the dataset begins.
const metaGroupLength = dv.getUint32(140, true);
let offset = 144 + metaGroupLength;
// PixelData (7FE0,0010), explicit VR (OB/OW) — long form: VR(2) + reserved(2) + length(4).
const group = dv.getUint16(offset, true);
const element = dv.getUint16(offset + 2, true);
if (group !== 0x7fe0 || element !== 0x0010) {
throw new Error(
`Expected PixelData at offset ${offset}, found ${group.toString(16)},${element.toString(16)}`
);
}
const length = dv.getUint32(offset + 8, true);
if (length !== 0xffffffff) {
return { encapsulated: false, length };
}
// Encapsulated: first item is the Basic Offset Table, then one item per fragment,
// terminated by the Sequence Delimitation Item (FFFE,E0DD).
let p = offset + 12;
const itemSizes: number[] = [];
while (p + 8 <= dv.byteLength) {
const itemGroup = dv.getUint16(p, true);
const itemElement = dv.getUint16(p + 2, true);
const itemLength = dv.getUint32(p + 4, true);
p += 8;
if (itemGroup === 0xfffe && itemElement === 0xe0dd) {
break; // sequence delimiter
}
if (itemGroup !== 0xfffe || itemElement !== 0xe000) {
throw new Error(`Unexpected item tag at ${p - 8}`);
}
itemSizes.push(itemLength);
p += itemLength;
}
// itemSizes[0] is the Basic Offset Table; the rest are frame fragments.
return {
encapsulated: true,
totalItems: itemSizes.length,
basicOffsetTableSize: itemSizes[0],
fragmentSizes: itemSizes.slice(1),
};
}
describe('dicomWriter DICOM_WRITE_OPTIONS fragmentation', () => {
it('writes exactly one fragment per frame (plus the Basic Offset Table) for compressed pixel data', () => {
const frames = [new Uint8Array(FRAME_BYTES).buffer, new Uint8Array(FRAME_BYTES).buffer];
const dict = makeDicomDict(RLE_LOSSLESS, 'OB', frames);
const buffer = writeDicomDictToPart10Buffer(dict);
const result = inspectPixelData(buffer);
expect(result.encapsulated).toBe(true);
// 1 Basic Offset Table item + 1 fragment per frame.
expect(result.totalItems).toBe(frames.length + 1);
expect(result.fragmentSizes).toHaveLength(frames.length);
// Each frame stayed in a single fragment despite exceeding the 20KB fragment size.
result.fragmentSizes.forEach(size => expect(size).toBe(FRAME_BYTES));
});
it('does not fragment uncompressed pixel data', () => {
const pixelData = new Uint16Array(FRAME_BYTES).buffer;
const dict = makeDicomDict(EXPLICIT_VR_LITTLE_ENDIAN, 'OW', [pixelData]);
const buffer = writeDicomDictToPart10Buffer(dict);
const result = inspectPixelData(buffer);
expect(result.encapsulated).toBe(false);
expect(result.length).toBe(pixelData.byteLength);
});
it('confirms fragmentMultiframe:false is what prevents a single large frame from splitting', () => {
// Control: with fragmentMultiframe enabled, a >20KB frame splits into multiple
// fragments — proving DICOM_WRITE_OPTIONS.fragmentMultiframe:false is meaningful.
const frames = [new Uint8Array(FRAME_BYTES).buffer];
const dict = makeDicomDict(RLE_LOSSLESS, 'OB', frames);
const buffer = dict.write({ ...DICOM_WRITE_OPTIONS, fragmentMultiframe: true });
const result = inspectPixelData(buffer);
expect(result.encapsulated).toBe(true);
expect(result.fragmentSizes.length).toBeGreaterThan(1);
});
});
/**
* Byte-level walk of the file meta group. Returns the meta element tags in file
* order and asserts that FileMetaInformationGroupLength spans them exactly.
*/
function readFileMetaTags(arrayBuffer: ArrayBuffer) {
const dv = new DataView(arrayBuffer);
// Preamble(128) + 'DICM'(4), then (0002,0000) UL <groupLength> must come first.
expect(dv.getUint16(132, true)).toBe(0x0002);
expect(dv.getUint16(134, true)).toBe(0x0000);
const groupLength = dv.getUint32(140, true);
const end = 144 + groupLength;
const tags: string[] = [];
let p = 144;
while (p < end) {
const group = dv.getUint16(p, true);
const element = dv.getUint16(p + 2, true);
const vr = String.fromCharCode(dv.getUint8(p + 4), dv.getUint8(p + 5));
// File meta is always Explicit VR Little Endian.
let length: number;
if (['OB', 'OW', 'OF', 'SQ', 'UT', 'UN'].includes(vr)) {
length = dv.getUint32(p + 8, true);
p += 12 + length;
} else {
length = dv.getUint16(p + 6, true);
p += 8 + length;
}
tags.push(
`${group.toString(16).padStart(4, '0')}${element.toString(16).padStart(4, '0')}`
);
}
// The declared group length covers the meta elements exactly — a garbage
// element counted into it (or omitted from it) would break this.
expect(p).toBe(end);
return tags;
}
function makeNaturalizedDataset(meta) {
return {
_meta: meta,
SOPClassUID: '1.2.840.10008.5.1.4.1.1.88.33',
SOPInstanceUID: '1.2.3.4.5',
StudyInstanceUID: '1.2.3.4',
SeriesInstanceUID: '1.2.3.4.1',
Modality: 'SR',
PatientID: 'TEST-PATIENT',
};
}
describe('datasetToDicomPart10Buffer file meta', () => {
it('writes only group-0002 elements (no garbage (0000,0000) tag) into the file meta', () => {
const dataset = makeNaturalizedDataset({
TransferSyntaxUID: { vr: 'UI', Value: [EXPLICIT_VR_LITTLE_ENDIAN] },
});
const buffer = datasetToDicomPart10Buffer(dataset);
const tags = readFileMetaTags(buffer);
expect(tags.length).toBeGreaterThan(0);
tags.forEach(tag => expect(tag.startsWith('0002')).toBe(true));
// Elements must appear in ascending tag order within group 2.
expect(tags).toEqual([...tags].sort());
const reread = dcmjs.data.DicomMessage.readFile(buffer);
const metaKeys = Object.keys(reread.meta);
expect(metaKeys).not.toContain('00000000');
metaKeys.forEach(key => expect(key.startsWith('0002')).toBe(true));
expect(reread.meta['00020010'].Value).toEqual([EXPLICIT_VR_LITTLE_ENDIAN]);
});
it('honors a plain-string _meta.TransferSyntaxUID that dcmjs alone would default away', () => {
// dcmjs datasetToDict only reads the object form (_meta.TransferSyntaxUID.Value[0])
// and silently falls back to Explicit VR LE for a plain string — the hex-key
// assignment in applyTransferSyntaxToFileMeta is what preserves it.
const dataset = makeNaturalizedDataset({
TransferSyntaxUID: IMPLICIT_VR_LITTLE_ENDIAN,
});
const buffer = datasetToDicomPart10Buffer(dataset);
const tags = readFileMetaTags(buffer);
tags.forEach(tag => expect(tag.startsWith('0002')).toBe(true));
const reread = dcmjs.data.DicomMessage.readFile(buffer);
expect(Object.keys(reread.meta)).not.toContain('00000000');
expect(reread.meta['00020010'].Value).toEqual([IMPLICIT_VR_LITTLE_ENDIAN]);
// The dataset body survives a round trip under the preserved syntax.
expect(reread.dict['00080018'].Value).toEqual(['1.2.3.4.5']);
});
});
+110
View File
@@ -0,0 +1,110 @@
import dcmjs from 'dcmjs';
export const EXPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2.1';
export const DICOM_WRITE_OPTIONS = {
allowInvalidVRLength: false,
// `fragmentMultiframe` only governs whether a SINGLE frame is split across
// multiple fragments (dcmjs splits frames larger than its 20KB fragment size).
// It does NOT merge frames: in an encapsulated (compressed) transfer syntax
// every frame is always written as its own fragment, preceded by the Basic
// Offset Table; in an uncompressed syntax pixel data is never fragmented at
// all. Keeping this `false` therefore yields exactly one fragment per frame
// for compressed SEG — the conformant layout — without splitting large frames.
fragmentMultiframe: false,
};
/** OHIF runtime fields — not DICOM tags; must not be enumerable for dcmjs datasetToDict. */
export const RUNTIME_INSTANCE_PROPERTY_KEYS = [
'url',
'wadorsuri',
'wadouri',
'wadoRoot',
'wadoUri',
'wadoUriRoot',
'imageRendering',
'imageId',
'_parentInstance',
'frameNumber',
] as const;
/**
* Attaches OHIF runtime data on an instance without enumerable keys (safe for dcmjs datasetToDict).
*/
export function setNonEnumerableInstanceProperty(
instance: Record<string, unknown>,
key: string,
value: unknown
) {
Object.defineProperty(instance, key, {
value,
enumerable: false,
writable: true,
configurable: true,
});
}
/**
* Re-defines any existing enumerable runtime properties as non-enumerable (keeps values).
*/
export function makeExistingPropertiesNonEnumerable(instance: Record<string, unknown>) {
for (const key of RUNTIME_INSTANCE_PROPERTY_KEYS) {
if (!Object.prototype.hasOwnProperty.call(instance, key)) {
continue;
}
const descriptor = Object.getOwnPropertyDescriptor(instance, key);
if (!descriptor || descriptor.enumerable === false) {
continue;
}
setNonEnumerableInstanceProperty(instance, key, descriptor.value);
}
}
export function getDatasetTransferSyntaxUID(dataset) {
const fromMeta = dataset?._meta?.TransferSyntaxUID;
if (typeof fromMeta === 'string') {
return fromMeta;
}
if (Array.isArray(fromMeta?.Value)) {
return fromMeta.Value[0];
}
if (typeof dataset?.TransferSyntaxUID === 'string') {
return dataset.TransferSyntaxUID;
}
return EXPLICIT_VR_LITTLE_ENDIAN;
}
function applyTransferSyntaxToFileMeta(dicomDict, transferSyntaxUID) {
if (!transferSyntaxUID || !dicomDict?.meta) {
return;
}
// Hex key only: DicomMessage.write treats every meta key as a tag string, so a
// naturalized key like 'TransferSyntaxUID' would be parsed via parseInt(..., 16)
// into tag (0000,0000) and written as a garbage element in group 2.
dicomDict.meta['00020010'] = { vr: 'UI', Value: [transferSyntaxUID] };
}
export function datasetToDicomPart10Buffer(dataset) {
makeExistingPropertiesNonEnumerable(dataset);
const transferSyntaxUID = getDatasetTransferSyntaxUID(dataset);
const dicomDict = dcmjs.data.datasetToDict(dataset);
applyTransferSyntaxToFileMeta(dicomDict, transferSyntaxUID);
return dicomDict.write(DICOM_WRITE_OPTIONS);
}
export function datasetToDicomBlob(dataset) {
const part10Buffer = datasetToDicomPart10Buffer(dataset);
return new Blob([part10Buffer], { type: 'application/dicom' });
}
export function writeDicomDictToPart10Buffer(dicomDict) {
return dicomDict.write(DICOM_WRITE_OPTIONS);
}
@@ -0,0 +1,146 @@
import dicomImageLoader from '@cornerstonejs/dicom-image-loader';
import OHIF from '@ohif/core';
import {
datasetToDicomBlob,
makeExistingPropertiesNonEnumerable,
setNonEnumerableInstanceProperty,
} from './dicomWriter';
import { appendFrameQueryToImageId } from './appendFrameQueryToImageId';
const metadataProvider = OHIF.classes.MetadataProvider;
const SEG_REGISTER_LOG_PREFIX = '[SEG register]';
// Every registration pins a full Part 10 Blob in the fileManager (and, once
// loaded, a parsed copy in the dataSetCacheManager) with no other owner, so
// track the imageIds and release them on mode exit.
const registeredImageIds = new Set();
/**
* Releases everything previously registered via
* {@link registerNaturalizedDatasetForLocalWadouri}: the Part 10 Blob held by the
* wadouri fileManager and any parsed dataset the dataSetCacheManager retained.
* Call on mode exit.
*/
export function releaseLocalWadouriRegistrations() {
const { fileManager, dataSetCacheManager } = dicomImageLoader.wadouri;
for (const imageId of registeredImageIds) {
// 'dicomfile:<index>' — the index doubles as the fileManager slot and the
// dataSetCacheManager uri (the scheme is stripped for cache keys).
const uri = imageId.substring(imageId.indexOf(':') + 1);
const fileIndex = Number(uri);
if (Number.isInteger(fileIndex) && fileIndex >= 0) {
fileManager.remove(fileIndex);
}
// unload() decrements a refcount shared with cornerstone's image decache;
// nothing may outlive mode exit, so drive it to zero.
for (let guard = 0; guard < 100000 && dataSetCacheManager.isLoaded(uri); guard++) {
dataSetCacheManager.unload(uri);
}
}
registeredImageIds.clear();
}
/**
* Registers a naturalized DICOM dataset with the wadouri file manager so it can be
* loaded like other locally stored instances (blob URL), instead of remote wadors URLs.
*
* Datasets without pixel data (SR, RTSTRUCT, ...) are skipped: they have no frames
* to serve through the image loader, so registering them would only pin their
* Part 10 Blob in memory for the rest of the session.
*
* @param {object} dataset - Naturalized DICOM instance (e.g. generated SEG).
* @param {object} [options]
* @param {string[]} [options.referencedImageIds] - Used for logging / frame count hints.
* @returns {string|undefined} wadouri imageId assigned to dataset.url, or undefined when skipped
*/
export function registerNaturalizedDatasetForLocalWadouri(dataset, options = {}) {
const { referencedImageIds = [] } = options;
if (
dataset.PixelData === undefined &&
!Array.isArray(dataset.PerFrameFunctionalGroupsSequence)
) {
OHIF.log.debug(
SEG_REGISTER_LOG_PREFIX,
'Skipping local wadouri registration (no pixel data)',
{ SOPClassUID: dataset.SOPClassUID, SOPInstanceUID: dataset.SOPInstanceUID }
);
return undefined;
}
const blob = datasetToDicomBlob(dataset);
const imageId = dicomImageLoader.wadouri.fileManager.add(blob);
registeredImageIds.add(imageId);
setNonEnumerableInstanceProperty(dataset, 'url', imageId);
const { StudyInstanceUID, SeriesInstanceUID } = dataset;
const SOPInstanceUID = dataset.SOPInstanceUID || dataset.SopInstanceUID;
const perFrameGroups = dataset.PerFrameFunctionalGroupsSequence;
if (Array.isArray(perFrameGroups) && !dataset.NumberOfFrames) {
dataset.NumberOfFrames = perFrameGroups.length;
}
// Local only — never written back to the dataset: single-frame IODs (SR,
// RTSTRUCT) must not gain a NumberOfFrames element in their serialized form.
const numberOfFrames = Math.max(
Number(dataset.NumberOfFrames) || 0,
Array.isArray(perFrameGroups) ? perFrameGroups.length : 0,
1
);
const frameImageIds = [];
if (StudyInstanceUID && SeriesInstanceUID && SOPInstanceUID) {
const registerMapping = (id, frameNumber = 1) => {
metadataProvider.addImageIdToUIDs(id, {
StudyInstanceUID,
SeriesInstanceUID,
SOPInstanceUID,
frameNumber,
});
};
for (let frame = 1; frame <= numberOfFrames; frame++) {
const frameImageId =
numberOfFrames > 1 ? appendFrameQueryToImageId(imageId, frame) : imageId;
frameImageIds.push(frameImageId);
registerMapping(frameImageId, frame);
}
}
makeExistingPropertiesNonEnumerable(dataset);
OHIF.log.debug(SEG_REGISTER_LOG_PREFIX, 'Registered local wadouri instance', {
StudyInstanceUID,
SeriesInstanceUID,
SOPInstanceUID,
numberOfFrames,
baseImageId: imageId,
frameImageIds,
blobSizeBytes: blob.size,
referencedImageIdCount: referencedImageIds.length,
SegmentationType: dataset.SegmentationType,
SOPClassUID: dataset.SOPClassUID,
});
return imageId;
}
export function registerNaturalizedDatasetsForLocalWadouri(instances, options = {}) {
const list = Array.isArray(instances) ? instances : [instances];
const { referencedImageIds = [] } = options;
list.forEach(instance =>
registerNaturalizedDatasetForLocalWadouri(instance, { referencedImageIds })
);
return list;
}
@@ -0,0 +1,177 @@
import { TextEncoder, TextDecoder } from 'util';
import dicomImageLoader from '@cornerstonejs/dicom-image-loader';
import OHIF from '@ohif/core';
import {
registerNaturalizedDatasetForLocalWadouri,
releaseLocalWadouriRegistrations,
} from './registerNaturalizedDatasetForLocalWadouri';
// jsdom does not expose TextEncoder/TextDecoder, which dcmjs's buffer streams need.
if (typeof global.TextEncoder === 'undefined') {
global.TextEncoder = TextEncoder;
}
if (typeof global.TextDecoder === 'undefined') {
global.TextDecoder = TextDecoder;
}
jest.mock('@cornerstonejs/dicom-image-loader', () => ({
__esModule: true,
default: {
wadouri: {
fileManager: {
add: jest.fn(() => 'dicomfile:0'),
remove: jest.fn(),
},
dataSetCacheManager: {
isLoaded: jest.fn(() => false),
unload: jest.fn(),
},
},
},
}));
jest.mock('@ohif/core', () => ({
__esModule: true,
default: {
classes: {
MetadataProvider: {
addImageIdToUIDs: jest.fn(),
},
},
log: {
debug: jest.fn(),
},
},
}));
const EXPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2.1';
const addBlob = dicomImageLoader.wadouri.fileManager.add;
const addImageIdToUIDs = OHIF.classes.MetadataProvider.addImageIdToUIDs;
function makeDataset(extra = {}) {
return {
_meta: { TransferSyntaxUID: { vr: 'UI', Value: [EXPLICIT_VR_LITTLE_ENDIAN] } },
SOPInstanceUID: '1.2.3.4.5',
StudyInstanceUID: '1.2.3.4',
SeriesInstanceUID: '1.2.3.4.1',
PatientID: 'TEST-PATIENT',
...extra,
};
}
describe('registerNaturalizedDatasetForLocalWadouri', () => {
beforeEach(() => {
jest.clearAllMocks();
});
afterEach(() => {
// Drain the module-level registration tracking between tests.
releaseLocalWadouriRegistrations();
});
it('skips datasets without pixel data (SR/RTSTRUCT) and does not mutate them', () => {
const dataset = makeDataset({
SOPClassUID: '1.2.840.10008.5.1.4.1.1.88.33',
Modality: 'SR',
});
const imageId = registerNaturalizedDatasetForLocalWadouri(dataset);
// No frames to serve through the image loader: nothing registered, no Blob pinned.
expect(imageId).toBeUndefined();
expect(addBlob).not.toHaveBeenCalled();
expect(addImageIdToUIDs).not.toHaveBeenCalled();
// The serialized form of an SR must not gain a (0028,0008) element or a url.
expect(Object.prototype.hasOwnProperty.call(dataset, 'NumberOfFrames')).toBe(false);
expect(Object.prototype.hasOwnProperty.call(dataset, 'url')).toBe(false);
});
it('registers a single-frame pixel-bearing dataset without stamping NumberOfFrames', () => {
const dataset = makeDataset({
SOPClassUID: '1.2.840.10008.5.1.4.1.1.7',
Modality: 'OT',
PixelData: new Uint8Array(4).buffer,
});
const imageId = registerNaturalizedDatasetForLocalWadouri(dataset);
expect(Object.prototype.hasOwnProperty.call(dataset, 'NumberOfFrames')).toBe(false);
expect(imageId).toBe('dicomfile:0');
expect(addBlob).toHaveBeenCalledTimes(1);
// Single frame: the bare imageId is mapped, no ?frame= query.
expect(addImageIdToUIDs).toHaveBeenCalledTimes(1);
expect(addImageIdToUIDs).toHaveBeenCalledWith('dicomfile:0', {
StudyInstanceUID: '1.2.3.4',
SeriesInstanceUID: '1.2.3.4.1',
SOPInstanceUID: '1.2.3.4.5',
frameNumber: 1,
});
});
it('still registers per-frame imageIds (and NumberOfFrames) for a multiframe SEG', () => {
const dataset = makeDataset({
SOPClassUID: '1.2.840.10008.5.1.4.1.1.66.4',
Modality: 'SEG',
PerFrameFunctionalGroupsSequence: [{}, {}, {}],
});
registerNaturalizedDatasetForLocalWadouri(dataset);
// Legitimately multiframe: the count is derived from the per-frame groups
// and must be serialized (enumerable).
expect(dataset.NumberOfFrames).toBe(3);
expect(Object.getOwnPropertyDescriptor(dataset, 'NumberOfFrames').enumerable).toBe(true);
expect(addImageIdToUIDs).toHaveBeenCalledTimes(3);
for (let frame = 1; frame <= 3; frame++) {
expect(addImageIdToUIDs).toHaveBeenNthCalledWith(frame, `dicomfile:0?frame=${frame}`, {
StudyInstanceUID: '1.2.3.4',
SeriesInstanceUID: '1.2.3.4.1',
SOPInstanceUID: '1.2.3.4.5',
frameNumber: frame,
});
}
});
it('keeps the wadouri imageId on the dataset without making it serializable', () => {
const dataset = makeDataset({
SOPClassUID: '1.2.840.10008.5.1.4.1.1.66.4',
Modality: 'SEG',
PixelData: new Uint8Array(4).buffer,
});
registerNaturalizedDatasetForLocalWadouri(dataset);
expect(dataset.url).toBe('dicomfile:0');
expect(Object.getOwnPropertyDescriptor(dataset, 'url').enumerable).toBe(false);
});
it('releases the retained Blob and cached dataset on releaseLocalWadouriRegistrations', () => {
const dataset = makeDataset({
SOPClassUID: '1.2.840.10008.5.1.4.1.1.66.4',
Modality: 'SEG',
PixelData: new Uint8Array(4).buffer,
});
dicomImageLoader.wadouri.fileManager.add.mockReturnValueOnce('dicomfile:7');
// Simulate a parsed dataset held with a refcount of 2 (e.g. two frame loads).
dicomImageLoader.wadouri.dataSetCacheManager.isLoaded
.mockReturnValueOnce(true)
.mockReturnValueOnce(true)
.mockReturnValue(false);
registerNaturalizedDatasetForLocalWadouri(dataset);
releaseLocalWadouriRegistrations();
expect(dicomImageLoader.wadouri.fileManager.remove).toHaveBeenCalledWith(7);
expect(dicomImageLoader.wadouri.dataSetCacheManager.unload).toHaveBeenCalledTimes(2);
expect(dicomImageLoader.wadouri.dataSetCacheManager.unload).toHaveBeenCalledWith('7');
// Idempotent: the tracking set was drained.
dicomImageLoader.wadouri.fileManager.remove.mockClear();
releaseLocalWadouriRegistrations();
expect(dicomImageLoader.wadouri.fileManager.remove).not.toHaveBeenCalled();
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-dicom-microscopy",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "OHIF extension for DICOM microscopy",
"author": "Bill Wallace, md-prog",
"license": "MIT",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-dicom-pdf",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "OHIF extension for PDF display",
"author": "OHIF",
"license": "MIT",
@@ -30,7 +30,7 @@
"peerDependencies": {
"@ohif/core": "workspace:*",
"@ohif/ui": "workspace:*",
"dcmjs": "0.49.4",
"dcmjs": "0.52.0",
"dicom-parser": "1.8.21",
"hammerjs": "2.0.8",
"prop-types": "15.8.1",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-dicom-video",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "OHIF extension for video display",
"author": "OHIF",
"license": "MIT",
@@ -30,7 +30,7 @@
"peerDependencies": {
"@ohif/core": "workspace:*",
"@ohif/ui": "workspace:*",
"dcmjs": "0.49.4",
"dcmjs": "0.52.0",
"dicom-parser": "1.8.21",
"hammerjs": "2.0.8",
"prop-types": "15.8.1",
+5 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-measurement-tracking",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "Tracking features and functionality for basic image viewing",
"author": "OHIF Core Team",
"license": "MIT",
@@ -27,14 +27,14 @@
"start": "pnpm run dev"
},
"peerDependencies": {
"@cornerstonejs/core": "5.1.3",
"@cornerstonejs/tools": "5.1.3",
"@cornerstonejs/core": "5.4.13",
"@cornerstonejs/tools": "5.4.13",
"@ohif/core": "workspace:*",
"@ohif/extension-cornerstone-dicom-sr": "workspace:*",
"@ohif/extension-default": "workspace:*",
"@ohif/ui": "workspace:*",
"classnames": "2.5.1",
"dcmjs": "0.49.4",
"dcmjs": "0.52.0",
"lodash.debounce": "4.0.8",
"prop-types": "15.8.1",
"react": "18.3.1",
@@ -48,6 +48,7 @@
"xstate": "4.38.3"
},
"devDependencies": {
"cross-env": "7.0.3",
"webpack-merge": "5.10.0"
},
"keywords": [
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-test",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "OHIF extension used inside e2e testing",
"author": "OHIF",
"license": "MIT",
@@ -30,7 +30,7 @@
"peerDependencies": {
"@ohif/core": "workspace:*",
"@ohif/ui": "workspace:*",
"dcmjs": "0.49.4",
"dcmjs": "0.52.0",
"dicom-parser": "1.8.21",
"hammerjs": "2.0.8",
"prop-types": "15.8.1",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-tmtv",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "OHIF extension for Total Metabolic Tumor Volume",
"author": "OHIF",
"license": "MIT",
@@ -30,7 +30,7 @@
"peerDependencies": {
"@ohif/core": "workspace:*",
"@ohif/ui": "workspace:*",
"dcmjs": "0.49.4",
"dcmjs": "0.52.0",
"dicom-parser": "1.8.21",
"hammerjs": "2.0.8",
"prop-types": "15.8.1",
@@ -1,7 +1,12 @@
import { toolGroupIds } from './initToolGroups';
import { ToolbarService } from '@ohif/core';
import i18n from 'i18next';
import { MIN_SEGMENTATION_DRAWING_RADIUS, MAX_SEGMENTATION_DRAWING_RADIUS } from './constants';
import { toolGroupIds } from '../toolGroupIds';
const { TOOLBAR_SECTIONS } = ToolbarService;
export const MIN_SEGMENTATION_DRAWING_RADIUS = 0.5;
export const MAX_SEGMENTATION_DRAWING_RADIUS = 99.5;
const setToolActiveToolbar = {
commandName: 'setToolActiveToolbar',
@@ -10,6 +15,11 @@ const setToolActiveToolbar = {
},
};
/**
* Default toolbar buttons for the TMTV mode, registered as the
* `tmtv.toolbarButtons` customization so `?customization=` modules can extend
* or replace them.
*/
const toolbarButtons = [
{
id: 'MeasurementTools',
@@ -301,7 +311,11 @@ const toolbarButtons = [
evaluate: [
{
name: 'evaluate.cornerstone.segmentation',
toolNames: ['ThresholdCircularBrush', 'ThresholdSphereBrush', 'ThresholdCircularBrushDynamic'],
toolNames: [
'ThresholdCircularBrush',
'ThresholdSphereBrush',
'ThresholdCircularBrushDynamic',
],
},
{
name: 'evaluate.cornerstone.segmentation.synchronizeDrawingRadius',
@@ -458,4 +472,51 @@ const toolbarButtons = [
},
];
export default toolbarButtons;
/**
* Default toolbar layout for the TMTV mode, registered as the
* `tmtv.toolbarSections` customization.
*/
export const toolbarSections: Record<string, string[]> = {
[TOOLBAR_SECTIONS.primary]: ['MeasurementTools', 'Zoom', 'Pan', 'WindowLevel', 'Crosshairs'],
[TOOLBAR_SECTIONS.viewportActionMenu.topLeft]: ['orientationMenu', 'dataOverlayMenu'],
[TOOLBAR_SECTIONS.viewportActionMenu.bottomMiddle]: ['AdvancedRenderingControls'],
AdvancedRenderingControls: [
'windowLevelMenuEmbedded',
'voiManualControlMenu',
'Colorbar',
'opacityMenu',
'thresholdMenu',
],
[TOOLBAR_SECTIONS.viewportActionMenu.topRight]: [
'modalityLoadBadge',
'trackingStatus',
'navigationComponent',
],
[TOOLBAR_SECTIONS.viewportActionMenu.bottomLeft]: ['windowLevelMenu'],
MeasurementTools: ['Length', 'Bidirectional', 'ArrowAnnotate', 'EllipticalROI'],
ROIThresholdToolbox: ['SegmentationTools'],
SegmentationTools: ['RectangleROIStartEndThreshold', 'BrushTools'],
BrushTools: ['Brush', 'Eraser', 'Threshold'],
};
/**
* TMTV-specific capability packs registered (at default scope) by the tmtv
* extension. These are the TMTV mode's specialized toolbar buttons and layout;
* the TMTV mode composes them by name in its own `toolbarButtons` /
* `toolbarSections` instance arrays, and `?customization=` modules extend the
* result through the `mode` phase.
*/
const toolbarCustomization = {
'tmtv.toolbarButtons': toolbarButtons,
'tmtv.toolbarSections': toolbarSections,
};
export { toolbarButtons };
export default toolbarCustomization;
@@ -0,0 +1,17 @@
import toolbarCustomization from './customizations/toolbarCustomization';
/**
* Registers the TMTV-specific capability packs (toolbar buttons and section
* layout) so the TMTV mode can compose them by name and `?customization=`
* modules can extend the result through the `mode` phase.
*/
export default function getCustomizationModule() {
return [
{
name: 'default',
value: {
...toolbarCustomization,
},
},
];
}
+4
View File
@@ -4,6 +4,8 @@ import getPanelModule from './getPanelModule';
import init from './init';
import commandsModule from './commandsModule';
import getToolbarModule from './getToolbarModule';
import getCustomizationModule from './getCustomizationModule';
import { toolGroupIds } from './toolGroupIds';
/**
*
@@ -19,6 +21,7 @@ const tmtvExtension = {
getToolbarModule,
getPanelModule,
getHangingProtocolModule,
getCustomizationModule,
getCommandsModule({ servicesManager, commandsManager, extensionManager }) {
return commandsModule({
servicesManager,
@@ -29,3 +32,4 @@ const tmtvExtension = {
};
export default tmtvExtension;
export { toolGroupIds };
+14
View File
@@ -0,0 +1,14 @@
/**
* The tool group ids used by the TMTV hanging protocols and mode. Defined in
* the extension so both the extension (hanging protocol viewports, toolbar
* buttons) and the mode (tool group creation) share one definition.
*/
export const toolGroupIds = {
CT: 'ctToolGroup',
PT: 'ptToolGroup',
Fusion: 'fusionToolGroup',
MIP: 'mipToolGroup',
default: 'default',
};
export default toolGroupIds;
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-ultrasound-pleura-bline",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "",
"author": "Rodrigo Basilio",
"license": "MIT",
@@ -36,8 +36,8 @@
},
"dependencies": {
"@babel/runtime": "7.29.7",
"@cornerstonejs/core": "5.1.3",
"@cornerstonejs/tools": "5.1.3",
"@cornerstonejs/core": "5.4.13",
"@cornerstonejs/tools": "5.4.13",
"@ohif/core": "workspace:*",
"@ohif/extension-cornerstone": "workspace:*",
"@ohif/extension-default": "workspace:*",
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-basic-dev-mode",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "Basic OHIF Viewer Using Cornerstone",
"author": "OHIF",
"license": "MIT",
@@ -41,6 +41,7 @@
"i18next": "17.3.1"
},
"devDependencies": {
"cross-env": "7.0.3",
"webpack-merge": "5.10.0"
}
}
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-test",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "Basic mode for testing",
"author": "OHIF",
"license": "MIT",
@@ -40,9 +40,11 @@
},
"dependencies": {
"@babel/runtime": "7.29.7",
"@ohif/mode-basic": "workspace:*",
"i18next": "17.3.1"
},
"devDependencies": {
"cross-env": "7.0.3",
"webpack-merge": "5.10.0"
},
"keywords": [
+165 -208
View File
@@ -1,7 +1,17 @@
import i18n from 'i18next';
import { ToolbarService } from '@ohif/core';
import {
isValidMode,
layoutTemplate,
modeFactory,
modeInstance as basicModeInstance,
} from '@ohif/mode-basic';
import toolbarButtons from './toolbarButtons';
import { id } from './id';
import initToolGroups from './initToolGroups';
import i18n from 'i18next';
const { TOOLBAR_SECTIONS } = ToolbarService;
// Allow this mode by excluding non-imaging modalities such as SR, SEG
// Also, SM is not a simple imaging modalities, so exclude it.
@@ -67,231 +77,178 @@ const extensionDependencies = {
'@ohif/extension-test': '^0.0.1',
};
function modeFactory() {
return {
id,
routeName: 'basic-test',
displayName: i18n.t('Modes:Basic Test Mode'),
/**
* Lifecycle hooks
*/
onModeEnter: ({ servicesManager, extensionManager, commandsManager }: withAppTypes) => {
const { measurementService, toolbarService, toolGroupService, customizationService } =
servicesManager.services;
/**
* The test mode's toolbar layout, supplied as literal values rather than
* `{ $reference }` capability-pack markers (the composition is resolved the
* same way either — literals pass through untouched).
*/
const toolbarSections = {
[TOOLBAR_SECTIONS.primary]: [
'MeasurementTools',
'Zoom',
'WindowLevelGroup',
'Pan',
'Capture',
'Layout',
'MPR',
'Crosshairs',
'MoreTools',
],
measurementService.clearMeasurements();
WindowLevelGroup: ['WindowLevel', 'Soft tissue', 'Lung', 'Liver', 'Bone', 'Brain'],
// Init Default and SR ToolGroups
initToolGroups(extensionManager, toolGroupService, commandsManager);
[TOOLBAR_SECTIONS.viewportActionMenu.topLeft]: ['orientationMenu', 'dataOverlayMenu'],
// init customizations
customizationService.setCustomizations([
'@ohif/extension-test.customizationModule.custom-context-menu',
]);
[TOOLBAR_SECTIONS.viewportActionMenu.bottomMiddle]: ['AdvancedRenderingControls'],
toolbarService.register(toolbarButtons);
console.debug('toolbarButtons', toolbarButtons);
toolbarService.updateSection(toolbarService.sections.primary, [
'MeasurementTools',
'Zoom',
'WindowLevelGroup',
'Pan',
'Capture',
'Layout',
'MPR',
'Crosshairs',
'MoreTools',
]);
AdvancedRenderingControls: ['voiManualControlMenu', 'Colorbar', 'opacityMenu', 'thresholdMenu'],
toolbarService.updateSection('WindowLevelGroup', [
'WindowLevel',
'Soft tissue',
'Lung',
'Liver',
'Bone',
'Brain',
]);
[TOOLBAR_SECTIONS.viewportActionMenu.topRight]: [
'modalityLoadBadge',
'trackingStatus',
'navigationComponent',
],
toolbarService.updateSection(toolbarService.sections.viewportActionMenu.topLeft, [
'orientationMenu',
'dataOverlayMenu',
]);
[TOOLBAR_SECTIONS.viewportActionMenu.bottomLeft]: ['windowLevelMenu'],
toolbarService.updateSection(toolbarService.sections.viewportActionMenu.bottomMiddle, [
'AdvancedRenderingControls',
]);
MeasurementTools: [
'Length',
'Bidirectional',
'ArrowAnnotate',
'EllipticalROI',
'CircleROI',
'PlanarFreehandROI',
'SplineROI',
'LivewireContour',
],
toolbarService.updateSection('AdvancedRenderingControls', [
'voiManualControlMenu',
'Colorbar',
'opacityMenu',
'thresholdMenu',
]);
MoreTools: [
'Reset',
'rotate-right',
'flipHorizontal',
'ImageSliceSync',
'ReferenceLines',
'ImageOverlayViewer',
'StackScroll',
'invert',
'Probe',
'Cine',
'Angle',
'CobbAngle',
'Magnify',
'RectangleROI',
'CalibrationLine',
'TagBrowser',
'AdvancedMagnify',
'UltrasoundDirectionalTool',
'WindowLevelRegion',
],
};
toolbarService.updateSection(toolbarService.sections.viewportActionMenu.topRight, [
'modalityLoadBadge',
'trackingStatus',
'navigationComponent',
]);
toolbarService.updateSection(toolbarService.sections.viewportActionMenu.bottomLeft, [
'windowLevelMenu',
]);
toolbarService.updateSection('WindowLevelGroup', [
'WindowLevel',
'Soft tissue',
'Lung',
'Liver',
'Bone',
'Brain',
]);
toolbarService.updateSection('MeasurementTools', [
'Length',
'Bidirectional',
'ArrowAnnotate',
'EllipticalROI',
'CircleROI',
'PlanarFreehandROI',
'SplineROI',
'LivewireContour',
]);
toolbarService.updateSection('MoreTools', [
'Reset',
'rotate-right',
'flipHorizontal',
'ImageSliceSync',
'ReferenceLines',
'ImageOverlayViewer',
'StackScroll',
'invert',
'Probe',
'Cine',
'Angle',
'CobbAngle',
'Magnify',
'RectangleROI',
'CalibrationLine',
'TagBrowser',
'AdvancedMagnify',
'UltrasoundDirectionalTool',
'WindowLevelRegion',
]);
customizationService.setCustomizations(
{
'ohif.hotkeyBindings': {
$push: [
{
commandName: 'undo',
label: 'Undo',
keys: ['ctrl+z'],
isEditable: true,
},
],
},
},
'mode'
);
},
onModeExit: ({ servicesManager }: withAppTypes) => {
const {
toolGroupService,
syncGroupService,
segmentationService,
cornerstoneViewportService,
uiDialogService,
uiModalService,
} = servicesManager.services;
uiDialogService.hideAll();
uiModalService.hide();
toolGroupService.destroy();
syncGroupService.destroy();
segmentationService.destroy();
cornerstoneViewportService.destroy();
},
validationTags: {
study: [],
series: [],
},
isValidMode: function ({ modalities }) {
const modalities_list = modalities.split('\\');
// Exclude non-image modalities
return {
valid: !!modalities_list.filter(modality => NON_IMAGE_MODALITIES.indexOf(modality) === -1)
.length,
description:
'The mode does not support studies that ONLY include the following modalities: SM, ECG, SR, SEG',
};
},
routes: [
export const basicTestLayout = {
id: ohif.layout,
props: {
// Literal panel lists; the shared layout template also accepts
// customization names here.
leftPanels: [tracked.thumbnailList],
leftPanelResizable: true,
rightPanels: [cornerstone.panel, tracked.measurements, testExtension.measurements],
rightPanelResizable: true,
viewports: [
{
path: 'basic-test',
layoutTemplate: () => {
return {
id: ohif.layout,
props: {
leftPanels: [tracked.thumbnailList],
leftPanelResizable: true,
rightPanels: [cornerstone.panel, tracked.measurements, testExtension.measurements],
rightPanelResizable: true,
viewports: [
{
namespace: tracked.viewport,
displaySetsToDisplay: [
ohif.sopClassHandler,
dicomvideo.sopClassHandler,
ohif.wsiSopClassHandler,
],
},
{
namespace: dicomsr.viewport,
displaySetsToDisplay: [dicomsr.sopClassHandler, dicomsr.sopClassHandler3D],
},
{
namespace: dicompdf.viewport,
displaySetsToDisplay: [dicompdf.sopClassHandler],
},
{
namespace: dicomSeg.viewport,
displaySetsToDisplay: [dicomSeg.sopClassHandler],
},
{
namespace: dicomPmap.viewport,
displaySetsToDisplay: [dicomPmap.sopClassHandler],
},
],
},
};
},
namespace: tracked.viewport,
displaySetsToDisplay: [
ohif.sopClassHandler,
dicomvideo.sopClassHandler,
ohif.wsiSopClassHandler,
],
},
{
namespace: dicomsr.viewport,
displaySetsToDisplay: [dicomsr.sopClassHandler, dicomsr.sopClassHandler3D],
},
{
namespace: dicompdf.viewport,
displaySetsToDisplay: [dicompdf.sopClassHandler],
},
{
namespace: dicomSeg.viewport,
displaySetsToDisplay: [dicomSeg.sopClassHandler],
},
{
namespace: dicomPmap.viewport,
displaySetsToDisplay: [dicomPmap.sopClassHandler],
},
],
extensions: extensionDependencies,
hangingProtocol: 'default',
sopClassHandlers: [
dicomvideo.sopClassHandler,
dicomSeg.sopClassHandler,
ohif.wsiSopClassHandler,
ohif.sopClassHandler,
dicompdf.sopClassHandler,
dicomsr.sopClassHandler,
dicomsr.sopClassHandler3D,
],
hotkeys: {
name: 'basic-test-hotkeys',
},
};
export const basicTestRoute = {
path: 'basic-test',
layoutTemplate,
layoutInstance: basicTestLayout,
};
/**
* Extends the basic mode instance: the shared onModeEnter/onModeExit are
* inherited, and the test specifics (toolbar layout, tool groups, test
* customizations) are supplied as instance data.
*/
export const modeInstance = {
...basicModeInstance,
id,
routeName: 'basic-test',
displayName: i18n.t('Modes:Basic Test Mode'),
// Literal toolbar values instead of the basic mode's customization names.
toolbarButtons,
toolbarSections,
// Tool group setup used by the shared onModeEnter.
initToolGroups,
// The mode's own customizations, applied by the mode route as the bottom
// layer of the mode scope: the test extension's custom context menu, plus
// the undo hotkey used by the E2E tests. Given as a literal here; modes may
// also reference a registered block by name (see `basicModeCustomizations`).
modeCustomizations: [
'@ohif/extension-test.customizationModule.custom-context-menu',
{
'ohif.hotkeyBindings': {
$push: [
{
commandName: 'undo',
label: 'Undo',
keys: ['ctrl+z'],
isEditable: true,
},
],
},
},
};
}
],
isValidMode,
nonModeModalities: NON_IMAGE_MODALITIES,
routes: [basicTestRoute],
extensions: extensionDependencies,
hangingProtocol: 'default',
sopClassHandlers: [
dicomvideo.sopClassHandler,
dicomSeg.sopClassHandler,
ohif.wsiSopClassHandler,
ohif.sopClassHandler,
dicompdf.sopClassHandler,
dicomsr.sopClassHandler,
dicomsr.sopClassHandler3D,
],
hotkeys: {
name: 'basic-test-hotkeys',
},
};
const mode = {
id,
modeFactory,
modeInstance,
extensionDependencies,
};
export default mode;
export { initToolGroups };
+1 -1
View File
@@ -267,7 +267,7 @@ function initVolume3DToolGroup(extensionManager, toolGroupService) {
toolGroupService.createToolGroupAndAddTools('volume3d', tools);
}
function initToolGroups(extensionManager, toolGroupService, commandsManager) {
function initToolGroups({ extensionManager, toolGroupService, commandsManager }) {
initDefaultToolGroup(extensionManager, toolGroupService, commandsManager, 'default');
initSRToolGroup(extensionManager, toolGroupService, commandsManager);
initMPRToolGroup(extensionManager, toolGroupService, commandsManager);
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-basic",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "A basic mode used to build other modes on top of",
"author": "OHIF Contributors",
"license": "MIT",
@@ -38,6 +38,7 @@
"@babel/runtime": "7.29.7"
},
"devDependencies": {
"cross-env": "7.0.3",
"webpack-merge": "5.10.0"
},
"keywords": [
+161 -82
View File
@@ -2,6 +2,11 @@ import update from 'immutability-helper';
import { utils } from '@ohif/core';
import initToolGroups from './initToolGroups';
import {
addActivatePanelTriggers,
applyToolGroupAdditions,
registerModeToolbar,
} from './modeCustomization';
import { id } from './id';
const { structuredCloneWithFunctions } = utils;
@@ -99,20 +104,48 @@ export const sopClassHandlers = [
];
/**
* Indicate this is a valid mode if:
* - it contains at least one of the modeModalities
* - it contains all of the array value in modeModalities
* Otherwise, if modeModalities is not defined:
* - it contains at least one modality other than the nonModeMOdalities.
* Data-driven mode validity check, using these mode instance properties:
* - `excludedStudies`: a list of `{ attribute: value }` objects; a study
* matching every attribute of any entry is invalid.
* - `excludedModalities`: the study is invalid when it contains ANY of these.
* - `modeModalities`: the study is valid when it contains at least one entry;
* an array entry requires all of its modalities to be present (e.g.
* `[['PT', 'CT']]` requires both PT and CT).
* - otherwise `nonModeModalities`: the study is valid when it contains at
* least one modality NOT in this list.
*/
export function isValidMode({ modalities }) {
export function isValidMode({ modalities, study }) {
const modalities_list = modalities.split('\\');
if (study && this.excludedStudies?.length) {
const excluded = this.excludedStudies.find(exclusion =>
Object.entries(exclusion).every(([key, value]) => study[key] === value)
);
if (excluded) {
return {
valid: false,
description: `The mode excludes studies matching: ${JSON.stringify(excluded)}`,
};
}
}
if (this.excludedModalities?.length) {
const excluded = this.excludedModalities.find(modality => modalities_list.includes(modality));
if (excluded) {
return {
valid: false,
description: `The mode does not support studies containing the ${excluded} modality`,
};
}
}
if (this.modeModalities?.length) {
for (const modeModality of this.modeModalities) {
if (Array.isArray(modeModality) && modeModality.every(m => modalities.indexOf(m) !== -1)) {
return { valid: true, description: `Matches ${modeModality.join(', ')}` };
} else if (modalities.indexOf(modeModality)) {
if (Array.isArray(modeModality)) {
if (modeModality.every(m => modalities_list.includes(m))) {
return { valid: true, description: `Matches ${modeModality.join(', ')}` };
}
} else if (modalities_list.includes(modeModality)) {
return { valid: true, description: `Matches ${modeModality}` };
}
}
@@ -122,84 +155,81 @@ export function isValidMode({ modalities }) {
};
}
const nonModeModalities = this.nonModeModalities ?? [];
return {
valid: !!modalities_list.find(modality => this.nonModeModalities.indexOf(modality) === -1),
description: `The mode does not support studies that ONLY include the following modalities: ${this.nonModeModalities.join(', ')}`,
valid: !!modalities_list.find(modality => !nonModeModalities.includes(modality)),
description: `The mode does not support studies that ONLY include the following modalities: ${nonModeModalities.join(', ')}`,
};
}
export function onModeEnter({
servicesManager,
extensionManager,
commandsManager,
panelService,
segmentationService,
}: withAppTypes) {
/**
* The panel activation triggers the basic family of modes historically shipped
* (commented out): activate the segmentation/measurement panel when a
* segmentation/measurement is added. Not enabled by default; a mode or
* customization can set them via the `activatePanelTriggers` instance
* property.
*/
export const defaultActivatePanelTriggers = [
{
panelId: cornerstone.segmentation,
sourceServiceName: 'segmentationService',
sourceEvents: ['SEGMENTATION_ADDED'],
},
{
panelId: cornerstone.measurements,
sourceServiceName: 'measurementService',
sourceEvents: ['MEASUREMENT_ADDED', 'RAW_MEASUREMENT_ADDED'],
},
];
export function onModeEnter({ servicesManager, extensionManager, commandsManager }: withAppTypes) {
const { measurementService, toolbarService, toolGroupService, customizationService } =
servicesManager.services;
measurementService.clearMeasurements();
// Init Default and SR ToolGroups
initToolGroups(extensionManager, toolGroupService, commandsManager);
// Subscriptions the mode creates are tracked as unsubscribe functions on the
// instance; the shared onModeExit cleans them up. Extending modes push
// their own unsubscribe functions here after calling this function.
this._unsubscriptions = [];
// Toolbar buttons and layout may be supplied either as a customization name
// (a string, resolved through the customization service so `?customization=`
// modules can extend the cornerstone-registered defaults) or as a literal
// value (the button array / sections object) for modes that define them inline.
const resolveToolbarCustomization = (value: unknown) =>
typeof value === 'string' ? customizationService.getCustomization(value) : value;
// Init the mode's tool groups. The function is a mode instance property so
// extending modes can substitute their own tool group setup.
this.initToolGroups?.({ extensionManager, toolGroupService, commandsManager, servicesManager });
const toolbarButtons = resolveToolbarCustomization(this.toolbarButtons) as any;
const toolbarSections = (resolveToolbarCustomization(this.toolbarSections) ?? {}) as Record<
string,
string[]
>;
// Toolbar buttons and layout come from the mode's composition, which the
// mode route seeded onto the Mode customization scope on enter (the plain
// `toolbarButtons` / `toolbarSections` keys) and the app config / URL `mode`
// phase then layered on top. Reading them here — after that layering — lets
// `?customization=` modules extend the toolbar without the mode restating it.
registerModeToolbar(
{ toolbarService },
{
toolbarButtons: customizationService.getCustomization('toolbarButtons'),
toolbarSections: customizationService.getCustomization('toolbarSections'),
}
);
toolbarService.register(toolbarButtons);
// Extra tools (e.g. segmentation editing tools added by a customization) are
// layered onto the tool groups created above, from the resolved
// `toolGroupAdditions` composition (seeded on enter, refined by the `mode`
// phase).
applyToolGroupAdditions(
{ toolGroupService },
customizationService.getCustomization('toolGroupAdditions')
);
for (const [key, section] of Object.entries(toolbarSections)) {
toolbarService.updateSection(key, section);
}
// Note: the mode's `modeCustomizations` are NOT applied here — the mode
// route applies them right after the mode scope is reset, before the app
// config / URL `mode` phase blocks, so the final value of every key is
// decided purely by customization scope precedence and application order.
if (!this.enableSegmentationEdit) {
customizationService.setCustomizations({
'panelSegmentation.disableEditing': {
$set: true,
},
});
}
// // ActivatePanel event trigger for when a segmentation or measurement is added.
// // Do not force activation so as to respect the state the user may have left the UI in.
if (this.activatePanelTrigger) {
this._activatePanelTriggersSubscriptions = [
...panelService.addActivatePanelTriggers(
cornerstone.segmentation,
[
{
sourcePubSubService: segmentationService,
sourceEvents: [segmentationService.EVENTS.SEGMENTATION_ADDED],
},
],
true
),
...panelService.addActivatePanelTriggers(
cornerstone.measurements,
[
{
sourcePubSubService: measurementService,
sourceEvents: [
measurementService.EVENTS.MEASUREMENT_ADDED,
measurementService.EVENTS.RAW_MEASUREMENT_ADDED,
],
},
],
true
),
true,
];
}
// ActivatePanel event triggers (e.g. activating the segmentation panel when
// a segmentation is added). Off by default; supplied as data so extending
// modes and customizations can point at their own panels.
this._unsubscriptions.push(
...addActivatePanelTriggers({ servicesManager }, this.activatePanelTriggers)
);
}
export function onModeExit({ servicesManager }: withAppTypes) {
@@ -212,8 +242,8 @@ export function onModeExit({ servicesManager }: withAppTypes) {
uiModalService,
} = servicesManager.services;
this._activatePanelTriggersSubscriptions.forEach(sub => sub.unsubscribe());
this._activatePanelTriggersSubscriptions.length = 0;
this._unsubscriptions?.forEach(unsubscribe => unsubscribe());
this._unsubscriptions = [];
uiDialogService.hideAll();
uiModalService.hide();
@@ -226,6 +256,11 @@ export function onModeExit({ servicesManager }: withAppTypes) {
export const basicLayout = {
id: ohif.layout,
props: {
// Literal panel lists. The mode route seeds these into the standard
// `leftPanels` / `rightPanels` customizations at the bottom of
// the mode scope, so `mode` phase blocks and global customizations can
// modify them (e.g. swap in the segmentation panels with editing tools)
// before the sidebars resolve.
leftPanels: [ohif.thumbnailList],
leftPanelResizable: true,
rightPanels: [cornerstone.segmentation, cornerstone.measurements],
@@ -284,11 +319,33 @@ export const modeInstance = {
// instance by default.
hide: false,
displayName: 'Non-Longitudinal Basic',
_activatePanelTriggersSubscriptions: [],
// Toolbar buttons and layout are referenced by customization name; the
// cornerstone extension registers the defaults and `?customization=` modules
// can extend them. onModeEnter resolves these names via the customization service.
toolbarSections: 'cornerstone.toolbarSections',
// Toolbar/tool-group composition: which capability packs this mode uses,
// named with `{ $reference }` markers the customization service expands at
// read time. The mode route seeds these onto the Mode customization scope on
// enter (as the plain `toolbarButtons` / `toolbarSections` /
// `toolGroupAdditions` keys), so `?customization=` modules extend them
// through the `mode` phase (e.g.
// `mode.basic.toolbarButtons: { $push: [{ $reference: '...' }] }`).
toolbarSections: [{ $reference: 'cornerstone.toolbarSections' }],
toolGroupAdditions: {
default: [],
mpr: [],
SRToolGroup: [],
volume3d: [],
},
// Tool group setup used by onModeEnter; extending modes can replace it.
initToolGroups,
// The mode's own customizations, referenced by name: the block is registered
// at default scope when the mode loads (see `customizations` below), and the
// mode route applies it as the bottom layer of the mode scope on enter.
// Later layers — the app config / URL `mode` phase blocks and any global
// customization (e.g. `segmentationEditing`) — override it purely by
// application order and scope precedence.
modeCustomizations: 'basicModeCustomizations',
// ActivatePanel event triggers, applied on mode enter. Empty by default so
// the state the user left the UI in is respected; extending modes or
// customizations can push `defaultActivatePanelTriggers` entries.
activatePanelTriggers: [],
/**
* Lifecycle hooks
@@ -310,8 +367,7 @@ export const modeInstance = {
// general handler needs to come last. For this case, the dicomvideo must
// come first to remove video transfer syntax before ohif uses images
sopClassHandlers,
toolbarButtons: 'cornerstone.toolbarButtons',
enableSegmentationEdit: false,
toolbarButtons: [{ $reference: 'cornerstone.toolbarButtons' }],
nonModeModalities: NON_IMAGE_MODALITIES,
};
@@ -327,12 +383,35 @@ export function modeFactory({ modeConfiguration }) {
return modeInstance;
}
/**
* Customizations the mode registers with the customization service (Default
* scope) when it loads — before the bootstrap phase applies, so bootstrap and
* `?customization=` modules can modify them before anything reads them.
* Values are plain data (registered customization values never carry `$`
* commands — commands are how later customizations modify them).
*/
export const customizations = {
// The mode's own mode-scope block, applied by the mode route as the bottom
// layer of the mode scope on mode enter (see `modeCustomizations` above).
basicModeCustomizations: {
// Segmentation panel editing is off in the basic modes; e.g. the
// `segmentationEditing` customization overrides this at global scope.
'panelSegmentation.disableEditing': true,
},
};
export const mode = {
id,
modeFactory,
modeInstance: { ...modeInstance, hide: true },
extensionDependencies,
customizations,
};
export default mode;
export { initToolGroups };
export {
addActivatePanelTriggers,
applyToolGroupAdditions,
registerModeToolbar,
} from './modeCustomization';
+7 -5
View File
@@ -83,10 +83,7 @@ function initDefaultToolGroup(extensionManager, toolGroupService, commandsManage
{ toolName: toolNames.LivewireContour },
{ toolName: toolNames.WindowLevelRegion },
],
enabled: [
{ toolName: toolNames.ImageOverlayViewer },
{ toolName: toolNames.ReferenceLines },
],
enabled: [{ toolName: toolNames.ImageOverlayViewer }, { toolName: toolNames.ReferenceLines }],
disabled: [
{
toolName: toolNames.AdvancedMagnify,
@@ -306,7 +303,12 @@ function initVolume3DToolGroup(extensionManager, toolGroupService) {
toolGroupService.createToolGroupAndAddTools('volume3d', tools);
}
function initToolGroups(extensionManager, toolGroupService, commandsManager) {
/**
* Mode tool group setup. All modes share this options-object signature so a
* mode (or a `modeConfiguration`) can substitute any other mode's
* implementation via the `initToolGroups` instance property.
*/
function initToolGroups({ extensionManager, toolGroupService, commandsManager }) {
initDefaultToolGroup(extensionManager, toolGroupService, commandsManager, 'default');
initSRToolGroup(extensionManager, toolGroupService);
initMPRToolGroup(extensionManager, toolGroupService, commandsManager);
+101
View File
@@ -0,0 +1,101 @@
/**
* Helpers for applying a mode's toolbar / tool-group composition.
*
* The composition values (`toolbarButtons`, `toolbarSections`,
* `toolGroupAdditions`) are ordinary customizations resolved through the
* customization service. A mode lists the capability packs it uses with
* `{ $reference: '<name>' }` markers; the service expands those at read time
* (packs that are arrays are flattened into the surrounding list), and a site
* `?customization=` module extends or replaces them with immutability-helper
* commands (`$push` another `{ $reference }`, `$set` a hard-coded value, ...).
* By the time these helpers run, the values passed in are already fully
* resolved — so they only need to shape/register them.
*/
/** Normalizes a value to an array (wrapping a single object, dropping nullish). */
function toArray(value: unknown): any[] {
if (value === undefined || value === null) {
return [];
}
return Array.isArray(value) ? value : [value];
}
/**
* Registers a mode's toolbar from its resolved composition.
*
* `toolbarButtons` is a flat list of button definitions registered with the
* toolbar service. `toolbarSections` is one or more
* `{ sectionKey: buttonIds[] }` objects shallow-merged in order (later values
* win per section) and applied with `updateSection`.
*/
export function registerModeToolbar({ toolbarService }, { toolbarButtons, toolbarSections }): void {
toolbarService.register(toArray(toolbarButtons));
const sections: Record<string, string[]> = Object.assign({}, ...toArray(toolbarSections));
for (const [key, section] of Object.entries(sections)) {
toolbarService.updateSection(key, section);
}
}
/**
* Adds extra tools to the tool groups a mode has already created.
*
* `toolGroupAdditions` is a resolved object mapping a tool group id to a list
* of tool blocks (each a `{ active/passive/enabled/disabled }` object). Tool
* groups the mode did not create are skipped, so a single additions object can
* be shared between modes with different tool group sets.
*/
export function applyToolGroupAdditions({ toolGroupService }, toolGroupAdditions): void {
if (!toolGroupAdditions) {
return;
}
for (const additions of toArray(toolGroupAdditions)) {
for (const [toolGroupId, toolBlocks] of Object.entries(additions)) {
if (!toolGroupService.getToolGroup(toolGroupId)) {
continue;
}
for (const tools of toArray(toolBlocks)) {
toolGroupService.addToolsToToolGroup(toolGroupId, tools);
}
}
}
}
/**
* Wires up a mode's ActivatePanel event triggers from data.
*
* `activatePanelTriggers` is a list of
* `{ panelId, sourceServiceName, sourceEvents, forceActive? }` entries;
* `sourceEvents` names are looked up in the source service's `EVENTS` map
* (falling back to the raw value) so the whole entry is JSON-serializable and
* can be supplied by a `?customization=` module or an extending mode.
*
* Returns the unsubscribe functions for the subscriptions created.
*/
export function addActivatePanelTriggers(
{ servicesManager },
activatePanelTriggers
): (() => void)[] {
const { panelService } = servicesManager.services;
const unsubscriptions: (() => void)[] = [];
for (const trigger of activatePanelTriggers ?? []) {
const { panelId, sourceServiceName, sourceEvents, forceActive = true } = trigger;
const sourcePubSubService = servicesManager.services[sourceServiceName];
if (!sourcePubSubService) {
console.warn(`addActivatePanelTriggers: no service registered for "${sourceServiceName}"`);
continue;
}
const subscriptions = panelService.addActivatePanelTriggers(
panelId,
[
{
sourcePubSubService,
sourceEvents: sourceEvents.map(name => sourcePubSubService.EVENTS?.[name] ?? name),
},
],
forceActive
);
unsubscriptions.push(...subscriptions.map(subscription => () => subscription.unsubscribe()));
}
return unsubscriptions;
}
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-longitudinal",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "Longitudinal Workflow",
"author": "OHIF",
"license": "MIT",
@@ -45,6 +45,7 @@
"i18next": "17.3.1"
},
"devDependencies": {
"cross-env": "7.0.3",
"webpack-merge": "5.10.0"
},
"keywords": [
+25 -24
View File
@@ -1,7 +1,9 @@
import i18n from 'i18next';
import { id } from './id';
import { initToolGroups, cornerstone,
import {
initToolGroups,
ohif,
cornerstone,
dicomsr,
dicomvideo,
basicLayout,
@@ -9,7 +11,7 @@ import { initToolGroups, cornerstone,
extensionDependencies as basicDependencies,
mode as basicMode,
modeInstance as basicModeInstance,
} from '@ohif/mode-basic';
} from '@ohif/mode-basic';
export const tracked = {
measurements: '@ohif/extension-measurement-tracking.panelModule.trackedMeasurements',
@@ -28,6 +30,9 @@ export const longitudinalInstance = {
id: ohif.layout,
props: {
...basicLayout.props,
// Literal panel lists; the mode route seeds them into the standard
// `leftPanels` / `rightPanels` customizations so `mode` phase
// blocks and global customizations can modify them.
leftPanels: [tracked.thumbnailList],
rightPanels: [cornerstone.segmentation, tracked.measurements],
viewports: [
@@ -37,33 +42,29 @@ export const longitudinalInstance = {
displaySetsToDisplay: basicLayout.props.viewports[0].displaySetsToDisplay,
},
...basicLayout.props.viewports,
],
}
};
],
},
};
export const longitudinalRoute =
{
...basicRoute,
path: 'longitudinal',
/*init: ({ servicesManager, extensionManager }) => {
export const longitudinalRoute = {
...basicRoute,
path: 'longitudinal',
/*init: ({ servicesManager, extensionManager }) => {
//defaultViewerRouteInit
},*/
layoutInstance: longitudinalInstance,
};
layoutInstance: longitudinalInstance,
};
export const modeInstance = {
...basicModeInstance,
// TODO: We're using this as a route segment
// We should not be.
id,
routeName: 'viewer',
displayName: i18n.t('Modes:Basic Viewer'),
routes: [
longitudinalRoute
],
extensions: extensionDependencies,
};
...basicModeInstance,
// TODO: We're using this as a route segment
// We should not be.
id,
routeName: 'viewer',
displayName: i18n.t('Modes:Basic Viewer'),
routes: [longitudinalRoute],
extensions: extensionDependencies,
};
const mode = {
...basicMode,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-microscopy",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "OHIF mode for DICOM microscopy",
"author": "OHIF",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-preclinical-4d",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "4D Workflow",
"author": "OHIF",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-segmentation",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "OHIF segmentation mode which enables labelmap segmentation read/edit/export",
"author": "@ohif",
"license": "MIT",
+128 -233
View File
@@ -1,249 +1,144 @@
import { id } from './id';
import toolbarButtons from './toolbarButtons';
import initToolGroups from './initToolGroups';
import setUpAutoTabSwitchHandler from './utils/setUpAutoTabSwitchHandler';
import { ohif, cornerstone, extensionDependencies, dicomRT, segmentation } from '@ohif/mode-basic';
export * from './toolbarButtons';
import {
ohif,
cornerstone,
extensionDependencies,
dicomRT,
segmentation,
isValidMode,
onModeEnter as basicOnModeEnter,
onModeExit,
layoutTemplate,
modeFactory,
} from '@ohif/mode-basic';
function modeFactory({ modeConfiguration }) {
const _unsubscriptions = [];
return {
/**
* Mode ID, which should be unique among modes used by the viewer. This ID
* is used to identify the mode in the viewer's state.
*/
id,
routeName: 'segmentation',
/**
* Mode name, which is displayed in the viewer's UI in the workList, for the
* user to select the mode.
*/
displayName: 'Segmentation',
/**
* Runs when the Mode Route is mounted to the DOM. Usually used to initialize
* Services and other resources.
*/
onModeEnter: ({ servicesManager, extensionManager, commandsManager }: withAppTypes) => {
const {
measurementService,
toolbarService,
toolGroupService,
segmentationService,
viewportGridService,
panelService,
} = servicesManager.services;
/**
* Extends the basic mode enter with the segmentation panel auto tab switch
* handling (switching between labelmap/contour panels as segmentations of the
* relevant type become active).
*/
export function onModeEnter(ctx: withAppTypes) {
basicOnModeEnter.call(this, ctx);
measurementService.clearMeasurements();
const { segmentationService, viewportGridService, panelService } = ctx.servicesManager.services;
// Init Default and SR ToolGroups
initToolGroups(extensionManager, toolGroupService, commandsManager);
const { unsubscribeAutoTabSwitchEvents } = setUpAutoTabSwitchHandler({
segmentationService,
viewportGridService,
panelService,
});
toolbarService.register(toolbarButtons);
toolbarService.updateSection(toolbarService.sections.primary, [
'WindowLevel',
'Pan',
'Zoom',
'TrackballRotate',
'Capture',
'Layout',
'Crosshairs',
'MoreTools',
]);
toolbarService.updateSection(toolbarService.sections.viewportActionMenu.topLeft, [
'orientationMenu',
'dataOverlayMenu',
]);
toolbarService.updateSection(toolbarService.sections.viewportActionMenu.bottomMiddle, [
'AdvancedRenderingControls',
]);
toolbarService.updateSection('AdvancedRenderingControls', [
'windowLevelMenuEmbedded',
'voiManualControlMenu',
'Colorbar',
'opacityMenu',
'thresholdMenu',
]);
toolbarService.updateSection(toolbarService.sections.viewportActionMenu.topRight, [
'modalityLoadBadge',
'trackingStatus',
'navigationComponent',
]);
toolbarService.updateSection(toolbarService.sections.viewportActionMenu.bottomLeft, [
'windowLevelMenu',
]);
toolbarService.updateSection('MoreTools', [
'Reset',
'rotate-right',
'flipHorizontal',
'ReferenceLines',
'ImageOverlayViewer',
'StackScroll',
'invert',
'Cine',
'Magnify',
'TagBrowser',
]);
toolbarService.updateSection(toolbarService.sections.labelMapSegmentationToolbox, [
'LabelMapTools',
]);
toolbarService.updateSection(toolbarService.sections.contourSegmentationToolbox, [
'ContourTools',
]);
toolbarService.updateSection('LabelMapTools', [
'LabelmapSlicePropagation',
'BrushTools',
'MarkerLabelmap',
'RegionSegmentPlus',
'Shapes',
'LabelMapEditWithContour',
]);
toolbarService.updateSection('ContourTools', [
'PlanarFreehandContourSegmentationTool',
'SculptorTool',
'SplineContourSegmentationTool',
'LivewireContourSegmentationTool',
]);
toolbarService.updateSection(toolbarService.sections.labelMapSegmentationUtilities, [
'LabelMapUtilities',
]);
toolbarService.updateSection(toolbarService.sections.contourSegmentationUtilities, [
'ContourUtilities',
]);
toolbarService.updateSection('LabelMapUtilities', [
'InterpolateLabelmap',
'SegmentBidirectional',
]);
toolbarService.updateSection('ContourUtilities', [
'LogicalContourOperations',
'SimplifyContours',
'SmoothContours',
]);
toolbarService.updateSection('BrushTools', ['Brush', 'Eraser', 'Threshold']);
const { unsubscribeAutoTabSwitchEvents } = setUpAutoTabSwitchHandler({
segmentationService,
viewportGridService,
panelService,
});
_unsubscriptions.push(...unsubscribeAutoTabSwitchEvents);
},
onModeExit: ({ servicesManager }: withAppTypes) => {
const {
toolGroupService,
syncGroupService,
segmentationService,
cornerstoneViewportService,
uiDialogService,
uiModalService,
} = servicesManager.services;
_unsubscriptions.forEach(unsubscribe => unsubscribe());
_unsubscriptions.length = 0;
uiDialogService.hideAll();
uiModalService.hide();
toolGroupService.destroy();
syncGroupService.destroy();
segmentationService.destroy();
cornerstoneViewportService.destroy();
},
/** */
validationTags: {
study: [],
series: [],
},
/**
* A boolean return value that indicates whether the mode is valid for the
* modalities of the selected studies. Currently we don't have stack viewport
* segmentations and we should exclude them
*/
isValidMode: ({ modalities }) => {
// Don't show the mode if the selected studies have only one modality
// that is not supported by the mode
const modalitiesArray = modalities.split('\\');
return {
valid:
modalitiesArray.length === 1
? !['SM', 'ECG', 'OT', 'DOC'].includes(modalitiesArray[0])
: true,
description:
'The mode does not support studies that ONLY include the following modalities: SM, OT, DOC',
};
},
/**
* Mode Routes are used to define the mode's behavior. A list of Mode Route
* that includes the mode's path and the layout to be used. The layout will
* include the components that are used in the layout. For instance, if the
* default layoutTemplate is used (id: '@ohif/extension-default.layoutTemplateModule.viewerLayout')
* it will include the leftPanels, rightPanels, and viewports. However, if
* you define another layoutTemplate that includes a Footer for instance,
* you should provide the Footer component here too. Note: We use Strings
* to reference the component's ID as they are registered in the internal
* ExtensionManager. The template for the string is:
* `${extensionId}.{moduleType}.${componentId}`.
*/
routes: [
{
path: 'template',
layoutTemplate: ({ location, servicesManager }) => {
return {
id: ohif.layout,
props: {
leftPanels: [ohif.thumbnailList],
leftPanelResizable: true,
rightPanels: [
cornerstone.labelMapSegmentationPanel,
cornerstone.contourSegmentationPanel,
],
rightPanelResizable: true,
// leftPanelClosed: true,
viewports: [
{
namespace: cornerstone.viewport,
displaySetsToDisplay: [ohif.sopClassHandler],
},
{
namespace: segmentation.viewport,
displaySetsToDisplay: [segmentation.sopClassHandler],
},
{
namespace: dicomRT.viewport,
displaySetsToDisplay: [dicomRT.sopClassHandler],
},
],
},
};
},
},
],
/** List of extensions that are used by the mode */
extensions: extensionDependencies,
/** HangingProtocol used by the mode */
// Commented out to just use the most applicable registered hanging protocol
// The example is used for a grid layout to specify that as a preferred layout
hangingProtocol: ['@ohif/mnGrid'],
/** SopClassHandlers used by the mode */
sopClassHandlers: [ohif.sopClassHandler, segmentation.sopClassHandler, dicomRT.sopClassHandler],
};
this._unsubscriptions.push(...unsubscribeAutoTabSwitchEvents);
}
export const segmentationLayout = {
id: ohif.layout,
props: {
// Literal panel lists; the mode route seeds them into the standard
// `leftPanels` / `rightPanels` customizations so `mode` phase
// blocks and global customizations can modify them.
leftPanels: [ohif.thumbnailList],
leftPanelResizable: true,
rightPanels: [cornerstone.labelMapSegmentationPanel, cornerstone.contourSegmentationPanel],
rightPanelResizable: true,
viewports: [
{
namespace: cornerstone.viewport,
displaySetsToDisplay: [ohif.sopClassHandler],
},
{
namespace: segmentation.viewport,
displaySetsToDisplay: [segmentation.sopClassHandler],
},
{
namespace: dicomRT.viewport,
displaySetsToDisplay: [dicomRT.sopClassHandler],
},
],
},
};
export const segmentationRoute = {
path: 'template',
layoutTemplate,
layoutInstance: segmentationLayout,
};
export const modeInstance = {
id,
routeName: 'segmentation',
displayName: 'Segmentation',
// Toolbar/tool-group composition: which capability packs this mode uses.
// The mode route seeds these onto the Mode customization scope on enter, so
// `?customization=` modules extend them through the `mode` phase (e.g. add
// the annotation tools/buttons). Pack names are resolved when the toolbar is
// registered.
toolbarButtons: [
{ $reference: 'cornerstone.toolbarButtons' },
{ $reference: 'cornerstone.segmentationToolbarButtons' },
],
toolbarSections: [
{ $reference: 'cornerstone.segmentationModeToolbarSections' },
{ $reference: 'cornerstone.segmentationToolbarSections' },
],
toolGroupAdditions: {
default: [],
mpr: [],
volume3d: [],
},
// Tool group setup used by onModeEnter; extending modes can replace it.
initToolGroups,
// The mode's own customizations, applied by the mode route as the bottom
// layer of the mode scope. Unlike basic, the registered block is empty (no
// `panelSegmentation.disableEditing`): the segmentation panel is editable.
modeCustomizations: 'segmentationModeCustomizations',
activatePanelTriggers: [],
/**
* Lifecycle hooks
*/
onModeEnter,
onModeExit,
validationTags: {
study: [],
series: [],
},
// Data-driven validity: valid unless the study ONLY contains modalities that
// segmentation cannot be performed on.
isValidMode,
nonModeModalities: ['SM', 'ECG', 'OT', 'DOC'],
routes: [segmentationRoute],
extensions: extensionDependencies,
// Prefer the grid layout hanging protocol when applicable.
hangingProtocol: ['@ohif/mnGrid'],
sopClassHandlers: [ohif.sopClassHandler, segmentation.sopClassHandler, dicomRT.sopClassHandler],
};
/**
* Customizations the mode registers (Default scope) when it loads. The mode's
* own block is empty — the segmentation panel is editable in this mode — but
* it is registered so bootstrap / `?customization=` modules can add
* mode-scoped values to it.
*/
export const customizations = {
segmentationModeCustomizations: {},
};
/**
* The mode uses the basic mode's `modeFactory`, which applies
* immutability-helper commands from `modeConfiguration` onto `modeInstance`,
* so a site can define a `mySegmentation` mode that extends this one.
*/
const mode = {
id,
modeFactory,
modeInstance,
extensionDependencies,
customizations,
};
export default mode;
export { initToolGroups };
+2 -2
View File
@@ -45,7 +45,7 @@ function createTools({ utilityModule, commandsManager }) {
toolName: toolNames.MarkerLabelmap,
},
{
toolName: toolNames.RegionSegmentPlus,
toolName: toolNames.ClickSegment,
},
{
toolName: 'CircularEraser',
@@ -258,7 +258,7 @@ function initVolume3DToolGroup(extensionManager, toolGroupService) {
toolGroupService.createToolGroupAndAddTools('volume3d', tools);
}
function initToolGroups(extensionManager, toolGroupService, commandsManager) {
function initToolGroups({ extensionManager, toolGroupService, commandsManager }) {
initDefaultToolGroup(extensionManager, toolGroupService, commandsManager, 'default');
initMPRToolGroup(extensionManager, toolGroupService, commandsManager);
initVolume3DToolGroup(extensionManager, toolGroupService);
+5 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-tmtv",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "Total Metabolic Tumor Volume Workflow",
"author": "OHIF",
"license": "MIT",
@@ -35,13 +35,16 @@
"@ohif/extension-default": "workspace:*",
"@ohif/extension-dicom-pdf": "workspace:*",
"@ohif/extension-dicom-video": "workspace:*",
"@ohif/extension-measurement-tracking": "workspace:*"
"@ohif/extension-measurement-tracking": "workspace:*",
"@ohif/extension-tmtv": "workspace:*",
"@ohif/mode-basic": "workspace:*"
},
"dependencies": {
"@babel/runtime": "7.29.7",
"i18next": "17.3.1"
},
"devDependencies": {
"cross-env": "7.0.3",
"webpack-merge": "5.10.0"
},
"keywords": [
+180 -220
View File
@@ -1,32 +1,39 @@
import { classes } from '@ohif/core';
import toolbarButtons from './toolbarButtons';
import {
isValidMode,
layoutTemplate,
modeFactory,
onModeEnter as basicOnModeEnter,
onModeExit,
} from '@ohif/mode-basic';
import i18n from 'i18next';
import { id } from './id.js';
import initToolGroups from './initToolGroups.js';
import initToolGroups, { toolGroupIds } from './initToolGroups.js';
import setCrosshairsConfiguration from './utils/setCrosshairsConfiguration.js';
import setFusionActiveVolume from './utils/setFusionActiveVolume.js';
import i18n from 'i18next';
const { MetadataProvider } = classes;
const ohif = {
export const ohif = {
layout: '@ohif/extension-default.layoutTemplateModule.viewerLayout',
sopClassHandler: '@ohif/extension-default.sopClassHandlerModule.stack',
thumbnailList: '@ohif/extension-default.panelModule.seriesList',
};
const cs3d = {
export const cs3d = {
viewport: '@ohif/extension-cornerstone.viewportModule.cornerstone',
segPanel: '@ohif/extension-cornerstone.panelModule.panelSegmentationNoHeader',
measurements: '@ohif/extension-cornerstone.panelModule.measurements',
};
const tmtv = {
export const tmtv = {
hangingProtocol: '@ohif/extension-tmtv.hangingProtocolModule.ptCT',
petSUV: '@ohif/extension-tmtv.panelModule.petSUV',
tmtv: '@ohif/extension-tmtv.panelModule.tmtv',
};
const extensionDependencies = {
export const extensionDependencies = {
// Can derive the versions at least process.env.from npm_package_version
'@ohif/extension-default': '^3.0.0',
'@ohif/extension-cornerstone': '^3.0.0',
@@ -34,234 +41,187 @@ const extensionDependencies = {
'@ohif/extension-tmtv': '^3.0.0',
};
const unsubscriptions = [];
function modeFactory({ modeConfiguration }) {
return {
// TODO: We're using this as a route segment
// We should not be.
id,
routeName: 'tmtv',
displayName: i18n.t('Modes:Total Metabolic Tumor Volume'),
/**
* Lifecycle hooks
*/
onModeEnter: ({ servicesManager, extensionManager, commandsManager }: withAppTypes) => {
const {
toolbarService,
toolGroupService,
customizationService,
hangingProtocolService,
displaySetService,
} = servicesManager.services;
/**
* Extends the basic mode enter (tool groups, toolbar, tool group additions)
* with the TMTV specifics: the fusion viewport crosshairs/active-volume
* configuration and the PT VOI hanging protocol attribute.
*/
export function onModeEnter(ctx: withAppTypes) {
basicOnModeEnter.call(this, ctx);
const utilityModule = extensionManager.getModuleEntry(
'@ohif/extension-cornerstone.utilityModule.tools'
);
const { servicesManager, extensionManager, commandsManager } = ctx;
const { toolGroupService, customizationService, hangingProtocolService, displaySetService } =
servicesManager.services;
const { toolNames, Enums } = utilityModule.exports;
const utilityModule = extensionManager.getModuleEntry(
'@ohif/extension-cornerstone.utilityModule.tools'
);
// Init Default and SR ToolGroups
initToolGroups(toolNames, Enums, toolGroupService, commandsManager);
const { toolNames } = utilityModule.exports;
const { unsubscribe } = toolGroupService.subscribe(
toolGroupService.EVENTS.VIEWPORT_ADDED,
() => {
// For fusion toolGroup we need to add the volumeIds for the crosshairs
// since in the fusion viewport we don't want both PT and CT to render MIP
// when slabThickness is modified
const { displaySetMatchDetails } = hangingProtocolService.getMatchDetails();
const { unsubscribe } = toolGroupService.subscribe(toolGroupService.EVENTS.VIEWPORT_ADDED, () => {
// For fusion toolGroup we need to add the volumeIds for the crosshairs
// since in the fusion viewport we don't want both PT and CT to render MIP
// when slabThickness is modified
const { displaySetMatchDetails } = hangingProtocolService.getMatchDetails();
setCrosshairsConfiguration(
displaySetMatchDetails,
toolNames,
toolGroupService,
displaySetService
);
setCrosshairsConfiguration(
displaySetMatchDetails,
toolNames,
toolGroupService,
displaySetService
);
setFusionActiveVolume(
displaySetMatchDetails,
toolNames,
toolGroupService,
displaySetService
);
}
);
setFusionActiveVolume(displaySetMatchDetails, toolNames, toolGroupService, displaySetService);
});
unsubscriptions.push(unsubscribe);
toolbarService.register(toolbarButtons);
toolbarService.updateSection(toolbarService.sections.primary, [
'MeasurementTools',
'Zoom',
'Pan',
'WindowLevel',
'Crosshairs',
]);
this._unsubscriptions.push(unsubscribe);
toolbarService.updateSection(toolbarService.sections.viewportActionMenu.topLeft, [
'orientationMenu',
'dataOverlayMenu',
]);
toolbarService.updateSection(toolbarService.sections.viewportActionMenu.bottomMiddle, [
'AdvancedRenderingControls',
]);
toolbarService.updateSection('AdvancedRenderingControls', [
'windowLevelMenuEmbedded',
'voiManualControlMenu',
'Colorbar',
'opacityMenu',
'thresholdMenu',
]);
toolbarService.updateSection(toolbarService.sections.viewportActionMenu.topRight, [
'modalityLoadBadge',
'trackingStatus',
'navigationComponent',
]);
toolbarService.updateSection(toolbarService.sections.viewportActionMenu.bottomLeft, [
'windowLevelMenu',
]);
toolbarService.updateSection('MeasurementTools', [
'Length',
'Bidirectional',
'ArrowAnnotate',
'EllipticalROI',
]);
toolbarService.updateSection('ROIThresholdToolbox', ['SegmentationTools']);
toolbarService.updateSection('SegmentationTools', [
'RectangleROIStartEndThreshold',
'BrushTools',
]);
toolbarService.updateSection('BrushTools', ['Brush', 'Eraser', 'Threshold']);
customizationService.setCustomizations({
'panelSegmentation.tableMode': {
$set: 'expanded',
},
'panelSegmentation.onSegmentationAdd': {
$set: () => {
commandsManager.run('createNewLabelmapFromPT');
},
},
});
// For the hanging protocol we need to decide on the window level
// based on whether the SUV is corrected or not, hence we can't hard
// code the window level in the hanging protocol but we add a custom
// attribute to the hanging protocol that will be used to get the
// window level based on the metadata
hangingProtocolService.addCustomAttribute(
'getPTVOIRange',
'get PT VOI based on corrected or not',
props => {
const ptDisplaySet = props.find(imageSet => imageSet.Modality === 'PT');
if (!ptDisplaySet) {
return;
}
const { imageId } = ptDisplaySet.images[0];
const imageIdScalingFactor = MetadataProvider.get('scalingModule', imageId);
const isSUVAvailable = imageIdScalingFactor && imageIdScalingFactor.suvbw;
if (isSUVAvailable) {
return {
windowWidth: 5,
windowCenter: 2.5,
};
}
return;
}
);
},
onModeExit: ({ servicesManager }: withAppTypes) => {
const {
toolGroupService,
syncGroupService,
segmentationService,
cornerstoneViewportService,
uiDialogService,
uiModalService,
} = servicesManager.services;
unsubscriptions.forEach(unsubscribe => unsubscribe());
uiDialogService.hideAll();
uiModalService.hide();
toolGroupService.destroy();
syncGroupService.destroy();
segmentationService.destroy();
cornerstoneViewportService.destroy();
},
validationTags: {
study: [],
series: [],
},
isValidMode: ({ modalities, study }) => {
const modalities_list = modalities.split('\\');
const invalidModalities = ['SM'];
const isValid =
modalities_list.includes('CT') &&
study.mrn !== 'M1' &&
modalities_list.includes('PT') &&
!invalidModalities.some(modality => modalities_list.includes(modality)) &&
// This is study is a 4D study with PT and CT and not a 3D study for the tmtv
// mode, until we have a better way to identify 4D studies we will use the
// StudyInstanceUID to identify the study
// Todo: when we add the 4D mode which comes with a mechanism to identify
// 4D studies we can use that
study.studyInstanceUid !== '1.3.6.1.4.1.12842.1.1.14.3.20220915.105557.468.2963630849';
// there should be both CT and PT modalities and the modality should not be SM
return {
valid: isValid,
description: 'The mode requires both PT and CT series in the study',
};
},
routes: [
{
path: 'tmtv',
/*init: ({ servicesManager, extensionManager }) => {
//defaultViewerRouteInit
},*/
layoutTemplate: () => {
return {
id: ohif.layout,
props: {
leftPanels: [ohif.thumbnailList],
leftPanelResizable: true,
leftPanelClosed: true,
rightPanels: [tmtv.tmtv, tmtv.petSUV],
rightPanelResizable: true,
viewports: [
{
namespace: cs3d.viewport,
displaySetsToDisplay: [ohif.sopClassHandler],
},
],
},
};
},
// Function-valued customization; kept out of the registered
// `tmtvModeCustomizations` block because it needs the mode's
// commandsManager. Written at mode scope, so a global-scope customization
// still overrides it by scope precedence.
customizationService.setCustomizations({
'panelSegmentation.onSegmentationAdd': {
$set: () => {
commandsManager.run('createNewLabelmapFromPT');
},
],
extensions: extensionDependencies,
hangingProtocol: tmtv.hangingProtocol,
sopClassHandlers: [ohif.sopClassHandler],
...modeConfiguration,
};
},
});
// For the hanging protocol we need to decide on the window level
// based on whether the SUV is corrected or not, hence we can't hard
// code the window level in the hanging protocol but we add a custom
// attribute to the hanging protocol that will be used to get the
// window level based on the metadata
hangingProtocolService.addCustomAttribute(
'getPTVOIRange',
'get PT VOI based on corrected or not',
props => {
const ptDisplaySet = props.find(imageSet => imageSet.Modality === 'PT');
if (!ptDisplaySet) {
return;
}
const { imageId } = ptDisplaySet.images[0];
const imageIdScalingFactor = MetadataProvider.get('scalingModule', imageId);
const isSUVAvailable = imageIdScalingFactor && imageIdScalingFactor.suvbw;
if (isSUVAvailable) {
return {
windowWidth: 5,
windowCenter: 2.5,
};
}
return;
}
);
}
export const tmtvLayout = {
id: ohif.layout,
props: {
// Literal panel lists; the mode route seeds them into the standard
// `leftPanels` / `rightPanels` customizations so `mode` phase
// blocks and global customizations can modify them.
leftPanels: [ohif.thumbnailList],
leftPanelResizable: true,
leftPanelClosed: true,
rightPanels: [tmtv.tmtv, tmtv.petSUV],
rightPanelResizable: true,
viewports: [
{
namespace: cs3d.viewport,
displaySetsToDisplay: [ohif.sopClassHandler],
},
],
},
};
export const tmtvRoute = {
path: 'tmtv',
layoutTemplate,
layoutInstance: tmtvLayout,
};
export const modeInstance = {
// TODO: We're using this as a route segment
// We should not be.
id,
routeName: 'tmtv',
displayName: i18n.t('Modes:Total Metabolic Tumor Volume'),
// Toolbar/tool-group composition: which capability packs this mode uses.
// The mode route seeds these onto the Mode customization scope on enter, so
// `?customization=` modules extend them through the `mode` phase. The tmtv
// extension supplies the TMTV-specific button/section packs.
toolbarButtons: [{ $reference: 'tmtv.toolbarButtons' }],
toolbarSections: [{ $reference: 'tmtv.toolbarSections' }],
toolGroupAdditions: {
[toolGroupIds.CT]: [],
[toolGroupIds.PT]: [],
[toolGroupIds.Fusion]: [],
[toolGroupIds.MIP]: [],
[toolGroupIds.default]: [],
},
// Tool group setup used by onModeEnter; extending modes can replace it.
initToolGroups,
// The mode's own customizations, referenced by name: the block is registered
// at default scope when the mode loads (see `customizations` below), and the
// mode route applies it as the bottom layer of the mode scope on enter.
modeCustomizations: 'tmtvModeCustomizations',
activatePanelTriggers: [],
/**
* Lifecycle hooks
*/
onModeEnter,
onModeExit,
validationTags: {
study: [],
series: [],
},
// Data-driven validity: requires both PT and CT, rejects SM, and excludes
// the demo studies that belong to the preclinical 4D mode. Until we have a
// better way to identify 4D studies we use the mrn/StudyInstanceUID.
isValidMode,
modeModalities: [['PT', 'CT']],
excludedModalities: ['SM'],
excludedStudies: [
{ mrn: 'M1' },
{ studyInstanceUid: '1.3.6.1.4.1.12842.1.1.14.3.20220915.105557.468.2963630849' },
],
routes: [tmtvRoute],
extensions: extensionDependencies,
hangingProtocol: tmtv.hangingProtocol,
sopClassHandlers: [ohif.sopClassHandler],
};
/**
* Customizations the mode registers (Default scope) when it loads — before
* the bootstrap phase applies, so bootstrap / `?customization=` modules can
* modify them before anything reads them. Values are plain data.
*/
export const customizations = {
tmtvModeCustomizations: {
'panelSegmentation.tableMode': 'expanded',
},
};
/**
* The mode uses the basic mode's `modeFactory`, which applies
* immutability-helper commands from `modeConfiguration` onto `modeInstance`,
* so a site can define a mode that extends this one.
*/
const mode = {
id,
modeFactory,
modeInstance,
extensionDependencies,
customizations,
};
export default mode;
export { initToolGroups };
+13 -8
View File
@@ -1,12 +1,8 @@
import { toolGroupIds } from '@ohif/extension-tmtv';
import { MIN_SEGMENTATION_DRAWING_RADIUS, MAX_SEGMENTATION_DRAWING_RADIUS } from './constants';
export const toolGroupIds = {
CT: 'ctToolGroup',
PT: 'ptToolGroup',
Fusion: 'fusionToolGroup',
MIP: 'mipToolGroup',
default: 'default',
};
export { toolGroupIds };
function _initToolGroups(toolNames, Enums, toolGroupService, commandsManager) {
const tools = {
@@ -189,7 +185,16 @@ function _initToolGroups(toolNames, Enums, toolGroupService, commandsManager) {
toolGroupService.createToolGroupAndAddTools(toolGroupIds.MIP, mipTools);
}
function initToolGroups(toolNames, Enums, toolGroupService, commandsManager) {
/**
* Mode tool group setup, sharing the options-object signature used by all
* modes so implementations are interchangeable via the `initToolGroups` mode
* instance property.
*/
function initToolGroups({ extensionManager, toolGroupService, commandsManager }) {
const utilityModule = extensionManager.getModuleEntry(
'@ohif/extension-cornerstone.utilityModule.tools'
);
const { toolNames, Enums } = utilityModule.exports;
_initToolGroups(toolNames, Enums, toolGroupService, commandsManager);
}
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-ultrasound-pleura-bline",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "Allows users to annotate ultrasound images with pleura B-line annotations.",
"author": "OHIF",
"license": "MIT",
@@ -29,8 +29,8 @@
},
"dependencies": {
"@babel/runtime": "7.29.7",
"@cornerstonejs/core": "5.1.3",
"@cornerstonejs/tools": "5.1.3",
"@cornerstonejs/core": "5.4.13",
"@cornerstonejs/tools": "5.4.13",
"@ohif/core": "workspace:*",
"@ohif/extension-cornerstone-dicom-sr": "workspace:*",
"@ohif/extension-ultrasound-pleura-bline": "workspace:*",
+1 -1
View File
@@ -124,5 +124,5 @@
"git add"
]
},
"version": "3.13.0-beta.115"
"version": "3.13.0-beta.121"
}
+1 -1
View File
@@ -7,5 +7,5 @@
#
PUBLIC_URL=/
APP_CONFIG=config/default.js
# Can choose a default app config, but this over-rides dev scripts: APP_CONFIG=config/default.js
USE_HASH_ROUTER=false
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/app",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"productVersion": "3.4.0",
"description": "OHIF Viewer",
"author": "OHIF Contributors",
@@ -51,7 +51,7 @@
"@cornerstonejs/codec-libjpeg-turbo-8bit": "1.2.2",
"@cornerstonejs/codec-openjpeg": "1.3.0",
"@cornerstonejs/codec-openjph": "2.4.7",
"@cornerstonejs/dicom-image-loader": "5.1.3",
"@cornerstonejs/dicom-image-loader": "5.4.13",
"@emotion/serialize": "1.3.3",
"@ohif/core": "workspace:*",
"@ohif/i18n": "workspace:*",
@@ -62,7 +62,7 @@
"classnames": "2.5.1",
"core-js": "3.45.1",
"cornerstone-math": "0.1.10",
"dcmjs": "0.49.4",
"dcmjs": "0.52.0",
"detect-gpu": "4.0.50",
"dicom-parser": "1.8.21",
"file-loader": "6.2.0",
+3 -3
View File
@@ -28,9 +28,9 @@ window.config = {
// - mode: applied (Mode) on each mode enter — `*` (general) first,
// then a block keyed by the mode id / routeName.
customizationService: {
// Pulls in platform/app/public/customizations/patientBirthDate.jsonc, which
// adds a "Birth Date" column to the WorkList study list (global phase).
requires: ['patientBirthDate'],
// Pulls in platform/app/public/customizations/worklist/patientBirthDate.jsonc,
// which adds a "Birth Date" column to the WorkList study list (global phase).
requires: ['worklist/patientBirthDate'],
// The previous (legacy-array) customizations, now in the explicit `global`
// phase. A `global` block accepts the same input as setCustomizations: an
+6 -2
View File
@@ -33,11 +33,10 @@ window.config = {
// are never executed. Example (left disabled here on purpose):
//
// customizationUrlPrefixes: {
// default: './customizations/', // ?customization=ctPresets
// default: './customizations/', // ?customization=tools/ctPresets
// '/remote/': 'https://cdn.example.com/ohif-custom/', // ?customization=/remote/siteA
// },
// ----------------------------------------------------------------------------
showStudyList: true,
// some windows systems have issues with more than 3 web workers
maxNumberOfWebWorkers: 3,
@@ -80,6 +79,11 @@ window.config = {
supportsFuzzyMatching: true,
supportsWildcard: true,
staticWado: true,
// Multiframe SEG loads fetch the whole instance as a single Part 10
// object by default and wait for it: the per-frame endpoint is
// efficient, but SEG frames are so small and numerous that one bulk
// fetch beats hundreds of tiny requests. Per-frame loading is the
// exception — set loadMultiframeAsPart10: false here to force it.
singlepart: 'bulkdata,video',
bulkDataURI: {
enabled: true,
+9 -6
View File
@@ -3,23 +3,26 @@
// Local development configuration.
//
// This is the default config for the dev server (`pnpm run dev`, `dev:fast`,
// `start`). Like config/netlify.js it is full-featured — every data source is
// enabled and the `?customization=` URL feature is ON via
// `customizationUrlPrefixes` — so the whole app can be exercised locally. The
// locked-down config/default.js is what a plain production build emits instead.
// `start`). It is intentionally kept at parity with config/netlify.js (the
// public demo deploy): every data source is enabled, the `?customization=` URL
// feature is ON via `customizationUrlPrefixes`, and the same startup
// `customizationService` modules are loaded — so the whole app, including
// customizations, can be exercised locally exactly as it runs on the demo.
// The locked-down config/default.js is what a plain production build emits
// instead.
window.config = {
name: 'config/dev.js',
routerBasename: null,
// whiteLabeling: {},
extensions: [],
modes: [],
customizationService: {},
customizationService: ['@ohif/extension-default.customizationModule.theme'],
// URL-driven customizations (?customization=). The `default` prefix (no
// slashes) is used for values without a leading slash; every other prefix
// must start AND end with a slash and matches the leading `/segment/` of the
// value. Files are fetched and parsed as JSONC data — never executed.
// e.g. ?customization=ctPresets -> ./customizations/ctPresets.jsonc
// e.g. ?customization=tools/ctPresets -> ./customizations/tools/ctPresets.jsonc
customizationUrlPrefixes: {
default: './customizations/',
},
+1 -1
View File
@@ -21,7 +21,7 @@ window.config = {
extensions: [],
modes: ['@ohif/mode-test'],
// Allow the `default` prefix so e2e specs can exercise `?customization=` (e.g.
// Customization.spec.ts loads `?customization=veterinaryOverlay`).
// Customization.spec.ts loads `?customization=veterinary/veterinaryOverlay`).
customizationUrlPrefixes: {
default: './customizations/',
},
+1 -1
View File
@@ -17,7 +17,7 @@ window.config = {
// slashes) is used for values without a leading slash; every other prefix
// must start AND end with a slash and matches the leading `/segment/` of the
// value. Files are fetched and parsed as JSONC data — never executed.
// e.g. ?customization=ctPresets -> ./customizations/ctPresets.jsonc
// e.g. ?customization=tools/ctPresets -> ./customizations/tools/ctPresets.jsonc
customizationUrlPrefixes: {
default: './customizations/',
},
@@ -0,0 +1,400 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>OHIF URL Customizations</title>
<style>
:root {
color-scheme: light dark;
--bg: #f5f6f8;
--card: #ffffff;
--card-border: #e3e6ea;
--text: #1a1f27;
--muted: #5c6774;
--accent: #2563eb;
--accent-contrast: #ffffff;
--code-bg: #eef1f5;
--tag-bg: #e6edff;
--tag-text: #2952cc;
--bar-bg: #ffffff;
}
/* This catalog page follows the OS light/dark preference automatically. */
@media (prefers-color-scheme: dark) {
:root {
--bg: #0e1116;
--card: #171b22;
--card-border: #2a3038;
--text: #e6e9ee;
--muted: #99a3b0;
--accent: #4f8cff;
--accent-contrast: #0e1116;
--code-bg: #0b0e13;
--tag-bg: #1c2740;
--tag-text: #8fb2ff;
--bar-bg: #12161c;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
background: var(--bg);
color: var(--text);
line-height: 1.5;
padding-bottom: 160px;
}
.wrap { max-width: 900px; margin: 0 auto; padding: 32px 20px 20px; }
.topbar { display: flex; align-items: flex-start; gap: 16px; }
.topbar .titles { flex: 1; min-width: 0; }
.theme-picker { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
.theme-picker label { font-size: 0.8rem; color: var(--muted); }
.theme-picker select {
background: var(--card); border: 1px solid var(--card-border); border-radius: 8px;
padding: 7px 10px; color: var(--text); font-size: 0.85rem; cursor: pointer;
}
header h1 { font-size: 1.7rem; margin: 0 0 6px; }
header p { color: var(--muted); margin: 0 0 8px; max-width: 62ch; }
code {
background: var(--code-bg);
border-radius: 4px;
padding: 1px 6px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.85em;
}
.group { margin-top: 28px; }
.group-head { display: flex; align-items: baseline; gap: 10px; margin-bottom: 4px; }
.group-head h2 { font-size: 1.15rem; margin: 0; }
.group-head .dir { color: var(--muted); font-size: 0.85rem; }
.group-head .toggle {
margin-left: auto; background: none; border: none; color: var(--accent);
cursor: pointer; font-size: 0.82rem; padding: 2px 4px;
}
.group-desc { color: var(--muted); font-size: 0.9rem; margin: 0 0 12px; }
.card {
display: flex; gap: 12px; align-items: flex-start;
background: var(--card); border: 1px solid var(--card-border);
border-radius: 10px; padding: 14px 16px; margin-bottom: 10px;
cursor: pointer; transition: border-color .12s ease;
}
.card:hover { border-color: var(--accent); }
.card input { margin-top: 3px; width: 17px; height: 17px; accent-color: var(--accent); cursor: pointer; }
.card .body { flex: 1; min-width: 0; }
.card .title-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.card .name { font-weight: 600; }
.card .param { color: var(--muted); font-size: 0.8rem; }
.card .desc { color: var(--muted); font-size: 0.9rem; margin: 4px 0 0; }
.tag {
font-size: 0.7rem; font-weight: 600; letter-spacing: .02em;
background: var(--tag-bg); color: var(--tag-text);
padding: 2px 7px; border-radius: 999px; text-transform: uppercase;
}
.launch {
position: fixed; bottom: 0; left: 0; right: 0;
background: var(--bar-bg); border-top: 1px solid var(--card-border);
box-shadow: 0 -4px 16px rgba(0,0,0,0.08);
}
.launch-inner { max-width: 900px; margin: 0 auto; padding: 14px 20px; }
.launch-row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.launch-label { font-size: 0.8rem; color: var(--muted); }
.url-box {
flex: 1; min-width: 240px;
background: var(--code-bg); border: 1px solid var(--card-border); border-radius: 8px;
padding: 9px 12px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.82rem; color: var(--text); overflow-x: auto; white-space: nowrap;
}
.base-input {
background: var(--card); border: 1px solid var(--card-border); border-radius: 8px;
padding: 8px 10px; color: var(--text); font-size: 0.85rem; width: 130px;
}
button.btn {
border: none; border-radius: 8px; padding: 9px 16px; font-size: 0.88rem; font-weight: 600;
cursor: pointer;
}
.btn-primary { background: var(--accent); color: var(--accent-contrast); }
.btn-primary[aria-disabled='true'] { opacity: .45; pointer-events: none; }
.btn-ghost { background: transparent; color: var(--accent); border: 1px solid var(--card-border); }
.count { font-size: 0.8rem; color: var(--muted); }
a { color: var(--accent); }
</style>
</head>
<body>
<div class="wrap">
<header>
<div class="topbar">
<div class="titles">
<h1>URL Customizations</h1>
</div>
<div class="theme-picker">
<label for="viewer-theme">Viewer theme</label>
<select id="viewer-theme" title="OHIF viewer theme — added as ?theme= to the launch URL">
<optgroup label="Tonal (surfaces carry the theme hue)">
<option value="default">OHIF Blue (default)</option>
<option value="orchid">Orchid</option>
<option value="arctic">Arctic</option>
<option value="verdant">Verdant</option>
</optgroup>
<optgroup label="Neutral (desaturated + one accent)">
<option value="midnight">Midnight</option>
<option value="slate">Slate</option>
<option value="deep">Deep</option>
</optgroup>
</select>
</div>
</div>
<p>
These are the example <code>?customization=</code> profiles shipped under
<code>platform/app/public/customizations/</code>, grouped by area. Each file is fetched as
JSONC <strong>data</strong> (never executed) and applied at startup. Tick the ones you want,
optionally pick a viewer theme (added as <code>?theme=</code>), then launch the viewer or copy
the generated query string onto any viewer URL. Multiple profiles are comma-separated and
applied in order.
</p>
<p style="font-size: 0.85rem">
See the
<a href="https://docs.ohif.org/platform/services/customization-service/specificCustomizations">
customization docs</a>
for how to author your own. The prefix allowlist is set by
<code>customizationUrlPrefixes</code> in the app config.
</p>
</header>
<main id="groups"></main>
</div>
<div class="launch">
<div class="launch-inner">
<div class="launch-row" style="margin-bottom: 10px">
<span class="launch-label">Viewer base</span>
<input
id="base"
class="base-input"
value="../"
title="Base viewer URL the customization query is appended to (relative to this page)"
/>
<span class="count" id="count">0 selected</span>
<button class="btn btn-ghost" id="clear" type="button">Clear all</button>
<button class="btn btn-ghost" id="copy" type="button">Copy URL</button>
<a class="btn btn-primary" id="launch" href="#" aria-disabled="true">Launch viewer &rarr;</a>
</div>
<div class="launch-row">
<div class="url-box" id="url">Select one or more profiles above&hellip;</div>
</div>
</div>
</div>
<script>
// Catalog of shipped URL customizations, grouped by area/folder. The
// `value` is the `?customization=` token (folder-relative path, no `.jsonc`).
const CATALOG = [
{
dir: 'tools/',
title: 'Tools & presets',
desc: 'General viewport tools and presets. These apply globally (every mode).',
items: [
{
value: 'tools/ctPresets',
name: 'CT window/level presets',
scope: 'global',
desc: 'Replaces the CT presets in the window-level menu with a site-specific set (soft tissue, lung, angio, bone). Other modalities keep their defaults.',
},
{
value: 'tools/smoothRotate',
name: 'Smooth Rotate button',
scope: 'global',
desc: 'Adds a "Smooth Rotate" button to the More Tools menu that activates the PlanarRotate tool — drag to rotate the image freely (unlike the fixed 90° Rotate Right).',
},
{
value: 'tools/measurementLabels',
name: 'Predefined measurement labels',
scope: 'global',
desc: 'Prompts for a label from a fixed, exclusive list (Head, Shoulder, Knee, Toe) whenever a measurement is created.',
},
],
},
{
dir: 'worklist/',
title: 'Study list',
desc: 'Customizations for the WorkList / study browser.',
items: [
{
value: 'worklist/patientBirthDate',
name: 'Birth Date column',
scope: 'global',
desc: 'Adds a "Birth Date" column to the study list, immediately after the Patient column. Shipped configs load this by default via customizationService.requires.',
},
],
},
{
dir: 'segmentation/',
title: 'Segmentation',
desc: 'Per-mode composition of the segmentation capability packs.',
items: [
{
value: 'segmentation/segmentationEditing',
name: 'Segmentation editing',
scope: 'basic / longitudinal',
desc: 'Adds the segmentation editing toolbar, tools, and panels to the basic and longitudinal (viewer) modes, and enables editing in the segmentation panel.',
},
{
value: 'segmentation/segmentationAnnotationTools',
name: 'Annotation tools in segmentation mode',
scope: 'segmentation',
desc: 'Enables the measurement/annotation tools (Length, Bidirectional, ROIs, freehand, spline, livewire) inside the segmentation mode and adds the measurement panel.',
},
],
},
{
dir: 'veterinary/',
title: 'Veterinary',
desc: 'Veterinary-oriented overlay and a chaining profile that pulls it in.',
items: [
{
value: 'veterinary/veterinary',
name: 'Veterinary profile',
scope: 'global',
desc: 'Chaining profile — declares requires: ["veterinary/veterinaryOverlay"], so selecting this one alone pulls in and applies the overlay first.',
},
{
value: 'veterinary/veterinaryOverlay',
name: 'Veterinary viewport overlay',
scope: 'global',
desc: 'Overrides the viewport overlay with a veterinary-style demographics layout (patient/ID/date on the left, species/breed on the right).',
},
],
},
];
const groupsEl = document.getElementById('groups');
const urlEl = document.getElementById('url');
const launchEl = document.getElementById('launch');
const countEl = document.getElementById('count');
const baseEl = document.getElementById('base');
const viewerThemeEl = document.getElementById('viewer-theme');
CATALOG.forEach((group, gi) => {
const section = document.createElement('section');
section.className = 'group';
section.innerHTML =
'<div class="group-head">' +
'<h2>' + group.title + '</h2>' +
'<span class="dir"><code>' + group.dir + '</code></span>' +
'<button class="toggle" type="button" data-group="' + gi + '">Select all</button>' +
'</div>' +
'<p class="group-desc">' + group.desc + '</p>';
group.items.forEach(item => {
const label = document.createElement('label');
label.className = 'card';
label.innerHTML =
'<input type="checkbox" value="' + item.value + '" />' +
'<span class="body">' +
'<span class="title-row">' +
'<span class="name">' + item.name + '</span>' +
'<span class="tag">' + item.scope + '</span>' +
'<span class="param"><code>?customization=' + item.value + '</code></span>' +
'</span>' +
'<span class="desc">' + item.desc + '</span>' +
'</span>';
section.appendChild(label);
});
groupsEl.appendChild(section);
});
function selectedValues() {
return Array.from(document.querySelectorAll('input[type=checkbox]:checked')).map(c => c.value);
}
// Builds the launch URL from the selected profiles and viewer theme. The
// `theme=` param is only added for a non-default preset (default is the
// viewer's built-in look and needs no param). Returns null when there is
// nothing to launch.
function buildUrl(base, values, theme) {
// Sanitize the DOM-derived inputs before they reach the launch href.
// Customization tokens are `folder/name` segments, so allow word chars,
// dot, dash and slash only; the theme is a plain preset id. Anything with
// query metacharacters or a URL scheme (e.g. `javascript:`) is dropped.
const TOKEN = /^[\w.-]+(?:\/[\w.-]+)*$/;
const safeValues = values.filter(v => TOKEN.test(v));
const safeTheme = /^[\w.-]+$/.test(theme || '') ? theme : 'default';
if (!safeValues.length && (!safeTheme || safeTheme === 'default')) {
return null;
}
// Resolve the (hand-typed) base against the current page and require an
// http(s) target, so the base can never turn the href into a
// javascript:/data: URL. searchParams.set() encodes the values safely.
let parsed;
try {
parsed = new URL(base, window.location.href);
} catch (_) {
return null;
}
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
return null;
}
if (safeValues.length) {
parsed.searchParams.set('customization', safeValues.join(','));
}
if (safeTheme && safeTheme !== 'default') {
parsed.searchParams.set('theme', safeTheme);
}
return parsed.toString();
}
function refresh() {
const values = selectedValues();
countEl.textContent = values.length + ' selected';
const url = buildUrl(baseEl.value.trim() || '../', values, viewerThemeEl.value);
if (!url) {
urlEl.textContent = 'Select one or more profiles, or a viewer theme, above…';
launchEl.setAttribute('aria-disabled', 'true');
launchEl.removeAttribute('href');
return;
}
urlEl.textContent = url;
launchEl.href = url;
launchEl.setAttribute('aria-disabled', 'false');
}
groupsEl.addEventListener('change', refresh);
baseEl.addEventListener('input', refresh);
viewerThemeEl.addEventListener('change', refresh);
groupsEl.addEventListener('click', e => {
const btn = e.target.closest('.toggle');
if (!btn) return;
e.preventDefault();
const section = btn.closest('.group');
const boxes = section.querySelectorAll('input[type=checkbox]');
const allChecked = Array.from(boxes).every(b => b.checked);
boxes.forEach(b => (b.checked = !allChecked));
btn.textContent = allChecked ? 'Select all' : 'Clear';
refresh();
});
document.getElementById('clear').addEventListener('click', () => {
document.querySelectorAll('input[type=checkbox]').forEach(b => (b.checked = false));
document.querySelectorAll('.toggle').forEach(t => (t.textContent = 'Select all'));
refresh();
});
document.getElementById('copy').addEventListener('click', async () => {
const text = buildUrl(baseEl.value.trim() || '../', selectedValues(), viewerThemeEl.value);
if (!text) return;
try {
await navigator.clipboard.writeText(text);
const b = document.getElementById('copy');
const prev = b.textContent;
b.textContent = 'Copied!';
setTimeout(() => (b.textContent = prev), 1200);
} catch (_) {
/* clipboard unavailable — the URL is visible in the box to copy manually */
}
});
refresh();
</script>
</body>
</html>
@@ -0,0 +1,19 @@
// URL-loaded customization: segmentation/binary
//
// Stores exported/saved DICOM SEG objects as a BINARY Segmentation — SOP Class
// 1.2.840.10008.5.1.4.1.1.66.4 (one frame per segment) — instead of the OHIF
// default Label Map Segmentation 1.2.840.10008.5.1.4.1.1.66.7. Binary SEG is
// broadly compatible with existing PACS/viewers; Label Map was only added to
// DICOM in 2024 and many back ends reject it.
//
// Applied in the `global` phase so it overrides the default registered by the
// cornerstone-dicom-seg extension. A data source may still override this per
// back end via `configuration.segmentation.store.defaultMode`.
//
// Load it with `?customization=segmentation/binary` (combine with
// `&customization=segmentation/uncompressed` to also drop RLE compression).
{
"global": {
"segmentation.store.defaultMode": { "$set": "bitmap" }
}
}
@@ -0,0 +1,48 @@
// URL-loaded customization: segmentationAnnotationTools
//
// Enables the measurement/annotation tools inside the segmentation mode by
// composing capability packs the cornerstone extension already exports:
//
// - the annotation buttons are already registered by the mode (its
// `toolbarButtons` composition includes `cornerstone.toolbarButtons`), so
// the toolbar only needs a `MeasurementTools` section added to the primary
// bar,
// - the annotation tools themselves are added to the mode's tool groups via
// `cornerstone.annotationTools`,
// - and the measurement panel is appended so annotations can be reviewed.
//
// Everything is per-mode, so it all lives in the `mode` phase keyed by the
// segmentation mode's route name. The section tweak patches the mode's toolbar
// layout pack at Mode scope (reset on mode exit), and the tools/panels `$push`
// onto the values the mode seeds on enter.
//
// Load it with `?customization=segmentation/segmentationAnnotationTools`.
{
"mode": {
"segmentation": {
"cornerstone.segmentationModeToolbarSections": {
"primary": { "$unshift": ["MeasurementTools"] },
"MeasurementTools": {
"$set": [
"Length",
"Bidirectional",
"ArrowAnnotate",
"EllipticalROI",
"RectangleROI",
"CircleROI",
"PlanarFreehandROI",
"SplineROI",
"LivewireContour"
]
}
},
"toolGroupAdditions": {
"default": { "$push": [{ "$reference": "cornerstone.annotationTools" }] },
"mpr": { "$push": [{ "$reference": "cornerstone.annotationTools" }] }
},
"rightPanels": {
"$push": ["@ohif/extension-cornerstone.panelModule.panelMeasurement"]
}
}
}
}
@@ -0,0 +1,59 @@
// URL-loaded customization: segmentationEditing
//
// Adds segmentation editing to the basic and longitudinal (viewer) modes by
// composing the capability packs the cornerstone extension already exports:
//
// - the segmentation editing toolbar buttons and toolbox section wiring
// (`cornerstone.segmentationToolbarButtons` / `cornerstone.segmentationToolbarSections`),
// - the segmentation editing tools for the modes' tool groups
// (`cornerstone.segmentationTools`),
// - the segmentation panels that render the editing toolbox
// (`panelSegmentationWithToolsLabelMap` / `panelSegmentationWithToolsContour`),
// - and enables editing in the segmentation panel.
//
// Composition is per-mode, so every patch lives in the `mode` phase keyed by
// the target mode's route name (`basic`, `viewer`). Each mode seeds its own
// `toolbarButtons` / `toolbarSections` / `toolGroupAdditions` / `rightPanels`
// onto the Mode scope on enter; these blocks `$push` / `$set` on top of that,
// exactly like the panel swaps. No app-wide `global` keys are needed.
//
// Load it with `?customization=segmentation/segmentationEditing`.
{
"mode": {
"basic": {
"toolbarButtons": { "$push": [{ "$reference": "cornerstone.segmentationToolbarButtons" }] },
"toolbarSections": { "$push": [{ "$reference": "cornerstone.segmentationToolbarSections" }] },
"toolGroupAdditions": {
"default": { "$push": [{ "$reference": "cornerstone.segmentationTools" }] },
"mpr": { "$push": [{ "$reference": "cornerstone.segmentationTools" }] }
},
// The basic/longitudinal modes seed `panelSegmentation.disableEditing: true`
// from their own `modeCustomizations`; this `mode` phase value is applied
// after that (both Mode scope) and enables editing.
"panelSegmentation.disableEditing": { "$set": false },
"rightPanels": {
"$set": [
"@ohif/extension-cornerstone.panelModule.panelSegmentationWithToolsLabelMap",
"@ohif/extension-cornerstone.panelModule.panelSegmentationWithToolsContour",
"@ohif/extension-cornerstone.panelModule.panelMeasurement"
]
}
},
"viewer": {
"toolbarButtons": { "$push": [{ "$reference": "cornerstone.segmentationToolbarButtons" }] },
"toolbarSections": { "$push": [{ "$reference": "cornerstone.segmentationToolbarSections" }] },
"toolGroupAdditions": {
"default": { "$push": [{ "$reference": "cornerstone.segmentationTools" }] },
"mpr": { "$push": [{ "$reference": "cornerstone.segmentationTools" }] }
},
"panelSegmentation.disableEditing": { "$set": false },
"rightPanels": {
"$set": [
"@ohif/extension-cornerstone.panelModule.panelSegmentationWithToolsLabelMap",
"@ohif/extension-cornerstone.panelModule.panelSegmentationWithToolsContour",
"@ohif/extension-measurement-tracking.panelModule.trackedMeasurements"
]
}
}
}
}
@@ -0,0 +1,19 @@
// URL-loaded customization: segmentation/uncompressed
//
// Stores exported/saved DICOM SEG objects UNCOMPRESSED — Explicit VR Little
// Endian (1.2.840.10008.1.2.1) — instead of the OHIF default of RLE Lossless
// (1.2.840.10008.1.2.5). Use this for back ends that reject compressed SEG
// PixelData.
//
// Applied in the `global` phase. OHIF already defaults to RLE Lossless; this
// customization opts into uncompressed Explicit VR Little Endian instead. A data
// source may still override per back end via
// `configuration.segmentation.store.transferSyntaxUID`.
//
// Load it with `?customization=segmentation/uncompressed` (combine with
// `&customization=segmentation/binary` to also switch the SOP class).
{
"global": {
"segmentation.store.transferSyntaxUID": { "$set": "1.2.840.10008.1.2.1" }
}
}
@@ -4,7 +4,7 @@
// site-specific set (key: `cornerstone.windowLevelPresets`). Other modalities
// keep their defaults because only the `CT` entry is overridden.
//
// Load it with `?customization=ctPresets`.
// Load it with `?customization=tools/ctPresets`.
{
"global": {
"cornerstone.windowLevelPresets": {
@@ -4,7 +4,7 @@
// is created (key: `measurementLabels`). `labelOnMeasure` triggers the prompt on
// creation and `exclusive` restricts entries to the provided items.
//
// Load it with `?customization=measurementLabels`.
// Load it with `?customization=tools/measurementLabels`.
{
"global": {
"measurementLabels": {
@@ -8,7 +8,7 @@
// extension (`cornerstone.toolbarButtons` / `cornerstone.toolbarSections`) using
// immutability-helper `$push` commands, so the built-in buttons are preserved.
//
// Load it with `?customization=smoothRotate`.
// Load it with `?customization=tools/smoothRotate`.
{
"global": {
"cornerstone.toolbarButtons": {
@@ -1,5 +0,0 @@
// Example chaining module: ensures `veterinaryOverlay` is loaded and applied
// first when using `?customization=veterinary` alone.
{
"requires": ["veterinaryOverlay"]
}
@@ -0,0 +1,5 @@
// Example chaining module: ensures `veterinary/veterinaryOverlay` is loaded and
// applied first when using `?customization=veterinary/veterinary` alone.
{
"requires": ["veterinary/veterinaryOverlay"]
}
@@ -2,7 +2,7 @@
//
// Demonstrates a runtime-loaded customization that overrides the default
// viewport overlay with a veterinary-style demographics layout. Loaded via
// `?customization=veterinaryOverlay` (see CustomizationService URL handling).
// `?customization=veterinary/veterinaryOverlay` (see CustomizationService URL handling).
//
// Uses the same `global`-at-top-level shape as the cornerstone overlay samples
// and `inheritsFrom: 'ohif.overlayItem'` on each row, matching
@@ -39,14 +39,14 @@
{
"id": "PatientSpecies",
"inheritsFrom": "ohif.overlayItem",
"attribute": "PatientSpecies",
"attribute": "PatientSpeciesDescription",
"label": "Species",
"title": "Patient species"
},
{
"id": "PatientBreed",
"inheritsFrom": "ohif.overlayItem",
"attribute": "PatientBreed",
"attribute": "PatientBreedDescription",
"label": "Breed",
"title": "Patient breed"
}
@@ -8,8 +8,8 @@
// tag 00100030).
//
// This applies in the `global` phase, so it is in place before the WorkList
// renders. Load it with `?customization=patientBirthDate`, or pull it in from
// `appConfig.customizationService.requires`.
// renders. Load it with `?customization=worklist/patientBirthDate`, or pull it in
// from `appConfig.customizationService.requires`.
{
"global": {
"workList.columns": {
+10 -5
View File
@@ -129,12 +129,17 @@ function App({
[ShepherdJourneyProvider],
];
// Loop through and register each of the service providers registered with the ServiceProvidersManager.
const providersFromManager = Object.entries(serviceProvidersManager.providers);
// Providers registered with the ServiceProvidersManager are inserted ahead of
// the dialog/modal providers: dialog and modal content renders at those
// providers' own level (as a sibling of their children, not inside the route
// tree), so any context a registered provider supplies must already be in
// scope there.
const providersFromManager = Object.entries(serviceProvidersManager.providers).map(
([serviceName, provider]) => [provider, { service: servicesManager.services[serviceName] }]
);
if (providersFromManager.length > 0) {
providersFromManager.forEach(([serviceName, provider]) => {
providers.push([provider, { service: servicesManager.services[serviceName] }]);
});
const dialogIndex = providers.findIndex(([component]) => component === DialogProvider);
providers.splice(dialogIndex, 0, ...providersFromManager);
}
const CombinedProviders = ({ children }) => Compose({ components: providers, children });
+53 -21
View File
@@ -93,13 +93,31 @@ async function appInit(appConfigOrFunc, defaultExtensions, defaultModes) {
const loadedExtensions = await loadModules([...defaultExtensions, ...appConfig.extensions]);
const { customizationService } = servicesManager.services;
if (!appConfig.modes) {
throw new Error('No modes are defined! Check your app-config.js');
}
// Load the mode modules and register the customizations they carry (plain
// `customizationId -> value` maps on the mode definition) at Default scope
// BEFORE the bootstrap phase applies, so bootstrap / `?customization=`
// modules can modify a mode's registered values before anything reads them.
// The mode *instances* are only created after the global phase (below), so
// they too see any modifications.
const loadedModes = await loadModules([...(appConfig.modes || []), ...defaultModes]);
for (const mode of loadedModes) {
if (mode?.customizations) {
customizationService.addReferences(mode.customizations, customizationService.Scope.Default);
}
}
// Resolve every customization module up front — from
// `appConfig.customizationService.requires` and the `?customization=` URL
// parameter — long before any mode loads, then apply the `bootstrap` phase
// BEFORE extensions register so it is in place while they initialize. Modules
// are only loaded when `appConfig.customizationUrlPrefixes` allows their
// prefix; the feature is off by default, and a value with an unconfigured
// prefix throws here (aborting startup) rather than being silently ignored.
// parameter — then apply the `bootstrap` phase BEFORE extensions register so
// it is in place while they initialize. Modules are only loaded when
// `appConfig.customizationUrlPrefixes` allows their prefix; the feature is
// off by default, and a value with an unconfigured prefix throws here
// (aborting startup) rather than being silently ignored.
await customizationService.loadAndApplyBootstrapCustomizations(extensionManager);
await extensionManager.registerExtensions(loadedExtensions, appConfig.dataSources);
@@ -114,12 +132,6 @@ async function appInit(appConfigOrFunc, defaultExtensions, defaultModes) {
// TODO: We no longer init webWorkers at app level
// TODO: We no longer init the user Manager
if (!appConfig.modes) {
throw new Error('No modes are defined! Check your app-config.js');
}
const loadedModes = await loadModules([...(appConfig.modes || []), ...defaultModes]);
// This is the name for the loaded instance object
appConfig.loadedModes = [];
const modesById = new Set();
@@ -130,19 +142,39 @@ async function appInit(appConfigOrFunc, defaultExtensions, defaultModes) {
}
const { id } = mode;
if (mode.modeFactory) {
// If the appConfig contains configuration for this mode, use it.
const modeConfiguration =
appConfig.modesConfiguration && appConfig.modesConfiguration[id]
? appConfig.modesConfiguration[id]
: {};
mode = await mode.modeFactory({ modeConfiguration, loadModules });
}
if (modesById.has(id)) {
continue;
}
// If the appConfig contains configuration for this mode, use it.
const modeConfiguration =
appConfig.modesConfiguration && appConfig.modesConfiguration[id]
? appConfig.modesConfiguration[id]
: {};
// Mirrors the extension commands path for modes, but registers before the
// mode is instantiated so the commands are usable on the worklist, ahead
// of any mode route being entered. Definitions land in the 'WORKLIST'
// context unless the module (or an individual command) declares its own.
if (typeof mode.getCommandsModule === 'function') {
extensionManager.registerCommandsModule(
mode.getCommandsModule({
appConfig,
commandsManager,
servicesManager,
serviceProvidersManager,
hotkeysManager,
extensionManager,
modeConfiguration,
}),
'WORKLIST'
);
}
if (mode.modeFactory) {
mode = await mode.modeFactory({ modeConfiguration, loadModules });
}
// Prevent duplication
modesById.add(id);
if (!mode || typeof mode !== 'object') {
+65 -3
View File
@@ -97,6 +97,15 @@ export default function ModeRoute({
}
}
// Mode dependency extensions register their customization modules here,
// but `registerExtension` does not merge them into the customization
// service — that otherwise only happens later in
// `extensionManager.onModeEnter`. Merge them now so anything that runs
// before setupRouteInit (e.g. a mode's layoutTemplate) can already read
// the defaults these extensions provide.
// `init` is idempotent — each extension module is merged at most once.
customizationService.init(extensionManager);
if (isMounted.current) {
setExtensionDependenciesLoaded(true);
}
@@ -180,10 +189,19 @@ export default function ModeRoute({
if (isMounted.current) {
const { leftPanels = [], rightPanels = [], ...layoutProps } = layoutData.props;
// Register panels immediately so ViewerLayout's first render sees them.
// ResizablePanelsHook only auto-expands side panels on the initial mount;
// if panels are added later, the viewport grid keeps the wrong width.
// setupRouteInit (below) resets and re-applies them after customizations
// are layered on, so URL/config modules can still modify the lists.
panelService.reset();
panelService.addPanels(panelService.PanelPosition.Left, leftPanels);
panelService.addPanels(panelService.PanelPosition.Right, rightPanels);
// Stash the layout lists for setupRouteInit to seed into the
// `leftPanels` / `rightPanels` customizations.
layoutData.panels = { leftPanels, rightPanels };
// layoutProps contains all props but leftPanels and rightPanels
layoutData.props = layoutProps;
@@ -222,11 +240,55 @@ export default function ModeRoute({
});
// `extensionManager.onModeEnter` resets the customization mode scope via
// `customizationService.onModeEnter`; now layer on the `mode` phase blocks
// for this mode — the general (`*`) block first, then any block keyed by
// this mode's id / routeName so a single mode can override the general one.
// `customizationService.onModeEnter`; the mode scope is then layered
// bottom-up so the final value of every key is decided by scope
// precedence (global > mode > default) and application order alone:
// 1. the mode's own values — its layout panel lists, seeded as the
// standard `leftPanels` / `rightPanels` customizations;
// its toolbar/tool-group composition, seeded as the plain
// `toolbarButtons` / `toolbarSections` / `toolGroupAdditions`
// customizations (resolved to concrete definitions later, when the
// mode's `onModeEnter` registers the toolbar); and its
// `modeCustomizations` block (declared as data on the mode
// instance, usually as a customization name registered at default
// scope when the mode loaded, so bootstrap/global customizations
// can modify the block itself before it is applied);
// 2. the app config / URL `mode` phase blocks — the general (`*`)
// block first, then any block keyed by this mode's id / routeName.
const { leftPanels = [], rightPanels = [] } = layoutTemplateData.current.panels ?? {};
customizationService.setCustomizations({
leftPanels,
rightPanels,
toolbarButtons: mode.toolbarButtons ?? [],
toolbarSections: mode.toolbarSections ?? [],
toolGroupAdditions: mode.toolGroupAdditions ?? {},
});
const modeCustomizations =
typeof mode.modeCustomizations === 'string'
? customizationService.getCustomization(mode.modeCustomizations)
: mode.modeCustomizations;
if (modeCustomizations) {
customizationService.setCustomizations(modeCustomizations);
}
customizationService.applyModeCustomizations([mode.id, mode.routeName]);
// Re-apply panels only when customizations changed the lists. When they
// match the layout, the panels registered in retrieveLayoutData are left
// in place so ViewerLayout's ResizablePanelsHook keeps the correct sizes
// from its one-time initial expand.
const resolvedLeftPanels = customizationService.getValue('leftPanels') ?? [];
const resolvedRightPanels = customizationService.getValue('rightPanels') ?? [];
const panelsChanged =
JSON.stringify(resolvedLeftPanels) !== JSON.stringify(leftPanels) ||
JSON.stringify(resolvedRightPanels) !== JSON.stringify(rightPanels);
if (panelsChanged) {
panelService.reset();
panelService.addPanels(panelService.PanelPosition.Left, resolvedLeftPanels);
panelService.addPanels(panelService.PanelPosition.Right, resolvedRightPanels);
}
// use the URL hangingProtocolId if it exists, otherwise use the one
// defined in the mode configuration
const hangingProtocolIdToUse = hangingProtocolService.getProtocolById(
+41 -3
View File
@@ -1,10 +1,18 @@
import React, { useEffect, useMemo, useState } from 'react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useAppConfig } from '@state';
import type { RunInput } from '@ohif/core/src/classes/CommandsManager';
import { preserveQueryParameters } from '../../utils/preserveQueryParameters';
import { useStudyListStateSync, useWorkListToolbarActions } from '../../hooks';
import { StudyList, Icons, InvestigationalUseDialog, type StudyRow } from '@ohif/ui-next';
import {
StudyList,
Icons,
InvestigationalUseDialog,
useSessionStorage,
type StudyRow,
type OnStudyDoubleClick,
} from '@ohif/ui-next';
import { StudyListSettingsPopover } from './StudyListSettingsPopover';
import { SidePanelPreview } from './SidePanelPreview';
@@ -26,6 +34,7 @@ export default function WorkList({
onRefresh,
servicesManager,
extensionManager,
commandsManager,
}: Props) {
const [appConfig] = useAppConfig();
const { customizationService } = servicesManager.services;
@@ -45,7 +54,35 @@ export default function WorkList({
const defaultSorting = useMemo(() => [{ id: 'studyDateTime', desc: true }], []);
const [selected, setSelected] = useState<StudyRow | null>(null);
const [isPreviewOpen, setPreviewOpen] = useState(true);
// Persist the preview panel open/closed state so it survives navigating
// into a study and back. The hook only handles objects, hence the wrapper.
const [previewState, updatePreviewState] = useSessionStorage({
key: 'studyList.previewOpen',
defaultValue: { open: true },
clearOnUnload: false,
});
const isPreviewOpen = previewState.open !== false;
const setPreviewOpen = useCallback(
(open: boolean) => updatePreviewState({ open }),
[updatePreviewState]
);
// `workList.onStudyDoubleClick` is the command (or command list) run when a
// study row is double-clicked — by default `launchDefaultMode`, which
// launches the default workflow, falling back to the first applicable one.
// The study and its applicable workflows are merged into the command options
// at call time, so an override only needs to name a command and any static
// options (e.g. a specific `workflowId`).
const studyDoubleClickCommand = customizationService.getCustomization(
'workList.onStudyDoubleClick'
) as RunInput;
const onStudyDoubleClick = useCallback<OnStudyDoubleClick>(
(study, { defaultWorkflow, workflows }) => {
commandsManager.run(studyDoubleClickCommand, { study, defaultWorkflow, workflows });
},
[commandsManager, studyDoubleClickCommand]
);
const columns = useMemo(() => {
// `workList.columns` is registered as a value (StudyList.defaultColumns) and
@@ -122,6 +159,7 @@ export default function WorkList({
)
}
title={'Study List'}
onStudyDoubleClick={studyDoubleClickCommand ? onStudyDoubleClick : undefined}
onSelectionChange={sel => setSelected((sel as StudyRow[])[0] ?? null)}
toolbarLeftComponent={logoComponent}
toolbarRightActionsComponent={toolbarActions}
+1 -1
View File
@@ -131,7 +131,7 @@ const createRoutes = ({
path: '/',
children: DataSourceWrapper,
private: true,
props: { children: WorkListComponent, servicesManager, extensionManager },
props: { children: WorkListComponent, servicesManager, extensionManager, commandsManager },
};
const customRoutes = customizationService.getCustomization('routes.customRoutes');
@@ -13,6 +13,14 @@ describe('preserveQueryParameters', () => {
expect(out.getAll('configUrl')).toEqual(['foo.js']);
});
it('preserves the theme key across mode navigation', () => {
const current = new URLSearchParams();
current.append('theme', 'arctic');
const out = new URLSearchParams();
preserveQueryParameters(out, undefined, current);
expect(out.get('theme')).toBe('arctic');
});
it('preserves all repeated values for the customization key', () => {
const current = new URLSearchParams();
current.append('customization', 'a');
@@ -12,6 +12,7 @@ export const preserveKeys = [
'screenNumber',
'hangingProtocolId',
'customization',
'theme',
];
function preserveKey(query: URLSearchParams, current: URLSearchParams, key: string) {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/cli",
"version": "3.13.0-beta.115",
"version": "3.13.0-beta.121",
"description": "A CLI to bootstrap new OHIF extension or mode",
"type": "module",
"main": "src/index.js",
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff. Show more