All files / packages/tools/src/stateManagement/segmentation SegmentationStateManager.ts

64.48% Statements 69/107
50% Branches 24/48
65.71% Functions 23/35
64.48% Lines 69/107

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                                        1x 1x 1x   1x                   1x                                   1x     1x 1x               45x                                 42x       20x             101x                 152x 138x                   20x           20x                       431x   431x 229x     202x                                                               20x 16x             20x       20x                 30x                                               37x   37x   37x       37x                                               20x   20x                   20x 20x   20x     20x             20x   20x   20x                                                                                                   33x   33x 2x     31x             2x         2x       2x                                                   2x         2x       2x                                                                                 2x   2x 2x               2x     2x                       20x       20x                                             40x     40x 18x       22x 20x 20x         2x 4x     2x             2x 2x 4x       2x                 1x    
import cloneDeep from 'lodash.clonedeep';
import type { Types } from '@cornerstonejs/core';
import { utilities as csUtils } from '@cornerstonejs/core';
 
import { SegmentationRepresentations } from '../../enums';
import getDefaultContourConfig from '../../tools/displayTools/Contour/contourConfig';
import getDefaultLabelmapConfig from '../../tools/displayTools/Labelmap/labelmapConfig';
import getDefaultSurfaceConfig from '../../tools/displayTools/Surface/surfaceConfig';
import type {
  RepresentationConfig,
  Segmentation,
  SegmentationRepresentationConfig,
  SegmentationState,
  SegmentSpecificRepresentationConfig,
  ToolGroupSpecificRepresentation,
  ToolGroupSpecificRepresentations,
} from '../../types/SegmentationStateTypes';
 
// Initialize the default configuration
// Note: when we get other representations, we should set their default representations too.
const defaultLabelmapConfig = getDefaultLabelmapConfig();
const defaultContourConfig = getDefaultContourConfig();
const defaultSurfaceConfig = getDefaultSurfaceConfig();
 
const newGlobalConfig: SegmentationRepresentationConfig = {
  renderInactiveSegmentations: true,
  representations: {
    [SegmentationRepresentations.Labelmap]: defaultLabelmapConfig,
    [SegmentationRepresentations.Contour]: defaultContourConfig,
    [SegmentationRepresentations.Surface]: defaultSurfaceConfig,
  },
};
 
/* A default initial state for the segmentation manager. */
const initialDefaultState: SegmentationState = {
  colorLUT: [],
  segmentations: [],
  globalConfig: newGlobalConfig,
  toolGroups: {},
};
 
/**
 * The SegmentationStateManager Class is responsible for managing the state of the
 * segmentations. It stores the segmentations and toolGroup specific representations
 * of the segmentation. It also stores a global config and a toolGroup specific
 * config. Note that this is a singleton state manager.
 */
export default class SegmentationStateManager {
  private state: SegmentationState;
  public readonly uid: string;
 
  constructor(uid?: string) {
    Iif (!uid) {
      uid = csUtils.uuidv4();
    }
    this.state = cloneDeep(initialDefaultState);
    this.uid = uid;
  }
 
  /**
   * It returns a copy of the current state of the segmentation
   * @returns A deep copy of the state.
   */
  getState(): SegmentationState {
    return this.state;
  }
 
  /**
   * It returns an array of toolGroupIds currently in the segmentation state.
   * @returns An array of strings.
   */
  getToolGroups(): string[] {
    return Object.keys(this.state.toolGroups);
  }
 
  /**
   * It returns the colorLUT at the specified index.
   * @param lutIndex - The index of the color LUT to retrieve.
   * @returns A ColorLUT object.
   */
  getColorLUT(lutIndex: number): Types.ColorLUT | undefined {
    return this.state.colorLUT[lutIndex];
  }
 
  getNextColorLUTIndex(): number {
    return this.state.colorLUT.length;
  }
 
  /**
   * Reset the state to the default state
   */
  resetState(): void {
    this.state = cloneDeep(initialDefaultState);
  }
 
  /**
   * Given a segmentation Id, return the segmentation state
   * @param segmentationId - The id of the segmentation to get the data for.
   * @returns - The segmentation data
   */
  getSegmentation(segmentationId: string): Segmentation | undefined {
    return this.state.segmentations.find(
      (segmentation) => segmentation.segmentationId === segmentationId
    );
  }
 
