@henols/c64-re-tools 2.6.0-rc.8 → 2.6.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-docs/SKILL.md +1 -1
  3. package/skills/c64-docs/scripts/docs.ts +6 -6
  4. package/skills/c64-knowledge/SKILL.md +2 -2
  5. package/skills/c64-source/SKILL.md +2 -2
  6. package/skills/c64-source/scripts/lib/source.ts +10 -0
  7. package/skills/c64-source/scripts/source.ts +15 -12
  8. package/skills/c64-static-analysis/SKILL.md +4 -2
  9. package/skills/c64-static-analysis/scripts/static-analysis.ts +15 -8
  10. package/skills/c64-testing/SKILL.md +1 -1
  11. package/skills/c64-testing/references/recording-format.md +11 -5
  12. package/skills/c64-testing/references/scenario-format.md +2 -3
  13. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  14. package/skills/c64-testing/scripts/lib/play.ts +39 -37
  15. package/skills/c64-testing/scripts/lib/recording.ts +21 -38
  16. package/skills/c64-testing/scripts/lib/runs.ts +2 -2
  17. package/skills/c64-testing/scripts/lib/scenario.ts +3 -5
  18. package/skills/c64-unpacker/SKILL.md +2 -1
  19. package/skills/c64-unpacker/scripts/lib/loads.ts +2 -2
  20. package/skills/emulator/SKILL.md +2 -5
  21. package/src/c64-keys.ts +98 -0
  22. package/src/host/vice/session.ts +82 -8
  23. package/src/host-client/steps.ts +17 -17
  24. package/src/host-client/vice-session.ts +7 -1
  25. package/src/knowledge/read.ts +9 -0
  26. package/src/mcp/inputs.ts +12 -0
  27. package/src/mcp/server.ts +1 -0
  28. package/src/mcp/tools/input.ts +38 -5
  29. package/src/native/c64run.ts +1 -1
  30. package/src/native/discover.ts +3 -3
  31. package/src/native/processes.ts +3 -3
  32. package/src/protocol/vice.ts +47 -0
  33. package/src/vsf.ts +98 -0
  34. package/tools/c64run.c +9 -12
  35. package/skills/c64-testing/scripts/lib/keys.ts +0 -36
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.6.0-rc.8",
3
+ "version": "2.6.0-rc.9",
4
4
  "description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
5
5
  "license": "MIT",
6
6
  "author": "Henrik Olsson",
