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

87.74% Statements 315/359
71% Branches 71/100
95.65% Functions 22/23
87.53% Lines 309/353

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 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212                                                                                                                                                                  7x   7x                             7x     7x       7x 7x 7x 7x 7x 7x   7x 7x   7x 7x   7x             7x   7x                                                           7x   7x         7x               7x   7x   7x   7x                           7x           2x 2x 2x   2x             2x 2x           7x             2x 2x   2x   2x         2x 2x   2x             2x               2x   2x   2x   2x                 1x 1x 1x   1x   1x     1x     2x       1x         1x           1x   1x   1x 1x   1x   1x     7x     23x 23x     23x   23x 23x     7x         16x 7x     7x 7x     9x 9x   9x 9x 9x   9x 9x   9x             9x   9x 6x     9x 9x                 7x     14x 14x 14x 14x 14x   14x     4x 4x     4x     10x   3x 3x       3x 3x         7x 7x     7x 7x     7x     9x 9x 9x                 9x 9x   9x                         9x         1x 1x 1x     1x 1x 1x 2x 2x 2x                     1x     8x 8x   8x 8x     9x   9x 9x   9x     7x   1x       1x 1x 1x 1x   1x 1x   1x         1x 1x   1x 1x   1x   1x 1x     1x 1x 1x     7x 3x   3x       3x       3x                 7x 10x   10x       10x       10x                 7x 7x   7x       7x       7x       7x       7x                 7x 10x   10x       10x       10x       10x       10x                                 7x       17x   17x 17x   17x     17x 4x     13x         13x       13x 13x   13x             13x 13x 13x 13x   13x   13x         42x     13x       12x                                               12x 1x                   13x                   13x         13x                               13x       13x         13x 13x                         13x     13x 5x     8x   8x                         8x 8x 8x 8x                 8x 8x   8x                                                           8x 3x     5x 5x                           5x   5x 5x   5x       5x       5x 5x                     5x   5x             5x                                                                                     8x       12x     12x 5x     7x 7x 7x                   7x 14x 28x       28x 9x 9x 9x 9x 9x       7x 7x   7x 28x     7x       7x         7x 7x     7x             7x 7x   7x 7x   7x                                         7x     7x   7x     7x 4x 4x 4x 4x 4x   4x                     4x                     4x           4x           4x 4x   4x 4x       4x               7x                         7x   7x 7x   7x 7x   7x   7x       7x   7x 7x     7x       7x     7x       7x               7x       7x     7x       7x           7x       7x     7x       7x               7x       7x     7x       7x         7x                       5x 5x   5x       5x   5x     1x    
import { vec3 } from 'gl-matrix';
import { Events } from '../../enums';
import { getEnabledElement } from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
 
import { AnnotationTool } from '../base';
import throttle from '../../utilities/throttle';
import {
  addAnnotation,
  getAnnotations,
  removeAnnotation,
} from '../../stateManagement/annotation/annotationState';
import { isAnnotationLocked } from '../../stateManagement/annotation/annotationLocking';
import {
  triggerAnnotationCompleted,
  triggerAnnotationModified,
} from '../../stateManagement/annotation/helpers/state';
import * as lineSegment from '../../utilities/math/line';
import angleBetweenLines from '../../utilities/math/angle/angleBetweenLines';
import { midPoint2 } from '../../utilities/math/midPoint';
 
import {
  drawHandles as drawHandlesSvg,
  drawLine as drawLineSvg,
  drawLinkedTextBox as drawLinkedTextBoxSvg,
  drawTextBox as drawTextBoxSvg,
} from '../../drawingSvg';
import { state } from '../../store';
import { getViewportIdsWithToolToRender } from '../../utilities/viewportFilters';
import { getTextBoxCoordsCanvas } from '../../utilities/drawing';
import triggerAnnotationRenderForViewportIds from '../../utilities/triggerAnnotationRenderForViewportIds';
 
import {
  resetElementCursor,
  hideElementCursor,
} from '../../cursors/elementCursor';
 
import {
  EventTypes,
  ToolHandle,
  TextBoxHandle,
  PublicToolProps,
  ToolProps,
  InteractionTypes,
  SVGDrawingHelper,
} from '../../types';
import { CobbAngleAnnotation } from '../../types/ToolSpecificAnnotationTypes';
import { StyleSpecifier } from '../../types/AnnotationStyle';
 
