RomVideoSmokeDemo.java

1
package com.rox;
2
3
import com.formdev.flatlaf.FlatDarkLaf;
4
import com.rox.cartridge.RomLoader;
5
import com.rox.debug.DockedDebugWindow;
6
import com.rox.debug.breakpoints.BreakpointsPanel;
7
import com.rox.debug.cpu.CpuStatePanel;
8
import com.rox.debug.labels.FileLabelStore;
9
import com.rox.debug.labels.LabelFileException;
10
import com.rox.debug.labels.LabelWatchModel;
11
import com.rox.debug.labels.LabelWatchPanel;
12
import com.rox.debug.labels.MemoryLabel;
13
import com.rox.debug.memory.MemoryViewerPanel;
14
import com.rox.debug.report.DebugReport;
15
import com.rox.debug.report.DebugReportWriter;
16
import com.rox.input.Controller;
17
import com.rox.input.ControllerConfigLoader;
18
import com.rox.input.ControllerConfiguration;
19
import com.rox.input.KeyboardController;
20
import com.rox.save.SavePaths;
21
import com.rox.roundabout.timing.FrameTimes;
22
import com.rox.roundabout.debugger.MemoryDebugger;
23
import com.rox.video.AppName;
24
import com.rox.video.MenuEntry;
25
import com.rox.video.SwingVideoOutput;
26
import io.github.andrewauclair.moderndocking.ext.ui.DockingUI;
27
28
import javax.swing.JMenuItem;
29
import javax.swing.KeyStroke;
30
import javax.sound.sampled.LineUnavailableException;
31
import javax.swing.SwingUtilities;
32
import java.awt.event.InputEvent;
33
import java.awt.event.KeyEvent;
34
import java.io.IOException;
35
import java.nio.file.Files;
36
import java.nio.file.Path;
37
import java.time.LocalDateTime;
38
import java.util.ArrayList;
39
import java.util.List;
40
import java.util.Optional;
41
import java.util.OptionalInt;
42
import java.util.concurrent.CountDownLatch;
43
import java.util.concurrent.TimeUnit;
44
import java.util.concurrent.atomic.AtomicReference;
45
import java.util.function.Consumer;
46
import java.util.prefs.Preferences;
47
48
/**
49
 * The game window: plays a real {@code .nes} ROM, opened from File > Open > ROM or given with
50
 * {@code --rom}, until the window is closed, or up to a fixed duration if one is given, whichever comes
51
 * first. A blank screen until a ROM is opened. See {@link LaunchOptions} for the command line.
52
 *
53
 * <pre>./gradlew runRomVideoSmokeDemo --args="--rom path/to/rom.nes --controllers path/to/controllers.properties"</pre>
54
 */
