Skip to content

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

17.7 KB
Raw Blame
/**
 * Authentic Typography & Manga Text Layout Engine
 *
 * Provides crisp, natural proportional text rendering with native OS/browser kerning
 * and shaping for horizontal text, plus traditional East Asian vertical lettering
 * (tate-gaki: vertical-rl, right-to-left columns) with punctuation rotation/shifting,
 * word wrapping, letter spacing, underline, opacity, and clean two-pass outlines.
 */

export interface MangaTextOptions {
  fontSize: number;
  fontFamily: string;
  writingMode?: 'horizontal-tb' | 'vertical-rl';
  bold?: boolean;
  italic?: boolean;
  underline?: boolean;
  align?: 'left' | 'center' | 'right';
  color?: string;
  outline?: boolean;
  outlineColor?: string;
  outlineWidth?: number;
  lineHeightRatio?: number;
  letterSpacing?: number;
  opacity?: number;
  maxWidth?: number | null;
  maxHeight?: number;
  anchorTopLeft?: boolean;
}

export interface PositionedGlyph {
  char: string;
  x: number;
  y: number;
  rotateDeg: number;
  scaleX?: number;
  scaleY?: number;
}

export interface PositionedLine {
  text: string;
  x: number;
  y: number;
  baselineY: number;
  width: number;
  height: number;
}

export interface TextLayoutResult {
  glyphs: PositionedGlyph[];
  lines: PositionedLine[];
  width: number;
  height: number;
  ascent: number;
  descent: number;
  lineHeight: number;
}

// Characters that should be rotated 90 degrees clockwise in vertical writing mode
const ROTATED_PUNCTUATION = new Set([
  '—', '―', '–', '-', 'ー', '…', '‥', '~', '~', '〜', ':', ';',
  '「', '」', '『', '』', '(', ')', '(', ')', '【', '】',
  '[', ']', '[', ']', '{', '}', '{', '}', '〈', '〉',
  '《', '》', '<', '>', '<', '>', '〔', '〕', '|', '|',
  '=', '=', '_', '_',
]);

// Japanese punctuation that needs shifting to the upper right corner in vertical mode
const SHIFTED_PUNCTUATION = new Set([
  '。', '、', ',', '.', '・',
]);

// Japanese small kana (拗音・促音) shift subtly toward top-right in traditional vertical lettering
const SMALL_KANA = new Set([
  'ぁ', 'ぃ', 'ぅ', 'ぇ', 'ぉ', 'っ', 'ゃ', 'ゅ', 'ょ', 'ゎ',
  'ァ', 'ィ', 'ゥ', 'ェ', 'ォ', 'ッ', 'ャ', 'ュ', 'ョ', 'ヮ', 'ヵ', 'ヶ',
]);

let cachedMeasureCtx: CanvasRenderingContext2D | null | undefined;
let supportsNativeLetterSpacing: boolean | undefined;

function getMeasureContext(): CanvasRenderingContext2D | null {
  if (cachedMeasureCtx !== undefined) return cachedMeasureCtx;
  if (typeof document === 'undefined') {
    cachedMeasureCtx = null;
    return null;
  }
  try {
    const canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = 1;
    const ctx = canvas.getContext('2d');
    cachedMeasureCtx = ctx ?? null;
  } catch {
    cachedMeasureCtx = null;
  }
  return cachedMeasureCtx;
}

function checkNativeLetterSpacing(ctx: CanvasRenderingContext2D): boolean {
  if (supportsNativeLetterSpacing !== undefined) return supportsNativeLetterSpacing;
  try {
    const anyCtx = ctx as unknown as { letterSpacing?: string };
    if (typeof anyCtx.letterSpacing !== 'string') {
      supportsNativeLetterSpacing = false;
      return false;
    }
    const prev = anyCtx.letterSpacing;
    anyCtx.letterSpacing = '4px';
    supportsNativeLetterSpacing = anyCtx.letterSpacing === '4px';
    anyCtx.letterSpacing = prev;
  } catch {
    supportsNativeLetterSpacing = false;
  }
  return supportsNativeLetterSpacing;
}

