All files / src mmc.js

87.73% Statements 508/579
76.34% Branches 213/279
82.97% Functions 78/94
89.48% Lines 468/523

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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077                                                    137x 137x 137x 137x 137x   137x 137x 137x   137x 137x   137x   137x 137x   137x 137x 137x 137x 137x   137x 137x 137x 137x     137x     137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x     137x 137x 137x 137x     137x 137x 137x     137x   137x 137x 137x 137x 137x 137x     137x 137x 137x 137x 137x 137x 137x 137x 137x 137x   137x     137x 137x 137x 137x                               73x 73x           1x 1x 1x 2x 2x 3x 2x   1x                           51x 51x   51x 51x 51x   51x   51x 51x 51x   51x   51x 51x         51x 51x 51x 51x       23x 43x 43x 23x       39x           5x 15x 15x 10x           23x 5x 22x 22x   5x           42x         42x       4x 4x       19x       74x 74x 74x       13x 12x 12x           14x 14x         1x 1x   1x 1x 1x       1x 1x                 1x 1x                                                     1x     1x     1x 1x 1x     1x   1x             17x 17x     20x     17x     17x         17x     17x           17x   17x     17x 7x   3x 3x   4x 4x   14x     17x     14x 14x       3x           1x 1x 1x     1x   1x 1x               1x   1x 1x 1x       1x       17x   17x 17x   17x       14x 17x 17x   17x 3x 3x     14x     14x   14x     11x 11x 11x 4x 4x       11x   11x 11x             2x     4x   1x   1x             1x 1x 2x 1x     1x     1x   1x     1x           1x 1x         1x 1x   1x 1x 1x                 1x 1x           1x                   1x   3x 1x   1x             50x       50x 50x       1x 1x 1x       9x 9x 8x 8x 8x       40x 40x 36x     36x 36x 36x 36x 5x   31x         12x 12x 11x     11x 11x 11x 11x 11x 11x 11x 11x 11x             1x 1x 1x                                   59x       69x 69x       175x 175x       246x 246x 246x 246x 246x       52x         6x 6x         24x                     6x 6x 6x 6x 24x 24x   6x 6x 6x 6x 6x       46x   46x   46x   4x 4x 4x   42x 42x 26x 16x 11x 5x 4x   42x 41x 41x 40x   40x   1x       1x     46x           94x     94x   46x 46x     46x 46x 46x     46x           46x                                 94x   46x     48x   94x             46x 46x 46x   56x 46x       43x 43x 53x   43x   4x 4x 4x 39x         43x               45x 45x     45x     45x     45x   45x 45x 39x 39x 39x 39x 39x     6x 2x       43x   43x 43x                                 9x               59x 58x 58x   59x               23x               9x             51x 51x 51x 51x 51x 51x 51x 51x 51x 51x   51x 51x       6x                         6x 6x 6x 6x 6x 6x 6x 6x               771x 771x 771x         526x 526x         469x 469x 469x 469x 469x 469x 469x 34x   435x 435x                 961x 961x 961x 961x 961x 435x 435x   192x 192x 192x       526x   297x 297x 69x 69x   297x 175x 175x   297x 297x 297x 1x 296x 14x 282x 1x 281x     281x     281x     281x 13x 268x 42x 226x 4x 222x   222x 1x 221x   221x 9x 212x 54x 54x 54x 158x 69x 89x 40x 40x 49x 12x 12x 37x   37x   37x   37x 5x 32x 1x 1x 31x   31x 10x 10x 21x 2x 19x 6x 13x 4x 4x 9x 9x 9x 9x 9x 9x 9x 9x 9x                 297x     175x 175x 175x     54x 54x 54x 54x             526x        
import { unzip } from "./archive.js";
import { loadData } from "./loader.js";
 
/*
highly adapted from:
https://github.com/hoglet67/Atomulator
in the src/atommc folder
 
Simulate the AtoMMC2 device, which is a MMC/SD card reader for the Acorn Atom.
 
First create a dictionary of the MMC data from a zipped file, into this.allfiles.
 
The Acorn Atom MMC2 eprom will communicate with the MMC via 0xb400-0xb40c, which is the Atom side of the MMC2 device.
The write() is called when 0xb400-0xb40c is written, read() is called when 0xb400-0xb40c is read.
 
the low byte determines which register is being accessed.
The registers are:
CMD_REG: 0xb400
LATCH_REG: 0xb401
READ_DATA_REG: 0xb402
WRITE_DATA_REG: 0xb403
STATUS_REG: 0xb404
 
*/
 
// Access an MMC file (zipped)
const CMD_REG = 0x0;
const LATCH_REG = 0x1;
const READ_DATA_REG = 0x2;
const WRITE_DATA_REG = 0x3;
const STATUS_REG = 0x4;
 
const CMD_DIR_OPEN = 0x0;
const CMD_DIR_READ = 0x1;
const CMD_DIR_CWD = 0x2;
// const CMD_DIR_GETCWD = 0x3;
const CMD_DIR_MKDIR = 0x4;
const CMD_DIR_RMDIR = 0x5;
 
const CMD_RENAME = 0x8;
 
