pico_export

Functions for reading/writing pico8 exports (javascript, native, etc)

   1"""Functions for reading/writing pico8 exports (javascript, native, etc)"""
   2
   3from utils import *
   4from media_utils import Image, Color, Palette, PixelFormat
   5from pico_defs import *
   6from pico_compress import get_lz77, Lz77Entry
   7from zipfile import ZipFile, ZipInfo, ZIP_STORED, ZIP_DEFLATED
   8import base64
   9
  10class ListOp(Enum):
  11    insert = replace = delete = rename = ...
  12
  13class CartExport:
  14    """A container of multiple carts"""
  15
  16    # get_carts_impl: () -> {name: <ref>} in cart order
  17    # read_impl: (<ref>, **opts) -> cart
  18    # insert_impl: (<ref> or None, name, cart, **opts) -> void
  19    # replace_impl: (<ref>, cart, **opts) -> void
  20    # delete_impl: (<ref>, **opts) -> void
  21    # rename_impl: (<ref>, new_name, **opts) -> void
  22    # NOTE: <ref>s are valid only until next modification or get_carts_impl call
  23
  24    def _default(m, carts, strict=True):
  25        name = dict_first_key(carts)
  26        if name is None and strict:
  27            throw(f"export is empty - contains no carts")
  28        return name
  29
  30    def _find(m, carts, cart_name, strict=True):
  31        ref = carts.get(cart_name)
  32        if ref is None and strict:
  33            throw(f"cart {cart_name} not found in export")
  34        return ref
  35
  36    def _contains(m, carts, cart_name):
  37        return e(m._find(carts, cart_name, strict=False))
  38    
  39    def list_carts(m):
  40        return m.get_carts_impl().keys()
  41
  42    def read_cart(m, cart_name=None, **opts):
  43        carts = m.get_carts_impl()
  44        if cart_name is None:
  45            cart_name = m._default(carts)
  46        ref = m._find(carts, cart_name)
  47
  48        return m.read_impl(ref, path=cart_name, **opts)
  49    
  50    def write_cart(m, cart, cart_name=None, cart_op=None, target_name=None, **opts):
  51        cart_op = default(cart_op, ListOp.insert)
  52        carts = m.get_carts_impl()
  53
  54        if cart_op == ListOp.insert:
  55            if cart_name is None:
  56                cart_name = cart.name
  57            if m._contains(carts, cart_name):
  58                throw(f"cart {cart_name} already found in export")
  59            
  60            target_ref = None
  61            if e(target_name):
  62                target_ref = m._find(carts, target_name)
  63            m.insert_impl(target_ref, cart_name, cart, **opts)
  64
  65        else:
  66            if cart_name is None:
  67                cart_name = m._default(carts)
  68            ref = m._find(carts, cart_name)
  69            
  70            if cart_op == ListOp.replace:
  71                m.replace_impl(ref, cart, **opts)
  72            elif cart_op == ListOp.delete:
  73                m.delete_impl(ref)
  74            elif cart_op == ListOp.rename:
  75                if m._contains(carts, target_name):
  76                    throw(f"cart {target_name} already found in export")
  77                
  78                m.rename_impl(ref, target_name)
  79            else:
  80                fail("invalid cart op")
  81        
  82        return m
  83
  84    def dump_cart(m, dest, fmt, name, raw_data):
  85        path = path_join(dest, filename_fixup(name))
  86
  87        if fmt == CartFormat.rom:
  88            file_write(path, raw_data)
  89        else:
  90            write_cart(path, read_cart_from_rom(raw_data), fmt)
  91
  92class JsExport(CartExport):
  93    """A javascript file containing one or more carts"""
  94
  95    def __init__(m, text):
  96        super().__init__()
  97        m.text = text
  98    
  99    def find_cartnames(m):
 100        match = re.search(r"var\s+_cartname\s*=\s*\[(.*?)\]", m.text, re.S)
 101        if not match:
 102            throw("can't find _cartname var in js")
 103        return match
 104    
 105    def find_cartdata(m):
 106        match = re.search(r"var\s+_cartdat\s*=\s*\[(.*?)\]", m.text, re.S)
 107        if not match:
 108            throw("can't find _cartdat var in js")
 109        return match
 110
 111    def get_carts_impl(m):
 112        m.cartnames = []
 113        cartnames_text = m.find_cartnames().group(1)
 114        if cartnames_text.strip():
 115            for i, cartname in enumerate(cartnames_text.split(",")):
 116                cartname = cartname.strip()[1:-1] # may fail if using special chars...
 117                m.cartnames.append(cartname)
 118
 119        m.cartdata = bytearray(k_cart_size * len(m.cartnames))
 120        cartdata_text = m.find_cartdata().group(1)
 121        if cartdata_text.strip():
 122            for i, b in enumerate(cartdata_text.split(",")):
 123                m.cartdata[i] = int(b.strip())
 124
 125        carts = {}
 126        for i, cartname in enumerate(m.cartnames):
 127            carts[cartname] = i
 128        return carts
 129
 130    def slice(m, i, end_i=None):
 131        return slice(k_cart_size * i, k_cart_size * default(end_i, i + 1))
 132
 133    def read_impl(m, i, **opts):
 134        return read_cart_from_rom(m.cartdata[m.slice(i)], **opts)
 135
 136    def insert_impl(m, i, name, cart, **opts):
 137        i = default(i, len(m.cartnames))
 138        m.cartdata[m.slice(i, i)] = write_cart_to_rom(cart, **opts)
 139        m.cartnames.insert(i, name)
 140        m.finish_write()
 141
 142    def replace_impl(m, i, cart, **opts):
 143        m.cartdata[m.slice(i)] = write_cart_to_rom(cart, **opts)
 144        m.finish_write()
 145    
 146    def delete_impl(m, i):
 147        del m.cartdata[m.slice(i)]
 148        del m.cartnames[i]
 149        m.finish_write()
 150    
 151    def rename_impl(m, i, name):
 152        m.cartnames[i] = name
 153        m.finish_write()
 154
 155    def finish_write(m):
 156        cartnames_text = ", ".join(f"`{name}`" for name in m.cartnames)
 157        m.text = str_replace_between(m.text, *m.find_cartnames().span(1), cartnames_text)
 158
 159        cartdata_chunks = ["\n"]
 160        for chunk in iter_chunk(m.cartdata, 0x100):
 161            if len(cartdata_chunks) > 1:
 162                cartdata_chunks.append(",\n")
 163            cartdata_chunks.append(",".join("%d" % b for b in chunk))
 164        m.text = str_replace_between(m.text, *m.find_cartdata().span(1), "".join(cartdata_chunks))
 165        m.cartnames = m.cartdata = None # need reparse
 166    
 167    def find_pod(m):
 168        matches = list(re.finditer(r"fileData0\.push\.apply\s*\(\s*fileData0\s*,\s*\[(.*?)\]\s*\)", m.text, re.S))
 169        if not matches:
 170            throw("can't find fileData0 pushes in js")
 171        return matches
 172    
 173    def read_pod(m): # this pod is the same for all carts, so it's not very interesting in retrospect
 174        pod_data = bytearray()
 175        for match in m.find_pod():
 176            match_text = match.group(1)
 177            if match_text.strip():
 178                for b in match_text.split(","):
 179                    pod_data.append(int(b.strip()))
 180        return PodFile(pod_data)
 181
 182    def dump_contents(m, dest, fmt, misc=False):
 183        carts = m.get_carts_impl()
 184        for name, i in carts.items():
 185            m.dump_cart(dest, fmt, name, m.cartdata[m.slice(i)])
 186        if misc:
 187            m.read_pod().dump_contents(dest, fmt, misc=True)
 188    
 189    @classmethod
 190    def create(cls, pico8_dat, html_pod=None, for_wasm=False, **_):
 191        if not html_pod:
 192            html_pod = PodFile(pico8_dat.find_named("pod/f_html5.pod"))
 193        js_file = "var _cartname=[];\n"
 194        js_file += "var _cdpos=0; var iii=0; var ciii=0;\n"
 195        js_file += "var _cartdat=[];\n\n"
 196        js_file += html_pod.find_named("src/pico8_wasm.js" if for_wasm else "src/pico8.js").decode()
 197        return JsExport(js_file)        
 198
 199class PodFile:
 200    """A pod file - used in pico8 inside exports/etc"""
 201
 202    k_header = "CPOD"
 203    k_file_header = "CFIL"
 204    k_cmpr_file_header = "cFIL"
 205    k_bmp_header = "CBMP"
 206    k_cmpr_bmp_header = "cBMP"
 207    k_pal_header = "CPAL"
 208    k_num_colors = 0x100
 209
 210    class Entry(Struct):
 211        header = pos = end_pos = name = content = ...
 212
 213    def __init__(m, data):
 214        m.data = data
 215        m.read_all()
 216
 217    def init_write(m):
 218        if not isinstance(m.data, bytearray):
 219            m.data = bytearray(m.data)
 220
 221    def read_all(m):
 222        with BinaryReader(BytesIO(m.data)) as r:
 223            check(r.str(4) == m.k_header, "invalid POD file")
 224            check(r.u32() == 0x44, "newer POD version?") # size of header?
 225            check(r.u32() == 1, "newer POD version?") # ???
 226            m.name = r.zstr(0x20) # ???
 227            count = r.u32()
 228            r.addpos(0x1c) # junk?
 229
 230            m.entries = []
 231            palette = None
 232            for i in range(count):
 233                pos = r.pos()
 234                header = r.str(4)
 235                name = None
 236
 237                if header in (m.k_file_header, m.k_cmpr_file_header):
 238                    check(r.u32() == 0, "unknown POD file header value")
 239                    size = r.u32()
 240                    name = r.zstr(0x40)
 241                    if header == m.k_cmpr_file_header:
 242                        content = lz4_uncompress(r.bytes(r.u32()))
 243                    else:
 244                        content = r.bytes(size)
 245                
 246                elif header in (m.k_bmp_header, m.k_cmpr_bmp_header):
 247                    size = r.u32()
 248                    w = r.u32()
 249                    h = r.u32()
 250                    bpp = r.u32()
 251                    check(r.u32() == 0, "unknown POD bmp header value")
 252                    check(r.u32() == 0, "unknown POD bmp header value")
 253                    if header == m.k_cmpr_bmp_header:
 254                        data = lz4_uncompress(r.bytes(r.u32()))
 255                    else:
 256                        data = r.bytes(size - 0x14)
 257                    
 258                    fmt = PixelFormat.i8 if bpp == 8 else PixelFormat.bgra8 if bpp == 32 else throw("unknown POD bmp bpp %d" % bpp)
 259                    content = Image.from_data(w, h, fmt, data)
 260                    if fmt == PixelFormat.i8:
 261                        content.palette = default(palette, m.default_palette)
 262
 263                elif header == m.k_pal_header:
 264                    size = r.u32()
 265                    num_colors = m.k_num_colors
 266                    check(size == 3 * num_colors, "wrong POD palette size?")
 267                    content = Palette.create(num_colors)
 268                    for i in range(num_colors):
 269                        content[i] = Color(r.u8(), r.u8(), r.u8())
 270
 271                else:
 272                    throw("unknown or unexpected POD content header %s" % header)
 273                
 274                end_pos = r.pos()
 275                m.entries.append(m.Entry(header, pos, end_pos, name, content))
 276    
 277    @lazy_classproperty
 278    def default_palette(cls): # used for fonts in pod - well, the 0 and 0xff colors are.
 279        palette = Palette.create(cls.k_num_colors)
 280        for i in range(0x100):
 281            palette[i] = Color(i, i, i)
 282        return palette
 283    
 284    def find_named(m, name, strict=True):
 285        for e in m.entries:
 286            if e.name == name:
 287                return e.content
 288        if strict:
 289            throw(f"expected to find {name} in pod")
 290
 291    def find_prefix(m, prefix, strict=True):
 292        found = False
 293        for e in m.entries:
 294            if e.name.startswith(prefix):
 295                yield e.name[len(prefix):], e.content
 296                found = True
 297        if strict and not found:
 298            throw(f"expected to find {prefix}* in pod")
 299
 300    def contains(m, name):
 301        return m.find_named(name, strict=False) != None
 302
 303    def shift_entry_positions(m, i, delta):
 304        for e in m.entries[i:]:
 305            e.pos += delta
 306            e.end_pos += delta
 307
 308    def update_count(m):
 309        buf = BinaryBuffer(m.data)
 310        buf.w_u32(0x2c, len(m.entries))
 311    
 312    @classmethod
 313    def create(cls, name=None):
 314        with BinaryWriter() as w:
 315            w.str(cls.k_header)
 316            w.u32(0x44) # size of header
 317            w.u32(1) # version?
 318            w.zstr(name or "", 0x20)
 319            w.u32(0)
 320            w.zstr("", 0x1c)
 321        
 322            return PodFile(w.f.getvalue())
 323
 324    def insert_content(m, i, name, content, compress=False):
 325        m.init_write()
 326        if i < len(m.entries):
 327            pos = m.entries[i].pos
 328        else:
 329            pos = len(m.data)
 330        
 331        def write_bytes(w, data):
 332            if compress:
 333                compressed = lz4_compress(data, fast=True)
 334                w.u32(len(compressed))
 335                w.bytes(compressed)
 336            else:
 337                w.bytes(data)
 338        
 339        with BinaryWriter() as w:
 340            if isinstance(content, bytes):
 341                header = m.k_cmpr_file_header if compress else m.k_file_header
 342
 343                w.str(header)
 344                w.u32(0)
 345                w.u32(len(content))
 346                w.zstr(name, 0x40)
 347                write_bytes(w, content)
 348            
 349            elif isinstance(content, Image):
 350                if content.format.bpp == 8:
 351                    format = PixelFormat.i8
 352                elif content.format.bpp == 32:
 353                    format = PixelFormat.bgra8
 354                else:
 355                    check("invalid surface format for pod")
 356                
 357                data = content.to_data(format)
 358                header = m.k_cmpr_bmp_header if compress else m.k_bmp_header
 359
 360                w.str(header)
 361                w.u32(len(data) + 0x14)
 362                w.u32(content.width)
 363                w.u32(content.height)
 364                w.u32(content.format.bpp)
 365                w.u32(0); w.u32(0)
 366                write_bytes(w, data)
 367
 368            elif isinstance(content, Palette):
 369                assert not compress
 370                header = m.k_pal_header
 371
 372                w.str(header)
 373                w.u32(3 * m.k_num_colors)
 374                for i in range(m.k_num_colors):
 375                    r, g, b, _ = content[i]
 376                    w.u8(r); w.u8(g); w.u8(b)
 377            
 378            else:
 379                fail("Unknown content type")
 380            
 381            size = w.pos()
 382            new_data = w.f.getvalue()
 383        
 384        m.data[pos:pos] = new_data
 385        m.entries.insert(i, m.Entry(header, pos, pos + size, name, content))
 386
 387        m.shift_entry_positions(i + 1, size)
 388        m.update_count()
 389        
 390    def append_content(m, name, content, compress=False):
 391        m.insert_content(len(m.entries), name, content, compress)
 392
 393    def delete_content(m, i):
 394        m.init_write()
 395        e = m.entries[i]
 396
 397        del m.data[e.pos:e.end_pos]
 398        del m.entries[i]
 399
 400        m.shift_entry_positions(i, -(e.end_pos - e.pos))
 401        m.update_count()
 402    
 403    def replace_content(m, i, content):
 404        e = m.entries[i]
 405        if e.header == m.k_file_header and isinstance(content, bytes) and len(content) == len(e.content):
 406            pos = e.pos + 0x4c
 407        else:
 408            m.delete_content(i)
 409            m.insert_content(i, e.name, content)
 410            return
 411
 412        m.init_write()
 413        m.data[pos:pos+len(content)] = content
 414        e.content = content
 415    
 416    def rename_content(m, i, name):
 417        m.init_write()
 418        e = m.entries[i]
 419        if isinstance(e.content, bytes):
 420            buf = BinaryBuffer(m.data)
 421            buf.w_zstr(e.pos + 0xc, name, 0x40)
 422            e.name = name
 423
 424    def dump_contents(m, dest, fmt, misc=False):
 425        for i, e in enumerate(m.entries):
 426            if isinstance(e.content, bytes):
 427                m.dump_file(dest, fmt, misc, i, e.name, e.content)
 428            elif isinstance(e.content, Image):
 429                with file_create(path_join(dest, f"{i}.png")) as f:
 430                    e.content.save(f)
 431            elif isinstance(e.content, Palette):
 432                with file_create(path_join(dest, f"{i}.pal.png")) as f:
 433                    e.content.to_surface().save(f)
 434            else:
 435                fail("wrong data in pod contents")
 436    
 437    def dump_file(m, dest, fmt, misc, i, name, content):
 438        if name.lower().endswith(".pod"):
 439            pod_dest = path_join(dest, filename_fixup(name[:-4]))
 440            dir_ensure_exists(pod_dest)
 441            PodFile(content).dump_contents(pod_dest, fmt, misc)
 442        else:
 443            file_write(path_join(dest, filename_fixup(name)), content)
 444
 445# (lz4 is used in both pico8 pods and in picotron)
 446
 447def lz4_uncompress(data, debug=None):
 448    def read_u8_sum(r):
 449        sum = 0
 450        while True:
 451            val = r.u8()
 452            sum += val
 453            if val != 0xff:
 454                return sum
 455
 456    uncdata = bytearray()
 457    with BinaryReader(BytesIO(data)) as r:
 458        if debug: debug.init(r, bytes)
 459
 460        while not r.eof():
 461            header = r.u8()
 462            size = header >> 4
 463            if size == 0xf:
 464                size += read_u8_sum(r)
 465            
 466            for i in range(size):
 467                uncdata.append(r.u8())
 468            if debug and size: debug.update(uncdata[-size:])
 469            
 470            if not r.eof():
 471                offset = r.u16()
 472                count = 4 + (header & 0xf)
 473                if count == 0x13:
 474                    count += read_u8_sum(r)
 475                
 476                for i in range(count):
 477                    uncdata.append(uncdata[-offset])
 478                if debug: debug.update(Lz77Entry(offset, count))
 479    
 480    if debug: debug.end()
 481    return bytes(uncdata)
 482
 483def lz4_compress(uncdata, fast=False, debug=None):
 484    literals = []
 485    min_c = 4
 486
 487    with BinaryWriter() as w:
 488        if debug: debug.init(w, bytes)
 489
 490        def write_u8_sum(val):
 491            while True:
 492                byte = min(val, 0xff)
 493                w.u8(byte)
 494                val -= byte
 495                if byte != 0xff:
 496                    break
 497
 498        def write_block(item):
 499            size = len(literals)
 500            count = (item.count - min_c) if item else 0
 501
 502            w.u8(min(count, 0xf) | (min(size, 0xf) << 4))
 503            if size >= 0xf:
 504                write_u8_sum(size - 0xf)
 505            
 506            for lit in literals:
 507                w.u8(lit)
 508            
 509            if debug and literals: debug.update(bytes(literals))
 510            literals.clear()
 511
 512            if item:
 513                w.u16(item.offset)
 514                if count >= 0xf:
 515                    write_u8_sum(count - 0xf)
 516                
 517                if debug: debug.update(item)
 518                    
 519        def measure(ctxt_litcount, item):
 520            ctxt_litcount = default(ctxt_litcount, len(literals))
 521
 522            if isinstance(item, Lz77Entry):
 523                count_bits = (item.count - min_c + 0xf0) // 0xff
 524                cost = 3 + count_bits # + 1 for the next header
 525                ctxt_litcount = 0
 526
 527            else:
 528                cost = 1
 529                ctxt_litcount += 1
 530                if (ctxt_litcount + 0xf0) % 0xff == 0:
 531                    cost += 1
 532
 533            return cost, ctxt_litcount
 534
 535        def get_cheaper_c(c):
 536            return round_down(c - min_c + 0xf0, 0xff) - 1 - 0xf0 + min_c
 537
 538        def min_cost(dist):
 539            # assume dist can be covered by an Lz77Entry without any overhead
 540            # plus subtract possible overhead *savings* of an Lz77Entry
 541            return max(((dist - min_c + 0xf0) // 0xff) - 1, 0)
 542
 543        # lz4 disallows lz77 entries near the end of the stream...
 544        end_of_lz77_reach = len(uncdata) - 5
 545        end_of_lz77s = len(uncdata) - 12
 546
 547        if fast:
 548            items = get_lz77(uncdata, min_c=min_c, max_c=None, max_o=0xffff)
 549        else:
 550            items = get_lz77(uncdata, min_c=min_c, max_c=None, max_o=0xffff,
 551                             get_cheaper_c=get_cheaper_c, measure=measure, min_cost=min_cost)
 552
 553        for i, item in items:
 554            if isinstance(item, Lz77Entry):
 555                if i < end_of_lz77s:
 556                    if i + item.count <= end_of_lz77_reach:
 557                        write_block(item)
 558                    else:
 559                        fixed_item = Lz77Entry(item.offset, end_of_lz77_reach - i)
 560                        assert fixed_item.count >= min_c
 561                        write_block(fixed_item)
 562                        literals.extend(uncdata[end_of_lz77_reach:i+item.count])
 563                else:
 564                    literals.extend(uncdata[i:i+item.count])
 565            else:
 566                literals.append(item)
 567        write_block(None)
 568
 569        if debug: debug.end()
 570        return w.f.getvalue()
 571
 572class PodExport(CartExport, PodFile):
 573    """A .pod file used in exports, containing one or more carts"""
 574
 575    k_pod_names = ["pod/pico8_boot.p8", "pod/gfx1.pod", "pod/f_pico8.pod"]
 576
 577    def __init__(m, data):
 578        CartExport.__init__(m)
 579        PodFile.__init__(m, data)
 580
 581    def get_carts_impl(m):
 582        carts = {}
 583        for i, e in enumerate(m.entries):
 584            if e.name and isinstance(e.content, bytes): # only carts are named in export pod files
 585                carts[e.name] = (i, e.content)
 586        return carts
 587
 588    def read_impl(m, tuple, **opts):
 589        _, bytes = tuple
 590        return read_cart_from_rom(bytes, **opts)
 591    
 592    def insert_impl(m, tuple, name, cart, **opts):
 593        if e(tuple):
 594            i, _ = tuple
 595        else:
 596            i = len(m.entries)
 597        
 598        new_bytes = write_cart_to_rom(cart, **opts)
 599        m.insert_content(i, name, new_bytes)
 600
 601    def replace_impl(m, tuple, cart, **opts):
 602        i, bytes = tuple
 603        new_bytes = write_cart_to_rom(cart, **opts)
 604
 605        if len(new_bytes) != len(bytes):
 606            throw(f"existing cart has size {len(bytes):#x} vs expected {len(new_bytes):#x}")
 607        m.replace_content(i, new_bytes)
 608
 609    def delete_impl(m, tuple):
 610        i, _ = tuple
 611        m.delete_content(i)
 612
 613    def rename_impl(m, tuple, name):
 614        i, _ = tuple
 615        m.rename_content(i, name)
 616        
 617    def dump_file(m, dest, fmt, misc, i, name, cdata):
 618        if name:
 619            m.dump_cart(dest, fmt, name, cdata)
 620        elif misc:
 621            name = m.k_pod_names[i] # names these files have in non-cart pods
 622            super().dump_file(dest, fmt, misc, i, name, cdata)
 623            
 624    @classmethod
 625    def create(cls, pico8_dat, cart=None, export_name="", **_):
 626        m = PodExport(PodFile.create().data)
 627
 628        boot_cart = read_cart_from_source(pico8_dat.find_named(m.k_pod_names[0]).decode())
 629        if cart:
 630            boot_cart.version_id = cart.version_id
 631        m.append_content("", write_cart_to_source(boot_cart).encode())
 632
 633        for pod_i, pod_name in enumerate(m.k_pod_names):
 634            if pod_i == 0: # handled above, not a pod
 635                continue
 636
 637            pod = PodFile(pico8_dat.find_named(pod_name))
 638            new_pod = PodFile.create(pod.name)
 639
 640            for i, e in enumerate(pod.entries):
 641                content = e.content
 642
 643                if pod_i == 1 and i == 4:
 644                    # this is the window title - it's reinterpreted to a bitmap
 645                    assert content.format.bpp == 8
 646                    x, y = 0, 0
 647                    pixels = content.pixels
 648                    for ch in export_name + "\0":
 649                        pixels[x, y] = ord(ch)
 650                        x += 1
 651                        if x == content.width:
 652                            x = 0
 653                            y += 1
 654
 655                elif pod_i == 1 and i == 6:
 656                    if cart and cart.label:
 657                        content = create_screenshot_surface(cart.label)
 658
 659                new_pod.append_content(e.name, content, compress=isinstance(content, Image))
 660
 661            m.append_content("", bytes(new_pod.data))
 662        return m
 663
 664class PicoDat(PodFile):
 665    def throw(m, *_, **__):
 666        throw("pico dat file can only be used with --dump")
 667
 668    list_carts = throw
 669    read_cart = throw
 670    write_cart = throw
 671
 672class FullExportBase:
 673    def __init__(m):
 674        m.curr_time = time.localtime(maybe_float(os.getenv("PICO8_EXPORT_REPRO_TIME", time.time())))[:6]
 675
 676    def find_icon_offset_in_exe(m, exe_data):
 677        r = BinaryReader(BytesIO(exe_data))
 678        assert r.str(2) == "MZ"
 679        r.setpos(0x3c)
 680        r.setpos(r.u32())
 681
 682        assert r.str(4) == "PE\0\0"
 683        _, num_sections, _, _, _, opt_header_size, _ = r.u16(), r.u16(), r.u32(), r.u32(), r.u32(), r.u16(), r.u16()
 684        header_end = r.pos() + opt_header_size
 685
 686        opt_header = r.u16()
 687        assert opt_header in (0x10b, 0x20b)
 688        is64 = (opt_header == 0x20b)
 689        r.addpos(126 if is64 else 110)
 690        rsrc_rva = r.u32()
 691
 692        r.setpos(header_end)
 693        sections = []
 694        for _ in range(num_sections):
 695            r.addpos(0x8)
 696            vsize, vaddr, _, offset = r.u32(), r.u32(), r.u32(), r.u32()
 697            r.addpos(0x10)
 698            sections.append((vaddr, vsize, offset))
 699        
 700        def rva_to_offset(rva):
 701            for vaddr, vsize, offset in sections:
 702                if rva >= vaddr and rva < vaddr + vsize:
 703                    return offset + (rva - vaddr)
 704
 705        rsrc_offset = rva_to_offset(rsrc_rva)
 706        if rsrc_offset is None:
 707            eprint("no rsrc in exe")
 708            return None
 709        
 710        def find_rsrc_entry(offset, target):
 711            if offset & 0x80000000:
 712                r.setpos(rsrc_offset + (offset & 0x7fffffff) + 0xc)
 713                num_named, num_indexed = r.u16(), r.u16()
 714                r.addpos(num_named * 0x8)
 715
 716                for _ in range(num_indexed):
 717                    idx, offset = r.u32(), r.u32()
 718                    if idx == target:
 719                        return offset
 720        
 721        icon_entry = find_rsrc_entry(0x80000000, 3)
 722        if e(icon_entry):
 723            icon_entry = find_rsrc_entry(icon_entry, 1)
 724        if e(icon_entry):
 725            icon_entry = find_rsrc_entry(icon_entry, 0x409)
 726        if icon_entry is None or icon_entry & 0x80000000:
 727            eprint("no english icon #1 in exe")
 728            return None
 729
 730        r.setpos(rsrc_offset + icon_entry)
 731        icon_rva, icon_size = r.u32(), r.u32()
 732        if icon_size != 0x10828:
 733            eprint("unknown icon size in exe")
 734            return None
 735
 736        icon_offset = rva_to_offset(icon_rva)
 737        assert e(icon_offset)
 738        return icon_offset + 0x28
 739
 740    def create_icns_data(m, raw_data, has_alpha=False):
 741        num_chan = 4 if has_alpha else 3
 742
 743        w = BinaryWriter(big_end=True)
 744        w.str("icns")
 745        w.u32(0) # filled below
 746        w.str("it32")
 747        w.u32(0xc + 0x80 * 0x81 * 3)
 748        w.u32(0)
 749
 750        # pico8 doesn't compress, so neither shall we
 751        for chan in range(3):
 752            for y in range(0x80):
 753                w.u8(0x7f)
 754                for x in range(0x80):
 755                    w.u8(raw_data[(x + y*0x80)*num_chan + chan])
 756
 757        w.str("t8mk")
 758        w.u32(0x8 + 0x80 * 0x80)
 759        for y in range(0x80):
 760            for x in range(0x80):
 761                w.u8(raw_data[(x + y*0x80)*num_chan + 3] if has_alpha else 0xff)
 762
 763        w.setpos(4)
 764        w.u32(w.len())
 765        return w.f.getvalue()
 766
 767    def find_zstr(m, data, prefix, infix):
 768        start = 0
 769        while True:
 770            start = data.find(prefix, start)
 771            if start < 0:
 772                break
 773
 774            end = data.find(b"\0", start)
 775            if end < 0:
 776                break
 777            
 778            zstr = data[start:end]
 779            if infix in zstr:
 780                return zstr.decode()
 781            
 782            start = end + 1
 783        
 784        return None
 785
 786    def zip_write(m, zip, dir, name, data, exec=False, is_dir=False):
 787
 788        info = ZipInfo(dir + "/" + name, m.curr_time)
 789        info.create_system = 3 # unix
 790        info.external_attr = (0o775 if exec or is_dir else 0o644) << 16
 791        if is_dir:
 792            info.external_attr |= 0x10 # w/o 0x40000000
 793            info.compress_type = ZIP_STORED
 794            info.filename += "/"
 795            zip.writestr(info, b"") # zip.mkdir is too new...
 796        else:
 797            info.external_attr |= 0x80000000
 798            info.compress_type = ZIP_DEFLATED
 799            zip.writestr(info, data)
 800    
 801    def zip_mkdir(m, zip, dir, name):
 802        m.zip_write(zip, dir, name, None, is_dir=True)
 803        return dir + "/" + name
 804
 805class FullExport(CartExport, FullExportBase):
 806    def __init__(m, pico8_dat, cart):
 807        super().__init__()
 808        m.pico8_dat = pico8_dat
 809        m.cart = cart
 810
 811    @classmethod
 812    def create(cls, pico8_dat, cart=None, export_name="", **opts):
 813        opts["cart"] = cart
 814        opts["export_name"] = export_name
 815
 816        m = FullExport(pico8_dat, cart)
 817        m.html_pod = PodFile(pico8_dat.find_named("pod/f_html5.pod"))
 818        m.bin_pod = PodFile(pico8_dat.find_named("pod/f_bin.pod"))
 819
 820        m.pod = PodExport.create(pico8_dat, **opts)
 821        m.js = JsExport.create(pico8_dat, html_pod=m.html_pod, **opts)
 822        m.wjs = JsExport.create(pico8_dat, html_pod=m.html_pod, for_wasm=True, **opts)
 823        m.exports = [m.pod, m.js, m.wjs]
 824        
 825        m.export_name = export_name
 826        return m
 827
 828    def write_cart(m, *args, **opts):
 829        for export in m.exports:
 830            export.write_cart(*args, **opts)
 831
 832    def zip_copy(m, zip, dir, pod, exclude=None):
 833        for e in pod.entries:
 834            if e.name and e.name.startswith("./"): # many unnamed entries?
 835                if exclude and exclude in e.name:
 836                    continue
 837
 838                exec = "." not in path_basename(e.name) # ???
 839                is_dir = not e.content # ???
 840                m.zip_write(zip, dir, e.name[2:], e.content, exec=exec, is_dir=is_dir)
 841
 842    def save(m, path, delete_existing=False):
 843        dir_create(path, delete_existing=delete_existing)
 844        basename = m.export_name
 845
 846        label_bmpdata = None
 847        label_icnsdata = None
 848        label_png = None
 849        label_url = ""
 850        if m.cart and m.cart.label:
 851            label = create_screenshot_surface(m.cart.label)
 852            label_bmpdata = label.to_data(PixelFormat.bgra8, flip=True)
 853            label_icnsdata = label.to_data(PixelFormat.rgb8)
 854            label_png = label.convert(PixelFormat.rgb8).save()
 855            label_url = "data:image/png;base64," + base64.b64encode(label_png).decode()
 856        
 857        html_data = m.html_pod.find_named("src/shell.html").decode()
 858        html_data = html_data.replace("##js_file##", "%s.js" % basename)
 859        html_data = html_data.replace("##label_file##", label_url)
 860        
 861        html_path = path_join(path, "%s_html" % basename)
 862        dir_ensure_exists(html_path)
 863        file_write_text(path_join(html_path, "%s.html" % basename), html_data)
 864        file_write_text(path_join(html_path, "%s.js" % basename), m.js.text)
 865        
 866        html_path = path_join(path, "%s_wasm" % basename)
 867        dir_ensure_exists(html_path)
 868        file_write_text(path_join(html_path, "%s.html" % basename), html_data)
 869        file_write(path_join(html_path, "%s.wasm" % basename), m.html_pod.find_named("src/pico8_wasm.wasm"))
 870        file_write_text(path_join(html_path, "%s.js" % basename), m.wjs.text.replace("pico8_wasm.wasm", "%s.wasm" % basename))
 871
 872        exe_data = m.bin_pod.find_named("bin/pico8.exe")
 873        if label_bmpdata:
 874            exe_icon_i = m.find_icon_offset_in_exe(exe_data)
 875            if e(exe_icon_i):
 876                exe_data = str_replace_at(exe_data, exe_icon_i, 0x10000, label_bmpdata)
 877            else:
 878                eprint("couldn't find icon in exe, not changing it")
 879
 880        win_dir = "%s_windows" % basename
 881        with ZipFile(path_join(path, win_dir + ".zip"), "w") as win_zip:
 882            m.zip_write(win_zip, win_dir, "%s.exe" % basename, exe_data, exec=True)
 883            m.zip_write(win_zip, win_dir, "data.pod", m.pod.data)
 884            m.zip_write(win_zip, win_dir, "SDL2.dll", m.bin_pod.find_named("bin/SDL2.dll"))
 885
 886        linux_dir = "%s_linux" % basename
 887        with ZipFile(path_join(path, linux_dir + ".zip"), "w") as linux_zip:
 888            m.zip_write(linux_zip, linux_dir, "data.pod", m.pod.data)
 889            if label_png: m.zip_write(linux_zip, linux_dir, "%s.png" % basename, label_png)
 890            m.zip_write(linux_zip, linux_dir, basename, m.bin_pod.find_named("bin/pico8_dyn.amd64"), exec=True)
 891        
 892        raspi_dir = "%s_raspi" % basename
 893        with ZipFile(path_join(path, raspi_dir + ".zip"), "w") as raspi_zip:
 894            m.zip_write(raspi_zip, raspi_dir, "data.pod", m.pod.data)
 895            if label_png: m.zip_write(raspi_zip, raspi_dir, "%s.png" % basename, label_png)
 896            for suffix, content in m.bin_pod.find_prefix("builds/pi_builds/pico8_player"):
 897                m.zip_write(raspi_zip, raspi_dir, basename + suffix, content, exec=True)
 898
 899        if label_icnsdata:
 900            icns_data = m.create_icns_data(label_icnsdata) # doesn't seem to use "builds/osx_builds/pico8.icns" in the pod
 901        else:
 902            icns_data = m.bin_pod.find_named("builds/osx_builds/pico8.icns")
 903
 904        # unfortunately, the plist template isn't in the pods - only in the exe. well, the exe's in the pod, so...
 905        info_plist = m.find_zstr(exe_data, b"<?xml", b"<key>CFBundleExecutable</key>")
 906        if info_plist is None: # in case it's ever not there anymore
 907            info_plist = file_read_text(path_join(get_res_path(), "template.plist"))
 908        info_plist = info_plist.replace("%s.%s", "pico8_author.%s" % basename)
 909        info_plist = info_plist.replace("%s", basename)
 910
 911        osx_dir = "%s.app" % basename
 912        with ZipFile(path_join(path, "%s_osx.zip" % basename), "w") as osx_zip:
 913            osx_cont_dir = m.zip_mkdir(osx_zip, osx_dir, "Contents")
 914            osx_mac_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "MacOS")
 915            osx_res_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "Resources")
 916            m.zip_write(osx_zip, osx_mac_dir, "data.pod", m.pod.data)
 917            m.zip_write(osx_zip, osx_mac_dir, basename, m.bin_pod.find_named("builds/osx_builds/pico8_player"), exec=True)
 918            m.zip_write(osx_zip, osx_res_dir, "%s.icns" % basename, icns_data)
 919            m.zip_write(osx_zip, osx_cont_dir, "Info.plist", info_plist.encode())
 920
 921            osx_sdlfw_pod = PodFile(list(m.bin_pod.find_prefix("builds/osx_builds/sdl2_framework"))[0][1])
 922            osx_fw_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "Frameworks")
 923            osx_sdlfw_dir = m.zip_mkdir(osx_zip, osx_fw_dir, "SDL2.framework")
 924            m.zip_copy(osx_zip, osx_sdlfw_dir, osx_sdlfw_pod, exclude="/_CodeSignature")
 925            osx_sdlver_dir = m.zip_mkdir(osx_zip, osx_sdlfw_dir, "Versions")
 926            m.zip_copy(osx_zip, m.zip_mkdir(osx_zip, osx_sdlver_dir, "Current"), osx_sdlfw_pod)
 927            m.zip_copy(osx_zip, m.zip_mkdir(osx_zip, osx_sdlver_dir, "A"), osx_sdlfw_pod)
 928
 929def read_pod_file(path):
 930    return PodFile(file_read(path))
 931
 932def read_cart_export(path, format):
 933    """Read a CartExport from the given path, assuming it is in the given format"""
 934    if format == CartFormat.js:
 935        return JsExport(file_read_text(path))
 936    if format == CartFormat.pod:
 937        return PodExport(file_read(path))
 938    if format == CartFormat.dat:
 939        return PicoDat(file_read(path))
 940    else:
 941        throw(f"invalid export format: {format}")
 942
 943def write_cart_export(path, export, delete_existing=False):
 944    """Write a CartExport to the given path"""
 945    if isinstance(export, JsExport):
 946        file_write_text(path, export.text)
 947    elif isinstance(export, PodExport):
 948        file_write(path, export.data)
 949    elif isinstance(export, FullExport):
 950        export.save(path, delete_existing)
 951    else:
 952        fail("invalid cart export")
 953
 954def create_cart_export(format, pico8_dat, **opts):
 955    """Create an empty CartExport in the given format"""
 956    if format == CartFormat.js:
 957        return JsExport.create(pico8_dat, **opts)
 958    elif format == CartFormat.pod:
 959        return PodExport.create(pico8_dat, **opts)
 960    elif format == CartFormat.bin:
 961        return FullExport.create(pico8_dat, **opts)
 962    else:
 963        throw(f"invalid export format: {format}")
 964
 965def read_from_cart_export(path, format, cart_name=None, extra_carts=None, **opts):
 966    """Read a cart or carts from a cart export"""
 967    export = read_cart_export(path, format)
 968
 969    if e(extra_carts):
 970        assert not cart_name
 971        main_cart = None
 972        for cart in export.list_carts():
 973            if main_cart:
 974                extra_carts.append(export.read_cart(cart, **opts))
 975            else:
 976                main_cart = export.read_cart(cart, **opts)
 977        return main_cart
 978    else:
 979        return export.read_cart(cart_name, **opts)
 980
 981def write_to_cart_export(path, cart, format, extra_carts=None, cart_name=None, target_name=None, cart_op=None, 
 982                         target_export=None, export_name=None, pico_dat=None, delete_existing=False, **opts):
 983    """Create or edit a CartExport in the given path, depending on cart_op/cart_args arguments"""
 984    if not export_name:
 985        export_name = path_basename_no_extension(path)
 986
 987    if cart_op is None:
 988        assert isinstance(pico_dat, PodFile)
 989        export = create_cart_export(format, pico_dat, cart=cart, export_name=export_name)
 990    else:
 991        assert isinstance(target_export, CartExport)
 992        export = target_export
 993        
 994    export.write_cart(cart, cart_name, cart_op, target_name, **opts)
 995    if extra_carts:
 996        for extra_cart in extra_carts:
 997            export.write_cart(extra_cart, **opts)
 998    
 999    write_cart_export(path, export, delete_existing)
