picotron_export

Functions to read/write picotron exports

  1"""Functions to read/write picotron exports"""
  2
  3from utils import *
  4from media_utils import PixelFormat
  5from pico_defs import get_res_path
  6from pico_export import FullExportBase
  7from zipfile import ZipFile
  8import base64
  9
 10k_icon64_size = Point(128, 128)
 11
 12class Cart64Export:
 13    """A picotron export"""
 14
 15    # def get_cart(m, **opts)
 16    # def set_cart(m, cart, **opts)
 17    
 18    def dump_contents(m, dest, fmt, **_):
 19        throw("dumping misc. contents is only support for a .dat file")
 20
 21class SysRom:
 22    """A picotron sysrom, used in both exports and in picotron.dat"""
 23
 24    def __init__(m, data=None):
 25        m.entries = []
 26        if data:
 27            with BinaryReader(BytesIO(data), big_end=True) as r:
 28                while not r.eof():
 29                    size = r.u32()
 30                    entry = r.bytes(size)
 31                    m.entries.append(entry)
 32
 33    class SysRomDir:
 34        def __init__(m, idx, entry):
 35            m.idx = idx
 36            m.files = read_cart64_from_rom(entry).files
 37        
 38        def get(m, name, strict=True):
 39            file = m.files.get(name)
 40            if not file:
 41                if strict:
 42                    throw(f"expected to find {name} in dat {m.idx} dir")
 43                else:
 44                    return None
 45            check(file.is_raw, "expected to find raw files inside dat dir")
 46            return file.data
 47
 48    def get(m, idx, strict=True, dir=False):
 49        entry = list_get(m.entries, int(idx))
 50        if entry is None and strict:
 51            throw(f"expected to find {idx} in dat file")
 52        return m.SysRomDir(idx, entry) if dir else entry
 53
 54    def set(m, idx, value):
 55        list_set(m.entries, int(idx), value, b"")
 56
 57    def to_bytes(m):
 58        with BinaryWriter(big_end=True) as w:
 59            for entry in m.entries:
 60                w.u32(len(entry))
 61                w.bytes(entry)
 62            
 63            return w.f.getvalue()
 64
 65    def dump_contents(m, dest, fmt, **_):
 66        cart_ext = f".{fmt}" if fmt.is_ext else ""
 67        for i, entry in enumerate(m.entries):
 68            is_cart = entry.startswith(k_rom_header_sig)
 69            path = path_join(dest, m.entry_name(i) + (cart_ext if is_cart else ""))
 70
 71            if is_cart and fmt != Cart64Format.rom:
 72                write_cart64(path, read_cart64_from_rom(entry), fmt)
 73            else:
 74                file_write(path, entry)
 75
 76class SysRomIndex(Enum):
 77    info = 0
 78    system = 1; cart = 2
 79    html_info = 3; linux_exe = 4
 80    win_exe = 5; win_sdl = 6
 81    mac_exe = 7; mac_sdl = 8
 82
 83class SysRomExport64(SysRom, Cart64Export):
 84    def get_cart(m, **opts):
 85        entry = m.get(SysRomIndex.cart, strict=False)
 86        if not entry:
 87            throw("no cart in sysrom file")
 88        return read_cart64_from_rom(entry, **opts)
 89
 90    def set_cart(m, cart, **opts):
 91        data = write_cart64_to_rom(cart, **opts)
 92        m.set(SysRomIndex.cart, data)
 93        
 94    def entry_name(m, i):
 95        try:
 96            return str(SysRomIndex(i))
 97        except ValueError:
 98            return f"unk{i}"
 99    
