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 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 | 3707x 3707x 247x 27624x 27624x 3707x 3707x 27624x 27624x 27624x 3551x 3707x 3707x 30661x 247x 247x 247x 247x 247x 247x 1140x 1140x 1172x 1172x 56080x 56066x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 1423x 247x 247x 247x 247x 247x 247x 247x 741x 259x 259x 247x 247x 247x 247x 247x 1423x 1423x 1423x 1423x 1325x 1257x 1275x 1257x 1257x 1257x 1275x 1275x 1275x 1275x 1275x 1275x 1257x 1257x 1257x 95x 95x 95x 95x 95x 243x 2x 16868x 247x 2211x 16223x 247x 199x 199x 199x 199x 199x 199x 199x 199x 15852x 199x 300x 300x 222x 274x 635x 635x 1306x 635x 5x 5x 5x 6x 5x 5x 5x 5x 5x 5x 247x 247309x 247309x 247x 1159x 1159x 1159x 1159x 1159x 1159x 1159x 1159x 2x 1159x 1159x 1159x 1159x 1159x 1159x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1159x 1159x 1159x 1159x 1159x 1159x 1159x 1159x 57244x 1162x 57244x 57244x 1159x 1159x 1162x 1162x 1159x 1159x 1159x 1159x 1159x 1159x 1159x 1159x 1162x 1162x 1162x 1162x 1162x 1162x 4149x 4149x 4149x 1141x 17x 1141x 2x 2x 16x 16x 16x 2x 1141x 1141x 3x 1138x 1156x 1138x 1138x 1138x 1138x 1162x 24x 24x 24x 24x 24x 24x 24x 24x 1162x 37x 37x 37x 2035x 832x 37x 4964x 4964x 1257x 3707x 3707x 30661x | import { groupInstancesBySplitRules, setMetadataContext } from '@cornerstonejs/metadata';
import type {
CreateDisplaySetSplitRulesOptions,
GroupInstancesOptions,
InstanceGroup,
NaturalizedInstance,
SplitRuleSet,
} from '@cornerstonejs/metadata';
import { ExtensionManager } from '../../extensions';
import { DisplaySet, InstanceMetadata, ReferencedSeriesSequence } from '../../types';
import { PubSubService } from '../_shared/pubSubServiceInterface';
import EVENTS from './EVENTS';
import * as displaySetStore from './displaySetStore';
import { compileSplitRules, SplitRuleRunError } from './compileSplitRules';
import type {
CompiledSplitRules,
SplitRuleCompileError,
SplitRuleCustomizationEntry,
} from './compileSplitRules';
import { compare, seriesSortCriteria } from '../../utils/sortStudy';
import { getDateTimeSortKey } from '../../utils/latestInstanceDateTime';
export type DisplaySetSort = {
sortFn: (a: DisplaySet, b: DisplaySet) => number;
direction: 'ascending' | 'descending';
};
/**
* A named display set order:
* - `default`: the system default order, the `sortingCriteria` customization.
* - `thumbnailTray`: the thumbnail tray order. The studies are newest first, and
* the series of a study follow the sort picked in the study browser.
*/
export type DisplaySetOrder = 'default' | 'thumbnailTray';
type DisplaySetComparator = (a: DisplaySet, b: DisplaySet) => number;
/**
* The series order once a sort has been picked: the picked sort in the picked
* direction, with ties broken by the default order. Only the picked sort
* reverses, so the display sets of one split series keep their default order
* in both directions. Without a picked sort it is the default order.
*/
export function sortCriteriaFor(
displaySetSort: DisplaySetSort | null,
defaultSortCriteria?: DisplaySetComparator
): DisplaySetComparator | undefined {
if (!displaySetSort) {
return defaultSortCriteria;
}
const sign = displaySetSort.direction === 'descending' ? -1 : 1;
return (a, b) => sign * displaySetSort.sortFn(a, b) || defaultSortCriteria?.(a, b) || 0;
}
const studyDateTimeKey = (displaySet: DisplaySet) => {
const instance = displaySet.instance ?? displaySet.instances?.[0];
return getDateTimeSortKey(instance?.StudyDate, instance?.StudyTime);
};
/**
* The study order of the thumbnail tray: newest study first. Each study gets one
* key (its earliest display set date/time), because a derived object of a study
* can carry another `StudyTime`, and a key per display set would split the study.
*/
function compareTrayStudyFor(displaySets: DisplaySet[]): DisplaySetComparator {
const studyKeys = new Map<string, string>();
for (const displaySet of displaySets) {
const key = studyDateTimeKey(displaySet);
const known = studyKeys.get(displaySet.StudyInstanceUID);
// A display set with no date does not make the study the oldest one.
if (known === undefined || (key && (!known || key < known))) {
studyKeys.set(displaySet.StudyInstanceUID, key);
}
}
const keyOf = (displaySet: DisplaySet) =>
studyKeys.get(displaySet.StudyInstanceUID) ?? studyDateTimeKey(displaySet);
return (a, b) =>
a.StudyInstanceUID === b.StudyInstanceUID
? 0
: compare(keyOf(b), keyOf(a)) || compare(a.StudyInstanceUID, b.StudyInstanceUID);
}
/**
* Memoizes compiled split rules by the identity of the `displaySetRules`,
* `displaySetRuleOrder` and `metadataContext` values. A mode that defines other
* rules, another order or another context gives a new object, and that object
* compiles again. `source` stands for the registry and the order together.
*/
const compiledSplitRulesCache = new WeakMap<
object,
{
registry: unknown;
order: unknown;
context: unknown;
compiled: CompiledSplitRules;
source: object;
}
>();
/** The cache key of a `displaySetRules` value that is not an object. */
const INVALID_REGISTRY_KEY = {};
/** The handler name of the unsupported display set. */
const UNSUPPORTED_HANDLER_NAME = 'unsupported';
/** The handler name of an image display set; a rule with no `handler` gets it. */
const IMAGE_HANDLER_NAME = 'image';
/**
* A SOP class handler entry, as the extension manager returns it. A handler
* that serves split-rule display sets declares `handlerNames` (data) and
* `extendDisplaySet`.
*/
type SopClassHandler = {
sopClassUids: string[];
getDisplaySetsFromSeries: (instances: InstanceMetadata[]) => DisplaySet[] | undefined;
/** The generic handler names of the split rules that this handler serves. */
handlerNames?: string[];
/**
* Adds the handler fields to a display set that a split rule made, in place
* and synchronously. `addedInstances` is undefined at creation, and lists
* the new instances (already in `displaySet.instances`) at an update.
* `false` at creation means: the handler cannot show it, so drop it.
*/
extendDisplaySet?: (
displaySet: DisplaySet,
options: {
addedInstances?: InstanceMetadata[];
servicesManager?: AppTypes.ServicesManager;
extensionManager: ExtensionManager;
}
) => void | boolean;
};
/** The title of the notification that reports a split rule error. */
const SPLIT_RULE_ERROR_TITLE = 'Display set split rules';
/**
* A split rule that failed at run time for a study (SP-SAFE-3). While the
* record exists, the service creates no further display sets for the study.
*/
type SplitRuleFailure = {
/** The rule registry and order that failed; a different value clears the record. */
ruleSource: object;
ruleId?: string;
field?: string;
seriesInstanceUID?: string;
message: string;
};
/**
* What `createDisplaySetFromGroup` is told about the group it builds.
*/
export type CreateDisplaySetFromGroupContext = {
/** Position of the group in the engine's group list for this split. */
splitNumber: number;
/**
* The host comparator the engine used to order the group (the customization's
* `compareInstances`). A factory that re-sorts the display set must apply it
* again, or the re-sort discards the order the engine computed.
*/
compareInstances?: GroupInstancesOptions['compareInstances'];
};
/**
* Value shape of the `useMetadataDisplaySet` customization. When `enabled`,
* series instances are split into display sets by the
* `@cornerstonejs/metadata` split-rules engine before (instead of, for the
* instances the rules match) the registered SOP class handlers. Instances
* not matched by any rule fall through to the legacy handler loop unchanged.
*
* A rule error stops display set creation, and never falls back to the SOP
* class handlers (a fallback gives a grouping that looks correct but is not
* the grouping the deployment intended):
*
* - a rule that does not compile, or an id of the order that is not in the
* registry (SP-SAFE-7): no display sets at all - SEG and SR included - while
* that registry and order are in effect;
* - a rule that throws at run time, in the engine or in
* `createDisplaySetFromGroup` / `extendInstances` (SP-SAFE-3): no further
* display sets for the study. The display sets that exist stay.
*
* Either error shows one persistent error notification that names the rule
* (and the series, for a run-time error).
*/
export type UseMetadataDisplaySetCustomization = {
/** Default false — the legacy SOP class handler path is used exclusively. */
enabled?: boolean;
/**
* The rule registry, keyed by rule id. A rule is used only when
* `displaySetRuleOrder` names it. A customization changes a rule by its id
* with the immutability-helper commands, and the rule keeps its place.
*
* An entry is a `@cornerstonejs/metadata` raw rule; a raw field can hold a
* function. A rule that the compiler has already compiled is not a valid
* entry. Every rule of the order is compiled by `createDisplaySetSplitRules`
* (see {@link compileSplitRules}), which keeps a function as is. A rule that
* does not compile is not dropped: it stops display set creation.
*/
displaySetRules?: Record<string, SplitRuleCustomizationEntry>;
/**
* The rule ids in evaluation order; the first rule that matches an instance
* claims it. A customization adds, removes or replaces an id with
* `$spliceById`, which takes a rule id as the position. An instance that no rule
* claims goes to the SOP class handlers.
*/
displaySetRuleOrder?: string[];
/**
* Set by `CustomizationService`: the URL modules that changed this
* customization and did not apply. Not empty means: create no display sets.
*/
moduleErrors?: string[];
/**
* Named series functions that a context group references with
* `{ function: '<name>' }`, in addition to the built-in `planeGeometry` and
* `timeClusters`. Code, supplied by an extension.
*/
seriesFunctions?: CreateDisplaySetSplitRulesOptions['seriesFunctions'];
/** Named comparators that a `sortBy` entry references with `{ sortFunction }`. */
sortFunctions?: CreateDisplaySetSplitRulesOptions['sortFunctions'];
/**
* Factory converting a matched instance group into an OHIF display set. A
* display set with a `handler` name then goes to the `extendDisplaySet` of
* the SOP class handler of the mode that declares that name.
*/
createDisplaySetFromGroup?: (
group: InstanceGroup,
context: CreateDisplaySetFromGroupContext
) => DisplaySet | undefined;
/**
* The base instance order the engine applies to every rule, before any rule's
* own `compareInstances`. A whole-list sort, because OHIF's default order is
* one — `sortImagesByPatientPosition` picks a reference instance and projects
* onto its normal, which no pairwise comparator expresses.
*
* Optional. The display set factory applies OHIF's default order itself (it
* needs `isReconstructable`, which only exists once the display set is built),
* so supplying this changes the order of the instances in each group, not
* which display sets the rules produce: only `groupBy` groups. Unset, the
* engine's acquisition order applies.
*/
sortInstances?: GroupInstancesOptions['sortInstances'];
/**
* A comparator the engine consults after a rule's own `compareInstances` and
* before falling back to the base order. Returning 0 declines to have an
* opinion rather than asserting equality.
*/
compareInstances?: GroupInstancesOptions['compareInstances'];
};
/** The customization after {@link compileSplitRules}: the rules the engine takes. */
type CompiledSplitConfig = Omit<
UseMetadataDisplaySetCustomization,
'displaySetRules' | 'displaySetRuleOrder'
> & {
splitRules?: SplitRuleSet;
/** Stands for the registry and the order that the rules came from. */
splitRulesSource?: object;
/** The rules that did not compile. Not empty means: create no display sets. */
compileErrors?: SplitRuleCompileError[];
};
/**
* Filters the instances set by instances not in
* display sets. Done in O(n) time.
*/
const filterInstances = (
instances: InstanceMetadata[],
displaySets: DisplaySet[]
): InstanceMetadata[] => {
const dsInstancesSOP = new Set();
displaySets.forEach(ds => {
const dsInstances = ds.instances;
Iif (!dsInstances) {
console.warn('No instances in', ds);
} else {
dsInstances.forEach(instance => dsInstancesSOP.add(instance.SOPInstanceUID));
}
});
return instances.filter(instance => !dsInstancesSOP.has(instance.SOPInstanceUID));
};
export default class DisplaySetService extends PubSubService {
public static REGISTRATION = {
altName: 'DisplaySetService',
name: 'displaySetService',
create: ({ servicesManager }) => {
return new DisplaySetService({ servicesManager });
},
};
public activeDisplaySets = [];
public unsupportedSOPClassHandler;
extensionManager: ExtensionManager;
protected servicesManager?: AppTypes.ServicesManager;
protected activeDisplaySetsMap = new Map<string, DisplaySet>();
// Record if the active display sets changed - used to group change events so
// that fewer events need to be fired when creating multiple display sets
protected activeDisplaySetsChanged = false;
/** The sort picked in the study browser; it sets the `thumbnailTray` order only. */
protected displaySetSort: DisplaySetSort | null = null;
/** The display set added last; `activeDisplaySets` is in default order, not add order. */
protected mostRecentDisplaySetUID: string | undefined;
/**
* The split rule failures at run time, by StudyInstanceUID (SP-SAFE-3). A
* study in this map gets no further display sets. A record clears when the
* registry or the order changes, and on `onModeExit`.
*/
protected splitRuleFailures = new Map<string, SplitRuleFailure>();
/**
* The rule sources whose compile errors this mode already reported,
* so that the notification shows once and not once per series.
*/
protected reportedSplitRuleSets = new WeakSet<object>();
/**
* The SOP class handler for each split-rule handler name, in the order of
* the mode's handlers: the first handler that declares a name serves it.
*/
protected handlersByName = new Map<string, SopClassHandler>();
/** The handler names with no handler in the mode, warned once each. */
protected warnedHandlerNames = new Set<string>();
/** The `metadataContext` value that is the active `@cornerstonejs/metadata` context. */
protected activeMetadataContext: CreateDisplaySetSplitRulesOptions['context'];
/** The customization subscriptions of the mode, removed at mode exit. */
protected customizationSubscriptions: { unsubscribe: () => void }[] = [];
constructor({ servicesManager }: { servicesManager?: AppTypes.ServicesManager } = {}) {
super(EVENTS);
this.servicesManager = servicesManager;
this.unsupportedSOPClassHandler =
'@ohif/extension-default.sopClassHandlerModule.not-supported-display-sets-handler';
}
/**
* Registers the mode's SOP class handlers, in order. The order decides
* which handler serves a split-rule handler name that two handlers declare.
*
* @throws when a handler declares `handlerNames` and has no
* `extendDisplaySet`.
*/
public init(extensionManager, SOPClassHandlerIds): void {
this.extensionManager = extensionManager;
this.SOPClassHandlerIds = SOPClassHandlerIds;
this.activeDisplaySets = [];
this.activeDisplaySetsMap.clear();
this.mostRecentDisplaySetUID = undefined;
this.handlersByName = new Map();
this.warnedHandlerNames.clear();
for (const id of SOPClassHandlerIds) {
this._registerHandlerNames(id, extensionManager.getModuleEntry(id));
}
this._subscribeToMetadataContext();
}
/**
* Makes the `metadataContext` customization the active `@cornerstonejs/metadata`
* context now, and again each time a customization changes, so that
* `isImageInstance` and the other code tests read the same lists as the
* split rules. `onModeExit` removes the subscriptions.
*/
private _subscribeToMetadataContext(): void {
this._unsubscribeFromMetadataContext();
const customizationService = this.servicesManager?.services?.customizationService;
this._applyMetadataContext();
Iif (typeof customizationService?.subscribe !== 'function') {
return;
}
const { EVENTS: CUSTOMIZATION_EVENTS } = customizationService;
this.customizationSubscriptions = [
CUSTOMIZATION_EVENTS.MODE_CUSTOMIZATION_MODIFIED,
CUSTOMIZATION_EVENTS.GLOBAL_CUSTOMIZATION_MODIFIED,
CUSTOMIZATION_EVENTS.DEFAULT_CUSTOMIZATION_MODIFIED,
].map(event => customizationService.subscribe(event, () => this._applyMetadataContext()));
}
private _unsubscribeFromMetadataContext(): void {
this.customizationSubscriptions.forEach(({ unsubscribe }) => unsubscribe());
this.customizationSubscriptions = [];
}
/**
* Reads the `metadataContext` customization, and sets it as the active
* `@cornerstonejs/metadata` context when the value changed.
*
* @returns the context, which the split rules compile with as well.
*/
private _applyMetadataContext(): CreateDisplaySetSplitRulesOptions['context'] {
const context = this.servicesManager?.services?.customizationService?.getCustomization(
'metadataContext'
) as CreateDisplaySetSplitRulesOptions['context'];
if (context !== this.activeMetadataContext) {
this.activeMetadataContext = context;
setMetadataContext(context);
}
return context;
}
/** Maps each `handlerNames` entry of a handler that no earlier handler took. */
private _registerHandlerNames(id: string, handler: SopClassHandler | undefined): void {
Iif (!handler?.handlerNames) {
return;
}
Iif (typeof handler.extendDisplaySet !== 'function') {
throw new Error(
`DisplaySetService: the SOP class handler '${id}' declares handlerNames ` +
`${JSON.stringify(handler.handlerNames)} and has no extendDisplaySet function.`
);
}
for (const name of handler.handlerNames) {
if (!this.handlersByName.has(name)) {
this.handlersByName.set(name, handler);
}
}
}
/**
* The handler for a split-rule handler name. A name with no handler in the
* mode gets the unsupported handler, and one console warning for each name.
*/
private _getHandlerForName(name: string): SopClassHandler | undefined {
const handler = this.handlersByName.get(name);
Iif (handler) {
return handler;
}
Iif (name !== UNSUPPORTED_HANDLER_NAME && !this.warnedHandlerNames.has(name)) {
this.warnedHandlerNames.add(name);
console.warn(
`DisplaySetService: no SOP class handler of the mode declares the handler name ` +
`'${name}'; its display sets are unsupported display sets.`
);
}
const unsupported = this.extensionManager.getModuleEntry(this.unsupportedSOPClassHandler) as
| SopClassHandler
| undefined;
this._registerHandlerNames(this.unsupportedSOPClassHandler, unsupported);
return unsupported;
}
/**
* Step 3 of a split-rule display set (SP-PIPE-17): the `extendDisplaySet`
* of the handler that serves the display set's `handler` name. A display set
* with no `handler` is an image display set: it gets the step of the `image`
* handler when the mode declares one, and no step otherwise.
*
* @returns false when the handler rejects the display set.
*/
private _extendWithHandler(
displaySet: DisplaySet,
addedInstances?: InstanceMetadata[]
): void | boolean {
const name = (displaySet as { handler?: string }).handler;
const handler = name
? this._getHandlerForName(name)
: this.handlersByName.get(IMAGE_HANDLER_NAME);
return handler?.extendDisplaySet?.(displaySet, {
addedInstances,
servicesManager: this.servicesManager,
extensionManager: this.extensionManager,
});
}
_addDisplaySetsToCache(displaySets: DisplaySet[]) {
displaySets.forEach(displaySet => {
displaySetStore.setDisplaySet(displaySet);
});
}
_addActiveDisplaySets(displaySets: DisplaySet[]) {
const { activeDisplaySets, activeDisplaySetsMap } = this;
let added = false;
displaySets.forEach(displaySet => {
if (!activeDisplaySetsMap.has(displaySet.displaySetInstanceUID)) {
this.activeDisplaySetsChanged = true;
added = true;
activeDisplaySets.push(displaySet);
activeDisplaySetsMap.set(displaySet.displaySetInstanceUID, displaySet);
this.mostRecentDisplaySetUID = displaySet.displaySetInstanceUID;
}
});
if (added) {
this._sortActiveDisplaySets();
}
}
/** Keeps `activeDisplaySets` in the default order, whatever the load order is. */
protected _sortActiveDisplaySets(): void {
this.activeDisplaySets.sort(this.getSortCriteria('default'));
}
/**
* Sets the handler for unsupported sop classes
* @param sopClassHandlerUID
*/
public setUnsuportedSOPClassHandler(sopClassHandler) {
this.unsupportedSOPClassHandler = sopClassHandler;
}
/**
* Adds new display sets directly, as specified.
* Use this function when the display sets are created externally directly
* rather than using the default sop class handlers to create display sets.
*/
public addDisplaySets(...displaySets: DisplaySet[]): string[] {
this._addDisplaySetsToCache(displaySets);
this._addActiveDisplaySets(displaySets);
// The activeDisplaySetsChanged flag is only seen if we add display sets
// so, don't broadcast the change if all the display sets were pre-existing.
this.activeDisplaySetsChanged = false;
this._broadcastEvent(EVENTS.DISPLAY_SETS_ADDED, {
displaySetsAdded: displaySets,
options: { madeInClient: displaySets[0].madeInClient },
});
return displaySets;
}
/**
* @deprecated Returns a read-only snapshot of the display set store —
* mutating the returned map has no effect. Display sets are stored in the
* `@cornerstonejs/metadata` DISPLAY_SET typed metadata module; use
* `getDisplaySetByUID`, `getActiveDisplaySets` or `getDisplaySetsBy`
* instead.
*/
public getDisplaySetCache(): Map<string, DisplaySet> {
return displaySetStore.getDisplaySetSnapshot();
}
public getMostRecentDisplaySet(): DisplaySet {
return this.activeDisplaySetsMap.get(this.mostRecentDisplaySetUID);
}
/**
* @returns the active display sets in the default order. Do not sort the
* returned array: use `getDisplaySets({ order })` for another order.
*/
public getActiveDisplaySets(): DisplaySet[] {
return this.activeDisplaySets;
}
/**
* Gets the set of display sets with this series instance UID
*
* <b>WARNING: Do not use this method when you have a referenced series sequence
* as this method does NOT check sop instances. Instead, use getDisplaySetsForReference
* to get those with the correct sop instances in them.</b>
*/
public getDisplaySetsForSeries = (seriesInstanceUID: string): DisplaySet[] => {
return displaySetStore
.getAllDisplaySets()
.filter(displaySet => displaySet.SeriesInstanceUID === seriesInstanceUID);
};
/**
* Given a reference to a series/sop, returns the set of display sets
* containing an instance from the references.
*/
public getDisplaySetsForReferences = (
references: ReferencedSeriesSequence | ReferencedSeriesSequence[]
): DisplaySet[] => {
const mapSeriesReferences = new Map<string, Set<string>>();
const referenceArr = Array.isArray(references) ? references : [references];
for (const seriesRef of referenceArr) {
const { SeriesInstanceUID, ReferencedInstanceSequence } = seriesRef;
if (!mapSeriesReferences.has(SeriesInstanceUID)) {
mapSeriesReferences.set(SeriesInstanceUID, new Set<string>());
}
const sops = mapSeriesReferences.get(SeriesInstanceUID);
for (const sopReference of ReferencedInstanceSequence) {
sops.add(sopReference.ReferencedSOPInstanceUID);
}
}
return displaySetStore.getAllDisplaySets().filter(displaySet => {
const sopReferences = mapSeriesReferences.get(displaySet.SeriesInstanceUID);
if (!sopReferences || !displaySet.instances) {
return;
}
return displaySet.instances.some(instance => sopReferences.has(instance.SOPInstanceUID));
});
};
public getDisplaySetForSOPInstanceUID(
sopInstanceUID: string,
seriesInstanceUID: string,
_frameNumber?: number
): DisplaySet {
const displaySets = seriesInstanceUID
? this.getDisplaySetsForSeries(seriesInstanceUID)
: displaySetStore.getAllDisplaySets();
const displaySet = displaySets.find(ds => {
return ds.instances?.some(i => i.SOPInstanceUID === sopInstanceUID);
});
return displaySet;
}
public setDisplaySetMetadataInvalidated(
displaySetInstanceUID: string,
invalidateData = true
): void {
const displaySet = this.getDisplaySetByUID(displaySetInstanceUID);
Iif (!displaySet) {
return;
}
// New metadata can change the sort keys.
this._sortActiveDisplaySets();
// broadcast event to update listeners with the new displaySets
this._broadcastEvent(EVENTS.DISPLAY_SET_SERIES_METADATA_INVALIDATED, {
displaySetInstanceUID,
invalidateData,
});
}
public deleteDisplaySet(displaySetInstanceUID) {
Iif (!displaySetInstanceUID) {
return;
}
const { activeDisplaySets, activeDisplaySetsMap } = this;
const activeDisplaySetsIndex = activeDisplaySets.findIndex(
ds => ds.displaySetInstanceUID === displaySetInstanceUID
);
displaySetStore.deleteDisplaySet(displaySetInstanceUID);
if (activeDisplaySetsIndex !== -1) {
activeDisplaySets.splice(activeDisplaySetsIndex, 1);
}
activeDisplaySetsMap.delete(displaySetInstanceUID);
this._broadcastEvent(EVENTS.DISPLAY_SETS_CHANGED, this.activeDisplaySets);
this._broadcastEvent(EVENTS.DISPLAY_SETS_REMOVED, {
displaySetInstanceUIDs: [displaySetInstanceUID],
});
}
/**
* @param {string} displaySetInstanceUID
* @returns {object} displaySet
*/
public getDisplaySetByUID = (displaySetInstanceUid: string): DisplaySet => {
Iif (typeof displaySetInstanceUid !== 'string') {
throw new Error(
`getDisplaySetByUID: displaySetInstanceUid must be a string, you passed ${displaySetInstanceUid}`
);
}
return displaySetStore.getDisplaySet(displaySetInstanceUid);
};
/**
*
* @param {*} input
* @param {*} param1: settings: initialViewportSettings by HP or callbacks after rendering
* @returns {string[]} - added displaySetInstanceUIDs
*/
makeDisplaySets = (input, { batch = false, madeInClient = false, settings = {} } = {}) => {
Iif (!input || !input.length) {
throw new Error('No instances were provided.');
}
Iif (batch && !input[0].length) {
throw new Error('Batch displaySet creation does not contain array of array of instances.');
}
// If array of instances => One instance.
const displaySetsAdded = new Array<DisplaySet>();
Iif (batch) {
for (let i = 0; i < input.length; i++) {
const instances = input[i];
const displaySets = this.makeDisplaySetForInstances(instances, settings);
displaySetsAdded.push(...displaySets);
}
} else {
const displaySets = this.makeDisplaySetForInstances(input, settings);
displaySetsAdded.push(...displaySets);
}
const options = {};
if (madeInClient) {
options.madeInClient = true;
}
if (this.activeDisplaySetsChanged) {
this.activeDisplaySetsChanged = false;
this._broadcastEvent(EVENTS.DISPLAY_SETS_CHANGED, this.activeDisplaySets);
}
if (displaySetsAdded?.length) {
// The response from displaySetsAdded will only contain newly added
// display sets.
this._broadcastEvent(EVENTS.DISPLAY_SETS_ADDED, {
displaySetsAdded,
options,
});
return displaySetsAdded;
}
};
/**
* The onModeExit returns the display set service to the initial state,
* that is without any display sets. To avoid recreating display sets,
* the mode specific onModeExit is called before this method and should
* store the active display sets and the cached data.
*
* It also clears the split rule errors: the next mode starts with no
* blocked study, and reports a rule set that still has compile errors again.
* And it sets the `@cornerstonejs/metadata` default context as the active
* context again.
*/
public onModeExit(): void {
displaySetStore.clearDisplaySets();
this.activeDisplaySets.length = 0;
this.activeDisplaySetsMap.clear();
this.mostRecentDisplaySetUID = undefined;
// A sort picked for one study does not carry over to the next one.
this.displaySetSort = null;
this.splitRuleFailures.clear();
this.reportedSplitRuleSets = new WeakSet();
this._unsubscribeFromMetadataContext();
this.activeMetadataContext = undefined;
setMetadataContext(undefined);
}
/**
* This function hides the old makeDisplaySetForInstances function to first
* separate the instances by sopClassUID so each call have only instances
* with the same sopClassUID, to avoid a series composed by different
* sopClassUIDs be filtered inside one of the SOPClassHandler functions and
* didn't appear in the series list.
*
* With the `useMetadataDisplaySet` customization enabled, a split rule error
* stops display set creation here, before the SOP class handlers too:
*
* - a rule set with a compile error creates no display sets (SP-SAFE-7);
* - a study with a rule that failed at run time gets no further display sets
* (SP-SAFE-3).
*
* @param instancesSrc
* @param settings
* @returns
*/
public makeDisplaySetForInstances(instancesSrc: InstanceMetadata[], settings): DisplaySet[] {
let allDisplaySets = [];
const splitConfig = this._getMetadataSplitCustomization();
this._clearStaleSplitRuleFailures(splitConfig?.splitRulesSource);
Iif (splitConfig?.compileErrors?.length) {
this._reportSplitRuleCompileErrors(splitConfig);
return allDisplaySets;
}
let remaining = this._withoutFailedStudies(instancesSrc);
// When the `useMetadataDisplaySet` customization is enabled, split the
// series with the `@cornerstonejs/metadata` split-rules engine first.
// The splitter sees a whole series across SOP classes (rules may
// aggregate series-level facts); instances not matched by any rule fall
// through to the legacy SOP class handler loop below unchanged.
Iif (remaining.length && splitConfig?.enabled && splitConfig.splitRules) {
const { displaySets, unmatched } = this._makeDisplaySetsWithSplitRules(
remaining,
splitConfig,
settings
);
allDisplaySets.push(...displaySets);
// A rule that failed during this call stops its study here too: the
// unmatched instances of that study do not go to the SOP class handlers.
remaining = this._withoutFailedStudies(unmatched);
}
Iif (!remaining.length) {
return allDisplaySets;
}
// creating a sopClassUID list and for each sopClass associate its respective
// instance list
const instancesForSetSOPClasses = remaining.reduce((sopClassList, instance) => {
if (!(instance.SOPClassUID in sopClassList)) {
sopClassList[instance.SOPClassUID] = [];
}
sopClassList[instance.SOPClassUID].push(instance);
return sopClassList;
}, {});
// for each sopClassUID, call the old makeDisplaySetForInstances with a
// instance list composed only by instances with the same sopClassUID and
// accumulate the displaySets in the variable allDisplaySets
const sopClasses = Object.keys(instancesForSetSOPClasses);
sopClasses.forEach(sopClass => {
const displaySets = this._makeDisplaySetForInstances(
instancesForSetSOPClasses[sopClass],
settings
);
allDisplaySets = [...allDisplaySets, ...displaySets];
});
return allDisplaySets;
}
/**
* Reads the `useMetadataDisplaySet` customization, when available, with its
* split rules compiled by the `@cornerstonejs/metadata` raw selector
* compiler (see {@link compileSplitRules}). The compile errors come back in
* `compileErrors`; the caller must not split with an incomplete rule set.
*/
private _getMetadataSplitCustomization(): CompiledSplitConfig | undefined {
const config = this.servicesManager?.services?.customizationService?.getCustomization(
'useMetadataDisplaySet'
) as UseMetadataDisplaySetCustomization | undefined;
const { displaySetRules: registry, displaySetRuleOrder: order, ...rest } = config ?? {};
if (!config?.enabled) {
return { ...rest, splitRules: undefined };
}
// A registry that is not an object is a compile error, not the old split (SP-SAFE-7).
const key = registry && typeof registry === 'object' ? registry : INVALID_REGISTRY_KEY;
const context = this._applyMetadataContext();
let cached = compiledSplitRulesCache.get(key);
Iif (
!cached ||
cached.registry !== registry ||
cached.order !== order ||
cached.context !== context
) {
const sameSource = cached?.registry === registry && cached?.order === order;
cached = {
registry,
order,
context,
compiled: compileSplitRules(registry, order, {
context,
seriesFunctions: config.seriesFunctions,
sortFunctions: config.sortFunctions,
}),
// A new context compiles again, but it is the same rule source.
source: sameSource ? cached.source : { registry, order },
};
compiledSplitRulesCache.set(key, cached);
}
const { moduleErrors = [], ...settings } = rest;
return {
...settings,
splitRules: cached.compiled.rules,
splitRulesSource: cached.source,
compileErrors: [...cached.compiled.errors, ...moduleErrors.map(message => ({ message }))],
};
}
/**
* Shows the compile errors of a rule set, once for each rule source
* in a mode (SP-SAFE-7, SP-PIPE-13). The message names every rule that
* failed, because {@link compileSplitRules} compiles each rule alone.
*/
private _reportSplitRuleCompileErrors(config: CompiledSplitConfig): void {
const source = config.splitRulesSource;
Iif (!source || this.reportedSplitRuleSets.has(source)) {
return;
}
this.reportedSplitRuleSets.add(source);
const details = config.compileErrors
.map(({ ruleId, message }) => (ruleId === undefined ? message : `'${ruleId}': ${message}`))
.join('; ');
const ruleIds = config.compileErrors
.map(({ ruleId }) => ruleId)
.filter(ruleId => ruleId !== undefined);
const names = ruleIds.length
? `${ruleIds.length === 1 ? 'split rule' : 'split rules'} ${ruleIds
.map(ruleId => `'${ruleId}'`)
.join(', ')} ${ruleIds.length === 1 ? 'has an error' : 'have errors'}`
: 'split rules have an error';
const message =
`No display sets were created, because the useMetadataDisplaySet ${names}. ` +
`Correct or remove the rule, then load the study again. ${details}`;
console.error(`DisplaySetService: ${message}`, config.compileErrors);
this._showSplitRuleError(message);
}
/**
* Records a split rule failure at run time for the study of the series, and
* shows it once (SP-SAFE-3, SP-PIPE-9). The study then gets no further
* display sets; the display sets that exist stay (SP-DET-3).
*
* @param failedRuleId - the rule of the group that the service placed when
* the error happened, for an error that does not name its rule itself.
* @param failedStep - the service step that failed, for the same case.
*/
private _recordSplitRuleFailure(
seriesInstances: InstanceMetadata[],
config: CompiledSplitConfig,
error: unknown,
failedRuleId?: string,
failedStep?: string
): void {
const { StudyInstanceUID, SeriesInstanceUID } = seriesInstances[0] ?? {};
Iif (this.splitRuleFailures.has(StudyInstanceUID)) {
return;
}
const named = error instanceof SplitRuleRunError;
const ruleId = named ? error.ruleId : failedRuleId;
const field = named ? error.field : failedStep;
const reason = named
? error.cause instanceof Error
? error.cause.message
: String(error.cause)
: error instanceof Error
? error.message
: String(error);
const where = ruleId
? `The split rule '${ruleId}' failed${field ? ` in '${field}'` : ''}`
: `The split rules failed${field ? ` in '${field}'` : ''}`;
const message =
`${where} for series ${SeriesInstanceUID}: ${reason}. ` +
`No further display sets are created for study ${StudyInstanceUID}.`;
this.splitRuleFailures.set(StudyInstanceUID, {
ruleSource: config.splitRulesSource,
ruleId,
field,
seriesInstanceUID: SeriesInstanceUID,
message,
});
console.error(`DisplaySetService: ${message}`, error);
this._showSplitRuleError(message);
}
/**
* Removes the run-time failures of a rule set that is no longer in effect:
* the corrected rules get a new chance for the study.
*/
private _clearStaleSplitRuleFailures(currentSource: object | undefined): void {
for (const [studyInstanceUID, failure] of this.splitRuleFailures) {
Iif (failure.ruleSource !== currentSource) {
this.splitRuleFailures.delete(studyInstanceUID);
}
}
}
/** The instances whose study has no split rule failure. */
private _withoutFailedStudies(instances: InstanceMetadata[]): InstanceMetadata[] {
if (!instances?.length || !this.splitRuleFailures.size) {
return instances ?? [];
}
return instances.filter(instance => !this.splitRuleFailures.has(instance.StudyInstanceUID));
}
/**
* Shows a split rule error that stays on screen until the user closes it.
* The notification service is absent in some unit tests.
*/
private _showSplitRuleError(message: string): void {
this.servicesManager?.services?.uiNotificationService?.show({
title: SPLIT_RULE_ERROR_TITLE,
message,
type: 'error',
// Sonner keeps a toast with an infinite duration until the user closes it.
duration: Infinity,
autoClose: false,
// The service shows each failure once; do not let the provider hide it.
allowDuplicates: true,
});
}
/**
* Splits `instancesSrc` into display sets using the customization-provided
* split rules, reconciling with display sets created by earlier calls for
* the same series (keyed by the deterministic, rule-namespaced `splitKey`).
*
* **Existing display sets only grow.** An instance that already has a display
* set stays in it. A later call - with new instances, or after the rules
* changed - only places the instances that are new to the series:
*
* - into the existing display set that holds the other instances of their
* group (via its `extendInstances` attribute, which fires the invalidation
* event), else the one with their group's `splitKey`;
* - otherwise into a new display set of their own.
*
* So the result can differ from a split of the complete series from the
* start: for example a late image that joins two time sweeps goes into the
* display set of its own group, and the display set of the other sweep keeps
* its instances. Repeated calls with the same instances add nothing.
*
* Splitting is performed one series at a time: unlike the legacy loop (which
* partitions by SOP class first), the splitter is handed a whole series so
* rules can aggregate series-level facts, and both the reconciliation key and
* the rules' `series()` facts are series-scoped (the upstream defaults read
* `instances[0].Modality`). Mixed-series input is therefore partitioned
* rather than assumed away.
*
* ### `splitKey` / `splitNumber` stability
*
* `splitKey` is the rule id and the rule's `groupBy` values, and holds no
* position. It is the key of the group that CREATED the display set; a
* display set that grew keeps it. `splitNumber` is only an index into the engine's group list and
* shifts when a new group appears, so it must not be used as a stable
* identity in `customAttributes`.
*
* ### A rule that fails at run time
*
* When a rule throws for a series - in the engine, or in the display set
* factory, which calls the rule's `customAttributes` - the series does NOT
* go to the SOP class handlers. The service records the failure for the
* study and shows it (see {@link _recordSplitRuleFailure}); the later series
* of the study in this call, and its later calls, create no display sets.
* The display sets that exist stay, including those the failing series
* created before the error.
*
* @returns the newly created display sets and the instances not matched by
* any split rule (which must flow to the legacy SOP class handler loop).
*/
private _makeDisplaySetsWithSplitRules(
instancesSrc: InstanceMetadata[],
config: CompiledSplitConfig,
settings
): { displaySets: DisplaySet[]; unmatched: InstanceMetadata[] } {
const bySeries = new Map<string, InstanceMetadata[]>();
for (const instance of instancesSrc) {
const seriesInstanceUID = instance.SeriesInstanceUID;
const series = bySeries.get(seriesInstanceUID);
if (series) {
series.push(instance);
} else {
bySeries.set(seriesInstanceUID, [instance]);
}
}
const displaySets: DisplaySet[] = [];
const unmatched: InstanceMetadata[] = [];
for (const seriesInstances of bySeries.values()) {
Iif (this.splitRuleFailures.has(seriesInstances[0].StudyInstanceUID)) {
// An earlier series of this call failed: no further display sets.
continue;
}
const result = this._splitSeriesIntoDisplaySets(seriesInstances, config, settings);
displaySets.push(...result.displaySets);
unmatched.push(...result.unmatched);
}
return { displaySets, unmatched };
}
/**
* Splits the instances of a SINGLE series. See
* {@link _makeDisplaySetsWithSplitRules} for the reconciliation semantics,
* and for what happens when a rule fails.
*/
private _splitSeriesIntoDisplaySets(
instancesSrc: InstanceMetadata[],
config: CompiledSplitConfig,
settings
): { displaySets: DisplaySet[]; unmatched: InstanceMetadata[] } {
const added: DisplaySet[] = [];
// The group and the step in progress, to name the rule of an error that
// the display set factory throws without a rule name.
let currentRuleId: string | undefined;
let currentStep: string | undefined;
try {
return this._placeSeriesGroups(instancesSrc, config, settings, added, (ruleId, step) => {
currentRuleId = ruleId;
currentStep = step;
});
} catch (error) {
this._recordSplitRuleFailure(instancesSrc, config, error, currentRuleId, currentStep);
// The display sets made before the error stay; nothing goes to the SOP
// class handlers.
return { displaySets: added, unmatched: [] };
}
}
/**
* The body of {@link _splitSeriesIntoDisplaySets}: groups the series, and
* places each group. It pushes each new display set into `added` as soon as
* the service stores it, so the caller keeps them when a later group throws.
* `onStep` receives the rule and the service step before each factory call.
*/
private _placeSeriesGroups(
instancesSrc: InstanceMetadata[],
config: CompiledSplitConfig,
settings,
added: DisplaySet[],
onStep: (ruleId: string | undefined, step: string | undefined) => void
): { displaySets: DisplaySet[]; unmatched: InstanceMetadata[] } {
const unmatched: InstanceMetadata[] = [];
const groups: InstanceGroup[] = groupInstancesBySplitRules(
instancesSrc as unknown as NaturalizedInstance[],
config.splitRules,
instance => unmatched.push(instance as unknown as InstanceMetadata),
// Ordering the engine applies to the instances of every group. Optional:
// with neither supplied the engine's own acquisition order applies.
{
sortInstances: config.sortInstances,
compareInstances: config.compareInstances,
}
);
const uidOf = (instance: { SOPInstanceUID?: string }) => instance.SOPInstanceUID;
const seriesDisplaySets = this.getDisplaySetsForSeries(instancesSrc[0].SeriesInstanceUID);
// Where each instance already lives. An instance never moves: a re-split
// only places the instances that are new to the series.
const homeOf = new Map<string, DisplaySet>();
const inOtherDisplaySet = new Set<string>();
const byKey = new Map<string, DisplaySet>();
for (const displaySet of seriesDisplaySets) {
Iif (!displaySet.splitKey) {
displaySet.instances?.forEach(instance => inOtherDisplaySet.add(uidOf(instance)));
continue;
}
byKey.set(displaySet.splitKey, displaySet);
displaySet.instances?.forEach(instance => {
Iif (!homeOf.has(uidOf(instance))) {
homeOf.set(uidOf(instance), displaySet);
}
});
}
const isNew = (instance: InstanceMetadata) =>
!homeOf.has(uidOf(instance)) && !inOtherDisplaySet.has(uidOf(instance));
groups.forEach((group, splitNumber) => {
const groupInstances = group.instances as unknown as InstanceMetadata[];
const newInstances = groupInstances.filter(isNew);
Iif (!newInstances.length) {
// Idempotent re-run: every instance already has a display set.
const homes = new Set(groupInstances.map(instance => homeOf.get(uidOf(instance))));
homes.delete(undefined);
this._addActiveDisplaySets([...homes]);
return;
}
// The display set that already holds the group's other instances, else
// the one with the group's key (a caller that passed only the new
// instances). Either way the existing display set only grows.
const target =
groupInstances.map(instance => homeOf.get(uidOf(instance))).find(Boolean) ??
byKey.get(group.splitKey);
onStep(group.matchedRule.id, 'extendInstances');
let home = target && this._extendSplitDisplaySet(target, newInstances, group, config);
Iif (!home) {
// No display set to extend: the new instances form a display set of
// their own. The group's older instances stay where they are.
onStep(group.matchedRule.id, 'createDisplaySetFromGroup');
home = config.createDisplaySetFromGroup?.(
{ ...group, instances: newInstances as unknown as NaturalizedInstance[] },
{ splitNumber, compareInstances: config.compareInstances }
);
Iif (!home) {
return;
}
onStep(group.matchedRule.id, 'extendDisplaySet');
Iif (this._extendWithHandler(home) === false) {
// The handler cannot show it, as its legacy path returns no display set.
return;
}
// applying hp-defined viewport settings to the displaysets
Object.keys(settings).forEach(key => {
home[key] = settings[key];
});
this._addDisplaySetsToCache([home]);
this._addActiveDisplaySets([home]);
added.push(home);
Iif (!byKey.has(group.splitKey)) {
byKey.set(group.splitKey, home);
}
}
newInstances.forEach(instance => homeOf.set(uidOf(instance), home));
});
// An instance that already has a split display set stays there, even when
// the rules no longer match it.
return {
displaySets: added,
unmatched: unmatched.filter(instance => !homeOf.has(uidOf(instance))),
};
}
/**
* Adds new instances to an existing split-rule display set, through its
* `extendInstances` hook, then the handler step with the new instances as
* `addedInstances`, and publishes the change.
*
* The series context of the re-split goes with the instances. Every rule of
* the split shares one context, so the context fits the display set even
* when another rule placed the new instances.
*
* @returns the display set, or undefined when it has no `extendInstances`
* hook or the hook declines the instances.
*/
private _extendSplitDisplaySet(
displaySet: DisplaySet,
newInstances: InstanceMetadata[],
group: InstanceGroup,
config: CompiledSplitConfig
): DisplaySet | undefined {
const updated = displaySet.extendInstances?.(
newInstances,
{
series: group.series,
compareInstances: config.compareInstances,
},
this
);
Iif (!updated) {
return undefined;
}
this._extendWithHandler(updated, newInstances);
this.activeDisplaySetsChanged = true;
this._addDisplaySetsToCache([updated]);
this._addActiveDisplaySets([updated]);
this.setDisplaySetMetadataInvalidated(updated.displaySetInstanceUID);
return updated;
}
/**
* Creates new display sets for the instances contained in instancesSrc
* according to the sop class handlers registered.
* This is idempotent in that calling it a second time with the
* same set of instances will not result in new display sets added.
* However, the response for the subsequent call will be empty as the data
* is already present.
* Calling it with some new instances and some existing instances will
* result in the new instances being added to existing display sets if
* they support the addInstances call, OR to new instances otherwise.
* Only the new instances are returned - the others are updated.
*
* @param instancesSrc are instances to add
* @param settings are settings to add
* @returns Array of the display sets added.
*/
private _makeDisplaySetForInstances(instancesSrc: InstanceMetadata[], settings): DisplaySet[] {
// Some of the sop class handlers take a direct reference to instances
// so make sure it gets copied here so that they have their own ref
let instances = [...instancesSrc];
const instance = instances[0];
const existingDisplaySets = this.getDisplaySetsForSeries(instance.SeriesInstanceUID) || [];
const SOPClassHandlerIds = this.SOPClassHandlerIds;
const allDisplaySets = [];
// Iterate over the sop class handlers while there are still instances to add
for (let i = 0; i < SOPClassHandlerIds.length && instances.length; i++) {
const SOPClassHandlerId = SOPClassHandlerIds[i];
const handler = this.extensionManager.getModuleEntry(SOPClassHandlerId);
if (handler.sopClassUids.includes(instance.SOPClassUID)) {
// Check if displaySets are already created using this SeriesInstanceUID/SOPClassHandler pair.
let displaySets = existingDisplaySets.filter(
displaySet => displaySet.SOPClassHandlerId === SOPClassHandlerId
);
if (displaySets.length) {
// This case occurs when there are already display sets, so remove
// any instances in existing display sets.
instances = filterInstances(instances, displaySets);
// See if an existing display set can add this instance to it,
// for example, if it is a new image to be added to the existing set
for (const ds of displaySets) {
const addedDs = ds.addInstances?.(instances, this);
Iif (addedDs) {
this.activeDisplaySetsChanged = true;
instances = filterInstances(instances, [addedDs]);
// Refresh the stored value so the metadata store reflects the
// merged display set (a pure overwrite).
this._addDisplaySetsToCache([addedDs]);
this._addActiveDisplaySets([addedDs]);
this.setDisplaySetMetadataInvalidated(addedDs.displaySetInstanceUID);
}
// This means that all instances already existed or got added to
// existing display sets, and had an invalidated event fired
Iif (!instances.length) {
return allDisplaySets;
}
}
Iif (!instances.length) {
// Everything is already added - this is just an update caused
// by something else
this._addActiveDisplaySets(displaySets);
return allDisplaySets;
}
}
// The instances array still contains some instances, so try
// creating additional display sets using the sop class handler
displaySets = handler.getDisplaySetsFromSeries(instances);
if (!displaySets || !displaySets.length) {
continue;
}
// applying hp-defined viewport settings to the displaysets
displaySets.forEach(ds => {
Object.keys(settings).forEach(key => {
ds[key] = settings[key];
});
});
this._addDisplaySetsToCache(displaySets);
this._addActiveDisplaySets(displaySets);
// It is possible that this SOP class handler handled some instances
// but there may need to be other instances handled by other handlers,
// so remove the handled instances
instances = filterInstances(instances, displaySets);
allDisplaySets.push(...displaySets);
}
}
// applying the default sopClassUID handler
if (allDisplaySets.length === 0) {
// applying hp-defined viewport settings to the displaysets
const handler = this.extensionManager.getModuleEntry(this.unsupportedSOPClassHandler);
const displaySets = handler.getDisplaySetsFromSeries(instances);
if (displaySets?.length) {
displaySets.forEach(ds => {
Object.keys(settings).forEach(key => {
ds[key] = settings[key];
});
});
this._addDisplaySetsToCache(displaySets);
this._addActiveDisplaySets(displaySets);
allDisplaySets.push(...displaySets);
}
}
return allDisplaySets;
}
/**
* Iterates over displaysets and invokes comparator for each element.
* It returns a list of items that has being succeed by comparator method.
*
* @param comparator - method to be used on the validation
* @returns list of displaysets
*/
public getDisplaySetsBy(comparator: (DisplaySet) => boolean): DisplaySet[] {
const result = [];
Iif (typeof comparator !== 'function') {
throw new Error(`The comparator ${comparator} was not a function`);
}
this.getActiveDisplaySets().forEach(displaySet => {
if (comparator(displaySet)) {
result.push(displaySet);
}
});
return result;
}
/**
* Sets the series sort of the thumbnail tray (the `thumbnailTray` order).
* It does not change `activeDisplaySets`, which keeps the default order, so
* the hanging protocols and the other users of the default order see no
* change. Ties under `sortFn` keep the default order.
*
* @param sortFn compares two display sets, ascending; returns 0 on a tie
* @param direction `descending` reverses `sortFn`, but not the default order
* that breaks its ties
* @param suppressEvent true to send no `DISPLAY_SET_ORDER_CHANGED` and no
* `DISPLAY_SETS_CHANGED`
*/
public sortDisplaySets(
sortFn: (a: DisplaySet, b: DisplaySet) => number,
direction: 'ascending' | 'descending' = 'ascending',
suppressEvent = false
): void {
this.displaySetSort = { sortFn, direction };
Iif (!suppressEvent) {
this._broadcastEvent(EVENTS.DISPLAY_SET_ORDER_CHANGED, { order: 'thumbnailTray' });
this._broadcastEvent(EVENTS.DISPLAY_SETS_CHANGED, this.activeDisplaySets);
}
}
/**
* @returns the sort last applied with sortDisplaySets, or null while the
* thumbnail tray uses the default order.
*/
public getDisplaySetSort(): DisplaySetSort | null {
return this.displaySetSort;
}
/**
* @returns the comparator of the named order. `default` is the
* `sortingCriteria` customization (or `seriesSortCriteria.default` without
* one). `thumbnailTray` orders the studies newest first, then applies the
* picked sort with the default order as the tie-break.
*/
public getSortCriteria(order: DisplaySetOrder = 'default'): DisplaySetComparator {
const defaultSortCriteria: DisplaySetComparator =
this.servicesManager?.services?.customizationService?.getCustomization('sortingCriteria') ??
seriesSortCriteria.default;
if (order === 'default') {
return defaultSortCriteria;
}
const seriesCriteria = sortCriteriaFor(this.displaySetSort, defaultSortCriteria);
const compareStudy = compareTrayStudyFor(this.activeDisplaySets);
return (a, b) => compareStudy(a, b) || seriesCriteria(a, b);
}
/**
* @returns a new array of the active display sets in the named order. The
* caller can sort or change the array; the store does not change.
*/
public getDisplaySets({ order = 'default' }: { order?: DisplaySetOrder } = {}): DisplaySet[] {
return [...this.activeDisplaySets].sort(this.getSortCriteria(order));
}
}
|