@ohif/extension-cornerstone 3.14.0-beta.12 → 3.14.0-beta.121

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 (335) 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 +498 -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 +3008 -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/FidelityIndicator/FidelityIndicator.tsx +152 -0
  33. package/src/components/FidelityIndicator/index.ts +1 -0
  34. package/src/components/MeasurementItems.tsx +70 -0
  35. package/src/components/MeasurementTableNested.tsx +30 -0
  36. package/src/components/MeasurementsMenu.tsx +84 -0
  37. package/src/components/MeasurementsOrAdditionalFindings.tsx +82 -0
  38. package/src/components/ModalityLoadBadge/ModalityLoadBadge.tsx +171 -0
  39. package/src/components/ModalityLoadBadge/index.ts +1 -0
  40. package/src/components/NavigationComponent/NavigationComponent.tsx +138 -0
  41. package/src/components/NavigationComponent/index.ts +3 -0
  42. package/src/components/OHIFViewportActionCorners.tsx +109 -0
  43. package/src/components/OpacityMenu/OpacityMenu.tsx +54 -0
  44. package/src/components/OpacityMenu/OpacityMenuWrapper.tsx +85 -0
  45. package/src/components/OpacityMenu/index.ts +2 -0
  46. package/src/components/PanelAccordionTrigger.tsx +48 -0
  47. package/src/components/SegmentationToolConfig.tsx +71 -0
  48. package/src/components/SegmentationUtilityButton.tsx +61 -0
  49. package/src/components/SelectItemWithModality.tsx +29 -0
  50. package/src/components/SeriesMeasurements.tsx +90 -0
  51. package/src/components/SeriesSummaryFromDisplaySet.tsx +21 -0
  52. package/src/components/StudyMeasurements.tsx +88 -0
  53. package/src/components/StudyMeasurementsActions.tsx +75 -0
  54. package/src/components/StudySummaryFromMetadata.test.ts +47 -0
  55. package/src/components/StudySummaryFromMetadata.tsx +31 -0
  56. package/src/components/StudySummaryWithActions.tsx +14 -0
  57. package/src/components/ThresholdMenu/ThresholdMenu.tsx +104 -0
  58. package/src/components/ThresholdMenu/ThresholdMenuWrapper.tsx +85 -0
  59. package/src/components/ThresholdMenu/index.ts +2 -0
  60. package/src/components/TrackingStatus/TrackingStatus.tsx +32 -0
  61. package/src/components/TrackingStatus/index.ts +1 -0
  62. package/src/components/VOIManualControlMenu/VOIManualControlMenu.tsx +190 -0
  63. package/src/components/VOIManualControlMenu/VOIManualControlMenuWrapper.tsx +85 -0
  64. package/src/components/VOIManualControlMenu/index.ts +2 -0
  65. package/src/components/ViewportColorbar/ViewportColorbar.tsx +150 -0
  66. package/src/components/ViewportColorbar/ViewportColorbarsContainer.tsx +125 -0
  67. package/src/components/ViewportColorbar/index.ts +5 -0
  68. package/src/components/ViewportDataOverlaySettingMenu/ViewportDataOverlayMenu.tsx +538 -0
  69. package/src/components/ViewportDataOverlaySettingMenu/ViewportDataOverlayMenuWrapper.tsx +91 -0
  70. package/src/components/ViewportDataOverlaySettingMenu/utils.ts +118 -0
  71. package/src/components/ViewportOrientationMenu/Viewport3DCompassMenu.tsx +261 -0
  72. package/src/components/ViewportOrientationMenu/ViewportOrientationMenu.tsx +249 -0
  73. package/src/components/ViewportOrientationMenu/ViewportOrientationMenuWrapper.tsx +40 -0
  74. package/src/components/ViewportWindowLevel/ViewportWindowLevel.tsx +261 -0
  75. package/src/components/ViewportWindowLevel/getViewportVolumeHistogram.ts +72 -0
  76. package/src/components/ViewportWindowLevel/histogramWorker.js +97 -0
  77. package/src/components/ViewportWindowLevel/index.js +1 -0
  78. package/src/components/ViewportWindowLevel/utils.ts +176 -0
  79. package/src/components/WindowLevelActionMenu/Colorbar.tsx +30 -0
  80. package/src/components/WindowLevelActionMenu/Colormap.tsx +121 -0
  81. package/src/components/WindowLevelActionMenu/VolumeLighting.tsx +82 -0
  82. package/src/components/WindowLevelActionMenu/VolumeRenderingOptions.tsx +38 -0
  83. package/src/components/WindowLevelActionMenu/VolumeRenderingPresets.tsx +36 -0
  84. package/src/components/WindowLevelActionMenu/VolumeRenderingPresetsContent.tsx +78 -0
  85. package/src/components/WindowLevelActionMenu/VolumeRenderingQuality.tsx +64 -0
  86. package/src/components/WindowLevelActionMenu/VolumeShade.tsx +47 -0
  87. package/src/components/WindowLevelActionMenu/VolumeShift.tsx +92 -0
  88. package/src/components/WindowLevelActionMenu/WindowLevel.tsx +157 -0
  89. package/src/components/WindowLevelActionMenu/WindowLevelActionMenu.tsx +102 -0
  90. package/src/components/WindowLevelActionMenu/WindowLevelActionMenuWrapper.tsx +131 -0
  91. package/src/components/WindowLevelActionMenu/defaultWindowLevelPresets.ts +23 -0
  92. package/src/components/WindowLevelActionMenu/index.ts +11 -0
  93. package/src/components/WindowLevelActionMenu/windowLevelPresetHotkeys.test.ts +19 -0
  94. package/src/components/index.ts +13 -0
  95. package/src/constants/index.ts +13 -0
  96. package/src/customizations/CustomDropdownMenuContent.tsx +106 -0
  97. package/src/customizations/CustomSegmentStatisticsHeader.tsx +140 -0
  98. package/src/customizations/captureViewportModalCustomization.tsx +175 -0
  99. package/src/customizations/colorbarCustomization.ts +93 -0
  100. package/src/customizations/gpuSettingsPresetCustomization.ts +8 -0
  101. package/src/customizations/layoutSelectorCustomization.ts +104 -0
  102. package/src/customizations/measurementsCustomization.ts +124 -0
  103. package/src/customizations/miscCustomization.ts +22 -0
  104. package/src/customizations/modalityColorMapCustomization.ts +23 -0
  105. package/src/customizations/segmentationHydrationCustomization.ts +16 -0
  106. package/src/customizations/segmentationPanelCustomization.tsx +119 -0
  107. package/src/customizations/segmentationToolbarCustomization.ts +964 -0
  108. package/src/customizations/toolGroupToolsCustomization.ts +204 -0
  109. package/src/customizations/toolbarButtonsCustomization.ts +805 -0
  110. package/src/customizations/viewportClickCommandsCustomization.ts +15 -0
  111. package/src/customizations/viewportDownloadWarningCustomization.tsx +6 -0
  112. package/src/customizations/viewportOverlayCustomization.tsx +46 -0
  113. package/src/customizations/viewportScrollbarCustomization.tsx +27 -0
  114. package/src/customizations/viewportToolsCustomization.ts +33 -0
  115. package/src/customizations/volumeRenderingCustomization.ts +14 -0
  116. package/src/customizations/windowLevelPresetsCustomization.ts +5 -0
  117. package/src/enums.ts +9 -0
  118. package/src/getCustomizationModule.tsx +54 -0
  119. package/src/getHangingProtocolModule.ts +47 -0
  120. package/src/getPanelModule.tsx +128 -0
  121. package/src/getSopClassHandlerModule.js +284 -0
  122. package/src/getToolbarModule.tsx +622 -0
  123. package/src/hooks/index.ts +9 -0
  124. package/src/hooks/useActiveViewportSegmentationRepresentations.ts +14 -0
  125. package/src/hooks/useMeasurementTracking.ts +132 -0
  126. package/src/hooks/useMeasurements.ts +104 -0
  127. package/src/hooks/useSegmentations.ts +147 -0
  128. package/src/hooks/useViewportDisplaySets.ts +284 -0
  129. package/src/hooks/useViewportFidelity.ts +243 -0
  130. package/src/hooks/useViewportHover.ts +77 -0
  131. package/src/hooks/useViewportRendering.tsx +868 -0
  132. package/src/hooks/useViewportSegmentations.ts +245 -0
  133. package/src/hps/fourUp.ts +117 -0
  134. package/src/hps/frameView.ts +1581 -0
  135. package/src/hps/main3D.ts +142 -0
  136. package/src/hps/mpr.ts +197 -0
  137. package/src/hps/mprAnd3DVolumeViewport.ts +124 -0
  138. package/src/hps/only3D.ts +70 -0
  139. package/src/hps/primary3D.ts +142 -0
  140. package/src/hps/primaryAxial.ts +114 -0
  141. package/src/id.js +5 -0
  142. package/src/index.tsx +352 -0
  143. package/src/init.tsx +450 -0
  144. package/src/initCineService.ts +75 -0
  145. package/src/initContextMenu.ts +94 -0
  146. package/src/initCornerstoneTools.js +191 -0
  147. package/src/initDoubleClick.ts +82 -0
  148. package/src/initMeasurementService.ts +576 -0
  149. package/src/initStudyPrefetcherService.ts +33 -0
  150. package/src/initWADOImageLoader.js +56 -0
  151. package/src/panels/PanelMeasurement.tsx +84 -0
  152. package/src/panels/PanelSegmentation.tsx +338 -0
  153. package/src/services/ColorbarService/ColorbarService.ts +242 -0
  154. package/src/services/ColorbarService/index.ts +2 -0
  155. package/src/services/CornerstoneCacheService/CornerstoneCacheService.ts +326 -0
  156. package/src/services/CornerstoneCacheService/index.js +3 -0
  157. package/src/services/SegmentationService/RTSTRUCT/mapROIContoursToRTStructData.ts +36 -0
  158. package/src/services/SegmentationService/SegmentationService.test.ts +3727 -0
  159. package/src/services/SegmentationService/SegmentationService.ts +2390 -0
  160. package/src/services/SegmentationService/backends/ISegmentationBackend.ts +102 -0
  161. package/src/services/SegmentationService/backends/ISegmentationServiceInternals.ts +44 -0
  162. package/src/services/SegmentationService/backends/LegacySegmentationBackend.ts +139 -0
  163. package/src/services/SegmentationService/backends/NextSegmentationBackend.ts +159 -0
  164. package/src/services/SegmentationService/backends/index.ts +4 -0
  165. package/src/services/SegmentationService/index.ts +3 -0
  166. package/src/services/SyncGroupService/SyncGroupService.ts +264 -0
  167. package/src/services/SyncGroupService/createHydrateSegmentationSynchronizer.ts +118 -0
  168. package/src/services/SyncGroupService/index.js +3 -0
  169. package/src/services/ToolGroupService/ToolGroupService.test.ts +83 -0
  170. package/src/services/ToolGroupService/ToolGroupService.ts +541 -0
  171. package/src/services/ToolGroupService/index.js +3 -0
  172. package/src/services/ViewedDataService/ViewedDataService.ts +58 -0
  173. package/src/services/ViewedDataService/index.ts +3 -0
  174. package/src/services/ViewportService/CornerstoneViewportService.ts +1814 -0
  175. package/src/services/ViewportService/IViewportService.ts +64 -0
  176. package/src/services/ViewportService/Viewport.ts +372 -0
  177. package/src/services/ViewportService/adapter/IViewportAdapter.contract.test.ts +467 -0
  178. package/src/services/ViewportService/adapter/IViewportAdapter.ts +179 -0
  179. package/src/services/ViewportService/adapter/LegacyViewportAdapter.ts +240 -0
  180. package/src/services/ViewportService/adapter/NextViewportAdapter.ts +241 -0
  181. package/src/services/ViewportService/adapter/getViewportAdapter.ts +62 -0
  182. package/src/services/ViewportService/adapter/index.ts +16 -0
  183. package/src/services/ViewportService/backends/IViewportBackend.ts +195 -0
  184. package/src/services/ViewportService/backends/IViewportOperations.ts +98 -0
  185. package/src/services/ViewportService/backends/IViewportServiceInternals.ts +47 -0
  186. package/src/services/ViewportService/backends/LegacyViewportBackend.ts +264 -0
  187. package/src/services/ViewportService/backends/LegacyViewportOperations.ts +272 -0
  188. package/src/services/ViewportService/backends/NextViewportBackend.ts +673 -0
  189. package/src/services/ViewportService/backends/NextViewportOperations.ts +169 -0
  190. package/src/services/ViewportService/backends/README.md +62 -0
  191. package/src/services/ViewportService/backends/dataIdRegistry.ts +121 -0
  192. package/src/services/ViewportService/backends/viewportOperations.ts +71 -0
  193. package/src/services/ViewportService/constants.ts +3 -0
  194. package/src/state.ts +34 -0
  195. package/src/stores/index.ts +5 -0
  196. package/src/stores/presentationUtils.ts +42 -0
  197. package/src/stores/useLutPresentationStore.ts +166 -0
  198. package/src/stores/usePositionPresentationStore.ts +172 -0
  199. package/src/stores/useSegmentationPresentationStore.test.ts +146 -0
  200. package/src/stores/useSegmentationPresentationStore.ts +417 -0
  201. package/src/stores/useSelectedSegmentationsForViewportStore.ts +85 -0
  202. package/src/stores/useSynchronizersStore.ts +84 -0
  203. package/src/synchronizers/frameViewSynchronizer.ts +52 -0
  204. package/src/tools/CalibrationLineTool.ts +97 -0
  205. package/src/tools/ImageOverlayViewerTool.tsx +279 -0
  206. package/src/tools/OverlayPlaneModuleProvider.ts +40 -0
  207. package/src/tools/WindowLevelTool.test.ts +55 -0
  208. package/src/tools/WindowLevelTool.ts +22 -0
  209. package/src/types/AppTypes.ts +70 -0
  210. package/src/types/Colorbar.ts +114 -0
  211. package/src/types/Colormap.ts +16 -0
  212. package/src/types/CornerstoneCacheService.ts +40 -0
  213. package/src/types/CornerstoneServices.ts +18 -0
  214. package/src/types/Presentation.ts +83 -0
  215. package/src/types/SelectedSegmentationByTypeMap.ts +3 -0
  216. package/src/types/ViewportPresets.ts +53 -0
  217. package/src/types/VolumeLighting.ts +7 -0
  218. package/src/types/VolumeRenderingConfig.ts +8 -0
  219. package/src/types/WindowLevel.ts +5 -0
  220. package/src/types/index.ts +10 -0
  221. package/src/utils/ActiveViewportBehavior.tsx +80 -0
  222. package/src/utils/CornerstoneViewportDownloadForm.tsx +319 -0
  223. package/src/utils/DicomFileUploader.ts +204 -0
  224. package/src/utils/JumpPresets.ts +14 -0
  225. package/src/utils/autoHydrateViewportTypes.ts +69 -0
  226. package/src/utils/colormaps.js +1597 -0
  227. package/src/utils/createSegmentationForViewport.test.ts +93 -0
  228. package/src/utils/createSegmentationForViewport.ts +123 -0
  229. package/src/utils/dicomLoaderService.js +225 -0
  230. package/src/utils/ecgMetadata.test.ts +137 -0
  231. package/src/utils/ecgMetadata.ts +109 -0
  232. package/src/utils/findNearbyToolData.test.ts +125 -0
  233. package/src/utils/findNearbyToolData.ts +21 -0
  234. package/src/utils/findWindowLevelPreset.test.ts +55 -0
  235. package/src/utils/findWindowLevelPreset.ts +46 -0
  236. package/src/utils/generateSegmentationCSVReport.test.ts +324 -0
  237. package/src/utils/generateSegmentationCSVReport.ts +131 -0
  238. package/src/utils/getActiveViewportEnabledElement.test.ts +70 -0
  239. package/src/utils/getActiveViewportEnabledElement.ts +8 -0
  240. package/src/utils/getCenterExtent.test.ts +313 -0
  241. package/src/utils/getCenterExtent.ts +46 -0
  242. package/src/utils/getCornerstoneBlendMode.test.ts +59 -0
  243. package/src/utils/getCornerstoneBlendMode.ts +25 -0
  244. package/src/utils/getCornerstoneOrientation.test.ts +78 -0
  245. package/src/utils/getCornerstoneOrientation.ts +31 -0
  246. package/src/utils/getCornerstoneViewportType.test.ts +169 -0
  247. package/src/utils/getCornerstoneViewportType.ts +88 -0
  248. package/src/utils/getInterleavedFrames.test.ts +85 -0
  249. package/src/utils/getInterleavedFrames.ts +73 -0
  250. package/src/utils/getLegacyViewportType.ts +64 -0
  251. package/src/utils/getNthFrames.test.ts +145 -0
  252. package/src/utils/getNthFrames.ts +31 -0
  253. package/src/utils/getViewportEnabledElement.test.ts +83 -0
  254. package/src/utils/getViewportEnabledElement.ts +8 -0
  255. package/src/utils/getViewportOrientationFromImageOrientationPatient.test.ts +50 -0
  256. package/src/utils/getViewportOrientationFromImageOrientationPatient.ts +56 -0
  257. package/src/utils/hydrationUtils.test.ts +572 -0
  258. package/src/utils/hydrationUtils.ts +197 -0
  259. package/src/utils/imageSliceSync/calculateViewportRegistrations.ts +28 -0
  260. package/src/utils/imageSliceSync/toggleImageSliceSync.ts +101 -0
  261. package/src/utils/index.ts +29 -0
  262. package/src/utils/initGpuSettingsPreset.ts +51 -0
  263. package/src/utils/initViewTiming.test.ts +342 -0
  264. package/src/utils/initViewTiming.ts +52 -0
  265. package/src/utils/initWebWorkerProgressHandler.test.ts +381 -0
  266. package/src/utils/initWebWorkerProgressHandler.ts +110 -0
  267. package/src/utils/interleave.test.ts +304 -0
  268. package/src/utils/interleave.ts +32 -0
  269. package/src/utils/interleaveCenterLoader.test.ts +547 -0
  270. package/src/utils/interleaveCenterLoader.ts +143 -0
  271. package/src/utils/interleaveTopToBottom.test.ts +487 -0
  272. package/src/utils/interleaveTopToBottom.ts +132 -0
  273. package/src/utils/isAnyDisplaySetCommon.ts +18 -0
  274. package/src/utils/isDisplaySetOverlayable.ts +106 -0
  275. package/src/utils/isMeasurementWithinViewport.test.ts +340 -0
  276. package/src/utils/isMeasurementWithinViewport.ts +33 -0
  277. package/src/utils/isReferenceViewable.test.ts +581 -0
  278. package/src/utils/isReferenceViewable.ts +95 -0
  279. package/src/utils/loadDisplaySetData.ts +49 -0
  280. package/src/utils/measurementServiceMappings/Angle.ts +200 -0
  281. package/src/utils/measurementServiceMappings/ArrowAnnotate.ts +176 -0
  282. package/src/utils/measurementServiceMappings/Bidirectional.ts +193 -0
  283. package/src/utils/measurementServiceMappings/CircleROI.ts +227 -0
  284. package/src/utils/measurementServiceMappings/CobbAngle.ts +206 -0
  285. package/src/utils/measurementServiceMappings/EllipticalROI.ts +221 -0
  286. package/src/utils/measurementServiceMappings/Length.ts +206 -0
  287. package/src/utils/measurementServiceMappings/LivewireContour.ts +175 -0
  288. package/src/utils/measurementServiceMappings/PlanarFreehandROI.ts +228 -0
  289. package/src/utils/measurementServiceMappings/Probe.ts +192 -0
  290. package/src/utils/measurementServiceMappings/RectangleROI.ts +225 -0
  291. package/src/utils/measurementServiceMappings/SegmentBidirectional.ts +184 -0
  292. package/src/utils/measurementServiceMappings/SplineROI.ts +227 -0
  293. package/src/utils/measurementServiceMappings/UltrasoundDirectional.ts +214 -0
  294. package/src/utils/measurementServiceMappings/UltrasoundPleuraBLine.ts +179 -0
  295. package/src/utils/measurementServiceMappings/constants/supportedTools.js +21 -0
  296. package/src/utils/measurementServiceMappings/index.ts +3 -0
  297. package/src/utils/measurementServiceMappings/measurementServiceMappingsFactory.ts +324 -0
  298. package/src/utils/measurementServiceMappings/utils/getDisplayUnit.js +3 -0
  299. package/src/utils/measurementServiceMappings/utils/getHandlesFromPoints.js +14 -0
  300. package/src/utils/measurementServiceMappings/utils/getIsLocked.ts +5 -0
  301. package/src/utils/measurementServiceMappings/utils/getIsVisible.ts +6 -0
  302. package/src/utils/measurementServiceMappings/utils/getSOPInstanceAttributes.js +66 -0
  303. package/src/utils/measurementServiceMappings/utils/getValueDisplayString.js +12 -0
  304. package/src/utils/measurementServiceMappings/utils/index.ts +17 -0
  305. package/src/utils/measurementServiceMappings/utils/selection.ts +33 -0
  306. package/src/utils/mpr/getProtocolViewportStructureFromGridViewports.ts +74 -0
  307. package/src/utils/nextViewportPolicies.ts +41 -0
  308. package/src/utils/nextViewports.ts +157 -0
  309. package/src/utils/nthLoader.test.ts +317 -0
  310. package/src/utils/nthLoader.ts +78 -0
  311. package/src/utils/presentations/getViewportPresentations.test.ts +280 -0
  312. package/src/utils/presentations/getViewportPresentations.ts +151 -0
  313. package/src/utils/promptHydrationDialog.test.ts +490 -0
  314. package/src/utils/promptHydrationDialog.ts +197 -0
  315. package/src/utils/promptTimePointScope.tsx +82 -0
  316. package/src/utils/removeViewportSegmentationRepresentations.test.ts +129 -0
  317. package/src/utils/removeViewportSegmentationRepresentations.ts +17 -0
  318. package/src/utils/segmentUtils.test.ts +515 -0
  319. package/src/utils/segmentUtils.ts +46 -0
  320. package/src/utils/segmentationExportUtils.test.ts +100 -0
  321. package/src/utils/segmentationExportUtils.ts +171 -0
  322. package/src/utils/segmentationHandlers.test.ts +614 -0
  323. package/src/utils/segmentationHandlers.ts +164 -0
  324. package/src/utils/setUpAnnotationEventHandlers.ts +26 -0
  325. package/src/utils/setUpSegmentationEventHandlers.test.ts +372 -0
  326. package/src/utils/setUpSegmentationEventHandlers.ts +122 -0
  327. package/src/utils/toggleVOISliceSync.test.ts +606 -0
  328. package/src/utils/toggleVOISliceSync.ts +103 -0
  329. package/src/utils/transitions.test.ts +351 -0
  330. package/src/utils/transitions.ts +300 -0
  331. package/src/utils/updateSegmentationStats.test.ts +942 -0
  332. package/src/utils/updateSegmentationStats.ts +192 -0
  333. package/src/utils/viewportDataShape.ts +85 -0
  334. package/src/utils/volume3dView.test.ts +48 -0
  335. package/src/utils/volume3dView.ts +113 -0