100    @staticmethod
101    def create(picotron_dat, cart=None, **_):
102        m = SysRomExport64()
103        m.set(SysRomIndex.info, cart.export_home.encode() if cart else b"")
104        m.set(SysRomIndex.system, picotron_dat.get(SysRomIndex.cart))
105        return m
106
107class HtmlExport64(Cart64Export):
108    def __init__(m, text):
109        m.text = text
110
111    def find_cart(m):
112        match = re.search(r'p64cart_str="([0-9a-fA-F]*)"', m.text)
113        if not match:
114            throw("can't find p64cart_str var in html")
115        return match
116
117    def get_cart(m, **opts):
118        match = m.find_cart()
119        return read_cart64_from_rom(bytes.fromhex(match.group(1)), **opts)
120
121    def set_cart(m, cart, **opts):
122        rom = write_cart64_to_rom(cart, **opts)
123        m.text = str_replace_between(m.text, *m.find_cart().span(1), rom.hex())
124
125    @staticmethod
126    def create(picotron_dat, cart=None, **_):
127        html_info = picotron_dat.get(SysRomIndex.html_info, dir=True)
128        html = html_info.get("shell.html").decode()
129        js = html_info.get("picotron_player.js").decode()
130        match = re.search(r'// ##pcart##\s+', html)
131        if not match:
132            throw("can't find pcart comment in html template")
133        
134        export_home = cart.export_home if cart else ""
135        html = str_insert(html, match.end(), f'\np64cart_str="";\nexport_home_str = "{export_home}";\n{js}')
136
137        title = list_get(cart.title, 0) if cart else None
138        html = html.replace("##page_title##", title or "Picotron Cartridge")
139
140        label = cart.load_label() if cart else None
141        label_png = label.convert(PixelFormat.rgb8).save() if label else None
142        if e(label_png):
143            label_url = "data:image/png;base64," + base64.b64encode(label_png).decode()
144            html = html.replace("##label_file##", label_url)
145
146        return HtmlExport64(html)
147
148class FullExport64(Cart64Export, FullExportBase):
149    def __init__(m, picotron_dat):
150        super().__init__()
151        m.picotron_dat = picotron_dat
152
153    @staticmethod
154    def create(picotron_dat, export_name="", **opts):
155        m = FullExport64(picotron_dat)
156        m.export_name = export_name
157        m.cart = None
158
159        m.sysrom = SysRomExport64.create(picotron_dat, **opts)
160        m.html = HtmlExport64.create(picotron_dat, **opts)
161        m.exports = [m.sysrom, m.html]
162        return m
163
164    def set_cart(m, cart, **opts):
165        m.cart = cart
166        for export in m.exports:
167            export.set_cart(cart, **opts)
168
169    def zip_copy(m, zip, dir, datdir, exclude=None):
170        for name, file in datdir.files.items():
171            if not name.endswith(".info.pod"):
172                if exclude and name.startswith(exclude):
173                    continue
174
175                exec = "." not in path_basename(name) # ???
176                m.zip_write(zip, dir, name, default(file.data, b""), exec=exec, is_dir=file.is_dir)
177
178    def save(m, path, delete_existing=False):
179        dir_create(path, delete_existing=delete_existing)
180        basename = m.export_name
181
182        icon = m.cart.load_icon()
183        if icon:
184            icon = icon.resize(k_icon64_size)
185            icon_bmpdata = icon.to_data(PixelFormat.bgra8, flip=True)
186            icon_icnsdata = icon.to_data(PixelFormat.rgba8)
187            icon_png = icon.convert(PixelFormat.rgba8).save()
188        else:
189            icon_bmpdata = icon_icnsdata = icon_png = None
190
191        html_path = path_join(path, "%s.html" % basename)
192        file_write_text(html_path, m.html.text)
193
194        exe_data = m.picotron_dat.get(SysRomIndex.win_exe)
195        if icon_bmpdata:
196            exe_icon_i = m.find_icon_offset_in_exe(exe_data)
197            if e(exe_icon_i):
198                exe_data = str_replace_at(exe_data, exe_icon_i, 0x10000, icon_bmpdata)
199            else:
200                eprint("couldn't find icon in exe, not changing it")
201
202        win_dir = "%s_windows" % basename
203        with ZipFile(path_join(path, win_dir + ".zip"), "w") as win_zip:
204            m.zip_write(win_zip, win_dir, "%s.exe" % basename, exe_data, exec=True)
205            m.zip_write(win_zip, win_dir, "sysrom.dat", m.sysrom.to_bytes())
206            m.zip_write(win_zip, win_dir, "SDL2.dll", m.picotron_dat.get(SysRomIndex.win_sdl))
207
208        linux_dir = "%s_linux" % basename
209        with ZipFile(path_join(path, linux_dir + ".zip"), "w") as linux_zip:
210            m.zip_write(linux_zip, linux_dir, "sysrom.dat", m.sysrom.to_bytes())
211            if icon_png: m.zip_write(linux_zip, linux_dir, "%s.png" % basename, icon_png)
212            m.zip_write(linux_zip, linux_dir, basename, m.picotron_dat.get(SysRomIndex.linux_exe), exec=True)
213        
214        icns_data = m.create_icns_data(icon_icnsdata, has_alpha=True) if icon_icnsdata else None
215
216        # unfortunately, the plist template isn't in the dats - only in the "real" exe (not even in the dat's exes...).
217        info_plist = file_read_text(path_join(get_res_path(), "template.plist"))
218        info_plist = info_plist.replace("%s.%s", "picotron_author.%s" % basename)
219        info_plist = info_plist.replace("%s", basename)
220
221        osx_dir = path_join("%s_mac" % basename, "%s.app" % basename)
222        with ZipFile(path_join(path, "%s_mac.zip" % basename), "w") as osx_zip:
223            osx_cont_dir = m.zip_mkdir(osx_zip, osx_dir, "Contents")
224            osx_mac_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "MacOS")
225            osx_res_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "Resources")
226            m.zip_write(osx_zip, osx_mac_dir, "sysrom.dat", m.sysrom.to_bytes())
227            m.zip_write(osx_zip, osx_mac_dir, basename, m.picotron_dat.get(SysRomIndex.mac_exe), exec=True)
228            if icns_data: m.zip_write(osx_zip, osx_res_dir, "%s.icns" % basename, icns_data)
229            m.zip_write(osx_zip, osx_cont_dir, "Info.plist", info_plist.encode())
230
231            osx_sdl_indir = m.picotron_dat.get(SysRomIndex.mac_sdl, dir=True)
232            osx_fw_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "Frameworks")
233            osx_sdlfw_dir = m.zip_mkdir(osx_zip, osx_fw_dir, "SDL2.framework")
234            m.zip_copy(osx_zip, osx_sdlfw_dir, osx_sdl_indir, exclude="_CodeSignature")
235            osx_sdlver_dir = m.zip_mkdir(osx_zip, osx_sdlfw_dir, "Versions")
236            m.zip_copy(osx_zip, m.zip_mkdir(osx_zip, osx_sdlver_dir, "Current"), osx_sdl_indir)
237            m.zip_copy(osx_zip, m.zip_mkdir(osx_zip, osx_sdlver_dir, "A"), osx_sdl_indir)
238
239def read_sysrom_file(path):
240    return SysRom(file_read(path))
241
242def read_cart64_export(path, format):
243    """Read a Cart64Export from the given path, assuming it is in the given format"""
244    if format == Cart64Format.dat:
245        return SysRomExport64(file_read(path))
246    elif format == Cart64Format.html:
247        return HtmlExport64(file_read_text(path))
248    else:
249        throw(f"invalid export format: {format}")
250
251def write_cart64_export(path, export, delete_existing=False):
252    """Write a CartExport to the given path"""
253    if isinstance(export, SysRomExport64):
254        file_write(path, export.to_bytes())
255    elif isinstance(export, HtmlExport64):
256        file_write_text(path, export.text)
257    elif isinstance(export, FullExport64):
258        export.save(path, delete_existing=delete_existing)
259    else:
260        fail("invalid cart export")
261
262def create_cart64_export(format, pico_dat, **opts):
263    """Create a Cart64Export in the given format"""
264    if format == Cart64Format.dat:
265        return SysRomExport64.create(pico_dat, **opts)
266    elif format == Cart64Format.html:
267        return HtmlExport64.create(pico_dat, **opts)
268    elif format == Cart64Format.bin:
269        return FullExport64.create(pico_dat, **opts)
270    else:
271        throw(f"invalid export format: {format}")
272
273def write_to_cart64_export(path, cart, format, pico_dat=None, export_name=None, delete_existing=False, **opts):
274    if not export_name:
275        export_name = path_basename_no_extension(path)
276    
277    assert isinstance(pico_dat, SysRom)
278    export = create_cart64_export(format, pico_dat, cart=cart, export_name=export_name)
279    export.set_cart(cart, **opts)
280    write_cart64_export(path, export, delete_existing)
281
282from picotron_cart import read_cart64_from_rom, write_cart64_to_rom, write_cart64, k_rom_header_sig, Cart64Format
k_icon64_size = Point(x=128, y=128)
class Cart64Export:
13class Cart64Export:
14    """A picotron export"""
15
16    # def get_cart(m, **opts)
17    # def set_cart(m, cart, **opts)
18    
19    def dump_contents(m, dest, fmt, **_):
20        throw("dumping misc. contents is only support for a .dat file")

