picotron_cart

Functions for reading/writing picotron carts

  1"""Functions for reading/writing picotron carts"""
  2
  3from utils import *
  4from media_utils import Image, Color, PixelFormat
  5from pico_cart import load_image_of_size, get_res_path, pico_base64_decode, pico_base64_encode
  6from pico_cart import k_png_header, k_qoi_header
  7from pico_export import lz4_uncompress, lz4_compress
  8from pico_defs import decode_luastr, encode_luastr
  9from pico_compress import print_size, compress_code, uncompress_code, encode_p8str, decode_p8str
 10from picotron_defs import get_default_picotron_runtime, get_picotron_version_id, Cart64Glob, k_palette_64
 11from picotron_fs import PicotronFile, PicotronDir, k_pod, k_pod_prefix_strs, UserData
 12
 13class Cart64Format(Enum):
 14    """An enum representing the supported cart formats"""
 15    auto = p64 = png = rom = tiny_rom = lua = pod = dir = dat = html = bin = fs = label = ...
 16    
 17    @property
 18    def is_input(m):
 19        return m != m.bin
 20    @property
 21    def is_output(m):
 22        return m != m.auto
 23    @property
 24    def is_ext(m):
 25        return m not in (m.auto, m.dir, m.fs, m.label, m.tiny_rom)
 26    @property
 27    def is_src(m):
 28        return m in (m.p64, m.lua, m.pod, m.dir, m.fs)
 29    @property
 30    def is_export(m):
 31        return m in (m.dat, m.html, m.bin)
 32    @property
 33    def is_exposed(m):
 34        return m != m.fs
 35    
 36    @classproperty
 37    def default_src(m):
 38        return m.p64
 39    @classproperty
 40    def default_dir(m):
 41        return m.dir
 42
 43k_info_file = ".info.pod"
 44k_label_png_file = "label.png"
 45k_label_qoi_file = "label.qoi"
 46k_label_files = (k_label_qoi_file, k_label_png_file)
 47
 48class Cart64:
 49    """A picotron cart - a collection of all its files"""
 50    def __init__(m, path="", name=""):
 51        m.version_id = get_picotron_version_id(get_default_picotron_runtime())
 52        m.path = path
 53        m.name = name if name else path_basename(path) if path else ""
 54        m.files = {}
 55        m.raw_title = m.raw_label = m.raw_icon = m.raw_home = m.raw_runtime_version = None
 56
 57    @property
 58    def metadata(m):
 59        info = m.files.get(k_info_file)
 60        return info.metadata if info else None
 61
 62    def set_metadata(m, key, value):
 63        info = m.files.get(k_info_file)
 64        if info and e(meta := info.metadata):
 65            meta[key] = value
 66            info.metadata = meta
 67            return True
 68
 69    @property
 70    def title(m):
 71        if e(m.raw_title):
 72            return m.raw_title
 73
 74        meta = m.metadata
 75        if not meta:
 76            return ()
 77        title = str(meta.get("title", ""))
 78        version = str(meta.get("version", ""))
 79        author = str(meta.get("author", ""))
 80        return (title, " ".join((version, ("by " + author if author else ""))))
 81
 82    def set_raw_title(m, title_lines):
 83        m.raw_title = title_lines
 84
 85    @property
 86    def label(m):
 87        if m.raw_label:
 88            return m.raw_label
 89        
 90        for label_file in k_label_files:
 91            label = m.files.get(label_file)
 92            if e(label):
 93                return label_file, label
 94        
 95        return None, None
 96
 97    def load_label(m):
 98        label_file, label = m.label
 99        if label:
