All files / packages/tools/src/store/ToolGroupManager ToolGroup.ts

68.8% Statements 172/250
55.22% Branches 74/134
77.77% Functions 35/45
68.69% Lines 169/246

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                                                            1x   1x                               102x 102x 102x 102x       102x 102x     102x               2x             5x                 1370x 1370x 2x     2x     1368x                                   10x                         121x 121x 121x   121x               121x             121x                 121x   121x           121x       121x               3x     3x   3x             3x   3x   3x             3x                                 124x       124x   124x           124x     124x 30x   124x             124x   124x 124x 124x     124x           124x                       13x   13x 13x 13x 13x   13x 1x     13x 12x       13x     12x 12x       13x           13x                                                                                                                                         97x   97x 1x       1x     96x             96x       96x             96x   92x 92x   92x       92x   92x           96x         96x 96x     96x 96x   96x 92x     4x 4x 4x 4x           96x 92x 92x         92x     96x 7x   96x   96x           96x 96x                                   5x   5x 1x       1x         4x 4x                   4x         4x   1x   1x         4x 4x         4x 4x   4x     4x             4x                     18x   18x 1x       1x     17x         17x 17x   17x 15x     17x 17x                     2x   2x 1x       1x     1x         1x   1x 1x   1x     1x 1x                 10x   10x 3x     7x                   128x 123x 123x                     228x   228x             228x                         228x   228x   228x 180x       48x   48x   48x       48x       232x 187x         187x       187x 187x                                                                                             323x                 295x                                                                                                                                                                     291x 291x 274x               118x 24x                             118x             118x                     275x     275x       275x    
import { MouseBindings, ToolModes } from '../../enums';
import get from 'lodash.get';
import cloneDeep from 'lodash.clonedeep';
import {
  triggerEvent,
  eventTarget,
  getRenderingEngine,
  getRenderingEngines,
  getEnabledElementByIds,
  Settings,
} from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
import { Events } from '../../enums';
import {
  ToolActivatedEventDetail,
  ToolModeChangedEventDetail,
} from '../../types/EventTypes';
import { ToolGroupManager, state } from '../index';
import {
  IToolBinding,
  IToolClassReference,
  IToolGroup,
  SetToolBindingsType,
  ToolOptionsType,
  ToolConfiguration,
} from '../../types';
 
import { MouseCursor, SVGMouseCursor } from '../../cursors';
import { initElementCursor } from '../../cursors/elementCursor';
 
const { Active, Passive, Enabled, Disabled } = ToolModes;
 
const PRIMARY_BINDINGS = [{ mouseButton: MouseBindings.Primary }];
 
/**
 * ToolGroup class which is a container for tools and their modes and states.
 * In Cornerstone3DTools, you need to create a tool group in order to use the
 * tools. ToolGroup is a way to share tool configuration, state (enabled, disabled, etc.)
 * across a set of viewports. Tools can set to be activated, enabled or disabled
 * in a toolGroup. You should not directly instantiate a ToolGroup. You need to use
 * ToolGroupManager helpers to create a new toolGroup or get a reference to an existing toolGroup.
 *
 * ```js
 * const toolGroup = csTools.ToolGroupManager.createToolGroup('toolGroupId')
 * ```
 */
export default class ToolGroup implements IToolGroup {
  id: string;
  viewportsInfo = [];
  toolOptions = {};
  currentActivePrimaryToolName: string | null = null;
  prevActivePrimaryToolName: string | null = null;
  /**
   * Options used for restoring a tool
   */
  restoreToolOptions = {};
  _toolInstances = {};
 
  constructor(id: string) {
    this.id = id;
  }
 
  /**
   * Get the viewport IDs of all the viewports in the current viewport
   * @returns An array of viewport IDs.
   */
  getViewportIds(): string[] {
    return this.viewportsInfo.map(({ viewportId }) => viewportId);
  }
 
  /**
   * Returns the toolGroup viewports info which is an array of {viewportId, renderingEngineId}
   */
  getViewportsInfo(): Array<Types.IViewportId> {
    return this.viewportsInfo.slice();
  }
 