A picotron export

def dump_contents(m, dest, fmt, **_):
19    def dump_contents(m, dest, fmt, **_):
20        throw("dumping misc. contents is only support for a .dat file")
class SysRom:
22class SysRom:
23    """A picotron sysrom, used in both exports and in picotron.dat"""
24
25    def __init__(m, data=None):
26        m.entries = []
27        if data:
28            with BinaryReader(BytesIO(data), big_end=True) as r:
29                while not r.eof():
30                    size = r.u32()
31                    entry = r.bytes(size)
32                    m.entries.append(entry)
33
34    class SysRomDir:
35        def __init__(m, idx, entry):
36            m.idx = idx
37            m.files = read_cart64_from_rom(entry).files
38        
39        def get(m, name, strict=True):
40            file = m.files.get(name)
41            if not file:
42                if strict:
43                    throw(f"expected to find {name} in dat {m.idx} dir")
44                else:
45                    return None
46            check(file.is_raw, "expected to find raw files inside dat dir")
47            return file.data
48
49    def get(m, idx, strict=True, dir=False):
50        entry = list_get(m.entries, int(idx))
51        if entry is None and strict:
52            throw(f"expected to find {idx} in dat file")
53        return m.SysRomDir(idx, entry) if dir else entry
54
55    def set(m, idx, value):
56        list_set(m.entries, int(idx), value, b"")
57
58    def to_bytes(m):
59        with BinaryWriter(big_end=True) as w:
60            for entry in m.entries:
61                w.u32(len(entry))
62                w.bytes(entry)
63            
64            return w.f.getvalue()
65
66    def dump_contents(m, dest, fmt, **_):
67        cart_ext = f".{fmt}" if fmt.is_ext else ""
68        for i, entry in enumerate(m.entries):
69            is_cart = entry.startswith(k_rom_header_sig)
70            path = path_join(dest, m.entry_name(i) + (cart_ext if is_cart else ""))
71
72            if is_cart and fmt != Cart64Format.rom:
73                write_cart64(path, read_cart64_from_rom(entry), fmt)
74            else:
75                file_write(path, entry)

