All files / src/web machine.js

82.75% Statements 48/58
80% Branches 24/30
73.68% Functions 14/19
83.63% Lines 46/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218                                                16x                                                                               13x 13x 13x   13x 13x 1x   12x     13x   26x                     13x                     13x                       13x   13x 13x 13x                 9x 9x   8x 8x     1397x                                         7x 7x     7x     7x     7x 7x 7x         7x 7x       7x 7x 3x 3x           7x 1x 1x   7x 2x 2x     7x       7x                       7x 1x 1x       7x      
import { machineSpec } from "../machine-spec.js";
import { describeRef } from "./media-catalogue.js";
import { Cmos, localStoragePersistence } from "../cmos.js";
import { Econet } from "../econet.js";
import { LoadSD } from "../mmc.js";
import { tubeModelFor } from "../models.js";
import { toast } from "./toast.js";
import { errorText, reportLoadFailure, showNotice } from "./reporting.js";
import { loadData } from "../loader.js";
 
/**
 * The machine's fittings as the CPU wants them handed over. Pure, so the bank
 * and flag decisions are testable on their own.
 */
export function buildEmulationConfig({
    settings,
    parsedQuery,
    keyLayout,
    cpuMultiplier,
    extraRoms,
    bankRoms,
    userPort,
    printer,
}) {
    return machineSpec({
        keyLayout,
        cpuMultiplier,
        tubeCpuMultiplier: settings.tubeCpuMultiplier,
        videoCyclesBatch: parsedQuery.videoCyclesBatch,
        tube: settings.coProcessor ? tubeModelFor(settings.model) : null,
        hasMusic5000: settings.hasMusic5000,
        hasTeletextAdaptor: settings.hasTeletextAdaptor,
        fittedRoms: settings.fittedRoms,
        bankRoms,
        extraRoms,
        userPort,
        printerPort: printer,
        getGamepads: function () {
            // Gamepads are only available in secure contexts. If e.g. loading from http:// urls they aren't there.
            return navigator.getGamepads ? navigator.getGamepads() : [];
        },
    });
}
 
/** The emulated machine itself: the processor with everything bolted to it, and its start-up. */
export class Machine {
    constructor({
        model,
        settings,
        parsedQuery,
        keyLayout,
        cpuMultiplier,
        extraRoms,
        bankRoms,
        stationId,
        userPort,
        printer,
        speechOutput,
        video,
        audioHandler,
        dbgr,
        gamepad,
        build = (cpuModel, options) => new cpuModel.Cpu(cpuModel, options),
    }) {
        this.model = model;
        this.audioHandler = audioHandler;
        this.speechOutput = speechOutput;
 
        this.econet = null;
        if (settings.hasEconet) {
            this.econet = new Econet(stationId, model.cyclesPerSecond);
        } else {
            document.getElementById("fsmenuitem").style.display = "none";
        }
 
        this.cmos = new Cmos(
            localStoragePersistence(
                () => window.localStorage,
                (error) =>
                    toast(
                        `Settings changed with *CONFIGURE will not be kept (${errorText(error)}). Check that this site is allowed to store data, and that its storage is not full.`,
                        { title: "Settings", quietKey: "quietCmosSave" },
                    ),
            ),
            model.cmosOverride,
            this.econet,
        );
 
        this.spec = buildEmulationConfig({
            settings,
            parsedQuery,
            keyLayout,
            cpuMultiplier,
            extraRoms,
            bankRoms,
            userPort,
            printer,
        });
 
        this.processor = build(model, {
            dbgr,
            video,
            soundChip: audioHandler.soundChip,
            ddNoise: audioHandler.ddNoise,
            relayNoise: audioHandler.relayNoise,
            music5000: settings.hasMusic5000 ? audioHandler.music5000 : null,
            cmos: this.cmos,
            econet: this.econet,
            config: this.spec,
        });
 
        printer.attach(this.processor);
        // The same pad presses the Atom's keys too.
        if (model.isAtom) this.processor.atommc.attachGamepad(gamepad);
        this.processor.teletextAdaptor?.addEventListener("notice", showNotice);
        this.processor.acia.addEventListener("notice", showNotice);
    }
 
    /**
     * Attach an RS-423 composite handler to the ACIA that combines the touchscreen
     * (which sends position data to the BBC) with the speech output (which speaks
     * text the BBC sends out).
     */
    setupRs423Handler() {
        const { processor, speechOutput } = this;
        processor.acia.setRs423Handler({
            onTransmit(val) {
                processor.touchScreen.onTransmit(val);
                if (!processor.replaying) speechOutput.onTransmit(val);
            },
            tryReceive(rts) {
                return processor.touchScreen.tryReceive(rts);
            },
        });
    }
 
    /**
     * Initialises the machine and starts every image the URL asked for, each
     * reporting its own failure without stopping the boot (#808).
     */
    async start({
        media,
        autoBoot,
        discImage,
        discImageInUrl = true,
        secondDiscImage,
        tape,
        mmcImage,
        loadBasic,
        embedBasic,
        basicNeedsRun,
    }) {
        const { processor } = this;
        await Promise.all([this.audioHandler.initialise(), processor.initialise()]);
 
        // Wire up the composite RS-423 handler now that the touchscreen exists.
        this.setupRs423Handler();
 
        // Ideally would start the loads first. But their completion needs the FDC from the processor
        const imageLoads = [];
 
        function startImageLoad(description, load) {
            const loading = (async () => {
                try {
                    await load();
                } catch (error) {
                    reportLoadFailure(description, error);
                }
            })();
            imageLoads.push(loading);
            return loading;
        }
 
        // The slots report their own failures; the page's default disc is not named in the URL.
        const { slots } = media;
        if (discImage)
            startImageLoad(`disc ${discImage}`, () =>
                slots.load(slots.drive(0), describeRef(discImage, "disc"), {
                    inUrl: discImageInUrl,
                    recent: false,
                    entry: discImageInUrl ? "url" : "default",
                }),
            );
        if (secondDiscImage)
            startImageLoad(`disc ${secondDiscImage}`, () =>
                slots.load(slots.drive(1), describeRef(secondDiscImage, "disc"), { recent: false, entry: "url" }),
            );
        if (tape)
            startImageLoad(`tape ${tape}`, () =>
                slots.load(slots.deck, describeRef(tape, "tape"), { recent: false, entry: "url" }),
            );
 
        Iif (mmcImage && this.model.isAtom) {
            startImageLoad(`MMC image ${mmcImage}`, async () => processor.atommc.SetMMCData(await LoadSD(mmcImage)));
        }
 
        Iif (loadBasic) {
            await startImageLoad(`BASIC program ${loadBasic}`, () =>
                autoBoot.insertBasic(
                    (async () => {
                        const data = await loadData(loadBasic);
                        return String.fromCharCode.apply(null, data);
                    })(),
                    basicNeedsRun,
                ),
            );
        }
 
        if (embedBasic) {
            await startImageLoad("the BASIC program from the URL", () =>
                autoBoot.insertBasic(Promise.resolve(embedBasic), true),
            );
        }
 
        return Promise.all(imageLoads);
    }
}