HardwareEnsemble.java

package libsidplay;

import libsidplay.common.CPUClock;
import libsidplay.common.Event;
import libsidplay.common.Event.Phase;
import libsidplay.common.Ultimate64Mode;
import libsidplay.common.VICModel;
import libsidplay.common.PalEmulationMode;
import libsidplay.common.VICChipModel;
import libsidplay.components.c1530.Datasette;
import libsidplay.components.c1541.*;
import libsidplay.components.cart.CartridgeType;
import libsidplay.components.iec.IECBus;
import libsidplay.components.iec.SerialIECDevice;
import libsidplay.components.mos656x.IPALEmulation;
import libsidplay.components.mos656x.IPalette;
import libsidplay.components.mos656x.PALEmulation;
import libsidplay.components.mos656x.VicePALEmulation;
import libsidplay.components.mos656x.MOS6569;
import libsidplay.components.printer.mps803.MPS803;
import libsidplay.config.IC1541Section;
import libsidplay.config.IConfig;
import libsidplay.config.IEmulationSection;
import libsidplay.config.ISidPlay2Section;
import libsidplay.sidtune.SidTune;
import libsidplay.sidtune.SidTuneError;
import libsidutils.IOUtils;
import libsidutils.prg2tap.PRG2TAP;
import libsidutils.prg2tap.PRG2TAPProgram;

import java.io.*;
import java.util.Locale;

/**
 * The HardwareEnsemble contains a C64 computer and additional peripherals.<BR> It is meant as a complete hardware setup
 * (C64, tape/disk drive, printer, and more).
 *
 * @author Ken Händel
 *
 */
public class HardwareEnsemble implements Ultimate64 {

    // NLQ's single-drive round trips calibrate the sum of the two directions.
    // The split and the half-cycle phase are an approximation. See the IEC timing README.
    private static final int IEC_WRITE_RELEASE_NS = 190;
    private static final int IEC_WRITE_NS = IEC_WRITE_RELEASE_NS + 40;
    private static final int IEC_READ_NS = 200;
    private static final int IEC_DATA_RISE_READ_NS = IEC_READ_NS + 30;

    /**
     * C64 JiffyDOS Kernal ROM.
     */
    private final byte[] JIFFYDOS_C64;
    /**
     * 1541 JiffyDOS drive ROM.
     */
    private final byte[] JIFFYDOS_C1541;
    /**
     * 1571 JiffyDOS drive ROM.
     */
    private final byte[] JIFFYDOS_C1571;
    /**
     * 1581 JiffyDOS drive ROM.
     */
    private final byte[] JIFFYDOS_C1581;

    /**
     * Configuration.
     */
    protected IConfig config;

    /**
     * C64 computer.
     */
    protected C64 c64;
    /**
     * C1530 datasette.
     */
    protected Datasette datasette;
    /**
     * IEC bus.
     */
    protected IECBus iecBus;
    /**
     * Additional serial devices like a printer (except for the floppies).
     */
    protected SerialIECDevice[] serialDevices;
    /**
     * Floppy disk drives.
     */
    private final FloppyDrive[] floppies;
    /**
     * Stock drive ROMs used when creating or replacing the first drive.
     */
    private final byte[] c1541Rom, c1541IIRom, c1571Rom, c1581Rom;
    /**
     * Image mounted in the first drive, retained when changing to a compatible model.
     */
    private File insertedDisk;
    /**
     * Mounted image format used to prepare disk autostart commands.
     */
    private DiskImage.Format insertedDiskFormat;
    /**
     * Whether JiffyDOS is installed in the active drive, independently of pending configuration changes.
     */
    private boolean floppyJiffyDosActive;
    /**
     * C64 clock used to synchronize the independently clocked drive CPU.
     */
    private CPUClock driveMasterClock = CPUClock.PAL;
    /**
     * Preferred 1541 ROM variant, restored when a D64 replaces a D81 image.
     */
    private FloppyType preferred1541 = FloppyType.C1541;
    /**
     * Synchronizes the C64 and the selected floppy drive CPU.
     */
    protected C1541Runner c1541Runner;
    /**
     * MPS803 printer.
     */
    protected MPS803 printer;

