Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

12.5 KB
Raw Blame
import { BrushPresetId, CspBrush, ToolType } from '../types/editor';
import {
  ALL_BUILTIN_BRUSHES,
  BUILTIN_BRUSH_SECTIONS,
  DECORATION_BRUSH_SECTIONS,
  isDecorationCategory,
  isDecorationPresetId,
} from './presetBrushes';
import {
  ERASER_PRESET_ID,
  NEUTRAL_BRUSH_DEFAULTS,
  getEffectiveBrushSettings,
  getSavedBrushSettings,
  migrateLegacyPresetId,
  saveActiveDecorationPresetId,
  saveActivePresetId,
} from './brushPresetManager';
import { getCachedCustomBrushes, prepareBrushSettingsForCsp } from './brushStorage';
import {
  ActiveSubToolGroupTab,
  getEffectiveBrushGroupId,
  getNavigableDecorationSubToolGroups,
  getNavigableSubToolGroups,
  getOrderedDecorationSubToolIdsForTab,
  getOrderedSubToolIdsForTab,
  getValidBrushIdsInCustomGroup,
  isDecorationCustomGroup,
} from './subToolGroups';
import { toolStoreActions, useToolStore } from '../stores/useToolStore';
import {
  subToolGroupStoreActions,
  useSubToolGroupStore,
} from '../stores/useSubToolGroupStore';

/**
 * Ordered list of drawing/editing instruments matching ToolStrip order
 * (excludes 'transform' which is a modal edit session triggered via Ctrl+T).
 */
export const TOOL_CYCLE_ORDER: readonly ToolType[] = [
  'brush',
  'decoration',
  'eraser',
  'pipette',
  'liquify',
  'retouch',
  'select-rect',
  'select-lasso',
  'select-wand',
  'select-pen',
  'fill',
  'gradient',
  'shape',
  'pen',
  'object',
  'text',
  'frame',
  'balloon',
  'vector-edit',
  '3d',
];

export const TOOL_DISPLAY_LABELS: Record<ToolType, string> = {
  brush: 'Brush',
  decoration: 'Decoration',
  eraser: 'Eraser',
  pipette: 'Eyedropper',
  transform: 'Transform',
  'select-rect': 'Rectangle Selection',
  'select-lasso': 'Lasso Selection',
  'select-wand': 'Magic Wand',
  'select-pen': 'Selection Pen',
  'select-eraser': 'Selection Eraser',
  fill: 'Fill Bucket',
  gradient: 'Gradient',
  retouch: 'Retouch',
  shape: 'Shapes',
  pen: 'Bézier Pen',
  text: 'Text',
  frame: 'Frame Border',
  balloon: 'Speech Balloon',
  object: 'Object',
  'vector-edit': 'Correct Line',
  liquify: 'Liquify',
  '3d': '3D Object & Camera',
};

export interface SubToolActivationResult {
  presetId: BrushPresetId;
  name: string;
}

export interface MainToolStepResult {
  tool: ToolType;
  label: string;
}

export interface SubToolGroupActivationResult {
  groupId: ActiveSubToolGroupTab;
  groupName: string;
  activatedBrushName?: string;
}

export function resolveSubToolDisplayName(
  presetId: BrushPresetId,
  customBrushes: readonly CspBrush[] = getCachedCustomBrushes()
): string {
  const norm = migrateLegacyPresetId(presetId);
  if (norm === ERASER_PRESET_ID || norm === 'eraser') return 'Eraser';
  const custom = customBrushes.find((b) => b.id === presetId || b.id === norm);
  if (custom) return custom.name;
  const builtin = ALL_BUILTIN_BRUSHES.find((b) => b.id === norm);
  if (builtin) return builtin.name;
  return presetId;
}

/**
 * Activates any subtool preset (built-in Brush, built-in Decoration, or custom CspBrush)
 * synchronously for immediate canvas response, while also hydrating custom brush images asynchronously.
 */