100            try:
101                check(label.is_raw, "label is not a raw file")
102                return load_image_of_size(BytesIO(label.raw_payload), k_label_size, is_qoi=label_file == k_label_qoi_file)
103            except CheckError as e:
104                eprint("ignoring invalid label due to: %s" % e)
105    
106    def set_raw_label(m, label_file, label):
107        m.raw_label = (label_file, label)
108
109    @property
110    def icon(m):
111        if m.raw_icon:
112            return m.raw_icon
113
114        meta = m.metadata
115        icon = meta.get("icon") if meta else None
116        return icon if isinstance(icon, UserData) else None
117
118    def load_icon(m):
119        icon = m.icon
120        if icon and icon.type == "u8" and icon.width and icon.height:
121            data = bytearray()
122            for i in bytes.fromhex(icon.data):
123                if i >= len(k_palette_64):
124                    i = 0
125                data += bytes(k_palette_64[i] if i else Color(0, 0, 0, 0))
126            return Image.from_data(icon.width, icon.height, PixelFormat.rgba8, data)
127
128    def set_raw_icon(m, icon):
129        m.raw_icon = icon
130
131    @property
132    def export_home(m):
133        if e(m.raw_home):
134            return m.raw_home
135        meta = m.metadata
136        home = meta.get("export_home") if meta else None
137        return home if isinstance(home, str) else ""
138
139    def set_raw_export_home(m, value):
140        m.raw_home = value
141
142    def get_runtime_version(m, default=sys.maxsize):
143        if e(m.raw_runtime_version):
144            return m.raw_runtime_version
145        meta = m.metadata
146        runtime = meta.get("runtime") if meta else None
147        return runtime if isinstance(runtime, (int, float)) else default
148
149    @lazy_property
150    def runtime_version(m):
151        return m.get_runtime_version()
152
153    def set_raw_runtime_version(m, runtime):
154        m.raw_runtime_version = runtime
155
156    def set_version(m, runtime):
157        m.set_raw_runtime_version(runtime)
158        m.version_id = get_picotron_version_id(runtime)
159        m.set_metadata("runtime", runtime)
160    
161k_cart64_size = 0x40000 # + 0x2000 ?
162k_rom_header_sig = b"p64"
163k_rom_header_size = 8
164
165def print_rom_compressed_size(size, **kwargs):
166    print_size("compressed", size, k_cart64_size, **kwargs)
167
168def read_cart64_from_rom(buffer, path=None, allow_tiny=False, size_handler=None, debug_handler=None, **opts):
169    cart = Cart64(path=path)
170    
171    with BinaryReader(BytesIO(buffer)) as r:
172        if r.bytes(3) == k_rom_header_sig:
173            cart.version_id = r.u8()
174            size = r.u32()
175            if size_handler:
176                print_rom_compressed_size(k_rom_header_size + size, prefix="input", handler=size_handler)
177            uncbuffer = lz4_uncompress(r.bytes(size), debug=debug_handler)
178            
179            with BinaryReader(BytesIO(uncbuffer)) as r:
180                while not r.eof():
181                    fspath = decode_luastr(r.zbytes())
182                    if fspath.endswith("/"):
183                        cart.files[fspath] = PicotronDir()
184                    else:
185                        size = r.u8()
186                        if size == 0xff:
187                            size = r.u32()
188                        data = r.bytes(size)
189
190                        cart.files[fspath] = PicotronFile(data)
191            return cart
192        
193        elif allow_tiny:
194            r.rewind()
195            r.big_end = True
196            tiny_cart = Cart64()
197            tiny_code = encode_p8str(uncompress_code(r, max_code_size=sys.maxsize, **opts))
198            tiny_cart.files[k_p64_main_path] = PicotronFile(tiny_code)
199            return tiny_cart
200
201        else:
202            throw("wrong rom header")
203
204def ext_order_key(pair):
205    # try to order things to maximize compression
206    dirname, filename = str_split_last(pair[0], "/")
207    if filename == "":
208        # put all directories first and in proper order, in case it matters
209        return (-10, "", dirname, filename) # (intentionally reversed from below)
210    
211    ext = path_extension(filename)
212    if filename == "main.lua":
213        order = 1
214    elif ext == ".lua":
215        order = 0
216    elif ext == ".pod":
217        order = 2
218    elif ext == ".gfx":
219        order = 3
220    elif ext == ".sfx":
221        order = 4
222    elif ext == ".map":
223        order = 5
224    else:
225        order = 6
226    return (order, ext, filename, dirname)
227
228def write_cart64_to_rom(cart, size_handler=None, debug_handler=None, padding=0,
229                        limit=None, fast_compress=False, **opts):
230    io = BytesIO()
231
232    with BinaryWriter(io) as w:
233        for fspath, file in sorted(cart.files.items(), key=ext_order_key):
234            w.zbytes(encode_luastr(fspath))
235            check(not fspath.endswith("/") == e(file.data), "wrong picotron file/directory path")
236            if e(file.data):
237                data = file.data
238                if len(data) < 0xff:
239                    w.u8(len(data))
240                else:
241                    w.u8(0xff)
242                    w.u32(len(data))
243                w.bytes(data)
244
245        compressed = lz4_compress(io.getvalue(), fast=fast_compress, debug=debug_handler)
246    
247    size = k_rom_header_size + len(compressed)
248    if size_handler:
249        print_rom_compressed_size(size, handler=size_handler)
250    if limit:
251        check(size <= limit, "cart takes too much compressed space!")
252    
253    io = BytesIO()
254    with BinaryWriter(io) as w:
255        w.bytes(k_rom_header_sig)
256        w.u8(cart.version_id)
257        w.u32(len(compressed))
258        w.bytes(compressed)
259
260        for _ in range(padding):
261            w.u8(0)
262
263        return io.getvalue()
264
265def write_cart64_to_tiny_rom(cart, size_handler=None, debug_handler=None, **opts):
266    main = cart.files.get(k_p64_main_path)
267    check(main, f"{k_p64_main_path} not found in cart")
268    data = main.raw_payload
269
270    tiny_cart = Cart64()
271    tiny_cart.files[k_p64_main_path] = PicotronFile(data)
272    compressed_lz4 = write_cart64_to_rom(tiny_cart, debug_handler=debug_handler, **opts)
273
274    io = BytesIO()
275    with BinaryWriter(io, big_end = True) as w:
276        compress_code(w, decode_p8str(data), force_compress=True)
277        compressed_pxa = io.getvalue()
278
279    result = data
280    if len(compressed_pxa) < len(result):
281        result = compressed_pxa
282    if len(compressed_lz4) < len(result):
283        result = compressed_lz4
284
285    if size_handler:
286        print_rom_compressed_size(len(result), handler=size_handler)
287
288    return result
289    
290k_cart64_image_size = Point(512, 384)
291k_label_size = Point(480, 270)
292k_label_offset = Point(16, 38)
293k_title_offset = Point(80, 330)
294k_title_width = 352 # ?
295k_subtitle_suboffset = Point(0, 26)
296
297def read_cart64_from_image(data, **opts):
298    image = load_image_of_size(BytesIO(data), k_cart64_image_size)
299    width, height = image.size
300
301    io = BytesIO()
302    pixels = image.pixels
303
304    with BinaryBitWriter(io) as bw:
305        for y in range(height):
306            for x in range(width):
307                r, g, b, a = pixels[x, y]
308                bw.bits(11, (r & 7) | ((g & 7) << 3) | ((b & 7) << 6) | ((a & 3) << 9))
309
310        data = io.getvalue()
311
312    cart = read_cart64_from_rom(data, **opts)
313
314    _, label = cart.label
315    if label is None:
316        label = Image.create(*k_label_size)
317        label_pixels = label.pixels
318        
319        for y in range(k_label_size.y):
320            for x in range(k_label_size.x):
321                r, g, b, a = pixels[k_label_offset.x + x, k_label_offset.y + y]
322                label_pixels[x, y] = (r & ~7, g & ~7, b & ~7, 0xff)
323
324        try:
325            cart.files[k_label_qoi_file] = PicotronFile(label.save(format="qoi"))
326        except KeyError:
327            cart.files[k_label_png_file] = PicotronFile(label.save())
328    
329    return cart
330
331def draw_title_on_image(image, title, subtitle, offset, width, suboffset):
332    # TODO: there seems to be some kerning?!
333
334    with file_open(path_join(get_res_path(), "font64.png")) as font_f:
335        font_surf = Image.load(font_f).alpha
336        font_pixels = font_surf.pixels
337        char_widths = {}
338
339        for sub in (False, True):
340            scale = 1 if sub else 2
341
342            if sub:
343                color = Color.gray(0x90)
344                scaled_surf = font_surf
345                color2 = scaled_surf2 = None
346            else:
347                color = Color.gray(0xd0)
348                scaled_surf = font_surf.scale(2)
349                color2 = Color.gray(0x80)
350                scaled_surf2 = scaled_surf.copy()
351                for y in range(scaled_surf.height):
352                    (scaled_surf if y % 2 else scaled_surf2).fill(0, Rect(0, y, scaled_surf.width, 1))
353            
354            x, y = 0, 0
355            for ch in title:
356                chi = ord(ch)
357                ch_x, ch_y = chi % 16 * 10, chi // 16 * 11
358                ch_w = char_widths.get(chi)
359                if ch_w is None:
360                    ch_w = 0
361                    while font_pixels[ch_x + ch_w, ch_y + 9]: # using an "underline" to measure char advance
362                        ch_w += 1
363                    char_widths[chi] = ch_w
364                
365                chrect = Rect(ch_x * scale, ch_y * scale, ch_w * scale, 9 * scale)
366                new_x = x + chrect.w
367                if new_x <= width:
368                    dest = Rect.from_pos_size(offset + Point (x, y), chrect.size)
369                    image.fill(color, dest, scaled_surf.slice(chrect))
370                    if scaled_surf2:
371                        image.fill(color2, dest, scaled_surf2.slice(chrect))
372                x = new_x
373            
374            offset += suboffset
375            title = subtitle
376
377def write_cart64_to_image(cart, template_image=None, template_only=False, optimize_image=False, **opts):
378    output = write_cart64_to_rom(cart, limit=k_cart64_size, padding=4, **opts) # some padding to easily tell when we're done without failing
379    end_pos = len(output) - 2
380
381    if not template_image:
382        template_image = path_join(get_res_path(), "template64.png")
383
384    with file_open(template_image) as template_f:
385        image = load_image_of_size(template_f, k_cart64_image_size)
386        width, height = image.size
387
388        if not template_only:
389            label = cart.load_label()
390            if label:
391                image.draw(label, k_label_offset)
392            
393            title = cart.title
394            if title:
395                draw_title_on_image(image, *list_unpack(title, 2), k_title_offset, k_title_width, k_subtitle_suboffset)
396        
397        pixels = image.pixels
398
399        with BinaryBitReader(BytesIO(output)) as br:
400            for y in range(height):
401                for x in range(width):
402                    word = br.bits(11) if br.pos() < end_pos else 0
403                    r, g, b, a = pixels[x,y]
404                    r = (r & ~7) | (word & 7)
405                    g = (g & ~7) | ((word >> 3) & 7)
406                    b = (b & ~7) | ((word >> 6) & 7)
407                    a = (a & ~3) | ((word >> 9) & 3)
408                    pixels[x, y] = (r, g, b, a)
409
410        if optimize_image:
411            return image.save(optimize=True)
412        else:
413            return image.save()
414
415def read_cart64_label(data, path=None, **_):
416    cart = Cart64(path=path)
417    if data.startswith(k_png_header):
418        label_file = k_label_png_file
419    elif data.startswith(k_qoi_header):
420        label_file = k_label_qoi_file
421    else:
422        throw("label in unexpected format")
423    
424    cart.files[label_file] = PicotronFile(data)
425    return cart
426
427def write_cart64_label(cart, **_):
428    label = cart.load_label()
429    if label:
430        return label.save()
431    else:
432        throw("no label to write")
433
434k_p64_prefix = b"picotron cartridge"
435k_p64_main_path = "main.lua"
436k_p64_file_prefix = b":: "
437k_p64_b64_prefix = b"b64$"
438k_p64_b64_line_size = 76
439k_p64_end_file = "[eoc]"
440
441def read_cart64_from_source(data, path=None, raw=False, **_):
442    cart = Cart64(path=path)
443    
444    if not raw and not data.startswith(k_p64_prefix) and not data.startswith(k_p64_file_prefix): # fallback to raw
445        raw = True
446
447    fspath = k_p64_main_path if raw else None
448    lines = []
449    line_start = 0
450
451    def flush():
452        if fspath:
453            if fspath.endswith("/"):
454                cart.files[fspath] = PicotronDir()
455            else:
456                data = b"\n".join(lines)
457                if data.startswith(k_p64_b64_prefix):
458                    data = pico_base64_decode(data[4:])
459
460                cart.files[fspath] = PicotronFile(data, line_start)
461
462    for line_i, line in enumerate(data.splitlines()):
463        if line.startswith(k_p64_file_prefix) and not raw:
464            flush()
465            lines = []
466            line_start = line_i + 1
467
468            fspath = decode_luastr(line[len(k_p64_file_prefix):].strip())
469            if fspath == k_p64_end_file:
470                fspath = None
471
472        elif fspath is None and line.startswith(b"version "):
473            cart.version_id = int(line.split()[1])
474
475        else:
476            lines.append(line)
477
478    if raw:
479        flush()
480    elif fspath:
481        throw(f"expected {k_p64_end_file} in p64")
482
483    return cart
484
485k_max_bad_p64_char_re = b"[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f-\xff]|^" + k_p64_file_prefix
486k_min_bad_p64_char_re = b"\x00|^" + k_p64_file_prefix
487
488def preview_order_key(pair):
489    # we prefer to sort p64 files for better visibility of code, e.g. in the webapp's preview
490    # (this is NOT what picotron does currently, hopefully doesn't matter)
491    dirname, filename = str_split_last(pair[0], "/")
492    if filename == "": # directory itself must be first
493        order = -3
494    elif filename == k_p64_main_path:
495        order = -2
496    elif filename.endswith(".lua"):
497        order = -1
498    elif filename in k_label_files:
499        order = 1
500    elif filename.startswith("."):
501        order = 2
502    else:
503        order = 0
504    return (dirname, order, filename)
505
506def write_cart64_to_source(cart, avoid_base64=False, **opts):
507    lines = [k_p64_prefix + b" // www.picotron.net"]
508    lines.append(b"version %d" % cart.version_id)
509    lines.append(b'')
510
511    bad_p64_char_re = k_min_bad_p64_char_re if avoid_base64 else k_max_bad_p64_char_re
512
513    for fspath, file in sorted(cart.files.items(), key=preview_order_key):
514        lines.append(k_p64_file_prefix + encode_luastr(fspath))
515        if e(file.data):
516            if re.search(bad_p64_char_re, file.data, re.M):
517                data = k_p64_b64_prefix + pico_base64_encode(file.data)
518                for line in str_chunk(data, k_p64_b64_line_size):
519                    lines.append(line)
520            else:
521                lines.append(file.data)
522
523    lines.append(k_p64_file_prefix + encode_luastr(k_p64_end_file))
524
525    return b"\n".join(lines) + b"\n"
526
527def write_cart64_to_raw_source(cart, **_):
528    main = cart.files.get(k_p64_main_path)
529    check(main, "{k_p64_main_path} not found in cart")
530    return main.data
531
532k_fictive_main_pod = "main.pod" # not a real picotron concept
533
534def read_cart64_from_single_pod(data, path=None, **_):
535    cart = Cart64(path=path)
536    main = PicotronFile(data)
537    if main.raw_metadata is None:
538        main.raw_metadata = k_pod
539    cart.files[k_fictive_main_pod] = main
540    return cart
541
542def write_cart64_to_single_pod(cart, **_):
543    main = cart.files.get(k_fictive_main_pod)
544    check(main, "{k_fictive_main_pod} not found in cart")
545    if main.raw_metadata == k_pod:
546        main.raw_metadata = None
547    return main.data
548
549def read_cart64_from_fs(path, is_dir=None, target_cart=None, fspath=None, sections=None, **opts):
550    if target_cart is None:
551        target_cart = Cart64(path=path)
552    if fspath is None or fspath in (".", "/"):
553        fspath = ""
554    if sections and not isinstance(sections, Cart64Glob):
555        sections = Cart64Glob(sections)
556    
557    if is_dir is None:
558        is_dir = path_is_dir(path)
559
560    if is_dir:
561        if fspath:
562            if not fspath.endswith("/"):
563                fspath += "/"
564            target_cart.files[fspath] = PicotronDir()
565
566        for child in dir_names(path):
567            child_path = path_join(path, child)
568            child_fspath = fspath + child
569            read_cart64_from_fs(child_path, None, target_cart, child_fspath, sections, **opts)
570    else:
571        if not fspath or fspath.endswith("/"):
572            fspath += path_basename(path) # good default
573        if not sections or sections.matches(fspath):
574            check(not fspath.endswith("/"), "filenames cannot end with '/'")
575            target_cart.files[fspath] = PicotronFile(file_read(path))
576
577    return target_cart
578
579def write_cart64_to_fs(cart, path, is_dir=None, fspath=None, delete_existing=False, **opts):
580    if fspath is None:
581        fspath = ""
582    
583    if is_dir is None:
584        file = cart.files.get(fspath)
585        is_dir = file.is_dir if file else False
586
587    if is_dir:
588        if fspath and not fspath.endswith("/"):
589            fspath += "/"
590        dir_create(path, delete_existing=delete_existing)
591
592        for child_fspath, file in cart.files.items():
593            if child_fspath.startswith(fspath):
594                child = child_fspath[len(fspath):]
595                if child.count("/") == (1 if file.is_dir else 0):
596                    child_path = path_join(path, child)
597                    check(path_is_inside(child_path, path), f"'{child_path}' is outside '{path}'")
598                    write_cart64_to_fs(cart, child_path, file.is_dir, child_fspath, **opts)
599    else:
600        if path_is_dir(path):
601            path = path_join(path, path_basename(fspath)) # good default
602        file = cart.files.get(fspath)
603        check(file, f"no file '{fspath}' in cart")
604        file_write(path, file.data)
605
606def read_cart64_autodetect(path, **opts):
607    if path_is_native(path) and path_is_dir(path):
608        return read_cart64_from_fs(path, is_dir=True, **opts)
609
610    data = file_read(path)
611
612    # cart?
613    if data.startswith(k_p64_prefix):
614        return read_cart64_from_source(data, path=path, **opts)
615    
616    # png?
617    if data.startswith(k_png_header):
618        return read_cart64_from_image(data, path=path, **opts)
619
620    # rom?
621    if data.startswith(k_rom_header_sig) and b"\0" in data[:k_rom_header_size]: # the rom size must have a nul
622        return read_cart64_from_rom(data, path=path, **opts)
623        
624    # plain text?
625    return read_cart64_from_source(data, raw=True, path=path, **opts)
626
627def read_cart64(path, format=None, **opts):
628    """Read a cart from the given path, assuming it is in the given format"""
629    if format in (None, Cart64Format.auto):
630        return read_cart64_autodetect(path, **opts)
631    elif format == Cart64Format.p64:
632        return read_cart64_from_source(file_read(path), path=path, **opts)
633    elif format == Cart64Format.png:
634        return read_cart64_from_image(file_read(path), path=path, **opts)
635    elif format in (Cart64Format.rom, Cart64Format.tiny_rom):
636        return read_cart64_from_rom(file_read(path), path=path, allow_tiny=True, **opts)
637    elif format == Cart64Format.lua:
638        return read_cart64_from_source(file_read(path), raw=True, path=path, **opts)
639    elif format == Cart64Format.pod:
640        return read_cart64_from_single_pod(file_read(path), path=path, **opts)
641    elif format in (Cart64Format.dir, Cart64Format.fs):
642        return read_cart64_from_fs(path, is_dir=True if format == Cart64Format.dir else None, **opts)
643    elif format == Cart64Format.label:
644        return read_cart64_label(file_read(path), path=path, **opts)
645    elif format.is_export:
646        return read_cart64_export(path, format).get_cart(path=path, **opts)
647    else:
648        throw(f"invalid format for reading: {format}")
649
650def write_cart64(path, cart, format, **opts):
651    """Writes a cart to the given path in the given format"""
652    if format == Cart64Format.p64:
653        file_write(path, write_cart64_to_source(cart, **opts))
654    elif format == Cart64Format.png:
655        file_write(path, write_cart64_to_image(cart, **opts))
656    elif format == Cart64Format.rom:
657        file_write(path, write_cart64_to_rom(cart, **opts))
658    elif format == Cart64Format.tiny_rom:
659        file_write(path, write_cart64_to_tiny_rom(cart, **opts))
660    elif format == Cart64Format.lua:
661        file_write(path, write_cart64_to_raw_source(cart, **opts))
662    elif format == Cart64Format.pod:
663        file_write(path, write_cart64_to_single_pod(cart, **opts))
664    elif format in (Cart64Format.dir, Cart64Format.fs):
665        write_cart64_to_fs(cart, path, is_dir=True if format == Cart64Format.dir else None, **opts)
666    elif format == Cart64Format.label:
667        file_write(path, write_cart64_label(cart, **opts))
668    elif format.is_export:
669        write_to_cart64_export(path, cart, format, **opts)
670    else:
671        throw(f"invalid format for writing: {format}")
672
673def filter_cart64(cart, sections):
674    glob = Cart64Glob(sections)
675    to_delete = [path for path in cart.files if not glob.matches(path)]
676    for path in to_delete:
677        del cart.files[path]
678
679def preproc_meta(cart, delete_meta, keep_meta_keys):
680    to_delete = []
681    glob = Cart64Glob(delete_meta)
682    key_glob = Cart64Glob(keep_meta_keys)
683
684    for path, file in cart.files.items():
685        if glob.matches(path) and not file.is_dir:
686            meta = file.metadata
687            new_meta = None
688            if e(meta):
689                new_meta = {}
690                for key, value in meta.items():
691                    if key_glob.matches(key):
692                        new_meta[key] = value
693                
694                if new_meta:
695                    for req_key in k_pod_prefix_strs: # at least the format
696                        if req_key in meta:
697                            new_meta[req_key] = meta[req_key]
698                else:
699                    if file.is_raw:
700                        new_meta = None
701            
702            if not new_meta and str_after_last(path, "/") == ".info.pod": # contains meta only
703                to_delete.append(path)
704            else:
705                file.metadata = new_meta
706    
707    for path in to_delete:
708        del cart.files[path]
709
710def preproc_cart64(cart, delete_meta=None, keep_meta_keys=None, delete_label=None,
711                   uncompress_pods=False, base64_pods=False, keep_pod_compression=False, need_pod_compression=False):
712    if delete_meta:
713        cart.set_raw_title(cart.title)
714        cart.set_raw_icon(cart.icon)
715        cart.set_raw_export_home(cart.export_home)
716        cart.set_raw_runtime_version(cart.get_runtime_version())
717        preproc_meta(cart, delete_meta, keep_meta_keys)
718    
719    if delete_label:
720        label_file, label = cart.label
721        for any_label_file in k_label_files:
722            cart.files.pop(any_label_file, None)
723        cart.set_raw_label(label_file, label)
724    
725    if not keep_pod_compression:
726        runtime = cart.runtime_version
727        for path, file in cart.files.items():
728            if not file.is_raw and not file.is_dir:
729                if uncompress_pods:
730                    file.set_payload(file.payload, compress=False, use_pxu=False, use_base64=base64_pods, runtime=runtime)
731                elif need_pod_compression:
732                    file.set_payload(file.payload, compress=True, use_pxu=True, use_base64=base64_pods, runtime=runtime)
733                else:
734                    file.set_payload(file.payload, compress=False, use_pxu=True, use_base64=base64_pods, runtime=runtime)
735
736def merge_cart64(dest, src, sections=None):
737    glob = Cart64Glob(sections) if e(sections) else None
738    for path, file in sorted(src.files.items()): # sort to get dirs first
739        if not glob or glob.matches(path):
740            dest.files[path] = file
741            
742            # create parent directories
743            parent = str_before_last(path.rstrip("/"), "/") + "/"
744            while parent != "/" and parent not in dest.files:
745                dest.files[parent] = PicotronDir()
746                parent = str_before_last(parent[:-1], "/") + "/"
747
748def write_cart64_compressed_size(cart, handler=True, **opts):
749    write_cart64_to_rom(cart, size_handler=handler, **opts)
750
751def write_cart64_version(cart):
752    print("file version: %d" % cart.version_id)
753    print("runtime version: %d" % cart.get_runtime_version(-1))
754
755from picotron_export import read_cart64_export, write_to_cart64_export
class Cart64Format(utils.Enum):
14class Cart64Format(Enum):
15    """An enum representing the supported cart formats"""
16    auto = p64 = png = rom = tiny_rom = lua = pod = dir = dat = html = bin = fs = label = ...
17    
18    @property
19    def is_input(m):
20        return m != m.bin
21    @property
22    def is_output(m):
23        return m != m.auto
24    @property
25    def is_ext(m):
26        return m not in (m.auto, m.dir, m.fs, m.label, m.tiny_rom)
27    @property
28    def is_src(m):
29        return m in (m.p64, m.lua, m.pod, m.dir, m.fs)
30    @property
31    def is_export(m):
32        return m in (m.dat, m.html, m.bin)
33    @property
34    def is_exposed(m):
35        return m != m.fs
36    
37    @classproperty
38    def default_src(m):
39        return m.p64
40    @classproperty
41    def default_dir(m):
42        return m.dir