1000
1001from pico_cart import CartFormat, write_cart, read_cart_from_rom, write_cart_to_rom
1002from pico_cart import read_cart_from_source, write_cart_to_source, create_screenshot_surface
class ListOp(utils.Enum):
11class ListOp(Enum):
12    insert = replace = delete = rename = ...

If a class has Enum as a baseclass, it's transformed into an enum. All non-private attributes of the class other than functions and descriptors become enum members. Atributes with a value of ... receive values automatically. Inherited classes behave like regular classes unless they have Enum as a direct baseclass. Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter Atributes with a name ending with _ can be referred to without the _.

ListOp(value)
172        def __init__(m, value):
173            if value in full_value_name_map:
174                m.value = value
175            elif value in full_name_value_map:
176                m.value = full_name_value_map[value]
177            else:
178                raise ValueError(f"{value} not value of {cls_name}")
value
insert = ListOp.insert
replace = ListOp.replace
delete = ListOp.delete
rename = ListOp.rename
class CartExport:
14class CartExport:
15    """A container of multiple carts"""
16
17    # get_carts_impl: () -> {name: <ref>} in cart order
18    # read_impl: (<ref>, **opts) -> cart
19    # insert_impl: (<ref> or None, name, cart, **opts) -> void
20    # replace_impl: (<ref>, cart, **opts) -> void
21    # delete_impl: (<ref>, **opts) -> void
22    # rename_impl: (<ref>, new_name, **opts) -> void
23    # NOTE: <ref>s are valid only until next modification or get_carts_impl call
24
25    def _default(m, carts, strict=True):
26        name = dict_first_key(carts)
27        if name is None and strict:
28            throw(f"export is empty - contains no carts")
29        return name
30
31    def _find(m, carts, cart_name, strict=True):
32        ref = carts.get(cart_name)
33        if ref is None and strict:
34            throw(f"cart {cart_name} not found in export")
35        return ref
36
37    def _contains(m, carts, cart_name):
38        return e(m._find(carts, cart_name, strict=False))
39    
40    def list_carts(m):
41        return m.get_carts_impl().keys()
42
43    def read_cart(m, cart_name=None, **opts):
44        carts = m.get_carts_impl()
45        if cart_name is None:
46            cart_name = m._default(carts)
47        ref = m._find(carts, cart_name)
48
49        return m.read_impl(ref, path=cart_name, **opts)
50    
51    def write_cart(m, cart, cart_name=None, cart_op=None, target_name=None, **opts):
52        cart_op = default(cart_op, ListOp.insert)
53        carts = m.get_carts_impl()
54
55        if cart_op == ListOp.insert:
56            if cart_name is None:
57                cart_name = cart.name
58            if m._contains(carts, cart_name):
59                throw(f"cart {cart_name} already found in export")
60            
61            target_ref = None
62            if e(target_name):
63                target_ref = m._find(carts, target_name)
64            m.insert_impl(target_ref, cart_name, cart, **opts)
65
66        else:
67            if cart_name is None:
68                cart_name = m._default(carts)
69            ref = m._find(carts, cart_name)
70            
71            if cart_op == ListOp.replace:
72                m.replace_impl(ref, cart, **opts)
73            elif cart_op == ListOp.delete:
74                m.delete_impl(ref)
75            elif cart_op == ListOp.rename:
76                if m._contains(carts, target_name):
77                    throw(f"cart {target_name} already found in export")
78                
79                m.rename_impl(ref, target_name)
80            else:
81                fail("invalid cart op")
82        
83        return m
84
85    def dump_cart(m, dest, fmt, name, raw_data):
86        path = path_join(dest, filename_fixup(name))
87
88        if fmt == CartFormat.rom:
89            file_write(path, raw_data)
90        else:
91            write_cart(path, read_cart_from_rom(raw_data), fmt)

