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

72.82% Statements 67/92
71.42% Branches 25/35
62.5% Functions 10/16
72.22% Lines 65/90

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                204x         204x       204x 204x     204x 204x                                 651x   651x               651x                         651x 651x         1x     651x       152x 499x   498x             1x               651x     651x   651x                                                                                                                                                                         1x 1x     1x 1x                           578x 498x 80x       498x 498x 578x   578x   578x   578x 412x   412x 412x     578x                 498x                           152x   152x 181x 181x 181x             181x 20x       20x 20x           20x       161x 161x 161x 161x       161x 130x   130x       130x     130x     161x                   152x             453x       130x 89x     41x   41x   204x      
import { Types } from '@ohif/core';
import { cache as cs3DCache, Enums, volumeLoader } from '@cornerstonejs/core';
 
import getCornerstoneViewportType from '../../utils/getCornerstoneViewportType';
import { loadDisplaySetData } from '../../utils/loadDisplaySetData';
import { StackViewportData, VolumeViewportData } from '../../types/CornerstoneCacheService';
import { VOLUME_LOADER_SCHEME } from '../../constants';
 
class CornerstoneCacheService {
  static REGISTRATION = {
    name: 'cornerstoneCacheService',
    altName: 'CornerstoneCacheService',
    create: ({ servicesManager }: Types.Extensions.ExtensionParams): CornerstoneCacheService => {
      return new CornerstoneCacheService(servicesManager);
    },
  };
 
  stackImageIds: Map<string, string[]> = new Map();
  volumeImageIds: Map<string, string[]> = new Map();
  readonly servicesManager: AppTypes.ServicesManager;
 
  constructor(servicesManager: AppTypes.ServicesManager) {
    this.servicesManager = servicesManager;
  }
 
  public getCacheSize() {
    return cs3DCache.getCacheSize();
  }
 
  public getCacheFreeSpace() {
    return cs3DCache.getBytesAvailable();
  }
 
  public async createViewportData(
    displaySets: Types.DisplaySet[],
    viewportOptions: AppTypes.ViewportGrid.GridViewportOptions,
    dataSource: unknown,
    initialImageIndex?: number
  ): Promise<StackViewportData | VolumeViewportData> {
    const viewportType = viewportOptions.viewportType as string;
 
    const cs3DViewportType = getCornerstoneViewportType(viewportType, displaySets);
    let viewportData: StackViewportData | VolumeViewportData;
 
    // Native Generic ("next") viewport types (e.g. PLANAR_NEXT) intentionally
    // collapse the stack/volume distinction into a single type, so they cannot
    // drive the stack-vs-volume data-builder decision below. Resolve the data
    // shape from the legacy mapping (which preserves that distinction) and keep
    // the resolved native type as the produced viewportData's viewportType.
    let dataShapeType = getCornerstoneViewportType(viewportType, displaySets, false);
 
    // A data overlay (fusion) of two or more reconstructable image display sets
    // must render as a volume viewport so the source and overlay share one
    // representation (volume slice). Without this, a next (PLANAR_NEXT) viewport
    // keeps the source in vtkImage (stack) mode while the added overlay is a
    // vtkVolumeSlice, producing the broken/unstable fusion. SEG/RT overlays are
    // non-reconstructable, so they are not affected.
    //
    // Scoped to the native (PLANAR_NEXT) path via cs3DViewportType — NOT the flag, and
    // NOT the legacy lane: a legacy stack-shaped reconstructable overlay must keep its
    // existing stack build so the flag-off path stays byte-identical.
    const isReconstructableFusion =
      displaySets.length > 1 && displaySets.every(ds => ds.isReconstructable);
    if (
      isReconstructableFusion &&
      dataShapeType === Enums.ViewportType.STACK &&
      cs3DViewportType === Enums.ViewportType.PLANAR_NEXT
    ) {
      dataShapeType = Enums.ViewportType.ORTHOGRAPHIC;
    }
 
    if (
      dataShapeType === Enums.ViewportType.ORTHOGRAPHIC ||
      dataShapeType === Enums.ViewportType.VOLUME_3D
    ) {
      viewportData = await this._getVolumeViewportData(dataSource, displaySets, cs3DViewportType);
    } else if (dataShapeType === Enums.ViewportType.STACK) {
      // Everything else looks like a stack
      viewportData = await this._getStackViewportData(
        dataSource,
        displaySets,
        initialImageIndex,
        cs3DViewportType
      );
    } else {
      viewportData = await this._getOtherViewportData(
        dataSource,
        displaySets,
        initialImageIndex,
        cs3DViewportType
      );
    }
 
    viewportData.viewportType = cs3DViewportType;
    // Persist the legacy stack/volume shape so consumers can distinguish stack from
    // volume content even when viewportType is a native Generic type (PLANAR_NEXT).
    viewportData.dataShapeType = dataShapeType;
 
    return viewportData;
  }
 