  /**
   * Get the tool instance for a given tool name in the toolGroup
   * @param toolName - The name of the tool.
   * @returns A tool instance.
   */
  public getToolInstance(toolInstanceName: string) {
    const toolInstance = this._toolInstances[toolInstanceName];
    if (!toolInstance) {
      console.warn(
        `'${toolInstanceName}' is not registered with this toolGroup (${this.id}).`
      );
      return;
    }
 
    return toolInstance;
  }
 
  /**
   * Retrieves the tool instances associated with this tool group.
   *
   * @returns A record containing the tool instances, where the keys are the tool names and the values are the tool instances.
   */
  public getToolInstances(): Record<string, any> {
    return this._toolInstances;
  }
 
  /**
   * Check if a tool is already added to the tool group
   * @param toolName - Tool name
   * @returns True if the tool is already added or false otherwise
   */
  hasTool(toolName: string): boolean {
    return !!this._toolInstances[toolName];
  }
 
  /**
   * Add a tool to the tool group with the given tool name and tool configuration.
   * Note that adding a tool to a tool group will not automatically set the tool
   * to be active. You must call setToolActive or setToolPassive and other methods
   * to set the tool to be active or passive or in other states.
   *
   * @param toolName - string
   * @param configuration - Tool configuration objects and a custom statistics calculator if needed
   */
  addTool(toolName: string, configuration: ToolConfiguration = {}): void {
    const toolDefinition = state.tools[toolName];
    const hasToolName = typeof toolName !== 'undefined' && toolName !== '';
    const localToolInstance = this.toolOptions[toolName];
 
    Iif (!hasToolName) {
      console.warn(
        'Tool with configuration did not produce a toolName: ',
        configuration
      );
      return;
    }
 
    Iif (!toolDefinition) {
      console.warn(
        `'${toolName}' is not registered with the library. You need to use cornerstoneTools.addTool to register it.`
      );
      return;
    }
 
    Iif (localToolInstance) {
      console.warn(
        `'${toolName}' is already registered for ToolGroup ${this.id}.`
      );
      return;
    }
 
    // Should these be renamed higher up, so we don't have to alias?
    // Wrap in try-catch so 3rd party tools don't explode?
    const { toolClass: ToolClass } = toolDefinition;
 
    const toolProps = {
      name: toolName,
      toolGroupId: this.id,
      configuration,
    };
 
    const instantiatedTool = new ToolClass(toolProps);
 
    // API instead of directly exposing schema?
    // Maybe not here, but feels like a "must" for any method outside of the ToolGroup itself
    this._toolInstances[toolName] = instantiatedTool;
  }
 
  public addToolInstance(
    toolName: string,
    parentClassName: string,
    configuration = {}
  ): void {
    let ToolClassToUse = state.tools[toolName]
      ?.toolClass as IToolClassReference;
 
    Eif (!ToolClassToUse) {
      // get parent class constructor
      const ParentClass = state.tools[parentClassName]
        .toolClass as IToolClassReference;
 
      // Todo: could not find a way to make this work with typescript
      // @ts-ignore
      class ToolInstance extends ParentClass {}
      // @ts-ignore
      ToolInstance.toolName = toolName;
      // @ts-ignore
      ToolClassToUse = ToolInstance;
 
      state.tools[toolName] = {
        toolClass: ToolInstance as IToolClassReference,
      };
    }
 
    // add the tool to the toolGroup
    // @ts-ignore
    this.addTool(ToolClassToUse.toolName, configuration);
  }
 