const CMD_FILE_CLOSE = 0x10;
const CMD_FILE_OPEN_READ = 0x11;
// const CMD_FILE_OPEN_IMG = 0x12;
const CMD_FILE_OPEN_WRITE = 0x13;
const CMD_FILE_DELETE = 0x14;
const CMD_FILE_GETINFO = 0x15;
const CMD_FILE_SEEK = 0x16;
const CMD_FILE_OPEN_RAF = 0x17;
 
const CMD_INIT_READ = 0x20;
const CMD_INIT_WRITE = 0x21;
const CMD_READ_BYTES = 0x22;
const CMD_WRITE_BYTES = 0x23;
 
// EXEC_PACKET_REG "commands"
const CMD_EXEC_PACKET = 0x3f;
 
// UTIL_CMD_REG commands
const CMD_GET_CARD_TYPE = 0x80;
const CMD_GET_PORT_DDR = 0xa0;
const CMD_SET_PORT_DDR = 0xa1;
const CMD_READ_PORT = 0xa2;
const CMD_WRITE_PORT = 0xa3;
const CMD_GET_FW_VER = 0xe0;
const CMD_GET_BL_VER = 0xe1;
const CMD_GET_CFG_BYTE = 0xf0;
const CMD_SET_CFG_BYTE = 0xf1;
const CMD_READ_AUX = 0xfd;
const CMD_GET_HEARTBEAT = 0xfe;
 
// Status codes
const STATUS_OK = 0x3f;
const STATUS_COMPLETE = 0x40;
const STATUS_EOF = 0x60;
const STATUS_BUSY = 0x80;
 
// STATUS_REG bit masks
const MMC_MCU_BUSY = 0x01;
const MMC_MCU_READ = 0x02;
const MMC_MCU_WROTE = 0x04;
 
// The PIC's weak pull-ups hold an unpressed joystick line high.
const JOYSTICK_IDLE = 0xff;
 
const VSN_MAJ = 2;
const VSN_MIN = 10;
const FA_OPEN_EXISTING = 0;
const FA_READ = 1;
const FA_WRITE = 2;
const FA_CREATE_NEW = 4;
 
// Simulate constants
const FR_OK = 0,
    FR_EXIST = 8,
    FR_NO_FILE = 4,
    FR_NO_PATH = 5,
    FR_INVALID_NAME = 6,
    FR_INVALID_OBJECT = 9;
const FA_CREATE_ALWAYS = 8,
    FA_OPEN_ALWAYS = 16,
    ERROR_TOO_MANY_OPEN = 0x12,
    FILENUM_OFFSET = 0x20;
// Stands in for a full card, where FatFs clips seeks and short-writes with FR_OK; files already larger keep their size.
const MaxGrowFileBytes = 16 * 1024 * 1024;
 
// Simulate open modes
const O_CREAT = 0x100,
    O_RDWR = 0x2,
    O_RDONLY = 0x0,
    O_BINARY = 0x8000;
 
// Reference: https://github.com/hoglet67/AtoMMC2Firmware (atmmmc2def.h)
 
/** WFN functions
 *
 */
/**
 * Represents a file with a path and data.
 */
export class WFNFile {
    /**
     * @param {string} path - The file path. prepended with § if deleted
     * @param {Uint8Array} data - The file data.
     */
    constructor(path, data) {
        this.path = path;
        this.data = data instanceof Uint8Array ? data : new Uint8Array();
    }
}
 
// Extract all files from a ZIP archive into WFNFile entries.
export async function extractSDFiles(data) {
    const files = await unzip(new Uint8Array(data));
    const result = [];
    for (const [name, fileData] of Object.entries(files)) {
        Iif (!/^[a-z0-9./_ -]+$/i.test(name)) continue;
        Iif (name.endsWith("/")) continue; // skip directory entries
        Iif (name.split("/").some((seg) => seg === "..")) continue;
        result.push(new WFNFile("/" + name, fileData));
    }
    return result;
}
 
export async function LoadSD(file) {
    const data = await loadData(file);
    return extractSDFiles(data);
}
 
class WFN {
    /**
     * Create a new WFN instance.
     * @param {Object} cpu - The CPU instance.
     */
    constructor(mmc, cpu) {
        this.mmc = mmc;
        this.cpu = cpu;
 
        this.globalData = new Uint8Array(256);
        this.globalIndex = 0;
        this.globalAmount = 0;
 
        this.fildata = new Array(4).fill(null);
 
        this.openeddir = ""; // Directory requested when reading directories
        this.foldersSeen = []; // Folders seen when reading directories
        this.dfn = 0; // Directory file number, used to track the current file in the zip file when reading directories
 
        this.CWD = "";
 
        this.filenum = -1;
        this.wildcard = "*";
 
        /**
         * @type {WFNFile[]}
         */
        this.allfiles = [];
        this.loadedFiles = [];
        this.loadedIndexByData = new Map();
        this.cardSnapshot = null;
    }
 
    load(files) {
        this.allfiles = files;
        this.loadedFiles = files.map(({ path, data }) => ({ path, data }));
        this.loadedIndexByData = new Map(files.map(({ data }, index) => [data, index]));
        this.cardChanged();
    }
 
    cardChanged() {
        this.cardSnapshot = null;
    }
 
