Cotton code
185 lines · 8.7 KB · TypeScriptRaw
// Derive every Android launcher raster from Cotton's one master artwork.////   assets/brand/logo-master.png//     -> mipmap-*/ic_launcher.png             legacy launchers//     -> mipmap-*/ic_launcher_foreground.png  adaptive launchers//     -> values/cotton_launcher.xml           palette-derived background//// Run with `pnpm exec tsx apps/cotton-android/scripts/derive-icons.ts`.// The logo texture is raster art, so Android icons come from the master PNG,// never from the vector geometry used for small in-app marks.import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";import sharp from "sharp";const androidDir = join(dirname(fileURLToPath(import.meta.url)), "..");const repoRoot = join(androidDir, "..", "..");const master = join(repoRoot, "assets", "brand", "logo-master.png");const palette = join(repoRoot, "crates", "cotton-core", "src", "design", "palette.json");const mark = join(repoRoot, "crates", "cotton-core", "src", "design", "mark.json");const resources = join(androidDir, "app", "src", "main", "res");const densities = [  ["mdpi", 48],  ["hdpi", 72],  ["xhdpi", 96],  ["xxhdpi", 144],  ["xxxhdpi", 192],] as const;function graphiteGround(): string {  const decoded = JSON.parse(readFileSync(palette, "utf8")) as {    graphite?: { ground?: unknown };  };  const ground = decoded.graphite?.ground;  if (typeof ground !== "string" || !/^#[0-9a-f]{6}$/i.test(ground)) {    throw new Error(`${palette} does not declare graphite.ground as #RRGGBB`);  }  return ground;}function centre(side: number, width: number, height: number): { left: number; top: number } {  return { left: Math.round((side - width) / 2), top: Math.round((side - height) / 2) };}async function masterInside(side: number, fraction: number): Promise<Buffer> {  const box = Math.round(side * fraction);  return sharp(master)    .resize(box, box, { fit: "inside", background: { r: 0, g: 0, b: 0, alpha: 0 } })    .png()    .toBuffer();}async function renderTile(side: number, ground: string): Promise<Buffer> {  const logo = await masterInside(side, 0.62);  const metadata = await sharp(logo).metadata();  if (!metadata.width || !metadata.height) throw new Error("master resize produced no dimensions");  const at = centre(side, metadata.width, metadata.height);  return sharp({ create: { width: side, height: side, channels: 4, background: ground } })    .composite([{ input: logo, left: at.left, top: at.top }])    .png()    .toBuffer();}async function renderAdaptiveForeground(side: number): Promise<Buffer> {  // Android may crop an adaptive icon to a circle or squircle. Keeping the  // trimmed master within the central 55% protects every thread and knot.  const logo = await masterInside(side, 0.55);  const metadata = await sharp(logo).metadata();  if (!metadata.width || !metadata.height) throw new Error("master resize produced no dimensions");  const at = centre(side, metadata.width, metadata.height);  return sharp({ create: { width: side, height: side, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } } })    .composite([{ input: logo, left: at.left, top: at.top }])    .png()    .toBuffer();}async function renderRoundTile(side: number, ground: string): Promise<Buffer> {  const tile = await renderTile(side, ground);  const mask = Buffer.from(    `<svg width="${side}" height="${side}" xmlns="http://www.w3.org/2000/svg">` +      `<circle cx="${side / 2}" cy="${side / 2}" r="${side / 2}" fill="#fff"/>` +      `</svg>`,  );  return sharp(tile).composite([{ input: mask, blend: "dest-in" }]).png().toBuffer();}type MarkPoint = { x: number; y: number; kind: "knot" | "turn" };type MarkRecord = {  knotRadius: number;  threadWidth: number;  points: MarkPoint[];  threads: [number, number][];};/** A tintable Android vector, fitted from the canonical generated geometry. */function monochromeVector(): string {  const record = JSON.parse(readFileSync(mark, "utf8")) as Partial<MarkRecord>;  if (    typeof record.knotRadius !== "number" ||    typeof record.threadWidth !== "number" ||    !Array.isArray(record.points) ||    !Array.isArray(record.threads)  ) {    throw new Error(`${mark} is not a complete constellation-C record`);  }  const points = record.points;  const threads = record.threads;  const knotRadius = record.knotRadius;  const threadWidth = record.threadWidth;  const grown = points.map((point) => {    const radius = point.kind === "knot" ? knotRadius : threadWidth / 2;    return { minX: point.x - radius, minY: point.y - radius, maxX: point.x + radius, maxY: point.y + radius };  });  const minX = Math.min(...grown.map((point) => point.minX));  const minY = Math.min(...grown.map((point) => point.minY));  const maxX = Math.max(...grown.map((point) => point.maxX));  const maxY = Math.max(...grown.map((point) => point.maxY));  const viewport = 108;  // Keep the complete mark in the adaptive mask safe zone, like the color layer.  const safeSide = viewport * 0.55;  const scale = Math.min(safeSide / (maxX - minX), safeSide / (maxY - minY));  const offsetX = (viewport - (maxX - minX) * scale) / 2 - minX * scale;  const offsetY = (viewport - (maxY - minY) * scale) / 2 - minY * scale;  const at = (point: MarkPoint) => ({ x: point.x * scale + offsetX, y: point.y * scale + offsetY });  const linePath = threads    .map(([from, to]) => {      const start = at(points[from]!);      const end = at(points[to]!);      return `M${start.x.toFixed(3)},${start.y.toFixed(3)} L${end.x.toFixed(3)},${end.y.toFixed(3)}`;    })    .join(" ");  const circles = points    .filter((point) => point.kind === "knot")    .map((point) => {      const centre = at(point);      const radius = knotRadius * scale;      // Two arcs make one circle; Android VectorDrawable has no circle node.      return `M${(centre.x - radius).toFixed(3)},${centre.y.toFixed(3)} a${radius.toFixed(3)},${radius.toFixed(3)} 0,1 0 ${(radius * 2).toFixed(3)},0 a${radius.toFixed(3)},${radius.toFixed(3)} 0,1 0 ${(-radius * 2).toFixed(3)},0`;    })    .join(" ");  return `<!-- GENERATED by apps/cotton-android/scripts/derive-icons.ts from crates/cotton-core/src/design/mark.json. -->\n<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">\n    <path android:fillColor="#FFFFFFFF" android:strokeColor="#FFFFFFFF" android:strokeWidth="${(threadWidth * scale).toFixed(3)}" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="${linePath}" />\n    <path android:fillColor="#FFFFFFFF" android:pathData="${circles}" />\n</vector>\n`;}function writeXml(ground: string): void {  const values = join(resources, "values");  const adaptive = join(resources, "mipmap-anydpi-v26");  const drawable = join(resources, "drawable");  mkdirSync(values, { recursive: true });  mkdirSync(adaptive, { recursive: true });  mkdirSync(drawable, { recursive: true });  writeFileSync(    join(values, "cotton_launcher.xml"),    `<!-- GENERATED by apps/cotton-android/scripts/derive-icons.ts from crates/cotton-core/src/design/palette.json. -->\n<resources>\n    <color name="cotton_launcher_background">${ground}</color>\n</resources>\n`,  );  writeFileSync(    join(adaptive, "ic_launcher.xml"),    `<!-- GENERATED by apps/cotton-android/scripts/derive-icons.ts from assets/brand/logo-master.png and crates/cotton-core/src/design/mark.json. -->\n<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">\n    <background android:drawable="@color/cotton_launcher_background" />\n    <foreground android:drawable="@mipmap/ic_launcher_foreground" />\n    <monochrome android:drawable="@drawable/ic_launcher_monochrome" />\n</adaptive-icon>\n`,  );  writeFileSync(join(drawable, "ic_launcher_monochrome.xml"), monochromeVector());}export async function deriveIcons(): Promise<void> {  statSync(master);  const ground = graphiteGround();  for (const [density, legacySide] of densities) {    const output = join(resources, `mipmap-${density}`);    mkdirSync(output, { recursive: true });    const tile = await renderTile(legacySide, ground);    writeFileSync(join(output, "ic_launcher.png"), tile);    writeFileSync(join(output, "ic_launcher_round.png"), await renderRoundTile(legacySide, ground));    writeFileSync(join(output, "ic_launcher_foreground.png"), await renderAdaptiveForeground(legacySide * 3));  }  writeXml(ground);  console.log(`Android launcher icons derived from ${master}`);}if (process.argv[1] === fileURLToPath(import.meta.url)) {  deriveIcons().catch((error: unknown) => {    console.error(error instanceof Error ? error.message : error);    process.exit(1);  });}