All files / extensions/cornerstone/src/services/ToolGroupService ToolGroupService.ts

89.91% Statements 107/119
69.23% Branches 18/26
93.1% Functions 27/29
89.91% Lines 107/119

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            130x                                     130x         130x       130x 130x 130x 130x   130x     130x 130x   130x   130x 130x 130x 130x 130x 130x 130x   130x       12x       130x                   998x   998x   1x   1x       1x 1x   1x                   1x     998x 998x       16615x       223041x 223041x       4337x 4337x 213x     4124x       21x 21x   21x       38x 38x               119x   119x 38x     81x   81x   81x                   432x             432x 432x       432x     432x             512x         512x 512x   512x       512x       512x   512x 512x       512x 512x 512x                 90x 90x       90x 90x       90x                     90x 90x 90x               512x   512x 512x 1917x       512x 339x 6202x       512x 232x 285x       512x 279x 777x           512x 1362x 9181x 1092x       8089x         512x 512x     512x 339x     512x 232x     512x 279x         1986x 1986x 2956x     1986x           1986x   1986x 581x     130x  
import { ToolGroupManager, Enums, Types } from '@cornerstonejs/tools';
import { eventTarget } from '@cornerstonejs/core';
 
import { Types as OhifTypes, pubSubServiceInterface } from '@ohif/core';
import getActiveViewportEnabledElement from '../../utils/getActiveViewportEnabledElement';
 
const EVENTS = {
  VIEWPORT_ADDED: 'event::cornerstone::toolgroupservice:viewportadded',
  TOOLGROUP_CREATED: 'event::cornerstone::toolgroupservice:toolgroupcreated',
  TOOL_ACTIVATED: 'event::cornerstone::toolgroupservice:toolactivated',
  PRIMARY_TOOL_ACTIVATED: 'event::cornerstone::toolgroupservice:primarytoolactivated',
};
 
type Tool = {
  toolName: string;
  bindings?: typeof Enums.MouseBindings | Enums.KeyboardBindings;
};
 
type Tools = {
  active: Tool[];
  passive?: Tool[];
  enabled?: Tool[];
  disabled?: Tool[];
};
 
export default class ToolGroupService {
  public static REGISTRATION = {
    name: 'toolGroupService',
    altName: 'ToolGroupService',
    create: ({ servicesManager }: OhifTypes.Extensions.ExtensionParams): ToolGroupService => {
      return new ToolGroupService(servicesManager);
    },
  };
 
  servicesManager: AppTypes.ServicesManager;
  cornerstoneViewportService: any;
  viewportGridService: any;
  uiNotificationService: any;
  private toolGroupIds: Set<string> = new Set();
  /**
   * Service-specific
   */
  listeners: { [key: string]: Function[] };
  EVENTS: { [key: string]: string };
 
  constructor(servicesManager: AppTypes.ServicesManager) {
    const { cornerstoneViewportService, viewportGridService, uiNotificationService } =
      servicesManager.services;
    this.cornerstoneViewportService = cornerstoneViewportService;
    this.viewportGridService = viewportGridService;
    this.uiNotificationService = uiNotificationService;
    this.listeners = {};
    this.EVENTS = EVENTS;
    Object.assign(this, pubSubServiceInterface);
 
    this._init();
  }
 
  onModeExit() {
    this.destroy();
  }
 
  private _init() {
    eventTarget.addEventListener(Enums.Events.TOOL_ACTIVATED, this._onToolActivated);
  }
 
