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 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 show_success(message):
40 showinfo(title=Constants.SUCCESS_TITLE, message=message)
41
42def set_progress(app, percent, message):
43 app.progress.set(percent)
44 app.status_text.set(message)
45
46def read_options(app, output, keys):
47 for key in keys:
48 new_option = getattr(app, key).get()
49 output[key] = Constants.ALT_FILENAMES[new_option]
50
51def start_patching(app):
52 set_progress(app, 20, Constants.STATUS_MD5)
53 delete_list = []
54
55 #sel_filenames = {}
56 #sel_patches = {}
57 read_options(app, sel_filenames, Constants.DEF_FILENAMES.keys())
58 read_options(app, sel_patches, Constants.DEF_PATCHES)
59
60 for key in sel_filenames.keys():
61 sel_list = sel_filenames[key]
62 def_list = Constants.DEF_FILENAMES[key]
63
64 for idx, i in enumerate(sel_list):
65 original = os.path.join(Constants.PATH_ALT, sel_list[idx])
66 target = os.path.join(Constants.PATH_TOOLS, def_list[idx])
67
68 copyfile(original, target)
69 delete_list.append(target)
70
71 target = os.path.join(Constants.PATH_TOOLS, 'test.gba')
72 copyfile(app.baserom, target)
73
74 set_progress(app, 40, Constants.STATUS_COPIED)
75 p = subprocess.Popen([Constants.OS_FILENAMES['xkas'], '-o', 'test.gba', 'm12.asm'],
76 cwd=Constants.PATH_TOOLS, shell=Constants.OS_SHELL)
77 p.wait()
78
79 set_progress(app, 50, Constants.STATUS_ASSEMBLY)
80 p = subprocess.Popen([Constants.OS_FILENAMES['insert']],
81 cwd=Constants.PATH_TOOLS, shell=Constants.OS_SHELL)
82 p.wait()
83
84 set_progress(app, 70, Constants.STATUS_INJECTED)
85 for key in sel_patches.keys():
86 val = sel_patches[key]
87
88 if val is not None:
89 path = os.path.join(Constants.PATH_ALT, val)
90 apply_patch(target, path)
91
92 os.replace(target, Constants.FINAL_ROM_NAME)
93
94 set_progress(app, 90, Constants.STATUS_PATCHED)
95 for item in delete_list:
96 os.remove(item)
97
98 set_progress(app, 100, Constants.STATUS_CLEANED)
99 show_success(Constants.SUCCESS_CONTENT)