An enum representing the supported cart formats

Cart64Format(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}")
is_input
18    @property
19    def is_input(m):
20        return m != m.bin
is_output
21    @property
22    def is_output(m):
23        return m != m.auto
is_ext
24    @property
25    def is_ext(m):
26        return m not in (m.auto, m.dir, m.fs, m.label, m.tiny_rom)
is_src
27    @property
28    def is_src(m):
29        return m in (m.p64, m.lua, m.pod, m.dir, m.fs)
is_export
30    @property
31    def is_export(m):
32        return m in (m.dat, m.html, m.bin)
is_exposed
33    @property
34    def is_exposed(m):
35        return m != m.fs
def default_src(unknown):

Method decorator that turns it into a read-only class property

def default_dir(unknown):

Method decorator that turns it into a read-only class property

value
k_info_file = '.info.pod'
k_label_png_file = 'label.png'
k_label_qoi_file = 'label.qoi'
k_label_files = ('label.qoi', 'label.png')
class Cart64:
 49class Cart64:
 50    """A picotron cart - a collection of all its files"""
 51    def __init__(m, path="", name=""):
 52        m.version_id = get_picotron_version_id(get_default_picotron_runtime())
 53        m.path = path
 54        m.name = name if name else path_basename(path) if path else ""
 55        m.files = {}
 56        m.raw_title = m.raw_label = m.raw_icon = m.raw_home = m.raw_runtime_version = None
 57
 58    @property
 59    def metadata(m):
 60        info = m.files.get(k_info_file)
 61        return info.metadata if info else None
 62
 63    def set_metadata(m, key, value):
 64        info = m.files.get(k_info_file)
 65        if info and e(meta := info.metadata):
 66            meta[key] = value
 67            info.metadata = meta
 68            return True
 69
 70    @property
 71    def title(m):
 72        if e(m.raw_title):
 73            return m.raw_title
 74
 75        meta = m.metadata
 76        if not meta:
 77            return ()
 78        title = str(meta.get("title", ""))
 79        version = str(meta.get("version", ""))
 80        author = str(meta.get("author", ""))
 81        return (title, " ".join((version, ("by " + author if author else ""))))
 82
 83    def set_raw_title(m, title_lines):
 84        m.raw_title = title_lines
 85
 86    @property
 87    def label(m):
 88        if m.raw_label:
 89            return m.raw_label
 90        
 91        for label_file in k_label_files:
 92            label = m.files.get(label_file)
 93            if e(label):
 94                return label_file, label
 95        
 96        return None, None
 97
 98    def load_label(m):
 99        label_file, label = m.label
