All files / packages/tools/src/tools/annotation CircleROITool.ts

64.3% Statements 227/353
43.82% Branches 39/89
57.69% Functions 15/26
64.55% Lines 224/347

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 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065                                                                                                                      1x                                                                                                                               5x                                 5x   5x                             5x     5x 5x 5x   5x 5x   5x   5x 5x   5x             5x   5x                                                                 5x   5x         5x           5x   5x   5x   5x   5x                           5x                                                               5x                                                               5x                                                                                           5x 3x 3x     3x 3x   3x               3x 3x   3x 3x   3x   3x   3x 3x   3x             3x   3x 3x       5x 5x 5x 5x 5x 5x 5x 5x 5x     5x 5x   5x         5x   5x   5x     5x                                                                                         5x                                                                         5x   2x 2x 2x 2x 2x   2x 2x   2x 2x   2x   2x         2x 2x     2x 2x       5x                       5x 5x   5x 5x 5x   5x 5x 5x     5x 5x   5x 5x 5x 5x   5x 5x 5x     5x 5x   5x 5x 5x 5x   5x 5x 5x                     5x       5x 5x 5x   5x   5x       5x         5x       5x   5x   5x           5x 5x 5x 5x 5x   5x   5x         5x 10x   5x 5x 5x   5x       5x       5x                       5x                                                                                                 5x             5x       5x                 5x                         5x 5x 5x                             5x                                 5x   5x 5x                           5x 5x             5x 5x   5x       5x       5x 5x                     5x   5x               5x     5x           5x 5x   5x   10x 5x   5x       5x 5x 5x   5x 5x 5x   5x 5x   5x         5x       5x   5x   5x 5x 5x   5x   5x 5x 5x         5x 5x 5x   5x 5x   5x 5x   5x           5x           5x             5x           5x 5x 5x       5x 5x           5x                 5x           5x     808x             5x   5x                                               5x     5x   5x     5x 5x               5x                     5x 5x   5x 5x     5x     5x 5x     5x     5x 5x     5x 5x     5x 1x     5x     1x    
import { AnnotationTool } from '../base';
 
import {
  getEnabledElement,
  VolumeViewport,
  utilities as csUtils,
} from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
 
import { getCalibratedAspect } from '../../utilities/getCalibratedUnits';
import { getCalibratedLengthUnitsAndScale, roundNumber } from '../../utilities';
import throttle from '../../utilities/throttle';
import {
  addAnnotation,
  getAnnotations,
  removeAnnotation,
} from '../../stateManagement/annotation/annotationState';
import { isAnnotationLocked } from '../../stateManagement/annotation/annotationLocking';
import { isAnnotationVisible } from '../../stateManagement/annotation/annotationVisibility';
import {
  triggerAnnotationCompleted,
  triggerAnnotationModified,
} from '../../stateManagement/annotation/helpers/state';
import {
  drawCircle as drawCircleSvg,
  drawHandles as drawHandlesSvg,
  drawLinkedTextBox as drawLinkedTextBoxSvg,
} from '../../drawingSvg';
import { state } from '../../store';
import { Events } from '../../enums';
import { getViewportIdsWithToolToRender } from '../../utilities/viewportFilters';
import { getTextBoxCoordsCanvas } from '../../utilities/drawing';
import getWorldWidthAndHeightFromTwoPoints from '../../utilities/planar/getWorldWidthAndHeightFromTwoPoints';
import {
  resetElementCursor,
  hideElementCursor,
} from '../../cursors/elementCursor';
import {
  EventTypes,
  ToolHandle,
  TextBoxHandle,
  PublicToolProps,
  ToolProps,
  SVGDrawingHelper,
} from '../../types';
import { CircleROIAnnotation } from '../../types/ToolSpecificAnnotationTypes';
 
import triggerAnnotationRenderForViewportIds from '../../utilities/triggerAnnotationRenderForViewportIds';
import { pointInShapeCallback } from '../../utilities';
import { StyleSpecifier } from '../../types/AnnotationStyle';
import { getModalityUnit } from '../../utilities/getModalityUnit';
import { isViewportPreScaled } from '../../utilities/viewport/isViewportPreScaled';
import {
  getCanvasCircleCorners,
  getCanvasCircleRadius,
} from '../../utilities/math/circle';
import { pointInEllipse } from '../../utilities/math/ellipse';
import { BasicStatsCalculator } from '../../utilities/math/basic';
 