A container of multiple carts

def list_carts(m):
40    def list_carts(m):
41        return m.get_carts_impl().keys()
def read_cart(m, cart_name=None, **opts):
43    def read_cart(m, cart_name=None, **opts):
44        carts = m.get_carts_impl()
45        if cart_name is None:
46            cart_name = m._default(carts)
47        ref = m._find(carts, cart_name)
48
49        return m.read_impl(ref, path=cart_name, **opts)
def write_cart(m, cart, cart_name=None, cart_op=None, target_name=None, **opts):
51    def write_cart(m, cart, cart_name=None, cart_op=None, target_name=None, **opts):
52        cart_op = default(cart_op, ListOp.insert)
53        carts = m.get_carts_impl()
54
55        if cart_op == ListOp.insert:
56            if cart_name is None:
57                cart_name = cart.name
58            if m._contains(carts, cart_name):
59                throw(f"cart {cart_name} already found in export")
60            
61            target_ref = None
62            if e(target_name):
63                target_ref = m._find(carts, target_name)
64            m.insert_impl(target_ref, cart_name, cart, **opts)
65
66        else:
67            if cart_name is None:
68                cart_name = m._default(carts)
69            ref = m._find(carts, cart_name)
70            
71            if cart_op == ListOp.replace:
72                m.replace_impl(ref, cart, **opts)
73            elif cart_op == ListOp.delete:
74                m.delete_impl(ref)
75            elif cart_op == ListOp.rename:
76                if m._contains(carts, target_name):
77                    throw(f"cart {target_name} already found in export")
78                
79                m.rename_impl(ref, target_name)
80            else:
81                fail("invalid cart op")
82        
83        return m
def dump_cart(m, dest, fmt, name, raw_data):
85    def dump_cart(m, dest, fmt, name, raw_data):
86        path = path_join(dest, filename_fixup(name))
87
88        if fmt == CartFormat.rom:
89            file_write(path, raw_data)
90        else:
91            write_cart(path, read_cart_from_rom(raw_data), fmt)
class JsExport(CartExport):
 93class JsExport(CartExport):
 94    """A javascript file containing one or more carts"""
 95
 96    def __init__(m, text):
 97        super().__init__()
 98        m.text = text
 99    