100        if label:
101            try:
102                check(label.is_raw, "label is not a raw file")
103                return load_image_of_size(BytesIO(label.raw_payload), k_label_size, is_qoi=label_file == k_label_qoi_file)
104            except CheckError as e:
105                eprint("ignoring invalid label due to: %s" % e)
106    
107    def set_raw_label(m, label_file, label):
108        m.raw_label = (label_file, label)
109
110    @property
111    def icon(m):
112        if m.raw_icon:
113            return m.raw_icon
114
115        meta = m.metadata
116        icon = meta.get("icon") if meta else None
117        return icon if isinstance(icon, UserData) else None
118
119    def load_icon(m):
120        icon = m.icon
121        if icon and icon.type == "u8" and icon.width and icon.height:
122            data = bytearray()
123            for i in bytes.fromhex(icon.data):
124                if i >= len(k_palette_64):
125                    i = 0
126                data += bytes(k_palette_64[i] if i else Color(0, 0, 0, 0))
127            return Image.from_data(icon.width, icon.height, PixelFormat.rgba8, data)
128
129    def set_raw_icon(m, icon):
130        m.raw_icon = icon
131
132    @property
133    def export_home(m):
134        if e(m.raw_home):
135            return m.raw_home
136        meta = m.metadata
137        home = meta.get("export_home") if meta else None
138        return home if isinstance(home, str) else ""
139
140    def set_raw_export_home(m, value):
141        m.raw_home = value
142
143    def get_runtime_version(m, default=sys.maxsize):
144        if e(m.raw_runtime_version):
145            return m.raw_runtime_version
146        meta = m.metadata
147        runtime = meta.get("runtime") if meta else None
148        return runtime if isinstance(runtime, (int, float)) else default
149
150    @lazy_property
151    def runtime_version(m):
152        return m.get_runtime_version()
153
154    def set_raw_runtime_version(m, runtime):
155        m.raw_runtime_version = runtime
156
157    def set_version(m, runtime):
158        m.set_raw_runtime_version(runtime)
159        m.version_id = get_picotron_version_id(runtime)
160        m.set_metadata("runtime", runtime)