const { transformWorldToIndex } = csUtils;
 
/**
 * CircleROITool let you draw annotations that measures the statistics
 * such as area, max, mean and stdDev of an elliptical region of interest.
 * You can use CircleROITool in all perpendicular views (axial, sagittal, coronal).
 * Note: annotation tools in cornerstone3DTools exists in the exact location
 * in the physical 3d space, as a result, by default, all annotations that are
 * drawing in the same frameOfReference will get shared between viewports that
 * are in the same frameOfReference. Circle tool's text box lines are dynamically
 * generated based on the viewport's underlying Modality. For instance, if
 * the viewport is displaying CT, the text box will shown the statistics in Hounsfield units,
 * and if the viewport is displaying PET, the text box will show the statistics in
 * SUV units.
 *
 * The resulting annotation's data (statistics) and metadata (the
 * state of the viewport while drawing was happening) will get added to the
 * ToolState manager and can be accessed from the ToolState by calling getAnnotations
 * or similar methods.
 *
 * Changing tool configuration (see below) you can make the tool to draw the center
 * point circle with a given radius.
 *
 * ```js
 * cornerstoneTools.addTool(CircleROITool)
 *
 * const toolGroup = ToolGroupManager.createToolGroup('toolGroupId')
 *
 * toolGroup.addTool(CircleROITool.toolName)
 *
 * toolGroup.addViewport('viewportId', 'renderingEngineId')
 *
 * toolGroup.setToolActive(CircleROITool.toolName, {
 *   bindings: [
 *    {
 *       mouseButton: MouseBindings.Primary, // Left Click
 *     },
 *   ],
 * })
 *
 * // draw a circle at the center point with 4px radius.
 * toolGroup.setToolConfiguration(CircleROITool.toolName, {
 *   centerPointRadius: 4,
 * });
 * ```
 *
 * Read more in the Docs section of the website.
 */
 
class CircleROITool extends AnnotationTool {
  static toolName;
 
  touchDragCallback: any;
  mouseDragCallback: any;
  _throttledCalculateCachedStats: any;
  editData: {
    annotation: any;
    viewportIdsToRender: Array<string>;
    handleIndex?: number;
    movingTextBox?: boolean;
    newAnnotation?: boolean;
    hasMoved?: boolean;
  } | null;
  isDrawing: boolean;
  isHandleOutsideImage = false;
 
  constructor(
    toolProps: PublicToolProps = {},
    defaultToolProps: ToolProps = {
      supportedInteractionTypes: ['Mouse', 'Touch'],
      configuration: {
        shadow: true,
        preventHandleOutsideImage: false,
        // Radius of the circle to draw  at the center point of the circle.
        // Set this zero(0) in order not to draw the circle.
        centerPointRadius: 0,
        getTextLines: defaultGetTextLines,
        statsCalculator: BasicStatsCalculator,
      },
    }
  ) {
    super(toolProps, defaultToolProps);
 
    this._throttledCalculateCachedStats = throttle(
      this._calculateCachedStats,
      100,
      { trailing: true }
    );
  }
 
  /**
   * Based on the current position of the mouse and the current imageId to create
   * a CircleROI Annotation and stores it in the annotationManager
   *
   * @param evt -  EventTypes.NormalizedMouseEventType
   * @returns The annotation object.
   *
   */
  addNewAnnotation = (
    evt: EventTypes.InteractionEventType
  ): CircleROIAnnotation => {
    const eventDetail = evt.detail;
    const { currentPoints, element } = eventDetail;
    const worldPos = currentPoints.world;
 
    const enabledElement = getEnabledElement(element);
    const { viewport, renderingEngine } = enabledElement;
 
    this.isDrawing = true;
 
    const camera = viewport.getCamera();
    const { viewPlaneNormal, viewUp } = camera;
 
    const referencedImageId = this.getReferencedImageId(
      viewport,
      worldPos,
      viewPlaneNormal,
      viewUp
    );
 
    const FrameOfReferenceUID = viewport.getFrameOfReferenceUID();
 
    const annotation = {
      highlighted: true,
      invalidated: true,
      metadata: {
        toolName: this.getToolName(),
        viewPlaneNormal: <Types.Point3>[...viewPlaneNormal],
        viewUp: <Types.Point3>[...viewUp],
        FrameOfReferenceUID,
        referencedImageId,
      },
      data: {
        label: '',
        handles: {
          textBox: {
            hasMoved: false,
            worldPosition: <Types.Point3>[0, 0, 0],
            worldBoundingBox: {
              topLeft: <Types.Point3>[0, 0, 0],
              topRight: <Types.Point3>[0, 0, 0],
              bottomLeft: <Types.Point3>[0, 0, 0],
              bottomRight: <Types.Point3>[0, 0, 0],
            },
          },
          points: [[...worldPos], [...worldPos]] as [
            Types.Point3, // center
            Types.Point3 // end
          ],
          activeHandleIndex: null,
        },
        cachedStats: {},
      },
    };
 
    addAnnotation(annotation, element);
 
    const viewportIdsToRender = getViewportIdsWithToolToRender(
      element,
      this.getToolName()
    );
 
    this.editData = {
      annotation,
      viewportIdsToRender,
      newAnnotation: true,
      hasMoved: false,
    };
    this._activateDraw(element);
 
    hideElementCursor(element);
 
    evt.preventDefault();
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    return annotation;
  };
 