100    def find_cartnames(m):
101        match = re.search(r"var\s+_cartname\s*=\s*\[(.*?)\]", m.text, re.S)
102        if not match:
103            throw("can't find _cartname var in js")
104        return match
105    
106    def find_cartdata(m):
107        match = re.search(r"var\s+_cartdat\s*=\s*\[(.*?)\]", m.text, re.S)
108        if not match:
109            throw("can't find _cartdat var in js")
110        return match
111
112    def get_carts_impl(m):
113        m.cartnames = []
114        cartnames_text = m.find_cartnames().group(1)
115        if cartnames_text.strip():
116            for i, cartname in enumerate(cartnames_text.split(",")):
117                cartname = cartname.strip()[1:-1] # may fail if using special chars...
118                m.cartnames.append(cartname)
119
120        m.cartdata = bytearray(k_cart_size * len(m.cartnames))
121        cartdata_text = m.find_cartdata().group(1)
122        if cartdata_text.strip():
123            for i, b in enumerate(cartdata_text.split(",")):
124                m.cartdata[i] = int(b.strip())
125
126        carts = {}
127        for i, cartname in enumerate(m.cartnames):
128            carts[cartname] = i
129        return carts
130
131    def slice(m, i, end_i=None):
132        return slice(k_cart_size * i, k_cart_size * default(end_i, i + 1))
133
134    def read_impl(m, i, **opts):
135        return read_cart_from_rom(m.cartdata[m.slice(i)], **opts)
136
137    def insert_impl(m, i, name, cart, **opts):
138        i = default(i, len(m.cartnames))
139        m.cartdata[m.slice(i, i)] = write_cart_to_rom(cart, **opts)
140        m.cartnames.insert(i, name)
141        m.finish_write()
142
143    def replace_impl(m, i, cart, **opts):
144        m.cartdata[m.slice(i)] = write_cart_to_rom(cart, **opts)
145        m.finish_write()
146    
147    def delete_impl(m, i):
148        del m.cartdata[m.slice(i)]
149        del m.cartnames[i]
150        m.finish_write()
151    
152    def rename_impl(m, i, name):
153        m.cartnames[i] = name
154        m.finish_write()
155
156    def finish_write(m):
157        cartnames_text = ", ".join(f"`{name}`" for name in m.cartnames)
158        m.text = str_replace_between(m.text, *m.find_cartnames().span(1), cartnames_text)
159
160        cartdata_chunks = ["\n"]
161        for chunk in iter_chunk(m.cartdata, 0x100):
162            if len(cartdata_chunks) > 1:
163                cartdata_chunks.append(",\n")
164            cartdata_chunks.append(",".join("%d" % b for b in chunk))
165        m.text = str_replace_between(m.text, *m.find_cartdata().span(1), "".join(cartdata_chunks))
166        m.cartnames = m.cartdata = None # need reparse
167    
168    def find_pod(m):
169        matches = list(re.finditer(r"fileData0\.push\.apply\s*\(\s*fileData0\s*,\s*\[(.*?)\]\s*\)", m.text, re.S))
170        if not matches:
171            throw("can't find fileData0 pushes in js")
172        return matches
173    
174    def read_pod(m): # this pod is the same for all carts, so it's not very interesting in retrospect
175        pod_data = bytearray()
176        for match in m.find_pod():
177            match_text = match.group(1)
178            if match_text.strip():
179                for b in match_text.split(","):
180                    pod_data.append(int(b.strip()))
181        return PodFile(pod_data)
182
183    def dump_contents(m, dest, fmt, misc=False):
184        carts = m.get_carts_impl()
185        for name, i in carts.items():
186            m.dump_cart(dest, fmt, name, m.cartdata[m.slice(i)])
187        if misc:
188            m.read_pod().dump_contents(dest, fmt, misc=True)
189    
190    @classmethod
191    def create(cls, pico8_dat, html_pod=None, for_wasm=False, **_):
192        if not html_pod:
193            html_pod = PodFile(pico8_dat.find_named("pod/f_html5.pod"))
194        js_file = "var _cartname=[];\n"
195        js_file += "var _cdpos=0; var iii=0; var ciii=0;\n"
196        js_file += "var _cartdat=[];\n\n"
197        js_file += html_pod.find_named("src/pico8_wasm.js" if for_wasm else "src/pico8.js").decode()
198        return JsExport(js_file)        

A javascript file containing one or more carts

