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

65.23% Statements 137/210
57.66% Branches 79/137
68.57% Functions 24/35
64.82% Lines 129/199

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                                              1x                                       390x 78x                                               833x 833x 2x     2x     831x                     88x 88x 88x 88x   88x               88x             88x                 88x   88x           88x       88x                                                                                               92x   92x           92x     92x 18x   92x             92x   92x 92x 92x                         6x   6x 6x 6x 6x   6x 1x     6x 5x       6x     5x 5x                                                                                                                                     73x 73x   73x 1x       1x     72x             72x       72x             72x   69x 69x   69x       69x   69x           72x         72x 72x     72x 72x   72x 69x     3x 3x 3x 3x       72x 3x   72x                       2x   2x 1x       1x         1x 1x                     1x 1x         1x 1x         1x 1x   1x     1x                     17x   17x 1x       1x     16x         16x 16x   16x 15x     16x                     2x   2x 1x       1x     1x         1x 1x   1x     1x                 1x   1x       1x                 95x 95x 98x 98x                     161x   161x             161x                         161x   161x   161x 136x       25x   25x   25x       25x       164x 119x         119x       119x 119x                                                                                                                                       150x 140x                   90x 12x                              
import { MouseBindings, ToolModes } from '../../enums';
import cloneDeep from 'lodash.clonedeep';
import get from 'lodash.get';
import {
  getRenderingEngine,
  getRenderingEngines,
  getEnabledElementByIds,
  Settings,
} from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
import { state } from '../index';
import {
  IToolBinding,
  IToolClassReference,
  IToolGroup,
  SetToolBindingsType,
  ToolOptionsType,
} from '../../types';
 
import { MouseCursor, SVGMouseCursor } from '../../cursors';
import { initElementCursor } from '../../cursors/elementCursor';
import deepmerge from '../../utilities/deepMerge';
 
const { Active, Passive, Enabled, Disabled } = ToolModes;
 
/**
 * 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 = {};
  _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.`
      );
      return;
    }
 
    return toolInstance;
  }
  /**
   * 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
   */
  addTool(toolName: string, configuration = {}): 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;
 
    if (!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 {
    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);
    }
  }
 
  /**
   * 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);
      }
    }
  }
 
  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);
      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 (typeof toolInstance.onSetToolActive === 'function') {
      toolInstance.onSetToolActive();
    }
    this._renderViewports();
  }
 
  /**
   * 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
   */
  public setToolPassive(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;
    }
 
    // 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,
      }
    );
 
    // Remove the primary button bindings without modifiers, if they exist
    toolOptions.bindings = toolOptions.bindings.filter(
      (binding) =>
        binding.mouseButton !== MouseBindings.Primary || 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();
  }
 
  /**
   * 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();
  }
 
  /**
   * 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.toolOptions[toolName] = toolOptions;
    toolInstance.mode = Disabled;
 
    Iif (typeof toolInstance.onSetToolDisabled === 'function') {
      toolInstance.onSetToolDisabled();
    }
    this._renderViewports();
  }
 
  /**
   * 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];
 
    Iif (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: Record<any, any>,
    overwrite?: boolean
  ): boolean {
    if (this._toolInstances[toolName] === undefined) {
      console.warn(
        `Tool ${toolName} not present, can't set tool configuration.`
      );
      return false;
    }
 
    let _configuration;
 
    if (overwrite) {
      _configuration = configuration;
    } else {
      _configuration = deepmerge(
        this._toolInstances[toolName].configuration,
        configuration
      );
    }
 
    this._toolInstances[toolName].configuration = _configuration;
 
    this._renderViewports();
 
    return true;
  }
 
  /**
   * 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
    );
 
    return cloneDeep(_configuration);
  }
 
  /**
   * 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) {
    return toolOptions?.bindings?.some(
      (binding) =>
        binding.mouseButton === MouseBindings.Primary &&
        binding.modifierKey === undefined
    );
  }
 
  /**
   * It re-renders the viewports in the toolGroup
   */
  private _renderViewports(): void {
    this.viewportsInfo.forEach(({ renderingEngineId, viewportId }) => {
      getRenderingEngine(renderingEngineId).renderViewport(viewportId);
    });
  }
}
 
function hasSameBinding(
  binding1: IToolBinding,
  binding2: IToolBinding
): boolean {
  if (binding1.mouseButton !== binding2.mouseButton) {
    return false;
  }
 
  return binding1.modifierKey === binding2.modifierKey;
}