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

84.25% Statements 337/400
55.55% Branches 55/99
100% Functions 24/24
84.09% Lines 333/396

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 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359                                                                                            1x                                                                                                                                 11x   11x                                   11x 11x 11x 11x 11x   11x   11x 11x   11x             11x   11x                                                                         11x   11x         11x               11x   11x   11x   11x   11x                           11x           4x 4x 4x 4x     4x 4x   4x                     4x           4x 4x                                                                         11x       4x 4x   4x   4x         4x           4x   4x 4x   4x   4x   4x                       11x         2x 2x 2x   2x   2x     2x     2x       2x         2x   2x           2x   2x 2x   2x   2x                     11x 15x 15x     15x 15x   15x       15x   15x 15x   15x   15x   15x 11x 11x 11x   11x                                                                                                             15x             15x   15x 9x     15x 15x           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 4x   4x 4x 4x 4x   4x 4x 4x                       4x   2x 2x 2x   2x 8x 8x 8x   2x   2x 2x     4x             11x 2x 2x 2x 2x 2x 2x     2x 2x             2x                   2x                       2x 2x   2x 2x     2x   2x           2x                 2x       2x     2x                               2x                 2x   2x             2x 2x   2x 2x     2x 2x   2x 2x       2x   2x     2x   2x     2x 2x   2x 2x     2x 2x             2x 2x 2x                                                                                                                                                                                                                               11x   2x 2x 2x 2x 2x   2x 2x   2x 2x   2x   2x         2x 2x     2x 2x       11x 11x   11x 11x 11x 11x   11x       11x       11x           11x 17x   17x 17x 17x 17x   17x       17x       17x           11x 6x   6x 6x 6x   6x       6x       6x           11x 17x   17x 17x 17x   17x       17x       17x                           11x       13x 13x 13x 13x   13x       13x         13x       13x   13x   13x           13x 13x 13x 13x 52x   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                     13x   13x               13x     11x       2x   2x           2x   2x                           2x             2x   2x       22x 22x 22x   22x     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 2x               13x 13x   13x 13x     13x           13x         13x     1x    
import { vec2, vec3 } from 'gl-matrix';
import { getEnabledElement, utilities as csUtils } from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
 
import { getCalibratedLengthUnitsAndScale } from '../../utilities/getCalibratedUnits';
import { roundNumber } from '../../utilities';
import { AnnotationTool } from '../base';
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 {
  drawLine as drawLineSvg,
  drawHandles as drawHandlesSvg,
  drawLinkedTextBox as drawLinkedTextBoxSvg,
} from '../../drawingSvg';
import { state } from '../../store';
import { Events } from '../../enums';
import { getViewportIdsWithToolToRender } from '../../utilities/viewportFilters';
import * as lineSegment from '../../utilities/math/line';
import { getTextBoxCoordsCanvas } from '../../utilities/drawing';
import {
  resetElementCursor,
  hideElementCursor,
} from '../../cursors/elementCursor';
import {
  EventTypes,
  ToolHandle,
  TextBoxHandle,
  PublicToolProps,
  ToolProps,
  SVGDrawingHelper,
} from '../../types';
import { BidirectionalAnnotation } from '../../types/ToolSpecificAnnotationTypes';
 
import triggerAnnotationRenderForViewportIds from '../../utilities/triggerAnnotationRenderForViewportIds';
import { StyleSpecifier } from '../../types/AnnotationStyle';
 
const { transformWorldToIndex } = csUtils;
 
/**
 * BidirectionalTool let you draw annotations that measures the length and
 * width at the same time in `mm` unit. It is consisted of two perpendicular lines and
 * a text box. You can use the BidirectionalTool in all planes even in oblique
 * reconstructed planes. 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.
 *
 * 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(BidirectionalTool)
 *
 * const toolGroup = ToolGroupManager.createToolGroup('toolGroupId')
 *
 * toolGroup.addTool(BidirectionalTool.toolName)
 *
 * toolGroup.addViewport('viewportId', 'renderingEngineId')
 *
 * toolGroup.setToolActive(BidirectionalTool.toolName, {
 *   bindings: [
 *    {
 *       mouseButton: MouseBindings.Primary, // Left Click
 *     },
 *   ],
 * })
 * ```
 *
 * Read more in the Docs section of the website.
 */
 
