@ohif/extension-cornerstone 3.14.0-beta.10 → 3.14.0-beta.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (325) hide show
  1. package/dist/915.ohif-extension-cornerstone.umd.js +1 -1
  2. package/dist/ohif-extension-cornerstone.umd.js +1 -5
  3. package/package.json +33 -25
  4. package/src/Viewport/OHIFCornerstoneViewport.css +46 -0
  5. package/src/Viewport/OHIFCornerstoneViewport.tsx +502 -0
  6. package/src/Viewport/Overlays/CornerstoneOverlays.tsx +103 -0
  7. package/src/Viewport/Overlays/CustomizableViewportOverlay.css +25 -0
  8. package/src/Viewport/Overlays/CustomizableViewportOverlay.tsx +469 -0
  9. package/src/Viewport/Overlays/ViewportImageScrollbar.tsx +106 -0
  10. package/src/Viewport/Overlays/ViewportImageSliceLoadingIndicator.tsx +87 -0
  11. package/src/Viewport/Overlays/ViewportOrientationMarkers.css +41 -0
  12. package/src/Viewport/Overlays/ViewportOrientationMarkers.tsx +136 -0
  13. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/ViewportSliceProgressScrollbar.tsx +195 -0
  14. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/helpers.ts +46 -0
  15. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/hooks.ts +383 -0
  16. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/index.ts +1 -0
  17. package/src/Viewport/Overlays/ViewportSliceProgressScrollbar/types.ts +17 -0
  18. package/src/Viewport/Overlays/utils.ts +66 -0
  19. package/src/commandsModule.ts +2951 -0
  20. package/src/components/AccordionGroup/AccordionGroup.tsx +195 -0
  21. package/src/components/AccordionGroup/index.ts +4 -0
  22. package/src/components/ActiveViewportWindowLevel/ActiveViewportWindowLevel.tsx +23 -0
  23. package/src/components/ActiveViewportWindowLevel/index.js +1 -0
  24. package/src/components/AdvancedRenderingControls/AdvancedRenderingControls.tsx +149 -0
  25. package/src/components/AdvancedRenderingControls/index.ts +1 -0
  26. package/src/components/CinePlayer/CinePlayer.tsx +247 -0
  27. package/src/components/CinePlayer/index.ts +3 -0
  28. package/src/components/DicomUpload/DicomUpload.tsx +111 -0
  29. package/src/components/DicomUpload/DicomUploadProgress.tsx +396 -0
  30. package/src/components/DicomUpload/DicomUploadProgressItem.tsx +119 -0
  31. package/src/components/ExportSegmentationSubMenuItem.tsx +75 -0
  32. package/src/components/MeasurementItems.tsx +70 -0
  33. package/src/components/MeasurementTableNested.tsx +30 -0
  34. package/src/components/MeasurementsMenu.tsx +84 -0
  35. package/src/components/MeasurementsOrAdditionalFindings.tsx +82 -0
  36. package/src/components/ModalityLoadBadge/ModalityLoadBadge.tsx +171 -0
  37. package/src/components/ModalityLoadBadge/index.ts +1 -0
  38. package/src/components/NavigationComponent/NavigationComponent.tsx +138 -0
  39. package/src/components/NavigationComponent/index.ts +3 -0
  40. package/src/components/OHIFViewportActionCorners.tsx +94 -0
  41. package/src/components/OpacityMenu/OpacityMenu.tsx +54 -0
  42. package/src/components/OpacityMenu/OpacityMenuWrapper.tsx +85 -0
  43. package/src/components/OpacityMenu/index.ts +2 -0
  44. package/src/components/PanelAccordionTrigger.tsx +48 -0
  45. package/src/components/SegmentationToolConfig.tsx +71 -0
  46. package/src/components/SegmentationUtilityButton.tsx +61 -0
  47. package/src/components/SelectItemWithModality.tsx +29 -0
  48. package/src/components/SeriesMeasurements.tsx +90 -0
  49. package/src/components/SeriesSummaryFromDisplaySet.tsx +21 -0
  50. package/src/components/StudyMeasurements.tsx +88 -0
  51. package/src/components/StudyMeasurementsActions.tsx +75 -0
  52. package/src/components/StudySummaryFromMetadata.test.ts +47 -0
  53. package/src/components/StudySummaryFromMetadata.tsx +31 -0
  54. package/src/components/StudySummaryWithActions.tsx +14 -0
  55. package/src/components/ThresholdMenu/ThresholdMenu.tsx +104 -0
  56. package/src/components/ThresholdMenu/ThresholdMenuWrapper.tsx +85 -0
  57. package/src/components/ThresholdMenu/index.ts +2 -0
  58. package/src/components/TrackingStatus/TrackingStatus.tsx +32 -0
  59. package/src/components/TrackingStatus/index.ts +1 -0
  60. package/src/components/VOIManualControlMenu/VOIManualControlMenu.tsx +190 -0
  61. package/src/components/VOIManualControlMenu/VOIManualControlMenuWrapper.tsx +85 -0
  62. package/src/components/VOIManualControlMenu/index.ts +2 -0
  63. package/src/components/ViewportColorbar/ViewportColorbar.tsx +150 -0
  64. package/src/components/ViewportColorbar/ViewportColorbarsContainer.tsx +125 -0
  65. package/src/components/ViewportColorbar/index.ts +5 -0
  66. package/src/components/ViewportDataOverlaySettingMenu/ViewportDataOverlayMenu.tsx +538 -0
  67. package/src/components/ViewportDataOverlaySettingMenu/ViewportDataOverlayMenuWrapper.tsx +91 -0
  68. package/src/components/ViewportDataOverlaySettingMenu/utils.ts +118 -0
  69. package/src/components/ViewportOrientationMenu/ViewportOrientationMenu.tsx +249 -0
  70. package/src/components/ViewportOrientationMenu/ViewportOrientationMenuWrapper.tsx +29 -0
  71. package/src/components/ViewportWindowLevel/ViewportWindowLevel.tsx +261 -0
  72. package/src/components/ViewportWindowLevel/getViewportVolumeHistogram.ts +72 -0
  73. package/src/components/ViewportWindowLevel/histogramWorker.js +97 -0
  74. package/src/components/ViewportWindowLevel/index.js +1 -0
  75. package/src/components/ViewportWindowLevel/utils.ts +176 -0
  76. package/src/components/WindowLevelActionMenu/Colorbar.tsx +30 -0
  77. package/src/components/WindowLevelActionMenu/Colormap.tsx +121 -0
  78. package/src/components/WindowLevelActionMenu/VolumeLighting.tsx +82 -0
  79. package/src/components/WindowLevelActionMenu/VolumeRenderingOptions.tsx +38 -0
  80. package/src/components/WindowLevelActionMenu/VolumeRenderingPresets.tsx +36 -0
  81. package/src/components/WindowLevelActionMenu/VolumeRenderingPresetsContent.tsx +78 -0
  82. package/src/components/WindowLevelActionMenu/VolumeRenderingQuality.tsx +64 -0
  83. package/src/components/WindowLevelActionMenu/VolumeShade.tsx +47 -0
  84. package/src/components/WindowLevelActionMenu/VolumeShift.tsx +92 -0
  85. package/src/components/WindowLevelActionMenu/WindowLevel.tsx +157 -0
  86. package/src/components/WindowLevelActionMenu/WindowLevelActionMenu.tsx +102 -0
  87. package/src/components/WindowLevelActionMenu/WindowLevelActionMenuWrapper.tsx +131 -0
  88. package/src/components/WindowLevelActionMenu/defaultWindowLevelPresets.ts +23 -0
  89. package/src/components/WindowLevelActionMenu/index.ts +11 -0
  90. package/src/components/WindowLevelActionMenu/windowLevelPresetHotkeys.test.ts +19 -0
  91. package/src/components/index.ts +12 -0
  92. package/src/constants/index.ts +13 -0
  93. package/src/customizations/CustomDropdownMenuContent.tsx +106 -0
  94. package/src/customizations/CustomSegmentStatisticsHeader.tsx +140 -0
  95. package/src/customizations/captureViewportModalCustomization.tsx +175 -0
  96. package/src/customizations/colorbarCustomization.ts +93 -0
  97. package/src/customizations/gpuSettingsPresetCustomization.ts +8 -0
  98. package/src/customizations/layoutSelectorCustomization.ts +104 -0
  99. package/src/customizations/measurementsCustomization.ts +124 -0
  100. package/src/customizations/miscCustomization.ts +22 -0
  101. package/src/customizations/modalityColorMapCustomization.ts +23 -0
  102. package/src/customizations/segmentationHydrationCustomization.ts +16 -0
  103. package/src/customizations/segmentationPanelCustomization.tsx +119 -0
  104. package/src/customizations/segmentationToolbarCustomization.ts +964 -0
  105. package/src/customizations/toolGroupToolsCustomization.ts +204 -0
  106. package/src/customizations/toolbarButtonsCustomization.ts +805 -0
  107. package/src/customizations/viewportClickCommandsCustomization.ts +15 -0
  108. package/src/customizations/viewportDownloadWarningCustomization.tsx +6 -0
  109. package/src/customizations/viewportOverlayCustomization.tsx +46 -0
  110. package/src/customizations/viewportScrollbarCustomization.tsx +27 -0
  111. package/src/customizations/viewportToolsCustomization.ts +33 -0
  112. package/src/customizations/volumeRenderingCustomization.ts +14 -0
  113. package/src/customizations/windowLevelPresetsCustomization.ts +5 -0
  114. package/src/enums.ts +9 -0
  115. package/src/getCustomizationModule.tsx +54 -0
  116. package/src/getHangingProtocolModule.ts +47 -0
  117. package/src/getPanelModule.tsx +128 -0
  118. package/src/getSopClassHandlerModule.js +284 -0
  119. package/src/getToolbarModule.tsx +622 -0
  120. package/src/hooks/index.ts +8 -0
  121. package/src/hooks/useActiveViewportSegmentationRepresentations.ts +14 -0
  122. package/src/hooks/useMeasurementTracking.ts +132 -0
  123. package/src/hooks/useMeasurements.ts +104 -0
  124. package/src/hooks/useSegmentations.ts +147 -0
  125. package/src/hooks/useViewportDisplaySets.ts +284 -0
  126. package/src/hooks/useViewportHover.ts +77 -0
  127. package/src/hooks/useViewportRendering.tsx +868 -0
  128. package/src/hooks/useViewportSegmentations.ts +245 -0
  129. package/src/hps/fourUp.ts +117 -0
  130. package/src/hps/frameView.ts +1581 -0
  131. package/src/hps/main3D.ts +142 -0
  132. package/src/hps/mpr.ts +197 -0
  133. package/src/hps/mprAnd3DVolumeViewport.ts +124 -0
  134. package/src/hps/only3D.ts +70 -0
  135. package/src/hps/primary3D.ts +142 -0
  136. package/src/hps/primaryAxial.ts +114 -0
  137. package/src/id.js +5 -0
  138. package/src/index.tsx +350 -0
  139. package/src/init.tsx +445 -0
  140. package/src/initCineService.ts +75 -0
  141. package/src/initContextMenu.ts +94 -0
  142. package/src/initCornerstoneTools.js +188 -0
  143. package/src/initDoubleClick.ts +82 -0
  144. package/src/initMeasurementService.ts +576 -0
  145. package/src/initStudyPrefetcherService.ts +33 -0
  146. package/src/initWADOImageLoader.js +56 -0
  147. package/src/panels/PanelMeasurement.tsx +84 -0
  148. package/src/panels/PanelSegmentation.tsx +338 -0
  149. package/src/services/ColorbarService/ColorbarService.ts +242 -0
  150. package/src/services/ColorbarService/index.ts +2 -0
  151. package/src/services/CornerstoneCacheService/CornerstoneCacheService.ts +326 -0
  152. package/src/services/CornerstoneCacheService/index.js +3 -0
  153. package/src/services/SegmentationService/RTSTRUCT/mapROIContoursToRTStructData.ts +36 -0
  154. package/src/services/SegmentationService/SegmentationService.test.ts +3698 -0
  155. package/src/services/SegmentationService/SegmentationService.ts +2376 -0
  156. package/src/services/SegmentationService/backends/ISegmentationBackend.ts +102 -0
  157. package/src/services/SegmentationService/backends/ISegmentationServiceInternals.ts +44 -0
  158. package/src/services/SegmentationService/backends/LegacySegmentationBackend.ts +139 -0
  159. package/src/services/SegmentationService/backends/NextSegmentationBackend.ts +159 -0
  160. package/src/services/SegmentationService/backends/index.ts +4 -0
  161. package/src/services/SegmentationService/index.ts +3 -0
  162. package/src/services/SyncGroupService/SyncGroupService.ts +264 -0
  163. package/src/services/SyncGroupService/createHydrateSegmentationSynchronizer.ts +118 -0
  164. package/src/services/SyncGroupService/index.js +3 -0
  165. package/src/services/ToolGroupService/ToolGroupService.test.ts +83 -0
  166. package/src/services/ToolGroupService/ToolGroupService.ts +541 -0
  167. package/src/services/ToolGroupService/index.js +3 -0
  168. package/src/services/ViewedDataService/ViewedDataService.ts +58 -0
  169. package/src/services/ViewedDataService/index.ts +3 -0
  170. package/src/services/ViewportService/CornerstoneViewportService.ts +1814 -0
  171. package/src/services/ViewportService/IViewportService.ts +64 -0
  172. package/src/services/ViewportService/Viewport.ts +372 -0
  173. package/src/services/ViewportService/adapter/IViewportAdapter.contract.test.ts +467 -0
  174. package/src/services/ViewportService/adapter/IViewportAdapter.ts +179 -0
  175. package/src/services/ViewportService/adapter/LegacyViewportAdapter.ts +240 -0
  176. package/src/services/ViewportService/adapter/NextViewportAdapter.ts +241 -0
  177. package/src/services/ViewportService/adapter/getViewportAdapter.ts +62 -0
  178. package/src/services/ViewportService/adapter/index.ts +16 -0
  179. package/src/services/ViewportService/backends/IViewportBackend.ts +195 -0
  180. package/src/services/ViewportService/backends/IViewportOperations.ts +98 -0
  181. package/src/services/ViewportService/backends/IViewportServiceInternals.ts +47 -0
  182. package/src/services/ViewportService/backends/LegacyViewportBackend.ts +264 -0
  183. package/src/services/ViewportService/backends/LegacyViewportOperations.ts +272 -0
  184. package/src/services/ViewportService/backends/NextViewportBackend.ts +671 -0
  185. package/src/services/ViewportService/backends/NextViewportOperations.ts +169 -0
  186. package/src/services/ViewportService/backends/README.md +62 -0
  187. package/src/services/ViewportService/backends/dataIdRegistry.ts +121 -0
  188. package/src/services/ViewportService/backends/viewportOperations.ts +71 -0
  189. package/src/services/ViewportService/constants.ts +3 -0
  190. package/src/state.ts +34 -0
  191. package/src/stores/index.ts +5 -0
  192. package/src/stores/presentationUtils.ts +42 -0
  193. package/src/stores/useLutPresentationStore.ts +166 -0
  194. package/src/stores/usePositionPresentationStore.ts +172 -0
  195. package/src/stores/useSegmentationPresentationStore.test.ts +146 -0
  196. package/src/stores/useSegmentationPresentationStore.ts +417 -0
  197. package/src/stores/useSelectedSegmentationsForViewportStore.ts +85 -0
  198. package/src/stores/useSynchronizersStore.ts +84 -0
  199. package/src/synchronizers/frameViewSynchronizer.ts +52 -0
  200. package/src/tools/CalibrationLineTool.ts +97 -0
  201. package/src/tools/ImageOverlayViewerTool.tsx +279 -0
  202. package/src/tools/OverlayPlaneModuleProvider.ts +40 -0
  203. package/src/tools/WindowLevelTool.test.ts +55 -0
  204. package/src/tools/WindowLevelTool.ts +22 -0
  205. package/src/types/AppTypes.ts +70 -0
  206. package/src/types/Colorbar.ts +114 -0
  207. package/src/types/Colormap.ts +16 -0
  208. package/src/types/CornerstoneCacheService.ts +40 -0
  209. package/src/types/CornerstoneServices.ts +18 -0
  210. package/src/types/Presentation.ts +83 -0
  211. package/src/types/SelectedSegmentationByTypeMap.ts +3 -0
  212. package/src/types/ViewportPresets.ts +53 -0
  213. package/src/types/VolumeLighting.ts +7 -0
  214. package/src/types/VolumeRenderingConfig.ts +8 -0
  215. package/src/types/WindowLevel.ts +5 -0
  216. package/src/types/index.ts +10 -0
  217. package/src/utils/ActiveViewportBehavior.tsx +80 -0
  218. package/src/utils/CornerstoneViewportDownloadForm.tsx +319 -0
  219. package/src/utils/DicomFileUploader.ts +204 -0
  220. package/src/utils/JumpPresets.ts +14 -0
  221. package/src/utils/autoHydrateViewportTypes.ts +69 -0
  222. package/src/utils/colormaps.js +1597 -0
  223. package/src/utils/createSegmentationForViewport.ts +83 -0
  224. package/src/utils/dicomLoaderService.js +225 -0
  225. package/src/utils/ecgMetadata.test.ts +137 -0
  226. package/src/utils/ecgMetadata.ts +109 -0
  227. package/src/utils/findNearbyToolData.test.ts +125 -0
  228. package/src/utils/findNearbyToolData.ts +21 -0
  229. package/src/utils/generateSegmentationCSVReport.test.ts +324 -0
  230. package/src/utils/generateSegmentationCSVReport.ts +131 -0
  231. package/src/utils/getActiveViewportEnabledElement.test.ts +70 -0
  232. package/src/utils/getActiveViewportEnabledElement.ts +8 -0
  233. package/src/utils/getCenterExtent.test.ts +313 -0
  234. package/src/utils/getCenterExtent.ts +46 -0
  235. package/src/utils/getCornerstoneBlendMode.test.ts +59 -0
  236. package/src/utils/getCornerstoneBlendMode.ts +25 -0
  237. package/src/utils/getCornerstoneOrientation.test.ts +78 -0
  238. package/src/utils/getCornerstoneOrientation.ts +31 -0
  239. package/src/utils/getCornerstoneViewportType.test.ts +169 -0
  240. package/src/utils/getCornerstoneViewportType.ts +88 -0
  241. package/src/utils/getInterleavedFrames.test.ts +85 -0
  242. package/src/utils/getInterleavedFrames.ts +73 -0
  243. package/src/utils/getLegacyViewportType.ts +64 -0
  244. package/src/utils/getNthFrames.test.ts +145 -0
  245. package/src/utils/getNthFrames.ts +31 -0
  246. package/src/utils/getViewportEnabledElement.test.ts +83 -0
  247. package/src/utils/getViewportEnabledElement.ts +8 -0
  248. package/src/utils/getViewportOrientationFromImageOrientationPatient.test.ts +50 -0
  249. package/src/utils/getViewportOrientationFromImageOrientationPatient.ts +56 -0
  250. package/src/utils/hydrationUtils.test.ts +572 -0
  251. package/src/utils/hydrationUtils.ts +197 -0
  252. package/src/utils/imageSliceSync/calculateViewportRegistrations.ts +28 -0
  253. package/src/utils/imageSliceSync/toggleImageSliceSync.ts +101 -0
  254. package/src/utils/index.ts +29 -0
  255. package/src/utils/initGpuSettingsPreset.ts +51 -0
  256. package/src/utils/initViewTiming.test.ts +342 -0
  257. package/src/utils/initViewTiming.ts +52 -0
  258. package/src/utils/initWebWorkerProgressHandler.test.ts +381 -0
  259. package/src/utils/initWebWorkerProgressHandler.ts +110 -0
  260. package/src/utils/interleave.test.ts +304 -0
  261. package/src/utils/interleave.ts +32 -0
  262. package/src/utils/interleaveCenterLoader.test.ts +547 -0
  263. package/src/utils/interleaveCenterLoader.ts +143 -0
  264. package/src/utils/interleaveTopToBottom.test.ts +487 -0
  265. package/src/utils/interleaveTopToBottom.ts +132 -0
  266. package/src/utils/isAnyDisplaySetCommon.ts +18 -0
  267. package/src/utils/isDisplaySetOverlayable.ts +96 -0
  268. package/src/utils/isMeasurementWithinViewport.test.ts +340 -0
  269. package/src/utils/isMeasurementWithinViewport.ts +33 -0
  270. package/src/utils/isReferenceViewable.test.ts +581 -0
  271. package/src/utils/isReferenceViewable.ts +95 -0
  272. package/src/utils/loadDisplaySetData.ts +49 -0
  273. package/src/utils/measurementServiceMappings/Angle.ts +200 -0
  274. package/src/utils/measurementServiceMappings/ArrowAnnotate.ts +176 -0
  275. package/src/utils/measurementServiceMappings/Bidirectional.ts +193 -0
  276. package/src/utils/measurementServiceMappings/CircleROI.ts +227 -0
  277. package/src/utils/measurementServiceMappings/CobbAngle.ts +206 -0
  278. package/src/utils/measurementServiceMappings/EllipticalROI.ts +221 -0
  279. package/src/utils/measurementServiceMappings/Length.ts +206 -0
  280. package/src/utils/measurementServiceMappings/LivewireContour.ts +175 -0
  281. package/src/utils/measurementServiceMappings/PlanarFreehandROI.ts +228 -0
  282. package/src/utils/measurementServiceMappings/Probe.ts +192 -0
  283. package/src/utils/measurementServiceMappings/RectangleROI.ts +225 -0
  284. package/src/utils/measurementServiceMappings/SegmentBidirectional.ts +184 -0
  285. package/src/utils/measurementServiceMappings/SplineROI.ts +227 -0
  286. package/src/utils/measurementServiceMappings/UltrasoundDirectional.ts +214 -0
  287. package/src/utils/measurementServiceMappings/UltrasoundPleuraBLine.ts +179 -0
  288. package/src/utils/measurementServiceMappings/constants/supportedTools.js +21 -0
  289. package/src/utils/measurementServiceMappings/index.ts +3 -0
  290. package/src/utils/measurementServiceMappings/measurementServiceMappingsFactory.ts +324 -0
  291. package/src/utils/measurementServiceMappings/utils/getDisplayUnit.js +3 -0
  292. package/src/utils/measurementServiceMappings/utils/getHandlesFromPoints.js +14 -0
  293. package/src/utils/measurementServiceMappings/utils/getIsLocked.ts +5 -0
  294. package/src/utils/measurementServiceMappings/utils/getIsVisible.ts +6 -0
  295. package/src/utils/measurementServiceMappings/utils/getSOPInstanceAttributes.js +66 -0
  296. package/src/utils/measurementServiceMappings/utils/getValueDisplayString.js +12 -0
  297. package/src/utils/measurementServiceMappings/utils/index.ts +17 -0
  298. package/src/utils/measurementServiceMappings/utils/selection.ts +33 -0
  299. package/src/utils/mpr/getProtocolViewportStructureFromGridViewports.ts +74 -0
  300. package/src/utils/nextViewportPolicies.ts +41 -0
  301. package/src/utils/nextViewports.ts +157 -0
  302. package/src/utils/nthLoader.test.ts +317 -0
  303. package/src/utils/nthLoader.ts +78 -0
  304. package/src/utils/presentations/getViewportPresentations.test.ts +280 -0
  305. package/src/utils/presentations/getViewportPresentations.ts +151 -0
  306. package/src/utils/promptHydrationDialog.test.ts +490 -0
  307. package/src/utils/promptHydrationDialog.ts +197 -0
  308. package/src/utils/removeViewportSegmentationRepresentations.test.ts +129 -0
  309. package/src/utils/removeViewportSegmentationRepresentations.ts +17 -0
  310. package/src/utils/segmentUtils.test.ts +515 -0
  311. package/src/utils/segmentUtils.ts +46 -0
  312. package/src/utils/segmentationExportUtils.test.ts +100 -0
  313. package/src/utils/segmentationExportUtils.ts +171 -0
  314. package/src/utils/segmentationHandlers.test.ts +614 -0
  315. package/src/utils/segmentationHandlers.ts +164 -0
  316. package/src/utils/setUpAnnotationEventHandlers.ts +26 -0
  317. package/src/utils/setUpSegmentationEventHandlers.test.ts +372 -0
  318. package/src/utils/setUpSegmentationEventHandlers.ts +122 -0
  319. package/src/utils/toggleVOISliceSync.test.ts +606 -0
  320. package/src/utils/toggleVOISliceSync.ts +103 -0
  321. package/src/utils/transitions.test.ts +351 -0
  322. package/src/utils/transitions.ts +300 -0
  323. package/src/utils/updateSegmentationStats.test.ts +942 -0
  324. package/src/utils/updateSegmentationStats.ts +192 -0
  325. package/src/utils/viewportDataShape.ts +85 -0