function setContextLetterSpacing(ctx: CanvasRenderingContext2D, letterSpacing: number): boolean {
  if (!checkNativeLetterSpacing(ctx)) return false;
  (ctx as unknown as { letterSpacing: string }).letterSpacing =
    letterSpacing === 0 ? '0px' : `${letterSpacing}px`;
  return true;
}

/**
 * Builds a consistent CSS font descriptor shared by measurement, canvas rendering, and DOM preview.
 */
export function buildCanvasFontString(options: {
  fontSize?: number;
  fontFamily?: string;
  bold?: boolean;
  italic?: boolean;
}): string {
  const fontSize = Math.max(1, options.fontSize || 20);
  const style = options.italic ? 'italic ' : '';
  const weight = options.bold ? '700 ' : '400 ';
  const family = options.fontFamily?.trim() || "Inter, 'Segoe UI', system-ui, sans-serif";
  return `${style}${weight}${fontSize}px ${family}`;
}

/**
 * Checks if a character is an ASCII Latin letter or digit.
 */
export function isLatinChar(char: string): boolean {
  const code = char.charCodeAt(0);
  return (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 48 && code <= 57);
}

function isWideCjkChar(char: string): boolean {
  const cp = char.codePointAt(0) ?? 0;
  return (
    (cp >= 0x3000 && cp <= 0x9fff) ||
    (cp >= 0xac00 && cp <= 0xd7af) ||
    (cp >= 0xf900 && cp <= 0xfaff) ||
    (cp >= 0xff01 && cp <= 0xff60)
  );
}

function estimateFallbackCharWidth(char: string, fontSize: number, bold?: boolean): number {
  const boldBoost = bold ? 1.06 : 1.0;
  if (char === ' ') return fontSize * 0.28;
  if (char === '\t') return fontSize * 1.12;
  if (isWideCjkChar(char)) return fontSize * 1.0;
  if ("ilI1|.,:;'!`".includes(char)) return fontSize * 0.3 * boldBoost;
  if ('WM@%#&'.includes(char)) return fontSize * 0.86 * boldBoost;
  if ('mwGOQD'.includes(char)) return fontSize * 0.72 * boldBoost;
  return fontSize * 0.56 * boldBoost;
}

function measureTextWidth(
  ctx: CanvasRenderingContext2D | null,
  str: string,
  fontSize: number,
  letterSpacing: number,
  bold?: boolean
): number {
  if (!str) return 0;
  if (ctx) {
    if (letterSpacing === 0) {
      setContextLetterSpacing(ctx, 0);
      return ctx.measureText(str).width;
    }
    if (setContextLetterSpacing(ctx, letterSpacing)) {
      const w = ctx.measureText(str).width;
      setContextLetterSpacing(ctx, 0);
      // Native letterSpacing applies after the final glyph in some engines; subtract trailing spacing
      const chars = Array.from(str);
      return Math.max(0, chars.length > 0 ? w - letterSpacing : w);
    }
    const chars = Array.from(str);
    let total = 0;
    for (let i = 0; i < chars.length; i++) {
      total += ctx.measureText(chars[i]).width;
      if (i < chars.length - 1) total += letterSpacing;
    }
    return Math.max(0, total);
  }

  const chars = Array.from(str);
  let total = 0;
  for (let i = 0; i < chars.length; i++) {
    total += estimateFallbackCharWidth(chars[i], fontSize, bold);
    if (i < chars.length - 1) total += letterSpacing;
  }
  return Math.max(0, total);
}

function measureFontVerticalMetrics(
  ctx: CanvasRenderingContext2D | null,
  fontSize: number
): { ascent: number; descent: number } {
  if (ctx) {
    try {
      const m = ctx.measureText('MgÅjpq');
      const ascent =
        (typeof m.fontBoundingBoxAscent === 'number' && m.fontBoundingBoxAscent > 0
          ? m.fontBoundingBoxAscent
          : m.actualBoundingBoxAscent) || fontSize * 0.82;
      const descent =
        (typeof m.fontBoundingBoxDescent === 'number' && m.fontBoundingBoxDescent > 0
          ? m.fontBoundingBoxDescent
          : m.actualBoundingBoxDescent) || fontSize * 0.2;
      return { ascent, descent };
    } catch {
      // Fallback below
    }
  }
  return {
    ascent: fontSize * 0.82,
    descent: fontSize * 0.2,
  };
}

