All files / src/web media-loader.js

97.81% Statements 134/137
95.65% Branches 44/46
96.87% Functions 31/32
98.27% Lines 114/116

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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270                        8x 204801x     2x                                                           27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x   27x 27x 27x 4x 4x 3x   27x 27x 27x 10x 10x 10x 6x 7x 6x       27x 1x 1x 1x 1x 1x       1x                   112x 85x               90x         4x                 7x 7x 7x 6x 6x   1x 1x                     10x 10x 10x 34x 10x 34x 32x   2x 2x     10x                     10x 10x 2x 1x     8x 8x 8x 2x 1x   6x 6x       2x                   7x 2x   6x 6x 6x 6x         6x   6x 6x 6x 6x         2x 1x 1x 1x       2x 2x 1x   1x 1x 1x 1x     1x 1x   1x       12x 11x 11x 11x 1x 1x           10x 1x 1x               9x 8x 8x 7x 7x       2x 1x 1x 1x      
import * as disc from "../fdc.js";
import { localDisc } from "./local-disc.js";
import { DiscLayout } from "../disc.js";
import { loadTapeFromData } from "../tapes.js";
import { toast } from "./toast.js";
import { errorText, reportIgnoredFiles, reportLoadFailure } from "./reporting.js";
import { MediaResolver, Schemas, openIfZip, routeOf, splitImage } from "../media-resolver.js";
import { MediaSlots } from "./media-slots.js";
import { noteFeature } from "./analytics.js";
import { failingFor, LoadFailures } from "../loader.js";
import { browserDiscNames, describeBrowserDisc, describeBuiltIn, describeSessionFile } from "./media-catalogue.js";
 
const isTapeName = (name) => /\.uef$/i.test(name);
const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i]);
 
/** The example discs that ship with jsbeeb. */
export const BuiltInImages = [
    {
        name: "Elite",
        desc: "An 8-bit classic. Hit F10 to launch from the space station, then use <, >, S, X and A to fly around.",
        file: "elite.ssd",
    },
    {
        name: "Welcome",
        desc: "The disc supplied with BBC Disc systems to demonstrate some of the features of the system.",
        file: "Welcome.ssd",
    },
    {
        name: "Music 5000",
        desc: "The Music 5000 system disk and demo songs.",
        file: "5000mstr36008.ssd",
    },
];
 
/**
 * Getting discs and tapes into the machine: resolving any image reference the
 * URL schema can name, files from this computer, and what every source has to
 * offer. What goes in a drive or the deck funnels through its `slots`.
 */
export class MediaLoader extends EventTarget {
    /**
     * @param {object} deps
     * @param {Function} deps.isSnapshotFile says whether a dropped file is a save state
     * @param {Function} deps.loadSnapshot restores a dropped save state
     */
    constructor({ processor, model, drives, urlState, modals, isSnapshotFile, loadSnapshot }) {
        super();
        this.processor = processor;
        this.model = model;
        this.drives = drives;
        this.urlState = urlState;
        this.modals = modals;
        this.resolver = new MediaResolver();
        this.driveSource = null;
        this.isSnapshotFile = isSnapshotFile;
        this.loadSnapshot = loadSnapshot;
        this.slots = new MediaSlots({ loader: this, drives, processor, urlState });
        this.listers = new Map();
        this.describers = new Map();
        /** Files opened this session, by key: the only media the URL cannot name. */
        this.sessionFiles = new Map();
        this.nextSessionFileId = 1;
        this.resolver.addSource("session", (key) => {
            const file = this.sessionFiles.get(key);
            if (!file) throw new Error(`${key} was not opened this session`);
            return { name: file.name, data: file.data, ignored: [] };
        });
        this.addLister("builtin", () => BuiltInImages.map(describeBuiltIn));
        this.addLister("browser", () => browserDiscNames().map(describeBrowserDisc));
        this.addLister("session", () => {
            const files = [...this.sessionFiles];
            const alike = (file) => files.filter(([, other]) => other.name === file.name && other.kind === file.kind);
            return files.map(([key, file]) => {
                const sameName = alike(file);
                const order = sameName.findIndex(([otherKey]) => otherKey === key) + 1;
                return describeSessionFile(key, file.name, file.kind, { order, count: sameName.length });
            });
        });
 
        document.getElementById("fs_load").addEventListener("change", async (evt) => {
            Iif (evt.target.files.length === 0) return;
            noteFeature(evt.target, "upload");
            const file = evt.target.files[0];
            try {
                await this.loadSCSIFile(file);
            } catch (error) {
                reportLoadFailure(file.name, error);
            }
            evt.target.value = ""; // clear so if the user picks the same file again after a reset we get a "change"
        });
    }
 