A picotron sysrom, used in both exports and in picotron.dat

SysRom(data=None)
25    def __init__(m, data=None):
26        m.entries = []
27        if data:
28            with BinaryReader(BytesIO(data), big_end=True) as r:
29                while not r.eof():
30                    size = r.u32()
31                    entry = r.bytes(size)
32                    m.entries.append(entry)
def get(m, idx, strict=True, dir=False):
49    def get(m, idx, strict=True, dir=False):
50        entry = list_get(m.entries, int(idx))
51        if entry is None and strict:
52            throw(f"expected to find {idx} in dat file")
53        return m.SysRomDir(idx, entry) if dir else entry
def set(m, idx, value):
55    def set(m, idx, value):
56        list_set(m.entries, int(idx), value, b"")
def to_bytes(m):
58    def to_bytes(m):
59        with BinaryWriter(big_end=True) as w:
60            for entry in m.entries:
61                w.u32(len(entry))
62                w.bytes(entry)
63            
64            return w.f.getvalue()
def dump_contents(m, dest, fmt, **_):
66    def dump_contents(m, dest, fmt, **_):
67        cart_ext = f".{fmt}" if fmt.is_ext else ""
68        for i, entry in enumerate(m.entries):
69            is_cart = entry.startswith(k_rom_header_sig)
70            path = path_join(dest, m.entry_name(i) + (cart_ext if is_cart else ""))
71
72            if is_cart and fmt != Cart64Format.rom:
73                write_cart64(path, read_cart64_from_rom(entry), fmt)
74            else:
75                file_write(path, entry)
class SysRom.SysRomDir:
34    class SysRomDir:
35        def __init__(m, idx, entry):
36            m.idx = idx
37            m.files = read_cart64_from_rom(entry).files
38        
39        def get(m, name, strict=True):
40            file = m.files.get(name)
41            if not file:
42                if strict:
43                    throw(f"expected to find {name} in dat {m.idx} dir")
44                else:
45                    return None
46            check(file.is_raw, "expected to find raw files inside dat dir")
47            return file.data
SysRom.SysRomDir(idx, entry)
35        def __init__(m, idx, entry):
36            m.idx = idx
37            m.files = read_cart64_from_rom(entry).files
def get(m, name, strict=True):
39        def get(m, name, strict=True):
40            file = m.files.get(name)
41            if not file:
42                if strict:
43                    throw(f"expected to find {name} in dat {m.idx} dir")
44                else:
45                    return None
46            check(file.is_raw, "expected to find raw files inside dat dir")
47            return file.data
class SysRomIndex(utils.Enum):
77class SysRomIndex(Enum):
78    info = 0
79    system = 1; cart = 2
80    html_info = 3; linux_exe = 4
81    win_exe = 5; win_sdl = 6
82    mac_exe = 7; mac_sdl = 8

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 _.

