diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 860a260..0036caf 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,7 +12,20 @@ on: jobs: test: - runs-on: ubuntu-latest + # The three the README hands the same zip to. The console is the same bytes on all of them -- + # nothing in mynes-core knows what a file separator is -- so what the second and third runner + # buy is everything that is not the console: the Swing panels every desktop test builds without + # a display, the sound card, the config file under a home directory, and the saves filed beside + # a ROM. Those are exactly the places a Java program still manages to be platform-specific. + strategy: + # One runner failing is a fact about that runner. Stopping the other two would throw away the + # thing worth knowing, which is whether it failed everywhere or only there. + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + + runs-on: ${{ matrix.os }} + steps: - uses: actions/checkout@v7 - name: Set up JDK 25 @@ -22,18 +35,24 @@ jobs: distribution: 'temurin' cache: 'maven' - # ~1.4GB of Tom Harte fixtures. The committed subset covers every opcode without - # this, so a cache miss that fails to download is not fatal to the test run. + # ~1.4GB of Tom Harte fixtures, on one runner rather than three. What they exercise is the + # 6502, which is the one part of this that cannot tell which machine it is running on, so + # fetching them again for the other two would cost three times the bandwidth to answer the + # same question. The committed subset covers every opcode everywhere, which is why the + # download is allowed to fail here at all: the other two runners test all 256 opcodes too, + # with 500 cases each instead of 10,000. # # Inside the module because HarteCaseLoader resolves the path relative to wherever # Surefire runs, which is the module rather than the checkout. - name: Cache 6502 test data + if: matrix.os == 'ubuntu-latest' uses: actions/cache@v6 with: path: mynes-core/testdata/nes6502 key: nes6502-${{ hashFiles('scripts/download-6502-tests.sh') }} - name: Download 6502 test data + if: matrix.os == 'ubuntu-latest' continue-on-error: true run: ./scripts/download-6502-tests.sh @@ -42,7 +61,13 @@ jobs: # Here rather than only in the release workflow, so that a distribution somebody has broken # fails on the pull request that broke it instead of at the moment a tag is pushed. + # + # Not on Windows, and not because bash is missing there: what this checks is that the + # launcher came out of the zip still executable, and a file mode is a question about the + # machine that wrote the zip rather than about the machine reading it. Windows has no answer + # to give, so asking it would be a step that either fails for no reason or passes for none. - name: Smoke test the distribution + if: runner.os != 'Windows' run: ./scripts/smoke-distribution.sh - name: Run tests diff --git a/CLAUDE.md b/CLAUDE.md index a7a9061..4a1b0ef 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1207,7 +1207,7 @@ Seven Maven modules, and the arrows between them only point one way. mynes-core/ depends on nothing mynes/ the console: CPU, PPU, APU, BUS, MMU, VRAM, Cart, Region, Overclock, controllers - mynes/mappers/ mappers 0 to 4 + mynes/mappers/ the twelve boards: 0 to 4, 7, 9 to 11, 66, 71, and 155 on MMC1's own class mynes/state/ save states, battery .sav files, and .mnm session recordings mynes/debug/ the disassembler, the breakpoints and their conditions, the tracer, and the meter that says how much of its frame the program used and which diff --git a/README.md b/README.md index 9c72fb4..e8a3fe9 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ file is where they live. - Toggles to hide the background or the sprite layer, and to take any of the five sound channels out of the mixer (`--mute pulse1,dmc` headless). -Not there yet: a second player, and Dendy (run as PAL for now). +Not there yet: a gamepad, the Zapper, and Dendy (run as PAL for now). ## Screenshots @@ -315,10 +315,10 @@ mvn -B package -DskipTests java -jar mynes-desktop/target/mynes.jar ``` -Four Maven modules — `mynes-core` (the console, no dependencies), `mynes-patch` (IPS), -`mynes-headless` (the command line) and `mynes-desktop` (the window) — flattened into one jar. -The same `mvn package` also produces the release zip. A fifth, `mynes-shots`, takes the pictures -above and is not in the jar. +Six Maven modules — `mynes-core` (the console, no dependencies), `mynes-patch` (IPS), +`mynes-archive` (zips), `mynes-midi` (MIDI files), `mynes-headless` (the command line) and +`mynes-desktop` (the window) — flattened into one jar. The same `mvn package` also produces the +release zip. A seventh, `mynes-shots`, takes the pictures above and is not in the jar. ## Tests diff --git a/mynes-core/src/main/java/com/github/dimiro1/mynes/CPU.java b/mynes-core/src/main/java/com/github/dimiro1/mynes/CPU.java index c1dc746..e303b1c 100644 --- a/mynes-core/src/main/java/com/github/dimiro1/mynes/CPU.java +++ b/mynes-core/src/main/java/com/github/dimiro1/mynes/CPU.java @@ -318,7 +318,9 @@ public void serialize(final StateIO io) { * that a freshly constructed CPU starts with. After this call the next {@link #tick()} * fetches an opcode from the supplied program counter. *