class BidirectionalTool extends AnnotationTool {
  static toolName;
 
  touchDragCallback: any;
  mouseDragCallback: any;
  _throttledCalculateCachedStats: any;
  editData: {
    annotation: any;
    viewportIdsToRender: string[];
    handleIndex?: number;
    movingTextBox: boolean;
    newAnnotation?: boolean;
    hasMoved?: boolean;
  } | null;
  isDrawing: boolean;
  isHandleOutsideImage: boolean;
  preventHandleOutsideImage: boolean;
 
  constructor(
    toolProps: PublicToolProps = {},
    defaultToolProps: ToolProps = {
      supportedInteractionTypes: ['Mouse', 'Touch'],
      configuration: {
        preventHandleOutsideImage: false,
        getTextLines: defaultGetTextLines,
      },
    }
  ) {
    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 Bidirectional Annotation and stores it in the annotationManager
   *
   * @param evt -  EventTypes.NormalizedMouseEventType
   * @returns The annotation object.
   *
   */
  addNewAnnotation(
    evt: EventTypes.InteractionEventType
  ): BidirectionalAnnotation {
    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: BidirectionalAnnotation = {
      highlighted: true,
      invalidated: true,
      metadata: {
        toolName: this.getToolName(),
        viewPlaneNormal: <Types.Point3>[...viewPlaneNormal],
        viewUp: <Types.Point3>[...viewUp],
        FrameOfReferenceUID,
        referencedImageId,
      },
      data: {
        handles: {
          points: [
            // long
            <Types.Point3>[...worldPos],
            <Types.Point3>[...worldPos],
            // short
            <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,
        },
        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);
 
    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: BidirectionalAnnotation,
    canvasCoords: Types.Point2,
    proximity: number
  ): boolean => {
    const enabledElement = getEnabledElement(element);
    const { viewport } = enabledElement;
    const { data } = annotation;
    const { points } = data.handles;
 
    // Check long axis
    let canvasPoint1 = viewport.worldToCanvas(points[0]);
    let canvasPoint2 = viewport.worldToCanvas(points[1]);
 
    let line = {
      start: {
        x: canvasPoint1[0],
        y: canvasPoint1[1],
      },
      end: {
        x: canvasPoint2[0],
        y: canvasPoint2[1],
      },
    };
 
    let distanceToPoint = lineSegment.distanceToPoint(
      [line.start.x, line.start.y],
      [line.end.x, line.end.y],
      [canvasCoords[0], canvasCoords[1]]
    );
 
    Eif (distanceToPoint <= proximity) {
      return true;
    }
 
    // Check short axis
    canvasPoint1 = viewport.worldToCanvas(points[2]);
    canvasPoint2 = viewport.worldToCanvas(points[3]);
 
    line = {
      start: {
        x: canvasPoint1[0],
        y: canvasPoint1[1],
      },
      end: {
        x: canvasPoint2[0],
        y: canvasPoint2[1],
      },
    };
 
    distanceToPoint = lineSegment.distanceToPoint(
      [line.start.x, line.start.y],
      [line.end.x, line.end.y],
      [canvasCoords[0], canvasCoords[1]]
    );
 
    if (distanceToPoint <= proximity) {
      return true;
    }
 
    return false;
  };
 
  /**
   * Handles the toolSelected callback for bidirectional tool
   * @param evt - EventTypes.MouseDownEventType
   * @param annotation - Bidirectional annotation
   * @param interactionType - interaction type (mouse, touch)
   */
  toolSelectedCallback = (
    evt: EventTypes.InteractionEventType,
    annotation: BidirectionalAnnotation
  ): 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);
 
    const enabledElement = getEnabledElement(element);
    const { renderingEngine } = enabledElement;
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    hideElementCursor(element);
 
    evt.preventDefault();
  };
 
  /**
   * Executes the callback for when mouse has selected a handle (anchor point) of
   * the bidirectional tool or when the text box has been selected.
   *
   * @param evt - EventTypes.MouseDownEventType
   * @param annotation - Bidirectional annotation
   * @param handle - Handle index or selected textBox information
   * @param interactionType - interaction type (mouse, touch)
   */
  handleSelectedCallback = (
    evt: EventTypes.InteractionEventType,
    annotation: BidirectionalAnnotation,
    handle: ToolHandle
  ): void => {
    const eventDetail = evt.detail;
    const { element } = eventDetail;
    const data = annotation.data;
 
    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()
    );
 
    hideElementCursor(element);
 
    this.editData = {
      annotation,
      viewportIdsToRender,
      handleIndex,
      movingTextBox,
    };
    this._activateModify(element);
 
    const enabledElement = getEnabledElement(element);
    const { renderingEngine } = enabledElement;
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    evt.preventDefault();
  };
 