function wrapParagraph(
  paragraph: string,
  maxWidth: number,
  measure: (s: string) => number
): string[] {
  if (!paragraph) return [''];
  if (measure(paragraph) <= maxWidth) return [paragraph];

  const tokens = paragraph.match(/\S+|\s+/g) ?? [paragraph];
  const wrapped: string[] = [];
  let current = '';

  const pushBreakLongWord = (word: string) => {
    const chars = Array.from(word);
    let chunk = '';
    for (const ch of chars) {
      const candidate = chunk + ch;
      if (chunk && measure(candidate) > maxWidth) {
        wrapped.push(chunk);
        chunk = ch;
      } else {
        chunk = candidate;
      }
    }
    current = chunk;
  };

  for (const token of tokens) {
    const candidate = current + token;
    if (measure(candidate) <= maxWidth) {
      current = candidate;
      continue;
    }
    if (/^\s+$/.test(token)) {
      // Drop overflowing trailing whitespace at line wrap
      if (current) {
        wrapped.push(current);
        current = '';
      }
      continue;
    }
    if (current) {
      wrapped.push(current.replace(/\s+$/, ''));
      current = '';
    }
    if (measure(token) <= maxWidth) {
      current = token;
    } else {
      pushBreakLongWord(token);
    }
  }

  if (current || wrapped.length === 0) {
    wrapped.push(current);
  }
  return wrapped;
}

/**
 * Computes natural proportional horizontal layout or traditional vertical-rl layout.
 */