    /**
     * Disk image extension policy (handle track number greater than 35).
     */
    private IExtendImageListener policy;

    /**
     * Create a complete hardware setup (C64, tape/disk drive, printer, and more).
     *
     * @param config           emulator configuration
     * @param charBin          C64 character ROM
     * @param basicBin         C64 BASIC ROM
     * @param kernalBin        C64 Kernal ROM
     * @param jiffyDosC64Bin   C64 JiffyDOS Kernal ROM
     * @param jiffyDosC1541Bin 1541 JiffyDOS drive ROM
     * @param jiffyDosC1571Bin 1571 JiffyDOS drive ROM
     * @param jiffyDosC1581Bin 1581 JiffyDOS drive ROM
     * @param c1541Bin         stock 1541 ROM
     * @param c1541_IIBin      stock 1541-II ROM
     * @param c1571Bin         stock 1571 ROM
     * @param c1581Bin         stock 1581 ROM
     * @param mps803CharBin    MPS803 printer character ROM
     */
    public HardwareEnsemble(IConfig config, byte[] charBin, byte[] basicBin, byte[] kernalBin,
                            byte[] jiffyDosC64Bin, byte[] jiffyDosC1541Bin,
                            byte[] jiffyDosC1571Bin, byte[] jiffyDosC1581Bin, byte[] c1541Bin,
                            byte[] c1541_IIBin, byte[] c1571Bin, byte[] c1581Bin, byte[] mps803CharBin) {
        c1541Rom = c1541Bin;
        c1541IIRom = c1541_IIBin;
        c1571Rom = c1571Bin;
        c1581Rom = c1581Bin;
        JIFFYDOS_C64 = jiffyDosC64Bin;
        JIFFYDOS_C1541 = jiffyDosC1541Bin;
        JIFFYDOS_C1571 = jiffyDosC1571Bin;
        JIFFYDOS_C1581 = jiffyDosC1581Bin;

        this.config = config;
        this.iecBus = new IECBus();

        this.printer = new MPS803(this.iecBus, (byte) 4, (byte) 7, mps803CharBin) {
            @Override
            public void setBusy(final boolean flag) {
                c64.cia2.setFlag(flag);
            }

            @Override
            public long clk() {
                return c64.context.getTime(Phase.PHI2);
            }
        };

        this.c64 = new C64(config.getEmulationSection().getC64Model(), config.getEmulationSection().getVicModel(),
                charBin, basicBin, kernalBin) {
            @Override
            public void printerUserportWriteData(final byte data) {
                if (config.getPrinterSection().isPrinterOn()) {
                    printer.printerUserportWriteData(data);
                }
            }

            @Override
            public void printerUserportWriteStrobe(final boolean strobe) {
                if (config.getPrinterSection().isPrinterOn()) {
                    printer.printerUserportWriteStrobe(strobe);
                }
            }

            @Override
            public byte readFromIECBus() {
                if (config.getC1541Section().isDriveOn()) {
                    c1541Runner.synchronize(0);
                    SameThreadC1541Runner runner = directIecRunner();
                    if (runner != null) {
                        return iecBus.readFromIECBus(runner.iecReadDeadline(IEC_READ_NS),
                                runner.iecReadDeadline(IEC_DATA_RISE_READ_NS));
                    }
                }
                return iecBus.readFromIECBus();
            }

            @Override
            public void writeToIECBus(final byte data) {
                if (config.getC1541Section().isDriveOn()) {
                    SameThreadC1541Runner runner = directIecRunner();
                    if (runner != null) {
                        runner.synchronizeIecWrite(iecBus.c64ReleasesClock(data) ? IEC_WRITE_RELEASE_NS : IEC_WRITE_NS);
                    } else {
                        c1541Runner.synchronize(1);
                    }
                }
                iecBus.writeToIECBus(data);
            }

            private SameThreadC1541Runner directIecRunner() {
                if (c1541Runner instanceof SameThreadC1541Runner runner
                        && (parallelCable == null || parallelCable instanceof DisconnectedParallelCable)
                        && iecBus.hasDirect1541II()) {
                    return runner;
                }
                return null;
            }

            @Override
            public boolean getTapeSense() {
                return datasette.getTapeSense();
            }

            @Override
            public void setMotor(final boolean state) {
                datasette.setMotor(state);
            }

            @Override
            public void toggleWriteBit(final boolean state) {
                datasette.toggleWriteBit(state);
            }
        };

        this.datasette = new Datasette(c64.getEventScheduler()) {
            @Override
            public void setFlag(final boolean flag) {
                c64.cia1.setFlag(flag);
            }
        };

        if (config.getC1541Section().getFloppyType() == FloppyType.C1541_II) preferred1541 = FloppyType.C1541_II;
        this.floppies = new FloppyDrive[]{createDrive(config.getC1541Section().getFloppyType())};
        this.serialDevices = new SerialIECDevice[]{printer};
        this.iecBus.setFloppies(floppies);
        this.iecBus.setSerialDevices(serialDevices);
        if (c64.getVicModel() != VICModel.DEFAULT) {
            driveMasterClock = c64.getClock();
            for (SerialIECDevice device : serialDevices) device.setClock(driveMasterClock);
        }
        installDriveRunner();
    }