    get params() {
        return this.urlState.params;
    }
 
    /** Register the fetcher behind an image schema; each source calls this as it is constructed. */
    addSource(schema, fetcher) {
        if (schema === "drive") this.driveSource = fetcher;
        else this.resolver.addSource(schema, fetcher);
    }
 
    /**
     * Register what a source has to offer the media window: a function returning
     * descriptors (see media-catalogue.js), fetched when the window asks.
     */
    addLister(source, lister) {
        this.listers.set(source, lister);
    }
 
    /** How a source describes one entry by path; only a source whose descriptors carry a requirement needs one. */
    addDescriber(source, describer) {
        this.describers.set(source, describer);
    }
 
    /**
     * The descriptor a reference's own source gives for it, whichever way the reference spells
     * the schema, or null: for a source with no describer, a reference it does not know, or a
     * source that cannot answer.
     */
    async describe(ref) {
        const { schema, image } = splitImage(ref);
        const describer = this.describers.get(Schemas[schema]?.source);
        if (!describer) return null;
        try {
            return (await describer(image)) ?? null;
        } catch (error) {
            console.error(`Describing ${ref} failed:`, error);
            return null;
        }
    }
 
    /**
     * Everything every source offers, merged. A source that fails is reported
     * and left out rather than taking the rest of the list with it.
     *
     * @returns {Promise<{descriptors: object[], failures: string[]}>}
     */
    async listAll() {
        const descriptors = [];
        const failures = [];
        const sources = [...this.listers.keys()];
        const outcomes = await Promise.allSettled(sources.map(async (source) => this.listers.get(source)()));
        outcomes.forEach((outcome, i) => {
            if (outcome.status === "fulfilled") {
                descriptors.push(...outcome.value);
            } else {
                console.error(`Listing ${sources[i]} failed:`, outcome.reason);
                failures.push(`${sources[i]}: ${errorText(outcome.reason)}`);
            }
        });
        return { descriptors, failures };
    }
 
    /**
     * A file from this computer, into whatever it is for: a save state is
     * restored, a tape goes in the deck, anything else into the named drive.
     *
     * @returns {Promise<?{kind: string, name: string, ref?: string, driveIndex?: number, words: string}>}
     *   what happened, with words for a toast; null when a restore failed and has been reported already
     */
    async openFile(file, driveIndex = 0, entry) {
        const arrayBuffer = await file.arrayBuffer();
        if (this.isSnapshotFile(file.name, arrayBuffer)) {
            if (!(await this.loadSnapshot(file, arrayBuffer))) return null;
            return { kind: "snapshot", name: file.name, words: `Restored the state saved in ${file.name}.` };
        }
        // What a zip holds decides whether it is a tape or a disc, so it is opened first.
        const { name, data, ignored } = await openIfZip(file.name, new Uint8Array(arrayBuffer));
        reportIgnoredFiles(name, ignored);
        if (isTapeName(name)) {
            const ref = await this.loadTapeFile(name, data, entry);
            return { kind: "tape", name, ref, words: `Loaded ${name} as the tape.` };
        }
        const ref = this.loadDiscFile(name, data, driveIndex, entry);
        return { kind: "disc", name, ref, driveIndex, words: `Loaded ${name} into drive ${driveIndex}.` };
    }
 