  public async invalidateViewportData(
    viewportData: VolumeViewportData | StackViewportData,
    invalidatedDisplaySetInstanceUID: string,
    dataSource,
    displaySetService
  ): Promise<VolumeViewportData | StackViewportData> {
    // Decide stack-vs-volume rebuild from the persisted data shape, NOT viewportType:
    // native viewports collapse both onto PLANAR_NEXT, so a native stack would
    // otherwise fall through to the volume rebuild and re-mount as volume data.
    // Falls back to viewportType for legacy/older viewportData (byte-identical off-path).
    const dataShapeType = viewportData.dataShapeType ?? viewportData.viewportType;
 
    Iif (dataShapeType === Enums.ViewportType.STACK) {
      const displaySet = displaySetService.getDisplaySetByUID(invalidatedDisplaySetInstanceUID);
      const imageIds = this._getCornerstoneStackImageIds(displaySet, dataSource);
 
      // remove images from the cache to be able to re-load them
      imageIds.forEach(imageId => {
        Iif (cs3DCache.getImageLoadObject(imageId)) {
          cs3DCache.removeImageLoadObject(imageId);
        }
      });
 
      return {
        // Preserve the original viewportType (legacy STACK or native PLANAR_NEXT);
        // the rebuilt data shape, not this field, drives the native re-mount dispatch.
        viewportType: viewportData.viewportType,
        dataShapeType: Enums.ViewportType.STACK,
        data: {
          StudyInstanceUID: displaySet.StudyInstanceUID,
          displaySetInstanceUID: invalidatedDisplaySetInstanceUID,
          imageIds,
        },
      };
    }
 
    // Todo: grab the volume and get the id from the viewport itself
    const volumeId = `${VOLUME_LOADER_SCHEME}:${invalidatedDisplaySetInstanceUID}`;
 
    const volume = cs3DCache.getVolume(volumeId);
 
    Iif (volume) {
      Iif (volume.imageIds) {
        // also for each imageId in the volume, remove the imageId from the cache
        // since that will hold the old metadata as well
 
        volume.imageIds.forEach(imageId => {
          Iif (cs3DCache.getImageLoadObject(imageId)) {
            cs3DCache.removeImageLoadObject(imageId, { force: true });
          }
        });
      }
 
      // this shouldn't be via removeVolumeLoadObject, since that will
      // remove the texture as well, but here we really just need a remove
      // from registry so that we load it again
      cs3DCache._volumeCache.delete(volumeId);
      this.volumeImageIds.delete(volumeId);
    }
 
    const displaySets = viewportData.data.map(({ displaySetInstanceUID }) =>
      displaySetService.getDisplaySetByUID(displaySetInstanceUID)
    );
 
    const newViewportData = await this._getVolumeViewportData(
      dataSource,
      displaySets,
      viewportData.viewportType
    );
    newViewportData.dataShapeType = dataShapeType;
 
    return newViewportData;
  }
 
  private async _getOtherViewportData(
    dataSource,
    displaySets,
    _initialImageIndex,
    viewportType: Enums.ViewportType
  ): Promise<StackViewportData> {
    // TODO - handle overlays and secondary display sets, but for now assume
    // the 1st display set is the one of interest
    const [displaySet] = displaySets;
    Iif (!displaySet.imageIds) {
      displaySet.imagesIds = this._getCornerstoneStackImageIds(displaySet, dataSource);
    }
    const { imageIds: data, viewportType: dsViewportType } = displaySet;
    return {
      viewportType: dsViewportType || viewportType,
      data: displaySets,
    };
  }
 