    /**
     * Get Configuration
     *
     * @return configuration
     */
    public final IConfig getConfig() {
        return config;
    }

    /**
     * Get C64.
     *
     * @return C64
     */
    public final C64 getC64() {
        return c64;
    }

    /**
     * Get C1530 datasette.
     *
     * @return C1530 datasette
     */
    public final Datasette getDatasette() {
        return datasette;
    }

    /**
     * Internal access to the first drive, also used by test-source diagnostics.
     *
     * @return first floppy drive
     */
    final FloppyDrive getFloppy() {
        return floppies[0];
    }

    /**
     * Get the model of the first floppy disk drive.
     *
     * @return floppy type
     */
    public final FloppyType getFloppyType() {
        return floppies[0].getFloppyType();
    }

    /**
     * Get the name of the disk in the first drive.
     *
     * @return disk file name, or null if empty
     */
    public final String getFloppyDiskName() {
        return floppies[0].getDiskName();
    }

    /**
     * Get the activity status of the first floppy disk drive.
     *
     * @return power and activity status
     */
    public final C1541.FloppyStatus getFloppyStatus() {
        return floppies[0].getStatus();
    }

    /**
     * Is the first floppy disk drive powered on?
     *
     * @return true if the drive is on
     */
    public final boolean isFloppyPowerOn() {
        return floppies[0].isPowerOn();
    }

    /**
     * Is the disk motor of the first drive running?
     *
     * @return true if the motor is running
     */
    public final boolean isFloppyMotorOn() {
        return floppies[0].getDiskController().isMotorOn();
    }

    /**
     * Get the head position of the first drive, with track 1 at half-track 2.
     *
     * @return current half-track
     */
    public final int getFloppyHalfTrack() {
        return floppies[0].getDiskController().getHalfTrack();
    }

    /**
     * Reset the first floppy disk drive without ejecting its disk.
     *
     * @throws IOException if the player cannot complete the drive mutation
     */
    public final void resetFloppyDrive() throws IOException {
        mutateDrive(() -> floppies[0].reset());
    }

    /**
     * Apply a RAM expansion setting to the first floppy disk drive.
     *
     * @param bank    RAM expansion bank, from 0 (0x2000) to 4 (0xA000)
     * @param enabled whether the bank is enabled
     * @throws IOException if the player cannot complete the drive mutation
     */
    public final void setFloppyRamExpansion(int bank, boolean enabled) throws IOException {
        mutateDrive(() -> floppies[0].setRamExpansion(bank, enabled));
    }

    /**
     * Get MPS803 printer.
     *
     * @return MPS803 printer
     */
    public final MPS803 getPrinter() {
        return printer;
    }

