All files / extensions/default/src/displaySetSplitting makeDisplaySetFromInstanceGroup.ts

1.96% Statements 1/51
0% Branches 0/17
0% Functions 0/10
2% Lines 1/50

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                                          248x                                                                                                                                                                                                                                                                                                                                                                                                                                                      
import { createDisplaySetFromGroup, orderInstancesForRule } from '@cornerstonejs/metadata';
import type {
  GroupInstancesOptions,
  InstanceGroup,
  SeriesFacts,
  SplitRule,
} from '@cornerstonejs/metadata';
import {
  applyImageAttributes,
  applyImageListAttributes,
  applyThumbnailSrc,
  makeSeriesDisplaySet,
  type ImageSetFactoryContext,
} from './makeImageSetDisplaySet';
 
/**
 * The fields of the `@cornerstonejs/metadata` display set that the OHIF
 * display set does not take: the CS3D identity and image id lists, and the
 * fields that define the identity or the content of the OHIF display set.
 * The rule's custom attributes cannot set these either.
 */
const NOT_COPIED = new Set([
  'displaySetId',
  'imageIds',
  'underlyingImageIds',
  'instances',
  'instance',
  'images',
  'uid',
  'displaySetInstanceUID',
  // The growth hook DisplaySetService calls on a re-split.
  'extendInstances',
  // `imageSet['__proto__'] = value` replaces the prototype of the ImageSet.
  '__proto__',
]);
 
/** The ordering inputs every sort of one split-rule display set uses. */
type InstanceOrder = {
  series?: SeriesFacts;
  compareInstances?: GroupInstancesOptions['compareInstances'];
};
 
/**
 * Puts a split-rule display set's images in the order the rule asks for.
 *
 * `orderInstancesForRule` composes OHIF's default order (`ImageSet.sortInstances`)
 * with the rule's comparator and the host comparator, with the precedence the
 * split engine uses, so the result is the order the engine computed. The host
 * comparator and the group's series facts must be passed again, or the re-sort
 * discards that order.
 *
 * Sorted in place, because `imageSet.images` is a non-writable property whose
 * contents are mutable.
 */
function applyInstanceOrder(
  imageSet,
  matchedRule: SplitRule,
  { series, compareInstances }: InstanceOrder,
  context: ImageSetFactoryContext
) {
  const { customizationService } = context.servicesManager.services;
  const ordered = orderInstancesForRule(imageSet.images, matchedRule, {
    sortInstances: list => imageSet.sortInstances(list, customizationService),
    compareInstances,
    series,
  });
  imageSet.images.splice(0, imageSet.images.length, ...ordered);
}
 
/**
 * Orders the images, then refreshes the attributes that depend on the order.
 *
 * OHIF's default sort reads `isReconstructable`, so the image-list attributes
 * must already describe the current images. `instance`, `messages` and the
 * thumbnail depend on the order, so they are applied again from the final
 * order. The initial build and the growth hook both end here, so a display
 * set that grew is the same as one built from all of its instances.
 */
function orderAndRefreshAttributes(
  imageSet,
  matchedRule: SplitRule,
  order: InstanceOrder,
  context: ImageSetFactoryContext,
  ruleIsReconstructable?: boolean
) {
  applyInstanceOrder(imageSet, matchedRule, order, context);
  const derived = applyImageListAttributes(imageSet, context, ruleIsReconstructable);
  applyThumbnailSrc(imageSet, context, derived);
}
 
/**
 * Step 1: the `@cornerstonejs/metadata` display set of the group, and the
 * `isReconstructable` that the rule's own attributes set, if any. The rule's
 * `customAttributes` runs once, inside `createDisplaySetFromGroup`; the
 * wrapper only reads its result.
 */
function buildRuleDisplaySet(group: InstanceGroup, splitNumber: number) {
  let ruleIsReconstructable: boolean | undefined;
  const { customAttributes } = group.matchedRule;
  const matchedRule = customAttributes
    ? {
        ...group.matchedRule,
        customAttributes: (attributes, options) => {
          const result = customAttributes(attributes, options);
          Iif (typeof result?.isReconstructable === 'boolean') {
            ruleIsReconstructable = result.isReconstructable;
          }
          return result;
        },
      }
    : group.matchedRule;
  const ruleDisplaySet = createDisplaySetFromGroup({ ...group, matchedRule }, { splitNumber });
  return { ruleDisplaySet, ruleIsReconstructable };
}
 
/**
 * Copies the fields of the `@cornerstonejs/metadata` display set onto the OHIF
 * display set: `splitKey`, `splitRuleId`, `splitGroupId`, `sopClassUids`,
 * `handler` and the rule's attributes. Applied after the OHIF
 * defaults, so the rule's attributes win over them.
 *
 * An image display set keeps the OHIF `isReconstructable`: the image part
 * refines the CS3D value for display, and already applied a rule attribute.
 */
