forked from Ariescyn/EldenRing-Save-Manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSaveManager.py
2972 lines (2287 loc) · 104 KB
/
SaveManager.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
import sys
import traceback
from tkinter import *
from tkinter import font as FNT
from tkinter import filedialog as fd
from tkinter import ttk
import tkinter as TKIN
from collections import Counter
from PIL import Image, ImageTk
import subprocess, os, zipfile, requests, re, time, hexedit, webbrowser, itemdata, lzma, datetime, json
from os_layer import *
from pathlib import Path as PATH
#Collapse all functions to navigate. In Atom editor: "Edit > Folding > Fold All"
# set always the working dir to the correct folder for unix env
if not is_windows:
os.chdir(os.path.dirname(os.path.abspath(__file__)))
class Config:
def __init__(self):
if not os.path.exists(post_update_file):
with open(post_update_file, 'w') as ff:
ff.write("True")
with open(post_update_file, 'r') as f:
x = f.read()
self.post_update = (True if x == 'True' else False)
if os.path.exists(config_path):
with open(config_path, 'r') as f:
dat = json.load(f)
if not "custom_ids" in dat.keys(): # custom_ids was an addition to v1.5, must create for current users with existing config.json from v1.5
dat["custom_ids"] = {}
self.cfg = dat
with open(config_path, 'w') as f:
json.dump(self.cfg, f)
if not os.path.exists(config_path): # Build dictionary for first time
dat = {}
dat["post_update"] = True
dat["gamedir"] = ""
dat["steamid"] = ""
dat["seamless-coop"] = False
dat["custom_ids"] = {}
self.cfg = dat
with open(config_path, 'w') as f:
json.dump(self.cfg, f)
else:
with open(config_path, 'r') as f:
js = json.load(f)
self.cfg = js
def set_update(self, val):
self.post_update = val
with open(post_update_file, 'w') as f:
f.write("True" if val else "False")
def set(self,k,v):
self.cfg[k] = v
with open(config_path, 'w') as f:
json.dump(self.cfg, f)
def add_to(self,k,v):
self.cfg[k].update(v)
with open(config_path, 'w') as f:
json.dump(self.cfg, f)
def delete_custom_id(self, k):
self.cfg['custom_ids'].pop(k)
with open(config_path, 'w') as f:
json.dump(self.cfg, f)
# ///// UTILITIES /////
def popup(text, command=None, functions=False, buttons=False, button_names=("Yes", "No"), b_width=(6,6), title="Manager", parent_window=None):
"""text: Message to display on the popup window.
command: Simply run the windows CMD command if you press yes.
functions: Pass in external functions to be executed for yes/no"""
def run_cmd():
cmd_out = run_command(command)
popupwin.destroy()
if cmd_out[0] == "error":
popupwin.destroy()
def dontrun_cmd():
popupwin.destroy()
def run_func(arg):
arg()
popupwin.destroy()
if parent_window is None:
parent_window = root
popupwin = Toplevel(parent_window)
popupwin.title(title)
lab = Label(popupwin, text=text)
lab.grid(row=0, column=0, padx=5, pady=5, columnspan=2)
# Places popup window at center of the root window
x = parent_window.winfo_x()
y = parent_window.winfo_y()
popupwin.geometry("+%d+%d" % (x + 200, y + 200))
# Runs for simple windows CMD execution
if functions is False and buttons is True:
but_yes = Button(
popupwin, text=button_names[0], borderwidth=5, width=b_width[0], command=run_cmd
).grid(row=1, column=0, padx=(10, 0), pady=(0, 10))
but_no = Button(
popupwin, text=button_names[1], borderwidth=5, width=b_width[1], command=dontrun_cmd
).grid(row=1, column=1, padx=(10, 10), pady=(0, 10))
elif functions is not False and buttons is True:
but_yes = Button(
popupwin,
text=button_names[0],
borderwidth=5,
width=b_width[0],
command=lambda: run_func(functions[0]),
).grid(row=1, column=0, padx=(10, 0), pady=(0, 10))
but_no = Button(
popupwin,
text=button_names[1],
borderwidth=5,
width=b_width[1],
command=lambda: run_func(functions[1]),
).grid(row=1, column=1, padx=(10, 10), pady=(0, 10))
# if text is the only arguement passed in, it will simply be a popup window to display text
def archive_file(file, name, metadata, names):
try:
name = name.replace(" ", "_")
if not os.path.exists(file): # If you try to load a save from listbox, and it tries to archive the file already present in the gamedir, but it doesn't exist, then skip
return
now = datetime.datetime.now()
date = now.strftime("%Y-%m-%d__(%I.%M.%S)")
name = f"{name}__{date}"
os.makedirs(f"./data/archive/{name}")
with open(file, "rb") as fhi, lzma.open(f"./data/archive/{name}/ER0000.xz", 'w') as fho:
fho.write(fhi.read())
names = [i for i in names if not i is None]
formatted_names = ", ".join(names)
meta = f"{metadata}\nCHARACTERS:\n {formatted_names}"
meta_ls = [i for i in meta]
try:
x = meta.encode("ascii") # Will fail with UnicodeEncodeError if special characters exist
with open(f"./data/archive/{name}/info.txt", 'w') as f:
f.write(meta)
except:
for ind,i in enumerate(meta):
try:
x = i.encode("ascii")
meta_ls[ind] = i
except:
meta_ls[ind] = '?'
fixed_meta = ""
for i in meta_ls:
fixed_meta = fixed_meta + i
with open(f"./data/archive/{name}/info.txt", 'w') as f:
f.write(fixed_meta)
except Exception as e:
traceback.print_exc()
str_err = "".join(traceback.format_exc())
popup(str_err)
return
def unarchive_file(file):
lzc = lzma.LZMACompressor()
name = file.split("/")[-2]
path = f"./data/recovered/{name}/"
if not os.path.exists("./data/recovered/"):
os.makedirs("./data/recovered/")
if not os.path.exists(path):
os.makedirs(path)
with lzma.open(file, "rb") as f_in, open(f"{path}/{ext()}", "wb") as f_out:
f_out.write(f_in.read())
def grab_metadata(file):
"""Used to grab metadata from archive info.txt"""
with open(file.replace(" ", "__").replace(":", "."), 'r') as f:
meta = f.read()
popup(meta.replace(",", "\n"))
def get_charnames(file):
"""wrapper for hexedit.get_names"""
out = hexedit.get_names(file)
if out is False:
popup(f"Error: Unable to get character names.\nDoes the following path exist?\n{file}")
else:
return out
def finish_update():
if os.path.exists("./data/GameSaveDir.txt"): # Legacy file for pre v1.5 versions
os.remove("./data/GameSaveDir.txt")
if config.post_update: # Will be ran on first launch after running update.exe
if not os.path.exists("./data/save-files-pre-V1.5-BACKUP"): # NONE OF THIS WILL BE RUN ON v1.5+
try:
copy_folder(savedir, "./data/save-files-pre-V1.5-BACKUP")
except Exception as e:
traceback.print_exc()
str_err = "".join(traceback.format_exc())
popup(str_err)
for dir in os.listdir(savedir): # Reconstruct save-file structure for pre v1.5 versions
try:
id = re.findall(r"\d{17}", str(os.listdir(f"{savedir}{dir}/")))
if len(id) < 1:
continue
shutil.move(f"{savedir}{dir}/{id[0]}/{ext()}", f"{savedir}{dir}/{ext()}")
for i in ["GraphicsConfig.xml", "notes.txt", "steam_autocloud.vdf"]:
if os.path.exists(f"{savedir}{dir}/{i}"):
os.remove(f"{savedir}{dir}/{i}")
delete_folder(f"{savedir}{dir}/{id[0]}")
except Exception as e:
traceback.print_exc()
str_err = "".join(traceback.format_exc())
popup(str_err)
continue
def ext():
if config.cfg["seamless-coop"]:
return "ER0000.co2"
elif config.cfg["seamless-coop"] is False:
return "ER0000.sl2"
def open_game_save_dir():
if config.cfg["gamedir"] == "":
popup("Please set your default game save directory first")
return
else:
print(config.cfg["gamedir"])
open_folder_standard_exporer(config.cfg["gamedir"])
return
def open_folder():
"""Right-click open file location in listbox"""
if len(lb.curselection()) < 1:
popup("No listbox item selected.")
return
name = fetch_listbox_entry(lb)[0]
cmd = lambda: open_folder_standard_exporer(f'{savedir}{name.replace(" ", "-")}')
run_command(cmd)
def forcequit():
comm = lambda: force_close_process("eldenring.exe")
popup(text="Are you sure?", buttons=True, command=comm)
def update_app(on_start=False):
"""Gets redirect URL of latest release, then pulls the version number from URL and makes a comparison"""
try:
version_url = (
"https://github.com/Ariescyn/EldenRing-Save-Manager/releases/latest"
)
r = requests.get(version_url) # Get redirect url
ver = float(r.url.split("/")[-1].split("v")[1])
except:
popup("Can not check for updates. Check your internet connection.")
return
if ver > v_num:
popup(
text=f" Release v{str(ver)} Available\nClose the program and run the Updater.",
buttons=True,
functions=(root.quit, donothing),
button_names=("Exit Now", "Cancel"),
)
if on_start is True:
return
else:
popup("Current version up to date")
return
def reset_default_dir():
"""DEPRECIATED! writes the original gamedir to text file"""
global gamedir
with open(gamesavedir_txt, "w") as fh:
fh.write(eldenring_savedata_dir)
with open(gamesavedir_txt, "r") as fh:
gamedir = fh.readline()
popup("Successfully reset default directory")
def help_me():
# out = run_command("notepad ./data/readme.txt")
info = ""
with open("./data/readme.txt", "r") as f:
dat = f.readlines()
for line in dat:
info = info + line
popup(info)
def load_listbox(lstbox):
"""LOAD current save files and insert them into listbox. This is Used
to load the listbox on startup and also after deleting an item from the listbox to refresh the entries."""
if os.path.isdir(savedir) is True:
for entry in os.listdir(savedir):
lstbox.insert(END, " " + entry.replace("-", " "))
def create_save():
"""Takes user input from the create save entry box and copies files from game save dir to the save-files dir of app"""
if len(config.cfg['gamedir']) < 2:
popup("Set your Default Game Directory first")
return
name = cr_save_ent.get().strip()
newdir = "{}{}".format(savedir, name.replace(" ", "-"))
# Check the given name in the entry
if len(name) < 1:
popup("No name entered")
isforbidden = False
for char in name:
if char in "~'{};:./\,:*?<>|-!@#$%^&()+":
isforbidden = True
if isforbidden is True:
popup("Forbidden character used")
if os.path.isdir(savedir) is False:
# subprocess.run("md .\\save-files", shell=True)
cmd_out = run_command(lambda: os.makedirs(savedir))
if cmd_out[0] == "error":
return
# If new save name doesnt exist, insert it into the listbox,
# otherwise duplicates will appear in listbox even though the copy command will overwrite original save
if len(name) > 0 and isforbidden is False:
path = "{}/{}".format(config.cfg["gamedir"], ext())
nms = get_charnames(path)
archive_file(path, name, "ACTION: Clicked Create Save", nms)
cp_to_saves_cmd = lambda: copy_file(path,newdir)
# /E – Copy subdirectories, including any empty ones.
# /H - Copy files with hidden and system file attributes.
# /C - Continue copying even if an error occurs.
# /I - If in doubt, always assume the destination is a folder. e.g. when the destination does not exist
# /Y - Overwrite all without PROMPT (ex: yes no)
if os.path.isdir(newdir) is False:
cmd_out = run_command(lambda: os.makedirs(newdir))
if cmd_out[0] == "error":
return
lb.insert(END, " " + name)
cmd_out = run_command(cp_to_saves_cmd)
if cmd_out[0] == "error":
return
create_notes(name, newdir)
else:
popup(
"File already exists, OVERWRITE?", command=cp_to_saves_cmd, buttons=True
)
#save_path = f"{newdir}/{user_steam_id}/ER0000.sl2"
#nms = get_charnames(save_path)
#archive_file(save_path, f"ACTION: Create save\nCHARACTERS: {nms}")
def donothing():
pass
def load_save_from_lb():
"""Fetches currently selected listbox item and copies files to game save dir."""
if len(config.cfg["gamedir"]) < 2:
popup("Set your Default Game Directory first")
return
def wrapper(comm):
"""Archives savefile in gamedir and runs command to overwrite. This function is then passed into popup function."""
#path = f"{gamedir}/{user_steam_id}/ER0000.sl2"
path = "{}/{}".format(config.cfg["gamedir"],ext())
if not os.path.exists(path):
run_command(comm)
else:
nms = get_charnames(path)
archive_file(path, "Loaded Save", "ACTION: Loaded save and overwrite current save file in EldenRing game directory", nms)
run_command(comm)
if len(lb.curselection()) < 1:
popup("No listbox item selected.")
return
name = fetch_listbox_entry(lb)[0]
src_dir = "".join((savedir, name.replace(" ", "-"), "/"))
comm = lambda: copy_folder(src_dir, str(config.cfg["gamedir"]))
if not os.path.isdir(f"{savedir}{name}"):
popup(
"Save slot does not exist.\nDid you move or delete it from data/save-files?"
)
lb.delete(0, END)
load_listbox(lb)
return
popup("Are you sure?", buttons=True, functions=(lambda: wrapper(comm), donothing))
def run_command(subprocess_command, optional_success_out="OK"):
"""Used throughout to run commands into subprocess and capture the output. Note that
it is integrated with popup function for in app error reporting."""
try:
subprocess_command()
except Exception as e:
traceback.print_exc()
str_err = "".join(traceback.format_exc())
popup(str_err)
return ("error", str_err)
return ("Successfully completed operation", optional_success_out)
def delete_save():
"""Removes entire directory in save-files dir"""
name = fetch_listbox_entry(lb)[0]
comm = lambda: delete_folder(f"{savedir}{name}")
def yes():
path = f"{savedir}{name}/{ext()}"
chars = get_charnames(path)
archive_file(path, name, "ACTION: Delete save file in Manager", chars)
out = run_command(comm)
lb.delete(0, END)
load_listbox(lb)
def no():
return
popup(f"Delete {fetch_listbox_entry(lb)[1]}?", functions=(yes, no), buttons=True)
def fetch_listbox_entry(lstbox):
"""Returns currently selected listbox entry.
internal name is for use with save directories and within this script.
Name is used for display within the listbox"""
name = ""
for i in lstbox.curselection():
name = name + lstbox.get(i)
internal_name = name.strip().replace(" ", "-")
return (internal_name, name)
def rename_slot():
"""Renames the name in save file listbox"""
def cancel():
popupwin.destroy()
def done():
new_name = ent.get()
if len(new_name) < 1:
popup("No name entered.")
return
isforbidden = False
for char in new_name:
if char in "~'{};:./\,:*?<>|-!@#$%^&()+":
isforbidden = True
if isforbidden is True:
popup("Forbidden character used")
return
elif isforbidden is False:
entries = []
for entry in os.listdir(savedir):
entries.append(entry)
if new_name in entries:
popup("Name already exists")
return
else:
newnm = new_name.replace(" ", "-")
cmd = lambda: os.rename(
f"{savedir}{lst_box_choice}", f"{savedir}{newnm}"
)
run_command(cmd)
lb.delete(0, END)
load_listbox(lb)
popupwin.destroy()
lst_box_choice = fetch_listbox_entry(lb)[0]
if len(lst_box_choice) < 1:
popup("No listbox item selected.")
return
popupwin = Toplevel(root)
popupwin.title("Rename")
# popupwin.geometry("200x70")
lab = Label(popupwin, text="Enter new Name:")
lab.grid(row=0, column=0)
ent = Entry(popupwin, borderwidth=5)
ent.grid(row=1, column=0, padx=25, pady=10)
x = root.winfo_x()
y = root.winfo_y()
popupwin.geometry("+%d+%d" % (x + 200, y + 200))
but_done = Button(popupwin, text="Done", borderwidth=5, width=6, command=done)
but_done.grid(row=2, column=0, padx=(25, 65), pady=(0, 15), sticky="w")
but_cancel = Button(popupwin, text="Cancel", borderwidth=5, width=6, command=cancel)
but_cancel.grid(row=2, column=0, padx=(70, 0), pady=(0, 15))
def update_slot():
"""Update the selected savefile with the current elden ring savedata"""
def do(file):
names = get_charnames(file)
archive_file(file, lst_box_choice, "ACTION: Clicked Update save-file in Manager", names)
copy_file(f"{config.cfg['gamedir']}/{ext()}", f"{savedir}{lst_box_choice}")
lst_box_choice = fetch_listbox_entry(lb)[0]
if len(lst_box_choice) < 1:
popup("No listbox item selected.")
return
path = f"{savedir}{lst_box_choice}/{ext()}"
popup(text="This will take your current save in-game\nand overwrite this save slot\nAre you sure?", buttons=True, command=lambda: do(path))
def change_default_dir():
"""Opens file explorer for user to choose new default elden ring directory. Writes changes to GameSaveDir.txt"""
newdir = fd.askdirectory()
if len(newdir) < 1: # User presses cancel
return
folder = newdir.split("/")[-1]
f_id = re.findall(r"\d{17}", folder)
if len(f_id) == 0:
popup("Please select the directory named after your 17 digit SteamID")
return
else:
config.set("gamedir", newdir)
popup(f"Directory set to:\n {newdir}\n")
def rename_char(file, nw_nm, dest_slot):
"""Wrapper for hexedit.change_name for error handling"""
try:
x = hexedit.change_name(file, nw_nm, dest_slot)
if x == "error":
raise Exception
except Exception:
popup("Error renaming character. This may happen\nwith short names like '4'.")
raise
def changelog(run=False):
info = ""
with open("./data/changelog.txt", "r") as f:
dat = f.readlines()
for line in dat:
info = info + f"\n\u2022 {line}\n"
if run:
popup(info, title="Changelog")
return
if config.post_update:
popup(info, title="Changelog")
# ////// MENUS //////
def char_manager_menu():
"""Entire character manager window for copying characters between save files"""
def readme():
info = ""
with open("./data/copy-readme.txt", "r") as f:
dat = f.readlines()
for line in dat:
info = info + line
popup(info)
# run_command("notepad ./data/copy-readme.txt")
def open_video():
webbrowser.open_new_tab(video_url)
def get_char_names(lstbox, drop, v):
"""Populates dropdown menu containing the name of characters in a save file"""
v.set("Character")
name = fetch_listbox_entry(lstbox)[0]
if len(name) < 1:
return
file = f"{savedir}{name}/{ext()}"
names = get_charnames(file)
drop["menu"].delete(0, "end") # remove full list
index = 1
for ind, opt in enumerate(names):
if not opt is None:
opt = f"{index}. {opt}"
drop["menu"].add_command(label=opt, command=TKIN._setit(v, opt))
index += 1
elif opt is None:
opt = f"{ind + 1}. "
drop["menu"].add_command(label=opt, command=TKIN._setit(v, opt))
index += 1
def do_copy():
def pop_up(txt, bold=True):
"""Basic popup window used only for parent function"""
win = Toplevel(popupwin)
win.title("Manager")
lab = Label(win, text=txt)
if bold is True:
lab.config(font=bolded)
lab.grid(row=0, column=0, padx=15, pady=15, columnspan=2)
x = popupwin.winfo_x()
y = popupwin.winfo_y()
win.geometry("+%d+%d" % (x + 200, y + 200))
src_char = vars1.get() # "1. charname"
dest_char = vars2.get()
if src_char == "Character" or dest_char == "Character":
pop_up("Select a character first")
return
if src_char.split(".")[1] == " " or dest_char.split(".")[1] == " ":
pop_up(
"Can't write to empty slot.\nGo in-game and create a character to overwrite."
)
return
name1 = fetch_listbox_entry(lb1)[0] # Save file name. EX: main
name2 = fetch_listbox_entry(lb2)[0]
if len(name1) < 1 or len(name2) < 1:
pop_up(txt="Slot not selected")
return
if src_char == "Character" or dest_char == "Character":
pop_up(txt="Character not selected")
return
src_file = f"{savedir}{name1}/{ext()}"
dest_file = f"{savedir}{name2}/{ext()}"
src_ind = int(src_char.split(".")[0])
dest_ind = int(dest_char.split(".")[0])
# Duplicate names check
src_char_real = src_char.split(". ")[1]
dest_names = get_charnames(dest_file)
nms = [i for i in dest_names] # For archive_file only
src_names = get_charnames(src_file)
# If there are two or more of the name name in a destination file, quits
rmv_none = [i for i in dest_names if not i is None]
if max(Counter(rmv_none).values()) > 1:
pop_up(
"""Sorry, Can't handle writing to a DESTINATION file with duplicate character names!\n\n
You can work around this limitation by using the save file with duplicate character names as the SOURCE file:\n
1. Select the save file with duplicate character names as the SOURCE file.\n
2. Select a different save file as the DESTINATION (can be anything).\n
3. Copy the first character with duplicate names to DESTINATION file\n
4. Rename the character in the DESTINATION file to something different.\n
5. Copy the second character with duplicate names to the DESTINATION file.\n\n
Why do you have to do this? Because character names vary greatly in frequency and location\n
within the save file, so this tool must replace ALL occurences of a given name.""",
bold=False,
)
return
src_names.pop(src_ind - 1)
dest_names.pop(dest_ind - 1)
backup_path = r"./data/temp/{}".format(ext())
# If performing operations on the same file. Changes name to random, copies character to specified slot, then rewrites the name and re-populates the dropdown entries
if src_file == dest_file:
archive_file(dest_file, name2, "ACTION: Copy Character", nms)
cmd = lambda: copy_file(src_file, backup_path)
x = run_command(cmd)
rand_name = hexedit.random_str()
rename_char(backup_path, rand_name, src_ind) # Change backup to random name
hexedit.copy_save(backup_path, src_file, src_ind, dest_ind)
rename_char(src_file, rand_name, dest_ind)
get_char_names(lb1, dropdown1, vars1)
get_char_names(lb2, dropdown2, vars2)
vars1.set("Character")
vars2.set("Character")
pop_up(
txt="Success!\nDuplicate names not supported\nGenerated a new random name",
bold=False,
)
return
# If source name in destination file, copies source file to temp folder, changes the name of copied save to random, then copies source character of
# copied file to destination save file, and rewrites names on destination file
elif src_char_real in dest_names:
archive_file(dest_file, name2, "ACTION: Copy character", nms)
cmd = lambda: copy_file(src_file, backup_path)
x = run_command(cmd)
rand_name = hexedit.random_str()
rename_char(backup_path, rand_name, src_ind)
hexedit.copy_save(backup_path, dest_file, src_ind, dest_ind)
rename_char(dest_file, rand_name, dest_ind)
get_char_names(lb1, dropdown1, vars1)
get_char_names(lb2, dropdown2, vars2)
vars1.set("Character")
vars2.set("Character")
pop_up(
txt="Duplicate names not supported\nGenerated a new random name",
bold=False,
)
return
archive_file(dest_file, name2, f"ACTION: Copy character", nms)
hexedit.copy_save(src_file, dest_file, src_ind, dest_ind)
rename_char(dest_file, src_char_real, dest_ind)
get_char_names(lb1, dropdown1, vars1)
get_char_names(lb2, dropdown2, vars2)
vars1.set("Character")
vars2.set("Character")
pop_up(txt="Success!")
def cancel():
popupwin.destroy()
# Main GUI content
popupwin = Toplevel(root)
popupwin.title("Character Manager")
popupwin.resizable(width=True, height=True)
popupwin.geometry("620x500")
bolded = FNT.Font(weight="bold") # will use the default font
x = root.winfo_x()
y = root.winfo_y()
popupwin.geometry("+%d+%d" % (x + 200, y + 200))
menubar = Menu(popupwin)
popupwin.config(
menu=menubar
) # menu is a parameter that lets you set a menubar for any given window
helpmen = Menu(menubar, tearoff=0)
helpmen.add_command(label="Readme", command=readme)
helpmen.add_command(label="Watch Video", command=open_video)
menubar.add_cascade(label="Help", menu=helpmen)
srclab = Label(popupwin, text="Source File")
srclab.config(font=bolded)
srclab.grid(row=0, column=0, padx=(70, 0), pady=(20, 0))
lb1 = Listbox(popupwin, borderwidth=3, width=15, height=10, exportselection=0)
lb1.config(font=bolded)
lb1.grid(row=1, column=0, padx=(70, 0), pady=(0, 0))
load_listbox(lb1)
destlab = Label(popupwin, text="Destination File")
destlab.config(font=bolded)
destlab.grid(row=0, column=1, padx=(175, 0), pady=(20, 0))
lb2 = Listbox(popupwin, borderwidth=3, width=15, height=10, exportselection=0)
lb2.config(font=bolded)
lb2.grid(row=1, column=1, padx=(175, 0), pady=(0, 0))
load_listbox(lb2)
opts = [""]
opts2 = [""]
vars1 = StringVar(popupwin)
vars1.set("Character")
vars2 = StringVar(popupwin)
vars2.set("Character")
dropdown1 = OptionMenu(popupwin, vars1, *opts)
dropdown1.grid(row=4, column=0, padx=(70, 0), pady=(20, 0))
dropdown2 = OptionMenu(popupwin, vars2, *opts2)
dropdown2.grid(row=4, column=1, padx=(175, 0), pady=(20, 0))
but_select1 = Button(
popupwin, text="Select", command=lambda: get_char_names(lb1, dropdown1, vars1)
)
but_select1.grid(row=3, column=0, padx=(70, 0), pady=(10, 0))
but_select2 = Button(
popupwin, text="Select", command=lambda: get_char_names(lb2, dropdown2, vars2)
)
but_select2.grid(row=3, column=1, padx=(175, 0), pady=(10, 0))
but_copy = Button(popupwin, text="Copy", command=do_copy)
but_copy.config(font=bolded)
but_copy.grid(row=5, column=1, padx=(175, 0), pady=(50, 0))
but_cancel = Button(popupwin, text="Cancel", command=cancel)
but_cancel.config(font=bolded)
but_cancel.grid(row=5, column=0, padx=(70, 0), pady=(50, 0))
#mainloop()
def rename_characters_menu():
"""Opens popup window and renames character of selected listbox item"""
def do():
choice = vars.get()
choice_real = choice.split(". ")[1]
slot_ind = int(choice.split(".")[0])
new_name = name_ent.get()
if len(new_name) > 16:
popup("Name too long. Maximum of 16 characters")
return
if len(new_name) < 1:
popup("Enter a name first")
return
if len(new_name) < 3:
popup("Minimum 3 characters")
return
# Duplicate names check
dest_names = [i for i in names]
dest_names.pop(slot_ind - 1)
if new_name in dest_names:
popup("Save can not have duplicate names")
return
archive_file(path, choice_real, "ACTION: Rename Character", names)
rename_char(path, new_name, slot_ind)
popup("Successfully Renamed Character")
drop["menu"].delete(0, "end")
rwin.destroy()
name = fetch_listbox_entry(lb)[0]
if name == "":
popup("No listbox item selected.")
return
path = f"{savedir}{name}/{ext()}"
names = get_charnames(path)
if names is False:
popup("FileNotFoundError: This is a known issue.\nPlease try re-importing your save file.")
chars = []
for ind, i in enumerate(names):
if i != None:
chars.append(f"{ind +1}. {i}")
rwin = Toplevel(root)
rwin.title("Rename Character")
rwin.resizable(width=True, height=True)
rwin.geometry("300x200")
bolded = FNT.Font(weight="bold") # will use the default font
x = root.winfo_x()
y = root.winfo_y()
rwin.geometry("+%d+%d" % (x + 200, y + 200))
opts = chars
vars = StringVar(rwin)
vars.set("Character")
info_lab = Label(rwin, text="Note: If you have more than one character\nwith the same name,\nthis will rename BOTH characters.\n\n")
info_lab.pack()
drop = OptionMenu(rwin, vars, *opts)
drop.pack()
# drop.grid(row=0, column=0, padx=(35, 0), pady=(10, 0))
name_ent = Entry(rwin, borderwidth=5)
name_ent.pack()
# name_ent.grid(row=1, column=0, padx=(35, 0), pady=(10, 0))
but_go = Button(rwin, text="Rename", borderwidth=5, command=do)
but_go.pack()
def stat_editor_menu():
def recalc_lvl():
# entries = [vig_ent, min_ent, end_ent, str_ent, dex_ent, int_ent, fai_ent, arc_ent]
lvl = 0
try:
for ent in entries:
lvl += int(ent.get())
lvl_var.set(f"Level: {lvl - 79}")
except Exception as e:
return
def set_stats():
stats = []
try:
for ent in entries:
stats.append(int(ent.get()))
except Exception as e:
pop_up(f"Error: Make sure all fields are completed.\n{e}")
return
if sum(stats) - 79 < 5:
pop_up("Character level too low.")
return
vig = stats[0]
min = stats[1]
end = stats[2]
char = vars.get().split(". ")[1]
char_slot = int(vars.get().split(".")[0])
name = fetch_listbox_entry(lb1)[0]
file = f"{savedir}{name}/{ext()}"
try:
nms = get_charnames(file)
archive_file(file, name, "ACTION: Edit stats", nms)
hexedit.set_stats(file, char_slot, stats)
hexedit.set_attributes(file, char_slot, [vig, min, end])
pop_up("Success!")
except Exception as e:
pop_up("Something went wrong!: ", e)
return
def pop_up(txt, bold=True):
"""Basic popup window used only for parent function"""
win = Toplevel(popupwin)
win.title("Manager")
lab = Label(win, text=txt)
if bold is True:
lab.config(font=bolded)
lab.grid(row=0, column=0, padx=15, pady=15, columnspan=2)
x = popupwin.winfo_x()
y = popupwin.winfo_y()
win.geometry("+%d+%d" % (x + 200, y + 200))
def validate(P):
if len(P) == 0:
return True
elif len(P) < 3 and P.isdigit() and int(P) > 0:
return True
else:
# Anything else, reject it
return False
def get_char_names(lstbox, drop, v):
"""Populates dropdown menu containing the name of characters in a save file"""
v.set("Character")
name = fetch_listbox_entry(lstbox)[0]
if len(name) < 1:
return
file = f"{savedir}{name}/{ext()}"