  /**
   * Retrieves a tool group from the ToolGroupManager by tool group ID.
   * If no tool group ID is provided, it retrieves the tool group of the active viewport.
   * @param toolGroupId - Optional ID of the tool group to retrieve.
   * @returns The tool group or undefined if it is not found.
   */
  public getToolGroup(toolGroupId?: string): Types.IToolGroup | void {
    let toolGroupIdToUse = toolGroupId;
 
    if (!toolGroupIdToUse) {
      // Use the active viewport's tool group if no tool group id is provided
      const enabledElement = getActiveViewportEnabledElement(this.viewportGridService);
 
      Iif (!enabledElement) {
        return;
      }
 
      const { renderingEngineId, viewportId } = enabledElement;
      const toolGroup = ToolGroupManager.getToolGroupForViewport(viewportId, renderingEngineId);
 
      Iif (!toolGroup) {
        console.warn(
          'No tool group found for viewportId:',
          viewportId,
          'and renderingEngineId:',
          renderingEngineId
        );
        return;
      }
 
      toolGroupIdToUse = toolGroup.id;
    }
 
    const toolGroup = ToolGroupManager.getToolGroup(toolGroupIdToUse);
    return toolGroup;
  }
 
  public getToolGroupIds(): string[] {
    return Array.from(this.toolGroupIds);
  }
 
  public getToolGroupForViewport(viewportId: string): Types.IToolGroup | void {
    const renderingEngine = this.cornerstoneViewportService.getRenderingEngine();
    return ToolGroupManager.getToolGroupForViewport(viewportId, renderingEngine.id);
  }
 
  public getActiveToolForViewport(viewportId: string): string {
    const toolGroup = this.getToolGroupForViewport(viewportId);
    if (!toolGroup) {
      return;
    }
 
    return toolGroup.getActivePrimaryMouseButtonTool();
  }
 
  public destroy(): void {
    ToolGroupManager.destroy();
    this.toolGroupIds = new Set();
 
    eventTarget.removeEventListener(Enums.Events.TOOL_ACTIVATED, this._onToolActivated);
  }
 
  public destroyToolGroup(toolGroupId: string): void {
    ToolGroupManager.destroyToolGroup(toolGroupId);
    this.toolGroupIds.delete(toolGroupId);
  }
 
  public removeViewportFromToolGroup(
    viewportId: string,
    renderingEngineId: string,
    deleteToolGroupIfEmpty?: boolean
  ): void {
    const toolGroup = ToolGroupManager.getToolGroupForViewport(viewportId, renderingEngineId);
 
    if (!toolGroup) {
      return;
    }
 
    toolGroup.removeViewports(renderingEngineId, viewportId);
 
    const viewportIds = toolGroup.getViewportIds();
 
    Iif (viewportIds.length === 0 && deleteToolGroupIfEmpty) {
      ToolGroupManager.destroyToolGroup(toolGroup.id);
    }
  }
 
  public addViewportToToolGroup(
    viewportId: string,
    renderingEngineId: string,
    toolGroupId?: string
  ): void {
    Iif (!toolGroupId) {
      // If toolGroupId is not provided, add the viewport to all toolGroups
      const toolGroups = ToolGroupManager.getAllToolGroups();
      toolGroups.forEach(toolGroup => {
        toolGroup.addViewport(viewportId, renderingEngineId);
      });
    } else {
      let toolGroup = ToolGroupManager.getToolGroup(toolGroupId);
      Iif (!toolGroup) {
        toolGroup = this.createToolGroup(toolGroupId);
      }
 
      toolGroup.addViewport(viewportId, renderingEngineId);
    }
 
    this._broadcastEvent(EVENTS.VIEWPORT_ADDED, {
      viewportId,
      toolGroupId,
    });
  }
 
  public createToolGroup(toolGroupId: string): Types.IToolGroup {
    Iif (this.getToolGroup(toolGroupId)) {
      throw new Error(`ToolGroup ${toolGroupId} already exists`);
    }
 
    // if the toolGroup doesn't exist, create it
    const toolGroup = ToolGroupManager.createToolGroup(toolGroupId);
    this.toolGroupIds.add(toolGroupId);
 
    this._broadcastEvent(EVENTS.TOOLGROUP_CREATED, {
      toolGroupId,
    });
 
    return toolGroup;
  }
 