@@ -0,0 +1,1814 @@
1
+ import { vec3 } from 'gl-matrix';
2
+ import { PubSubService } from '@ohif/core';
3
+ import { Types as OhifTypes } from '@ohif/core';
4
+ import {
5
+ RenderingEngine,
6
+ Types,
7
+ getRenderingEngine,
8
+ utilities as csUtils,
9
+ cache,
10
+ Enums as csEnums,
11
+ metaData,
12
+ } from '@cornerstonejs/core';
13
+
14
+ import { utilities as csToolsUtils, Enums as csToolsEnums } from '@cornerstonejs/tools';
15
+ import { IViewportService } from './IViewportService';
16
+ import { RENDERING_ENGINE_ID } from './constants';
17
+ import ViewportInfo, {
18
+ DisplaySetOptions,
19
+ PublicViewportOptions,
20
+ ViewportOptions,
21
+ } from './Viewport';
22
+ import { StackViewportData, VolumeViewportData } from '../../types/CornerstoneCacheService';
23
+ import {
24
+ LutPresentation,
25
+ PositionPresentation,
26
+ Presentations,
27
+ SegmentationPresentation,
28
+ SegmentationPresentationItem,
29
+ } from '../../types/Presentation';
30
+
31
+ import JumpPresets from '../../utils/JumpPresets';
32
+ import { ViewportProperties } from '@cornerstonejs/core/types';
33
+ import { useLutPresentationStore } from '../../stores/useLutPresentationStore';
34
+ import { usePositionPresentationStore } from '../../stores/usePositionPresentationStore';
35
+ import { useSynchronizersStore } from '../../stores/useSynchronizersStore';
36
+ import { useSegmentationPresentationStore } from '../../stores/useSegmentationPresentationStore';
37
+ import getClosestOrientationFromIOP from '../../utils/isReferenceViewable';
38
+ import { getViewportAdapter } from './adapter';
39
+ import { viewportOperations } from './backends/viewportOperations';
40
+ import {
41
+ getLegacyViewportType,
42
+ isVolume3DViewportType,
43
+ isVolumeViewportType,
44
+ } from '../../utils/getLegacyViewportType';
45
+ import { BlendModes } from '@cornerstonejs/core/enums';
46
+ import { isNextViewportsEnabled } from '../../utils/nextViewports';
47
+ import { isAutoHydrateViewportType } from '../../utils/autoHydrateViewportTypes';
48
+ import type { IViewportBackend } from './backends/IViewportBackend';
49
+ import type { IViewportServiceInternals } from './backends/IViewportServiceInternals';
50
+ import { LegacyViewportBackend } from './backends/LegacyViewportBackend';
51
+ import { NextViewportBackend } from './backends/NextViewportBackend';
52
+
53
+ const EVENTS = {
54
+ VIEWPORT_DATA_CHANGED: 'event::cornerstoneViewportService:viewportDataChanged',
55
+ VIEWPORT_VOLUMES_CHANGED: 'event::cornerstoneViewportService:viewportVolumesChanged',
56
+ };
57
+
58
+ const MIN_STACK_VIEWPORTS_TO_ENQUEUE_RESIZE = 12;
59
+ const MIN_VOLUME_VIEWPORTS_TO_ENQUEUE_RESIZE = 6;
60
+
61
+ // Actor class names that represent a primary volume binding in a viewport.
62
+ // Legacy ORTHOGRAPHIC / VOLUME_3D render the source volume as a 'vtkVolume'
63
+ // actor. Under the GenericViewport-backed compat path (useGenericViewport),
64
+ // the MPR slice render path emits 'vtkImageSlice' actors instead, so the
65
+ // volume-set-vs-add optimization below must recognize both. (3D still uses
66
+ // 'vtkVolume'.) Without this, the optimization silently no-ops and a full
67
+ // setVolumes() teardown blanks MPR during SEG hydration.
68
+ const VOLUME_ACTOR_CLASS_NAMES = new Set(['vtkVolume', 'vtkImageSlice']);
69
+
70
+ function getVolumeActorReferencedIds(viewport: Types.IVolumeViewport): string[] {
71
+ const actors = viewport.getActors?.() ?? [];
72
+ return actors
73
+ .filter(ac => VOLUME_ACTOR_CLASS_NAMES.has(ac.actor?.getClassName?.() ?? ''))
74
+ .map(ac => ac.referencedId)
75
+ .filter(Boolean) as string[];
76
+ }
77
+
78
+ function volumeIdPrefixesMatch(
79
+ existingIds: string[],
80
+ prefixLen: number,
81
+ targetIds: string[]
82
+ ): boolean {
83
+ if (prefixLen > targetIds.length) {
84
+ return false;
85
+ }
86
+ for (let i = 0; i < prefixLen; i++) {
87
+ if (existingIds[i] !== targetIds[i]) {
88
+ return false;
89
+ }
90
+ }
91
+ return true;
92
+ }
93
+
94
+ /**
95
+ * Returns true when the viewport type matches a volume-based presentation (ORTHOGRAPHIC or VOLUME_3D).
96
+ */
97
+ function viewportMatchesDesiredVolumePresentation(
98
+ viewport: Types.IViewport,
99
+ desiredViewportInfo: ViewportInfo
100
+ ): boolean {
101
+ const desiredType = desiredViewportInfo.getViewportType();
102
+ if (getLegacyViewportType(viewport) !== desiredType) {
103
+ return false;
104
+ }
105
+ return (
106
+ desiredType === csEnums.ViewportType.ORTHOGRAPHIC ||
107
+ desiredType === csEnums.ViewportType.VOLUME_3D
108
+ );
109
+ }
110
+
111
+ export const WITH_NAVIGATION = { withNavigation: true, withOrientation: false };
112
+ export const WITH_ORIENTATION = { withNavigation: true, withOrientation: true };
113
+
114
+ /**
115
+ * Handles cornerstone viewport logic including enabling, disabling, and
116
+ * updating the viewport.
117
+ */
118
+ class CornerstoneViewportService
119
+ extends PubSubService
120
+ implements IViewportService, IViewportServiceInternals
121
+ {
122
+ static REGISTRATION = {
123
+ name: 'cornerstoneViewportService',
124
+ altName: 'CornerstoneViewportService',
125
+ create: ({
126
+ servicesManager,
127
+ }: OhifTypes.Extensions.ExtensionParams): CornerstoneViewportService => {
128
+ return new CornerstoneViewportService(servicesManager);
129
+ },
130
+ };
131
+
132
+ renderingEngine: Types.IRenderingEngine | null;
133
+ viewportsById: Map<string, ViewportInfo> = new Map();
134
+ viewportGridResizeObserver: ResizeObserver | null;
135
+ viewportsDisplaySets: Map<string, string[]> = new Map();
136
+ beforeResizePositionPresentations: Map<string, PositionPresentation> = new Map();
137
+
138
+ // Some configs
139
+ servicesManager: AppTypes.ServicesManager = null;
140
+
141
+ resizeQueue = [];
142
+ viewportResizeTimer = null;
143
+ gridResizeDelay = 50;
144
+ gridResizeTimeOut = null;
145
+
146
+ // Resolved once, lazily, on first use. Forked viewport concerns (mount dispatch +
147
+ // native dataId lifecycle) route through it.
148
+ private _backend: IViewportBackend | null = null;
149
+
150
+ constructor(servicesManager: AppTypes.ServicesManager) {
151
+ super(EVENTS);
152
+ this.renderingEngine = null;
153
+ this.viewportGridResizeObserver = null;
154
+ this.servicesManager = servicesManager;
155
+ }
156
+
157
+ /**
158
+ * Sanctioned flag read (the exhaustive list lives in backends/README.md): pick
159
+ * the viewport backend once, on first use. Resolved lazily (not in the
160
+ * constructor) because the service singleton is constructed during extension
161
+ * registration, BEFORE init.tsx runs setNextViewportsEnabled — the first mount
162
+ * (when this is first read) always happens after init, so the flag is settled.
163
+ */
164
+ private get backend(): IViewportBackend {
165
+ if (!this._backend) {
166
+ this._backend = isNextViewportsEnabled()
167
+ ? new NextViewportBackend(this)
168
+ : new LegacyViewportBackend(this);
169
+ }
170
+ return this._backend;
171
+ }
172
+ hangingProtocolService: unknown;
173
+ viewportsInfo: unknown;
174
+ sceneVolumeInputs: unknown;
175
+ viewportDivElements: unknown;
176
+ ViewportPropertiesMap: unknown;
177
+ volumeUIDs: unknown;
178
+ displaySetsNeedRerendering: unknown;
179
+ viewportDisplaySets: unknown;
180
+
181
+ /**
182
+ * Adds the HTML element to the viewportService
183
+ * @param {*} viewportId
184
+ * @param {*} elementRef
185
+ */
186
+ public enableViewport(viewportId: string, elementRef: HTMLDivElement): void {
187
+ const viewportInfo = new ViewportInfo(viewportId);
188
+ viewportInfo.setElement(elementRef);
189
+ this.viewportsById.set(viewportId, viewportInfo);
190
+ }
191
+
192
+ public getViewportIds(): string[] {
193
+ return Array.from(this.viewportsById.keys());
194
+ }
195
+
196
+ /**
197
+ * It retrieves the renderingEngine if it does exist, or creates one otherwise
198
+ * @returns {RenderingEngine} rendering engine
199
+ */
200
+ public getRenderingEngine() {
201
+ // get renderingEngine from cache if it exists
202
+ const renderingEngine = getRenderingEngine(RENDERING_ENGINE_ID);
203
+
204
+ if (renderingEngine) {
205
+ this.renderingEngine = renderingEngine;
206
+ return this.renderingEngine;
207
+ }
208
+
209
+ if (!renderingEngine || renderingEngine.hasBeenDestroyed) {
210
+ this.renderingEngine = new RenderingEngine(RENDERING_ENGINE_ID);
211
+ }
212
+
213
+ return this.renderingEngine;
214
+ }
215
+
216
+ /**
217
+ * It triggers the resize on the rendering engine, and renders the viewports
218
+ *
219
+ */
220
+ public resize() {
221
+ // https://stackoverflow.com/a/26279685
222
+ // This resize() call, among other things, rerenders the viewports. But when the entire viewer is
223
+ // display: none'd, it makes the size of all hidden elements 0, including the viewport canvas and its containers.
224
+ // Even if the viewer is later displayed again, trying to render when the size is 0 permanently "breaks" the
225
+ // viewport, making it fully black even after the size is normal again. So just ignore resize events when hidden:
226
+ const areViewportsHidden = Array.from(this.viewportsById.values()).every(viewportInfo => {
227
+ const element = viewportInfo.getElement();
228
+
229
+ return element.clientWidth === 0 && element.clientHeight === 0;
230
+ });
231
+ if (areViewportsHidden) {
232
+ console.warn('Ignoring resize when viewports have size 0');
233
+ return;
234
+ }
235
+
236
+ const numStackViewportsInViewportGrid = Array.from(this.viewportsById.values()).filter(
237
+ viewportInfo => viewportInfo.getViewportType() === csEnums.ViewportType.STACK
238
+ ).length;
239
+
240
+ const numVolumeViewportsInViewportGrid = Array.from(this.viewportsById.values()).filter(
241
+ viewportInfo => viewportInfo.getViewportType() === csEnums.ViewportType.ORTHOGRAPHIC
242
+ ).length;
243
+
244
+ const isEasyResize =
245
+ numStackViewportsInViewportGrid <= MIN_STACK_VIEWPORTS_TO_ENQUEUE_RESIZE &&
246
+ numVolumeViewportsInViewportGrid <= MIN_VOLUME_VIEWPORTS_TO_ENQUEUE_RESIZE;
247
+
248
+ // if there is a grid resize happening, it means the viewport grid
249
+ // has been manipulated (e.g., panels closed, added, etc.) and we need
250
+ // to resize all viewports, so we will add a timeout here to make sure
251
+ // we don't double resize the viewports when viewports in the grid are
252
+ // resized individually
253
+ if (isEasyResize) {
254
+ this.performResize();
255
+ this.resetGridResizeTimeout();
256
+ this.resizeQueue = [];
257
+ clearTimeout(this.viewportResizeTimer);
258
+ } else {
259
+ this.enqueueViewportResizeRequest();
260
+ }
261
+ }
262
+
263
+ /**
264
+ * Removes the viewport from cornerstone, and destroys the rendering engine
265
+ */
266
+ public destroy() {
267
+ this._removeResizeObserver();
268
+ this.viewportGridResizeObserver = null;
269
+ // Flush any native dataId registrations the backend owns (§4.7); no-op for legacy.
270
+ this.backend.destroy();
271
+ try {
272
+ this.renderingEngine?.destroy?.();
273
+ } catch (e) {
274
+ console.warn('Rendering engine not destroyed', e);
275
+ }
276
+ this.viewportsDisplaySets.clear();
277
+ this.renderingEngine = null;
278
+ cache.purgeCache();
279
+ }
280
+
281
+ /**
282
+ * Disables the viewport inside the renderingEngine, if no viewport is left
283
+ * it destroys the renderingEngine.
284
+ *
285
+ * This is called when the element goes away entirely - with new viewportId's
286
+ * created for every new viewport, this will be called whenever the set of
287
+ * viewports is changed, but NOT when the viewport position changes only.
288
+ *
289
+ * @param viewportId - The viewportId to disable
290
+ */
291
+ public disableElement(viewportId: string): void {
292
+ // Release native dataId registrations BEFORE the viewport bookkeeping is
293
+ // deleted (§4.7 ref-counted GC); no-op for the legacy backend.
294
+ this.backend.onViewportDisabled(viewportId);
295
+
296
+ this.renderingEngine?.disableElement(viewportId);
297
+
298
+ // clean up
299
+ this.viewportsById.delete(viewportId);
300
+ this.viewportsDisplaySets.delete(viewportId);
301
+ }
302
+
303
+ /**
304
+ * Sets the presentations for a given viewport. Presentations is an object
305
+ * that can define the lut or position for a viewport.
306
+ *
307
+ * @param viewportId - The ID of the viewport.
308
+ * @param presentations - The presentations to apply to the viewport.
309
+ * @param viewportInfo - Contains a view reference for immediate application
310
+ */
311
+ // Public so the viewport backends (IViewportServiceInternals) can record which
312
+ // display sets a viewport shows from their mount bodies.
313
+ _trackViewportDisplaySets(viewportId: string, displaySetInstanceUIDs: string[]): void {
314
+ this.viewportsDisplaySets.set(viewportId, displaySetInstanceUIDs);
315
+ }
316
+
317
+ public setPresentations(viewportId: string, presentations: Presentations): void {
318
+ const viewport = this.getCornerstoneViewport(viewportId) as
319
+ | Types.IStackViewport
320
+ | Types.IVolumeViewport;
321
+
322
+ if (!viewport || !presentations) {
323
+ return;
324
+ }
325
+
326
+ const { lutPresentation, positionPresentation, segmentationPresentation } = presentations;
327
+
328
+ // Always set the segmentation presentation first, since there might be some
329
+ // lutpresentation states that need to be set on the segmentation
330
+ // Todo: i think we should even await this
331
+ this._setSegmentationPresentation(viewport, segmentationPresentation);
332
+
333
+ this._setLutPresentation(viewport, lutPresentation);
334
+ this._setPositionPresentation(viewport, { ...positionPresentation, viewportId });
335
+ }
336
+
337
+ /**
338
+ * Stores the presentation state for a given viewport inside the
339
+ * each store. This is used to persist the presentation state
340
+ * across different scenarios e.g., when the viewport is changing the
341
+ * display set, or when the viewport is moving to a different layout.
342
+ *
343
+ * @param viewportId The ID of the viewport.
344
+ */
345
+ public storePresentation({ viewportId }) {
346
+ const presentationIds = this.getPresentationIds(viewportId);
347
+ const { syncGroupService } = this.servicesManager.services;
348
+ const synchronizers = syncGroupService.getSynchronizersForViewport(viewportId);
349
+
350
+ if (!presentationIds || Object.keys(presentationIds).length === 0) {
351
+ return null;
352
+ }
353
+
354
+ const { lutPresentationId, positionPresentationId, segmentationPresentationId } =
355
+ presentationIds;
356
+
357
+ const positionPresentation = this._getPositionPresentation(viewportId);
358
+ const lutPresentation = this._getLutPresentation(viewportId);
359
+ const segmentationPresentation = this._getSegmentationPresentation(viewportId);
360
+
361
+ const { setLutPresentation } = useLutPresentationStore.getState();
362
+ const { setPositionPresentation } = usePositionPresentationStore.getState();
363
+ const { setSynchronizers } = useSynchronizersStore.getState();
364
+ const { syncSegmentationPresentation } = useSegmentationPresentationStore.getState();
365
+
366
+ if (lutPresentationId) {
367
+ setLutPresentation(lutPresentationId, lutPresentation);
368
+ }
369
+
370
+ if (positionPresentationId) {
371
+ setPositionPresentation(positionPresentationId, positionPresentation);
372
+ }
373
+
374
+ if (segmentationPresentationId) {
375
+ syncSegmentationPresentation(
376
+ segmentationPresentationId,
377
+ (segmentationPresentation ?? []).map(item => ({
378
+ ...item,
379
+ hydrated: this._getInitialHydrationForSync(item.segmentationId),
380
+ }))
381
+ );
382
+ }
383
+
384
+ if (synchronizers?.length) {
385
+ setSynchronizers(
386
+ viewportId,
387
+ synchronizers.map(synchronizer => ({
388
+ id: synchronizer.id,
389
+ sourceViewports: [...synchronizer.getSourceViewports()],
390
+ targetViewports: [...synchronizer.getTargetViewports()],
391
+ }))
392
+ );
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Retrieves the presentations for a given viewport.
398
+ * @param viewportId - The ID of the viewport.
399
+ * @returns The presentations for the viewport.
400
+ */
401
+ public getPresentations(viewportId: string): Presentations {
402
+ const positionPresentation = this._getPositionPresentation(viewportId);
403
+ const lutPresentation = this._getLutPresentation(viewportId);
404
+ const segmentationPresentation = this._getSegmentationPresentation(viewportId);
405
+
406
+ return {
407
+ positionPresentation,
408
+ lutPresentation,
409
+ segmentationPresentation,
410
+ };
411
+ }
412
+
413
+ private getPresentationIds(viewportId: string): AppTypes.PresentationIds | null {
414
+ const viewportInfo = this.viewportsById.get(viewportId);
415
+ if (!viewportInfo) {
416
+ return null;
417
+ }
418
+
419
+ return viewportInfo.getPresentationIds();
420
+ }
421
+
422
+ private _getPositionPresentation(viewportId: string): PositionPresentation {
423
+ const csViewport = this.getCornerstoneViewport(viewportId);
424
+ if (!csViewport) {
425
+ return;
426
+ }
427
+
428
+ const viewportInfo = this.viewportsById.get(viewportId);
429
+
430
+ // Forked per backend (§4.3 presentation read): legacy reads getViewPresentation
431
+ // (pan/zoom); native omits it (a PLANAR_NEXT viewport has no getViewPresentation).
432
+ return this.backend.getPositionPresentation(csViewport, viewportInfo, viewportId);
433
+ }
434
+
435
+ private _getLutPresentation(viewportId: string): LutPresentation {
436
+ const csViewport = this.getCornerstoneViewport(viewportId) as
437
+ | Types.IStackViewport
438
+ | Types.IVolumeViewport;
439
+
440
+ if (!csViewport) {
441
+ return;
442
+ }
443
+
444
+ const cleanProperties = properties => {
445
+ if (properties?.isComputedVOI) {
446
+ delete properties?.voiRange;
447
+ delete properties?.VOILUTFunction;
448
+ }
449
+ if (properties?.colormap) {
450
+ if (properties.colormap?.opacity?.length === 0) {
451
+ delete properties.colormap.opacity;
452
+ }
453
+ }
454
+ return properties;
455
+ };
456
+
457
+ const properties = isVolumeViewportType(csViewport)
458
+ ? new Map()
459
+ : cleanProperties(getViewportAdapter(csViewport).getPresentation());
460
+
461
+ if (properties instanceof Map) {
462
+ const volumeIds = (csViewport as Types.IBaseVolumeViewport).getAllVolumeIds();
463
+ volumeIds?.forEach(volumeId => {
464
+ const csProps = cleanProperties(csViewport.getProperties(volumeId));
465
+ properties.set(volumeId, csProps);
466
+ });
467
+ }
468
+
469
+ const viewportInfo = this.viewportsById.get(viewportId);
470
+
471
+ return {
472
+ viewportType: viewportInfo.getViewportType(),
473
+ properties,
474
+ };
475
+ }
476
+
477
+ private _getSegmentationPresentation(viewportId: string): SegmentationPresentation {
478
+ const { segmentationService } = this.servicesManager.services;
479
+
480
+ const presentation = segmentationService.getPresentation(viewportId);
481
+ return presentation;
482
+ }
483
+
484
+ /**
485
+ * The `hydrated` to record for a segmentation the presentation store has not
486
+ * heard of yet (`syncSegmentationPresentation` keeps the recorded value for
487
+ * one it has).
488
+ *
489
+ * Hydration is owned by the hydration paths exactly when they can record it,
490
+ * and `updateStoredSegmentationPresentation` keys the store by the referenced
491
+ * display set - so a segmentation whose display set has one gets `null` ("no
492
+ * statement"), leaving it to the hydration prompt, the segmentation panel and
493
+ * the study browser to say whether it belongs in the standard view. Anything
494
+ * else - a segmentation drawn in the client, or one whose display set has not
495
+ * been registered yet - has no other record, so the viewport it lives in is
496
+ * the authority and it is recorded as shown.
497
+ */
498
+ private _getInitialHydrationForSync(segmentationId: string): boolean | null {
499
+ const { displaySetService } = this.servicesManager.services;
500
+
501
+ const displaySet = displaySetService.getDisplaySetByUID(segmentationId);
502
+
503
+ return displaySet?.referencedDisplaySetInstanceUID ? null : true;
504
+ }
505
+
506
+ /**
507
+ * Sets the viewport data for a viewport.
508
+ * @param viewportId - The ID of the viewport to set the data for.
509
+ * @param viewportData - The viewport data to set.
510
+ * @param publicViewportOptions - The public viewport options.
511
+ * @param publicDisplaySetOptions - The public display set options.
512
+ * @param presentations - The presentations to set.
513
+ */
514
+ public setViewportData(
515
+ viewportId: string,
516
+ viewportData: StackViewportData | VolumeViewportData,
517
+ publicViewportOptions: PublicViewportOptions,
518
+ publicDisplaySetOptions: DisplaySetOptions[],
519
+ presentations?: Presentations
520
+ ): void {
521
+ const renderingEngine = this.getRenderingEngine();
522
+
523
+ // if not valid viewportData then return early
524
+ if (viewportData.viewportType === csEnums.ViewportType.STACK) {
525
+ // check if imageIds is valid
526
+ if (!viewportData.data[0].imageIds?.length) {
527
+ return;
528
+ }
529
+ }
530
+
531
+ // This is the old viewportInfo, which may have old options but we might be
532
+ // using its viewport (same viewportId as the new viewportInfo)
533
+ const viewportInfo = this.viewportsById.get(viewportId);
534
+
535
+ // We should store the presentation for the current viewport since we can't only
536
+ // rely to store it WHEN the viewport is disabled since we might keep around the
537
+ // same viewport/element and just change the viewportData for it (drag and drop etc.)
538
+ // the disableElement storePresentation handle would not be called in this case
539
+ // and we would lose the presentation.
540
+ this.storePresentation({ viewportId: viewportInfo.getViewportId() });
541
+
542
+ // Todo: i don't like this here, move it
543
+ this.servicesManager.services.segmentationService.clearSegmentationRepresentations(
544
+ viewportInfo.getViewportId()
545
+ );
546
+
547
+ if (!viewportInfo) {
548
+ throw new Error('element is not enabled for the given viewportId');
549
+ }
550
+
551
+ // override the viewportOptions and displaySetOptions with the public ones
552
+ // since those are the newly set ones, we set them here so that it handles defaults
553
+ const displaySetOptions = viewportInfo.setPublicDisplaySetOptions(publicDisplaySetOptions);
554
+ // Specify an over-ride for the viewport type, even though it is in the public
555
+ // viewport options, because the one in the viewportData is a requirement based on the
556
+ // type of data being displayed.
557
+ const viewportOptions = viewportInfo.setPublicViewportOptions(
558
+ publicViewportOptions,
559
+ viewportData.viewportType
560
+ );
561
+
562
+ const element = viewportInfo.getElement();
563
+ const type = viewportInfo.getViewportType();
564
+ const background = viewportInfo.getBackground();
565
+ const orientation = viewportInfo.getOrientation();
566
+ const displayArea = viewportInfo.getDisplayArea();
567
+
568
+ const viewportInput: Types.PublicViewportInput = {
569
+ viewportId,
570
+ element,
571
+ type,
572
+ defaultOptions: {
573
+ background,
574
+ orientation,
575
+ displayArea,
576
+ },
577
+ };
578
+
579
+ // Rendering Engine Id set should happen before enabling the element
580
+ // since there are callbacks that depend on the renderingEngine id
581
+ // Todo: however, this is a limitation which means that we can't change
582
+ // the rendering engine id for a given viewport which might be a super edge
583
+ // case
584
+ viewportInfo.setRenderingEngineId(renderingEngine.id);
585
+
586
+ // Todo: this is not optimal at all, we are re-enabling the already enabled
587
+ // element which is not what we want. But enabledElement as part of the
588
+ // renderingEngine is designed to be used like this. This will trigger
589
+ // ENABLED_ELEMENT again and again, which will run onEnableElement callbacks
590
+ renderingEngine.enableElement(viewportInput);
591
+
592
+ viewportInfo.setViewportOptions(viewportOptions);
593
+ viewportInfo.setDisplaySetOptions(displaySetOptions);
594
+ viewportInfo.setViewportData(viewportData);
595
+ viewportInfo.setViewportId(viewportId);
596
+
597
+ this.viewportsById.set(viewportId, viewportInfo);
598
+
599
+ const viewport = renderingEngine.getViewport(viewportId);
600
+ const displaySetPromise = this._setDisplaySets(
601
+ viewport,
602
+ viewportData,
603
+ viewportInfo,
604
+ presentations
605
+ );
606
+
607
+ // The broadcast event here ensures that listeners have a valid, up to date
608
+ // viewport to access. Doing it too early can result in exceptions or
609
+ // invalid data.
610
+ displaySetPromise.then(
611
+ () => {
612
+ this._broadcastEvent(this.EVENTS.VIEWPORT_DATA_CHANGED, {
613
+ viewportData,
614
+ viewportId,
615
+ });
616
+ },
617
+ error => console.error('[CornerstoneViewportService] Failed to set the viewport data', error)
618
+ );
619
+ }
620
+
621
+ public getViewportOptions(viewportId: string): ViewportOptions {
622
+ return this.viewportsById.get(viewportId).getViewportOptions();
623
+ }
624
+
625
+ /**
626
+ * Retrieves the Cornerstone viewport with the specified ID.
627
+ *
628
+ * @param viewportId - The ID of the viewport.
629
+ * @returns The Cornerstone viewport object if found, otherwise null.
630
+ */
631
+ public getCornerstoneViewport(viewportId: string): Types.IViewport | null {
632
+ const viewportInfo = this.getViewportInfo(viewportId);
633
+
634
+ if (!viewportInfo || !this.renderingEngine || this.renderingEngine.hasBeenDestroyed) {
635
+ return null;
636
+ }
637
+
638
+ const viewport = this.renderingEngine.getViewport(viewportId);
639
+
640
+ return viewport;
641
+ }
642
+
643
+ /**
644
+ * Retrieves the viewport information for a given viewport ID. The viewport information
645
+ * is the OHIF construct that holds different options and data for a given viewport and
646
+ * is different from the cornerstone viewport.
647
+ *
648
+ * @param viewportId The ID of the viewport.
649
+ * @returns The viewport information.
650
+ */
651
+ public getViewportInfo(viewportId: string): ViewportInfo {
652
+ return this.viewportsById.get(viewportId);
653
+ }
654
+
655
+ public getOrientation(viewportId: string): string {
656
+ const viewportInfo = this.getViewportInfo(viewportId);
657
+ return viewportInfo.getOrientation();
658
+ }
659
+
660
+ /**
661
+ * Looks through the viewports to see if the specified measurement can be
662
+ * displayed in one of the viewports. This function tries to get a "best fit"
663
+ * viewport to display the image in where it matches, in order:
664
+ * * Active viewport that can be navigated to the given image without orientation change
665
+ * * Other viewport that can be navigated to the given image without orientation change
666
+ * * Best-aligned viewport that can display the image with an orientation change
667
+ *
668
+ * It returns `null` otherwise, indicating that a viewport needs display set/type
669
+ * changes in order to display the image.
670
+ *
671
+ * Notes:
672
+ * * If the display set is displayed in multiple viewports all needing orientation change,
673
+ * then the active one or first one listed will be modified. This can create unexpected
674
+ * behaviour for MPR views.
675
+ * * If the image is contained in multiple display sets, then the first one
676
+ * found will be navigated (active first, followed by first found)
677
+ *
678
+ * @param measurement - The measurement that is desired to view.
679
+ * @param activeViewportId - the index that was active at the time the jump
680
+ * was initiated.
681
+ * @return the viewportId that the measurement should be displayed in.
682
+ */
683
+ public findNavigationCompatibleViewportId(activeViewportId: string, metadata): string {
684
+ // First check if the active viewport can just be navigated to show the given item
685
+ const activeViewport = this.getCornerstoneViewport(activeViewportId);
686
+ if (!activeViewport) {
687
+ console.warn('No active viewport found for', activeViewportId);
688
+ }
689
+ if (activeViewport?.isReferenceViewable(metadata, WITH_NAVIGATION)) {
690
+ return activeViewportId;
691
+ }
692
+
693
+ // Next, see if any viewport could be navigated to show the given item,
694
+ // without considering orientation changes.
695
+ for (const id of this.viewportsById.keys()) {
696
+ const viewport = this.getCornerstoneViewport(id);
697
+ if (viewport?.isReferenceViewable(metadata, WITH_NAVIGATION)) {
698
+ return id;
699
+ }
700
+ }
701
+
702
+ // Compute view-plane alignment scores for all viewports to prefer the one
703
+ // requiring the least orientation change when navigation-only is not possible.
704
+ const viewportAlignmentData = this.getViewportAlignmentData(metadata);
705
+
706
+ // See if any viewport could show this with an orientation change
707
+ for (const { viewportId: id } of viewportAlignmentData) {
708
+ const viewport = this.getCornerstoneViewport(id);
709
+ if (viewport?.isReferenceViewable(metadata, WITH_ORIENTATION)) {
710
+ return id;
711
+ }
712
+ }
713
+
714
+ // No luck, need to update the viewport itself
715
+ return null;
716
+ }
717
+
718
+ /**
719
+ * Given a metadata instance containing a planeRestriction, returns the
720
+ * ordered list of best orientation match viewport ids.
721
+ *
722
+ * This uses the planeRestriction preferentially as that one is more reliably
723
+ * filled than the viewport normal since it is created from data points on
724
+ * rehydration.
725
+ */
726
+ public getViewportAlignmentData(metadata) {
727
+ const viewportAlignmentData = [];
728
+ const { viewPlaneNormal: refViewPlaneNormal, planeRestriction } = metadata;
729
+ const inPlaneVector1 = planeRestriction?.inPlaneVector1;
730
+ const inPlaneVector2 = planeRestriction?.inPlaneVector2;
731
+
732
+ for (const id of this.viewportsById.keys()) {
733
+ const viewport = this.getCornerstoneViewport(id);
734
+ // Lane-appropriate view-plane normal (legacy getCamera vs native getViewReference).
735
+ const viewPlaneNormal = viewportOperations.getViewPlaneNormal(viewport);
736
+
737
+ if (!viewPlaneNormal) {
738
+ continue;
739
+ }
740
+ let alignmentScore = 0;
741
+ if (inPlaneVector1 || inPlaneVector2) {
742
+ const inPlane1Score = inPlaneVector1
743
+ ? -Math.abs(vec3.dot(viewPlaneNormal, inPlaneVector1))
744
+ : 0;
745
+ const inPlane2Score = inPlaneVector2
746
+ ? -Math.abs(vec3.dot(viewPlaneNormal, inPlaneVector2))
747
+ : 0;
748
+ alignmentScore = inPlane1Score + inPlane2Score;
749
+ } else if (refViewPlaneNormal) {
750
+ alignmentScore = Math.abs(vec3.dot(viewPlaneNormal, refViewPlaneNormal));
751
+ }
752
+ viewportAlignmentData.push({ viewportId: id, alignmentScore });
753
+ }
754
+
755
+ // Try best-aligned viewports first
756
+ viewportAlignmentData.sort((a, b) => b.alignmentScore - a.alignmentScore);
757
+ return viewportAlignmentData;
758
+ }
759
+
760
+ /**
761
+ * Figures out which viewport to update when the viewport type needs to change.
762
+ * Orchestrates the search strategies in order of preference.
763
+ */
764
+ public findUpdateableViewportConfiguration(activeViewportId: string, measurement) {
765
+ const { metadata, displaySetInstanceUID } = measurement;
766
+ const { displaySetService } = this.servicesManager.services;
767
+ const displaySet = displaySetService.getDisplaySetByUID(displaySetInstanceUID);
768
+
769
+ // 1. Determine the target Viewport Type (Stack vs Volume)
770
+ const viewportType = this.determineTargetViewportType(displaySet, metadata);
771
+
772
+ // 2. Strategy: Find viewport already showing this volume
773
+ const volumeMatch = this.findViewportShowingVolume(
774
+ metadata,
775
+ displaySetInstanceUID,
776
+ viewportType
777
+ );
778
+ if (volumeMatch) {
779
+ return volumeMatch;
780
+ }
781
+
782
+ // 3. Strategy: Find viewport with compatible orientation (even if different display set)
783
+ const compatibleMatch = this.findViewportConvertibleToVolume(
784
+ metadata,
785
+ displaySetInstanceUID,
786
+ viewportType
787
+ );
788
+ if (compatibleMatch) {
789
+ return compatibleMatch;
790
+ }
791
+
792
+ // 4. Strategy: Find viewport with matching orientation via IOP
793
+ const orientationMatch = this.findViewportWithMatchingOrientation(
794
+ metadata,
795
+ displaySetInstanceUID,
796
+ viewportType
797
+ );
798
+ if (orientationMatch) {
799
+ return orientationMatch;
800
+ }
801
+
802
+ // 5. Fallback: Use the active viewport
803
+ return {
804
+ viewportId: activeViewportId,
805
+ displaySetInstanceUID,
806
+ viewportOptions: { viewportType },
807
+ };
808
+ }
809
+
810
+ /**
811
+ * Determines if the viewport should be what is specified in
812
+ * the viewportType of the display set, or stack if the display
813
+ * set isn't reconstructable and there is a referenced image id, otherwise
814
+ * volume.
815
+ *
816
+ * Expect there to be more rules in the future for different types of annotations/settings
817
+ * such as 3d annotations.
818
+ */
819
+ public determineTargetViewportType(displaySet, metadata): string {
820
+ let { viewportType } = displaySet;
821
+
822
+ if (!viewportType) {
823
+ if (metadata.referencedImageId && !displaySet.isReconstructable) {
824
+ viewportType = csEnums.ViewportType.STACK;
825
+ } else if (metadata.volumeId) {
826
+ viewportType = 'volume';
827
+ }
828
+ }
829
+ return viewportType;
830
+ }
831
+
832
+ /**
833
+ * Find viewports that could be updated to be volumes to show this view.
834
+ * Prefers a viewport already showing the right display set.
835
+ */
836
+ public findViewportShowingVolume(metadata, displaySetInstanceUID, viewportType) {
837
+ if (!metadata.volumeId) {
838
+ return null;
839
+ }
840
+
841
+ for (const id of this.viewportsById.keys()) {
842
+ const viewport = this.getCornerstoneViewport(id);
843
+ if (viewport?.isReferenceViewable(metadata, { asVolume: true, withNavigation: true })) {
844
+ return {
845
+ viewportId: id,
846
+ displaySetInstanceUID,
847
+ viewportOptions: { viewportType },
848
+ };
849
+ }
850
+ }
851
+ return null;
852
+ }
853
+
854
+ /**
855
+ * Find a viewport that could be converted to a volume to show this annotation,
856
+ * already showing the right display set.
857
+ */
858
+ public findViewportConvertibleToVolume(metadata, displaySetInstanceUID, viewportType) {
859
+ const { viewportGridService } = this.servicesManager.services;
860
+ const altMetadata = { ...metadata, volumeId: null, referencedImageId: null };
861
+
862
+ for (const id of this.viewportsById.keys()) {
863
+ const viewport = this.getCornerstoneViewport(id);
864
+ const viewportDisplaySetUID = viewportGridService.getDisplaySetsUIDsForViewport(id)?.[0];
865
+
866
+ if (!viewportDisplaySetUID || !viewport) {
867
+ continue;
868
+ }
869
+
870
+ if (metadata.volumeId) {
871
+ altMetadata.volumeId = viewportDisplaySetUID;
872
+ }
873
+ altMetadata.FrameOfReferenceUID = this._getFrameOfReferenceUID(viewportDisplaySetUID);
874
+
875
+ if (viewport.isReferenceViewable(altMetadata, { asVolume: true, withNavigation: true })) {
876
+ return {
877
+ viewportId: id,
878
+ displaySetInstanceUID,
879
+ viewportOptions: { viewportType },
880
+ };
881
+ }
882
+ }
883
+ return null;
884
+ }
885
+
886
+ /**
887
+ * Find a viewport with the closest orientation but on a different display set.
888
+ */
889
+ public findViewportWithMatchingOrientation(metadata, displaySetInstanceUID, viewportType) {
890
+ const viewportAlignmentData = this.getViewportAlignmentData(metadata);
891
+ if (viewportAlignmentData?.length) {
892
+ return {
893
+ ...viewportAlignmentData[0],
894
+ displaySetInstanceUID,
895
+ viewportOptions: { viewportType },
896
+ };
897
+ }
898
+ return null;
899
+ }
900
+
901
+ /**
902
+ * Sets the image data for the given viewport.
903
+ */
904
+ // Public so the viewport backends (IViewportServiceInternals) can dispatch to it.
905
+ async _setEcgViewport(
906
+ viewport: Types.IECGViewport,
907
+ viewportData: StackViewportData
908
+ ): Promise<void> {
909
+ const [displaySet] = viewportData.data;
910
+ const imageId = displaySet.imageIds?.[0];
911
+ if (!imageId) {
912
+ console.error('[CornerstoneViewportService] ECG display set has no imageId');
913
+ return;
914
+ }
915
+
916
+ try {
917
+ await this.backend.mountEcg(viewport, displaySet, imageId);
918
+ } catch (error) {
919
+ // Tell the user, then reject so that setViewportData does not report a successful mount.
920
+ this.servicesManager.services.uiNotificationService?.show({
921
+ title: 'ECG',
922
+ message: 'The ECG waveform could not be loaded.',
923
+ type: 'error',
924
+ });
925
+ throw error;
926
+ }
927
+ }
928
+
929
+ // Public so the viewport backends (IViewportServiceInternals) can dispatch to it.
930
+ async _setOtherViewport(
931
+ viewport: Types.IStackViewport,
932
+ viewportData: StackViewportData,
933
+ viewportInfo: ViewportInfo,
934
+ _presentations: Presentations = {}
935
+ ): Promise<void> {
936
+ const [displaySet] = viewportData.data;
937
+
938
+ await this.backend.mountOther(viewport, displaySet);
939
+
940
+ const viewReference = viewportInfo.getViewReference();
941
+ if (viewReference) {
942
+ viewport.setViewReference(viewReference);
943
+ }
944
+ }
945
+
946
+ // Public so the viewport backends (IViewportServiceInternals) can dispatch to it.
947
+ async _setStackViewport(
948
+ viewport: Types.IStackViewport,
949
+ viewportData: StackViewportData,
950
+ viewportInfo: ViewportInfo,
951
+ presentations: Presentations = {}
952
+ ): Promise<void> {
953
+ const displaySetOptions = viewportInfo.getDisplaySetOptions();
954
+
955
+ const displaySetInstanceUIDs = viewportData.data.map(data => data.displaySetInstanceUID);
956
+
957
+ // based on the cache service construct always the first one is the non-overlay
958
+ // and the rest are overlays
959
+
960
+ this.viewportsDisplaySets.set(viewport.id, [...displaySetInstanceUIDs]);
961
+
962
+ const { initialImageIndex, imageIds } = viewportData.data[0];
963
+
964
+ // Use the slice index from any provided view reference, as the view reference
965
+ // is being used to navigate to the initial view position for measurement
966
+ // navigation and other navigation forcing specific views.
967
+ let initialImageIndexToUse =
968
+ presentations?.positionPresentation?.initialImageIndex ?? (initialImageIndex as number);
969
+
970
+ const { rotation, flipHorizontal, displayArea } = viewportInfo.getViewportOptions();
971
+
972
+ const properties = { ...presentations.lutPresentation?.properties };
973
+ if (!presentations.lutPresentation?.properties) {
974
+ const { voi, voiInverted, colormap } = displaySetOptions[0];
975
+ if (voi && (voi.windowWidth || voi.windowCenter)) {
976
+ const { lower, upper } = csUtils.windowLevel.toLowHighRange(
977
+ voi.windowWidth,
978
+ voi.windowCenter
979
+ );
980
+ properties.voiRange = { lower, upper };
981
+ }
982
+
983
+ properties.invert = voiInverted ?? properties.invert;
984
+ properties.colormap = colormap ?? properties.colormap;
985
+ }
986
+
987
+ viewport.element.addEventListener(csEnums.Events.VIEWPORT_NEW_IMAGE_SET, evt => {
988
+ const { element } = evt.detail;
989
+
990
+ if (element !== viewport.element) {
991
+ return;
992
+ }
993
+
994
+ csToolsUtils.stackContextPrefetch.enable(element);
995
+ });
996
+
997
+ const overlayProcessingResults = this._processExtraDisplaySetsForViewport(viewport);
998
+
999
+ const referencedImageId = presentations?.positionPresentation?.viewReference?.referencedImageId;
1000
+ if (referencedImageId && imageIds) {
1001
+ initialImageIndexToUse = imageIds.indexOf(referencedImageId);
1002
+ }
1003
+
1004
+ if (
1005
+ initialImageIndexToUse === undefined ||
1006
+ initialImageIndexToUse === null ||
1007
+ initialImageIndexToUse < 0
1008
+ ) {
1009
+ initialImageIndexToUse = this._getInitialImageIndexForViewport(viewportInfo, imageIds) || 0;
1010
+ }
1011
+
1012
+ // The lane-specific mount (legacy setStack/setProperties vs native
1013
+ // setDisplaySets/setDisplaySetPresentation/setViewState) lives in the backend.
1014
+ return this.backend.mountStack(viewport, {
1015
+ displaySetInstanceUIDs,
1016
+ imageIds,
1017
+ initialImageIndex: initialImageIndexToUse,
1018
+ properties,
1019
+ displayArea,
1020
+ rotation,
1021
+ flipHorizontal,
1022
+ presentations,
1023
+ viewportInfo,
1024
+ overlayProcessingResults,
1025
+ });
1026
+ }
1027
+
1028
+ private _getInitialImageIndexForViewport(
1029
+ viewportInfo: ViewportInfo,
1030
+ imageIds?: string[]
1031
+ ): number {
1032
+ const initialImageOptions = viewportInfo.getInitialImageOptions();
1033
+ if (!initialImageOptions) {
1034
+ return;
1035
+ }
1036
+ const { index, preset } = initialImageOptions;
1037
+ const viewportType = viewportInfo.getViewportType();
1038
+
1039
+ let numberOfSlices;
1040
+ if (viewportType === csEnums.ViewportType.STACK) {
1041
+ numberOfSlices = imageIds.length;
1042
+ } else if (viewportType === csEnums.ViewportType.ORTHOGRAPHIC) {
1043
+ const viewport = this.getCornerstoneViewport(viewportInfo.getViewportId());
1044
+ const imageSliceData = csUtils.getImageSliceDataForVolumeViewport(viewport);
1045
+
1046
+ if (!imageSliceData) {
1047
+ return;
1048
+ }
1049
+
1050
+ ({ numberOfSlices } = imageSliceData);
1051
+ } else {
1052
+ return;
1053
+ }
1054
+
1055
+ return this._getInitialImageIndex(numberOfSlices, index, preset);
1056
+ }
1057
+
1058
+ _getInitialImageIndex(numberOfSlices: number, imageIndex?: number, preset?: JumpPresets): number {
1059
+ const lastSliceIndex = numberOfSlices - 1;
1060
+
1061
+ if (imageIndex !== undefined) {
1062
+ return csUtils.clip(imageIndex, 0, lastSliceIndex);
1063
+ }
1064
+
1065
+ if (preset === JumpPresets.First) {
1066
+ return 0;
1067
+ }
1068
+
1069
+ if (preset === JumpPresets.Last) {
1070
+ return lastSliceIndex;
1071
+ }
1072
+
1073
+ if (preset === JumpPresets.Middle) {
1074
+ // Note: this is a simple but yet very important formula.
1075
+ // since viewport reset works with the middle slice
1076
+ // if the below formula is not correct, on a viewport reset
1077
+ // it will jump to a different slice than the middle one which
1078
+ // was the initial slice, and we have some tools such as Crosshairs
1079
+ // which rely on a relative camera modifications and those will break.
1080
+ return lastSliceIndex % 2 === 0 ? lastSliceIndex / 2 : (lastSliceIndex + 1) / 2;
1081
+ }
1082
+
1083
+ return 0;
1084
+ }
1085
+
1086
+ async _setVolumeViewport(
1087
+ viewport: Types.IVolumeViewport,
1088
+ viewportData: VolumeViewportData,
1089
+ viewportInfo: ViewportInfo,
1090
+ presentations: Presentations = {}
1091
+ ): Promise<void> {
1092
+ // TODO: We need to overhaul the way data sources work so requests can be made
1093
+ // async. I think we should follow the image loader pattern which is async and
1094
+ // has a cache behind it.
1095
+ // The problem is that to set this volume, we need the metadata, but the request is
1096
+ // already in-flight, and the promise is not cached, so we have no way to wait for
1097
+ // it and know when it has fully arrived.
1098
+ // loadStudyMetadata(StudyInstanceUID) => Promise([instances for study])
1099
+ // loadSeriesMetadata(StudyInstanceUID, SeriesInstanceUID) => Promise([instances for series])
1100
+ // If you call loadStudyMetadata and it's not in the DicomMetadataStore cache, it should fire
1101
+ // a request through the data source?
1102
+ // (This call may or may not create sub-requests for series metadata)
1103
+ const { displaySetService } = this.servicesManager.services;
1104
+ const volumeInputArray = [];
1105
+ const displaySetOptionsArray = viewportInfo.getDisplaySetOptions();
1106
+ const { hangingProtocolService } = this.servicesManager.services;
1107
+
1108
+ const volumeToLoad = [];
1109
+ const displaySetInstanceUIDs = [];
1110
+
1111
+ for (const [index, data] of viewportData.data.entries()) {
1112
+ const { imageIds, displaySetInstanceUID } = data;
1113
+ let volume = data.volume;
1114
+
1115
+ const displaySet = displaySetService.getDisplaySetByUID(displaySetInstanceUID);
1116
+ if (!volume && displaySet.images) {
1117
+ volume = csToolsUtils.getOrCreateImageVolume(displaySet.images.map(image => image.imageId));
1118
+ }
1119
+
1120
+ displaySetInstanceUIDs.push(displaySetInstanceUID);
1121
+
1122
+ if (!volume) {
1123
+ console.log('Volume display set not found');
1124
+ continue;
1125
+ }
1126
+
1127
+ volumeToLoad.push(volume);
1128
+
1129
+ const displaySetOptions = displaySetOptionsArray[index];
1130
+ const { volumeId } = volume;
1131
+ volumeInputArray.push({
1132
+ imageIds,
1133
+ volumeId,
1134
+ modality: displaySet.Modality,
1135
+ displaySetInstanceUID,
1136
+ blendMode: displaySetOptions.blendMode,
1137
+ slabThickness: this._getSlabThickness(displaySetOptions, volumeId),
1138
+ });
1139
+ }
1140
+
1141
+ this.viewportsDisplaySets.set(viewport.id, displaySetInstanceUIDs);
1142
+
1143
+ const volumesNotLoaded = volumeToLoad.filter(volume => !volume.loadStatus?.loaded);
1144
+ if (volumesNotLoaded.length) {
1145
+ if (hangingProtocolService.getShouldPerformCustomImageLoad()) {
1146
+ // delegate the volume loading to the hanging protocol service if it has a custom image load strategy
1147
+ return hangingProtocolService.runImageLoadStrategy({
1148
+ viewportId: viewport.id,
1149
+ volumeInputArray,
1150
+ });
1151
+ }
1152
+
1153
+ volumesNotLoaded.forEach(volume => {
1154
+ if (!volume.loadStatus?.loading && volume.load instanceof Function) {
1155
+ volume.load();
1156
+ }
1157
+ });
1158
+ }
1159
+
1160
+ // It's crucial not to return here because the volume may be loaded,
1161
+ // but the viewport also needs to set the volume.
1162
+ // if (!volumesNotLoaded.length) {
1163
+ // return;
1164
+ // }
1165
+
1166
+ // This returns the async continuation only
1167
+ return this.setVolumesForViewport(viewport, volumeInputArray, presentations);
1168
+ }
1169
+
1170
+ public async setVolumesForViewport(viewport, volumeInputArray, presentations) {
1171
+ const { displaySetService, viewportGridService } = this.servicesManager.services;
1172
+
1173
+ const viewportInfo = this.getViewportInfo(viewport.id);
1174
+ const displaySetOptions = viewportInfo.getDisplaySetOptions();
1175
+ const displaySetUIDs = viewportGridService.getDisplaySetsUIDsForViewport(viewport.id);
1176
+ const displaySet = displaySetService.getDisplaySetByUID(displaySetUIDs[0]);
1177
+ const displaySetModality = displaySet?.Modality;
1178
+
1179
+ // seems like a hack but we need the actor to be ready first before
1180
+ // we set the properties
1181
+ const timeoutViewportCallback = (callback: () => void) => setTimeout(callback, 0);
1182
+
1183
+ // filter overlay display sets (e.g. segmentation) since they will get handled below via the segmentation service
1184
+ const filteredVolumeInputArray = volumeInputArray
1185
+ .map((volumeInput, index) => {
1186
+ return { volumeInput, displaySetOptions: displaySetOptions[index] };
1187
+ })
1188
+ .filter(({ volumeInput }) => {
1189
+ const displaySet = displaySetService.getDisplaySetByUID(volumeInput.displaySetInstanceUID);
1190
+ return !displaySet?.isOverlayDisplaySet;
1191
+ });
1192
+
1193
+ // Todo: use presentations states
1194
+ const volumesProperties = filteredVolumeInputArray.map(({ volumeInput, displaySetOptions }) => {
1195
+ const { volumeId } = volumeInput;
1196
+ const { voi, voiInverted, colormap, displayPreset } = displaySetOptions;
1197
+ const properties = {} as ViewportProperties;
1198
+
1199
+ if (voi && (voi.windowWidth || voi.windowCenter)) {
1200
+ const { lower, upper } = csUtils.windowLevel.toLowHighRange(
1201
+ voi.windowWidth,
1202
+ voi.windowCenter
1203
+ );
1204
+ properties.voiRange = { lower, upper };
1205
+ }
1206
+
1207
+ if (voiInverted !== undefined) {
1208
+ properties.invert = voiInverted;
1209
+ }
1210
+
1211
+ if (colormap !== undefined) {
1212
+ properties.colormap = colormap;
1213
+ }
1214
+
1215
+ if (displayPreset !== undefined) {
1216
+ properties.preset = displayPreset[displaySetModality] || displayPreset.default;
1217
+ }
1218
+
1219
+ return { properties, volumeId };
1220
+ });
1221
+
1222
+ // For SEG and RT viewports
1223
+ const overlayProcessingResults = this._processExtraDisplaySetsForViewport(viewport) || [];
1224
+
1225
+ // Lane-specific volume mount: the native backend mounts registered dataIds via
1226
+ // setDisplaySets + per-binding presentations and reports the mount handled;
1227
+ // legacy reports unhandled and runs the shared setVolumes tail below (which a
1228
+ // native overlay-only mount also traverses — its legacy-surface steps are
1229
+ // lane-guarded via mountOverlayOnlyVolumes).
1230
+ const handledByBackend = await this.backend.mountVolumes(viewport, {
1231
+ filteredVolumeInputArray,
1232
+ volumesProperties,
1233
+ viewportInfo,
1234
+ overlayProcessingResults,
1235
+ presentations,
1236
+ });
1237
+ if (handledByBackend) {
1238
+ this._broadcastEvent(this.EVENTS.VIEWPORT_VOLUMES_CHANGED, { viewportInfo });
1239
+ return;
1240
+ }
1241
+
1242
+ if (!filteredVolumeInputArray.length && overlayProcessingResults?.length) {
1243
+ overlayProcessingResults.forEach(({ imageIds, addOverlayFn }) => {
1244
+ if (addOverlayFn) {
1245
+ // if there is no volume input array, and there is an addOverlayFn, means we need to take
1246
+ // care of the background overlay display set first then the addOverlayFn will add the
1247
+ // SEG displaySet
1248
+ const sampleImageId = imageIds[0];
1249
+ const backgroundDisplaySet = displaySetService.getDisplaySetsBy(
1250
+ displaySet =>
1251
+ !displaySet.isOverlayDisplaySet &&
1252
+ displaySet.images?.some(image => image.imageId === sampleImageId)
1253
+ );
1254
+
1255
+ if (backgroundDisplaySet.length !== 1) {
1256
+ throw new Error('Background display set not found');
1257
+ }
1258
+
1259
+ if (isVolume3DViewportType(viewport)) {
1260
+ timeoutViewportCallback(() => {
1261
+ viewportGridService.setDisplaySetsForViewport({
1262
+ viewportId: viewport.id,
1263
+ displaySetInstanceUIDs: [backgroundDisplaySet[0].displaySetInstanceUID],
1264
+ });
1265
+ });
1266
+ }
1267
+ }
1268
+ });
1269
+ }
1270
+
1271
+ const baseVolumeInputs = filteredVolumeInputArray.map(({ volumeInput }) => volumeInput);
1272
+ const nextBaseVolumeIds = baseVolumeInputs.map(v => v.volumeId);
1273
+ const existingVolumeIds = getVolumeActorReferencedIds(viewport);
1274
+
1275
+ let skippedIdenticalBaseVolumes = false;
1276
+
1277
+ if (baseVolumeInputs.length) {
1278
+ const singleBaseViewport = nextBaseVolumeIds.length === 1;
1279
+
1280
+ // Only skip setVolumes() when the viewport type already matches the desired OHIF type
1281
+ // (ORTHOGRAPHIC / VOLUME_3D); otherwise a stack → MPR switch with the same volumeId
1282
+ // would incorrectly skip rebuilding the viewport.
1283
+ if (
1284
+ singleBaseViewport &&
1285
+ existingVolumeIds.length >= nextBaseVolumeIds.length &&
1286
+ volumeIdPrefixesMatch(existingVolumeIds, nextBaseVolumeIds.length, nextBaseVolumeIds) &&
1287
+ viewportMatchesDesiredVolumePresentation(viewport, viewportInfo)
1288
+ ) {
1289
+ // Same primary volume already loaded (e.g. labelmap / extra actors after it) — avoid
1290
+ // setVolumes(), which tears down all actors and blanks MPR during SEG hydrate.
1291
+ skippedIdenticalBaseVolumes = true;
1292
+ } else if (
1293
+ existingVolumeIds.length &&
1294
+ nextBaseVolumeIds.length > existingVolumeIds.length &&
1295
+ volumeIdPrefixesMatch(existingVolumeIds, existingVolumeIds.length, nextBaseVolumeIds) &&
1296
+ typeof viewport.addVolumes === 'function'
1297
+ ) {
1298
+ const toAdd = baseVolumeInputs.slice(existingVolumeIds.length);
1299
+ if (toAdd.length) {
1300
+ await viewport.addVolumes(toAdd);
1301
+ }
1302
+ } else {
1303
+ await viewport.setVolumes(baseVolumeInputs);
1304
+ }
1305
+ } else if (volumeInputArray.length) {
1306
+ // Every volume input is an overlay display set. Legacy still mounts them via
1307
+ // setVolumes; the native backend no-ops (its overlays are added via
1308
+ // _addOverlayRepresentations below).
1309
+ await this.backend.mountOverlayOnlyVolumes(viewport, volumeInputArray);
1310
+ }
1311
+
1312
+ await this._addOverlayRepresentations(overlayProcessingResults);
1313
+ viewport.render();
1314
+
1315
+ volumesProperties.forEach(({ properties, volumeId }) => {
1316
+ timeoutViewportCallback(() => {
1317
+ viewport.setProperties(properties, volumeId);
1318
+ viewport.render();
1319
+ });
1320
+ });
1321
+
1322
+ this.setPresentations(viewport.id, presentations);
1323
+ // Presentations apply segmentation (hydrated labelmap etc.) after the render above — redraw so
1324
+ // every orthographic/3D tile shows the updated scene (fixes MPR siblings blank after SEG hydrate).
1325
+ viewport.render();
1326
+
1327
+ if (!presentations.positionPresentation && !skippedIdenticalBaseVolumes) {
1328
+ const imageIndex = this._getInitialImageIndexForViewport(viewportInfo);
1329
+
1330
+ if (imageIndex !== undefined) {
1331
+ csUtils.jumpToSlice(viewport.element, {
1332
+ imageIndex,
1333
+ });
1334
+ }
1335
+ }
1336
+
1337
+ this._broadcastEvent(this.EVENTS.VIEWPORT_VOLUMES_CHANGED, {
1338
+ viewportInfo,
1339
+ });
1340
+ }
1341
+
1342
+ private _processExtraDisplaySetsForViewport(
1343
+ viewport: Types.IStackViewport | Types.IVolumeViewport
1344
+ ) {
1345
+ const { displaySetService } = this.servicesManager.services;
1346
+
1347
+ // load any secondary displaySets
1348
+ const displaySetInstanceUIDs = this.viewportsDisplaySets.get(viewport.id);
1349
+
1350
+ // Find overlay display sets (e.g. SEG, RTSTRUCT)
1351
+ const overlayDisplaySets = displaySetInstanceUIDs
1352
+ .map(displaySetService.getDisplaySetByUID)
1353
+ .filter(displaySet => displaySet?.isOverlayDisplaySet);
1354
+
1355
+ // if it is only the overlay displaySet, then we need to get the reference
1356
+ // displaySet imageIds and set them as the imageIds for the viewport,
1357
+ // here we can do some logic if the reference is missing
1358
+ // then find the most similar match of displaySet instead
1359
+ if (!overlayDisplaySets?.length) {
1360
+ return;
1361
+ }
1362
+
1363
+ return overlayDisplaySets.map(overlayDisplaySet => {
1364
+ let imageIds;
1365
+ if (overlayDisplaySet.referencedDisplaySetInstanceUID) {
1366
+ const referenceDisplaySet = displaySetService.getDisplaySetByUID(
1367
+ overlayDisplaySet.referencedDisplaySetInstanceUID
1368
+ );
1369
+ imageIds = referenceDisplaySet.images.map(image => image.imageId);
1370
+ }
1371
+ return {
1372
+ imageIds,
1373
+ addOverlayFn: () => this.addOverlayRepresentationForDisplaySet(overlayDisplaySet, viewport),
1374
+ };
1375
+ });
1376
+ }
1377
+
1378
+ private addOverlayRepresentationForDisplaySet(
1379
+ displaySet: OhifTypes.DisplaySet,
1380
+ viewport: Types.IViewport
1381
+ ): Promise<void> {
1382
+ const { segmentationService } = this.servicesManager.services;
1383
+ const segmentationId = displaySet.displaySetInstanceUID;
1384
+
1385
+ const representationType =
1386
+ displaySet.Modality === 'SEG'
1387
+ ? csToolsEnums.SegmentationRepresentations.Labelmap
1388
+ : csToolsEnums.SegmentationRepresentations.Contour;
1389
+
1390
+ const applyRepresentation = () => {
1391
+ const { predecessorImageId } = displaySet;
1392
+ const segmentationRepresentationPromise =
1393
+ segmentationService.addSegmentationRepresentation(viewport.id, {
1394
+ segmentationId,
1395
+ predecessorImageId,
1396
+ type: representationType,
1397
+ config: {
1398
+ blendMode:
1399
+ viewport?.getBlendMode?.() === 1
1400
+ ? BlendModes.LABELMAP_EDGE_PROJECTION_BLEND
1401
+ : undefined,
1402
+ },
1403
+ });
1404
+ this.storePresentation({ viewportId: viewport.id });
1405
+ return segmentationRepresentationPromise;
1406
+ };
1407
+
1408
+ // SEG overlay is registered during stack setup, but cornerstone segmentation state
1409
+ // is created in displaySet.load() (async). Wait until it exists before adding representation.
1410
+ if (displaySet.Modality === 'SEG') {
1411
+ if (segmentationService.getSegmentation(segmentationId)) {
1412
+ return applyRepresentation();
1413
+ }
1414
+
1415
+ // Bound the wait so a failed/aborted SEG load (where SEGMENTATION_LOADING_COMPLETE
1416
+ // never fires) cannot leave this promise — and the viewport setup awaiting it —
1417
+ // hanging indefinitely.
1418
+ const SEG_LOADING_TIMEOUT_MS = 120000;
1419
+
1420
+ return new Promise<void>(resolve => {
1421
+ let settled = false;
1422
+ let timeoutId;
1423
+
1424
+ // Final resolution — extra calls are harmless (resolve is a no-op after
1425
+ // the first), which lets the timeout stay armed while a representation
1426
+ // apply is in flight and still bound it.
1427
+ const finish = () => {
1428
+ clearTimeout(timeoutId);
1429
+ resolve();
1430
+ };
1431
+
1432
+ // Give up without applying (load failure / timeout before the event).
1433
+ const settleWithoutApply = () => {
1434
+ settled = true;
1435
+ unsubscribe();
1436
+ finish();
1437
+ };
1438
+
1439
+ const { unsubscribe } = segmentationService.subscribe(
1440
+ segmentationService.EVENTS.SEGMENTATION_LOADING_COMPLETE,
1441
+ async (evt: { segDisplaySet?: OhifTypes.DisplaySet }) => {
1442
+ if (settled || evt.segDisplaySet?.displaySetInstanceUID !== segmentationId) {
1443
+ return;
1444
+ }
1445
+
1446
+ // Dedupe immediately, but resolve only after the representation is
1447
+ // applied: awaiters continue into rotation/flip/render and broadcast
1448
+ // VIEWPORT_DATA_CHANGED (hanging-protocol callbacks, toolbar, e2e
1449
+ // readiness), which must not observe a viewport whose overlay
1450
+ // doesn't exist yet. applyRepresentation can be genuinely async
1451
+ // (stack→volume viewport conversion). The timeout is deliberately
1452
+ // NOT cleared here — a hung apply stays bounded.
1453
+ settled = true;
1454
+ unsubscribe();
1455
+
1456
+ try {
1457
+ await applyRepresentation();
1458
+ } catch (error) {
1459
+ console.warn(
1460
+ `Failed to apply segmentation representation for "${segmentationId}":`,
1461
+ error
1462
+ );
1463
+ } finally {
1464
+ finish();
1465
+ }
1466
+ }
1467
+ );
1468
+
1469
+ // Stop waiting immediately if the SEG load itself fails — otherwise the
1470
+ // loading-complete event never fires and we would idle until the timeout.
1471
+ const loadingPromise = (displaySet as { loadingPromise?: Promise<unknown> })
1472
+ .loadingPromise;
1473
+ loadingPromise?.catch(error => {
1474
+ if (settled) {
1475
+ return;
1476
+ }
1477
+
1478
+ console.warn(
1479
+ `Segmentation "${segmentationId}" failed to load; skipping representation setup.`,
1480
+ error
1481
+ );
1482
+ settleWithoutApply();
1483
+ });
1484
+
1485
+ timeoutId = setTimeout(() => {
1486
+ if (settled) {
1487
+ // The load completed but applyRepresentation is hung — resolve so
1488
+ // viewport setup is never blocked past the bound (best-effort
1489
+ // semantics; the apply may still land later).
1490
+ console.warn(
1491
+ `Timed out applying segmentation representation for "${segmentationId}"; resolving viewport readiness anyway.`
1492
+ );
1493
+ resolve();
1494
+ return;
1495
+ }
1496
+
1497
+ console.warn(
1498
+ `Timed out waiting for segmentation "${segmentationId}" to load; skipping representation setup.`
1499
+ );
1500
+ settleWithoutApply();
1501
+ }, SEG_LOADING_TIMEOUT_MS);
1502
+ });
1503
+ }
1504
+
1505
+ return applyRepresentation();
1506
+ }
1507
+
1508
+ // Public so the viewport backends (IViewportServiceInternals) can run the
1509
+ // pending overlay adds from their mount bodies.
1510
+ async _addOverlayRepresentations(
1511
+ overlayProcessingResults?: Array<{ addOverlayFn?: () => Promise<void> }>
1512
+ ): Promise<void> {
1513
+ if (!overlayProcessingResults?.length) {
1514
+ return;
1515
+ }
1516
+ for (const overlayProcessingResult of overlayProcessingResults) {
1517
+ if (overlayProcessingResult?.addOverlayFn) {
1518
+ await overlayProcessingResult.addOverlayFn();
1519
+ }
1520
+ }
1521
+ }
1522
+
1523
+ // Todo: keepCamera is an interim solution until we have a better solution for
1524
+ // keeping the camera position when the viewport data is changed
1525
+ public updateViewport(viewportId: string, viewportData, keepCamera = false) {
1526
+ const viewportInfo = this.getViewportInfo(viewportId);
1527
+ const viewport = this.getCornerstoneViewport(viewportId);
1528
+
1529
+ // The camera snapshot/restore surface is forked per lane (legacy
1530
+ // getCamera/setCamera vs native view state), so the backend owns the re-mount.
1531
+ const displaySetPromise = this.backend.remount(
1532
+ viewport,
1533
+ viewportData,
1534
+ viewportInfo,
1535
+ keepCamera
1536
+ );
1537
+
1538
+ // remount() returns undefined for viewport families with no re-mount path
1539
+ // (matching legacy behavior); nothing changed, so skip the event broadcast.
1540
+ if (!displaySetPromise) {
1541
+ return;
1542
+ }
1543
+
1544
+ displaySetPromise.then(
1545
+ () => {
1546
+ this._broadcastEvent(this.EVENTS.VIEWPORT_DATA_CHANGED, {
1547
+ viewportData,
1548
+ viewportId,
1549
+ });
1550
+ },
1551
+ error => console.error('[CornerstoneViewportService] Failed to update the viewport', error)
1552
+ );
1553
+ }
1554
+
1555
+ _setDisplaySets(
1556
+ viewport: Types.IViewport,
1557
+ viewportData: StackViewportData | VolumeViewportData,
1558
+ viewportInfo: ViewportInfo,
1559
+ presentations: Presentations = {}
1560
+ ): Promise<void> {
1561
+ // The backend (legacy vs native, selected once in the constructor) owns the
1562
+ // per-family routing: legacy dispatches by the runtime cornerstone viewport
1563
+ // type; native dispatches by the bound data shape, because native stack and
1564
+ // volume content both report a single PLANAR_NEXT type (§4.4).
1565
+ return this.backend.dispatchMount(viewport, viewportData, viewportInfo, presentations);
1566
+ }
1567
+
1568
+ /**
1569
+ * Removes the resize observer from the viewport element
1570
+ */
1571
+ _removeResizeObserver() {
1572
+ if (this.viewportGridResizeObserver) {
1573
+ this.viewportGridResizeObserver.disconnect();
1574
+ }
1575
+ }
1576
+
1577
+ _getSlabThickness(displaySetOptions, volumeId) {
1578
+ const { blendMode } = displaySetOptions;
1579
+ if (blendMode === undefined || displaySetOptions.slabThickness === undefined) {
1580
+ return;
1581
+ }
1582
+
1583
+ // if there is a slabThickness set as a number then use it
1584
+ if (typeof displaySetOptions.slabThickness === 'number') {
1585
+ return displaySetOptions.slabThickness;
1586
+ }
1587
+
1588
+ if (displaySetOptions.slabThickness.toLowerCase() === 'fullvolume') {
1589
+ // calculate the slab thickness based on the volume dimensions
1590
+ const imageVolume = cache.getVolume(volumeId);
1591
+
1592
+ const { dimensions, spacing } = imageVolume;
1593
+ const slabThickness = Math.sqrt(
1594
+ Math.pow(dimensions[0] * spacing[0], 2) +
1595
+ Math.pow(dimensions[1] * spacing[1], 2) +
1596
+ Math.pow(dimensions[2] * spacing[2], 2)
1597
+ );
1598
+
1599
+ return slabThickness;
1600
+ }
1601
+ }
1602
+
1603
+ _getFrameOfReferenceUID(displaySetInstanceUID) {
1604
+ const { displaySetService } = this.servicesManager.services;
1605
+ const displaySet = displaySetService.getDisplaySetByUID(displaySetInstanceUID);
1606
+
1607
+ if (!displaySet) {
1608
+ return;
1609
+ }
1610
+
1611
+ if (displaySet.FrameOfReferenceUID) {
1612
+ return displaySet.FrameOfReferenceUID;
1613
+ }
1614
+
1615
+ if (displaySet.Modality === 'SEG') {
1616
+ const { instance } = displaySet;
1617
+ return instance.FrameOfReferenceUID;
1618
+ }
1619
+
1620
+ if (displaySet.Modality === 'RTSTRUCT') {
1621
+ const { instance } = displaySet;
1622
+ return instance.ReferencedFrameOfReferenceSequence.FrameOfReferenceUID;
1623
+ }
1624
+
1625
+ const { images } = displaySet;
1626
+ if (images && images.length) {
1627
+ return images[0].FrameOfReferenceUID;
1628
+ }
1629
+ }
1630
+
1631
+ private enqueueViewportResizeRequest() {
1632
+ this.resizeQueue.push(false); // false indicates viewport resize
1633
+
1634
+ clearTimeout(this.viewportResizeTimer);
1635
+ this.viewportResizeTimer = setTimeout(() => {
1636
+ this.processViewportResizeQueue();
1637
+ }, this.gridResizeDelay);
1638
+ }
1639
+
1640
+ private processViewportResizeQueue() {
1641
+ const isGridResizeInQueue = this.resizeQueue.some(isGridResize => isGridResize);
1642
+ if (this.resizeQueue.length > 0 && !isGridResizeInQueue && !this.gridResizeTimeOut) {
1643
+ this.performResize();
1644
+ }
1645
+
1646
+ // Clear the queue after processing viewport resizes
1647
+ this.resizeQueue = [];
1648
+ }
1649
+
1650
+ private performResize() {
1651
+ const isImmediate = false;
1652
+
1653
+ try {
1654
+ const viewports = this.getRenderingEngine().getViewports();
1655
+
1656
+ // Store the current position presentations for each viewport.
1657
+ viewports.forEach(({ id: viewportId }) => {
1658
+ const presentation = this._getPositionPresentation(viewportId);
1659
+
1660
+ // During a resize, the slice index should remain unchanged. This is a temporary fix for
1661
+ // a larger issue regarding the definition of slice index with slab thickness.
1662
+ // We need to revisit this to make it more robust and understandable.
1663
+ delete presentation.viewReference?.sliceIndex;
1664
+ this.beforeResizePositionPresentations.set(viewportId, presentation);
1665
+ });
1666
+
1667
+ // Resize the rendering engine and render.
1668
+ const renderingEngine = this.renderingEngine;
1669
+ renderingEngine.resize(isImmediate);
1670
+ renderingEngine.render();
1671
+
1672
+ // Reset the camera for all viewports using position presentation to maintain relative size/position
1673
+ // which means only those viewports that have a zoom level of 1.
1674
+ this.beforeResizePositionPresentations.forEach((positionPresentation, viewportId) => {
1675
+ this.setPresentations(viewportId, {
1676
+ positionPresentation,
1677
+ });
1678
+ });
1679
+
1680
+ // Resize and render the rendering engine again.
1681
+ renderingEngine.resize(isImmediate);
1682
+ renderingEngine.render();
1683
+ } catch (e) {
1684
+ // This can happen if the resize is too close to navigation or shutdown
1685
+ console.warn('Caught resize exception', e);
1686
+ }
1687
+ }
1688
+
1689
+ private resetGridResizeTimeout() {
1690
+ clearTimeout(this.gridResizeTimeOut);
1691
+ this.gridResizeTimeOut = setTimeout(() => {
1692
+ this.gridResizeTimeOut = null;
1693
+ }, this.gridResizeDelay);
1694
+ }
1695
+
1696
+ private _setLutPresentation(
1697
+ viewport: Types.IStackViewport | Types.IVolumeViewport,
1698
+ lutPresentation: LutPresentation
1699
+ ): void {
1700
+ // Forked per backend (§4.3 presentation write): legacy applies via setProperties;
1701
+ // native via setDisplaySetPresentation (a PLANAR_NEXT viewport has no setProperties),
1702
+ // so setPresentations no longer throws on the native path.
1703
+ this.backend.setLutPresentation(viewport, lutPresentation);
1704
+ }
1705
+
1706
+ private _setPositionPresentation(
1707
+ viewport: Types.IStackViewport | Types.IVolumeViewport,
1708
+ positionPresentation: PositionPresentation
1709
+ ): void {
1710
+ // Forked per backend (§4.3 presentation write): both apply the view reference;
1711
+ // legacy then applies getViewPresentation pan/zoom via setViewPresentation, native
1712
+ // omits it for now (a PLANAR_NEXT viewport has no setViewPresentation).
1713
+ this.backend.setPositionPresentation(viewport, positionPresentation);
1714
+ }
1715
+
1716
+ private _setSegmentationPresentation(
1717
+ viewport: Types.IStackViewport | Types.IVolumeViewport,
1718
+ segmentationPresentation: SegmentationPresentation
1719
+ ): void {
1720
+ if (!segmentationPresentation) {
1721
+ return;
1722
+ }
1723
+
1724
+ const { segmentationService, customizationService, viewportGridService } =
1725
+ this.servicesManager.services;
1726
+
1727
+ // A site can narrow which viewport types a hydrated segmentation appears in
1728
+ // automatically (surface generation for a 3D viewport being the expensive
1729
+ // case). This gates only the automatic add - an explicit add from the
1730
+ // overlay menu goes through addSegmentationRepresentation directly.
1731
+ //
1732
+ // The type comes from the grid, not from ViewportInfo: the customization is
1733
+ // written in OHIF viewport types and getUpdatedViewportsForSegmentation
1734
+ // reads the same field, so one configured list means the same thing in both
1735
+ // places. ViewportInfo holds the cornerstone type, which under
1736
+ // `useNextViewports` is 'planarNext' for stack and MPR alike.
1737
+ const autoHydrateAllowed = isAutoHydrateViewportType({
1738
+ viewportType: viewportGridService.getState().viewports.get(viewport.id)?.viewportOptions
1739
+ ?.viewportType,
1740
+ customizationService,
1741
+ });
1742
+
1743
+ // Display sets the viewport carries as explicit layers. Those are added by
1744
+ // _addOverlayRepresentations as part of this same mount, and the two run in
1745
+ // opposite orders on the stack and volume paths, so a stored `hydrated:
1746
+ // false` must not remove one of them - being listed in the viewport is the
1747
+ // more specific statement, and it is what the overlay menu's per-viewport
1748
+ // Add records.
1749
+ const explicitLayerUIDs = new Set(this.viewportsDisplaySets.get(viewport.id) || []);
1750
+
1751
+ segmentationPresentation.forEach((presentationItem: SegmentationPresentationItem) => {
1752
+ const { segmentationId, type, hydrated } = presentationItem;
1753
+
1754
+ const { Labelmap, Surface } = csToolsEnums.SegmentationRepresentations;
1755
+ const isVolume3D = isVolume3DViewportType(viewport);
1756
+
1757
+ // The stored type is a hint: it was recorded when the segmentation was
1758
+ // hydrated, possibly against a viewport of a different kind than this
1759
+ // one, or with no viewport at all. Surface only renders in a 3D viewport
1760
+ // and a 3D viewport renders a labelmap as a surface, so correct in both
1761
+ // directions here. Being tolerant of the stored value is what lets the
1762
+ // hydration path record a type without needing a live viewport.
1763
+ let representationType = type;
1764
+
1765
+ if (type === Surface && !isVolume3D) {
1766
+ representationType = Labelmap;
1767
+ } else if (type === Labelmap && isVolume3D) {
1768
+ representationType = Surface;
1769
+ }
1770
+
1771
+ if (hydrated && autoHydrateAllowed) {
1772
+ segmentationService.addSegmentationRepresentation(viewport.id, {
1773
+ segmentationId,
1774
+ type: representationType,
1775
+ config: {
1776
+ blendMode:
1777
+ viewport?.getBlendMode?.() === 1
1778
+ ? BlendModes.LABELMAP_EDGE_PROJECTION_BLEND
1779
+ : undefined,
1780
+ },
1781
+ });
1782
+ return;
1783
+ }
1784
+
1785
+ // hydrated === false means this segmentation was explicitly removed from
1786
+ // the presentation (closed from the segmentation panel, or the layer
1787
+ // removed). Converge the viewport on the stored state instead of only
1788
+ // ever adding, so a re-created viewport does not restore a segmentation
1789
+ // the user dismissed. hydrated == null is "no representation yet" and is
1790
+ // deliberately left alone.
1791
+ if (hydrated === false && !explicitLayerUIDs.has(segmentationId)) {
1792
+ segmentationService.removeRepresentationsFromViewport(viewport.id, {
1793
+ segmentationId,
1794
+ });
1795
+ }
1796
+ });
1797
+ }
1798
+
1799
+ /**
1800
+ * Gets the display sets for a given viewport
1801
+ * @param viewportId - The ID of the viewport to get display sets for
1802
+ * @returns Array of display sets for the viewport
1803
+ */
1804
+ public getViewportDisplaySets(viewportId: string): OhifTypes.DisplaySet[] {
1805
+ const { displaySetService } = this.servicesManager.services;
1806
+ const displaySetInstanceUIDs = this.viewportsDisplaySets.get(viewportId) || [];
1807
+
1808
+ return displaySetInstanceUIDs
1809
+ .map(uid => displaySetService.getDisplaySetByUID(uid))
1810
+ .filter(Boolean);
1811
+ }
1812
+ }
1813
+
1814
+ export default CornerstoneViewportService;