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.

9.8 KB
Raw Blame
import type { CanvasKeyOwner, CanvasSurfaceAttachOptions } from '@workbench/canvas-engine/capabilities';
import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { RenderScheduler, RenderSchedulerDeps } from '@workbench/canvas-engine/render/scheduler';

import { createRenderScheduler } from '@workbench/canvas-engine/render/scheduler';

import type { RasterMemoryBudgetController, RasterMemoryLease } from './rasterMemoryBudgetController';

import { PreviewStateController } from './previewStateController';

const wrapCanvasSurface = (canvas: HTMLCanvasElement): RasterSurface => {
  const ctx = canvas.getContext('2d');
  if (!ctx) {
    throw new Error('Failed to acquire a 2D context from the canvas element');
  }
  return {
    canvas,
    ctx,
    get height() {
      return canvas.height;
    },
    resize(width: number, height: number) {
      canvas.width = width;
      canvas.height = height;
    },
    // The mounted canvas element must retain identity, so growth copies through a temporary surface instead of swapping
    // backing stores. Only layer caches currently grow.
    resizePreserving(width: number, height: number, dx: number, dy: number) {
      const previous = document.createElement('canvas');
      previous.width = canvas.width;
      previous.height = canvas.height;
      previous.getContext('2d')?.drawImage(canvas, 0, 0);
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(previous, dx, dy);
    },
    get width() {
      return canvas.width;
    },
  };
};

export interface RenderControllerOptions extends RenderSchedulerDeps {
  readonly backend: Pick<RasterBackend, 'createSurface'>;
  readonly rasterMemory: Pick<RasterMemoryBudgetController, 'trackDetached'>;
  readonly isEngineDisposed: () => boolean;
  readonly getInputHandlers: () => {
    onPointerDown: (event: PointerEvent) => void;
    onPointerMove: (event: PointerEvent) => void;
    onPointerUp: (event: PointerEvent) => void;
    onPointerCancel: (event: PointerEvent) => void;
    onPointerEnter: (event: PointerEvent) => void;
    onPointerLeave: (event: PointerEvent) => void;
    onKeyDown: (event: KeyboardEvent) => void;
    onKeyUp: (event: KeyboardEvent) => void;
    /** Both key events in the capture phase, so no handler that stops propagation hides them. */
    onKeyCapture: (event: KeyboardEvent) => void;
    onFocusIn: (event: FocusEvent) => void;
    onWindowFocus: () => void;
    onWheel: (event: WheelEvent) => void;
    onPinchGestureStart: (event: Event) => void;
    onPinchGestureChange: (event: Event) => void;
    reset(): void;
  };
  readonly onPageHide: () => void;
  readonly onWindowBlur: () => void;
  readonly onVisibilityChange: () => void;
  readonly applyCursor: (value: string) => void;
  readonly updateCursor: () => void;
  readonly updateAnimation: () => void;
  readonly setViewportReady: (ready: boolean) => void;
}

/** Owns render targets, scheduling, DOM input bindings, and attach/detach lifecycle. */
export class RenderController {
  readonly scheduler: RenderScheduler;
  readonly previews = new PreviewStateController();
  private screen: RasterSurface | null = null;
  private maskScratch: { surface: RasterSurface; lease: RasterMemoryLease } | null = null;
  private overlay: RasterSurface | null = null;
  private input: HTMLCanvasElement | null = null;
  private keyboardRoot: HTMLElement | null = null;
  private resolveKeyOwner: ((event: KeyboardEvent) => CanvasKeyOwner) | null = null;
  private disposed = false;

  constructor(private readonly options: RenderControllerOptions) {
    this.scheduler = createRenderScheduler(options);
  }

  getScreen(): RasterSurface | null {
    return this.screen;
  }

  readonly getMaskScratch = (width: number, height: number): RasterSurface => {
    const current = this.maskScratch;
    if (current) {
      this.resizeMaskScratch(Math.max(current.surface.width, width), Math.max(current.surface.height, height));
      return current.surface;
    }
    const surface = this.options.backend.createSurface(width, height);
    this.maskScratch = { surface, lease: this.options.rasterMemory.trackDetached(width * height * 4) };
    return surface;
  };

  private resizeMaskScratch(width: number, height: number): void {
    const current = this.maskScratch;
    if (!current || (current.surface.width === width && current.surface.height === height)) {
      return;
    }
    current.surface.resize(width, height);
    current.lease.release();
    current.lease = this.options.rasterMemory.trackDetached(width * height * 4);
  }

  releaseMaskScratch(): void {
    const current = this.maskScratch;
    if (current) {
      current.surface.resize(0, 0);
      current.lease.release();
      this.maskScratch = null;
    }
  }

  getOverlay(): RasterSurface | null {
    return this.overlay;
  }

  getInputElement(): HTMLCanvasElement | null {
    return this.input;
  }

  getKeyboardRoot(): HTMLElement | null {
    return this.keyboardRoot;
  }

