All files / extensions/usAnnotation/src getCommandsModule.ts

4.95% Statements 5/101
0% Branches 0/25
5.55% Functions 1/18
4.95% Lines 5/101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353            54x                       54x   54x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       54x                                                                                               54x                
import { UltrasoundPleuraBLineTool, Enums as csToolsEnums } from '@cornerstonejs/tools';
import { Types as OhifTypes } from '@ohif/core';
import { eventTarget, triggerEvent, utilities } from '@cornerstonejs/core';
import getInstanceByImageId from './getInstanceByImageId';
import { setShowPercentage } from './PleuraBlinePercentage';
 
const { transformWorldToIndex } = utilities;
 
/**
 * Creates and returns the commands module for ultrasound annotation
 * @param params - Extension parameters including servicesManager and commandsManager
 * @returns The commands module with actions and definitions
 */
function commandsModule({
  servicesManager,
  commandsManager,
}: OhifTypes.Extensions.ExtensionParams): OhifTypes.Extensions.CommandsModule {
  const { viewportGridService, toolGroupService, cornerstoneViewportService } =
    servicesManager.services as AppTypes.Services;
 
  const actions = {
    /**
     * Switches the active ultrasound annotation type
     * @param options - Object containing the annotationType to switch to
     */
    switchUSPleuraBLineAnnotation: ({ annotationType }) => {
      const activeViewportId = viewportGridService.getActiveViewportId();
      const toolGroup = toolGroupService.getToolGroupForViewport(activeViewportId);
      Iif (!toolGroup) {
        return;
      }
      const usAnnotation = toolGroup.getToolInstance(UltrasoundPleuraBLineTool.toolName);
      Iif (usAnnotation) {
        usAnnotation.setActiveAnnotationType(annotationType);
      }
    },
    /**
     * Convenience method to switch to pleura line annotation type
     */
    switchUSPleuraBLineAnnotationToPleuraLine: () => {
      actions.switchUSPleuraBLineAnnotation({
        annotationType: UltrasoundPleuraBLineTool.USPleuraBLineAnnotationType.PLEURA,
      });
    },
    /**
     * Convenience method to switch to B-line annotation type
     */
    switchUSPleuraBLineAnnotationToBLine: () => {
      actions.switchUSPleuraBLineAnnotation({
        annotationType: UltrasoundPleuraBLineTool.USPleuraBLineAnnotationType.BLINE,
      });
    },
    /**
     * Deletes the last annotation of the specified type
     * @param options - Object containing the annotationType to delete
     */
    deleteLastUSPleuraBLineAnnotation: ({ annotationType }) => {
      const activeViewportId = viewportGridService.getActiveViewportId();
      const toolGroup = toolGroupService.getToolGroupForViewport(activeViewportId);
      Iif (!toolGroup) {
        return;
      }
      const usAnnotation = toolGroup.getToolInstance(UltrasoundPleuraBLineTool.toolName);
      Iif (usAnnotation) {
        const viewport = cornerstoneViewportService.getCornerstoneViewport(activeViewportId);
        usAnnotation.deleteLastAnnotationType(viewport.element, annotationType);
        viewport.render();
      }
    },
 
    /**
     * Convenience method to delete the last pleura line annotation
     */
    deleteLastPleuraAnnotation: () => {
      actions.deleteLastUSPleuraBLineAnnotation({
        annotationType: UltrasoundPleuraBLineTool.USPleuraBLineAnnotationType.PLEURA,
      });
    },
    /**
     * Convenience method to delete the last B-line annotation
     */
    deleteLastBLineAnnotation: () => {
      actions.deleteLastUSPleuraBLineAnnotation({
        annotationType: UltrasoundPleuraBLineTool.USPleuraBLineAnnotationType.BLINE,
      });
    },
    /**
     * Toggles a boolean attribute of the ultrasound annotation tool
     * @param options - Object containing the attribute name to toggle
     */
    toggleUSToolAttribute: ({ attribute }) => {
      const activeViewportId = viewportGridService.getActiveViewportId();
      const toolGroup = toolGroupService.getToolGroupForViewport(activeViewportId);
      Iif (!toolGroup) {
        return;
      }
      const configuration = toolGroup.getToolConfiguration(UltrasoundPleuraBLineTool.toolName);
      Iif (!configuration) {
        return;
      }
      toolGroup.setToolConfiguration(UltrasoundPleuraBLineTool.toolName, {
        [attribute]: !configuration[attribute],
      });
      const viewport = cornerstoneViewportService.getCornerstoneViewport(activeViewportId);
      viewport.render();
    },
    /**
     * Sets a specific attribute of the ultrasound annotation tool to a given value
     * @param options - Object containing the attribute name and value to set
     */
    setUSToolAttribute: ({ attribute, value }) => {
      const activeViewportId = viewportGridService.getActiveViewportId();
      const toolGroup = toolGroupService.getToolGroupForViewport(activeViewportId);
      Iif (!toolGroup) {
        return;
      }
      const configuration = toolGroup.getToolConfiguration(UltrasoundPleuraBLineTool.toolName);
      Iif (!configuration) {
        return;
      }
      toolGroup.setToolConfiguration(UltrasoundPleuraBLineTool.toolName, {
        [attribute]: value,
      });
      const viewport = cornerstoneViewportService.getCornerstoneViewport(activeViewportId);
      viewport.render();
    },
    /**
     * Toggles the display of fan annotations
     */
    toggleDisplayFanAnnotation: () => {
      actions.toggleUSToolAttribute({
        attribute: 'showFanAnnotations',
      });
    },
    /**
     * Toggles the display of the depth guide
     */
    toggleDepthGuide: () => {
      actions.toggleUSToolAttribute({
        attribute: 'drawDepthGuide',
      });
    },
    /**
     * Sets the depth guide display state
     * @param options - Object containing the boolean value to set
     */
    setDepthGuide: ({ value }) => {
      actions.setUSToolAttribute({
        attribute: 'drawDepthGuide',
        value,
      });
    },
    /**
     * Sets the fan annotation display state
     * @param options - Object containing the boolean value to set
     */
    setDisplayFanAnnotation: ({ value }) => {
      actions.setUSToolAttribute({
        attribute: 'showFanAnnotations',
        value,
      });
    },
    /**
     * Sets whether to show the pleura percentage in the viewport overlay
     * @param options - Object containing the boolean value to set
     */
    setShowPleuraPercentage: ({ value }) => {
      setShowPercentage(value);
      // Trigger ANNOTATION_MODIFIED event to update the overlay
      triggerEvent(eventTarget, csToolsEnums.Events.ANNOTATION_MODIFIED, {
        annotation: {
          metadata: {
            toolName: UltrasoundPleuraBLineTool.toolName,
          },
        },
      });
    },
    /**
     * Generates a JSON representation of the ultrasound annotations
     * @param labels - Array of annotation labels
     * @param imageIds - Array of image IDs to include in the JSON
     * @returns A JSON object containing the annotations data or undefined if generation fails
     */
    generateUSPleuraBLineAnnotationsJSON: (labels: string[] = [], imageIds: string[] = []) => {
      const activeViewportId = viewportGridService.getActiveViewportId();
      const viewport = cornerstoneViewportService.getCornerstoneViewport(activeViewportId);
      Iif (!viewport) {
        return;
      }
      const { imageData } = viewport.getImageData() || {};
      Iif (!imageData) {
        return;
      }
 
      const toolGroup = toolGroupService.getToolGroupForViewport(activeViewportId);
      Iif (!toolGroup) {
        return;
      }
      const usAnnotation = toolGroup.getToolInstance(UltrasoundPleuraBLineTool.toolName);
      Iif (usAnnotation) {
        const configuration = toolGroup.getToolConfiguration(UltrasoundPleuraBLineTool.toolName);
        const imageId = viewport.getCurrentImageId();
        const filterImageIds = (imageId: string) => {
          if (imageIds.length === 0) {
            return true;
          } else {
            return imageIds.includes(imageId);
          }
        };
        const annotations = UltrasoundPleuraBLineTool.filterAnnotations(
          viewport.element,
          filterImageIds
        );
        const frame_annotations = {};
        const viewportImageIds = viewport.getImageIds();
        annotations.forEach(annotation => {
          const imageId = annotation.metadata.referencedImageId;
          const { annotationType } = annotation.data;
          const [point1, point2] = annotation.data.handles.points;
          const p1 = transformWorldToIndex(imageData, point1);
          const p2 = transformWorldToIndex(imageData, point2);
          const imageIdIndex = viewportImageIds.indexOf(imageId);
          Iif (frame_annotations[imageIdIndex] === undefined) {
            frame_annotations[imageIdIndex] = {
              pleura_lines: [],
              b_lines: [],
            };
          }
          if (annotationType === UltrasoundPleuraBLineTool.USPleuraBLineAnnotationType.PLEURA) {
            frame_annotations[imageIdIndex].pleura_lines.push([
              [p1[0], p1[1], 0],
              [p2[0], p2[1], 0],
            ]);
          } else Iif (
            annotationType === UltrasoundPleuraBLineTool.USPleuraBLineAnnotationType.BLINE
          ) {
            frame_annotations[imageIdIndex].b_lines.push([
              [p1[0], p1[1], 0],
              [p2[0], p2[1], 0],
            ]);
          }
        });
 
        const instance = getInstanceByImageId(servicesManager.services, imageId);
        const json = {
          SOPInstanceUID: instance.SOPInstanceUID,
          GrayscaleConversion: false,
          mask_type: 'fan',
          angle1: configuration.startAngle,
          angle2: configuration.endAngle,
          center_rows_px: configuration.center[0],
          center_cols_px: configuration.center[1],
          radius1: configuration.innerRadius,
          radius2: configuration.outerRadius,
          image_size_rows: instance.rows,
          image_size_cols: instance.columns,
          AnnotationLabels: labels,
          frame_annotations,
        };
        return json;
      }
    },
    /**
     * Downloads the ultrasound annotations as a JSON file
     * @param options - Object containing labels and imageIds arrays
     */
    downloadUSPleuraBLineAnnotationsJSON({ labels = [], imageIds = [] }) {
      const json = actions.generateUSPleuraBLineAnnotationsJSON(labels, imageIds);
      Iif (!json) {
        return;
      }
 
      // Convert JSON object to a string
      const jsonString = JSON.stringify(json, null, 2);
 
      // Create a blob with the JSON data
      const blob = new Blob([jsonString], { type: 'application/json' });
 
      // Create a URL for the blob
      const url = URL.createObjectURL(blob);
 
      // Create an anchor element
      const a = document.createElement('a');
      a.href = url;
      a.download = `ultrasound_annotations_${new Date().toISOString().slice(0, 10)}.json`;
 
      // Append to the document, click to download, and remove
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
 
      // Clean up by revoking the URL
      URL.revokeObjectURL(url);
    },
  };
 
  const definitions = {
    switchUSAnnotation: {
      commandFn: actions.switchUSPleuraBLineAnnotation,
    },
    deleteLastAnnotation: {
      commandFn: actions.deleteLastUSPleuraBLineAnnotation,
    },
    toggleDepthGuide: {
      commandFn: actions.toggleDepthGuide,
    },
    setDepthGuide: {
      commandFn: actions.setDepthGuide,
    },
    setShowPleuraPercentage: {
      commandFn: actions.setShowPleuraPercentage,
    },
    toggleUSToolAttribute: {
      commandFn: actions.toggleUSToolAttribute,
    },
    setUSToolAttribute: {
      commandFn: actions.setUSToolAttribute,
    },
    toggleDisplayFanAnnotation: {
      commandFn: actions.toggleDisplayFanAnnotation,
    },
    setDisplayFanAnnotation: {
      commandFn: actions.setDisplayFanAnnotation,
    },
    generateJSON: {
      commandFn: actions.generateUSPleuraBLineAnnotationsJSON,
    },
    downloadJSON: {
      commandFn: actions.downloadUSPleuraBLineAnnotationsJSON,
    },
    switchUSAnnotationToPleuraLine: {
      commandFn: actions.switchUSPleuraBLineAnnotationToPleuraLine,
    },
    switchUSAnnotationToBLine: {
      commandFn: actions.switchUSPleuraBLineAnnotationToBLine,
    },
    deleteLastPleuraAnnotation: {
      commandFn: actions.deleteLastPleuraAnnotation,
    },
    deleteLastBLineAnnotation: {
      commandFn: actions.deleteLastBLineAnnotation,
    },
  };
 
  return {
    actions,
    definitions,
    defaultContext: 'CORNERSTONE',
  };
}
 
export default commandsModule;