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.

32.0 KB
Raw Blame
import type { CanvasManager } from 'features/controlLayers/konva/CanvasManager';
import { CanvasModuleBase } from 'features/controlLayers/konva/CanvasModuleBase';
import type { AnyObjectState } from 'features/controlLayers/konva/CanvasObject/types';
import { CanvasBboxToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasBboxToolModule';
import { CanvasBrushToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasBrushToolModule';
import { CanvasColorPickerToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasColorPickerToolModule';
import { CanvasEraserToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasEraserToolModule';
import { CanvasGradientToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasGradientToolModule';
import { CanvasLassoToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasLassoToolModule';
import { CanvasMoveToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasMoveToolModule';
import { CanvasShapeToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasShapeToolModule';
import { CanvasTextToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasTextToolModule';
import { CanvasViewToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasViewToolModule';
import {
  type BboxToolHotkeyPressedState,
  beginBboxToolHotkeyPress,
  type CanvasToolHotkeyState,
  clearTemporaryToolHotkeysInState,
  endBboxToolHotkeyPress,
  getActiveToolFromState,
  getToolToCancelOnEscape,
  pressAltInState,
  pressSpaceInState,
  releaseAltInState,
  releaseSpaceInState,
  setBaseToolInState,
  shouldPreserveSuspendableShapesSession,
  shouldQuickSwitchToColorPickerOnAlt,
  shouldTranslateShapeDragOnSpace,
} from 'features/controlLayers/konva/CanvasTool/toolHotkeys';
import { ZOOM_DRAG_CURSOR } from 'features/controlLayers/konva/cursors/zoomDragCursor';
import {
  calculateNewBrushSizeFromWheelDelta,
  getIsPrimaryMouseDown,
  getPrefixedId,
} from 'features/controlLayers/konva/util';
import { selectCanvasSettingsSlice } from 'features/controlLayers/store/canvasSettingsSlice';
import { selectCanvasSlice } from 'features/controlLayers/store/selectors';
import type {
  CanvasControlLayerState,
  CanvasInpaintMaskState,
  CanvasRasterLayerState,
  CanvasRegionalGuidanceState,
  Coordinate,
  Tool,
} from 'features/controlLayers/store/types';
import Konva from 'konva';
import type { KonvaEventObject } from 'konva/lib/Node';
import { atom } from 'nanostores';
import type { Logger } from 'roarr';

// Konva's docs say the default drag buttons are [0], but it's actually [0,1]. We only want left-click to drag, so we
// need to override the default. The stage handles middle-mouse dragging on its own with dedicated event listeners.
// TODO(psyche): Fix the docs upstream!
Konva.dragButtons = [0];

// Typo insurance
const KEY_ESCAPE = 'Escape';
const KEY_SPACE = ' ';
const KEY_ALT = 'Alt';
const CODE_SPACE = 'Space';

type CanvasToolModuleConfig = {
  BRUSH_SPACING_TARGET_SCALE: number;
  PRESSURE_OPACITY_BRUSH_SPACING_TARGET_SCALE: number;
};

const DEFAULT_CONFIG: CanvasToolModuleConfig = {
  BRUSH_SPACING_TARGET_SCALE: 0.1,
  PRESSURE_OPACITY_BRUSH_SPACING_TARGET_SCALE: 0.05,
};

export class CanvasToolModule extends CanvasModuleBase {
  readonly type = 'tool';
  readonly id: string;
  readonly path: string[];
  readonly parent: CanvasManager;
  readonly manager: CanvasManager;
  readonly log: Logger;
  subscriptions: Set<() => void> = new Set();

  config: CanvasToolModuleConfig = DEFAULT_CONFIG;

  tools: {
    brush: CanvasBrushToolModule;
    eraser: CanvasEraserToolModule;
    rect: CanvasShapeToolModule;
    lasso: CanvasLassoToolModule;
    gradient: CanvasGradientToolModule;
    colorPicker: CanvasColorPickerToolModule;
    bbox: CanvasBboxToolModule;
    view: CanvasViewToolModule;
    move: CanvasMoveToolModule;
    text: CanvasTextToolModule;
  };

  /**
   * The currently active tool, including temporary overrides like Space, Alt, and bbox hold.
   */
  $tool = atom<Tool>('move');
  /**
   * The user's persistent tool selection. Temporary overrides resolve on top of this.
   */
  $baseTool = atom<Tool>('move');
  $isSpacePressed = atom<boolean>(false);
  $isAltPressed = atom<boolean>(false);
  $bboxToolHotkeyPressedState = atom<BboxToolHotkeyPressedState | null>(null);
  /**
   * Whether the primary pointer (left mouse, pen, first touch) is currently down on the stage.
   *
   * This is set true when the pointer down is fired on the stage and false when the pointer up is fired anywhere,
   * including outside of the stage. This flag is thus true when the user is actively drawing on the stage.
   *
   * For example, if the pointer down was fired on the stage and the cursor then leaves the stage without a pointer up
   * event, this will still be true. If the cursor then moves back onto the stage, this will still be true.
   *
   * However, if the pointer down was initially fired _outside_ the stage, and the cursor moves onto the stage, this
   * will be false.
   */
  $isPrimaryPointerDown = atom<boolean>(false);
  /**
   * The last cursor position.
   */
  $cursorPos = atom<{ relative: Coordinate; absolute: Coordinate } | null>(null);
  /**
   * The last pointer type that was used on the stage. This is used to determine if we should show a tool preview. For
   * example, when using a pen, we should not show a brush preview.
   */
  $lastPointerType = atom<string | null>(null);

  konva: {
    stage: Konva.Stage;
    group: Konva.Group;
  };

  constructor(manager: CanvasManager) {
    super();
    this.id = getPrefixedId(this.type);
    this.parent = manager;
    this.manager = manager;
    this.path = this.manager.buildPath(this);
    this.log = this.manager.buildLogger(this);

    this.log.debug('Creating tool module');

    this.tools = {
      brush: new CanvasBrushToolModule(this),
      eraser: new CanvasEraserToolModule(this),
      rect: new CanvasShapeToolModule(this),
      lasso: new CanvasLassoToolModule(this),
      gradient: new CanvasGradientToolModule(this),
      colorPicker: new CanvasColorPickerToolModule(this),
      bbox: new CanvasBboxToolModule(this),
      text: new CanvasTextToolModule(this),
      view: new CanvasViewToolModule(this),
      move: new CanvasMoveToolModule(this),
    };

    this.konva = {
      stage: this.manager.stage.konva.stage,
      group: new Konva.Group({ name: `${this.type}:group`, listening: true }),
    };

    this.konva.group.add(this.tools.brush.konva.group);
    this.konva.group.add(this.tools.eraser.konva.group);
    this.konva.group.add(this.tools.rect.konva.group);
    this.konva.group.add(this.tools.colorPicker.konva.group);
    this.konva.group.add(this.tools.text.konva.group);
    this.konva.group.add(this.tools.bbox.konva.group);
    this.konva.group.add(this.tools.lasso.konva.group);

    this.subscriptions.add(this.manager.stage.$stageAttrs.listen(this.render));
    this.subscriptions.add(this.manager.$isBusy.listen(this.render));
    this.subscriptions.add(this.manager.stateApi.createStoreSubscription(selectCanvasSettingsSlice, this.render));
    this.subscriptions.add(this.manager.stateApi.createStoreSubscription(selectCanvasSlice, this.render));
    this.subscriptions.add(
      this.$tool.listen((tool, previousTool) => {
        // Preserve pointer state across temporary hotkey overrides so lasso and suspendable shape sessions can
        // freeze/resume cleanly when Space/Alt are pressed and released.
        const shouldPreserveLassoPointerState =
          this.$baseTool.get() === 'lasso' &&
          this.tools.lasso.hasActiveSession() &&
          (previousTool === 'lasso' || previousTool === 'view') &&
          (tool === 'lasso' || tool === 'view');
        const shouldPreserveShapesPointerState =
          this.$baseTool.get() === 'rect' &&
          this.tools.rect.hasSuspendableSession() &&
          (previousTool === 'rect' || previousTool === 'view' || previousTool === 'colorPicker') &&
          (tool === 'rect' || tool === 'view' || tool === 'colorPicker');
        const shouldPreservePointerState = shouldPreserveLassoPointerState || shouldPreserveShapesPointerState;

        if (!shouldPreservePointerState) {
          // On tool switch, reset mouse state
          this.manager.tool.$isPrimaryPointerDown.set(false);
        }

        this.tools.rect.onToolChanged();
        this.tools.lasso.onToolChanged();
        void this.tools.text.onToolChanged();
        this.render();
      })
    );

    const cleanupListeners = this.setEventListeners();

    this.subscriptions.add(cleanupListeners);
  }

  initialize = () => {
    this.log.debug('Initializing module');
    this.render();
    this.syncCursorStyle();
  };

  getToolHotkeyState = (): CanvasToolHotkeyState => {
    return {
      baseTool: this.$baseTool.get(),
      isSpacePressed: this.$isSpacePressed.get(),
      isAltPressed: this.$isAltPressed.get(),
      bboxToolHotkeyPressedState: this.$bboxToolHotkeyPressedState.get(),
    };
  };

  applyToolHotkeyState = (state: CanvasToolHotkeyState) => {
    const previousActiveTool = this.$tool.get();

    this.$baseTool.set(state.baseTool);
    this.$isSpacePressed.set(state.isSpacePressed);
    this.manager.stateApi.$spaceKey.set(state.isSpacePressed);
    this.$isAltPressed.set(state.isAltPressed);
    if (this.$bboxToolHotkeyPressedState.get() !== state.bboxToolHotkeyPressedState) {
      this.$bboxToolHotkeyPressedState.set(state.bboxToolHotkeyPressedState);
    }

    const nextActiveTool = getActiveToolFromState(state);
    if (previousActiveTool !== nextActiveTool) {
      this.$tool.set(nextActiveTool);
    }
  };

  setBaseTool = (tool: Tool) => {
    this.applyToolHotkeyState(setBaseToolInState(this.getToolHotkeyState(), tool));
  };

  pressSpaceKey = () => {
    this.applyToolHotkeyState(pressSpaceInState(this.getToolHotkeyState()));
  };

  releaseSpaceKey = () => {
    this.applyToolHotkeyState(releaseSpaceInState(this.getToolHotkeyState()));
  };

  pressAltKey = () => {
    this.applyToolHotkeyState(pressAltInState(this.getToolHotkeyState()));
  };

  releaseAltKey = () => {
    this.applyToolHotkeyState(releaseAltInState(this.getToolHotkeyState()));
  };

  getHotkeyBindingId = (event: KeyboardEvent) => {
    return event.code || event.key.toLowerCase();
  };

  onBboxToolHotkeyDown = (event: KeyboardEvent) => {
    this.applyToolHotkeyState(
      beginBboxToolHotkeyPress(this.getToolHotkeyState(), {
        bindingId: this.getHotkeyBindingId(event),
        pressedAt: Date.now(),
      })
    );
  };

  onBboxToolHotkeyUp = (event: KeyboardEvent) => {
    this.applyToolHotkeyState(
      endBboxToolHotkeyPress({
        state: this.getToolHotkeyState(),
        bindingId: this.getHotkeyBindingId(event),
        releasedAt: Date.now(),
      })
    );
  };

  clearBboxToolHotkey = () => {
    const state = this.getToolHotkeyState();
    if (!state.bboxToolHotkeyPressedState) {
      return;
    }
    this.applyToolHotkeyState({
      ...state,
      bboxToolHotkeyPressedState: null,
    });
  };

  clearTemporaryToolHotkeys = () => {
    this.applyToolHotkeyState(clearTemporaryToolHotkeysInState(this.getToolHotkeyState()));
  };

  syncCursorStyle = () => {
    const stage = this.manager.stage;
    const tool = this.$tool.get();
    const segmentingAdapter = this.manager.stateApi.$segmentingAdapter.get();
    const transformingAdapter = this.manager.stateApi.$transformingAdapter.get();
    const selectedEntityAdapter = this.manager.stateApi.getSelectedEntityAdapter();

    if (this.manager.stage.getIsZoomDragging()) {
      stage.setCursor(ZOOM_DRAG_CURSOR);
    } else if (this.manager.stage.getIsDragging()) {
      stage.setCursor('grabbing');
    } else if (tool === 'view') {
      this.tools.view.syncCursorStyle();
    } else if (segmentingAdapter) {
      segmentingAdapter.segmentAnything.syncCursorStyle();
    } else if (transformingAdapter) {
      transformingAdapter.transformer.syncCursorStyle();
    } else if (this.manager.stateApi.$isFiltering.get()) {
      stage.setCursor('not-allowed');
    } else if (this.manager.stagingArea.$isStaging.get()) {
      stage.setCursor('not-allowed');
    } else if (tool === 'bbox') {
      this.tools.bbox.syncCursorStyle();
    } else if (tool === 'colorPicker') {
      this.tools.colorPicker.syncCursorStyle();
    } else if (tool === 'text') {
      this.tools.text.syncCursorStyle();
    } else if (tool === 'lasso') {
      this.tools.lasso.syncCursorStyle();
    } else if (selectedEntityAdapter) {
      if (selectedEntityAdapter.$isDisabled.get()) {
        stage.setCursor('not-allowed');
      } else if (selectedEntityAdapter.$isEntityTypeHidden.get()) {
        stage.setCursor('not-allowed');
      } else if (selectedEntityAdapter.$isLocked.get()) {
        stage.setCursor('not-allowed');
      } else if (tool === 'brush') {
        this.tools.brush.syncCursorStyle();
      } else if (tool === 'eraser') {
        this.tools.eraser.syncCursorStyle();
      } else if (tool === 'move') {
        this.tools.move.syncCursorStyle();
      } else if (tool === 'rect') {
        this.tools.rect.syncCursorStyle();
      } else if (tool === 'gradient') {
        this.tools.gradient.syncCursorStyle();
      }
    } else if (this.manager.stateApi.getRenderedEntityCount() === 0) {
      stage.setCursor('not-allowed');
    } else {
      stage.setCursor('not-allowed');
    }
  };

  render = () => {
    this.syncCursorStyle();

    this.tools.brush.render();
    this.tools.eraser.render();
    this.tools.rect.render();
    this.tools.colorPicker.render();
    this.tools.text.render();
    this.tools.bbox.render();
    this.tools.lasso.render();
  };

  syncCursorPositions = () => {
    const relative = this.konva.stage.getRelativePointerPosition();
    const absolute = this.konva.stage.getPointerPosition();

    if (!relative || !absolute) {
      return;
    }

    this.$cursorPos.set({ relative, absolute });
  };

  syncCursorPositionsFromWindowEvent = (e: PointerEvent): boolean => {
    this.konva.stage.setPointersPositions(e);
    const relative = this.konva.stage.getRelativePointerPosition();
    const absolute = this.konva.stage.getPointerPosition();

    if (!relative || !absolute) {
      return false;
    }

    this.$cursorPos.set({ relative, absolute });
    return true;
  };

  getClip = (
    entity: CanvasRegionalGuidanceState | CanvasControlLayerState | CanvasRasterLayerState | CanvasInpaintMaskState
  ) => {
    const settings = this.manager.stateApi.getSettings();

    if (settings.clipToBbox) {
      const { x, y, width, height } = this.manager.stateApi.getBbox().rect;
      return {
        x: x - entity.position.x,
        y: y - entity.position.y,
        width,
        height,
      };
    } else {
      const { x, y } = this.manager.stage.getPosition();
      const scale = this.manager.stage.getScale();
      const { width, height } = this.manager.stage.getSize();
      return {
        x: -x / scale - entity.position.x,
        y: -y / scale - entity.position.y,
        width: width / scale,
        height: height / scale,
      };
    }
  };

  setEventListeners = (): (() => void) => {
    this.konva.stage.on('pointerenter', this.onStagePointerEnter);
    this.konva.stage.on('pointerdown', this.onStagePointerDown);
    this.konva.stage.on('pointerup', this.onStagePointerUp);
    this.konva.stage.on('pointermove', this.onStagePointerMove);

    // The Konva stage doesn't appear to handle pointerleave events, so we need to listen to the container instead
    this.manager.stage.container.addEventListener('pointerleave', this.onStagePointerLeave);

    this.konva.stage.on('wheel', this.onStageMouseWheel);

    window.addEventListener('keydown', this.onKeyDown);
    window.addEventListener('keyup', this.onKeyUp);
    window.addEventListener('pointermove', this.onWindowPointerMove);
    window.addEventListener('pointerup', this.onWindowPointerUp);
    window.addEventListener('blur', this.onWindowBlur);

    return () => {
      this.konva.stage.off('pointerenter', this.onStagePointerEnter);
      this.konva.stage.off('pointerdown', this.onStagePointerDown);
      this.konva.stage.off('pointerup', this.onStagePointerUp);
      this.konva.stage.off('pointermove', this.onStagePointerMove);

      this.manager.stage.container.removeEventListener('pointerleave', this.onStagePointerLeave);

      this.konva.stage.off('wheel', this.onStageMouseWheel);

      window.removeEventListener('keydown', this.onKeyDown);
      window.removeEventListener('keyup', this.onKeyUp);
      window.removeEventListener('pointermove', this.onWindowPointerMove);
      window.removeEventListener('pointerup', this.onWindowPointerUp);
      window.removeEventListener('blur', this.onWindowBlur);
    };
  };

  /**
   * Gets whether the user is allowed to draw on the canvas.
   * - There must be at least one entity rendered on the canvas.
   * - The canvas must not be busy (e.g. transforming, filtering, rasterizing, staging, compositing, segment-anything-ing).
   * - There must be a selected entity.
   * - The selected entity must be interactable (e.g. not hidden, disabled or locked).
   * @returns Whether the user is allowed to draw on the canvas.
   */
  getCanDraw = (): boolean => {
    const tool = this.$tool.get();
    if (tool === 'text') {
      if (this.manager.$isBusy.get()) {
        return false;
      }

      if (this.manager.stage.getIsDragging()) {
        return false;
      }

      return true;
    }

    if (tool === 'lasso') {
      if (this.manager.$isBusy.get()) {
        return false;
      }

      if (this.manager.stage.getIsDragging()) {
        return false;
      }

      return true;
    }

    if (this.manager.stateApi.getRenderedEntityCount() === 0) {
      return false;
    }

    if (this.manager.$isBusy.get()) {
      return false;
    }

    if (this.manager.stage.getIsDragging()) {
      return false;
    }

    const selectedEntity = this.manager.stateApi.getSelectedEntityAdapter();

    if (!selectedEntity) {
      return false;
    }

    if (selectedEntity.$isDisabled.get()) {
      return false;
    }

    if (selectedEntity.$isEntityTypeHidden.get()) {
      return false;
    }

    if (selectedEntity.$isLocked.get()) {
      return false;
    }

    return true;
  };

  onStagePointerEnter = async (e: KonvaEventObject<PointerEvent>) => {
    try {
      this.$lastPointerType.set(e.evt.pointerType);

      if (!this.getCanDraw()) {
        return;
      }

      this.syncCursorPositions();

      const tool = this.$tool.get();
      const selectedEntity = this.manager.stateApi.getSelectedEntityAdapter();

      if (
        selectedEntity?.bufferRenderer.hasBuffer() &&
        !this.shouldDeferEnterLeaveCommit(selectedEntity.bufferRenderer.state)
      ) {
        selectedEntity.bufferRenderer.commitBuffer();
        return;
      }

      if (tool === 'brush') {
        await this.tools.brush.onStagePointerEnter(e);
      } else if (tool === 'eraser') {
        await this.tools.eraser.onStagePointerEnter(e);
      } else if (tool === 'text') {
        await this.tools.text.onStagePointerEnter(e);
      }
    } finally {
      this.render();
    }
  };

  onStagePointerDown = async (e: KonvaEventObject<PointerEvent>) => {
    if (e.target !== this.konva.stage) {
      return;
    }

    try {
      this.$lastPointerType.set(e.evt.pointerType);

      if (!this.getCanDraw()) {
        return;
      }

      this.$isPrimaryPointerDown.set(getIsPrimaryMouseDown(e));

      this.syncCursorPositions();

      const tool = this.$tool.get();

      if (tool === 'brush') {
        await this.tools.brush.onStagePointerDown(e);
      } else if (tool === 'eraser') {
        await this.tools.eraser.onStagePointerDown(e);
      } else if (tool === 'rect') {
        await this.tools.rect.onStagePointerDown(e);
      } else if (tool === 'lasso') {
        await this.tools.lasso.onStagePointerDown(e);
      } else if (tool === 'gradient') {
        await this.tools.gradient.onStagePointerDown(e);
      } else if (tool === 'text') {
        await this.tools.text.onStagePointerDown(e);
      }
    } finally {
      this.render();
    }
  };

  onStagePointerUp = async (e: KonvaEventObject<PointerEvent>) => {
    if (e.target !== this.konva.stage) {
      return;
    }

    try {
      this.$lastPointerType.set(e.evt.pointerType);

      const tool = this.$tool.get();

      if (tool === 'colorPicker') {
        this.tools.colorPicker.onStagePointerUp(e);
      }

      if (!this.getCanDraw()) {
        return;
      }

      if (tool === 'brush') {
        this.tools.brush.onStagePointerUp(e);
      } else if (tool === 'eraser') {
        this.tools.eraser.onStagePointerUp(e);
      } else if (tool === 'rect') {
        await this.tools.rect.onStagePointerUp(e);
      } else if (tool === 'lasso') {
        void this.tools.lasso.onStagePointerUp(e);
      } else if (tool === 'gradient') {
        this.tools.gradient.onStagePointerUp(e);
      }
    } finally {
      this.render();
    }
  };

  onStagePointerMove = async (e: KonvaEventObject<PointerEvent>) => {
    if (e.target !== this.konva.stage) {
      return;
    }

    try {
      this.$lastPointerType.set(e.evt.pointerType);
      this.syncCursorPositions();

      const tool = this.$tool.get();

      if (tool === 'colorPicker') {
        this.tools.colorPicker.onStagePointerMove(e);
      } else if (tool === 'text') {
        this.tools.text.onStagePointerMove(e);
      }

      if (!this.getCanDraw()) {
        return;
      }

      if (tool === 'brush') {
        await this.tools.brush.onStagePointerMove(e);
      } else if (tool === 'eraser') {
        await this.tools.eraser.onStagePointerMove(e);
      } else if (tool === 'rect') {
        await this.tools.rect.onStagePointerMove(e);
      } else if (tool === 'lasso') {
        await this.tools.lasso.onStagePointerMove(e);
      } else if (tool === 'gradient') {
        await this.tools.gradient.onStagePointerMove(e);
      } else if (tool === 'text') {
        // Already handled above
      } else if (this.isTemporaryShapesToolSwitch()) {
        // Preserve in-progress polygon/freehand shapes while temporarily switching to view or color picker.
      } else {
        this.manager.stateApi.getSelectedEntityAdapter()?.bufferRenderer.clearBuffer();
      }
    } finally {
      this.render();
    }
  };

  onStagePointerLeave = (e: PointerEvent) => {
    if (e.target !== this.manager.stage.container) {
      return;
    }

    try {
      this.$lastPointerType.set(e.pointerType);
      this.$cursorPos.set(null);

      if (!this.getCanDraw()) {
        return;
      }

      const selectedEntity = this.manager.stateApi.getSelectedEntityAdapter();

      if (
        selectedEntity &&
        selectedEntity.bufferRenderer.hasBuffer() &&
        !this.shouldDeferEnterLeaveCommit(selectedEntity.bufferRenderer.state)
      ) {
        selectedEntity.bufferRenderer.commitBuffer();
      }
    } finally {
      this.render();
    }
  };

  onStageMouseWheel = (e: KonvaEventObject<WheelEvent>) => {
    if (e.target !== this.konva.stage) {
      return;
    }

    if (!this.getCanDraw()) {
      return;
    }

    e.evt.preventDefault();

    if (!e.evt.ctrlKey && !e.evt.metaKey) {
      return;
    }

    const settings = this.manager.stateApi.getSettings();
    const tool = this.$tool.get();

    let delta = e.evt.deltaY;

    if (settings.invertScrollForToolWidth) {
      delta = -delta;
    }

    // Holding ctrl or meta while scrolling changes the brush size
    if (tool === 'brush') {
      this.manager.stateApi.setBrushWidth(calculateNewBrushSizeFromWheelDelta(settings.brushWidth, delta));
    } else if (tool === 'eraser') {
      this.manager.stateApi.setEraserWidth(calculateNewBrushSizeFromWheelDelta(settings.eraserWidth, delta));
    }

    this.render();
  };

  onWindowPointerUp = async (_: PointerEvent) => {
    try {
      this.$isPrimaryPointerDown.set(false);
      void this.tools.lasso.onWindowPointerUp();
      await this.tools.rect.onWindowPointerUp();
      const selectedEntity = this.manager.stateApi.getSelectedEntityAdapter();

      if (
        selectedEntity &&
        selectedEntity.bufferRenderer.hasBuffer() &&
        !this.manager.$isBusy.get() &&
        !this.shouldSkipWindowPointerUpCommit(selectedEntity.bufferRenderer.state)
      ) {
        selectedEntity.bufferRenderer.commitBuffer();
      }
    } finally {
      this.render();
    }
  };

  onWindowPointerMove = async (e: PointerEvent) => {
    const target = e.target;
    if (target instanceof Node && this.manager.stage.container.contains(target)) {
      return;
    }

    try {
      this.$lastPointerType.set(e.pointerType);

      if (!this.getCanDraw()) {
        return;
      }

      if (!this.$isPrimaryPointerDown.get()) {
        return;
      }

      if (!this.syncCursorPositionsFromWindowEvent(e)) {
        return;
      }

      if (this.$tool.get() === 'rect') {
        if (!this.tools.rect.hasActiveDragSession()) {
          return;
        }
        await this.tools.rect.onWindowPointerMove();
      } else if (this.$tool.get() === 'lasso') {
        if (!this.tools.lasso.hasActiveSession()) {
          return;
        }
        this.tools.lasso.onWindowPointerMove(e);
      }
    } finally {
      this.render();
    }
  };

  /**
   * We want to reset any "quick-switch" tool selection on window blur. Fixes an issue where you alt-tab out of the app
   * and the color picker tool is still active when you come back.
   *
   * Bbox hold is also a temporary override, but unlike view/color-picker it may have an active Konva drag/transform in
   * flight. Stop that interaction before clearing temporary hotkeys so the bbox cannot get stuck half-active after
   * focus returns.
   */
  onWindowBlur = () => {
    this.tools.bbox.stopInteraction();
    this.clearTemporaryToolHotkeys();
    this.manager.stateApi.$spaceKey.set(false);
    this.tools.rect.stopDragTranslation();
  };

  onKeyDown = (e: KeyboardEvent) => {
    const isSpaceKey = e.key === KEY_SPACE || e.code === CODE_SPACE;
    if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
      return;
    }
    // Suppress canvas key handlers while an uncommitted text session is active.
    const hasActiveTextSession = this.tools.text.$session.get() !== null;
    if (hasActiveTextSession) {
      return;
    }

    // Handle nudging - must be before repeat, as we may want to catch repeating keys
    if (this.tools.move.isNudgeKey(e.key)) {
      this.tools.move.nudge(e.key);
    }

    if (e.repeat) {
      return;
    }

    if (e.key === KEY_ESCAPE) {
      // Cancel shape drawing on escape
      e.preventDefault();
      const tool = this.$tool.get();
      const toolToCancel = getToolToCancelOnEscape(
        tool,
        this.$baseTool.get(),
        this.tools.lasso.hasActiveSession(),
        this.tools.rect.hasSuspendableSession()
      );

      this.manager.stateApi.$spaceKey.set(false);
      this.tools.rect.stopDragTranslation();
      if (toolToCancel === 'rect') {
        this.tools.rect.cancel();
      }
      if (toolToCancel === 'lasso') {
        this.tools.lasso.reset();
      }
      if (toolToCancel && tool !== toolToCancel) {
        this.clearTemporaryToolHotkeys();
      }
      const selectedEntity = this.manager.stateApi.getSelectedEntityAdapter();
      if (
        selectedEntity &&
        !selectedEntity.filterer?.$isFiltering.get() &&
        !selectedEntity.transformer.$isTransforming.get() &&
        selectedEntity.bufferRenderer.hasBuffer()
      ) {
        selectedEntity.bufferRenderer.clearBuffer();
      }
      return;
    }

    if (isSpaceKey) {
      e.preventDefault();
      e.stopPropagation();
      const currentTool = this.$tool.get();
      const shapeType = this.manager.stateApi.getSettings().shapeType;
      const hasActiveShapeDragSession = this.tools.rect.hasActiveDragSession();
      const isPrimaryPointerDown = this.$isPrimaryPointerDown.get();

      if (shouldTranslateShapeDragOnSpace(currentTool, shapeType, hasActiveShapeDragSession, isPrimaryPointerDown)) {
        this.manager.stateApi.$spaceKey.set(true);
        this.tools.rect.startDragTranslation();
        return;
      }

      if (currentTool === 'rect' && this.tools.rect.hasActivePolygonSession()) {
        void this.tools.rect.freezePolygonPreview();
      }

      this.pressSpaceKey();
      if (currentTool === 'lasso' && this.tools.lasso.hasActiveSession() && this.$isPrimaryPointerDown.get()) {
        // Start panning immediately if user is already drawing with freehand lasso.
        this.manager.stage.startDragging();
      } else if (
        currentTool === 'rect' &&
        this.tools.rect.hasSuspendableSession() &&
        this.$isPrimaryPointerDown.get()
      ) {
        // Match lasso: allow an in-progress freehand shapes session to freeze and pan immediately on space.
        this.manager.stage.startDragging();
      } else if (currentTool === 'rect' && this.tools.rect.hasActivePolygonSession()) {
        // Match polygon lasso: when a polygon session is active, Space should immediately enter panning without
        // requiring an extra click on the canvas.
        this.manager.stage.startDragging();
      } else {
        this.$cursorPos.set(null);
      }
      return;
    }

    if (e.key === KEY_ALT) {
      const tool = this.$tool.get();
      const shapeType = this.manager.stateApi.getSettings().shapeType;
      const hasActiveShapeDragSession = this.tools.rect.hasActiveDragSession();
      if (!shouldQuickSwitchToColorPickerOnAlt(tool, shapeType, hasActiveShapeDragSession)) {
        e.preventDefault();
        return;
      }
      // Select the color picker on alt key down
      e.preventDefault();
      e.stopPropagation();
      this.pressAltKey();
    }
  };

  onKeyUp = (e: KeyboardEvent) => {
    if (e.repeat) {
      return;
    }

    if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
      return;
    }
    // Suppress canvas key handlers while an uncommitted text session is active.
    const hasActiveTextSession = this.tools.text.$session.get() !== null;
    if (hasActiveTextSession) {
      return;
    }

    if (e.key === KEY_SPACE || e.code === CODE_SPACE) {
      e.preventDefault();
      e.stopPropagation();
      this.manager.stateApi.$spaceKey.set(false);
      if (this.tools.rect.isTranslatingDragSession()) {
        this.tools.rect.stopDragTranslation();
        return;
      }
      this.releaseSpaceKey();
      return;
    }

    if (e.key === KEY_ALT) {
      // Revert the tool to the previous tool on alt key up
      e.preventDefault();
      e.stopPropagation();
      this.releaseAltKey();
      return;
    }
  };

  repr = () => {
    return {
      id: this.id,
      type: this.type,
      path: this.path,
      config: this.config,
      $tool: this.$tool.get(),
      $baseTool: this.$baseTool.get(),
      $isSpacePressed: this.$isSpacePressed.get(),
      $isAltPressed: this.$isAltPressed.get(),
      $bboxToolHotkeyPressedState: this.$bboxToolHotkeyPressedState.get(),
      $isPrimaryPointerDown: this.$isPrimaryPointerDown.get(),
      $cursorPos: this.$cursorPos.get(),
      $lastPointerType: this.$lastPointerType.get(),
      tools: {
        brush: this.tools.brush.repr(),
        eraser: this.tools.eraser.repr(),
        colorPicker: this.tools.colorPicker.repr(),
        rect: this.tools.rect.repr(),
        lasso: this.tools.lasso.repr(),
        gradient: this.tools.gradient.repr(),
        bbox: this.tools.bbox.repr(),
        view: this.tools.view.repr(),
        move: this.tools.move.repr(),
      },
    };
  };

  destroy = () => {
    this.log.debug('Destroying module');
    this.subscriptions.forEach((unsubscribe) => unsubscribe());
    this.subscriptions.clear();
    for (const tool of Object.values(this.tools)) {
      tool.destroy();
    }
    this.konva.group.destroy();
  };

  private shouldDeferEnterLeaveCommit = (state: AnyObjectState | null) => {
    if (!state) {
      return false;
    }

    if (state.type === 'rect' || state.type === 'oval' || state.type === 'gradient') {
      return true;
    }

    return state.type === 'polygon';
  };

  private shouldSkipWindowPointerUpCommit = (state: AnyObjectState | null) => {
    return Boolean(state?.type === 'polygon' && state.previewPoint);
  };

  private isTemporaryShapesToolSwitch = () => {
    return shouldPreserveSuspendableShapesSession(
      this.$tool.get(),
      this.$baseTool.get(),
      this.tools.rect.hasSuspendableSession()
    );
  };
}