All files / extensions/default/src commandsModule.ts

58.59% Statements 150/256
45.96% Branches 57/124
58.53% Functions 24/41
59.12% Lines 149/252

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          248x                                                                                 248x                         248x     248x   248x                 15x         15x           15x     15x 15x         15x     15x           15x                               15x           15x 15x                 15x           15x                           8x                   8x     8x 8x                   8x 8x 8x                                           8x 4x   4x               8x     8x 4x     4x           4x 4x                 4x           4x                                                                                                                                           5x   5x   5x 5x       5x 5x             5x         262x                                                                                                               34x 34x       34x 34x 34x 34x 34x   34x           34x   34x 34x       34x           34x   34x       34x   34x   34x                               34x                       34x           34x         34x 34x           34x 34x                                                                                                                                             8x 8x 8x           8x   8x 8x 8x   8x   8x             8x               8x       6x 6x   6x   6x   1x   1x         1x               1x       1x                     1x   4x 10x       4x 4x     4x             1x         1x                   1x     1x 1x           5x 5x     5x 5x               5x                                                               5x 5x 5x   5x 5x     5x   5x                                               1x   1x 1x   1x       1x   1x       1x   1x       1x             8x   8x     8x   8x   8x 39x         8x         1x 1x     1x 1x       8x 7x     1x   1x   1x 1x                               1x   1x                     2x 2x 2x 2x 2x 2x     2x 2x                                                                                                                                                                     248x                                                                 248x                
import { Types, DicomMetadataStore, utils } from '@ohif/core';
import { datasetToDicomBlob, setNonEnumerableInstanceProperty } from './utils/dicomWriter';
import { registerNaturalizedDatasetsForLocalWadouri } from './utils/registerNaturalizedDatasetForLocalWadouri';
import { registerStoredInstanceImageIds } from './utils/registerStoredInstanceImageId';
 
const { downloadBlob } = utils;
 
import { ContextMenuController } from './CustomizableContextMenu';
import DicomTagBrowser from './DicomTagBrowser/DicomTagBrowser';
import reuseCachedLayouts from './utils/reuseCachedLayouts';
import {
  configureViewportForLayerAddition,
  configureViewportForLayerRemoval,
  canAddDisplaySetToViewport,
  DERIVED_OVERLAY_MODALITIES,
} from './utils/layerConfigurationUtils';
import findViewportsByPosition, {
  findOrCreateViewport as layoutFindOrCreate,
} from './findViewportsByPosition';
 
import { ContextMenuProps } from './CustomizableContextMenu/types';
import { NavigateHistory } from './types/commandModuleTypes';
import { history } from '@ohif/app';
import { useViewportGridStore } from './stores/useViewportGridStore';
import { useDisplaySetSelectorStore } from './stores/useDisplaySetSelectorStore';
import { useHangingProtocolStageIndexStore } from './stores/useHangingProtocolStageIndexStore';
import { useToggleHangingProtocolStore } from './stores/useToggleHangingProtocolStore';
import { useViewportsByPositionStore } from './stores/useViewportsByPositionStore';
import { useToggleOneUpViewportGridStore } from './stores/useToggleOneUpViewportGridStore';
import requestDisplaySetCreationForStudy from './Panels/requestDisplaySetCreationForStudy';
import promptSaveReport from './utils/promptSaveReport';
 
export type HangingProtocolParams = {
  protocolId?: string;
  stageIndex?: number;
  activeStudyUID?: string;
  stageId?: string;
  reset?: false;
  restoreCachedLayout?: boolean;
};
 
export type UpdateViewportDisplaySetParams = {
  direction: number;
  excludeNonImageModalities?: boolean;
};
 
