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

0.41% Statements 1/239
0% Branches 0/100
0% Functions 0/25
0.42% Lines 1/237

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    1x    
import {
  utilities as csUtils,
  cache,
  getEnabledElement,
  StackViewport,
  eventTarget,
  Enums,
} from '@cornerstonejs/core';
import { vec3, vec2 } from 'gl-matrix';
 
import type { Types } from '@cornerstonejs/core';
import type {
  PublicToolProps,
  ToolProps,
  EventTypes,
  SVGDrawingHelper,
} from '../../types';
import { BaseTool } from '../base';
import {
  fillInsideSphere,
  thresholdInsideSphere,
} from './strategies/fillSphere';
import { eraseInsideSphere } from './strategies/eraseSphere';
import {
  thresholdInsideCircle,
  fillInsideCircle,
} from './strategies/fillCircle';
import { eraseInsideCircle } from './strategies/eraseCircle';
import {
  Events,
  ToolModes,
  SegmentationRepresentations,
  StrategyCallbacks,
} from '../../enums';
import { drawCircle as drawCircleSvg } from '../../drawingSvg';
import {
  resetElementCursor,
  hideElementCursor,
} from '../../cursors/elementCursor';
 
import triggerAnnotationRenderForViewportUIDs from '../../utilities/triggerAnnotationRenderForViewportIds';
import {
  config as segmentationConfig,
  segmentLocking,
  segmentIndex as segmentIndexController,
  state as segmentationState,
  activeSegmentation,
} from '../../stateManagement/segmentation';
import {
  LabelmapSegmentationDataVolume,
  LabelmapSegmentationDataStack,
} from '../../types/LabelmapTypes';
import { isVolumeSegmentation } from './strategies/utils/stackVolumeCheck';
 
/**
 * A type for preview data/information, used to setup previews on hover, or
 * maintain the preview information.
 */
export type PreviewData = {
  /**
   *  The preview data returned from the strategy
   */
  preview: unknown;
  timer?: number;
  timerStart: number;
  startPoint: Types.Point2;
  element: HTMLDivElement;
  isDrag: boolean;
};
 
/**
 * @public
 */
class BrushTool extends BaseTool {
  static toolName;
  private _editData: {
    segmentsLocked: number[]; //
    segmentationRepresentationUID?: string;
    imageIdReferenceMap?: Map<string, string>;
    volumeId?: string;
    referencedVolumeId?: string;
  } | null;
  private _hoverData?: {
    brushCursor: any;
    segmentationId: string;
    segmentIndex: number;
    segmentationRepresentationUID: string;
    segmentColor: [number, number, number, number];
    viewportIdsToRender: string[];
    centerCanvas?: Array<number>;
  };
 
  private _previewData?: PreviewData = {
    preview: null,
    element: null,
    timerStart: 0,
    timer: null,
    startPoint: [NaN, NaN],
    isDrag: false,
  };
 
  constructor(
    toolProps: PublicToolProps = {},
    defaultToolProps: ToolProps = {
      supportedInteractionTypes: ['Mouse', 'Touch'],
      configuration: {
        strategies: {
          FILL_INSIDE_CIRCLE: fillInsideCircle,
          ERASE_INSIDE_CIRCLE: eraseInsideCircle,
          FILL_INSIDE_SPHERE: fillInsideSphere,
          ERASE_INSIDE_SPHERE: eraseInsideSphere,
          THRESHOLD_INSIDE_CIRCLE: thresholdInsideCircle,
          THRESHOLD_INSIDE_SPHERE: thresholdInsideSphere,
        },
        strategySpecificConfiguration: {
          THRESHOLD: {
            threshold: [-150, -70], // E.g. CT Fat // Only used during threshold strategies.
          },
        },
        defaultStrategy: 'FILL_INSIDE_CIRCLE',
        activeStrategy: 'FILL_INSIDE_CIRCLE',
        thresholdVolumeId: null,
        brushSize: 25,
        preview: {
          // Have to enable the preview to use this
          enabled: false,
          previewColors: {},
          // The time before showing a preview
          previewTimeMs: 250,
          // The distance to move to show a preview before preview time expired
          previewMoveDistance: 8,
          // The distance to drag before being considered a drag rather than click
          dragMoveDistance: 4,
          // The time to consider a mouse click a drag when moved less than dragMoveDistance
          dragTimeMs: 500,
        },
        actions: {
          [StrategyCallbacks.AcceptPreview]: {
            method: StrategyCallbacks.AcceptPreview,
            bindings: [
              {
                key: 'Enter',
              },
            ],
          },
          [StrategyCallbacks.RejectPreview]: {
            method: StrategyCallbacks.RejectPreview,
            bindings: [
              {
                key: 'Escape',
              },
            ],
          },
        },
      },
    }
  ) {
    super(toolProps, defaultToolProps);
  }
 