  private async _getStackViewportData(
    dataSource,
    displaySets,
    initialImageIndex,
    viewportType: Enums.ViewportType
  ): Promise<StackViewportData> {
    // Overlays are loaded before the loop below so that a segmentation can
    // back-fill the imageIds of the series it references.
    const overlayDisplaySets = displaySets.filter(ds => ds.isOverlayDisplaySet);
    for (const overlayDisplaySet of overlayDisplaySets) {
      await loadDisplaySetData(overlayDisplaySet, this.servicesManager);
    }
 
    // Ensuring the first non-overlay `displaySet` is always the primary one
    const StackViewportData = [];
    for (const displaySet of displaySets) {
      const { displaySetInstanceUID, StudyInstanceUID, isCompositeStack } = displaySet;
 
      await loadDisplaySetData(displaySet, this.servicesManager);
 
      let stackImageIds = this.stackImageIds.get(displaySet.displaySetInstanceUID);
 
      if (!stackImageIds) {
        stackImageIds = this._getCornerstoneStackImageIds(displaySet, dataSource);
        // assign imageIds to the displaySet
        displaySet.imageIds = stackImageIds;
        this.stackImageIds.set(displaySet.displaySetInstanceUID, stackImageIds);
      }
 
      StackViewportData.push({
        StudyInstanceUID,
        displaySetInstanceUID,
        isCompositeStack,
        imageIds: stackImageIds,
        initialImageIndex,
      });
    }
 
    return {
      viewportType,
      data: StackViewportData,
    };
  }
 
  private async _getVolumeViewportData(
    dataSource,
    displaySets,
    viewportType: Enums.ViewportType
  ): Promise<VolumeViewportData> {
    // Todo: Check the cache for multiple scenarios to see if we need to
    // decache the volume data from other viewports or not
 
    const volumeData = [];
 
    for (const displaySet of displaySets) {
      const { Modality } = displaySet;
      const isParametricMap = Modality === 'PMAP';
      const isSegOrRtstruct = Modality === 'SEG' || Modality === 'RTSTRUCT';
 
      // Don't create volumes for the displaySets that have custom load
      // function (e.g., SEG, RT, since they rely on the reference volumes
      // and they take care of their own loading after they are created in their
      // getSOPClassHandler method
 
      if (displaySet.load instanceof Function) {
        await loadDisplaySetData(displaySet, this.servicesManager);
 
        // Parametric maps have a `load` method but it should not be loaded in the
        // same way as SEG and RTSTRUCT but like a normal volume
        if (!isParametricMap) {
          volumeData.push({
            studyInstanceUID: displaySet.StudyInstanceUID,
            displaySetInstanceUID: displaySet.displaySetInstanceUID,
          });
 
          // Todo: do some cache check and empty the cache if needed
          continue;
        }
      }
 
      const volumeLoaderSchema = displaySet.volumeLoaderSchema ?? VOLUME_LOADER_SCHEME;
      const volumeId = `${volumeLoaderSchema}:${displaySet.displaySetInstanceUID}`;
      let volumeImageIds = this.volumeImageIds.get(displaySet.displaySetInstanceUID);
      let volume = cs3DCache.getVolume(volumeId);
 
      // Parametric maps do not have image ids but they already have volume data
      // therefore a new volume should not be created.
      if (!isParametricMap && !isSegOrRtstruct && (!volumeImageIds || !volume)) {
        volumeImageIds = this._getCornerstoneVolumeImageIds(displaySet, dataSource);
 
        volume = await volumeLoader.createAndCacheVolume(volumeId, {
          imageIds: volumeImageIds,
        });
 
        this.volumeImageIds.set(displaySet.displaySetInstanceUID, volumeImageIds);
 
        // Add imageIds to the displaySet for volumes
        displaySet.imageIds = volumeImageIds;
      }
 
      volumeData.push({
        StudyInstanceUID: displaySet.StudyInstanceUID,
        displaySetInstanceUID: displaySet.displaySetInstanceUID,
        volume,
        volumeId,
        imageIds: volumeImageIds,
        isDynamicVolume: displaySet.isDynamicVolume,
      });
    }
 
    return {
      viewportType,
      data: volumeData,
    };
  }
 
  private _getCornerstoneStackImageIds(displaySet, dataSource): string[] {
    return dataSource.getImageIdsForDisplaySet(displaySet);
  }
 
  private _getCornerstoneVolumeImageIds(displaySet, dataSource): string[] {
    if (displaySet.imageIds) {
      return displaySet.imageIds;
    }
 
    const stackImageIds = this._getCornerstoneStackImageIds(displaySet, dataSource);
 
    return stackImageIds;
  }
}
 
export default CornerstoneCacheService;