SysRomIndex(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}")
html_info = SysRomIndex.html_info
linux_exe = SysRomIndex.linux_exe
value
class SysRomExport64(SysRom, Cart64Export):
 84class SysRomExport64(SysRom, Cart64Export):
 85    def get_cart(m, **opts):
 86        entry = m.get(SysRomIndex.cart, strict=False)
 87        if not entry:
 88            throw("no cart in sysrom file")
 89        return read_cart64_from_rom(entry, **opts)
 90
 91    def set_cart(m, cart, **opts):
 92        data = write_cart64_to_rom(cart, **opts)
 93        m.set(SysRomIndex.cart, data)
 94        
 95    def entry_name(m, i):
 96        try:
 97            return str(SysRomIndex(i))
 98        except ValueError:
 99            return f"unk{i}"
100    
101    @staticmethod
102    def create(picotron_dat, cart=None, **_):
103        m = SysRomExport64()
104        m.set(SysRomIndex.info, cart.export_home.encode() if cart else b"")
105        m.set(SysRomIndex.system, picotron_dat.get(SysRomIndex.cart))
106        return m

A picotron sysrom, used in both exports and in picotron.dat

def get_cart(m, **opts):
85    def get_cart(m, **opts):
86        entry = m.get(SysRomIndex.cart, strict=False)
87        if not entry:
88            throw("no cart in sysrom file")
89        return read_cart64_from_rom(entry, **opts)
def set_cart(m, cart, **opts):
91    def set_cart(m, cart, **opts):
92        data = write_cart64_to_rom(cart, **opts)
93        m.set(SysRomIndex.cart, data)
def entry_name(m, i):
95    def entry_name(m, i):
96        try:
97            return str(SysRomIndex(i))
98        except ValueError:
99            return f"unk{i}"
@staticmethod
def create(picotron_dat, cart=None, **_):
101    @staticmethod
102    def create(picotron_dat, cart=None, **_):
103        m = SysRomExport64()
104        m.set(SysRomIndex.info, cart.export_home.encode() if cart else b"")
105        m.set(SysRomIndex.system, picotron_dat.get(SysRomIndex.cart))
106        return m
class HtmlExport64(Cart64Export):
108class HtmlExport64(Cart64Export):
109    def __init__(m, text):
110        m.text = text
111
112    def find_cart(m):
113        match = re.search(r'p64cart_str="([0-9a-fA-F]*)"', m.text)
114        if not match:
115            throw("can't find p64cart_str var in html")
116        return match
117
118    def get_cart(m, **opts):
119        match = m.find_cart()
120        return read_cart64_from_rom(bytes.fromhex(match.group(1)), **opts)
121
122    def set_cart(m, cart, **opts):
123        rom = write_cart64_to_rom(cart, **opts)
124        m.text = str_replace_between(m.text, *m.find_cart().span(1), rom.hex())
125
126    @staticmethod
127    def create(picotron_dat, cart=None, **_):
128        html_info = picotron_dat.get(SysRomIndex.html_info, dir=True)
129        html = html_info.get("shell.html").decode()
130        js = html_info.get("picotron_player.js").decode()
131        match = re.search(r'// ##pcart##\s+', html)
132        if not match:
133            throw("can't find pcart comment in html template")
134        
135        export_home = cart.export_home if cart else ""
136        html = str_insert(html, match.end(), f'\np64cart_str="";\nexport_home_str = "{export_home}";\n{js}')
137
138        title = list_get(cart.title, 0) if cart else None
139        html = html.replace("##page_title##", title or "Picotron Cartridge")
140
141        label = cart.load_label() if cart else None
142        label_png = label.convert(PixelFormat.rgb8).save() if label else None
143        if e(label_png):
144            label_url = "data:image/png;base64," + base64.b64encode(label_png).decode()
145            html = html.replace("##label_file##", label_url)
146
147        return HtmlExport64(html)

A picotron export