JsExport(text)
96    def __init__(m, text):
97        super().__init__()
98        m.text = text
def find_cartnames(m):
100    def find_cartnames(m):
101        match = re.search(r"var\s+_cartname\s*=\s*\[(.*?)\]", m.text, re.S)
102        if not match:
103            throw("can't find _cartname var in js")
104        return match
def find_cartdata(m):
106    def find_cartdata(m):
107        match = re.search(r"var\s+_cartdat\s*=\s*\[(.*?)\]", m.text, re.S)
108        if not match:
109            throw("can't find _cartdat var in js")
110        return match
def get_carts_impl(m):
112    def get_carts_impl(m):
113        m.cartnames = []
114        cartnames_text = m.find_cartnames().group(1)
115        if cartnames_text.strip():
116            for i, cartname in enumerate(cartnames_text.split(",")):
117                cartname = cartname.strip()[1:-1] # may fail if using special chars...
118                m.cartnames.append(cartname)
119
120        m.cartdata = bytearray(k_cart_size * len(m.cartnames))
121        cartdata_text = m.find_cartdata().group(1)
122        if cartdata_text.strip():
123            for i, b in enumerate(cartdata_text.split(",")):
124                m.cartdata[i] = int(b.strip())
125
126        carts = {}
127        for i, cartname in enumerate(m.cartnames):
128            carts[cartname] = i
129        return carts
def slice(m, i, end_i=None):
131    def slice(m, i, end_i=None):
132        return slice(k_cart_size * i, k_cart_size * default(end_i, i + 1))
def read_impl(m, i, **opts):
134    def read_impl(m, i, **opts):
135        return read_cart_from_rom(m.cartdata[m.slice(i)], **opts)
def insert_impl(m, i, name, cart, **opts):
137    def insert_impl(m, i, name, cart, **opts):
138        i = default(i, len(m.cartnames))
139        m.cartdata[m.slice(i, i)] = write_cart_to_rom(cart, **opts)
140        m.cartnames.insert(i, name)
141        m.finish_write()
def replace_impl(m, i, cart, **opts):
143    def replace_impl(m, i, cart, **opts):
144        m.cartdata[m.slice(i)] = write_cart_to_rom(cart, **opts)
145        m.finish_write()
def delete_impl(m, i):
147    def delete_impl(m, i):
148        del m.cartdata[m.slice(i)]
149        del m.cartnames[i]
150        m.finish_write()
def rename_impl(m, i, name):
152    def rename_impl(m, i, name):
153        m.cartnames[i] = name
154        m.finish_write()
def finish_write(m):
156    def finish_write(m):
157        cartnames_text = ", ".join(f"`{name}`" for name in m.cartnames)
158        m.text = str_replace_between(m.text, *m.find_cartnames().span(1), cartnames_text)
159
160        cartdata_chunks = ["\n"]
161        for chunk in iter_chunk(m.cartdata, 0x100):
162            if len(cartdata_chunks) > 1:
163                cartdata_chunks.append(",\n")
164            cartdata_chunks.append(",".join("%d" % b for b in chunk))
165        m.text = str_replace_between(m.text, *m.find_cartdata().span(1), "".join(cartdata_chunks))
166        m.cartnames = m.cartdata = None # need reparse
def find_pod(m):
168    def find_pod(m):
169        matches = list(re.finditer(r"fileData0\.push\.apply\s*\(\s*fileData0\s*,\s*\[(.*?)\]\s*\)", m.text, re.S))
170        if not matches:
171            throw("can't find fileData0 pushes in js")
172        return matches
def read_pod(m):
174    def read_pod(m): # this pod is the same for all carts, so it's not very interesting in retrospect
175        pod_data = bytearray()
176        for match in m.find_pod():
177            match_text = match.group(1)
178            if match_text.strip():
179                for b in match_text.split(","):
180                    pod_data.append(int(b.strip()))
181        return PodFile(pod_data)
def dump_contents(m, dest, fmt, misc=False):
183    def dump_contents(m, dest, fmt, misc=False):
184        carts = m.get_carts_impl()
185        for name, i in carts.items():
186            m.dump_cart(dest, fmt, name, m.cartdata[m.slice(i)])
187        if misc:
188            m.read_pod().dump_contents(dest, fmt, misc=True)
@classmethod
def create(cls, pico8_dat, html_pod=None, for_wasm=False, **_):
190    @classmethod
191    def create(cls, pico8_dat, html_pod=None, for_wasm=False, **_):
192        if not html_pod:
193            html_pod = PodFile(pico8_dat.find_named("pod/f_html5.pod"))
194        js_file = "var _cartname=[];\n"
195        js_file += "var _cdpos=0; var iii=0; var ciii=0;\n"
196        js_file += "var _cartdat=[];\n\n"
197        js_file += html_pod.find_named("src/pico8_wasm.js" if for_wasm else "src/pico8.js").decode()
198        return JsExport(js_file)        
class PodFile:
200class PodFile:
201    """A pod file - used in pico8 inside exports/etc"""
202
203    k_header = "CPOD"
204    k_file_header = "CFIL"
205    k_cmpr_file_header = "cFIL"
206    k_bmp_header = "CBMP"
207    k_cmpr_bmp_header = "cBMP"
208    k_pal_header = "CPAL"
209    k_num_colors = 0x100
210
211    class Entry(Struct):
212        header = pos = end_pos = name = content = ...
213
214    def __init__(m, data):
215        m.data = data
216        m.read_all()
217
218    def init_write(m):
219        if not isinstance(m.data, bytearray):
220            m.data = bytearray(m.data)
221
222    def read_all(m):
223        with BinaryReader(BytesIO(m.data)) as r:
224            check(r.str(4) == m.k_header, "invalid POD file")
225            check(r.u32() == 0x44, "newer POD version?") # size of header?
226            check(r.u32() == 1, "newer POD version?") # ???
227            m.name = r.zstr(0x20) # ???
228            count = r.u32()
229            r.addpos(0x1c) # junk?
230
231            m.entries = []
232            palette = None
233            for i in range(count):
234                pos = r.pos()
235                header = r.str(4)
236                name = None
237
238                if header in (m.k_file_header, m.k_cmpr_file_header):
239                    check(r.u32() == 0, "unknown POD file header value")
240                    size = r.u32()
241                    name = r.zstr(0x40)
242                    if header == m.k_cmpr_file_header:
243                        content = lz4_uncompress(r.bytes(r.u32()))
244                    else:
245                        content = r.bytes(size)
246                
247                elif header in (m.k_bmp_header, m.k_cmpr_bmp_header):
248                    size = r.u32()
249                    w = r.u32()
250                    h = r.u32()
251                    bpp = r.u32()
252                    check(r.u32() == 0, "unknown POD bmp header value")
253                    check(r.u32() == 0, "unknown POD bmp header value")
254                    if header == m.k_cmpr_bmp_header:
255                        data = lz4_uncompress(r.bytes(r.u32()))
256                    else:
257                        data = r.bytes(size - 0x14)
258                    
259                    fmt = PixelFormat.i8 if bpp == 8 else PixelFormat.bgra8 if bpp == 32 else throw("unknown POD bmp bpp %d" % bpp)
260                    content = Image.from_data(w, h, fmt, data)
261                    if fmt == PixelFormat.i8:
262                        content.palette = default(palette, m.default_palette)
263
264                elif header == m.k_pal_header:
265                    size = r.u32()
266                    num_colors = m.k_num_colors
267                    check(size == 3 * num_colors, "wrong POD palette size?")
268                    content = Palette.create(num_colors)
269                    for i in range(num_colors):
270                        content[i] = Color(r.u8(), r.u8(), r.u8())
271
272                else:
273                    throw("unknown or unexpected POD content header %s" % header)
274                
275                end_pos = r.pos()
276                m.entries.append(m.Entry(header, pos, end_pos, name, content))
277    
278    @lazy_classproperty
279    def default_palette(cls): # used for fonts in pod - well, the 0 and 0xff colors are.
280        palette = Palette.create(cls.k_num_colors)
281        for i in range(0x100):
282            palette[i] = Color(i, i, i)
283        return palette
284    
285    def find_named(m, name, strict=True):
286        for e in m.entries:
287            if e.name == name:
288                return e.content
289        if strict:
290            throw(f"expected to find {name} in pod")
291
292    def find_prefix(m, prefix, strict=True):
293        found = False
294        for e in m.entries:
295            if e.name.startswith(prefix):
296                yield e.name[len(prefix):], e.content
297                found = True
298        if strict and not found:
299            throw(f"expected to find {prefix}* in pod")
300
301    def contains(m, name):
302        return m.find_named(name, strict=False) != None
303
304    def shift_entry_positions(m, i, delta):
305        for e in m.entries[i:]:
306            e.pos += delta
307            e.end_pos += delta
308
309    def update_count(m):
310        buf = BinaryBuffer(m.data)
311        buf.w_u32(0x2c, len(m.entries))
312    
313    @classmethod
314    def create(cls, name=None):
315        with BinaryWriter() as w:
316            w.str(cls.k_header)
317            w.u32(0x44) # size of header
318            w.u32(1) # version?
319            w.zstr(name or "", 0x20)
320            w.u32(0)
321            w.zstr("", 0x1c)
322        
323            return PodFile(w.f.getvalue())
324
325    def insert_content(m, i, name, content, compress=False):
326        m.init_write()
327        if i < len(m.entries):
328            pos = m.entries[i].pos
329        else:
330            pos = len(m.data)
331        
332        def write_bytes(w, data):
333            if compress:
334                compressed = lz4_compress(data, fast=True)
335                w.u32(len(compressed))
336                w.bytes(compressed)
337            else:
338                w.bytes(data)
339        
340        with BinaryWriter() as w:
341            if isinstance(content, bytes):
342                header = m.k_cmpr_file_header if compress else m.k_file_header
343
344                w.str(header)
345                w.u32(0)
346                w.u32(len(content))
347                w.zstr(name, 0x40)
348                write_bytes(w, content)
349            
350            elif isinstance(content, Image):
351                if content.format.bpp == 8:
352                    format = PixelFormat.i8
353                elif content.format.bpp == 32:
354                    format = PixelFormat.bgra8
355                else:
356                    check("invalid surface format for pod")
357                
358                data = content.to_data(format)
359                header = m.k_cmpr_bmp_header if compress else m.k_bmp_header
360
361                w.str(header)
362                w.u32(len(data) + 0x14)
363                w.u32(content.width)
364                w.u32(content.height)
365                w.u32(content.format.bpp)
366                w.u32(0); w.u32(0)
367                write_bytes(w, data)
368
369            elif isinstance(content, Palette):
370                assert not compress
371                header = m.k_pal_header
372
373                w.str(header)
374                w.u32(3 * m.k_num_colors)
375                for i in range(m.k_num_colors):
376                    r, g, b, _ = content[i]
377                    w.u8(r); w.u8(g); w.u8(b)
378            
379            else:
380                fail("Unknown content type")
381            
382            size = w.pos()
383            new_data = w.f.getvalue()
384        
385        m.data[pos:pos] = new_data
386        m.entries.insert(i, m.Entry(header, pos, pos + size, name, content))
387
388        m.shift_entry_positions(i + 1, size)
389        m.update_count()
390        
391    def append_content(m, name, content, compress=False):
392        m.insert_content(len(m.entries), name, content, compress)
393
394    def delete_content(m, i):
395        m.init_write()
396        e = m.entries[i]
397
398        del m.data[e.pos:e.end_pos]
399        del m.entries[i]
400
401        m.shift_entry_positions(i, -(e.end_pos - e.pos))
402        m.update_count()
403    
404    def replace_content(m, i, content):
405        e = m.entries[i]
406        if e.header == m.k_file_header and isinstance(content, bytes) and len(content) == len(e.content):
407            pos = e.pos + 0x4c
408        else:
409            m.delete_content(i)
410            m.insert_content(i, e.name, content)
411            return
412
413        m.init_write()
414        m.data[pos:pos+len(content)] = content
415        e.content = content
416    
417    def rename_content(m, i, name):
418        m.init_write()
419        e = m.entries[i]
420        if isinstance(e.content, bytes):
421            buf = BinaryBuffer(m.data)
422            buf.w_zstr(e.pos + 0xc, name, 0x40)
423            e.name = name
424
425    def dump_contents(m, dest, fmt, misc=False):
426        for i, e in enumerate(m.entries):
427            if isinstance(e.content, bytes):
428                m.dump_file(dest, fmt, misc, i, e.name, e.content)
429            elif isinstance(e.content, Image):
430                with file_create(path_join(dest, f"{i}.png")) as f:
431                    e.content.save(f)
432            elif isinstance(e.content, Palette):
433                with file_create(path_join(dest, f"{i}.pal.png")) as f:
434                    e.content.to_surface().save(f)
435            else:
436                fail("wrong data in pod contents")
437    
438    def dump_file(m, dest, fmt, misc, i, name, content):
439        if name.lower().endswith(".pod"):
440            pod_dest = path_join(dest, filename_fixup(name[:-4]))
441            dir_ensure_exists(pod_dest)
442            PodFile(content).dump_contents(pod_dest, fmt, misc)
443        else:
444            file_write(path_join(dest, filename_fixup(name)), content)

A pod file - used in pico8 inside exports/etc

PodFile(data)
214    def __init__(m, data):
215        m.data = data
216        m.read_all()
k_header = 'CPOD'
k_file_header = 'CFIL'
k_cmpr_file_header = 'cFIL'
k_bmp_header = 'CBMP'
k_cmpr_bmp_header = 'cBMP'
k_pal_header = 'CPAL'
k_num_colors = 256
def init_write(m):
218    def init_write(m):
219        if not isinstance(m.data, bytearray):
220            m.data = bytearray(m.data)
def read_all(m):
222    def read_all(m):
223        with BinaryReader(BytesIO(m.data)) as r:
224            check(r.str(4) == m.k_header, "invalid POD file")
225            check(r.u32() == 0x44, "newer POD version?") # size of header?
226            check(r.u32() == 1, "newer POD version?") # ???
227            m.name = r.zstr(0x20) # ???
228            count = r.u32()
229            r.addpos(0x1c) # junk?
230
231            m.entries = []
232            palette = None
233            for i in range(count):
234                pos = r.pos()
235                header = r.str(4)
236                name = None
237
238                if header in (m.k_file_header, m.k_cmpr_file_header):
239                    check(r.u32() == 0, "unknown POD file header value")
240                    size = r.u32()
241                    name = r.zstr(0x40)
242                    if header == m.k_cmpr_file_header:
243                        content = lz4_uncompress(r.bytes(r.u32()))
244                    else:
245                        content = r.bytes(size)
246                
247                elif header in (m.k_bmp_header, m.k_cmpr_bmp_header):
248                    size = r.u32()
249                    w = r.u32()
250                    h = r.u32()
251                    bpp = r.u32()
252                    check(r.u32() == 0, "unknown POD bmp header value")
253                    check(r.u32() == 0, "unknown POD bmp header value")
254                    if header == m.k_cmpr_bmp_header:
255                        data = lz4_uncompress(r.bytes(r.u32()))
256                    else:
257                        data = r.bytes(size - 0x14)
258                    
259                    fmt = PixelFormat.i8 if bpp == 8 else PixelFormat.bgra8 if bpp == 32 else throw("unknown POD bmp bpp %d" % bpp)
260                    content = Image.from_data(w, h, fmt, data)
261                    if fmt == PixelFormat.i8:
262                        content.palette = default(palette, m.default_palette)
263
264                elif header == m.k_pal_header:
265                    size = r.u32()
266                    num_colors = m.k_num_colors
267                    check(size == 3 * num_colors, "wrong POD palette size?")
268                    content = Palette.create(num_colors)
269                    for i in range(num_colors):
270                        content[i] = Color(r.u8(), r.u8(), r.u8())
271
272                else:
273                    throw("unknown or unexpected POD content header %s" % header)
274                
275                end_pos = r.pos()
276                m.entries.append(m.Entry(header, pos, end_pos, name, content))
def default_palette(unknown):

Method decorator that turns it into a lazily-evaluated class property

def find_named(m, name, strict=True):
285    def find_named(m, name, strict=True):
286        for e in m.entries:
287            if e.name == name:
288                return e.content
289        if strict:
290            throw(f"expected to find {name} in pod")
def find_prefix(m, prefix, strict=True):
292    def find_prefix(m, prefix, strict=True):
293        found = False
294        for e in m.entries:
295            if e.name.startswith(prefix):
296                yield e.name[len(prefix):], e.content
297                found = True
298        if strict and not found:
299            throw(f"expected to find {prefix}* in pod")
def contains(m, name):
301    def contains(m, name):
302        return m.find_named(name, strict=False) != None
def shift_entry_positions(m, i, delta):
304    def shift_entry_positions(m, i, delta):
305        for e in m.entries[i:]:
306            e.pos += delta
307            e.end_pos += delta
def update_count(m):
309    def update_count(m):
310        buf = BinaryBuffer(m.data)
311        buf.w_u32(0x2c, len(m.entries))
@classmethod
def create(cls, name=None):
313    @classmethod
314    def create(cls, name=None):
315        with BinaryWriter() as w:
316            w.str(cls.k_header)
317            w.u32(0x44) # size of header
318            w.u32(1) # version?
319            w.zstr(name or "", 0x20)
320            w.u32(0)
321            w.zstr("", 0x1c)
322        
323            return PodFile(w.f.getvalue())
def insert_content(m, i, name, content, compress=False):
325    def insert_content(m, i, name, content, compress=False):
326        m.init_write()
327        if i < len(m.entries):
328            pos = m.entries[i].pos
329        else:
330            pos = len(m.data)
331        
332        def write_bytes(w, data):
333            if compress:
334                compressed = lz4_compress(data, fast=True)
335                w.u32(len(compressed))
336                w.bytes(compressed)
337            else:
338                w.bytes(data)
339        
340        with BinaryWriter() as w:
341            if isinstance(content, bytes):
342                header = m.k_cmpr_file_header if compress else m.k_file_header
343
344                w.str(header)
345                w.u32(0)
346                w.u32(len(content))
347                w.zstr(name, 0x40)
348                write_bytes(w, content)
349            
350            elif isinstance(content, Image):
351                if content.format.bpp == 8:
352                    format = PixelFormat.i8
353                elif content.format.bpp == 32:
354                    format = PixelFormat.bgra8
355                else:
356                    check("invalid surface format for pod")
357                
358                data = content.to_data(format)
359                header = m.k_cmpr_bmp_header if compress else m.k_bmp_header
360
361                w.str(header)
362                w.u32(len(data) + 0x14)
363                w.u32(content.width)
364                w.u32(content.height)
365                w.u32(content.format.bpp)
366                w.u32(0); w.u32(0)
367                write_bytes(w, data)
368
369            elif isinstance(content, Palette):
370                assert not compress
371                header = m.k_pal_header
372
373                w.str(header)
374                w.u32(3 * m.k_num_colors)
375                for i in range(m.k_num_colors):
376                    r, g, b, _ = content[i]
377                    w.u8(r); w.u8(g); w.u8(b)
378            
379            else:
380                fail("Unknown content type")
381            
382            size = w.pos()
383            new_data = w.f.getvalue()
384        
385        m.data[pos:pos] = new_data
386        m.entries.insert(i, m.Entry(header, pos, pos + size, name, content))
387
388        m.shift_entry_positions(i + 1, size)
389        m.update_count()
def append_content(m, name, content, compress=False):
391    def append_content(m, name, content, compress=False):
392        m.insert_content(len(m.entries), name, content, compress)
def delete_content(m, i):
394    def delete_content(m, i):
395        m.init_write()
396        e = m.entries[i]
397
398        del m.data[e.pos:e.end_pos]
399        del m.entries[i]
400
401        m.shift_entry_positions(i, -(e.end_pos - e.pos))
402        m.update_count()
def replace_content(m, i, content):
404    def replace_content(m, i, content):
405        e = m.entries[i]
406        if e.header == m.k_file_header and isinstance(content, bytes) and len(content) == len(e.content):
407            pos = e.pos + 0x4c
408        else:
409            m.delete_content(i)
410            m.insert_content(i, e.name, content)
411            return
412
413        m.init_write()
414        m.data[pos:pos+len(content)] = content
415        e.content = content
def rename_content(m, i, name):
417    def rename_content(m, i, name):
418        m.init_write()
419        e = m.entries[i]
420        if isinstance(e.content, bytes):
421            buf = BinaryBuffer(m.data)
422            buf.w_zstr(e.pos + 0xc, name, 0x40)
423            e.name = name
def dump_contents(m, dest, fmt, misc=False):
425    def dump_contents(m, dest, fmt, misc=False):
426        for i, e in enumerate(m.entries):
427            if isinstance(e.content, bytes):
428                m.dump_file(dest, fmt, misc, i, e.name, e.content)
429            elif isinstance(e.content, Image):
430                with file_create(path_join(dest, f"{i}.png")) as f:
431                    e.content.save(f)
432            elif isinstance(e.content, Palette):
433                with file_create(path_join(dest, f"{i}.pal.png")) as f:
434                    e.content.to_surface().save(f)
435            else:
436                fail("wrong data in pod contents")
def dump_file(m, dest, fmt, misc, i, name, content):
438    def dump_file(m, dest, fmt, misc, i, name, content):
439        if name.lower().endswith(".pod"):
440            pod_dest = path_join(dest, filename_fixup(name[:-4]))
441            dir_ensure_exists(pod_dest)
442            PodFile(content).dump_contents(pod_dest, fmt, misc)
443        else:
444            file_write(path_join(dest, filename_fixup(name)), content)
class PodFile.Entry(utils.Struct):
211    class Entry(Struct):
212        header = pos = end_pos = name = content = ...