    // A file's bytes are replaced on a write, never written into, so snapshots share them; one the card was
    // given with is saved as its index in the card as loaded.
    snapshotCard() {
        return this.allfiles.map(({ path, data }) => {
            const loaded = this.loadedIndexByData.get(data);
            if (loaded === undefined) return { path, data };
            return path === this.loadedFiles[loaded].path ? { loaded } : { path, loaded };
        });
    }
 
    // A card without the files the snapshot's card was loaded with keeps its own.
    restoreCard(card) {
        if (card.some(({ loaded }) => loaded >= this.loadedFiles.length)) return;
        this.allfiles = card.map(({ path, data, loaded }) => {
            const asLoaded = this.loadedFiles[loaded];
            return new WFNFile(path ?? asLoaded.path, data ?? asLoaded.data);
        });
        this.cardSnapshot = card;
    }
 
    WFN_WorkerTest() {}
 
    WFN_FileOpenRead() {
        const res = this.fileOpen(FA_OPEN_EXISTING | FA_READ);
        // if (filenum < 4) {
        //      FILINFO *filinfo = &filinfodata[filenum];
        //     get_fileinfo_special(filinfo);
        // }
        this.mmc.WriteDataPort(STATUS_COMPLETE | res);
    }
 
    WFN_FileOpenWrite() {
        const res = this.fileOpen(FA_CREATE_NEW | FA_WRITE);
        this.mmc.WriteDataPort(STATUS_COMPLETE | res);
    }
 
    static sizeLimit(handle) {
        return Math.max(MaxGrowFileBytes, handle.file.data.length);
    }
 
    handleOrAnswerInvalid() {
        const handle = this.fildata[this.filenum];
        if (!handle) this.mmc.WriteDataPort(STATUS_COMPLETE | FR_INVALID_OBJECT);
        return handle;
    }
 
    WFN_FileClose() {
        if (!this.handleOrAnswerInvalid()) return;
        this.fildata[this.filenum] = null;
        this.mmc.WriteDataPort(STATUS_COMPLETE);
    }
 
    // Convert a glob pattern (with * and ?) to an anchored regex string.
    static wildcardToRegex(pattern) {
        // Escape regex metacharacters except * and ?, then convert glob wildcards.
        const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
        return "^" + escaped.replace(/\*/g, ".*").replace(/\?/g, ".") + "$";
    }
 
    GetWildcard() {
        // Extract the path from this.globalData (Uint8Array) until the first null byte
        const path = this.trimToFilename(this.globalData).replace(/\\/g, "/");
        const hasWildcard = path.includes("*") || path.includes("?");
 
        if (hasWildcard) {
            const lastSlashIndex = path.lastIndexOf("/");
            Iif (lastSlashIndex !== -1) {
                this.globalData = new TextEncoder().encode(path.slice(0, lastSlashIndex + 1) + "\0");
                this.wildcard = path.slice(lastSlashIndex + 1);
            } else {
                this.wildcard = path;
                this.globalData = new TextEncoder().encode("\0");
            }
        } else E{
            this.wildcard = "*";
        }
    }
 
    // Strip trailing slash from a path string
    stripTrailingSlash(path) {
        Eif (path.endsWith("/")) {
            return path.slice(0, -1);
        }
        return path;
    }
 
    /*
    MMCData file contains only files with paths, and no directories.
    To simulate directories, a basepath with multiple entries is a directory
    For example, if the MMCData file contains:
    /dir1/file1.txt
    /dir1/file2.txt
    /dir2/file3.txt
    then /dir1/ is a directory, and /dir2/ is a directory.
    The findfirst and findnext functions will simulate directory traversal by checking the paths in allfiles.
    The findfirst function will set this.dfn to the index of the first file in the directory, and this.openeddir to the directory path.
    The findnext function will iterate through the files in the directory, checking if the file path starts with this.openeddir.
    If a file path starts with this.openeddir, it is considered to be in the directory.
    If a file path does not start with this.openeddir, it is considered to be outside the directory.
    If a file path has a subdirectory (i.e., it contains a slash after the directory path), it is considered to be in a subdirectory and is returned
    once and subsequent calls to findnext will skip it.
 
 
 
    */
 
    // Simulate findfirst: check if a directory exists in allfiles
    findfirst(path) {
        const dirPrefix = this.stripTrailingSlash(path) + "/"; // Ensure path ends with a slash
 
        // Simulate directory open: check if any file starts with path + "/"
        const f_index = this.allfiles.findIndex((file) => file.path.startsWith(dirPrefix));
 
        // if index is found, set dfn to the index of the first file in the directory
        Eif (f_index !== -1) {
            this.dfn = f_index + 1; // Set dfn to the next entry after the first one in this directory
            this.openeddir = dirPrefix; // record the opened directory
        }
 
        this.foldersSeen = [];
 
        return f_index !== -1;
    }
 
    // this.dfn is the index of the next file in the zip file
 