55
public final class RomVideoSmokeDemo {
56
    private static final int CPU_STATE_REFRESH_MILLIS = 100;
57
    //slower than the CPU view: a region can be 32KB, and memory changes are easier to follow at this pace
58
    private static final int MEMORY_VIEWER_REFRESH_MILLIS = 250;
59
    /** Frame intervals each Roundabout frame-timing graph keeps: ten seconds at 60 fps. */
60
    private static final int ROUNDABOUT_FRAME_HISTORY = 600;
61
    private static final float ROUNDABOUT_FRAME_BUDGET_MS = 1000 / 60f;
62
    private static final List<String> ROM_MENU = List.of("File", "Open", "ROM");
63
    private static final List<String> DEBUG_MENU = List.of("Debug");
64
65
    private final SwingVideoOutput videoOutput;
66
    /** frames finished by the emulation and frames drawn by Swing, for Roundabout's frame-timing graphs */
67
    private final List<FrameTimes> frameTimings;
68
    private final GameSwitcher switcher;
69
    /** greyed out while no game is loaded - EDT only */
70
    private final List<JMenuItem> debugItems = new ArrayList<>();
71
    /** File > Open > ROM's list, kept between runs - EDT only */
72
    private final RecentRoms recentRoms = new RecentRoms(RecentRoms.in(
73
            Preferences.userNodeForPackage(RomVideoSmokeDemo.class).node("recentRoms")));
74
    /** where Browse starts when no game is loaded: the last folder a ROM was opened from - EDT only */
75
    private Path lastRomDirectory;
76
    /** created with the first game, kept for later ones - EDT only */
77
    private DockedDebugWindow debugger;
78
    /** Roundabout was open when the last game closed, so opens again on the next */
79
    private volatile boolean reopenRoundabout;
80
    /** the Roundabout memory debugger, while one is open - its own GLFW window on its own thread */
81
    private final AtomicReference<OpenRoundabout> roundabout = new AtomicReference<>();
82
83
    private record OpenRoundabout(MemoryDebugger debugger, Thread thread) {
84
    }
85
86
    private RomVideoSmokeDemo(final SwingVideoOutput videoOutput, final ControllerConfiguration controllers,
87
                              final List<FrameTimes> frameTimings){
88
        this.videoOutput = videoOutput;
89
        this.frameTimings = frameTimings;
90
        this.switcher = new GameSwitcher(RomLoader::load,
91
                (rom, cartridge) -> GameSession.start(rom, cartridge, c -> new NES(videoOutput, controllers, c)),
92
                new GameSwitcher.Listener(){
93
                    @Override
94
                    public void closing(final GameSession session){
95
                        reopenRoundabout = closeRoundabout();
96
                        //now, when switching on the EDT - queued, it would land after the next game starts
97 1 1. closing : removed call to com/rox/RomVideoSmokeDemo::onEdt → NO_COVERAGE
                        onEdt(() -> {
98 2 1. lambda$closing$0 : removed call to java/util/List::forEach → NO_COVERAGE
2. lambda$closing$1 : removed call to javax/swing/JMenuItem::setEnabled → NO_COVERAGE
                            debugItems.forEach(item -> item.setEnabled(false));
99 1 1. lambda$closing$0 : removed call to com/rox/video/SwingVideoOutput::showGame → NO_COVERAGE
                            videoOutput.showGame(null);
100
                        });
101
                    }
102
103
                    @Override
104
                    public void started(final GameSession session){
105 1 1. started : removed call to com/rox/RomVideoSmokeDemo::gameStarted → NO_COVERAGE
                        gameStarted(session);
106
                    }
107
                });
108
    }
109
110
    static void main(final String[] args) throws Exception {
111
        final LaunchOptions options;
112
        try {
113
            options = LaunchOptions.parse(args);
114
        } catch (IllegalArgumentException e){
115
            System.err.println(e.getMessage());
116
            System.err.println(LaunchOptions.USAGE);
117
            System.exit(1);
118
            return;
119
        }
120
        final ControllerConfiguration controllers = loadControllers(options.controllers());
121
        AppName.set("EmuRoxLab");
122
123
        final CountDownLatch windowClosed = new CountDownLatch(1);
124
        //Swing components must only be constructed on the EDT - see PpuDebugViewerDemo's own comment.
125
        //invokeLater + our own retried-on-interrupt latch, not invokeAndWait, since invokeAndWait's own
126
        //InterruptedException doesn't cancel the already-posted EDT task - the window could still get
127
        //constructed asynchronously afterward with nothing left to close it, leaking a visible JFrame
128
        final SwingVideoOutput[] videoOutputHolder = new SwingVideoOutput[1];
129
        final CountDownLatch videoOutputConstructed = new CountDownLatch(1);
130
        SwingUtilities.invokeLater(() -> {
131
            //modern UI prototype: dark theme for every window, set before any of them exists
132
            FlatDarkLaf.setup();
133
            DockingUI.initialize();
134
            videoOutputHolder[0] = new SwingVideoOutput(windowClosed::countDown);
135
            videoOutputConstructed.countDown();
136
        });
137
        boolean constructionInterrupted = false;
138
        while (true){
139
            try {
140
                videoOutputConstructed.await();
141
                break;
142
            } catch (InterruptedException e){
143
                constructionInterrupted = true;
144
            }
145
        }
146
        final SwingVideoOutput videoOutput = videoOutputHolder[0];
147
        if (constructionInterrupted){
148
            Thread.currentThread().interrupt();
149
        }
150
        attachKeyboardControllers(videoOutput, controllers);
151
        final List<FrameTimes> frameTimings = List.of(new FrameTimes("emu frames", ROUNDABOUT_FRAME_HISTORY,
152
                ROUNDABOUT_FRAME_BUDGET_MS), new FrameTimes("shown frames", ROUNDABOUT_FRAME_HISTORY, ROUNDABOUT_FRAME_BUDGET_MS));
153
        videoOutput.onFrameTimes(frameTimings.get(0)::record, frameTimings.get(1)::record);
154
        final RomVideoSmokeDemo app = new RomVideoSmokeDemo(videoOutput, controllers, frameTimings);
155
156
        //always close the window, even if something here throws - a visible, undisposed JFrame keeps a
157
        //non-daemon EDT thread alive, so the JVM would hang on exit instead of surfacing the error
158
        try {
159
            SwingUtilities.invokeLater(() -> {
160
                videoOutput.showGame(null);
161
                app.addFileMenu();
162
                app.addDebugMenu();
163
                options.rom().ifPresent(app::openRom);
164
            });
165
            final OptionalInt runSeconds = options.seconds();
166
            System.out.println(options.rom().map(rom -> "Showing " + rom).orElse("No ROM given - open one from File > Open > ROM")
167
                    + (runSeconds.isPresent() ? ", for up to " + runSeconds.getAsInt() + " seconds" : "")
168
                    + " (close the window to stop" + (runSeconds.isPresent() ? " early" : "") + ")...");
169
            try {
170
                if (runSeconds.isPresent()){
171
                    windowClosed.await(runSeconds.getAsInt(), TimeUnit.SECONDS);
172
                } else {
173
                    windowClosed.await();
174
                }
175
            } catch (InterruptedException e){
176
                Thread.currentThread().interrupt();
177
            }
178
        } finally {
179
            try {
180
                //also stops a ROM opened from here on - an --rom still queued, or picked in a chooser left open
181
                app.switcher.shutDown();
182
            } finally {
183
                SwingUtilities.invokeLater(() -> {
184
                    if (app.debugger != null){
185
                        app.debugger.dispose();
186
                    }
187
                });
188
                videoOutput.close();
189
                //only once the game has ended all gamepad polling
190
                ControllerConfigLoader.closeConnectedGamepads();
191
            }
192
        }
193
        System.out.println("Done.");
194
    }
195
196
    /** EDT only. */
197
    private void addFileMenu(){
198
        videoOutput.addMenuItem(ROM_MENU, "Browse...", KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK),
199
                this::browseForRom);
200
        videoOutput.fillMenuOnOpen(ROM_MENU, this::recentRomEntries);
201
        videoOutput.onFilesDropped(files -> DroppedRom.of(files).ifPresent(this::openRom));
202
    }