  //   class InstanceTool extends parentClass;
  // InstanceTool.constructor.toolName = name;
  // addTool(InstanceTool,configuration)
  /**
   * Add a viewport to the ToolGroup. It accepts viewportId and optional
   * renderingEngineId parameter. If renderingEngineId is not provided,
   * it checks if cornerstone-core has more than one renderingEngine; If so,
   * it will throw an error. If cornerstone-core has only one renderingEngine,
   * it will use that renderingEngine.
   *
   * @param viewportId - The unique identifier for the viewport.
   * @param renderingEngineId - The rendering engine to use.
   */
  public addViewport(viewportId: string, renderingEngineId?: string): void {
    Iif (typeof viewportId !== 'string') {
      throw new Error('viewportId must be defined and be a string');
    }
 
    const renderingEngines = getRenderingEngines();
 
    Iif (!renderingEngineId && renderingEngines.length > 1) {
      throw new Error(
        'You must specify a renderingEngineId when there are multiple rendering engines.'
      );
    }
 
    const renderingEngineUIDToUse = renderingEngineId || renderingEngines[0].id;
 
    // Don't overwrite if it already exists
    Eif (
      !this.viewportsInfo.some(({ viewportId: vpId }) => vpId === viewportId)
    ) {
      this.viewportsInfo.push({
        viewportId,
        renderingEngineId: renderingEngineUIDToUse,
      });
    }
 
    // Handle the newly added viewport's mouse cursor
    const toolName = this.getActivePrimaryMouseButtonTool();
 
    const runtimeSettings = Settings.getRuntimeSettings();
    Eif (runtimeSettings.get('useCursors')) {
      this.setViewportsCursorByToolName(toolName);
    }
 
    const eventDetail = {
      toolGroupId: this.id,
      viewportId,
      renderingEngineId: renderingEngineUIDToUse,
    };
 
    triggerEvent(eventTarget, Events.TOOLGROUP_VIEWPORT_ADDED, eventDetail);
  }
 
  /**
   * Removes viewport from the toolGroup. If only renderingEngineId is defined
   * it removes all the viewports with the same renderingEngineId, if viewportId
   * is also provided, it will remove that specific viewport from the ToolGroup.
   *
   * @param renderingEngineId - renderingEngine id
   * @param viewportId - viewport id
   */
  public removeViewports(renderingEngineId: string, viewportId?: string): void {
    const indices = [];
 
    this.viewportsInfo.forEach((vpInfo, index) => {
      let match = false;
      Eif (vpInfo.renderingEngineId === renderingEngineId) {
        match = true;
 
        if (viewportId && vpInfo.viewportId !== viewportId) {
          match = false;
        }
      }
      if (match) {
        indices.push(index);
      }
    });
 
    if (indices.length) {
      // Note: Traverse the array backwards, such that when we remove items we
      // do not immediately mess up our loop indicies.
      for (let i = indices.length - 1; i >= 0; i--) {
        this.viewportsInfo.splice(indices[i], 1);
      }
    }
 
    const eventDetail = {
      toolGroupId: this.id,
      viewportId,
      renderingEngineId,
    };
 
    triggerEvent(eventTarget, Events.TOOLGROUP_VIEWPORT_REMOVED, eventDetail);
  }
 
  public setActiveStrategy(toolName: string, strategyName: string) {
    const toolInstance = this._toolInstances[toolName];
 
    if (toolInstance === undefined) {
      console.warn(
        `Tool ${toolName} not added to toolGroup, can't set tool configuration.`
      );
 
      return;
    }
 
    toolInstance.setActiveStrategy(strategyName);
  }
 
  setToolMode(
    toolName: string,
    mode: ToolModes,
    options = {} as SetToolBindingsType
  ): void {
    if (!toolName) {
      console.warn('setToolMode: toolName must be defined');
      return;
    }
 
    if (mode === ToolModes.Active) {
      this.setToolActive(
        toolName,
        options || this.restoreToolOptions[toolName]
      );
      return;
    }
 
    if (mode === ToolModes.Passive) {
      this.setToolPassive(toolName);
      return;
    }
 
    if (mode === ToolModes.Enabled) {
      this.setToolEnabled(toolName);
      return;
    }
 
    if (mode === ToolModes.Disabled) {
      this.setToolDisabled(toolName);
      return;
    }
 
    console.warn('setToolMode: mode must be defined');
  }
 