@@ -0,0 +1,3008 @@
1
+ import {
2
+ getEnabledElement,
3
+ utilities as csUtils,
4
+ Types as CoreTypes,
5
+ getRenderingEngines,
6
+ } from '@cornerstonejs/core';
7
+ import {
8
+ ToolGroupManager,
9
+ Enums,
10
+ utilities as cstUtils,
11
+ annotation,
12
+ Types as ToolTypes,
13
+ SplineContourSegmentationTool,
14
+ cancelActiveManipulations,
15
+ } from '@cornerstonejs/tools';
16
+ import {
17
+ SegmentInfo,
18
+ LogicalOperation,
19
+ OperatorOptions,
20
+ } from '@cornerstonejs/tools/utilities/contourSegmentation/logicalOperators';
21
+ import * as cornerstoneTools from '@cornerstonejs/tools';
22
+ import * as labelmapInterpolation from '@cornerstonejs/labelmap-interpolation';
23
+ import { ONNXSegmentationController } from '@cornerstonejs/ai';
24
+
25
+ import { Types as OhifTypes, utils } from '@ohif/core';
26
+ import {
27
+ callInputDialogAutoComplete,
28
+ createReportAsync,
29
+ colorPickerDialog,
30
+ callInputDialog,
31
+ } from '@ohif/extension-default';
32
+ import toggleImageSliceSync from './utils/imageSliceSync/toggleImageSliceSync';
33
+ // Sanctioned flag read: RTSTRUCT contour hydration pins the referenced image to
34
+ // stack mode on the native ("next") path, a decision made before a target viewport exists.
35
+ import { getHydrationViewportTypeForModality } from './utils/nextViewportPolicies';
36
+ import { getFirstAnnotationSelected } from './utils/measurementServiceMappings/utils/selection';
37
+ import { getViewportEnabledElement } from './utils/getViewportEnabledElement';
38
+ import getActiveViewportEnabledElement from './utils/getActiveViewportEnabledElement';
39
+ import toggleVOISliceSync from './utils/toggleVOISliceSync';
40
+ import { findWindowLevelPreset } from './utils/findWindowLevelPreset';
41
+ import {
42
+ isStackViewportType,
43
+ isOrthographicViewportType,
44
+ isVolume3DViewportType,
45
+ isVolumeViewportType,
46
+ } from './utils/getLegacyViewportType';
47
+ import { viewportOperations as ops } from './services/ViewportService/backends/viewportOperations';
48
+ import { getViewportAdapter } from './services/ViewportService/adapter';
49
+ import {
50
+ rotateVolume3D,
51
+ setVolume3DSpin,
52
+ setVolume3DViewDirection,
53
+ type ViewDirection,
54
+ } from './utils/volume3dView';
55
+ import {
56
+ usePositionPresentationStore,
57
+ useSegmentationPresentationStore,
58
+ useSelectedSegmentationsForViewportStore,
59
+ } from './stores';
60
+ import { toolNames } from './initCornerstoneTools';
61
+ import CornerstoneViewportDownloadForm from './utils/CornerstoneViewportDownloadForm';
62
+ import { updateSegmentBidirectionalStats } from './utils/updateSegmentationStats';
63
+ import { generateSegmentationCSVReport } from './utils/generateSegmentationCSVReport';
64
+ import { getUpdatedViewportsForSegmentation } from './utils/hydrationUtils';
65
+ import { loadDisplaySetData } from './utils/loadDisplaySetData';
66
+ import { SegmentationRepresentations } from '@cornerstonejs/tools/enums';
67
+ import { EasingFunctionEnum } from './utils/transitions';
68
+ import { createSegmentationForViewport } from './utils/createSegmentationForViewport';
69
+ import { utilities as segmentationUtilities } from '@cornerstonejs/tools/segmentation';
70
+ import i18n from '@ohif/i18n';
71
+
72
+ const { add, intersect, subtract, copy } = cstUtils.contourSegmentation;
73
+
74
+ const { DefaultHistoryMemo } = csUtils.HistoryMemo;
75
+ const toggleSyncFunctions = {
76
+ imageSlice: toggleImageSliceSync,
77
+ voi: toggleVOISliceSync,
78
+ };
79
+
80
+ const { segmentation: segmentationUtils } = cstUtils;
81
+
82
+ const getLabelmapTools = ({ toolGroupService }) => {
83
+ const labelmapTools = [];
84
+ const toolGroupIds = toolGroupService.getToolGroupIds();
85
+ toolGroupIds.forEach(toolGroupId => {
86
+ const toolGroup = cornerstoneTools.ToolGroupManager.getToolGroup(toolGroupId);
87
+ const tools = toolGroup.getToolInstances();
88
+ // tools is an object with toolName as the key and tool as the value
89
+ Object.keys(tools).forEach(toolName => {
90
+ const tool = tools[toolName];
91
+ if (tool instanceof cornerstoneTools.LabelmapBaseTool) {
92
+ labelmapTools.push(tool);
93
+ }
94
+ });
95
+ });
96
+ return labelmapTools;
97
+ };
98
+
99
+ const getPreviewTools = ({ toolGroupService }) => {
100
+ const labelmapTools = getLabelmapTools({ toolGroupService });
101
+
102
+ const previewTools = labelmapTools.filter(tool => tool.acceptPreview || tool.rejectPreview);
103
+
104
+ return previewTools;
105
+ };
106
+
107
+ const segmentAI = new ONNXSegmentationController({
108
+ autoSegmentMode: true,
109
+ models: {
110
+ sam_b: [
111
+ {
112
+ name: 'sam-b-encoder',
113
+ url: 'https://huggingface.co/schmuell/sam-b-fp16/resolve/b64d0347d4d2cafd9a4e43b38853d6b5daa319fb/sam_vit_b_01ec64.encoder-fp16.onnx',
114
+ size: 180,
115
+ key: 'encoder',
116
+ },
117
+ {
118
+ name: 'sam-b-decoder',
119
+ url: 'https://huggingface.co/schmuell/sam-b-fp16/resolve/b64d0347d4d2cafd9a4e43b38853d6b5daa319fb/sam_vit_b_01ec64.decoder.onnx',
120
+ size: 17,
121
+ key: 'decoder',
122
+ },
123
+ ],
124
+ },
125
+ modelName: 'sam_b',
126
+ });
127
+ let segmentAIEnabled = false;
128
+
129
+ /**
130
+ * Converts a CSS color (hex or rgb/rgba string) to the { r, g, b, a }
131
+ * object shape the color picker dialog expects.
132
+ */
133
+ function _cssColorToRgba(cssColor = ''): { r: number; g: number; b: number; a: number } {
134
+ const rgbMatch = cssColor.match(
135
+ /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+)\s*)?\)/
136
+ );
137
+ if (rgbMatch) {
138
+ return {
139
+ r: Number(rgbMatch[1]),
140
+ g: Number(rgbMatch[2]),
141
+ b: Number(rgbMatch[3]),
142
+ a: rgbMatch[4] !== undefined ? Number(rgbMatch[4]) : 1,
143
+ };
144
+ }
145
+ return { r: 255, g: 255, b: 0, ...csUtils.color.hexToRgb(cssColor), a: 1 };
146
+ }
147
+
148
+ function commandsModule({
149
+ servicesManager,
150
+ commandsManager,
151
+ extensionManager,
152
+ }: OhifTypes.Extensions.ExtensionParams): OhifTypes.Extensions.CommandsModule {
153
+ const {
154
+ viewportGridService,
155
+ toolbarService,
156
+ toolGroupService,
157
+ cineService,
158
+ uiDialogService,
159
+ cornerstoneViewportService,
160
+ uiNotificationService,
161
+ measurementService,
162
+ customizationService,
163
+ colorbarService,
164
+ hangingProtocolService,
165
+ syncGroupService,
166
+ segmentationService,
167
+ displaySetService,
168
+ } = servicesManager.services as AppTypes.Services;
169
+
170
+ function _getActiveViewportEnabledElement() {
171
+ return getActiveViewportEnabledElement(viewportGridService);
172
+ }
173
+
174
+ function _getViewportEnabledElement(viewportId: string) {
175
+ return getViewportEnabledElement(viewportId);
176
+ }
177
+
178
+ // Resolves the cornerstone viewport for a command: the given viewport id, else the
179
+ // active one. Returns undefined when nothing is enabled.
180
+ function _resolveViewport(viewportId?: string) {
181
+ const enabledElement = viewportId
182
+ ? _getViewportEnabledElement(viewportId)
183
+ : _getActiveViewportEnabledElement();
184
+ return enabledElement?.viewport;
185
+ }
186
+
187
+ function _getActiveViewportToolGroupId() {
188
+ const viewport = _getActiveViewportEnabledElement();
189
+ const toolGroup = viewport && toolGroupService.getToolGroupForViewport(viewport.id);
190
+ return toolGroup?.id;
191
+ }
192
+
193
+ function _usesPrimaryActivation(bindings) {
194
+ if (!bindings?.length) {
195
+ return true;
196
+ }
197
+
198
+ return bindings.some(
199
+ binding =>
200
+ binding.mouseButton === Enums.MouseBindings.Primary &&
201
+ binding.modifierKey == null &&
202
+ binding.numTouchPoints == null
203
+ );
204
+ }
205
+
206
+ function _getActiveSegmentationInfo() {
207
+ const viewportId = viewportGridService.getActiveViewportId();
208
+ const activeSegmentation = segmentationService.getActiveSegmentation(viewportId);
209
+ const segmentationId = activeSegmentation?.segmentationId;
210
+ const activeSegmentIndex = segmentationService.getActiveSegment(viewportId).segmentIndex;
211
+
212
+ return {
213
+ segmentationId,
214
+ segmentIndex: activeSegmentIndex,
215
+ };
216
+ }
217
+
218
+ function _handleBrushSizeAction(action: 'increase' | 'decrease') {
219
+ const toolGroupIds = toolGroupService.getToolGroupIds();
220
+ if (!toolGroupIds?.length) {
221
+ return;
222
+ }
223
+
224
+ for (const toolGroupId of toolGroupIds) {
225
+ const brushSize = segmentationUtils.getBrushSizeForToolGroup(toolGroupId);
226
+
227
+ const newBrushSize = action === 'increase' ? brushSize + 3 : brushSize - 3;
228
+
229
+ if (brushSize) {
230
+ segmentationUtils.setBrushSizeForToolGroup(toolGroupId, newBrushSize);
231
+
232
+ toolbarService.refreshToolbarState({ toolGroupId });
233
+ }
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Creates a command function that sets a style property for segmentation types.
239
+ * If type is provided, sets the property for that type only.
240
+ * If type is not provided, sets the property for both Labelmap and Contour types.
241
+ * @param propertyName - The name of the style property to set
242
+ * @returns A command function that takes { type, value }
243
+ */
244
+ const createSetStyleCommand = (propertyName: string) => {
245
+ return ({ type, value }) => {
246
+ const { segmentationService } = servicesManager.services;
247
+ if (type) {
248
+ segmentationService.setStyle({ type }, { [propertyName]: value });
249
+ } else {
250
+ segmentationService.setStyle(
251
+ { type: SegmentationRepresentations.Labelmap },
252
+ { [propertyName]: value }
253
+ );
254
+ segmentationService.setStyle(
255
+ { type: SegmentationRepresentations.Contour },
256
+ { [propertyName]: value }
257
+ );
258
+ }
259
+ };
260
+ };
261
+
262
+ const actions = {
263
+ jumpToMeasurementViewport: ({ annotationUID, measurement }) => {
264
+ cornerstoneTools.annotation.selection.setAnnotationSelected(annotationUID, true);
265
+ const { metadata } = measurement;
266
+
267
+ const activeViewportId = viewportGridService.getActiveViewportId();
268
+ // Finds the best viewport to jump to for showing the annotation view reference
269
+ // This may be different from active if there is a viewport already showing the display set.
270
+ const viewportId = cornerstoneViewportService.findNavigationCompatibleViewportId(
271
+ activeViewportId,
272
+ metadata
273
+ );
274
+ if (viewportId) {
275
+ const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
276
+ viewport.setViewReference(metadata);
277
+ viewport.render();
278
+
279
+ // If the measurement is not visible inside the current viewport, move the
280
+ // camera to it. The operations backend handles the lane: legacy re-centers
281
+ // in-plane (getCamera/setCamera), native skips it (no in-plane pan yet, CS-14)
282
+ // since setViewReference above already navigated to the measurement's slice.
283
+ if (ops.centerOnMeasurement(viewport, measurement)) {
284
+ viewport.render();
285
+ }
286
+
287
+ return;
288
+ }
289
+
290
+ const { displaySetInstanceUID: referencedDisplaySetInstanceUID } = measurement;
291
+ if (!referencedDisplaySetInstanceUID) {
292
+ console.warn('ViewportGrid::No display set found in', measurement);
293
+ return;
294
+ }
295
+
296
+ // Finds the viewport to update to show the given displayset/orientation.
297
+ // This will choose a view already containing the measurement display set
298
+ // if possible, otherwise will fallback to the active.
299
+ const viewportToUpdate = cornerstoneViewportService.findUpdateableViewportConfiguration(
300
+ activeViewportId,
301
+ measurement
302
+ );
303
+
304
+ if (!viewportToUpdate) {
305
+ console.warn('Unable to find a viewport to show this in');
306
+ return;
307
+ }
308
+ const updatedViewports = hangingProtocolService.getViewportsRequireUpdate(
309
+ viewportToUpdate.viewportId,
310
+ referencedDisplaySetInstanceUID
311
+ );
312
+
313
+ if (!updatedViewports?.[0]) {
314
+ console.warn(
315
+ 'ViewportGrid::Unable to navigate to viewport containing',
316
+ referencedDisplaySetInstanceUID
317
+ );
318
+ return;
319
+ }
320
+
321
+ updatedViewports[0].viewportOptions = viewportToUpdate.viewportOptions;
322
+
323
+ // Update stored position presentation
324
+ commandsManager.run('updateStoredPositionPresentation', {
325
+ viewportId: viewportToUpdate.viewportId,
326
+ displaySetInstanceUIDs: [referencedDisplaySetInstanceUID],
327
+ referencedImageId: measurement.referencedImageId,
328
+ options: {
329
+ ...measurement.metadata,
330
+ },
331
+ });
332
+
333
+ commandsManager.run('setDisplaySetsForViewports', { viewportsToUpdate: updatedViewports });
334
+ },
335
+
336
+ /**
337
+ * Cancels any in-progress annotation manipulation (e.g. drawing a Spline,
338
+ * Livewire or PlanarFreehand contour) on the active viewport. Reached on
339
+ * Escape via the `cancelActiveOperation` command. `cancelActiveManipulations`
340
+ * invokes the `cancel` method of each active/passive tool that has an
341
+ * in-progress annotation, so it is a no-op when nothing is being drawn.
342
+ */
343
+ cancelMeasurement: () => {
344
+ const element = _getActiveViewportEnabledElement()?.viewport?.element;
345
+ if (element) {
346
+ cancelActiveManipulations(element);
347
+ }
348
+ },
349
+
350
+ /**
351
+ * Loads a display set's data without reference to a viewport.
352
+ *
353
+ * The viewport-independent counterpart to displaying it: this makes the data
354
+ * available (for a segmentation, present in the segmentation state), while
355
+ * where it is shown remains a separate decision. Loading is memoized per
356
+ * display set, so calling this early or more than once is free.
357
+ */
358
+ loadDisplaySetData: async ({ displaySet, displaySetInstanceUID }) => {
359
+ const displaySetToLoad =
360
+ displaySet ?? displaySetService.getDisplaySetByUID(displaySetInstanceUID);
361
+
362
+ if (!displaySetToLoad) {
363
+ return;
364
+ }
365
+
366
+ await loadDisplaySetData(displaySetToLoad, servicesManager);
367
+ },
368
+
369
+ hydrateSecondaryDisplaySet: async ({ displaySet, viewportId }) => {
370
+ if (!displaySet) {
371
+ return;
372
+ }
373
+
374
+ const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
375
+
376
+ if (displaySet.isOverlayDisplaySet) {
377
+ // update the previously stored segmentationPresentation with the new viewportId
378
+ // presentation so that when we put the referencedDisplaySet back in the viewport
379
+ // it will have the correct segmentation representation hydrated
380
+
381
+ // Recorded as a hint only: _setSegmentationPresentation corrects
382
+ // Labelmap <-> Surface against the viewport that actually renders it,
383
+ // so this does not have to be resolved against a viewport here.
384
+ const segmentationType =
385
+ // Todo: check if PMAP modality should be handled such as SEG
386
+ displaySet.Modality !== 'SEG'
387
+ ? SegmentationRepresentations.Contour
388
+ : viewport && isVolume3DViewportType(viewport)
389
+ ? SegmentationRepresentations.Surface
390
+ : SegmentationRepresentations.Labelmap;
391
+
392
+ commandsManager.runCommand('updateStoredSegmentationPresentation', {
393
+ displaySet,
394
+ type: segmentationType,
395
+ });
396
+ }
397
+
398
+ // isHydrated means "display this display set as part of a standard view".
399
+ // That is decided here and does not depend on a viewport existing yet.
400
+ displaySet.isHydrated = true;
401
+
402
+ const referencedDisplaySetInstanceUID = displaySet.referencedDisplaySetInstanceUID;
403
+
404
+ const storePositionPresentation = refDisplaySet => {
405
+ // update the previously stored positionPresentation with the new viewportId
406
+ // presentation so that when we put the referencedDisplaySet back in the viewport
407
+ // it will be in the correct position zoom and pan
408
+ commandsManager.runCommand('updateStoredPositionPresentation', {
409
+ viewportId,
410
+ displaySetInstanceUIDs: [refDisplaySet.displaySetInstanceUID],
411
+ });
412
+ };
413
+
414
+ if (displaySet.Modality === 'SEG' || displaySet.Modality === 'RTSTRUCT') {
415
+ const referencedDisplaySet = displaySetService.getDisplaySetByUID(
416
+ referencedDisplaySetInstanceUID
417
+ );
418
+ storePositionPresentation(referencedDisplaySet);
419
+
420
+ const results = commandsManager.runCommand('loadSegmentationDisplaySetsForViewport', {
421
+ viewportId,
422
+ displaySetInstanceUIDs: [referencedDisplaySet.displaySetInstanceUID],
423
+ derivedDisplaySetInstanceUID: displaySet.displaySetInstanceUID,
424
+ // RTSTRUCT-on-next pins the referenced image to stack mode on hydrate;
425
+ // see the policy's rationale in utils/nextViewportPolicies.
426
+ viewportType: getHydrationViewportTypeForModality(displaySet.Modality),
427
+ });
428
+
429
+ const disableEditing = customizationService.getCustomization(
430
+ 'panelSegmentation.disableEditing'
431
+ );
432
+ if (disableEditing) {
433
+ // Locking is a property of the segmentation, not of a per-viewport
434
+ // representation. Reading the segments from the representations would
435
+ // silently skip locking whenever hydration ran before the viewport
436
+ // had one.
437
+ const segmentationId = displaySet.displaySetInstanceUID;
438
+ const segmentation = segmentationService.getSegmentation(segmentationId);
439
+
440
+ Object.keys(segmentation?.segments ?? {}).forEach(segmentIndex => {
441
+ segmentationService.setSegmentLocked(segmentationId, parseInt(segmentIndex), true);
442
+ });
443
+ }
444
+ return results;
445
+ } else if (displaySet.Modality === 'SR') {
446
+ const results = commandsManager.runCommand('hydrateStructuredReport', {
447
+ displaySetInstanceUID: displaySet.displaySetInstanceUID,
448
+ });
449
+ const { SeriesInstanceUIDs } = results;
450
+ const referencedDisplaySets = displaySetService.getDisplaySetsForSeries(
451
+ SeriesInstanceUIDs[0]
452
+ );
453
+ referencedDisplaySets.forEach(storePositionPresentation);
454
+
455
+ if (referencedDisplaySets.length) {
456
+ actions.setDisplaySetsForViewports({
457
+ viewportsToUpdate: [
458
+ {
459
+ viewportId: viewportGridService.getActiveViewportId(),
460
+ displaySetInstanceUIDs: [referencedDisplaySets[0].displaySetInstanceUID],
461
+ },
462
+ ],
463
+ });
464
+ }
465
+ return results;
466
+ }
467
+ },
468
+ runSegmentBidirectional: async ({ segmentationId, segmentIndex } = {}) => {
469
+ // Get active segmentation if not specified
470
+ const targetSegmentation =
471
+ segmentationId && segmentIndex
472
+ ? { segmentationId, segmentIndex }
473
+ : _getActiveSegmentationInfo();
474
+
475
+ const { segmentationId: targetId, segmentIndex: targetIndex } = targetSegmentation;
476
+
477
+ // Check if the segment has voxels before computing bidirectional measurement
478
+ const uniqueSegmentIndices = cstUtils.segmentation.getUniqueSegmentIndices(targetId);
479
+ const hasVoxels = uniqueSegmentIndices.includes(targetIndex);
480
+
481
+ if (!hasVoxels) {
482
+ uiNotificationService.show({
483
+ title: i18n.t('SegmentationPanel:Segment Bidirectional'),
484
+ message: i18n.t(
485
+ 'SegmentationPanel:Draw a segment before using bidirectional measurement'
486
+ ),
487
+ type: 'warning',
488
+ });
489
+ return;
490
+ }
491
+
492
+ // Get bidirectional measurement data
493
+ const bidirectionalData = await cstUtils.segmentation.getSegmentLargestBidirectional({
494
+ segmentationId: targetId,
495
+ segmentIndices: [targetIndex],
496
+ });
497
+
498
+ if (!bidirectionalData.length) {
499
+ return;
500
+ }
501
+
502
+ const activeViewportId = viewportGridService.getActiveViewportId();
503
+
504
+ // Process each bidirectional measurement
505
+ bidirectionalData.forEach(measurement => {
506
+ const { segmentIndex, majorAxis, minorAxis } = measurement;
507
+
508
+ // Create annotation
509
+ const annotation = cornerstoneTools.SegmentBidirectionalTool.hydrate(
510
+ activeViewportId,
511
+ [majorAxis, minorAxis],
512
+ {
513
+ segmentIndex,
514
+ segmentationId: targetId,
515
+ }
516
+ );
517
+
518
+ measurement.annotationUID = annotation.annotationUID;
519
+
520
+ // Update segmentation stats
521
+ const updatedSegmentation = updateSegmentBidirectionalStats({
522
+ segmentationId: targetId,
523
+ segmentIndex: targetIndex,
524
+ bidirectionalData: measurement,
525
+ segmentationService,
526
+ annotation,
527
+ });
528
+
529
+ // Save changes if needed
530
+ if (updatedSegmentation) {
531
+ segmentationService.addOrUpdateSegmentation({
532
+ segmentationId: targetId,
533
+ segments: updatedSegmentation.segments,
534
+ });
535
+ }
536
+ });
537
+
538
+ // get the active segmentIndex bidirectional annotation and jump to it
539
+ const activeBidirectional = bidirectionalData.find(
540
+ measurement => measurement.segmentIndex === targetIndex
541
+ );
542
+ commandsManager.run('jumpToMeasurement', {
543
+ uid: activeBidirectional?.annotationUID,
544
+ });
545
+ },
546
+ interpolateLabelmap: () => {
547
+ const { segmentationId, segmentIndex } = _getActiveSegmentationInfo();
548
+ labelmapInterpolation.interpolate({
549
+ segmentationId,
550
+ segmentIndex,
551
+ });
552
+ },
553
+ /**
554
+ * Generates the selector props for the context menu, specific to
555
+ * the cornerstone viewport, and then runs the context menu.
556
+ */
557
+ showCornerstoneContextMenu: options => {
558
+ const element = _getActiveViewportEnabledElement()?.viewport?.element;
559
+
560
+ const optionsToUse = { ...options, element };
561
+ const { useSelectedAnnotation, nearbyToolData, event } = optionsToUse;
562
+
563
+ // This code is used to invoke the context menu via keyboard shortcuts
564
+ if (useSelectedAnnotation && !nearbyToolData) {
565
+ const firstAnnotationSelected = getFirstAnnotationSelected(element);
566
+ // filter by allowed selected tools from config property (if there is any)
567
+ const isToolAllowed =
568
+ !optionsToUse.allowedSelectedTools ||
569
+ optionsToUse.allowedSelectedTools.includes(firstAnnotationSelected?.metadata?.toolName);
570
+ if (isToolAllowed) {
571
+ optionsToUse.nearbyToolData = firstAnnotationSelected;
572
+ } else {
573
+ return;
574
+ }
575
+ }
576
+
577
+ optionsToUse.defaultPointsPosition = [];
578
+ // if (optionsToUse.nearbyToolData) {
579
+ // optionsToUse.defaultPointsPosition = commandsManager.runCommand(
580
+ // 'getToolDataActiveCanvasPoints',
581
+ // { toolData: optionsToUse.nearbyToolData }
582
+ // );
583
+ // }
584
+
585
+ // TODO - make the selectorProps richer by including the study metadata and display set.
586
+ optionsToUse.selectorProps = {
587
+ toolName: optionsToUse.nearbyToolData?.metadata?.toolName,
588
+ value: optionsToUse.nearbyToolData,
589
+ uid: optionsToUse.nearbyToolData?.annotationUID,
590
+ nearbyToolData: optionsToUse.nearbyToolData,
591
+ event,
592
+ ...optionsToUse.selectorProps,
593
+ };
594
+
595
+ commandsManager.run(options, optionsToUse);
596
+ },
597
+ /**
598
+ * Records the desired presentation of a derived (SEG/RTSTRUCT) display set
599
+ * against the display set it references.
600
+ *
601
+ * @param props.hydrated - true to display it in the standard viewports for
602
+ * the referenced display set, false to stop displaying it there. Writing
603
+ * false matters: the store is the desired state a viewport converges on,
604
+ * so simply omitting an entry would let an earlier `true` keep restoring
605
+ * a segmentation that was removed.
606
+ */
607
+ updateStoredSegmentationPresentation: ({ displaySet, type, hydrated = true }) => {
608
+ const {
609
+ addSegmentationPresentationItem,
610
+ setHydrationForSegmentation,
611
+ segmentationPresentationStore,
612
+ } = useSegmentationPresentationStore.getState();
613
+
614
+ const referencedDisplaySetInstanceUID = displaySet.referencedDisplaySetInstanceUID;
615
+ const segmentationId = displaySet.displaySetInstanceUID;
616
+
617
+ // The store is keyed by the referenced display set, so there is no key to
618
+ // create an entry under without one - segmentations created in the client
619
+ // (see the SEGMENTATION_ADDED handler) have no referenced display set,
620
+ // and writing them would land every one of them under a single
621
+ // `undefined` key.
622
+ //
623
+ // They are still recorded, though: storePresentation records a
624
+ // client-drawn segmentation as hydrated under the key of whatever
625
+ // viewport it was drawn in (see _getInitialHydrationForSync), and that
626
+ // record is what re-adds it on the next mount. Nothing else supersedes it
627
+ // - syncSegmentationPresentation only ever merges - so a removal has to
628
+ // update it in place wherever it was written, or a segmentation the user
629
+ // dismissed or deleted comes back.
630
+ if (!referencedDisplaySetInstanceUID) {
631
+ setHydrationForSegmentation(segmentationId, { hydrated, type });
632
+ return;
633
+ }
634
+
635
+ // A caller that only changes hydration (removing the layer) has no reason
636
+ // to know the representation type, so keep whatever hydration recorded.
637
+ const existingType = segmentationPresentationStore[referencedDisplaySetInstanceUID]?.find(
638
+ item => item.segmentationId === segmentationId
639
+ )?.type;
640
+
641
+ addSegmentationPresentationItem(referencedDisplaySetInstanceUID, {
642
+ segmentationId,
643
+ hydrated,
644
+ type: type ?? existingType,
645
+ });
646
+ },
647
+
648
+ /** Stores the changed position presentation */
649
+ updateStoredPositionPresentation: ({
650
+ viewportId,
651
+ displaySetInstanceUIDs,
652
+ referencedImageId,
653
+ options,
654
+ }) => {
655
+ const presentations = cornerstoneViewportService.getPresentations(viewportId);
656
+ const { positionPresentationStore, setPositionPresentation, getPositionPresentationId } =
657
+ usePositionPresentationStore.getState();
658
+
659
+ // Look inside positionPresentationStore and find the key that includes ALL the displaySetInstanceUIDs
660
+ // and the value has viewportId as activeViewportId.
661
+ let previousReferencedDisplaySetStoreKey;
662
+
663
+ if (
664
+ displaySetInstanceUIDs &&
665
+ Array.isArray(displaySetInstanceUIDs) &&
666
+ displaySetInstanceUIDs.length > 0
667
+ ) {
668
+ previousReferencedDisplaySetStoreKey = Object.entries(positionPresentationStore).find(
669
+ ([key, value]) => {
670
+ return (
671
+ displaySetInstanceUIDs.every(uid => key.includes(uid)) &&
672
+ value?.viewportId === viewportId
673
+ );
674
+ }
675
+ )?.[0];
676
+ }
677
+
678
+ // Create presentation data with referencedImageId and options if provided
679
+ const presentationData =
680
+ referencedImageId || options?.FrameOfReferenceUID
681
+ ? {
682
+ ...presentations.positionPresentation,
683
+ viewReference: {
684
+ referencedImageId,
685
+ ...options,
686
+ },
687
+ }
688
+ : presentations.positionPresentation;
689
+
690
+ // With no live viewport there is no position to record - getPresentations
691
+ // returns an object whose positionPresentation is undefined. Writing that
692
+ // would clobber the referenced series' stored slice/pan/zoom with
693
+ // undefined, which matters now that hydration runs without a viewport.
694
+ if (!presentationData) {
695
+ return;
696
+ }
697
+
698
+ if (previousReferencedDisplaySetStoreKey) {
699
+ setPositionPresentation(previousReferencedDisplaySetStoreKey, presentationData);
700
+ return;
701
+ }
702
+
703
+ // if not found means we have not visited that referencedDisplaySetInstanceUID before
704
+ // so we need to grab the positionPresentationId directly from the store,
705
+ // Todo: this is really hacky, we should have a better way for this
706
+ const positionPresentationId = getPositionPresentationId({
707
+ displaySetInstanceUIDs,
708
+ viewportId,
709
+ });
710
+
711
+ setPositionPresentation(positionPresentationId, presentationData);
712
+ },
713
+ getNearbyToolData({ nearbyToolData, element, canvasCoordinates }) {
714
+ return nearbyToolData ?? cstUtils.getAnnotationNearPoint(element, canvasCoordinates);
715
+ },
716
+ getNearbyAnnotation({ element, canvasCoordinates }) {
717
+ const nearbyToolData = actions.getNearbyToolData({
718
+ nearbyToolData: null,
719
+ element,
720
+ canvasCoordinates,
721
+ });
722
+
723
+ const isAnnotation = toolName => {
724
+ const enabledElement = getEnabledElement(element);
725
+
726
+ if (!enabledElement) {
727
+ return;
728
+ }
729
+
730
+ const { renderingEngineId, viewportId } = enabledElement;
731
+ const toolGroup = ToolGroupManager.getToolGroupForViewport(viewportId, renderingEngineId);
732
+
733
+ const toolInstance = toolGroup.getToolInstance(toolName);
734
+
735
+ return toolInstance?.constructor?.isAnnotation ?? true;
736
+ };
737
+
738
+ return nearbyToolData?.metadata?.toolName && isAnnotation(nearbyToolData.metadata.toolName)
739
+ ? nearbyToolData
740
+ : null;
741
+ },
742
+ /**
743
+ * Common logic for handling measurement label updates through dialog
744
+ * @param uid - measurement uid
745
+ * @returns Promise that resolves when the label is updated
746
+ */
747
+ _handleMeasurementLabelDialog: async uid => {
748
+ const labelConfig = customizationService.getCustomization('measurementLabels');
749
+ const renderContent = customizationService.getCustomization('ui.labellingComponent');
750
+ const measurement = measurementService.getMeasurement(uid);
751
+
752
+ if (!measurement) {
753
+ console.debug('No measurement found for label editing');
754
+ return;
755
+ }
756
+
757
+ if (!labelConfig) {
758
+ const label = await callInputDialog({
759
+ uiDialogService,
760
+ title: i18n.t('Tools:Edit Measurement Label'),
761
+ placeholder: measurement.label || i18n.t('Tools:Enter new label'),
762
+ defaultValue: measurement.label,
763
+ });
764
+
765
+ if (label !== undefined && label !== null) {
766
+ measurementService.update(uid, { ...measurement, label }, true);
767
+ }
768
+ return;
769
+ }
770
+
771
+ const val = await callInputDialogAutoComplete({
772
+ measurement,
773
+ uiDialogService,
774
+ labelConfig,
775
+ renderContent,
776
+ });
777
+
778
+ if (val !== undefined && val !== null) {
779
+ measurementService.update(uid, { ...measurement, label: val }, true);
780
+ }
781
+ },
782
+ /**
783
+ * Show the measurement labelling input dialog and update the label
784
+ * on the measurement with a response if not cancelled.
785
+ */
786
+ setMeasurementLabel: async ({ uid }) => {
787
+ await actions._handleMeasurementLabelDialog(uid);
788
+ },
789
+ renameMeasurement: async ({ uid }) => {
790
+ await actions._handleMeasurementLabelDialog(uid);
791
+ },
792
+ /**
793
+ *
794
+ * @param props - containing the updates to apply
795
+ * @param props.measurementKey - chooses the measurement key to apply the
796
+ * code to. This will typically be finding or site to apply a
797
+ * finding code or a findingSites code.
798
+ * @param props.code - A coding scheme value from DICOM, including:
799
+ * * CodeValue - the language independent code, for example '1234'
800
+ * * CodingSchemeDesignator - the issue of the code value
801
+ * * CodeMeaning - the text value shown to the user
802
+ * * ref - a string reference in the form `<designator>:<codeValue>`
803
+ * * type - defaulting to 'finding'. Will replace other codes of same type
804
+ * * style - a styling object to use
805
+ * * Other fields
806
+ * Note it is a valid option to remove the finding or site values by
807
+ * supplying null for the code.
808
+ * @param props.uid - the measurement UID to find it with
809
+ * @param props.label - the text value for the code. Has NOTHING to do with
810
+ * the measurement label, which can be set with textLabel
811
+ * @param props.textLabel is the measurement label to apply. Set to null to
812
+ * delete.
813
+ *
814
+ * If the measurementKey is `site`, then the code will also be added/replace
815
+ * the 0 element of findingSites. This behaviour is expected to be enhanced
816
+ * in the future with ability to set other site information.
817
+ */
818
+ updateMeasurement: props => {
819
+ const { code, uid, textLabel, label } = props;
820
+ let { style } = props;
821
+ const measurement = measurementService.getMeasurement(uid);
822
+ if (!measurement) {
823
+ console.warn('No measurement found to update', uid);
824
+ return;
825
+ }
826
+ const updatedMeasurement = {
827
+ ...measurement,
828
+ };
829
+ // Call it textLabel as the label value
830
+ // TODO - remove the label setting when direct rendering of findingSites is enabled
831
+ if (textLabel !== undefined) {
832
+ updatedMeasurement.label = textLabel;
833
+ }
834
+ if (code !== undefined) {
835
+ const measurementKey = code.type || 'finding';
836
+
837
+ if (code.ref && !code.CodeValue) {
838
+ const split = code.ref.indexOf(':');
839
+ code.CodeValue = code.ref.substring(split + 1);
840
+ code.CodeMeaning = code.text || label;
841
+ code.CodingSchemeDesignator = code.ref.substring(0, split);
842
+ }
843
+ updatedMeasurement[measurementKey] = code;
844
+ if (measurementKey !== 'finding') {
845
+ if (updatedMeasurement.findingSites) {
846
+ updatedMeasurement.findingSites = updatedMeasurement.findingSites.filter(
847
+ it => it.type !== measurementKey
848
+ );
849
+ updatedMeasurement.findingSites.push(code);
850
+ } else {
851
+ updatedMeasurement.findingSites = [code];
852
+ }
853
+ }
854
+ }
855
+
856
+ style ||= updatedMeasurement.finding?.style;
857
+ style ||= updatedMeasurement.findingSites?.find(site => site?.style)?.style;
858
+
859
+ if (style) {
860
+ // Reset the selected values to preserve appearance on selection
861
+ style.lineDashSelected ||= style.lineDash;
862
+ annotation.config.style.setAnnotationStyles(measurement.uid, style);
863
+
864
+ // this is a bit ugly, but given the underlying behavior, this is how it needs to work.
865
+ switch (measurement.toolName) {
866
+ case toolNames.PlanarFreehandROI: {
867
+ const targetAnnotation = annotation.state.getAnnotation(measurement.uid);
868
+ targetAnnotation.data.isOpenUShapeContour = !!style.isOpenUShapeContour;
869
+ break;
870
+ }
871
+ default:
872
+ break;
873
+ }
874
+ }
875
+ measurementService.update(updatedMeasurement.uid, updatedMeasurement, true);
876
+ },
877
+
878
+ /**
879
+ * Opens a color picker for the measurement and applies the chosen color
880
+ * to the annotation (and its text box) via per-annotation styles.
881
+ */
882
+ changeMeasurementColor: ({ uid }) => {
883
+ const measurement = measurementService.getMeasurement(uid);
884
+ if (!measurement) {
885
+ console.warn('No measurement found to change color', uid);
886
+ return;
887
+ }
888
+
889
+ const currentColor = annotation.config.style.getStyleProperty('color', {
890
+ annotationUID: uid,
891
+ toolName: measurement.toolName,
892
+ });
893
+
894
+ uiDialogService.show({
895
+ content: colorPickerDialog,
896
+ title: i18n.t('Tools:Measurement Color'),
897
+ contentProps: {
898
+ value: _cssColorToRgba(currentColor),
899
+ onSave: newRgbaColor => {
900
+ const { r, g, b, a = 1 } = newRgbaColor;
901
+ const cssColor = `rgba(${r}, ${g}, ${b}, ${a})`;
902
+ // updateMeasurement replaces the annotation styles and sets the contour shape from them
903
+ actions.updateMeasurement({
904
+ uid,
905
+ style: {
906
+ ...annotation.config.style.getAnnotationToolStyles(uid),
907
+ isOpenUShapeContour: annotation.state.getAnnotation(uid)?.data?.isOpenUShapeContour,
908
+ color: cssColor,
909
+ colorHighlighted: cssColor,
910
+ colorSelected: cssColor,
911
+ colorLocked: cssColor,
912
+ textBoxColor: cssColor,
913
+ textBoxColorHighlighted: cssColor,
914
+ textBoxColorSelected: cssColor,
915
+ textBoxColorLocked: cssColor,
916
+ },
917
+ });
918
+ },
919
+ },
920
+ });
921
+ },
922
+
923
+ /**
924
+ * Records the instance that the given measurements were just stored as, so
925
+ * that storing them again offers to extend that series rather than creating
926
+ * another one.
927
+ *
928
+ * The predecessor is kept on the annotation as well as on the measurement,
929
+ * because the measurement is re-derived from the annotation whenever the
930
+ * annotation is edited.
931
+ *
932
+ * @param props.measurements - the measurements that were stored
933
+ * @param props.predecessorImageId - imageId of the instance they were stored as
934
+ * @returns the number of measurements the predecessor was recorded on
935
+ */
936
+ recordMeasurementsPredecessor: ({ measurements = [], predecessorImageId }) => {
937
+ if (!predecessorImageId) {
938
+ return 0;
939
+ }
940
+
941
+ let recorded = 0;
942
+
943
+ for (const { uid } of measurements) {
944
+ const measurement = measurementService.getMeasurement(uid);
945
+
946
+ if (!measurement) {
947
+ continue;
948
+ }
949
+
950
+ measurement.predecessorImageId = predecessorImageId;
951
+
952
+ const targetAnnotation = annotation.state.getAnnotation(uid);
953
+ if (targetAnnotation) {
954
+ targetAnnotation.predecessorImageId = predecessorImageId;
955
+ }
956
+
957
+ recorded++;
958
+ }
959
+
960
+ return recorded;
961
+ },
962
+
963
+ /**
964
+ * Jumps to the specified (by uid) measurement in the active viewport.
965
+ * Also marks any provided display measurements isActive value
966
+ */
967
+ jumpToMeasurement: ({ uid, displayMeasurements = [] }) => {
968
+ if (!uid) {
969
+ return;
970
+ }
971
+ measurementService.jumpToMeasurement(viewportGridService.getActiveViewportId(), uid);
972
+ for (const measurement of displayMeasurements) {
973
+ measurement.isActive = measurement.uid === uid;
974
+ }
975
+ },
976
+
977
+ removeMeasurement: ({ uid }) => {
978
+ if (Array.isArray(uid)) {
979
+ measurementService.removeMany(uid);
980
+ } else {
981
+ measurementService.remove(uid);
982
+ }
983
+ },
984
+
985
+ toggleLockMeasurement: ({ uid }) => {
986
+ measurementService.toggleLockMeasurement(uid);
987
+ },
988
+
989
+ toggleVisibilityMeasurement: ({ uid, items, visibility }) => {
990
+ if (visibility === undefined && items?.length) {
991
+ visibility = !items[0].isVisible;
992
+ }
993
+ if (Array.isArray(uid)) {
994
+ measurementService.toggleVisibilityMeasurementMany(uid, visibility);
995
+ } else {
996
+ measurementService.toggleVisibilityMeasurement(uid, visibility);
997
+ }
998
+ },
999
+
1000
+ /**
1001
+ * Download the CSV report for the measurements.
1002
+ */
1003
+ downloadCSVMeasurementsReport: ({ measurementFilter }) => {
1004
+ utils.downloadCSVReport(measurementService.getMeasurements(measurementFilter));
1005
+ },
1006
+
1007
+ downloadCSVSegmentationReport: ({ segmentationId }) => {
1008
+ const segmentation = segmentationService.getSegmentation(segmentationId);
1009
+
1010
+ const { representationData } = segmentation;
1011
+ const { Labelmap } = representationData;
1012
+ const { referencedImageIds } = Labelmap;
1013
+
1014
+ const firstImageId = referencedImageIds[0];
1015
+
1016
+ // find displaySet for firstImageId
1017
+ const displaySet = displaySetService
1018
+ .getActiveDisplaySets()
1019
+ .find(ds => ds.imageIds?.some(i => i === firstImageId));
1020
+
1021
+ const {
1022
+ SeriesNumber,
1023
+ SeriesInstanceUID,
1024
+ StudyInstanceUID,
1025
+ SeriesDate,
1026
+ SeriesTime,
1027
+ SeriesDescription,
1028
+ } = displaySet;
1029
+
1030
+ const additionalInfo = {
1031
+ reference: {
1032
+ SeriesNumber,
1033
+ SeriesInstanceUID,
1034
+ StudyInstanceUID,
1035
+ SeriesDate,
1036
+ SeriesTime,
1037
+ SeriesDescription,
1038
+ },
1039
+ };
1040
+
1041
+ generateSegmentationCSVReport(segmentation, additionalInfo);
1042
+ },
1043
+
1044
+ // Retrieve value commands
1045
+ getActiveViewportEnabledElement: _getActiveViewportEnabledElement,
1046
+
1047
+ setViewportActive: ({ viewportId }) => {
1048
+ const viewportInfo = cornerstoneViewportService.getViewportInfo(viewportId);
1049
+ if (!viewportInfo) {
1050
+ console.warn('No viewport found for viewportId:', viewportId);
1051
+ return;
1052
+ }
1053
+
1054
+ viewportGridService.setActiveViewportId(viewportId);
1055
+ },
1056
+ arrowTextCallback: async ({ callback, data }) => {
1057
+ const labelConfig = customizationService.getCustomization('measurementLabels');
1058
+ const renderContent = customizationService.getCustomization('ui.labellingComponent');
1059
+ // ArrowAnnotateTool removes a just-drawn annotation when its text
1060
+ // callback returns a falsy label. Saving an empty label should keep
1061
+ // the arrow (same as Cancel), so skip the callback for new
1062
+ // annotations (no `data` means the annotation is new, not edited).
1063
+ const isNewAnnotation = !data;
1064
+
1065
+ if (!labelConfig) {
1066
+ const label = await callInputDialog({
1067
+ uiDialogService,
1068
+ title: i18n.t('Tools:Edit Arrow Text'),
1069
+ placeholder: data?.data?.label || i18n.t('Tools:Enter new text'),
1070
+ defaultValue: data?.data?.label || '',
1071
+ });
1072
+
1073
+ if (isNewAnnotation && !label) {
1074
+ return;
1075
+ }
1076
+ callback?.(label);
1077
+ return;
1078
+ }
1079
+
1080
+ const value = await callInputDialogAutoComplete({
1081
+ uiDialogService,
1082
+ labelConfig,
1083
+ renderContent,
1084
+ });
1085
+ if (isNewAnnotation && !value) {
1086
+ return;
1087
+ }
1088
+ callback?.(value);
1089
+ },
1090
+
1091
+ toggleCine: () => {
1092
+ const { viewports } = viewportGridService.getState();
1093
+ const { isCineEnabled } = cineService.getState();
1094
+ cineService.setIsCineEnabled(!isCineEnabled);
1095
+ viewports.forEach((_, index) => cineService.setCine({ id: index, isPlaying: false }));
1096
+ },
1097
+
1098
+ setViewportWindowLevel({
1099
+ viewportId,
1100
+ windowWidth,
1101
+ windowCenter,
1102
+ displaySetInstanceUID,
1103
+ }: {
1104
+ viewportId: string;
1105
+ windowWidth: number;
1106
+ windowCenter: number;
1107
+ displaySetInstanceUID?: string;
1108
+ }) {
1109
+ // convert to numbers
1110
+ const windowWidthNum = Number(windowWidth);
1111
+ const windowCenterNum = Number(windowCenter);
1112
+
1113
+ const renderingEngine = cornerstoneViewportService.getRenderingEngine();
1114
+ const viewport = renderingEngine.getViewport(viewportId);
1115
+
1116
+ // Stale/invalid viewport ids resolve to undefined; bail out before the VOI
1117
+ // apply + render below would throw.
1118
+ if (!viewport) {
1119
+ return;
1120
+ }
1121
+
1122
+ // Legacy volume viewports target a specific volume; the command owns that
1123
+ // resolution (it needs the service). The operations backend applies the VOI
1124
+ // (legacy setProperties vs native setDisplaySetPresentation on the active binding).
1125
+ const volumeId = isVolumeViewportType(viewport)
1126
+ ? actions.getVolumeIdForDisplaySet({ viewportId, displaySetInstanceUID })
1127
+ : undefined;
1128
+
1129
+ ops.setWindowLevel(viewport, {
1130
+ windowWidth: windowWidthNum,
1131
+ windowCenter: windowCenterNum,
1132
+ volumeId,
1133
+ displaySetInstanceUID,
1134
+ });
1135
+ viewport.render();
1136
+ },
1137
+ toggleViewportColorbar: ({ viewportId, displaySetInstanceUIDs, options = {} }) => {
1138
+ const hasColorbar = colorbarService.hasColorbar(viewportId);
1139
+ if (hasColorbar) {
1140
+ colorbarService.removeColorbar(viewportId);
1141
+ return;
1142
+ }
1143
+ colorbarService.addColorbar(viewportId, displaySetInstanceUIDs, options);
1144
+ },
1145
+ setWindowLevel(props) {
1146
+ const { toolGroupId } = props;
1147
+ const { viewportId } = _getActiveViewportEnabledElement();
1148
+ const viewportToolGroupId = toolGroupService.getToolGroupForViewport(viewportId);
1149
+
1150
+ if (toolGroupId && toolGroupId !== viewportToolGroupId) {
1151
+ return;
1152
+ }
1153
+
1154
+ actions.setViewportWindowLevel({ ...props, viewportId });
1155
+ },
1156
+ setWindowLevelPreset: ({ presetName, presetIndex }) => {
1157
+ const windowLevelPresets = customizationService.getCustomization(
1158
+ 'cornerstone.windowLevelPresets'
1159
+ );
1160
+
1161
+ const activeViewport = viewportGridService.getActiveViewportId();
1162
+ const viewport = cornerstoneViewportService.getCornerstoneViewport(activeViewport);
1163
+ const metadata = viewport.getImageData().metadata;
1164
+
1165
+ const modality = metadata.Modality;
1166
+
1167
+ if (!modality) {
1168
+ return;
1169
+ }
1170
+
1171
+ const windowLevelPresetForModality = windowLevelPresets[modality];
1172
+
1173
+ if (!windowLevelPresetForModality) {
1174
+ return;
1175
+ }
1176
+
1177
+ const windowLevelPreset = findWindowLevelPreset(
1178
+ windowLevelPresetForModality,
1179
+ presetName,
1180
+ presetIndex
1181
+ );
1182
+
1183
+ // A customization can have fewer presets than there are W/L hotkeys.
1184
+ if (!windowLevelPreset) {
1185
+ return;
1186
+ }
1187
+
1188
+ actions.setViewportWindowLevel({
1189
+ viewportId: activeViewport,
1190
+ windowWidth: windowLevelPreset.window,
1191
+ windowCenter: windowLevelPreset.level,
1192
+ });
1193
+ },
1194
+ getVolumeIdForDisplaySet: ({ viewportId, displaySetInstanceUID }) => {
1195
+ const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
1196
+ // `instanceof BaseVolumeViewport` is false for GenericViewport compat adapters,
1197
+ // so use the capability guard instead (cornerstone 5.x generic-viewport guide).
1198
+ // A stack-mode adapter passes the guard but getAllVolumeIds() returns [], so the
1199
+ // result is the same null as before on stacks.
1200
+ if (csUtils.viewportSupportsVolumeId(viewport)) {
1201
+ const volumeIds = (viewport as CoreTypes.IVolumeViewport).getAllVolumeIds();
1202
+ const volumeId = volumeIds.find(id => id.includes(displaySetInstanceUID));
1203
+ return volumeId;
1204
+ }
1205
+ return null;
1206
+ },
1207
+ setToolEnabled: ({ toolName, toggle, toolGroupId }) => {
1208
+ const { viewports } = viewportGridService.getState();
1209
+
1210
+ if (!viewports.size) {
1211
+ return;
1212
+ }
1213
+
1214
+ const toolGroup = toolGroupService.getToolGroup(toolGroupId ?? null);
1215
+
1216
+ if (!toolGroup || !toolGroup.hasTool(toolName)) {
1217
+ return;
1218
+ }
1219
+
1220
+ const toolIsEnabled = toolGroup.getToolOptions(toolName).mode === Enums.ToolModes.Enabled;
1221
+
1222
+ // Toggle the tool's state only if the toggle is true
1223
+ if (toggle) {
1224
+ toolIsEnabled ? toolGroup.setToolDisabled(toolName) : toolGroup.setToolEnabled(toolName);
1225
+ } else {
1226
+ toolGroup.setToolEnabled(toolName);
1227
+ }
1228
+
1229
+ const renderingEngine = cornerstoneViewportService.getRenderingEngine();
1230
+ renderingEngine.render();
1231
+ },
1232
+ /** Looks at a volume3d viewport from an anatomical direction (S, I, R, L, A, P). */
1233
+ setViewport3DViewDirection: ({
1234
+ viewportId,
1235
+ direction,
1236
+ }: {
1237
+ viewportId: string;
1238
+ direction: ViewDirection;
1239
+ }) => {
1240
+ setVolume3DViewDirection(
1241
+ cornerstoneViewportService.getCornerstoneViewport(viewportId),
1242
+ direction
1243
+ );
1244
+ },
1245
+ /** Orbits a volume3d viewport camera by `angle` degrees about the patient superior axis. */
1246
+ rotateViewport3DBy: ({ viewportId, angle }: { viewportId: string; angle: number }) => {
1247
+ rotateVolume3D(cornerstoneViewportService.getCornerstoneViewport(viewportId), angle);
1248
+ },
1249
+ /** Spins a volume3d viewport continuously; `speed` 0 stops it, a negative value reverses it. */
1250
+ setViewport3DSpin: ({ viewportId, speed }: { viewportId: string; speed: number }) => {
1251
+ setVolume3DSpin(viewportId, speed, id =>
1252
+ cornerstoneViewportService.getCornerstoneViewport(id)
1253
+ );
1254
+ },
1255
+ toggleEnabledDisabledToolbar({ value, itemId, toolGroupId }) {
1256
+ const toolName = itemId || value;
1257
+ toolGroupId = toolGroupId ?? _getActiveViewportToolGroupId();
1258
+
1259
+ const toolGroup = toolGroupService.getToolGroup(toolGroupId);
1260
+ if (!toolGroup || !toolGroup.hasTool(toolName)) {
1261
+ return;
1262
+ }
1263
+
1264
+ const toolIsEnabled = toolGroup.getToolOptions(toolName).mode === Enums.ToolModes.Enabled;
1265
+
1266
+ toolIsEnabled ? toolGroup.setToolDisabled(toolName) : toolGroup.setToolEnabled(toolName);
1267
+ },
1268
+ toggleActiveDisabledToolbar({ value, itemId, toolGroupId, toolGroupIds }) {
1269
+ const toolName = itemId || value;
1270
+ const resolvedToolGroupIds = toolGroupIds?.length
1271
+ ? toolGroupIds
1272
+ : [toolGroupId ?? _getActiveViewportToolGroupId()];
1273
+
1274
+ resolvedToolGroupIds.forEach(toolGroupId => {
1275
+ const toolGroup = toolGroupService.getToolGroup(toolGroupId);
1276
+ if (!toolGroup || !toolGroup.hasTool(toolName)) {
1277
+ return;
1278
+ }
1279
+
1280
+ const toolIsActive = [
1281
+ Enums.ToolModes.Active,
1282
+ Enums.ToolModes.Enabled,
1283
+ Enums.ToolModes.Passive,
1284
+ ].includes(toolGroup.getToolOptions(toolName).mode);
1285
+
1286
+ if (toolIsActive) {
1287
+ toolGroup.setToolDisabled(toolName);
1288
+
1289
+ const bindings = toolGroupService.getToolBindings(toolGroupId, toolName);
1290
+
1291
+ if (_usesPrimaryActivation(bindings)) {
1292
+ // we should set the previously active tool to active after we set the
1293
+ // current tool disabled
1294
+ const prevToolName = toolGroup.getPrevActivePrimaryToolName();
1295
+ if (prevToolName !== toolName) {
1296
+ actions.setToolActive({ toolName: prevToolName, toolGroupId });
1297
+ }
1298
+ }
1299
+
1300
+ return;
1301
+ }
1302
+
1303
+ const bindings = toolGroupService.getToolBindings(toolGroupId, toolName);
1304
+ if (_usesPrimaryActivation(bindings)) {
1305
+ actions.setToolActive({ toolName, toolGroupId, bindings });
1306
+ } else {
1307
+ toolGroup.setToolActive(toolName, { bindings });
1308
+ }
1309
+ });
1310
+ },
1311
+ setToolActiveToolbar: ({ value, itemId, toolName, toolGroupIds = [], bindings }) => {
1312
+ // Sometimes it is passed as value (tools with options), sometimes as itemId (toolbar buttons)
1313
+ toolName = toolName || itemId || value;
1314
+
1315
+ toolGroupIds = toolGroupIds.length ? toolGroupIds : toolGroupService.getToolGroupIds();
1316
+
1317
+ toolGroupIds.forEach(toolGroupId => {
1318
+ actions.setToolActive({ toolName, toolGroupId, bindings });
1319
+ });
1320
+ },
1321
+ setToolActive: ({
1322
+ toolName,
1323
+ toolGroupId = null,
1324
+ bindings = [{ mouseButton: Enums.MouseBindings.Primary }],
1325
+ }) => {
1326
+ const { viewports } = viewportGridService.getState();
1327
+
1328
+ if (!viewports.size) {
1329
+ return;
1330
+ }
1331
+
1332
+ const toolGroup = toolGroupService.getToolGroup(toolGroupId);
1333
+
1334
+ if (!toolGroup) {
1335
+ return;
1336
+ }
1337
+
1338
+ if (!toolGroup?.hasTool(toolName)) {
1339
+ return;
1340
+ }
1341
+
1342
+ const activeToolName = toolGroup.getActivePrimaryMouseButtonTool();
1343
+
1344
+ if (activeToolName) {
1345
+ const activeToolOptions = toolGroup.getToolConfiguration(activeToolName);
1346
+ activeToolOptions?.disableOnPassive
1347
+ ? toolGroup.setToolDisabled(activeToolName)
1348
+ : toolGroup.setToolPassive(activeToolName);
1349
+ }
1350
+
1351
+ // Set the new toolName to be active
1352
+ toolGroup.setToolActive(toolName, {
1353
+ bindings,
1354
+ });
1355
+ },
1356
+ // capture viewport
1357
+ showDownloadViewportModal: () => {
1358
+ const { activeViewportId } = viewportGridService.getState();
1359
+
1360
+ if (!cornerstoneViewportService.getCornerstoneViewport(activeViewportId)) {
1361
+ // Cannot download a non-cornerstone viewport (image).
1362
+ uiNotificationService.show({
1363
+ title: i18n.t('Tools:Download Image'),
1364
+ message: i18n.t('Tools:Image cannot be downloaded'),
1365
+ type: 'error',
1366
+ });
1367
+ return;
1368
+ }
1369
+
1370
+ const { uiModalService } = servicesManager.services;
1371
+
1372
+ if (uiModalService) {
1373
+ uiModalService.show({
1374
+ content: CornerstoneViewportDownloadForm,
1375
+ title: i18n.t('Tools:Download High Quality Image'),
1376
+ contentProps: {
1377
+ activeViewportId,
1378
+ cornerstoneViewportService,
1379
+ },
1380
+ containerClassName: 'max-w-4xl p-4',
1381
+ });
1382
+ }
1383
+ },
1384
+ /**
1385
+ * Rotates the viewport by `rotation` relative to its current rotation.
1386
+ */
1387
+ rotateViewportBy: ({ rotation, viewportId }: { rotation: number; viewportId?: string }) => {
1388
+ actions._rotateViewport({ rotation, viewportId, rotationMode: 'apply' });
1389
+ },
1390
+ /**
1391
+ * Sets the viewport rotation to an absolute value `rotation`.
1392
+ */
1393
+ setViewportRotation: ({ rotation, viewportId }: { rotation: number; viewportId?: string }) => {
1394
+ actions._rotateViewport({ rotation, viewportId, rotationMode: 'set' });
1395
+ },
1396
+ flipViewportHorizontal: ({
1397
+ viewportId,
1398
+ newValue = 'toggle',
1399
+ }: {
1400
+ viewportId?: string;
1401
+ newValue?: 'toggle' | boolean;
1402
+ }) => {
1403
+ const viewport = _resolveViewport(viewportId);
1404
+ if (!viewport) {
1405
+ return;
1406
+ }
1407
+ ops.flipHorizontal(viewport, newValue);
1408
+ viewport.render();
1409
+ },
1410
+ flipViewportVertical: ({
1411
+ viewportId,
1412
+ newValue = 'toggle',
1413
+ }: {
1414
+ viewportId?: string;
1415
+ newValue?: 'toggle' | boolean;
1416
+ }) => {
1417
+ const viewport = _resolveViewport(viewportId);
1418
+ if (!viewport) {
1419
+ return;
1420
+ }
1421
+ ops.flipVertical(viewport, newValue);
1422
+ viewport.render();
1423
+ },
1424
+ invertViewport: ({ element }) => {
1425
+ const viewport = element === undefined ? _resolveViewport() : element.viewport;
1426
+ if (!viewport) {
1427
+ return;
1428
+ }
1429
+ ops.invert(viewport);
1430
+ viewport.render();
1431
+ },
1432
+ resetViewport: () => {
1433
+ const viewport = _resolveViewport();
1434
+ if (!viewport) {
1435
+ return;
1436
+ }
1437
+ ops.reset(viewport);
1438
+ viewport.render();
1439
+ },
1440
+ scaleViewport: ({ direction }) => {
1441
+ const viewport = _resolveViewport();
1442
+ if (!viewport) {
1443
+ return;
1444
+ }
1445
+ ops.scaleBy(viewport, direction);
1446
+ viewport.render();
1447
+ },
1448
+
1449
+ /** Jumps the active viewport or the specified one to the given slice index */
1450
+ jumpToImage: ({ imageIndex, viewport: gridViewport }): void => {
1451
+ // Get current active viewport (return if none active)
1452
+ let viewport;
1453
+ if (!gridViewport) {
1454
+ const enabledElement = _getActiveViewportEnabledElement();
1455
+ if (!enabledElement) {
1456
+ return;
1457
+ }
1458
+ viewport = enabledElement.viewport;
1459
+ } else {
1460
+ viewport = cornerstoneViewportService.getCornerstoneViewport(gridViewport.id);
1461
+ }
1462
+
1463
+ // Get number of slices
1464
+ // -> Copied from cornerstone3D jumpToSlice\_getImageSliceData()
1465
+ let numberOfSlices = 0;
1466
+
1467
+ if (isStackViewportType(viewport)) {
1468
+ numberOfSlices = viewport.getImageIds().length;
1469
+ } else if (isOrthographicViewportType(viewport)) {
1470
+ numberOfSlices = csUtils.getImageSliceDataForVolumeViewport(viewport).numberOfSlices;
1471
+ } else {
1472
+ throw new Error('Unsupported viewport type');
1473
+ }
1474
+
1475
+ const jumpIndex = imageIndex < 0 ? numberOfSlices + imageIndex : imageIndex;
1476
+ if (jumpIndex >= numberOfSlices || jumpIndex < 0) {
1477
+ throw new Error(`Can't jump to ${imageIndex}`);
1478
+ }
1479
+
1480
+ // Set slice to last slice
1481
+ const options = { imageIndex: jumpIndex };
1482
+ csUtils.jumpToSlice(viewport.element, options);
1483
+ },
1484
+ scroll: (options: ToolTypes.ScrollOptions) => {
1485
+ const enabledElement = _getActiveViewportEnabledElement();
1486
+ // Allow either or direction for consistency in scroll implementation
1487
+ options.delta ??= options.direction || 1;
1488
+ options.direction ??= options.delta;
1489
+
1490
+ if (!enabledElement) {
1491
+ return;
1492
+ }
1493
+
1494
+ const { viewport } = enabledElement;
1495
+
1496
+ csUtils.scroll(viewport, options);
1497
+ },
1498
+ setViewportColormap: ({
1499
+ viewportId,
1500
+ displaySetInstanceUID,
1501
+ colormap,
1502
+ opacity = 1,
1503
+ immediate = false,
1504
+ }) => {
1505
+ const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
1506
+
1507
+ let hpOpacity;
1508
+ // Retrieve active protocol's viewport match details
1509
+ const { viewportMatchDetails } = hangingProtocolService.getActiveProtocol();
1510
+ // Get display set options for the specified viewport ID
1511
+ const displaySetsInfo = viewportMatchDetails.get(viewportId)?.displaySetsInfo;
1512
+
1513
+ if (displaySetsInfo) {
1514
+ // Find the display set that matches the given UID
1515
+ const matchingDisplaySet = displaySetsInfo.find(
1516
+ displaySet => displaySet.displaySetInstanceUID === displaySetInstanceUID
1517
+ );
1518
+ // If a matching display set is found, update the opacity with its value
1519
+ hpOpacity = matchingDisplaySet?.displaySetOptions?.options?.colormap?.opacity;
1520
+ }
1521
+
1522
+ // HP takes priority over the default opacity
1523
+ colormap = { ...colormap, opacity: hpOpacity || opacity };
1524
+
1525
+ // The legacy orthographic branch resolves the volumeId from the display set;
1526
+ // fall back to the viewport's first display set (needs viewportGridService, so
1527
+ // it is resolved here in the command rather than in the operations backend).
1528
+ if (isOrthographicViewportType(viewport) && !displaySetInstanceUID) {
1529
+ const { viewports } = viewportGridService.getState();
1530
+ displaySetInstanceUID = viewports.get(viewportId)?.displaySetInstanceUIDs[0];
1531
+ }
1532
+
1533
+ ops.setColormap(viewport, { colormap, displaySetInstanceUID });
1534
+
1535
+ if (immediate) {
1536
+ viewport.render();
1537
+ }
1538
+ },
1539
+ changeActiveViewport: ({ direction = 1 }) => {
1540
+ const { activeViewportId, viewports } = viewportGridService.getState();
1541
+ const viewportIds = Array.from(viewports.keys());
1542
+ const currentIndex = viewportIds.indexOf(activeViewportId);
1543
+ const nextViewportIndex =
1544
+ (currentIndex + direction + viewportIds.length) % viewportIds.length;
1545
+ viewportGridService.setActiveViewportId(viewportIds[nextViewportIndex] as string);
1546
+ },
1547
+ /**
1548
+ * If the syncId is given and a synchronizer with that ID already exists, it will
1549
+ * toggle it on/off for the provided viewports. If not, it will attempt to create
1550
+ * a new synchronizer using the given syncId and type for the specified viewports.
1551
+ * If no viewports are provided, you may notice some default behavior.
1552
+ * - 'voi' type, we will aim to synchronize all viewports with the same modality
1553
+ * -'imageSlice' type, we will aim to synchronize all viewports with the same orientation.
1554
+ *
1555
+ * @param options
1556
+ * @param options.viewports - The viewports to synchronize
1557
+ * @param options.syncId - The synchronization group ID
1558
+ * @param options.type - The type of synchronization to perform
1559
+ */
1560
+ toggleSynchronizer: ({ type, viewports, syncId }) => {
1561
+ const synchronizer = syncGroupService.getSynchronizer(syncId);
1562
+
1563
+ if (synchronizer) {
1564
+ synchronizer.isDisabled() ? synchronizer.setEnabled(true) : synchronizer.setEnabled(false);
1565
+ return;
1566
+ }
1567
+
1568
+ const fn = toggleSyncFunctions[type];
1569
+
1570
+ if (fn) {
1571
+ fn({
1572
+ servicesManager,
1573
+ viewports,
1574
+ syncId,
1575
+ });
1576
+ }
1577
+ },
1578
+ setViewportForToolConfiguration: ({ viewportId, toolName }) => {
1579
+ if (!viewportId) {
1580
+ const { activeViewportId } = viewportGridService.getState();
1581
+ viewportId = activeViewportId ?? 'default';
1582
+ }
1583
+
1584
+ const toolGroup = toolGroupService.getToolGroupForViewport(viewportId);
1585
+
1586
+ if (!toolGroup?.hasTool(toolName)) {
1587
+ return;
1588
+ }
1589
+
1590
+ const prevConfig = toolGroup?.getToolConfiguration(toolName);
1591
+ toolGroup?.setToolConfiguration(
1592
+ toolName,
1593
+ {
1594
+ ...prevConfig,
1595
+ sourceViewportId: viewportId,
1596
+ },
1597
+ true // overwrite
1598
+ );
1599
+
1600
+ const renderingEngine = cornerstoneViewportService.getRenderingEngine();
1601
+ renderingEngine.render();
1602
+ },
1603
+ storePresentation: ({ viewportId }) => {
1604
+ cornerstoneViewportService.storePresentation({ viewportId });
1605
+ },
1606
+ updateVolumeData: ({ volume }) => {
1607
+ // Marks the imageData and every texture set (full and reduced) of the computed volume dirty.
1608
+ volume.modified();
1609
+ },
1610
+
1611
+ attachProtocolViewportDataListener: ({ protocol, stageIndex }) => {
1612
+ const EVENT = cornerstoneViewportService.EVENTS.VIEWPORT_DATA_CHANGED;
1613
+ const command = protocol.callbacks.onViewportDataInitialized;
1614
+ const numPanes = protocol.stages?.[stageIndex]?.viewports.length ?? 1;
1615
+ let numPanesWithData = 0;
1616
+ const { unsubscribe } = cornerstoneViewportService.subscribe(EVENT, evt => {
1617
+ numPanesWithData++;
1618
+
1619
+ if (numPanesWithData === numPanes) {
1620
+ commandsManager.run(...command);
1621
+
1622
+ // Unsubscribe from the event
1623
+ unsubscribe(EVENT);
1624
+ }
1625
+ });
1626
+ },
1627
+
1628
+ setViewportPreset: ({ viewportId, preset }) => {
1629
+ const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
1630
+ if (!viewport) {
1631
+ return;
1632
+ }
1633
+ ops.setPreset(viewport, preset);
1634
+ viewport.render();
1635
+ },
1636
+
1637
+ /**
1638
+ * Sets the volume quality for a given viewport.
1639
+ * @param {string} viewportId - The ID of the viewport to set the volume quality.
1640
+ * @param {number} volumeQuality - The desired quality level of the volume rendering.
1641
+ */
1642
+
1643
+ setVolumeRenderingQulaity: ({ viewportId, volumeQuality }) => {
1644
+ const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
1645
+ if (!viewport) {
1646
+ return;
1647
+ }
1648
+ ops.setVolumeRenderingQuality(viewport, volumeQuality);
1649
+ viewport.render();
1650
+ },
1651
+
1652
+ /**
1653
+ * Shifts opacity points for a given viewport id.
1654
+ * @param {string} viewportId - The ID of the viewport to set the mapping range.
1655
+ * @param {number} shift - The shift value to shift the points by.
1656
+ */
1657
+ shiftVolumeOpacityPoints: ({ viewportId, shift }) => {
1658
+ const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
1659
+ if (!viewport) {
1660
+ return;
1661
+ }
1662
+ ops.shiftVolumeOpacityPoints(viewport, shift);
1663
+ viewport.render();
1664
+ },
1665
+
1666
+ /**
1667
+ * Sets the volume lighting settings for a given viewport.
1668
+ * @param {string} viewportId - The ID of the viewport to set the lighting settings.
1669
+ * @param {Object} options - The lighting settings to be set.
1670
+ * @param {boolean} options.shade - The shade setting for the lighting.
1671
+ * @param {number} options.ambient - The ambient setting for the lighting.
1672
+ * @param {number} options.diffuse - The diffuse setting for the lighting.
1673
+ * @param {number} options.specular - The specular setting for the lighting.
1674
+ **/
1675
+
1676
+ setVolumeLighting: ({ viewportId, options }) => {
1677
+ const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
1678
+ if (!viewport) {
1679
+ return;
1680
+ }
1681
+ ops.setVolumeLighting(viewport, options);
1682
+ viewport.render();
1683
+ },
1684
+ resetCrosshairs: ({ viewportId }) => {
1685
+ const crosshairInstances = [];
1686
+
1687
+ const getCrosshairInstances = toolGroupId => {
1688
+ const toolGroup = toolGroupService.getToolGroup(toolGroupId);
1689
+ // Only fetch the instance when Crosshairs is registered in this tool
1690
+ // group. getToolInstance logs a warning for an unregistered tool, and a
1691
+ // viewport's default tool group does not always include Crosshairs (e.g.
1692
+ // next viewports), which made Reset Viewport log a spurious warning.
1693
+ if (toolGroup?.hasTool('Crosshairs')) {
1694
+ crosshairInstances.push(toolGroup.getToolInstance('Crosshairs'));
1695
+ }
1696
+ };
1697
+
1698
+ if (!viewportId) {
1699
+ const toolGroupIds = toolGroupService.getToolGroupIds();
1700
+ toolGroupIds.forEach(getCrosshairInstances);
1701
+ } else {
1702
+ const toolGroup = toolGroupService.getToolGroupForViewport(viewportId);
1703
+ if (toolGroup) {
1704
+ getCrosshairInstances(toolGroup.id);
1705
+ }
1706
+ }
1707
+
1708
+ crosshairInstances.forEach(ins => {
1709
+ ins?.computeToolCenter();
1710
+ });
1711
+ },
1712
+ /**
1713
+ * Creates a labelmap for the active viewport
1714
+ *
1715
+ * The created labelmap will be registered as a display set and also added
1716
+ * as a segmentation representation to the viewport.
1717
+ */
1718
+ createLabelmapForViewport: async ({ viewportId, options = {} }) => {
1719
+ return createSegmentationForViewport(servicesManager, {
1720
+ viewportId,
1721
+ options,
1722
+ segmentationType: SegmentationRepresentations.Labelmap,
1723
+ });
1724
+ },
1725
+ /**
1726
+ * Creates a contour for the active viewport
1727
+ *
1728
+ * The created contour will be registered as a display set and also added
1729
+ * as a segmentation representation to the viewport.
1730
+ */
1731
+ createContourForViewport: async ({ viewportId, options = {} }) => {
1732
+ return createSegmentationForViewport(servicesManager, {
1733
+ viewportId,
1734
+ options,
1735
+ segmentationType: SegmentationRepresentations.Contour,
1736
+ });
1737
+ },
1738
+
1739
+ /**
1740
+ * Sets the active segmentation for a viewport
1741
+ * @param props.segmentationId - The ID of the segmentation to set as active
1742
+ */
1743
+ setActiveSegmentation: ({ segmentationId }) => {
1744
+ const { viewportGridService, segmentationService } = servicesManager.services;
1745
+ segmentationService.setActiveSegmentation(
1746
+ viewportGridService.getActiveViewportId(),
1747
+ segmentationId
1748
+ );
1749
+ },
1750
+
1751
+ /**
1752
+ * Adds a new segment to a segmentation
1753
+ * @param props.segmentationId - The ID of the segmentation to add the segment to
1754
+ */
1755
+ addSegmentCommand: ({ segmentationId, config }) => {
1756
+ const { segmentationService } = servicesManager.services;
1757
+ segmentationService.addSegment(segmentationId, config);
1758
+ },
1759
+
1760
+ /**
1761
+ * Sets the active segment and jumps to its center
1762
+ * @param props.segmentationId - The ID of the segmentation
1763
+ * @param props.segmentIndex - The index of the segment to activate
1764
+ */
1765
+ setActiveSegmentAndCenterCommand: ({ segmentationId, segmentIndex }) => {
1766
+ const { segmentationService, viewportGridService } = servicesManager.services;
1767
+ // set both active segmentation and active segment
1768
+ segmentationService.setActiveSegmentation(
1769
+ viewportGridService.getActiveViewportId(),
1770
+ segmentationId
1771
+ );
1772
+ segmentationService.setActiveSegment(segmentationId, segmentIndex);
1773
+
1774
+ const { highlightAlpha, highlightSegment, animationLength, animationFunctionType } =
1775
+ (customizationService.getCustomization(
1776
+ 'panelSegmentation.jumpToSegmentHighlightAnimationConfig'
1777
+ ) as Object as {
1778
+ highlightAlpha?: number;
1779
+ highlightSegment?: boolean;
1780
+ animationLength?: number;
1781
+ animationFunctionType?: EasingFunctionEnum;
1782
+ }) ?? {};
1783
+
1784
+ const validAnimationFunctionType = Object.values(EasingFunctionEnum).includes(
1785
+ animationFunctionType
1786
+ )
1787
+ ? animationFunctionType
1788
+ : undefined;
1789
+
1790
+ segmentationService.jumpToSegmentNext(
1791
+ segmentationId,
1792
+ segmentIndex,
1793
+ undefined,
1794
+ highlightAlpha,
1795
+ highlightSegment,
1796
+ animationLength,
1797
+ undefined,
1798
+ validAnimationFunctionType
1799
+ );
1800
+ },
1801
+
1802
+ /**
1803
+ * Toggles the visibility of a segment
1804
+ * @param props.segmentationId - The ID of the segmentation
1805
+ * @param props.segmentIndex - The index of the segment
1806
+ * @param props.type - The type of visibility to toggle
1807
+ */
1808
+ toggleSegmentVisibilityCommand: ({ segmentationId, segmentIndex, type }) => {
1809
+ const { segmentationService, viewportGridService } = servicesManager.services;
1810
+ segmentationService.toggleSegmentVisibility(
1811
+ viewportGridService.getActiveViewportId(),
1812
+ segmentationId,
1813
+ segmentIndex,
1814
+ type
1815
+ );
1816
+ },
1817
+
1818
+ /**
1819
+ * Toggles the lock state of a segment
1820
+ * @param props.segmentationId - The ID of the segmentation
1821
+ * @param props.segmentIndex - The index of the segment
1822
+ */
1823
+ toggleSegmentLockCommand: ({ segmentationId, segmentIndex }) => {
1824
+ const { segmentationService } = servicesManager.services;
1825
+ segmentationService.toggleSegmentLocked(segmentationId, segmentIndex);
1826
+ },
1827
+
1828
+ /**
1829
+ * Toggles the visibility of a segmentation representation
1830
+ * @param props.segmentationId - The ID of the segmentation
1831
+ * @param props.type - The type of representation
1832
+ */
1833
+ toggleSegmentationVisibilityCommand: ({ segmentationId, type }) => {
1834
+ const { segmentationService, viewportGridService } = servicesManager.services;
1835
+ segmentationService.toggleSegmentationRepresentationVisibility(
1836
+ viewportGridService.getActiveViewportId(),
1837
+ { segmentationId, type }
1838
+ );
1839
+ },
1840
+
1841
+ /**
1842
+ * Downloads a segmentation
1843
+ * @param props.segmentationId - The ID of the segmentation to download
1844
+ */
1845
+ downloadSegmentationCommand: ({ segmentationId }) => {
1846
+ const { segmentationService } = servicesManager.services;
1847
+ segmentationService.downloadSegmentation(segmentationId);
1848
+ },
1849
+
1850
+ /**
1851
+ * Stores a segmentation and shows it in the viewport
1852
+ * @param props.segmentationId - The ID of the segmentation to store
1853
+ */
1854
+ storeSegmentationCommand: async args => {
1855
+ const { segmentationId } = args;
1856
+ const { segmentationService, viewportGridService } = servicesManager.services;
1857
+
1858
+ const displaySetInstanceUIDs = await createReportAsync({
1859
+ servicesManager,
1860
+ getReport: () => commandsManager.runCommand('storeSegmentation', args),
1861
+ reportType: 'Segmentation',
1862
+ });
1863
+
1864
+ if (displaySetInstanceUIDs) {
1865
+ segmentationService.remove(segmentationId);
1866
+ viewportGridService.setDisplaySetsForViewport({
1867
+ viewportId: viewportGridService.getActiveViewportId(),
1868
+ displaySetInstanceUIDs,
1869
+ });
1870
+ }
1871
+ },
1872
+
1873
+ /**
1874
+ * Downloads a segmentation as RTSS
1875
+ * @param props.segmentationId - The ID of the segmentation
1876
+ */
1877
+ downloadRTSSCommand: ({ segmentationId }) => {
1878
+ const { segmentationService } = servicesManager.services;
1879
+ segmentationService.downloadRTSS(segmentationId);
1880
+ },
1881
+
1882
+ /**
1883
+ * Sets the style for a segmentation
1884
+ * @param props.segmentationId - The ID of the segmentation
1885
+ * @param props.type - The type of style
1886
+ * @param props.key - The style key to set
1887
+ * @param props.value - The style value
1888
+ */
1889
+ setSegmentationStyleCommand: ({ type, key, value }) => {
1890
+ const { segmentationService } = servicesManager.services;
1891
+ segmentationService.setStyle({ type }, { [key]: value });
1892
+ },
1893
+
1894
+ /**
1895
+ * Deletes a segment from a segmentation
1896
+ * @param props.segmentationId - The ID of the segmentation
1897
+ * @param props.segmentIndex - The index of the segment to delete
1898
+ */
1899
+ deleteSegmentCommand: ({ segmentationId, segmentIndex }) => {
1900
+ const { segmentationService } = servicesManager.services;
1901
+ segmentationService.removeSegment(segmentationId, segmentIndex);
1902
+ },
1903
+
1904
+ /**
1905
+ * Deletes an entire segmentation
1906
+ * @param props.segmentationId - The ID of the segmentation to delete
1907
+ */
1908
+ deleteSegmentationCommand: ({ segmentationId }) => {
1909
+ const { segmentationService } = servicesManager.services;
1910
+ segmentationService.remove(segmentationId);
1911
+ },
1912
+
1913
+ /**
1914
+ * Removes a segmentation from the viewport.
1915
+ *
1916
+ * This is the segmentation panel's Remove from Viewport, which lists the
1917
+ * segmentations of the study rather than the layers of one pane, so it is
1918
+ * the global statement: it un-hydrates the display set as well as clearing
1919
+ * it from the active viewport. The per-viewport equivalent is the viewport
1920
+ * data overlay menu's Remove, which runs `removeDisplaySetLayer` without
1921
+ * `unhydrate`.
1922
+ *
1923
+ * @param props.segmentationId - The ID of the segmentation to remove
1924
+ */
1925
+ removeSegmentationFromViewportCommand: ({ segmentationId: displaySetInstanceUID }) => {
1926
+ const { viewportGridService } = servicesManager.services;
1927
+ const viewportId = viewportGridService.getActiveViewportId();
1928
+
1929
+ commandsManager.runCommand('removeDisplaySetLayer', {
1930
+ viewportId,
1931
+ displaySetInstanceUID,
1932
+ unhydrate: true,
1933
+ });
1934
+ },
1935
+
1936
+ /**
1937
+ * Toggles rendering of inactive segmentations
1938
+ */
1939
+ toggleRenderInactiveSegmentationsCommand: () => {
1940
+ const { segmentationService, viewportGridService } = servicesManager.services;
1941
+ const viewportId = viewportGridService.getActiveViewportId();
1942
+ const renderInactive = segmentationService.getRenderInactiveSegmentations(viewportId);
1943
+ segmentationService.setRenderInactiveSegmentations(viewportId, !renderInactive);
1944
+ },
1945
+
1946
+ editSegmentLabel: async ({ segmentationId, segmentIndex }) => {
1947
+ const { segmentationService, uiDialogService } = servicesManager.services;
1948
+ const segmentation = segmentationService.getSegmentation(segmentationId);
1949
+
1950
+ if (!segmentation) {
1951
+ return;
1952
+ }
1953
+
1954
+ const segment = segmentation.segments[segmentIndex];
1955
+
1956
+ callInputDialog({
1957
+ uiDialogService,
1958
+ title: i18n.t('Tools:Edit Segment Label'),
1959
+ placeholder: i18n.t('Tools:Enter new label'),
1960
+ defaultValue: segment.label,
1961
+ }).then(label => {
1962
+ segmentationService.setSegmentLabel(segmentationId, segmentIndex, label);
1963
+ });
1964
+ },
1965
+
1966
+ editSegmentationLabel: ({ segmentationId }) => {
1967
+ const { segmentationService, uiDialogService } = servicesManager.services;
1968
+ const segmentation = segmentationService.getSegmentation(segmentationId);
1969
+
1970
+ if (!segmentation) {
1971
+ return;
1972
+ }
1973
+
1974
+ const { label } = segmentation;
1975
+
1976
+ callInputDialog({
1977
+ uiDialogService,
1978
+ title: i18n.t('Tools:Edit Segmentation Label'),
1979
+ placeholder: i18n.t('Tools:Enter new label'),
1980
+ defaultValue: label,
1981
+ }).then(label => {
1982
+ // The update clears `labelIsGenerated` - the user chose this label.
1983
+ segmentationService.addOrUpdateSegmentation({ segmentationId, label });
1984
+ });
1985
+ },
1986
+
1987
+ editSegmentColor: ({ segmentationId, segmentIndex }) => {
1988
+ const { segmentationService, uiDialogService, viewportGridService } =
1989
+ servicesManager.services;
1990
+ const viewportId = viewportGridService.getActiveViewportId();
1991
+ const color = segmentationService.getSegmentColor(viewportId, segmentationId, segmentIndex);
1992
+
1993
+ const rgbaColor = {
1994
+ r: color[0],
1995
+ g: color[1],
1996
+ b: color[2],
1997
+ a: color[3] / 255.0,
1998
+ };
1999
+
2000
+ uiDialogService.show({
2001
+ content: colorPickerDialog,
2002
+ title: i18n.t('Tools:Segment Color'),
2003
+ contentProps: {
2004
+ value: rgbaColor,
2005
+ onSave: newRgbaColor => {
2006
+ const color = [newRgbaColor.r, newRgbaColor.g, newRgbaColor.b, newRgbaColor.a * 255.0];
2007
+ segmentationService.setSegmentColor(viewportId, segmentationId, segmentIndex, color);
2008
+ },
2009
+ },
2010
+ });
2011
+ },
2012
+
2013
+ getRenderInactiveSegmentations: () => {
2014
+ const { segmentationService, viewportGridService } = servicesManager.services;
2015
+ return segmentationService.getRenderInactiveSegmentations(
2016
+ viewportGridService.getActiveViewportId()
2017
+ );
2018
+ },
2019
+
2020
+ deleteActiveAnnotation: () => {
2021
+ const activeAnnotationsUID = cornerstoneTools.annotation.selection.getAnnotationsSelected();
2022
+ activeAnnotationsUID.forEach(activeAnnotationUID => {
2023
+ measurementService.remove(activeAnnotationUID);
2024
+ });
2025
+ },
2026
+ setDisplaySetsForViewports: ({ viewportsToUpdate }) => {
2027
+ const { cineService, viewportGridService } = servicesManager.services;
2028
+ // Stopping the cine of modified viewports before changing the viewports to
2029
+ // avoid inconsistent state and lost references
2030
+ viewportsToUpdate.forEach(viewport => {
2031
+ const state = cineService.getState();
2032
+ const currentCineState = state.cines?.[viewport.viewportId];
2033
+ cineService.setCine({
2034
+ id: viewport.viewportId,
2035
+ frameRate: currentCineState?.frameRate ?? state.default?.frameRate ?? 24,
2036
+ isPlaying: false,
2037
+ });
2038
+ });
2039
+
2040
+ viewportGridService.setDisplaySetsForViewports(viewportsToUpdate);
2041
+ },
2042
+ undo: () => {
2043
+ DefaultHistoryMemo.undo();
2044
+ },
2045
+ redo: () => {
2046
+ DefaultHistoryMemo.redo();
2047
+ },
2048
+ toggleSegmentPreviewEdit: ({ toggle }) => {
2049
+ let labelmapTools = getLabelmapTools({ toolGroupService });
2050
+ labelmapTools = labelmapTools.filter(tool => !tool.toolName.includes('Eraser'));
2051
+ labelmapTools.forEach(tool => {
2052
+ tool.configuration = {
2053
+ ...tool.configuration,
2054
+ preview: {
2055
+ ...tool.configuration.preview,
2056
+ enabled: toggle,
2057
+ },
2058
+ };
2059
+ });
2060
+ },
2061
+ toggleSegmentSelect: ({ toggle }) => {
2062
+ const toolGroupIds = toolGroupService.getToolGroupIds();
2063
+ toolGroupIds.forEach(toolGroupId => {
2064
+ const toolGroup = cornerstoneTools.ToolGroupManager.getToolGroup(toolGroupId);
2065
+ if (toggle) {
2066
+ toolGroup.setToolActive(cornerstoneTools.SegmentSelectTool.toolName);
2067
+ } else {
2068
+ toolGroup.setToolDisabled(cornerstoneTools.SegmentSelectTool.toolName);
2069
+ }
2070
+ });
2071
+ },
2072
+ toggleSegmentLabel: ({ enabled }: { enabled?: boolean }) => {
2073
+ const toolName = cornerstoneTools.SegmentLabelTool.toolName;
2074
+ const toolGroupIds = toolGroupService.getToolGroupIds();
2075
+
2076
+ const isToolOn = toolGroupIds.some(toolGroupId => {
2077
+ const toolGroup = cornerstoneTools.ToolGroupManager.getToolGroup(toolGroupId);
2078
+ const mode = toolGroup.getToolInstance(toolName)?.mode;
2079
+ return mode === 'Active';
2080
+ });
2081
+
2082
+ const enableTool = enabled !== undefined ? enabled : !isToolOn;
2083
+
2084
+ toolGroupIds.forEach(toolGroupId => {
2085
+ const toolGroup = cornerstoneTools.ToolGroupManager.getToolGroup(toolGroupId);
2086
+ if (enableTool) {
2087
+ toolGroup.setToolActive(toolName);
2088
+ } else {
2089
+ toolGroup.setToolDisabled(toolName);
2090
+ }
2091
+ });
2092
+ },
2093
+ /**
2094
+ * Used to sync the apps initial state with the config file settings.
2095
+ *
2096
+ * Will mutate the tools object of the given tool group and add the segmentLabelTool to the proper place.
2097
+ *
2098
+ * Use it before initializing the toolGroup with the tools.
2099
+ */
2100
+ initializeSegmentLabelTool: ({ tools }) => {
2101
+ const { customizationService } = servicesManager.services;
2102
+ const segmentLabelConfig = customizationService.getCustomization(
2103
+ 'segmentation.segmentLabel'
2104
+ ) as {
2105
+ enabledByDefault?: boolean;
2106
+ labelColor?: number[];
2107
+ hoverTimeout?: number;
2108
+ background?: string;
2109
+ };
2110
+
2111
+ if (segmentLabelConfig?.enabledByDefault) {
2112
+ const activeTools = tools?.active ?? [];
2113
+ activeTools.push({
2114
+ toolName: toolNames.SegmentLabel,
2115
+ configuration: {
2116
+ hoverTimeout: segmentLabelConfig?.hoverTimeout ?? 1,
2117
+ color: segmentLabelConfig?.labelColor,
2118
+ background: segmentLabelConfig?.background,
2119
+ },
2120
+ });
2121
+
2122
+ tools.active = activeTools;
2123
+ return tools;
2124
+ }
2125
+
2126
+ const disabledTools = tools?.disabled ?? [];
2127
+ disabledTools.push({
2128
+ toolName: toolNames.SegmentLabel,
2129
+ configuration: {
2130
+ hoverTimeout: segmentLabelConfig?.hoverTimeout ?? 1,
2131
+ color: segmentLabelConfig?.labelColor,
2132
+ },
2133
+ });
2134
+ tools.disabled = disabledTools;
2135
+ return tools;
2136
+ },
2137
+ toggleUseCenterSegmentIndex: ({ toggle }) => {
2138
+ let labelmapTools = getLabelmapTools({ toolGroupService });
2139
+ labelmapTools = labelmapTools.filter(tool => !tool.toolName.includes('Eraser'));
2140
+ labelmapTools.forEach(tool => {
2141
+ tool.configuration = {
2142
+ ...tool.configuration,
2143
+ useCenterSegmentIndex: toggle,
2144
+ };
2145
+ });
2146
+ },
2147
+ _handlePreviewAction: action => {
2148
+ // May be undefined when no viewport is enabled (e.g. Escape pressed while
2149
+ // a modal such as Preferences is open).
2150
+ const enabledElement = _getActiveViewportEnabledElement();
2151
+ const previewTools = getPreviewTools({ toolGroupService });
2152
+
2153
+ previewTools.forEach(tool => {
2154
+ try {
2155
+ tool[`${action}Preview`]();
2156
+ } catch (error) {
2157
+ console.debug('Error accepting preview for tool', tool.toolName);
2158
+ }
2159
+ });
2160
+
2161
+ if (segmentAI.enabled) {
2162
+ segmentAI[`${action}Preview`](enabledElement?.viewport?.element);
2163
+ }
2164
+ },
2165
+ acceptPreview: () => {
2166
+ actions._handlePreviewAction('accept');
2167
+ },
2168
+ rejectPreview: () => {
2169
+ actions._handlePreviewAction('reject');
2170
+ },
2171
+ /**
2172
+ * Generic Escape handler. A single Escape press should discard whatever the
2173
+ * user has in progress, but that can be one of two unrelated things: a
2174
+ * provisional segmentation preview, or an annotation being drawn. Rather
2175
+ * than bind both `rejectPreview` and `cancelMeasurement` to `esc` (Mousetrap
2176
+ * keeps only one handler per key, so the second silently shadows the first),
2177
+ * this command orchestrates both single-purpose commands. Each is a no-op
2178
+ * when its state is not active, so running both is safe and order-independent.
2179
+ */
2180
+ cancelActiveOperation: () => {
2181
+ try {
2182
+ actions.rejectPreview();
2183
+ } catch (error) {
2184
+ console.debug('Error rejecting active preview', error);
2185
+ } finally {
2186
+ actions.cancelMeasurement();
2187
+ }
2188
+ },
2189
+ clearMarkersForMarkerLabelmap: () => {
2190
+ const { viewport } = _getActiveViewportEnabledElement();
2191
+ const toolGroup = cornerstoneTools.ToolGroupManager.getToolGroupForViewport(viewport.id);
2192
+ const toolInstance = toolGroup.getToolInstance('MarkerLabelmap');
2193
+
2194
+ if (!toolInstance) {
2195
+ return;
2196
+ }
2197
+
2198
+ toolInstance.clearMarkers(viewport);
2199
+ },
2200
+ interpolateScrollForMarkerLabelmap: () => {
2201
+ const { viewport } = _getActiveViewportEnabledElement();
2202
+ const toolGroup = cornerstoneTools.ToolGroupManager.getToolGroupForViewport(viewport.id);
2203
+ const toolInstance = toolGroup.getToolInstance('MarkerLabelmap');
2204
+
2205
+ if (!toolInstance) {
2206
+ return;
2207
+ }
2208
+
2209
+ toolInstance.interpolateScroll(viewport, 1);
2210
+ },
2211
+ toggleLabelmapAssist: async () => {
2212
+ const { viewport } = _getActiveViewportEnabledElement();
2213
+ const newState = !segmentAI.enabled;
2214
+ segmentAI.enabled = newState;
2215
+
2216
+ if (!segmentAIEnabled) {
2217
+ await segmentAI.initModel();
2218
+ segmentAIEnabled = true;
2219
+ }
2220
+
2221
+ // set the brush tool to active
2222
+ const toolGroupIds = toolGroupService.getToolGroupIds();
2223
+ if (newState) {
2224
+ actions.setToolActiveToolbar({
2225
+ toolName: 'CircularBrushForAutoSegmentAI',
2226
+ toolGroupIds: toolGroupIds,
2227
+ });
2228
+ } else {
2229
+ toolGroupIds.forEach(toolGroupId => {
2230
+ const toolGroup = cornerstoneTools.ToolGroupManager.getToolGroup(toolGroupId);
2231
+ toolGroup.setToolPassive('CircularBrushForAutoSegmentAI');
2232
+ });
2233
+ }
2234
+
2235
+ if (segmentAI.enabled) {
2236
+ segmentAI.initViewport(viewport);
2237
+ }
2238
+ },
2239
+ setBrushSize: ({ value }) => {
2240
+ const brushSize = Number(value);
2241
+
2242
+ toolGroupService.getToolGroupIds()?.forEach(toolGroupId => {
2243
+ segmentationUtils.setBrushSizeForToolGroup(toolGroupId, brushSize);
2244
+ });
2245
+ },
2246
+ setThresholdRange: ({
2247
+ value,
2248
+ toolNames = [
2249
+ 'ThresholdCircularBrush',
2250
+ 'ThresholdSphereBrush',
2251
+ 'ThresholdCircularBrushDynamic',
2252
+ 'ThresholdSphereBrushDynamic',
2253
+ ],
2254
+ }) => {
2255
+ const toolGroupIds = toolGroupService.getToolGroupIds();
2256
+ if (!toolGroupIds?.length) {
2257
+ return;
2258
+ }
2259
+
2260
+ for (const toolGroupId of toolGroupIds) {
2261
+ const toolGroup = toolGroupService.getToolGroup(toolGroupId);
2262
+ toolNames?.forEach(toolName => {
2263
+ toolGroup.setToolConfiguration(toolName, {
2264
+ threshold: {
2265
+ range: value,
2266
+ },
2267
+ });
2268
+ });
2269
+ }
2270
+ },
2271
+ increaseBrushSize: () => {
2272
+ _handleBrushSizeAction('increase');
2273
+ },
2274
+ decreaseBrushSize: () => {
2275
+ _handleBrushSizeAction('decrease');
2276
+ },
2277
+ addNewSegment: () => {
2278
+ const { segmentationService } = servicesManager.services;
2279
+ const { activeViewportId } = viewportGridService.getState();
2280
+ const activeSegmentation = segmentationService.getActiveSegmentation(activeViewportId);
2281
+ if (!activeSegmentation) {
2282
+ return;
2283
+ }
2284
+ segmentationService.addSegment(activeSegmentation.segmentationId);
2285
+ },
2286
+ loadSegmentationDisplaySetsForViewport: ({
2287
+ viewportId,
2288
+ displaySetInstanceUIDs,
2289
+ viewportType,
2290
+ // The SEG/RTSTRUCT being hydrated. Passing it lets the target selection
2291
+ // include panes that share its frame of reference rather than only those
2292
+ // hung with the exact referenced display set, and lets it work when there
2293
+ // is no viewport to match against at all.
2294
+ derivedDisplaySetInstanceUID,
2295
+ }) => {
2296
+ const updatedViewports = getUpdatedViewportsForSegmentation({
2297
+ viewportId,
2298
+ servicesManager,
2299
+ displaySetInstanceUIDs,
2300
+ derivedDisplaySetInstanceUID,
2301
+ });
2302
+
2303
+ if (!updatedViewports?.length) {
2304
+ return;
2305
+ }
2306
+
2307
+ updatedViewports.forEach(({ viewportId: csViewportId }) => {
2308
+ const csViewport = cornerstoneViewportService.getCornerstoneViewport(csViewportId);
2309
+ csViewport?.setNeedsRender?.();
2310
+ });
2311
+
2312
+ // A pinned viewportType (RTSTRUCT contour hydration on a native "next"
2313
+ // viewport requests 'stack') is a statement about the pane hydration was
2314
+ // invoked on, whose background is being set to the referenced image. The
2315
+ // other panes here were matched because they already show something the
2316
+ // segmentation can be drawn over - by frame of reference, and keeping the
2317
+ // display sets they already have - so their own render mode is the right
2318
+ // one and forcing 'stack' onto them would flip an MPR pane to a stack.
2319
+ // Note the merged entries carry no viewportOptions at all, so the grid
2320
+ // reducer would merge a bare `{ viewportType }` straight over the pane's
2321
+ // real options.
2322
+ const targetViewportId = viewportId || viewportGridService.getActiveViewportId();
2323
+
2324
+ actions.setDisplaySetsForViewports({
2325
+ viewportsToUpdate: updatedViewports.map(viewport => ({
2326
+ viewportId: viewport.viewportId,
2327
+ displaySetInstanceUIDs: viewport.displaySetInstanceUIDs,
2328
+ ...(viewportType && viewport.viewportId === targetViewportId
2329
+ ? { viewportOptions: { ...viewport.viewportOptions, viewportType } }
2330
+ : {}),
2331
+ })),
2332
+ });
2333
+ },
2334
+ setViewportOrientation: ({ viewportId, orientation }) => {
2335
+ const viewport = cornerstoneViewportService.getCornerstoneViewport(viewportId);
2336
+
2337
+ // Accept any viewport already rendering volume content (legacy ORTHOGRAPHIC
2338
+ // or a native viewport in volume mode) — both expose setOrientation().
2339
+ if (!viewport || !getViewportAdapter(viewport).canReorientInPlace()) {
2340
+ console.warn('Orientation can only be set on volume viewports');
2341
+ return;
2342
+ }
2343
+
2344
+ // Get display sets for this viewport to verify at least one is reconstructable
2345
+ const displaySetUIDs = viewportGridService.getDisplaySetsUIDsForViewport(viewportId);
2346
+ const displaySets = displaySetUIDs.map(uid => displaySetService.getDisplaySetByUID(uid));
2347
+
2348
+ if (!displaySets.some(ds => ds.isReconstructable)) {
2349
+ console.warn('Cannot change orientation: No reconstructable display sets in viewport');
2350
+ return;
2351
+ }
2352
+
2353
+ viewport.setOrientation(orientation);
2354
+ viewport.render();
2355
+
2356
+ // update the orientation in the viewport info
2357
+ const viewportInfo = cornerstoneViewportService.getViewportInfo(viewportId);
2358
+ viewportInfo.setOrientation(orientation);
2359
+ },
2360
+ /**
2361
+ * Toggles the horizontal flip state of the viewport.
2362
+ */
2363
+ toggleViewportHorizontalFlip: ({ viewportId }: { viewportId?: string } = {}) => {
2364
+ actions.flipViewportHorizontal({ viewportId, newValue: 'toggle' });
2365
+ },
2366
+
2367
+ /**
2368
+ * Explicitly sets the horizontal flip state of the viewport.
2369
+ */
2370
+ setViewportHorizontalFlip: ({
2371
+ flipped,
2372
+ viewportId,
2373
+ }: {
2374
+ flipped: boolean;
2375
+ viewportId?: string;
2376
+ }) => {
2377
+ actions.flipViewportHorizontal({ viewportId, newValue: flipped });
2378
+ },
2379
+
2380
+ /**
2381
+ * Toggles the vertical flip state of the viewport.
2382
+ */
2383
+ toggleViewportVerticalFlip: ({ viewportId }: { viewportId?: string } = {}) => {
2384
+ actions.flipViewportVertical({ viewportId, newValue: 'toggle' });
2385
+ },
2386
+
2387
+ /**
2388
+ * Explicitly sets the vertical flip state of the viewport.
2389
+ */
2390
+ setViewportVerticalFlip: ({
2391
+ flipped,
2392
+ viewportId,
2393
+ }: {
2394
+ flipped: boolean;
2395
+ viewportId?: string;
2396
+ }) => {
2397
+ actions.flipViewportVertical({ viewportId, newValue: flipped });
2398
+ },
2399
+ /**
2400
+ * Internal helper to rotate or set absolute rotation for a viewport.
2401
+ */
2402
+ _rotateViewport: ({
2403
+ rotation,
2404
+ viewportId,
2405
+ rotationMode = 'apply',
2406
+ }: {
2407
+ rotation: number;
2408
+ viewportId?: string;
2409
+ rotationMode?: 'apply' | 'set';
2410
+ }) => {
2411
+ const viewport = _resolveViewport(viewportId);
2412
+ if (!viewport) {
2413
+ return;
2414
+ }
2415
+ ops.rotate(viewport, rotation, rotationMode);
2416
+ viewport.render();
2417
+ },
2418
+ startRecordingForAnnotationGroup: () => {
2419
+ cornerstoneTools.AnnotationTool.startGroupRecording();
2420
+ },
2421
+ endRecordingForAnnotationGroup: () => {
2422
+ cornerstoneTools.AnnotationTool.endGroupRecording();
2423
+ },
2424
+ triggerCreateAnnotationMemo: ({
2425
+ annotation,
2426
+ FrameOfReferenceUID,
2427
+ options,
2428
+ }: {
2429
+ annotation: ToolTypes.Annotation;
2430
+ FrameOfReferenceUID: string;
2431
+ options: { newAnnotation?: boolean; deleting?: boolean };
2432
+ }): void => {
2433
+ const { newAnnotation, deleting } = options;
2434
+ const renderingEngines = getRenderingEngines();
2435
+ const viewports = renderingEngines.flatMap(re => re.getViewports());
2436
+ const validViewport = viewports.find(
2437
+ vp => vp.getFrameOfReferenceUID() === FrameOfReferenceUID
2438
+ );
2439
+
2440
+ if (!validViewport) {
2441
+ return;
2442
+ }
2443
+
2444
+ cornerstoneTools.AnnotationTool.createAnnotationMemo(validViewport.element, annotation, {
2445
+ newAnnotation,
2446
+ deleting,
2447
+ });
2448
+ },
2449
+ activateSelectedSegmentationOfType: ({ segmentationRepresentationType }) => {
2450
+ const { segmentationService, viewportGridService } = servicesManager.services;
2451
+ const activeViewportId = viewportGridService.getActiveViewportId();
2452
+ const { selectedSegmentationsForViewport } =
2453
+ useSelectedSegmentationsForViewportStore.getState();
2454
+ const segmentationId = selectedSegmentationsForViewport[activeViewportId]?.get(
2455
+ segmentationRepresentationType
2456
+ );
2457
+
2458
+ if (!segmentationId) {
2459
+ return;
2460
+ }
2461
+
2462
+ segmentationService.setActiveSegmentation(activeViewportId, segmentationId);
2463
+ },
2464
+ setDynamicCursorSizeForSculptorTool: ({ value: isDynamicCursorSize }) => {
2465
+ const viewportId = viewportGridService.getActiveViewportId();
2466
+ const toolGroup = toolGroupService.getToolGroupForViewport(viewportId);
2467
+ const sculptorToolInstance = toolGroup.getToolInstance(toolNames.SculptorTool);
2468
+ const oldConfiguration = sculptorToolInstance.configuration;
2469
+
2470
+ sculptorToolInstance.configuration = {
2471
+ ...oldConfiguration,
2472
+ updateCursorSize: isDynamicCursorSize ? 'dynamic' : '',
2473
+ };
2474
+ },
2475
+ setInterpolationToolConfiguration: ({ value: interpolateContours, toolNames }) => {
2476
+ const viewportId = viewportGridService.getActiveViewportId();
2477
+ const toolGroup = toolGroupService.getToolGroupForViewport(viewportId);
2478
+
2479
+ // Set the interpolation configuration for the active tool.
2480
+ const activeTool = toolGroupService.getActiveToolForViewport(viewportId);
2481
+ const interpolationConfig = {
2482
+ interpolation: {
2483
+ enabled: interpolateContours,
2484
+ },
2485
+ };
2486
+ toolGroup.setToolConfiguration(activeTool, interpolationConfig);
2487
+
2488
+ // Now set the interpolation configuration for the other tools specified.
2489
+ if (toolNames) {
2490
+ Object.values(toolGroup.getToolInstances()).forEach(toolInstance => {
2491
+ if (toolNames?.includes(toolInstance.toolName)) {
2492
+ toolGroup.setToolConfiguration(toolInstance.toolName, interpolationConfig);
2493
+ }
2494
+ });
2495
+ }
2496
+ },
2497
+ setSimplifiedSplineForSplineContourSegmentationTool: ({ value: simplifiedSpline }) => {
2498
+ const viewportId = viewportGridService.getActiveViewportId();
2499
+ const toolGroup = toolGroupService.getToolGroupForViewport(viewportId);
2500
+ Object.values(toolGroup.getToolInstances()).forEach(toolInstance => {
2501
+ if (toolInstance instanceof SplineContourSegmentationTool) {
2502
+ const oldConfiguration = toolInstance.configuration;
2503
+ toolInstance.configuration = {
2504
+ ...oldConfiguration,
2505
+ simplifiedSpline,
2506
+ };
2507
+ }
2508
+ });
2509
+ },
2510
+ removeSmallContours: ({ areaThreshold: threshold }) => {
2511
+ const viewportId = viewportGridService.getActiveViewportId();
2512
+ const activeSegmentation = segmentationService.getActiveSegmentation(viewportId);
2513
+ const activeSegment = segmentationService.getActiveSegment(viewportId);
2514
+
2515
+ if (!activeSegmentation || !activeSegment) {
2516
+ return;
2517
+ }
2518
+
2519
+ const { removeContourIslands } = segmentationUtilities;
2520
+ removeContourIslands(activeSegmentation.segmentationId, activeSegment.segmentIndex, {
2521
+ threshold,
2522
+ });
2523
+ const renderingEngine = cornerstoneViewportService.getRenderingEngine();
2524
+ renderingEngine.render();
2525
+ },
2526
+ applyLogicalContourOperation: ({
2527
+ segmentAInfo,
2528
+ segmentBInfo,
2529
+ resultSegmentInfo,
2530
+ logicalOperation,
2531
+ }: {
2532
+ segmentAInfo: SegmentInfo;
2533
+ segmentBInfo: SegmentInfo;
2534
+ resultSegmentInfo: OperatorOptions;
2535
+ logicalOperation: LogicalOperation;
2536
+ }) => {
2537
+ switch (logicalOperation) {
2538
+ case LogicalOperation.Union:
2539
+ add(segmentAInfo, segmentBInfo, resultSegmentInfo);
2540
+ break;
2541
+ case LogicalOperation.Intersect:
2542
+ intersect(segmentAInfo, segmentBInfo, resultSegmentInfo);
2543
+ break;
2544
+ case LogicalOperation.Subtract:
2545
+ subtract(segmentAInfo, segmentBInfo, resultSegmentInfo);
2546
+ break;
2547
+ default:
2548
+ throw new Error('Unsupported logical operation');
2549
+ }
2550
+ },
2551
+ copyContourSegment: ({
2552
+ sourceSegmentInfo,
2553
+ targetSegmentInfo,
2554
+ }: {
2555
+ sourceSegmentInfo: SegmentInfo;
2556
+ targetSegmentInfo?: SegmentInfo;
2557
+ }) => {
2558
+ if (!targetSegmentInfo) {
2559
+ const sourceSegmentation = segmentationService.getSegmentation(
2560
+ sourceSegmentInfo.segmentationId
2561
+ );
2562
+ const sourceCachedStats =
2563
+ sourceSegmentation?.segments?.[sourceSegmentInfo.segmentIndex]?.cachedStats;
2564
+
2565
+ targetSegmentInfo = {
2566
+ segmentationId: sourceSegmentInfo.segmentationId,
2567
+ segmentIndex: segmentationService.getNextAvailableSegmentIndex(
2568
+ sourceSegmentInfo.segmentationId
2569
+ ),
2570
+ };
2571
+
2572
+ // Copy source cachedStats so jump-to-segment navigation works on the duplicate segment.
2573
+ segmentationService.addSegment(targetSegmentInfo.segmentationId, {
2574
+ segmentIndex: targetSegmentInfo.segmentIndex,
2575
+ ...(sourceCachedStats && {
2576
+ cachedStats: csUtils.deepClone(sourceCachedStats) as Record<string, unknown>,
2577
+ }),
2578
+ });
2579
+ }
2580
+
2581
+ copy(sourceSegmentInfo, targetSegmentInfo);
2582
+ },
2583
+ smoothContours: () => {
2584
+ const viewportId = viewportGridService.getActiveViewportId();
2585
+ const activeSegmentation = segmentationService.getActiveSegmentation(viewportId);
2586
+ const activeSegment = segmentationService.getActiveSegment(viewportId);
2587
+
2588
+ if (!activeSegmentation || !activeSegment) {
2589
+ return;
2590
+ }
2591
+
2592
+ const { smoothContours } = segmentationUtilities;
2593
+ smoothContours(activeSegmentation.segmentationId, activeSegment.segmentIndex);
2594
+
2595
+ const renderingEngine = cornerstoneViewportService.getRenderingEngine();
2596
+ renderingEngine.render();
2597
+ },
2598
+ removeContourHoles: () => {
2599
+ const viewportId = viewportGridService.getActiveViewportId();
2600
+ const activeSegmentation = segmentationService.getActiveSegmentation(viewportId);
2601
+ const activeSegment = segmentationService.getActiveSegment(viewportId);
2602
+
2603
+ if (!activeSegmentation || !activeSegment) {
2604
+ return;
2605
+ }
2606
+
2607
+ const { removeContourHoles } = segmentationUtilities;
2608
+ removeContourHoles(activeSegmentation.segmentationId, activeSegment.segmentIndex);
2609
+
2610
+ const renderingEngine = cornerstoneViewportService.getRenderingEngine();
2611
+ renderingEngine.render();
2612
+ },
2613
+ decimateContours: () => {
2614
+ const viewportId = viewportGridService.getActiveViewportId();
2615
+ const activeSegmentation = segmentationService.getActiveSegmentation(viewportId);
2616
+ const activeSegment = segmentationService.getActiveSegment(viewportId);
2617
+
2618
+ if (!activeSegmentation || !activeSegment) {
2619
+ return;
2620
+ }
2621
+
2622
+ const { decimateContours } = segmentationUtilities;
2623
+ decimateContours(activeSegmentation.segmentationId, activeSegment.segmentIndex);
2624
+
2625
+ const renderingEngine = cornerstoneViewportService.getRenderingEngine();
2626
+ renderingEngine.render();
2627
+ },
2628
+ convertContourHoles: () => {
2629
+ const viewportId = viewportGridService.getActiveViewportId();
2630
+ const activeSegmentation = segmentationService.getActiveSegmentation(viewportId);
2631
+ const activeSegment = segmentationService.getActiveSegment(viewportId);
2632
+
2633
+ if (!activeSegmentation || !activeSegment) {
2634
+ return;
2635
+ }
2636
+
2637
+ const targetSegmentInfo = {
2638
+ segmentationId: activeSegmentation.segmentationId,
2639
+ segmentIndex: segmentationService.getNextAvailableSegmentIndex(
2640
+ activeSegmentation.segmentationId
2641
+ ),
2642
+ };
2643
+
2644
+ segmentationService.addSegment(targetSegmentInfo.segmentationId, {
2645
+ segmentIndex: targetSegmentInfo.segmentIndex,
2646
+ });
2647
+
2648
+ const { convertContourHoles } = segmentationUtilities;
2649
+ convertContourHoles(
2650
+ activeSegmentation.segmentationId,
2651
+ activeSegment.segmentIndex,
2652
+ targetSegmentInfo.segmentationId,
2653
+ targetSegmentInfo.segmentIndex
2654
+ );
2655
+
2656
+ const renderingEngine = cornerstoneViewportService.getRenderingEngine();
2657
+ renderingEngine.render();
2658
+ },
2659
+ };
2660
+
2661
+ const definitions = {
2662
+ // The command here is to show the viewer context menu, as being the
2663
+ // context menu
2664
+ showCornerstoneContextMenu: {
2665
+ commandFn: actions.showCornerstoneContextMenu,
2666
+ options: {
2667
+ menuCustomizationId: 'measurementsContextMenu',
2668
+ commands: [
2669
+ {
2670
+ commandName: 'showContextMenu',
2671
+ },
2672
+ ],
2673
+ },
2674
+ },
2675
+
2676
+ getNearbyToolData: {
2677
+ commandFn: actions.getNearbyToolData,
2678
+ },
2679
+ getNearbyAnnotation: {
2680
+ commandFn: actions.getNearbyAnnotation,
2681
+ storeContexts: [],
2682
+ options: {},
2683
+ },
2684
+ toggleViewportColorbar: {
2685
+ commandFn: actions.toggleViewportColorbar,
2686
+ },
2687
+ setMeasurementLabel: {
2688
+ commandFn: actions.setMeasurementLabel,
2689
+ },
2690
+ renameMeasurement: {
2691
+ commandFn: actions.renameMeasurement,
2692
+ },
2693
+ updateMeasurement: {
2694
+ commandFn: actions.updateMeasurement,
2695
+ },
2696
+ changeMeasurementColor: {
2697
+ commandFn: actions.changeMeasurementColor,
2698
+ },
2699
+ jumpToMeasurement: actions.jumpToMeasurement,
2700
+ recordMeasurementsPredecessor: {
2701
+ commandFn: actions.recordMeasurementsPredecessor,
2702
+ },
2703
+ removeMeasurement: {
2704
+ commandFn: actions.removeMeasurement,
2705
+ },
2706
+ cancelMeasurement: {
2707
+ commandFn: actions.cancelMeasurement,
2708
+ },
2709
+ toggleLockMeasurement: {
2710
+ commandFn: actions.toggleLockMeasurement,
2711
+ },
2712
+ toggleVisibilityMeasurement: {
2713
+ commandFn: actions.toggleVisibilityMeasurement,
2714
+ },
2715
+ downloadCSVMeasurementsReport: {
2716
+ commandFn: actions.downloadCSVMeasurementsReport,
2717
+ },
2718
+ setViewportWindowLevel: {
2719
+ commandFn: actions.setViewportWindowLevel,
2720
+ },
2721
+ setWindowLevel: {
2722
+ commandFn: actions.setWindowLevel,
2723
+ },
2724
+ setWindowLevelPreset: {
2725
+ commandFn: actions.setWindowLevelPreset,
2726
+ },
2727
+ setToolActive: {
2728
+ commandFn: actions.setToolActive,
2729
+ },
2730
+ setToolActiveToolbar: {
2731
+ commandFn: actions.setToolActiveToolbar,
2732
+ },
2733
+ setToolEnabled: {
2734
+ commandFn: actions.setToolEnabled,
2735
+ },
2736
+ rotateViewportCW: {
2737
+ commandFn: actions.rotateViewportBy,
2738
+ options: { rotation: 90 },
2739
+ },
2740
+ rotateViewportCCW: {
2741
+ commandFn: actions.rotateViewportBy,
2742
+ options: { rotation: -90 },
2743
+ },
2744
+ rotateViewportCWSet: {
2745
+ commandFn: actions.setViewportRotation,
2746
+ options: { rotation: 90 },
2747
+ },
2748
+ incrementActiveViewport: {
2749
+ commandFn: actions.changeActiveViewport,
2750
+ },
2751
+ decrementActiveViewport: {
2752
+ commandFn: actions.changeActiveViewport,
2753
+ options: { direction: -1 },
2754
+ },
2755
+ flipViewportHorizontal: {
2756
+ commandFn: actions.toggleViewportHorizontalFlip,
2757
+ },
2758
+ flipViewportVertical: {
2759
+ commandFn: actions.toggleViewportVerticalFlip,
2760
+ },
2761
+ setViewportHorizontalFlip: {
2762
+ commandFn: actions.setViewportHorizontalFlip,
2763
+ options: { flipped: true },
2764
+ },
2765
+ setViewportVerticalFlip: {
2766
+ commandFn: actions.setViewportVerticalFlip,
2767
+ options: { flipped: true },
2768
+ },
2769
+ invertViewport: {
2770
+ commandFn: actions.invertViewport,
2771
+ },
2772
+ resetViewport: {
2773
+ commandFn: actions.resetViewport,
2774
+ },
2775
+ scaleUpViewport: {
2776
+ commandFn: actions.scaleViewport,
2777
+ options: { direction: 1 },
2778
+ },
2779
+ scaleDownViewport: {
2780
+ commandFn: actions.scaleViewport,
2781
+ options: { direction: -1 },
2782
+ },
2783
+ fitViewportToWindow: {
2784
+ commandFn: actions.scaleViewport,
2785
+ options: { direction: 0 },
2786
+ },
2787
+ nextImage: {
2788
+ commandFn: actions.scroll,
2789
+ options: { direction: 1 },
2790
+ },
2791
+ previousImage: {
2792
+ commandFn: actions.scroll,
2793
+ options: { direction: -1 },
2794
+ },
2795
+ firstImage: {
2796
+ commandFn: actions.jumpToImage,
2797
+ options: { imageIndex: 0 },
2798
+ },
2799
+ lastImage: {
2800
+ commandFn: actions.jumpToImage,
2801
+ options: { imageIndex: -1 },
2802
+ },
2803
+ jumpToImage: {
2804
+ commandFn: actions.jumpToImage,
2805
+ },
2806
+ showDownloadViewportModal: {
2807
+ commandFn: actions.showDownloadViewportModal,
2808
+ },
2809
+ toggleCine: {
2810
+ commandFn: actions.toggleCine,
2811
+ },
2812
+ arrowTextCallback: {
2813
+ commandFn: actions.arrowTextCallback,
2814
+ },
2815
+ setViewportActive: {
2816
+ commandFn: actions.setViewportActive,
2817
+ },
2818
+ setViewportColormap: {
2819
+ commandFn: actions.setViewportColormap,
2820
+ },
2821
+ setViewportForToolConfiguration: {
2822
+ commandFn: actions.setViewportForToolConfiguration,
2823
+ },
2824
+ storePresentation: {
2825
+ commandFn: actions.storePresentation,
2826
+ },
2827
+ attachProtocolViewportDataListener: {
2828
+ commandFn: actions.attachProtocolViewportDataListener,
2829
+ },
2830
+ setViewportPreset: {
2831
+ commandFn: actions.setViewportPreset,
2832
+ },
2833
+ setVolumeRenderingQulaity: {
2834
+ commandFn: actions.setVolumeRenderingQulaity,
2835
+ },
2836
+ shiftVolumeOpacityPoints: {
2837
+ commandFn: actions.shiftVolumeOpacityPoints,
2838
+ },
2839
+ setVolumeLighting: {
2840
+ commandFn: actions.setVolumeLighting,
2841
+ },
2842
+ resetCrosshairs: {
2843
+ commandFn: actions.resetCrosshairs,
2844
+ },
2845
+ toggleSynchronizer: {
2846
+ commandFn: actions.toggleSynchronizer,
2847
+ },
2848
+ updateVolumeData: {
2849
+ commandFn: actions.updateVolumeData,
2850
+ },
2851
+ setViewport3DViewDirection: {
2852
+ commandFn: actions.setViewport3DViewDirection,
2853
+ },
2854
+ rotateViewport3DBy: {
2855
+ commandFn: actions.rotateViewport3DBy,
2856
+ },
2857
+ setViewport3DSpin: {
2858
+ commandFn: actions.setViewport3DSpin,
2859
+ },
2860
+ toggleEnabledDisabledToolbar: {
2861
+ commandFn: actions.toggleEnabledDisabledToolbar,
2862
+ },
2863
+ toggleActiveDisabledToolbar: {
2864
+ commandFn: actions.toggleActiveDisabledToolbar,
2865
+ },
2866
+ updateStoredPositionPresentation: {
2867
+ commandFn: actions.updateStoredPositionPresentation,
2868
+ },
2869
+ updateStoredSegmentationPresentation: {
2870
+ commandFn: actions.updateStoredSegmentationPresentation,
2871
+ },
2872
+ createLabelmapForViewport: {
2873
+ commandFn: actions.createLabelmapForViewport,
2874
+ },
2875
+ createContourForViewport: {
2876
+ commandFn: actions.createContourForViewport,
2877
+ },
2878
+ setActiveSegmentation: {
2879
+ commandFn: actions.setActiveSegmentation,
2880
+ },
2881
+ addSegment: {
2882
+ commandFn: actions.addSegmentCommand,
2883
+ },
2884
+ setActiveSegmentAndCenter: {
2885
+ commandFn: actions.setActiveSegmentAndCenterCommand,
2886
+ },
2887
+ toggleSegmentVisibility: {
2888
+ commandFn: actions.toggleSegmentVisibilityCommand,
2889
+ },
2890
+ toggleSegmentLock: {
2891
+ commandFn: actions.toggleSegmentLockCommand,
2892
+ },
2893
+ toggleSegmentationVisibility: {
2894
+ commandFn: actions.toggleSegmentationVisibilityCommand,
2895
+ },
2896
+ downloadSegmentation: {
2897
+ commandFn: actions.downloadSegmentationCommand,
2898
+ },
2899
+ storeSegmentation: {
2900
+ commandFn: actions.storeSegmentationCommand,
2901
+ },
2902
+ downloadRTSS: {
2903
+ commandFn: actions.downloadRTSSCommand,
2904
+ },
2905
+ setSegmentationStyle: {
2906
+ commandFn: actions.setSegmentationStyleCommand,
2907
+ },
2908
+ deleteSegment: {
2909
+ commandFn: actions.deleteSegmentCommand,
2910
+ },
2911
+ deleteSegmentation: {
2912
+ commandFn: actions.deleteSegmentationCommand,
2913
+ },
2914
+ removeSegmentationFromViewport: {
2915
+ commandFn: actions.removeSegmentationFromViewportCommand,
2916
+ },
2917
+ toggleRenderInactiveSegmentations: {
2918
+ commandFn: actions.toggleRenderInactiveSegmentationsCommand,
2919
+ },
2920
+ setFillAlpha: {
2921
+ commandFn: createSetStyleCommand('fillAlpha'),
2922
+ },
2923
+ setOutlineWidth: {
2924
+ commandFn: createSetStyleCommand('outlineWidth'),
2925
+ },
2926
+ setRenderFill: {
2927
+ commandFn: createSetStyleCommand('renderFill'),
2928
+ },
2929
+ setRenderFillInactive: {
2930
+ commandFn: createSetStyleCommand('renderFillInactive'),
2931
+ },
2932
+ setRenderOutline: {
2933
+ commandFn: createSetStyleCommand('renderOutline'),
2934
+ },
2935
+ setRenderOutlineInactive: {
2936
+ commandFn: createSetStyleCommand('renderOutlineInactive'),
2937
+ },
2938
+ setFillAlphaInactive: {
2939
+ commandFn: createSetStyleCommand('fillAlphaInactive'),
2940
+ },
2941
+ editSegmentLabel: {
2942
+ commandFn: actions.editSegmentLabel,
2943
+ },
2944
+ editSegmentationLabel: {
2945
+ commandFn: actions.editSegmentationLabel,
2946
+ },
2947
+ editSegmentColor: {
2948
+ commandFn: actions.editSegmentColor,
2949
+ },
2950
+ getRenderInactiveSegmentations: {
2951
+ commandFn: actions.getRenderInactiveSegmentations,
2952
+ },
2953
+ deleteActiveAnnotation: {
2954
+ commandFn: actions.deleteActiveAnnotation,
2955
+ },
2956
+ setDisplaySetsForViewports: actions.setDisplaySetsForViewports,
2957
+ undo: actions.undo,
2958
+ redo: actions.redo,
2959
+ interpolateLabelmap: actions.interpolateLabelmap,
2960
+ runSegmentBidirectional: actions.runSegmentBidirectional,
2961
+ downloadCSVSegmentationReport: actions.downloadCSVSegmentationReport,
2962
+ toggleSegmentPreviewEdit: actions.toggleSegmentPreviewEdit,
2963
+ toggleSegmentSelect: actions.toggleSegmentSelect,
2964
+ acceptPreview: actions.acceptPreview,
2965
+ rejectPreview: actions.rejectPreview,
2966
+ cancelActiveOperation: actions.cancelActiveOperation,
2967
+ toggleUseCenterSegmentIndex: actions.toggleUseCenterSegmentIndex,
2968
+ toggleLabelmapAssist: actions.toggleLabelmapAssist,
2969
+ interpolateScrollForMarkerLabelmap: actions.interpolateScrollForMarkerLabelmap,
2970
+ clearMarkersForMarkerLabelmap: actions.clearMarkersForMarkerLabelmap,
2971
+ setBrushSize: actions.setBrushSize,
2972
+ setThresholdRange: actions.setThresholdRange,
2973
+ increaseBrushSize: actions.increaseBrushSize,
2974
+ decreaseBrushSize: actions.decreaseBrushSize,
2975
+ addNewSegment: actions.addNewSegment,
2976
+ loadSegmentationDisplaySetsForViewport: actions.loadSegmentationDisplaySetsForViewport,
2977
+ setViewportOrientation: actions.setViewportOrientation,
2978
+ hydrateSecondaryDisplaySet: actions.hydrateSecondaryDisplaySet,
2979
+ loadDisplaySetData: actions.loadDisplaySetData,
2980
+ getVolumeIdForDisplaySet: actions.getVolumeIdForDisplaySet,
2981
+ triggerCreateAnnotationMemo: actions.triggerCreateAnnotationMemo,
2982
+ startRecordingForAnnotationGroup: actions.startRecordingForAnnotationGroup,
2983
+ endRecordingForAnnotationGroup: actions.endRecordingForAnnotationGroup,
2984
+ toggleSegmentLabel: actions.toggleSegmentLabel,
2985
+ jumpToMeasurementViewport: actions.jumpToMeasurementViewport,
2986
+ initializeSegmentLabelTool: actions.initializeSegmentLabelTool,
2987
+ activateSelectedSegmentationOfType: actions.activateSelectedSegmentationOfType,
2988
+ setDynamicCursorSizeForSculptorTool: actions.setDynamicCursorSizeForSculptorTool,
2989
+ setSimplifiedSplineForSplineContourSegmentationTool:
2990
+ actions.setSimplifiedSplineForSplineContourSegmentationTool,
2991
+ removeSmallContours: actions.removeSmallContours,
2992
+ applyLogicalContourOperation: actions.applyLogicalContourOperation,
2993
+ copyContourSegment: actions.copyContourSegment,
2994
+ smoothContours: actions.smoothContours,
2995
+ removeContourHoles: actions.removeContourHoles,
2996
+ decimateContours: actions.decimateContours,
2997
+ convertContourHoles: actions.convertContourHoles,
2998
+ setInterpolationToolConfiguration: actions.setInterpolationToolConfiguration,
2999
+ };
3000
+
3001
+ return {
3002
+ actions,
3003
+ definitions,
3004
+ defaultContext: 'CORNERSTONE',
3005
+ };
3006
+ }
3007
+
3008
+ export default commandsModule;