203
204
    /** File > Open > ROM's recent ROMs, newest first, then a way to clear them. EDT only. */
205
    private List<MenuEntry> recentRomEntries(){
206
        final List<Path> roms = recentRoms.list();
207
        if (roms.isEmpty()){
208
            return List.of(MenuEntry.disabled("No recent ROMs"));
209
        }
210
        final List<MenuEntry> entries = new ArrayList<>();
211
        roms.forEach(rom -> entries.add(new MenuEntry(recentRoms.label(rom), () -> openRecentRom(rom))));
212
        entries.add(MenuEntry.SEPARATOR);
213
        entries.add(new MenuEntry("Clear recent", recentRoms::clear));
214
        return entries;
215
    }
216
217
    /** A recent ROM that's since gone is taken off the list, rather than left to fail again. EDT only. */
218
    private void openRecentRom(final Path rom){
219
        if (!Files.isRegularFile(rom)){
220
            recentRoms.remove(rom);
221
            videoOutput.showError("ROM not found", rom + " isn't there any more - taken off the recent list.");
222
            return;
223
        }
224
        openRom(rom);
225
    }
226
227
    /** File > Open > ROM > Browse...: pick a ROM, starting in the current one's folder. EDT only. */
228
    private void browseForRom(){
229
        final Path startIn = switcher.current().map(session -> session.romPath().toAbsolutePath().getParent())
230
                .orElse(lastRomDirectory);
231
        videoOutput.chooseFileToOpen("Open ROM", startIn, "NES ROMs (*.nes)", "nes").ifPresent(this::openRom);
232
    }