  onSetToolPassive = (evt) => {
    this.disableCursor();
  };
 
  onSetToolEnabled = () => {
    this.disableCursor();
  };
 
  onSetToolDisabled = (evt) => {
    this.disableCursor();
  };
 
  private disableCursor() {
    this._hoverData = undefined;
    this.rejectPreview();
  }
 
  createEditData(element) {
    const enabledElement = getEnabledElement(element);
    const { viewport } = enabledElement;
 
    const toolGroupId = this.toolGroupId;
 
    const activeSegmentationRepresentation =
      activeSegmentation.getActiveSegmentationRepresentation(toolGroupId);
    if (!activeSegmentationRepresentation) {
      throw new Error(
        'No active segmentation detected, create a segmentation representation before using the brush tool'
      );
    }
 
    const { segmentationId, type, segmentationRepresentationUID } =
      activeSegmentationRepresentation;
 
    if (type === SegmentationRepresentations.Contour) {
      throw new Error('Not implemented yet');
    }
 
    const segmentsLocked = segmentLocking.getLockedSegments(segmentationId);
 
    const { representationData } =
      segmentationState.getSegmentation(segmentationId);
 
    const labelmapData =
      representationData[SegmentationRepresentations.Labelmap];
 
    if (isVolumeSegmentation(labelmapData, viewport)) {
      const { volumeId } = representationData[
        type
      ] as LabelmapSegmentationDataVolume;
      const actors = viewport.getActors();
 
      const isStackViewport = viewport instanceof StackViewport;
 
      if (isStackViewport) {
        const event = new CustomEvent(Enums.Events.ERROR_EVENT, {
          detail: {
            type: 'Segmentation',
            message: 'Cannot perform brush operation on the selected viewport',
          },
          cancelable: true,
        });
        eventTarget.dispatchEvent(event);
        return null;
      }
 
      // we used to take the first actor here but we should take the one that is
      // probably the same size as the segmentation volume
      const volumes = actors.map((actorEntry) =>
        cache.getVolume(actorEntry.referenceId)
      );
 
      const segmentationVolume = cache.getVolume(volumeId);
 
      const referencedVolumeIdToThreshold =
        volumes.find((volume) =>
          csUtils.isEqual(volume.dimensions, segmentationVolume.dimensions)
        )?.volumeId || volumes[0]?.volumeId;
 
      return {
        volumeId,
        referencedVolumeId:
          this.configuration.thresholdVolumeId ?? referencedVolumeIdToThreshold,
        segmentsLocked,
        segmentationRepresentationUID,
      };
    } else {
      const { imageIdReferenceMap } =
        labelmapData as LabelmapSegmentationDataStack;
 
      const currentImageId = viewport.getCurrentImageId();
 
      if (!imageIdReferenceMap.get(currentImageId)) {
        // if there is no stack segmentation slice for the current image
        // we should not allow the user to perform any operation
        return;
      }
 
      // here we should identify if we can perform sphere manipulation
      // for these stack of images, if the metadata is not present
      // to create a volume or if there are inconsistencies between
      // the image metadata we should not allow the sphere manipulation
      // and should throw an error or maybe simply just allow circle manipulation
      // and not sphere manipulation
      if (this.configuration.activeStrategy.includes('SPHERE')) {
        throw new Error(
          'Sphere manipulation is not supported for stacks of image segmentations yet'
        );
        // Todo: add sphere (volumetric) manipulation support for stacks of images
        // we should basically check if the stack constructs a valid volume
        // meaning all the metadata is present and consistent
        // then we use a VoxelManager mapping to map a volume like appearance
        // for the stack data.
        // csUtils.isValidVolume(referencedImageIds
      }
 
      return {
        imageIdReferenceMap,
        segmentsLocked,
        segmentationRepresentationUID,
      };
    }
  }
 