  /**
   * It adds a segmentation to the segmentations array.
   * @param segmentation - Segmentation
   */
  addSegmentation(segmentation: Segmentation): void {
    // Check if the segmentation already exists with the segmentationId
    Iif (this.getSegmentation(segmentation.segmentationId)) {
      throw new Error(
        `Segmentation with id ${segmentation.segmentationId} already exists`
      );
    }
 
    this.state.segmentations.push(segmentation);
  }
 
  /**
   * Get the segmentation representations for a tool group
   * @param toolGroupId - string
   * @returns A list of segmentation representations.
   */
  getSegmentationRepresentations(
    toolGroupId: string
  ): ToolGroupSpecificRepresentations | undefined {
    const toolGroupSegRepresentationsWithConfig =
      this.state.toolGroups[toolGroupId];
 
    if (!toolGroupSegRepresentationsWithConfig) {
      return;
    }
 
    return toolGroupSegRepresentationsWithConfig.segmentationRepresentations;
  }
 
  /**
   * Returns an array of all segmentation representations for all tool groups.
   * @returns An array of ToolGroupSpecificRepresentations.
   */
  getAllSegmentationRepresentations(): Record<
    string,
    ToolGroupSpecificRepresentation[]
  > {
    const toolGroupSegReps: Record<string, ToolGroupSpecificRepresentation[]> =
      {};
    Object.entries(this.state.toolGroups).forEach(
      ([toolGroupId, toolGroupSegRepresentationsWithConfig]) => {
        toolGroupSegReps[toolGroupId] =
          toolGroupSegRepresentationsWithConfig.segmentationRepresentations;
      }
    );
    return toolGroupSegReps;
  }
 
  /**
   * Add a new segmentation representation to the toolGroup's segmentation representations.
   * @param toolGroupId - The Id of the tool group .
   * @param segmentationRepresentation - The segmentation representation to add.
   */
  addSegmentationRepresentation(
    toolGroupId: string,
    segmentationRepresentation: ToolGroupSpecificRepresentation
  ): void {
    // Initialize the default toolGroup state if not created yet
    if (!this.state.toolGroups[toolGroupId]) {
      this.state.toolGroups[toolGroupId] = {
        segmentationRepresentations: [],
        config: {} as SegmentationRepresentationConfig,
      };
    }
 
    // local toolGroupSpecificSegmentationState
    this.state.toolGroups[toolGroupId].segmentationRepresentations.push(
      segmentationRepresentation
    );
 
    this._handleActiveSegmentation(toolGroupId, segmentationRepresentation);
  }
 
  /**
   * Get the global config containing both representation config
   * and render inactive segmentations config
   * @returns The global config object.
   */
  getGlobalConfig(): SegmentationRepresentationConfig {
    return this.state.globalConfig;
  }
 
  /**
   * It sets the global segmentation config including both representation config
   * and render inactive segmentations config
   * @param config - The global configuration for the segmentations.
   */
  setGlobalConfig(config: SegmentationRepresentationConfig): void {
    this.state.globalConfig = config;
  }
 
  /**
   * Given a toolGroupId and a segmentationRepresentationUID, return the segmentation
   * representation for that tool group.
   * @param toolGroupId - The Id of the tool group
   * @param segmentationRepresentationUID - string
   * @returns The segmentation representation.
   */
  getSegmentationRepresentationByUID(
    toolGroupId: string,
    segmentationRepresentationUID: string
  ): ToolGroupSpecificRepresentation | undefined {
    const toolGroupSegRepresentations =
      this.getSegmentationRepresentations(toolGroupId);
 
    const segmentationData = toolGroupSegRepresentations?.find(
      (representation) =>
        representation.segmentationRepresentationUID ===
        segmentationRepresentationUID
    );
 
    return segmentationData;
  }
 
  /**
   * It removes the segmentation from the segmentation state.
   * @param segmentationId - The id of the segmentation to remove.
   */
  removeSegmentation(segmentationId: string): void {
    this.state.segmentations = this.state.segmentations.filter(
      (segmentation) => segmentation.segmentationId !== segmentationId
    );
  }
 