HtmlExport64(text)
109    def __init__(m, text):
110        m.text = text
def find_cart(m):
112    def find_cart(m):
113        match = re.search(r'p64cart_str="([0-9a-fA-F]*)"', m.text)
114        if not match:
115            throw("can't find p64cart_str var in html")
116        return match
def get_cart(m, **opts):
118    def get_cart(m, **opts):
119        match = m.find_cart()
120        return read_cart64_from_rom(bytes.fromhex(match.group(1)), **opts)
def set_cart(m, cart, **opts):
122    def set_cart(m, cart, **opts):
123        rom = write_cart64_to_rom(cart, **opts)
124        m.text = str_replace_between(m.text, *m.find_cart().span(1), rom.hex())
@staticmethod
def create(picotron_dat, cart=None, **_):
126    @staticmethod
127    def create(picotron_dat, cart=None, **_):
128        html_info = picotron_dat.get(SysRomIndex.html_info, dir=True)
129        html = html_info.get("shell.html").decode()
130        js = html_info.get("picotron_player.js").decode()
131        match = re.search(r'// ##pcart##\s+', html)
132        if not match:
133            throw("can't find pcart comment in html template")
134        
135        export_home = cart.export_home if cart else ""
136        html = str_insert(html, match.end(), f'\np64cart_str="";\nexport_home_str = "{export_home}";\n{js}')
137
138        title = list_get(cart.title, 0) if cart else None
139        html = html.replace("##page_title##", title or "Picotron Cartridge")
140
141        label = cart.load_label() if cart else None
142        label_png = label.convert(PixelFormat.rgb8).save() if label else None
143        if e(label_png):
144            label_url = "data:image/png;base64," + base64.b64encode(label_png).decode()
145            html = html.replace("##label_file##", label_url)
146
147        return HtmlExport64(html)
Inherited Members
Cart64Export
dump_contents
class FullExport64(Cart64Export, pico_export.FullExportBase):
149class FullExport64(Cart64Export, FullExportBase):
150    def __init__(m, picotron_dat):
151        super().__init__()
152        m.picotron_dat = picotron_dat
153
154    @staticmethod
155    def create(picotron_dat, export_name="", **opts):
156        m = FullExport64(picotron_dat)
157        m.export_name = export_name
158        m.cart = None
159
160        m.sysrom = SysRomExport64.create(picotron_dat, **opts)
161        m.html = HtmlExport64.create(picotron_dat, **opts)
162        m.exports = [m.sysrom, m.html]
163        return m
164
165    def set_cart(m, cart, **opts):
166        m.cart = cart
167        for export in m.exports:
168            export.set_cart(cart, **opts)
169
170    def zip_copy(m, zip, dir, datdir, exclude=None):
171        for name, file in datdir.files.items():
172            if not name.endswith(".info.pod"):
173                if exclude and name.startswith(exclude):
174                    continue
175
176                exec = "." not in path_basename(name) # ???
177                m.zip_write(zip, dir, name, default(file.data, b""), exec=exec, is_dir=file.is_dir)
178
179    def save(m, path, delete_existing=False):
180        dir_create(path, delete_existing=delete_existing)
181        basename = m.export_name
182
183        icon = m.cart.load_icon()
184        if icon:
185            icon = icon.resize(k_icon64_size)
186            icon_bmpdata = icon.to_data(PixelFormat.bgra8, flip=True)
187            icon_icnsdata = icon.to_data(PixelFormat.rgba8)
188            icon_png = icon.convert(PixelFormat.rgba8).save()
189        else:
190            icon_bmpdata = icon_icnsdata = icon_png = None
191
192        html_path = path_join(path, "%s.html" % basename)
193        file_write_text(html_path, m.html.text)
194
195        exe_data = m.picotron_dat.get(SysRomIndex.win_exe)
196        if icon_bmpdata:
197            exe_icon_i = m.find_icon_offset_in_exe(exe_data)
198            if e(exe_icon_i):
199                exe_data = str_replace_at(exe_data, exe_icon_i, 0x10000, icon_bmpdata)
200            else:
201                eprint("couldn't find icon in exe, not changing it")
202
203        win_dir = "%s_windows" % basename
204        with ZipFile(path_join(path, win_dir + ".zip"), "w") as win_zip:
205            m.zip_write(win_zip, win_dir, "%s.exe" % basename, exe_data, exec=True)
206            m.zip_write(win_zip, win_dir, "sysrom.dat", m.sysrom.to_bytes())
207            m.zip_write(win_zip, win_dir, "SDL2.dll", m.picotron_dat.get(SysRomIndex.win_sdl))
208
209        linux_dir = "%s_linux" % basename
210        with ZipFile(path_join(path, linux_dir + ".zip"), "w") as linux_zip:
211            m.zip_write(linux_zip, linux_dir, "sysrom.dat", m.sysrom.to_bytes())
212            if icon_png: m.zip_write(linux_zip, linux_dir, "%s.png" % basename, icon_png)
213            m.zip_write(linux_zip, linux_dir, basename, m.picotron_dat.get(SysRomIndex.linux_exe), exec=True)
214        
215        icns_data = m.create_icns_data(icon_icnsdata, has_alpha=True) if icon_icnsdata else None
216
217        # unfortunately, the plist template isn't in the dats - only in the "real" exe (not even in the dat's exes...).
218        info_plist = file_read_text(path_join(get_res_path(), "template.plist"))
219        info_plist = info_plist.replace("%s.%s", "picotron_author.%s" % basename)
220        info_plist = info_plist.replace("%s", basename)
221
222        osx_dir = path_join("%s_mac" % basename, "%s.app" % basename)
223        with ZipFile(path_join(path, "%s_mac.zip" % basename), "w") as osx_zip:
224            osx_cont_dir = m.zip_mkdir(osx_zip, osx_dir, "Contents")
225            osx_mac_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "MacOS")
226            osx_res_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "Resources")
227            m.zip_write(osx_zip, osx_mac_dir, "sysrom.dat", m.sysrom.to_bytes())
228            m.zip_write(osx_zip, osx_mac_dir, basename, m.picotron_dat.get(SysRomIndex.mac_exe), exec=True)
229            if icns_data: m.zip_write(osx_zip, osx_res_dir, "%s.icns" % basename, icns_data)
230            m.zip_write(osx_zip, osx_cont_dir, "Info.plist", info_plist.encode())
231
232            osx_sdl_indir = m.picotron_dat.get(SysRomIndex.mac_sdl, dir=True)
233            osx_fw_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "Frameworks")
234            osx_sdlfw_dir = m.zip_mkdir(osx_zip, osx_fw_dir, "SDL2.framework")
235            m.zip_copy(osx_zip, osx_sdlfw_dir, osx_sdl_indir, exclude="_CodeSignature")
236            osx_sdlver_dir = m.zip_mkdir(osx_zip, osx_sdlfw_dir, "Versions")
237            m.zip_copy(osx_zip, m.zip_mkdir(osx_zip, osx_sdlver_dir, "Current"), osx_sdl_indir)
238            m.zip_copy(osx_zip, m.zip_mkdir(osx_zip, osx_sdlver_dir, "A"), osx_sdl_indir)