  public addToolsToToolGroup(toolGroupId: string, tools: Array<Tool>, configs: any = {}): void {
    const toolGroup = ToolGroupManager.getToolGroup(toolGroupId);
    // this.changeConfigurationIfNecessary(toolGroup, volumeId);
    this._addTools(toolGroup, tools, configs);
    this._setToolsMode(toolGroup, tools);
  }
 
  public createToolGroupAndAddTools(toolGroupId: string, tools: Array<Tool>): Types.IToolGroup {
    const toolGroup = this.createToolGroup(toolGroupId);
    this.addToolsToToolGroup(toolGroupId, tools);
    return toolGroup;
  }
  /**
   * Get the tool's configuration based on the tool name and tool group id
   * @param toolGroupId - The id of the tool group that the tool instance belongs to.
   * @param toolName - The name of the tool
   * @returns The configuration of the tool.
   */
  public getToolConfiguration(toolGroupId: string, toolName: string) {
    const toolGroup = ToolGroupManager.getToolGroup(toolGroupId);
    Iif (!toolGroup) {
      return null;
    }
 
    const tool = toolGroup.getToolInstance(toolName);
    Iif (!tool) {
      return null;
    }
 
    return tool.configuration;
  }
 
  /**
   * Set the tool instance configuration. This will update the tool instance configuration
   * on the toolGroup
   * @param toolGroupId - The id of the tool group that the tool instance belongs to.
   * @param toolName - The name of the tool
   * @param config - The configuration object that you want to set.
   */
  public setToolConfiguration(toolGroupId, toolName, config) {
    const toolGroup = ToolGroupManager.getToolGroup(toolGroupId);
    const toolInstance = toolGroup.getToolInstance(toolName);
    toolInstance.configuration = config;
  }
 
  public getActivePrimaryMouseButtonTool(toolGroupId?: string): string {
    return this.getToolGroup(toolGroupId)?.getActivePrimaryMouseButtonTool();
  }
 
  private _setToolsMode(toolGroup, tools) {
    const { active, passive, enabled, disabled } = tools;
 
    if (active) {
      active.forEach(({ toolName, bindings }) => {
        toolGroup.setToolActive(toolName, { bindings });
      });
    }
 
    if (passive) {
      passive.forEach(({ toolName }) => {
        toolGroup.setToolPassive(toolName);
      });
    }
 
    if (enabled) {
      enabled.forEach(({ toolName }) => {
        toolGroup.setToolEnabled(toolName);
      });
    }
 
    if (disabled) {
      disabled.forEach(({ toolName }) => {
        toolGroup.setToolDisabled(toolName);
      });
    }
  }
 
  private _addTools(toolGroup, tools) {
    const addTools = tools => {
      tools.forEach(({ toolName, parentTool, configuration }) => {
        if (parentTool) {
          toolGroup.addToolInstance(toolName, parentTool, {
            ...configuration,
          });
        } else {
          toolGroup.addTool(toolName, { ...configuration });
        }
      });
    };
 
    if (tools.active) {
      addTools(tools.active);
    }
 
    if (tools.passive) {
      addTools(tools.passive);
    }
 
    if (tools.enabled) {
      addTools(tools.enabled);
    }
 
    if (tools.disabled) {
      addTools(tools.disabled);
    }
  }
 
  private _onToolActivated = (evt: Types.EventTypes.ToolActivatedEventType) => {
    const { toolGroupId, toolName, toolBindingsOptions } = evt.detail;
    const isPrimaryTool = toolBindingsOptions.bindings?.some(
      binding => binding.mouseButton === Enums.MouseBindings.Primary
    );
 
    const callbackProps = {
      toolGroupId,
      toolName,
      toolBindingsOptions,
    };
 
    this._broadcastEvent(EVENTS.TOOL_ACTIVATED, callbackProps);
 
    if (isPrimaryTool) {
      this._broadcastEvent(EVENTS.PRIMARY_TOOL_ACTIVATED, callbackProps);
    }
  };
}