    // Simulate findnext: iterate through directory entries in allfiles[].path
    findnext() {
        let foundDirEntry = "";
        do {
            // entry = readdir()
 
            if (this.dfn >= this.allfiles.length) break;
 
            // Check if the next file starts with the opened directory
            const nextFullName = this.allfiles[this.dfn].path;
            //
 
            Iif (!nextFullName.startsWith(this.openeddir)) {
                this.dfn += 1;
                continue; // Skip to the next entry if it doesn't match the opened directory
            }
 
            let relativeName = nextFullName.slice(this.openeddir.length);
 
            // Skip empty or root entries
            Iif (relativeName === "" && relativeName !== "/") {
                this.dfn += 1;
                continue; // Skip to the next entry if it doesn't match the opened directory
            }
 
            //
            let folders = relativeName.split("/");
 
            relativeName = folders[0];
 
            // skip files in subdirectories if the subdirecty has been seen before
            if (folders.length > 1) {
                if (this.foldersSeen.includes(folders[0])) {
                    // If this is seen subfolder, skip this entry
                    this.dfn += 1;
                    continue;
                }
                this.foldersSeen.push(folders[0]);
                relativeName = folders[0] + "/"; // relative name is the folder + slash
            }
            foundDirEntry = relativeName;
        } while (foundDirEntry == "");
 
        if (foundDirEntry) {
            // Optionally, check for valid 8.3 filename here if needed
            // For now, just return the entry
            this.dfn += 1;
            return foundDirEntry;
        }
 
        // No more entries
        return "";
    }
 
    // Simulate f_opendir: open a directory
    f_opendir(path) {
        // Build absolute path and check validity
        const xpath = this.trimToFilename(path);
        const absResult = this.buildAbsolutePath(xpath, false);
        Iif (absResult.error) {
            return absResult.error;
        }
        const newpath = absResult.path;
 
        if (this.findfirst(newpath)) {
            return FR_OK;
        } else E{
            return FR_NO_PATH;
        }
    }
 
    WFN_DirectoryOpen() {
        // Separate wildcard and path
        this.GetWildcard();
 
        let res = this.f_opendir(this.globalData);
        this.dfn = 0;
        Iif (res !== 0) {
            this.mmc.WriteDataPort(STATUS_COMPLETE | res);
            return;
        }
        this.mmc.WriteDataPort(STATUS_OK);
    }
 
    f_readdir() {
        let fno = { fname: "", fsize: 0, fattrib: 0 };
        // If a file found copy it's details, else set size to 0 and filename to ''
        const nextentry = this.findnext();
        fno.fname = nextentry;
 
        return { error: FR_OK, fno: fno };
    }
 
    WFN_DirectoryRead() {
        while (true) {
            let result = this.f_readdir();
            let res = result.error;
 
            if (res !== FR_OK || result.fno.fname === "") {
                this.mmc.WriteDataPort(STATUS_COMPLETE | res);
                return;
            }
 
            const fname = result.fno.fname;
 
            // Check to see if filename matches current wildcard
            const Match = fname.match(new RegExp(WFN.wildcardToRegex(this.wildcard)));
 
            if (Match) {
                // if is a directory, str will be <fname>
 
                const isdir = fname.endsWith("/");
                let str = fname;
                if (isdir) {
                    str = str.slice(0, -1); // Remove trailing slash for directory names
                    str = `<${str}>`; // Enclose directory names in <>
                }
 
                // Convert the string to a Uint8Array
                this.globalData = new TextEncoder().encode(str + "\0");
 
                this.mmc.WriteDataPort(STATUS_OK);
                return;
            }
        }
    }
 
    dir_exists(path) {
        // ensure path ends in slash
        Eif (!path.endsWith("/")) path += "/";
 
        // Check if the path exists in the names array
        if (this.allfiles.some((file) => file.path === path || file.path.startsWith(path))) {
            // Check if the path is a directory (ends with '/')
            return FR_OK;
        }
        return FR_NO_PATH;
    }
 
    realpath(path) {
        // In C, realpath resolves all symbolic links, relative paths, and returns the absolute path.
        // In JS, we just normalize the path (remove redundant slashes, resolve '.' and '..').
        // This is a simplified version and does not handle symlinks.
        const parts = [];
        for (const part of path.split("/")) {
            if (part === "" || part === ".") continue;
            Iif (part === "..") {
                if (parts.length > 0) parts.pop();
            } else {
                parts.push(part);
            }
        }
        path = "/" + parts.join("/");
 
        while (path.length > 0 && path.endsWith("/")) {
            path = path.slice(0, -1);
        }
        return path;
    }
 
    f_chdir(path) {
        // ensure newpath is an absolute path (relative paths appended to CWD,
        // absolute paths are used as is)
        const newpath = this.buildAbsolutePath(path, false);
        Iif (newpath.error) {
            return newpath.error; // Return error if path is invalid
        }
 
        // Resolve the newpath
        const fullpath = this.realpath(newpath.path);
        Eif (fullpath !== undefined) {
            // Path exists and is a directory
            Eif (this.dir_exists(fullpath) == FR_OK) {
                this.CWD = fullpath; // Update the base path
                return FR_OK; // Success
            }
        }
        return FR_NO_PATH;
    }
 