export function computeMangaTextLayout(
  text: string,
  options: MangaTextOptions
): TextLayoutResult {
  const isVertical = options.writingMode === 'vertical-rl';
  const fontSize = Math.max(1, options.fontSize || 20);
  const lineHeightRatio = options.lineHeightRatio || (isVertical ? 1.4 : 1.25);
  const lineHeight = fontSize * lineHeightRatio;
  const letterSpacing = options.letterSpacing ?? 0;
  const rawParagraphs = text.split('\n');

  const measureCtx = getMeasureContext();
  if (measureCtx) {
    measureCtx.font = buildCanvasFontString(options);
  }
  const { ascent, descent } = measureFontVerticalMetrics(measureCtx, fontSize);

  if (!isVertical) {
    const measure = (s: string) =>
      measureTextWidth(measureCtx, s, fontSize, letterSpacing, options.bold);

    const wrapWidth =
      typeof options.maxWidth === 'number' && Number.isFinite(options.maxWidth) && options.maxWidth >= 24
        ? options.maxWidth
        : null;

    const visualLines: string[] = [];
    for (const para of rawParagraphs) {
      if (wrapWidth !== null) {
        visualLines.push(...wrapParagraph(para, wrapWidth, measure));
      } else {
        visualLines.push(para);
      }
    }

    const lineWidths = visualLines.map((l) => measure(l));
    let maxMeasuredWidth = 0;
    for (const w of lineWidths) {
      if (w > maxMeasuredWidth) maxMeasuredWidth = w;
    }

    const boxWidth = wrapWidth !== null ? Math.max(wrapWidth, maxMeasuredWidth) : Math.max(fontSize * 0.6, maxMeasuredWidth);
    const leading = lineHeight - (ascent + descent);
    const baselineInLine = leading * 0.5 + ascent;

    const lines: PositionedLine[] = [];
    const glyphs: PositionedGlyph[] = [];

    visualLines.forEach((lineText, lineIdx) => {
      const lineY = lineIdx * lineHeight;
      const baselineY = lineY + baselineInLine;
      const lw = lineWidths[lineIdx];

      let startX = 0;
      if (options.align === 'center') {
        startX = (boxWidth - lw) * 0.5;
      } else if (options.align === 'right') {
        startX = boxWidth - lw;
      }

      lines.push({
        text: lineText,
        x: startX,
        y: lineY,
        baselineY,
        width: lw,
        height: lineHeight,
      });

      // Populate per-character glyph coordinates for hit-testing and consumers
      const chars = Array.from(lineText);
      let cursorX = startX;
      const glyphCenterY = lineY + lineHeight * 0.5;
      for (let i = 0; i < chars.length; i++) {
        const ch = chars[i];
        const cw = measureTextWidth(measureCtx, ch, fontSize, 0, options.bold);
        glyphs.push({
          char: ch,
          x: cursorX + cw * 0.5,
          y: glyphCenterY,
          rotateDeg: 0,
        });
        cursorX += cw + letterSpacing;
      }
    });

    const totalHeight = Math.max(lineHeight, visualLines.length * lineHeight);
    return {
      glyphs,
      lines,
      width: boxWidth,
      height: totalHeight,
      ascent,
      descent,
      lineHeight,
    };
  }

  // Vertical-rl layout: Columns proceed Right to Left, characters Top to Bottom
  const numColumns = rawParagraphs.length;
  const totalWidth = numColumns * lineHeight;
  const stepY = Math.max(fontSize * 0.5, fontSize + letterSpacing);
  let maxColHeight = 0;
  const glyphs: PositionedGlyph[] = [];
  const lines: PositionedLine[] = [];

  rawParagraphs.forEach((line, colIndex) => {
    const chars = Array.from(line);
    // In vertical-rl, col 0 is at rightmost position
    const colX = (numColumns - 1 - colIndex) * lineHeight + lineHeight * 0.5;
    let currentY = fontSize * 0.6;

    for (let cIdx = 0; cIdx < chars.length; cIdx++) {
      const char = chars[cIdx];
      let rotateDeg = 0;
      let dx = 0;
      let dy = 0;

      if (ROTATED_PUNCTUATION.has(char)) {
        rotateDeg = 90;
      } else if (SHIFTED_PUNCTUATION.has(char)) {
        dx = fontSize * 0.28;
        dy = -fontSize * 0.28;
      } else if (SMALL_KANA.has(char)) {
        dx = fontSize * 0.1;
        dy = -fontSize * 0.08;
      }

      glyphs.push({
        char,
        x: colX + dx,
        y: currentY + dy,
        rotateDeg,
      });

      currentY += stepY;
    }

    const colHeight = chars.length > 0 ? currentY - stepY + fontSize * 0.6 : fontSize;
    lines.push({
      text: line,
      x: colX - lineHeight * 0.5,
      y: 0,
      baselineY: fontSize * 0.6,
      width: lineHeight,
      height: colHeight,
    });

    if (colHeight > maxColHeight) {
      maxColHeight = colHeight;
    }
  });

  return {
    glyphs,
    lines,
    width: Math.max(fontSize, totalWidth),
    height: Math.max(fontSize, maxColHeight),
    ascent,
    descent,
    lineHeight,
  };
}

function drawHorizontalLine(
  ctx: CanvasRenderingContext2D,
  line: PositionedLine,
  offsetX: number,
  offsetY: number,
  letterSpacing: number,
  mode: 'stroke' | 'fill'
): void {
  if (!line.text) return;
  const drawX = offsetX + line.x;
  const drawY = offsetY + line.baselineY;

  if (letterSpacing === 0) {
    setContextLetterSpacing(ctx, 0);
    if (mode === 'stroke') {
      ctx.strokeText(line.text, drawX, drawY);
    } else {
      ctx.fillText(line.text, drawX, drawY);
    }
    return;
  }

  if (setContextLetterSpacing(ctx, letterSpacing)) {
    if (mode === 'stroke') {
      ctx.strokeText(line.text, drawX, drawY);
    } else {
      ctx.fillText(line.text, drawX, drawY);
    }
    setContextLetterSpacing(ctx, 0);
    return;
  }

  // Fallback per-grapheme rendering when native ctx.letterSpacing is unavailable
  const chars = Array.from(line.text);
  let cursorX = drawX;
  for (let i = 0; i < chars.length; i++) {
    const ch = chars[i];
    if (mode === 'stroke') {
      ctx.strokeText(ch, cursorX, drawY);
    } else {
      ctx.fillText(ch, cursorX, drawY);
    }
    cursorX += ctx.measureText(ch).width + letterSpacing;
  }
}

