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

84.52% Statements 273/323
56.16% Branches 41/73
95.45% Functions 21/22
84.32% Lines 269/319

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                                                                                                              1x                                                                                                                                       11x   11x                             11x     11x 11x 11x   11x 11x   11x   11x 11x   11x             11x   11x                                                                     11x   11x         11x               11x   11x   11x   11x   11x                           11x           6x 6x   6x 6x   6x 6x   6x         6x 6x   6x         6x 6x           11x       6x 6x   6x   6x         6x           6x   6x   6x 6x   6x   6x     11x         2x 2x 2x   2x   2x     2x     2x       2x         2x           2x   2x   2x 2x   2x   2x     11x 17x 17x     17x 17x   17x       17x   17x 17x   17x   17x   17x 17x   17x             17x   17x 11x       11x 17x   17x 17x     17x 17x   17x                         17x   4x 4x   4x   4x 16x 16x 16x   4x     13x 13x 13x 13x   13x     13x                       13x         13x 13x   13x 13x   13x 13x   13x 13x   13x                                               13x     17x   17x 17x   17x     11x   2x 2x 2x 2x 2x   2x   2x   2x 2x   2x   2x         2x       2x 2x           11x 11x   11x 11x 11x 11x   11x 11x 11x           11x 19x   19x 19x 19x 19x   19x 19x 19x           11x 8x   8x 8x 8x   8x 8x 8x           11x 19x   19x 19x 19x   19x 19x 19x                     11x       13x 13x 13x   13x   13x       13x         13x       13x 13x   13x           13x 13x 13x 13x 52x   13x   13x         13x       13x       11x                 11x             2x                                                                                           13x             13x       13x                 13x                           13x 13x 13x                           13x   13x 13x                           13x 13x       13x 13x   13x       13x       13x 13x                     13x   13x               13x     11x               6x   6x                                     11x             11x 11x 11x   11x 11x 11x   11x   11x 11x   11x         11x       11x   11x   11x 11x 11x   11x   11x 11x 11x         11x 11x       11x 11x   11x 11x   11x 11x   11x           11x             11x 11x         11x   11x                   11x           11x   961x         11x   11x                                     11x     11x   11x     11x 11x                             13x 13x   13x       13x   13x 13x 13x 13x   13x     1x    
import { AnnotationTool } from '../base';
 
import {
  getEnabledElement,
  VolumeViewport,
  utilities as csUtils,
} from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
 
import { getCalibratedLengthUnitsAndScale } from '../../utilities/getCalibratedUnits';
import { roundNumber } from '../../utilities';
import throttle from '../../utilities/throttle';
import {
  addAnnotation,
  getAnnotations,
  removeAnnotation,
} from '../../stateManagement';
import { isAnnotationLocked } from '../../stateManagement/annotation/annotationLocking';
import { isAnnotationVisible } from '../../stateManagement/annotation/annotationVisibility';
import {
  triggerAnnotationCompleted,
  triggerAnnotationModified,
} from '../../stateManagement/annotation/helpers/state';
import {
  drawHandles as drawHandlesSvg,
  drawLinkedTextBox as drawLinkedTextBoxSvg,
  drawRect as drawRectSvg,
} from '../../drawingSvg';
import { state } from '../../store';
import { Events } from '../../enums';
import { getViewportIdsWithToolToRender } from '../../utilities/viewportFilters';
import * as rectangle from '../../utilities/math/rectangle';
import { getTextBoxCoordsCanvas } from '../../utilities/drawing';
import getWorldWidthAndHeightFromCorners from '../../utilities/planar/getWorldWidthAndHeightFromCorners';
import {
  resetElementCursor,
  hideElementCursor,
} from '../../cursors/elementCursor';
import triggerAnnotationRenderForViewportIds from '../../utilities/triggerAnnotationRenderForViewportIds';
 