A picotron cart - a collection of all its files

Cart64(path='', name='')
51    def __init__(m, path="", name=""):
52        m.version_id = get_picotron_version_id(get_default_picotron_runtime())
53        m.path = path
54        m.name = name if name else path_basename(path) if path else ""
55        m.files = {}
56        m.raw_title = m.raw_label = m.raw_icon = m.raw_home = m.raw_runtime_version = None
metadata
58    @property
59    def metadata(m):
60        info = m.files.get(k_info_file)
61        return info.metadata if info else None
def set_metadata(m, key, value):
63    def set_metadata(m, key, value):
64        info = m.files.get(k_info_file)
65        if info and e(meta := info.metadata):
66            meta[key] = value
67            info.metadata = meta
68            return True
title
70    @property
71    def title(m):
72        if e(m.raw_title):
73            return m.raw_title
74
75        meta = m.metadata
76        if not meta:
77            return ()
78        title = str(meta.get("title", ""))
79        version = str(meta.get("version", ""))
80        author = str(meta.get("author", ""))
81        return (title, " ".join((version, ("by " + author if author else ""))))
def set_raw_title(m, title_lines):
83    def set_raw_title(m, title_lines):
84        m.raw_title = title_lines
label
86    @property
87    def label(m):
88        if m.raw_label:
89            return m.raw_label
90        
91        for label_file in k_label_files:
92            label = m.files.get(label_file)
93            if e(label):
94                return label_file, label
95        
96        return None, None
def load_label(m):
 98    def load_label(m):
 99        label_file, label = m.label
100        if label:
101            try:
102                check(label.is_raw, "label is not a raw file")
103                return load_image_of_size(BytesIO(label.raw_payload), k_label_size, is_qoi=label_file == k_label_qoi_file)
104            except CheckError as e:
105                eprint("ignoring invalid label due to: %s" % e)
def set_raw_label(m, label_file, label):
107    def set_raw_label(m, label_file, label):
108        m.raw_label = (label_file, label)
icon
110    @property
111    def icon(m):
112        if m.raw_icon:
113            return m.raw_icon
114
115        meta = m.metadata
116        icon = meta.get("icon") if meta else None
117        return icon if isinstance(icon, UserData) else None
def load_icon(m):
119    def load_icon(m):
120        icon = m.icon
121        if icon and icon.type == "u8" and icon.width and icon.height:
122            data = bytearray()
123            for i in bytes.fromhex(icon.data):
124                if i >= len(k_palette_64):
125                    i = 0
126                data += bytes(k_palette_64[i] if i else Color(0, 0, 0, 0))
127            return Image.from_data(icon.width, icon.height, PixelFormat.rgba8, data)
def set_raw_icon(m, icon):
129    def set_raw_icon(m, icon):
130        m.raw_icon = icon
export_home
132    @property
133    def export_home(m):
134        if e(m.raw_home):
135            return m.raw_home
136        meta = m.metadata
137        home = meta.get("export_home") if meta else None
138        return home if isinstance(home, str) else ""
def set_raw_export_home(m, value):
140    def set_raw_export_home(m, value):
141        m.raw_home = value
def get_runtime_version(m, default=9223372036854775807):
143    def get_runtime_version(m, default=sys.maxsize):
144        if e(m.raw_runtime_version):
145            return m.raw_runtime_version
146        meta = m.metadata
147        runtime = meta.get("runtime") if meta else None
148        return runtime if isinstance(runtime, (int, float)) else default
def runtime_version(unknown):

Method decorator that turns it into a lazily-evaluated property

