All files / packages/tools/src/tools/segmentation SphereScissorsTool.ts

76.85% Statements 93/121
44.44% Branches 8/18
87.5% Functions 7/8
77.5% Lines 93/120

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 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401                                                                                                                                                                  1x                     1x       1x       1x 1x 1x 1x   1x 1x   1x   1x 1x 1x     1x 1x             1x   1x 1x   1x           1x     1x                                       1x   1x                               1x   1x   1x     1x 1x   1x                             1x   1x   1x   1x   1x     1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x   1x 1x 1x   1x       1x 1x       1x         1x             1x   1x   1x     1x 1x 1x                 1x 1x 1x   1x     1x 1x   1x   1x   1x   1x                   1x 1x   1x           1x 1x 1x 1x 1x   1x 1x 1x           1x 1x 1x 1x 1x   1x 1x 1x                     1x       10x 10x 10x                                                                                                               1x    
import { cache, getEnabledElement } from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
 
import { BaseTool } from '../base';
import {
  PublicToolProps,
  ToolProps,
  EventTypes,
  SVGDrawingHelper,
} from '../../types';
 
import { fillInsideSphere } from './strategies/fillSphere';
import { eraseInsideSphere } from './strategies/eraseSphere';
import { Events, SegmentationRepresentations } from '../../enums';
import { drawCircle as drawCircleSvg } from '../../drawingSvg';
import {
  resetElementCursor,
  hideElementCursor,
} from '../../cursors/elementCursor';
 
import triggerAnnotationRenderForViewportIds from '../../utilities/triggerAnnotationRenderForViewportIds';
import {
  config as segmentationConfig,
  segmentLocking,
  segmentIndex as segmentIndexController,
  activeSegmentation,
} from '../../stateManagement/segmentation';
 
import { getSegmentation } from '../../stateManagement/segmentation/segmentationState';
import {
  LabelmapSegmentationData,
  LabelmapSegmentationDataVolume,
  LabelmapSegmentationDataStack,
} from '../../types/LabelmapTypes';
import { isVolumeSegmentation } from './strategies/utils/stackVolumeCheck';
/**
 * Tool for manipulating segmentation data by drawing a sphere in 3d space. It acts on the
 * active Segmentation on the viewport (enabled element) and requires an active
 * segmentation to be already present. By default it will use the activeSegmentIndex
 * for the segmentation to modify. You can use SegmentationModule to set the active
 * segmentation and segmentIndex. Todo: sphere scissor has some memory problem which
 * lead to ui blocking behavior that needs to be fixed.
 */
class SphereScissorsTool extends BaseTool {
  static toolName;
  editData: {
    annotation: any;
    segmentIndex: number;
    segmentsLocked: number[];
    segmentationRepresentationUID: string;
    //
    volumeId: string;
    referencedVolumeId: string;
    imageIdReferenceMap: Map<string, string>;
    //
    toolGroupId: string;
    segmentColor: [number, number, number, number];
    viewportIdsToRender: string[];
    handleIndex?: number;
    movingTextBox: boolean;
    newAnnotation?: boolean;
    hasMoved?: boolean;
    centerCanvas?: Array<number>;
  } | null;
  isDrawing: boolean;
  isHandleOutsideImage: boolean;
 
  constructor(
    toolProps: PublicToolProps = {},
    defaultToolProps: ToolProps = {
      supportedInteractionTypes: ['Mouse', 'Touch'],
      configuration: {
        strategies: {
          FILL_INSIDE: fillInsideSphere,
          ERASE_INSIDE: eraseInsideSphere,
        },
        defaultStrategy: 'FILL_INSIDE',
        activeStrategy: 'FILL_INSIDE',
      },
    }
  ) {
    super(toolProps, defaultToolProps);
  }
 