    f_unlink(path) {
        // ensure newpath is an absolute path (relative paths appended to CWD,
        // absolute paths are used as is)
        const newpath = this.buildAbsolutePath(path, true);
        Iif (newpath.error) {
            return newpath.error; // Return error if path is invalid
        }
 
        // remove all in a folder, but this doesn't seem to be
        // used for *DELETE as files are deleted one by one
        Iif (this.dir_exists(newpath.path) == FR_OK) {
            // delete all the files within the folder
            const dirPrefix = newpath.path.endsWith("/") ? newpath.path : newpath.path + "/";
            this.allfiles
                .filter((file) => file.path.startsWith(dirPrefix))
                .forEach((file) => (file.path = "§" + file.path));
            this.cardChanged();
            return FR_OK;
        }
 
        Eif (this.file_exists(newpath.path) == FR_OK) {
            // remove the file from the list
            this.allfiles.filter((file) => file.path == newpath.path).forEach((file) => (file.path = "§" + file.path));
            this.cardChanged();
 
            return FR_OK;
        }
 
        return FR_NO_PATH;
    }
 
    trimToFilename(globaldata) {
        let path = String.fromCharCode(...globaldata.slice(0, -1)).split("\0")[0];
        // when deleting folders, the pathname is echoed
        // back by the ATOM which means they have <...> around the
        // name
        Iif (path.startsWith("<") && path.endsWith(">")) path = path.slice(1, -1);
        return path;
    }
 
    WFN_SetCWDirectory() {
        const dirname = this.trimToFilename(this.globalData);
        let ret = this.f_chdir(dirname);
        this.mmc.WriteDataPort(STATUS_COMPLETE | ret);
    }
 
    WFN_FileSeek() {
        const handle = this.handleOrAnswerInvalid();
        if (!handle) return;
        const [b0, b1, b2, b3] = this.globalData;
        handle.pos = Math.min((b0 | (b1 << 8) | (b2 << 16) | (b3 << 24)) >>> 0, WFN.sizeLimit(handle));
        this.mmc.WriteDataPort(STATUS_COMPLETE);
    }
 
    WFN_FileRead() {
        const handle = this.handleOrAnswerInvalid();
        if (!handle) return;
        Iif (this.globalAmount === 0) {
            this.globalAmount = 256;
        }
        const data = handle.file.data.slice(handle.pos, handle.pos + this.globalAmount);
        this.globalData = data;
        handle.pos += data.length;
        if (this.filenum > 0 && this.globalAmount !== data.length) {
            this.mmc.WriteDataPort(STATUS_EOF);
        } else {
            this.mmc.WriteDataPort(STATUS_COMPLETE);
        }
    }
 
    WFN_FileWrite() {
        const handle = this.handleOrAnswerInvalid();
        if (!handle) return;
        Iif (this.globalAmount === 0) {
            this.globalAmount = 256;
        }
        const end = Math.min(handle.pos + this.globalAmount, WFN.sizeLimit(handle));
        const oldData = handle.file.data;
        const newData = new Uint8Array(Math.max(oldData.length, end));
        newData.set(oldData, 0);
        newData.set(this.globalData.slice(0, end - handle.pos), handle.pos);
        handle.file.data = newData;
        handle.pos = end;
        this.cardChanged();
        this.mmc.WriteDataPort(STATUS_COMPLETE);
    }
 
    WFN_ExecuteArbitrary() {}
 
    WFN_FileOpenRAF() {}
    WFN_FileDelete() {
        const pathname = this.trimToFilename(this.globalData);
        const ret = this.f_unlink(pathname);
        this.mmc.WriteDataPort(STATUS_COMPLETE | ret);
    }
    WFN_FileGetInfo() {
        this.mmc.WriteDataPort(STATUS_EOF);
    }
 
    WFN_DirectoryCreate() {
        // Not implemented — return EOF to signal failure to the Atom
        this.mmc.WriteDataPort(STATUS_EOF);
    }
    WFN_DirectoryDelete() {
        this.mmc.WriteDataPort(STATUS_EOF);
    }
    WFN_Rename() {
        this.mmc.WriteDataPort(STATUS_EOF);
    }
 
    reset() {
        this.CWD = "";
    }
 
    clearData() {
        this.globalData = new Uint8Array(256);
        this.globalIndex = 0;
    }
 
    addData(data) {
        this.globalData[this.globalIndex] = data;
        ++this.globalIndex;
    }
 
    getData(restart = false) {
        if (restart) this.globalIndex = 0;
        let val = 0;
        if (this.globalIndex < this.globalData.length) val = this.globalData[this.globalIndex] | 0;
        this.globalIndex++;
        return val;
    }
 
    setTransferLength(length) {
        this.globalAmount = length;
    }
 
    // An open handle saves which file it has by the file's place on the card.
    snapshotState() {
        this.cardSnapshot ??= this.snapshotCard();
        return {
            card: this.cardSnapshot,
            globalData: this.globalData.slice(),
            globalIndex: this.globalIndex,
            fildata: this.fildata.map(
                (handle) => handle && { file: this.allfiles.indexOf(handle.file), pos: handle.pos },
            ),
            openeddir: this.openeddir,
            foldersSeen: [...this.foldersSeen],
            dfn: this.dfn,
            CWD: this.CWD,
            wildcard: this.wildcard,
        };
    }
 