    setAutoboot(on) {
        this.urlState.set({ autoboot: on ? true : undefined });
    }
 
    /**
     * Keeps a file opened this session for the list, and says so with "files-changed".
     * A file with the same name and bytes as one already kept is that one again.
     *
     * @returns {string} the `session:` reference the file is known by
     */
    rememberFile(name, data, kind) {
        for (const [key, file] of this.sessionFiles) {
            if (file.name === name && file.kind === kind && sameBytes(file.data, data)) return `session:${key}`;
        }
        const key = `${this.nextSessionFileId++}/${name}`;
        this.sessionFiles.set(key, { name, data, kind });
        this.dispatchEvent(new Event("files-changed"));
        return `session:${key}`;
    }
 
    /** A disc image from this computer, into a drive; the URL cannot name it, so it is unnamed there. */
    loadDiscFile(name, data, driveIndex, entry) {
        const loadedDisc = disc.discFor(name, data, undefined, this.drives.layoutForDrive(driveIndex));
        // Local file: retain the image bytes for embedding in save-to-file snapshots.
        loadedDisc.setOriginalImage(data);
        const ref = this.rememberFile(name, data, "disc");
        this.slots.put(this.slots.drive(driveIndex), loadedDisc, ref, { inUrl: false, entry });
        return ref;
    }
 
    /** A tape image from this computer, into the deck; likewise unnamed in the URL. */
    async loadTapeFile(name, data, entry) {
        const tape = await loadTapeFromData(name, data, this.model);
        const ref = this.rememberFile(name, data, "tape");
        this.slots.put(this.slots.deck, tape, ref, { inUrl: false, entry });
        return ref;
    }
 
    async loadSCSIFile(file) {
        const { processor } = this;
        if (!processor.filestore) return;
        processor.filestore.scsi = new Uint8Array(await file.arrayBuffer());
 
        processor.filestore.PC = 0x400;
        processor.filestore.SP = 0xff;
        processor.filestore.A = 1;
        processor.filestore.emulationSpeed = 0;
 
        // Reset any open receive blocks
        processor.econet.receiveBlocks = [];
        processor.econet.nextReceiveBlockNumber = 1;
 
        this.modals.hide("econetfs");
    }
 
    async loadDiscImage(discImage, layout = DiscLayout.auto) {
        if (!discImage) return null;
        const { image } = splitImage(discImage);
        const route = routeOf(discImage);
        if (route === "browser") {
            return localDisc(image, layout, (error) =>
                toast(
                    `Browser storage would not take changes to ${image} (${errorText(error)}). Use the drive's Save button to keep a copy.`,
                    { title: "Disc", quietKey: "quietLocalDiscSaveFailed" },
                ),
            );
        }
        if (route === "drive") {
            const [, id, name = "(unknown)"] = image.match(/([^/]+)\/?(.*)/) ?? [null, image];
            return this.driveSource({ name, id }, layout);
        }
        // TODO(#822) come up with a decent UX for passing an 'onChange' parameter to each of these.
        // Consider:
        // * hashing contents and making a local disc image named by original disc hash, save by that, and offer
        //   to load the modified disc on load.
        // * popping up a message that notes the disc has changed, and offers a way to make a local image
        // * Dialog box (ugh) saying "is this ok?"
        const { name, data, ignored } = await this.resolver.resolve("disc", discImage);
        reportIgnoredFiles(name, ignored);
        const loaded = await failingFor(LoadFailures.badImage, () => disc.discFor(name, data, undefined, layout));
        if (route === "session") loaded.setOriginalImage(data);
        return loaded;
    }
 
    async loadTapeImage(tapeImage) {
        if (!tapeImage) return null;
        const { name, data, ignored } = await this.resolver.resolve("tape", tapeImage);
        reportIgnoredFiles(name, ignored);
        return failingFor(LoadFailures.badImage, () => loadTapeFromData(name, data, this.model));
    }
}