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

61.53% Statements 56/91
47.05% Branches 16/34
50% Functions 15/30
63.21% Lines 55/87

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            34x                                     34x 34x 34x 34x 34x 34x   34x 156x   34x         34x       34x 34x 34x                   34x       34x 34x 34x 34x   34x         48x 48x   48x   48x   48x 48x 48x                                                           34x                 474x               156x   156x 48x   156x               108x       108x   108x 156x 156x   156x   156x       156x   156x 156x 156x 156x                             1026x 1132x     1026x 1026x   1090x                   27x   27x 36x     27x                                                                                                                                 34x  
import { synchronizers, SynchronizerManager, Synchronizer } from '@cornerstonejs/tools';
import { getRenderingEngines, utilities } from '@cornerstonejs/core';
 
import { pubSubServiceInterface, Types } from '@ohif/core';
import createHydrateSegmentationSynchronizer from './createHydrateSegmentationSynchronizer';
 
const EVENTS = {
  TOOL_GROUP_CREATED: 'event::cornerstone::syncgroupservice:toolgroupcreated',
};
 
/**
 * @params options - are an optional set of options associated with the first
 * sync group declared.
 */
export type SyncCreator = (id: string, options?: Record<string, unknown>) => Synchronizer;
 
export type SyncGroup = {
  type: string;
  id?: string;
  // Source and target default to true if not specified
  source?: boolean;
  target?: boolean;
  options?: Record<string, unknown>;
};
 
const POSITION = 'cameraposition';
const VOI = 'voi';
const ZOOMPAN = 'zoompan';
const STACKIMAGE = 'stackimage';
const IMAGE_SLICE = 'imageslice';
const HYDRATE_SEG = 'hydrateseg';
 
const asSyncGroup = (syncGroup: string | SyncGroup): SyncGroup =>
  typeof syncGroup === 'string' ? { type: syncGroup } : syncGroup;
 
export default class SyncGroupService {
  static REGISTRATION = {
    name: 'syncGroupService',
    altName: 'SyncGroupService',
    create: ({ servicesManager }: Types.Extensions.ExtensionParams): SyncGroupService => {
      return new SyncGroupService(servicesManager);
    },
  };
 
  servicesManager: AppTypes.ServicesManager;
  listeners: { [key: string]: (...args: any[]) => void } = {};
  EVENTS: { [key: string]: string };
  synchronizerCreators: Record<string, SyncCreator> = {
    [POSITION]: synchronizers.createCameraPositionSynchronizer,
    [VOI]: synchronizers.createVOISynchronizer,
    [ZOOMPAN]: synchronizers.createZoomPanSynchronizer,
    // todo: remove stack image since it is legacy now and the image_slice
    // handles both stack and volume viewports
    [STACKIMAGE]: synchronizers.createImageSliceSynchronizer,
    [IMAGE_SLICE]: synchronizers.createImageSliceSynchronizer,
    [HYDRATE_SEG]: createHydrateSegmentationSynchronizer,
  };
 
  synchronizersByType: { [key: string]: Synchronizer[] } = {};
 
  constructor(servicesManager: AppTypes.ServicesManager) {
    this.servicesManager = servicesManager;
    this.listeners = {};
    this.EVENTS = EVENTS;
    //
    Object.assign(this, pubSubServiceInterface);
  }
 
  private _createSynchronizer(type: string, id: string, options): Synchronizer | undefined {
    // Initialize if not already done
    this.synchronizersByType[type] = this.synchronizersByType[type] || [];
    const syncCreator = this.synchronizerCreators[type.toLowerCase()];
 
    if (syncCreator) {
      // Pass the servicesManager along with other parameters
      const synchronizer = syncCreator(id, { ...options, servicesManager: this.servicesManager });
 
      if (synchronizer) {
        this.synchronizersByType[type].push(synchronizer);
        return synchronizer;
      }
    } else E{
      console.debug(`Unknown synchronizer type: ${type}, id: ${id}`);
    }
  }
 
  public getSyncCreatorForType(type: string): SyncCreator {
    return this.synchronizerCreators[type.toLowerCase()];
  }
 
  /**
   * Creates a synchronizer type.
   * @param type is the type of the synchronizer to create
   * @param creator
   */
  public addSynchronizerType(type: string, creator: SyncCreator): void {
    this.synchronizerCreators[type.toLowerCase()] = creator;
  }
 
  public getSynchronizer(id: string): Synchronizer | void {
    return SynchronizerManager.getSynchronizer(id);
  }
 
  /**
   * Registers a custom synchronizer.
   * @param id - The id of the synchronizer.
   * @param createFunction - The function that creates the synchronizer.
   */
  public registerCustomSynchronizer(id: string, createFunction: SyncCreator): void {
    this.synchronizerCreators[id] = createFunction;
  }
 
  /**
   * Retrieves an array of synchronizers of a specific type.
   * @param type - The type of synchronizers to retrieve.
   * @returns An array of synchronizers of the specified type.
   */
  public getSynchronizersOfType(type: string): Synchronizer[] {
    return this.synchronizersByType[type];
  }
 
