Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

12.4 KB
Raw Blame
import type { CanvasDocumentSnapshot, PsdExportResult, PsdExportStatus } from '@workbench/canvas-engine/capabilities';
import type { CanvasNodeContract } from '@workbench/canvas-engine/contracts';
import type {
  CanvasDetachedLayerSurface,
  CaptureRasterSnapshotResult,
} from '@workbench/canvas-engine/rasterTransactions';
import type { RasterBackend } from '@workbench/canvas-engine/render/raster';

import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';
import { isGroupNode } from '@workbench/canvas-engine/document/documentTree';
import {
  executePsdExport,
  planPsdExport,
  type ExecutePsdExportDeps,
  type PsdExportNodeInput,
  type PsdExportPlan,
  type PsdGroupStack,
  type PsdPlanNode,
} from '@workbench/canvas-engine/export/psdExport';
import { isExportableRasterLayer } from '@workbench/canvas-engine/layerExportGuards';
import { isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';
import {
  AdjustmentRefusedError,
  adjustmentRefusal,
  type SpatialRunner,
} from '@workbench/canvas-engine/render/exactAdjustments';

type RasterMemoryReservationResult =
  | { status: 'ok'; lease: { release(): void } }
  | { status: 'over-budget'; requestedBytes: number; availableBytes: number };

export interface PsdExportControllerOptions {
  readonly backend: RasterBackend;
  readonly onStatus?: (status: PsdExportStatus) => void;
  readonly captureDocumentSnapshot: () => CanvasDocumentSnapshot | null;
  readonly captureRasterSnapshot: (
    snapshot: CanvasDocumentSnapshot,
    layerIds: readonly string[],
    options: { signal: AbortSignal; includeDisabled: boolean }
  ) => Promise<CaptureRasterSnapshotResult>;
  readonly execute?: (plan: PsdExportPlan, fileName: string, deps: ExecutePsdExportDeps) => Promise<void>;
  readonly getAvailableBytes: () => number;
  readonly isDocumentSnapshotCurrent: (snapshot: CanvasDocumentSnapshot) => boolean;
  readonly reserve: (bytes: number) => RasterMemoryReservationResult;
  /** Evaluates spatial adjustment runs; without it a spatial stack refuses `error`. */
  readonly runSpatial?: SpatialRunner;
}

export const PSD_ALLOCATION_BYTES_PER_PIXEL = 8;

const countIsolatedFolders = (nodes: readonly PsdPlanNode[]): number =>
  nodes.reduce(
    (total, node) =>
      node.kind === 'folder'
        ? total +
          countIsolatedFolders(node.children) +
          (node.opacity !== 1 || node.compositeBlend !== 'source-over' ? 1 : 0)
        : total,
    0
  );

// Layers bake one at a time; an adjusted layer's transient layer-local copy is counted once, at the largest.
const getRequiredAllocationPixelArea = (plan: Extract<PsdExportPlan, { status: 'ok' }>): number =>
  plan.width * plan.height * (1 + countIsolatedFolders(plan.tree)) +
  plan.layers.reduce((total, layer) => total + layer.worldRect.width * layer.worldRect.height, 0) +
  plan.layers.reduce(
    (largest, layer) =>
      layer.adjustments ? Math.max(largest, layer.contentRect.width * layer.contentRect.height) : largest,
    0
  );

/** Raster preparation remains under the engine cache budget. Serialization has its own bounded lifetime. */
export const getPsdRequiredBytes = (plan: Extract<PsdExportPlan, { status: 'ok' }>): number =>
  getRequiredAllocationPixelArea(plan) * PSD_ALLOCATION_BYTES_PER_PIXEL;

/** One private worker per engine, including uncollected writer growth buffers; not a browser RSS limit. */
export const PSD_SERIALIZATION_ALLOWANCE_BYTES = 1280 * 1024 * 1024;

/**
 * Installed PackBits: full literal packets add one byte per 128 samples. An interrupted literal header is paid for by
 * the following >=3-sample run's saving. A final 1/2-sample packet can add one more header. Add the two-byte row length
 * table for each of four channels.
 */
export const getPsdRleBound = (width: number, height: number): number =>
  4 * height * (width + Math.ceil(width / 128) + 3);

export const getPsdSerializationBudget = (plan: Extract<PsdExportPlan, { status: 'ok' }>) => {
  const compositeArea = plan.width * plan.height;
  const layerArea = plan.layers.reduce((sum, layer) => sum + layer.worldRect.width * layer.worldRect.height, 0);
  let encodedLayers = 0;
  let metadata = 4096;
  const visit = (nodes: readonly PsdPlanNode[]): void => {
    for (const node of nodes) {
      metadata += (node.kind === 'folder' ? 2 : 1) * (1024 + 6 * node.name.length);
      if (node.kind === 'folder') {
        visit(node.children);
      } else {
        encodedLayers += getPsdRleBound(node.worldRect.width, node.worldRect.height);
      }
    }
  };
  visit(plan.tree);
  const encodedComposite = getPsdRleBound(plan.width, plan.height);
  const outputBound = metadata + encodedLayers + encodedComposite;
  // Retain every geometric growth allocation (<4B), plus writePsd's exact slice (B): no GC assumption.
  const workerBytes =
    4 * (layerArea + compositeArea) +
    encodedLayers +
    encodedComposite +
    12 * compositeArea +
    2 * plan.height +
    5 * outputBound;
  // Worker terminates before download; exact bytes + Blob can overlap without any writer heap.
  return { outputBound, requiredBytes: Math.max(workerBytes, 2 * outputBound) };
};

/** Owns immutable PSD snapshot capture, budget reservation, execution, and cancellation. */
export class PsdExportController {
  private disposed = false;
  private active: AbortController | null = null;
  private status: PsdExportStatus = 'idle';

  private setStatus(status: PsdExportStatus): void {
    this.status = status;
    this.deps.onStatus?.(status);
  }

  constructor(private readonly deps: PsdExportControllerOptions) {}

  async export(fileName: string): Promise<PsdExportResult> {
    if (this.disposed) {
      return 'aborted';
    }
    if (this.active) {
      return 'busy';
    }
    const abortController = new AbortController();
    this.active = abortController;
    this.setStatus('preparing');
    try {
      const documentSnapshot = this.deps.captureDocumentSnapshot();
      if (!documentSnapshot) {
        return 'nothing';
      }
      if (!this.deps.isDocumentSnapshotCurrent(documentSnapshot)) {
        return 'stale';
      }
      const document = documentSnapshot.canvas.document;
      const leaves = compileDocumentLeaves(document).filter((leaf) => isExportableRasterLayer(leaf.layer));
      const layers = leaves.map((leaf) => leaf.layer);
      if (layers.length === 0) {
        return 'nothing';
      }
      const capture = await this.deps.captureRasterSnapshot(
        documentSnapshot,
        layers.map((layer) => layer.id),
        { includeDisabled: true, signal: abortController.signal }
      );
      if (capture.status === 'unreadable') {
        return capture;
      }
      if (capture.status !== 'ok') {
        return capture.status;
      }
      const rasterSnapshot = capture.snapshot;
      let snapshotReleased = false;
      const releaseSnapshot = (): void => {
        if (!snapshotReleased) {
          snapshotReleased = true;
          rasterSnapshot.release();
        }
      };
      try {
        if (abortController.signal.aborted) {
          return 'aborted';
        }
        if (!this.deps.isDocumentSnapshotCurrent(documentSnapshot)) {
          return 'stale';
        }
        // Omit uncaptured leaves; derive effective visibility from own flags as Photoshop does.
        let missing: string | null = null;
        // PSD cannot represent a group stack: bake enclosing stacks into each leaf (own first, then innermost outward).
        // Approximate under member opacity/blending, and for spatial entries (clarity, texture, dehaze), which see the
        // leaf's pixels alone rather than the group composite; the merged preview flattens the same baked pixels.
        const toInputs = (
          nodes: readonly CanvasNodeContract[],
          ancestorStacks: readonly PsdGroupStack[] = []
        ): PsdExportNodeInput[] =>
          nodes.flatMap((node): PsdExportNodeInput[] => {
            if (isGroupNode(node)) {
              const stacks = isIdentityAdjustments(node.adjustments)
                ? ancestorStacks
                : [...ancestorStacks, { adjustments: node.adjustments!, id: node.id }];
              return [
                {
                  blendMode: node.blendMode,
                  children: toInputs(node.children, stacks),
                  colorLabel: node.colorLabel,
                  id: node.id,
                  isEnabled: node.isEnabled,
                  name: node.name,
                  opacity: node.opacity,
                  type: 'group',
                },
              ];
            }
            if (!isExportableRasterLayer(node)) {
              return [];
            }
            const detached = rasterSnapshot.layerSurfaces.get(node.id);
            if (!detached) {
              if (!rasterSnapshot.emptyLayerIds.has(node.id)) {
                missing ??= node.id;
              }
              return [];
            }
            const own = node.type === 'raster' ? node.adjustments : undefined;
            return [
              {
                // Identity-aware: an emptied stack must not trigger the executor's bake writeback.
                adjustments: isIdentityAdjustments(own) ? undefined : own,
                groupStacks: ancestorStacks.length > 0 ? [...ancestorStacks].reverse() : undefined,
                blendMode: node.blendMode,
                colorLabel: node.colorLabel,
                contentRect: detached.rect,
                id: node.id,
                isEnabled: node.isEnabled,
                name: node.name,
                opacity: node.opacity,
                transform: node.transform,
              },
            ];
          });
        const inputs = toInputs(document.stacks.raster);
        if (missing !== null) {
          return 'not-ready';
        }
        const plan = planPsdExport(inputs);
        if (plan.status === 'empty') {
          return 'nothing';
        }
        if (plan.status === 'too-large') {
          return 'too-large';
        }
        if (getPsdSerializationBudget(plan).requiredBytes > PSD_SERIALIZATION_ALLOWANCE_BYTES) {
          return 'too-large';
        }
        const requestedBytes = getPsdRequiredBytes(plan);
        if (requestedBytes > this.deps.getAvailableBytes()) {
          return 'over-budget';
        }
        const reservation = this.deps.reserve(requestedBytes);
        if (reservation.status === 'over-budget') {
          return 'over-budget';
        }
        let reservationReleased = false;
        const releasePreparation = (): void => {
          if (!reservationReleased) {
            reservationReleased = true;
            reservation.lease.release();
            releaseSnapshot();
          }
        };
        try {
          const getLayerSurface = (layerId: string): Promise<CanvasDetachedLayerSurface> => {
            const detached = rasterSnapshot.layerSurfaces.get(layerId);
            if (!detached) {
              return Promise.reject(new Error(`PSD raster snapshot is missing layer ${layerId}.`));
            }
            return Promise.resolve(detached);
          };
          try {
            await (this.deps.execute ?? executePsdExport)(
              plan,
              /\.psd$/i.test(fileName) ? fileName : `${fileName}.psd`,
              {
                backend: this.deps.backend,
                onStage: (stage) => {
                  if (stage === 'serializing') {
                    releasePreparation();
                  }
                  this.setStatus(abortController.signal.aborted ? 'cancelling' : stage);
                },
                getLayerSurface,
                runSpatial: this.deps.runSpatial,
                signal: abortController.signal,
              }
            );
          } catch (error) {
            if (abortController.signal.aborted || (error instanceof DOMException && error.name === 'AbortError')) {
              return 'aborted';
            }
            if (error instanceof AdjustmentRefusedError) {
              return adjustmentRefusal(document, error.ownerId, error.reason);
            }
            throw error;
          }
          return 'exported';
        } finally {
          releasePreparation();
        }
      } finally {
        releaseSnapshot();
      }
    } finally {
      this.active = null;
      this.setStatus('idle');
    }
  }

  cancel(): void {
    if (this.active && this.status !== 'downloading') {
      this.setStatus('cancelling');
      this.active.abort();
    }
  }

  dispose(): void {
    if (this.disposed) {
      return;
    }
    this.disposed = true;
    this.cancel();
  }
}