  /**
   * Remove a segmentation representation from the toolGroup
   * @param toolGroupId - The Id of the tool group
   * @param segmentationRepresentationUID - the uid of the segmentation representation to remove
   * @param immediate - If true, the viewport will be updated immediately.
   */
  removeSegmentationRepresentation(
    toolGroupId: string,
    segmentationRepresentationUID: string
  ): void {
    const toolGroupSegmentationRepresentations =
      this.getSegmentationRepresentations(toolGroupId);
 
    Iif (
      !toolGroupSegmentationRepresentations ||
      !toolGroupSegmentationRepresentations.length
    ) {
      throw new Error(
        `No viewport specific segmentation state found for viewport ${toolGroupId}`
      );
    }
 
    const state =
      toolGroupSegmentationRepresentations as ToolGroupSpecificRepresentations;
    const index = state.findIndex(
      (segData) =>
        segData.segmentationRepresentationUID === segmentationRepresentationUID
    );
 
    Iif (index === -1) {
      console.warn(
        `No viewport specific segmentation state data found for viewport ${toolGroupId} and segmentation data UID ${segmentationRepresentationUID}`
      );
    }
 
    const removedSegmentationRepresentation =
      toolGroupSegmentationRepresentations[index];
 
    toolGroupSegmentationRepresentations.splice(index, 1);
 
    this._handleActiveSegmentation(
      toolGroupId,
      removedSegmentationRepresentation
    );
  }
 
  /**
   * Set the active segmentation data for a tool group
   * @param toolGroupId - The Id of the tool group that owns the
   * segmentation data.
   * @param segmentationRepresentationUID - string
   */
  setActiveSegmentationRepresentation(
    toolGroupId: string,
    segmentationRepresentationUID: string
  ): void {
    const toolGroupSegmentations =
      this.getSegmentationRepresentations(toolGroupId);
 
    if (!toolGroupSegmentations || !toolGroupSegmentations.length) {
      throw new Error(
        `No segmentation data found for toolGroupId: ${toolGroupId}`
      );
    }
 
    const segmentationData = toolGroupSegmentations.find(
      (segmentationData) =>
        segmentationData.segmentationRepresentationUID ===
        segmentationRepresentationUID
    );
 
    if (!segmentationData) {
      throw new Error(
        `No segmentation data found for segmentation data UID ${segmentationRepresentationUID}`
      );
    }
 
    segmentationData.active = true;
    this._handleActiveSegmentation(toolGroupId, segmentationData);
  }
 
  /**
   * Given a tool group Id it returns the tool group specific representation config
   *
   * @param toolGroupId - The Id of the tool group
   * @returns A SegmentationConfig object.
   */
  getToolGroupSpecificConfig(
    toolGroupId: string
  ): SegmentationRepresentationConfig | undefined {
    const toolGroupStateWithConfig = this.state.toolGroups[toolGroupId];
 
    if (!toolGroupStateWithConfig) {
      return;
    }
 
    return toolGroupStateWithConfig.config;
  }
 
  getSegmentationRepresentationSpecificConfig(
    toolGroupId: string,
    segmentationRepresentationUID: string
  ): RepresentationConfig {
    const segmentationRepresentation = this.getSegmentationRepresentationByUID(
      toolGroupId,
      segmentationRepresentationUID
    );
 
    Iif (!segmentationRepresentation) {
      return;
    }
 
    return segmentationRepresentation.segmentationRepresentationSpecificConfig;
  }
 
  setSegmentationRepresentationSpecificConfig(
    toolGroupId: string,
    segmentationRepresentationUID: string,
    config: RepresentationConfig
  ): void {
    const segmentationRepresentation = this.getSegmentationRepresentationByUID(
      toolGroupId,
      segmentationRepresentationUID
    );
 
    if (!segmentationRepresentation) {
      return;
    }
 
    segmentationRepresentation.segmentationRepresentationSpecificConfig =
      config;
  }
 
  getSegmentSpecificConfig(
    toolGroupId: string,
    segmentationRepresentationUID: string,
    segmentIndex: number
  ): RepresentationConfig {
    const segmentationRepresentation = this.getSegmentationRepresentationByUID(
      toolGroupId,
      segmentationRepresentationUID
    );
 
    Iif (!segmentationRepresentation) {
      return;
    }
 
    return segmentationRepresentation.segmentSpecificConfig[segmentIndex];
  }
 
