feat(actions): simplify action corner api through the toolbarService (#5033)
This commit is contained in:
1 parent
f71b88e639
commit
7c15bb8901
246 files changed
+7930
-4270
No files matched your search
@@ -1,4 +1,8 @@
|
||||
export * from './useViewportActionCorners';
|
||||
export * from './useActiveViewportSegmentationRepresentations';
|
||||
export * from './useMeasurements';
|
||||
export * from './useSegmentations';
|
||||
export * from './useViewportSegmentations';
|
||||
export * from './useViewportHover';
|
||||
export * from './useViewportDisplaySets';
|
||||
export * from './useMeasurementTracking';
|
||||
export * from './useViewportRendering';
|
||||
@@ -1,216 +1,14 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import debounce from 'lodash.debounce';
|
||||
import { roundNumber } from '@ohif/core/src/utils';
|
||||
import {
|
||||
SegmentationData,
|
||||
SegmentationRepresentation,
|
||||
} from '../services/SegmentationService/SegmentationService';
|
||||
import { useViewportGrid } from '@ohif/ui-next';
|
||||
import { useViewportSegmentations } from './useViewportSegmentations';
|
||||
|
||||
const excludedModalities = ['SM', 'OT', 'DOC', 'ECG'];
|
||||
function useActiveViewportSegmentationRepresentations() {
|
||||
const [viewportGrid] = useViewportGrid();
|
||||
|
||||
function mapSegmentationToDisplay(segmentation, customizationService) {
|
||||
const { label, segments } = segmentation;
|
||||
const viewportId = viewportGrid?.activeViewportId;
|
||||
|
||||
// Get the readable text mapping once
|
||||
const readableTextMap = customizationService.getCustomization('panelSegmentation.readableText');
|
||||
const segmentations = useViewportSegmentations({ viewportId });
|
||||
|
||||
// Helper function to recursively map cachedStats to readable display text
|
||||
function mapStatsToDisplay(stats, indent = 0) {
|
||||
const primary = [];
|
||||
const indentation = ' '.repeat(indent);
|
||||
|
||||
for (const key in stats) {
|
||||
if (Object.prototype.hasOwnProperty.call(stats, key)) {
|
||||
const value = stats[key];
|
||||
const readableText = readableTextMap?.[key];
|
||||
|
||||
if (!readableText) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
||||
// Add empty row before category (except for the first category)
|
||||
if (primary.length > 0) {
|
||||
primary.push('');
|
||||
}
|
||||
// Add category title
|
||||
primary.push(`${indentation}${readableText}`);
|
||||
// Recursively handle nested objects
|
||||
primary.push(...mapStatsToDisplay(value, indent + 1));
|
||||
} else {
|
||||
// For non-nested values, don't add empty rows
|
||||
primary.push(`${indentation}${readableText}: ${roundNumber(value, 2)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return primary;
|
||||
}
|
||||
|
||||
// Get customization for display text mapping
|
||||
const displayTextMapper = segment => {
|
||||
const defaultDisplay = {
|
||||
primary: [],
|
||||
secondary: [],
|
||||
};
|
||||
|
||||
// If the segment has cachedStats, map it to readable text
|
||||
if (segment.cachedStats) {
|
||||
const primary = mapStatsToDisplay(segment.cachedStats);
|
||||
defaultDisplay.primary = primary;
|
||||
}
|
||||
|
||||
return defaultDisplay;
|
||||
};
|
||||
|
||||
const updatedSegments = {};
|
||||
|
||||
Object.entries(segments).forEach(([segmentIndex, segment]) => {
|
||||
updatedSegments[segmentIndex] = {
|
||||
...segment,
|
||||
displayText: displayTextMapper(segment),
|
||||
};
|
||||
});
|
||||
|
||||
// Map the segments and apply the display text mapper
|
||||
return {
|
||||
...segmentation,
|
||||
label,
|
||||
segments: updatedSegments,
|
||||
};
|
||||
return segmentations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the combination of segmentation data and its representation in a viewport.
|
||||
*/
|
||||
type ViewportSegmentationRepresentation = {
|
||||
segmentationsWithRepresentations: {
|
||||
representation: SegmentationRepresentation;
|
||||
segmentation: SegmentationData;
|
||||
}[];
|
||||
disabled: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Custom hook that provides segmentation data and their representations for the active viewport.
|
||||
* @param options - The options object.
|
||||
* @param options.servicesManager - The services manager object.
|
||||
* @param options.subscribeToDataModified - Whether to subscribe to segmentation data modifications.
|
||||
* @param options.debounceTime - Debounce time in milliseconds for updates.
|
||||
* @returns An array of segmentation data and their representations for the active viewport.
|
||||
*/
|
||||
export function useActiveViewportSegmentationRepresentations({
|
||||
servicesManager,
|
||||
subscribeToDataModified = false,
|
||||
debounceTime = 0,
|
||||
}: withAppTypes<{ debounceTime?: number }>): ViewportSegmentationRepresentation {
|
||||
const { segmentationService, viewportGridService, customizationService, displaySetService } =
|
||||
servicesManager.services;
|
||||
|
||||
const [segmentationsWithRepresentations, setSegmentationsWithRepresentations] =
|
||||
useState<ViewportSegmentationRepresentation>({
|
||||
segmentationsWithRepresentations: [],
|
||||
disabled: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const update = () => {
|
||||
const viewportId = viewportGridService.getActiveViewportId();
|
||||
const displaySetUIDs = viewportGridService.getDisplaySetsUIDsForViewport(viewportId);
|
||||
|
||||
if (!displaySetUIDs?.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const displaySet = displaySetService.getDisplaySetByUID(displaySetUIDs[0]);
|
||||
|
||||
if (!displaySet) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (excludedModalities.includes(displaySet.Modality)) {
|
||||
setSegmentationsWithRepresentations(prev => ({
|
||||
segmentationsWithRepresentations: [],
|
||||
disabled: true,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
const segmentations = segmentationService.getSegmentations();
|
||||
|
||||
if (!segmentations?.length) {
|
||||
setSegmentationsWithRepresentations(prev => ({
|
||||
segmentationsWithRepresentations: [],
|
||||
disabled: false,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
const representations = segmentationService.getSegmentationRepresentations(viewportId);
|
||||
|
||||
const newSegmentationsWithRepresentations = representations.map(representation => {
|
||||
const segmentation = segmentationService.getSegmentation(representation.segmentationId);
|
||||
const mappedSegmentation = mapSegmentationToDisplay(segmentation, customizationService);
|
||||
return {
|
||||
representation,
|
||||
segmentation: mappedSegmentation,
|
||||
};
|
||||
});
|
||||
|
||||
setSegmentationsWithRepresentations({
|
||||
segmentationsWithRepresentations: newSegmentationsWithRepresentations,
|
||||
disabled: false,
|
||||
});
|
||||
};
|
||||
|
||||
const debouncedUpdate =
|
||||
debounceTime > 0 ? debounce(update, debounceTime, { leading: true, trailing: true }) : update;
|
||||
|
||||
update();
|
||||
|
||||
const subscriptions = [
|
||||
segmentationService.subscribe(
|
||||
segmentationService.EVENTS.SEGMENTATION_MODIFIED,
|
||||
debouncedUpdate
|
||||
),
|
||||
segmentationService.subscribe(
|
||||
segmentationService.EVENTS.SEGMENTATION_REMOVED,
|
||||
debouncedUpdate
|
||||
),
|
||||
segmentationService.subscribe(
|
||||
segmentationService.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED,
|
||||
debouncedUpdate
|
||||
),
|
||||
viewportGridService.subscribe(
|
||||
viewportGridService.EVENTS.ACTIVE_VIEWPORT_ID_CHANGED,
|
||||
debouncedUpdate
|
||||
),
|
||||
viewportGridService.subscribe(viewportGridService.EVENTS.GRID_STATE_CHANGED, debouncedUpdate),
|
||||
];
|
||||
|
||||
if (subscribeToDataModified) {
|
||||
subscriptions.push(
|
||||
segmentationService.subscribe(
|
||||
segmentationService.EVENTS.SEGMENTATION_DATA_MODIFIED,
|
||||
debouncedUpdate
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return () => {
|
||||
subscriptions.forEach(subscription => subscription.unsubscribe());
|
||||
if (debounceTime > 0) {
|
||||
debouncedUpdate.cancel();
|
||||
}
|
||||
};
|
||||
}, [
|
||||
segmentationService,
|
||||
viewportGridService,
|
||||
customizationService,
|
||||
displaySetService,
|
||||
debounceTime,
|
||||
subscribeToDataModified,
|
||||
]);
|
||||
|
||||
return segmentationsWithRepresentations;
|
||||
}
|
||||
export { useActiveViewportSegmentationRepresentations };
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useSystem } from '@ohif/core/src';
|
||||
import { useViewportDisplaySets } from './useViewportDisplaySets';
|
||||
import { BaseVolumeViewport } from '@cornerstonejs/core';
|
||||
|
||||
/**
|
||||
* Hook that provides measurement tracking information for a viewport
|
||||
*
|
||||
* @param options - The hook options
|
||||
* @param options.viewportId - The ID of the viewport to track
|
||||
* @returns An object containing the tracking state, related information, and tracked measurement UIDs
|
||||
*/
|
||||
export function useMeasurementTracking({ viewportId }: { viewportId: string }) {
|
||||
const { servicesManager } = useSystem();
|
||||
const { cornerstoneViewportService, trackedMeasurementsService, measurementService } =
|
||||
servicesManager.services;
|
||||
|
||||
const { backgroundDisplaySet } = useViewportDisplaySets(viewportId);
|
||||
|
||||
// Tracking states
|
||||
const [isTracked, setIsTracked] = useState(false);
|
||||
const [isLocked, setIsLocked] = useState(false);
|
||||
const [trackedMeasurementUIDs, setTrackedMeasurementUIDs] = useState<string[]>([]);
|
||||
|
||||
const updateTrackedMeasurements = useCallback(() => {
|
||||
if (!measurementService || !backgroundDisplaySet?.SeriesInstanceUID || !isTracked) {
|
||||
setTrackedMeasurementUIDs([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const seriesInstanceUID = backgroundDisplaySet.SeriesInstanceUID;
|
||||
|
||||
const seriesMeasurements = measurementService.getMeasurements(
|
||||
measurement => measurement.referenceSeriesUID === seriesInstanceUID
|
||||
);
|
||||
|
||||
const uids = seriesMeasurements.map(measurement => measurement.uid);
|
||||
setTrackedMeasurementUIDs(uids);
|
||||
}, [measurementService, backgroundDisplaySet, isTracked]);
|
||||
|
||||
const updateIsTracked = useCallback(() => {
|
||||
if (!trackedMeasurementsService || !backgroundDisplaySet?.SeriesInstanceUID) {
|
||||
setIsTracked(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const trackedSeries = trackedMeasurementsService.getTrackedSeries();
|
||||
|
||||
if (!trackedSeries?.length) {
|
||||
setIsTracked(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const viewport = cornerstoneViewportService?.getCornerstoneViewport(viewportId);
|
||||
const SeriesInstanceUID = backgroundDisplaySet.SeriesInstanceUID;
|
||||
|
||||
if (viewport instanceof BaseVolumeViewport) {
|
||||
const currentImageId = viewport?.getCurrentImageId();
|
||||
|
||||
if (!currentImageId) {
|
||||
setIsTracked(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const seriesIsTracked = trackedSeries.includes(SeriesInstanceUID);
|
||||
setIsTracked(seriesIsTracked);
|
||||
}, [viewportId, backgroundDisplaySet, cornerstoneViewportService, trackedMeasurementsService]);
|
||||
|
||||
// Update tracked measurements whenever tracking state changes
|
||||
useEffect(() => {
|
||||
updateTrackedMeasurements();
|
||||
}, [isTracked, updateTrackedMeasurements]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!trackedMeasurementsService) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLocked(trackedMeasurementsService.isTrackingEnabled());
|
||||
updateIsTracked();
|
||||
|
||||
const subscriptions = [
|
||||
trackedMeasurementsService.subscribe(trackedMeasurementsService.EVENTS.TRACKING_ENABLED, () =>
|
||||
setIsLocked(true)
|
||||
),
|
||||
trackedMeasurementsService.subscribe(
|
||||
trackedMeasurementsService.EVENTS.TRACKING_DISABLED,
|
||||
() => setIsLocked(false)
|
||||
),
|
||||
|
||||
trackedMeasurementsService.subscribe(
|
||||
trackedMeasurementsService.EVENTS.TRACKED_SERIES_CHANGED,
|
||||
() => updateIsTracked()
|
||||
),
|
||||
trackedMeasurementsService.subscribe(trackedMeasurementsService.EVENTS.SERIES_ADDED, () =>
|
||||
updateIsTracked()
|
||||
),
|
||||
trackedMeasurementsService.subscribe(trackedMeasurementsService.EVENTS.SERIES_REMOVED, () =>
|
||||
updateIsTracked()
|
||||
),
|
||||
];
|
||||
|
||||
// Subscribe to measurement service events to update trackedMeasurementUIDs
|
||||
if (measurementService) {
|
||||
[
|
||||
measurementService.EVENTS.MEASUREMENT_ADDED,
|
||||
measurementService.EVENTS.RAW_MEASUREMENT_ADDED,
|
||||
measurementService.EVENTS.MEASUREMENT_UPDATED,
|
||||
measurementService.EVENTS.MEASUREMENT_REMOVED,
|
||||
measurementService.EVENTS.MEASUREMENTS_CLEARED,
|
||||
].forEach(eventType => {
|
||||
subscriptions.push(
|
||||
measurementService.subscribe(eventType, () => updateTrackedMeasurements())
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
subscriptions.forEach(sub => sub.unsubscribe());
|
||||
};
|
||||
}, [trackedMeasurementsService, measurementService, updateIsTracked, updateTrackedMeasurements]);
|
||||
|
||||
return {
|
||||
isTracked,
|
||||
isLocked,
|
||||
seriesInstanceUID: backgroundDisplaySet?.SeriesInstanceUID,
|
||||
trackedMeasurementUIDs,
|
||||
};
|
||||
}
|
||||
|
||||
export default useMeasurementTracking;
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import debounce from 'lodash.debounce';
|
||||
|
||||
import { useSystem } from '@ohif/core';
|
||||
function mapMeasurementToDisplay(measurement, displaySetService) {
|
||||
const { referenceSeriesUID } = measurement;
|
||||
|
||||
@@ -56,13 +56,14 @@ function mapMeasurementToDisplay(measurement, displaySetService) {
|
||||
* @param {Object} options.valueTypes - The value types for mapping measurements.
|
||||
* @returns {Array} An array of mapped and filtered measurements.
|
||||
*/
|
||||
export function useMeasurements(servicesManager, { measurementFilter }) {
|
||||
export function useMeasurements({ measurementFilter }) {
|
||||
const { servicesManager } = useSystem();
|
||||
const { measurementService, displaySetService } = servicesManager.services;
|
||||
const [displayMeasurements, setDisplayMeasurements] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
const updateDisplayMeasurements = () => {
|
||||
let measurements = measurementService.getMeasurements(measurementFilter);
|
||||
const measurements = measurementService.getMeasurements(measurementFilter);
|
||||
const mappedMeasurements = measurements.map(m =>
|
||||
mapMeasurementToDisplay(m, displaySetService)
|
||||
);
|
||||
|
||||
@@ -48,30 +48,38 @@ export type UseViewportDisplaySetsOptions = {
|
||||
* Return type for useViewportDisplaySets
|
||||
*/
|
||||
export type ViewportDisplaySets = {
|
||||
/**
|
||||
* All display sets for the viewport
|
||||
*/
|
||||
allDisplaySets: AppTypes.DisplaySet[];
|
||||
/**
|
||||
* The viewport display sets for the viewport
|
||||
*/
|
||||
viewportDisplaySets: AppTypes.DisplaySet[];
|
||||
/**
|
||||
* The primary display set for the viewport (base image)
|
||||
*/
|
||||
backgroundDisplaySet?: any;
|
||||
backgroundDisplaySet?: AppTypes.DisplaySet;
|
||||
/**
|
||||
* Display sets currently shown with background (non-overlay layers)
|
||||
*/
|
||||
foregroundDisplaySets?: any[];
|
||||
foregroundDisplaySets?: AppTypes.DisplaySet[];
|
||||
/**
|
||||
* Segmentation display sets currently applied as overlays
|
||||
*/
|
||||
overlayDisplaySets?: any[];
|
||||
overlayDisplaySets?: AppTypes.DisplaySet[];
|
||||
/**
|
||||
* Display sets that could be toggled on as overlays (derived modalities)
|
||||
*/
|
||||
potentialOverlayDisplaySets?: any[];
|
||||
potentialOverlayDisplaySets?: AppTypes.DisplaySet[];
|
||||
/**
|
||||
* Display sets that could be added as foreground layers
|
||||
*/
|
||||
potentialForegroundDisplaySets?: any[];
|
||||
potentialForegroundDisplaySets?: AppTypes.DisplaySet[];
|
||||
/**
|
||||
* Display sets that could replace the current background
|
||||
*/
|
||||
potentialBackgroundDisplaySets?: any[];
|
||||
potentialBackgroundDisplaySets?: AppTypes.DisplaySet[];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -82,7 +90,7 @@ export type ViewportDisplaySets = {
|
||||
* @returns Object containing requested display set collections based on options
|
||||
*/
|
||||
export function useViewportDisplaySets(
|
||||
viewportId: string,
|
||||
viewportId?: string,
|
||||
options?: UseViewportDisplaySetsOptions
|
||||
): ViewportDisplaySets {
|
||||
const { servicesManager } = useSystem();
|
||||
@@ -91,7 +99,9 @@ export function useViewportDisplaySets(
|
||||
// Note: this is very important we should use the useViewportGrid hook here,
|
||||
// since if the viewport displaySet is changed we should re-run this hook
|
||||
// to get the latest displaySets
|
||||
const [_, viewportGridService] = useViewportGrid();
|
||||
const [viewportGridState, viewportGridService] = useViewportGrid();
|
||||
|
||||
const viewportIdToUse = viewportId || viewportGridState.activeViewportId;
|
||||
|
||||
// Apply defaults - include everything if no options specified
|
||||
const {
|
||||
@@ -114,8 +124,8 @@ export function useViewportDisplaySets(
|
||||
const needsSegmentations = includeOverlay;
|
||||
const segmentationRepresentations = useMemo(
|
||||
() =>
|
||||
needsSegmentations ? segmentationService.getSegmentationRepresentations(viewportId) : [],
|
||||
[segmentationService, viewportId, needsSegmentations]
|
||||
needsSegmentations ? segmentationService.getSegmentationRepresentations(viewportIdToUse) : [],
|
||||
[segmentationService, viewportIdToUse, needsSegmentations]
|
||||
);
|
||||
|
||||
const overlayDisplaySets = useMemo(() => {
|
||||
@@ -142,10 +152,10 @@ export function useViewportDisplaySets(
|
||||
return { viewportDisplaySets: [], enhancedDisplaySets: [] };
|
||||
}
|
||||
return getEnhancedDisplaySets({
|
||||
viewportId,
|
||||
viewportId: viewportIdToUse,
|
||||
services: { displaySetService, viewportGridService },
|
||||
});
|
||||
}, [viewportId, displaySetService, viewportGridService, needsEnhancedDisplaySets]);
|
||||
}, [viewportIdToUse, displaySetService, viewportGridService, needsEnhancedDisplaySets]);
|
||||
|
||||
const backgroundDisplaySet = useMemo(
|
||||
() => (includeBackground ? viewportDisplaySets[0] : undefined),
|
||||
@@ -217,7 +227,7 @@ export function useViewportDisplaySets(
|
||||
foregroundDisplaySetUIDs,
|
||||
]);
|
||||
|
||||
const result: ViewportDisplaySets = {};
|
||||
const result: ViewportDisplaySets = { allDisplaySets, viewportDisplaySets };
|
||||
|
||||
if (includeBackground) {
|
||||
result.backgroundDisplaySet = backgroundDisplaySet;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useViewportGrid } from '@ohif/ui-next';
|
||||
|
||||
/**
|
||||
* Hook to track whether the mouse is hovering over a specific viewport
|
||||
* and whether the viewport is active
|
||||
*
|
||||
* @param viewportId - The ID of the viewport to track
|
||||
* @returns { isHovered, isActive } - Whether the viewport is hovered and active
|
||||
*/
|
||||
export function useViewportHover(viewportId: string): { isHovered: boolean; isActive: boolean } {
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const [viewportGrid] = useViewportGrid();
|
||||
const { activeViewportId } = viewportGrid;
|
||||
|
||||
const isActive = activeViewportId === viewportId;
|
||||
|
||||
const setupListeners = useCallback(() => {
|
||||
const viewportElement = document.querySelector(`[data-viewportId="${viewportId}"]`);
|
||||
const element = viewportElement?.closest('.viewport-wrapper') || viewportElement;
|
||||
|
||||
if (!element) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let elementRect = (element as HTMLElement).getBoundingClientRect();
|
||||
let lastIsInside = false;
|
||||
|
||||
// Update rectangle when window is resized
|
||||
const updateRect = () => {
|
||||
elementRect = (element as HTMLElement).getBoundingClientRect();
|
||||
};
|
||||
|
||||
const isPointInViewport = (x, y) => {
|
||||
return (
|
||||
x >= elementRect.left &&
|
||||
x <= elementRect.right &&
|
||||
y >= elementRect.top &&
|
||||
y <= elementRect.bottom
|
||||
);
|
||||
};
|
||||
|
||||
const handleMouseMove = event => {
|
||||
const isInside = isPointInViewport(event.clientX, event.clientY);
|
||||
|
||||
if (isInside !== lastIsInside) {
|
||||
lastIsInside = isInside;
|
||||
setIsHovered(isInside);
|
||||
}
|
||||
};
|
||||
|
||||
let resizeTimeout;
|
||||
const handleResize = () => {
|
||||
clearTimeout(resizeTimeout);
|
||||
resizeTimeout = setTimeout(updateRect, 10);
|
||||
};
|
||||
|
||||
window.addEventListener('resize', handleResize);
|
||||
document.addEventListener('mousemove', handleMouseMove);
|
||||
|
||||
updateRect();
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('resize', handleResize);
|
||||
document.removeEventListener('mousemove', handleMouseMove);
|
||||
clearTimeout(resizeTimeout);
|
||||
};
|
||||
}, [viewportId]);
|
||||
|
||||
useEffect(() => {
|
||||
const cleanup = setupListeners();
|
||||
return cleanup;
|
||||
}, [setupListeners]);
|
||||
|
||||
// Memoize the return value to prevent unnecessary re-renders
|
||||
return useMemo(() => ({ isHovered, isActive }), [isHovered, isActive]);
|
||||
}
|
||||
@@ -0,0 +1,882 @@
|
||||
import React, { useCallback, useState, useEffect, useMemo } from 'react';
|
||||
import { useSystem } from '@ohif/core';
|
||||
import { useViewportDisplaySets } from './useViewportDisplaySets';
|
||||
import {
|
||||
StackViewport,
|
||||
Types,
|
||||
VolumeViewport3D,
|
||||
utilities,
|
||||
Enums,
|
||||
BaseVolumeViewport,
|
||||
cache,
|
||||
} from '@cornerstonejs/core';
|
||||
import { WindowLevelPreset } from '../types/WindowLevel';
|
||||
import { ColorbarPositionType, ColorbarOptions, ColorbarProperties } from '../types/Colorbar';
|
||||
import { VolumeRenderingConfig } from '../types/VolumeRenderingConfig';
|
||||
import { VolumeLightingParams } from '../types';
|
||||
import { ButtonLocation } from '@ohif/core/src/services/ToolBarService/ToolbarService';
|
||||
|
||||
interface ViewportRenderingOptions {
|
||||
location?: number;
|
||||
displaySetInstanceUID?: string;
|
||||
}
|
||||
|
||||
interface PixelValueRange {
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
interface WindowLevelHook {
|
||||
// Viewport information
|
||||
is3DVolume: boolean;
|
||||
isViewportBackgroundLight: boolean;
|
||||
viewportDisplaySets: AppTypes.DisplaySet[] | undefined;
|
||||
voiRange: { lower: number; upper: number } | undefined;
|
||||
windowLevel: { windowWidth: number; windowCenter: number } | undefined;
|
||||
|
||||
// Window level functions
|
||||
setWindowLevel: (preset: {
|
||||
windowWidth: number;
|
||||
windowCenter: number;
|
||||
immediate?: boolean;
|
||||
}) => void;
|
||||
setVOIRange: (params: { lower: number; upper: number }) => void;
|
||||
windowLevelPresets: WindowLevelPreset[];
|
||||
allWindowLevelPresets: Array<{
|
||||
displaySetInstanceUID: string;
|
||||
modality: string;
|
||||
presets: WindowLevelPreset[];
|
||||
}>;
|
||||
|
||||
// Colorbar functions
|
||||
hasColorbar: boolean;
|
||||
toggleColorbar: (options?: Partial<ColorbarOptions>) => void;
|
||||
colorbarProperties: ColorbarProperties;
|
||||
colorbarPosition: ColorbarPositionType;
|
||||
setColorbarPosition: React.Dispatch<React.SetStateAction<ColorbarPositionType>>;
|
||||
|
||||
// Colormap functions
|
||||
setColormap: (params: { colormap: any; opacity?: number; immediate?: boolean }) => void;
|
||||
colormap: any;
|
||||
|
||||
// Opacity functions
|
||||
opacity: number | undefined;
|
||||
setOpacity: (opacity: number) => void;
|
||||
opacityLinear: number | undefined;
|
||||
setOpacityLinear: (opacityLinear: number) => void;
|
||||
|
||||
// Threshold functions
|
||||
threshold: number | undefined;
|
||||
setThreshold: (threshold: number) => void;
|
||||
pixelValueRange: PixelValueRange;
|
||||
|
||||
// 3D volume rendering functions
|
||||
setVolumeRenderingPreset: (preset: any) => void;
|
||||
setVolumeRenderingQuality: (quality: number) => void;
|
||||
setVolumeLighting: (params: { ambient: number; diffuse: number; specular: number }) => void;
|
||||
setVolumeShading: (enabled: boolean) => void;
|
||||
volumeRenderingPresets: Array<any>;
|
||||
volumeRenderingQualityRange: { min: number; max: number; step: number };
|
||||
}
|
||||
|
||||
const getPosition = (location: number): ColorbarPositionType => {
|
||||
switch (location) {
|
||||
case ButtonLocation.LeftMiddle:
|
||||
return 'left';
|
||||
case ButtonLocation.RightMiddle:
|
||||
return 'right';
|
||||
case ButtonLocation.BottomMiddle:
|
||||
return 'bottom';
|
||||
case ButtonLocation.TopMiddle:
|
||||
return 'top';
|
||||
default:
|
||||
return 'bottom'; // Default to bottom if location doesn't match a middle position
|
||||
}
|
||||
};
|
||||
|
||||
const GAMMA = 1 / 5;
|
||||
|
||||
const linearToOpacity = (linearValue: number): number => {
|
||||
return Math.pow(linearValue, GAMMA);
|
||||
};
|
||||
|
||||
const opacityToLinear = (opacityValue: number): number => {
|
||||
return Math.pow(opacityValue, 1.0 / GAMMA);
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to access window level functionality for a specific viewport
|
||||
*
|
||||
* @param viewportId - The ID of the viewport to get window level functionality for
|
||||
* @param options - Options for the hook, including location and displaySetInstanceUID
|
||||
* @returns Window level API for the specified viewport
|
||||
*/
|
||||
export function useViewportRendering(
|
||||
viewportId?: string,
|
||||
options?: ViewportRenderingOptions
|
||||
): WindowLevelHook {
|
||||
const { servicesManager, commandsManager } = useSystem();
|
||||
const { cornerstoneViewportService, colorbarService, customizationService } =
|
||||
servicesManager.services;
|
||||
|
||||
const [is3DVolume, setIs3DVolume] = useState(false);
|
||||
const [hasColorbar, setHasColorbar] = useState(colorbarService.hasColorbar(viewportId));
|
||||
const [colorbarPosition, setColorbarPosition] = useState<ColorbarPositionType>(
|
||||
options?.location ? getPosition(options.location) : 'bottom'
|
||||
);
|
||||
const [voiRange, setVoiRange] = useState<{ lower: number; upper: number } | undefined>();
|
||||
const voiRangeRef = React.useRef<{ lower: number; upper: number } | undefined>();
|
||||
const [opacity, setOpacityState] = useState<number | undefined>();
|
||||
const [opacityLinear, setOpacityLinearState] = useState<number | undefined>();
|
||||
const [threshold, setThresholdState] = useState<number | undefined>();
|
||||
const [pixelValueRange, setPixelValueRange] = useState<PixelValueRange>({ min: 0, max: 255 });
|
||||
|
||||
const { viewportDisplaySets } = useViewportDisplaySets(viewportId);
|
||||
const { displaySetService } = servicesManager.services;
|
||||
|
||||
// Determine the active display set instance UID (internal only, not exposed)
|
||||
const activeDisplaySetInstanceUID = useMemo(() => {
|
||||
if (options?.displaySetInstanceUID) {
|
||||
return options.displaySetInstanceUID;
|
||||
}
|
||||
|
||||
if (viewportDisplaySets && viewportDisplaySets.length > 0) {
|
||||
return viewportDisplaySets[0].displaySetInstanceUID;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [options?.displaySetInstanceUID, viewportDisplaySets]);
|
||||
|
||||
const viewportInfo = viewportId ? cornerstoneViewportService.getViewportInfo(viewportId) : null;
|
||||
|
||||
const { presets, colorbarProperties, volumeRenderingPresets, volumeRenderingQualityRange } =
|
||||
getCustomizationData(customizationService);
|
||||
|
||||
const backgroundColor = viewportInfo?.getViewportOptions().background;
|
||||
const isViewportBackgroundLight = backgroundColor
|
||||
? utilities.isEqual(backgroundColor, [1, 1, 1])
|
||||
: false;
|
||||
|
||||
const allWindowLevelPresets = useMemo(() => {
|
||||
return (
|
||||
viewportDisplaySets
|
||||
?.filter(displaySet => presets?.[displaySet.Modality as string])
|
||||
.map(displaySet => {
|
||||
return {
|
||||
displaySetInstanceUID: displaySet.displaySetInstanceUID,
|
||||
modality: displaySet.Modality as string,
|
||||
presets: presets[displaySet.Modality as string],
|
||||
};
|
||||
}) || []
|
||||
);
|
||||
}, [viewportDisplaySets, presets]);
|
||||
|
||||
// Calculate pixel value range for the active display set
|
||||
useEffect(() => {
|
||||
if (!activeDisplaySetInstanceUID) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedDisplaySet = displaySetService.getDisplaySetByUID(activeDisplaySetInstanceUID);
|
||||
if (!selectedDisplaySet?.imageIds?.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const csViewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
|
||||
|
||||
if (!csViewport) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(csViewport instanceof BaseVolumeViewport)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const volumeIds = csViewport.getAllVolumeIds();
|
||||
const volumeId = volumeIds.find(id => id.includes(activeDisplaySetInstanceUID));
|
||||
|
||||
if (!volumeId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// only handle volume viewports for now
|
||||
const imageData = csViewport.getImageData(volumeId);
|
||||
|
||||
if (!imageData) {
|
||||
return;
|
||||
}
|
||||
|
||||
const imageDataVtk = imageData.imageData;
|
||||
|
||||
const { voxelManager } = imageDataVtk.get('voxelManager');
|
||||
|
||||
const range = voxelManager.getRange();
|
||||
|
||||
setPixelValueRange({ min: range[0], max: range[1] });
|
||||
}, [activeDisplaySetInstanceUID, displaySetService, cornerstoneViewportService, viewportId]);
|
||||
|
||||
// Get the presets specifically for the active display set
|
||||
const activeDisplaySetPresets = useMemo(() => {
|
||||
if (!activeDisplaySetInstanceUID || allWindowLevelPresets.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const activePresetData = allWindowLevelPresets.find(
|
||||
preset => preset.displaySetInstanceUID === activeDisplaySetInstanceUID
|
||||
);
|
||||
|
||||
if (!activePresetData) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return activePresetData.presets;
|
||||
}, [allWindowLevelPresets, activeDisplaySetInstanceUID]);
|
||||
|
||||
useEffect(() => {
|
||||
const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
|
||||
setIs3DVolume(viewport instanceof VolumeViewport3D);
|
||||
|
||||
// Initialize the VOI range from the viewport
|
||||
if (viewport && activeDisplaySetInstanceUID) {
|
||||
try {
|
||||
let properties;
|
||||
|
||||
if (viewport instanceof StackViewport) {
|
||||
properties = viewport.getProperties();
|
||||
if (properties.voiRange) {
|
||||
setVoiRange(properties.voiRange);
|
||||
voiRangeRef.current = properties.voiRange;
|
||||
}
|
||||
} else if (viewport instanceof BaseVolumeViewport) {
|
||||
// For volume viewports, find the actor for the active display set
|
||||
const volumeIds = viewport.getAllVolumeIds();
|
||||
const volumeId = volumeIds.find(id => id.includes(activeDisplaySetInstanceUID));
|
||||
|
||||
if (volumeId) {
|
||||
properties = viewport.getProperties(volumeId);
|
||||
if (properties.voiRange) {
|
||||
setVoiRange(properties.voiRange);
|
||||
voiRangeRef.current = properties.voiRange;
|
||||
}
|
||||
|
||||
// Get opacity from colormap if available
|
||||
if (properties.colormap && properties.colormap.opacity !== undefined) {
|
||||
const isArray = Array.isArray(properties.colormap.opacity);
|
||||
const opacity = isArray
|
||||
? properties.colormap.opacity.reduce((max, current) => Math.max(max, current), 0)
|
||||
: properties.colormap.opacity;
|
||||
|
||||
setOpacityState(opacity);
|
||||
setOpacityLinearState(opacityToLinear(opacity));
|
||||
}
|
||||
|
||||
// Get threshold from colormap if available
|
||||
if (properties.colormap && properties.colormap.threshold !== undefined) {
|
||||
setThresholdState(properties.colormap.threshold);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error initializing VOI range:', error);
|
||||
}
|
||||
}
|
||||
}, [cornerstoneViewportService, viewportId, activeDisplaySetInstanceUID]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!viewportId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const updateColorbarState = () => {
|
||||
const hasColorbarValue = colorbarService.hasColorbar(viewportId);
|
||||
setHasColorbar(hasColorbarValue);
|
||||
};
|
||||
|
||||
updateColorbarState();
|
||||
|
||||
const { unsubscribe } = colorbarService.subscribe(
|
||||
colorbarService.EVENTS.STATE_CHANGED,
|
||||
updateColorbarState
|
||||
);
|
||||
|
||||
return () => {
|
||||
unsubscribe();
|
||||
};
|
||||
}, [colorbarService, viewportId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!viewportId || !activeDisplaySetInstanceUID) {
|
||||
return;
|
||||
}
|
||||
|
||||
const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
|
||||
if (!viewport) {
|
||||
return;
|
||||
}
|
||||
|
||||
const element = viewport.element;
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
|
||||
const updateVOI = eventDetail => {
|
||||
const { range } = eventDetail.detail;
|
||||
|
||||
if (!range) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if this update is coming from our own setVOIRange or setWindowLevel call
|
||||
// If so, we already updated our state and don't need to do it again
|
||||
const isInternalUpdate = voiRangeRef.current && areVoiRangesClose(voiRangeRef.current, range);
|
||||
|
||||
if (!isInternalUpdate) {
|
||||
voiRangeRef.current = range;
|
||||
setVoiRange(range);
|
||||
}
|
||||
};
|
||||
|
||||
const updateColormap = eventDetail => {
|
||||
const { colormap } = eventDetail.detail;
|
||||
|
||||
if (!colormap) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract threshold from colormap in the event detail
|
||||
if (colormap.threshold !== undefined) {
|
||||
setThresholdState(colormap.threshold);
|
||||
}
|
||||
|
||||
if (colormap.opacity !== undefined) {
|
||||
setOpacityState(colormap.opacity);
|
||||
setOpacityLinearState(opacityToLinear(colormap.opacity));
|
||||
}
|
||||
};
|
||||
|
||||
element.addEventListener(Enums.Events.VOI_MODIFIED, updateVOI);
|
||||
element.addEventListener(Enums.Events.COLORMAP_MODIFIED, updateColormap);
|
||||
|
||||
return () => {
|
||||
element.removeEventListener(Enums.Events.VOI_MODIFIED, updateVOI);
|
||||
element.removeEventListener(Enums.Events.COLORMAP_MODIFIED, updateColormap);
|
||||
};
|
||||
}, [viewportId, activeDisplaySetInstanceUID, cornerstoneViewportService, opacityToLinear]);
|
||||
|
||||
const validateActiveDisplaySet = useCallback(() => {
|
||||
if (!activeDisplaySetInstanceUID) {
|
||||
throw new Error('No active display set instance UID is available');
|
||||
}
|
||||
|
||||
if (viewportDisplaySets?.length === 0) {
|
||||
throw new Error('No display sets are available for this viewport');
|
||||
}
|
||||
|
||||
// Verify the active display set is in the viewport
|
||||
const isDisplaySetInViewport = viewportDisplaySets?.some(
|
||||
ds => ds.displaySetInstanceUID === activeDisplaySetInstanceUID
|
||||
);
|
||||
|
||||
if (!isDisplaySetInViewport) {
|
||||
throw new Error(
|
||||
`Display set with UID ${activeDisplaySetInstanceUID} is not present in the viewport`
|
||||
);
|
||||
}
|
||||
|
||||
return activeDisplaySetInstanceUID;
|
||||
}, [activeDisplaySetInstanceUID, viewportDisplaySets]);
|
||||
|
||||
const setWindowLevel = useCallback(
|
||||
(preset: { windowWidth: number; windowCenter: number; immediate?: boolean }) => {
|
||||
if (!viewportId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const displaySetInstanceUID = validateActiveDisplaySet();
|
||||
|
||||
// Update voiRange as well, to ensure immediate UI updates
|
||||
const { lower, upper } = utilities.windowLevel.toLowHighRange(
|
||||
preset.windowWidth,
|
||||
preset.windowCenter
|
||||
);
|
||||
|
||||
const newVoiRange = { lower, upper };
|
||||
|
||||
if (!voiRangeRef.current || !areVoiRangesClose(voiRangeRef.current, newVoiRange)) {
|
||||
voiRangeRef.current = newVoiRange;
|
||||
setVoiRange(newVoiRange);
|
||||
|
||||
commandsManager.run({
|
||||
commandName: 'setViewportWindowLevel',
|
||||
commandOptions: {
|
||||
...preset,
|
||||
viewportId,
|
||||
displaySetInstanceUID,
|
||||
},
|
||||
context: 'CORNERSTONE',
|
||||
});
|
||||
}
|
||||
},
|
||||
[commandsManager, viewportId, validateActiveDisplaySet]
|
||||
);
|
||||
|
||||
const setVOIRange = useCallback(
|
||||
(params: { lower: number; upper: number }) => {
|
||||
if (!viewportId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only update if VOI values have actually changed
|
||||
if (!voiRangeRef.current || !areVoiRangesClose(voiRangeRef.current, params)) {
|
||||
// Update the ref and state immediately to avoid race conditions with the event listener
|
||||
voiRangeRef.current = params;
|
||||
setVoiRange(params);
|
||||
|
||||
const windowLevel = utilities.windowLevel.toWindowLevel(params.lower, params.upper);
|
||||
|
||||
// Set window level using the command manager directly to avoid circular calls
|
||||
const displaySetInstanceUID = validateActiveDisplaySet();
|
||||
commandsManager.run({
|
||||
commandName: 'setViewportWindowLevel',
|
||||
commandOptions: {
|
||||
...windowLevel,
|
||||
viewportId,
|
||||
displaySetInstanceUID,
|
||||
},
|
||||
context: 'CORNERSTONE',
|
||||
});
|
||||
}
|
||||
},
|
||||
[viewportId, commandsManager, validateActiveDisplaySet]
|
||||
);
|
||||
|
||||
const toggleColorbar = useCallback(
|
||||
(options?: Partial<ColorbarOptions>) => {
|
||||
if (!viewportId) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (viewportDisplaySets?.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!colorbarProperties) {
|
||||
return;
|
||||
}
|
||||
|
||||
const {
|
||||
width: colorbarWidth,
|
||||
colorbarTickPosition,
|
||||
colorbarInitialColormap,
|
||||
} = colorbarProperties as ColorbarProperties;
|
||||
|
||||
let appropriateTickPosition = colorbarTickPosition || 'top';
|
||||
|
||||
if (colorbarPosition === 'left' || colorbarPosition === 'right') {
|
||||
appropriateTickPosition = colorbarPosition === 'left' ? 'right' : 'left';
|
||||
} else {
|
||||
appropriateTickPosition = colorbarPosition === 'top' ? 'bottom' : 'top';
|
||||
}
|
||||
|
||||
const colorbarOptions = {
|
||||
viewportId,
|
||||
colormaps: colorbarProperties.colormaps || {},
|
||||
ticks: {
|
||||
position: appropriateTickPosition,
|
||||
},
|
||||
width: colorbarWidth,
|
||||
position: colorbarPosition,
|
||||
activeColormapName: colorbarInitialColormap || 'Grayscale',
|
||||
...options,
|
||||
};
|
||||
|
||||
// If light background, adjust tick style but keep the appropriate position
|
||||
if (isViewportBackgroundLight) {
|
||||
colorbarOptions.ticks = {
|
||||
position: appropriateTickPosition,
|
||||
style: {
|
||||
font: '13px Inter',
|
||||
color: '#000000',
|
||||
maxNumTicks: 8,
|
||||
tickSize: 5,
|
||||
tickWidth: 1,
|
||||
labelMargin: 3,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const displaySetInstanceUIDs = viewportDisplaySets.map(ds => ds.displaySetInstanceUID);
|
||||
|
||||
try {
|
||||
commandsManager.run('toggleViewportColorbar', {
|
||||
viewportId,
|
||||
options: colorbarOptions,
|
||||
displaySetInstanceUIDs,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error toggling colorbar:', error);
|
||||
}
|
||||
},
|
||||
[
|
||||
commandsManager,
|
||||
viewportId,
|
||||
colorbarProperties,
|
||||
isViewportBackgroundLight,
|
||||
viewportDisplaySets,
|
||||
colorbarPosition,
|
||||
]
|
||||
);
|
||||
|
||||
const setColormap = useCallback(
|
||||
({ colormap, opacity = 1, immediate = false }) => {
|
||||
if (!viewportId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const displaySetInstanceUID = validateActiveDisplaySet();
|
||||
|
||||
// Update local opacity state
|
||||
if (opacity !== undefined) {
|
||||
setOpacityState(opacity);
|
||||
}
|
||||
|
||||
commandsManager.run({
|
||||
commandName: 'setViewportColormap',
|
||||
commandOptions: {
|
||||
viewportId,
|
||||
colormap,
|
||||
displaySetInstanceUID,
|
||||
opacity,
|
||||
immediate,
|
||||
},
|
||||
context: 'CORNERSTONE',
|
||||
});
|
||||
},
|
||||
[commandsManager, viewportId, validateActiveDisplaySet]
|
||||
);
|
||||
|
||||
const setOpacity = useCallback(
|
||||
(opacityValue: number) => {
|
||||
if (!viewportId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
|
||||
if (!viewport || !(viewport instanceof BaseVolumeViewport)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Apply the actual opacity value
|
||||
setOpacityState(opacityValue);
|
||||
// Update the linear value for UI
|
||||
setOpacityLinearState(opacityToLinear(opacityValue));
|
||||
|
||||
const displaySetInstanceUID = validateActiveDisplaySet();
|
||||
const volumeIds = viewport.getAllVolumeIds();
|
||||
const volumeId = volumeIds.find(id => id.includes(displaySetInstanceUID));
|
||||
|
||||
if (!volumeId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get current properties including colormap
|
||||
const properties = viewport.getProperties(volumeId);
|
||||
const currentColormap = properties.colormap || {};
|
||||
|
||||
// Update colormap with new opacity
|
||||
const updatedColormap = {
|
||||
...currentColormap,
|
||||
opacity: opacityValue,
|
||||
};
|
||||
|
||||
// Apply updated colormap
|
||||
viewport.setProperties(
|
||||
{
|
||||
colormap: updatedColormap,
|
||||
},
|
||||
volumeId
|
||||
);
|
||||
|
||||
viewport.render();
|
||||
},
|
||||
[cornerstoneViewportService, viewportId, validateActiveDisplaySet, opacityToLinear]
|
||||
);
|
||||
|
||||
const setOpacityLinear = useCallback(
|
||||
(linearValue: number) => {
|
||||
// Convert linear UI value to actual opacity value and apply it
|
||||
const actualOpacity = linearToOpacity(linearValue);
|
||||
setOpacity(actualOpacity);
|
||||
},
|
||||
[linearToOpacity, setOpacity]
|
||||
);
|
||||
|
||||
const setThreshold = useCallback(
|
||||
(thresholdValue: number) => {
|
||||
if (!viewportId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
|
||||
if (!viewport || !(viewport instanceof BaseVolumeViewport)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setThresholdState(thresholdValue);
|
||||
|
||||
const displaySetInstanceUID = validateActiveDisplaySet();
|
||||
const volumeIds = viewport.getAllVolumeIds();
|
||||
const volumeId = volumeIds.find(id => id.includes(displaySetInstanceUID));
|
||||
|
||||
if (!volumeId) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.debug('🚀 ~ thresholdValue:', thresholdValue);
|
||||
|
||||
viewport.setProperties(
|
||||
{
|
||||
colormap: {
|
||||
threshold: thresholdValue,
|
||||
},
|
||||
},
|
||||
volumeId
|
||||
);
|
||||
|
||||
viewport.render();
|
||||
},
|
||||
[cornerstoneViewportService, viewportId, validateActiveDisplaySet]
|
||||
);
|
||||
|
||||
// Get the current colormap for the active display set
|
||||
const colormap = useMemo(() => {
|
||||
if (!viewportId || !activeDisplaySetInstanceUID || !viewportDisplaySets?.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
|
||||
|
||||
if (!viewport) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (viewport instanceof StackViewport) {
|
||||
const { colormap } = viewport.getProperties();
|
||||
if (!colormap) {
|
||||
return (
|
||||
colorbarProperties?.colormaps?.find(c => c.Name === 'Grayscale') ||
|
||||
colorbarProperties?.colormaps?.[0]
|
||||
);
|
||||
}
|
||||
return colormap;
|
||||
}
|
||||
|
||||
const actorEntries = viewport.getActors();
|
||||
const actorEntry = actorEntries?.find(entry =>
|
||||
entry.referencedId.includes(activeDisplaySetInstanceUID)
|
||||
);
|
||||
|
||||
if (!actorEntry) {
|
||||
return (
|
||||
colorbarProperties?.colormaps?.find(c => c.Name === 'Grayscale') ||
|
||||
colorbarProperties?.colormaps?.[0]
|
||||
);
|
||||
}
|
||||
|
||||
const { colormap } = (viewport as Types.IVolumeViewport).getProperties(
|
||||
actorEntry.referencedId
|
||||
);
|
||||
|
||||
if (!colormap) {
|
||||
return (
|
||||
colorbarProperties?.colormaps?.find(c => c.Name === 'Grayscale') ||
|
||||
colorbarProperties?.colormaps?.[0]
|
||||
);
|
||||
}
|
||||
|
||||
return colormap;
|
||||
} catch (error) {
|
||||
console.error('Error getting viewport colormap:', error);
|
||||
return (
|
||||
colorbarProperties?.colormaps?.find(c => c.Name === 'Grayscale') ||
|
||||
colorbarProperties?.colormaps?.[0]
|
||||
);
|
||||
}
|
||||
}, [
|
||||
cornerstoneViewportService,
|
||||
viewportId,
|
||||
activeDisplaySetInstanceUID,
|
||||
viewportDisplaySets,
|
||||
colorbarProperties?.colormaps,
|
||||
]);
|
||||
|
||||
// 3D volume rendering functions
|
||||
const setVolumeRenderingPreset = useCallback(
|
||||
(preset: any) => {
|
||||
if (!viewportId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const displaySetInstanceUID = validateActiveDisplaySet();
|
||||
|
||||
commandsManager.run({
|
||||
commandName: 'setVolumesPreset',
|
||||
commandOptions: {
|
||||
preset,
|
||||
viewportId,
|
||||
displaySetInstanceUID,
|
||||
},
|
||||
});
|
||||
},
|
||||
[commandsManager, viewportId, validateActiveDisplaySet]
|
||||
);
|
||||
|
||||
const setVolumeRenderingQuality = useCallback(
|
||||
(quality: number) => {
|
||||
if (!viewportId) {
|
||||
return;
|
||||
}
|
||||
|
||||
commandsManager.run({
|
||||
commandName: 'setVolumeRenderingQuality',
|
||||
commandOptions: {
|
||||
quality,
|
||||
viewportId,
|
||||
},
|
||||
});
|
||||
},
|
||||
[commandsManager, viewportId]
|
||||
);
|
||||
|
||||
const setVolumeLighting = useCallback(
|
||||
({ ambient, diffuse, specular }: VolumeLightingParams) => {
|
||||
if (!viewportId) {
|
||||
return;
|
||||
}
|
||||
|
||||
commandsManager.run({
|
||||
commandName: 'setVolumeLighting',
|
||||
commandOptions: {
|
||||
ambient,
|
||||
diffuse,
|
||||
specular,
|
||||
viewportId,
|
||||
},
|
||||
});
|
||||
},
|
||||
[commandsManager, viewportId]
|
||||
);
|
||||
|
||||
const setVolumeShading = useCallback(
|
||||
(enabled: boolean) => {
|
||||
if (!viewportId) {
|
||||
return;
|
||||
}
|
||||
|
||||
commandsManager.run({
|
||||
commandName: 'setVolumeShading',
|
||||
commandOptions: {
|
||||
enabled,
|
||||
viewportId,
|
||||
},
|
||||
});
|
||||
},
|
||||
[commandsManager, viewportId]
|
||||
);
|
||||
|
||||
return {
|
||||
is3DVolume,
|
||||
isViewportBackgroundLight,
|
||||
|
||||
// Window level functions
|
||||
setWindowLevel,
|
||||
setVOIRange,
|
||||
voiRange,
|
||||
windowLevel: utilities.windowLevel.toWindowLevel(voiRange?.lower, voiRange?.upper),
|
||||
|
||||
// Colorbar functions
|
||||
hasColorbar,
|
||||
toggleColorbar,
|
||||
|
||||
// Colormap functions
|
||||
setColormap,
|
||||
colormap,
|
||||
|
||||
// Opacity functions
|
||||
opacity,
|
||||
setOpacity,
|
||||
opacityLinear,
|
||||
setOpacityLinear,
|
||||
|
||||
// Threshold functions
|
||||
threshold,
|
||||
setThreshold,
|
||||
pixelValueRange,
|
||||
|
||||
// 3D volume rendering functions
|
||||
setVolumeRenderingPreset,
|
||||
setVolumeRenderingQuality,
|
||||
setVolumeLighting,
|
||||
setVolumeShading,
|
||||
|
||||
// Display sets
|
||||
viewportDisplaySets,
|
||||
|
||||
// Colorbar properties
|
||||
colorbarProperties,
|
||||
colorbarPosition,
|
||||
setColorbarPosition,
|
||||
|
||||
// Presets
|
||||
windowLevelPresets: activeDisplaySetPresets,
|
||||
allWindowLevelPresets,
|
||||
volumeRenderingPresets,
|
||||
volumeRenderingQualityRange,
|
||||
};
|
||||
}
|
||||
|
||||
export default useViewportRendering;
|
||||
|
||||
/**
|
||||
* Helper function to compare two VOI ranges with a small tolerance.
|
||||
* @param rangeA - The first VOI range { lower, upper }.
|
||||
* @param rangeB - The second VOI range { lower, upper }.
|
||||
* @param epsilon - The tolerance for comparison.
|
||||
* @returns True if the ranges are considered close, false otherwise.
|
||||
*/
|
||||
function areVoiRangesClose(
|
||||
rangeA: { lower: number; upper: number },
|
||||
rangeB: { lower: number; upper: number },
|
||||
epsilon = 0.001
|
||||
): boolean {
|
||||
if (!rangeA || !rangeB) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
Math.abs(rangeA.lower - rangeB.lower) < epsilon &&
|
||||
Math.abs(rangeA.upper - rangeB.upper) < epsilon
|
||||
);
|
||||
}
|
||||
|
||||
function getCustomizationData(customizationService) {
|
||||
const presets = customizationService.getCustomization('cornerstone.windowLevelPresets');
|
||||
const colorbarProperties = customizationService.getCustomization(
|
||||
'cornerstone.colorbar'
|
||||
) as ColorbarProperties;
|
||||
|
||||
const {
|
||||
volumeRenderingPresets = [],
|
||||
volumeRenderingQualityRange = { min: 0, max: 1, step: 0.1 },
|
||||
} =
|
||||
(customizationService.getCustomization(
|
||||
'cornerstone.3dVolumeRendering'
|
||||
) as VolumeRenderingConfig) || {};
|
||||
|
||||
return {
|
||||
presets,
|
||||
colorbarProperties,
|
||||
volumeRenderingPresets,
|
||||
volumeRenderingQualityRange,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import debounce from 'lodash.debounce';
|
||||
import { roundNumber } from '@ohif/core/src/utils';
|
||||
import {
|
||||
SegmentationData,
|
||||
SegmentationRepresentation,
|
||||
} from '../services/SegmentationService/SegmentationService';
|
||||
import { useSystem } from '@ohif/core';
|
||||
const excludedModalities = ['SM', 'OT', 'DOC', 'ECG'];
|
||||
|
||||
function mapSegmentationToDisplay(segmentation, customizationService) {
|
||||
const { label, segments } = segmentation;
|
||||
|
||||
// Get the readable text mapping once
|
||||
const readableTextMap = customizationService.getCustomization('panelSegmentation.readableText');
|
||||
|
||||
// Helper function to recursively map cachedStats to readable display text
|
||||
function mapStatsToDisplay(stats, indent = 0) {
|
||||
const primary = [];
|
||||
const indentation = ' '.repeat(indent);
|
||||
|
||||
for (const key in stats) {
|
||||
if (Object.prototype.hasOwnProperty.call(stats, key)) {
|
||||
const value = stats[key];
|
||||
const readableText = readableTextMap?.[key];
|
||||
|
||||
if (!readableText) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
||||
// Add empty row before category (except for the first category)
|
||||
if (primary.length > 0) {
|
||||
primary.push('');
|
||||
}
|
||||
// Add category title
|
||||
primary.push(`${indentation}${readableText}`);
|
||||
// Recursively handle nested objects
|
||||
primary.push(...mapStatsToDisplay(value, indent + 1));
|
||||
} else {
|
||||
// For non-nested values, don't add empty rows
|
||||
primary.push(`${indentation}${readableText}: ${roundNumber(value, 2)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return primary;
|
||||
}
|
||||
|
||||
// Get customization for display text mapping
|
||||
const displayTextMapper = segment => {
|
||||
const defaultDisplay = {
|
||||
primary: [],
|
||||
secondary: [],
|
||||
};
|
||||
|
||||
// If the segment has cachedStats, map it to readable text
|
||||
if (segment.cachedStats) {
|
||||
const primary = mapStatsToDisplay(segment.cachedStats);
|
||||
defaultDisplay.primary = primary;
|
||||
}
|
||||
|
||||
return defaultDisplay;
|
||||
};
|
||||
|
||||
const updatedSegments = {};
|
||||
|
||||
Object.entries(segments).forEach(([segmentIndex, segment]) => {
|
||||
updatedSegments[segmentIndex] = {
|
||||
...segment,
|
||||
displayText: displayTextMapper(segment),
|
||||
};
|
||||
});
|
||||
|
||||
// Map the segments and apply the display text mapper
|
||||
return {
|
||||
...segmentation,
|
||||
label,
|
||||
segments: updatedSegments,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the combination of segmentation data and its representation in a viewport.
|
||||
*/
|
||||
type ViewportSegmentationRepresentation = {
|
||||
segmentationsWithRepresentations: {
|
||||
representation: SegmentationRepresentation;
|
||||
segmentation: SegmentationData;
|
||||
}[];
|
||||
disabled: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Custom hook that provides segmentation data and their representations for the active viewport.
|
||||
* @param options - The options object.
|
||||
* @param options.servicesManager - The services manager object.
|
||||
* @param options.subscribeToDataModified - Whether to subscribe to segmentation data modifications.
|
||||
* @param options.debounceTime - Debounce time in milliseconds for updates.
|
||||
* @returns An array of segmentation data and their representations for the active viewport.
|
||||
*/
|
||||
export function useViewportSegmentations({
|
||||
viewportId,
|
||||
subscribeToDataModified = false,
|
||||
debounceTime = 0,
|
||||
}: {
|
||||
viewportId: string;
|
||||
subscribeToDataModified?: boolean;
|
||||
debounceTime?: number;
|
||||
}): ViewportSegmentationRepresentation {
|
||||
const { servicesManager } = useSystem();
|
||||
const { segmentationService, viewportGridService, customizationService, displaySetService } =
|
||||
servicesManager.services;
|
||||
|
||||
const [segmentationsWithRepresentations, setSegmentationsWithRepresentations] =
|
||||
useState<ViewportSegmentationRepresentation>({
|
||||
segmentationsWithRepresentations: [],
|
||||
disabled: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const update = () => {
|
||||
const displaySetUIDs = viewportGridService.getDisplaySetsUIDsForViewport(viewportId);
|
||||
|
||||
if (!displaySetUIDs?.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const displaySet = displaySetService.getDisplaySetByUID(displaySetUIDs[0]);
|
||||
|
||||
if (!displaySet) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (excludedModalities.includes(displaySet.Modality)) {
|
||||
setSegmentationsWithRepresentations(prev => ({
|
||||
segmentationsWithRepresentations: [],
|
||||
disabled: true,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
const segmentations = segmentationService.getSegmentations();
|
||||
|
||||
if (!segmentations?.length) {
|
||||
setSegmentationsWithRepresentations(prev => ({
|
||||
segmentationsWithRepresentations: [],
|
||||
disabled: false,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
const representations = segmentationService.getSegmentationRepresentations(viewportId);
|
||||
|
||||
const newSegmentationsWithRepresentations = representations.map(representation => {
|
||||
const segmentation = segmentationService.getSegmentation(representation.segmentationId);
|
||||
const mappedSegmentation = mapSegmentationToDisplay(segmentation, customizationService);
|
||||
return {
|
||||
representation,
|
||||
segmentation: mappedSegmentation,
|
||||
};
|
||||
});
|
||||
|
||||
setSegmentationsWithRepresentations({
|
||||
segmentationsWithRepresentations: newSegmentationsWithRepresentations,
|
||||
disabled: false,
|
||||
});
|
||||
};
|
||||
|
||||
const debouncedUpdate =
|
||||
debounceTime > 0 ? debounce(update, debounceTime, { leading: true, trailing: true }) : update;
|
||||
|
||||
update();
|
||||
|
||||
const subscriptions = [
|
||||
segmentationService.subscribe(
|
||||
segmentationService.EVENTS.SEGMENTATION_MODIFIED,
|
||||
debouncedUpdate
|
||||
),
|
||||
segmentationService.subscribe(
|
||||
segmentationService.EVENTS.SEGMENTATION_REMOVED,
|
||||
debouncedUpdate
|
||||
),
|
||||
segmentationService.subscribe(
|
||||
segmentationService.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED,
|
||||
debouncedUpdate
|
||||
),
|
||||
viewportGridService.subscribe(
|
||||
viewportGridService.EVENTS.ACTIVE_VIEWPORT_ID_CHANGED,
|
||||
debouncedUpdate
|
||||
),
|
||||
viewportGridService.subscribe(viewportGridService.EVENTS.GRID_STATE_CHANGED, debouncedUpdate),
|
||||
];
|
||||
|
||||
if (subscribeToDataModified) {
|
||||
subscriptions.push(
|
||||
segmentationService.subscribe(
|
||||
segmentationService.EVENTS.SEGMENTATION_DATA_MODIFIED,
|
||||
debouncedUpdate
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return () => {
|
||||
subscriptions.forEach(subscription => subscription.unsubscribe());
|
||||
if (debounceTime > 0) {
|
||||
debouncedUpdate.cancel();
|
||||
}
|
||||
};
|
||||
}, [
|
||||
segmentationService,
|
||||
viewportGridService,
|
||||
customizationService,
|
||||
displaySetService,
|
||||
debounceTime,
|
||||
subscribeToDataModified,
|
||||
viewportId,
|
||||
]);
|
||||
|
||||
return segmentationsWithRepresentations;
|
||||
}
|
||||
Reference in new issue
Block a user