If a class has Struct as a baseclass, it's transformed into a struct. All non-private attributes of the class other than functions and descriptors become struct fields. Atributes with a value of ... are required, otherwise - optional with the given default value. A struct is like a mutable named tuple, except equality goes by identity. Inherited classes behave like regular classes unless they have Struct as a direct baseclass. Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter, const base fields keyword parameters Atributes with a name ending with _ can be referred to without the _.

PodFile.Entry(header, pos, end_pos, name, content)
content
end_pos
header
name
pos
def lz4_uncompress(data, debug=None):
448def lz4_uncompress(data, debug=None):
449    def read_u8_sum(r):
450        sum = 0
451        while True:
452            val = r.u8()
453            sum += val
454            if val != 0xff:
455                return sum
456
457    uncdata = bytearray()
458    with BinaryReader(BytesIO(data)) as r:
459        if debug: debug.init(r, bytes)
460
461        while not r.eof():
462            header = r.u8()
463            size = header >> 4
464            if size == 0xf:
465                size += read_u8_sum(r)
466            
467            for i in range(size):
468                uncdata.append(r.u8())
469            if debug and size: debug.update(uncdata[-size:])
470            
471            if not r.eof():
472                offset = r.u16()
473                count = 4 + (header & 0xf)
474                if count == 0x13:
475                    count += read_u8_sum(r)
476                
477                for i in range(count):
478                    uncdata.append(uncdata[-offset])
479                if debug: debug.update(Lz77Entry(offset, count))
480    
481    if debug: debug.end()
482    return bytes(uncdata)
def lz4_compress(uncdata, fast=False, debug=None):
484def lz4_compress(uncdata, fast=False, debug=None):
485    literals = []
486    min_c = 4
487
488    with BinaryWriter() as w:
489        if debug: debug.init(w, bytes)
490
491        def write_u8_sum(val):
492            while True:
493                byte = min(val, 0xff)
494                w.u8(byte)
495                val -= byte
496                if byte != 0xff:
497                    break
498
499        def write_block(item):
500            size = len(literals)
501            count = (item.count - min_c) if item else 0
502
503            w.u8(min(count, 0xf) | (min(size, 0xf) << 4))
504            if size >= 0xf:
505                write_u8_sum(size - 0xf)
506            
507            for lit in literals:
508                w.u8(lit)
509            
510            if debug and literals: debug.update(bytes(literals))
511            literals.clear()
512
513            if item:
514                w.u16(item.offset)
515                if count >= 0xf:
516                    write_u8_sum(count - 0xf)
517                
518                if debug: debug.update(item)
519                    
520        def measure(ctxt_litcount, item):
521            ctxt_litcount = default(ctxt_litcount, len(literals))
522
523            if isinstance(item, Lz77Entry):
524                count_bits = (item.count - min_c + 0xf0) // 0xff
525                cost = 3 + count_bits # + 1 for the next header
526                ctxt_litcount = 0
527
528            else:
529                cost = 1
530                ctxt_litcount += 1
531                if (ctxt_litcount + 0xf0) % 0xff == 0:
532                    cost += 1
533
534            return cost, ctxt_litcount
535
536        def get_cheaper_c(c):
537            return round_down(c - min_c + 0xf0, 0xff) - 1 - 0xf0 + min_c
538
539        def min_cost(dist):
540            # assume dist can be covered by an Lz77Entry without any overhead
541            # plus subtract possible overhead *savings* of an Lz77Entry
542            return max(((dist - min_c + 0xf0) // 0xff) - 1, 0)
543
544        # lz4 disallows lz77 entries near the end of the stream...
545        end_of_lz77_reach = len(uncdata) - 5
546        end_of_lz77s = len(uncdata) - 12
547
548        if fast:
549            items = get_lz77(uncdata, min_c=min_c, max_c=None, max_o=0xffff)
550        else:
551            items = get_lz77(uncdata, min_c=min_c, max_c=None, max_o=0xffff,
552                             get_cheaper_c=get_cheaper_c, measure=measure, min_cost=min_cost)
553
554        for i, item in items:
555            if isinstance(item, Lz77Entry):
556                if i < end_of_lz77s:
557                    if i + item.count <= end_of_lz77_reach:
558                        write_block(item)
559                    else:
560                        fixed_item = Lz77Entry(item.offset, end_of_lz77_reach - i)
561                        assert fixed_item.count >= min_c
562                        write_block(fixed_item)
563                        literals.extend(uncdata[end_of_lz77_reach:i+item.count])
564                else:
565                    literals.extend(uncdata[i:i+item.count])
566            else:
567                literals.append(item)
568        write_block(None)
569
570        if debug: debug.end()
571        return w.f.getvalue()
class PodExport(CartExport, PodFile):
573class PodExport(CartExport, PodFile):
574    """A .pod file used in exports, containing one or more carts"""
575
576    k_pod_names = ["pod/pico8_boot.p8", "pod/gfx1.pod", "pod/f_pico8.pod"]
577
578    def __init__(m, data):
579        CartExport.__init__(m)
580        PodFile.__init__(m, data)
581
582    def get_carts_impl(m):
583        carts = {}
584        for i, e in enumerate(m.entries):
585            if e.name and isinstance(e.content, bytes): # only carts are named in export pod files
586                carts[e.name] = (i, e.content)
587        return carts
588
589    def read_impl(m, tuple, **opts):
590        _, bytes = tuple
591        return read_cart_from_rom(bytes, **opts)
592    
593    def insert_impl(m, tuple, name, cart, **opts):
594        if e(tuple):
595            i, _ = tuple
596        else:
597            i = len(m.entries)
598        
599        new_bytes = write_cart_to_rom(cart, **opts)
600        m.insert_content(i, name, new_bytes)
601
602    def replace_impl(m, tuple, cart, **opts):
603        i, bytes = tuple
604        new_bytes = write_cart_to_rom(cart, **opts)
605
606        if len(new_bytes) != len(bytes):
607            throw(f"existing cart has size {len(bytes):#x} vs expected {len(new_bytes):#x}")
608        m.replace_content(i, new_bytes)
609
610    def delete_impl(m, tuple):
611        i, _ = tuple
612        m.delete_content(i)
613
614    def rename_impl(m, tuple, name):
615        i, _ = tuple
616        m.rename_content(i, name)
617        
618    def dump_file(m, dest, fmt, misc, i, name, cdata):
619        if name:
620            m.dump_cart(dest, fmt, name, cdata)
621        elif misc:
622            name = m.k_pod_names[i] # names these files have in non-cart pods
623            super().dump_file(dest, fmt, misc, i, name, cdata)
624            
625    @classmethod
626    def create(cls, pico8_dat, cart=None, export_name="", **_):
627        m = PodExport(PodFile.create().data)
628
629        boot_cart = read_cart_from_source(pico8_dat.find_named(m.k_pod_names[0]).decode())
630        if cart:
631            boot_cart.version_id = cart.version_id
632        m.append_content("", write_cart_to_source(boot_cart).encode())
633
634        for pod_i, pod_name in enumerate(m.k_pod_names):
635            if pod_i == 0: # handled above, not a pod
636                continue
637
638            pod = PodFile(pico8_dat.find_named(pod_name))
639            new_pod = PodFile.create(pod.name)
640
641            for i, e in enumerate(pod.entries):
642                content = e.content
643
644                if pod_i == 1 and i == 4:
645                    # this is the window title - it's reinterpreted to a bitmap
646                    assert content.format.bpp == 8
647                    x, y = 0, 0
648                    pixels = content.pixels
649                    for ch in export_name + "\0":
650                        pixels[x, y] = ord(ch)
651                        x += 1
652                        if x == content.width:
653                            x = 0
654                            y += 1
655
656                elif pod_i == 1 and i == 6:
657                    if cart and cart.label:
658                        content = create_screenshot_surface(cart.label)
659
660                new_pod.append_content(e.name, content, compress=isinstance(content, Image))
661
662            m.append_content("", bytes(new_pod.data))
663        return m

A .pod file used in exports, containing one or more carts

PodExport(data)
578    def __init__(m, data):
579        CartExport.__init__(m)
580        PodFile.__init__(m, data)
k_pod_names = ['pod/pico8_boot.p8', 'pod/gfx1.pod', 'pod/f_pico8.pod']
def get_carts_impl(m):
582    def get_carts_impl(m):
583        carts = {}
584        for i, e in enumerate(m.entries):
585            if e.name and isinstance(e.content, bytes): # only carts are named in export pod files
586                carts[e.name] = (i, e.content)
587        return carts
def read_impl(m, tuple, **opts):
589    def read_impl(m, tuple, **opts):
590        _, bytes = tuple
591        return read_cart_from_rom(bytes, **opts)
def insert_impl(m, tuple, name, cart, **opts):
593    def insert_impl(m, tuple, name, cart, **opts):
594        if e(tuple):
595            i, _ = tuple
596        else:
597            i = len(m.entries)
598        
599        new_bytes = write_cart_to_rom(cart, **opts)
600        m.insert_content(i, name, new_bytes)
def replace_impl(m, tuple, cart, **opts):
602    def replace_impl(m, tuple, cart, **opts):
603        i, bytes = tuple
604        new_bytes = write_cart_to_rom(cart, **opts)
605
606        if len(new_bytes) != len(bytes):
607            throw(f"existing cart has size {len(bytes):#x} vs expected {len(new_bytes):#x}")
608        m.replace_content(i, new_bytes)
def delete_impl(m, tuple):
610    def delete_impl(m, tuple):
611        i, _ = tuple
612        m.delete_content(i)
def rename_impl(m, tuple, name):
614    def rename_impl(m, tuple, name):
615        i, _ = tuple
616        m.rename_content(i, name)
def dump_file(m, dest, fmt, misc, i, name, cdata):
618    def dump_file(m, dest, fmt, misc, i, name, cdata):
619        if name:
620            m.dump_cart(dest, fmt, name, cdata)
621        elif misc:
622            name = m.k_pod_names[i] # names these files have in non-cart pods
623            super().dump_file(dest, fmt, misc, i, name, cdata)
@classmethod
def create(cls, pico8_dat, cart=None, export_name='', **_):
625    @classmethod
626    def create(cls, pico8_dat, cart=None, export_name="", **_):
627        m = PodExport(PodFile.create().data)
628
629        boot_cart = read_cart_from_source(pico8_dat.find_named(m.k_pod_names[0]).decode())
630        if cart:
631            boot_cart.version_id = cart.version_id
632        m.append_content("", write_cart_to_source(boot_cart).encode())
633
634        for pod_i, pod_name in enumerate(m.k_pod_names):
635            if pod_i == 0: # handled above, not a pod
636                continue
637
638            pod = PodFile(pico8_dat.find_named(pod_name))
639            new_pod = PodFile.create(pod.name)
640
641            for i, e in enumerate(pod.entries):
642                content = e.content
643
644                if pod_i == 1 and i == 4:
645                    # this is the window title - it's reinterpreted to a bitmap
646                    assert content.format.bpp == 8
647                    x, y = 0, 0
648                    pixels = content.pixels
649                    for ch in export_name + "\0":
650                        pixels[x, y] = ord(ch)
651                        x += 1
652                        if x == content.width:
653                            x = 0
654                            y += 1
655
656                elif pod_i == 1 and i == 6:
657                    if cart and cart.label:
658                        content = create_screenshot_surface(cart.label)
659
660                new_pod.append_content(e.name, content, compress=isinstance(content, Image))
661
662            m.append_content("", bytes(new_pod.data))
663        return m
class PicoDat(PodFile):
665class PicoDat(PodFile):
666    def throw(m, *_, **__):
667        throw("pico dat file can only be used with --dump")
668
669    list_carts = throw
670    read_cart = throw
671    write_cart = throw

A pod file - used in pico8 inside exports/etc

def throw(m, *_, **__):
666    def throw(m, *_, **__):
667        throw("pico dat file can only be used with --dump")
def list_carts(m, *_, **__):
666    def throw(m, *_, **__):
667        throw("pico dat file can only be used with --dump")
def read_cart(m, *_, **__):
666    def throw(m, *_, **__):
667        throw("pico dat file can only be used with --dump")
def write_cart(m, *_, **__):
666    def throw(m, *_, **__):
667        throw("pico dat file can only be used with --dump")
class FullExportBase:
673class FullExportBase:
674    def __init__(m):
675        m.curr_time = time.localtime(maybe_float(os.getenv("PICO8_EXPORT_REPRO_TIME", time.time())))[:6]
676
677    def find_icon_offset_in_exe(m, exe_data):
678        r = BinaryReader(BytesIO(exe_data))
679        assert r.str(2) == "MZ"
680        r.setpos(0x3c)
681        r.setpos(r.u32())
682
683        assert r.str(4) == "PE\0\0"
684        _, num_sections, _, _, _, opt_header_size, _ = r.u16(), r.u16(), r.u32(), r.u32(), r.u32(), r.u16(), r.u16()
685        header_end = r.pos() + opt_header_size
686
687        opt_header = r.u16()
688        assert opt_header in (0x10b, 0x20b)
689        is64 = (opt_header == 0x20b)
690        r.addpos(126 if is64 else 110)
691        rsrc_rva = r.u32()
692
693        r.setpos(header_end)
694        sections = []
695        for _ in range(num_sections):
696            r.addpos(0x8)
697            vsize, vaddr, _, offset = r.u32(), r.u32(), r.u32(), r.u32()
698            r.addpos(0x10)
699            sections.append((vaddr, vsize, offset))
700        
701        def rva_to_offset(rva):
702            for vaddr, vsize, offset in sections:
703                if rva >= vaddr and rva < vaddr + vsize:
704                    return offset + (rva - vaddr)
705
706        rsrc_offset = rva_to_offset(rsrc_rva)
707        if rsrc_offset is None:
708            eprint("no rsrc in exe")
709            return None
710        
711        def find_rsrc_entry(offset, target):
712            if offset & 0x80000000:
713                r.setpos(rsrc_offset + (offset & 0x7fffffff) + 0xc)
714                num_named, num_indexed = r.u16(), r.u16()
715                r.addpos(num_named * 0x8)
716
717                for _ in range(num_indexed):
718                    idx, offset = r.u32(), r.u32()
719                    if idx == target:
720                        return offset
721        
722        icon_entry = find_rsrc_entry(0x80000000, 3)
723        if e(icon_entry):
724            icon_entry = find_rsrc_entry(icon_entry, 1)
725        if e(icon_entry):
726            icon_entry = find_rsrc_entry(icon_entry, 0x409)
727        if icon_entry is None or icon_entry & 0x80000000:
728            eprint("no english icon #1 in exe")
729            return None
730
731        r.setpos(rsrc_offset + icon_entry)
732        icon_rva, icon_size = r.u32(), r.u32()
733        if icon_size != 0x10828:
734            eprint("unknown icon size in exe")
735            return None
736
737        icon_offset = rva_to_offset(icon_rva)
738        assert e(icon_offset)
739        return icon_offset + 0x28
740
741    def create_icns_data(m, raw_data, has_alpha=False):
742        num_chan = 4 if has_alpha else 3
743
744        w = BinaryWriter(big_end=True)
745        w.str("icns")
746        w.u32(0) # filled below
747        w.str("it32")
748        w.u32(0xc + 0x80 * 0x81 * 3)
749        w.u32(0)
750
751        # pico8 doesn't compress, so neither shall we
752        for chan in range(3):
753            for y in range(0x80):
754                w.u8(0x7f)
755                for x in range(0x80):
756                    w.u8(raw_data[(x + y*0x80)*num_chan + chan])
757
758        w.str("t8mk")
759        w.u32(0x8 + 0x80 * 0x80)
760        for y in range(0x80):
761            for x in range(0x80):
762                w.u8(raw_data[(x + y*0x80)*num_chan + 3] if has_alpha else 0xff)
763
764        w.setpos(4)
765        w.u32(w.len())
766        return w.f.getvalue()
767
768    def find_zstr(m, data, prefix, infix):
769        start = 0
770        while True:
771            start = data.find(prefix, start)
772            if start < 0:
773                break
774
775            end = data.find(b"\0", start)
776            if end < 0:
777                break
778            
779            zstr = data[start:end]
780            if infix in zstr:
781                return zstr.decode()
782            
783            start = end + 1
784        
785        return None
786
787    def zip_write(m, zip, dir, name, data, exec=False, is_dir=False):
788
789        info = ZipInfo(dir + "/" + name, m.curr_time)
790        info.create_system = 3 # unix
791        info.external_attr = (0o775 if exec or is_dir else 0o644) << 16
792        if is_dir:
793            info.external_attr |= 0x10 # w/o 0x40000000
794            info.compress_type = ZIP_STORED
795            info.filename += "/"
796            zip.writestr(info, b"") # zip.mkdir is too new...
797        else:
798            info.external_attr |= 0x80000000
799            info.compress_type = ZIP_DEFLATED
800            zip.writestr(info, data)
801    
802    def zip_mkdir(m, zip, dir, name):
803        m.zip_write(zip, dir, name, None, is_dir=True)
804        return dir + "/" + name
def find_icon_offset_in_exe(m, exe_data):
677    def find_icon_offset_in_exe(m, exe_data):
678        r = BinaryReader(BytesIO(exe_data))
679        assert r.str(2) == "MZ"
680        r.setpos(0x3c)
681        r.setpos(r.u32())
682
683        assert r.str(4) == "PE\0\0"
684        _, num_sections, _, _, _, opt_header_size, _ = r.u16(), r.u16(), r.u32(), r.u32(), r.u32(), r.u16(), r.u16()
685        header_end = r.pos() + opt_header_size
686
687        opt_header = r.u16()
688        assert opt_header in (0x10b, 0x20b)
689        is64 = (opt_header == 0x20b)
690        r.addpos(126 if is64 else 110)
691        rsrc_rva = r.u32()
692
693        r.setpos(header_end)
694        sections = []
695        for _ in range(num_sections):
696            r.addpos(0x8)
697            vsize, vaddr, _, offset = r.u32(), r.u32(), r.u32(), r.u32()
698            r.addpos(0x10)
699            sections.append((vaddr, vsize, offset))
700        
701        def rva_to_offset(rva):
702            for vaddr, vsize, offset in sections:
703                if rva >= vaddr and rva < vaddr + vsize:
704                    return offset + (rva - vaddr)
705
706        rsrc_offset = rva_to_offset(rsrc_rva)
707        if rsrc_offset is None:
708            eprint("no rsrc in exe")
709            return None
710        
711        def find_rsrc_entry(offset, target):
712            if offset & 0x80000000:
713                r.setpos(rsrc_offset + (offset & 0x7fffffff) + 0xc)
714                num_named, num_indexed = r.u16(), r.u16()
715                r.addpos(num_named * 0x8)
716
717                for _ in range(num_indexed):
718                    idx, offset = r.u32(), r.u32()
719                    if idx == target:
720                        return offset
721        
722        icon_entry = find_rsrc_entry(0x80000000, 3)
723        if e(icon_entry):
724            icon_entry = find_rsrc_entry(icon_entry, 1)
725        if e(icon_entry):
726            icon_entry = find_rsrc_entry(icon_entry, 0x409)
727        if icon_entry is None or icon_entry & 0x80000000:
728            eprint("no english icon #1 in exe")
729            return None
730
731        r.setpos(rsrc_offset + icon_entry)
732        icon_rva, icon_size = r.u32(), r.u32()
733        if icon_size != 0x10828:
734            eprint("unknown icon size in exe")
735            return None
736
737        icon_offset = rva_to_offset(icon_rva)
738        assert e(icon_offset)
739        return icon_offset + 0x28
def create_icns_data(m, raw_data, has_alpha=False):
741    def create_icns_data(m, raw_data, has_alpha=False):
742        num_chan = 4 if has_alpha else 3
743
744        w = BinaryWriter(big_end=True)
745        w.str("icns")
746        w.u32(0) # filled below
747        w.str("it32")
748        w.u32(0xc + 0x80 * 0x81 * 3)
749        w.u32(0)
750
751        # pico8 doesn't compress, so neither shall we
752        for chan in range(3):
753            for y in range(0x80):
754                w.u8(0x7f)
755                for x in range(0x80):
756                    w.u8(raw_data[(x + y*0x80)*num_chan + chan])
757
758        w.str("t8mk")
759        w.u32(0x8 + 0x80 * 0x80)
760        for y in range(0x80):
761            for x in range(0x80):
762                w.u8(raw_data[(x + y*0x80)*num_chan + 3] if has_alpha else 0xff)
763
764        w.setpos(4)
765        w.u32(w.len())
766        return w.f.getvalue()
def find_zstr(m, data, prefix, infix):
768    def find_zstr(m, data, prefix, infix):
769        start = 0
770        while True:
771            start = data.find(prefix, start)
772            if start < 0:
773                break
774
775            end = data.find(b"\0", start)
776            if end < 0:
777                break
778            
779            zstr = data[start:end]
780            if infix in zstr:
781                return zstr.decode()
782            
783            start = end + 1
784        
785        return None
def zip_write(m, zip, dir, name, data, exec=False, is_dir=False):
787    def zip_write(m, zip, dir, name, data, exec=False, is_dir=False):
788
789        info = ZipInfo(dir + "/" + name, m.curr_time)
790        info.create_system = 3 # unix
791        info.external_attr = (0o775 if exec or is_dir else 0o644) << 16
792        if is_dir:
793            info.external_attr |= 0x10 # w/o 0x40000000
794            info.compress_type = ZIP_STORED
795            info.filename += "/"
796            zip.writestr(info, b"") # zip.mkdir is too new...
797        else:
798            info.external_attr |= 0x80000000
799            info.compress_type = ZIP_DEFLATED
800            zip.writestr(info, data)
def zip_mkdir(m, zip, dir, name):
802    def zip_mkdir(m, zip, dir, name):
803        m.zip_write(zip, dir, name, None, is_dir=True)
804        return dir + "/" + name
class FullExport(CartExport, FullExportBase):
806class FullExport(CartExport, FullExportBase):
807    def __init__(m, pico8_dat, cart):
808        super().__init__()
809        m.pico8_dat = pico8_dat
810        m.cart = cart
811
812    @classmethod
813    def create(cls, pico8_dat, cart=None, export_name="", **opts):
814        opts["cart"] = cart
815        opts["export_name"] = export_name
816
817        m = FullExport(pico8_dat, cart)
818        m.html_pod = PodFile(pico8_dat.find_named("pod/f_html5.pod"))
819        m.bin_pod = PodFile(pico8_dat.find_named("pod/f_bin.pod"))
820
821        m.pod = PodExport.create(pico8_dat, **opts)
822        m.js = JsExport.create(pico8_dat, html_pod=m.html_pod, **opts)
823        m.wjs = JsExport.create(pico8_dat, html_pod=m.html_pod, for_wasm=True, **opts)
824        m.exports = [m.pod, m.js, m.wjs]
825        
826        m.export_name = export_name
827        return m
828
829    def write_cart(m, *args, **opts):
830        for export in m.exports:
831            export.write_cart(*args, **opts)
832
833    def zip_copy(m, zip, dir, pod, exclude=None):
834        for e in pod.entries:
835            if e.name and e.name.startswith("./"): # many unnamed entries?
836                if exclude and exclude in e.name:
837                    continue
838
839                exec = "." not in path_basename(e.name) # ???
840                is_dir = not e.content # ???
841                m.zip_write(zip, dir, e.name[2:], e.content, exec=exec, is_dir=is_dir)
842
843    def save(m, path, delete_existing=False):
844        dir_create(path, delete_existing=delete_existing)
845        basename = m.export_name
846
847        label_bmpdata = None
848        label_icnsdata = None
849        label_png = None
850        label_url = ""
851        if m.cart and m.cart.label:
852            label = create_screenshot_surface(m.cart.label)
853            label_bmpdata = label.to_data(PixelFormat.bgra8, flip=True)
854            label_icnsdata = label.to_data(PixelFormat.rgb8)
855            label_png = label.convert(PixelFormat.rgb8).save()
856            label_url = "data:image/png;base64," + base64.b64encode(label_png).decode()
857        
858        html_data = m.html_pod.find_named("src/shell.html").decode()
859        html_data = html_data.replace("##js_file##", "%s.js" % basename)
860        html_data = html_data.replace("##label_file##", label_url)
861        
862        html_path = path_join(path, "%s_html" % basename)
863        dir_ensure_exists(html_path)
864        file_write_text(path_join(html_path, "%s.html" % basename), html_data)
865        file_write_text(path_join(html_path, "%s.js" % basename), m.js.text)
866        
867        html_path = path_join(path, "%s_wasm" % basename)
868        dir_ensure_exists(html_path)
869        file_write_text(path_join(html_path, "%s.html" % basename), html_data)
870        file_write(path_join(html_path, "%s.wasm" % basename), m.html_pod.find_named("src/pico8_wasm.wasm"))
871        file_write_text(path_join(html_path, "%s.js" % basename), m.wjs.text.replace("pico8_wasm.wasm", "%s.wasm" % basename))
872
873        exe_data = m.bin_pod.find_named("bin/pico8.exe")
874        if label_bmpdata:
875            exe_icon_i = m.find_icon_offset_in_exe(exe_data)
876            if e(exe_icon_i):
877                exe_data = str_replace_at(exe_data, exe_icon_i, 0x10000, label_bmpdata)
878            else:
879                eprint("couldn't find icon in exe, not changing it")
880
881        win_dir = "%s_windows" % basename
882        with ZipFile(path_join(path, win_dir + ".zip"), "w") as win_zip:
883            m.zip_write(win_zip, win_dir, "%s.exe" % basename, exe_data, exec=True)
884            m.zip_write(win_zip, win_dir, "data.pod", m.pod.data)
885            m.zip_write(win_zip, win_dir, "SDL2.dll", m.bin_pod.find_named("bin/SDL2.dll"))
886
887        linux_dir = "%s_linux" % basename
888        with ZipFile(path_join(path, linux_dir + ".zip"), "w") as linux_zip:
889            m.zip_write(linux_zip, linux_dir, "data.pod", m.pod.data)
890            if label_png: m.zip_write(linux_zip, linux_dir, "%s.png" % basename, label_png)
891            m.zip_write(linux_zip, linux_dir, basename, m.bin_pod.find_named("bin/pico8_dyn.amd64"), exec=True)
892        
893        raspi_dir = "%s_raspi" % basename
894        with ZipFile(path_join(path, raspi_dir + ".zip"), "w") as raspi_zip:
895            m.zip_write(raspi_zip, raspi_dir, "data.pod", m.pod.data)
896            if label_png: m.zip_write(raspi_zip, raspi_dir, "%s.png" % basename, label_png)
897            for suffix, content in m.bin_pod.find_prefix("builds/pi_builds/pico8_player"):
898                m.zip_write(raspi_zip, raspi_dir, basename + suffix, content, exec=True)
899
900        if label_icnsdata:
901            icns_data = m.create_icns_data(label_icnsdata) # doesn't seem to use "builds/osx_builds/pico8.icns" in the pod
902        else:
903            icns_data = m.bin_pod.find_named("builds/osx_builds/pico8.icns")
904
905        # unfortunately, the plist template isn't in the pods - only in the exe. well, the exe's in the pod, so...
906        info_plist = m.find_zstr(exe_data, b"<?xml", b"<key>CFBundleExecutable</key>")
907        if info_plist is None: # in case it's ever not there anymore
908            info_plist = file_read_text(path_join(get_res_path(), "template.plist"))
909        info_plist = info_plist.replace("%s.%s", "pico8_author.%s" % basename)
910        info_plist = info_plist.replace("%s", basename)
911
912        osx_dir = "%s.app" % basename
913        with ZipFile(path_join(path, "%s_osx.zip" % basename), "w") as osx_zip:
914            osx_cont_dir = m.zip_mkdir(osx_zip, osx_dir, "Contents")
915            osx_mac_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "MacOS")
916            osx_res_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "Resources")
917            m.zip_write(osx_zip, osx_mac_dir, "data.pod", m.pod.data)
918            m.zip_write(osx_zip, osx_mac_dir, basename, m.bin_pod.find_named("builds/osx_builds/pico8_player"), exec=True)
919            m.zip_write(osx_zip, osx_res_dir, "%s.icns" % basename, icns_data)
920            m.zip_write(osx_zip, osx_cont_dir, "Info.plist", info_plist.encode())
921
922            osx_sdlfw_pod = PodFile(list(m.bin_pod.find_prefix("builds/osx_builds/sdl2_framework"))[0][1])
923            osx_fw_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "Frameworks")
924            osx_sdlfw_dir = m.zip_mkdir(osx_zip, osx_fw_dir, "SDL2.framework")
925            m.zip_copy(osx_zip, osx_sdlfw_dir, osx_sdlfw_pod, exclude="/_CodeSignature")
926            osx_sdlver_dir = m.zip_mkdir(osx_zip, osx_sdlfw_dir, "Versions")
927            m.zip_copy(osx_zip, m.zip_mkdir(osx_zip, osx_sdlver_dir, "Current"), osx_sdlfw_pod)
928            m.zip_copy(osx_zip, m.zip_mkdir(osx_zip, osx_sdlver_dir, "A"), osx_sdlfw_pod)