  /**
   * Based on the current position of the mouse and the enabledElement, it
   * finds the active segmentation info and use it for the current tool.
   *
   * @param evt -  EventTypes.NormalizedMouseEventType
   * @returns The annotation object.
   *
   */
  preMouseDownCallback = (evt: EventTypes.InteractionEventType): true => {
    // if we are already drawing, means we have started with a click, and now we
    // are moving the mouse (not dragging) so the final click should not
    // be handled by this preMouseDownCallback but rather the endCallback
    Iif (this.isDrawing === true) {
      return;
    }
 
    const eventDetail = evt.detail;
    const { currentPoints, element } = eventDetail;
    const worldPos = currentPoints.world;
    const canvasPos = currentPoints.canvas;
 
    const enabledElement = getEnabledElement(element);
    const { viewport, renderingEngine } = enabledElement;
 
    this.isDrawing = true;
 
    const camera = viewport.getCamera();
    const { viewPlaneNormal, viewUp } = camera;
    const toolGroupId = this.toolGroupId;
 
    const activeSegmentationRepresentation =
      activeSegmentation.getActiveSegmentationRepresentation(toolGroupId);
    Iif (!activeSegmentationRepresentation) {
      throw new Error(
        'No active segmentation detected, create one before using scissors tool'
      );
    }
 
    const { segmentationRepresentationUID, segmentationId } =
      activeSegmentationRepresentation;
    const segmentIndex =
      segmentIndexController.getActiveSegmentIndex(segmentationId);
    const segmentsLocked = segmentLocking.getLockedSegments(segmentationId);
 
    const segmentColor = segmentationConfig.color.getColorForSegmentIndex(
      toolGroupId,
      segmentationRepresentationUID,
      segmentIndex
    );
 
    this.isDrawing = true;
 
    // Used for drawing the svg only, we might not need it at all
    const annotation = {
      metadata: {
        viewPlaneNormal: <Types.Point3>[...viewPlaneNormal],
        viewUp: <Types.Point3>[...viewUp],
        FrameOfReferenceUID: viewport.getFrameOfReferenceUID(),
        referencedImageId: '',
        toolName: this.getToolName(),
        segmentColor,
      },
      data: {
        invalidated: true,
        handles: {
          points: [[...worldPos], [...worldPos], [...worldPos], [...worldPos]],
          activeHandleIndex: null,
        },
        cachedStats: {},
        highlighted: true,
      },
    };
 
    const viewportIdsToRender = [viewport.id];
 
    this.editData = {
      annotation,
      centerCanvas: canvasPos,
      segmentationRepresentationUID,
      segmentIndex,
      segmentationId,
      segmentsLocked,
      segmentColor,
      toolGroupId,
      viewportIdsToRender,
      handleIndex: 3,
      movingTextBox: false,
      newAnnotation: true,
      hasMoved: false,
    } as any;
 
    const { representationData } = getSegmentation(segmentationId);
    const labelmapData =
      representationData[SegmentationRepresentations.Labelmap];
 
    if (
      isVolumeSegmentation(labelmapData as LabelmapSegmentationData, viewport)
    ) {
      const { volumeId } = labelmapData as LabelmapSegmentationDataVolume;
      const segmentation = cache.getVolume(volumeId);
 
      this.editData = {
        ...this.editData,
        volumeId,
        referencedVolumeId: segmentation.referencedVolumeId,
      };
    } else E{
      const { imageIdReferenceMap } =
        labelmapData as LabelmapSegmentationDataStack;
 
      this.editData = {
        ...this.editData,
        imageIdReferenceMap,
      };
    }
 
    this._activateDraw(element);
 
    hideElementCursor(element);
 
    evt.preventDefault();
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    return true;
  };
 
  _dragCallback = (evt: EventTypes.InteractionEventType) => {
    this.isDrawing = true;
    const eventDetail = evt.detail;
    const { element } = eventDetail;
    const { currentPoints } = eventDetail;
    const currentCanvasPoints = currentPoints.canvas;
    const enabledElement = getEnabledElement(element);
    const { renderingEngine, viewport } = enabledElement;
    const { canvasToWorld } = viewport;
 
    //////
    const { annotation, viewportIdsToRender, centerCanvas } = this.editData;
    const { data } = annotation;
 
    const dX = Math.abs(currentCanvasPoints[0] - centerCanvas[0]);
    const dY = Math.abs(currentCanvasPoints[1] - centerCanvas[1]);
    const radius = Math.sqrt(dX * dX + dY * dY);
 
    const bottomCanvas: Types.Point2 = [
      centerCanvas[0],
      centerCanvas[1] + radius,
    ];
    const topCanvas: Types.Point2 = [centerCanvas[0], centerCanvas[1] - radius];
    const leftCanvas: Types.Point2 = [
      centerCanvas[0] - radius,
      centerCanvas[1],
    ];
    const rightCanvas: Types.Point2 = [
      centerCanvas[0] + radius,
      centerCanvas[1],
    ];
 
    data.handles.points = [
      canvasToWorld(bottomCanvas),
      canvasToWorld(topCanvas),
      canvasToWorld(leftCanvas),
      canvasToWorld(rightCanvas),
    ];
 
    annotation.invalidated = true;
 
    this.editData.hasMoved = true;
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
  };
 