  preMouseDownCallback = (
    evt: EventTypes.MouseDownActivateEventType
  ): boolean => {
    const eventData = evt.detail;
    const { element } = eventData;
    const enabledElement = getEnabledElement(element);
    const { renderingEngine } = enabledElement;
 
    this._editData = this.createEditData(element);
    this._activateDraw(element);
 
    hideElementCursor(element);
 
    evt.preventDefault();
 
    // This might be a mouse down
    this._previewData.isDrag = false;
    this._previewData.timerStart = Date.now();
 
    const hoverData = this._hoverData || this.createHoverData(element);
 
    triggerAnnotationRenderForViewportUIDs(
      renderingEngine,
      hoverData.viewportIdsToRender
    );
 
    this.applyActiveStrategyCallback(
      enabledElement,
      this.getOperationData(element),
      StrategyCallbacks.OnInteractionStart
    );
 
    return true;
  };
 
  /**
   * This call will be made when the mouse moves and the tool is active, but
   * not actually drawing at the moment.
   * The behavior is:
   *    1. Update the cursor
   *    2. Call the active strategy event 'preview' and 'rejectPreview'
   *       on the mouse cursor position on a periodic basis to create a preview
   *       when configured to do so.
   *
   * The preview will be shown after the mouse has been stationary for 250 ms.
   * Any preview will be cancelled (immediately) after moving outside the center
   * distance.
   * As well, if the mouse moves but stays inside the center area for 250 ms,
   * then the cancel will happen with a new preview being added.
   *
   * See mouse up details for how the preview gets accepted.
   *
   * The preview also needs to be cancelled on changing tools.
   */
  mouseMoveCallback = (evt: EventTypes.InteractionEventType): void => {
    if (this.mode === ToolModes.Active) {
      this.updateCursor(evt);
      if (!this.configuration.preview.enabled) {
        return;
      }
      const { previewTimeMs, previewMoveDistance, dragMoveDistance } =
        this.configuration.preview;
      const { currentPoints, element } = evt.detail;
      const { canvas } = currentPoints;
 
      const { preview, startPoint, timer, timerStart, isDrag } =
        this._previewData;
      const delta = vec2.distance(canvas, startPoint);
      const time = Date.now() - timerStart;
      if (
        delta > previewMoveDistance ||
        (time > previewTimeMs && delta > dragMoveDistance)
      ) {
        if (timer) {
          window.clearTimeout(timer);
          this._previewData.timer = null;
        }
        if (preview && !isDrag) {
          this.rejectPreview(element);
        }
      }
      if (!this._previewData.timer) {
        const timer = window.setTimeout(this.previewCallback, 250);
        Object.assign(this._previewData, {
          timerStart: Date.now(),
          timer,
          startPoint: canvas,
          element,
        });
      }
    }
  };
 
  previewCallback = () => {
    if (this._previewData.preview) {
      return;
    }
    this._previewData.timer = null;
    this._previewData.preview = this.applyActiveStrategyCallback(
      getEnabledElement(this._previewData.element),
      this.getOperationData(this._previewData.element),
      StrategyCallbacks.Preview
    );
  };
 
  private createHoverData(element, centerCanvas?) {
    const enabledElement = getEnabledElement(element);
    const { viewport } = enabledElement;
 
    const camera = viewport.getCamera();
    const { viewPlaneNormal, viewUp } = camera;
 
    const viewportIdsToRender = [viewport.id];
 
    const {
      segmentIndex,
      segmentationId,
      segmentationRepresentationUID,
      segmentColor,
    } = this.getActiveSegmentationData() || {};
 
    // Center of circle in canvas Coordinates
    const brushCursor = {
      metadata: {
        viewPlaneNormal: <Types.Point3>[...viewPlaneNormal],
        viewUp: <Types.Point3>[...viewUp],
        FrameOfReferenceUID: viewport.getFrameOfReferenceUID(),
        referencedImageId: '',
        toolName: this.getToolName(),
        segmentColor,
      },
      data: {},
    };
 
    return {
      brushCursor,
      centerCanvas,
      segmentIndex,
      segmentationId,
      segmentationRepresentationUID,
      segmentColor,
      viewportIdsToRender,
    };
  }
 