A container of multiple carts

FullExport(pico8_dat, cart)
807    def __init__(m, pico8_dat, cart):
808        super().__init__()
809        m.pico8_dat = pico8_dat
810        m.cart = cart
@classmethod
def create(cls, pico8_dat, cart=None, export_name='', **opts):
812    @classmethod
813    def create(cls, pico8_dat, cart=None, export_name="", **opts):
814        opts["cart"] = cart
815        opts["export_name"] = export_name
816
817        m = FullExport(pico8_dat, cart)
818        m.html_pod = PodFile(pico8_dat.find_named("pod/f_html5.pod"))
819        m.bin_pod = PodFile(pico8_dat.find_named("pod/f_bin.pod"))
820
821        m.pod = PodExport.create(pico8_dat, **opts)
822        m.js = JsExport.create(pico8_dat, html_pod=m.html_pod, **opts)
823        m.wjs = JsExport.create(pico8_dat, html_pod=m.html_pod, for_wasm=True, **opts)
824        m.exports = [m.pod, m.js, m.wjs]
825        
826        m.export_name = export_name
827        return m
def write_cart(m, *args, **opts):
829    def write_cart(m, *args, **opts):
830        for export in m.exports:
831            export.write_cart(*args, **opts)
def zip_copy(m, zip, dir, pod, exclude=None):
833    def zip_copy(m, zip, dir, pod, exclude=None):
834        for e in pod.entries:
835            if e.name and e.name.startswith("./"): # many unnamed entries?
836                if exclude and exclude in e.name:
837                    continue
838
839                exec = "." not in path_basename(e.name) # ???
840                is_dir = not e.content # ???
841                m.zip_write(zip, dir, e.name[2:], e.content, exec=exec, is_dir=is_dir)
def save(m, path, delete_existing=False):
843    def save(m, path, delete_existing=False):
844        dir_create(path, delete_existing=delete_existing)
845        basename = m.export_name
846
847        label_bmpdata = None
848        label_icnsdata = None
849        label_png = None
850        label_url = ""
851        if m.cart and m.cart.label:
852            label = create_screenshot_surface(m.cart.label)
853            label_bmpdata = label.to_data(PixelFormat.bgra8, flip=True)
854            label_icnsdata = label.to_data(PixelFormat.rgb8)
855            label_png = label.convert(PixelFormat.rgb8).save()
856            label_url = "data:image/png;base64," + base64.b64encode(label_png).decode()
857        
858        html_data = m.html_pod.find_named("src/shell.html").decode()
859        html_data = html_data.replace("##js_file##", "%s.js" % basename)
860        html_data = html_data.replace("##label_file##", label_url)
861        
862        html_path = path_join(path, "%s_html" % basename)
863        dir_ensure_exists(html_path)
864        file_write_text(path_join(html_path, "%s.html" % basename), html_data)
865        file_write_text(path_join(html_path, "%s.js" % basename), m.js.text)
866        
867        html_path = path_join(path, "%s_wasm" % basename)
868        dir_ensure_exists(html_path)
869        file_write_text(path_join(html_path, "%s.html" % basename), html_data)
870        file_write(path_join(html_path, "%s.wasm" % basename), m.html_pod.find_named("src/pico8_wasm.wasm"))
871        file_write_text(path_join(html_path, "%s.js" % basename), m.wjs.text.replace("pico8_wasm.wasm", "%s.wasm" % basename))
872
873        exe_data = m.bin_pod.find_named("bin/pico8.exe")
874        if label_bmpdata:
875            exe_icon_i = m.find_icon_offset_in_exe(exe_data)
876            if e(exe_icon_i):
877                exe_data = str_replace_at(exe_data, exe_icon_i, 0x10000, label_bmpdata)
878            else:
879                eprint("couldn't find icon in exe, not changing it")
880
881        win_dir = "%s_windows" % basename
882        with ZipFile(path_join(path, win_dir + ".zip"), "w") as win_zip:
883            m.zip_write(win_zip, win_dir, "%s.exe" % basename, exe_data, exec=True)
884            m.zip_write(win_zip, win_dir, "data.pod", m.pod.data)
885            m.zip_write(win_zip, win_dir, "SDL2.dll", m.bin_pod.find_named("bin/SDL2.dll"))
886
887        linux_dir = "%s_linux" % basename
888        with ZipFile(path_join(path, linux_dir + ".zip"), "w") as linux_zip:
889            m.zip_write(linux_zip, linux_dir, "data.pod", m.pod.data)
890            if label_png: m.zip_write(linux_zip, linux_dir, "%s.png" % basename, label_png)
891            m.zip_write(linux_zip, linux_dir, basename, m.bin_pod.find_named("bin/pico8_dyn.amd64"), exec=True)
892        
893        raspi_dir = "%s_raspi" % basename
894        with ZipFile(path_join(path, raspi_dir + ".zip"), "w") as raspi_zip:
895            m.zip_write(raspi_zip, raspi_dir, "data.pod", m.pod.data)
896            if label_png: m.zip_write(raspi_zip, raspi_dir, "%s.png" % basename, label_png)
897            for suffix, content in m.bin_pod.find_prefix("builds/pi_builds/pico8_player"):
898                m.zip_write(raspi_zip, raspi_dir, basename + suffix, content, exec=True)
899
900        if label_icnsdata:
901            icns_data = m.create_icns_data(label_icnsdata) # doesn't seem to use "builds/osx_builds/pico8.icns" in the pod
902        else:
903            icns_data = m.bin_pod.find_named("builds/osx_builds/pico8.icns")
904
905        # unfortunately, the plist template isn't in the pods - only in the exe. well, the exe's in the pod, so...
906        info_plist = m.find_zstr(exe_data, b"<?xml", b"<key>CFBundleExecutable</key>")
907        if info_plist is None: # in case it's ever not there anymore
908            info_plist = file_read_text(path_join(get_res_path(), "template.plist"))
909        info_plist = info_plist.replace("%s.%s", "pico8_author.%s" % basename)
910        info_plist = info_plist.replace("%s", basename)
911
912        osx_dir = "%s.app" % basename
913        with ZipFile(path_join(path, "%s_osx.zip" % basename), "w") as osx_zip:
914            osx_cont_dir = m.zip_mkdir(osx_zip, osx_dir, "Contents")
915            osx_mac_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "MacOS")
916            osx_res_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "Resources")
917            m.zip_write(osx_zip, osx_mac_dir, "data.pod", m.pod.data)
918            m.zip_write(osx_zip, osx_mac_dir, basename, m.bin_pod.find_named("builds/osx_builds/pico8_player"), exec=True)
919            m.zip_write(osx_zip, osx_res_dir, "%s.icns" % basename, icns_data)
920            m.zip_write(osx_zip, osx_cont_dir, "Info.plist", info_plist.encode())
921
922            osx_sdlfw_pod = PodFile(list(m.bin_pod.find_prefix("builds/osx_builds/sdl2_framework"))[0][1])
923            osx_fw_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "Frameworks")
924            osx_sdlfw_dir = m.zip_mkdir(osx_zip, osx_fw_dir, "SDL2.framework")
925            m.zip_copy(osx_zip, osx_sdlfw_dir, osx_sdlfw_pod, exclude="/_CodeSignature")
926            osx_sdlver_dir = m.zip_mkdir(osx_zip, osx_sdlfw_dir, "Versions")
927            m.zip_copy(osx_zip, m.zip_mkdir(osx_zip, osx_sdlver_dir, "Current"), osx_sdlfw_pod)
928            m.zip_copy(osx_zip, m.zip_mkdir(osx_zip, osx_sdlver_dir, "A"), osx_sdlfw_pod)
def read_pod_file(path):
930def read_pod_file(path):
931    return PodFile(file_read(path))
def read_cart_export(path, format):
933def read_cart_export(path, format):
934    """Read a CartExport from the given path, assuming it is in the given format"""
935    if format == CartFormat.js:
936        return JsExport(file_read_text(path))
937    if format == CartFormat.pod:
938        return PodExport(file_read(path))
939    if format == CartFormat.dat:
940        return PicoDat(file_read(path))
941    else:
942        throw(f"invalid export format: {format}")