  _endCallback = (evt: EventTypes.InteractionEventType) => {
    const eventDetail = evt.detail;
    const { element } = eventDetail;
 
    const {
      annotation,
      newAnnotation,
      hasMoved,
      segmentIndex,
      segmentationRepresentationUID,
      segmentsLocked,
    } = this.editData;
    const { data } = annotation;
    const { viewPlaneNormal, viewUp } = annotation.metadata;
 
    Iif (newAnnotation && !hasMoved) {
      return;
    }
    annotation.highlighted = false;
    data.handles.activeHandleIndex = null;
 
    this._deactivateDraw(element);
 
    resetElementCursor(element);
 
    const enabledElement = getEnabledElement(element);
 
    const operationData = {
      ...this.editData,
      points: data.handles.points,
      segmentIndex,
      segmentationRepresentationUID,
      segmentsLocked,
      viewPlaneNormal,
      viewUp,
    };
 
    this.editData = null;
    this.isDrawing = false;
 
    this.applyActiveStrategy(enabledElement, operationData);
  };
 
  /**
   * Add event handlers for the modify event loop, and prevent default event propagation.
   */
  _activateDraw = (element) => {
    element.addEventListener(Events.MOUSE_UP, this._endCallback);
    element.addEventListener(Events.MOUSE_DRAG, this._dragCallback);
    element.addEventListener(Events.MOUSE_CLICK, this._endCallback);
    element.addEventListener(Events.MOUSE_MOVE, this._dragCallback);
 
    element.addEventListener(Events.TOUCH_END, this._endCallback);
    element.addEventListener(Events.TOUCH_TAP, this._endCallback);
    element.addEventListener(Events.TOUCH_DRAG, this._dragCallback);
  };
 
  /**
   * Add event handlers for the modify event loop, and prevent default event prapogation.
   */
  _deactivateDraw = (element) => {
    element.removeEventListener(Events.MOUSE_UP, this._endCallback);
    element.removeEventListener(Events.MOUSE_DRAG, this._dragCallback);
    element.removeEventListener(Events.MOUSE_CLICK, this._endCallback);
    element.removeEventListener(Events.MOUSE_MOVE, this._dragCallback);
 
    element.removeEventListener(Events.TOUCH_END, this._endCallback);
    element.removeEventListener(Events.TOUCH_DRAG, this._dragCallback);
    element.removeEventListener(Events.TOUCH_TAP, this._endCallback);
  };
 
  /**
   * it is used to draw the sphereScissor annotation in each
   * request animation frame. Note that the annotation are disappeared
   * after the segmentation modification.
   *
   * @param enabledElement - The Cornerstone's enabledElement.
   * @param svgDrawingHelper - The svgDrawingHelper providing the context for drawing.
   */
  renderAnnotation = (
    enabledElement: Types.IEnabledElement,
    svgDrawingHelper: SVGDrawingHelper
  ): boolean => {
    let renderStatus = false;
    Eif (!this.editData) {
      return renderStatus;
    }
 
    const { viewport } = enabledElement;
    const { viewportIdsToRender } = this.editData;
 
    if (!viewportIdsToRender.includes(viewport.id)) {
      return renderStatus;
    }
 
    const { annotation } = this.editData;
 
    // Todo: rectangle color based on segment index
    const toolMetadata = annotation.metadata;
    const annotationUID = annotation.annotationUID;
 
    const data = annotation.data;
    const { points } = data.handles;
    const canvasCoordinates = points.map((p) => viewport.worldToCanvas(p));
 
    const bottom = canvasCoordinates[0];
    const top = canvasCoordinates[1];
 
    const center = [
      Math.floor((bottom[0] + top[0]) / 2),
      Math.floor((bottom[1] + top[1]) / 2),
    ];
 
    const radius = Math.abs(bottom[1] - Math.floor((bottom[1] + top[1]) / 2));
 
    const color = `rgb(${toolMetadata.segmentColor.slice(0, 3)})`;
 
    // If rendering engine has been destroyed while rendering
    if (!viewport.getRenderingEngine()) {
      console.warn('Rendering Engine has been destroyed');
      return renderStatus;
    }
 
    const circleUID = '0';
    drawCircleSvg(
      svgDrawingHelper,
      annotationUID,
      circleUID,
      center as Types.Point2,
      radius,
      {
        color,
      }
    );
 
    renderStatus = true;
 
    return renderStatus;
  };
}
 
SphereScissorsTool.toolName = 'SphereScissor';
export default SphereScissorsTool;