  setSegmentSpecificConfig(
    toolGroupId: string,
    segmentationRepresentationUID: string,
    config: SegmentSpecificRepresentationConfig,
    options?: {
      clear: false;
    }
  ): void {
    const segmentationRepresentation = this.getSegmentationRepresentationByUID(
      toolGroupId,
      segmentationRepresentationUID
    );
 
    if (!segmentationRepresentation) {
      return;
    }
 
    if (!segmentationRepresentation.segmentSpecificConfig || options?.clear) {
      segmentationRepresentation.segmentSpecificConfig = {};
    }
 
    Object.keys(config).forEach((key) => {
      segmentationRepresentation.segmentSpecificConfig[key] = config[key];
    });
  }
 
  /**
   * Set the segmentation representations config for a given tool group. It will create a new
   * tool group specific config if one does not exist.
   *
   * @param toolGroupId - The Id of the tool group that the segmentation
   * belongs to.
   * @param config - SegmentationConfig
   */
  setSegmentationRepresentationConfig(
    toolGroupId: string,
    config: SegmentationRepresentationConfig
  ): void {
    let toolGroupStateWithConfig = this.state.toolGroups[toolGroupId];
 
    Eif (!toolGroupStateWithConfig) {
      this.state.toolGroups[toolGroupId] = {
        segmentationRepresentations: [],
        config: {
          renderInactiveSegmentations: true,
          representations: {},
        },
      };
 
      toolGroupStateWithConfig = this.state.toolGroups[toolGroupId];
    }
 
    toolGroupStateWithConfig.config = {
      ...toolGroupStateWithConfig.config,
      ...config,
    };
  }
 
  /**
   * It adds a color LUT to the state.
   * @param colorLUT - ColorLUT
   * @param lutIndex - The index of the color LUT table to add.
   */
  addColorLUT(colorLUT: Types.ColorLUT, lutIndex: number): void {
    Iif (this.state.colorLUT[lutIndex]) {
      console.warn('Color LUT table already exists, overwriting');
    }
 
    this.state.colorLUT[lutIndex] = cloneDeep(colorLUT);
  }
 
  /**
   * Removes a color LUT to the state.
   * @param colorLUTIndex - The index of the color LUT table to remove.
   */
  removeColorLUT(colorLUTIndex: number): void {
    delete this.state.colorLUT[colorLUTIndex];
  }
 
  /**
   * It handles the active segmentation representation based on the active status of the
   * segmentation representation that was added or removed.
   *
   * @param toolGroupId - The Id of the tool group that the segmentation representation belongs to.
   * @param recentlyAddedOrRemovedSegmentationRepresentation - ToolGroupSpecificSegmentationData
   */
  _handleActiveSegmentation(
    toolGroupId: string,
    recentlyAddedOrRemovedSegmentationRepresentation: ToolGroupSpecificRepresentation
  ): void {
    const segmentationRepresentations =
      this.getSegmentationRepresentations(toolGroupId);
 
    // 1. If there is no segmentation representations, return early
    if (segmentationRepresentations.length === 0) {
      return;
    }
 
    // 2. If there is only one segmentation representation, make that one active
    if (segmentationRepresentations.length === 1) {
      segmentationRepresentations[0].active = true;
      return;
    }
 
    // 3. If removed Segmentation representation was active, make the first one active
    const activeSegmentationRepresentations =
      segmentationRepresentations.filter(
        (representation) => representation.active
      );
 
    Iif (activeSegmentationRepresentations.length === 0) {
      segmentationRepresentations[0].active = true;
      return;
    }
 
    // 4. If the added segmentation representation is active, make other segmentation
    // representations inactive
    Eif (recentlyAddedOrRemovedSegmentationRepresentation.active) {
      segmentationRepresentations.forEach((representation) => {
        if (
          representation.segmentationRepresentationUID !==
          recentlyAddedOrRemovedSegmentationRepresentation.segmentationRepresentationUID
        ) {
          representation.active = false;
        }
      });
    }
 
    // 5. if added/removed segmentation is is inactive, do nothing
  }
}
 
const defaultSegmentationStateManager = new SegmentationStateManager('DEFAULT');
export { defaultSegmentationStateManager };