AutostartControl.java

package sidplay.player;

import libsidplay.C64;
import libsidplay.common.Event;
import libsidplay.components.cart.MusicCartridge;
import libsidplay.components.cart.supported.GeoRAM;
import libsidplay.components.cart.supported.REU;
import libsidplay.components.cart.supported.SFXSoundExpander;

import java.util.function.Consumer;

/**
 * Load through the emulated hardware, then release startup WARP before entering the following command.
 * Editor state and instruction addresses are observed without bus reads, ROM traps or changes to CPU timing.
 */
public final class AutostartControl {
    private final C64 c64;
    private final Consumer<String> typeCommand;
    private final Runnable finishWarp;
    private final Event promptEvent;

    private boolean active, enteredRom, commandStarted;
    private String followingCommand;

    public AutostartControl(C64 c64, Consumer<String> typeCommand, Runnable finishWarp) {
        this.c64 = c64;
        this.typeCommand = typeCommand;
        this.finishWarp = finishWarp;
        promptEvent = Event.of("Autostart prompt", event -> {
            observePrompt();
            if (active) {
                c64.getEventScheduler().schedule(event, c64.getCyclesPerFrame(), Event.Phase.PHI2);
            }
        });
    }

    public static boolean isLoadCommand(String command) {
        return command != null && command.startsWith("LOAD")
                && (command.length() == 4 || !Character.isLetterOrDigit(command.charAt(4)));
    }

    public static boolean isCartridgeBoot(C64 c64, boolean reset, String command) {
        var cartridge = c64.getCartridge();
        return reset && c64.isCartridge() && !isLoadCommand(command)
                && !(cartridge instanceof REU) && !(cartridge instanceof GeoRAM)
                && !(cartridge instanceof SFXSoundExpander) && !(cartridge instanceof MusicCartridge);
    }

    public boolean isActive() {
        return active;
    }

    /**
     * Return false for commands which do not begin with LOAD. Nonstandard editors retain the original command input
     * after releasing automatic WARP; the BASIC editor must accept input before command delivery is staged.
     */
    public boolean start(String command) {
        cancel();
        if (!isLoadCommand(command)) {
            return false;
        }
        byte[] ram = c64.getRAM();
        int cursor = editorCursor(ram);
        if (!editorReady(ram, cursor)) {
            finishWarp.run();
            typeCommand.accept(command);
            return true;
        }
        int separator = commandSeparator(command);
        String load = command;
        followingCommand = null;
        if (separator >= 0) {
            load = command.substring(0, separator) + '\r';
            String following = command.substring(separator + 1);
            if (!following.isBlank()) {
                followingCommand = following;
            }
        }
        active = true;
        enteredRom = commandStarted = false;
        c64.setCpuExecutionObserver(this::observeExecution);
        typeCommand.accept(load);
        c64.getEventScheduler().schedule(promptEvent, 0, Event.Phase.PHI2);
        return true;
    }

    /** Cancel a pending follow-up command on stop, reset, an error or a program taking over execution. */
    public void cancel() {
        complete(false);
    }

    private void complete(boolean success) {
        if (!active) {
            return;
        }
        String following = success ? followingCommand : null;
        active = false;
        followingCommand = null;
        c64.setCpuExecutionObserver(null);
        c64.getEventScheduler().cancel(promptEvent);
        finishWarp.run();
        if (following != null) {
            typeCommand.accept(following);
        }
    }

    private void observeExecution(int pc) {
        observeCommandStart(c64.getRAM());
        boolean ram = c64.isCpuReadFromRam(pc);
        if (pc >= 0xe000 && !ram) {
            enteredRom = true;
        } else if (enteredRom && ram && (pc < 0x0073 || pc > 0x008a)) {
            // A loader/program which starts itself must not receive a delayed RUN later.
            cancel();
        }
    }

    private void observePrompt() {
        if (!active) {
            return;
        }
        byte[] ram = c64.getRAM();
        observeCommandStart(ram);
        int cursor = editorCursor(ram);
        if (!editorReady(ram, cursor)) {
            return;
        }
        for (int line = 1; line <= 3 && cursor - line * 40 >= (cursor & ~0x3ff); line++) {
            int address = cursor - line * 40;
            if (matches(ram, address, "?") || matches(ram, address, "BREAK")) {
                cancel();
                return;
            }
        }
        if (!commandStarted) {
            return; // A consumed RETURN can precede the editor leaving its old READY prompt.
        }
        if (matches(ram, cursor - 40, "READY.")) {
            complete(true);
        } else if (!blankLine(ram, cursor - 40)) {
            // The editor accepts input again, but loading did not finish at the expected prompt.
            cancel();
        }
    }

    private void observeCommandStart(byte[] ram) {
        if (ram[0xc6] == 0 && ram[0xcc] != 0) {
            commandStarted = true;
        }
    }

    private static int commandSeparator(String command) {
        boolean quoted = false;
        for (int index = 0; index < command.length(); index++) {
            char character = command.charAt(index);
            if (character == '"') {
                quoted = !quoted;
            } else if (character == '\r' || character == ':' && !quoted) {
                return index;
            }
        }
        return -1;
    }

    private static int editorCursor(byte[] ram) {
        // Derive the page from the editor pointer, not a possibly half-updated low byte. As in VICE, normalize a
        // wrapped logical line to its physical 40-column screen line before inspecting the preceding prompt.
        int base = ((ram[0xd1] & 255) | (ram[0xd2] & 255) << 8) & ~0x3ff;
        int row = (ram[0xd6] & 255) + (ram[0xd3] & 255) / 40;
        return base >= 0x400 && row > 0 && row < 25 && base + 1000 <= ram.length ? base + row * 40 : -1;
    }

    private static boolean editorReady(byte[] ram, int cursor) {
        return cursor >= 0 && ram[0xc6] == 0 && ram[0xcc] == 0 && (ram[0xd3] & 255) % 40 == 0;
    }

    private static boolean blankLine(byte[] ram, int address) {
        for (int column = 0; column < 40; column++) {
            if ((ram[address + column] & 0x7f) != 32) {
                return false;
            }
        }
        return true;
    }

    private static boolean matches(byte[] ram, int address, String text) {
        for (int index = 0; index < text.length(); index++) {
            if ((ram[address + index] & 0x7f) != (text.charAt(index) & 0x3f)) {
                return false;
            }
        }
        return true;
    }
}