  private getActiveSegmentationData() {
    const toolGroupId = this.toolGroupId;
 
    const activeSegmentationRepresentation =
      activeSegmentation.getActiveSegmentationRepresentation(toolGroupId);
    if (!activeSegmentationRepresentation) {
      console.warn(
        'No active segmentation detected, create one before using the brush tool'
      );
      return;
    }
 
    const { segmentationRepresentationUID, segmentationId } =
      activeSegmentationRepresentation;
    const segmentIndex =
      segmentIndexController.getActiveSegmentIndex(segmentationId);
 
    const segmentColor = segmentationConfig.color.getColorForSegmentIndex(
      toolGroupId,
      segmentationRepresentationUID,
      segmentIndex
    );
 
    return {
      segmentIndex,
      segmentationId,
      segmentationRepresentationUID,
      segmentColor,
    };
  }
 
  /**
   * Updates the cursor position and whether it is showing or not.
   * Can be over-ridden to add more cursor details or a preview.
   */
  protected updateCursor(evt: EventTypes.InteractionEventType) {
    const eventData = evt.detail;
    const { element } = eventData;
    const { currentPoints } = eventData;
    const centerCanvas = currentPoints.canvas;
    this._hoverData = this.createHoverData(element, centerCanvas);
 
    this._calculateCursor(element, centerCanvas);
 
    if (!this._hoverData) {
      return;
    }
 
    triggerAnnotationRenderForViewportUIDs(
      getEnabledElement(element).renderingEngine,
      this._hoverData.viewportIdsToRender
    );
  }
 
  private _dragCallback = (evt: EventTypes.InteractionEventType): void => {
    const eventData = evt.detail;
    const { element, currentPoints } = eventData;
    const enabledElement = getEnabledElement(element);
    const { renderingEngine } = enabledElement;
 
    this.updateCursor(evt);
 
    const { viewportIdsToRender } = this._hoverData;
 
    triggerAnnotationRenderForViewportUIDs(
      renderingEngine,
      viewportIdsToRender
    );
 
    const delta = vec2.distance(
      currentPoints.canvas,
      this._previewData.startPoint
    );
    const { dragTimeMs, dragMoveDistance } = this.configuration.preview;
    if (
      !this._previewData.isDrag &&
      this._previewData.preview &&
      Date.now() - this._previewData.timerStart < dragTimeMs &&
      delta < dragMoveDistance
    ) {
      // If we are showing a preview, then don't start dragging quite immediately
      // so that click up can accept the preview.
      return;
    }
 
    this._previewData.preview = this.applyActiveStrategy(
      enabledElement,
      this.getOperationData(element)
    );
    this._previewData.element = element;
    // Add a bit of time to the timer start so small accidental movements dont
    // cause issues on clicking
    this._previewData.timerStart = Date.now() + dragTimeMs;
    this._previewData.isDrag = true;
    this._previewData.startPoint = currentPoints.canvas;
  };
 
  protected getOperationData(element?) {
    const editData = this._editData || this.createEditData(element);
 
    const {
      segmentIndex,
      segmentationId,
      segmentationRepresentationUID,
      brushCursor,
    } = this._hoverData || this.createHoverData(element);
    const { data, metadata = {} } = brushCursor || {};
    const { viewPlaneNormal, viewUp } = metadata;
    const operationData = {
      ...editData,
      points: data?.handles?.points,
      segmentIndex,
      previewColors: this.configuration.preview.enabled
        ? this.configuration.preview.previewColors
        : null,
      viewPlaneNormal,
      toolGroupId: this.toolGroupId,
      segmentationId,
      segmentationRepresentationUID,
      viewUp,
      strategySpecificConfiguration:
        this.configuration.strategySpecificConfiguration,
      // Provide the preview information so that data can be used directly
      preview: this._previewData?.preview,
    };
    return operationData;
  }
 