def set_raw_runtime_version(m, runtime):
154    def set_raw_runtime_version(m, runtime):
155        m.raw_runtime_version = runtime
def set_version(m, runtime):
157    def set_version(m, runtime):
158        m.set_raw_runtime_version(runtime)
159        m.version_id = get_picotron_version_id(runtime)
160        m.set_metadata("runtime", runtime)
k_cart64_size = 262144
k_rom_header_sig = b'p64'
k_rom_header_size = 8
def read_cart64_from_rom( buffer, path=None, allow_tiny=False, size_handler=None, debug_handler=None, **opts):
169def read_cart64_from_rom(buffer, path=None, allow_tiny=False, size_handler=None, debug_handler=None, **opts):
170    cart = Cart64(path=path)
171    
172    with BinaryReader(BytesIO(buffer)) as r:
173        if r.bytes(3) == k_rom_header_sig:
174            cart.version_id = r.u8()
175            size = r.u32()
176            if size_handler:
177                print_rom_compressed_size(k_rom_header_size + size, prefix="input", handler=size_handler)
178            uncbuffer = lz4_uncompress(r.bytes(size), debug=debug_handler)
179            
180            with BinaryReader(BytesIO(uncbuffer)) as r:
181                while not r.eof():
182                    fspath = decode_luastr(r.zbytes())
183                    if fspath.endswith("/"):
184                        cart.files[fspath] = PicotronDir()
185                    else:
186                        size = r.u8()
187                        if size == 0xff:
188                            size = r.u32()
189                        data = r.bytes(size)
190
191                        cart.files[fspath] = PicotronFile(data)
192            return cart
193        
194        elif allow_tiny:
195            r.rewind()
196            r.big_end = True
197            tiny_cart = Cart64()
198            tiny_code = encode_p8str(uncompress_code(r, max_code_size=sys.maxsize, **opts))
199            tiny_cart.files[k_p64_main_path] = PicotronFile(tiny_code)
200            return tiny_cart
201
202        else:
203            throw("wrong rom header")
def ext_order_key(pair):
205def ext_order_key(pair):
206    # try to order things to maximize compression
207    dirname, filename = str_split_last(pair[0], "/")
208    if filename == "":
209        # put all directories first and in proper order, in case it matters
210        return (-10, "", dirname, filename) # (intentionally reversed from below)
211    
212    ext = path_extension(filename)
213    if filename == "main.lua":
214        order = 1
215    elif ext == ".lua":
216        order = 0
217    elif ext == ".pod":
218        order = 2
219    elif ext == ".gfx":
220        order = 3
221    elif ext == ".sfx":
222        order = 4
223    elif ext == ".map":
224        order = 5
225    else:
226        order = 6
227    return (order, ext, filename, dirname)
def write_cart64_to_rom( cart, size_handler=None, debug_handler=None, padding=0, limit=None, fast_compress=False, **opts):
229def write_cart64_to_rom(cart, size_handler=None, debug_handler=None, padding=0,
230                        limit=None, fast_compress=False, **opts):
231    io = BytesIO()
232
233    with BinaryWriter(io) as w:
234        for fspath, file in sorted(cart.files.items(), key=ext_order_key):
235            w.zbytes(encode_luastr(fspath))
236            check(not fspath.endswith("/") == e(file.data), "wrong picotron file/directory path")
237            if e(file.data):
238                data = file.data
239                if len(data) < 0xff:
240                    w.u8(len(data))
241                else:
242                    w.u8(0xff)
243                    w.u32(len(data))
244                w.bytes(data)
245
246        compressed = lz4_compress(io.getvalue(), fast=fast_compress, debug=debug_handler)
247    
248    size = k_rom_header_size + len(compressed)
249    if size_handler:
250        print_rom_compressed_size(size, handler=size_handler)
251    if limit:
252        check(size <= limit, "cart takes too much compressed space!")
253    
254    io = BytesIO()
255    with BinaryWriter(io) as w:
256        w.bytes(k_rom_header_sig)
257        w.u8(cart.version_id)
258        w.u32(len(compressed))
259        w.bytes(compressed)
260
261        for _ in range(padding):
262            w.u8(0)
263
264        return io.getvalue()
def write_cart64_to_tiny_rom(cart, size_handler=None, debug_handler=None, **opts):
266def write_cart64_to_tiny_rom(cart, size_handler=None, debug_handler=None, **opts):
267    main = cart.files.get(k_p64_main_path)
268    check(main, f"{k_p64_main_path} not found in cart")
269    data = main.raw_payload
270
271    tiny_cart = Cart64()
272    tiny_cart.files[k_p64_main_path] = PicotronFile(data)
273    compressed_lz4 = write_cart64_to_rom(tiny_cart, debug_handler=debug_handler, **opts)
274
275    io = BytesIO()
276    with BinaryWriter(io, big_end = True) as w:
277        compress_code(w, decode_p8str(data), force_compress=True)
278        compressed_pxa = io.getvalue()
279
280    result = data
281    if len(compressed_pxa) < len(result):
282        result = compressed_pxa
283    if len(compressed_lz4) < len(result):
284        result = compressed_lz4
285
286    if size_handler:
287        print_rom_compressed_size(len(result), handler=size_handler)
288
289    return result
k_cart64_image_size = Point(x=512, y=384)
k_label_size = Point(x=480, y=270)
k_label_offset = Point(x=16, y=38)
k_title_offset = Point(x=80, y=330)
k_title_width = 352
k_subtitle_suboffset = Point(x=0, y=26)
def read_cart64_from_image(data, **opts):
298def read_cart64_from_image(data, **opts):
299    image = load_image_of_size(BytesIO(data), k_cart64_image_size)
300    width, height = image.size
301
302    io = BytesIO()
303    pixels = image.pixels
304
305    with BinaryBitWriter(io) as bw:
306        for y in range(height):
307            for x in range(width):
308                r, g, b, a = pixels[x, y]
309                bw.bits(11, (r & 7) | ((g & 7) << 3) | ((b & 7) << 6) | ((a & 3) << 9))
310
311        data = io.getvalue()
312
313    cart = read_cart64_from_rom(data, **opts)
314
315    _, label = cart.label
316    if label is None:
317        label = Image.create(*k_label_size)
318        label_pixels = label.pixels
319        
320        for y in range(k_label_size.y):
321            for x in range(k_label_size.x):
322                r, g, b, a = pixels[k_label_offset.x + x, k_label_offset.y + y]
323                label_pixels[x, y] = (r & ~7, g & ~7, b & ~7, 0xff)
324
325        try:
326            cart.files[k_label_qoi_file] = PicotronFile(label.save(format="qoi"))
327        except KeyError:
328            cart.files[k_label_png_file] = PicotronFile(label.save())
329    
330    return cart
def draw_title_on_image(image, title, subtitle, offset, width, suboffset):
332def draw_title_on_image(image, title, subtitle, offset, width, suboffset):
333    # TODO: there seems to be some kerning?!
334
335    with file_open(path_join(get_res_path(), "font64.png")) as font_f:
336        font_surf = Image.load(font_f).alpha
337        font_pixels = font_surf.pixels
338        char_widths = {}
339
340        for sub in (False, True):
341            scale = 1 if sub else 2
342
343            if sub:
344                color = Color.gray(0x90)
345                scaled_surf = font_surf
346                color2 = scaled_surf2 = None
347            else:
348                color = Color.gray(0xd0)
349                scaled_surf = font_surf.scale(2)
350                color2 = Color.gray(0x80)
351                scaled_surf2 = scaled_surf.copy()
352                for y in range(scaled_surf.height):
353                    (scaled_surf if y % 2 else scaled_surf2).fill(0, Rect(0, y, scaled_surf.width, 1))
354            
355            x, y = 0, 0
356            for ch in title:
357                chi = ord(ch)
358                ch_x, ch_y = chi % 16 * 10, chi // 16 * 11
359                ch_w = char_widths.get(chi)
360                if ch_w is None:
361                    ch_w = 0
362                    while font_pixels[ch_x + ch_w, ch_y + 9]: # using an "underline" to measure char advance
363                        ch_w += 1
364                    char_widths[chi] = ch_w
365                
366                chrect = Rect(ch_x * scale, ch_y * scale, ch_w * scale, 9 * scale)
367                new_x = x + chrect.w
368                if new_x <= width:
369                    dest = Rect.from_pos_size(offset + Point (x, y), chrect.size)
370                    image.fill(color, dest, scaled_surf.slice(chrect))
371                    if scaled_surf2:
372                        image.fill(color2, dest, scaled_surf2.slice(chrect))
373                x = new_x
374            
375            offset += suboffset
376            title = subtitle
def write_cart64_to_image( cart, template_image=None, template_only=False, optimize_image=False, **opts):
378def write_cart64_to_image(cart, template_image=None, template_only=False, optimize_image=False, **opts):
379    output = write_cart64_to_rom(cart, limit=k_cart64_size, padding=4, **opts) # some padding to easily tell when we're done without failing
380    end_pos = len(output) - 2
381
382    if not template_image:
383        template_image = path_join(get_res_path(), "template64.png")
384
385    with file_open(template_image) as template_f:
386        image = load_image_of_size(template_f, k_cart64_image_size)
387        width, height = image.size
388
389        if not template_only:
390            label = cart.load_label()
391            if label:
392                image.draw(label, k_label_offset)
393            
394            title = cart.title
395            if title:
396                draw_title_on_image(image, *list_unpack(title, 2), k_title_offset, k_title_width, k_subtitle_suboffset)
397        
398        pixels = image.pixels
399
400        with BinaryBitReader(BytesIO(output)) as br:
401            for y in range(height):
402                for x in range(width):
403                    word = br.bits(11) if br.pos() < end_pos else 0
404                    r, g, b, a = pixels[x,y]
405                    r = (r & ~7) | (word & 7)
406                    g = (g & ~7) | ((word >> 3) & 7)
407                    b = (b & ~7) | ((word >> 6) & 7)
408                    a = (a & ~3) | ((word >> 9) & 3)
409                    pixels[x, y] = (r, g, b, a)
410
411        if optimize_image:
412            return image.save(optimize=True)
413        else:
414            return image.save()
def read_cart64_label(data, path=None, **_):
416def read_cart64_label(data, path=None, **_):
417    cart = Cart64(path=path)
418    if data.startswith(k_png_header):
419        label_file = k_label_png_file
420    elif data.startswith(k_qoi_header):
421        label_file = k_label_qoi_file
422    else:
423        throw("label in unexpected format")
424    
425    cart.files[label_file] = PicotronFile(data)
426    return cart
def write_cart64_label(cart, **_):
428def write_cart64_label(cart, **_):
429    label = cart.load_label()
430    if label:
431        return label.save()
432    else:
433        throw("no label to write")
k_p64_prefix = b'picotron cartridge'
k_p64_main_path = 'main.lua'
k_p64_file_prefix = b':: '
k_p64_b64_prefix = b'b64$'
k_p64_b64_line_size = 76
k_p64_end_file = '[eoc]'
def read_cart64_from_source(data, path=None, raw=False, **_):
442def read_cart64_from_source(data, path=None, raw=False, **_):
443    cart = Cart64(path=path)
444    
445    if not raw and not data.startswith(k_p64_prefix) and not data.startswith(k_p64_file_prefix): # fallback to raw
446        raw = True
447
448    fspath = k_p64_main_path if raw else None
449    lines = []
450    line_start = 0
451
452    def flush():
453        if fspath:
454            if fspath.endswith("/"):
455                cart.files[fspath] = PicotronDir()
456            else:
457                data = b"\n".join(lines)
458                if data.startswith(k_p64_b64_prefix):
459                    data = pico_base64_decode(data[4:])
460
461                cart.files[fspath] = PicotronFile(data, line_start)
462
463    for line_i, line in enumerate(data.splitlines()):
464        if line.startswith(k_p64_file_prefix) and not raw:
465            flush()
466            lines = []
467            line_start = line_i + 1
468
469            fspath = decode_luastr(line[len(k_p64_file_prefix):].strip())
470            if fspath == k_p64_end_file:
471                fspath = None
472
473        elif fspath is None and line.startswith(b"version "):
474            cart.version_id = int(line.split()[1])
475
476        else:
477            lines.append(line)
478
479    if raw:
480        flush()
481    elif fspath:
482        throw(f"expected {k_p64_end_file} in p64")
483
484    return cart
k_max_bad_p64_char_re = b'[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f-\xff]|^:: '
k_min_bad_p64_char_re = b'\x00|^:: '
def preview_order_key(pair):
489def preview_order_key(pair):
490    # we prefer to sort p64 files for better visibility of code, e.g. in the webapp's preview
491    # (this is NOT what picotron does currently, hopefully doesn't matter)
492    dirname, filename = str_split_last(pair[0], "/")
493    if filename == "": # directory itself must be first
494        order = -3
495    elif filename == k_p64_main_path:
496        order = -2
497    elif filename.endswith(".lua"):
498        order = -1
499    elif filename in k_label_files:
500        order = 1
501    elif filename.startswith("."):
502        order = 2
503    else:
504        order = 0
505    return (dirname, order, filename)
def write_cart64_to_source(cart, avoid_base64=False, **opts):
507def write_cart64_to_source(cart, avoid_base64=False, **opts):
508    lines = [k_p64_prefix + b" // www.picotron.net"]
509    lines.append(b"version %d" % cart.version_id)
510    lines.append(b'')
511
512    bad_p64_char_re = k_min_bad_p64_char_re if avoid_base64 else k_max_bad_p64_char_re
513
514    for fspath, file in sorted(cart.files.items(), key=preview_order_key):
515        lines.append(k_p64_file_prefix + encode_luastr(fspath))
516        if e(file.data):
517            if re.search(bad_p64_char_re, file.data, re.M):
518                data = k_p64_b64_prefix + pico_base64_encode(file.data)
519                for line in str_chunk(data, k_p64_b64_line_size):
520                    lines.append(line)
521            else:
522                lines.append(file.data)
523
524    lines.append(k_p64_file_prefix + encode_luastr(k_p64_end_file))
525
526    return b"\n".join(lines) + b"\n"
def write_cart64_to_raw_source(cart, **_):
528def write_cart64_to_raw_source(cart, **_):
529    main = cart.files.get(k_p64_main_path)
530    check(main, "{k_p64_main_path} not found in cart")
531    return main.data
k_fictive_main_pod = 'main.pod'
def read_cart64_from_single_pod(data, path=None, **_):
535def read_cart64_from_single_pod(data, path=None, **_):
536    cart = Cart64(path=path)
537    main = PicotronFile(data)
538    if main.raw_metadata is None:
539        main.raw_metadata = k_pod
540    cart.files[k_fictive_main_pod] = main
541    return cart
def write_cart64_to_single_pod(cart, **_):
543def write_cart64_to_single_pod(cart, **_):
544    main = cart.files.get(k_fictive_main_pod)
545    check(main, "{k_fictive_main_pod} not found in cart")
546    if main.raw_metadata == k_pod:
547        main.raw_metadata = None
548    return main.data
def read_cart64_from_fs( path, is_dir=None, target_cart=None, fspath=None, sections=None, **opts):
550def read_cart64_from_fs(path, is_dir=None, target_cart=None, fspath=None, sections=None, **opts):
551    if target_cart is None:
552        target_cart = Cart64(path=path)
553    if fspath is None or fspath in (".", "/"):
554        fspath = ""
555    if sections and not isinstance(sections, Cart64Glob):
556        sections = Cart64Glob(sections)
557    
558    if is_dir is None:
559        is_dir = path_is_dir(path)
560
561    if is_dir:
562        if fspath:
563            if not fspath.endswith("/"):
564                fspath += "/"
565            target_cart.files[fspath] = PicotronDir()
566
567        for child in dir_names(path):
568            child_path = path_join(path, child)
569            child_fspath = fspath + child
570            read_cart64_from_fs(child_path, None, target_cart, child_fspath, sections, **opts)
571    else:
572        if not fspath or fspath.endswith("/"):
573            fspath += path_basename(path) # good default
574        if not sections or sections.matches(fspath):
575            check(not fspath.endswith("/"), "filenames cannot end with '/'")
576            target_cart.files[fspath] = PicotronFile(file_read(path))
577
578    return target_cart
def write_cart64_to_fs(cart, path, is_dir=None, fspath=None, delete_existing=False, **opts):
580def write_cart64_to_fs(cart, path, is_dir=None, fspath=None, delete_existing=False, **opts):
581    if fspath is None:
582        fspath = ""
583    
584    if is_dir is None:
585        file = cart.files.get(fspath)
586        is_dir = file.is_dir if file else False
587
588    if is_dir:
589        if fspath and not fspath.endswith("/"):
590            fspath += "/"
591        dir_create(path, delete_existing=delete_existing)
592
593        for child_fspath, file in cart.files.items():
594            if child_fspath.startswith(fspath):
595                child = child_fspath[len(fspath):]
596                if child.count("/") == (1 if file.is_dir else 0):
597                    child_path = path_join(path, child)
598                    check(path_is_inside(child_path, path), f"'{child_path}' is outside '{path}'")
599                    write_cart64_to_fs(cart, child_path, file.is_dir, child_fspath, **opts)
600    else:
601        if path_is_dir(path):
602            path = path_join(path, path_basename(fspath)) # good default
603        file = cart.files.get(fspath)
604        check(file, f"no file '{fspath}' in cart")
605        file_write(path, file.data)
def read_cart64_autodetect(path, **opts):
607def read_cart64_autodetect(path, **opts):
608    if path_is_native(path) and path_is_dir(path):
609        return read_cart64_from_fs(path, is_dir=True, **opts)
610
611    data = file_read(path)
612
613    # cart?
614    if data.startswith(k_p64_prefix):
615        return read_cart64_from_source(data, path=path, **opts)
616    
617    # png?
618    if data.startswith(k_png_header):
619        return read_cart64_from_image(data, path=path, **opts)
620
621    # rom?
622    if data.startswith(k_rom_header_sig) and b"\0" in data[:k_rom_header_size]: # the rom size must have a nul
623        return read_cart64_from_rom(data, path=path, **opts)
624        
625    # plain text?
626    return read_cart64_from_source(data, raw=True, path=path, **opts)
def read_cart64(path, format=None, **opts):
628def read_cart64(path, format=None, **opts):
629    """Read a cart from the given path, assuming it is in the given format"""
630    if format in (None, Cart64Format.auto):
631        return read_cart64_autodetect(path, **opts)
632    elif format == Cart64Format.p64:
633        return read_cart64_from_source(file_read(path), path=path, **opts)
634    elif format == Cart64Format.png:
635        return read_cart64_from_image(file_read(path), path=path, **opts)
636    elif format in (Cart64Format.rom, Cart64Format.tiny_rom):
637        return read_cart64_from_rom(file_read(path), path=path, allow_tiny=True, **opts)
638    elif format == Cart64Format.lua:
639        return read_cart64_from_source(file_read(path), raw=True, path=path, **opts)
640    elif format == Cart64Format.pod:
641        return read_cart64_from_single_pod(file_read(path), path=path, **opts)
642    elif format in (Cart64Format.dir, Cart64Format.fs):
643        return read_cart64_from_fs(path, is_dir=True if format == Cart64Format.dir else None, **opts)
644    elif format == Cart64Format.label:
645        return read_cart64_label(file_read(path), path=path, **opts)
646    elif format.is_export:
647        return read_cart64_export(path, format).get_cart(path=path, **opts)
648    else:
649        throw(f"invalid format for reading: {format}")

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