  /**
   * It returns if the canvas point is near the provided annotation in the provided
   * element or not. A proximity is passed to the function to determine the
   * proximity of the point to the annotation in number of pixels.
   *
   * @param element - HTML Element
   * @param annotation - Annotation
   * @param canvasCoords - Canvas coordinates
   * @param proximity - Proximity to tool to consider
   * @returns Boolean, whether the canvas point is near tool
   */
  isPointNearTool = (
    element: HTMLDivElement,
    annotation: CircleROIAnnotation,
    canvasCoords: Types.Point2,
    proximity: number
  ): boolean => {
    const enabledElement = getEnabledElement(element);
    const { viewport } = enabledElement;
 
    const { data } = annotation;
    const { points } = data.handles;
 
    // For some reason Typescript doesn't understand this, so we need to be
    // more specific about the type
    const canvasCoordinates = points.map((p) => viewport.worldToCanvas(p)) as [
      Types.Point2,
      Types.Point2
    ];
 
    const radius = getCanvasCircleRadius(canvasCoordinates);
    const radiusPoint = getCanvasCircleRadius([
      canvasCoordinates[0],
      canvasCoords,
    ]);
 
    if (Math.abs(radiusPoint - radius) < proximity / 2) {
      return true;
    }
 
    return false;
  };
 
  toolSelectedCallback = (
    evt: EventTypes.InteractionEventType,
    annotation: CircleROIAnnotation
  ): void => {
    const eventDetail = evt.detail;
    const { element } = eventDetail;
 
    annotation.highlighted = true;
 
    const viewportIdsToRender = getViewportIdsWithToolToRender(
      element,
      this.getToolName()
    );
 
    this.editData = {
      annotation,
      viewportIdsToRender,
      movingTextBox: false,
    };
 
    hideElementCursor(element);
 
    this._activateModify(element);
 
    const enabledElement = getEnabledElement(element);
    const { renderingEngine } = enabledElement;
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    evt.preventDefault();
  };
 
  handleSelectedCallback = (
    evt: EventTypes.InteractionEventType,
    annotation: CircleROIAnnotation,
    handle: ToolHandle
  ): void => {
    const eventDetail = evt.detail;
    const { element } = eventDetail;
    const { data } = annotation;
 
    annotation.highlighted = true;
 
    let movingTextBox = false;
    let handleIndex;
 
    if ((handle as TextBoxHandle).worldPosition) {
      movingTextBox = true;
    } else {
      const { points } = data.handles;
 
      handleIndex = points.findIndex((p) => p === handle);
    }
 
    // Find viewports to render on drag.
    const viewportIdsToRender = getViewportIdsWithToolToRender(
      element,
      this.getToolName()
    );
 
    this.editData = {
      annotation,
      viewportIdsToRender,
      handleIndex,
      movingTextBox,
    };
    this._activateModify(element);
 
    hideElementCursor(element);
 
    const enabledElement = getEnabledElement(element);
    const { renderingEngine } = enabledElement;
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    evt.preventDefault();
  };
 