import {
  EventTypes,
  ToolHandle,
  TextBoxHandle,
  ToolProps,
  PublicToolProps,
  SVGDrawingHelper,
} from '../../types';
import { RectangleROIAnnotation } from '../../types/ToolSpecificAnnotationTypes';
import { StyleSpecifier } from '../../types/AnnotationStyle';
import { getModalityUnit } from '../../utilities/getModalityUnit';
import { isViewportPreScaled } from '../../utilities/viewport/isViewportPreScaled';
import { pointInShapeCallback } from '../../utilities/';
import { BasicStatsCalculator } from '../../utilities/math/basic';
 
const { transformWorldToIndex } = csUtils;
 
/**
 * RectangleROIAnnotation let you draw annotations that measures the statistics
 * such as area, max, mean and stdDev of a Rectangular region of interest.
 * You can use RectangleROIAnnotation 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. RectangleROI 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.
 *
 * ```js
 * cornerstoneTools.addTool(RectangleROITool)
 *
 * const toolGroup = ToolGroupManager.createToolGroup('toolGroupId')
 *
 * toolGroup.addTool(RectangleROITool.toolName)
 *
 * toolGroup.addViewport('viewportId', 'renderingEngineId')
 *
 * toolGroup.setToolActive(RectangleROITool.toolName, {
 *   bindings: [
 *    {
 *       mouseButton: MouseBindings.Primary, // Left Click
 *     },
 *   ],
 * })
 * ```
 *
 * Read more in the Docs section of the website.
 */
 
class RectangleROITool extends AnnotationTool {
  static toolName;
 
  _throttledCalculateCachedStats: any;
  editData: {
    annotation: any;
    viewportIdsToRender: string[];
    handleIndex?: number;
    movingTextBox?: boolean;
    newAnnotation?: boolean;
    hasMoved?: boolean;
  } | null;
  isDrawing: boolean;
  isHandleOutsideImage: boolean;
 
  constructor(
    toolProps: PublicToolProps = {},
    defaultToolProps: ToolProps = {
      supportedInteractionTypes: ['Mouse', 'Touch'],
      configuration: {
        shadow: true,
        preventHandleOutsideImage: false,
        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 RectangleROI Annotation and stores it in the annotationManager
   *
   * @param evt -  EventTypes.NormalizedMouseEventType
   * @returns The annotation object.
   *
   */
  addNewAnnotation = (
    evt: EventTypes.InteractionEventType
  ): RectangleROIAnnotation => {
    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 = {
      invalidated: true,
      highlighted: true,
      metadata: {
        toolName: this.getToolName(),
        viewPlaneNormal: <Types.Point3>[...viewPlaneNormal],
        viewUp: <Types.Point3>[...viewUp],
        FrameOfReferenceUID,
        referencedImageId,
      },
      data: {
        label: '',
        handles: {
          points: [
            <Types.Point3>[...worldPos],
            <Types.Point3>[...worldPos],
            <Types.Point3>[...worldPos],
            <Types.Point3>[...worldPos],
          ],
          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],
            },
          },
          activeHandleIndex: null,
        },
        cachedStats: {},
      },
    };
 
    addAnnotation(annotation, element);
 
    const viewportIdsToRender = getViewportIdsWithToolToRender(
      element,
      this.getToolName()
    );
 
    this.editData = {
      annotation,
      viewportIdsToRender,
      handleIndex: 3,
      movingTextBox: false,
      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: RectangleROIAnnotation,
    canvasCoords: Types.Point2,
    proximity: number
  ): boolean => {
    const enabledElement = getEnabledElement(element);
    const { viewport } = enabledElement;
 
    const { data } = annotation;
    const { points } = data.handles;
 
    const canvasPoint1 = viewport.worldToCanvas(points[0]);
    const canvasPoint2 = viewport.worldToCanvas(points[3]);
 
    const rect = this._getRectangleImageCoordinates([
      canvasPoint1,
      canvasPoint2,
    ]);
 
    const point = [canvasCoords[0], canvasCoords[1]];
    const { left, top, width, height } = rect;
 
    const distanceToPoint = rectangle.distanceToPoint(
      [left, top, width, height],
      point as Types.Point2
    );
 
    Eif (distanceToPoint <= proximity) {
      return true;
    }
 
    return false;
  };
 
  toolSelectedCallback = (
    evt: EventTypes.InteractionEventType,
    annotation: RectangleROIAnnotation
  ): void => {
    const eventDetail = evt.detail;
    const { element } = eventDetail;
 
    annotation.highlighted = true;
 
    const viewportIdsToRender = getViewportIdsWithToolToRender(
      element,
      this.getToolName()
    );
 
    this.editData = {
      annotation,
      viewportIdsToRender,
      movingTextBox: false,
    };
 
    this._activateModify(element);
 
    hideElementCursor(element);
 
    const enabledElement = getEnabledElement(element);
    const { renderingEngine } = enabledElement;
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    evt.preventDefault();
  };
 
  handleSelectedCallback = (
    evt: EventTypes.InteractionEventType,
    annotation: RectangleROIAnnotation,
    handle: ToolHandle
  ): void => {
    const eventDetail = evt.detail;
    const { element } = eventDetail;
    const { data } = annotation;
 
    annotation.highlighted = true;
 
    let movingTextBox = false;
    let handleIndex;
 
    Iif ((handle as TextBoxHandle).worldPosition) {
      movingTextBox = true;
    } else {
      handleIndex = data.handles.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;
    }
 
    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);
 
    if (newAnnotation) {
      triggerAnnotationCompleted(annotation);
    }
  };
 