const commandsModule = ({
  servicesManager,
  commandsManager,
  extensionManager,
}: Types.Extensions.ExtensionParams): Types.Extensions.CommandsModule => {
  const {
    customizationService,
    measurementService,
    hangingProtocolService,
    uiNotificationService,
    viewportGridService,
    displaySetService,
    multiMonitorService,
  } = servicesManager.services;
 
  // Define a context menu controller for use with any context menus
  const contextMenuController = new ContextMenuController(servicesManager, commandsManager);
 
  const actions = {
    /**
     * Adds a display set as a layer to the specified viewport
     *
     * @param options.viewportId - The ID of the viewport to add the layer to
     * @param options.displaySetInstanceUID - The UID of the display set to add as a layer
     * @param options.removeFirst - Optional flag to remove the display set first if it's already added
     */
    addDisplaySetAsLayer: ({ viewportId, displaySetInstanceUID, removeFirst = false }) => {
      Iif (!viewportId) {
        const { activeViewportId } = servicesManager.services.viewportGridService.getState();
        viewportId = activeViewportId;
      }
 
      Iif (!viewportId || !displaySetInstanceUID) {
        console.warn('Missing required parameters for addDisplaySetAsLayer command');
        return;
      }
 
      const { displaySetService, viewportGridService, hangingProtocolService } =
        servicesManager.services;
 
      // Get the display set
      const displaySet = displaySetService.getDisplaySetByUID(displaySetInstanceUID);
      Iif (!displaySet) {
        return;
      }
 
      // Get current display sets for the viewport
      const currentDisplaySetUIDs = viewportGridService.getDisplaySetsUIDsForViewport(viewportId);
 
      // Check if we can add this display set to the viewport
      const canAdd = canAddDisplaySetToViewport({
        viewportId,
        displaySetInstanceUID,
        servicesManager,
      });
 
      Iif (!canAdd) {
        return;
      }
 
      // Adding a layer is a per-viewport action: it shows the display set in the
      // one viewport it is given, and leaves `isHydrated` and the segmentation
      // presentation store alone. Those two are display-set-global ("show this
      // wherever it logically belongs"), so a viewport re-created after a
      // per-viewport add re-applies whatever hydration says rather than
      // inheriting the add. The global statement is made by the hydration
      // commands (hydrateSecondaryDisplaySet / loadSegmentationDisplaySetsForViewport
      // in extensions/cornerstone), which record it themselves; the removal
      // counterpart here is `removeDisplaySetLayer`'s `unhydrate` flag, which
      // exists because removal has callers that are themselves global.
      //
      // Add the display set to the viewport
      const updatedViewports = hangingProtocolService.getViewportsRequireUpdate(
        viewportId,
        displaySetInstanceUID
      );
 
      // Configure each viewport for layer addition
      updatedViewports.forEach(viewport => {
        configureViewportForLayerAddition({
          viewport,
          displaySetInstanceUID,
          currentDisplaySetUIDs,
          servicesManager,
        });
      });
 
      // Update position presentation
      commandsManager.runCommand('updateStoredPositionPresentation', {
        viewportId,
        displaySetInstanceUIDs: updatedViewports[0].displaySetInstanceUIDs,
      });
 
      // Run command to update viewports
      commandsManager.run('setDisplaySetsForViewports', {
        viewportsToUpdate: updatedViewports,
      });
    },
 
    /**
     * Removes a display set layer from the specified viewport
     *
     * @param options.viewportId - The ID of the viewport to remove the layer from
     * @param options.displaySetInstanceUID - The UID of the display set to remove
     * @param options.unhydrate - Whether this removal also means "stop showing
     *   this display set anywhere" (see the note below).
     */
    removeDisplaySetLayer: ({ viewportId, displaySetInstanceUID, unhydrate = false }) => {
      Iif (!viewportId || !displaySetInstanceUID) {
        console.warn('Missing required parameters for removeDisplaySetLayer command');
        return;
      }
 
      const {
        displaySetService,
        viewportGridService,
        hangingProtocolService,
        segmentationService,
      } = servicesManager.services;
 
      // Get the display set
      const displaySet = displaySetService.getDisplaySetByUID(displaySetInstanceUID);
      Iif (!displaySet) {
        return;
      }
 
      // Check if it's a segmentation and handle accordingly.
      // Note that for the sake of hydrated segmentations, we remove the
      // segmentation before checking if the display set is indeed in the viewport.
      // This is because hydrated segmentations are not in the viewport per se
      // {i.e. they are not layered) but are simply referenced by the display
      // set in the viewport.
      const isSegmentation = DERIVED_OVERLAY_MODALITIES.includes(displaySet.Modality);
      if (isSegmentation) {
        segmentationService.removeRepresentationsFromViewport(viewportId, {
          segmentationId: displaySetInstanceUID,
        });
 
        // By default this command is the single-viewport primitive: it removes
        // the layer from the one viewport it is given and leaves
        // `displaySet.isHydrated` and the segmentation presentation store alone,
        // both of which are display-set-global ("show this wherever it
        // logically belongs"). That is what the viewport overlay menu wants -
        // its Remove hides the overlay here, and a viewport re-created later
        // re-applies whatever hydration says. Clearing them unconditionally
        // would also let a layer *replacement* (remove + add) silently
        // un-hydrate the display set everywhere.
        //
        // `unhydrate: true` is the global statement, used by the removal paths
        // that are themselves global - the segmentation panel's Remove from
        // Viewport, and the SEGMENTATION_REMOVED handler in
        // extensions/cornerstone/src/utils/setUpSegmentationEventHandlers.ts
        // (which records it itself, before this loop over viewports). Recording
        // `hydrated: false` rather than dropping the entry keeps the store a
        // statement of desired state, so a viewport created later converges on
        // "not shown" instead of replaying an earlier `hydrated: true`.
        if (unhydrate) {
          displaySet.isHydrated = false;
 
          commandsManager.runCommand('updateStoredSegmentationPresentation', {
            displaySet,
            hydrated: false,
          });
        }
      }
 
      // Get current display sets for the viewport
      const currentDisplaySetUIDs = viewportGridService.getDisplaySetsUIDsForViewport(viewportId);
 
      // If the display set is not in the viewport, no need to remove it
      if (!currentDisplaySetUIDs.includes(displaySetInstanceUID)) {
        return;
      }
 
      const updatedViewports = hangingProtocolService.getViewportsRequireUpdate(
        viewportId,
        displaySetInstanceUID
      );
 
      // Configure each viewport for layer removal
      updatedViewports.forEach(viewport => {
        configureViewportForLayerRemoval({
          viewport,
          displaySetInstanceUID,
          currentDisplaySetUIDs,
          servicesManager,
        });
      });
 
      // Update position presentation
      commandsManager.runCommand('updateStoredPositionPresentation', {
        viewportId,
        displaySetInstanceUIDs: updatedViewports[0].displaySetInstanceUIDs,
      });
 
      // Update the viewports
      commandsManager.run('setDisplaySetsForViewports', {
        viewportsToUpdate: updatedViewports,
      });
    },
    /**
     * Runs a command in multi-monitor mode.  No-op if not multi-monitor.
     */
    multimonitor: async options => {
      const { screenDelta, StudyInstanceUID, commands, hashParams } = options;
      Iif (multiMonitorService.numberOfScreens < 2) {
        return options.fallback?.(options);
      }
 
      const newWindow = await multiMonitorService.launchWindow(
        StudyInstanceUID,
        screenDelta,
        hashParams
      );
 
      // Only run commands if we successfully got a window with a commands manager
      Iif (newWindow && commands) {
        // Todo: fix this properly, but it takes time for the new window to load
        // and then the commandsManager is available for it
        setTimeout(() => {
          multiMonitorService.run(screenDelta, commands, options);
        }, 1000);
      }
    },
 
    /** Displays a prompt and then save the report if relevant */
    promptSaveReport: props => {
      const { StudyInstanceUID } = props;
      promptSaveReport({ servicesManager, commandsManager, extensionManager }, props, {
        data: { StudyInstanceUID },
      });
    },
 
    /**
     * Ensures that the specified study is available for display
     * Then, if commands is specified, runs the given commands list/instance
     */
    loadStudy: async options => {
      const { StudyInstanceUID } = options;
      const displaySets = displaySetService.getActiveDisplaySets();
      const isActive = displaySets.find(ds => ds.StudyInstanceUID === StudyInstanceUID);
      Iif (isActive) {
        return;
      }
      const [dataSource] = extensionManager.getActiveDataSource();
      await requestDisplaySetCreationForStudy(dataSource, displaySetService, StudyInstanceUID);
 
      const study = DicomMetadataStore.getStudy(StudyInstanceUID);
      hangingProtocolService.addStudy(study);
    },
 
    /**
     * Show the context menu.
     * @param options.menuId defines the menu name to lookup, from customizationService
     * @param options.defaultMenu contains the default menu set to use
     * @param options.element is the element to show the menu within
     * @param options.event is the event that caused the context menu
     * @param options.selectorProps is the set of selection properties to use
     */
    showContextMenu: (options: ContextMenuProps) => {
      const {
        menuCustomizationId,
        element,
        event,
        selectorProps,
        defaultPointsPosition = [],
      } = options;
 
      const optionsToUse = { ...options };
 
      if (menuCustomizationId) {
        Object.assign(optionsToUse, customizationService.getCustomization(menuCustomizationId));
      }
 
      // TODO - make the selectorProps richer by including the study metadata and display set.
      const { protocol, stage } = hangingProtocolService.getActiveProtocol();
      optionsToUse.selectorProps = {
        event,
        protocol,
        stage,
        ...selectorProps,
      };
 
      contextMenuController.showContextMenu(optionsToUse, element, defaultPointsPosition);
    },
 
    /** Close a context menu currently displayed */
    closeContextMenu: () => {
      contextMenuController.closeContextMenu();
    },
 
    displayNotification: ({ text, title, type }) => {
      uiNotificationService.show({
        title: title,
        message: text,
        type: type,
      });
    },
 
    clearMeasurements: options => {
      measurementService.clearMeasurements(options.measurementFilter);
    },
 
    /**
     *  Sets the specified protocol
     *    1. Records any existing state using the viewport grid service
     *    2. Finds the destination state - this can be one of:
     *       a. The specified protocol stage
     *       b. An alternate (toggled or restored) protocol stage
     *       c. A restored custom layout
     *    3. Finds the parameters for the specified state
     *       a. Gets the displaySetSelectorMap
     *       b. Gets the map by position
     *       c. Gets any toggle mapping to map position to/from current view
     *    4. If restore, then sets layout
     *       a. Maps viewport position by currently displayed viewport map id
     *       b. Uses toggle information to map display set id
     *    5. Else applies the hanging protocol
     *       a. HP Service is provided displaySetSelectorMap
     *       b. HP Service will throw an exception if it isn't applicable
     * @param options - contains information on the HP to apply
     * @param options.activeStudyUID - the updated study to apply the HP to
     * @param options.protocolId - the protocol ID to change to
     * @param options.stageId - the stageId to apply
     * @param options.stageIndex - the index of the stage to go to.
     * @param options.reset - flag to indicate if the HP should be reset to its original and not restored to a previous state
     *
     * commandsManager.run('setHangingProtocol', {
     *   activeStudyUID: '1.2.3',
     *   protocolId: 'myProtocol',
     *   stageId: 'myStage',
     *   stageIndex: 0,
     *   reset: false,
     * });
     */
    setHangingProtocol: ({
      activeStudyUID = '',
      StudyInstanceUID = '',
      protocolId,
      stageId,
      stageIndex,
      reset = false,
      restoreCachedLayout = true,
    }: HangingProtocolParams): boolean => {
      const toUseStudyInstanceUID = activeStudyUID || StudyInstanceUID;
      try {
        // Stores in the state the display set selector id to displaySetUID mapping
        // Pass in viewportId for the active viewport.  This item will get set as
        // the activeViewportId
        const state = viewportGridService.getState();
        const hpInfo = hangingProtocolService.getState();
        reuseCachedLayouts(state, hangingProtocolService);
        const { hangingProtocolStageIndexMap } = useHangingProtocolStageIndexStore.getState();
        const { displaySetSelectorMap } = useDisplaySetSelectorStore.getState();
 
        Iif (!protocolId) {
          // Reuse the previous protocol id, and optionally stage
          protocolId = hpInfo.protocolId;
          Iif (stageId === undefined && stageIndex === undefined) {
            stageIndex = hpInfo.stageIndex;
          }
        } else if (stageIndex === undefined && stageId === undefined) {
          // Re-set the same stage as was previously used
          const hangingId = `${toUseStudyInstanceUID || hpInfo.activeStudyUID}:${protocolId}`;
          stageIndex = hangingProtocolStageIndexMap[hangingId]?.stageIndex;
        }
 
        const useStageIdx =
          stageIndex ??
          hangingProtocolService.getStageIndex(protocolId, {
            stageId,
            stageIndex,
          });
 
        const activeStudyChanged = hangingProtocolService.setActiveStudyUID(toUseStudyInstanceUID);
 
        const storedHanging = `${toUseStudyInstanceUID || hangingProtocolService.getState().activeStudyUID}:${protocolId}:${
          useStageIdx || 0
        }`;
 
        const { viewportGridState } = useViewportGridStore.getState();
        // An explicit preset selection passes restoreCachedLayout: false so the stage layout wins over a stale cached grid
        const restoreProtocol = !reset && restoreCachedLayout && viewportGridState[storedHanging];
 
        Iif (
          reset ||
          (activeStudyChanged &&
            !viewportGridState[storedHanging] &&
            stageIndex === undefined &&
            stageId === undefined)
        ) {
          // Run the hanging protocol fresh, re-using the existing study data
          // This is done on reset or when the study changes and we haven't yet
          // applied it, and don't specify exact stage to use.
          const displaySets = displaySetService.getActiveDisplaySets();
          const activeStudy = {
            StudyInstanceUID: toUseStudyInstanceUID,
            displaySets,
          };
          hangingProtocolService.run(activeStudy, protocolId);
        } else Iif (
          protocolId === hpInfo.protocolId &&
          useStageIdx === hpInfo.stageIndex &&
          !toUseStudyInstanceUID
        ) {
          // Clear the HP setting to reset them
          hangingProtocolService.setProtocol(protocolId, {
            stageId,
            stageIndex: useStageIdx,
            displaySetSelectorMap,
          });
        } else {
          hangingProtocolService.setProtocol(protocolId, {
            displaySetSelectorMap,
            stageId,
            stageIndex: useStageIdx,
            restoreProtocol,
          });
          Iif (restoreProtocol) {
            viewportGridService.set(viewportGridState[storedHanging]);
          }
        }
        // Do this after successfully applying the update
        const { setDisplaySetSelector } = useDisplaySetSelectorStore.getState();
        setDisplaySetSelector(
          `${toUseStudyInstanceUID || hpInfo.activeStudyUID}:activeDisplaySet:0`,
          null
        );
 
        // An applied protocol is an explicit layout change, so abandon any pending one-up toggle
        useToggleOneUpViewportGridStore.getState().clearToggleOneUpViewportGridStore();
        return true;
      } catch (e) {
        console.error(e);
        uiNotificationService.show({
          title: 'Apply Hanging Protocol',
          message: 'The hanging protocol could not be applied.',
          type: 'error',
          duration: 3000,
        });
        return false;
      }
    },
 
    toggleHangingProtocol: ({ protocolId, stageIndex }: HangingProtocolParams): boolean => {
      const {
        protocol,
        stageIndex: desiredStageIndex,
        activeStudy,
      } = hangingProtocolService.getActiveProtocol();
      const { toggleHangingProtocol, setToggleHangingProtocol } =
        useToggleHangingProtocolStore.getState();
      const storedHanging = `${activeStudy.StudyInstanceUID}:${protocolId}:${stageIndex | 0}`;
      if (
        protocol.id === protocolId &&
        (stageIndex === undefined || stageIndex === desiredStageIndex)
      ) {
        // Toggling off - restore to previous state
        const previousState = toggleHangingProtocol[storedHanging] || {
          protocolId: 'default',
        };
        return actions.setHangingProtocol(previousState);
      } else {
        setToggleHangingProtocol(storedHanging, {
          protocolId: protocol.id,
          stageIndex: desiredStageIndex,
        });
        return actions.setHangingProtocol({
          protocolId,
          stageIndex,
          reset: true,
        });
      }
    },
 
    deltaStage: ({ direction }) => {
      const { protocolId, stageIndex: oldStageIndex } = hangingProtocolService.getState();
      const { protocol } = hangingProtocolService.getActiveProtocol();
      for (
        let stageIndex = oldStageIndex + direction;
        stageIndex >= 0 && stageIndex < protocol.stages.length;
        stageIndex += direction
      ) {
        Iif (protocol.stages[stageIndex].status !== 'disabled') {
          return actions.setHangingProtocol({
            protocolId,
            stageIndex,
          });
        }
      }
      uiNotificationService.show({
        title: 'Change Stage',
        message: 'The hanging protocol has no more applicable stages',
        type: 'info',
        duration: 3000,
      });
    },
 
    /**
     * Changes the viewport grid layout in terms of the MxN layout.
     */
    setViewportGridLayout: ({ numRows, numCols, isHangingProtocolLayout = false }) => {
      const { protocol } = hangingProtocolService.getActiveProtocol();
      const onLayoutChange = protocol.callbacks?.onLayoutChange;
      Iif (commandsManager.run(onLayoutChange, { numRows, numCols }) === false) {
        // Don't apply the layout if the run command returns false
        return;
      }
 
      // An explicit grid selection abandons any pending one-up toggle; clear only past the onLayoutChange veto
      useToggleOneUpViewportGridStore.getState().clearToggleOneUpViewportGridStore();
 
      const completeLayout = () => {
        const state = viewportGridService.getState();
        findViewportsByPosition(state, { numRows, numCols });
 
        const { viewportsByPosition, initialInDisplay } = useViewportsByPositionStore.getState();
 
        const findOrCreateViewport = layoutFindOrCreate.bind(
          null,
          hangingProtocolService,
          isHangingProtocolLayout,
          { ...viewportsByPosition, initialInDisplay }
        );
 
        viewportGridService.setLayout({
          numRows,
          numCols,
          findOrCreateViewport,
          isHangingProtocolLayout,
        });
      };
      // Need to finish any work in the callback
      window.setTimeout(completeLayout, 0);
    },
 
    toggleOneUp() {
      const viewportGridState = viewportGridService.getState();
      const { activeViewportId, viewports, layout, isHangingProtocolLayout } = viewportGridState;
      const { displaySetInstanceUIDs, displaySetOptions, viewportOptions } =
        viewports.get(activeViewportId);
 
      if (layout.numCols === 1 && layout.numRows === 1) {
        // The viewer is in one-up. Check if there is a state to restore/toggle back to.
        const { toggleOneUpViewportGridStore } = useToggleOneUpViewportGridStore.getState();
 
        Iif (!toggleOneUpViewportGridStore) {
          return;
        }
        // There is a state to toggle back to. The viewport that was
        // originally toggled to one up was the former active viewport.
        const viewportIdToUpdate = toggleOneUpViewportGridStore.activeViewportId;
 
        // We are restoring the previous layout but taking into the account that
        // the current one up viewport might have a new displaySet dragged and dropped on it.
        // updatedViewportsViaHP below contains the viewports applicable to the HP that existed
        // prior to the toggle to one-up - including the updated viewports if a display
        // set swap were to have occurred.
        const updatedViewportsViaHP =
          displaySetInstanceUIDs.length > 1
            ? []
            : displaySetInstanceUIDs
                .map(displaySetInstanceUID =>
                  hangingProtocolService.getViewportsRequireUpdate(
                    viewportIdToUpdate,
                    displaySetInstanceUID,
                    isHangingProtocolLayout
                  )
                )
                .flat();
 
        // findOrCreateViewport returns either one of the updatedViewportsViaHP
        // returned from the HP service OR if there is not one from the HP service then
        // simply returns what was in the previous state for a given position in the layout.
        const findOrCreateViewport = (position: number, positionId: string) => {
          // Find the viewport for the given position prior to the toggle to one-up.
          const preOneUpViewport = Array.from(toggleOneUpViewportGridStore.viewports.values()).find(
            viewport => viewport.positionId === positionId
          );
 
          // Use the viewport id from before the toggle to one-up to find any updates to the viewport.
          const viewport = updatedViewportsViaHP.find(
            viewport => viewport.viewportId === preOneUpViewport.viewportId
          );
 
          return viewport
            ? // Use the applicable viewport from the HP updated viewports
              { viewportOptions, displaySetOptions, ...viewport }
            : // Use the previous viewport for the given position
              preOneUpViewport;
        };
 
        const layoutOptions = viewportGridService.getLayoutOptionsFromState(
          toggleOneUpViewportGridStore
        );
 
        // Restore the previous layout including the active viewport.
        viewportGridService.setLayout({
          numRows: toggleOneUpViewportGridStore.layout.numRows,
          numCols: toggleOneUpViewportGridStore.layout.numCols,
          activeViewportId: viewportIdToUpdate,
          layoutOptions,
          findOrCreateViewport,
          isHangingProtocolLayout: true,
        });
 
        // Toggled back, so drop the stored layout; the store only holds a currently active one-up
        useToggleOneUpViewportGridStore.getState().clearToggleOneUpViewportGridStore();
 
        // Reset crosshairs after restoring the layout
        setTimeout(() => {
          commandsManager.runCommand('resetCrosshairs');
        }, 0);
      } else {
        // We are not in one-up, so toggle to one up.
 
        // Store the current viewport grid state so we can toggle it back later.
        const { setToggleOneUpViewportGridStore } = useToggleOneUpViewportGridStore.getState();
        setToggleOneUpViewportGridStore(viewportGridState);
 
        // one being toggled to one up.
        const findOrCreateViewport = () => {
          return {
            displaySetInstanceUIDs,
            displaySetOptions,
            viewportOptions,
          };
        };
 
        // Set the layout to be 1x1/one-up.
        viewportGridService.setLayout({
          numRows: 1,
          numCols: 1,
          findOrCreateViewport,
          isHangingProtocolLayout: true,
        });
      }
    },
 
    /**
     * Exposes the browser history navigation used by OHIF. This command can be used to either replace or
     * push a new entry into the browser history. For example, the following will replace the current
     * browser history entry with the specified relative URL which changes the study displayed to the
     * study with study instance UID 1.2.3. Note that as a result of using `options.replace = true`, the
     * page prior to invoking this command cannot be returned to via the browser back button.
     *
     * navigateHistory({
     *   to: 'viewer?StudyInstanceUIDs=1.2.3',
     *   options: { replace: true },
     * });
     *
     * @param historyArgs - arguments for the history function;
     *                      the `to` property is the URL;
     *                      the `options.replace` is a boolean indicating if the current browser history entry
     *                      should be replaced or a new entry pushed onto the history (stack); the default value
     *                      for `replace` is false
     */
    navigateHistory(historyArgs: NavigateHistory) {
      history.navigate(historyArgs.to, historyArgs.options);
    },
 
    openDICOMTagViewer({ displaySetInstanceUID }: { displaySetInstanceUID?: string }) {
      const { activeViewportId, viewports } = viewportGridService.getState();
      const activeViewportSpecificData = viewports.get(activeViewportId);
      const { displaySetInstanceUIDs } = activeViewportSpecificData;
 
      const displaySets = displaySetService.activeDisplaySets;
      const { UIModalService } = servicesManager.services;
 
      const defaultDisplaySetInstanceUID =
        displaySetInstanceUID || displaySetInstanceUIDs[0] || displaySets[0]?.displaySetInstanceUID;
 
      UIModalService.show({
        content: DicomTagBrowser,
        contentProps: {
          displaySets,
          displaySetInstanceUID: defaultDisplaySetInstanceUID,
        },
        title: 'DICOM Tag Browser',
        containerClassName: 'max-w-3xl',
      });
    },
 
    /**
     * Toggle viewport overlay (the information panel shown on the four corners
     * of the viewport)
     * @see ViewportOverlay and CustomizableViewportOverlay components
     */
    toggleOverlays: () => {
      const overlays = document.getElementsByClassName('viewport-overlay');
      for (let i = 0; i < overlays.length; i++) {
        overlays.item(i).classList.toggle('hidden');
      }
    },
 
    scrollActiveThumbnailIntoView: () => {
      const { activeViewportId, viewports } = viewportGridService.getState();
 
      const activeViewport = viewports.get(activeViewportId);
      const activeDisplaySetInstanceUID = activeViewport?.displaySetInstanceUIDs?.[0];
 
      Iif (!activeDisplaySetInstanceUID) {
        return;
      }
 
      const thumbnailList = document.querySelector('#ohif-thumbnail-list');
 
      Iif (!thumbnailList) {
        return;
      }
 
      const thumbnail = document.querySelector(`#thumbnail-${activeDisplaySetInstanceUID}`);
 
      Iif (!thumbnail) {
        return;
      }
 
      thumbnail.scrollIntoView({ behavior: 'smooth' });
    },
 
    updateViewportDisplaySet: ({
      direction,
      excludeNonImageModalities,
    }: UpdateViewportDisplaySetParams) => {
      const nonImageModalities = ['SR', 'SEG', 'SM', 'RTSTRUCT', 'RTPLAN', 'RTDOSE'];
 
      const currentDisplaySets = [...displaySetService.activeDisplaySets];
 
      const { activeViewportId, viewports, isHangingProtocolLayout } =
        viewportGridService.getState();
 
      const { displaySetInstanceUIDs } = viewports.get(activeViewportId);
 
      const activeDisplaySetIndex = currentDisplaySets.findIndex(displaySet =>
        displaySetInstanceUIDs.includes(displaySet.displaySetInstanceUID)
      );
 
      let displaySetIndexToShow: number;
 
      for (
        displaySetIndexToShow = activeDisplaySetIndex + direction;
        displaySetIndexToShow > -1 && displaySetIndexToShow < currentDisplaySets.length;
        displaySetIndexToShow += direction
      ) {
        const nextDisplaySet = currentDisplaySets[displaySetIndexToShow];
        Iif (nextDisplaySet.madeInClient) {
          continue;
        }
        if (!excludeNonImageModalities || !nonImageModalities.includes(nextDisplaySet.Modality)) {
          break;
        }
      }
 
      if (displaySetIndexToShow < 0 || displaySetIndexToShow >= currentDisplaySets.length) {
        return;
      }
 
      const { displaySetInstanceUID } = currentDisplaySets[displaySetIndexToShow];
 
      let updatedViewports = [];
 
      try {
        updatedViewports = hangingProtocolService.getViewportsRequireUpdate(
          activeViewportId,
          displaySetInstanceUID,
          isHangingProtocolLayout
        );
      } catch (error) {
        console.warn(error);
        uiNotificationService.show({
          title: 'Navigate Viewport Display Set',
          message:
            'The requested display sets could not be added to the viewport due to a mismatch in the Hanging Protocol rules.',
          type: 'info',
          duration: 3000,
        });
      }
 
      commandsManager.run('setDisplaySetsForViewports', { viewportsToUpdate: updatedViewports });
 
      setTimeout(() => actions.scrollActiveThumbnailIntoView(), 0);
    },
 
    /**
     * Creates a store function based on the data source type.
     * @param dataSource - 'download', 'copyToClipboard', or a named data source
     * @param defaultFileName - Default filename for download/clipboard
     * @param defaultContentType - Default content type for clipboard
     * @returns A store function, or null if no valid store exists
     */
    createStoreFunction: ({ dataSource, defaultFileName, defaultContentType }) => {
      if (dataSource === 'download') {
        return async dicom => {
          const instances = Array.isArray(dicom) ? dicom : [dicom];
          registerNaturalizedDatasetsForLocalWadouri(instances);
          DicomMetadataStore.addInstances(instances, true);
          Iif (instances.length !== 1) {
            throw new Error('Download only supports a single DICOM instance');
          }
          const reportBlob = datasetToDicomBlob(instances[0]);
          downloadBlob(reportBlob, { filename: defaultFileName || 'dicom.dcm' });
        };
      }
 
      Iif (dataSource === 'copyToClipboard') {
        return async dicom => {
          const instances = Array.isArray(dicom) ? dicom : [dicom];
          registerNaturalizedDatasetsForLocalWadouri(instances);
          DicomMetadataStore.addInstances(instances, true);
          Iif (instances.length !== 1) {
            throw new Error('Copy to clipboard only supports a single DICOM instance');
          }
          const reportBlob = datasetToDicomBlob(instances[0]);
          const type = defaultContentType || 'application/dicom';
          await navigator.clipboard.write([new ClipboardItem({ [type]: reportBlob })]);
        };
      }
 
      // DICOM STOW path — resolve the named data source
      const dataSources = extensionManager.getDataSources(dataSource);
      const resolvedDataSource = dataSources?.[0];
      Iif (!resolvedDataSource?.store?.dicom) {
        return null;
      }
 
      return async (dicom, { dicomDict } = {}) => {
        const instances = Array.isArray(dicom) ? dicom : [dicom];
        // Always keep an in-memory wadouri copy so DICOM can be read without re-fetching.
        registerNaturalizedDatasetsForLocalWadouri(instances);
 
        Iif (dataSource !== 'dicomlocal') {
          const config = resolvedDataSource.getConfig?.();
          Iif (config?.wadoRoot) {
            instances.forEach(instance => {
              setNonEnumerableInstanceProperty(instance, 'wadoRoot', config.wadoRoot);
            });
          }
        }
 
        // Identify the stored instances before they reach the metadata store, so
        // that the display sets made from them know which instance they came
        // from, and a later save of the same data can extend this series.
        registerStoredInstanceImageIds(instances, resolvedDataSource);
 
        DicomMetadataStore.addInstances(instances, true);
        for (const instance of instances) {
          await resolvedDataSource.store.dicom(instance, null, dicomDict);
        }
        const studyUIDs = new Set(instances.map(i => i.StudyInstanceUID).filter(Boolean));
        for (const uid of studyUIDs) {
          resolvedDataSource.deleteStudyMetadataPromise(uid);
        }
      };
    },
 
    /**
     * Launches a workflow (mode) for a study from the worklist. This is the
     * default `workList.onStudyDoubleClick` command.
     *
     * @param study - the StudyRow the action applies to
     * @param workflows - the workflows applicable to the study, in menu order;
     *   each has `id`, `displayName`, `isDefault` and `launchWithStudy(study)`
     * @param defaultWorkflow - the user's default workflow when it applies to
     *   the study
     * @param workflowId - command option to force a specific workflow (mode id)
     *   instead of the default/first applicable one
     */
    launchDefaultMode: ({ study, workflows = [], defaultWorkflow, workflowId }) => {
      const workflow = workflowId
        ? workflows.find(w => w.id === workflowId)
        : (defaultWorkflow ?? workflows[0]);
      Iif (!workflow) {
        console.warn(
          workflowId
            ? `launchDefaultMode: workflow '${workflowId}' is not applicable to the study`
            : 'launchDefaultMode: no workflow is applicable to the study'
        );
        return;
      }
      workflow.launchWithStudy(study);
    },
  };
 
  const definitions = {
    multimonitor: actions.multimonitor,
    promptSaveReport: actions.promptSaveReport,
    loadStudy: actions.loadStudy,
    showContextMenu: actions.showContextMenu,
    closeContextMenu: actions.closeContextMenu,
    clearMeasurements: actions.clearMeasurements,
    displayNotification: actions.displayNotification,
    setHangingProtocol: actions.setHangingProtocol,
    toggleHangingProtocol: actions.toggleHangingProtocol,
    navigateHistory: actions.navigateHistory,
    nextStage: {
      commandFn: actions.deltaStage,
      options: { direction: 1 },
    },
    previousStage: {
      commandFn: actions.deltaStage,
      options: { direction: -1 },
    },
    setViewportGridLayout: actions.setViewportGridLayout,
    toggleOneUp: actions.toggleOneUp,
    openDICOMTagViewer: actions.openDICOMTagViewer,
    updateViewportDisplaySet: actions.updateViewportDisplaySet,
    scrollActiveThumbnailIntoView: actions.scrollActiveThumbnailIntoView,
    addDisplaySetAsLayer: actions.addDisplaySetAsLayer,
    removeDisplaySetLayer: actions.removeDisplaySetLayer,
    createStoreFunction: actions.createStoreFunction,
    launchDefaultMode: {
      commandFn: actions.launchDefaultMode,
      context: 'WORKLIST',
    },
  };
 
  return {
    actions,
    definitions,
    defaultContext: 'DEFAULT',
  };
};
 
export default commandsModule;