  /** The host's key-owner judge from the current attach; null when detached or none was given. */
  getKeyOwnerResolver(): ((event: KeyboardEvent) => CanvasKeyOwner) | null {
    return this.resolveKeyOwner;
  }

  attach(
    screenCanvas: HTMLCanvasElement,
    overlayCanvas: HTMLCanvasElement,
    keyboardRoot?: HTMLElement,
    options?: CanvasSurfaceAttachOptions
  ): void {
    if (this.disposed || this.options.isEngineDisposed()) {
      return;
    }
    if (this.input) {
      this.detach();
    }
    this.screen = wrapCanvasSurface(screenCanvas);
    this.overlay = wrapCanvasSurface(overlayCanvas);
    this.input = overlayCanvas;
    this.keyboardRoot = keyboardRoot ?? overlayCanvas;
    this.resolveKeyOwner = options?.resolveKeyOwner ?? null;
    const handlers = this.options.getInputHandlers();
    this.input.addEventListener('pointerdown', handlers.onPointerDown);
    this.input.addEventListener('pointermove', handlers.onPointerMove);
    this.input.addEventListener('pointerup', handlers.onPointerUp);
    this.input.addEventListener('pointercancel', handlers.onPointerCancel);
    this.input.addEventListener('pointerenter', handlers.onPointerEnter);
    this.input.addEventListener('pointerleave', handlers.onPointerLeave);
    this.input.addEventListener('wheel', handlers.onWheel, { passive: false });
    this.input.addEventListener('gesturestart', handlers.onPinchGestureStart, { passive: false });
    this.input.addEventListener('gesturechange', handlers.onPinchGestureChange, { passive: false });
    if (typeof globalThis.addEventListener === 'function') {
      globalThis.addEventListener('keydown', handlers.onKeyDown);
      globalThis.addEventListener('keyup', handlers.onKeyUp);
      globalThis.addEventListener('keydown', handlers.onKeyCapture, true);
      globalThis.addEventListener('keyup', handlers.onKeyCapture, true);
      globalThis.addEventListener('focusin', handlers.onFocusIn);
      globalThis.addEventListener('focus', handlers.onWindowFocus);
      globalThis.addEventListener('pagehide', this.options.onPageHide);
      globalThis.addEventListener('blur', this.options.onWindowBlur);
    }
    if (typeof document !== 'undefined') {
      document.addEventListener('visibilitychange', this.options.onVisibilityChange);
    }
    this.scheduler.resume();
    this.options.setViewportReady(true);
    this.options.updateCursor();
    this.scheduler.invalidate({ all: true });
    this.options.updateAnimation();
  }

  detach(): void {
    const handlers = this.options.getInputHandlers();
    if (this.input) {
      this.input.removeEventListener('pointerdown', handlers.onPointerDown);
      this.input.removeEventListener('pointermove', handlers.onPointerMove);
      this.input.removeEventListener('pointerup', handlers.onPointerUp);
      this.input.removeEventListener('pointercancel', handlers.onPointerCancel);
      this.input.removeEventListener('pointerenter', handlers.onPointerEnter);
      this.input.removeEventListener('pointerleave', handlers.onPointerLeave);
      this.input.removeEventListener('wheel', handlers.onWheel);
      this.input.removeEventListener('gesturestart', handlers.onPinchGestureStart);
      this.input.removeEventListener('gesturechange', handlers.onPinchGestureChange);
      this.options.applyCursor('');
    }
    if (typeof globalThis.removeEventListener === 'function') {
      globalThis.removeEventListener('keydown', handlers.onKeyDown);
      globalThis.removeEventListener('keyup', handlers.onKeyUp);
      globalThis.removeEventListener('keydown', handlers.onKeyCapture, true);
      globalThis.removeEventListener('keyup', handlers.onKeyCapture, true);
      globalThis.removeEventListener('focusin', handlers.onFocusIn);
      globalThis.removeEventListener('focus', handlers.onWindowFocus);
      globalThis.removeEventListener('pagehide', this.options.onPageHide);
      globalThis.removeEventListener('blur', this.options.onWindowBlur);
    }
    if (typeof document !== 'undefined') {
      document.removeEventListener('visibilitychange', this.options.onVisibilityChange);
    }
    handlers.reset();
    this.scheduler.pause();
    this.options.setViewportReady(false);
    this.releaseMaskScratch();
    this.screen = null;
    this.overlay = null;
    this.input = null;
    this.keyboardRoot = null;
    this.resolveKeyOwner = null;
    this.options.updateAnimation();
  }

  resize(width: number, height: number): void {
    this.screen?.resize(width, height);
    this.overlay?.resize(width, height);
    if (this.maskScratch) {
      const { surface } = this.maskScratch;
      if (width === 0 || height === 0) {
        this.releaseMaskScratch();
      } else {
        this.resizeMaskScratch(Math.min(width, surface.width), Math.min(height, surface.height));
      }
    }
  }

  dispose(): void {
    if (this.disposed) {
      return;
    }
    this.detach();
    this.disposed = true;
    this.scheduler.dispose();
    this.previews.dispose();
  }
}