  private _calculateCursor(element, centerCanvas) {
    const enabledElement = getEnabledElement(element);
    const { viewport } = enabledElement;
    const { canvasToWorld } = viewport;
    const camera = viewport.getCamera();
    const { brushSize } = this.configuration;
 
    const viewUp = vec3.fromValues(
      camera.viewUp[0],
      camera.viewUp[1],
      camera.viewUp[2]
    );
    const viewPlaneNormal = vec3.fromValues(
      camera.viewPlaneNormal[0],
      camera.viewPlaneNormal[1],
      camera.viewPlaneNormal[2]
    );
    const viewRight = vec3.create();
 
    vec3.cross(viewRight, viewUp, viewPlaneNormal);
 
    // in the world coordinate system, the brushSize is the radius of the circle
    // in mm
    const centerCursorInWorld: Types.Point3 = canvasToWorld([
      centerCanvas[0],
      centerCanvas[1],
    ]);
 
    const bottomCursorInWorld = vec3.create();
    const topCursorInWorld = vec3.create();
    const leftCursorInWorld = vec3.create();
    const rightCursorInWorld = vec3.create();
 
    // Calculate the bottom and top points of the circle in world coordinates
    for (let i = 0; i <= 2; i++) {
      bottomCursorInWorld[i] = centerCursorInWorld[i] - viewUp[i] * brushSize;
      topCursorInWorld[i] = centerCursorInWorld[i] + viewUp[i] * brushSize;
      leftCursorInWorld[i] = centerCursorInWorld[i] - viewRight[i] * brushSize;
      rightCursorInWorld[i] = centerCursorInWorld[i] + viewRight[i] * brushSize;
    }
 
    if (!this._hoverData) {
      return;
    }
 
    const { brushCursor } = this._hoverData;
    const { data } = brushCursor;
 
    if (data.handles === undefined) {
      data.handles = {};
    }
 
    data.handles.points = [
      bottomCursorInWorld,
      topCursorInWorld,
      leftCursorInWorld,
      rightCursorInWorld,
    ];
 
    const activeStrategy = this.configuration.activeStrategy;
    const strategy = this.configuration.strategies[activeStrategy];
 
    // Note: i don't think this is the best way to implement this
    // but don't think we have a better way to do it for now
    if (typeof strategy.computeInnerCircleRadius === 'function') {
      strategy.computeInnerCircleRadius({
        configuration: this.configuration,
        viewport,
      });
    }
 
    data.invalidated = false;
  }
 
  /**
   * The end callback call is made when the mouse is released.  This will
   * perform another active strategy render event to render the final position.
   * As well, the finish strategy callback will be made during this time.
   */
  private _endCallback = (evt: EventTypes.InteractionEventType): void => {
    const eventData = evt.detail;
    const { element } = eventData;
    const enabledElement = getEnabledElement(element);
 
    const operationData = this.getOperationData(element);
    // Don't re-fill when the preview is showing and the user clicks again
    // otherwise the new area of hover may get filled, which is unexpected
    if (!this._previewData.preview && !this._previewData.isDrag) {
      this.applyActiveStrategy(enabledElement, operationData);
    }
 
    this._deactivateDraw(element);
 
    resetElementCursor(element);
 
    this.updateCursor(evt);
 
    this._editData = null;
 
    this.applyActiveStrategyCallback(
      enabledElement,
      operationData,
      StrategyCallbacks.OnInteractionEnd
    );
 
    if (!this._previewData.isDrag) {
      this.acceptPreview(element);
    }
  };
 
  /**
   * Cancels any preview view being shown, resetting any segments being shown.
   */
  public rejectPreview(element = this._previewData.element) {
    if (!element || !this._previewData.preview) {
      return;
    }
    const enabledElement = getEnabledElement(element);
    this.applyActiveStrategyCallback(
      enabledElement,
      this.getOperationData(element),
      StrategyCallbacks.RejectPreview
    );
    this._previewData.preview = null;
    this._previewData.isDrag = false;
  }
 