def write_cart64(path, cart, format, **opts):
651def write_cart64(path, cart, format, **opts):
652    """Writes a cart to the given path in the given format"""
653    if format == Cart64Format.p64:
654        file_write(path, write_cart64_to_source(cart, **opts))
655    elif format == Cart64Format.png:
656        file_write(path, write_cart64_to_image(cart, **opts))
657    elif format == Cart64Format.rom:
658        file_write(path, write_cart64_to_rom(cart, **opts))
659    elif format == Cart64Format.tiny_rom:
660        file_write(path, write_cart64_to_tiny_rom(cart, **opts))
661    elif format == Cart64Format.lua:
662        file_write(path, write_cart64_to_raw_source(cart, **opts))
663    elif format == Cart64Format.pod:
664        file_write(path, write_cart64_to_single_pod(cart, **opts))
665    elif format in (Cart64Format.dir, Cart64Format.fs):
666        write_cart64_to_fs(cart, path, is_dir=True if format == Cart64Format.dir else None, **opts)
667    elif format == Cart64Format.label:
668        file_write(path, write_cart64_label(cart, **opts))
669    elif format.is_export:
670        write_to_cart64_export(path, cart, format, **opts)
671    else:
672        throw(f"invalid format for writing: {format}")

Writes a cart to the given path in the given format