    restoreState(state) {
        Eif (state.card) this.restoreCard(state.card);
        this.globalData = state.globalData.slice();
        this.globalIndex = state.globalIndex;
        this.fildata = state.fildata.map((handle) => {
            const file = handle && this.allfiles[handle.file];
            return file ? { file, pos: handle.pos } : null;
        });
        this.openeddir = state.openeddir;
        this.foldersSeen = [...state.foldersSeen];
        this.dfn = state.dfn;
        this.CWD = state.CWD;
        this.wildcard = state.wildcard;
    }
 
    fileOpen(mode) {
        Iif (!this.allfiles) return 4; // no file
        let ret;
        let fname = this.trimToFilename(this.globalData);
 
        if (this.filenum === 0) {
            // The scratch file is fixed, so we are backwards compatible with 2.9 firmware
            let fopen = this.f_open(fname, mode);
            this.fildata[0] = fopen.error == FR_OK ? { file: this.allfiles[fopen.fp], pos: 0 } : null;
            ret = fopen.error;
        } else {
            this.filenum = 0;
            if (this.fildata[1] == null) {
                this.filenum = 1;
            } else if (this.fildata[2] == null) {
                this.filenum = 2;
            } else if (this.fildata[3] == null) {
                this.filenum = 3;
            }
            if (this.filenum > 0) {
                let fopen = this.f_open(fname, mode);
                if (fopen.error == FR_OK) {
                    this.fildata[this.filenum] = { file: this.allfiles[fopen.fp], pos: 0 };
                    // No error, so update the return value to indicate the file num
                    ret = FILENUM_OFFSET | this.filenum;
                } else {
                    ret = fopen.error;
                }
            } else {
                // All files are open, return too many open files
                ret = ERROR_TOO_MANY_OPEN;
            }
        }
        return STATUS_COMPLETE | ret;
    }
 
    // Convert a path to an absolute, normalized path and optionally validate 8.3 filename
    buildAbsolutePath(xpath, validateName = true) {
        // Normalize path separators
        let path = String(xpath).replace(/\\/g, "/");
 
        // Optionally validate 8.3 filename rules
        if (validateName) {
            // Find the last element of the path
            let nameIdx = path.lastIndexOf("/");
            let name = nameIdx === -1 ? path : path.slice(nameIdx + 1);
 
            // Find the suffix
            let suffixIdx = name.indexOf(".");
            let namePart = suffixIdx !== -1 ? name.slice(0, suffixIdx) : name;
            let suffixPart = suffixIdx !== -1 ? name.slice(suffixIdx + 1) : "";
 
            // Validate the name part
            Iif (namePart.length < 1 || namePart.length > 8) {
                // Name not between 1 and 8 characters
                return { error: FR_INVALID_NAME };
            }
 
            // Validate the optional suffix part
            Iif (suffixIdx !== -1) {
                // Reject multiple suffixes
                if (suffixPart.includes(".")) {
                    return { error: FR_INVALID_NAME };
                }
                if (suffixPart.length === 0) {
                    // Remove a dangling suffix
                    path = path.slice(0, path.length - 1);
                } else if (suffixPart.length > 3) {
                    // Suffix too long
                    return { error: FR_INVALID_NAME };
                }
            }
        }
 
        // Make the path absolute
        let absPath;
        if (path.startsWith("/")) {
            // absolute: append the path to the root directory path
            absPath = path;
        } else {
            // relative: append the path to current directory path
            absPath = this.CWD + "/" + path; // CWD should be MMCPath
        }
        return { path: absPath };
    }
 
    // Check if a file exists in allfiles by name (returns FR_OK if exists, FR_NO_PATH if not)
    file_exists(name) {
        // if (!this.allfiles || !Array.isArray(this.allfiles)) return FR_NO_PATH;
        // Normalize name to absolute path
        const absResult = this.buildAbsolutePath(name, false);
        Iif (absResult.error) return FR_NO_PATH;
        const absName = absResult.path;
        // Search for a WFNFile with matching path (not a directory)
        const file = this.allfiles.find((f) => f.path === absName && !f.path.startsWith("§"));
        return file ? FR_OK : FR_NO_PATH;
    }
 
    open(path, mode) {
        let fileIndex = -1;
        Eif (this.allfiles) {
            fileIndex = this.allfiles.findIndex((f) => f.path === path);
 
            if (fileIndex === -1 && mode & O_CREAT) {
                // Create new file
                this.allfiles.push(new WFNFile(path, new Uint8Array()));
                this.cardChanged();
                fileIndex = this.allfiles.length - 1;
            } else Eif (fileIndex !== -1) {
                //cannot find file and not creating it.
            }
        }
 
        return fileIndex;
    }
 