- * This method is primarily for testing purposes. + * Nothing in a running console ever does this: a machine reaches a state by having run to it. + * It is here for the Tom Harte fixtures, which hand over a whole architectural state and one + * instruction and ask what comes back out. * * @param state the state to load. */ diff --git a/mynes-core/src/main/java/com/github/dimiro1/mynes/Cart.java b/mynes-core/src/main/java/com/github/dimiro1/mynes/Cart.java index a9536af..3c2c910 100644 --- a/mynes-core/src/main/java/com/github/dimiro1/mynes/Cart.java +++ b/mynes-core/src/main/java/com/github/dimiro1/mynes/Cart.java @@ -21,10 +21,18 @@ import java.security.NoSuchAlgorithmException; /** - * Represents a NES game cartridge (ROM). + * A cartridge: the two ROMs on the board, the mapper wired to switch between them, and what the + * header said to build both from. *

- * A Cart contains the program ROM (PRG-ROM), character ROM (CHR-ROM), and the - * memory mapper implementation that controls bank switching and special hardware features. + * The header is kept beside the mapper rather than thrown away once it has been read, + * because the two disagree in ways worth being able to see. {@link #ram()} is what the header + * claimed is fitted, where {@link Mapper#prgRAM()} is what the board actually got -- and + * they differ wherever a header said nothing and the mapper fell back to the 8KB every board here + * has. {@link #mapperNumber()} and the class of {@link #mapper()} part company the same way, since + * 1 and 155 build one class between them. + *

+ * {@link #sha256()} is taken over the file as it arrived, header and any patch included, so it + * names what ran rather than what is on disk. * * @param filename the original filename of the ROM * @param prgROM program ROM data (CPU-addressable) diff --git a/mynes-core/src/main/java/com/github/dimiro1/mynes/Controller.java b/mynes-core/src/main/java/com/github/dimiro1/mynes/Controller.java index f0275e6..2460cb7 100644 --- a/mynes-core/src/main/java/com/github/dimiro1/mynes/Controller.java +++ b/mynes-core/src/main/java/com/github/dimiro1/mynes/Controller.java @@ -3,7 +3,18 @@ import com.github.dimiro1.mynes.state.StateIO; /** - * Represents a NES controller/joypad. + * A pad on one of the two ports: eight buttons, a shift register, and the strobe line that decides + * which of the two the register is following. + *

+ * Shaped like the hardware rather than like a set of button getters, because that is what + * every awkward case here turns on. A game never asks which buttons are down. It raises the strobe + * to make the register follow them, drops it to make the register hold them, and then clocks the + * bits out one read at a time -- so "what is being held" and "what the game has been told" are two + * different questions, which is why {@link #getButtons()} and {@link #read()} are both here and + * answer differently for most of a frame. + *

+ * Only the second of them is state the machine owns, and {@link #serialize} saves accordingly: the + * register and the strobe come back, and whose fingers were on what does not. */ public interface Controller { /** diff --git a/mynes-core/src/main/java/com/github/dimiro1/mynes/InvalidNesFileException.java b/mynes-core/src/main/java/com/github/dimiro1/mynes/InvalidNesFileException.java index 672be27..fee047c 100644 --- a/mynes-core/src/main/java/com/github/dimiro1/mynes/InvalidNesFileException.java +++ b/mynes-core/src/main/java/com/github/dimiro1/mynes/InvalidNesFileException.java @@ -1,16 +1,13 @@ package com.github.dimiro1.mynes; /** - * Exception thrown when attempting to load an invalid or malformed NES ROM file. + * A file that is not a cartridge at all. *

- * This exception is thrown when a file fails to meet the iNES format specifications, - * such as: - *

+ * The sibling of {@link UnsupportedMapperException}, and the line between the two is worth keeping. + * This one means the bytes are not an iNES or NES 2.0 image -- the wrong four at the front, or a + * header promising more banks than the file has left to give. That one means the image parsed + * perfectly and named a board nobody has written. The first is somebody's file being wrong; the + * second is this emulator being unfinished, and only one of them is worth reporting. */ public class InvalidNesFileException extends RuntimeException { /** diff --git a/mynes-core/src/main/java/com/github/dimiro1/mynes/UnsupportedMapperException.java b/mynes-core/src/main/java/com/github/dimiro1/mynes/UnsupportedMapperException.java index d9225d1..e7de465 100644 --- a/mynes-core/src/main/java/com/github/dimiro1/mynes/UnsupportedMapperException.java +++ b/mynes-core/src/main/java/com/github/dimiro1/mynes/UnsupportedMapperException.java @@ -1,19 +1,75 @@ package com.github.dimiro1.mynes; +import java.util.Map; + /** - * Exception thrown when attempting to load a ROM that uses an unsupported mapper. + * A cartridge whose board nobody has written. + *

+ * The number is the least useful half of the answer. A mapper number names a circuit rather + * than a chip -- what the cartridge does with the fifteen address lines and eight data lines the + * port gives it -- and there are hundreds of them where this runs twelve. Somebody told their file + * wants mapper 69 has to go and look up what 69 is before they know whether it is a famous board, a + * pirate multicart, or a header somebody filled in wrongly; told it wants Sunsoft FME-7, they + * already know. *

- * The NES used various memory mappers (MMC chips) to extend the capabilities - * of the base hardware. This emulator may not support all mapper types. + * So the boards are named. Not all of them -- the tail is hundreds of bootleg conversions nobody + * loads on purpose -- but every one a real release shipped on, which is the set a collection can + * actually hand this. The names are the ones NESdev's list prints, because that is what somebody + * will search for next. + * + * @see NESdev: list of mappers */ public class UnsupportedMapperException extends RuntimeException { + + /** + * What each unsupported board is called, for the numbers a real cartridge carries. + *

+ * Only boards this does not run: the twelve it does never reach here, and an entry for + * one of them would be a second place to update when a thirteenth is written. + */ + private static final Map BOARDS = Map.ofEntries( + Map.entry(5, "MMC5"), + Map.entry(16, "the Bandai FCG board"), + Map.entry(18, "Jaleco SS8806"), + Map.entry(19, "Namco 163"), + Map.entry(20, "the Famicom Disk System"), + Map.entry(21, "Konami VRC4a or VRC4c"), + Map.entry(22, "Konami VRC2a"), + Map.entry(23, "Konami VRC2b or VRC4e"), + Map.entry(24, "Konami VRC6a"), + Map.entry(25, "Konami VRC4b or VRC4d"), + Map.entry(26, "Konami VRC6b"), + Map.entry(34, "BNROM or NINA-001"), + Map.entry(64, "Tengen RAMBO-1"), + Map.entry(68, "Sunsoft-4"), + Map.entry(69, "Sunsoft FME-7 or 5B"), + Map.entry(73, "Konami VRC3"), + Map.entry(75, "Konami VRC1"), + Map.entry(76, "Namco 109"), + Map.entry(85, "Konami VRC7"), + Map.entry(118, "TxSROM, an MMC3 variant"), + Map.entry(119, "TQROM, an MMC3 variant"), + Map.entry(180, "UNROM wired the way Crazy Climber has it"), + Map.entry(185, "CNROM with protection diodes"), + Map.entry(206, "DxROM, or Namco 118"), + Map.entry(210, "Namco 175 or 340"), + Map.entry(232, "the Camerica Quattro board")); + /** * Creates a new exception for an unsupported mapper. * - * @param mapperNumber the mapper number that is not supported - * @param filename the ROM file that uses this mapper + * @param mapperNumber the mapper number the header asked for + * @param filename the ROM that asked for it, which is what somebody has to go and look at */ public UnsupportedMapperException(final int mapperNumber, final String filename) { - super("Mapper " + mapperNumber + " is not supported in file: " + filename); + super(message(mapperNumber, filename)); + } + + private static String message(final int mapperNumber, final String filename) { + var board = BOARDS.get(mapperNumber); + + return filename + " wants mapper " + mapperNumber + + (board == null ? "" : ", " + board) + + ", which this does not run."; } } diff --git a/mynes-core/src/test/java/com/github/dimiro1/mynes/cart/CartTests.java b/mynes-core/src/test/java/com/github/dimiro1/mynes/cart/CartTests.java index a773cf6..6e99fc4 100644 --- a/mynes-core/src/test/java/com/github/dimiro1/mynes/cart/CartTests.java +++ b/mynes-core/src/test/java/com/github/dimiro1/mynes/cart/CartTests.java @@ -60,20 +60,43 @@ void loadInvalid() throws IOException { } /** - * The mapper number is split across the high nibbles of flags 6 and 7. Reading it wrongly is - * silent: an unsupported cart loads as mapper 0 and then misbehaves at run time instead of - * being rejected here. + * A board nobody has written is refused here rather than run wrongly, which is the whole of why + * this is an exception and not a warning: reading the mapper number wrongly is otherwise silent, + * and an unsupported cart that loaded as mapper 0 would misbehave at run time instead. + *

+ * The number alone means nothing to somebody holding a cartridge, so a board this knows the name + * of is named. Both halves are asserted: a message that dropped the file would leave somebody + * with a collection open guessing which of it failed. */ @Test - void loadUnsupportedMapper() { - var rom = synthesizeRom(0x50, 0x00); // mapper 5, MMC5 + void theRefusalNamesTheBoardWhenItKnowsWhatOneIsCalled() { + var rom = synthesizeRom(0x50, 0x00); // mapper 5 var thrown = assertThrowsExactly( - UnsupportedMapperException.class, - () -> Cart.load(rom, "mapper5.nes") - ); + UnsupportedMapperException.class, () -> Cart.load(rom, "mapper5.nes")); + + assertTrue(thrown.getMessage().contains("MMC5"), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("mapper5.nes"), thrown.getMessage()); + } - assertTrue(thrown.getMessage().contains("5"), "should name the mapper: " + thrown.getMessage()); + /** + * The table stops at the boards a real release shipped on, so most numbers are not in it. That + * is the common case rather than the edge one -- the refusal still has to read as a sentence, + * with no gap where the name would have gone. + */ + @Test + void theRefusalReadsAsASentenceForABoardNobodyHasNamed() { + var rom = synthesizeRom(0xE0, 0xC0); // mapper 206, which is named + var named = assertThrowsExactly( + UnsupportedMapperException.class, () -> Cart.load(rom, "known.nes")); + + var unknown = synthesizeRom(0x80, 0xD0); // mapper 216, which is not + var bare = assertThrowsExactly( + UnsupportedMapperException.class, () -> Cart.load(unknown, "unknown.nes")); + + assertEquals("known.nes wants mapper 206, DxROM, or Namco 118, which this does not run.", + named.getMessage()); + assertEquals("unknown.nes wants mapper 216, which this does not run.", bare.getMessage()); } @ParameterizedTest(name = "mapper ${0} loads as ${1}") diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/BatterySaves.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/BatterySaves.java new file mode 100644 index 0000000..4c5f5e4 --- /dev/null +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/BatterySaves.java @@ -0,0 +1,169 @@ +package com.github.dimiro1.mynes.ui; + +import com.github.dimiro1.mynes.NES; +import com.github.dimiro1.mynes.state.BatteryRAM; + +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import java.awt.Component; +import java.io.IOException; +import java.lang.System.Logger; +import java.lang.System.Logger.Level; +import java.nio.file.Path; +import java.util.Arrays; + +/** + * The cartridge's {@code .sav} file, kept in step with the chip the game is writing to. + *

+ * A class rather than three methods on the window because there is a rule in here that needs + * a memory of its own: the file is written when the bytes have changed and not otherwise, which + * takes a copy of what they held last time. {@link #shadow} is that copy, and it is the whole + * reason this is an object. A game that saves once an hour costs one file write an hour and one + * array comparison a minute for the rest of it. + *

+ * Three entry points on two threads, and the difference is not cosmetic. {@link #load} and + * {@link #save} are called with the emulation thread stopped or not yet started, which is what + * makes reading the machine from the event dispatch thread safe there, and they put their dialogs + * up directly. {@link #autosave} runs on the emulation thread, which is what makes reading + * the mapper's array safe there -- so its dialog has to be handed back to the event dispatch + * thread, the only one allowed to put one on the screen. + *

+ * Which file is not decided here. The window works out the game's path -- a romhack is filed apart + * from the cartridge it was cut against, and a cartridge out of a zip is filed beside the zip -- + * and hands it in, because that decision belongs to whatever knows what was opened. + */ +final class BatterySaves { + + private static final Logger logger = System.getLogger("UI"); + + /** + * How often the cartridge RAM is checked and written out while a game is running. + *

+ * There is a save on quit and one on changing cartridges, and neither helps the laptop that runs + * out of power mid-dungeon. A minute of lost progress is a tolerable worst case, and the check + * costs an {@link Arrays#equals} against a shadow copy -- so nothing is written unless the game + * has actually saved something, and nothing is added to the hot path of every store to $6000, + * which a dirty flag on the mapper would have been. + *

+ * A minute is also far too long to be worth its own thread, so the window runs it off a Swing + * timer and posts the work to the machine's. + */ + static final int AUTOSAVE_MILLIS = 60_000; + + private final Component parent; + + /** + * What the cartridge's RAM held the last time it was written out, or when the machine started. + *

+ * Compared against rather than trusting a flag, because there is no flag: nothing in the + * hardware says "the game has saved". A board with a battery on it is one whose RAM survives + * the power going off, and a game writes to it whenever it likes. + */ + private byte[] shadow = new byte[0]; + + BatterySaves(final Component parent) { + this.parent = parent; + } + + /** + * Fills the cartridge's RAM from its {@code .sav} file, if it has a battery and there is one. + */ + void load(final NES nes, final Path gamePath) { + if (nes == null || gamePath == null || !BatteryRAM.isWorthSaving(nes)) { + return; + } + + var path = BatteryRAM.pathFor(gamePath); + + try { + var read = BatteryRAM.read(nes, path); + + if (read >= 0) { + logger.log(Level.INFO, + "restored " + read + " bytes of save RAM from " + path.getFileName()); + } + } catch (IOException e) { + // Worth a dialog rather than a log line: carrying on means the game says the save file + // is corrupt, and the player deserves to know it was the emulator that could not read + // it. + logger.log(Level.ERROR, "could not read the save file", e); + JOptionPane.showMessageDialog( + parent, + "Could not read " + path.getFileName() + ": " + e.getMessage() + + "\n\nThe game will start as though its battery were flat.", + "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + /** + * Takes the copy every later {@link #autosave} is compared against. + *

+ * Called once the machine has its battery, so that whatever the RAM arrived holding is the + * starting point and the first check after a load does not rewrite an unchanged file. + */ + void track(final NES nes) { + shadow = nes.getBus().getMapper().prgRAM().clone(); + } + + /** + * Writes the cartridge's RAM out, if a real console would have kept it. + *

+ * Unconditional, unlike {@link #autosave}: the callers are the window closing and a cartridge + * being replaced, and neither gets a second chance to be right. + */ + void save(final NES nes, final Path gamePath) { + if (nes == null || gamePath == null || !BatteryRAM.isWorthSaving(nes)) { + return; + } + + var path = BatteryRAM.pathFor(gamePath); + + try { + BatteryRAM.write(nes, path); + logger.log(Level.INFO, "wrote save RAM to " + path.getFileName()); + } catch (IOException e) { + logger.log(Level.ERROR, "could not write the save file", e); + JOptionPane.showMessageDialog( + parent, + "Could not write " + path.getFileName() + ": " + e.getMessage() + + "\n\nThe game's progress since it was last saved may be lost.", + "Error", + JOptionPane.ERROR_MESSAGE); + } + } + + /** + * Writes the cartridge RAM out if the game has changed it since the last time, and does nothing + * at all if it has not. + *

+ * Runs on the emulation thread. + */ + void autosave(final NES nes, final Path gamePath) { + if (nes == null || gamePath == null || !BatteryRAM.isWorthSaving(nes)) { + return; + } + + var ram = nes.getBus().getMapper().prgRAM(); + + if (Arrays.equals(ram, shadow)) { + return; + } + + var path = BatteryRAM.pathFor(gamePath); + + try { + BatteryRAM.write(nes, path); + shadow = ram.clone(); + logger.log(Level.INFO, "the game saved, so " + path.getFileName() + " was written"); + } catch (IOException e) { + // Hopped back onto the event dispatch thread, which is the only one allowed to put a + // dialog on the screen -- this is the one of the three that is not already on it. + var what = "Could not write " + path.getFileName(); + + logger.log(Level.ERROR, what, e); + SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog( + parent, what + ": " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE)); + } + } +} diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/EmulationSpeed.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/EmulationSpeed.java index d4e88e5..f973230 100644 --- a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/EmulationSpeed.java +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/EmulationSpeed.java @@ -22,9 +22,11 @@ *

* {@link #UNLIMITED} is the odd one out, and deliberately so: it does not wait at all, so how fast * it goes is a fact about the computer rather than about the setting. On the machine this was - * written on that is around ten times, which is also the ceiling the numbered speeds sit under. - * Asking for more than the host can manage is not an error -- the loop simply never catches up with - * its deadline and the machine runs at whatever the host does manage. + * written on the console runs at about four times -- unpaced, with nothing hashed and no picture + * drawn -- and that is the ceiling the numbered speeds sit under too, so {@link #EIGHT_TIMES} is + * above it and comes out wherever {@link #UNLIMITED} does. Asking for more than the host can manage + * is not an error: the loop simply never catches up with its deadline and the machine runs at + * whatever the host does manage. */ public enum EmulationSpeed { NORMAL("1x", "Normal", 1), diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/GameUIFrame.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/GameUIFrame.java index 78411f6..4ee705f 100644 --- a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/GameUIFrame.java +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/GameUIFrame.java @@ -14,7 +14,6 @@ import com.github.dimiro1.mynes.debug.Debugger; import com.github.dimiro1.mynes.debug.Tracer; import com.github.dimiro1.mynes.patch.IPSPatch; -import com.github.dimiro1.mynes.state.BatteryRAM; import com.github.dimiro1.mynes.state.Movie; import com.github.dimiro1.mynes.state.MovieException; import com.github.dimiro1.mynes.state.Rewind; @@ -46,25 +45,14 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.Arrays; -import java.util.Locale; // Explicitly, because java.awt.* is on demand above and brings a List of its own with it. import java.util.List; import java.util.function.Consumer; -import java.util.function.IntConsumer; import java.util.stream.Collectors; public class GameUIFrame extends JFrame { private static final Logger logger = System.getLogger("UI"); - /** - * How many save state slots there are. Nine because that is how many fit on the number row, and - * because a tenth would be the one nobody could remember what they put in. - */ - private static final int SLOTS = 9; - /** * What a cartridge inside a zip is called. The only one: this runs iNES and NES 2.0 images, and * a zip full of names nobody recognises is better refused with a list of what was in it than @@ -72,17 +60,6 @@ public class GameUIFrame extends JFrame { */ private static final String ROM_EXTENSION = "nes"; - /** - * How often the cartridge RAM is checked and written out while a game is running. - *

- * There is a save on quit and one on changing cartridges, and neither helps the laptop that runs - * out of power mid-dungeon. A minute of lost progress is a tolerable worst case, and the check - * costs an {@link java.util.Arrays#equals} against a shadow copy -- so nothing is written unless - * the game has actually saved something, and nothing is added to the hot path of every store to - * $6000, which a dirty flag on the mapper would have been. - */ - private static final int BATTERY_AUTOSAVE_MILLIS = 60_000; - /** * How often the status bar is worked out again, and so the window the frame rate is measured * over. @@ -132,6 +109,18 @@ public class GameUIFrame extends JFrame { private final SystemFileChooser traceChooser; private final SystemFileChooser musicChooser; + /** + * The cartridge's {@code .sav} file. Holds the copy the autosave compares against, which is why + * it is an object rather than three methods here. + */ + private final BatterySaves battery = new BatterySaves(this); + + /** + * The nine slots and the two quick items. Holds which slot is current and what each one says; + * the writing and the reading stay here, since they need the machine and its thread. + */ + private final SaveSlots slots = new SaveSlots(this::saveSlot, this::loadSlot); + private final ScreenComponent screen = new ScreenComponent(); private final StatusBar statusBar = new StatusBar(); private final KeyboardInput keyboardInput; @@ -184,11 +173,6 @@ public class GameUIFrame extends JFrame { * The Load State items, kept so the menu can relabel them with what is in each slot and grey out * the ones with nothing in them. */ - private final JMenuItem[] loadSlotItems = new JMenuItem[SLOTS]; - - private final JMenuItem machineMenuQuickSave = new JMenuItem("Quick Save"); - private final JMenuItem machineMenuQuickLoad = new JMenuItem("Quick Load"); - /** * The four movie items, and the two things a movie will not survive. *

@@ -310,18 +294,6 @@ public void setPaused(final boolean paused) { */ private Path patchPath; - /** - * Which slot the two quick items use. Whichever was last picked from either submenu, so the pair - * of keys and the menus are one setting rather than two. - */ - private int currentSlot = 1; - - /** - * What the cartridge RAM held when it was last written to disk, so the autosave can tell whether - * the game has saved anything since. Touched only on the emulation thread. - */ - private byte[] batteryShadow = new byte[0]; - /** * Whether a movie is being recorded, and where it is going when it stops. *

@@ -497,19 +469,11 @@ private void init() { machineMenu.addSeparator(); - machineMenu.add(slotMenu("Save State", this::saveSlot, null)); - machineMenu.add(slotMenu("Load State", this::loadSlot, loadSlotItems)); + machineMenu.add(slots.saveMenu()); + machineMenu.add(slots.loadMenu()); - // Function keys, for three reasons. They sit in the same physical place on every keyboard - // layout, which a letter does not -- this one is Colemak-DH. F5 and F7 are what ZSNES and - // SNES9x used, so they are the keys a player already has in their fingers. And they need no - // modifier, which matters here: Shift is bound to Select, so KeyboardInput deliberately does - // not treat it as a shortcut modifier and any Shift+key shortcut would be a hazard. - machineMenuQuickSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); - machineMenu.add(machineMenuQuickSave); - - machineMenuQuickLoad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0)); - machineMenu.add(machineMenuQuickLoad); + machineMenu.add(slots.quickSaveItem()); + machineMenu.add(slots.quickLoadItem()); machineMenu.addSeparator(); @@ -737,9 +701,6 @@ public void actionPerformed(final ActionEvent e) { } }); - machineMenuQuickSave.addActionListener(e -> saveSlot(currentSlot)); - machineMenuQuickLoad.addActionListener(e -> loadSlot(currentSlot)); - machineMenuRecord.addActionListener(e -> startRecording()); machineMenuStopRecording.addActionListener(e -> stopRecording()); machineMenuPlay.addActionListener(e -> playMovie()); @@ -774,7 +735,7 @@ public void menuCanceled(final MenuEvent e) { machineMenu.addMenuListener(new MenuListener() { @Override public void menuSelected(final MenuEvent e) { - describeSlots(); + slots.describe(romPath == null ? null : gamePath()); } @Override @@ -838,7 +799,7 @@ public void windowClosing(final WindowEvent e) { // After the runner has stopped, so the machine is this thread's to read. Last chance: // the process is about to go, and a battery game that was not written here is an hour // of somebody's evening. - saveBattery(); + battery.save(nes, gamePath()); // And a trace holds up to sixty-four kilobytes of instructions that have not reached // the disk yet, which is the end of whatever the file was opened to look at. @@ -871,9 +832,18 @@ public void windowActivated(final WindowEvent e) { // A minute is far too long to be worth its own thread, and a Swing timer only fires on the // event dispatch thread -- so all it does is post the real work to the machine's own thread, // the same way the CHR viewer's refresh does. - var autosave = new Timer(BATTERY_AUTOSAVE_MILLIS, e -> { + // + // Which machine and which file are both read here rather than inside the posted task, + // because this is the thread that writes them: startMachine runs on the event dispatch + // thread, so a pair taken here is a machine and the path its own saves go to, where two + // reads on the far side could straddle a cartridge being swapped and file one game's RAM + // under another's name. + var autosave = new Timer(BatterySaves.AUTOSAVE_MILLIS, e -> { if (runner != null) { - runner.post(this::autosaveBattery); + var machine = nes; + var path = gamePath(); + + runner.post(() -> battery.autosave(machine, path)); } }); @@ -1375,13 +1345,32 @@ private void applyVideoFilter() { * for. */ private void applyCrop() { - // Asked of the content pane on either side of the change, the way applyStatusBar asks it - // and for the same reason: the difference is the rows and the columns, however big the - // magnification makes them. + repackAround(() -> { + screen.setOverscan(config.overscan()); + screen.setLeftEdge(config.leftEdge()); + }); + } + + /** + * Makes a change that moves how much room the picture asks for, and gives the window the + * difference. + *

+ * Written once because the two callers really are the same arithmetic. Show Overscan and + * Show Left Edge decide how many of the chip's rows and columns are picture, and TV Aspect Ratio + * decides how wide one of those columns is drawn -- three questions about the same rectangle, so + * a window that answered them differently would be the bug. Which is also why the size is asked + * of the content pane on either side of the change rather than worked out: the difference is + * whatever moved, however big the magnification makes it, and neither reading has to know which + * of the three it was. + *

+ * A full screen window is packed nowhere, because packing one would hand it back a size while + * the display still held it. What takes the difference there is the size it will be given back, + * so that leaving full screen does not land on a shape decided before any of this was asked for. + */ + private void repackAround(final Runnable change) { var before = getContentPane().getPreferredSize(); - screen.setOverscan(config.overscan()); - screen.setLeftEdge(config.leftEdge()); + change.run(); var after = getContentPane().getPreferredSize(); @@ -1420,26 +1409,12 @@ private void applyPixelAspect() { * The same, for the tick rather than for the cartridge: the shape changes and the window is * given the columns rather than having them taken out of the picture. *

- * {@link #applyCrop} down to the arithmetic -- it measures the content pane on either side of - * the change and hands a full screen window's share to the size waiting for it, because a - * display decides how big a full screen window is and the four screen sizes are greyed out - * there for the same reason. What differs is only what moved: that one takes rows and columns - * off the frame, and this one stretches the columns that are left. + * {@link #applyCrop} down to the arithmetic, which is why both go through + * {@link #repackAround}. What differs is only what moved: that one takes rows and columns off + * the frame, and this one stretches the columns that are left. */ private void applyTvAspect() { - var before = getContentPane().getPreferredSize(); - - applyPixelAspect(); - - var after = getContentPane().getPreferredSize(); - - if (switches.fullScreen().isOn()) { - growWindowedBounds(after.width - before.width, after.height - before.height); - } else { - pack(); - } - - updateStatusBar(); + repackAround(this::applyPixelAspect); } /** @@ -1537,6 +1512,10 @@ private void measureFrameRate() { * remember to announce itself to the bar would be the one that eventually did not. */ private void updateStatusBar() { + updateStatusBar(describe()); + } + + private void updateStatusBar(final MachineDescription description) { // With no machine there is no overclock on one, so the menu's answer stands in -- otherwise // the bar would say a machine is running the hardware's timing while the Hacks menu has // +50% ticked. Everything else here is read the same way for the same reason: what is on @@ -1564,7 +1543,7 @@ private void updateStatusBar() { config.volume(), config.audioLatencyMs())); - statusBar.setActivity(machineState()); + statusBar.setActivity(description.state()); } /** @@ -1835,124 +1814,6 @@ private void resumeFromBackground() { describeMachine(); } - /** - * Fills the cartridge's RAM from its {@code .sav} file, if it has a battery and there is one. - *

- * Only ever called with the emulation thread stopped or not yet started. - */ - private void loadBattery() { - if (romPath == null || !BatteryRAM.isWorthSaving(nes)) { - return; - } - - var path = BatteryRAM.pathFor(gamePath()); - - try { - var read = BatteryRAM.read(nes, path); - - if (read >= 0) { - logger.log(Level.INFO, "restored " + read + " bytes of save RAM from " + path.getFileName()); - } - } catch (IOException e) { - // Worth a dialog rather than a log line: carrying on means the game says the save file is - // corrupt, and the player deserves to know it was the emulator that could not read it. - logger.log(Level.ERROR, "could not read the save file", e); - JOptionPane.showMessageDialog( - this, - "Could not read " + path.getFileName() + ": " + e.getMessage() - + "\n\nThe game will start as though its battery were flat.", - "Error", - JOptionPane.ERROR_MESSAGE); - } - } - - /** - * Writes the cartridge's RAM out, if a real console would have kept it. - *

- * Only ever called with the emulation thread stopped, which is what makes reading the machine from - * the event dispatch thread safe here. - */ - private void saveBattery() { - if (nes == null || romPath == null || !BatteryRAM.isWorthSaving(nes)) { - return; - } - - var path = BatteryRAM.pathFor(gamePath()); - - try { - BatteryRAM.write(nes, path); - logger.log(Level.INFO, "wrote save RAM to " + path.getFileName()); - } catch (IOException e) { - logger.log(Level.ERROR, "could not write the save file", e); - JOptionPane.showMessageDialog( - this, - "Could not write " + path.getFileName() + ": " + e.getMessage() - + "\n\nThe game's progress since it was last saved may be lost.", - "Error", - JOptionPane.ERROR_MESSAGE); - } - } - - /** - * Writes the cartridge RAM out if the game has changed it since the last time. - *

- * Runs on the emulation thread, which is what makes reading the mapper's array safe. Comparing - * against a shadow copy rather than trusting a flag means a game that writes its save once an hour - * costs one file write an hour, and one array comparison a minute the rest of the time. - */ - private void autosaveBattery() { - if (romPath == null || !BatteryRAM.isWorthSaving(nes)) { - return; - } - - var ram = nes.getBus().getMapper().prgRAM(); - - if (Arrays.equals(ram, batteryShadow)) { - return; - } - - var path = BatteryRAM.pathFor(gamePath()); - - try { - BatteryRAM.write(nes, path); - batteryShadow = ram.clone(); - logger.log(Level.INFO, "the game saved, so " + path.getFileName() + " was written"); - } catch (IOException e) { - report("Could not write " + path.getFileName(), e); - } - } - - /** - * Builds one of the two slot submenus, nine items numbered from one. - * - * @param items where to keep the items for later relabelling, or null if they never change. - */ - private JMenu slotMenu(final String title, final IntConsumer action, final JMenuItem[] items) { - var menu = new JMenu(title); - - for (var slot = 1; slot <= SLOTS; slot++) { - var item = new JMenuItem("Slot " + slot); - var chosen = slot; - - // No accelerators on these eighteen. Command-1 to Command-9 is "switch tab" everywhere - // else, and eighteen global shortcuts for something two keys already do would be - // eighteen chances to collide with a game's controls. - item.addActionListener(e -> { - currentSlot = chosen; - action.accept(chosen); - describeQuickItems(); - }); - - if (items != null) { - items[slot - 1] = item; - } - - menu.add(item); - } - - return menu; - } - /** * Writes the machine into a slot. *

@@ -1967,7 +1828,7 @@ private void saveSlot(final int slot) { return; } - var path = slotPath(slot); + var path = SaveState.slotPath(gamePath(), slot); runner.post(() -> { try { @@ -1984,7 +1845,7 @@ private void loadSlot(final int slot) { return; } - var path = slotPath(slot); + var path = SaveState.slotPath(gamePath(), slot); if (!Files.exists(path)) { // Worth saying out loud rather than doing nothing: the keys are one press apart, and a @@ -2211,49 +2072,12 @@ private void updateMovieItems() { switches.overclock().setEnabled(!busy); } - /** - * Puts what is in each slot onto its menu item, and greys out the empty ones. - *

- * This is what makes nine numbered slots usable instead of a guessing game, and it is why the - * state's header is not compressed: nine files get their frame number read without any of them - * being inflated. - */ - private void describeSlots() { - describeQuickItems(); - - for (var slot = 1; slot <= SLOTS; slot++) { - var item = loadSlotItems[slot - 1]; - var path = romPath == null ? null : slotPath(slot); - - if (path == null || !Files.exists(path)) { - item.setText("Slot " + slot); - item.setEnabled(false); - continue; - } - - item.setEnabled(true); - - try { - var header = SaveState.header(path); - var when = Files.getLastModifiedTime(path).toInstant() - .atZone(ZoneId.systemDefault()) - .format(DateTimeFormatter.ofPattern("d MMM HH:mm")); - - item.setText("Slot " + slot + " — frame " + header.frame() + ", " + when); - } catch (IOException | SaveStateException ex) { - // A file that will not even give up its header is still offered, because refusing to - // list it would hide the only clue that something is wrong with it. - item.setText("Slot " + slot + " — unreadable"); - } - } - } - /** * Puts the games somebody has opened onto Open Recent, and greys out the ones whose files are * not where they were left. *

- * Greyed rather than dropped, which is the same answer {@link #describeSlots} gives for a slot - * with nothing in it: a cartridge on a volume that is not mounted this afternoon is still the + * Greyed rather than dropped, which is the same answer {@link SaveSlots#describe} gives for a + * slot with nothing in it: a cartridge on a volume that is not mounted this afternoon is still the * game somebody was playing, and a list that quietly shortened itself every time a drive was * unplugged would be worse than one with a dead entry in it. */ @@ -2300,18 +2124,6 @@ private void describeRecent() { fileMenuOpenRecent.add(clear); } - private void describeQuickItems() { - machineMenuQuickSave.setText("Quick Save (Slot " + currentSlot + ")"); - machineMenuQuickLoad.setText("Quick Load (Slot " + currentSlot + ")"); - } - - /** - * Where a slot lives: beside the ROM, numbered, with {@code .mn} for "MyNES". - */ - private Path slotPath(final int slot) { - return SaveState.slotPath(gamePath(), slot); - } - /** * Tells the player about a failure that happened on the emulation thread. *

@@ -2564,7 +2376,7 @@ private void startMachine( // fields still name the outgoing game, and saving after they had moved would write the // outgoing game's RAM into the incoming game's .sav -- which the incoming game would then // read back as its own progress. - saveBattery(); + battery.save(nes, gamePath()); // Power Cycle and Region are greyed out while a movie is running, so the only way here with // one in progress is a new cartridge -- which is a decision worth honouring rather than @@ -2680,11 +2492,11 @@ private void startMachine( // The cartridge finds its battery already charged, which is what a real one did. In the same // window as the two lines above: the runner does not exist yet, so this thread owns the // machine. - loadBattery(); + battery.load(nes, gamePath()); // What the autosave compares against from here on: whatever the battery arrived holding, so // the first check after a load does not rewrite an unchanged file. - batteryShadow = nes.getBus().getMapper().prgRAM().clone(); + battery.track(nes); // Each machine brings its own controllers, so the keyboard has to be pointed at the new // pair. Nothing races: the old runner has already stopped and this is the event dispatch @@ -2793,125 +2605,36 @@ private void saveConfig() { * disagreeing with itself. */ private void describeMachine() { - updateTitle(); - updateStatusBar(); - - if (controlPanel != null) { - controlPanel.setRunning(dashboardLine()); - } - } - - /** - * The control panel's first line: how the machine is being run. - *

- * Everything on it is the window's rather than the machine's -- whether the loop is paused, - * what the rate has measured, which cartridge somebody put in, whether a movie is going -- and - * none of it can be read off the NES at all, which is why the panel is handed it written rather - * than working it out. Whichever frame the machine has reached is on the line below, with the - * rest of what the machine is doing. - */ - private String dashboardLine() { - var parts = new java.util.ArrayList(); - - parts.add(runner == null ? "No machine" : runner.isPaused() ? "Paused" : "Running"); - - if (lastFrameRate != FrameRate.UNKNOWN) { - parts.add(lastFrameRate + " fps"); - } - - parts.add(currentRegion().label()); - - if (cart != null) { - parts.add(String.format( - "%s (mapper %d, %dK+%dK)", - cart.filename(), - cart.mapperNumber(), - cart.prgROM().length / 1024, - cart.chrROM().length / 1024)); - } + var description = describe(); - var activity = machineState(); + setTitle(description.title()); + updateStatusBar(description); - if (!activity.isEmpty() && !"Paused".equals(activity)) { - parts.add(activity); - } - - return String.join(" · ", parts); - } - - private void updateTitle() { - if (cart == null) { - setTitle("MyNES"); - return; + if (controlPanel != null) { + controlPanel.setRunning(description.dashboard()); } - - var state = machineState(); - - setTitle("MyNES - " + cart.filename() + patched() + machineKind() - + (state.isEmpty() ? "" : " (" + state.toLowerCase(Locale.ROOT) + ")")); - } - - /** - * Which hack is playing, when one is. - *

- * The cartridge's own name is still first: a patched game is that game plus a patch, and a title - * bar naming only the patch would leave nothing to say which ROM it was applied to. - */ - private String patched() { - return patchPath == null ? "" : " + " + patchPath.getFileName(); - } - - /** - * The kind of machine, when it is not the usual one. - *

- * Only PAL is worth the words. A machine's region is invisible from the picture until something - * is wrong, and when it is wrong -- a game running fast because the header said nothing -- this - * is the line that says which way to reach for. - */ - private String machineKind() { - return nes != null && nes.getRegion() == Region.PAL ? " (PAL)" : ""; } /** - * What the machine is doing, when it is doing anything other than simply running. Pause wins - * over fast forward: a machine that is not running is not running fast. - *

- * One sentence for two places. The status bar shows it as it is and the title bar puts it in - * brackets in lower case, which is what keeps the two from drifting into describing the same - * machine differently. + * Gathers what the window has to say about itself into one value, so that the three places it + * says anything are saying the same thing. */ - private String machineState() { - if (runner == null) { - return ""; - } - - if (runner.isPaused()) { - return "Paused"; - } - - // Above fast forward, because what the machine is doing to a file is a bigger surprise than - // how fast it is going -- and a recording somebody has forgotten about is the one state - // worth being reminded of on every glance at the window. - if (moviePlaying) { - return "Playback"; - } - - if (movieRecording) { - return "Recording"; - } - - // Below the movie and above the speed, for the reason the movie is above the speed: a file - // growing at a couple of megabytes a second is a bigger surprise than how fast the game is - // going, and a trace somebody started an hour ago is the state most worth being reminded of. - if (tracer != null) { - return "Tracing"; - } - - if (runner.getSpeed() != EmulationSpeed.NORMAL) { - return "Fast forward"; - } - - return ""; + private MachineDescription describe() { + return new MachineDescription( + runner != null, + runner != null && runner.isPaused(), + moviePlaying, + movieRecording, + tracer != null, + runner != null && runner.getSpeed() != EmulationSpeed.NORMAL, + lastFrameRate, + currentRegion(), + nes == null ? null : nes.getRegion(), + cart == null ? null : cart.filename(), + cart == null ? 0 : cart.mapperNumber(), + cart == null ? 0 : cart.prgROM().length, + cart == null ? 0 : cart.chrROM().length, + patchPath == null ? null : patchPath.getFileName().toString()); } /** @@ -3171,7 +2894,7 @@ private void openControlPanel() { controlPanel.setMachine(nes, runner, debugger, cart, config.palette(currentRegion())); } - controlPanel.setRunning(dashboardLine()); + controlPanel.setRunning(describe().dashboard()); controlPanel.setVisible(true); controlPanel.toFront(); diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/MachineDescription.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/MachineDescription.java new file mode 100644 index 0000000..23a2698 --- /dev/null +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/MachineDescription.java @@ -0,0 +1,166 @@ +package com.github.dimiro1.mynes.ui; + +import com.github.dimiro1.mynes.Region; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Locale; + +/** + * What the window says about itself, in the three places it says anything: the title bar, the status + * bar's activity, and the control panel's first line. + *

+ * One sentence for three places. {@link #state()} is written once and the three callers each + * dress it differently -- the status bar shows it as it is, the title bar puts it in brackets in + * lower case, and the dashboard drops it when it would only repeat the word already there. That is + * what keeps the window from describing the same machine three ways, which is what happened when + * each of them worked it out for itself. + *

+ * None of this is the machine's. Whether the loop is paused, what the frame rate has + * measured, which cartridge somebody put in, whether a movie is going -- not one of them can be read + * off a NES, which is why the control panel is handed its line written rather than working it out. + * Whichever frame the machine has actually reached is on the line below, with the rest of what the + * machine is doing. + *

+ * A record because it is a description rather than a describer: it holds no reference to the runner, + * the cartridge or the machine, so one taken now and read later says what was true when it was + * taken. + * + * @param running whether there is a machine at all, which is a different question from + * whether it is going anywhere. + * @param paused whether the loop is stopped. Wins over everything below it: a machine that + * is not running is not running fast. + * @param playingMovie whether a movie is being replayed. + * @param recordingMovie whether one is being written. + * @param tracing whether every instruction is going to a file. + * @param fastForward whether the loop is being paced at anything other than 1x. + * @param frameRate the measured rate, or {@link FrameRate#UNKNOWN} when nothing has measured + * one yet. + * @param region which console the window says it is running, which is on the bar + * before a cartridge is loaded too: it is what the next one will run under. + * @param machineRegion which console is actually running, or null when none is. Not always + * {@link #region}, which is why both are here. + * @param cartridge the cartridge's file name, or null when nothing is loaded. + * @param mapperNumber the board the header asked for. + * @param prgBytes how much program ROM is on it. + * @param chrBytes how much character ROM is on it. + * @param patch the IPS patch applied on the way in, or null for an unpatched cartridge. + */ +record MachineDescription( + boolean running, + boolean paused, + boolean playingMovie, + boolean recordingMovie, + boolean tracing, + boolean fastForward, + int frameRate, + Region region, + @Nullable Region machineRegion, + @Nullable String cartridge, + int mapperNumber, + int prgBytes, + int chrBytes, + @Nullable String patch) { + + /** + * What the machine is doing, when it is doing anything other than simply running. + *

+ * The order is the order of surprise rather than of importance. A movie above a trace and both + * above the speed: what the machine is doing to a file is a bigger surprise than how + * fast it is going, and a recording or a trace somebody started an hour ago is the state most + * worth being reminded of on every glance at the window. + */ + String state() { + if (!running) { + return ""; + } + + if (paused) { + return "Paused"; + } + + if (playingMovie) { + return "Playback"; + } + + if (recordingMovie) { + return "Recording"; + } + + if (tracing) { + return "Tracing"; + } + + if (fastForward) { + return "Fast forward"; + } + + return ""; + } + + /** + * The title bar, which is for a window list and a dock rather than for whoever is playing. + */ + String title() { + if (cartridge == null) { + return "MyNES"; + } + + var state = state(); + + return "MyNES - " + cartridge + patched() + kind() + + (state.isEmpty() ? "" : " (" + state.toLowerCase(Locale.ROOT) + ")"); + } + + /** + * The control panel's first line: how the machine is being run. + */ + String dashboard() { + var parts = new ArrayList(); + + parts.add(!running ? "No machine" : paused ? "Paused" : "Running"); + + if (frameRate != FrameRate.UNKNOWN) { + parts.add(frameRate + " fps"); + } + + parts.add(region.label()); + + if (cartridge != null) { + parts.add(String.format( + "%s (mapper %d, %dK+%dK)", + cartridge, mapperNumber, prgBytes / 1024, chrBytes / 1024)); + } + + var activity = state(); + + // "Paused" is already the first thing on the line, and saying it twice would read as two + // different facts that happen to agree. + if (!activity.isEmpty() && !"Paused".equals(activity)) { + parts.add(activity); + } + + return String.join(" · ", parts); + } + + /** + * Which hack is playing, when one is. + *

+ * The cartridge's own name is still first: a patched game is that game plus a patch, and a title + * bar naming only the patch would leave nothing to say which ROM it was applied to. + */ + private String patched() { + return patch == null ? "" : " + " + patch; + } + + /** + * The kind of machine, when it is not the usual one. + *

+ * Only PAL is worth the words. A machine's region is invisible from the picture until something + * is wrong, and when it is wrong -- a game running fast because the header said nothing -- this + * is the line that says which way to reach for. + */ + private String kind() { + return machineRegion == Region.PAL ? " (PAL)" : ""; + } +} diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/SaveSlots.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/SaveSlots.java new file mode 100644 index 0000000..03b9a99 --- /dev/null +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/SaveSlots.java @@ -0,0 +1,183 @@ +package com.github.dimiro1.mynes.ui; + +import com.github.dimiro1.mynes.state.SaveState; +import com.github.dimiro1.mynes.state.SaveStateException; +import org.jetbrains.annotations.Nullable; + +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.KeyStroke; +import java.awt.event.KeyEvent; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.function.IntConsumer; + +/** + * The nine save state slots: the two submenus, the two quick items, and which slot they mean. + *

+ * What is really here is the labelling. Writing and reading a slot belongs to the window, + * which owns the machine and the thread allowed to touch it, so both are handed in as callbacks. + * What this owns is the part with a decision in it: going to the disk when the menu opens, reading + * each state's header, and saying what is in every slot. That is what makes nine numbered slots + * usable instead of a guessing game, and it is why the state's header is deliberately not + * compressed -- nine files give up their frame number without any of them being inflated. + *

+ * Which slot is current is one setting rather than two. Picking Slot 4 from either submenu + * moves the pair of quick keys onto slot 4, so the menus and {@code F5}/{@code F7} can never come + * to mean different things. + *

+ * The labels are worked out when the menu is pulled down rather than when it is built, because what + * is on the disk moves without anybody telling the emulator: a slot can be written by another copy + * of this program, or deleted in a file manager, while the menu sits there built. + */ +final class SaveSlots { + + /** + * How many save state slots there are. Nine because that is how many fit on the number row, and + * because a tenth would be the one nobody could remember what they put in. + */ + static final int COUNT = 9; + + /** + * How a slot's time is put on its label. Short: the item already carries a slot number and a + * frame count, and a full date would push the useful half off the edge of a menu. + */ + private static final DateTimeFormatter WHEN = DateTimeFormatter.ofPattern("d MMM HH:mm"); + + private final JMenuItem[] loadItems = new JMenuItem[COUNT]; + private final JMenuItem quickSave = new JMenuItem("Quick Save"); + private final JMenuItem quickLoad = new JMenuItem("Quick Load"); + + private final IntConsumer save; + private final IntConsumer load; + + /** + * Which slot the two quick items use. Whichever was last picked from either submenu, so the + * pair of keys and the menus are one setting rather than two. + */ + private int current = 1; + + SaveSlots(final IntConsumer save, final IntConsumer load) { + this.save = save; + this.load = load; + + // Function keys, for three reasons. They sit in the same physical place on every keyboard + // layout, which a letter does not -- this one is Colemak-DH. F5 and F7 are what ZSNES and + // SNES9x used, so they are the keys a player already has in their fingers. And they need no + // modifier, which matters here: Shift is bound to Select, so KeyboardInput deliberately does + // not treat it as a shortcut modifier and any Shift+key shortcut would be a hazard. + quickSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); + quickLoad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0)); + + quickSave.addActionListener(e -> save.accept(current)); + quickLoad.addActionListener(e -> load.accept(current)); + + describeQuickItems(); + } + + /** + * The Save State submenu, whose nine items never change their labels: every slot can be written + * to, so there is nothing about one worth saying beyond its number. + */ + JMenu saveMenu() { + return menu("Save State", save, false); + } + + /** + * The Load State submenu, whose nine items are relabelled by {@link #describe} with what is in + * them. + */ + JMenu loadMenu() { + return menu("Load State", load, true); + } + + JMenuItem quickSaveItem() { + return quickSave; + } + + JMenuItem quickLoadItem() { + return quickLoad; + } + + /** + * Puts what is in each slot onto its menu item, and greys out the empty ones. + * + * @param gamePath the cartridge the slots belong to, or null when nothing is loaded -- which + * greys all nine, since there is no game for them to be slots of. + */ + void describe(final @Nullable Path gamePath) { + describeQuickItems(); + + for (var slot = 1; slot <= COUNT; slot++) { + var item = loadItems[slot - 1]; + var path = gamePath == null ? null : SaveState.slotPath(gamePath, slot); + + if (path == null || !Files.exists(path)) { + item.setText("Slot " + slot); + item.setEnabled(false); + continue; + } + + item.setEnabled(true); + item.setText("Slot " + slot + " — " + describeState(path)); + } + } + + /** + * What one slot's file has in it, as it goes on the label. + *

+ * A file that will not even give up its header is still offered rather than greyed, because + * refusing to list it would hide the only clue that something is wrong with it. + */ + private static String describeState(final Path path) { + try { + var header = SaveState.header(path); + var when = Files.getLastModifiedTime(path).toInstant() + .atZone(ZoneId.systemDefault()) + .format(WHEN); + + return "frame " + header.frame() + ", " + when; + } catch (IOException | SaveStateException ex) { + return "unreadable"; + } + } + + private void describeQuickItems() { + quickSave.setText("Quick Save (Slot " + current + ")"); + quickLoad.setText("Quick Load (Slot " + current + ")"); + } + + /** + * Builds one of the two submenus, nine items numbered from one. + * + * @param keep whether to hold on to the items for {@link #describe} to relabel later. + */ + private JMenu menu(final String title, final IntConsumer action, final boolean keep) { + var menu = new JMenu(title); + + for (var slot = 1; slot <= COUNT; slot++) { + var item = new JMenuItem("Slot " + slot); + var chosen = slot; + + // No accelerators on these eighteen. Command-1 to Command-9 is "switch tab" everywhere + // else, and eighteen global shortcuts for something two keys already do would be + // eighteen chances to collide with a game's controls. + item.addActionListener(e -> { + current = chosen; + action.accept(chosen); + describeQuickItems(); + }); + + if (keep) { + loadItems[slot - 1] = item; + } + + menu.add(item); + } + + return menu; + } +} diff --git a/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/BatterySavesTests.java b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/BatterySavesTests.java new file mode 100644 index 0000000..9525204 --- /dev/null +++ b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/BatterySavesTests.java @@ -0,0 +1,216 @@ +package com.github.dimiro1.mynes.ui; + +import com.github.dimiro1.mynes.Cart; +import com.github.dimiro1.mynes.NES; +import com.github.dimiro1.mynes.state.BatteryRAM; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The rule the autosave exists for: write the {@code .sav} when the game has changed the chip, and + * not otherwise. + *

+ * Every test here is about a file that should not appear. That is the whole point of the + * shadow copy -- a timer that wrote 8KB to disk every minute of every game, battery or not, would + * pass any test asking whether saving works. + *

+ * Nothing here touches a failure path, and deliberately: those put a dialog up, and a test that + * raised one would hang the build on a machine with no display. + */ +class BatterySavesTests { + + @TempDir + private Path directory; + + @Test + void aCartridgeWithNoBatteryOnItIsNeverWrittenOut() { + var nes = machine(false); + var game = directory.resolve("scratch.nes"); + var saves = new BatterySaves(null); + + saves.track(nes); + fill(nes, 0x5A); + saves.autosave(nes, game); + saves.save(nes, game); + + assertFalse(Files.exists(BatteryRAM.pathFor(game)), + "every board here has RAM at $6000 whether a battery was wired to it or not"); + } + + /** + * The first check after a game has loaded is the one most likely to be wrong: the RAM is full of + * whatever came off the disk, which is a difference from nothing but not a difference the game + * made. + */ + @Test + void theFirstCheckAfterLoadingDoesNotRewriteWhatWasJustRead() { + var game = directory.resolve("game.nes"); + var sav = BatteryRAM.pathFor(game); + + var played = machine(true); + fill(played, 0x11); + new BatterySaves(null).save(played, game); + + var reloaded = machine(true); + var saves = new BatterySaves(null); + + saves.load(reloaded, game); + saves.track(reloaded); + + assertTrue(deleteSav(sav), "the save from the first session should be there"); + + saves.autosave(reloaded, game); + + assertFalse(Files.exists(sav), "nothing has changed, so nothing should have been written"); + } + + @Test + void anAutosaveWritesOnceTheGameHasChangedTheRAM() { + var nes = machine(true); + var game = directory.resolve("game.nes"); + var saves = new BatterySaves(null); + + saves.track(nes); + fill(nes, 0x7E); + saves.autosave(nes, game); + + assertTrue(Files.exists(BatteryRAM.pathFor(game))); + } + + /** + * The one that matters for a laptop's disk: a game that saved an hour ago is still not being + * written every minute since. + */ + @Test + void anAutosaveAfterAnAutosaveWritesNothingUntilTheGameSavesAgain() { + var nes = machine(true); + var game = directory.resolve("game.nes"); + var sav = BatteryRAM.pathFor(game); + var saves = new BatterySaves(null); + + saves.track(nes); + fill(nes, 0x7E); + saves.autosave(nes, game); + + assertTrue(deleteSav(sav), "the first autosave should have written one"); + + saves.autosave(nes, game); + + assertFalse(Files.exists(sav), "the game has not saved again since"); + + fill(nes, 0x7F); + saves.autosave(nes, game); + + assertTrue(Files.exists(sav), "and now it has"); + } + + /** + * Unlike the autosave, which is a timer nobody asked for. This one is the window closing and a + * cartridge being swapped, and neither gets a second chance to be right. + */ + @Test + void anExplicitSaveWritesWhetherAnythingChangedOrNot() { + var nes = machine(true); + var game = directory.resolve("game.nes"); + var sav = BatteryRAM.pathFor(game); + var saves = new BatterySaves(null); + + saves.track(nes); + + saves.save(nes, game); + + assertTrue(deleteSav(sav), "nothing had changed and it should still have been written"); + } + + @Test + void whatOneSessionWroteIsWhatTheNextOneStartsHolding() { + var game = directory.resolve("game.nes"); + + var played = machine(true); + fill(played, 0x3C); + new BatterySaves(null).save(played, game); + + var reloaded = machine(true); + new BatterySaves(null).load(reloaded, game); + + assertArrayEquals(ram(played), ram(reloaded)); + } + + /** + * A game with nothing open yet, which is what the window holds before a cartridge is chosen. It + * reaches all three of these through a timer that does not stop for it. + */ + @Test + void aWindowWithNoGameInItIsNotAskedToWriteOneOut() { + var nes = machine(true); + var saves = new BatterySaves(null); + + saves.load(nes, null); + saves.autosave(nes, null); + saves.save(nes, null); + saves.autosave(null, directory.resolve("game.nes")); + + assertTrue(isEmpty(directory), "nothing should have been written anywhere"); + } + + private static byte[] ram(final NES nes) { + return nes.getBus().getMapper().prgRAM(); + } + + private static void fill(final NES nes, final int value) { + Arrays.fill(ram(nes), (byte) value); + } + + /** + * Deleting rather than reading a modification time, which has a resolution somewhere between a + * nanosecond and two seconds depending on whose file system this is running on. A file that is + * not there cannot have been written again by accident. + * + * @return whether it was there to delete. + */ + private static boolean deleteSav(final Path sav) { + try { + return Files.deleteIfExists(sav); + } catch (Exception e) { + throw new AssertionError(e); + } + } + + private static boolean isEmpty(final Path directory) { + try (var entries = Files.list(directory)) { + return entries.findAny().isEmpty(); + } catch (Exception e) { + throw new AssertionError(e); + } + } + + /** + * An NROM cartridge, with or without the flags 6 bit that says a battery was wired to the RAM. + */ + private static NES machine(final boolean battery) { + var image = new byte[16 + 0x4000 + 0x2000]; + + image[0] = 'N'; + image[1] = 'E'; + image[2] = 'S'; + image[3] = 0x1A; + image[4] = 1; + image[5] = 1; + image[6] = (byte) (battery ? 0x02 : 0x00); + + // A reset vector that points at the start of the bank, so the machine is a machine rather + // than one that fetches its first instruction from nowhere. + image[16 + 0x3FFC] = 0x00; + image[16 + 0x3FFD] = (byte) 0x80; + + return new NES(Cart.load(image, battery ? "game.nes" : "scratch.nes")); + } +} diff --git a/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/ConfigTests.java b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/ConfigTests.java index 4765aed..295b31b 100644 --- a/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/ConfigTests.java +++ b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/ConfigTests.java @@ -14,6 +14,7 @@ import org.junit.jupiter.api.io.TempDir; import java.awt.event.KeyEvent; +import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -24,6 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Tests for {@code ~/.mynes/config.properties} and everything kept in it. @@ -1124,11 +1126,20 @@ void aPathOutsideLatinOneSurvivesTheRoundTrip() throws IOException { } /** - * A filename may hold one on every platform this runs on, and a value split over two lines - * is a file that will not read back. + * A value split over two lines is a file that will not read back, and a tab is the + * character that would do it. + *

+ * Not on Windows, and the assumption is the point rather than a way round it. This + * said a filename may hold a tab on every platform it runs on, which the CI matrix + * disproved the day it was widened: Windows forbids one outright, so {@code Path.of} + * refuses the name before any of this is reached. The case cannot arise there, which is a + * different thing from arising and being mishandled -- and {@link Config} still escapes a + * tab, since what it escapes is a value rather than a filename. */ @Test void aTabInAPathSurvivesTheRoundTrip() throws IOException { + assumeTrue(File.separatorChar == '/', "no filename on Windows holds a tab"); + var game = game("two\twords.nes"); var config = Config.load(config()); @@ -1206,7 +1217,14 @@ void aSaveWritesEverySection() throws IOException { assertTrue(text.contains("rewind.seconds=45"), text); assertTrue(text.contains("rewind.key=VK_BACK_SPACE"), text); assertTrue(text.contains("controller1.a=VK_L"), text); - assertTrue(text.contains("recent.1=" + directory.resolve("a.nes")), text); + // The key and the file name rather than the whole path, which is the one value in this + // file that is not written verbatim: Properties reads a backslash as an escape, so a + // Windows path goes in doubled and comparing the raw text against Path.toString would + // be asserting that the separator is a slash. That the escaping round-trips is + // aBackslashInAPathSurvivesTheRoundTrip's claim, and one rule wants one owner -- what + // is being asked here is whether the section was written at all. + assertTrue(text.contains("recent.1="), text); + assertTrue(text.contains("a.nes"), text); } @Test diff --git a/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/MachineDescriptionTests.java b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/MachineDescriptionTests.java new file mode 100644 index 0000000..7bae971 --- /dev/null +++ b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/MachineDescriptionTests.java @@ -0,0 +1,125 @@ +package com.github.dimiro1.mynes.ui; + +import com.github.dimiro1.mynes.Region; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The words the window puts on itself, and the one rule that holds the three places together: they + * are all reading the same sentence. + */ +class MachineDescriptionTests { + + /** + * A machine playing a cartridge with nothing unusual about it. + */ + private static MachineDescription playing() { + return new MachineDescription( + true, false, false, false, false, false, + 60, Region.NTSC, Region.NTSC, + "Super Mario Bros.nes", 0, 32 * 1024, 8 * 1024, null); + } + + @Test + void withNothingLoadedTheTitleIsJustTheProgramsName() { + var nothing = new MachineDescription( + false, false, false, false, false, false, + FrameRate.UNKNOWN, Region.NTSC, null, null, 0, 0, 0, null); + + assertEquals("MyNES", nothing.title()); + assertEquals("", nothing.state(), "there is nothing being done to a machine that is not there"); + assertEquals("No machine · NTSC", nothing.dashboard()); + } + + @Test + void aRunningGameIsNamedInTheTitleWithNoStateAfterIt() { + assertEquals("MyNES - Super Mario Bros.nes", playing().title()); + } + + @Test + void theDashboardCarriesTheRateTheRegionAndTheBoard() { + assertEquals( + "Running · 60 fps · NTSC · Super Mario Bros.nes (mapper 0, 32K+8K)", + playing().dashboard()); + } + + /** + * The one thing that separates the two regions in the window: a PAL game running fast because + * the header said nothing is invisible until something says which way to reach. + */ + @Test + void onlyAPalMachineIsNamedInTheTitle() { + var pal = new MachineDescription( + true, false, false, false, false, false, + 50, Region.PAL, Region.PAL, "Tetris.nes", 1, 32 * 1024, 0, null); + + assertTrue(pal.title().contains("(PAL)"), pal.title()); + assertTrue(!playing().title().contains("NTSC"), "the usual machine is not worth the words"); + } + + /** + * A patched game is that game plus a patch, so the cartridge is still named first -- a title + * naming only the hack would leave nothing to say which ROM it was applied to. + */ + @Test + void aPatchedGameNamesTheCartridgeAndThenThePatch() { + var hacked = new MachineDescription( + true, false, false, false, false, false, + 60, Region.NTSC, Region.NTSC, "smb.nes", 0, 32 * 1024, 8 * 1024, "hack.ips"); + + assertEquals("MyNES - smb.nes + hack.ips", hacked.title()); + } + + /** + * The order is the order of surprise: what the machine is doing to a file beats how fast it is + * going, and a machine that is not running is not running fast. + */ + @Test + void pauseWinsOverEverythingAndAFileWinsOverTheSpeed() { + assertEquals("Paused", busy(true, true, true, true, true).state()); + assertEquals("Playback", busy(false, true, true, true, true).state()); + assertEquals("Recording", busy(false, false, true, true, true).state()); + assertEquals("Tracing", busy(false, false, false, true, true).state()); + assertEquals("Fast forward", busy(false, false, false, false, true).state()); + assertEquals("", busy(false, false, false, false, false).state()); + } + + /** + * The whole reason this is one value rather than three methods on the window: the status bar + * shows the sentence as it is and the title bar puts it in brackets in lower case, so they can + * never come to describe the same machine differently. + */ + @Test + void theTitleAndTheStatusBarAreReadingTheSameSentence() { + var recording = busy(false, false, true, false, false); + + assertEquals("Recording", recording.state()); + assertTrue(recording.title().endsWith(" (recording)"), recording.title()); + } + + /** + * Because it is already the first word on the line, and saying it twice would read as two facts + * that happen to agree rather than as one. + */ + @Test + void theDashboardDoesNotSayPausedTwice() { + var paused = busy(true, false, false, false, false); + + assertEquals("Paused", paused.state()); + assertEquals(1, paused.dashboard().split("Paused", -1).length - 1, paused.dashboard()); + } + + private static MachineDescription busy( + final boolean paused, + final boolean playing, + final boolean recording, + final boolean tracing, + final boolean fast + ) { + return new MachineDescription( + true, paused, playing, recording, tracing, fast, + 60, Region.NTSC, Region.NTSC, "game.nes", 4, 128 * 1024, 128 * 1024, null); + } +} diff --git a/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/SaveSlotsTests.java b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/SaveSlotsTests.java new file mode 100644 index 0000000..c7f4ee8 --- /dev/null +++ b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/SaveSlotsTests.java @@ -0,0 +1,177 @@ +package com.github.dimiro1.mynes.ui; + +import com.github.dimiro1.mynes.Cart; +import com.github.dimiro1.mynes.NES; +import com.github.dimiro1.mynes.state.SaveState; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import javax.swing.JMenu; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * What the nine slots say they have in them, which is the half of this that has a decision in it. + *

+ * Writing and reading a slot belongs to the window, so none of that is here. What is here is the + * labelling: nine numbered items are a guessing game unless each one says what is in it, and that + * answer comes off the disk every time the menu is pulled down. + */ +class SaveSlotsTests { + + @TempDir + private Path directory; + + private final List saved = new ArrayList<>(); + private final List loaded = new ArrayList<>(); + + private SaveSlots slots() { + return new SaveSlots(saved::add, loaded::add); + } + + @Test + void thereAreNineOfThemInEachSubmenuNumberedFromOne() { + var slots = slots(); + + assertEquals(SaveSlots.COUNT, slots.saveMenu().getItemCount()); + assertEquals(SaveSlots.COUNT, slots.loadMenu().getItemCount()); + assertEquals("Slot 1", slots.saveMenu().getItem(0).getText()); + assertEquals("Slot 9", slots.saveMenu().getItem(SaveSlots.COUNT - 1).getText()); + } + + @Test + void aSlotWithNothingInItIsGreyedOutAndSaysOnlyItsNumber() { + var slots = slots(); + var menu = slots.loadMenu(); + + slots.describe(directory.resolve("game.nes")); + + for (var slot = 1; slot <= SaveSlots.COUNT; slot++) { + var item = menu.getItem(slot - 1); + + assertEquals("Slot " + slot, item.getText()); + assertFalse(item.isEnabled(), "slot " + slot + " has nothing in it"); + } + } + + @Test + void aSlotWithAStateInItSaysWhichFrameItStopped() throws IOException { + var game = directory.resolve("game.nes"); + var slots = slots(); + var menu = slots.loadMenu(); + + SaveState.write(machine(), SaveState.slotPath(game, 4)); + + slots.describe(game); + + var item = menu.getItem(3); + + assertTrue(item.isEnabled()); + assertTrue(item.getText().startsWith("Slot 4 — frame 0, "), item.getText()); + assertFalse(menu.getItem(2).isEnabled(), "and the ones either side are still empty"); + assertFalse(menu.getItem(4).isEnabled()); + } + + /** + * Still listed rather than greyed, because refusing to show it would hide the only clue that + * something is wrong with the file. + */ + @Test + void aStateThatWillNotGiveUpItsHeaderIsStillOffered() throws IOException { + var game = directory.resolve("game.nes"); + var slots = slots(); + var menu = slots.loadMenu(); + + Files.write(SaveState.slotPath(game, 1), "not a save state".getBytes()); + + slots.describe(game); + + assertEquals("Slot 1 — unreadable", menu.getItem(0).getText()); + assertTrue(menu.getItem(0).isEnabled()); + } + + /** + * The window holds nine slots before anything has been opened, and the menu can still be pulled + * down. There is no game for them to be slots of, so all nine say so. + */ + @Test + void withNoCartridgeLoadedEverySlotIsEmpty() { + var slots = slots(); + var menu = slots.loadMenu(); + + slots.describe(null); + + for (var slot = 1; slot <= SaveSlots.COUNT; slot++) { + assertFalse(menu.getItem(slot - 1).isEnabled()); + } + } + + @Test + void theQuickItemsSayWhichSlotTheyWouldUse() { + var slots = slots(); + + assertEquals("Quick Save (Slot 1)", slots.quickSaveItem().getText()); + assertEquals("Quick Load (Slot 1)", slots.quickLoadItem().getText()); + } + + /** + * The pair of keys and the two menus are one setting rather than two, so picking a slot from + * either submenu is what moves them -- including from Save State, which is the half somebody + * would expect to be about saving alone. + */ + @Test + void pickingASlotFromEitherSubmenuMovesBothQuickKeysOntoIt() { + var slots = slots(); + + click(slots.loadMenu(), 6); + + assertEquals("Quick Save (Slot 7)", slots.quickSaveItem().getText()); + assertEquals("Quick Load (Slot 7)", slots.quickLoadItem().getText()); + + click(slots.saveMenu(), 2); + + assertEquals("Quick Save (Slot 3)", slots.quickSaveItem().getText()); + assertEquals("Quick Load (Slot 3)", slots.quickLoadItem().getText()); + } + + @Test + void theQuickItemsAndTheSubmenusReachTheSameTwoActions() { + var slots = slots(); + + click(slots.saveMenu(), 4); + click(slots.loadMenu(), 1); + + slots.quickSaveItem().doClick(); + slots.quickLoadItem().doClick(); + + assertEquals(List.of(5, 2), saved, "slot 5 from the menu, then slot 2 from the quick key"); + assertEquals(List.of(2, 2), loaded); + } + + private static void click(final JMenu menu, final int index) { + menu.getItem(index).doClick(); + } + + private static NES machine() { + var image = new byte[16 + 0x4000 + 0x2000]; + + image[0] = 'N'; + image[1] = 'E'; + image[2] = 'S'; + image[3] = 0x1A; + image[4] = 1; + image[5] = 1; + + image[16 + 0x3FFC] = 0x00; + image[16 + 0x3FFD] = (byte) 0x80; + + return new NES(Cart.load(image, "game.nes")); + } +} diff --git a/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/controlpanel/ControlPanelTests.java b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/controlpanel/ControlPanelTests.java index 800c3bf..c8bda7f 100644 --- a/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/controlpanel/ControlPanelTests.java +++ b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/controlpanel/ControlPanelTests.java @@ -166,6 +166,7 @@ void theWindowRemembersWhereItWasAndWhatWasInFront() throws Exception { assumeFalse(GraphicsEnvironment.isHeadless(), "no display to put a window on"); var remembered = new Layout[1]; + var actual = new Rectangle[1]; onSwingThread(() -> { var panel = new ControlPanelFrame( @@ -175,13 +176,19 @@ void theWindowRemembersWhereItWasAndWhatWasInFront() throws Exception { panel.setMachine(nes, runner, debugger, cart, Palettes.defaultPalette()); panel.setBounds(new Rectangle(40, 60, 1200, 800)); + // What the window actually became, which is not always what it was asked for: a + // window manager may clamp one to the display it is on, and a CI runner's display + // is smaller than this asks for. currentLayout() reads getBounds(), so the claim + // worth making is that it reports the window rather than the request -- asserting + // the rectangle that went in would be asserting the screen is big enough. + actual[0] = panel.getBounds(); remembered[0] = panel.currentLayout(); } finally { panel.dispose(); } }); - assertEquals(new Rectangle(40, 60, 1200, 800), remembered[0].bounds()); + assertEquals(actual[0], remembered[0].bounds(), "what the window is, not what it was asked"); assertNotNull(remembered[0].tab(), "and which instrument was in front"); var back = new Layout[1]; diff --git a/mynes-headless/src/main/java/com/github/dimiro1/mynes/headless/Headless.java b/mynes-headless/src/main/java/com/github/dimiro1/mynes/headless/Headless.java index 9521aae..06795b8 100644 --- a/mynes-headless/src/main/java/com/github/dimiro1/mynes/headless/Headless.java +++ b/mynes-headless/src/main/java/com/github/dimiro1/mynes/headless/Headless.java @@ -130,7 +130,17 @@ private static int runCartridge(final Options options) throws IOException { // Everything Cart.load throws is unchecked, and a file that is not a cartridge can // fail in several ways -- a bad magic number, a mapper nobody has written, a truncated // image that runs the buffer out. They are all the same answer to the caller. - System.err.println(options.rom() + " is not a cartridge this can run: " + e); + // + // The message rather than the exception, because printing the object puts a + // package-qualified class name in front of it, which is the one part of this nobody + // running a script can use. The first two name the file themselves; the third is + // whatever the array threw and may carry no message at all, which is what the framing + // is kept for. + var because = e.getMessage(); + + System.err.println(because != null ? because + : options.rom() + " is not a cartridge this can run: " + e); + return EXIT_ROM; } diff --git a/mynes-headless/src/main/java/com/github/dimiro1/mynes/headless/Options.java b/mynes-headless/src/main/java/com/github/dimiro1/mynes/headless/Options.java index 734ff84..434a677 100644 --- a/mynes-headless/src/main/java/com/github/dimiro1/mynes/headless/Options.java +++ b/mynes-headless/src/main/java/com/github/dimiro1/mynes/headless/Options.java @@ -175,8 +175,8 @@ public enum Format { public static final Set HACKS = Set.of(UNLIMITED_SPRITES, OVERCLOCK); /** - * Ten seconds of emulated time, which is about a second of real time and long enough for most - * cartridges to have drawn something. + * Ten seconds of emulated time, which is two or three seconds of real time and long enough for + * most cartridges to have drawn something. */ private static final long DEFAULT_FRAMES = 600; diff --git a/mynes-headless/src/test/java/com/github/dimiro1/mynes/headless/RomHackTests.java b/mynes-headless/src/test/java/com/github/dimiro1/mynes/headless/RomHackTests.java index 14b00ab..68e2bbf 100644 --- a/mynes-headless/src/test/java/com/github/dimiro1/mynes/headless/RomHackTests.java +++ b/mynes-headless/src/test/java/com/github/dimiro1/mynes/headless/RomHackTests.java @@ -121,12 +121,20 @@ void twoRunsOfTheSameHackAgree() throws Exception { assertArrayEquals(shotIn(first), shotIn(second)); } + /** + * The path is compared through {@link Path}, not against {@link #PATCH} itself. + *

+ * The report writes what {@code Path.toString()} gives, which is the separator of whatever + * machine ran it: {@code Path.of("a/b")} on Windows is {@code a\b}, and the same path. Asserting + * the string that went in would be asserting that this test was run on a platform whose + * separator is a slash, which is a different claim and one nobody wants to make. + */ @Test void theReportSaysWhichHackItWas() throws Exception { var patches = report(run("hacked", "--patch", PATCH)).at("/cart/patches"); assertEquals(1, patches.size()); - assertEquals(PATCH, patches.get(0).get("path").asText()); + assertEquals(Path.of(PATCH).toString(), patches.get(0).get("path").asText()); assertEquals(1, patches.get(0).get("records").asInt()); assertEquals(HACKED.length(), patches.get(0).get("bytes").asInt()); }