  _endCallback = (evt: EventTypes.InteractionEventType): void => {
    const eventDetail = evt.detail;
    const { element } = eventDetail;
 
    const { annotation, viewportIdsToRender, newAnnotation, hasMoved } =
      this.editData;
    const { data } = annotation;
 
    Iif (newAnnotation && !hasMoved) {
      return;
    }
 
    // Circle ROI tool should reset its highlight to false on mouse up (as opposed
    // to other tools that keep it highlighted until the user moves. The reason
    // is that we use top-left and bottom-right handles to define the circle,
    // and they are by definition not in the circle on mouse up.
    annotation.highlighted = false;
    data.handles.activeHandleIndex = null;
 
    this._deactivateModify(element);
    this._deactivateDraw(element);
 
    resetElementCursor(element);
 
    const { renderingEngine } = getEnabledElement(element);
 
    this.editData = null;
    this.isDrawing = false;
 
    Iif (
      this.isHandleOutsideImage &&
      this.configuration.preventHandleOutsideImage
    ) {
      removeAnnotation(annotation.annotationUID);
    }
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    Eif (newAnnotation) {
      triggerAnnotationCompleted(annotation);
    }
  };
 
  _dragDrawCallback = (evt: EventTypes.InteractionEventType): void => {
    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 } = this.editData;
    const { data } = annotation;
 
    data.handles.points = [
      data.handles.points[0], // center stays
      canvasToWorld(currentCanvasPoints), // end point moves (changing radius)
    ];
 
    annotation.invalidated = true;
 