  protected _getOrCreateSynchronizer(
    type: string,
    id: string,
    options: Record<string, unknown>
  ): Synchronizer | undefined {
    let synchronizer = SynchronizerManager.getSynchronizer(id);
 
    if (!synchronizer) {
      synchronizer = this._createSynchronizer(type, id, options);
    }
    return synchronizer;
  }
 
  public addViewportToSyncGroup(
    viewportId: string,
    renderingEngineId: string,
    syncGroups?: SyncGroup | string | SyncGroup[] | string[]
  ): void {
    Iif (!syncGroups) {
      return;
    }
 
    const syncGroupsArray = Array.isArray(syncGroups) ? syncGroups : [syncGroups];
 
    syncGroupsArray.forEach(syncGroup => {
      const syncGroupObj = asSyncGroup(syncGroup);
      const { type, target = true, source = true, options = {}, id = type } = syncGroupObj;
 
      const synchronizer = this._getOrCreateSynchronizer(type, id, options);
 
      Iif (!synchronizer) {
        return;
      }
 
      synchronizer.setOptions(viewportId, options);
 
      const viewportInfo = { viewportId, renderingEngineId };
      if (target && source) {
        synchronizer.add(viewportInfo);
        return;
      } else Eif (source) {
        synchronizer.addSource(viewportInfo);
      } else Iif (target) {
        synchronizer.addTarget(viewportInfo);
      }
    });
  }
 
  public destroy(): void {
    SynchronizerManager.destroy();
  }
 
  public getSynchronizersForViewport(viewportId: string): Synchronizer[] {
    const renderingEngine =
      getRenderingEngines().find(re => {
        return re.getViewports().find(vp => vp.id === viewportId);
      }) || getRenderingEngines()[0];
 
    const synchronizers = SynchronizerManager.getAllSynchronizers();
    return synchronizers.filter(
      s =>
        s.hasSourceViewport(renderingEngine.id, viewportId) ||
        s.hasTargetViewport(renderingEngine.id, viewportId)
    );
  }
 
  public removeViewportFromSyncGroup(
    viewportId: string,
    renderingEngineId: string,
    syncGroupId?: string
  ): void {
    const synchronizers = SynchronizerManager.getAllSynchronizers();
 
    const filteredSynchronizers = syncGroupId
      ? synchronizers.filter(s => s.id === syncGroupId)
      : synchronizers;
 
    filteredSynchronizers.forEach(synchronizer => {
      Iif (!synchronizer) {
        return;
      }
 
      // Only image slice synchronizer register spatial registration
      Iif (this.isImageSliceSyncronizer(synchronizer)) {
        this.unRegisterSpatialRegistration(synchronizer);
      }
 
      synchronizer.remove({
        viewportId,
        renderingEngineId,
      });
 
      // check if any viewport is left in any of the sync groups, if not, delete that sync group
      const sourceViewports = synchronizer.getSourceViewports();
      const targetViewports = synchronizer.getTargetViewports();
 
      Iif (!sourceViewports.length && !targetViewports.length) {
        SynchronizerManager.destroySynchronizer(synchronizer.id);
      }
    });
  }
  /**
   * Clean up the spatial registration metadata created by synchronizer
   * This is needed to be able to re-sync images slices if needed
   * @param synchronizer
   */
  unRegisterSpatialRegistration(synchronizer: Synchronizer) {
    const sourceViewports = synchronizer.getSourceViewports().map(vp => vp.viewportId);
    const targetViewports = synchronizer.getTargetViewports().map(vp => vp.viewportId);
 
    // Create an array of pair of viewports to remove from spatialRegistrationMetadataProvider
    // All sourceViewports combined with all targetViewports
    const toUnregister = sourceViewports
      .map((sourceViewportId: string) => {
        return targetViewports.map(targetViewportId => [targetViewportId, sourceViewportId]);
      })
      .reduce((acc, c) => acc.concat(c), []);
 
    toUnregister.forEach(viewportIdPair => {
      utilities.spatialRegistrationMetadataProvider.add(viewportIdPair, undefined);
    });
  }
  /**
   * Check if the synchronizer type is IMAGE_SLICE
   * Need to convert to lowercase here because the types are lowercase
   * e.g: synchronizerCreators
   * @param synchronizer
   */
  isImageSliceSyncronizer(synchronizer: Synchronizer) {
    return this.getSynchronizerType(synchronizer).toLowerCase() === IMAGE_SLICE;
  }
  /**
   * Returns the syncronizer type
   * @param synchronizer
   */
  getSynchronizerType(synchronizer: Synchronizer): string {
    const synchronizerTypes = Object.keys(this.synchronizersByType);
    const syncType = synchronizerTypes.find(syncType =>
      this.getSynchronizersOfType(syncType).includes(synchronizer)
    );
    return syncType;
  }
}