diff --git a/cli/shots/capture.ts b/cli/shots/capture.ts index 70a5fb0c..766bd8d4 100644 --- a/cli/shots/capture.ts +++ b/cli/shots/capture.ts @@ -1,5 +1,6 @@ // Raw frames from a running build of your game, from any engine. // storebound shots capture [--lang en,tr] [--only hero,shop] [--device phone|tablet] [--source web|ios-sim|android-emu|folder] +// [--dry] [--keep-booted] // Frames go to ///.png: the screen BELOW the status bar (the template draws one). // shots.capture.source (default web): // web headless Chromium (playwright), mobile viewport + touch at phone / tablet size. Each shot: @@ -13,6 +14,8 @@ // `exec-out screencap -p`. Works on an emulator or a USB device. Nothing is wiped or rebooted. // folder your own frames (any tool, any engine): only checks that every frame the scenes use exists with the // right aspect ratio and resolution. +// A simulator storebound booted itself is shut down at the end (--keep-booted keeps it); one that was already running is +// left running with its status bar restored. --dry prints the simctl / adb commands without running them. // Simulator / emulator screenshots are full screen: cropTop rows (the status bar) are cut so the frame fits the template. // The game needs switches for this: language, scene, fixed seed, no ads / tutorial, freeze. See the store-screenshots skill. import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; @@ -22,11 +25,12 @@ import { spawnSync } from 'node:child_process'; import type { ShipConfig } from '../lib/config'; import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; -import { done, log, warn } from '../lib/log'; +import { done, log, step, warn } from '../lib/log'; import { launch } from './browser'; import { checkFrameFolder } from './check'; -import { adbAppLocaleArgs, adbDemoExitArgs, adbDemoModeArgs, adbForceStopArgs, adbScreencapArgs, adbStartArgs, cropArgs, defaultCropTop, pickSimulator, - shotsFor, simLaunchArgs, simOpenUrlArgs, simScreenshotArgs, simStatusBarArgs, type Source } from './devices'; +import { adbAppLocaleArgs, adbDemoExitArgs, adbDemoModeArgs, adbForceStopArgs, adbInstallArgs, adbScreencapArgs, adbStartArgs, adbStateArgs, adbTarget, + cropArgs, defaultCropTop, fill, pickSimulator, shotsFor, simBootArgs, simBootStatusArgs, simInstallArgs, simLaunchArgs, simOpenUrlArgs, + simScreenshotArgs, simShutdownArgs, simStatusBarArgs, simStatusBarClearArgs, simTarget, SOURCES, type Source, TOOL_HINTS, validateCapture } from './devices'; import { DEFAULT_PHONE, DEFAULT_TABLET } from './lib'; import { imageInfo } from './spec'; @@ -46,6 +50,12 @@ export function adbPath(): string { return existsSync(p) ? p : 'adb'; } +/** Throws the install hint when a tool is neither a path that exists nor on PATH. */ +function requireTool(cmd: string, name = cmd): void { + if (existsSync(cmd) || Bun.which(cmd)) return; + throw new Error(TOOL_HINTS[name] ?? `${name} not found on PATH`); +} + /** Language ids -> the locale each source should use (App Store locale for iOS, first Play code for Android). */ function localeOf(config: ShipConfig, lang: string, source: Source): string { const l = config.languages.find(x => x.id === lang); @@ -54,7 +64,7 @@ function localeOf(config: ShipConfig, lang: string, source: Source): string { return (Array.isArray(p) ? p[0] : p) ?? lang; } -/** Crop the status bar off a full-screen capture and store it as a frame. */ +/** Crop the status bar off a full-screen capture and store it as a 24-bit RGB frame. */ function storeFrame(tmp: string, out: string, cropTop: number | undefined): void { const h = imageInfo(readFileSync(tmp)).h; if (!h) throw new Error('screenshot is not a PNG'); @@ -67,26 +77,42 @@ export async function run(ctx: Ctx): Promise { const shots = need(config.shots, 'shots'); const cap = need(shots.capture, 'shots.capture'); const a = ctx.args; + const dry = a.has('dry'); const source = (a.get('source') ?? cap.source ?? 'web') as Source; + if (!SOURCES.includes(source)) throw new Error(`--source: one of ${SOURCES.join(', ')}`); + const problems = validateCapture({ ...cap, source }); + if (problems.length) throw new Error(`shots.capture:\n ${problems.join('\n ')}`); const langs = a.list('lang').length ? a.list('lang') : config.languages.map(l => l.id); const only = a.list('only'); const devices: Device[] = a.get('device') ? [a.get('device') as Device] : ['phone', 'tablet']; + if (devices.some(d => d !== 'phone' && d !== 'tablet')) throw new Error('--device: phone | tablet'); const framesDir = resolve(shots.frames); const tmpDir = join(root, '.storebound', 'tmp'); - mkdirSync(tmpDir, { recursive: true }); - const target = (lang: string, device: Device, name: string) => { const d = join(framesDir, lang, device); mkdirSync(d, { recursive: true }); return join(d, `${name}.png`); }; - let failed = 0, n = 0; + const target = (lang: string, device: Device, name: string) => { const d = join(framesDir, lang, device); if (!dry) mkdirSync(d, { recursive: true }); return join(d, `${name}.png`); }; + const total = langs.length * devices.reduce((t, d) => t + shotsFor(cap, d, only).length, 0); + let failed = 0, n = 0, i = 0; + const progress = (what: string) => log('shots', step(++i, total, what)); + /** Runs a simctl / adb step, or prints it with --dry. */ + const exec = (cmd: string, args: string[], o: { allowFail?: boolean; timeout?: number } = {}) => { + if (dry) { log('shots', `would run: ${cmd === 'xcrun' || cmd === 'ffmpeg' ? cmd : 'adb'} ${args.join(' ')}`); return { out: Buffer.alloc(0), err: '', code: 0 }; } + return sh(cmd, args, o); + }; if (source === 'folder') { const dir = resolve(cap.folder ?? shots.frames); const issues = checkFrameFolder(config, dir, langs); - for (const i of issues) warn('shots', `frames/${i.file}: ${i.msg}`); + for (const x of issues) warn('shots', `frames/${x.file}: ${x.msg}`); if (issues.length) throw new Error(`${issues.length} frame problems in ${dir} (expected //.png)`); if (dir !== framesDir) warn('shots', `frames are read from shots.frames (${shots.frames}); point it at ${cap.folder} or copy them there`); return done('shots', `folder frames ok: ${dir}`); } + if (!dry) mkdirSync(tmpDir, { recursive: true }); if (source === 'web') { + if (dry) { + for (const lang of langs) for (const device of devices) for (const [name, s] of shotsFor(cap, device, only)) progress(`${lang}/${device}/${name}.png <- ${cap.baseUrl}${(s.path ?? '/').replaceAll('{lang}', lang)}`); + return done('shots', `capture planned (dry run): ${total} frames from web`); + } const dims = { phone: { ...DEFAULT_PHONE, ...shots.phone }, tablet: { ...DEFAULT_TABLET, ...shots.tablet } }; const browser = await launch(root, { headless: true, args: ['--mute-audio', '--ignore-gpu-blocklist', '--enable-webgl', '--enable-gpu'] }); try { @@ -106,7 +132,7 @@ export async function run(ctx: Ctx): Promise { await page.waitForTimeout(s.delayMs ?? 1000); await page.screenshot({ path: target(lang, device, name) }); n++; - log('shots', `${lang}/${device}/${name}.png${errs.length ? ' (page errors: ' + errs.join(' | ').slice(0, 200) + ')' : ''}`); + progress(`${lang}/${device}/${name}.png${errs.length ? ' (page errors: ' + errs.join(' | ').slice(0, 200) + ')' : ''}`); } catch (e) { failed++; warn('shots', `${lang}/${device}/${name}: ${(e as Error).message.slice(0, 300)}`); } await c.close(); } @@ -115,33 +141,42 @@ export async function run(ctx: Ctx): Promise { if (source === 'ios-sim') { const ios = need(cap.ios, 'shots.capture.ios'); - const list = sh('xcrun', ['simctl', 'list', 'devices', '-j']).out.toString(); + if (!dry) { requireTool('xcrun'); requireTool('ffmpeg'); } + const list = dry && !Bun.which('xcrun') ? '{"devices":{}}' : sh('xcrun', ['simctl', 'list', 'devices', '-j']).out.toString(); for (const device of devices) { - const want = device === 'tablet' ? ios.devices?.tablet : ios.devices?.phone ?? ios.device; + const want = simTarget(ios, device); const todo = shotsFor(cap, device, only); if (!todo.length) continue; - if (!want) { warn('shots', `no ios.devices.${device}: ${todo.length} ${device} shots skipped`); continue; } - const sim = pickSimulator(list, want); - if (!sim) throw new Error(`no simulator "${want}" (xcrun simctl list devices)`); - if (sim.state !== 'Booted') { + if (!want) { warn('shots', `no shots.capture.ios.devices.${device}: ${todo.length} ${device} shots skipped`); i += todo.length * langs.length; continue; } + const sim = pickSimulator(list, want) ?? (dry ? { udid: want, name: want, state: 'Shutdown' } : null); + if (!sim) throw new Error(`no simulator "${want}" (xcrun simctl list devices; create one in Xcode > Window > Devices and Simulators)`); + const bootedByUs = sim.state !== 'Booted'; + if (bootedByUs) { log('shots', `booting ${sim.name} (${sim.udid})`); - sh('xcrun', ['simctl', 'boot', sim.udid], { allowFail: true }); - sh('xcrun', ['simctl', 'bootstatus', sim.udid, '-b'], { timeout: 300_000 }); - } - if (ios.app) { log('shots', `installing ${ios.app}`); sh('xcrun', ['simctl', 'install', sim.udid, resolve(ios.app)], { timeout: 300_000 }); } - if (ios.statusBar !== false) sh('xcrun', simStatusBarArgs(sim.udid)); - for (const lang of langs) for (const [name, s] of todo) { - try { - const locale = localeOf(config, lang, 'ios-sim'); - sh('xcrun', simLaunchArgs(sim.udid, ios.bundleId, { lang, locale, shot: name, baseArgs: ios.args, args: s.args })); - if (s.url) { await Bun.sleep(1500); sh('xcrun', simOpenUrlArgs(sim.udid, s.url.replaceAll('{lang}', lang).replaceAll('{shot}', name))); } - await Bun.sleep(s.delayMs ?? 2500); - const tmp = join(tmpDir, `sim-${name}.png`); - sh('xcrun', simScreenshotArgs(sim.udid, tmp)); - storeFrame(tmp, target(lang, device, name), cap.cropTop); - n++; - log('shots', `${lang}/${device}/${name}.png (${sim.name})`); - } catch (e) { failed++; warn('shots', `${lang}/${device}/${name}: ${(e as Error).message.slice(0, 300)}`); } + exec('xcrun', simBootArgs(sim.udid), { allowFail: true }); + exec('xcrun', simBootStatusArgs(sim.udid), { timeout: 300_000 }); + } else log('shots', `using running simulator ${sim.name} (${sim.udid})`); + try { + if (ios.app) { log('shots', `installing ${ios.app}`); exec('xcrun', simInstallArgs(sim.udid, resolve(ios.app)), { timeout: 300_000 }); } + if (ios.statusBar !== false) exec('xcrun', simStatusBarArgs(sim.udid)); + for (const lang of langs) for (const [name, s] of todo) { + try { + const locale = localeOf(config, lang, 'ios-sim'); + exec('xcrun', simLaunchArgs(sim.udid, ios.bundleId, { lang, locale, shot: name, baseArgs: ios.args, args: s.args })); + if (s.url) { if (!dry) await Bun.sleep(1500); exec('xcrun', simOpenUrlArgs(sim.udid, fill(s.url, { lang, locale, shot: name }))); } + const out = target(lang, device, name); + if (dry) { progress(`${lang}/${device}/${name}.png (${sim.name}, would wait ${s.delayMs ?? 2500} ms)`); continue; } + await Bun.sleep(s.delayMs ?? 2500); + const tmp = join(tmpDir, `sim-${name}.png`); + sh('xcrun', simScreenshotArgs(sim.udid, tmp)); + storeFrame(tmp, out, cap.cropTop); + n++; + progress(`${lang}/${device}/${name}.png (${sim.name})`); + } catch (e) { failed++; i++; warn('shots', `${lang}/${device}/${name}: ${(e as Error).message.slice(0, 300)}`); } + } + } finally { + if (ios.statusBar !== false) exec('xcrun', simStatusBarClearArgs(sim.udid), { allowFail: true }); + if (bootedByUs && !a.has('keep-booted')) { log('shots', `shutting down ${sim.name} (booted by storebound; --keep-booted keeps it)`); exec('xcrun', simShutdownArgs(sim.udid), { allowFail: true }); } } } } @@ -149,39 +184,44 @@ export async function run(ctx: Ctx): Promise { if (source === 'android-emu') { const and = need(cap.android, 'shots.capture.android'); const adb = adbPath(); + if (!dry) { requireTool(adb, 'adb'); requireTool('ffmpeg'); } for (const device of devices) { const todo = shotsFor(cap, device, only); if (!todo.length) continue; - const serial = device === 'tablet' ? and.serials?.tablet : and.serials?.phone ?? and.serial; - if (device === 'tablet' && !serial) { warn('shots', `no android.serials.tablet: ${todo.length} tablet shots skipped`); continue; } - const state = sh(adb, [...(serial ? ['-s', serial] : []), 'get-state'], { allowFail: true }); - if (state.code !== 0) throw new Error(`no Android device${serial ? ` ${serial}` : ''} (adb devices): start an emulator or plug in a device`); - if (and.apk) { log('shots', `installing ${and.apk}`); sh(adb, [...(serial ? ['-s', serial] : []), 'install', '-r', resolve(and.apk)], { timeout: 300_000 }); } - if (and.demoMode !== false) for (const args of adbDemoModeArgs(serial)) sh(adb, args, { allowFail: true }); - for (const lang of langs) { - const locale = localeOf(config, lang, 'android-emu'); - if (and.appLocale !== false) { - const r = sh(adb, adbAppLocaleArgs(and.package, locale, serial), { allowFail: true }); - if (r.code !== 0) warn('shots', `per-app language needs Android 13+; set the language from a launch extra instead (${r.err.trim().slice(0, 120)})`); - } - for (const [name, s] of todo) { - try { - sh(adb, adbForceStopArgs(and.package, serial)); - sh(adb, adbStartArgs(and.package, { lang, locale, shot: name, url: s.url, activity: and.activity, extras: s.extras }, serial)); - await Bun.sleep(s.delayMs ?? 2500); - const tmp = join(tmpDir, `adb-${name}.png`); - writeFileSync(tmp, sh(adb, adbScreencapArgs(serial)).out); - storeFrame(tmp, target(lang, device, name), cap.cropTop); - n++; - log('shots', `${lang}/${device}/${name}.png${serial ? ` (${serial})` : ''}`); - } catch (e) { failed++; warn('shots', `${lang}/${device}/${name}: ${(e as Error).message.slice(0, 300)}`); } + const serial = adbTarget(and, device); + if (device === 'tablet' && !serial) { warn('shots', `no shots.capture.android.serials.tablet: ${todo.length} tablet shots skipped`); i += todo.length * langs.length; continue; } + if (!dry && sh(adb, adbStateArgs(serial), { allowFail: true }).code !== 0) throw new Error(`no Android device${serial ? ` ${serial}` : ''} (adb devices): start an emulator or plug in a device; with several, set shots.capture.android.serial`); + log('shots', `using Android device ${serial ?? '(the only one)'}`); + if (and.apk) { log('shots', `installing ${and.apk}`); exec(adb, adbInstallArgs(resolve(and.apk), serial), { timeout: 300_000 }); } + if (and.demoMode !== false) for (const args of adbDemoModeArgs(serial)) exec(adb, args, { allowFail: true }); + try { + for (const lang of langs) { + const locale = localeOf(config, lang, 'android-emu'); + if (and.appLocale !== false) { + const r = exec(adb, adbAppLocaleArgs(and.package, locale, serial), { allowFail: true }); + if (r.code !== 0) warn('shots', `per-app language needs Android 13+; set the language from a launch extra instead (${r.err.trim().slice(0, 120)})`); + } + for (const [name, s] of todo) { + try { + exec(adb, adbForceStopArgs(and.package, serial)); + exec(adb, adbStartArgs(and.package, { lang, locale, shot: name, url: s.url, activity: and.activity, extras: s.extras }, serial)); + const out = target(lang, device, name); + if (dry) { progress(`${lang}/${device}/${name}.png (would wait ${s.delayMs ?? 2500} ms, screencap)`); continue; } + await Bun.sleep(s.delayMs ?? 2500); + const tmp = join(tmpDir, `adb-${name}.png`); + writeFileSync(tmp, sh(adb, adbScreencapArgs(serial)).out); + storeFrame(tmp, out, cap.cropTop); + n++; + progress(`${lang}/${device}/${name}.png${serial ? ` (${serial})` : ''}`); + } catch (e) { failed++; i++; warn('shots', `${lang}/${device}/${name}: ${(e as Error).message.slice(0, 300)}`); } + } } + } finally { + if (and.demoMode !== false) exec(adb, adbDemoExitArgs(serial), { allowFail: true }); } - if (and.demoMode !== false) sh(adb, adbDemoExitArgs(serial), { allowFail: true }); } } - if (!existsSync(framesDir)) mkdirSync(framesDir, { recursive: true }); if (failed) throw new Error(`${failed} captures failed (${n} ok)`); - done('shots', `capture done: ${n} frames from ${source}`); + done('shots', dry ? `capture planned (dry run): ${total} frames from ${source}` : `capture done: ${n} frames from ${source} in ${framesDir}`); } diff --git a/cli/shots/devices.ts b/cli/shots/devices.ts index 6127829d..c0247fb7 100644 --- a/cli/shots/devices.ts +++ b/cli/shots/devices.ts @@ -43,6 +43,23 @@ export function validateCapture(c: ShotsCapture | undefined): string[] { return e; } +/** Install hints for the external tools each source needs (shown when the tool is not on PATH). */ +export const TOOL_HINTS: Record = { + xcrun: 'xcrun not found: the iOS Simulator needs macOS with Xcode (App Store) and its command line tools (xcode-select --install)', + adb: 'adb not found: install the Android SDK platform-tools (Android Studio > SDK Manager) and set ANDROID_HOME, or put adb on PATH', + ffmpeg: 'ffmpeg not found: install it (brew install ffmpeg, apt install ffmpeg, winget install ffmpeg); it crops the status bar off the screenshots', +}; + +/** Simulator name / UDID for a device class: ios.devices., phone falls back to ios.device. */ +export function simTarget(ios: NonNullable, device: 'phone' | 'tablet'): string | undefined { + return device === 'tablet' ? ios.devices?.tablet : ios.devices?.phone ?? ios.device; +} + +/** adb serial for a device class: android.serials., phone falls back to android.serial (undefined = the only device). */ +export function adbTarget(and: NonNullable, device: 'phone' | 'tablet'): string | undefined { + return device === 'tablet' ? and.serials?.tablet : and.serials?.phone ?? and.serial; +} + /** Which shots run on which device class. */ export function shotsFor(c: ShotsCapture, device: 'phone' | 'tablet', only: string[] = []): [string, ShotSpec][] { return Object.entries(c.shots ?? {}).filter(([name, s]) => (!only.length || only.includes(name)) && ((s.device ?? 'phone') === 'both' || (s.device ?? 'phone') === device)); @@ -80,6 +97,11 @@ export function simLaunchArgs(udid: string, bundleId: string, o: { lang: string; } export const simOpenUrlArgs = (udid: string, url: string): string[] => ['simctl', 'openurl', udid, url]; +export const simBootArgs = (udid: string): string[] => ['simctl', 'boot', udid]; +export const simBootStatusArgs = (udid: string): string[] => ['simctl', 'bootstatus', udid, '-b']; +export const simShutdownArgs = (udid: string): string[] => ['simctl', 'shutdown', udid]; +export const simStatusBarClearArgs = (udid: string): string[] => ['simctl', 'status_bar', udid, 'clear']; +export const simInstallArgs = (udid: string, app: string): string[] => ['simctl', 'install', udid, app]; export const simScreenshotArgs = (udid: string, out: string): string[] => ['simctl', 'io', udid, 'screenshot', '--type=png', '--mask=ignored', out]; export const simRecordArgs = (udid: string, out: string): string[] => ['simctl', 'io', udid, 'recordVideo', '--codec=h264', '--mask=ignored', '--force', out]; @@ -112,6 +134,8 @@ export const androidLocale = (l: string): string => l.replace('_', '-'); * game from a launch extra instead (see `extras` with "{lang}"). */ export const adbAppLocaleArgs = (pkg: string, lang: string, serial?: string): string[] => adb(serial, 'shell', 'cmd', 'locale', 'set-app-locales', pkg, '--locales', androidLocale(lang)); +export const adbStateArgs = (serial?: string): string[] => adb(serial, 'get-state'); +export const adbInstallArgs = (apk: string, serial?: string): string[] => adb(serial, 'install', '-r', apk); export const adbForceStopArgs = (pkg: string, serial?: string): string[] => adb(serial, 'shell', 'am', 'force-stop', pkg); /** `am start` for one shot: a deep link (VIEW intent to the package) or the launch activity, plus typed extras. */