233
234
    /** EDT only: the debug tools, each acting on whichever game is loaded. */
235
    private void addDebugMenu(){
236
        debugItems.add(videoOutput.addMenuItem(DEBUG_MENU, "Breakpoints", key(KeyEvent.VK_F7), () -> showDebugPanel("breakpoints")));
237
        debugItems.add(videoOutput.addMenuItem(DEBUG_MENU, "Roundabout", key(KeyEvent.VK_F8), () -> withGame(this::openRoundabout)));
238
        debugItems.add(videoOutput.addMenuItem(DEBUG_MENU, "Watch", key(KeyEvent.VK_F9), () -> showDebugPanel("watch")));
239
        debugItems.add(videoOutput.addMenuItem(DEBUG_MENU, "Memory", key(KeyEvent.VK_F10), () -> showDebugPanel("memory")));
240
        debugItems.add(videoOutput.addMenuItem(DEBUG_MENU, "CPU state", key(KeyEvent.VK_F11), () -> showDebugPanel("cpu")));
241
        debugItems.add(videoOutput.addMenuItem(DEBUG_MENU, "Flag issue", key(KeyEvent.VK_F12),
242
                () -> withGame(session -> flagIssue(session.nes(), videoOutput, session.romPath()))));
243
        debugItems.forEach(item -> item.setEnabled(false));
244
    }
245
246
    /** A menu item's accelerator still fires while it's greyed out, so each action checks too. */
247
    private void withGame(final Consumer<GameSession> action){
248
        switcher.current().ifPresent(action);
249
    }
250
251
    private void showDebugPanel(final String id){
252
        withGame(session -> debugger.showPanel(id));
253
    }
254
255
    /** EDT only: loads {@code rom} in place of the current game, or says why it couldn't. */
256
    private void openRom(final Path rom){
257
        lastRomDirectory = rom.toAbsolutePath().getParent();
258
        try {
259
            switcher.open(rom);
260
            recentRoms.add(rom);
261
        } catch (IOException | IllegalArgumentException | LineUnavailableException e){
262
            System.err.println("Couldn't open " + rom + ": " + e.getMessage());
263
            videoOutput.showError("Couldn't open ROM", "Couldn't open " + rom.getFileName() + ":\n" + e.getMessage());
264
        }
265
    }
266
267
    /** EDT (via {@link #openRom}): hooks the debug tools up to the new game, as they were for the last. */
268
    private void gameStarted(final GameSession session){
269
        final List<DockedDebugWindow.Panel> panels = debuggerPanels(session);
270
        final boolean firstGame = debugger == null;
271
        if (firstGame){
272
            debugger = new DockedDebugWindow("EmuRoxLab - Debugger", panels);
273
        } else {
274
            debugger.replacePanels(panels);
275
        }
276
        debugItems.forEach(item -> item.setEnabled(true));
277
        videoOutput.showGame(session.romPath().getFileName().toString());
278
        if (reopenRoundabout || firstGame && Boolean.getBoolean("roundabout.open")){
279
            openRoundabout(session);
280
        }
281
    }