  /**
   * Handles the mouse up action for the bidirectional tool. It can be at the end
   * of the annotation drawing (MouseUpEventType) or when the user clicks and release
   * the mouse button instantly which let to the annotation to draw without holding
   * the mouse button (MouseClickEventType).
   *
   * @param evt - mouse up or mouse click event types
   */
  _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);
 
    if (this.editData.handleIndex !== undefined) {
      const { points } = data.handles;
      const firstLineSegmentLength = vec3.distance(points[0], points[1]);
      const secondLineSegmentLength = vec3.distance(points[2], points[3]);
 
      Iif (secondLineSegmentLength > firstLineSegmentLength) {
        // Switch points so [0,1] is the long axis and [2,3] is the short axis.
 
        const longAxis = [[...points[2]], [...points[3]]];
 
        const shortAxisPoint0 = [...points[0]];
        const shortAxisPoint1 = [...points[1]];
 
        // shortAxis[0->1] should be perpendicular (counter-clockwise) to longAxis[0->1]
        const longAxisVector = vec2.create();
 
        vec2.set(
          longAxisVector,
          longAxis[1][0] - longAxis[0][0],
          longAxis[1][1] - longAxis[1][0]
        );
 
        const counterClockWisePerpendicularToLongAxis = vec2.create();
 
        vec2.set(
          counterClockWisePerpendicularToLongAxis,
          -longAxisVector[1],
          longAxisVector[0]
        );
 
        const currentShortAxisVector = vec2.create();
 
        vec2.set(
          currentShortAxisVector,
          shortAxisPoint1[0] - shortAxisPoint0[0],
          shortAxisPoint1[1] - shortAxisPoint0[0]
        );
 
        let shortAxis;
 
        if (
          vec2.dot(
            currentShortAxisVector,
            counterClockWisePerpendicularToLongAxis
          ) > 0
        ) {
          shortAxis = [shortAxisPoint0, shortAxisPoint1];
        } else {
          shortAxis = [shortAxisPoint1, shortAxisPoint0];
        }
 
        data.handles.points = [
          longAxis[0],
          longAxis[1],
          shortAxis[0],
          shortAxis[1],
        ];
      }
    }
 
    Iif (
      this.isHandleOutsideImage &&
      this.configuration.preventHandleOutsideImage
    ) {
      removeAnnotation(annotation.annotationUID);
    }
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    if (newAnnotation) {
      triggerAnnotationCompleted(annotation);
    }
 
    this.editData = null;
    this.isDrawing = false;
  };
 
  /**
   * @param evt - mouse move event type or mouse drag
   */
  _dragDrawCallback = (evt: EventTypes.InteractionEventType): void => {
    this.isDrawing = true;
 
    const eventDetail = evt.detail;
    const { currentPoints, element } = eventDetail;
    const enabledElement = getEnabledElement(element);
    const { renderingEngine, viewport } = enabledElement;
    const { worldToCanvas } = viewport;
    const { annotation, viewportIdsToRender, handleIndex } = this.editData;
    const { data } = annotation;
 
    const worldPos = currentPoints.world;
 
    // Update first move handle
    data.handles.points[handleIndex] = [...worldPos];
 
    const canvasCoordPoints = data.handles.points.map(worldToCanvas);
 
    const canvasCoords = {
      longLineSegment: {
        start: {
          x: canvasCoordPoints[0][0],
          y: canvasCoordPoints[0][1],
        },
        end: {
          x: canvasCoordPoints[1][0],
          y: canvasCoordPoints[1][1],
        },
      },
      shortLineSegment: {
        start: {
          x: canvasCoordPoints[2][0],
          y: canvasCoordPoints[2][1],
        },
        end: {
          x: canvasCoordPoints[3][0],
          y: canvasCoordPoints[3][1],
        },
      },
    };
 
    // ~~ calculate worldPos of our short axis handles
    // short axis is perpendicular to long axis, and we set its length to be 2/3 of long axis
    // (meaning each)
    const dist = vec2.distance(canvasCoordPoints[0], canvasCoordPoints[1]);
 
    const shortAxisDistFromCenter = dist / 3;
    // Calculate long line's incline
    const dx =
      canvasCoords.longLineSegment.start.x - canvasCoords.longLineSegment.end.x;
    const dy =
      canvasCoords.longLineSegment.start.y - canvasCoords.longLineSegment.end.y;
    const length = Math.sqrt(dx * dx + dy * dy);
    const vectorX = dx / length;
    const vectorY = dy / length;
    // middle point between long line segment's points
    const xMid =
      (canvasCoords.longLineSegment.start.x +
        canvasCoords.longLineSegment.end.x) /
      2;
    const yMid =
      (canvasCoords.longLineSegment.start.y +
        canvasCoords.longLineSegment.end.y) /
      2;
    // short points 1/3 distance from center of long points
    const startX = xMid + shortAxisDistFromCenter * vectorY;
    const startY = yMid - shortAxisDistFromCenter * vectorX;
    const endX = xMid - shortAxisDistFromCenter * vectorY;
    const endY = yMid + shortAxisDistFromCenter * vectorX;
 
    // Update perpendicular line segment's points
    data.handles.points[2] = viewport.canvasToWorld([startX, startY]);
    data.handles.points[3] = viewport.canvasToWorld([endX, endY]);
 
    annotation.invalidated = true;
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
 
    this.editData.hasMoved = true;
  };
 
  /**
   * Mouse drag to edit annotation callback
   * @param evt - mouse drag event
   */
  _dragModifyCallback = (evt: EventTypes.InteractionEventType): void => {
    this.isDrawing = true;
 
    const eventDetail = evt.detail;
    const { element } = eventDetail;
    const enabledElement = getEnabledElement(element);
    const { renderingEngine } = enabledElement;
    const { annotation, viewportIdsToRender, handleIndex, movingTextBox } =
      this.editData;
    const { data } = annotation;
    Iif (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._dragModifyHandle(evt);
      annotation.invalidated = true;
    }
 
    triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
  };
 
  /**
   * Mouse dragging a handle callback
   * @param evt - mouse drag event
   */
  _dragModifyHandle = (evt: EventTypes.InteractionEventType): void => {
    const eventDetail = evt.detail;
    const { currentPoints, element } = eventDetail;
    const enabledElement = getEnabledElement(element);
    const { viewport } = enabledElement;
    const { annotation, handleIndex: movingHandleIndex } = this.editData;
    const { data } = annotation;
 
    // Moving handle
    const worldPos = currentPoints.world;
    const canvasCoordHandlesCurrent = [
      viewport.worldToCanvas(data.handles.points[0]),
      viewport.worldToCanvas(data.handles.points[1]),
      viewport.worldToCanvas(data.handles.points[2]),
      viewport.worldToCanvas(data.handles.points[3]),
    ];
 
    const firstLineSegment = {
      start: {
        x: canvasCoordHandlesCurrent[0][0],
        y: canvasCoordHandlesCurrent[0][1],
      },
      end: {
        x: canvasCoordHandlesCurrent[1][0],
        y: canvasCoordHandlesCurrent[1][1],
      },
    };
    const secondLineSegment = {
      start: {
        x: canvasCoordHandlesCurrent[2][0],
        y: canvasCoordHandlesCurrent[2][1],
      },
      end: {
        x: canvasCoordHandlesCurrent[3][0],
        y: canvasCoordHandlesCurrent[3][1],
      },
    };
 
    // Handle we've selected's proposed point
    const proposedPoint = <Types.Point3>[...worldPos];
    const proposedCanvasCoord = viewport.worldToCanvas(proposedPoint);
 
    if (movingHandleIndex === 0 || movingHandleIndex === 1) {
      const fixedHandleIndex = movingHandleIndex === 0 ? 1 : 0;
 
      const fixedHandleCanvasCoord =
        canvasCoordHandlesCurrent[fixedHandleIndex];
 
      const fixedHandleToProposedCoordVec = vec2.set(
        vec2.create(),
        proposedCanvasCoord[0] - fixedHandleCanvasCoord[0],
        proposedCanvasCoord[1] - fixedHandleCanvasCoord[1]
      );
 
      const fixedHandleToOldCoordVec = vec2.set(
        vec2.create(),
        canvasCoordHandlesCurrent[movingHandleIndex][0] -
          fixedHandleCanvasCoord[0],
        canvasCoordHandlesCurrent[movingHandleIndex][1] -
          fixedHandleCanvasCoord[1]
      );
 
      // normalize vector
      vec2.normalize(
        fixedHandleToProposedCoordVec,
        fixedHandleToProposedCoordVec
      );
      vec2.normalize(fixedHandleToOldCoordVec, fixedHandleToOldCoordVec);
 
      // Check whether this
      const proposedFirstLineSegment = {
        start: {
          x: fixedHandleCanvasCoord[0],
          y: fixedHandleCanvasCoord[1],
        },
        end: {
          x: proposedCanvasCoord[0],
          y: proposedCanvasCoord[1],
        },
      };
 
      // Note: this is the case when we are modifying the long axis line segment
      // and we make it shorter and shorter until its second half size becomes zero
      // which basically means that any more modification would make the long axis
      // second half disappear. In this case, we just bail out and do not update
      // since we don't want to disrupt the bidirectional shape.
      Iif (
        this._movingLongAxisWouldPutItThroughShortAxis(
          proposedFirstLineSegment,
          secondLineSegment
        )
      ) {
        return;
      }
 
      const centerOfRotation = fixedHandleCanvasCoord;
 
      const angle = this._getSignedAngle(
        fixedHandleToOldCoordVec,
        fixedHandleToProposedCoordVec
      );
 
      // rotate handles around the center of rotation, first translate to origin,
      // then rotate, then translate back
      let firstPointX = canvasCoordHandlesCurrent[2][0];
      let firstPointY = canvasCoordHandlesCurrent[2][1];
 
      let secondPointX = canvasCoordHandlesCurrent[3][0];
      let secondPointY = canvasCoordHandlesCurrent[3][1];
 
      // translate to origin
      firstPointX -= centerOfRotation[0];
      firstPointY -= centerOfRotation[1];
 
      secondPointX -= centerOfRotation[0];
      secondPointY -= centerOfRotation[1];
 
      // rotate
      const rotatedFirstPoint =
        firstPointX * Math.cos(angle) - firstPointY * Math.sin(angle);
      const rotatedFirstPointY =
        firstPointX * Math.sin(angle) + firstPointY * Math.cos(angle);
 
      const rotatedSecondPoint =
        secondPointX * Math.cos(angle) - secondPointY * Math.sin(angle);
      const rotatedSecondPointY =
        secondPointX * Math.sin(angle) + secondPointY * Math.cos(angle);
 
      // translate back
      firstPointX = rotatedFirstPoint + centerOfRotation[0];
      firstPointY = rotatedFirstPointY + centerOfRotation[1];
 
      secondPointX = rotatedSecondPoint + centerOfRotation[0];
      secondPointY = rotatedSecondPointY + centerOfRotation[1];
 
      // update handles
      const newFirstPoint = viewport.canvasToWorld([firstPointX, firstPointY]);
      const newSecondPoint = viewport.canvasToWorld([
        secondPointX,
        secondPointY,
      ]);
 
      // the fixed handle is the one that is not being moved so we
      // don't need to update it
      data.handles.points[movingHandleIndex] = proposedPoint;
      data.handles.points[2] = newFirstPoint;
      data.handles.points[3] = newSecondPoint;
    } else E{
      // Translation manipulator
      const translateHandleIndex = movingHandleIndex === 2 ? 3 : 2;
 
      const canvasCoordsCurrent = {
        longLineSegment: {
          start: firstLineSegment.start,
          end: firstLineSegment.end,
        },
        shortLineSegment: {
          start: secondLineSegment.start,
          end: secondLineSegment.end,
        },
      };
 
      const longLineSegmentVec = vec2.subtract(
        vec2.create(),
        [
          canvasCoordsCurrent.longLineSegment.end.x,
          canvasCoordsCurrent.longLineSegment.end.y,
        ],
        [
          canvasCoordsCurrent.longLineSegment.start.x,
          canvasCoordsCurrent.longLineSegment.start.y,
        ]
      );
 
      const longLineSegmentVecNormalized = vec2.normalize(
        vec2.create(),
        longLineSegmentVec
      );
 
      const proposedToCurrentVec = vec2.subtract(
        vec2.create(),
        [proposedCanvasCoord[0], proposedCanvasCoord[1]],
        [
          canvasCoordHandlesCurrent[movingHandleIndex][0],
          canvasCoordHandlesCurrent[movingHandleIndex][1],
        ]
      );
 
      const movementLength = vec2.length(proposedToCurrentVec);
 
      const angle = this._getSignedAngle(
        longLineSegmentVecNormalized,
        proposedToCurrentVec
      );
 
      const movementAlongLineSegmentLength = Math.cos(angle) * movementLength;
 
      const newTranslatedPoint = vec2.scaleAndAdd(
        vec2.create(),
        [
          canvasCoordHandlesCurrent[translateHandleIndex][0],
          canvasCoordHandlesCurrent[translateHandleIndex][1],
        ],
        longLineSegmentVecNormalized,
        movementAlongLineSegmentLength
      );
 
      // don't update if it passes through the other line segment
      if (
        this._movingLongAxisWouldPutItThroughShortAxis(
          {
            start: {
              x: proposedCanvasCoord[0],
              y: proposedCanvasCoord[1],
            },
            end: {
              x: newTranslatedPoint[0],
              y: newTranslatedPoint[1],
            },
          },
          {
            start: {
              x: canvasCoordsCurrent.longLineSegment.start.x,
              y: canvasCoordsCurrent.longLineSegment.start.y,
            },
            end: {
              x: canvasCoordsCurrent.longLineSegment.end.x,
              y: canvasCoordsCurrent.longLineSegment.end.y,
            },
          }
        )
      ) {
        return;
      }
 
      const intersectionPoint = lineSegment.intersectLine(
        [proposedCanvasCoord[0], proposedCanvasCoord[1]],
        [newTranslatedPoint[0], newTranslatedPoint[1]],
        [firstLineSegment.start.x, firstLineSegment.start.y],
        [firstLineSegment.end.x, firstLineSegment.end.y]
      );
 
      // don't update if it doesn't intersect
      if (!intersectionPoint) {
        return;
      }
 
      data.handles.points[translateHandleIndex] = viewport.canvasToWorld(
        newTranslatedPoint as Types.Point2
      );
      data.handles.points[movingHandleIndex] = proposedPoint;
    }
  };
 
  /**
   * Cancels an ongoing drawing of a bidirectional annotation
   * @param element - HTML Element
   */
  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;
    }
  };
 
  _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_TAP,
      this._endCallback as EventListener
    );
    element.addEventListener(
      Events.TOUCH_END,
      this._endCallback as EventListener
    );
    element.addEventListener(
      Events.TOUCH_DRAG,
      this._dragDrawCallback as EventListener
    );
  };
 
  _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_TAP,
      this._endCallback as EventListener
    );
    element.removeEventListener(
      Events.TOUCH_END,
      this._endCallback as EventListener
    );
    element.removeEventListener(
      Events.TOUCH_DRAG,
      this._dragDrawCallback as EventListener
    );
  };
 
  _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 as EventListener
    );
    element.addEventListener(
      Events.TOUCH_DRAG,
      this._dragModifyCallback as EventListener
    );
    element.addEventListener(
      Events.TOUCH_TAP,
      this._endCallback as EventListener
    );
  };
 
  _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 as EventListener
    );
    element.removeEventListener(
      Events.TOUCH_DRAG,
      this._dragModifyCallback as EventListener
    );
    element.removeEventListener(
      Events.TOUCH_TAP,
      this._endCallback as EventListener
    );
  };
 
  /**
   * it is used to draw the bidirectional 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 = true;
    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 BidirectionalAnnotation;
      const { annotationUID, data } = annotation;
      const { points, activeHandleIndex } = data.handles;
      const canvasCoordinates = points.map((p) => viewport.worldToCanvas(p));
 
      styleSpecifier.annotationUID = annotationUID;
 
      const { color, lineWidth, lineDash, shadow } = this.getAnnotationStyle({
        annotation,
        styleSpecifier,
      });
 
      // 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].unit == null
      ) {
        data.cachedStats[targetId] = {
          length: null,
          width: null,
          unit: null,
        };
 
        this._calculateCachedStats(annotation, renderingEngine, enabledElement);
      } else Iif (annotation.invalidated) {
        this._throttledCalculateCachedStats(
          annotation,
          renderingEngine,
          enabledElement
        );
      }
 
      // 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 dataId1 = `${annotationUID}-line-1`;
      const dataId2 = `${annotationUID}-line-2`;
 
      const lineUID = '0';
      drawLineSvg(
        svgDrawingHelper,
        annotationUID,
        lineUID,
        canvasCoordinates[0],
        canvasCoordinates[1],
        {
          color,
          lineDash,
          lineWidth,
          shadow,
        },
        dataId1
      );
 
      const secondLineUID = '1';
      drawLineSvg(
        svgDrawingHelper,
        annotationUID,
        secondLineUID,
        canvasCoordinates[2],
        canvasCoordinates[3],
        {
          color,
          lineDash,
          lineWidth,
          shadow,
        },
        dataId2
      );
 
      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;
      }
 
      let canvasTextBoxCoords;
 
      Eif (!data.handles.textBox.hasMoved) {
        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;
  };
 
  _movingLongAxisWouldPutItThroughShortAxis = (
    firstLineSegment,
    secondLineSegment
  ) => {
    const vectorInSecondLineDirection = vec2.create();
 
    vec2.set(
      vectorInSecondLineDirection,
      secondLineSegment.end.x - secondLineSegment.start.x,
      secondLineSegment.end.y - secondLineSegment.start.y
    );
 
    vec2.normalize(vectorInSecondLineDirection, vectorInSecondLineDirection);
 
    const extendedSecondLineSegment = {
      start: {
        x: secondLineSegment.start.x - vectorInSecondLineDirection[0] * 10,
        y: secondLineSegment.start.y - vectorInSecondLineDirection[1] * 10,
      },
      end: {
        x: secondLineSegment.end.x + vectorInSecondLineDirection[0] * 10,
        y: secondLineSegment.end.y + vectorInSecondLineDirection[1] * 10,
      },
    };
 
    // Add some buffer in the secondLineSegment when finding the proposedIntersectionPoint
    // Of points to stop us getting stack when rotating quickly.
 
    const proposedIntersectionPoint = lineSegment.intersectLine(
      [extendedSecondLineSegment.start.x, extendedSecondLineSegment.start.y],
      [extendedSecondLineSegment.end.x, extendedSecondLineSegment.end.y],
      [firstLineSegment.start.x, firstLineSegment.start.y],
      [firstLineSegment.end.x, firstLineSegment.end.y]
    );
 
    const wouldPutThroughShortAxis = !proposedIntersectionPoint;
 
    return wouldPutThroughShortAxis;
  };
 
  _calculateLength(pos1, pos2) {
    const dx = pos1[0] - pos2[0];
    const dy = pos1[1] - pos2[1];
    const dz = pos1[2] - pos2[2];
 
    return Math.sqrt(dx * dx + dy * dy + dz * dz);
  }
 
  _calculateCachedStats = (annotation, renderingEngine, enabledElement) => {
    const { data } = annotation;
    const { element } = enabledElement.viewport;
 
    const worldPos1 = data.handles.points[0];
    const worldPos2 = data.handles.points[1];
    const worldPos3 = data.handles.points[2];
    const worldPos4 = 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 { imageData, dimensions } = image;
      const index1 = transformWorldToIndex(imageData, worldPos1);
      const index2 = transformWorldToIndex(imageData, worldPos2);
      const index3 = transformWorldToIndex(imageData, worldPos3);
      const index4 = transformWorldToIndex(imageData, worldPos4);
 
      const handles1 = [index1, index2];
      const handles2 = [index3, index4];
 
      const { scale: scale1, units: units1 } = getCalibratedLengthUnitsAndScale(
        image,
        handles1
      );
 
      const { scale: scale2, units: units2 } = getCalibratedLengthUnitsAndScale(
        image,
        handles2
      );
 
      const dist1 = this._calculateLength(worldPos1, worldPos2) / scale1;
      const dist2 = this._calculateLength(worldPos3, worldPos4) / scale2;
      const length = dist1 > dist2 ? dist1 : dist2;
      const width = dist1 > dist2 ? dist2 : dist1;
 
      const lengthUnit = dist1 > dist2 ? units1 : units2;
      const widthUnit = dist1 > dist2 ? units2 : units1;
 
      this._isInsideVolume(index1, index2, index3, index4, dimensions)
        ? (this.isHandleOutsideImage = false)
        : (this.isHandleOutsideImage = true);
 
      cachedStats[targetId] = {
        length,
        width,
        unit: units1,
        lengthUnit,
        widthUnit,
      };
    }
 
    annotation.invalidated = false;
 
    // Dispatching annotation modified
    triggerAnnotationModified(annotation, element);
 
    return cachedStats;
  };
 
  _isInsideVolume = (index1, index2, index3, index4, dimensions): boolean => {
    return (
      csUtils.indexWithinDimensions(index1, dimensions) &&
      csUtils.indexWithinDimensions(index2, dimensions) &&
      csUtils.indexWithinDimensions(index3, dimensions) &&
      csUtils.indexWithinDimensions(index4, dimensions)
    );
  };
 
  _getSignedAngle = (vector1, vector2) => {
    return Math.atan2(
      vector1[0] * vector2[1] - vector1[1] * vector2[0],
      vector1[0] * vector2[0] + vector1[1] * vector2[1]
    );
  };
}
 
function defaultGetTextLines(data, targetId): string[] {
  const { cachedStats, label } = data;
  const { length, width, unit, lengthUnit, widthUnit } = cachedStats[targetId];
 
  const textLines = [];
  Iif (label) {
    textLines.push(label);
  }
  Iif (length === undefined) {
    return textLines;
  }
 
  // spaceBetweenSlices & pixelSpacing &
  // magnitude in each direction? Otherwise, this is "px"?
  textLines.push(
    `L: ${roundNumber(length)} ${lengthUnit || unit}`,
    `W: ${roundNumber(width)} ${widthUnit || unit}`
  );
 
  return textLines;
}
 
BidirectionalTool.toolName = 'Bidirectional';
export default BidirectionalTool;