-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTWLMagician.py
2579 lines (2167 loc) · 102 KB
/
TWLMagician.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# coding=utf-8
# TWLMagician
# Version 1.3.7
# Author: R-YaTian
# Original "HiyaCFW-Helper" Author: mondul <[email protected]>
from tkinter import (Tk, Frame, LabelFrame, PhotoImage, Button, Entry, Checkbutton, Radiobutton, OptionMenu,
Label, Toplevel, Scrollbar, Text, StringVar, IntVar, RIGHT, W, X, Y, DISABLED, NORMAL, SUNKEN,
END)
from tkinter.messagebox import askokcancel, showerror, showinfo, WARNING
from tkinter.filedialog import askopenfilename, askdirectory
from os import path, remove, chmod, listdir, environ, mkdir
from sys import exit, stdout, argv
from threading import Thread
from queue import Queue, Empty
from hashlib import sha1
from urllib.request import urlopen
from urllib.error import URLError
from subprocess import Popen, PIPE
from struct import unpack_from
from shutil import rmtree, copyfile
from re import search
from inspect import isclass
from datetime import datetime
from time import sleep
from binascii import hexlify, unhexlify
from appgen import agen
from py_langs.langs import lang_init
from pyutils import copyfileobj, copytree
import ctypes
import platform
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
ntime_tmp = None
downloadfile = False
version_number = 137
# Check Update
def get_version():
if path.isfile('version.bin'):
remove('version.bin')
if loc == 'zh_cn' or (loca == 'zh_hans' and region == 'cn'):
version_url = 'https://gitee.com/ryatian/mirrors/raw/master/'
else:
version_url = 'https://raw.githubusercontent.com/R-YaTian/TWLMagician/main/Res/'
try:
with urlopen(version_url + 'version.bin') as src0, open('version.bin', 'wb') as dst0:
copyfileobj(src0, dst0, show_progress=False)
with open('version.bin', 'rb') as ftmp:
data = ftmp.read()
number = unpack_from('<I', data, offset=0)[0]
remove('version.bin')
return number
except:
if path.isfile('version.bin'):
remove('version.bin')
return -1
def WriteRestartCmd():
from os import startfile
fbat = open('upgrade.cmd', 'w')
TempList = '@echo off\n'
TempList += 'if not exist ' + 'OTA.exe' + ' exit\n'
TempList += 'sleep 3\n'
TempList += 'start OTA.exe\n'
TempList += 'del %0\n'
fbat.write(TempList)
fbat.close()
startfile('upgrade.cmd')
def check_update():
printl(_('检查更新中...'))
if path.isfile('OTA.exe'):
remove('OTA.exe')
new_version = get_version()
if new_version == -1:
printl(_('检查更新失败'))
elif new_version > version_number:
if sysname == 'Darwin' or sysname == 'Linux':
import webbrowser
if loc == 'zh_cn' or (loca == 'zh_hans' and region == 'cn'):
release_url = 'https://gitee.com/ryatian/mirrors/releases/tag/TWLMagician'
else:
release_url = 'https://github.com/R-YaTian/TWLMagician/releases/latest'
showinfo(_('提示'), _('检测到新版本, 由于本程序新版本包含重要更新\n暂不支持跳过更新, 即将前往发布页'))
webbrowser.open(release_url, 2, autoraise=True)
exit(1)
else:
showinfo(_('提示'), _('检测到新版本, 由于本程序新版本包含重要更新\n暂不支持跳过更新, 即将下载并更新'))
pybits = platform.architecture()[0]
ota_fname = 'OTA.exe' if pybits == '64bit' else 'OTA_x86.exe'
if loc == 'zh_cn' or (loca == 'zh_hans' and region == 'cn'):
ota_url = 'https://gitee.com/ryatian/mirrors/releases/download/Res/'
else:
ota_url = 'https://raw.githubusercontent.com/R-YaTian/TWLMagician/main/Res/'
try:
with urlopen(ota_url + ota_fname) as src0, open('OTA.exe', 'wb') as dst0:
copyfileobj(src0, dst0)
WriteRestartCmd()
except:
showerror(_('错误'), _('下载或执行更新失败, 程序即将退出'))
exit(1)
else:
printl(_('当前为最新版本!'))
# TimeLog-Print
def printl(*objects, sep=' ', end='\n', file=stdout, flush=False, fixn=False):
global ntime_tmp, downloadfile
clog = open('Console.log', 'a', encoding="UTF-8")
ntime = datetime.now().strftime('%F %T')
if downloadfile:
fixn = True
downloadfile = False
if ntime_tmp != ntime or ntime_tmp is None:
if fixn is False:
print('[' + ntime + ']')
else:
print('\n[' + ntime + ']')
clog.write('[' + ntime + ']\n')
print(*objects, sep=sep, end=end, file=file, flush=flush)
clog.write(*objects)
clog.write('\n')
ntime_tmp = ntime
clog.close()
# Thread-Control
def _async_raise(tid, exctype):
tid = ctypes.c_long(tid)
if not isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("Invalid Thread ID")
elif res != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc Failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
####################################################################################################
# Thread-safe text class
class ThreadSafeText(Text):
def __init__(self, master, **options):
Text.__init__(self, master, **options)
self.wlog = None
self.now_time_tmp = None
self.queue = Queue()
self.update_me()
def write(self, line):
self.wlog = open('Window.log', 'a', encoding="UTF-8")
now_time = datetime.now().strftime('%F %T')
if self.now_time_tmp != now_time or self.now_time_tmp is None:
self.queue.put('[' + now_time + ']')
self.wlog.write('[' + now_time + ']\n')
self.queue.put(line)
self.wlog.write(line + '\n')
self.now_time_tmp = now_time
self.wlog.close()
def update_me(self):
try:
while 1:
self.insert(END, str(self.queue.get_nowait()) + '\n')
self.see(END)
self.update_idletasks()
except Empty:
pass
self.after(500, self.update_me)
####################################################################################################
# Main application class
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.log = None
self.out_path = None
self.dialog = None
self.dest_region = None
self.cur_region = None
self.origin_region = None
self.twlp = None
self.loop_dev = None
self.raw_disk = None
self.mounted = None
self.launcher_region = None
self.suffix = None
self.proc = None
self.TThread = None
self.sd_path = None
self.sd_path1 = None
self.pack()
self.adv_mode = False
self.nand_mode = False
self.transfer_mode = False
self.setup_select = False
self.have_hiya = False
self.is_tds = False
self.have_menu = False
self.finish = False
self.image_file = StringVar()
# First row
f1 = Frame(self)
self.bak_frame = LabelFrame(f1, text=_(
'含有No$GBA footer的NAND备份文件'), padx=10, pady=10)
self.nand_button = Button(
self.bak_frame, image=nand_icon, command=self.change_mode, state=DISABLED)
self.nand_button.pack(side='left')
self.nand_file = StringVar()
self.nandfile = Entry(
self.bak_frame, textvariable=self.nand_file, state='readonly', width=40)
self.nandfile.pack(side='left')
self.chb = Button(self.bak_frame, text='...', command=self.choose_nand)
self.chb.pack(side='left')
self.bak_frame.pack(fill=X)
self.adv_frame = LabelFrame(f1, text=_('存储卡根目录'), padx=10, pady=10)
self.transfer_button = Button(
self.adv_frame, image=nand_icon, command=self.change_mode2, state=DISABLED)
self.transfer_button.pack(side='left')
self.sdp = StringVar()
self.sdpath = Entry(
self.adv_frame, textvariable=self.sdp, state='readonly', width=40)
self.sdpath.pack(side='left')
self.chb1 = Button(self.adv_frame, text='...', command=self.choose_sdp)
self.chb1.pack(side='left')
f1.pack(padx=10, pady=10, fill=X)
# Second row
f2 = Frame(self)
self.setup_frame = LabelFrame(f2, text=_('NAND解压选项'), padx=10, pady=10)
self.setup_operation = IntVar()
if fatcat is None:
if _7z is not None:
self.setup_operation.set(1)
elif osfmount is not None:
self.setup_operation.set(2)
else:
self.setup_operation.set(0)
self.rb1 = Radiobutton(self.setup_frame, text=_(
'Fatcat(默认)'), variable=self.setup_operation, value=0)
self.rb2 = Radiobutton(
self.setup_frame, text='7-Zip', variable=self.setup_operation, value=1)
self.rb3 = Radiobutton(self.setup_frame, text=_(
'OSFMount(需要管理员权限)'), variable=self.setup_operation, value=2)
self.common_pack(True)
# Check boxes
self.checks_frame = Frame(f2)
# Install TWiLight check
self.twilight = IntVar()
self.twilight.set(1)
twl_chk = Checkbutton(self.checks_frame,
text=_('同时安装TWiLightMenu++'), variable=self.twilight)
twl_chk.pack(padx=10, anchor=W)
self.appgen = IntVar()
self.appgen.set(0)
ag_chk = Checkbutton(self.checks_frame, text=_(
'使用AppGen'), variable=self.appgen)
ag_chk.pack(padx=10, anchor=W)
self.devkp = IntVar()
self.devkp.set(0)
dkp_chk = Checkbutton(self.checks_frame, text=_(
'启用系统设置-数据管理功能'), variable=self.devkp)
dkp_chk.pack(padx=10, anchor=W)
self.photo = IntVar()
self.photo.set(0)
photo_chk = Checkbutton(self.checks_frame, text=_(
'提取相册分区'), variable=self.photo)
photo_chk.pack(padx=10, anchor=W)
self.altdl = IntVar()
if loc == 'zh_cn' or (loca == 'zh_hans' and region == 'cn'):
self.altdl.set(1)
else:
self.altdl.set(0)
if loc == 'zh_cn' or (loca == 'zh_hans' and region == 'cn'):
adl_chk = Checkbutton(
self.checks_frame, text='优先使用备用载点', variable=self.altdl)
adl_chk.pack(padx=10, anchor=W)
self.checks_frame.pack(fill=X)
self.checks_frame1 = Frame(f2)
self.ag1_chk = Checkbutton(self.checks_frame1, text=_(
'使用AppGen'), variable=self.appgen, state=DISABLED)
self.ag1_chk.pack(padx=10, anchor=W)
self.updatehiya = IntVar()
self.updatehiya.set(0)
self.uh_chk = Checkbutton(self.checks_frame1, text=_(
'更新hiyaCFW'), variable=self.updatehiya, state=DISABLED)
self.uh_chk.pack(padx=10, anchor=W)
self.dkp1_chk = Checkbutton(self.checks_frame1, text=_(
'启用系统设置-数据管理功能'), variable=self.devkp, state=DISABLED)
self.dkp1_chk.pack(padx=10, anchor=W)
if loc == 'zh_cn' or (loca == 'zh_hans' and region == 'cn'):
adl1_chk = Checkbutton(
self.checks_frame1, text='优先使用备用载点', variable=self.altdl)
adl1_chk.pack(padx=10, anchor=W)
self.checks_frame2 = Frame(f2)
label = Label(self.checks_frame2, text=_("选择目标系统区域:"))
label.grid(row=0, column=0, padx=10, sticky="w")
region_items = ["JPN", "JPN-kst", "USA", "EUR", "AUS", "CHN", "KOR"]
self.selected_option = StringVar(value="JPN")
self.dropdown = OptionMenu(self.checks_frame2, self.selected_option, *region_items)
self.dropdown.grid(row=0, column=1, padx=0, pady=0, sticky="w")
self.dkp2_chk = Checkbutton(self.checks_frame2, text=_(
'启用系统设置-数据管理功能'), variable=self.devkp)
self.dkp2_chk.grid(row=1, column=0, padx=10, sticky="w")
self.ntm = IntVar()
self.ntm.set(0)
self.ntm_chk = Checkbutton(
self.checks_frame2, text=_('同时安装NTM'), variable=self.ntm)
self.ntm_chk.grid(row=2, column=0, padx=10, sticky="w")
self.updatemenu = IntVar()
self.updatemenu.set(0)
self.um_chk = Checkbutton(self.checks_frame2, text=_(
'安装或更新TWiLightMenu++'), variable=self.updatemenu)
self.um_chk.grid(row=3, column=0, padx=10, sticky="w")
if loc == 'zh_cn' or (loca == 'zh_hans' and region == 'cn'):
adl2_chk = Checkbutton(
self.checks_frame2, text='优先使用备用载点', variable=self.altdl)
adl2_chk.grid(row=4, column=0, padx=10, sticky="w")
# NAND operation frame
self.nand_frame = LabelFrame(f2, text=_('NAND操作选项'), padx=10, pady=10)
self.nand_operation = IntVar()
self.nand_operation.set(0)
rb0 = Radiobutton(self.nand_frame, text=_('安装或卸载最新版本的unlaunch'),
variable=self.nand_operation, value=2,
command=lambda: self.enable_entries(False))
if osfmount is not None or (sysname == 'Linux' and su is True) or sysname == 'Darwin':
rb0.pack(anchor=W)
Radiobutton(self.nand_frame, text=_('移除 No$GBA footer'), variable=self.nand_operation,
value=0, command=lambda: self.enable_entries(False)).pack(anchor=W)
Radiobutton(self.nand_frame, text=_('添加 No$GBA footer'), variable=self.nand_operation,
value=1, command=lambda: self.enable_entries(True)).pack(anchor=W)
fl = Frame(self.nand_frame)
self.cid_label = Label(fl, text='eMMC CID', state=DISABLED)
self.cid_label.pack(anchor=W, padx=(24, 0))
self.cid = StringVar()
self.cid_entry = Entry(fl, textvariable=self.cid,
width=35, state=DISABLED)
self.cid_entry.pack(anchor=W, padx=(24, 0))
fl.pack(anchor=W)
fr = Frame(self.nand_frame)
self.console_id_label = Label(fr, text='Console ID', state=DISABLED)
self.console_id_label.pack(anchor=W, padx=(24, 0))
self.console_id = StringVar()
self.console_id_entry = Entry(
fr, textvariable=self.console_id, width=35, state=DISABLED)
self.console_id_entry.pack(anchor=W, padx=(24, 0))
fr.pack(anchor=W)
f2.pack(fill=X)
# Third row
f3 = Frame(self)
self.start_button = Button(f3, text=_(
'开始'), width=13, command=self.start_point, state=DISABLED)
self.start_button.pack(side='left', padx=(0, 5))
self.adv_button = Button(f3, text=_(
'高级'), command=self.change_mode1, width=13)
self.back_button = Button(f3, text=_(
'返回'), command=self.change_mode, width=13)
self.back1_button = Button(f3, text=_(
'返回'), command=self.change_mode1, width=13)
self.back2_button = Button(f3, text=_(
'返回'), command=self.change_mode2, width=13)
self.adv_button.pack(side='left', padx=(0, 0))
self.exit_button = Button(f3, text=_(
'退出'), command=root.destroy, width=13)
self.exit_button.pack(side='left', padx=(5, 0))
f3.pack(pady=(10, 20))
self.folders = []
self.files = []
# General ToolTip
if sysname == 'Darwin':
from tkinter_tooltips.ToolTips import ToolTips
import tkinter.font as tk_font
widgets = [ag_chk, dkp_chk, photo_chk, self.ag1_chk,
self.dkp1_chk, self.dkp2_chk, self.adv_button]
tooltip_text = [_('提取Nand备份中的DSiWare软件并复制到\nroms/dsiware'),
_('勾选此选项将会在CFW中开启系统设置中的数据管理功能,如果\n已经在NAND中开启了此功能,则不需要勾选此选项'),
_('提取Nand备份中的相册分区文件到存储卡中,此操作会占用\n一定的存储卡空间(取决于相片数量,最多可达32MB左右)'),
_('提取SDNand中的DSiWare软件并复制到\nroms/dsiware'),
_('勾选此选项将会在CFW中开启系统设置中的数据管理功能,如果\n已经在NAND中开启了此功能,则不需要勾选此选项'),
_('勾选此选项将会在CFW中开启系统设置中的数据管理功能,如果\n已经在NAND中开启了此功能,则不需要勾选此选项'),
_('高级模式提供了单独安装TWiLightMenu++\n等功能')]
if loc == 'zh_cn' or (loca == 'zh_hans' and region == 'cn'):
widgets.append(adl_chk)
widgets.append(adl1_chk)
widgets.append(adl2_chk)
tooltip_text.append('使用备用载点可能可以提高下载必要文件的速度')
tooltip_text.append('使用备用载点可能可以提高下载必要文件的速度')
tooltip_text.append('使用备用载点可能可以提高下载必要文件的速度')
font_obj = tk_font.Font(family="Microsoft YaHei UI", size=13)
ToolTips(widgets, tooltip_text, font=font_obj)
else:
from tk_tooltip.tooltip import ToolTip
ToolTip(ag_chk, msg=_('提取Nand备份中的DSiWare软件并复制到\nroms/dsiware'))
ToolTip(dkp_chk, msg=_(
'勾选此选项将会在CFW中开启系统设置中的数据管理功能,如果已经在NAND中开启了此功能,则不需要勾选此选项'))
ToolTip(photo_chk, msg=_(
'提取Nand备份中的相册分区文件到存储卡中,此操作会占用一定的存储卡空间(取决于相片数量,最多可达32MB左右)'))
ToolTip(self.ag1_chk, msg=_(
'提取SDNand中的DSiWare软件并复制到\nroms/dsiware'))
ToolTip(self.dkp1_chk, msg=_(
'勾选此选项将会在CFW中开启系统设置中的数据管理功能,如果已经在NAND中开启了此功能,则不需要勾选此选项'))
ToolTip(self.dkp2_chk, msg=_(
'勾选此选项将会在CFW中开启系统设置中的数据管理功能,如果已经在NAND中开启了此功能,则不需要勾选此选项'))
ToolTip(self.adv_button, msg=_('高级模式提供了单独安装TWiLightMenu++等功能'))
if loc == 'zh_cn' or (loca == 'zh_hans' and region == 'cn'):
ToolTip(adl_chk, msg='使用备用载点可能可以提高下载必要文件的速度')
ToolTip(adl1_chk, msg='使用备用载点可能可以提高下载必要文件的速度')
ToolTip(adl2_chk, msg='使用备用载点可能可以提高下载必要文件的速度')
################################################################################################
def common_pack(self, init):
if osfmount or _7z is not None:
if fatcat is not None:
self.rb1.pack(anchor=W)
if _7z is not None:
self.rb2.pack(anchor=W)
if osfmount is not None:
self.rb3.pack(anchor=W)
if (fatcat is not None) or (osfmount and _7z is not None):
self.setup_frame.pack(padx=10, pady=(0, 10), fill=X)
if init is True:
self.setup_select = True
if init is not True:
self.checks_frame.pack(anchor=W)
def change_mode(self):
if self.nand_mode:
self.nand_operation.set(0)
self.enable_entries(False)
self.nand_frame.pack_forget()
self.start_button.pack_forget()
self.back_button.pack_forget()
self.exit_button.pack_forget()
self.common_pack(False)
self.start_button.pack(side='left', padx=(0, 5))
self.adv_button.pack(side='left', padx=(0, 0))
self.exit_button.pack(side='left', padx=(5, 0))
self.nand_mode = False
else:
if askokcancel(_('警告'), (_('你正要进入NAND操作模式, 请确认你知道自己在做什么, 继续吗?')), icon=WARNING):
self.have_hiya = False
self.is_tds = False
self.have_menu = False
if self.setup_select:
self.setup_frame.pack_forget()
self.setup_operation.set(0)
self.checks_frame.pack_forget()
self.start_button.pack_forget()
self.adv_button.pack_forget()
self.exit_button.pack_forget()
self.nand_frame.pack(padx=10, pady=(0, 10), fill=X)
self.start_button.pack(side='left', padx=(0, 5))
self.back_button.pack(side='left', padx=(0, 0))
self.exit_button.pack(side='left', padx=(5, 0))
self.nand_mode = True
def change_mode1(self):
if self.adv_mode:
self.transfer_button['state'] = DISABLED
self.have_menu = False
self.is_tds = False
self.have_hiya = False
self.common_set()
if self.sdp.get() != '':
self.sdp.set('')
self.adv_frame.pack_forget()
self.checks_frame1.pack_forget()
self.start_button.pack_forget()
self.back1_button.pack_forget()
self.exit_button.pack_forget()
self.bak_frame.pack(fill=X)
self.common_pack(False)
self.start_button['state'] = DISABLED
self.nand_button['state'] = DISABLED
self.start_button.pack(side='left', padx=(0, 5))
self.adv_button.pack(side='left', padx=(0, 0))
self.exit_button.pack(side='left', padx=(5, 0))
self.adv_mode = False
else:
self.have_menu = False
self.is_tds = False
self.have_hiya = False
self.common_set()
if self.nand_file.get() != '':
self.nand_file.set('')
self.bak_frame.pack_forget()
if self.setup_select:
self.setup_frame.pack_forget()
self.checks_frame.pack_forget()
self.start_button.pack_forget()
self.adv_button.pack_forget()
self.exit_button.pack_forget()
self.adv_frame.pack(fill=X)
self.checks_frame1.pack(anchor=W)
self.uh_chk['state'] = DISABLED
self.dkp1_chk['state'] = DISABLED
self.ag1_chk['state'] = DISABLED
self.start_button['state'] = DISABLED
self.start_button.pack(side='left', padx=(0, 5))
self.back1_button.pack(side='left', padx=(0, 0))
self.exit_button.pack(side='left', padx=(5, 0))
self.adv_mode = True
def change_mode2(self):
if self.updatehiya.get() == 1:
self.updatehiya.set(0)
if self.updatemenu.get() == 1:
self.updatemenu.set(0)
if self.ntm.get() == 1:
self.ntm.set(0)
self.start_button.pack_forget()
self.exit_button.pack_forget()
if self.transfer_mode:
self.back2_button.pack_forget()
self.checks_frame2.pack_forget()
self.checks_frame1.pack(anchor=W)
self.start_button.pack(side='left', padx=(0, 5))
self.back1_button.pack(side='left', padx=(0, 0))
self.exit_button.pack(side='left', padx=(5, 0))
self.chb1['state'] = NORMAL
self.transfer_mode = False
self.adv_mode = True
else:
self.chb1['state'] = DISABLED
self.back1_button.pack_forget()
self.checks_frame1.pack_forget()
self.checks_frame2.pack(anchor=W)
self.start_button.pack(side='left', padx=(0, 5))
self.back2_button.pack(side='left', padx=(0, 0))
self.exit_button.pack(side='left', padx=(5, 0))
self.transfer_mode = True
self.adv_mode = False
################################################################################################
def enable_entries(self, status):
self.cid_label['state'] = (NORMAL if status else DISABLED)
self.cid_entry['state'] = (NORMAL if status else DISABLED)
self.console_id_label['state'] = (NORMAL if status else DISABLED)
self.console_id_entry['state'] = (NORMAL if status else DISABLED)
def check_console(self, spath):
tmenu = path.join(spath, '_nds', 'TWiLightMenu', 'main.srldr')
if path.exists(tmenu):
self.have_menu = True
tds = path.join(spath, 'Nintendo 3DS')
tds1 = path.join(spath, 'boot.firm')
if path.exists(tds) or path.exists(tds1):
self.is_tds = True
else:
hiyad = path.join(spath, 'hiya.dsi')
hiyab = path.join(spath, 'hiya', 'bootloader.nds')
hiyas = path.join(spath, 'sys', 'HWINFO_S.dat')
if path.exists(hiyad) or path.exists(hiyab) or path.exists(hiyas):
self.have_hiya = True
def make_dekp(self, dpath):
dekp = path.join(dpath, 'sys', 'dev.kp')
if not path.exists(dekp):
with open(dekp, 'wb+') as f:
f.seek(0, 0)
f.write(b'DUMMY')
f.close()
self.log.write(_('"系统设置-数据管理"功能启用成功'))
################################################################################################
def choose_sdp(self):
self.have_hiya = False
self.is_tds = False
self.have_menu = False
showinfo(_('提示'), _('请选择机器的存储卡根目录'))
self.sd_path1 = askdirectory(title='')
self.sdp.set(self.sd_path1)
self.common_set()
self.start_button['state'] = (
NORMAL if self.sd_path1 != '' else DISABLED)
if self.sd_path1 == '':
self.uh_chk['state'] = DISABLED
self.dkp1_chk['state'] = DISABLED
self.ag1_chk['state'] = DISABLED
self.transfer_button['state'] = DISABLED
return
self.check_console(self.sd_path1)
if self.is_tds:
self.uh_chk['state'] = DISABLED
self.dkp1_chk['state'] = DISABLED
self.ag1_chk['state'] = DISABLED
self.transfer_button['state'] = DISABLED
elif self.have_hiya:
self.uh_chk['state'] = NORMAL
self.dkp1_chk['state'] = NORMAL
self.ag1_chk['state'] = (
DISABLED if self.have_menu is True else NORMAL)
self.transfer_button['state'] = NORMAL
elif self.have_menu:
self.uh_chk['state'] = DISABLED
self.dkp1_chk['state'] = DISABLED
self.ag1_chk['state'] = DISABLED
self.transfer_button['state'] = DISABLED
else:
self.uh_chk['state'] = DISABLED
self.dkp1_chk['state'] = DISABLED
self.ag1_chk['state'] = DISABLED
self.transfer_button['state'] = DISABLED
def choose_nand(self):
name = askopenfilename(filetypes=(
('nand.bin', '*.bin'), ('DSi-1.mmc', '*.mmc')))
self.nand_file.set(name)
self.nand_button['state'] = (NORMAL if name != '' else DISABLED)
self.start_button['state'] = (NORMAL if name != '' else DISABLED)
################################################################################################
def start_point(self):
if not self.transfer_mode:
self.TThread = Thread(target=self.hiya)
self.TThread.start()
else:
self.TThread = Thread(target=self.transfer)
self.TThread.start()
def log_window(self):
self.dialog = Toplevel(class_='Magician') if sysname == 'Linux' else Toplevel()
if sysname == 'Windows':
self.dialog.iconbitmap("icon.ico")
# Open as dialog (parent disabled)
self.dialog.grab_set()
self.dialog.title(_('状态'))
# Disable maximizing
self.dialog.resizable(False, False)
self.dialog.protocol("WM_DELETE_WINDOW", self.closethread)
frame = Frame(self.dialog, bd=2, relief=SUNKEN)
scrollbar = Scrollbar(frame)
scrollbar.pack(side=RIGHT, fill=Y)
self.log = ThreadSafeText(frame, bd=0, width=52, height=20,
yscrollcommand=scrollbar.set)
self.log.bind("<Key>", lambda a: "break")
self.log.pack()
scrollbar.config(command=self.log.yview)
frame.pack()
Button(self.dialog, text=_('关闭'),
command=self.closethread, width=16).pack(pady=10)
# Center in window
self.dialog.update_idletasks()
width = self.dialog.winfo_width()
height = self.dialog.winfo_height()
self.dialog.geometry('%dx%d+%d+%d' % (width, height, root.winfo_x() + (root.winfo_width() / 2) -
(width / 2), root.winfo_y() + (root.winfo_height() / 2) - (height / 2)))
self.finish = False
def transfer(self):
showinfo(_('提示'), _('接下来将自动下载目标区域的TWLTransfer镜像文件\n请注意: TWLCFG会被重置'))
if taskbar is not None:
taskbar.set_mode(0x1)
self.log_window()
self.TThread = Thread(target=self.get_transfer_image)
self.TThread.start()
def hiya(self):
if not self.adv_mode:
if self.setup_operation.get() == 2 or self.nand_operation.get() == 2:
if sysname == 'Windows' and ctypes.windll.shell32.IsUserAnAdmin() == 0:
showerror(_('错误'), _('此功能需要以管理员权限运行本工具'))
return
if not self.nand_mode:
self.have_hiya = False
self.is_tds = False
self.have_menu = False
if not self.adv_mode:
showinfo(_('提示'), _('接下来请选择你用来安装自制系统的存储卡路径(或输出路径)\n为了避免 启动错误 请确保目录下无任何文件'))
self.sd_path = askdirectory(title='')
# Exit if no path was selected
if self.sd_path == '':
return
self.check_console(self.sd_path)
if self.is_tds or self.have_hiya:
showerror(_('错误'), _('目录检测未通过,若CFW已安装,请转到高级模式,或选择一个空目录以继续'))
return
else:
self.check_console(self.sd_path1)
else:
showinfo(_('提示'), _('接下来请选择一个输出路径'))
self.out_path = askdirectory(title='')
if self.out_path == '':
return
# If adding a No$GBA footer, check if CID and ConsoleID values are OK
if self.nand_operation.get() == 1:
cid = self.cid.get()
console_id = self.console_id.get()
# Check lengths
if len(cid) != 32:
showerror(_('错误'), 'Bad eMMC CID')
return
elif len(console_id) != 16:
showerror(_('错误'), 'Bad Console ID')
return
# Parse strings to hex
try:
cid = bytearray.fromhex(cid)
except ValueError:
showerror(_('错误'), 'Bad eMMC CID')
return
try:
console_id = bytearray(reversed(bytearray.fromhex(console_id)))
except ValueError:
showerror(_('错误'), 'Bad Console ID')
return
if taskbar is not None:
taskbar.set_mode(0x1)
self.log_window()
# Check if we'll be adding a No$GBA footer
if self.nand_mode and self.nand_operation.get() == 1:
self.TThread = Thread(target=self.add_footer,
args=(cid, console_id))
self.TThread.start()
elif self.adv_mode:
if self.updatehiya.get() == 1:
self.TThread = Thread(target=self.get_latest_hiyacfw)
self.TThread.start()
else:
self.TThread = Thread(target=self.get_latest_twilight)
self.TThread.start()
else:
self.TThread = Thread(target=self.check_nand)
self.TThread.start()
################################################################################################
def common_set(self):
if self.appgen.get() == 1:
self.appgen.set(0)
if self.devkp.get() == 1:
self.devkp.set(0)
if self.updatehiya.get() == 1:
self.updatehiya.set(0)
def closethread(self):
if self.adv_mode:
self.sd_path1 = ''
self.sdp.set(self.sd_path1)
self.common_set()
self.start_button['state'] = DISABLED
self.transfer_button['state'] = DISABLED
self.uh_chk['state'] = DISABLED
self.dkp1_chk['state'] = DISABLED
self.ag1_chk['state'] = DISABLED
if self.dialog is not None:
self.dialog.destroy()
self.dialog = None
if self.finish:
self.finish = False
return
try:
stop_thread(self.TThread)
self.proc.kill()
except:
pass
Thread(target=self.after_close).start()
def after_close(self):
sleep(1)
printl(_('操作过程发生错误或用户终止操作'))
if self.setup_operation.get() == 2 or self.nand_operation.get() == 2:
if not self.adv_mode:
self.unmount_nand1()
else:
self.clean(True, )
def check_nand(self):
self.log.write(_('正在检查NAND文件...'))
# Read the NAND file
try:
with open(self.nand_file.get(), 'rb') as f:
# Go to the No$GBA footer offset
f.seek(-64, 2)
# Read the footer's header :-)
bstr = f.read(0x10)
if bstr == b'DSi eMMC CID/CPU':
# Read the CID
bstr = f.read(0x10)
self.cid.set(hexlify(bstr).upper().decode('ascii'))
self.log.write('- eMMC CID: ' + self.cid.get())
# Read the console ID
bstr = f.read(8)
f.close()
self.console_id.set(
hexlify(bytearray(reversed(bstr))).upper().decode('ascii'))
self.log.write('- Console ID: ' + self.console_id.get())
if self.nand_mode:
if self.nand_operation.get() == 2:
self.TThread = Thread(target=self.decrypt_nand)
self.TThread.start()
else:
self.TThread = Thread(target=self.remove_footer)
self.TThread.start()
else:
self.TThread = Thread(target=self.get_latest_hiyacfw)
self.TThread.start()
else:
self.log.write(
_('错误: 没有检测到No$GBA footer\n警告: 若确定Nand已完整dump, 则用于dump的存储卡极有可能是扩容卡或者已出现坏块'))
except IOError as e:
printl(str(e))
self.log.write(_('错误: 无法打开文件 ') +
path.basename(self.nand_file.get()))
def get_transfer_image(self):
global downloadfile
if downloadfile is False:
downloadfile = True
REGION_CODES_IMAGE = {
'5E1186D17265F03A526AF127B61080AC501A5372': 'CHN',
'61AEBB53F63DED24E8FBC0861D7A51ED85F095E7': 'USA',
'B5F42ACF2C1C4F7C4DE785F545FB4E40A2EEF8DF': 'JPN',
'886A40EB67C2F9E240449CF6A15C9A15D7381981': 'KOR',
'8833DCA9E5236D54AAA9EB61D0FDF8A6E7C247FC': 'EUR',
'751F7F79FB4360A5A409D70288ECB7611484AC56': 'AUS',
'417E985E5A2E8110F20FAF6106AB8A4C2ED25693': 'JPN-kst'
}
REGION_HWINFO = {
'00': 'JPN',
'01': 'USA',
'02': 'EUR',
'03': 'AUS',
'04': 'CHN',
'05': 'KOR'
}
filename = self.selected_option.get() + '.bin'
try:
if not path.isfile(filename):
self.log.write(_('正在下载 TWLTransfer 镜像文件: ') + filename)
with urlopen('https://gitee.com/ryatian/mirrors/releases/download/TWLTransfer/' +
filename) as src, open(filename, 'wb') as dst:
copyfileobj(src, dst)
except SystemExit:
return
except (URLError, IOError) as e:
printl(str(e))
self.log.write(_('错误: 无法下载 TWLTransfer 镜像文件'))
return
self.image_file.set(filename)
try:
sha1_hash = sha1()
with open(self.image_file.get(), 'rb') as f:
sha1_hash.update(f.read())
f.close()
image_sha1 = hexlify(sha1_hash.digest()).upper().decode('ascii')
image_filename = path.basename(self.image_file.get())
try:
self.dest_region = REGION_CODES_IMAGE[image_sha1]
except SystemExit:
return
except:
self.log.write(_('错误: 无效的镜像文件'))
remove(self.image_file.get())
return
self.log.write('- ' + image_filename + ' SHA1:\n' + image_sha1)
self.log.write(_('目标系统: ') + self.dest_region)
except IOError as e:
printl(str(e))
self.log.write(_('错误: 无法打开文件 ') + image_filename)
return
hwinfo = path.join(self.sd_path1, 'sys', 'HWINFO_S.dat')
if path.exists(hwinfo):
with open(hwinfo, 'rb') as infotmp:
infotmp.seek(0x90, 0)
self.cur_region = REGION_HWINFO[hexlify(
infotmp.read(0x01)).decode('ascii')]
infotmp.close()
self.log.write(_('当前区域: ') + self.cur_region)
else:
self.log.write(_('错误: 无法检测系统区域'))
return
self.origin_region = self.check_serial(self.sd_path1)