282
283
    private static List<DockedDebugWindow.Panel> debuggerPanels(final GameSession session){
284
        final NES nes = session.nes();
285
        final Path romPath = session.romPath();
286
        final CpuStatePanel cpuStatePanel = new CpuStatePanel(new NesCpuDebugSource(nes));
287
        final MemoryViewerPanel memoryViewerPanel = new MemoryViewerPanel(new NesMemoryDebugSource(nes));
288
        final LabelWatchPanel labelWatchPanel = new LabelWatchPanel(new LabelWatchModel(
289
                new FileLabelStore(SavePaths.labelsFile(romPath)), new NesLabelWatchTarget(nes)));
290
        final BreakpointsPanel breakpointsPanel = new BreakpointsPanel(nes.breakpoints(), nes::lastHit,
291
                new FileLabelStore(SavePaths.labelsFile(romPath)));
292
        return List.of(
293
                new DockedDebugWindow.Panel("cpu", "CPU state", cpuStatePanel, cpuStatePanel::refresh, CPU_STATE_REFRESH_MILLIS),
294
                new DockedDebugWindow.Panel("memory", "Memory", memoryViewerPanel, memoryViewerPanel::refresh, MEMORY_VIEWER_REFRESH_MILLIS),
295
                new DockedDebugWindow.Panel("watch", "Watch", labelWatchPanel, labelWatchPanel::refresh, MEMORY_VIEWER_REFRESH_MILLIS),
296
                new DockedDebugWindow.Panel("breakpoints", "Breakpoints", breakpointsPanel, breakpointsPanel::refresh,
297
                        CPU_STATE_REFRESH_MILLIS));
298
    }
299
300
    /**
301
     * Debug > Flag issue (runs on the EDT): freeze the game, capture everything, ask what went
302
     * wrong, then unfreeze - and, unless cancelled, write it all to a {@code debug-snapshot-<timestamp>}
303
     * folder beside the ROM's saves.
304
     */
305
    private static void flagIssue(final NES nes, final SwingVideoOutput videoOutput, final Path romPath){
306
        //already paused from the CPU state window: capture there, and leave it paused afterwards
307
        final boolean alreadyPaused = nes.isPaused();
308
        //at a frame's end, so the captured state matches the screenshot
309
        if (!alreadyPaused && !nes.pause(NES.PauseAt.END_OF_FRAME)){
310
            return; //nothing running to flag - not started yet, or already shutting down
311
        }
312
        final DebugReport report;
313
        try {
314
            final LocalDateTime capturedAt = LocalDateTime.now();
315
            final DebugReport captured = DebugCapture.capture(nes, romPath.getFileName().toString(),
316
                    videoOutput.lastPresentedFrame(), capturedAt);
317
            final Optional<String> description = videoOutput.askForIssueDescription();
318
            if (description.isEmpty()){
319
                return;
320
            }
321
            report = captured.withDescription(description.get());
322
        } finally {
323
            if (!alreadyPaused){
324
                nes.resume();
325
            }
326
        }
327
        //everything in the report is already a copy, so the game carries on while it's written - and
328
        //off the EDT, so slow storage can't freeze the window. Not a daemon thread: closing the window
329
        //mid-write still lets the write finish before the JVM exits
330
        new Thread(() -> writeFlaggedIssue(report, romPath, videoOutput), "flagged-issue-writer").start();
331
    }
332
333
    private static void writeFlaggedIssue(final DebugReport report, final Path romPath, final SwingVideoOutput videoOutput){
334
        try {
335
            final Path directory = SavePaths.reserveDebugSnapshotDirectory(romPath, report.capturedAt());
336
            DebugReportWriter.write(directory, report);
337
            System.out.println("Flagged issue saved to " + directory);
338
            SwingUtilities.invokeLater(() -> videoOutput.showStatus("flagged issue saved to " + directory.getFileName()));
339
        } catch (IOException e){
340
            final String message = "Couldn't write a flagged issue under " + SavePaths.saveDirectory(romPath) + ":\n" + e.getMessage();
341
            System.err.println(message);
342
            SwingUtilities.invokeLater(() -> videoOutput.showError("Couldn't save flagged issue", message));
343
        }
344
    }
345
346
    /**
347
     * Debug > Roundabout: opens the Roundabout memory debugger on {@code session}'s game, watching its saved
348
     * labels - at most one at a time. A daemon thread, so an open debugger never keeps the JVM alive once
349
     * the game window has closed.
350
     */
