All files / packages/tools/src/utilities/segmentation triggerSegmentationRender.ts

84.74% Statements 50/59
60% Branches 12/20
100% Functions 13/13
84.74% Lines 50/59

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                                                        1x 1x 1x       102x   102x 102x         33x               25x                     33x 33x       33x                 33x 25x         25x       1x 25x     25x   25x 25x     25x       25x 25x 25x 25x         25x   25x         25x   25x   33x   33x         33x   33x 33x         25x     25x           33x   33x         33x   33x         33x         33x                               25x 33x           25x             102x   102x 102x 102x       1x             33x          
import {
  triggerEvent,
  eventTarget,
  getRenderingEngine,
  Enums,
  Types,
} from '@cornerstonejs/core';
import { Events as csToolsEvents } from '../../enums';
import {
  getToolGroup,
  getToolGroupForViewport,
} from '../../store/ToolGroupManager';
 
import { SegmentationDisplayTool } from '../../tools';
import { SegmentationRenderedEventDetail } from '../../types/EventTypes';
 
/**
 * SegmentationRenderingEngine is a class that is responsible for rendering
 * segmentations for a toolGroup. It will call SegmentationDisplayTool to render the segmentation
 * based on the segmentation data and their configurations. Note: This is a Singleton class
 * and should not be instantiated directly. To trigger a render for all the
 * segmentations of a tool group you can use.
 *
 * ```
 * triggerSegmentationRender(toolGroupId)
 * ```
 */
class SegmentationRenderingEngine {
  private _needsRender: Set<string> = new Set();
  private _animationFrameSet = false;
  private _animationFrameHandle: number | null = null;
  public hasBeenDestroyed: boolean;
 
  public removeToolGroup(toolGroupId) {
    this._needsRender.delete(toolGroupId);
 
    Eif (this._needsRender.size === 0) {
      this._reset();
    }
  }
 
  public renderToolGroupSegmentations(toolGroupId): void {
    this._setToolGroupSegmentationToBeRenderedNextFrame([toolGroupId]);
  }
 
  /**
   *  _throwIfDestroyed Throws an error if trying to interact with the `RenderingEngine`
   * instance after its `destroy` method has been called.
   */
  private _throwIfDestroyed() {
    Iif (this.hasBeenDestroyed) {
      throw new Error(
        'this.destroy() has been manually called to free up memory, can not longer use this instance. Instead make a new one.'
      );
    }
  }
 
  private _setToolGroupSegmentationToBeRenderedNextFrame(
    toolGroupIds: string[]
  ) {
    // Add the viewports to the set of flagged viewports
    toolGroupIds.forEach((toolGroupId) => {
      this._needsRender.add(toolGroupId);
    });
 
    // Render any flagged viewports
    this._render();
  }
 
  /**
   *  _render Sets up animation frame if necessary
   */
  private _render() {
    // If we have viewports that need rendering and we have not already
    // set the RAF callback to run on the next frame.
    if (this._needsRender.size > 0 && this._animationFrameSet === false) {
      this._animationFrameHandle = window.requestAnimationFrame(
        this._renderFlaggedToolGroups
      );
 
      // Set the flag that we have already set up the next RAF call.
      this._animationFrameSet = true;
    }
  }
 
  private _renderFlaggedToolGroups = () => {
    this._throwIfDestroyed();
 
    // for each toolGroupId insides the _needsRender set, render the segmentation
    const toolGroupIds = Array.from(this._needsRender.values());
 
    for (const toolGroupId of toolGroupIds) {
      this._triggerRender(toolGroupId);
 
      // This viewport has been rendered, we can remove it from the set
      this._needsRender.delete(toolGroupId);
 
      // If there is nothing left that is flagged for rendering, stop here
      // and allow RAF to be called again
      Eif (this._needsRender.size === 0) {
        this._animationFrameSet = false;
        this._animationFrameHandle = null;
        return;
      }
    }
  };
  _triggerRender(toolGroupId) {
    const toolGroup = getToolGroup(toolGroupId);
 
    Iif (!toolGroup) {
      console.warn(`No tool group found with toolGroupId: ${toolGroupId}`);
      return;
    }
 
    const { viewportsInfo } = toolGroup;
 
    const viewports = viewportsInfo
      .map(({ viewportId, renderingEngineId }) => {
        const renderingEngine = getRenderingEngine(renderingEngineId);
 
        Iif (!renderingEngine) {
          console.warn('rendering Engine has been destroyed');
          return;
        }
 
        const viewport = renderingEngine.getViewport(viewportId);
 
        Eif (viewport) {
          return viewport;
        }
      })
      .filter(Boolean);
 
    const segmentationDisplayToolInstance = toolGroup.getToolInstance(
      SegmentationDisplayTool.toolName
    ) as SegmentationDisplayTool;
    Iif (!segmentationDisplayToolInstance) {
      console.warn('No segmentation tool found inside', toolGroupId);
      return;
    }
 
    function onSegmentationRender(evt: Types.EventTypes.ImageRenderedEvent) {
      const { element, viewportId, renderingEngineId } = evt.detail;
 
      element.removeEventListener(
        Enums.Events.IMAGE_RENDERED,
        onSegmentationRender as EventListener
      );
 
      const toolGroup = getToolGroupForViewport(viewportId, renderingEngineId);
 
      Iif (!toolGroup) {
        console.warn('toolGroup has been destroyed');
        return;
      }
 
      const eventDetail: SegmentationRenderedEventDetail = {
        toolGroupId: toolGroup.id,
        viewportId,
      };
 
      triggerEvent(eventTarget, csToolsEvents.SEGMENTATION_RENDERED, {
        ...eventDetail,
      });
    }
 
    // Todo: for other representations we probably need the drawSVG, but right now we are not using it
    // drawSvg(element, (svgDrawingHelper) => {
    //   const handleDrawSvg = (tool) => {
    //     if (tool instanceof SegmentationDisplayTool && tool.renderAnnotation) {
    //       tool.renderAnnotation({ detail: eventDetail })
    //       triggerEvent(element, csToolsEvents.SEGMENTATION_RENDERED, { ...eventDetail })
    //     }
    //   }
    //   enabledTools.forEach(handleDrawSvg)
    // })
 
    viewports.forEach(({ element }) => {
      element.addEventListener(
        Enums.Events.IMAGE_RENDERED,
        onSegmentationRender as EventListener
      );
    });
 
    segmentationDisplayToolInstance.renderSegmentation(toolGroupId);
  }
 
  /**
   *  _reset Resets the `RenderingEngine`
   */
  private _reset() {
    window.cancelAnimationFrame(this._animationFrameHandle);
 
    this._needsRender.clear();
    this._animationFrameSet = false;
    this._animationFrameHandle = null;
  }
}
 
const segmentationRenderingEngine = new SegmentationRenderingEngine();
 
/**
 * It triggers a render for all the segmentations of the tool group with the given Id.
 * @param toolGroupId - The Id of the tool group to render.
 */
function triggerSegmentationRender(toolGroupId: string): void {
  segmentationRenderingEngine.renderToolGroupSegmentations(toolGroupId);
}
 
export { segmentationRenderingEngine, triggerSegmentationRender };
export default triggerSegmentationRender;