Read a CartExport from the given path, assuming it is in the given format

def write_cart_export(path, export, delete_existing=False):
944def write_cart_export(path, export, delete_existing=False):
945    """Write a CartExport to the given path"""
946    if isinstance(export, JsExport):
947        file_write_text(path, export.text)
948    elif isinstance(export, PodExport):
949        file_write(path, export.data)
950    elif isinstance(export, FullExport):
951        export.save(path, delete_existing)
952    else:
953        fail("invalid cart export")

Write a CartExport to the given path

def create_cart_export(format, pico8_dat, **opts):
955def create_cart_export(format, pico8_dat, **opts):
956    """Create an empty CartExport in the given format"""
957    if format == CartFormat.js:
958        return JsExport.create(pico8_dat, **opts)
959    elif format == CartFormat.pod:
960        return PodExport.create(pico8_dat, **opts)
961    elif format == CartFormat.bin:
962        return FullExport.create(pico8_dat, **opts)
963    else:
964        throw(f"invalid export format: {format}")

Create an empty CartExport in the given format

def read_from_cart_export(path, format, cart_name=None, extra_carts=None, **opts):
966def read_from_cart_export(path, format, cart_name=None, extra_carts=None, **opts):
967    """Read a cart or carts from a cart export"""
968    export = read_cart_export(path, format)
969
970    if e(extra_carts):
971        assert not cart_name
972        main_cart = None
973        for cart in export.list_carts():
974            if main_cart:
975                extra_carts.append(export.read_cart(cart, **opts))
976            else:
977                main_cart = export.read_cart(cart, **opts)
978        return main_cart
979    else:
980        return export.read_cart(cart_name, **opts)

Read a cart or carts from a cart export

def write_to_cart_export( path, cart, format, extra_carts=None, cart_name=None, target_name=None, cart_op=None, target_export=None, export_name=None, pico_dat=None, delete_existing=False, **opts):
 982def write_to_cart_export(path, cart, format, extra_carts=None, cart_name=None, target_name=None, cart_op=None, 
 983                         target_export=None, export_name=None, pico_dat=None, delete_existing=False, **opts):
 984    """Create or edit a CartExport in the given path, depending on cart_op/cart_args arguments"""
 985    if not export_name:
 986        export_name = path_basename_no_extension(path)
 987
 988    if cart_op is None:
 989        assert isinstance(pico_dat, PodFile)
 990        export = create_cart_export(format, pico_dat, cart=cart, export_name=export_name)
 991    else:
 992        assert isinstance(target_export, CartExport)
 993        export = target_export
 994        
 995    export.write_cart(cart, cart_name, cart_op, target_name, **opts)
 996    if extra_carts:
 997        for extra_cart in extra_carts:
 998            export.write_cart(extra_cart, **opts)
 999    
1000    write_cart_export(path, export, delete_existing)

Create or edit a CartExport in the given path, depending on cart_op/cart_args arguments