    this.editData.hasMoved = true;
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
  };
 
  _dragModifyCallback = (evt: EventTypes.InteractionEventType): void => {
    this.isDrawing = true;
    const eventDetail = evt.detail;
    const { element } = eventDetail;
 
    const { annotation, viewportIdsToRender, handleIndex, movingTextBox } =
      this.editData;
    const { data } = annotation;
 
    if (movingTextBox) {
      const { deltaPoints } = eventDetail;
      const worldPosDelta = deltaPoints.world;
 
      const { textBox } = data.handles;
      const { worldPosition } = textBox;
 
      worldPosition[0] += worldPosDelta[0];
      worldPosition[1] += worldPosDelta[1];
      worldPosition[2] += worldPosDelta[2];
 
      textBox.hasMoved = true;
    } else if (handleIndex === undefined) {
      // Moving tool
      const { deltaPoints } = eventDetail;
      const worldPosDelta = deltaPoints.world;
 
      const points = data.handles.points;
 
      points.forEach((point) => {
        point[0] += worldPosDelta[0];
        point[1] += worldPosDelta[1];
        point[2] += worldPosDelta[2];
      });
      annotation.invalidated = true;
    } else {
      this._dragHandle(evt);
      annotation.invalidated = true;
    }
 
    const enabledElement = getEnabledElement(element);
    const { renderingEngine } = enabledElement;
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
  };
 
  _dragHandle = (evt: EventTypes.InteractionEventType): void => {
    const eventDetail = evt.detail;
    const { element } = eventDetail;
    const enabledElement = getEnabledElement(element);
    const { canvasToWorld, worldToCanvas } = enabledElement.viewport;
 
    const { annotation, handleIndex } = this.editData;
    const { data } = annotation;
    const { points } = data.handles;
 
    const canvasCoordinates = points.map((p) => worldToCanvas(p));
 
    // Move current point in that direction.
    // Move other points in opposite direction.
 
    const { currentPoints } = eventDetail;
    const currentCanvasPoints = currentPoints.canvas;
 
    if (handleIndex === 0) {
      // Dragging center, move the circle ROI
      const dXCanvas = currentCanvasPoints[0] - canvasCoordinates[0][0];
      const dYCanvas = currentCanvasPoints[1] - canvasCoordinates[0][1];
 
      const canvasCenter = currentCanvasPoints as Types.Point2;
      const canvasEnd = <Types.Point2>[
        canvasCoordinates[1][0] + dXCanvas,
        canvasCoordinates[1][1] + dYCanvas,
      ];
 
      points[0] = canvasToWorld(canvasCenter);
      points[1] = canvasToWorld(canvasEnd);
    } else {
      // Dragging end point, center stays
      points[1] = canvasToWorld(currentCanvasPoints);
    }
  };
 
  cancel = (element: HTMLDivElement) => {
    // If it is mid-draw or mid-modify
    Eif (this.isDrawing) {
      this.isDrawing = false;
      this._deactivateDraw(element);
      this._deactivateModify(element);
      resetElementCursor(element);
 
      const { annotation, viewportIdsToRender, newAnnotation } = this.editData;
      const { data } = annotation;
 
      annotation.highlighted = false;
      data.handles.activeHandleIndex = null;
 
      const { renderingEngine } = getEnabledElement(element);
 
      triggerAnnotationRenderForViewportIds(
        renderingEngine,
        viewportIdsToRender
      );
 
      Eif (newAnnotation) {
        triggerAnnotationCompleted(annotation);
      }
 
      this.editData = null;
      return annotation.annotationUID;
    }
  };
 
  _activateModify = (element) => {
    state.isInteractingWithTool = true;
 
    element.addEventListener(Events.MOUSE_UP, this._endCallback);
    element.addEventListener(Events.MOUSE_DRAG, this._dragModifyCallback);
    element.addEventListener(Events.MOUSE_CLICK, this._endCallback);
 
    element.addEventListener(Events.TOUCH_END, this._endCallback);
    element.addEventListener(Events.TOUCH_DRAG, this._dragModifyCallback);
    element.addEventListener(Events.TOUCH_TAP, this._endCallback);
  };
 
  _deactivateModify = (element) => {
    state.isInteractingWithTool = false;
 
    element.removeEventListener(Events.MOUSE_UP, this._endCallback);
    element.removeEventListener(Events.MOUSE_DRAG, this._dragModifyCallback);
    element.removeEventListener(Events.MOUSE_CLICK, this._endCallback);
 
    element.removeEventListener(Events.TOUCH_END, this._endCallback);
    element.removeEventListener(Events.TOUCH_DRAG, this._dragModifyCallback);
    element.removeEventListener(Events.TOUCH_TAP, this._endCallback);
  };
 
  _activateDraw = (element) => {
    state.isInteractingWithTool = true;
 
    element.addEventListener(Events.MOUSE_UP, this._endCallback);
    element.addEventListener(Events.MOUSE_DRAG, this._dragDrawCallback);
    element.addEventListener(Events.MOUSE_MOVE, this._dragDrawCallback);
    element.addEventListener(Events.MOUSE_CLICK, this._endCallback);
 
    element.addEventListener(Events.TOUCH_END, this._endCallback);
    element.addEventListener(Events.TOUCH_DRAG, this._dragDrawCallback);
    element.addEventListener(Events.TOUCH_TAP, this._endCallback);
  };
 
  _deactivateDraw = (element) => {
    state.isInteractingWithTool = false;
 
    element.removeEventListener(Events.MOUSE_UP, this._endCallback);
    element.removeEventListener(Events.MOUSE_DRAG, this._dragDrawCallback);
    element.removeEventListener(Events.MOUSE_MOVE, this._dragDrawCallback);
    element.removeEventListener(Events.MOUSE_CLICK, this._endCallback);
 
    element.removeEventListener(Events.TOUCH_END, this._endCallback);
    element.removeEventListener(Events.TOUCH_DRAG, this._dragDrawCallback);
    element.removeEventListener(Events.TOUCH_TAP, this._endCallback);
  };
 
  /**
   * it is used to draw the circleROI annotation in each
   * request animation frame. It calculates the updated cached statistics if
   * data is invalidated and cache it.
   *
   * @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;
    const { viewport } = enabledElement;
    const { element } = viewport;
 
    let annotations = getAnnotations(this.getToolName(), element);
 
    Iif (!annotations?.length) {
      return renderStatus;
    }
 
    annotations = this.filterInteractableAnnotationsForElement(
      element,
      annotations
    );
 
    Iif (!annotations?.length) {
      return renderStatus;
    }
 
    const targetId = this.getTargetId(viewport);
 
    const renderingEngine = viewport.getRenderingEngine();
 
    const styleSpecifier: StyleSpecifier = {
      toolGroupId: this.toolGroupId,
      toolName: this.getToolName(),
      viewportId: enabledElement.viewport.id,
    };
 
    for (let i = 0; i < annotations.length; i++) {
      const annotation = annotations[i] as CircleROIAnnotation;
      const { annotationUID, data } = annotation;
      const { handles } = data;
      const { points, activeHandleIndex } = handles;
 
      styleSpecifier.annotationUID = annotationUID;
 
      const { color, lineWidth, lineDash } = this.getAnnotationStyle({
        annotation,
        styleSpecifier,
      });
 
      const canvasCoordinates = points.map((p) =>
        viewport.worldToCanvas(p)
      ) as [Types.Point2, Types.Point2];
      const center = canvasCoordinates[0];
      const radius = getCanvasCircleRadius(canvasCoordinates);
      const canvasCorners = getCanvasCircleCorners(canvasCoordinates);
 
      const { centerPointRadius } = this.configuration;
 
      // If cachedStats does not exist, or the unit is missing (as part of import/hydration etc.),
      // force to recalculate the stats from the points
      if (
        !data.cachedStats[targetId] ||
        data.cachedStats[targetId].areaUnit == null
      ) {
        data.cachedStats[targetId] = {
          Modality: null,
          area: null,
          max: null,
          mean: null,
          stdDev: null,
          areaUnit: null,
          radius: null,
          radiusUnit: null,
          perimeter: null,
        };
 
        this._calculateCachedStats(
          annotation,
          viewport,
          renderingEngine,
          enabledElement
        );
      } else Eif (annotation.invalidated) {
        this._throttledCalculateCachedStats(
          annotation,
          viewport,
          renderingEngine,
          enabledElement
        );
        // If the invalidated data is as a result of volumeViewport manipulation
        // of the tools, we need to invalidate the related viewports data, so that
        // when scrolling to the related slice in which the tool were manipulated
        // we re-render the correct tool position. This is due to stackViewport
        // which doesn't have the full volume at each time, and we are only working
        // on one slice at a time.
        if (viewport instanceof VolumeViewport) {
          const { referencedImageId } = annotation.metadata;
 
          // invalidate all the relevant stackViewports if they are not
          // at the referencedImageId
          for (const targetId in data.cachedStats) {
            if (targetId.startsWith('imageId')) {
              const viewports = renderingEngine.getStackViewports();
 
              const invalidatedStack = viewports.find((vp) => {
                // The stack viewport that contains the imageId but is not
                // showing it currently
                const referencedImageURI =
                  csUtils.imageIdToURI(referencedImageId);
                const hasImageURI = vp.hasImageURI(referencedImageURI);
                const currentImageURI = csUtils.imageIdToURI(
                  vp.getCurrentImageId()
                );
                return hasImageURI && currentImageURI !== referencedImageURI;
              });
 
              if (invalidatedStack) {
                delete data.cachedStats[targetId];
              }
            }
          }
        }
      }
 
      // If rendering engine has been destroyed while rendering
      Iif (!viewport.getRenderingEngine()) {
        console.warn('Rendering Engine has been destroyed');
        return renderStatus;
      }
 
      let activeHandleCanvasCoords;
 
      Iif (!isAnnotationVisible(annotationUID)) {
        continue;
      }
 
      Iif (
        !isAnnotationLocked(annotation) &&
        !this.editData &&
        activeHandleIndex !== null
      ) {
        // Not locked or creating and hovering over handle, so render handle.
        activeHandleCanvasCoords = [canvasCoordinates[activeHandleIndex]];
      }
 
      Iif (activeHandleCanvasCoords) {
        const handleGroupUID = '0';
        drawHandlesSvg(
          svgDrawingHelper,
          annotationUID,
          handleGroupUID,
          activeHandleCanvasCoords,
          {
            color,
          }
        );
      }
 
      const dataId = `${annotationUID}-circle`;
      const circleUID = '0';
      drawCircleSvg(
        svgDrawingHelper,
        annotationUID,
        circleUID,
        center,
        radius,
        {
          color,
          lineDash,
          lineWidth,
        },
        dataId
      );
 
      // draw center point, if "centerPointRadius" configuration is valid.
      Iif (centerPointRadius > 0) {
        if (radius > 3 * centerPointRadius) {
          drawCircleSvg(
            svgDrawingHelper,
            annotationUID,
            `${circleUID}-center`,
            center,
            centerPointRadius,
            {
              color,
              lineDash,
              lineWidth,
            }
          );
        }
      }
 
      renderStatus = true;
 
      const options = this.getLinkedTextBoxStyle(styleSpecifier, annotation);
      Iif (!options.visibility) {
        data.handles.textBox = {
          hasMoved: false,
          worldPosition: <Types.Point3>[0, 0, 0],
          worldBoundingBox: {
            topLeft: <Types.Point3>[0, 0, 0],
            topRight: <Types.Point3>[0, 0, 0],
            bottomLeft: <Types.Point3>[0, 0, 0],
            bottomRight: <Types.Point3>[0, 0, 0],
          },
        };
        continue;
      }
 
      const textLines = this.configuration.getTextLines(data, targetId);
      Iif (!textLines || textLines.length === 0) {
        continue;
      }
 
      // Poor man's cached?
      let canvasTextBoxCoords;
 
      Eif (!data.handles.textBox.hasMoved) {
        canvasTextBoxCoords = getTextBoxCoordsCanvas(canvasCorners);
 
        data.handles.textBox.worldPosition =
          viewport.canvasToWorld(canvasTextBoxCoords);
      }
 
      const textBoxPosition = viewport.worldToCanvas(
        data.handles.textBox.worldPosition
      );
 
      const textBoxUID = '1';
      const boundingBox = drawLinkedTextBoxSvg(
        svgDrawingHelper,
        annotationUID,
        textBoxUID,
        textLines,
        textBoxPosition,
        canvasCoordinates,
        {},
        options
      );
 
      const { x: left, y: top, width, height } = boundingBox;
 
      data.handles.textBox.worldBoundingBox = {
        topLeft: viewport.canvasToWorld([left, top]),
        topRight: viewport.canvasToWorld([left + width, top]),
        bottomLeft: viewport.canvasToWorld([left, top + height]),
        bottomRight: viewport.canvasToWorld([left + width, top + height]),
      };
    }
 
    return renderStatus;
  };
 
  _calculateCachedStats = (
    annotation,
    viewport,
    renderingEngine,
    enabledElement
  ) => {
    const data = annotation.data;
    const { element } = viewport;
 
    const { points } = data.handles;
 
    const canvasCoordinates = points.map((p) => viewport.worldToCanvas(p));
    const { viewPlaneNormal, viewUp } = viewport.getCamera();
 
    const [topLeftCanvas, bottomRightCanvas] = <Array<Types.Point2>>(
      getCanvasCircleCorners(canvasCoordinates)
    );
 
    const topLeftWorld = viewport.canvasToWorld(topLeftCanvas);
    const bottomRightWorld = viewport.canvasToWorld(bottomRightCanvas);
    const { cachedStats } = data;
 
    const targetIds = Object.keys(cachedStats);
    const worldPos1 = topLeftWorld;
    const worldPos2 = bottomRightWorld;
 
    for (let i = 0; i < targetIds.length; i++) {
      const targetId = targetIds[i];
 
      const image = this.getTargetIdImage(targetId, renderingEngine);
 
      // If image does not exists for the targetId, skip. This can be due
      // to various reasons such as if the target was a volumeViewport, and
      // the volumeViewport has been decached in the meantime.
      Iif (!image) {
        continue;
      }
 
      const { dimensions, imageData, metadata, hasPixelSpacing } = image;
 
      const pos1Index = transformWorldToIndex(imageData, worldPos1);
 
      pos1Index[0] = Math.floor(pos1Index[0]);
      pos1Index[1] = Math.floor(pos1Index[1]);
      pos1Index[2] = Math.floor(pos1Index[2]);
 
      const pos2Index = transformWorldToIndex(imageData, worldPos2);
 
      pos2Index[0] = Math.floor(pos2Index[0]);
      pos2Index[1] = Math.floor(pos2Index[1]);
      pos2Index[2] = Math.floor(pos2Index[2]);
 
      // Check if one of the indexes are inside the volume, this then gives us
      // Some area to do stats over.
 
      if (this._isInsideVolume(pos1Index, pos2Index, dimensions)) {
        const iMin = Math.min(pos1Index[0], pos2Index[0]);
        const iMax = Math.max(pos1Index[0], pos2Index[0]);
 
        const jMin = Math.min(pos1Index[1], pos2Index[1]);
        const jMax = Math.max(pos1Index[1], pos2Index[1]);
 
        const kMin = Math.min(pos1Index[2], pos2Index[2]);
        const kMax = Math.max(pos1Index[2], pos2Index[2]);
 
        const boundsIJK = [
          [iMin, iMax],
          [jMin, jMax],
          [kMin, kMax],
        ] as [Types.Point2, Types.Point2, Types.Point2];
 
        const center = [
          (topLeftWorld[0] + bottomRightWorld[0]) / 2,
          (topLeftWorld[1] + bottomRightWorld[1]) / 2,
          (topLeftWorld[2] + bottomRightWorld[2]) / 2,
        ] as Types.Point3;
 
        const ellipseObj = {
          center,
          xRadius: Math.abs(topLeftWorld[0] - bottomRightWorld[0]) / 2,
          yRadius: Math.abs(topLeftWorld[1] - bottomRightWorld[1]) / 2,
          zRadius: Math.abs(topLeftWorld[2] - bottomRightWorld[2]) / 2,
        };
 
        const { worldWidth, worldHeight } = getWorldWidthAndHeightFromTwoPoints(
          viewPlaneNormal,
          viewUp,
          worldPos1,
          worldPos2
        );
        const isEmptyArea = worldWidth === 0 && worldHeight === 0;
        const handles = [pos1Index, pos2Index];
        const { scale, units, areaUnits } = getCalibratedLengthUnitsAndScale(
          image,
          handles
        );
        const aspect = getCalibratedAspect(image);
        const area = Math.abs(
          Math.PI *
            (worldWidth / scale / 2) *
            (worldHeight / aspect / scale / 2)
        );
 
        const modalityUnitOptions = {
          isPreScaled: isViewportPreScaled(viewport, targetId),
          isSuvScaled: this.isSuvScaled(
            viewport,
            targetId,
            annotation.metadata.referencedImageId
          ),
        };
 
        const modalityUnit = getModalityUnit(
          metadata.Modality,
          annotation.metadata.referencedImageId,
          modalityUnitOptions
        );
 
        const pointsInShape = pointInShapeCallback(
          imageData,
          (pointLPS) =>
            pointInEllipse(ellipseObj, pointLPS, {
              fast: true,
            }),
          this.configuration.statsCalculator.statsCallback,
          boundsIJK
        );
 
        const stats = this.configuration.statsCalculator.getStatistics();
 
        cachedStats[targetId] = {
          Modality: metadata.Modality,
          area,
          mean: stats.mean?.value,
          max: stats.max?.value,
          stdDev: stats.stdDev?.value,
          statsArray: stats.array,
          pointsInShape: pointsInShape,
          isEmptyArea,
          areaUnit: areaUnits,
          radius: worldWidth / 2 / scale,
          radiusUnit: units,
          perimeter: (2 * Math.PI * (worldWidth / 2)) / scale,
          modalityUnit,
        };
      } else E{
        this.isHandleOutsideImage = true;
 
        cachedStats[targetId] = {
          Modality: metadata.Modality,
        };
      }
    }
 
    annotation.invalidated = false;
 
    // Dispatching annotation modified
    triggerAnnotationModified(annotation, element);
 
    return cachedStats;
  };
 
  _isInsideVolume = (index1, index2, dimensions) => {
    return (
      csUtils.indexWithinDimensions(index1, dimensions) &&
      csUtils.indexWithinDimensions(index2, dimensions)
    );
  };
}
 
function defaultGetTextLines(data, targetId): string[] {
  const cachedVolumeStats = data.cachedStats[targetId];
  const {
    radius,
    radiusUnit,
    area,
    mean,
    stdDev,
    max,
    isEmptyArea,
    areaUnit,
    modalityUnit,
  } = cachedVolumeStats;
  const textLines: string[] = [];
 
  Eif (radius) {
    const radiusLine = isEmptyArea
      ? `Radius: Oblique not supported`
      : `Radius: ${roundNumber(radius)} ${radiusUnit}`;
    textLines.push(radiusLine);
  }
 
  Eif (area) {
    const areaLine = isEmptyArea
      ? `Area: Oblique not supported`
      : `Area: ${roundNumber(area)} ${areaUnit}`;
    textLines.push(areaLine);
  }
 
  Eif (mean) {
    textLines.push(`Mean: ${roundNumber(mean)} ${modalityUnit}`);
  }
 
  Eif (max) {
    textLines.push(`Max: ${roundNumber(max)} ${modalityUnit}`);
  }
 
  if (stdDev) {
    textLines.push(`Std Dev: ${roundNumber(stdDev)} ${modalityUnit}`);
  }
 
  return textLines;
}
 
CircleROITool.toolName = 'CircleROI';
export default CircleROITool;