class CobbAngleTool extends AnnotationTool {
  static toolName;
 
  public touchDragCallback: any;
  public mouseDragCallback: any;
  angleStartedNotYetCompleted: boolean;
  _throttledCalculateCachedStats: any;
  editData: {
    annotation: any;
    viewportIdsToRender: string[];
    handleIndex?: number;
    movingTextBox?: boolean;
    newAnnotation?: boolean;
    hasMoved?: boolean;
    isNearFirstLine?: boolean;
    isNearSecondLine?: boolean;
  } | null;
  isDrawing: boolean;
  isHandleOutsideImage: boolean;
 
  constructor(
    toolProps: PublicToolProps = {},
    defaultToolProps: ToolProps = {
      supportedInteractionTypes: ['Mouse', 'Touch'],
      configuration: {
        shadow: true,
        preventHandleOutsideImage: false,
        getTextLines: defaultGetTextLines,
        showArcLines: false,
      },
    }
  ) {
    super(toolProps, defaultToolProps);
 
    this._throttledCalculateCachedStats = throttle(
      this._calculateCachedStats,
      25,
      { trailing: true }
    );
  }
 
  /**
   * Based on the current position of the mouse and the current imageId to create
   * a Length Annotation and stores it in the annotationManager
   *
   * @param evt -  EventTypes.NormalizedMouseEventType
   * @returns The annotation object.
   *
   */
  addNewAnnotation = (
    evt: EventTypes.MouseDownActivateEventType
  ): CobbAngleAnnotation => {
    Iif (this.angleStartedNotYetCompleted) {
      return;
    }
 
    this.angleStartedNotYetCompleted = true;
    const eventDetail = evt.detail;
    const { currentPoints, element } = eventDetail;
    const worldPos = currentPoints.world;
    const enabledElement = getEnabledElement(element);
    const { viewport, renderingEngine } = enabledElement;
 
    hideElementCursor(element);
    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: {
        handles: {
          points: [<Types.Point3>[...worldPos], <Types.Point3>[...worldPos]],
          activeHandleIndex: null,
          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],
            },
          },
        },
        label: '',
        cachedStats: {},
      },
    };
 
    addAnnotation(annotation, element);
 
    const viewportIdsToRender = getViewportIdsWithToolToRender(
      element,
      this.getToolName()
    );
 
    this.editData = {
      annotation,
      viewportIdsToRender,
      handleIndex: 1,
      movingTextBox: false,
      newAnnotation: true,
      hasMoved: false,
    };
    this._activateDraw(element);
 
    evt.preventDefault();
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    return annotation;
  };
 
  /**
   * It returns if the canvas point is near the provided length 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: CobbAngleAnnotation,
    canvasCoords: Types.Point2,
    proximity: number
  ): boolean => {
    const enabledElement = getEnabledElement(element);
    const { viewport } = enabledElement;
    const { data } = annotation;
 
    const { distanceToPoint, distanceToPoint2 } = this.distanceToLines({
      viewport,
      points: data.handles.points,
      canvasCoords,
      proximity,
    });
 
    Eif (distanceToPoint <= proximity || distanceToPoint2 <= proximity) {
      return true;
    }
 
    return false;
  };
 
  toolSelectedCallback = (
    evt: EventTypes.MouseDownEventType,
    annotation: CobbAngleAnnotation,
    interactionType: InteractionTypes,
    canvasCoords: Types.Point2,
    proximity = 6
  ): void => {
    const eventDetail = evt.detail;
    const { element } = eventDetail;
 
    annotation.highlighted = true;
 
    const viewportIdsToRender = getViewportIdsWithToolToRender(
      element,
      this.getToolName()
    );
 
    const enabledElement = getEnabledElement(element);
    const { renderingEngine, viewport } = enabledElement;
 
    const { isNearFirstLine, isNearSecondLine } = this.distanceToLines({
      viewport,
      points: annotation.data.handles.points,
      canvasCoords,
      proximity,
    });
 
    this.editData = {
      annotation,
      viewportIdsToRender,
      movingTextBox: false,
      isNearFirstLine,
      isNearSecondLine,
    };
 
    this._activateModify(element);
 
    hideElementCursor(element);
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    evt.preventDefault();
  };
 
  handleSelectedCallback(
    evt: EventTypes.MouseDownEventType,
    annotation: CobbAngleAnnotation,
    handle: ToolHandle,
    interactionType = 'mouse'
  ): 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();
  }
 
  _mouseUpCallback = (
    evt: EventTypes.MouseUpEventType | EventTypes.MouseClickEventType
  ) => {
    const eventDetail = evt.detail;
    const { element } = eventDetail;
 
    const { annotation, viewportIdsToRender, newAnnotation, hasMoved } =
      this.editData;
 
    const { data } = annotation;
    if (newAnnotation && !hasMoved) {
      // when user starts the drawing by click, and moving the mouse, instead
      // of click and drag
      return;
    }
 
    // If preventing new measurement means we are in the middle of an existing measurement
    // we shouldn't deactivate modify or draw
    if (this.angleStartedNotYetCompleted && data.handles.points.length < 4) {
      resetElementCursor(element);
 
      // adds the first point of the second line
      this.editData.handleIndex = data.handles.points.length;
      return;
    }
 
    this.angleStartedNotYetCompleted = false;
    data.handles.activeHandleIndex = null;
 
    this._deactivateModify(element);
    this._deactivateDraw(element);
    resetElementCursor(element);
 
    const enabledElement = getEnabledElement(element);
    const { renderingEngine } = enabledElement;
 
    Iif (
      this.isHandleOutsideImage &&
      this.configuration.preventHandleOutsideImage
    ) {
      removeAnnotation(annotation.annotationUID);
    }
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    if (newAnnotation) {
      triggerAnnotationCompleted(annotation);
    }
 
    this.editData = null;
    this.isDrawing = false;
  };
 
  /**
   * Handles the mouse down for all points that follow the very first mouse down.
   * The very first mouse down is handled by addAnnotation.
   * This method ensures that the state of the tool is correct for the drawing of the second line segment.
   * In particular it ensures that the second segment can be created via a mouse down and drag.
   */
  _mouseDownCallback = (
    evt: EventTypes.MouseUpEventType | EventTypes.MouseClickEventType
  ) => {
    const { annotation, handleIndex } = this.editData;
    const eventDetail = evt.detail;
    const { element, currentPoints } = eventDetail;
    const worldPos = currentPoints.world;
    const { data } = annotation;
 
    if (handleIndex === 1) {
      // This is the mouse down for the second point of the first segment.
      // The mouse up takes care of adding the first point of the second segment.
      data.handles.points[1] = worldPos;
      this.editData.hasMoved =
        data.handles.points[1][0] !== data.handles.points[0][0] ||
        data.handles.points[1][1] !== data.handles.points[0][0];
      return;
    }
 
    if (handleIndex === 3) {
      // This is the mouse down for the second point of the second segment (i.e. the last point)
      data.handles.points[3] = worldPos;
      this.editData.hasMoved =
        data.handles.points[3][0] !== data.handles.points[2][0] ||
        data.handles.points[3][1] !== data.handles.points[2][0];
 
      this.angleStartedNotYetCompleted = false;
      return;
    }
 
    // This is the first mouse down of the first point of the second line segment.
    // It is as if we have not moved yet because Cobb Angle has two, disjoint sections, each with its own move.
    this.editData.hasMoved = false;
    hideElementCursor(element);
 
    // Add the last segment points for the subsequent drag/mouse move.
    data.handles.points[2] = data.handles.points[3] = worldPos;
    this.editData.handleIndex = data.handles.points.length - 1;
  };
 
  _mouseDragCallback = (
    evt: EventTypes.MouseDragEventType | EventTypes.MouseMoveEventType
  ) => {
    this.isDrawing = true;
    const eventDetail = evt.detail;
    const { element } = eventDetail;
 
    const {
      annotation,
      viewportIdsToRender,
      handleIndex,
      movingTextBox,
      isNearFirstLine,
      isNearSecondLine,
    } = this.editData;
    const { data } = annotation;
 
    Iif (movingTextBox) {
      // Drag mode - moving text box
      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 &&
      (isNearFirstLine || isNearSecondLine)
    ) {
      // select tool mode - moving annotation
      const { deltaPoints } = eventDetail as EventTypes.MouseDragEventDetail;
      const worldPosDelta = deltaPoints.world;
      const points = data.handles.points;
 
      // separate the logic for moving handles to move them separately
      if (isNearFirstLine) {
        const firstLinePoints = [points[0], points[1]];
        firstLinePoints.forEach((point) => {
          point[0] += worldPosDelta[0];
          point[1] += worldPosDelta[1];
          point[2] += worldPosDelta[2];
        });
      } else Eif (isNearSecondLine) {
        const secondLinePoints = [points[2], points[3]];
        secondLinePoints.forEach((point) => {
          point[0] += worldPosDelta[0];
          point[1] += worldPosDelta[1];
          point[2] += worldPosDelta[2];
        });
      }
 
      annotation.invalidated = true;
    } else {
      // Drag handle mode - after double click, and mouse move to draw
      const { currentPoints } = eventDetail;
      const worldPos = currentPoints.world;
 
      data.handles.points[handleIndex] = [...worldPos];
      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
    Iif (!this.isDrawing) {
      return;
    }
 
    this.isDrawing = false;
    this._deactivateDraw(element);
    this._deactivateModify(element);
    resetElementCursor(element);
 
    const { annotation, viewportIdsToRender, newAnnotation } = this.editData;
    const { data } = annotation;
 
    Iif (data.handles.points.length < 4) {
      // If it is mid-draw
      removeAnnotation(annotation.annotationUID);
    }
 
    annotation.highlighted = false;
    data.handles.activeHandleIndex = null;
 
    const enabledElement = getEnabledElement(element);
    const { renderingEngine } = enabledElement;
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    Eif (newAnnotation) {
      triggerAnnotationCompleted(annotation);
    }
 
    this.editData = null;
    this.angleStartedNotYetCompleted = false;
    return annotation.annotationUID;
  };
 
  _activateModify = (element: HTMLDivElement) => {
    state.isInteractingWithTool = true;
 
    element.addEventListener(
      Events.MOUSE_UP,
      this._mouseUpCallback as EventListener
    );
    element.addEventListener(
      Events.MOUSE_DRAG,
      this._mouseDragCallback as EventListener
    );
    element.addEventListener(
      Events.MOUSE_CLICK,
      this._mouseUpCallback as EventListener
    );
 
    // element.addEventListener(Events.TOUCH_END, this._mouseUpCallback)
    // element.addEventListener(Events.TOUCH_DRAG, this._mouseDragCallback)
  };
 
  _deactivateModify = (element: HTMLDivElement) => {
    state.isInteractingWithTool = false;
 
    element.removeEventListener(
      Events.MOUSE_UP,
      this._mouseUpCallback as EventListener
    );
    element.removeEventListener(
      Events.MOUSE_DRAG,
      this._mouseDragCallback as EventListener
    );
    element.removeEventListener(
      Events.MOUSE_CLICK,
      this._mouseUpCallback as EventListener
    );
 
    // element.removeEventListener(Events.TOUCH_END, this._mouseUpCallback)
    // element.removeEventListener(Events.TOUCH_DRAG, this._mouseDragCallback)
  };
 
  _activateDraw = (element: HTMLDivElement) => {
    state.isInteractingWithTool = true;
 
    element.addEventListener(
      Events.MOUSE_UP,
      this._mouseUpCallback as EventListener
    );
    element.addEventListener(
      Events.MOUSE_DRAG,
      this._mouseDragCallback as EventListener
    );
    element.addEventListener(
      Events.MOUSE_MOVE,
      this._mouseDragCallback as EventListener
    );
    element.addEventListener(
      Events.MOUSE_CLICK,
      this._mouseUpCallback as EventListener
    );
    element.addEventListener(
      Events.MOUSE_DOWN,
      this._mouseDownCallback as EventListener
    );
 
    // element.addEventListener(Events.TOUCH_END, this._mouseUpCallback)
    // element.addEventListener(Events.TOUCH_DRAG, this._mouseDragCallback)
  };
 
  _deactivateDraw = (element: HTMLDivElement) => {
    state.isInteractingWithTool = false;
 
    element.removeEventListener(
      Events.MOUSE_UP,
      this._mouseUpCallback as EventListener
    );
    element.removeEventListener(
      Events.MOUSE_DRAG,
      this._mouseDragCallback as EventListener
    );
    element.removeEventListener(
      Events.MOUSE_MOVE,
      this._mouseDragCallback as EventListener
    );
    element.removeEventListener(
      Events.MOUSE_CLICK,
      this._mouseUpCallback as EventListener
    );
    element.removeEventListener(
      Events.MOUSE_DOWN,
      this._mouseDownCallback as EventListener
    );
 
    // element.removeEventListener(Events.TOUCH_END, this._mouseUpCallback)
    // element.removeEventListener(Events.TOUCH_DRAG, this._mouseDragCallback)
  };
 
  /**
   * it is used to draw the length 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);
 
    // Todo: We don't need this anymore, filtering happens in triggerAnnotationRender
    if (!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,
    };
 
    // Draw SVG
    for (let i = 0; i < annotations.length; i++) {
      const annotation = annotations[i] as CobbAngleAnnotation;
      const { annotationUID, data } = annotation;
      const { points, activeHandleIndex } = data.handles;
 
      styleSpecifier.annotationUID = annotationUID;
 
      const { color, lineWidth, lineDash } = this.getAnnotationStyle({
        annotation,
        styleSpecifier,
      });
 
      const canvasCoordinates = points.map((p) => viewport.worldToCanvas(p));
 
      // WE HAVE TO CACHE STATS BEFORE FETCHING TEXT
      if (
        !data.cachedStats[targetId] ||
        data.cachedStats[targetId].angle == null
      ) {
        data.cachedStats[targetId] = {
          angle: null,
          arc1Angle: null,
          arc2Angle: null,
          points: {
            world: {
              arc1Start: null,
              arc1End: null,
              arc2Start: null,
              arc2End: null,
              arc1Angle: null,
              arc2Angle: null,
            },
            canvas: {
              arc1Start: null,
              arc1End: null,
              arc2Start: null,
              arc2End: null,
              arc1Angle: null,
              arc2Angle: null,
            },
          },
        };
 
        this._calculateCachedStats(annotation, renderingEngine, enabledElement);
      } else Iif (annotation.invalidated) {
        this._throttledCalculateCachedStats(
          annotation,
          renderingEngine,
          enabledElement
        );
      }
 
      let activeHandleCanvasCoords;
 
      Iif (
        !isAnnotationLocked(annotation) &&
        !this.editData &&
        activeHandleIndex !== null
      ) {
        // Not locked or creating and hovering over handle, so render handle.
        activeHandleCanvasCoords = [canvasCoordinates[activeHandleIndex]];
      }
 
      // If rendering engine has been destroyed while rendering
      Iif (!viewport.getRenderingEngine()) {
        console.warn('Rendering Engine has been destroyed');
        return renderStatus;
      }
 
      Iif (activeHandleCanvasCoords) {
        const handleGroupUID = '0';
 
        drawHandlesSvg(
          svgDrawingHelper,
          annotationUID,
          handleGroupUID,
          canvasCoordinates,
          {
            color,
            lineDash,
            lineWidth,
          }
        );
      }
 
      const firstLine = [canvasCoordinates[0], canvasCoordinates[1]] as [
        Types.Point2,
        Types.Point2
      ];
      const secondLine = [canvasCoordinates[2], canvasCoordinates[3]] as [
        Types.Point2,
        Types.Point2
      ];
 
      let lineUID = 'line1';
      drawLineSvg(
        svgDrawingHelper,
        annotationUID,
        lineUID,
        firstLine[0],
        firstLine[1],
        {
          color,
          width: lineWidth,
          lineDash,
        }
      );
 
      renderStatus = true;
 
      // Don't add the stats until annotation has 4 anchor points
      if (canvasCoordinates.length < 4) {
        return renderStatus;
      }
 
      lineUID = 'line2';
 
      drawLineSvg(
        svgDrawingHelper,
        annotationUID,
        lineUID,
        secondLine[0],
        secondLine[1],
        {
          color,
          width: lineWidth,
          lineDash,
        }
      );
 
      lineUID = 'linkLine';
      const mid1 = midPoint2(firstLine[0], firstLine[1]);
      const mid2 = midPoint2(secondLine[0], secondLine[1]);
      drawLineSvg(svgDrawingHelper, annotationUID, lineUID, mid1, mid2, {
        color,
        lineWidth: '1',
        lineDash: '1,4',
      });
 
      // Calculating the arcs
 
      const { arc1Start, arc1End, arc2End, arc2Start } =
        data.cachedStats[targetId].points.canvas;
      const { arc1Angle, arc2Angle } = data.cachedStats[targetId];
 
      Iif (this.configuration.showArcLines) {
        lineUID = 'arc1';
 
        drawLineSvg(
          svgDrawingHelper,
          annotationUID,
          lineUID,
          arc1Start as Types.Point2,
          arc1End as Types.Point2,
          {
            color,
            lineWidth: '1',
          }
        );
 
        lineUID = 'arc2';
 
        drawLineSvg(
          svgDrawingHelper,
          annotationUID,
          lineUID,
          arc2Start as Types.Point2,
          arc2End as Types.Point2,
          {
            color,
            lineWidth: '1',
          }
        );
      }
 
      if (!data.cachedStats[targetId]?.angle) {
        continue;
      }
 
      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);
 
      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 = 'cobbAngleText';
      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]),
      };
 
      Iif (this.configuration.showArcLines) {
        const arc1TextBoxUID = 'arcAngle1';
 
        const arc1TextLine = [
          `${arc1Angle.toFixed(2)} ${String.fromCharCode(176)}`,
        ];
 
        const arch1TextPosCanvas = midPoint2(arc1Start, arc1End);
 
        drawTextBoxSvg(
          svgDrawingHelper,
          annotationUID,
          arc1TextBoxUID,
          arc1TextLine,
          arch1TextPosCanvas,
          {
            ...options,
            padding: 3,
          }
        );
 
        const arc2TextBoxUID = 'arcAngle2';
 
        const arc2TextLine = [
          `${arc2Angle.toFixed(2)} ${String.fromCharCode(176)}`,
        ];
 
        const arch2TextPosCanvas = midPoint2(arc2Start, arc2End);
 
        drawTextBoxSvg(
          svgDrawingHelper,
          annotationUID,
          arc2TextBoxUID,
          arc2TextLine,
          arch2TextPosCanvas,
          {
            ...options,
            padding: 3,
          }
        );
      }
    }
 
    return renderStatus;
  };
 
  _calculateCachedStats(annotation, renderingEngine, enabledElement) {
    const data = annotation.data;
 
    // Until we have all four anchors bail out
    if (data.handles.points.length !== 4) {
      return;
    }
 
    const seg1: [Types.Point3, Types.Point3] = [null, null];
    const seg2: [Types.Point3, Types.Point3] = [null, null];
    let minDist = Number.MAX_VALUE;
 
    // Order the endpoints of each line segment such that seg1[1] and seg2[0]
    // are the closest (Euclidean distance-wise) to each other. Thus
    // the angle formed between the vectors seg1[1]->seg1[0] and seg2[0]->seg[1]
    // is calculated.
    // The assumption here is that the Cobb angle line segments are drawn
    // such that the segments intersect nearest the segment endpoints
    // that are closest AND those closest endpoints are the tails of the
    // vectors used to calculate the angle between the vectors/line segments.
    for (let i = 0; i < 2; i += 1) {
      for (let j = 2; j < 4; j += 1) {
        const dist = vec3.distance(
          data.handles.points[i],
          data.handles.points[j]
        );
        if (dist < minDist) {
          minDist = dist;
          seg1[1] = data.handles.points[i];
          seg1[0] = data.handles.points[(i + 1) % 2];
          seg2[0] = data.handles.points[j];
          seg2[1] = data.handles.points[2 + ((j - 1) % 2)];
        }
      }
    }
    const { viewport } = enabledElement;
    const { element } = viewport;
 
    const canvasPoints = data.handles.points.map((p) =>
      viewport.worldToCanvas(p)
    );
 
    const firstLine = [canvasPoints[0], canvasPoints[1]] as [
      Types.Point2,
      Types.Point2
    ];
    const secondLine = [canvasPoints[2], canvasPoints[3]] as [
      Types.Point2,
      Types.Point2
    ];
 
    const mid1 = midPoint2(firstLine[0], firstLine[1]);
    const mid2 = midPoint2(secondLine[0], secondLine[1]);
 
    const { arc1Start, arc1End, arc2End, arc2Start, arc1Angle, arc2Angle } =
      this.getArcsStartEndPoints({
        firstLine,
        secondLine,
        mid1,
        mid2,
      });
 
    const { cachedStats } = data;
    const targetIds = Object.keys(cachedStats);
 
    for (let i = 0; i < targetIds.length; i++) {
      const targetId = targetIds[i];
 
      cachedStats[targetId] = {
        angle: angleBetweenLines(seg1, seg2),
        arc1Angle,
        arc2Angle,
        points: {
          canvas: {
            arc1Start,
            arc1End,
            arc2End,
            arc2Start,
          },
          world: {
            arc1Start: viewport.canvasToWorld(arc1Start),
            arc1End: viewport.canvasToWorld(arc1End),
            arc2End: viewport.canvasToWorld(arc2End),
            arc2Start: viewport.canvasToWorld(arc2Start),
          },
        },
      };
    }
 
    annotation.invalidated = false;
 
    // Dispatching annotation modified
    triggerAnnotationModified(annotation, element);
 
    return cachedStats;
  }
 
  distanceToLines = ({ viewport, points, canvasCoords, proximity }) => {
    const [point1, point2, point3, point4] = points;
    const canvasPoint1 = viewport.worldToCanvas(point1);
    const canvasPoint2 = viewport.worldToCanvas(point2);
    const canvasPoint3 = viewport.worldToCanvas(point3);
    const canvasPoint4 = viewport.worldToCanvas(point4);
 
    const line1 = {
      start: {
        x: canvasPoint1[0],
        y: canvasPoint1[1],
      },
      end: {
        x: canvasPoint2[0],
        y: canvasPoint2[1],
      },
    };
 
    const line2 = {
      start: {
        x: canvasPoint3[0],
        y: canvasPoint3[1],
      },
      end: {
        x: canvasPoint4[0],
        y: canvasPoint4[1],
      },
    };
 
    const distanceToPoint = lineSegment.distanceToPoint(
      [line1.start.x, line1.start.y],
      [line1.end.x, line1.end.y],
      [canvasCoords[0], canvasCoords[1]]
    );
 
    const distanceToPoint2 = lineSegment.distanceToPoint(
      [line2.start.x, line2.start.y],
      [line2.end.x, line2.end.y],
      [canvasCoords[0], canvasCoords[1]]
    );
 
    let isNearFirstLine = false;
    let isNearSecondLine = false;
 
    if (distanceToPoint <= proximity) {
      isNearFirstLine = true;
    } else Eif (distanceToPoint2 <= proximity) {
      isNearSecondLine = true;
    }
    return {
      distanceToPoint,
      distanceToPoint2,
      isNearFirstLine,
      isNearSecondLine,
    };
  };
 
  getArcsStartEndPoints = ({
    firstLine,
    secondLine,
    mid1,
    mid2,
  }): {
    arc1Start: Types.Point2;
    arc1End: Types.Point2;
    arc2Start: Types.Point2;
    arc2End: Types.Point2;
    arc1Angle: number;
    arc2Angle: number;
  } => {
    const linkLine = [mid1, mid2] as [Types.Point2, Types.Point2];
 
    const arc1Angle = angleBetweenLines(firstLine, linkLine);
    const arc2Angle = angleBetweenLines(secondLine, linkLine);
 
    const arc1Side = arc1Angle > 90 ? 1 : 0;
    const arc2Side = arc2Angle > 90 ? 0 : 1;
 
    const midLinkLine = midPoint2(linkLine[0], linkLine[1]);
 
    const linkLineLength = Math.sqrt(
      (linkLine[1][0] - linkLine[0][0]) ** 2 +
        (linkLine[1][1] - linkLine[0][1]) ** 2
    );
    const ratio = 0.1; // 10% of the line length
 
    const midFirstLine = midPoint2(firstLine[0], firstLine[1]);
    const midSecondLine = midPoint2(secondLine[0], secondLine[1]);
 
    // For arc1Start
    const directionVectorStartArc1 = [
      firstLine[arc1Side][0] - midFirstLine[0],
      firstLine[arc1Side][1] - midFirstLine[1],
    ];
    const magnitudeStartArc1 = Math.sqrt(
      directionVectorStartArc1[0] ** 2 + directionVectorStartArc1[1] ** 2
    );
    const normalizedDirectionStartArc1 = [
      directionVectorStartArc1[0] / magnitudeStartArc1,
      directionVectorStartArc1[1] / magnitudeStartArc1,
    ];
    const arc1Start = [
      midFirstLine[0] +
        normalizedDirectionStartArc1[0] * linkLineLength * ratio,
      midFirstLine[1] +
        normalizedDirectionStartArc1[1] * linkLineLength * ratio,
    ] as Types.Point2;
 
    // Existing logic for arc1End
    const directionVectorEndArc1 = [
      midLinkLine[0] - mid1[0],
      midLinkLine[1] - mid1[1],
    ];
    const magnitudeEndArc1 = Math.sqrt(
      directionVectorEndArc1[0] ** 2 + directionVectorEndArc1[1] ** 2
    );
    const normalizedDirectionEndArc1 = [
      directionVectorEndArc1[0] / magnitudeEndArc1,
      directionVectorEndArc1[1] / magnitudeEndArc1,
    ];
    const arc1End = [
      mid1[0] + normalizedDirectionEndArc1[0] * linkLineLength * ratio,
      mid1[1] + normalizedDirectionEndArc1[1] * linkLineLength * ratio,
    ] as Types.Point2;
 
    // Similar logic for arc2Start
    const directionVectorStartArc2 = [
      secondLine[arc2Side][0] - midSecondLine[0],
      secondLine[arc2Side][1] - midSecondLine[1],
    ];
    const magnitudeStartArc2 = Math.sqrt(
      directionVectorStartArc2[0] ** 2 + directionVectorStartArc2[1] ** 2
    );
    const normalizedDirectionStartArc2 = [
      directionVectorStartArc2[0] / magnitudeStartArc2,
      directionVectorStartArc2[1] / magnitudeStartArc2,
    ];
    const arc2Start = [
      midSecondLine[0] +
        normalizedDirectionStartArc2[0] * linkLineLength * ratio,
      midSecondLine[1] +
        normalizedDirectionStartArc2[1] * linkLineLength * ratio,
    ] as Types.Point2;
 
    // Similar logic for arc2End
    const directionVectorEndArc2 = [
      midLinkLine[0] - mid2[0],
      midLinkLine[1] - mid2[1],
    ];
    const magnitudeEndArc2 = Math.sqrt(
      directionVectorEndArc2[0] ** 2 + directionVectorEndArc2[1] ** 2
    );
    const normalizedDirectionEndArc2 = [
      directionVectorEndArc2[0] / magnitudeEndArc2,
      directionVectorEndArc2[1] / magnitudeEndArc2,
    ];
    const arc2End = [
      mid2[0] + normalizedDirectionEndArc2[0] * linkLineLength * ratio,
      mid2[1] + normalizedDirectionEndArc2[1] * linkLineLength * ratio,
    ] as Types.Point2;
 
    return {
      arc1Start,
      arc1End,
      arc2Start,
      arc2End,
      arc1Angle: arc1Angle > 90 ? 180 - arc1Angle : arc1Angle,
      arc2Angle: arc2Angle > 90 ? 180 - arc2Angle : arc2Angle,
    };
  };
}
 
function defaultGetTextLines(data, targetId): string[] {
  const cachedVolumeStats = data.cachedStats[targetId];
  const { angle } = cachedVolumeStats;
 
  Iif (angle === undefined) {
    return;
  }
 
  const textLines = [`${angle.toFixed(2)} ${String.fromCharCode(176)}`];
 
  return textLines;
}
 
CobbAngleTool.toolName = 'CobbAngle';
export default CobbAngleTool;