Functions.py (view raw)
1#!/usr/bin/python3
2from hashlib import md5
3from tkinter.messagebox import showwarning, showinfo
4from ips_util import Patch
5from shutil import copyfile
6import os, subprocess, Constants
7
8def check_rom(filename):
9 if not os.path.exists(filename):
10 return False
11 with open(filename, 'rb') as f:
12 file_hash = md5()
13 while chunk := f.read(8192):
14 file_hash.update(chunk)
15
16 return file_hash.hexdigest() == 'f41e36204356974c94fabf7d144dd32a'
17
18def apply_preset(app, preset_name):
19 if preset_name in Constants.PRESETS:
20 preset = Constants.PRESETS[preset_name]
21 for key in preset.keys():
22 getattr(app, key).set(preset[key])
23 return True
24 return False
25
26def apply_patch(base, ips):
27 patch = Patch.load(ips)
28 target = base + '_temp'
29
30 with open(base, 'rb') as f_in:
31 with open(target, 'w+b') as f_out:
32 f_out.write(patch.apply(f_in.read()))
33
34 os.replace(target, base)
35
36def show_warning(message):
37 showwarning(title=Constants.WARNING_TITLE, message=message)
38
39def set_progress(app, percent, message):
40 app.progress.set(percent)
41 app.status_text.set(message)
42
43def read_options(app, keys):
44 output = {}
45 for key in keys:
46 new_option = getattr(app, key).get()
47 output[key] = Constants.ALT_FILENAMES[new_option]
48 return output
49
50def start_patching(app):
51 set_progress(app, 20, Constants.STATUS_MD5)
52 delete_list = []
53
54 sel_filenames = read_options(app, Constants.DEF_FILENAMES.keys())
55
56 for key in sel_filenames.keys():
57 sel_list = sel_filenames[key]
58 def_list = Constants.DEF_FILENAMES[key]
59
60 for idx, i in enumerate(sel_list):
61 original = os.path.join(Constants.PATH_ALT, sel_list[idx])
62 target = os.path.join(Constants.PATH_TOOLS, def_list[idx])
63
64 copyfile(original, target)
65 delete_list.append(target)
66
67 target = os.path.join(Constants.PATH_TOOLS, 'test.gba')
68 copyfile(app.baserom, target)
69 set_progress(app, 40, Constants.STATUS_COPIED)
70
71 p = subprocess.Popen([Constants.OS_FILENAMES['xkas'], '-o', 'test.gba', 'm12.asm'],
72 cwd=Constants.PATH_TOOLS, shell=Constants.OS_SHELL)
73 p.wait()
74 set_progress(app, 50, Constants.STATUS_ASSEMBLY)
75
76 p = subprocess.Popen([Constants.OS_FILENAMES['insert']],
77 cwd=Constants.PATH_TOOLS, shell=Constants.OS_SHELL)
78 p.wait()
79 set_progress(app, 70, Constants.STATUS_INJECTED)
80
81 sel_patches = read_options(app, Constants.DEF_PATCHES)
82
83 for key in sel_patches.keys():
84 val = sel_patches[key]
85
86 if val is not None:
87 path = os.path.join(Constants.PATH_ALT, val)
88 apply_patch(target, path)
89
90 os.replace(target, Constants.FINAL_ROM_NAME)
91 set_progress(app, 90, Constants.STATUS_PATCHED)
92
93 for item in delete_list:
94 os.remove(item)
95
96 set_progress(app, 100, Constants.STATUS_CLEANED)
97 showinfo(title=Constants.SUCCESS_TITLE, message=Constants.SUCCESS_CONTENT)