@@ -34,7 +34,7 @@
34
34
  "scripts": {
35
35
  "host": "node src/host/main.ts",
36
36
  "typecheck": "tsc -p tsconfig.json",
37
- "test": "node --test \"src/**/*.test.ts\" \"test/**/*.test.ts\""
37
+ "test": "node test/run.ts"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@types/node": "24.13.3",
@@ -41,7 +41,7 @@ The documentation is Markdown in the project. It has two parts:
41
41
 
42
42
  Get the values for the commands from these places:
43
43
 
44
- - `<source-dir>` and `--source`: the folder of the source that you generated from the project knowledge, for example `src`. The source must be from the current revision of the project knowledge.
44
+ - `<source-dir>` and `--source`: the folder of the source that you generated from the project knowledge, for example `src`. The source must be from the current revision of the project knowledge in its space. A change in another space does not make the source old.
45
45
  - `--out`: a folder that holds only the reference, for example `docs/reference`. Keep the pages that you write outside it.
46
46
  - `<page>`: the entry page `README.md` and the folder of the other pages, for example `docs`.
47
47
  - The program bytes: put them into the project knowledge before `generate`. Then the reference decodes the tables and shows the graphics.
@@ -14,7 +14,7 @@ import { writeProjectFile, writeReported } from "#src/host-client/transfer.ts";
14
14
  import { conflicts } from "#src/knowledge/conflicts.ts";
15
15
  import { openForRead } from "#src/knowledge/database.ts";
16
16
  import { programImage, type ProgramImage } from "#src/knowledge/program.ts";
17
- import { currentRevision, listComments, listModules, listReferences, listRegions, listSymbols } from "#src/knowledge/read.ts";
17
+ import { listComments, listModules, listReferences, listRegions, listSymbols, sourceRevision } from "#src/knowledge/read.ts";
18
18
  import { groupOf, namedGroup, projectRoot, resolveProjectFile, resolveProjectPath, type ProjectGroup } from "#src/project.ts";
19
19
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
20
20
  import { checkLinks, linkPage, type Files, type LinkContext, type Names, type Problem } from "./lib/links.ts";
@@ -64,10 +64,10 @@ function generate(call: Call): Reply {
64
64
  image = programImage(db, map.space);
65
65
  const found = conflicts(db).length;
66
66
  if (found > 0) throw new Refusal("conflict", `The knowledge has ${found} conflict${found === 1 ? "" : "s"} from a git merge. Nothing was written. Resolve the merge conflicts of the project knowledge. Then generate the source again from the knowledge, and run generate again.`);
67
- const revision = currentRevision(db);
68
- // A source of another revision has other lines: the links would point to the wrong code.
67
+ // A source of another revision has other lines: the links would point to the wrong code. A change in another space does not change the source.
68
+ const revision = sourceRevision(db, map.space);
69
69
  if (map.revision !== revision) {
70
- throw new WireFailure("invalid-input", `${map.mapPath} is from knowledge revision ${map.revision}, and the knowledge is at revision ${revision}. Nothing was written. Generate the source again from the knowledge. Then run generate again.`);
70
+ throw new WireFailure("invalid-input", `${map.mapPath} is from knowledge revision ${map.revision}, and the knowledge of the source is at revision ${revision}. Nothing was written. Generate the source again from the knowledge. Then run generate again.`);
71
71
  }
72
72
  knowledge = {
73
73
  revision,
@@ -266,13 +266,13 @@ function link(call: Call): Reply {
266
266
  let symbols;
267
267
  let revision;
268
268
  try {
269
- revision = currentRevision(db);
269
+ revision = sourceRevision(db, map.space);
270
270
  symbols = listSymbols(db, undefined, undefined, undefined, map.space);
271
271
  } finally {
272
272
  db?.close();
273
273
  }
274
274
  if (map.revision !== revision) {
275
- problems.push({ page: inProject(map.mapPath), line: 1, kind: "stale-reference", message: `The source${of} is from knowledge revision ${map.revision}, and the knowledge is at ${revision}. Generate the source and the reference again, then run docs.ts link.` });
275
+ problems.push({ page: inProject(map.mapPath), line: 1, kind: "stale-reference", message: `The source${of} is from knowledge revision ${map.revision}, and the knowledge of the source is at ${revision}. Generate the source and the reference again, then run docs.ts link.` });
276
276
  }
277
277
  const addresses = new Map<string, number>();
278
278
  for (const label of map.labels) addresses.set(label.name, label.address);
@@ -248,8 +248,8 @@ When a git merge left conflicts in the knowledge, each read body also has `confl
248
248
 
249
249
  ### `listing <range>`
250
250
 
251
- - `body.lines` lists one line for each instruction of a code region, and one `!byte` line for other bytes.
252
- - Each line has `address`, `bytes`, `text`, `referencesIn` and `referencesOut`. It can also have `label`, `analyzerNames` and `comment`.
251
+ - `body.lines` has `count` and `listed`. `listed` holds one line for each instruction of a code region, and one `!byte` line for other bytes.
252
+ - Each line has `address`, `bytes`, `text`, `referencesIn` and `referencesOut`. It can also have `label`, `analyzerNames`, `lineComments` and `comment`. `lineComments` are the line comments before the line. `comment` is the side comment.
253
253
  - `text` is the instruction with the names of its target. An operand expression of the knowledge replaces the operand.
254
254
  - When the knowledge has coverage, `access` tells if a run executed (`x`), read (`r`) or wrote (`w`) the bytes of the line, or `-` for none.
255
255
  - With `--out`, the body has `lines` as a number, and `out`, `bytes` and `sha256` of the text file.
@@ -195,7 +195,7 @@ Do these actions for the findings:
195
195
 
196
196
  #### The leftovers
197
197
 
198
- A leftover is a range of the program that nothing uses: unused code, old copies and old data. The script finds the leftovers from the coverage, as the export finds its free ranges (see "The free ranges"). The start screen, the patches, the macro uses and the addresses that the code of a patch names are never leftovers.
198
+ A leftover is a range of the program that nothing uses: unused code, old copies and old data. The script finds the leftovers from the coverage, as the export finds its free ranges (see "The free ranges"). The start screen, the patches and the addresses that the code of a patch names are never leftovers. A macro use in code that nothing uses is in the leftover with that code. A leftover never cuts a macro use in two.
199
199
 
200
200
  - Each range of leftovers is a file `leftovers/leftover_xxxx.asm`. When a range cuts a module, the module continues after the range in `<module>_xxxx.asm`, in the folder of the module. The module in the knowledge does not change.
201
201
  - `main.asm` builds a leftover file only when `LEFTOVERS` is 1. When it is 0, the build skips the bytes. Thus the addresses after the range do not change.
@@ -274,7 +274,7 @@ The start screen:
274
274
  - With a start screen, the copier uses three pages, not two.
275
275
  - The start screen is part of the clean build only. The loader program always shows it. A release build has no start screen, and `LEFTOVERS = 1` also turns it off.
276
276
  - To start the program at once, set `START_SCREEN = 0` in `config.asm`, and assemble `loader.asm`. Do not define `START_SCREEN` on the command line of the build: `config.asm` sets it.
277
- - A test that runs the loader program stops at the start screen, because the emulator cannot press a key of the keyboard matrix. Run until `loader_start_screen_wait`. Then set the PC to `loader_start_screen_continue`.
277
+ - A test that runs the loader program stops at the start screen, because the start screen waits for a key. Run until `loader_start_screen_wait`. Then set the PC to `loader_start_screen_continue`.
278
278
 
279
279
  `loader` holds these fields:
280
280
 
@@ -561,6 +561,16 @@ export function layout(input: SourceInput): Layout {
561
561
  }
562
562
  }
563
563
  }
564
+ // A macro line also uses the addresses that its instructions name besides its args, for example the high byte
565
+ // CUTHI of +mov16 CUTLO: a name of the source counts that use too. The args count as macro argument above.
566
+ for (const candidate of accepted) {
567
+ const argAddresses = new Set(candidate.use.args.flatMap((arg) => identifiers(arg)).map((name) => byName.get(name)));
568
+ for (const item of candidate.items) {
569
+ if (!takesAddress(OPCODES[item.opcode]!.mode)) continue;
570
+ const value = operandValue(item.address, item.opcode, input.byteAt)!;
571
+ if (!argAddresses.has(value) && uses.has(value)) tally(value, useKind(item.opcode));
572
+ }
573
+ }
564
574
 
565
575
  const names = new Map<number, string>();
566
576
  const taken = new Set([...knowledgeNames, ...platform.values()]);
@@ -25,7 +25,7 @@ import { conflicts } from "#src/knowledge/conflicts.ts";
25
25
  import { openForRead, withWrite } from "#src/knowledge/database.ts";
26
26
  import { identifiers } from "#src/knowledge/expression.ts";
27
27
  import { analyzedBytes, memoryRows, programCoverage, releaseImage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
28
- import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, spacesRevision, startScreenRanges, type StartScreenRow, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSpaces, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
28
+ import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, sourceRevision, startScreenRanges, type StartScreenRow, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSpaces, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
29
29
  import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
30
30
  import { subtract, write } from "#src/knowledge/write.ts";
31
31
  import { assemble, symbolsFileText } from "#src/native/acme.ts";
@@ -95,8 +95,8 @@ function readKnowledge(space: Space, analyzerNames = false) {
95
95
  const startScreen = space === DEFAULT_SPACE ? currentStartScreen(db, space) : undefined;
96
96
  return {
97
97
  revision: currentRevision(db),
98
- // The loader holds the program of this space and the stage of its start screen: a change elsewhere does not change it.
99
- loaderRevision: spacesRevision(db, [space, ...(startScreen?.stage === undefined ? [] : [startScreen.stage])]),
98
+ // The source and its loader hold the program of this space and the stage of its start screen: a change elsewhere does not change them.
99
+ sourceRevision: sourceRevision(db, space),
100
100
  program: requireProgram(db, space),
101
101
  // The coverage of the space: a run of the C64, or of a captured stage that coverage put into that space.
102
102
  coverage: programCoverage(db, space)?.map,
@@ -570,8 +570,8 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state:
570
570
  const port01 = `$${port.toString(16).padStart(2, "0")}`;
571
571
  return { verified: false, differences: [`The loader did not get to ${what}; it stopped at ${formatC64Address(pc)}.`], stop: { pc: formatC64Address(pc), port: port01, ...(cause === undefined ? {} : { cause }), history } };
572
572
  };
573
- // The start screen waits for a key or a fire button. The emulator cannot press a key of the keyboard matrix
574
- // on each VICE, so the check lets it wait, then sets the PC to the code after the wait.
573
+ // The start screen waits for a key or a fire button. Not each VICE can press a key of the keyboard matrix,
574
+ // so the check lets it wait, then sets the PC to the code after the wait.
575
575
  let screen: LoaderRun["startScreen"];
576
576
  const screenDifferences: string[] = [];
577
577
  const showScreen = async (at: { wait: number; continue: number }, wanted: StartScreenPlan, frames: number, copied: boolean, parts: readonly StagePart[] = [], colourRam?: Uint8Array): Promise<LoaderRun | undefined> => {
@@ -1139,8 +1139,8 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1139
1139
  const given = existsSync(configPath) ? configValues(readFileSync(configPath, "utf8")) : new Map<string, 0 | 1>();
1140
1140
  const configNames = new Set([...knowledge.switches.map((row) => row.name), START_SCREEN_SWITCH, LEFTOVERS_SWITCH]);
1141
1141
  const loaderValues = new Map([...given].filter(([name]) => configNames.has(name)));
1142
- const header = [`Generated by c64-source from knowledge revision ${knowledge.revision}${space === DEFAULT_SPACE ? "" : ` in space ${space}`}.`, "Change names, comments, regions and modules in knowledge, then generate again."];
1143
- const loaderHeader = [`${LOADER_REVISION}${knowledge.loaderRevision}.`, "It copies the segments into place, sets the entry state and jumps to the entry."];
1142
+ const header = [`Generated by c64-source from knowledge revision ${knowledge.sourceRevision}${space === DEFAULT_SPACE ? "" : ` in space ${space}`}.`, "Change names, comments, regions and modules in knowledge, then generate again."];
1143
+ const loaderHeader = [`${LOADER_REVISION}${knowledge.sourceRevision}.`, "It copies the segments into place, sets the entry state and jumps to the entry."];
1144
1144
  const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused } = await buildSource(knowledge, {
1145
1145
  space,
1146
1146
  entries,
@@ -1160,11 +1160,11 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1160
1160
  // Read before the old files go: the leftovers of the earlier run, to tell what changed.
1161
1161
  const earlier = earlierLeftovers(out);
1162
1162
  const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted);
1163
- const stale = loaderWanted || space !== DEFAULT_SPACE ? undefined : staleLoader(out, knowledge.loaderRevision);
1163
+ const stale = loaderWanted || space !== DEFAULT_SPACE ? undefined : staleLoader(out, knowledge.sourceRevision);
1164
1164
  const written: Written[] = withValues(files, laid, kept).map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
1165
1165
  // The reports go to the local folder: the source folder holds only source files.
1166
1166
  const reports = generatedDirectory(projectRelative(out));
1167
- written.push(writeReported(`${reports}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.revision, files)));
1167
+ written.push(writeReported(`${reports}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.sourceRevision, files)));
1168
1168
  const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
1169
1169
  const inData = entriesInData(entries, knowledge.regions);
1170
1170
  if (rendered.notExecuted !== undefined) {
@@ -1177,7 +1177,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1177
1177
  });
1178
1178
  const files: Record<string, number> = {};
1179
1179
  for (const range of placed) if (range.file !== undefined) files[range.file] = (files[range.file] ?? 0) + 1;
1180
- const all = { revision: knowledge.revision, instructions: rendered.notExecuted.instructions, files, ranges: placed };
1180
+ const all = { revision: knowledge.sourceRevision, instructions: rendered.notExecuted.instructions, files, ranges: placed };
1181
1181
  written.push(writeReported(`${reports}/${NOT_EXECUTED_FILE}`, `${JSON.stringify(all, null, 2)}\n`));
1182
1182
  }
1183
1183
  // The leftovers that changed since the earlier run: the default build and the loader now leave out other bytes.
@@ -1469,9 +1469,12 @@ function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<numbe
1469
1469
  const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
1470
1470
  const screenParts = knowledge.startScreen === undefined || knowledge.startScreen.stage !== undefined ? [] : startScreenRanges(knowledge.startScreen).map((part) => part.range);
1471
1471
  const named = knowledge.patches.flatMap((patch) => patchTargets(patch.code, addressOf)).map((address) => ({ start: address, end: address }));
1472
- const keep = [...screenParts, ...kept, ...knowledge.macroUses, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
1472
+ const keep = [...screenParts, ...kept, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
1473
1473
  const changed = knowledge.patches.map((patch) => ({ start: patch.start, end: patch.end })).filter(inImage);
1474
- return freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] }).free.map((range) => ({ start: range.start, end: range.end }));
1474
+ const free = freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] }).free.map((range) => ({ start: range.start, end: range.end }));
1475
+ // A macro use in code that nothing uses goes with that code. A leftover never cuts a use in two: its edge stops at the use.
1476
+ const cut = (range: AddressRange) => knowledge.macroUses.filter((use) => use.start <= range.end && range.start <= use.end && (use.start < range.start || use.end > range.end));
1477
+ return free.flatMap((range) => subtract(range, cut(range)));
1475
1478
  }
1476
1479
 
1477
1480
  /** Every file in a folder with its path in it, with / between the parts, in path order. `skip` leaves out a folder by its path. */
@@ -30,6 +30,7 @@ To get the command list, run the script with no arguments.
30
30
  | Get each instruction as JSON | `analyze --entry '$080d' --out-instructions .c64-re-tools/local/instructions.json` |
31
31
  | Analyze drive code or a cartridge bank | `analyze --space drive8` |
32
32
  | Write the macro candidates to the project knowledge | `analyze --apply-macros` |
33
+ | Write only the correct macro candidates | `analyze --apply-macros --skip '$1e64' --skip '$2010'` |
33
34
  | Get more items in each list | `analyze --max-listed 500` |
34
35
 
35
36
  ---
@@ -87,6 +88,7 @@ Each flag applies only to the commands in the table. On another command, the scr
87
88
  | `--out-listing <file>` | `analyze` | DXA only. Write the disassembly listing to this project file. There is no default. |
88
89
  | `--out-instructions <file>` | `analyze` | Ghidra only. Write each instruction to this project file as JSON. There is no default. |
89
90
  | `--apply-macros` | `analyze` | Write the macro candidates and their macros to the project knowledge as one revision of the LLM. Off by default. |
91
+ | `--skip <address>` | `analyze` | With `--apply-macros`: the start of a macro candidate that is not correct. The run does not write it. Give one `--skip` for each such candidate. |
90
92
 
91
93
  ---
92
94
 
@@ -127,7 +129,7 @@ The `hint` gives each of these cases:
127
129
 
128
130
  - `conflicts` is not empty. Find the correct answer in the emulator. Then correct the project knowledge.
129
131
  - `coverageConflicts` is not empty. Classify each range as code in the project knowledge, or as `dual-use` when its bytes are also data. For many ranges, write all classifications in one batch of changes.
130
- - `idioms.candidates.macros` has candidates, and the run had no `--apply-macros`. Examine the candidates. To write them to the project knowledge, run the analysis again with `--apply-macros`. Then generate the source again.
132
+ - `idioms.candidates.macros` has candidates, and the run had no `--apply-macros`. Examine the candidates. To write the correct candidates to the project knowledge, run the analysis again with `--apply-macros`. Give `--skip` with the start of each candidate that is not correct. Then generate the source again.
131
133
  - A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels` and `functions` as analyzer names.
132
134
 
133
135
  There is no `nextAction`.
@@ -140,7 +142,7 @@ The script does not record the candidates. Examine each candidate and decide.
140
142
  - `selfModified`: opcodes that the program wrote and then executed. The write and the execution must be in one coverage file. A coverage file does not record the order. Thus a candidate can also be code that ran first, and that the program then wrote over. To prevent this, save one coverage file for each part of the program, for example the intro, the game, or a loader that copies code. Clear the memory map between the parts.
141
143
  - `pointers`: code that makes an address from immediates. A `vector` or a `zero-page pointer` candidate stores a low byte (`low`) and a high byte (`high`) to a vector or to a zero-page pair. A `sprite pointer` candidate stores an immediate (`at`) to a sprite pointer of the screen at `$0400` in VIC bank 0. For each correct candidate, record a low and a high operand expression to its `target` in the project knowledge. Then a rebuild can move the target.
142
144
  - `pitfalls`: code that a C64 runs in a different way than it reads. For `raster-bit-8`, the instruction at `at` reads `$D011`, and the instruction at `store` writes the value back. The write can move the raster interrupt to line 256 or later. On PAL, past line 311, the interrupt never comes. Where the code must not keep bit 7, add a comment and test the program.
143
- - `macros`: runs of instructions that one macro line can replace, for example `+inc16 ptr`. Each candidate has `macro`, `start`, `end`, `args` and `text`. The macros are `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. An arg is a name of the user or the LLM, or a platform name of a ROM that the program uses. `known` counts the uses that the project knowledge has. `leftOut` counts the candidates with a label inside, or with a patch over them, or with another use of the project knowledge over them. With `--apply-macros`, `revision` gives the revision of the writes, and `writes` counts them. The writes hold the macros that the project knowledge does not have, with their bodies, and the uses. Do not write these macros yourself. `otherMacros` names each macro that the project knowledge has with another body. The writes do not have the uses of that macro.
145
+ - `macros`: runs of instructions that one macro line can replace, for example `+inc16 ptr`. Each candidate has `macro`, `start`, `end`, `args` and `text`. The macros are `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. An arg is a name of the user or the LLM, or a platform name of a ROM that the program uses. `known` counts the uses that the project knowledge has. `leftOut` counts the candidates with a label inside, or with a patch over them, or with another use of the project knowledge over them. With `--apply-macros`, `revision` gives the revision of the writes, and `writes` counts them. The writes hold the macros that the project knowledge does not have, with their bodies, and the uses. Do not write these macros yourself. `otherMacros` names each macro that the project knowledge has with another body. The writes do not have the uses of that macro. `skipped` counts the candidates that `--skip` left out. `notCandidates` lists each `--skip` address that starts no candidate.
144
146
 
145
147
  #### Which facts the analysis replaces
146
148
 
@@ -75,11 +75,11 @@ function showMacro(candidate: MacroCandidate) {
75
75
  * the ROMs that the program uses, as c64-source names them. A candidate is left out when
76
76
  * a name or a reference target is inside it, or a patch or a use overlaps it:
77
77
  * c64-source would write its instructions. The same use in the knowledge is
78
- * known. The writes are the candidates with the macros they need. A macro of
79
- * the catalogue that the knowledge has with another body leaves its
80
- * candidates out of the writes.
78
+ * known. The writes are the candidates with the macros they need, without the
79
+ * candidates that start at an address of `skip`. A macro of the catalogue that
80
+ * the knowledge has with another body leaves its candidates out of the writes.
81
81
  */
82
- function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse) {
82
+ function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse, skip: ReadonlySet<number>) {
83
83
  const db = openForRead();
84
84
  try {
85
85
  // The platform names that c64-source uses: a name of a ROM that the program does not use is no arg.
@@ -104,16 +104,18 @@ function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse) {
104
104
  const macros = new Map(listMacros(db, undefined, space).map((macro) => [macro.name, macro]));
105
105
  const writes: BatchOperation[] = [];
106
106
  const other = new Set<string>();
107
- for (const idiom of CATALOGUE.filter((item) => candidates.some((candidate) => candidate.macro === item.name))) {
107
+ const chosen = candidates.filter((candidate) => !skip.has(candidate.start));
108
+ for (const idiom of CATALOGUE.filter((item) => chosen.some((candidate) => candidate.macro === item.name))) {
108
109
  const existing = macros.get(idiom.name);
109
110
  if (existing === undefined) writes.push({ op: "macro", space, name: idiom.name, params: [...idiom.params], body: idiom.body, comment: idiom.comment });
110
111
  else if (existing.params.join(",") !== idiom.params.join(",") || existing.body !== idiom.body) other.add(idiom.name);
111
112
  }
112
- for (const candidate of candidates) {
113
+ for (const candidate of chosen) {
113
114
  if (other.has(candidate.macro)) continue;
114
115
  writes.push({ op: "use", space, start: candidate.start, end: candidate.end, macro: candidate.macro, args: candidate.args });
115
116
  }
116
- return { candidates, known, leftOut, writes, otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not written.`) };
117
+ const notCandidates = [...skip].filter((address) => !candidates.some((candidate) => candidate.start === address)).sort((a, b) => a - b);
118
+ return { candidates, known, leftOut, writes, skipped: candidates.length - chosen.length, notCandidates, otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not written.`) };
117
119
  } finally {
118
120
  db?.close();
119
121
  }
@@ -177,6 +179,8 @@ async function analyze(call: Call): Promise<unknown> {
177
179
  const listingPath = call.string("out-listing");
178
180
  const instructionsPath = call.string("out-instructions");
179
181
  const applyMacros = call.flag("apply-macros");
182
+ const skip = new Set(call.addresses("skip"));
183
+ if (skip.size > 0 && !applyMacros) throw new UsageError("--skip works only with --apply-macros: it names a macro candidate that the run does not write");
180
184
  if (analyzer === "dxa" && decompile.length > 0) throw new UsageError("--decompile works only with --analyzer ghidra");
181
185
  if (analyzer === "ghidra" && listingPath !== undefined) throw new UsageError("--out-listing works only with --analyzer dxa");
182
186
  if (analyzer === "dxa" && instructionsPath !== undefined) throw new UsageError("--out-instructions works only with --analyzer ghidra");
@@ -223,7 +227,7 @@ async function analyze(call: Call): Promise<unknown> {
223
227
  const idiomsResult = () => {
224
228
  const imported = withWrite((db) => importFindings(db, { ...idioms.findings, space }, { description: "Idioms in the program" }));
225
229
  // The macro candidates read the code regions after both imports.
226
- const macros = macroCandidates(space, byteAt, romUseOfProgram(coverage, program.state));
230
+ const macros = macroCandidates(space, byteAt, romUseOfProgram(coverage, program.state), skip);
227
231
  // With --apply-macros, the candidates and their macros are a third revision of the LLM.
228
232
  const platformNamed = new Map(platformNames().map((entry) => [entry.name, entry.address]));
229
233
  const written = applyMacros && macros.writes.length > 0 ? withWrite((db) => applyBatch(db, { origin: "llm", description: "Macro candidates in the program", image: operandImages(db, platformNamed) }, macros.writes)) : undefined;
@@ -253,6 +257,8 @@ async function analyze(call: Call): Promise<unknown> {
253
257
  ...(macros.known === 0 ? {} : { known: macros.known }),
254
258
  ...(macros.leftOut === 0 ? {} : { leftOut: macros.leftOut }),
255
259
  ...(written === undefined ? {} : { revision: written.revision, writes: macros.writes.length }),
260
+ ...(macros.skipped === 0 ? {} : { skipped: macros.skipped }),
261
+ ...(macros.notCandidates.length === 0 ? {} : { notCandidates: macros.notCandidates.map(formatC64Address) }),
256
262
  ...(macros.otherMacros.length === 0 ? {} : { otherMacros: macros.otherMacros }),
257
263
  },
258
264
  },
@@ -355,6 +361,7 @@ await runScript({
355
361
  "out-listing": { kind: "path", output: "file", value: "<file>", help: "dxa: write the disassembly listing to this project file" },
356
362
  "out-instructions": { kind: "path", output: "file", value: "<file>", help: "ghidra: write every instruction (address, bytes, mnemonic, mode, operand, target, executed) to this project file as JSON" },
357
363
  "apply-macros": { kind: "flag", help: "write the macro candidates (the macros and their uses) to the project knowledge as one revision of the LLM" },
364
+ skip: { kind: "address", value: "<address>", multiple: true, help: "with --apply-macros: the start of a macro candidate that is not correct. The run does not write it" },
358
365
  },
359
366
  notes: "The program and the coverage come from the project knowledge: put them into the project knowledge first. The executed code of the coverage gives entry points. Routine symbols in the knowledge are entry points too. Ghidra needs at least one entry point. DXA finds the SYS of a BASIC start by itself.",
360
367
  run: analyze,
@@ -251,7 +251,7 @@ Do this for each result:
251
251
 
252
252
  Traps:
253
253
 
254
- - `idleReads` counts the input reads of the rebuild that the recording had no value for. On the original, such a read makes the result INCONCLUSIVE.
254
+ - `idleReads` counts the input reads of the rebuild that the recording had no value for. On the original, such a read makes the result INCONCLUSIVE. The rebuild can read input where the original does not, for example in its loader before the start screen. Such reads do not change a PASS of the rebuild.
255
255
  - The script refuses a recording of version 2.0 with `invalid-input`. Record the session again.
256
256
 
257
257
  ---
@@ -37,7 +37,7 @@ A record file is one JSON object in a project file.
37
37
  The steps have the form of the steps of a scenario. Two steps behave differently:
38
38
 
39
39
  - `type` puts at most 10 keys into the keyboard queue of the KERNAL. It is an event: a replay does it again.
40
- - `press` pushes keys of the keyboard matrix. It is input. A scenario has no `press` step.
40
+ - `press` pushes keys of the keyboard matrix. It is input.
41
41
 
42
42
  A record file has no `raster` target and no `condition`. `write` and `runUntil` have only the space `c64`.
43
43
 
@@ -45,27 +45,33 @@ A record file has no `raster` target and no `condition`. `write` and `runUntil`
45
45
  |---|---|
46
46
  | `{ "frames": 300 }` | Run 300 frames (19656 cycles each). |
47
47
  | `{ "joystick": { "port": 2, "direction": "left", "fire": true } }` | Set a joystick. It stays in this state until the next joystick step. |
48
- | `{ "press": "RUN\n" }` | Press each key of the text on the keyboard matrix for 3 frames, then release it for 3 frames. |
48
+ | `{ "press": { "keys": "RUN\n" } }` | Press the keys of the keyboard matrix. Each tap holds its keys for 3 frames, then releases them for 3 frames. `frames` sets a different number, from 1 to 3000. |
49
49
  | `{ "type": { "mode": "text", "text": "RUN\n" } }` | Put at most 10 keys into the keyboard queue of the KERNAL, after the keys that wait there. |
50
50
  | `{ "write": { "address": "next_room", "data": "01" } }` | Write bytes into RAM. |
51
51
  | `{ "registers": { "pc": "change_room", "a": 16 } }` | Set registers at the next instruction. `pc` continues the program at that address. |
52
52
  | `{ "runUntil": { "target": { "kind": "address", "address": "main_loop" }, "timeoutFrames": 300 } }` | Run until the CPU gets to an address. |
53
53
  | `{ "runUntil": { "target": { "kind": "memory", "address": "room", "operator": "eq", "value": 2 }, "timeoutFrames": 600 } }` | Run until a byte compares true with `value`. The script reads the byte at the end of each frame. |
54
54
 
55
- A `press` step can press A to Z, 0 to 9, space, return (`\n`) and `+-.:@,*;=/!"#$%&'()[]<>?`. It presses a to z as A to Z.
55
+ Each character of `keys` is one tap. a to z press the same keys as A to Z. `\n` presses RETURN. A character with SHIFT, for example `!`, also presses the left SHIFT.
56
+
57
+ The program runs while a `press` step taps its keys. An event in these frames is past when the next step starts. After a `press` step, run until an address that the program gets to later. For example, after F1 starts a game, run until the main loop of the game, not until the routine that starts the game.
56
58
 
57
59
  A key without a character has its name in braces, in upper or lower case. `{STOP}` is RUN/STOP, and `{CBM}` is the Commodore key. The names are:
58
60
 
59
61
  - `{F1}` to `{F8}`, `{RETURN}`, `{SPACE}`, `{DEL}`, `{INST}`, `{HOME}`, `{CLR}`
60
- - `{STOP}`, `{RUN}`, `{CTRL}`, `{CBM}`, `{LSHIFT}`, `{RSHIFT}`
62
+ - `{STOP}`, `{RUN}`, `{RESTORE}`, `{CTRL}`, `{CBM}`, `{LSHIFT}`, `{RSHIFT}`
61
63
  - `{UP}`, `{DOWN}`, `{LEFT}`, `{RIGHT}`, `{POUND}`, `{UPARROW}`, `{LEFTARROW}`
62
64
 
63
- For example, `{ "press": "{F1}" }` presses F1. The step presses each key alone, one after the other. It cannot hold two keys at the same time.
65
+ `{F2}`, `{F4}`, `{F6}`, `{F8}`, `{RUN}`, `{CLR}`, `{INST}`, `{UP}` and `{LEFT}` also press the left SHIFT.
66
+
67
+ To hold keys together in one tap, join them with `+` in braces. For example, `{ "press": { "keys": "{LSHIFT+CBM}" } }` holds the left SHIFT and the Commodore key together. One tap holds at most 4 keys. RESTORE counts as a key.
64
68
 
65
69
  The keyboard queue of the KERNAL holds 10 keys. If the keys of a `type` step and the keys that wait in the queue do not fit, the session stops. A program that reads the keyboard hardware does not see the keys of a `type` step. Use `press` for that program.
66
70
 
67
71
  `joystick`, `press` and `frames` steps are input and time. The recording keeps their effect in the reads, so a replay does not do these steps again.
68
72
 
73
+ RESTORE starts an NMI and is not a read. The recording keeps each RESTORE of a `press` step as an event of that step. The replay presses RESTORE again at the same read of the program.
74
+
69
75
  `type`, `write`, `registers` and `runUntil` steps are events. The recording keeps a point in the program for each event. The point is the next read at the input site with the most reads. That site is not in ROM. A replay does the event again at the same read. An event that comes directly after another event runs at once after that event.
70
76
 
71
77
  ## Play
@@ -46,8 +46,9 @@ Before the first step of each side, the script does a hard reset. The CPU stops
46
46
  | `{ "write": { "address": "seed", "data": "0102" } }` | Write 1 to 4096 bytes into memory. Optional: `space` (`c64` or `drive8`, default `c64`) and `view` (`cpu` or `ram`, default `cpu`). |
47
47
  | `{ "registers": { "pc": "start", "a": 0, "flags": { "i": true } } }` | Set registers: `pc`, `a`, `x`, `y`, `sp` and `flags` (`n`, `v`, `b`, `d`, `i`, `z`, `c`). Only `pc` can be a name. |
48
48
  | `{ "joystick": { "port": 2, "direction": "left", "fire": true } }` | Set a joystick. `fire` is `false` by default. The joystick stays in this state until the next joystick step. |
49
- | `{ "type": { "mode": "text", "text": "RUN\n" } }` | Put at most 1024 keys into the keyboard queue of the KERNAL. A program that reads the keyboard hardware does not see them. |
49
+ | `{ "type": { "mode": "text", "text": "RUN\n" } }` | Put at most 1024 keys into the keyboard queue of the KERNAL. A program that reads the keyboard hardware does not see them. Use `press` for that program. |
50
50
  | `{ "type": { "mode": "petscii", "bytes": [147] } }` | Put PETSCII codes from 1 to 255 into the keyboard queue of the KERNAL. Use it for keys that mode `text` does not have. |
51
+ | `{ "press": { "keys": "{F1}" } }` | Press keys of the keyboard matrix and RESTORE. A program that reads the keyboard hardware sees them. Each tap holds its keys for 3 frames, then releases them for 3 frames. Optional: `frames` from 1 to 3000. The keys are the same as the keys of a `press` step of a record file. |
51
52
  | `{ "runUntil": { "target": { "kind": "address", "address": "main_loop" }, "timeoutFrames": 600 } }` | Run until the CPU gets to an address. |
52
53
  | `{ "runUntil": { "target": { "kind": "memory", "address": "game_state", "operator": "eq", "value": 2 }, "timeoutFrames": 600 } }` | Run until a write to the byte makes the comparison with `value` true. `operator` is `eq`, `ne`, `lt`, `lte`, `gt` or `gte`. The run does not stop for a byte that is already true at the start. It also does not stop for a register that the hardware changes, for example `$d012`. For a raster line, use a `raster` target. |
53
54
  | `{ "runUntil": { "target": { "kind": "raster", "line": 250 }, "timeoutFrames": 5 } }` | Run until the raster beam gets to a line (0 to 311 for PAL, 0 to 262 for NTSC). Optional: `cycle` from 0 to 64. |
@@ -62,8 +63,6 @@ A `condition` has the `kind` `register`, `memory` or `raster`. A `register` cond
62
63
 
63
64
  `timeoutFrames` is from 1 to 30000, and 3000 by default. A `runUntil` that does not get to its target in `timeoutFrames` frames makes the result INCONCLUSIVE.
64
65
 
65
- A scenario has no `press` step. Only a record file has `press` for keys of the keyboard matrix.
66
-
67
66
  Each step except `observe` can have `"side": "original"` or `"side": "rebuild"`. Then only that side does the step. Use it when only one side needs a step, for example a key for the intro of the original. An `observe` step has no `side`, because it compares both sides.
68
67
 
69
68
  Each side finds a name in its own symbols.
@@ -10,8 +10,9 @@ import { isObject } from "#src/host-client/steps.ts";
10
10
  import { WireFailure } from "#src/host-client/tools.ts";
11
11
  import { readProjectFile, writeReported } from "#src/host-client/transfer.ts";
12
12
  import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
13
- import { checkSnapshotFile, hasSignature, VSF_SIGNATURE } from "#src/media.ts";
13
+ import { checkSnapshotFile } from "#src/media.ts";
14
14
  import { listed, UsageError } from "#src/script.ts";
15
+ import { snapshotModule } from "#src/vsf.ts";
15
16
  import { diffStates, type ChangedRange, type MachineState } from "./diff.ts";
16
17
 
17
18
  type Kind = "snapshot" | "memory" | "observation";
@@ -58,29 +59,14 @@ function cpuValues(registers: Record<string, unknown>): Record<string, number |
58
59
  return values;
59
60
  }
60
61
 
61
- /** The size of the header of a module in a VICE snapshot file: the name (16 bytes), the version (2 bytes) and the size (4 bytes). */
62
- const MODULE_HEADER = 22;
63
- const VSF_VERSION = "VICE Version\x1a";
64
-
65
62
  /**
66
63
  * The data of the C64MEM module of a VICE snapshot file: the data and the
67
64
  * direction register of the CPU port, the cartridge lines (2 bytes), then
68
65
  * the 64 KiB of RAM. Undefined when the file has no such module.
69
66
  */
70
67
  function c64Memory(file: Uint8Array): Buffer | undefined {
71
- const bytes = Buffer.from(file);
72
- if (!hasSignature("vsf", bytes)) return undefined;
73
- // The magic, the version (2 bytes) and the machine name (16 bytes); a newer VICE adds its own version (8 bytes).
74
- let at = VSF_SIGNATURE.length + 2 + 16;
75
- if (bytes.subarray(at, at + VSF_VERSION.length).toString("latin1") === VSF_VERSION) at += VSF_VERSION.length + 8;
76
- while (at + MODULE_HEADER <= bytes.length) {
77
- const name = bytes.subarray(at, at + 16).toString("latin1").replace(/\0+$/, "");
78
- const size = bytes.readUInt32LE(at + 18);
79
- if (size < MODULE_HEADER) return undefined;
80
- if (name === "C64MEM") return at + MODULE_HEADER + 4 + 0x10000 <= bytes.length ? bytes.subarray(at + MODULE_HEADER, at + MODULE_HEADER + 4 + 0x10000) : undefined;
81
- at += size;
82
- }
83
- return undefined;
68
+ const data = snapshotModule(Buffer.from(file), "C64MEM")?.data;
69
+ return data !== undefined && data.length >= 4 + 0x10000 ? data.subarray(0, 4 + 0x10000) : undefined;
84
70
  }
85
71
 
86
72
  /** The 64 KiB of C64 RAM that a VICE snapshot file holds, also the RAM under the CPU port at $00/$01. Undefined when the file has no C64MEM module. */
@@ -8,8 +8,8 @@
8
8
 
9
9
  import { createServer, type ServerResponse } from "node:http";
10
10
 
11
+ import { keyTaps, type KeyTap } from "#src/c64-keys.ts";
11
12
  import { PAL_FRAME_CYCLES, type C64RunSession } from "#src/native/c64run.ts";
12
- import { C64_KEYS, F_KEYS } from "./keys.ts";
13
13
 
14
14
  const FRAME_MS = 20;
15
15
 
@@ -27,45 +27,46 @@ export interface PlayOptions {
27
27
  restore: () => Promise<string | undefined>;
28
28
  }
29
29
 
30
- const C64 = C64_KEYS;
31
30
  const LETTERS = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
32
31
  const DIGITS = [..."0123456789"];
33
- const code = (character: string) => character.charCodeAt(0);
32
+ const F_KEYS = [1, 2, 3, 4, 5, 6, 7, 8].map((number) => `{F${number}}`);
33
+ /** The matrix places of one key, as a press step names it: a character, or a name in braces. */
34
+ const places = (key: string) => (keyTaps(key) as KeyTap[])[0]!.keys;
34
35
 
35
36
  /**
36
- * The key maps of the page. Each one maps a KeyboardEvent property to a key code.
37
- * The symbolic map (event.key) gives the character on the PC key; the positional
38
- * map (event.code) gives the C64 key at the place of the PC key, with each SHIFT alone.
37
+ * The key maps of the page. Each one maps a KeyboardEvent property to the matrix places
38
+ * that go down together. The symbolic map (event.key) gives the character on the PC key;
39
+ * the positional map (event.code) gives the C64 key at the place of the PC key, with each SHIFT alone.
39
40
  */
40
41
  export const KEY_MAPS = {
41
42
  /** event.code, in both maps. */
42
- both: { Tab: C64.ctrl, AltLeft: C64.cbm },
43
+ both: { Tab: places("{CTRL}"), AltLeft: places("{CBM}") },
43
44
  /** event.code, when the arrow keys and space are keyboard keys. */
44
- arrows: { ArrowUp: C64.csrUp, ArrowDown: C64.csrDown, ArrowLeft: C64.csrLeft, ArrowRight: C64.csrRight, Space: C64.space },
45
+ arrows: { ArrowUp: places("{UP}"), ArrowDown: places("{DOWN}"), ArrowLeft: places("{LEFT}"), ArrowRight: places("{RIGHT}"), Space: places(" ") },
45
46
  /** event.code */
46
47
  positional: {
47
- ...Object.fromEntries(LETTERS.map((letter) => ["Key" + letter, code(letter)])),
48
- ...Object.fromEntries(DIGITS.map((digit) => ["Digit" + digit, code(digit)])),
49
- ...Object.fromEntries(F_KEYS.map((key, index) => ["F" + (index + 1), key])),
50
- Backquote: C64.leftArrow, Minus: code("+"), Equal: code("-"), Insert: C64.pound, Home: C64.home, Backspace: C64.del,
51
- BracketLeft: code("@"), BracketRight: code("*"), Delete: C64.upArrow,
52
- Escape: C64.stop, Semicolon: code(":"), Quote: code(";"), Backslash: code("="), Enter: C64.return,
53
- ShiftLeft: C64.leftShift, ShiftRight: C64.rightShift, Comma: code(","), Period: code("."), Slash: code("/"),
54
- } as Record<string, number>,
48
+ ...Object.fromEntries(LETTERS.map((letter) => ["Key" + letter, places(letter)])),
49
+ ...Object.fromEntries(DIGITS.map((digit) => ["Digit" + digit, places(digit)])),
50
+ ...Object.fromEntries(F_KEYS.map((key, index) => ["F" + (index + 1), places(key)])),
51
+ Backquote: places("{LEFTARROW}"), Minus: places("+"), Equal: places("-"), Insert: places("{POUND}"), Home: places("{HOME}"), Backspace: places("{DEL}"),
52
+ BracketLeft: places("@"), BracketRight: places("*"), Delete: places("{UPARROW}"),
53
+ Escape: places("{STOP}"), Semicolon: places(":"), Quote: places(";"), Backslash: places("="), Enter: places("{RETURN}"),
54
+ ShiftLeft: places("{LSHIFT}"), ShiftRight: places("{RSHIFT}"), Comma: places(","), Period: places("."), Slash: places("/"),
55
+ } as Record<string, number[]>,
55
56
  /** event.key; a-z are the C64 letters, A-Z the letters with SHIFT. */
56
57
  symbolic: {
57
- ...Object.fromEntries(LETTERS.flatMap((letter) => [[letter.toLowerCase(), code(letter)], [letter, code(letter.toLowerCase())]])),
58
- ...Object.fromEntries([...DIGITS, ..."+-.:@,*;=/!\"#$%&'()[]<>?"].map((character) => [character, code(character)])),
59
- ...Object.fromEntries(F_KEYS.map((key, index) => ["F" + (index + 1), key])),
60
- "£": C64.pound, "^": C64.upArrow, "`": C64.leftArrow,
61
- Enter: C64.return, Backspace: C64.del, Delete: C64.del, Insert: C64.inst, Home: C64.home, Escape: C64.stop,
62
- } as Record<string, number>,
58
+ ...Object.fromEntries(LETTERS.flatMap((letter) => [[letter.toLowerCase(), places(letter)], [letter, places(`{LSHIFT+${letter}}`)]])),
59
+ ...Object.fromEntries([...DIGITS, ..."+-.:@,*;=/!\"#$%&'()[]<>?"].map((character) => [character, places(character)])),
60
+ ...Object.fromEntries(F_KEYS.map((key, index) => ["F" + (index + 1), places(key)])),
61
+ "£": places("{POUND}"), "^": places("{UPARROW}"), "`": places("{LEFTARROW}"),
62
+ Enter: places("{RETURN}"), Backspace: places("{DEL}"), Delete: places("{DEL}"), Insert: places("{INST}"), Home: places("{HOME}"), Escape: places("{STOP}"),
63
+ } as Record<string, number[]>,
63
64
  /** event.key with SHIFT held, in the symbolic map. */
64
- symbolicShift: { Home: C64.clr, Backspace: C64.inst, Escape: C64.run, F1: 0xf2, F3: 0xf4, F5: 0xf6, F7: 0xf8 } as Record<string, number>,
65
+ symbolicShift: { Home: places("{CLR}"), Backspace: places("{INST}"), Escape: places("{RUN}"), F1: places("{F2}"), F3: places("{F4}"), F5: places("{F6}"), F7: places("{F8}") } as Record<string, number[]>,
65
66
  };
66
67
 
67
- /** The key codes that the page can send: every code of the key maps. */
68
- const PAGE_KEYS = new Set(Object.values(KEY_MAPS).flatMap((map) => Object.values(map)));
68
+ /** The matrix places that the page can send: every place of the key maps. */
69
+ const PAGE_KEYS = new Set(Object.values(KEY_MAPS).flatMap((map) => Object.values(map).flat()));
69
70
 
70
71
  const PAGE = String.raw`<!doctype html>
71
72
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
@@ -96,7 +97,7 @@ const BITS = { ArrowUp: 1, ArrowDown: 2, ArrowLeft: 4, ArrowRight: 8, Space: 16
96
97
  const $ = (id) => document.getElementById(id);
97
98
  const canvas = $("screen"), context = canvas.getContext("2d"), state = $("state");
98
99
  let palette = [], image = context.createImageData(392, 272), frames = 0, phase = "connecting", port = 2, arrows = "joystick", keyMap = "symbolic", sent = -1;
99
- // The C64 key of each PC key that is down (by event.code), and the joystick keys that are down.
100
+ // The matrix places of each PC key that is down (by event.code), and the joystick keys that are down.
100
101
  const pressed = new Map(), stick = new Set();
101
102
  // One request at a time, so that the core gets each key down before its key up.
102
103
  let queue = Promise.resolve();
@@ -116,7 +117,7 @@ function show() {
116
117
  else state.textContent = phase;
117
118
  }
118
119
  function releaseAll() {
119
- for (const code of pressed.values()) send("key?code=" + code.toString(16) + "&down=0");
120
+ for (const keys of pressed.values()) send("key?keys=" + keys.join(",") + "&down=0");
120
121
  pressed.clear();
121
122
  stick.clear();
122
123
  }
@@ -176,19 +177,19 @@ function key(event, down) {
176
177
  }
177
178
  if (arrows === "joystick" && event.code in BITS) { event.preventDefault(); down ? stick.add(event.code) : stick.delete(event.code); return; }
178
179
  if (!down) {
179
- const code = pressed.get(event.code);
180
- if (code === undefined) return;
180
+ const keys = pressed.get(event.code);
181
+ if (keys === undefined) return;
181
182
  event.preventDefault();
182
183
  pressed.delete(event.code);
183
- send("key?code=" + code.toString(16) + "&down=0");
184
+ send("key?keys=" + keys.join(",") + "&down=0");
184
185
  return;
185
186
  }
186
- const code = c64Key(event);
187
- if (code === undefined) return;
187
+ const keys = c64Key(event);
188
+ if (keys === undefined) return;
188
189
  event.preventDefault();
189
190
  if (event.repeat || phase !== "playing" || pressed.has(event.code)) return;
190
- pressed.set(event.code, code);
191
- send("key?code=" + code.toString(16) + "&down=1");
191
+ pressed.set(event.code, keys);
192
+ send("key?keys=" + keys.join(",") + "&down=1");
192
193
  }
193
194
  addEventListener("keydown", (event) => key(event, true));
194
195
  addEventListener("keyup", (event) => key(event, false));
@@ -258,9 +259,10 @@ export async function play(core: Pick<C64RunSession, "command" | "status">, opti
258
259
  if (phase === "playing") mask = Number(url.searchParams.get("mask")) & 0x1f;
259
260
  answer(phase === "playing");
260
261
  } else if (request.method === "POST" && url.pathname === "/key") {
261
- const key = Number.parseInt(url.searchParams.get("code") ?? "", 16);
262
- if (!PAGE_KEYS.has(key)) return void response.writeHead(400).end();
263
- if (phase === "playing") pending.push("key " + key.toString(16) + " " + (url.searchParams.get("down") === "1" ? "down" : "up"));
262
+ const keys = (url.searchParams.get("keys") ?? "").split(",").map((key) => (/^\d{1,2}$/.test(key) ? Number(key) : -1));
263
+ if (!keys.every((key) => PAGE_KEYS.has(key))) return void response.writeHead(400).end();
264
+ const state = url.searchParams.get("down") === "1" ? "down" : "up";
265
+ if (phase === "playing") for (const key of keys) pending.push("key " + (0x80 + key).toString(16) + " " + state);
264
266
  answer(phase === "playing");
265
267
  } else if (request.method === "POST" && url.pathname === "/restore") {
266
268
  if (phase === "playing") pending.push(RESTORE);