def filter_cart64(cart, sections):
674def filter_cart64(cart, sections):
675    glob = Cart64Glob(sections)
676    to_delete = [path for path in cart.files if not glob.matches(path)]
677    for path in to_delete:
678        del cart.files[path]
def preproc_meta(cart, delete_meta, keep_meta_keys):
680def preproc_meta(cart, delete_meta, keep_meta_keys):
681    to_delete = []
682    glob = Cart64Glob(delete_meta)
683    key_glob = Cart64Glob(keep_meta_keys)
684
685    for path, file in cart.files.items():
686        if glob.matches(path) and not file.is_dir:
687            meta = file.metadata
688            new_meta = None
689            if e(meta):
690                new_meta = {}
691                for key, value in meta.items():
692                    if key_glob.matches(key):
693                        new_meta[key] = value
694                
695                if new_meta:
696                    for req_key in k_pod_prefix_strs: # at least the format
697                        if req_key in meta:
698                            new_meta[req_key] = meta[req_key]
699                else:
700                    if file.is_raw:
701                        new_meta = None
702            
703            if not new_meta and str_after_last(path, "/") == ".info.pod": # contains meta only
704                to_delete.append(path)
705            else:
706                file.metadata = new_meta
707    
708    for path in to_delete:
709        del cart.files[path]
def preproc_cart64( cart, delete_meta=None, keep_meta_keys=None, delete_label=None, uncompress_pods=False, base64_pods=False, keep_pod_compression=False, need_pod_compression=False):
711def preproc_cart64(cart, delete_meta=None, keep_meta_keys=None, delete_label=None,
712                   uncompress_pods=False, base64_pods=False, keep_pod_compression=False, need_pod_compression=False):
713    if delete_meta:
714        cart.set_raw_title(cart.title)
715        cart.set_raw_icon(cart.icon)
716        cart.set_raw_export_home(cart.export_home)
717        cart.set_raw_runtime_version(cart.get_runtime_version())
718        preproc_meta(cart, delete_meta, keep_meta_keys)
719    
720    if delete_label:
721        label_file, label = cart.label
722        for any_label_file in k_label_files:
723            cart.files.pop(any_label_file, None)
724        cart.set_raw_label(label_file, label)
725    
726    if not keep_pod_compression:
727        runtime = cart.runtime_version
728        for path, file in cart.files.items():
729            if not file.is_raw and not file.is_dir:
730                if uncompress_pods:
731                    file.set_payload(file.payload, compress=False, use_pxu=False, use_base64=base64_pods, runtime=runtime)
732                elif need_pod_compression:
733                    file.set_payload(file.payload, compress=True, use_pxu=True, use_base64=base64_pods, runtime=runtime)
734                else:
735                    file.set_payload(file.payload, compress=False, use_pxu=True, use_base64=base64_pods, runtime=runtime)
def merge_cart64(dest, src, sections=None):
737def merge_cart64(dest, src, sections=None):
738    glob = Cart64Glob(sections) if e(sections) else None
739    for path, file in sorted(src.files.items()): # sort to get dirs first
740        if not glob or glob.matches(path):
741            dest.files[path] = file
742            
743            # create parent directories
744            parent = str_before_last(path.rstrip("/"), "/") + "/"
745            while parent != "/" and parent not in dest.files:
746                dest.files[parent] = PicotronDir()
747                parent = str_before_last(parent[:-1], "/") + "/"
def write_cart64_compressed_size(cart, handler=True, **opts):
749def write_cart64_compressed_size(cart, handler=True, **opts):
750    write_cart64_to_rom(cart, size_handler=handler, **opts)
def write_cart64_version(cart):
752def write_cart64_version(cart):
753    print("file version: %d" % cart.version_id)
754    print("runtime version: %d" % cart.get_runtime_version(-1))