export function activateSubToolPreset(
  presetId: BrushPresetId,
  customBrushesInput?: readonly CspBrush[]
): SubToolActivationResult | null {
  const norm = migrateLegacyPresetId(presetId);
  if (!norm) return null;

  if (norm === ERASER_PRESET_ID || norm === 'eraser') {
    toolStoreActions.selectTool('eraser');
    return { presetId: ERASER_PRESET_ID, name: 'Eraser' };
  }

  const customBrushes = customBrushesInput ? [...customBrushesInput] : getCachedCustomBrushes();
  const customMatch = customBrushes.find((b) => b.id === presetId || b.id === norm);
  const builtinMatch = !customMatch ? ALL_BUILTIN_BRUSHES.find((b) => b.id === norm) : undefined;
  if (!customMatch && !builtinMatch) return null;

  const targetId = customMatch ? customMatch.id : builtinMatch!.id;
  const displayName = customMatch ? customMatch.name : builtinMatch!.name;

  const groupState = useSubToolGroupStore.getState();
  const ownerGroupId = getEffectiveBrushGroupId(
    targetId,
    groupState.groups,
    groupState.brushGroupOverrides,
    customBrushes
  );
  const ownerCustomGroup = groupState.groups.find((g) => g.id === ownerGroupId);
  const targetIsDecoration =
    Boolean(ownerCustomGroup && isDecorationCustomGroup(ownerCustomGroup)) ||
    isDecorationCategory(ownerGroupId) ||
    (!ownerCustomGroup &&
      (isDecorationPresetId(targetId) || isDecorationCategory(customMatch?.category)));

  toolStoreActions.selectTool(targetIsDecoration ? 'decoration' : 'brush');
  if (targetIsDecoration) {
    saveActiveDecorationPresetId(targetId);
  } else {
    saveActivePresetId(targetId);
  }

  // Immediate synchronous activation so zero frames are dropped on hotkey press
  const effective = getEffectiveBrushSettings(targetId, customBrushes);
  toolStoreActions.updateBrushSettings({
    ...NEUTRAL_BRUSH_DEFAULTS,
    ...effective,
    preset: targetId,
  });
  subToolGroupStoreActions.recordActiveBrush(targetId);

  // Async image decode hydration for custom brushes whose tip images aren't yet decoded
  if (customMatch) {
    void prepareBrushSettingsForCsp(customMatch).then((prepared) => {
      // Only apply if user hasn't already switched away to another preset
      if (useToolStore.getState().activePresetId !== targetId) return;
      const saved = getSavedBrushSettings(targetId);
      toolStoreActions.updateBrushSettings({
        ...NEUTRAL_BRUSH_DEFAULTS,
        ...prepared,
        ...saved,
        preset: targetId,
      });
    });
  }

  return { presetId: targetId, name: displayName };
}

/**
 * Switches to the previous (-1) or next (+1) sub tool within the currently active SubTool group
 * (wrapping cleanly around the edges, matching Clip Studio Paint's ',' and '.' workflow).
 */
export function stepSubTool(
  direction: -1 | 1,
  customBrushesInput?: readonly CspBrush[]
): SubToolActivationResult | null {
  const customBrushes = customBrushesInput ? [...customBrushesInput] : getCachedCustomBrushes();
  const currentState = useToolStore.getState();
  const { activeTab, activeDecorationTab, groups, brushGroupOverrides, builtinGroupOrders } =
    useSubToolGroupStore.getState();

  const isDecoMode = currentState.tool === 'decoration';
  let ordered = isDecoMode
    ? getOrderedDecorationSubToolIdsForTab(
        activeDecorationTab,
        groups,
        customBrushes,
        brushGroupOverrides,
        builtinGroupOrders
      )
    : getOrderedSubToolIdsForTab(
        activeTab,
        groups,
        customBrushes,
        brushGroupOverrides,
        builtinGroupOrders
      );
  if (ordered.length === 0) {
    // Active custom group is empty — fall back to full list so shortcut always feels responsive
    ordered = isDecoMode
      ? getOrderedDecorationSubToolIdsForTab(
          'all',
          groups,
          customBrushes,
          brushGroupOverrides,
          builtinGroupOrders
        )
      : getOrderedSubToolIdsForTab(
          'all',
          groups,
          customBrushes,
          brushGroupOverrides,
          builtinGroupOrders
        );
  }
  if (ordered.length === 0) return null;

  const currentPreset = migrateLegacyPresetId(currentState.activePresetId);
  const currentIdx = ordered.findIndex(
    (id) => id === currentState.activePresetId || migrateLegacyPresetId(id) === currentPreset
  );

  let nextIdx: number;
  if (currentIdx < 0) {
    nextIdx = direction > 0 ? 0 : ordered.length - 1;
  } else {
    nextIdx = (currentIdx + direction + ordered.length) % ordered.length;
  }

  return activateSubToolPreset(ordered[nextIdx], customBrushes);
}

/**
 * Switches to the previous (-1) or next (+1) main instrument along the ToolStrip.
 */
export function stepMainTool(
  direction: -1 | 1,
  hasOpenDocument: boolean
): MainToolStepResult {
  const available = hasOpenDocument
    ? TOOL_CYCLE_ORDER
    : TOOL_CYCLE_ORDER.filter((t) => t !== '3d');

  const currentTool = useToolStore.getState().tool;
  const idx = available.indexOf(currentTool);
  const nextIdx =
    idx < 0
      ? direction > 0
        ? 0
        : available.length - 1
      : (idx + direction + available.length) % available.length;

  const nextTool = available[nextIdx];
  toolStoreActions.selectTool(nextTool);
  return {
    tool: nextTool,
    label: TOOL_DISPLAY_LABELS[nextTool] || nextTool,
  };
}