    /**
     * Set frequency (PAL/NTSC)
     *
     * @param cpuFreq frequency (PAL/NTSC)
     */
    public void setClock(final CPUClock cpuFreq) {
        c64.setClock(cpuFreq);
        CPUClock effectiveClock = c64.getClock();
        driveMasterClock = effectiveClock;
        c1541Runner.setClockDivider(effectiveClock);
        for (SerialIECDevice device : serialDevices) {
            device.setClock(effectiveClock);
        }
    }

    /**
     * Reset hardware.
     */
    public void reset() {
        final ISidPlay2Section sidplay2section = config.getSidplay2Section();
        final IEmulationSection emulationSection = config.getEmulationSection();
        c64.configureVICs(vic -> {
            IPALEmulation palEmulation = vic.getPalEmulation();
            // Respect explicitly disabled video and custom adapters (including TeaVM).
            if (palEmulation instanceof PALEmulation || palEmulation instanceof VicePALEmulation) {
                boolean vice = vic instanceof MOS6569 && sidplay2section.getPalEmulationMode() == PalEmulationMode.VICE;
                if (vice && !(palEmulation instanceof VicePALEmulation)) {
                    vic.setPalEmulation(palEmulation = new VicePALEmulation());
                } else if (!vice && palEmulation instanceof VicePALEmulation) {
                    vic.setPalEmulation(palEmulation = new PALEmulation(VICChipModel.MOS6567R8));
                }
            }
            if (palEmulation != PALEmulation.NONE) {
                palEmulation.setPalEmulationEnable(sidplay2section.isPalEmulation());
                IPalette palette = palEmulation.getPalette();
                palette.setBrightness(sidplay2section.getBrightness());
                palette.setContrast(sidplay2section.getContrast());
                palette.setGamma(sidplay2section.getGamma());
                palette.setSaturation(sidplay2section.getSaturation());
                palette.setPhaseShift(sidplay2section.getPhaseShift());
                palette.setOffset(sidplay2section.getOffset());
                palette.setTint(sidplay2section.getTint());
                palette.setLuminanceC(sidplay2section.getBlur());
                palette.setDotCreep(sidplay2section.getBleed());
            }
        });
        final IC1541Section c1541Section = config.getC1541Section();
        byte[] jiffyDosRom = getJiffyDosRom(c1541Section.getFloppyType());
        c64.setCustomKernal(jiffyDosRom != null ? JIFFYDOS_C64 : null);
        c64.reset();
        iecBus.reset();
        datasette.reset();
        emulationSection.getOverrideSection().reset();

        // The selected model survives reset and disk autostart.
        if (floppies[0].getFloppyType() != c1541Section.getFloppyType()) {
            try {
                setFloppyType(c1541Section.getFloppyType());
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
        // Reset Floppies
        for (final FloppyDrive floppy : floppies) {
            floppy.setRamExpansion(0, c1541Section.isRamExpansion(0));
            floppy.setRamExpansion(1, c1541Section.isRamExpansion(1));
            floppy.setRamExpansion(2, c1541Section.isRamExpansion(2));
            floppy.setRamExpansion(3, c1541Section.isRamExpansion(3));
            floppy.setRamExpansion(4, c1541Section.isRamExpansion(4));
            configureDriveRom(floppy, jiffyDosRom);
            floppy.reset();
        }
        // Both schedulers were reset, even if the drives were already powered on.
        enableFloppyDiskDrives(c1541Section.isDriveOn(), true);
        connectC64AndC1541WithParallelCable(c1541Section.isParallelCable());

        // Reset IEC devices
        for (final SerialIECDevice serialDevice : serialDevices) {
            serialDevice.reset();
        }

        enablePrinter(config.getPrinterSection().isPrinterOn());
    }

    /**
     * Enable floppy disk drives.
     *
     * @param on floppy disk drives enable
     */
    public final void enableFloppyDiskDrives(final boolean on) {
        enableFloppyDiskDrives(on, false);
    }

    private void enableFloppyDiskDrives(final boolean on, final boolean forceReset) {
        c64.getEventScheduler().scheduleThreadSafe(Event.of("C64-C1541 sync", event -> {
            // Disk insertion also enables the drive. Keep its pending clocks and
            // fractional clock conversion when it is already running.
            if (!forceReset && floppies[0].isPowerOn() == on) {
                return;
            }
            if (on) {
                iecBus.clearDriveReadHistory();
                c1541Runner.reset();
            } else {
                c1541Runner.cancel();
            }
            for (FloppyDrive floppy : floppies) {
                floppy.setPowerOn(on);
            }
        }));
    }

    /**
     * Plug in a parallel cable between the C64 user port and the C1541 floppy disk drive.
     *
     * @param connected connected enable
     */
    public final void connectC64AndC1541WithParallelCable(final boolean connected) {
        final IParallelCable cable = connected ? makeCableBetweenC64AndC1541() : new DisconnectedParallelCable();
        c64.setParallelCable(cable);
        for (final FloppyDrive floppy : floppies) {
            floppy.setParallelCable(cable);
        }
    }

    /**
     * Create a parallel cable between the C64 user port and the C1541 floppy disk drive.
     *
     * @return parallel cable
     */
    private IParallelCable makeCableBetweenC64AndC1541() {
        return new IParallelCable() {

            private byte parallelCableCpuValue = (byte) 0xff;
            private final byte[] parallelCableDriveValue = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};

            @Override
            public void driveWrite(final byte data, final boolean handshake, final int dnr) {
                c64.cia2.setFlag(handshake);
                parallelCableDriveValue[dnr & ~0x08] = data;
            }

            @Override
            public byte driveRead(final boolean handshake) {
                c64.cia2.setFlag(handshake);
                return parallelCableValue();
            }

            /**
             * Return the current state of the parallel cable.
             *
             * @return the current state of the parallel cable
             */
            private byte parallelCableValue() {
                byte val = parallelCableCpuValue;

                for (final FloppyDrive floppy : floppies) {
                    val &= parallelCableDriveValue[floppy.getID() & ~0x08];
                }
                return val;
            }

            @Override
            public void c64Write(final byte data) {
                if (config.getC1541Section().isDriveOn()) {
                    c1541Runner.synchronize(0);
                }
                parallelCableCpuValue = data;
            }

            @Override
            public byte c64Read() {
                if (config.getC1541Section().isDriveOn()) {
                    c1541Runner.synchronize(0);
                }
                return parallelCableValue();
            }

            @Override
            public void pulse() {
                if (config.getC1541Section().isDriveOn()) {
                    c1541Runner.synchronize(0);
                }
                for (final FloppyDrive floppy : floppies) {
                    floppy.parallelPulse();
                }
            }
        };
    }

    /**
     * Turn-on printer.
     *
     * @param printerOn printer on/off
     */
    public final void enablePrinter(boolean printerOn) {
        printer.setModel(config.getPrinterSection().getPrinterModel());
        printer.setConnection(config.getPrinterSection().getPrinterConnection());
        printer.turnPrinterOnOff(printerOn);
    }

    /**
     * Extend the floppy disk strategy (&gt; 35 tracks)
     *
     * @param policy extension policy
     */
    public final void setExtendImagePolicy(IExtendImageListener policy) {
        this.policy = policy;
    }

    /**
     * Insert a disk into the first floppy disk drive.
     *
     * @param file disk file to insert
     * @throws IOException image read error
     */
    public final void insertDisk(final File file) throws IOException {
        if (config.getEmulationSection().getUltimate64Mode() != Ultimate64Mode.OFF) {
            sendInsertDisk(config, file);
        }
        config.getSidplay2Section().setLastDirectory(file.getParentFile());
        if (config.getEmulationSection().getUltimate64Mode() != Ultimate64Mode.STANDALONE) {
            insertLocalDisk(file);
        }
    }

    /**
     * Insert into the local emulator and select compatible drive electronics when needed.
     * The browser also uses this entry point without network forwarding.
     *
     * @param file disk image file
     * @throws IOException image is invalid or cannot be mounted
     */
    public final void insertLocalDisk(File file) throws IOException {
        // Validate before detaching or replacing an existing drive.
        try (DiskImage checked = DiskImage.openReadOnly(file)) {
            // Opening the image validates its contents; closing releases the temporary handle.
        }
        mutateDrive(() -> {
            DiskImage.Format format = DiskImage.detect(file);
            FloppyType current = floppies[0].getFloppyType();
            if (!supports(current, format)) changeDrive(switch (format) {
                case D71 -> FloppyType.C1571;
                case D81 -> FloppyType.C1581;
                default -> preferred1541;
            });
            DiskImage disk = floppies[0].getDiskController().insertDisk(file);
            insertedDisk = file;
            insertedDiskFormat = format;
            if (policy != null) {
                disk.setExtendImagePolicy(policy);
            }
            config.getC1541Section().setDriveOn(true);
            enableFloppyDiskDrives(true);
        });
    }

    /**
     * Drive operation that may fail while reading or writing media.
     */
    @FunctionalInterface
    protected interface DriveMutation {
        /**
         * Apply the drive operation.
         *
         * @throws IOException media operation could not be completed
         */
        void run() throws IOException;
    }

    /**
     * Apply a drive operation. Player overrides this hook to serialize operations with its emulation thread.
     *
     * @param mutation drive operation
     * @throws IOException operation could not be completed
     */
    protected void mutateDrive(DriveMutation mutation) throws IOException {
        mutation.run();
    }

    /**
     * Check whether a drive can use an image without changing its electronics.
     *
     * @param type   drive model
     * @param format image format
     * @return true if the model supports the image
     */
    private static boolean supports(FloppyType type, DiskImage.Format format) {
        return switch (format) {
            case D81 -> type == FloppyType.C1581;
            case D71 -> type == FloppyType.C1571;
            default -> type != FloppyType.C1581;
        };
    }

    /**
     * Create a drive using the configured stock or JiffyDOS ROM.
     *
     * @param type drive model
     * @return configured drive
     */
    private FloppyDrive createDrive(FloppyType type) {
        return createDrive(type, getJiffyDosRom(type));
    }

    /**
     * Create the first IEC drive and configure its supported expansions and ROM.
     *
     * @param type        drive model
     * @param jiffyDosRom custom drive ROM, or null for the stock ROM
     * @return configured drive
     */
    private FloppyDrive createDrive(FloppyType type, byte[] jiffyDosRom) {
        FloppyDrive drive = switch (type) {
            case C1541, C1541_II -> new C1541(iecBus, 8, type, c1541Rom, c1541IIRom);
            case C1571 -> new C1571(iecBus, 8, requireDriveRom(c1571Rom, type), c1541Rom, c1541IIRom);
            case C1581 -> new C1581(iecBus, 8, requireDriveRom(c1581Rom, type));
        };
        drive.setParallelCable(new DisconnectedParallelCable());
        if (type == FloppyType.C1541 || type == FloppyType.C1541_II) {
            for (int bank = 0; bank < 5; bank++)
                drive.setRamExpansion(bank, config.getC1541Section().isRamExpansion(bank));
        }
        configureDriveRom(drive, jiffyDosRom);
        return drive;
    }

    /**
     * Select and validate the configured JiffyDOS ROM for a drive model.
     *
     * @param type drive model
     * @return JiffyDOS ROM, or null when JiffyDOS is disabled
     * @throws IllegalStateException required ROM is missing or has an unsupported size
     */
    private byte[] getJiffyDosRom(FloppyType type) {
        if (!config.getC1541Section().isJiffyDosInstalled()) return null;
        byte[] rom = switch (type) {
            case C1541, C1541_II -> JIFFYDOS_C1541;
            case C1571 -> JIFFYDOS_C1571;
            case C1581 -> JIFFYDOS_C1581;
        };
        int length = type == FloppyType.C1541 || type == FloppyType.C1541_II ? 0x4000 : 0x8000;
        if (rom == null || rom.length != length)
            throw new IllegalStateException("A " + length + "-byte JiffyDOS ROM is required for " + type);
        return rom;
    }

    /**
     * Install the selected ROM and remember whether the active drive uses JiffyDOS.
     *
     * @param drive       drive to configure
     * @param jiffyDosRom custom drive ROM, or null for the stock ROM
     */
    private void configureDriveRom(FloppyDrive drive, byte[] jiffyDosRom) {
        drive.setCustomKernalRom(jiffyDosRom);
        if (drive.getFloppyType() == FloppyType.C1541 || drive.getFloppyType() == FloppyType.C1541_II)
            ((C1541) drive).setFloppyType(drive.getFloppyType());
        floppyJiffyDosActive = jiffyDosRom != null;
    }

    /**
     * Validate the stock ROM before replacing a drive or ejecting its media.
     *
     * @param rom  stock drive ROM
     * @param type drive model
     * @return validated ROM
     * @throws IllegalStateException required ROM is missing or has an unsupported size
     */
    private static byte[] requireDriveRom(byte[] rom, FloppyType type) {
        if (rom == null || rom.length != 0x8000)
            throw new IllegalStateException("A 32768-byte ROM is required for " + type);
        return rom;
    }

    /**
     * Connect the first drive's scheduler and clock changes to C64 synchronization.
     */
    private void installDriveRunner() {
        FloppyDrive drive = floppies[0];
        c1541Runner = new SameThreadC1541Runner(c64.getEventScheduler(), drive.getEventScheduler());
        c1541Runner.setClockDivider(driveMasterClock);
        c1541Runner.setDriveFrequency(drive.getClockFrequency());
        if (drive instanceof C1571 c1571)
            c1571.setClockChanged(() -> c1541Runner.setDriveFrequency(c1571.getClockFrequency()));
    }

    /**
     * Validate ROMs, eject the old media and replace the first drive and its runner.
     *
     * @param type replacement drive model
     * @throws IOException old drive could not flush or eject its media
     */
    private void changeDrive(FloppyType type) throws IOException {
        FloppyDrive previous = floppies[0];
        if (previous.getFloppyType() == type) return;
        // Missing/invalid ROMs must not eject the current media.
        if (type == FloppyType.C1571) requireDriveRom(c1571Rom, type);
        if (type == FloppyType.C1581) requireDriveRom(c1581Rom, type);
        byte[] jiffyDosRom = getJiffyDosRom(type);
        previous.getDiskController().ejectDisk();
        c1541Runner.cancel();
        previous.setPowerOn(false);
        iecBus.connectFastSerial(8, null);
        FloppyDrive next = createDrive(type, jiffyDosRom);
        floppies[0] = next;
        iecBus.deviceWrite(8, (byte) 0xc0);
        next.setParallelCable(new DisconnectedParallelCable());
        next.reset();
        installDriveRunner();
        config.getC1541Section().setFloppyType(type);
        insertedDisk = null;
        insertedDiskFormat = null;
    }

    /**
     * Select the first drive's model while retaining compatible mounted media.
     * Switching between the 1541 variants preserves the controller and attached media.
     *
     * @param type requested floppy model
     * @throws IOException mounted media is incompatible or the change cannot be completed
     */
    public final void setFloppyType(FloppyType type) throws IOException {
        mutateDrive(() -> {
            FloppyType current = floppies[0].getFloppyType();
            if (current == type) return;
            // The 1541 variants share the controller implementation and media formats.
            if ((current == FloppyType.C1541 || current == FloppyType.C1541_II)
                    && (type == FloppyType.C1541 || type == FloppyType.C1541_II)) {
                ((C1541) floppies[0]).setFloppyType(type);
                iecBus.clearDriveReadHistory();
                preferred1541 = type;
                config.getC1541Section().setFloppyType(type);
                return;
            }
            File image = insertedDisk;
            if (image != null && !supports(type, DiskImage.detect(image)))
                throw new IOException(type + " cannot read " + DiskImage.detect(image));
            boolean on = floppies[0].isPowerOn();
            changeDrive(type);
            if (image != null) {
                DiskImage disk = floppies[0].getDiskController().insertDisk(image);
                if (policy != null) disk.setExtendImagePolicy(policy);
                insertedDisk = image;
                insertedDiskFormat = disk.getFormat();
            }
            if (type == FloppyType.C1541 || type == FloppyType.C1541_II) preferred1541 = type;
            config.getC1541Section().setFloppyType(type);
            connectC64AndC1541WithParallelCable(config.getC1541Section().isParallelCable());
            enableFloppyDiskDrives(on);
        });
    }

    /**
     * Simulate a user typed-in command, applying the mounted disk's command requirements.
     *
     * @param multiLineCommand command to type-in (PETSCII)
     */
    public final void typeInCommand(final String multiLineCommand) {
        c64.typeInCommand(prepareDiskCommand(multiLineCommand));
    }

    /**
     * Prefix a stock-ROM 1571 D71 LOAD with the native-mode command when required.
     *
     * @param command typed command
     * @return command prepared for the mounted image and installed ROM
     */
    private String prepareDiskCommand(String command) {
        // Stock 1571 ROMs need U0>M1 (native mode) to access both sides of a D71.
        // JiffyDOS can access both sides in 1541 compatibility mode; forcing native
        // mode reduces its performance. Use the installed ROM, not a pending setting.
        return insertedDiskFormat == DiskImage.Format.D71 && !floppyJiffyDosActive
                && command != null && command.startsWith("LOAD")
                && command.contains(",8") ? "OPEN15,8,15,\"U0>M1\":CLOSE15:" + command : command;
    }

    public final void ejectDisk() throws IOException {
        mutateDrive(() -> {
            floppies[0].getDiskController().ejectDisk();
            insertedDisk = null;
            insertedDiskFormat = null;
        });
    }

    /**
     * Insert a tape into the datasette.<BR> Note: If the file is different to the TAP format, it will be converted.
     *
     * @param file tape file to insert
     * @throws IOException image read error
     */
    public final void insertTape(final File file) throws IOException, SidTuneError {
        config.getSidplay2Section().setLastDirectory(file.getParentFile());
        if (!file.getName().toLowerCase(Locale.ENGLISH).endsWith(".tap")) {
            // Everything that is not a tape convert to tape first

            final File convertedTape = new File(config.getSidplay2Section().getTmpDir(), file.getName() + ".tap");
            convertedTape.deleteOnExit();

            SidTune prog = SidTune.load(file);

            PRG2TAPProgram program = new PRG2TAPProgram(prog, IOUtils.getFilenameWithoutSuffix(file.getName()));

            PRG2TAP prg2tap = new PRG2TAP();
            prg2tap.setTurboTape(config.getSidplay2Section().isTurboTape());
            prg2tap.open();
            prg2tap.add(program);
            prg2tap.close();

            try (OutputStream os = new FileOutputStream(convertedTape)) {
                os.write(prg2tap.getResult());
            }
            datasette.insertTape(convertedTape);
        } else {
            datasette.insertTape(file);
        }
    }

    /**
     * Insert a cartridge of a given size with empty contents.
     *
     * @param type   cartridge type
     * @param sizeKB size in KB
     * @throws IOException never thrown here
     */
    public final void insertCartridge(final CartridgeType type, final int sizeKB) throws IOException {
        if (type != CartridgeType.GEORAM) c64.ejectCartridge();
        c64.setCartridge(type, sizeKB);
    }

    /**
     * Insert a cartridge loading an image file.
     *
     * @param type cartridge type
     * @param file file to load the RAM contents
     * @throws IOException image read error
     */
    public final void insertCartridge(final CartridgeType type, final File file) throws IOException {
        config.getSidplay2Section().setLastDirectory(file.getParentFile());
        if (type != CartridgeType.GEORAM) c64.ejectCartridge();
        c64.setCartridge(type, file);
    }

    /**
     * Insert a cartridge of type CRT loading an image.
     *
     * @param is input stream to load the RAM contents
     * @throws IOException image read error
     */
    public final void insertCartridgeCRT(final InputStream is) throws IOException {
        config.getC1541Section().setJiffyDosInstalled(false);
        c64.ejectCartridge();
        c64.setCartridgeCRT(is);
    }

}