  /**
   * Set the tool mode on the toolGroup to be Active. This means the tool
   * can be actively used by the defined bindings (e.g., Mouse primary click)
   *
   * - Can be actively used by mouse/touch events mapped to its `ToolBinding`s.
   * - Can add data if an annotation tool.
   * - Can be passively interacted by grabbing a tool or its handles.
   * - Renders data if the tool has a `renderAnnotation` method.
   *
   * @param toolName - tool name
   * @param toolBindingsOptions - tool bindings
   */
  public setToolActive(
    toolName: string,
    toolBindingsOptions = {} as SetToolBindingsType
  ): void {
    const toolInstance = this._toolInstances[toolName];
 
    if (toolInstance === undefined) {
      console.warn(
        `Tool ${toolName} not added to toolGroup, can't set tool mode.`
      );
 
      return;
    }
 
    Iif (!toolInstance) {
      console.warn(
        `'${toolName}' instance ${toolInstance} is not registered with this toolGroup, can't set tool mode.`
      );
      return;
    }
 
    const prevBindings: IToolBinding[] = this.toolOptions[toolName]
      ? this.toolOptions[toolName].bindings
      : [];
 
    const newBindings = toolBindingsOptions.bindings
      ? toolBindingsOptions.bindings
      : [];
 
    // combine the new bindings with the previous bindings to avoid duplicates
    // it allows duplicated mouse buttons as long as they don't have same
    // modifier keys.
    const bindingsToUse = [...prevBindings, ...newBindings].reduce(
      (unique, binding) => {
        const TouchBinding = binding.numTouchPoints !== undefined;
        const MouseBinding = binding.mouseButton !== undefined;
 
        Eif (
          !unique.some((obj) => hasSameBinding(obj, binding)) &&
          (TouchBinding || MouseBinding)
        ) {
          unique.push(binding);
        }
        return unique;
      },
      []
    );
 
    // We should not override the bindings if they are already set
    const toolOptions: ToolOptionsType = {
      bindings: bindingsToUse,
      mode: Active,
    };
 
    this.toolOptions[toolName] = toolOptions;
    this._toolInstances[toolName].mode = Active;
 
    // reset the mouse cursor if tool has left click binding
    const runtimeSettings = Settings.getRuntimeSettings();
    const useCursor = runtimeSettings.get('useCursors');
 
    if (this._hasMousePrimaryButtonBinding(toolBindingsOptions) && useCursor) {
      this.setViewportsCursorByToolName(toolName);
    } else {
      // reset to default cursor only if there is no other tool with primary binding
      const activeToolIdentifier = this.getActivePrimaryMouseButtonTool();
      Eif (!activeToolIdentifier && useCursor) {
        const cursor = MouseCursor.getDefinedCursor('default');
        this._setCursorForViewports(cursor);
      }
    }
 
    // if it is a primary tool binding, we should store it as the previous primary tool
    // so that we can restore it when the tool is disabled if desired
    if (this._hasMousePrimaryButtonBinding(toolBindingsOptions)) {
      if (this.prevActivePrimaryToolName === null) {
        this.prevActivePrimaryToolName = toolName;
      } else E{
        this.prevActivePrimaryToolName = this.currentActivePrimaryToolName;
      }
 
      this.currentActivePrimaryToolName = toolName;
    }
 
    if (typeof toolInstance.onSetToolActive === 'function') {
      toolInstance.onSetToolActive();
    }
    this._renderViewports();
 
    const eventDetail: ToolActivatedEventDetail = {
      toolGroupId: this.id,
      toolName,
      toolBindingsOptions,
    };
 
    triggerEvent(eventTarget, Events.TOOL_ACTIVATED, eventDetail);
    this._triggerToolModeChangedEvent(toolName, Active, toolBindingsOptions);
  }
 