351
    private void openRoundabout(final GameSession session){
352
        final Path romPath = session.romPath();
353
        List<MemoryLabel> labels;
354
        try {
355
            labels = new FileLabelStore(SavePaths.labelsFile(romPath)).load();
356
        } catch (IOException | LabelFileException e){
357
            System.err.println("Roundabout: not watching saved labels - " + e.getMessage());
358
            labels = List.of();
359
        }
360
        final MemoryDebugger debugger = new MemoryDebugger(new NesRoundaboutTarget(session.nes(), labels, frameTimings),
361
                "EmuRoxLab - Roundabout - " + romPath.getFileName());
362
        final Thread thread = new Thread(debugger::run, "roundabout");
363
        thread.setDaemon(true);
364
        final OpenRoundabout open = new OpenRoundabout(debugger, thread);
365
        if (!roundabout.compareAndSet(null, open)){
366
            return;
367
        }
368
        thread.start();
369
        //closed from its own window: free the slot for the next one
370
        final Thread watcher = new Thread(() -> {
371
            joinUninterruptibly(thread);
372
            roundabout.compareAndSet(open, null);
373
        }, "roundabout-watcher");
374
        watcher.setDaemon(true);
375
        watcher.start();
376
    }
377
378
    /**
379
     * Closes Roundabout, if open, and waits for its window to go - each one starts and ends GLFW itself.
380
     *
381
     * @return whether one was open
382
     */
383
    private boolean closeRoundabout(){
384
        final OpenRoundabout open = roundabout.getAndSet(null);
385
        if (open == null){
386
            return false;
387
        }
388
        open.debugger().close();
389
        joinUninterruptibly(open.thread());
390
        return true;
391
    }
392
393
    private static void joinUninterruptibly(final Thread thread){
394
        boolean interrupted = false;
395
        while (thread.isAlive()){
396
            try {
397
                thread.join();
398
            } catch (InterruptedException e){
399
                interrupted = true;
400
            }
401
        }
402
        if (interrupted){
403
            Thread.currentThread().interrupt();
404
        }
405
    }
406
407
    private static void onEdt(final Runnable action){
408
        if (SwingUtilities.isEventDispatchThread()){
409
            action.run();
410
        } else {
411
            SwingUtilities.invokeLater(action);
412
        }
413
    }
414
415
    private static KeyStroke key(final int keyCode){
416
        return KeyStroke.getKeyStroke(keyCode, 0);
417
    }
418
419
    private static ControllerConfiguration loadControllers(final Optional<Path> configPath) throws IOException {
420
        if (configPath.isEmpty()){
421
            System.out.println("No controller config given - running with no controller input (see controllers.properties.example)");
422
            return ControllerConfiguration.NONE;
423
        }
424
        return ControllerConfigLoader.load(configPath.get());
425
    }
426
427
    private static void attachKeyboardControllers(final SwingVideoOutput videoOutput, final ControllerConfiguration controllers){
428
        final Controller[] players = {controllers.player1(), controllers.player2(), controllers.player3(), controllers.player4()};
429
        for (final Controller controller : players){
430
            if (controller instanceof KeyboardController keyboardController){
431
                videoOutput.addKeyListener(keyboardController);
432
            }
433
        }
434
    }
435
}

Mutations

97

1.1
Location : closing
Killed by : none
removed call to com/rox/RomVideoSmokeDemo::onEdt → NO_COVERAGE

98

1.1
Location : lambda$closing$0
Killed by : none
removed call to java/util/List::forEach → NO_COVERAGE

2.2
Location : lambda$closing$1
Killed by : none
removed call to javax/swing/JMenuItem::setEnabled → NO_COVERAGE

99

1.1
Location : lambda$closing$0
Killed by : none
removed call to com/rox/video/SwingVideoOutput::showGame → NO_COVERAGE

105

1.1
Location : started
Killed by : none
removed call to com/rox/RomVideoSmokeDemo::gameStarted → NO_COVERAGE

Active mutators

Tests examined


Report generated by PIT 1.22.1