/**
 * Opens/focuses a SubTool group by ID (custom group ID, built-in category, or 'custom')
 * and activates its last-used or first subtool (like CSP).
 */
export function activateSubToolGroup(
  groupId: ActiveSubToolGroupTab,
  customBrushesInput?: readonly CspBrush[]
): SubToolGroupActivationResult | null {
  const customBrushes = customBrushesInput ? [...customBrushesInput] : getCachedCustomBrushes();
  const { groups, brushGroupOverrides, builtinGroupOrders } = useSubToolGroupStore.getState();

  const customGroup = groups.find((g) => g.id === groupId);
  if (customGroup) {
    const isDecoGroup = isDecorationCustomGroup(customGroup);
    if (isDecoGroup) {
      subToolGroupStoreActions.setActiveDecorationTab(customGroup.id);
    } else {
      subToolGroupStoreActions.setActiveTab(customGroup.id);
    }
    const validIds = getValidBrushIdsInCustomGroup(customGroup, customBrushes);
    const preferred =
      customGroup.lastActiveBrushId && validIds.includes(customGroup.lastActiveBrushId)
        ? customGroup.lastActiveBrushId
        : validIds[0];
    const activated = preferred ? activateSubToolPreset(preferred, customBrushes) : null;
    if (!activated) {
      toolStoreActions.selectTool(isDecoGroup ? 'decoration' : 'brush');
    }
    return {
      groupId: customGroup.id,
      groupName: customGroup.name,
      activatedBrushName: activated?.name,
    };
  }

  const builtinSection = BUILTIN_BRUSH_SECTIONS.find((s) => s.id === groupId);
  if (builtinSection) {
    subToolGroupStoreActions.setActiveTab(builtinSection.id);
    const ids = getOrderedSubToolIdsForTab(
      builtinSection.id,
      groups,
      customBrushes,
      brushGroupOverrides,
      builtinGroupOrders
    );
    const activated = ids[0] ? activateSubToolPreset(ids[0], customBrushes) : null;
    return {
      groupId: builtinSection.id,
      groupName: builtinSection.label,
      activatedBrushName: activated?.name,
    };
  }

  const decoSection = DECORATION_BRUSH_SECTIONS.find((s) => s.id === groupId);
  if (decoSection && isDecorationCategory(decoSection.id)) {
    subToolGroupStoreActions.setActiveDecorationTab(decoSection.id);
    const ids = getOrderedDecorationSubToolIdsForTab(
      decoSection.id,
      groups,
      customBrushes,
      brushGroupOverrides,
      builtinGroupOrders
    );
    const activated = ids[0] ? activateSubToolPreset(ids[0], customBrushes) : null;
    if (!activated) {
      toolStoreActions.selectTool('decoration');
    }
    return {
      groupId: decoSection.id,
      groupName: decoSection.label,
      activatedBrushName: activated?.name,
    };
  }

  if (groupId === 'custom') {
    subToolGroupStoreActions.setActiveTab('custom');
    const ids = getOrderedSubToolIdsForTab(
      'custom',
      groups,
      customBrushes,
      brushGroupOverrides,
      builtinGroupOrders
    );
    const activated = ids[0] ? activateSubToolPreset(ids[0], customBrushes) : null;
    return {
      groupId: 'custom',
      groupName: 'Imported',
      activatedBrushName: activated?.name,
    };
  }

  return null;
}

/**
 * Cycles to the previous (-1) or next (+1) SubTool group tab and selects its brush.
 */
export function stepSubToolGroup(
  direction: -1 | 1,
  customBrushesInput?: readonly CspBrush[]
): SubToolGroupActivationResult | null {
  const customBrushes = customBrushesInput ? [...customBrushesInput] : getCachedCustomBrushes();
  const isDecoMode = useToolStore.getState().tool === 'decoration';
  const { activeTab, activeDecorationTab, groups, brushGroupOverrides, builtinGroupOrders } =
    useSubToolGroupStore.getState();
  const navigable = isDecoMode
    ? getNavigableDecorationSubToolGroups(
        groups,
        customBrushes,
        brushGroupOverrides,
        builtinGroupOrders
      )
    : getNavigableSubToolGroups(
        groups,
        customBrushes,
        brushGroupOverrides,
        builtinGroupOrders
      );
  if (navigable.length === 0) return null;

  const currentTab = isDecoMode ? activeDecorationTab : activeTab;
  const idx = navigable.findIndex((entry) => entry.id === currentTab);
  const nextIdx =
    idx < 0
      ? direction > 0
        ? 0
        : navigable.length - 1
      : (idx + direction + navigable.length) % navigable.length;

  return activateSubToolGroup(navigable[nextIdx].id, customBrushes);
}