  /**
   * Set the tool mode on the toolGroup to be Passive.
   *
   * - Can be passively interacted by grabbing a tool or its handles.
   * - Renders data if the tool has a `renderAnnotation` method.
   *
   * @param toolName - tool name
   * @param options - Options used when setting the tool as passive
   *  - removeAllBindings: only the primary button bindings are removed but
   *  if this parameter is set to true all bindings are removed.
   */
  public setToolPassive(
    toolName: string,
    options?: { removeAllBindings?: boolean | IToolBinding[] }
  ): void {
    const toolInstance = this._toolInstances[toolName];
 
    if (toolInstance === undefined) {
      console.warn(
        `Tool ${toolName} not added to toolGroup, can't set tool mode.`
      );
 
      return;
    }
 
    // We should only remove the primary button bindings and keep
    // the other ones (Zoom on right click)
    const prevToolOptions = this.getToolOptions(toolName);
    const toolOptions = Object.assign(
      {
        bindings: prevToolOptions ? prevToolOptions.bindings : [],
      },
      prevToolOptions,
      {
        mode: Passive,
      }
    );
 
    const matchBindings = Array.isArray(options?.removeAllBindings)
      ? options.removeAllBindings
      : this.getDefaultPrimaryBindings();
 
    // Remove the primary button bindings without modifiers, if they exist
    toolOptions.bindings = toolOptions.bindings.filter(
      (binding) =>
        options?.removeAllBindings !== true &&
        !matchBindings.some((matchBinding) =>
          hasSameBinding(binding, matchBinding)
        )
      //(binding.mouseButton !== defaultMousePrimary || binding.modifierKey)
    );
    // If there are other bindings, set the tool to be active
    let mode = Passive;
    Iif (toolOptions.bindings.length !== 0) {
      mode = Active;
      toolOptions.mode = mode;
    }
 
    this.toolOptions[toolName] = toolOptions;
    toolInstance.mode = mode;
 
    Iif (typeof toolInstance.onSetToolPassive === 'function') {
      toolInstance.onSetToolPassive();
    }
    this._renderViewports();
 
    // It would make sense to use `toolInstance.mode` as mode when setting a tool
    // as passive because it can still be actived in the end but `Passive` must
    // be used when synchronizing ToolGroups so that other ToolGroups can take the
    // same action (update tool bindings). Should the event have two different modes
    // to handle this special case?
    this._triggerToolModeChangedEvent(toolName, Passive);
  }
 
  /**
   * Set the tool mode on the toolGroup to be Enabled.
   *
   * - Renders data if the tool has a `renderAnnotation` method..
   *
   * @param toolName - tool name
   */
  public setToolEnabled(toolName: string): void {
    const toolInstance = this._toolInstances[toolName];
 
    if (toolInstance === undefined) {
      console.warn(
        `Tool ${toolName} not added to toolGroup, can't set tool mode.`
      );
 
      return;
    }
 
    const toolOptions = {
      bindings: [],
      mode: Enabled,
    };
 
    this.toolOptions[toolName] = toolOptions;
    toolInstance.mode = Enabled;
 
    if (typeof toolInstance.onSetToolEnabled === 'function') {
      toolInstance.onSetToolEnabled();
    }
 
    this._renderViewports();
    this._triggerToolModeChangedEvent(toolName, Enabled);
  }
 
  /**
   * Set the tool mode on the toolGroup to be Disabled.
   *
   * - Annotation does not render.
   *
   * @param toolName - tool name
   */
  public setToolDisabled(toolName: string): void {
    const toolInstance = this._toolInstances[toolName];
 
    if (toolInstance === undefined) {
      console.warn(
        `Tool ${toolName} not added to toolGroup, can't set tool mode.`
      );
 
      return;
    }
 
    const toolOptions = {
      bindings: [],
      mode: Disabled,
    };
 
    this.restoreToolOptions[toolName] = this.toolOptions[toolName];
 
    this.toolOptions[toolName] = toolOptions;
    toolInstance.mode = Disabled;
 
    Iif (typeof toolInstance.onSetToolDisabled === 'function') {
      toolInstance.onSetToolDisabled();
    }
    this._renderViewports();
    this._triggerToolModeChangedEvent(toolName, Disabled);
  }
 