function copyRuleDisplaySet(displaySet, ruleDisplaySet: object, isImage: boolean) {
  for (const [key, value] of Object.entries(ruleDisplaySet)) {
    Iif (!NOT_COPIED.has(key) && !(isImage && key === 'isReconstructable')) {
      displaySet.setAttribute(key, value);
    }
  }
}
 
/**
 * Converts a `@cornerstonejs/metadata` split-rule instance group into an OHIF
 * display set. This is the default `createDisplaySetFromGroup` of the
 * `useMetadataDisplaySet` customization.
 *
 * The build has three steps (SP-PIPE-17); this function runs the first two:
 *
 * 1. CS3D `createDisplaySetFromGroup` builds the display set of the group,
 *    the same one that a server builds.
 * 2. The OHIF generic step builds an ImageSet with the series identity, and
 *    copies the fields of step 1. Its image part (the stack handler id, the
 *    image-list attributes, the thumbnail and the instance order) runs only
 *    for a rule with no `handler`, or with the `image` handler.
 * 3. DisplaySetService calls the `extendDisplaySet` of the SOP class handler
 *    that declares the rule's `handler` name.
 *
 * The `extendInstances` hook repeats steps 1 and 2 for the instances that
 * arrive later. It only adds: a split-rule display set never loses an
 * instance. It is not named `addInstances` (the SOP class handler merge
 * hook), so the legacy handler loop never feeds instances into it.
 */
export function makeDisplaySetFromInstanceGroup(
  group: InstanceGroup,
  {
    splitNumber,
    compareInstances,
  }: { splitNumber: number; compareInstances?: GroupInstancesOptions['compareInstances'] },
  context: ImageSetFactoryContext
) {
  const { matchedRule } = group;
  // What every re-sort of this display set orders with.
  const order: InstanceOrder = { series: group.series, compareInstances };
 
  // Step 1. `compileSplitRules` wraps `customAttributes`, so an error here
  // names the rule and the field; DisplaySetService catches it and stops the
  // study.
  const { ruleDisplaySet, ruleIsReconstructable } = buildRuleDisplaySet(group, splitNumber);
  const { handler } = ruleDisplaySet as { handler?: string };
  const isImage = !handler || handler === 'image';
 
  // Step 2.
  const displaySet = makeSeriesDisplaySet([...group.instances]);
  Iif (isImage) {
    // The order is applied below, once, with the matched rule folded in.
    applyImageAttributes(displaySet, context, {
      skipSort: true,
      isReconstructable: ruleIsReconstructable,
    });
    orderAndRefreshAttributes(displaySet, matchedRule, order, context, ruleIsReconstructable);
  }
  copyRuleDisplaySet(displaySet, ruleDisplaySet, isImage);
 
  displaySet.setAttribute(
    'extendInstances',
    (
      newInstances,
      options: {
        series?: SeriesFacts;
        compareInstances?: GroupInstancesOptions['compareInstances'];
      } = {}
    ) => {
      const known = new Set(displaySet.images.map(instance => instance.SOPInstanceUID));
      const instancesToAdd = newInstances.filter(instance => {
        Iif (known.has(instance.SOPInstanceUID)) {
          return false;
        }
        known.add(instance.SOPInstanceUID);
        return true;
      });
      Iif (!instancesToAdd.length) {
        return undefined;
      }
      // The series context of the re-split, which saw the whole series
      // including the new instances.
      Iif (options.series) {
        order.series = options.series;
      }
      Iif (options.compareInstances) {
        order.compareInstances = options.compareInstances;
      }
 
      // `images` is a non-writable property, but the array contents are
      // mutable. A non-image display set keeps the new instances at the end.
      displaySet.images.push(...instancesToAdd);
      // The display set keeps the `splitKey` of the group that created it.
      const grown = buildRuleDisplaySet(
        { ...group, series: order.series, instances: [...displaySet.images] },
        splitNumber
      );
      Iif (isImage) {
        // The sort reads `isReconstructable`: one slice is not reconstructable,
        // but more slices can be. So the attributes come first for the grown
        // list, then again from the final order.
        applyImageListAttributes(displaySet, context, grown.ruleIsReconstructable);
        orderAndRefreshAttributes(
          displaySet,
          matchedRule,
          order,
          context,
          grown.ruleIsReconstructable
        );
      }
      copyRuleDisplaySet(displaySet, grown.ruleDisplaySet, isImage);
      return displaySet;
    }
  );
  return displaySet;
}