572 lines
38 KiB
JavaScript
572 lines
38 KiB
JavaScript
// The Amstrad CPC window: remaking a CPC game from its .dsk (AGENTS.md §12) with dsk2jumphp's headless emulator and tools,
|
||
// run in Docker by ide/src/Cpc/CpcCommands.php. Three tabs:
|
||
// - Run: the disc (remembered per project), N frames, keys typed on a timeline; the screenshots played as a film;
|
||
// - Debug: watched writes, readers / writers, registers at PCs, trace, alarm, dumps (hex, registers, disassembly with what
|
||
// ran, the dump's screen), pokes (infinite lives...), two dumps compared; the logs as tables;
|
||
// - Extract: palette, screen, sprites, tiles, texts from a dump; sound segments of the AY log, rendered to WAV / OGG;
|
||
// "Save to assets" copies a result into a game and adds its commands to the game's tools/extract/extract.sh.
|
||
// Everything the tools write stays in var/cpc/ (never committed). Claude: cpc_* tools at the end.
|
||
import { backend } from './backend.js';
|
||
import { el, clear, icon, notify, prefs, t, prompt, confirm } from './ui.js';
|
||
import { zoom } from './zoom.js';
|
||
|
||
const KEY_NAMES = ['joy_up', 'joy_down', 'joy_left', 'joy_right', 'joy_fire', 'joy_fire2', 'space', 'return', 'enter', 'shift', 'control', 'esc', 'tab',
|
||
'caps', 'del', 'copy', 'clr', 'up', 'down', 'left', 'right', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9'];
|
||
// the DOM's append() writes null as text: what is not there is left out
|
||
const put = (parent, ...kids) => parent.append(...kids.filter((k) => k !== null && k !== undefined && k !== false));
|
||
const REGS = ['a', 'f', 'b', 'c', 'd', 'e', 'h', 'l', 'ix', 'iy', 'sp', 'pc'];
|
||
const hex4 = (n) => Number(n).toString(16).padStart(4, '0');
|
||
const DEFAULT_SPEC = { frames: 500, shotEvery: 10, keys: [], boot: 'disc', pc: '', label: '', dumps: '', watch: '', readers: '', writers: '', regs: '', regsIx: 0,
|
||
trace: '', alarm: '', breaks: '', pokes: [] };
|
||
|
||
export class CpcPanel {
|
||
constructor(app) {
|
||
this.app = app;
|
||
this.node = el('div.cryo-view.cpc-view');
|
||
this.tab = prefs.get('cpcTab', 'run');
|
||
this.state = null;
|
||
this.runs = [];
|
||
this.run = null; // the run shown (cpc.result)
|
||
this.busy = null; // what is running ('run', 'extract'...)
|
||
this.spec = { ...DEFAULT_SPEC, ...prefs.get('cpcSpec:' + (app.projectKey || ''), {}) };
|
||
this.film = { index: 0, playing: false, timer: null, speed: 1 };
|
||
this.urls = new Map(); // var/cpc path -> data URL
|
||
this.dump = { file: null, addr: '0000', data: null, disasm: null, screen: null, from: '', to: '' };
|
||
this.extracted = [];
|
||
this.results = { pens: null, text: '', segments: null, diff: '', loop: '' };
|
||
this.render();
|
||
// a .dsk opened in the project: this window, on that disc
|
||
const editors = app.editors;
|
||
if (editors?.open) {
|
||
const open = editors.open.bind(editors);
|
||
editors.open = (path, options = {}) => (/\.dsk$/i.test(path || '') ? this.openDisc(path) : open(path, options));
|
||
}
|
||
}
|
||
|
||
title() { return 'Amstrad CPC'; }
|
||
|
||
actions() {
|
||
const b = (title, ico, fn) => el('button', { title: t(title), onclick: fn }, icon(ico));
|
||
return [
|
||
b('Choose the .dsk disc…', 'disk', () => this.chooseDisc()),
|
||
b('Refresh', 'refresh', () => this.refresh()),
|
||
];
|
||
}
|
||
|
||
shown() { this.refresh(); }
|
||
|
||
/** whether this project is a CPC remake (or has a disc): the window is then in the tool stripe */
|
||
async check() {
|
||
try { this.state = await backend.invoke('cpc.state', {}); } catch { return false; }
|
||
const kinds = (this.app.project?.modules || []).map((m) => m.kind);
|
||
if (this.state.relevant || kinds.includes('cpc')) this.enable();
|
||
return this.state.relevant;
|
||
}
|
||
|
||
enable() {
|
||
if (this.app.tools.cpc) return;
|
||
this.app.tools.cpc = { id: 'cpc', side: 'right', label: 'Amstrad CPC', icon: 'disk', view: this, key: null };
|
||
zoom.define('cpc', { kind: 'pct', label: 'Amstrad CPC' });
|
||
this.app.renderStripes();
|
||
}
|
||
|
||
async openDisc(path) {
|
||
try {
|
||
await backend.invoke('cpc.disc.set', { path });
|
||
this.enable();
|
||
this.setTab('run');
|
||
this.app.showTool('cpc');
|
||
notify(t('The Amstrad CPC window runs this disc: choose the frames and the keys, then Run.'), 'info', { title: 'Amstrad CPC' });
|
||
} catch (e) { notify(String(e.message || e), 'error'); }
|
||
return null;
|
||
}
|
||
|
||
async refresh() {
|
||
try {
|
||
[this.state, this.runs, this.extracted] = await Promise.all([backend.invoke('cpc.state', {}), backend.invoke('cpc.runs', {}), backend.invoke('cpc.extracted', {})]);
|
||
if (!this.run && this.runs.length) this.run = await backend.invoke('cpc.result', { run: this.runs[0].id }).catch(() => null);
|
||
} catch (e) { notify(String(e.message || e), 'error', { title: 'Amstrad CPC' }); }
|
||
this.render();
|
||
}
|
||
|
||
saveSpec() { prefs.set('cpcSpec:' + (this.app.projectKey || ''), this.spec); }
|
||
|
||
setTab(tab) { this.tab = tab; prefs.set('cpcTab', tab); this.render(); }
|
||
|
||
async chooseDisc() {
|
||
const f = await backend.invoke('native.open', { filters: { 'Amstrad CPC disc': ['dsk', 'DSK'] }, title: t('The .dsk disc of the game') }).catch(() => null);
|
||
if (!f) return;
|
||
try { await backend.invoke('cpc.disc.set', { path: f }); } catch (e) { notify(String(e.message || e), 'error'); }
|
||
this.refresh();
|
||
}
|
||
|
||
async chooseRoms(folder) {
|
||
const f = await backend.invoke('native.open', folder ? { folder: true, title: t('A folder with the CPC 6128 ROMs') } : { title: t('The CPC 6128 ROM (OS + BASIC)') }).catch(() => null);
|
||
if (!f) return;
|
||
try { await backend.invoke('cpc.roms.set', { path: f }); } catch (e) { notify(String(e.message || e), 'error'); }
|
||
this.refresh();
|
||
}
|
||
|
||
async url(path) {
|
||
if (!this.urls.has(path)) this.urls.set(path, backend.invoke('cpc.file', { path }).then((r) => r.url).catch(() => null));
|
||
return this.urls.get(path);
|
||
}
|
||
|
||
// rendering ----------------------------------------------------------------------------------------------
|
||
|
||
render() {
|
||
clear(this.node);
|
||
const tabs = [['run', 'Run'], ['debug', 'Debug'], ['extract', 'Extract']];
|
||
this.node.append(el('div.cryo-tabs', {}, ...tabs.map(([id, label]) => el('button' + (this.tab === id ? '.on' : ''), { onclick: () => this.setTab(id) }, t(label)))));
|
||
this.body = el('div.cryo-body');
|
||
this.node.append(this.body);
|
||
if (this.state && this.state.docker === false) {
|
||
put(this.body, el('div.cryo-warn', {}, t('Docker does not answer: the CPC tools run in Docker (built once, a minute or two).')));
|
||
} else if (this.state && !this.state.imageReady) {
|
||
put(this.body, el('div.pub-faint', {}, t('The first run builds the CPC tools\' Docker image (once, a minute or two).')));
|
||
}
|
||
if (this.busy) put(this.body, el('div.cpc-busy', {}, el('span.spinner'), ' ', t(this.busy)));
|
||
if (this.tab === 'run') this.renderRun();
|
||
else if (this.tab === 'debug') this.renderDebug();
|
||
else this.renderExtract();
|
||
}
|
||
|
||
field(label, input, hint) {
|
||
return el('label.cpc-field', { title: hint ? t(hint) : '' }, el('span', {}, t(label)), input);
|
||
}
|
||
|
||
input(key, { width = 80, placeholder = '', type = 'text' } = {}) {
|
||
return el('input.input.cpc-in', { type, value: this.spec[key] ?? '', placeholder, style: { width: width + 'px' },
|
||
oninput: (e) => { this.spec[key] = type === 'number' ? Number(e.target.value) : e.target.value; this.saveSpec(); } });
|
||
}
|
||
|
||
renderRun() {
|
||
const s = this.state || {};
|
||
const disc = s.disc ? s.disc.split(/[\\/]/).pop() : null;
|
||
put(this.body, el('div.cryo-row', {},
|
||
el('b', {}, t('Disc')), disc ? el('code', { title: s.disc }, disc) : el('span.pub-faint', {}, t('none')),
|
||
s.disc && !s.discExists ? el('span.cryo-error', {}, t('not found')) : null,
|
||
el('button.btn.small', { onclick: () => this.chooseDisc() }, icon('disk'), t('Choose the .dsk…')),
|
||
el('select.input.cpc-in', { style: { width: 'auto' }, onchange: (e) => { this.spec.boot = e.target.value; this.saveSpec(); this.render(); } },
|
||
el('option', { value: 'disc', selected: this.spec.boot !== 'rom' }, t('Boot sector (no ROM)')),
|
||
el('option', { value: 'rom', selected: this.spec.boot === 'rom' }, t('CPC 6128 ROM (BASIC)')))));
|
||
if (this.spec.boot === 'rom') {
|
||
const r = s.romFiles || {};
|
||
put(this.body, el('div.cryo-row', {},
|
||
el('span', {}, t('ROMs from your computer (never downloaded):')), el('code', {}, r.os ? r.os.split(/[\\/]/).pop() : t('no OS ROM')), r.amsdos ? el('code', {}, r.amsdos.split(/[\\/]/).pop()) : null,
|
||
el('button.btn.small', { onclick: () => this.chooseRoms(false) }, t('ROM file…')), el('button.btn.small', { onclick: () => this.chooseRoms(true) }, t('ROM folder…'))),
|
||
el('div.pub-faint', {}, t('BASIC is ready around frame 100: type for example RUN"DISC then RETURN at frame 120.')));
|
||
}
|
||
put(this.body, el('div.cryo-row', {},
|
||
this.field('Frames', this.input('frames', { type: 'number', width: 80 }), '50 frames = 1 s of CPC time'),
|
||
this.field('Picture every', this.input('shotEvery', { type: 'number', width: 60 }), 'frames between two screenshots'),
|
||
this.spec.boot !== 'rom' ? this.field('Start PC', this.input('pc', { width: 60, placeholder: '100' }), 'boot sector start (110 for a CP/M parameter block)') : null,
|
||
this.field('Label', this.input('label', { width: 140, placeholder: t('optional') })),
|
||
el('button.btn.primary', { disabled: !!this.busy || !s.discExists && this.spec.boot !== 'rom', onclick: () => this.start() }, icon('play'), t('Run'))));
|
||
put(this.body, this.keysEditor());
|
||
if (this.run) put(this.body, this.filmView());
|
||
put(this.body, this.runsList());
|
||
}
|
||
|
||
keysEditor() {
|
||
const keys = this.spec.keys;
|
||
const save = () => { this.saveSpec(); };
|
||
const list = el('datalist', { id: 'cpcKeyNames' }, ...KEY_NAMES.map((k) => el('option', { value: k })));
|
||
const rows = keys.map((k, i) => el('tr', {},
|
||
el('td', {}, el('input.input.cpc-in', { type: 'number', min: 0, value: k.frame ?? 0, style: { width: '70px' }, oninput: (e) => { k.frame = Number(e.target.value); save(); } })),
|
||
el('td', {}, k.text !== undefined
|
||
? el('input.input.cpc-in', { value: k.text, placeholder: 'RUN"DISC\\n', title: t('Text typed (\\n = RETURN)'), oninput: (e) => { k.text = e.target.value; save(); } })
|
||
: el('input.input.cpc-in', { value: k.key || '', list: 'cpcKeyNames', style: { width: '110px' }, title: t('A key: a letter, a digit, row.bit, or a name (space, joy_fire...)'), oninput: (e) => { k.key = e.target.value; save(); } })),
|
||
el('td', {}, k.text !== undefined ? '' : el('input.input.cpc-in', { type: 'number', min: 1, value: k.hold ?? 5, title: t('Held for N frames'), style: { width: '56px' }, oninput: (e) => { k.hold = Number(e.target.value); save(); } })),
|
||
el('td', {}, el('button.cryo-del', { title: t('Remove'), onclick: () => { keys.splice(i, 1); save(); this.render(); } }, '×'))));
|
||
const add = (entry) => { const last = keys.length ? Number(keys[keys.length - 1].frame || 0) : 0; keys.push({ frame: last + 50, ...entry }); save(); this.render(); };
|
||
return el('div.cpc-keys', {}, list,
|
||
el('div.cryo-row', {}, el('b', {}, t('Keys')), el('span.pub-faint', {}, t('at a frame: a key held N frames, or a text typed')),
|
||
el('span.tw-spacer'), el('button.btn.small', { onclick: () => add({ key: 'space', hold: 5 }) }, t('+ Key')), el('button.btn.small', { onclick: () => add({ text: '' }) }, t('+ Text'))),
|
||
keys.length ? el('table.cryo-table', {}, el('tr', {}, el('th', {}, t('Frame')), el('th', {}, t('Key / text')), el('th', {}, t('Hold')), el('th')), ...rows) : null);
|
||
}
|
||
|
||
filmView() {
|
||
const r = this.run;
|
||
const shots = r.shots || [];
|
||
const head = el('div.cryo-row', {}, el('b', {}, r.label || r.id), el('span.pub-faint', {}, t('{frames} frames in {seconds} s', { frames: r.args?.[2] ?? '?', seconds: r.seconds ?? '?' })),
|
||
r.code ? el('span.cryo-error', {}, t('exit code {code}', { code: r.code })) : null);
|
||
if (!shots.length) return el('div.cpc-film', {}, head, el('p.pub-faint', {}, t('No screenshot in this run (Picture every).')), r.stderr ? el('pre.cryo-out', {}, r.stderr) : null);
|
||
const f = this.film;
|
||
f.index = Math.min(f.index, shots.length - 1);
|
||
const img = el('img.cpc-screen', { alt: '' });
|
||
const label = el('span.cpc-frame');
|
||
const slider = el('input.cpc-slider', { type: 'range', min: 0, max: shots.length - 1, value: f.index, oninput: (e) => show(Number(e.target.value)) });
|
||
const show = async (i) => {
|
||
f.index = Math.max(0, Math.min(shots.length - 1, i));
|
||
slider.value = f.index;
|
||
label.textContent = t('frame {frame}', { frame: shots[f.index].frame }) + ` (${f.index + 1}/${shots.length})`;
|
||
const u = await this.url(shots[f.index].path);
|
||
if (u && shots[f.index] && f.index === Number(slider.value)) img.src = u;
|
||
for (let k = 1; k <= 3; k++) if (shots[f.index + k]) this.url(shots[f.index + k].path);
|
||
};
|
||
const playBtn = el('button.btn.small', { title: t('Play / pause'), onclick: () => toggle() }, f.playing ? '❚❚' : '►');
|
||
const step = () => {
|
||
if (!f.playing || !img.isConnected) { f.playing = false; return; }
|
||
if (f.index >= shots.length - 1) { f.playing = false; playBtn.textContent = '►'; return; }
|
||
show(f.index + 1);
|
||
const gap = shots[f.index + 1] ? shots[f.index + 1].frame - shots[f.index].frame : 10;
|
||
f.timer = setTimeout(step, Math.max(16, (gap * 20) / f.speed));
|
||
};
|
||
const toggle = () => {
|
||
f.playing = !f.playing;
|
||
playBtn.textContent = f.playing ? '❚❚' : '►';
|
||
clearTimeout(f.timer);
|
||
if (f.playing) { if (f.index >= shots.length - 1) show(0); step(); }
|
||
};
|
||
show(f.index);
|
||
return el('div.cpc-film', {}, head, el('div.cpc-screen-box', {}, img),
|
||
el('div.cryo-row', {},
|
||
el('button.btn.small', { title: t('Previous picture'), onclick: () => show(f.index - 1) }, '‹'), playBtn,
|
||
el('button.btn.small', { title: t('Next picture'), onclick: () => show(f.index + 1) }, '›'),
|
||
el('select.input.cpc-in', { style: { width: '70px' }, onchange: (e) => { f.speed = Number(e.target.value); } },
|
||
...[0.25, 0.5, 1, 2, 4].map((s) => el('option', { value: s, selected: s === f.speed }, s + '×'))),
|
||
label),
|
||
slider);
|
||
}
|
||
|
||
runsList() {
|
||
if (!this.runs.length) return el('div');
|
||
return el('details.cpc-runs', { open: this.runs.length < 6 }, el('summary', {}, t('Runs ({n})', { n: this.runs.length })),
|
||
el('div.cryo-files', {}, ...this.runs.map((r) => el('div.cryo-file' + (this.run?.id === r.id ? '.on' : ''), {},
|
||
el('a', { href: '#', onclick: (e) => { e.preventDefault(); this.load(r.id); } }, (r.label ? r.label + ' · ' : '') + r.id),
|
||
el('span.pub-faint', {}, t('{n} frames', { n: r.frames })),
|
||
el('button.cryo-del', { title: t('Delete this run'), onclick: () => this.deleteRun(r.id) }, '×')))));
|
||
}
|
||
|
||
async load(id) {
|
||
try { this.run = await backend.invoke('cpc.result', { run: id }); } catch (e) { notify(String(e.message || e), 'error'); }
|
||
this.film.index = 0;
|
||
this.dump = { ...this.dump, file: null, data: null, disasm: null, screen: null };
|
||
this.render();
|
||
}
|
||
|
||
async deleteRun(id) {
|
||
if (!(await confirm(t('Delete this run?'), t('Its screenshots, dumps and logs in var/cpc/runs/ are deleted.'), { ok: 'Delete', danger: true }))) return;
|
||
await backend.invoke('cpc.run.delete', { run: id }).catch(() => null);
|
||
if (this.run?.id === id) this.run = null;
|
||
this.refresh();
|
||
}
|
||
|
||
/** one run of the emulator with the whole form (Run and Debug share it) */
|
||
async start(extra = {}) {
|
||
if (this.busy) return null;
|
||
this.busy = this.state?.imageReady ? 'Running the emulator…' : 'Building the CPC tools (once), then running…';
|
||
this.render();
|
||
let result = null;
|
||
try {
|
||
const spec = { ...this.spec, ...extra };
|
||
result = await backend.invoke('cpc.run', { spec });
|
||
this.run = result;
|
||
this.film.index = 0;
|
||
this.dump = { ...this.dump, file: result.dumps?.[0]?.file || null, data: null, disasm: null, screen: null };
|
||
if (result.code) notify(result.stderr || t('exit code {code}', { code: result.code }), 'error', { title: 'Amstrad CPC' });
|
||
} catch (e) { notify(String(e.message || e), 'error', { title: 'Amstrad CPC' }); }
|
||
this.busy = null;
|
||
this.state = await backend.invoke('cpc.state', {}).catch(() => this.state);
|
||
this.runs = await backend.invoke('cpc.runs', {}).catch(() => this.runs);
|
||
this.render();
|
||
return result;
|
||
}
|
||
|
||
// Debug --------------------------------------------------------------------------------------------------
|
||
|
||
renderDebug() {
|
||
const s = this.spec;
|
||
put(this.body, el('p.pub-faint', {}, t('Observe, then read: watch writes to find a variable, then disassemble only around the PCs the logs give. These options are added to the run of the Run tab.')),
|
||
el('div.cpc-grid', {},
|
||
this.field('Dumps at frames', this.input('dumps', { width: 120, placeholder: '500, 1000' }), 'the whole machine at the end of those frames'),
|
||
this.field('Watch writes', this.input('watch', { width: 160, placeholder: 'c000-c0ff, fee0' }), 'every write in those ranges (8 at most)'),
|
||
this.field('Readers of', this.input('readers', { width: 100, placeholder: '4000-7fff' }), 'the code that reads that range'),
|
||
this.field('Writers of', this.input('writers', { width: 100, placeholder: '4000-7fff' }), 'the code that writes that range'),
|
||
this.field('Registers at PCs', this.input('regs', { width: 120, placeholder: '2a4c, 3a10' }), 'registers each time those PCs run'),
|
||
this.field('+ bytes at IX', this.input('regsIx', { type: 'number', width: 60 }), 'object structures'),
|
||
this.field('Trace', this.input('trace', { width: 100, placeholder: '0100-7fff' }), 'the order in which code of that range is first reached'),
|
||
this.field('Alarm on', this.input('alarm', { width: 100, placeholder: '0-ff' }), 'when execution first enters that range (crash finder)'),
|
||
this.field('Dump at PC', this.input('breaks', { width: 100, placeholder: '7123' }), 'a dump each time PC reaches that address')),
|
||
this.pokesEditor(),
|
||
el('div.cryo-row', {}, el('button.btn.primary', { disabled: !!this.busy, onclick: () => this.start() }, icon('play'), t('Run with these'))));
|
||
const r = this.run;
|
||
if (!r) return;
|
||
const log = r.log || {};
|
||
const table = (title, cols, rows, total) => (rows?.length ? el('details.cpc-section', { open: rows.length < 40 },
|
||
el('summary', {}, t(title), ' ', el('span.pub-faint', {}, String(total ?? rows.length))),
|
||
el('div.cpc-scroll', {}, el('table.cryo-table', {}, el('tr', {}, ...cols.map(([, h]) => el('th', {}, t(h)))),
|
||
...rows.slice(0, 1500).map((row) => el('tr', {}, ...cols.map(([k, , fmt]) => el('td', {}, fmt ? fmt(row[k], row) : String(row[k] ?? '')))))))) : null);
|
||
const pc = (v) => el('a.cpc-pc', { href: '#', title: t('Disassemble here'), onclick: (e) => { e.preventDefault(); this.disasmAt(v); } }, v);
|
||
put(this.body, el('h4.cpc-h', {}, t('Results of {run}', { run: r.label || r.id })),
|
||
log.alarms?.length ? el('div.cryo-warn', {}, ...log.alarms.map((a) => el('div', {}, a))) : null,
|
||
table('Watched writes', [['frame', 'Frame'], ['addr', 'Address'], ['value', 'Value'], ['pc', 'PC', pc]], log.writes, log.writesTotal),
|
||
table('Disc reads', [['track', 'Track'], ['side', 'Side'], ['sector', 'Sector'], ['bytes', 'Bytes'], ['to', 'Loaded at'], ['pc', 'PC', pc]], log.loads),
|
||
table('Keyboard rows read', [['row', 'Row'], ['pc', 'PC', pc], ['count', 'Times']], log.keys),
|
||
table('Readers', [['pc', 'PC', pc], ['count', 'Reads']], log.readers),
|
||
table('Writers', [['pc', 'PC', pc], ['count', 'Writes']], log.writers),
|
||
table('Registers', [['frame', 'Frame'], ['line', 'Line'], ['pc', 'PC', pc], ['regs', 'Registers', (v) => Object.entries(v || {}).map(([k, x]) => `${k}=${x}`).join(' ')], ['ix', '(IX)']], r.regs?.rows, r.regs?.total),
|
||
table('Trace', [['frame', 'Frame'], ['pc', 'PC', pc]], r.trace?.rows, r.trace?.total));
|
||
put(this.body, this.dumpView());
|
||
}
|
||
|
||
pokesEditor() {
|
||
const pokes = this.spec.pokes;
|
||
const save = () => this.saveSpec();
|
||
const rows = pokes.map((p, i) => el('tr', {},
|
||
el('td', {}, el('select.input.cpc-in', { onchange: (e) => { p.when = e.target.value; save(); this.render(); } },
|
||
el('option', { value: 'frame', selected: p.when === 'frame' }, t('at frame')), el('option', { value: 'pc', selected: p.when === 'pc' }, t('when PC reaches')),
|
||
el('option', { value: 'keep', selected: p.when === 'keep' }, t('keep (when 0, at PC)')))),
|
||
el('td', {}, el('input.input.cpc-in', { value: p.at ?? '', style: { width: '64px' }, placeholder: p.when === 'frame' ? '200' : '2a4c', oninput: (e) => { p.at = e.target.value; save(); } })),
|
||
el('td', {}, el('input.input.cpc-in', { value: p.addr ?? '', style: { width: '64px' }, placeholder: 'fee0', oninput: (e) => { p.addr = e.target.value; save(); } })),
|
||
el('td', {}, el('input.input.cpc-in', { value: p.value ?? '', style: { width: '44px' }, placeholder: '09', oninput: (e) => { p.value = e.target.value; save(); } })),
|
||
el('td', {}, p.when === 'keep' ? el('input.input.cpc-in', { type: 'number', value: p.count ?? 100, style: { width: '60px' }, oninput: (e) => { p.count = Number(e.target.value); save(); } }) : ''),
|
||
el('td', {}, el('button.cryo-del', { title: t('Remove'), onclick: () => { pokes.splice(i, 1); save(); this.render(); } }, '×'))));
|
||
return el('div', {}, el('div.cryo-row', {}, el('b', {}, t('Pokes')), el('span.pub-faint', {}, t('a byte written: cheats (infinite lives), forcing a level, playing music N')),
|
||
el('span.tw-spacer'), el('button.btn.small', { onclick: () => { pokes.push({ when: 'frame', at: '', addr: '', value: '' }); save(); this.render(); } }, t('+ Poke'))),
|
||
pokes.length ? el('table.cryo-table', {}, el('tr', {}, el('th', {}, t('When')), el('th', {}, t('Frame / PC')), el('th', {}, t('Address')), el('th', {}, t('Value')), el('th', {}, t('Times')), el('th')), ...rows) : null);
|
||
}
|
||
|
||
dumpSelect(onchange) {
|
||
const dumps = this.run?.dumps || [];
|
||
if (!this.dump.file && dumps.length) this.dump.file = dumps[0].file;
|
||
return el('select.input.cpc-in', { style: { width: '150px' }, onchange: (e) => { this.dump.file = e.target.value; this.dump.data = null; onchange?.(); this.render(); } },
|
||
...dumps.map((d) => el('option', { value: d.file, selected: d.file === this.dump.file }, d.label)));
|
||
}
|
||
|
||
dumpView() {
|
||
const box = el('div.cpc-dump');
|
||
if (!this.run?.dumps?.length) {
|
||
put(box, el('p.pub-faint', {}, t('No dump in this run: give frames in "Dumps at frames" (or a PC in "Dump at PC") and run again.')));
|
||
return box;
|
||
}
|
||
const d = this.dump;
|
||
const addr = el('input.input.cpc-in', { value: d.addr, style: { width: '70px' }, onkeydown: (e) => { if (e.key === 'Enter') this.peek(addr.value); } });
|
||
put(box, el('h4.cpc-h', {}, t('Dump')), el('div.cryo-row', {}, this.dumpSelect(), t('Address'), addr,
|
||
el('button.btn.small', { onclick: () => this.peek(addr.value) }, t('Show')),
|
||
el('button.btn.small', { onclick: () => this.peek((parseInt(d.addr, 16) - 512 + 65536) % 65536) }, '−512'),
|
||
el('button.btn.small', { onclick: () => this.peek((parseInt(d.addr, 16) + 512) % 65536) }, '+512'),
|
||
el('button.btn.small', { onclick: () => this.dumpScreen() }, t('Its screen'))));
|
||
if (!d.data) { if (d.tried !== d.file) { d.tried = d.file; this.peek(d.addr); } return box; }
|
||
const regs = d.data.regs || {};
|
||
put(box, el('div.cpc-regs', {}, REGS.filter((k) => k in regs).map((k) => [k, regs[k]]).map(([k, v]) => el('span', {}, el('b', {}, k), ' ', k === 'pc' ? el('a.cpc-pc', { href: '#', onclick: (e) => { e.preventDefault(); this.disasmAt(v); } }, v) : v)),
|
||
el('span', {}, el('b', {}, 'mode'), ' ', String(d.data.mode)), el('span', {}, el('b', {}, 'banks'), ' ', (d.data.banks || []).join(' '))));
|
||
const bytes = d.data.hex.match(/../g) || [];
|
||
const lines = [];
|
||
for (let i = 0; i < bytes.length; i += 16) {
|
||
const row = bytes.slice(i, i + 16);
|
||
const ascii = row.map((b) => { const c = parseInt(b, 16); return c >= 32 && c < 127 ? String.fromCharCode(c) : '.'; }).join('');
|
||
lines.push(hex4((d.data.addr + i) & 0xffff) + ' ' + row.join(' ').padEnd(48) + ' ' + ascii);
|
||
}
|
||
put(box, el('pre.cpc-hex', {}, lines.join('\n')));
|
||
if (d.screen) put(box, el('div.cpc-screen-box', {}, el('img.cpc-screen', { src: d.screen })));
|
||
const from = el('input.input.cpc-in', { value: d.from, placeholder: '0100', style: { width: '64px' } });
|
||
const to = el('input.input.cpc-in', { value: d.to, placeholder: '0180', style: { width: '64px' } });
|
||
put(box, el('h4.cpc-h', {}, t('Disassembly')), el('div.cryo-row', {}, t('From'), from, t('to'), to,
|
||
el('button.btn.small', { onclick: () => this.disasm(from.value, to.value) }, t('Disassemble')), el('span.pub-faint', {}, t('* = executed in this run'))));
|
||
if (d.disasm) {
|
||
put(box, el('pre.cpc-hex.cpc-dis', {}, ...d.disasm.map((l) => el('div' + (l.executed ? '.ran' : ''), {}, (l.executed ? '*' : ' ') + l.addr + ' ' + l.bytes.padEnd(10) + ' ' + l.text))));
|
||
}
|
||
// two dumps compared (what changed: lives, level, score...)
|
||
const dumps = this.run.dumps;
|
||
if (dumps.length > 1) {
|
||
const a = el('select.input.cpc-in', {}, ...dumps.map((x, i) => el('option', { value: x.file, selected: i === 0 }, x.label)));
|
||
const b = el('select.input.cpc-in', {}, ...dumps.map((x, i) => el('option', { value: x.file, selected: i === 1 }, x.label)));
|
||
const fv = el('input.input.cpc-in', { placeholder: t('from'), style: { width: '50px' } });
|
||
const tv = el('input.input.cpc-in', { placeholder: t('to'), style: { width: '50px' } });
|
||
const range = el('input.input.cpc-in', { placeholder: 'c000-ffff', style: { width: '90px' } });
|
||
put(box, el('h4.cpc-h', {}, t('Compare two dumps')), el('div.cryo-row', {}, a, b, t('values'), fv, '→', tv, range,
|
||
el('button.btn.small', { onclick: async () => {
|
||
try { this.results.diff = (await backend.invoke('cpc.diff', { run: this.run.id, a: a.value, b: b.value, from: fv.value, to: tv.value, range: range.value })).text || t('nothing changed'); } catch (e) { this.results.diff = String(e.message || e); }
|
||
this.render();
|
||
} }, t('Compare'))), this.results.diff ? el('pre.cryo-out', {}, this.results.diff) : null);
|
||
}
|
||
return box;
|
||
}
|
||
|
||
async peek(addr) {
|
||
const d = this.dump;
|
||
if (!d.file) return;
|
||
try {
|
||
const a = typeof addr === 'number' ? hex4(addr) : String(addr || '0');
|
||
d.data = await backend.invoke('cpc.peek', { run: this.run.id, dump: d.file, addr: a, len: 512 });
|
||
d.addr = hex4(d.data.addr);
|
||
} catch (e) { notify(String(e.message || e), 'error'); return; }
|
||
this.render();
|
||
}
|
||
|
||
async disasm(from, to) {
|
||
const d = this.dump;
|
||
d.from = from; d.to = to;
|
||
try { d.disasm = (await backend.invoke('cpc.disasm', { run: this.run.id, dump: d.file, from, to: to || undefined })).lines; } catch (e) { notify(String(e.message || e), 'error'); }
|
||
this.render();
|
||
}
|
||
|
||
disasmAt(pc) {
|
||
if (!this.dump.file) { notify(t('No dump in this run: give frames in "Dumps at frames" (or a PC in "Dump at PC") and run again.'), 'info'); return; }
|
||
const n = parseInt(pc, 16);
|
||
this.disasm(hex4(Math.max(0, n - 0x20)), hex4(Math.min(0xffff, n + 0x40)));
|
||
}
|
||
|
||
async dumpScreen() {
|
||
try {
|
||
const r = await backend.invoke('cpc.screen', { run: this.run.id, dump: this.dump.file });
|
||
this.dump.screen = await this.url(r.path);
|
||
} catch (e) { notify(String(e.message || e), 'error'); }
|
||
this.render();
|
||
}
|
||
|
||
// Extract ------------------------------------------------------------------------------------------------
|
||
|
||
renderExtract() {
|
||
const r = this.run;
|
||
if (!r) { put(this.body, el('p.pub-faint', {}, t('Run the disc first (Run tab), with dumps at the frames where the graphics are in memory.'))); return; }
|
||
const res = this.results;
|
||
const g = prefs.get('cpcGfx', { addr: '', w: 4, h: 16, n: 8, mode: 0, zigzag: false, scale: 4, count: 64, tw: 2, th: 8, perRow: 16, text: '' });
|
||
const gi = (k, w, ph = '') => el('input.input.cpc-in', { value: g[k] ?? '', placeholder: ph, style: { width: w + 'px' }, oninput: (e) => { g[k] = e.target.value; prefs.set('cpcGfx', g); } });
|
||
if (r.dumps?.length) {
|
||
put(this.body, el('h4.cpc-h', {}, t('Graphics')), el('div.cryo-row', {}, t('Dump'), this.dumpSelect(() => { res.pens = null; }),
|
||
el('button.btn.small', { onclick: () => this.extract('cpc.palette', {}, (x) => { res.pens = x.pens; }) }, t('Palette')),
|
||
el('button.btn.small', { onclick: () => this.extract('cpc.screen', {}) }, t('Screen'))));
|
||
if (res.pens) {
|
||
put(this.body, el('div.cpc-pens', {}, ...res.pens.map((p) => el('span.cpc-pen', { title: `${p.pen}: hardware ${p.hardware}, firmware ${p.firmware}, ${p.color}` },
|
||
el('i', { style: { background: p.color } }), p.pen.replace('pen ', '')))));
|
||
}
|
||
put(this.body,
|
||
el('div.cryo-row', {}, el('b', {}, t('Sprites')), t('Address'), gi('addr', 64, 'c000'), t('Width (bytes)'), gi('w', 40), t('Lines'), gi('h', 40), t('Count'), gi('n', 40),
|
||
t('Mode'), gi('mode', 30), el('label', {}, el('input', { type: 'checkbox', checked: !!g.zigzag, onchange: (e) => { g.zigzag = e.target.checked; prefs.set('cpcGfx', g); } }), ' zigzag'),
|
||
el('button.btn.small', { onclick: () => this.extract('cpc.gfx', { addr: g.addr, w: g.w, h: g.h, n: g.n, mode: g.mode, zigzag: g.zigzag, scale: g.scale }) }, t('Extract'))),
|
||
el('div.cryo-row', {}, el('b', {}, t('Tiles')), t('Address'), gi('taddr', 64, 'c000'), t('Count'), gi('count', 40), t('Width (bytes)'), gi('tw', 40), t('Lines'), gi('th', 40),
|
||
t('Per row'), gi('perRow', 40),
|
||
el('button.btn.small', { onclick: () => this.extract('cpc.tiles', { addr: g.taddr, count: g.count, w: g.tw, h: g.th, mode: g.mode, perRow: g.perRow }) }, t('Extract'))),
|
||
el('div.cryo-row', {}, el('b', {}, t('Texts')), gi('text', 160, 'GAME OVER'),
|
||
el('button.btn.small', { title: t('Finds a text in any charset (relative search)'), onclick: () => this.extract('cpc.text', { text: g.text }, (x) => { res.text = x.text || t('not found'); }) }, t('Find'))),
|
||
res.text ? el('pre.cryo-out', {}, res.text) : null);
|
||
} else {
|
||
put(this.body, el('p.pub-faint', {}, t('No dump in this run: give frames in "Dumps at frames" (or a PC in "Dump at PC") and run again.')));
|
||
}
|
||
// sound: the AY log of the run
|
||
const snd = prefs.get('cpcSound', { from: 0, to: 250, channels: 7, ogg: true, gap: 25 });
|
||
const si = (k, w) => el('input.input.cpc-in', { value: snd[k], style: { width: w + 'px' }, oninput: (e) => { snd[k] = e.target.value; prefs.set('cpcSound', snd); } });
|
||
put(this.body, el('h4.cpc-h', {}, t('Sound')), el('div.cryo-row', {},
|
||
el('span.pub-faint', {}, t('{n} frames of AY registers', { n: r.psgFrames })), t('Silence gap'), si('gap', 40),
|
||
el('button.btn.small', { onclick: () => this.extract('cpc.sound.segments', { gap: snd.gap }, (x) => { res.segments = x.segments; }) }, t('Where it plays'))));
|
||
if (res.segments) {
|
||
put(this.body, res.segments.length ? el('table.cryo-table', {}, el('tr', {}, el('th', {}, t('From')), el('th', {}, t('To')), el('th', {}, t('Seconds')), el('th')),
|
||
...res.segments.map((s) => el('tr', {}, el('td', {}, s.from), el('td', {}, s.to), el('td', {}, s.seconds),
|
||
el('td', {}, el('button.btn.small', { onclick: () => { snd.from = s.from; snd.to = s.to; prefs.set('cpcSound', snd); this.render(); } }, t('Use')))))) : el('p.pub-faint', {}, t('Silence: no sound in this run.')));
|
||
}
|
||
put(this.body, el('div.cryo-row', {}, t('Frames'), si('from', 60), '–', si('to', 60), t('Channels (mask)'), si('channels', 30),
|
||
el('label', {}, el('input', { type: 'checkbox', checked: !!snd.ogg, onchange: (e) => { snd.ogg = e.target.checked; prefs.set('cpcSound', snd); } }), ' OGG'),
|
||
el('button.btn.small', { onclick: () => this.extract('cpc.sound.render', { from: snd.from, to: snd.to, channels: snd.channels, ogg: snd.ogg }) }, t('Render')),
|
||
el('button.btn.small', { title: t('Estimated length of a music loop in that range'), onclick: () => this.extract('cpc.sound.loop', { from: snd.from, to: snd.to }, (x) => { res.loop = x.text; }) }, t('Loop length'))),
|
||
res.loop ? el('p.pub-faint', {}, res.loop) : null);
|
||
put(this.body, this.gallery());
|
||
}
|
||
|
||
async extract(command, params, after) {
|
||
if (this.busy) return;
|
||
this.busy = 'Extracting…';
|
||
this.render();
|
||
try {
|
||
const x = await backend.invoke(command, { run: this.run.id, dump: this.dump.file, ...params });
|
||
after?.(x);
|
||
this.extracted = await backend.invoke('cpc.extracted', {}).catch(() => this.extracted);
|
||
if (x?.path) this.urls.delete(x.path);
|
||
} catch (e) { notify(String(e.message || e), 'error', { title: 'Amstrad CPC' }); }
|
||
this.busy = null;
|
||
this.render();
|
||
}
|
||
|
||
gallery() {
|
||
const box = el('div.cpc-gallery');
|
||
if (!this.extracted.length) return box;
|
||
put(box, el('h4.cpc-h', {}, t('Extracted ({n})', { n: this.extracted.length }), el('span.pub-faint', {}, ' var/cpc/extract/')));
|
||
for (const f of this.extracted.slice(0, 60)) {
|
||
const name = f.path.split('/').pop();
|
||
const isSound = /\.(wav|ogg)$/i.test(name);
|
||
const media = isSound ? el('audio', { controls: true, preload: 'none' }) : el('img.cpc-thumb', { alt: name });
|
||
this.url(f.path).then((u) => { if (u) media.src = u; });
|
||
put(box, el('div.cpc-item', {}, media, el('div.cpc-item-name', { title: name }, name),
|
||
el('button.btn.small', { onclick: () => this.saveToAssets(f.path, isSound) }, t('Save to assets…'))));
|
||
}
|
||
return box;
|
||
}
|
||
|
||
async saveToAssets(path, isSound) {
|
||
const games = (this.state?.games || []).filter((g) => g.startsWith('games/'));
|
||
if (!games.length) { notify(t('No game in this project to save into (games/<id>).'), 'error'); return; }
|
||
const name = path.split('/').pop();
|
||
let game = games[0];
|
||
if (games.length > 1) {
|
||
const g = await prompt(t('Into which game?'), { value: games[0], label: games.join(', ') });
|
||
if (!g) return;
|
||
game = g;
|
||
}
|
||
const dir = isSound ? (/^sound/.test(name) ? 'assets/sfx/' : 'assets/music/') : (/^tiles/.test(name) ? 'assets/tiles/' : 'assets/sprites/');
|
||
const to = await prompt(t('Save to assets'), { value: dir + name, label: t('Path in {game} (assets/sprites, assets/tiles, assets/sfx, assets/music…). Its commands are added to tools/extract/extract.sh.', { game }) });
|
||
if (!to) return;
|
||
try {
|
||
const r = await backend.invoke('cpc.save', { path, game, to });
|
||
notify(t('Saved to {path}', { path: r.saved }) + (r.script ? ' · ' + r.script : ''), 'success', { title: 'Amstrad CPC' });
|
||
this.app.tree?.refresh();
|
||
} catch (e) { notify(String(e.message || e), 'error'); }
|
||
}
|
||
}
|
||
|
||
// Claude's tools (agent.js): the same as the window
|
||
export const cpcAgentTools = {
|
||
cpcPanel() {
|
||
if (!this.app.cpc) throw new Error('no Amstrad CPC window here: it needs a JumPHP project run on this computer (Docker)');
|
||
this.app.cpc.enable();
|
||
return this.app.cpc;
|
||
},
|
||
async tool_cpc_run(args) {
|
||
const panel = this.cpcPanel();
|
||
if (args.dsk) await backend.invoke('cpc.disc.set', { path: args.dsk });
|
||
const spec = { frames: args.frames || 250, shotEvery: args.shot_every ?? 25, shots: args.shots, dumps: args.dumps, keys: args.keys || [], boot: args.rom ? 'rom' : 'disc',
|
||
pc: args.pc, watch: args.watch, readers: args.readers, writers: args.writers, regs: args.regs, regsIx: args.regs_ix, trace: args.trace, alarm: args.alarm,
|
||
breaks: args.dump_at_pc, pokes: args.pokes || [], label: args.label || 'Claude' };
|
||
const r = await backend.invoke('cpc.run', { spec });
|
||
panel.run = r; panel.film.index = 0; panel.dump.file = r.dumps?.[0]?.file || null; panel.dump.data = null;
|
||
panel.runs = await backend.invoke('cpc.runs', {}).catch(() => panel.runs);
|
||
panel.render();
|
||
const log = r.log || {};
|
||
return { run: r.id, code: r.code, stderr: r.stderr, folder: r.dir, screenshots: r.shots.map((s) => `${s.path} (frame ${s.frame})`), dumps: r.dumps.map((d) => d.file),
|
||
psg_frames: r.psgFrames, alarms: log.alarms, writes: { total: log.writesTotal, first: (log.writes || []).slice(0, 200) }, disc_reads: log.loads?.slice(0, 100),
|
||
keyboard: log.keys, readers: log.readers?.slice(0, 50), writers: log.writers?.slice(0, 50), regs: { total: r.regs?.total, first: r.regs?.rows?.slice(0, 100) },
|
||
trace: { total: r.trace?.total, first: r.trace?.rows?.slice(0, 200) } };
|
||
},
|
||
async tool_cpc_dump(args) {
|
||
this.cpcPanel();
|
||
const out = {};
|
||
if (args.addr !== undefined || args.from === undefined) out.memory = await backend.invoke('cpc.peek', { run: args.run, dump: args.dump, addr: args.addr || '0', len: args.len || 256 });
|
||
if (args.from !== undefined) out.disassembly = (await backend.invoke('cpc.disasm', { run: args.run, dump: args.dump, from: args.from, to: args.to })).lines
|
||
.map((l) => (l.executed ? '*' : ' ') + l.addr + ' ' + l.bytes.padEnd(10) + ' ' + l.text).join('\n');
|
||
if (args.find_text) out.text = (await backend.invoke('cpc.text', { run: args.run, dump: args.dump, text: args.find_text })).text;
|
||
if (args.compare_with) out.diff = (await backend.invoke('cpc.diff', { run: args.run, a: args.dump, b: args.compare_with, from: args.diff_from, to: args.diff_to, range: args.diff_range })).text;
|
||
return out;
|
||
},
|
||
async tool_cpc_extract_gfx(args) {
|
||
const panel = this.cpcPanel();
|
||
const kind = args.kind || 'gfx';
|
||
const command = { gfx: 'cpc.gfx', tiles: 'cpc.tiles', screen: 'cpc.screen', palette: 'cpc.palette' }[kind];
|
||
if (!command) throw new Error('kind: gfx, tiles, screen or palette');
|
||
const r = await backend.invoke(command, { ...args, run: args.run, dump: args.dump });
|
||
panel.extracted = await backend.invoke('cpc.extracted', {}).catch(() => panel.extracted);
|
||
if (args.save_to && args.game && r.path) r.saved = await backend.invoke('cpc.save', { path: r.path, game: args.game, to: args.save_to });
|
||
panel.render();
|
||
return r;
|
||
},
|
||
async tool_cpc_extract_sound(args) {
|
||
const panel = this.cpcPanel();
|
||
if (args.from === undefined) return backend.invoke('cpc.sound.segments', { run: args.run, gap: args.gap || 25 });
|
||
const r = await backend.invoke('cpc.sound.render', { run: args.run, from: args.from, to: args.to, channels: args.channels || 7, ogg: args.ogg !== false, name: args.name });
|
||
if (args.loop) r.loop = (await backend.invoke('cpc.sound.loop', { run: args.run, from: args.from, to: args.to })).text;
|
||
if (args.save_to && args.game) r.saved = await backend.invoke('cpc.save', { path: r.path, game: args.game, to: args.save_to });
|
||
panel.extracted = await backend.invoke('cpc.extracted', {}).catch(() => panel.extracted);
|
||
panel.render();
|
||
return r;
|
||
},
|
||
};
|