A picotron export

FullExport64(picotron_dat)
150    def __init__(m, picotron_dat):
151        super().__init__()
152        m.picotron_dat = picotron_dat
@staticmethod
def create(picotron_dat, export_name='', **opts):
154    @staticmethod
155    def create(picotron_dat, export_name="", **opts):
156        m = FullExport64(picotron_dat)
157        m.export_name = export_name
158        m.cart = None
159
160        m.sysrom = SysRomExport64.create(picotron_dat, **opts)
161        m.html = HtmlExport64.create(picotron_dat, **opts)
162        m.exports = [m.sysrom, m.html]
163        return m
def set_cart(m, cart, **opts):
165    def set_cart(m, cart, **opts):
166        m.cart = cart
167        for export in m.exports:
168            export.set_cart(cart, **opts)
def zip_copy(m, zip, dir, datdir, exclude=None):
170    def zip_copy(m, zip, dir, datdir, exclude=None):
171        for name, file in datdir.files.items():
172            if not name.endswith(".info.pod"):
173                if exclude and name.startswith(exclude):
174                    continue
175
176                exec = "." not in path_basename(name) # ???
177                m.zip_write(zip, dir, name, default(file.data, b""), exec=exec, is_dir=file.is_dir)
def save(m, path, delete_existing=False):
179    def save(m, path, delete_existing=False):
180        dir_create(path, delete_existing=delete_existing)
181        basename = m.export_name
182
183        icon = m.cart.load_icon()
184        if icon:
185            icon = icon.resize(k_icon64_size)
186            icon_bmpdata = icon.to_data(PixelFormat.bgra8, flip=True)
187            icon_icnsdata = icon.to_data(PixelFormat.rgba8)
188            icon_png = icon.convert(PixelFormat.rgba8).save()
189        else:
190            icon_bmpdata = icon_icnsdata = icon_png = None
191
192        html_path = path_join(path, "%s.html" % basename)
193        file_write_text(html_path, m.html.text)
194
195        exe_data = m.picotron_dat.get(SysRomIndex.win_exe)
196        if icon_bmpdata:
197            exe_icon_i = m.find_icon_offset_in_exe(exe_data)
198            if e(exe_icon_i):
199                exe_data = str_replace_at(exe_data, exe_icon_i, 0x10000, icon_bmpdata)
200            else:
201                eprint("couldn't find icon in exe, not changing it")
202
203        win_dir = "%s_windows" % basename
204        with ZipFile(path_join(path, win_dir + ".zip"), "w") as win_zip:
205            m.zip_write(win_zip, win_dir, "%s.exe" % basename, exe_data, exec=True)
206            m.zip_write(win_zip, win_dir, "sysrom.dat", m.sysrom.to_bytes())
207            m.zip_write(win_zip, win_dir, "SDL2.dll", m.picotron_dat.get(SysRomIndex.win_sdl))
208
209        linux_dir = "%s_linux" % basename
210        with ZipFile(path_join(path, linux_dir + ".zip"), "w") as linux_zip:
211            m.zip_write(linux_zip, linux_dir, "sysrom.dat", m.sysrom.to_bytes())
212            if icon_png: m.zip_write(linux_zip, linux_dir, "%s.png" % basename, icon_png)
213            m.zip_write(linux_zip, linux_dir, basename, m.picotron_dat.get(SysRomIndex.linux_exe), exec=True)
214        
215        icns_data = m.create_icns_data(icon_icnsdata, has_alpha=True) if icon_icnsdata else None
216
217        # unfortunately, the plist template isn't in the dats - only in the "real" exe (not even in the dat's exes...).
218        info_plist = file_read_text(path_join(get_res_path(), "template.plist"))
219        info_plist = info_plist.replace("%s.%s", "picotron_author.%s" % basename)
220        info_plist = info_plist.replace("%s", basename)
221
222        osx_dir = path_join("%s_mac" % basename, "%s.app" % basename)
223        with ZipFile(path_join(path, "%s_mac.zip" % basename), "w") as osx_zip:
224            osx_cont_dir = m.zip_mkdir(osx_zip, osx_dir, "Contents")
225            osx_mac_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "MacOS")
226            osx_res_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "Resources")
227            m.zip_write(osx_zip, osx_mac_dir, "sysrom.dat", m.sysrom.to_bytes())
228            m.zip_write(osx_zip, osx_mac_dir, basename, m.picotron_dat.get(SysRomIndex.mac_exe), exec=True)
229            if icns_data: m.zip_write(osx_zip, osx_res_dir, "%s.icns" % basename, icns_data)
230            m.zip_write(osx_zip, osx_cont_dir, "Info.plist", info_plist.encode())
231
232            osx_sdl_indir = m.picotron_dat.get(SysRomIndex.mac_sdl, dir=True)
233            osx_fw_dir = m.zip_mkdir(osx_zip, osx_cont_dir, "Frameworks")
234            osx_sdlfw_dir = m.zip_mkdir(osx_zip, osx_fw_dir, "SDL2.framework")
235            m.zip_copy(osx_zip, osx_sdlfw_dir, osx_sdl_indir, exclude="_CodeSignature")
236            osx_sdlver_dir = m.zip_mkdir(osx_zip, osx_sdlfw_dir, "Versions")
237            m.zip_copy(osx_zip, m.zip_mkdir(osx_zip, osx_sdlver_dir, "Current"), osx_sdl_indir)
238            m.zip_copy(osx_zip, m.zip_mkdir(osx_zip, osx_sdlver_dir, "A"), osx_sdl_indir)
def read_sysrom_file(path):
240def read_sysrom_file(path):
241    return SysRom(file_read(path))
def read_cart64_export(path, format):
243def read_cart64_export(path, format):
244    """Read a Cart64Export from the given path, assuming it is in the given format"""
245    if format == Cart64Format.dat:
246        return SysRomExport64(file_read(path))
247    elif format == Cart64Format.html:
248        return HtmlExport64(file_read_text(path))
249    else:
250        throw(f"invalid export format: {format}")

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