  /**
   * Get the options for a given tool
   * @param toolName - The name of the tool.
   * @returns the tool options
   */
  public getToolOptions(toolName: string): ToolOptionsType {
    const toolOptionsForTool = this.toolOptions[toolName];
 
    if (toolOptionsForTool === undefined) {
      return;
    }
 
    return toolOptionsForTool;
  }
 
  /**
   * Find the name of the tool that is Active and has a primary button binding
   * (Mouse primary click)
   *
   * @returns The name of the tool
   */
  public getActivePrimaryMouseButtonTool(): string {
    return Object.keys(this.toolOptions).find((toolName) => {
      const toolOptions = this.toolOptions[toolName];
      return (
        toolOptions.mode === Active &&
        this._hasMousePrimaryButtonBinding(toolOptions)
      );
    });
  }
 
  public setViewportsCursorByToolName(
    toolName: string,
    strategyName?: string
  ): void {
    const cursor = this._getCursor(toolName, strategyName);
 
    this._setCursorForViewports(cursor);
  }
 
  private _getCursor(toolName: string, strategyName?: string): MouseCursor {
    let cursorName;
    let cursor;
 
    Iif (strategyName) {
      // Try combinations with strategyName first:
      // Try with toolName and toolInstanceName first.
      cursorName = `${toolName}.${strategyName}`;
 
      cursor = SVGMouseCursor.getDefinedCursor(cursorName, true);
 
      if (cursor) {
        return cursor;
      }
    }
 
    // Try with toolName and toolInstanceName first.
    cursorName = `${toolName}`;
 
    cursor = SVGMouseCursor.getDefinedCursor(cursorName, true);
 
    if (cursor) {
      return cursor;
    }
 
    // Try with just toolName.
    cursorName = toolName;
 
    cursor = SVGMouseCursor.getDefinedCursor(cursorName, true);
 
    Iif (cursor) {
      return cursor;
    }
 
    return MouseCursor.getDefinedCursor('default');
  }
 
  _setCursorForViewports(cursor: MouseCursor): void {
    this.viewportsInfo.forEach(({ renderingEngineId, viewportId }) => {
      const enabledElement = getEnabledElementByIds(
        viewportId,
        renderingEngineId
      );
 
      Iif (!enabledElement) {
        return;
      }
 
      const { viewport } = enabledElement;
      initElementCursor(viewport.element, cursor);
    });
  }
 
  /**
   * Set a configuration of a tool by the given toolName.
   * Use overwrite as true in case you want to overwrite any existing configuration (be careful, depending on config change it might break the annotation flow).
   */
  public setToolConfiguration(
    toolName: string,
    configuration: ToolConfiguration,
    overwrite?: boolean
  ): boolean {
    const toolInstance = this._toolInstances[toolName];
    if (toolInstance === undefined) {
      console.warn(
        `Tool ${toolName} not present, can't set tool configuration.`
      );
      return false;
    }
 
    let _configuration;
 
    if (overwrite) {
      _configuration = configuration;
    } else {
      // We should not deep copy here, it is the job of the application to
      // deep copy the configuration before passing it to the toolGroup, otherwise
      // some strange appending behaviour happens for the arrays
      _configuration = Object.assign(toolInstance.configuration, configuration);
    }
 
    toolInstance.configuration = _configuration;
 
    if (typeof toolInstance.onSetToolConfiguration === 'function') {
      toolInstance.onSetToolConfiguration();
    }
 
    this._renderViewports();
 
    return true;
  }
 
  /**
   * Returns the default mouse primary button.
   */
  public getDefaultMousePrimary(): MouseBindings {
    return MouseBindings.Primary;
  }
 
  /**
   * Gets an array of bindings that is the full primary binding.
   * Currently this is just the primary mouse button, but may be extended in the
   * future to include touch or other binding types.
   */
  public getDefaultPrimaryBindings(): IToolBinding[] {
    return PRIMARY_BINDINGS;
  }
 