    // Simulate f_open in JavaScript
    // Returns FR_OK (0) on success, or error code
    // fp: file object (JS object), path: string, mode: integer flags
    f_open(path, mode) {
        // Build absolute path and check validity
        const absResult = this.buildAbsolutePath(path, true);
        Iif (absResult.error) {
            return { error: FR_INVALID_NAME };
        }
        const open_path = absResult.path;
 
        // Check if file exists
        let exists = this.file_exists(open_path);
 
        // Mask mode flags
        mode &= FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW;
 
        let open_mode = 0;
        if (exists === FR_OK) {
            Iif (mode & FA_CREATE_NEW) return { error: FR_EXIST };
            Iif (mode & FA_CREATE_ALWAYS) open_mode = O_CREAT;
            Eif (mode & (FA_READ | FA_WRITE)) {
                Iif (mode & FA_WRITE) open_mode |= O_RDWR;
                else open_mode |= O_RDONLY;
            }
        } else {
            if (mode & (FA_OPEN_ALWAYS | FA_CREATE_NEW | FA_CREATE_ALWAYS)) open_mode = O_CREAT | O_RDWR;
            else return { error: FR_NO_FILE };
        }
 
        // Simulate file open/create
        let fileIndex = this.open(open_path, open_mode | O_BINARY);
 
        if (fileIndex >= 0) {
            return { fp: fileIndex, error: FR_OK };
        } else E{
            return { error: FR_INVALID_NAME };
        }
    }
}
 
/**
 * AtomMMC2 emulates the AtoMMC2 device for the Acorn Atom.
 * Handles SD/MMC file operations and communication with the Atom.
 */
export class AtomMMC2 {
    /**
     * Attach a gamepad object for joystick support.
     * @param {Object} gamepad
     */
    attachGamepad(gamepad) {
        this.gamepad = gamepad;
    }
 
    /**
     * Reset the MMC state.
     * @param {boolean} hard - If true, perform a hard reset.
     */
    reset(hard) {
        if (hard) {
            this.configByte = 0xff;
            this.WFN.fildata.fill(null);
        }
        this.WFN.reset();
    }
 
    /**
     * Set the MMC data (unzipped files).
     * @param {Object} data
     */
    SetMMCData(data) {
        this.WFN.load(data);
    }
 
    /**
     * Get the MMC data.
     * @returns {Object}
     */
    GetMMCData() {
        return this.WFN.allfiles;
    }
 
    /**
     * @param {Object} cpu - The CPU instance.
     */
    constructor(cpu) {
        this.cpu = cpu;
        this.gamepad = null;
        this.MMCtoAtom = STATUS_BUSY;
        this.heartbeat = 0x55;
        this.MCUStatus = MMC_MCU_BUSY;
        this.configByte = 0;
        this.lastaddr = CMD_REG; // address latch for reads
        this.byteValueLatch = 0;
        this.TRISB = 0;
        this.LATB = 0;
 
        this.WFN = new WFN(this, cpu);
        this.reset(true);
    }
 
    snapshotState() {
        return {
            MMCtoAtom: this.MMCtoAtom,
            heartbeat: this.heartbeat,
            MCUStatus: this.MCUStatus,
            configByte: this.configByte,
            lastaddr: this.lastaddr,
            byteValueLatch: this.byteValueLatch,
            TRISB: this.TRISB,
            files: this.WFN.snapshotState(),
        };
    }
 
    restoreState(state) {
        this.MMCtoAtom = state.MMCtoAtom;
        this.heartbeat = state.heartbeat;
        this.MCUStatus = state.MCUStatus;
        this.configByte = state.configByte;
        this.lastaddr = state.lastaddr;
        this.byteValueLatch = state.byteValueLatch;
        this.TRISB = state.TRISB;
        this.WFN.restoreState(state.files);
    }
 
    // MMCtoAtom and MCUStatus are used to transfer data
    // from the MMC to the Atom and vice versa.
 
    // Set the WROTE bit and write data to the Atom
    WriteDataPort(b) {
        this.MMCtoAtom = b;
        this.MCUStatus &= ~MMC_MCU_BUSY;
        this.MCUStatus |= MMC_MCU_WROTE;
    }
 
    // CPU is writing to 0xb400-0xb40c
    write(addr, val) {
        this.lastaddr = addr;
        this.at_process(addr, val, true);
    }
 