  /**
   * Accepts a preview, marking it as the active segment.
   */
  public acceptPreview(element = this._previewData.element) {
    if (!element) {
      return;
    }
    const enabledElement = getEnabledElement(element);
 
    this.applyActiveStrategyCallback(
      enabledElement,
      this.getOperationData(element),
      StrategyCallbacks.AcceptPreview
    );
    this._previewData.isDrag = false;
    this._previewData.preview = null;
  }
 
  /**
   * Add event handlers for the modify event loop, and prevent default event propagation.
   */
  private _activateDraw = (element: HTMLDivElement): void => {
    element.addEventListener(
      Events.MOUSE_UP,
      this._endCallback as EventListener
    );
    element.addEventListener(
      Events.MOUSE_DRAG,
      this._dragCallback as EventListener
    );
    element.addEventListener(
      Events.MOUSE_CLICK,
      this._endCallback as EventListener
    );
  };
 
  /**
   * Add event handlers for the modify event loop, and prevent default event prapogation.
   */
  private _deactivateDraw = (element: HTMLDivElement): void => {
    element.removeEventListener(
      Events.MOUSE_UP,
      this._endCallback as EventListener
    );
    element.removeEventListener(
      Events.MOUSE_DRAG,
      this._dragCallback as EventListener
    );
    element.removeEventListener(
      Events.MOUSE_CLICK,
      this._endCallback as EventListener
    );
  };
 
  public invalidateBrushCursor() {
    if (this._hoverData === undefined) {
      return;
    }
    const { data } = this._hoverData.brushCursor;
 
    data.invalidated = true;
 
    // Todo: figure out if other brush metadata (other than segment color) should get updated
    // during the brush cursor invalidation
    const { segmentColor } = this.getActiveSegmentationData() || {};
    this._hoverData.brushCursor.metadata.segmentColor = segmentColor;
  }
 
  renderAnnotation(
    enabledElement: Types.IEnabledElement,
    svgDrawingHelper: SVGDrawingHelper
  ): void {
    if (!this._hoverData) {
      return;
    }
 
    const { viewport } = enabledElement;
 
    const viewportIdsToRender = this._hoverData.viewportIdsToRender;
 
    if (!viewportIdsToRender.includes(viewport.id)) {
      return;
    }
 
    const brushCursor = this._hoverData.brushCursor;
 
    if (brushCursor.data.invalidated === true) {
      const { centerCanvas } = this._hoverData;
      const { element } = viewport;
 
      // This can be set true when changing the brush size programmatically
      // whilst the cursor is being rendered.
      this._calculateCursor(element, centerCanvas);
    }
 
    const toolMetadata = brushCursor.metadata;
    if (!toolMetadata) {
      return;
    }
 
    const annotationUID = toolMetadata.brushCursorUID;
 
    const data = brushCursor.data;
    const { points } = data.handles;
    const canvasCoordinates = points.map((p) => viewport.worldToCanvas(p));
 
    const bottom = canvasCoordinates[0];
    const top = canvasCoordinates[1];
 
    const center = [
      Math.floor((bottom[0] + top[0]) / 2),
      Math.floor((bottom[1] + top[1]) / 2),
    ];
 
    const radius = Math.abs(bottom[1] - Math.floor((bottom[1] + top[1]) / 2));
 
    const color = `rgb(${toolMetadata.segmentColor?.slice(0, 3) || [0, 0, 0]})`;
 
    // If rendering engine has been destroyed while rendering
    if (!viewport.getRenderingEngine()) {
      console.warn('Rendering Engine has been destroyed');
      return;
    }
 
    const circleUID = '0';
    drawCircleSvg(
      svgDrawingHelper,
      annotationUID,
      circleUID,
      center as Types.Point2,
      radius,
      {
        color,
      }
    );
 
    const activeStrategy = this.configuration.activeStrategy;
    const { dynamicRadiusInCanvas } = this.configuration
      .strategySpecificConfiguration[activeStrategy] || {
      dynamicRadiusInCanvas: 0,
    };
 
    if (dynamicRadiusInCanvas) {
      const circleUID1 = '1';
      drawCircleSvg(
        svgDrawingHelper,
        annotationUID,
        circleUID1,
        center as Types.Point2,
        dynamicRadiusInCanvas,
        {
          color,
        }
      );
    }
  }
}
 
BrushTool.toolName = 'Brush';
export default BrushTool;