  /**
   * Get the configuration of tool. It returns only the config for the given path (in case exists).
   * ConfigurationPath is the the path of the property to get separated by '.'.
   *
   * @example
   * getToolConfiguration('LengthTool', 'firstLevel.secondLevel')
   * // get from LengthTool instance the configuration value as being LengthToolInstance[configuration][firstLevel][secondLevel]
   */
  getToolConfiguration(toolName: string, configurationPath?: string): any {
    if (this._toolInstances[toolName] === undefined) {
      console.warn(
        `Tool ${toolName} not present, can't set tool configuration.`
      );
      return;
    }
 
    const _configuration =
      get(this._toolInstances[toolName].configuration, configurationPath) ||
      this._toolInstances[toolName].configuration;
 
    return cloneDeep(_configuration);
  }
 
  /**
   * Gets the name of the previously active tool.
   * @returns The name of the previously active tool.
   */
  public getPrevActivePrimaryToolName(): string {
    return this.prevActivePrimaryToolName;
  }
 
  /**
   *
   * @param newToolGroupId - Id of the new (clone) tool group
   * @param fnToolFilter - Function to filter which tools from this tool group
   * should be added to the new (clone) one. Example: only annotations tools
   * can be filtered and added to the new tool group.
   * @returns A new tool group that is a clone of this one
   */
  public clone(
    newToolGroupId,
    fnToolFilter: (toolName: string) => void = null
  ): IToolGroup {
    let toolGroup = ToolGroupManager.getToolGroup(newToolGroupId);
 
    if (toolGroup) {
      console.warn(`ToolGroup ${newToolGroupId} already exists`);
      return toolGroup;
    }
 
    toolGroup = ToolGroupManager.createToolGroup(newToolGroupId);
    fnToolFilter = fnToolFilter ?? (() => true);
 
    Object.keys(this._toolInstances)
      .filter(fnToolFilter)
      .forEach((toolName) => {
        const sourceToolInstance = this._toolInstances[toolName];
        const sourceToolOptions = this.toolOptions[toolName];
        const sourceToolMode = sourceToolInstance.mode;
 
        toolGroup.addTool(toolName);
 
        (toolGroup as unknown as ToolGroup).setToolMode(
          toolName,
          sourceToolMode,
          {
            bindings: sourceToolOptions.bindings ?? [],
          }
        );
      });
 
    return toolGroup;
  }
 
  /**
   * Check if the tool binding is set to be primary mouse button.
   * @param toolOptions - The options for the tool mode.
   * @returns A boolean value.
   */
  private _hasMousePrimaryButtonBinding(toolOptions) {
    const primaryBindings = this.getDefaultPrimaryBindings();
    return toolOptions?.bindings?.some((binding) =>
      primaryBindings.some((primary) => hasSameBinding(binding, primary))
    );
  }
 
  /**
   * It re-renders the viewports in the toolGroup
   */
  private _renderViewports(): void {
    this.viewportsInfo.forEach(({ renderingEngineId, viewportId }) => {
      getRenderingEngine(renderingEngineId).renderViewport(viewportId);
    });
  }
 
  /**
   * Trigger ToolModeChangedEvent when changing the tool mode
   * @param toolName - Tool name
   * @param mode - Tool mode
   * @param toolBindingsOptions - Binding options used when a tool is activated
   */
  private _triggerToolModeChangedEvent(
    toolName: string,
    mode: ToolModes,
    toolBindingsOptions?: SetToolBindingsType
  ): void {
    const eventDetail: ToolModeChangedEventDetail = {
      toolGroupId: this.id,
      toolName,
      mode,
      toolBindingsOptions,
    };
 
    triggerEvent(eventTarget, Events.TOOL_MODE_CHANGED, eventDetail);
  }
}
 
/**
 * Figure out if the two bindings are the same
 */
function hasSameBinding(
  binding1: IToolBinding,
  binding2: IToolBinding
): boolean {
  Iif (binding1.mouseButton !== binding2.mouseButton) {
    return false;
  }
  Iif (binding1.numTouchPoints !== binding2.numTouchPoints) {
    return false;
  }
 
  return binding1.modifierKey === binding2.modifierKey;
}