    // CPU is reading from 0xb400-0xb40c
    read(addr) {
        const Current = this.MMCtoAtom;
        const val = Current & 0xff;
        const reg = addr & 0x0f;
        const stat = this.MCUStatus;
        this.MCUStatus &= ~MMC_MCU_READ;
        addr = this.lastaddr;
        if (reg === STATUS_REG) {
            return stat;
        }
        this.at_process(addr, val, false);
        return Current;
    }
    /**
     * Process Atom MMC register access.
     * @param {number} addr
     * @param {number} val
     * @param {boolean} write
     */
    at_process(addr, val, write) {
        const LatchedAddress = addr & 0x0f;
        const ADDRESS_MASK = 0x07;
        let worker = null;
        this.MCUStatus |= MMC_MCU_READ;
        if (write === false) {
            this.MCUStatus &= ~MMC_MCU_READ;
            switch (LatchedAddress) {
                case READ_DATA_REG: {
                    let data = this.WFN.getData();
                    this.WriteDataPort(data);
                    break;
                }
            }
        } else {
            switch (LatchedAddress & ADDRESS_MASK) {
                case CMD_REG: {
                    let received = val & 0xff;
                    if ((received & 0x98) === 0x10) {
                        this.WFN.filenum = (received >> 5) & 3;
                        received &= 0x9f;
                    }
                    if ((received & 0xf0) === 0x20) {
                        this.WFN.filenum = (received >> 2) & 3;
                        received &= 0xf3;
                    }
                    this.WriteDataPort(STATUS_BUSY);
                    this.MCUStatus |= MMC_MCU_BUSY;
                    if (received === CMD_DIR_OPEN) {
                        worker = () => this.WFN.WFN_DirectoryOpen();
                    } else if (received === CMD_DIR_READ) {
                        worker = () => this.WFN.WFN_DirectoryRead();
                    } else if (received === CMD_DIR_CWD) {
                        worker = () => this.WFN.WFN_SetCWDirectory();
                    } else Iif (received == CMD_DIR_MKDIR) {
                        // create directory
                        worker = () => this.WFN.WFN_DirectoryCreate();
                    } else Iif (received == CMD_DIR_RMDIR) {
                        // delete directory
                        worker = () => this.WFN.WFN_DirectoryDelete();
                    } else Iif (received == CMD_RENAME) {
                        // rename
                        worker = () => this.WFN.WFN_Rename();
                    } else if (received === CMD_FILE_CLOSE) {
                        worker = () => this.WFN.WFN_FileClose();
                    } else if (received === CMD_FILE_OPEN_READ) {
                        worker = () => this.WFN.WFN_FileOpenRead();
                    } else if (received === CMD_FILE_OPEN_WRITE) {
                        worker = () => this.WFN.WFN_FileOpenWrite();
                    } else Iif (received === CMD_FILE_OPEN_RAF) {
                        worker = () => this.WFN.WFN_FileOpenRAF();
                    } else if (received === CMD_FILE_DELETE) {
                        worker = () => this.WFN.WFN_FileDelete();
                    } else Iif (received === CMD_FILE_GETINFO) {
                        worker = () => this.WFN.WFN_FileGetInfo();
                    } else if (received === CMD_FILE_SEEK) {
                        worker = () => this.WFN.WFN_FileSeek();
                    } else if (received === CMD_INIT_READ) {
                        let data = this.WFN.getData(true);
                        this.WriteDataPort(data);
                        this.lastaddr = READ_DATA_REG;
                    } else if (received === CMD_INIT_WRITE) {
                        this.WFN.clearData();
                    } else if (received === CMD_READ_BYTES) {
                        this.WFN.setTransferLength(this.byteValueLatch);
                        worker = () => this.WFN.WFN_FileRead();
                    } else if (received === CMD_WRITE_BYTES) {
                        this.WFN.setTransferLength(this.byteValueLatch);
                        worker = () => this.WFN.WFN_FileWrite();
                    } else Iif (received === CMD_EXEC_PACKET) {
                        worker = () => this.WFN.WFN_ExecuteArbitrary();
                    } else Iif (received === CMD_GET_FW_VER) {
                        this.WriteDataPort((VSN_MAJ << 4) | VSN_MIN);
                    } else Iif (received === CMD_GET_BL_VER) {
                        this.WriteDataPort(1);
                    } else if (received === CMD_GET_CFG_BYTE) {
                        this.WriteDataPort(this.configByte);
                    } else if (received === CMD_SET_CFG_BYTE) {
                        this.configByte = this.byteValueLatch;
                        this.WriteDataPort(STATUS_OK);
                    } else Iif (received === CMD_READ_AUX) {
                        this.WriteDataPort(LatchedAddress);
                    } else if (received === CMD_GET_HEARTBEAT) {
                        this.WriteDataPort(this.heartbeat);
                        this.heartbeat ^= 0xff;
                    } else if (received === CMD_GET_CARD_TYPE) {
                        this.WriteDataPort(0x01);
                    } else if (received === CMD_GET_PORT_DDR) {
                        this.WriteDataPort(this.TRISB);
                    } else if (received === CMD_SET_PORT_DDR) {
                        this.TRISB = this.byteValueLatch;
                        this.WriteDataPort(STATUS_OK);
                    } else if (received === CMD_READ_PORT) {
                        const buttons = this.gamepad?.gamepadButtons ?? [];
                        let joystick = JOYSTICK_IDLE;
                        if (buttons[15]) joystick ^= 1;
                        if (buttons[14]) joystick ^= 2;
                        if (buttons[13]) joystick ^= 4;
                        if (buttons[12]) joystick ^= 8;
                        if (buttons[0]) joystick ^= 0x10;
                        this.WriteDataPort(
                            this.cpu.inputLog ? this.cpu.inputLog.sample("mmcJoystick", joystick) : joystick,
                        );
                    } else Eif (received === CMD_WRITE_PORT) {
                        this.LATB = this.byteValueLatch;
                        this.WriteDataPort(STATUS_OK);
                    } else {
                        console.warn(`MMC: unrecognised CMD: 0x${received.toString(16)}`);
                    }
                    break;
                }
                case WRITE_DATA_REG: {
                    const received = val & 0xff;
                    this.WFN.addData(received);
                    break;
                }
                case LATCH_REG: {
                    const received = val & 0xff;
                    this.byteValueLatch = received;
                    this.WriteDataPort(this.byteValueLatch);
                    break;
                }
                case STATUS_REG: {
                    // does nothing
                    break;
                }
            }
            if (worker) worker();
        }
    }
}