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 | 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 14x 14x 4x 6x 4x 3x 3x 5x 4x 4x 4x 3x 3x 3x 3x 4x 4x 6x 4x 3x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 11x 11x 11x 11x 11x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 1x 1x 1x 1x 1x 1x 1x 60x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 5x 5x 21x 21x 21x 21x 21x 21x 21x 16x 5x 5x 10x 10x 10x 10x 10x 10x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 4x 4x 4x 3x 3x 1x 1x 5x 5x | import { createZipBlob, 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;
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;
const FA_CREATE_ALWAYS = 8,
FA_OPEN_ALWAYS = 16,
ERROR_TOO_MANY_OPEN = 0x12,
FILENUM_OFFSET = 0x20;
// 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();
}
}
// Sanitize a WFNFile path for use as a ZIP entry name.
function sanitizeZipEntryName(path) {
const name = path.startsWith("/") ? path.slice(1) : path;
Iif (!name || name.includes("\\") || name.split("/").some((seg) => seg === "..")) return null;
return name;
}
// Create a ZIP blob from an array of WFNFile entries (stored, no compression).
export async function toMMCZipAsync(data) {
const files = [];
for (const entry of data) {
if (entry.path.startsWith("§")) continue; // skip unlinked files
const name = sanitizeZipEntryName(entry.path);
Iif (!name) continue;
files.push({ name, data: entry.data });
}
return createZipBlob(files);
}
// 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.globalDataPresent = 0;
this.globalAmount = 0;
this.fildata = new Array(4).fill(null);
this.fildataIndex = 0;
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.seekpos = 0;
this.WildPattern = ".*"; // Default wildcard pattern (for regex not ATOM)
/**
* @type {WFNFile[]}
*/
this.allfiles = [];
}
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);
}
WFN_FileClose() {
this.seekpos = 0;
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("/");
if (lastSlashIndex !== -1) {
this.globalData = new TextEncoder().encode(path.slice(0, lastSlashIndex + 1) + "\0");
this.WildPattern = WFN.wildcardToRegex(path.slice(lastSlashIndex + 1));
} else {
this.WildPattern = WFN.wildcardToRegex(path);
this.globalData = new TextEncoder().encode("\0");
}
} else {
this.WildPattern = ".*";
}
}
// Strip trailing slash from a path string
stripTrailingSlash(path) {
if (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
if (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;
//
if (!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
if (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);
if (absResult.error) {
return absResult.error;
}
const newpath = absResult.path;
if (this.findfirst(newpath)) {
return FR_OK;
} else {
return FR_NO_PATH;
}
}
WFN_DirectoryOpen() {
// Separate wildcard and path
this.GetWildcard();
let res = this.f_opendir(this.globalData);
this.dfn = 0;
if (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 = wildcmp(WildPattern, longname);
const Match = fname.match(new RegExp(this.WildPattern));
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
if (!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;
if (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);
if (newpath.error) {
return newpath.error; // Return error if path is invalid
}
// Resolve the newpath
const fullpath = this.realpath(newpath.path);
if (fullpath !== undefined) {
// Path exists and is a directory
if (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);
if (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
if (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));
return FR_OK;
}
if (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));
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
if (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() {
this.seekpos =
this.globalData[0] | (this.globalData[1] << 8) | (this.globalData[2] << 16) | (this.globalData[3] << 24);
}
WFN_FileRead() {
if (this.globalAmount === 0) {
this.globalAmount = 256;
}
const read = Math.min(this.fildata[0].data.length, this.globalAmount);
const fildataEnd = this.fildataIndex + read;
const data = this.fildata[0].data.slice(this.fildataIndex, fildataEnd);
let ret = 0;
this.globalData = data;
this.fildataIndex = fildataEnd;
if (this.filenum > 0 && ret === 0 && this.globalAmount !== read) {
this.mmc.WriteDataPort(STATUS_EOF);
} else {
this.mmc.WriteDataPort(STATUS_COMPLETE | ret);
}
}
WFN_FileWrite() {
if (this.globalAmount === 0) {
this.globalAmount = 256;
}
const wrote = this.globalAmount;
const fildataEnd = this.fildataIndex + wrote;
// append this.globalData to this.fildata[0] at this.fildataIndex
let oldData = this.fildata[0].data;
let newLength = Math.max(oldData.length, fildataEnd);
let newData = new Uint8Array(newLength);
newData.set(oldData, 0);
newData.set(this.globalData.slice(0, wrote), this.fildataIndex);
this.fildata[0].data = newData;
this.fildataIndex = fildataEnd;
// const res = this.f_write(fil, (void*)globalData, globalAmount, &written);
let res = 0; // always works !
this.mmc.WriteDataPort(STATUS_COMPLETE | res);
}
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;
this.globalDataPresent = 0;
}
addData(data) {
this.globalData[this.globalIndex] = data;
++this.globalIndex;
this.globalDataPresent = 1;
}
getData(restart = false) {
if (restart) {
this.globalIndex = 0;
this.globalDataPresent = 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;
}
fileOpen(mode) {
if (!this.allfiles) return 4; // no file
let ret = 0;
let fname = this.trimToFilename(this.globalData);
if (this.filenum === 0) {
this.fildataIndex = 0; // FIXME(#1068) should be one for each fildata if going down this line!
// The scratch file is fixed, so we are backwards compatible with 2.9 firmware
let fopen = this.f_open(fname, mode);
if (fopen.error == FR_OK) this.fildata[0] = this.allfiles[fopen.fp];
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] = this.allfiles[fopen.fp];
// No error, so update the return value to indicate the file num
ret = FILENUM_OFFSET | this.filenum;
}
} 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
if (namePart.length < 1 || namePart.length > 8) {
// Name not between 1 and 8 characters
return { error: FR_INVALID_NAME };
}
// Validate the optional suffix part
if (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);
if (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;
if (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()));
fileIndex = this.allfiles.length - 1;
} else if (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);
if (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) {
if (mode & FA_CREATE_NEW) return { error: FR_EXIST };
if (mode & FA_CREATE_ALWAYS) open_mode = O_CREAT;
if (mode & (FA_READ | FA_WRITE)) {
if (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 {
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) {
Eif (hard) {
this.configByte = 0xff;
}
this.WFN.reset();
this.seekpos = 0;
}
/**
* Set the MMC data (unzipped files).
* @param {Object} data
*/
SetMMCData(data) {
this.WFN.allfiles = data;
}
/**
* Get the MMC data.
* @returns {Object}
*/
GetMMCData() {
return this.WFN.allfiles;
}
/**
* clear
* @returns
*/
ClearMMCData() {
const fname = "README".padEnd(16, "\0");
const loadaddr = 0x2900;
const basicstart = 0xb2c2;
const flen = 0x003e;
const basicfile = "\r\0\n REM created by jsatom\r\0\x14 REM \x19commandercoder.com\r\0\x1E END\r";
const fend = 0xc3;
// Build the byte array for the README file
// Format: [fname (16 bytes), loadaddr (2 bytes LE), basicstart (2 bytes LE), flen (2 bytes LE), basicfile (flen bytes), fend (1 byte)]
const readmeBytes = new Uint8Array(16 + 2 + 2 + 2 + basicfile.length + 1);
let offset = 0;
// fname (16 bytes)
for (let i = 0; i < 16; i++) {
readmeBytes[offset++] = fname.charCodeAt(i);
}
// loadaddr (2 bytes, little endian)
readmeBytes[offset++] = loadaddr & 0xff;
readmeBytes[offset++] = (loadaddr >> 8) & 0xff;
// basicstart (2 bytes, little endian)
readmeBytes[offset++] = basicstart & 0xff;
readmeBytes[offset++] = (basicstart >> 8) & 0xff;
// flen (2 bytes, little endian)
readmeBytes[offset++] = flen & 0xff;
readmeBytes[offset++] = (flen >> 8) & 0xff;
// basicfile (flen bytes)
for (let i = 0; i < basicfile.length; i++) {
readmeBytes[offset++] = basicfile.charCodeAt(i);
}
// fend (1 byte)
readmeBytes[offset] = fend;
this.WFN.allfiles = [new WFNFile("/README", readmeBytes)];
}
/**
* @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.worker = null;
this.seekpos = 0;
this.WildPattern = ".*";
this.foldersSeen = [];
this.dfn = 0;
this.TRISB = 0;
this.PORTB = 0;
this.LATB = 0;
this.WFN = new WFN(this, cpu);
this.reset(true);
}
// 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;
}
// Set the WROTE bit and return the data from the Atom
ReadDataPort() {
this.MCUStatus &= ~MMC_MCU_READ;
this.MCUStatus |= MMC_MCU_WROTE;
return this.MMCtoAtom;
}
// 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;
this.latchedAddress = LatchedAddress;
const ADDRESS_MASK = 0x07;
this.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;
Iif ((received & 0x98) === 0x10) {
this.WFN.filenum = (received >> 5) & 3;
received &= 0x9f;
}
Iif ((received & 0xf0) === 0x20) {
this.WFN.filenum = (received >> 2) & 3;
received &= 0xf3;
}
this.WriteDataPort(STATUS_BUSY);
this.MCUStatus |= MMC_MCU_BUSY;
Iif (received === CMD_DIR_OPEN) {
this.worker = () => this.WFN.WFN_DirectoryOpen();
} else Iif (received === CMD_DIR_READ) {
this.worker = () => this.WFN.WFN_DirectoryRead();
} else Iif (received === CMD_DIR_CWD) {
this.worker = () => this.WFN.WFN_SetCWDirectory();
} else Iif (received == CMD_DIR_MKDIR) {
// create directory
this.worker = () => this.WFN.WFN_DirectoryCreate();
} else Iif (received == CMD_DIR_RMDIR) {
// delete directory
this.worker = () => this.WFN.WFN_DirectoryDelete();
} else Iif (received == CMD_RENAME) {
// rename
this.worker = () => this.WFN.WFN_Rename();
} else Iif (received === CMD_FILE_CLOSE) {
this.worker = () => this.WFN.WFN_FileClose();
} else Iif (received === CMD_FILE_OPEN_READ) {
this.worker = () => this.WFN.WFN_FileOpenRead();
} else Iif (received === CMD_FILE_OPEN_WRITE) {
this.worker = () => this.WFN.WFN_FileOpenWrite();
} else Iif (received === CMD_FILE_OPEN_RAF) {
this.worker = () => this.WFN.WFN_FileOpenRAF();
} else Iif (received === CMD_FILE_DELETE) {
this.worker = () => this.WFN.WFN_FileDelete();
} else Iif (received === CMD_FILE_GETINFO) {
this.worker = () => this.WFN.WFN_FileGetInfo();
} else Iif (received === CMD_FILE_SEEK) {
this.worker = () => this.WFN.WFN_FileSeek();
} else Iif (received === CMD_INIT_READ) {
let data = this.WFN.getData(true);
this.WriteDataPort(data);
this.lastaddr = READ_DATA_REG;
} else Iif (received === CMD_INIT_WRITE) {
this.WFN.clearData();
} else Iif (received === CMD_READ_BYTES) {
this.WFN.setTransferLength(this.byteValueLatch);
this.worker = () => this.WFN.WFN_FileRead();
} else Iif (received === CMD_WRITE_BYTES) {
this.WFN.setTransferLength(this.byteValueLatch);
this.worker = () => this.WFN.WFN_FileWrite();
} else Iif (received === CMD_EXEC_PACKET) {
this.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 Iif (received === CMD_SET_CFG_BYTE) {
this.configByte = this.byteValueLatch;
this.WriteDataPort(STATUS_OK);
} else Iif (received === CMD_READ_AUX) {
this.WriteDataPort(this.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 Eif (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) {
let JOYSTICK = 0xff;
const joyst = true;
if (joyst && this.gamepad && this.gamepad.gamepadButtons !== undefined) {
if (this.gamepad.gamepadButtons[15]) JOYSTICK ^= 1;
if (this.gamepad.gamepadButtons[14]) JOYSTICK ^= 2;
if (this.gamepad.gamepadButtons[13]) JOYSTICK ^= 4;
if (this.gamepad.gamepadButtons[12]) JOYSTICK ^= 8;
if (this.gamepad.gamepadButtons[0]) JOYSTICK ^= 0x10;
this.WriteDataPort(JOYSTICK);
} else {
this.WriteDataPort(this.PORTB);
}
} else if (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;
}
}
Iif (this.worker) {
this.worker();
}
}
}
}
|