def write_cart64_export(path, export, delete_existing=False):
252def write_cart64_export(path, export, delete_existing=False):
253    """Write a CartExport to the given path"""
254    if isinstance(export, SysRomExport64):
255        file_write(path, export.to_bytes())
256    elif isinstance(export, HtmlExport64):
257        file_write_text(path, export.text)
258    elif isinstance(export, FullExport64):
259        export.save(path, delete_existing=delete_existing)
260    else:
261        fail("invalid cart export")

Write a CartExport to the given path

def create_cart64_export(format, pico_dat, **opts):
263def create_cart64_export(format, pico_dat, **opts):
264    """Create a Cart64Export in the given format"""
265    if format == Cart64Format.dat:
266        return SysRomExport64.create(pico_dat, **opts)
267    elif format == Cart64Format.html:
268        return HtmlExport64.create(pico_dat, **opts)
269    elif format == Cart64Format.bin:
270        return FullExport64.create(pico_dat, **opts)
271    else:
272        throw(f"invalid export format: {format}")

Create a Cart64Export in the given format

def write_to_cart64_export( path, cart, format, pico_dat=None, export_name=None, delete_existing=False, **opts):
274def write_to_cart64_export(path, cart, format, pico_dat=None, export_name=None, delete_existing=False, **opts):
275    if not export_name:
276        export_name = path_basename_no_extension(path)
277    
278    assert isinstance(pico_dat, SysRom)
279    export = create_cart64_export(format, pico_dat, cart=cart, export_name=export_name)
280    export.set_cart(cart, **opts)
281    write_cart64_export(path, export, delete_existing)