  _dragCallback = (evt: EventTypes.InteractionEventType): void => {
    this.isDrawing = true;
 
    const eventDetail = evt.detail;
    const { element } = eventDetail;
 
    const { annotation, viewportIdsToRender, handleIndex, movingTextBox } =
      this.editData;
    const { data } = annotation;
 
    Iif (movingTextBox) {
      // Drag mode - Move the text boxes world position
      const { deltaPoints } = eventDetail as EventTypes.MouseDragEventDetail;
      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) {
      // Drag mode - Moving tool, so move all points by the world points delta
      const { deltaPoints } = eventDetail as EventTypes.MouseDragEventDetail;
      const worldPosDelta = deltaPoints.world;
 
      const { points } = data.handles;
 
      points.forEach((point) => {
        point[0] += worldPosDelta[0];
        point[1] += worldPosDelta[1];
        point[2] += worldPosDelta[2];
      });
      annotation.invalidated = true;
    } else {
      // Moving handle.
      const { currentPoints } = eventDetail;
      const enabledElement = getEnabledElement(element);
      const { worldToCanvas, canvasToWorld } = enabledElement.viewport;
      const worldPos = currentPoints.world;
 
      const { points } = data.handles;
 
      // Move this handle.
      points[handleIndex] = [...worldPos];
 
      let bottomLeftCanvas;
      let bottomRightCanvas;
      let topLeftCanvas;
      let topRightCanvas;
 
      let bottomLeftWorld;
      let bottomRightWorld;
      let topLeftWorld;
      let topRightWorld;
 
      switch (handleIndex) {
        case 0:
        case 3:
          // Moving bottomLeft or topRight
 
          bottomLeftCanvas = worldToCanvas(points[0]);
          topRightCanvas = worldToCanvas(points[3]);
 
          bottomRightCanvas = [topRightCanvas[0], bottomLeftCanvas[1]];
          topLeftCanvas = [bottomLeftCanvas[0], topRightCanvas[1]];
 
          bottomRightWorld = canvasToWorld(bottomRightCanvas);
          topLeftWorld = canvasToWorld(topLeftCanvas);
 
          points[1] = bottomRightWorld;
          points[2] = topLeftWorld;
 
          break;
        case 1:
        case 2:
          // Moving bottomRight or topLeft
          bottomRightCanvas = worldToCanvas(points[1]);
          topLeftCanvas = worldToCanvas(points[2]);
 
          bottomLeftCanvas = <Types.Point2>[
            topLeftCanvas[0],
            bottomRightCanvas[1],
          ];
          topRightCanvas = <Types.Point2>[
            bottomRightCanvas[0],
            topLeftCanvas[1],
          ];
 
          bottomLeftWorld = canvasToWorld(bottomLeftCanvas);
          topRightWorld = canvasToWorld(topRightCanvas);
 
          points[0] = bottomLeftWorld;
          points[3] = topRightWorld;
 
          break;
      }
      annotation.invalidated = true;
    }
 
    this.editData.hasMoved = true;
 
    const enabledElement = getEnabledElement(element);
    const { renderingEngine } = enabledElement;
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
  };
 
  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
      );
 
      Iif (newAnnotation) {
        triggerAnnotationCompleted(annotation);
      }
 
      this.editData = null;
      return annotation.annotationUID;
    }
  };
  /**
   * Add event handlers for the modify event loop, and prevent default event prapogation.
   */
  _activateDraw = (element) => {
    state.isInteractingWithTool = true;
 
    element.addEventListener(Events.MOUSE_UP, this._endCallback);
    element.addEventListener(Events.MOUSE_DRAG, this._dragCallback);
    element.addEventListener(Events.MOUSE_MOVE, this._dragCallback);
    element.addEventListener(Events.MOUSE_CLICK, this._endCallback);
 
    element.addEventListener(Events.TOUCH_END, this._endCallback);
    element.addEventListener(Events.TOUCH_DRAG, this._dragCallback);
    element.addEventListener(Events.TOUCH_TAP, this._endCallback);
  };
 
  /**
   * Add event handlers for the modify event loop, and prevent default event prapogation.
   */
  _deactivateDraw = (element) => {
    state.isInteractingWithTool = false;
 
    element.removeEventListener(Events.MOUSE_UP, this._endCallback);
    element.removeEventListener(Events.MOUSE_DRAG, this._dragCallback);
    element.removeEventListener(Events.MOUSE_MOVE, this._dragCallback);
    element.removeEventListener(Events.MOUSE_CLICK, this._endCallback);
 
    element.removeEventListener(Events.TOUCH_END, this._endCallback);
    element.removeEventListener(Events.TOUCH_DRAG, this._dragCallback);
    element.removeEventListener(Events.TOUCH_TAP, this._endCallback);
  };
 
  /**
   * Add event handlers for the modify event loop, and prevent default event prapogation.
   */
  _activateModify = (element) => {
    state.isInteractingWithTool = true;
 
    element.addEventListener(Events.MOUSE_UP, this._endCallback);
    element.addEventListener(Events.MOUSE_DRAG, this._dragCallback);
    element.addEventListener(Events.MOUSE_CLICK, this._endCallback);
 
    element.addEventListener(Events.TOUCH_END, this._endCallback);
    element.addEventListener(Events.TOUCH_DRAG, this._dragCallback);
    element.addEventListener(Events.TOUCH_TAP, this._endCallback);
  };
 
  /**
   * Remove event handlers for the modify event loop, and enable default event propagation.
   */
  _deactivateModify = (element) => {
    state.isInteractingWithTool = false;
 
    element.removeEventListener(Events.MOUSE_UP, this._endCallback);
    element.removeEventListener(Events.MOUSE_DRAG, this._dragCallback);
    element.removeEventListener(Events.MOUSE_CLICK, this._endCallback);
 
    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 rectangleROI 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 RectangleROIAnnotation;
      const { annotationUID, data } = annotation;
      const { points, activeHandleIndex } = data.handles;
      const canvasCoordinates = points.map((p) => viewport.worldToCanvas(p));
 
      styleSpecifier.annotationUID = annotationUID;
 
      const { color, lineWidth, lineDash } = this.getAnnotationStyle({
        annotation,
        styleSpecifier,
      });
 
      const { viewPlaneNormal, viewUp } = viewport.getCamera();
 
      // 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,
        };
 
        this._calculateCachedStats(
          annotation,
          viewPlaneNormal,
          viewUp,
          renderingEngine,
          enabledElement
        );
      } else Iif (annotation.invalidated) {
        this._throttledCalculateCachedStats(
          annotation,
          viewPlaneNormal,
          viewUp,
          renderingEngine,
          enabledElement
        );
 
        // If the invalidated data is as a result of volumeViewport manipulation
        // of the tools, we need to invalidate the related stackViewports data if
        // they are not at the referencedImageId, 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}-rect`;
      const rectangleUID = '0';
      drawRectSvg(
        svgDrawingHelper,
        annotationUID,
        rectangleUID,
        canvasCoordinates[0],
        canvasCoordinates[3],
        {
          color,
          lineDash,
          lineWidth,
        },
        dataId
      );
 
      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;
      }
 
      Eif (!data.handles.textBox.hasMoved) {
        const canvasTextBoxCoords = getTextBoxCoordsCanvas(canvasCoordinates);
 
        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;
  };
 
  _getRectangleImageCoordinates = (
    points: Array<Types.Point2>
  ): {
    left: number;
    top: number;
    width: number;
    height: number;
  } => {
    const [point0, point1] = points;
 
    return {
      left: Math.min(point0[0], point1[0]),
      top: Math.min(point0[1], point1[1]),
      width: Math.abs(point0[0] - point1[0]),
      height: Math.abs(point0[1] - point1[1]),
    };
  };
 
  /**
   * _calculateCachedStats - For each volume in the frame of reference that a
   * tool instance in particular viewport defines as its target volume, find the
   * volume coordinates (i,j,k) being probed by the two corners. One of i,j or k
   * will be constant across the two points. In the other two directions iterate
   * over the voxels and calculate the first and second-order statistics.
   *
   * @param data - The annotation tool-specific data.
   * @param viewPlaneNormal - The normal vector of the camera.
   * @param viewUp - The viewUp vector of the camera.
   */
  _calculateCachedStats = (
    annotation,
    viewPlaneNormal,
    viewUp,
    renderingEngine,
    enabledElement
  ) => {
    const { data } = annotation;
    const { viewport } = enabledElement;
    const { element } = viewport;
 
    const worldPos1 = data.handles.points[0];
    const worldPos2 = data.handles.points[3];
    const { cachedStats } = data;
 
    const targetIds = Object.keys(cachedStats);
 
    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 } = 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)) {
        this.isHandleOutsideImage = false;
 
        // Calculate index bounds to iterate over
 
        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 { worldWidth, worldHeight } = getWorldWidthAndHeightFromCorners(
          viewPlaneNormal,
          viewUp,
          worldPos1,
          worldPos2
        );
 
        const handles = [pos1Index, pos2Index];
        const { scale, areaUnits } = getCalibratedLengthUnitsAndScale(
          image,
          handles
        );
 
        const area = Math.abs(worldWidth * worldHeight) / (scale * scale);
 
        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,
          () => true,
          this.configuration.statsCalculator.statsCallback,
          boundsIJK
        );
 
        const stats = this.configuration.statsCalculator.getStatistics();
 
        cachedStats[targetId] = {
          Modality: metadata.Modality,
          area,
          mean: stats.mean?.value,
          stdDev: stats.stdDev?.value,
          max: stats.max?.value,
          statsArray: stats.array,
          pointsInShape: pointsInShape,
          areaUnit: areaUnits,
          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)
    );
  };
}
 
/**
 * _getTextLines - Returns the Area, mean and std deviation of the area of the
 * target volume enclosed by the rectangle.
 *
 * @param data - The annotation tool-specific data.
 * @param targetId - The volumeId of the volume to display the stats for.
 */
function defaultGetTextLines(data, targetId: string): string[] {
  const cachedVolumeStats = data.cachedStats[targetId];
  const { area, mean, max, stdDev, areaUnit, modalityUnit } = cachedVolumeStats;
 
  Iif (mean === undefined) {
    return;
  }
 
  const textLines: string[] = [];
 
  textLines.push(`Area: ${roundNumber(area)} ${areaUnit}`);
  textLines.push(`Mean: ${roundNumber(mean)} ${modalityUnit}`);
  textLines.push(`Max: ${roundNumber(max)} ${modalityUnit}`);
  textLines.push(`Std Dev: ${roundNumber(stdDev)} ${modalityUnit}`);
 
  return textLines;
}
 
RectangleROITool.toolName = 'RectangleROI';
export default RectangleROITool;