/**
 * Renders authentic typography onto a 2D Canvas context using two-pass outline-then-fill
 * rendering and native font shaping for horizontal text.
 */
export function renderMangaTextToCanvas(
  ctx: CanvasRenderingContext2D,
  text: string,
  originX: number,
  originY: number,
  options: MangaTextOptions
): void {
  if (!text || !text.trim()) return;

  const isVertical = options.writingMode === 'vertical-rl';
  const fontSize = Math.max(1, options.fontSize || 20);
  const letterSpacing = options.letterSpacing ?? 0;
  const opacity =
    typeof options.opacity === 'number' && Number.isFinite(options.opacity)
      ? Math.max(0.05, Math.min(1, options.opacity))
      : 1;
  const fontStyle = buildCanvasFontString(options);
  const layout = computeMangaTextLayout(text, options);

  ctx.save();
  ctx.globalAlpha *= opacity;
  ctx.font = fontStyle;
  ctx.lineJoin = 'round';
  ctx.lineCap = 'round';
  ctx.miterLimit = 2;

  let offsetX = originX - layout.width * 0.5;
  let offsetY = originY - layout.height * 0.5;

  if (options.anchorTopLeft) {
    offsetX = originX;
    offsetY = originY;
  } else if (options.align === 'left') {
    offsetX = originX;
  } else if (options.align === 'right') {
    offsetX = originX - layout.width;
  }

  const hasOutline = Boolean(options.outline && (options.outlineWidth ?? 0) > 0);
  const outlineStrokeWidth = (options.outlineWidth ?? 2) * 2;
  const outlineColor = options.outlineColor || '#000000';
  const fillColor = options.color || '#ffffff';

  if (!isVertical) {
    ctx.textAlign = 'left';
    ctx.textBaseline = 'alphabetic';

    const underlineThickness = Math.max(1, fontSize * 0.065);
    const underlineOffset = Math.max(2, fontSize * 0.13);

    // Pass 1: Draw ALL outlines first so strokes never bleed over adjacent glyphs
    if (hasOutline) {
      ctx.strokeStyle = outlineColor;
      ctx.lineWidth = outlineStrokeWidth;
      for (const line of layout.lines) {
        drawHorizontalLine(ctx, line, offsetX, offsetY, letterSpacing, 'stroke');
        if (options.underline && line.width > 0) {
          const uy = offsetY + line.baselineY + underlineOffset;
          ctx.beginPath();
          ctx.lineWidth = underlineThickness + outlineStrokeWidth;
          ctx.moveTo(offsetX + line.x, uy);
          ctx.lineTo(offsetX + line.x + line.width, uy);
          ctx.stroke();
          ctx.lineWidth = outlineStrokeWidth;
        }
      }
    }

    // Pass 2: Draw crisp main text fill on top
    ctx.fillStyle = fillColor;
    for (const line of layout.lines) {
      drawHorizontalLine(ctx, line, offsetX, offsetY, letterSpacing, 'fill');
      if (options.underline && line.width > 0) {
        const uy = offsetY + line.baselineY + underlineOffset - underlineThickness * 0.5;
        ctx.fillRect(offsetX + line.x, uy, line.width, underlineThickness);
      }
    }

    ctx.restore();
    return;
  }

  // Vertical-rl two-pass rendering
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';

  if (hasOutline) {
    ctx.strokeStyle = outlineColor;
    ctx.lineWidth = outlineStrokeWidth;
    for (const g of layout.glyphs) {
      ctx.save();
      ctx.translate(offsetX + g.x, offsetY + g.y);
      if (g.rotateDeg !== 0) {
        ctx.rotate((g.rotateDeg * Math.PI) / 180);
      }
      ctx.strokeText(g.char, 0, 0);
      ctx.restore();
    }
  }

  ctx.fillStyle = fillColor;
  for (const g of layout.glyphs) {
    ctx.save();
    ctx.translate(offsetX + g.x, offsetY + g.y);
    if (g.rotateDeg !== 0) {
      ctx.rotate((g.rotateDeg * Math.PI) / 180);
    }
    ctx.fillText(g.char, 0, 0);
    ctx.restore();
  }

  ctx.restore();
}