-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.py
More file actions
2147 lines (1967 loc) · 97.4 KB
/
main.py
File metadata and controls
2147 lines (1967 loc) · 97.4 KB
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
# MTGA Swapper - A tool for swapping Magic: The Gathering Arena card arts
# Main application module containing the GUI and core functionality
# fmt: off
from pathlib import Path
from src.sql_editor import (
save_grp_id_info,
change_grp_id,
fetch_all_data,
save_loc_id_info,
json,
find_mtga_db_path
)
import sys
import os
import shutil
def get_resource_path(relative_path: str) -> str:
"""
Get absolute path to resource, works for both development and PyInstaller builds.
Args:
relative_path: Path relative to the application directory
Returns:
Absolute path to the resource file
"""
try:
# Only exists when bundled with PyInstaller
base_path = sys._MEIPASS
except AttributeError:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
user_config_directory = Path.home() / ".mtga_swapper"
user_config_directory.mkdir(exist_ok=True)
user_config_file_path = user_config_directory / "config.json"
user_save_changes_path = user_config_directory / "changes.json"
update_path = user_config_directory / "update.json"
backup_directory = Path.home() / "MTGA_Swapper_Backups"
backup_directory.mkdir(exist_ok=True)
# Create default config file if it doesn't exist
if not user_config_file_path.exists():
with open(get_resource_path("config.json"), "r") as source_config:
with open(user_config_file_path, "w") as destination_config:
destination_config.write(source_config.read())
if not user_save_changes_path.exists():
with open(get_resource_path("changes.json"), "r") as source_config:
with open(user_save_changes_path, "w") as destination_config:
destination_config.write(source_config.read())
with open(get_resource_path("update.json"), "r") as source_config:
with open(update_path, "w") as destination_config:
content = source_config.read()
destination_config.write(content)
version = json.loads(content).get("version", "v0.0.0")
print(f"MTGA Swapper Version: {version if version else 'v0.0.0'}")
from src.updater import main as check_for_updates
if check_for_updates(update_path):
sys.exit(0)
import src.sql_editor as database_manager
from random import randint
from src.upscaler import is_upscaling_available
# Import upscaling functionality only if dependencies are available
if is_upscaling_available:
from src.upscaler import upscale_card_image
from src.decklist import create_decklist_import_window, create_search_tokens_window
from src.card_models import MTGACard, format_card_display, sort_cards_by_attribute
from src.gui_utils import (
open_file_dialog,
open_directory_dialog,
convert_pil_image_to_bytes,
)
from src.set_swapper import create_set_swap_window, generate_swap_file, perform_set_swap, spiderman_localizations
import io
from src.image_utils import (
remove_alpha_channel,
resize_image_to_screen,
adjust_image_aspect_ratio,
resize_image_for_gallery,
)
from src.unity_bundle import (
load_unity_bundle,
extract_fonts,
get_card_texture_data,
convert_texture_to_bytes,
save_image_to_file,
extract_textures_from_bundle,
replace_texture_in_bundle,
configure_unity_version,
export_3d_meshes,
)
from webbrowser import open as open_webbrowser
import FreeSimpleGUI as sg
from tkinter import Tk
from tkinter.filedialog import askopenfilename, askdirectory
from PIL import Image
import io
from typing import Dict, Any, Optional, List, Union, Tuple
# Set GUI theme for dark appearance
sg.theme("DarkBlue3")
# Initialize configuration directory and file
# Initialize variables for database connection
database_cursor = None
get_cards_query = """
SELECT
CASE
WHEN NULLIF(c1.Order_Title, '') IS NOT NULL THEN c1.Order_Title
WHEN NULLIF(c1.Order_Title, '') IS NULL
AND NULLIF(c2.Order_Title, '') IS NOT NULL THEN c2.Order_Title || '-flip-side'
END AS Order_Title,
c1.ExpansionCode,
c1.ArtSize,
c1.GrpId,
c1.ArtId
FROM Cards c1
LEFT JOIN Cards c2
ON c1.LinkedFaceGrpIds = c2.GrpId
AND NULLIF(c2.Order_Title, '') IS NOT NULL
WHERE NULLIF(c1.Order_Title, '') IS NOT NULL
OR NULLIF(c2.Order_Title, '') IS NOT NULL;
"""
database_connection = None
database_file_path = None
all_cards_formatted = ["Select a database first"]
displayed_cards = ["Select a database first"]
image_save_directory = None
is_alternate = False
database_file_path = find_mtga_db_path()
lands_set = ("island", "forest", "mountain", "plains", "wastes", "swamp", "snowcoveredforest", "snowcoveredisland", "snowcoveredmountain", "snowcoveredplains", "snowcoveredswamp")
# Load configuration from file or initialize with defaults
if (
database_file_path or sg.popup_yes_no(
"Do you want to load from config file?",
title="Load Config",
)
== "Yes"
):
# Load existing configuration
with open(user_config_file_path, "r") as config_file:
try:
user_config = sg.json.loads(config_file.read())
except sg.json.JSONDecodeError:
sg.popup_error("Error loading config file", auto_close_duration=3)
user_config = {"SavePath": "", "DatabasePath": ""}
image_save_directory = (
user_config["SavePath"] if user_config["SavePath"] else None
)
# Validate and load database if path exists
if database_file_path or user_config["DatabasePath"] != "" and os.path.exists(
user_config["DatabasePath"]
):
if not database_file_path:
database_file_path = user_config["DatabasePath"]
try:
# Initialize database connection
database_cursor, database_connection, database_file_path = (
database_manager.create_database_connection(database_file_path)
)
# Query all cards from database with proper formatting
all_cards_formatted = list(
map(
format_card_display,
sorted(
database_cursor.execute(
get_cards_query
).fetchall()
),
)
)
except (
database_manager.sqlite3.OperationalError,
database_manager.sqlite3.DatabaseError,
TypeError,
):
sg.popup_error(
"Missing or incorrect database selected", auto_close_duration=3
)
database_file_path = None
all_cards_formatted = ["Select a database first"]
displayed_cards = all_cards_formatted
filtered_search_results = displayed_cards
if not image_save_directory:
image_save_directory = sg.popup_get_folder("Select Image Save Folder")
asset_bundle_directory = (
os.path.dirname(database_file_path)[0:-3] + "AssetBundle"
)
configure_unity_version(database_file_path, "2022.3.42f1")
if image_save_directory and database_file_path:
with open(user_config_file_path, "w") as config_file:
user_config["SavePath"] = str(Path(image_save_directory).as_posix())
user_config["DatabasePath"] = str(Path(database_file_path).as_posix())
config_file.write(sg.json.dumps(user_config, indent=4))
else:
database_file_path = None
all_cards_formatted = ["Select a database first"]
displayed_cards = ["Select a database first"]
sg.popup_error(
"Invalid or missing database file. Please select a valid .mtga file.",
auto_close_duration=3,
)
else:
# Initialize with empty configuration
user_config = {"SavePath": None, "DatabasePath": None}
image_save_directory = None
database_file_path = None
all_cards_formatted = ["Select a database first"]
displayed_cards = ["Select a database first"]
# Initialize card swap variables and deck filtering state
first_card_to_swap, second_card_to_swap = None, None
current_search_input = ""
is_using_decklist_filter = False
cards_from_imported_deck = None
# Create main GUI layout
main_window_layout = [
[
sg.Frame(
"",
[
[
sg.Button(
"Select database file & image save location",
key="-SELECT_DATABASE-",
size=(35, 1),
pad=(5, 5),
),
sg.Button("Swap Arts", key="-SWAP_ARTS-", size=(15, 1), pad=(5, 5)),
sg.Button(
"Load Decklist", key="-LOAD_DECKLIST-", size=(15, 1), pad=(5, 5)
),
],
[
sg.Button(
(
"Select database and image save location before changing sleeves and avatars"
if database_file_path is None
else "Change Sleeves, Avatars, etc."
),
key="-CHANGE_ASSETS-",
disabled=database_file_path is None,
size=(35, 1),
),
sg.Button(
"Export Fonts", key="-EXPORT_FONTS-", size=(15, 1), pad=(5, 5)
),
sg.Button("Crop Editor", key="-CROP_EDITOR-", size=(15, 1), pad=(5, 5)),
],
[
sg.Button("Search tokens", key="-SEARCH_TOKENS-", expand_x=True),
sg.Button(
"Load Changes Preset", key="-LOAD_PRESET-", expand_x=True
),
sg.Button(
"Export Changes Preset", key="-EXPORT_PRESET-", expand_x=True
),
],
[
sg.Button(
"Set Swapper (Swap entire sets)",
key="-SET_SWAPPER-",
expand_x=True,
disabled=database_file_path is None,
),
],
[sg.Button("Join Discord Server", key="-JOIN_DISCORD-", expand_x=True)],
[
sg.Input(
"Database: "
+ (database_file_path if database_file_path else "None"),
key="DATABASE_DISPLAY",
readonly=True,
font=("Segoe UI", 8),
size=(80, 1),
)
],
[
sg.Input(
"Image Save Location: "
+ (image_save_directory if image_save_directory else "None"),
key="IMAGE_SAVE_DISPLAY",
readonly=True,
font=("Segoe UI", 8),
size=(80, 1),
)
],
],
relief=sg.RELIEF_RIDGE,
)
],
[
sg.Frame(
"Search Cards",
[
[
sg.Text(
"Search by any of these attributes (Format: Name, Set, ArtType, GrpID, ArtID)",
justification="left",
)
],
[
sg.Input(
size=(40, 1),
enable_events=True,
key="-SEARCH_INPUT-",
pad=(5, 5),
),
sg.Checkbox(
"Use Decklist",
key="-USE_DECKLIST-",
default=is_using_decklist_filter,
enable_events=True,
),
],
[
sg.Button(
"Unlock Parallax Style for all cards in the list below",
key="-UNLOCK_PARALLAX-",
),
sg.Button(
"Backup changes for all cards in the list below",
key="-LOAD_OLD_CHANGES-",
expand_x=True,
),
],
[
sg.Button("Export arts for all cards in the list below", key="-EXPORT_ALL_ARTS-", expand_x=True),
],
[
sg.Text("Sort by:"),
sg.Combo(
["Name", "Set", "ArtType", "GrpID", "ArtID"],
default_value="Name",
key="-SORT_BY-",
enable_events=True,
readonly=True,
size=(15, 1),
),
],
[
sg.Text(
f"{'Name':<30} {'Set':<7} {'ArtType':<12} {'GrpID':<8} {'ArtID':<8}",
font=("Courier New", 10, "bold"),
)
],
[
sg.Listbox(
displayed_cards,
size=(70, 20),
enable_events=True,
key="-CARD_LIST-",
pad=(5, 5),
font=("Courier New", 10),
)
],
],
relief=sg.RELIEF_GROOVE,
expand_x=True,
)
],
]
# Create main application window
main_window = sg.Window(
"MTGA Swapper " + version if version else "",
main_window_layout,
grab_anywhere=True,
finalize=True,
font=("Segoe UI", 10),
element_justification="center",
background_color="#1B2838",
relative_location=(0, 0),
)
# Main GUI Event Loop
while True:
event, values = main_window.read()
if event in (sg.WIN_CLOSED, "Exit"):
break
if event == "-JOIN_DISCORD-":
open_webbrowser("https://discord.gg/339qjyVc8C")
continue
# Handle sorting of cards by selected attribute
if event == "-SORT_BY-":
selected_sort_attribute = values["-SORT_BY-"]
sorted_card_list = sort_cards_by_attribute(
main_window["-CARD_LIST-"].Values or displayed_cards,
selected_sort_attribute,
)
main_window["-CARD_LIST-"].update(sorted_card_list)
if event == "-LOAD_PRESET-":
preset_path = open_file_dialog(
"Select your changes preset JSON file", "JSON files", "*.json"
)
if preset_path == "" or preset_path is None:
continue
change_grp_id(preset_path, database_cursor, database_connection, None, asset_bundle_directory)
sg.popup_auto_close("Preset loaded successfully!", auto_close_duration=1)
if event == "-EXPORT_PRESET-":
with open(user_save_changes_path, "r") as changes_file:
changes_data = json.load(changes_file)
with open("exported_changes.json", "w") as export_file:
json.dump(changes_data, export_file, indent=4)
sg.popup_auto_close(
"Exported changes to exported_changes.json", auto_close_duration=0.5
)
if event == "-CROP_EDITOR-":
from src.crop_editor import create_crop_editor_window
if not database_file_path:
sg.popup_error(
"Please select database and image save location first",
auto_close_duration=3,
)
continue
# Create crop editor window (it handles its own event loop)
create_crop_editor_window(database_file_path, database_cursor, str(user_save_changes_path))
# Handle Set Swapper functionality
if event == "-SET_SWAPPER-":
if not database_file_path or not image_save_directory:
sg.popup_error(
"Please select database and image save location first",
auto_close_duration=3,
)
continue
# Create set swapper window
swap_window = create_set_swap_window()
try:
while True:
swap_event, swap_values = swap_window.read()
if swap_event in (sg.WIN_CLOSED, "-CLOSE-"):
break
if swap_event == "-GENERATE_SWAPS-":
source_set = swap_values["-SOURCE_SET-"].strip().lower()
target_set = swap_values["-TARGET_SET-"].strip().lower()
if not source_set or not target_set:
sg.popup_error("Please enter both source and target set codes.")
continue
# Generate to Downloads folder
output_path = (
Path.home()
/ "Downloads"
/ f"swaps_{source_set}_to_{target_set}.json"
)
if generate_swap_file(source_set, target_set, output_path):
swap_window["-SWAP_FILE-"].update(str(output_path))
sg.popup_ok(
f"Swap file generated successfully!\n\nSaved to:\n{output_path}",
title="Success",
)
else:
sg.popup_error(
"Failed to generate swap file.\n\n"
"Possible reasons:\n"
"- Invalid set codes\n"
"- No matching cards found\n"
"- Network error"
)
if swap_event == "-APPLY_SWAPS-":
swap_file = swap_values["-SWAP_FILE-"].strip()
if not swap_file or not Path(swap_file).exists():
sg.popup_error("Please select a valid swap file.")
continue
# Confirm before applying
confirm = sg.popup_yes_no(
"This will modify your game files.\n\n"
"A backup will be created automatically.\n\n"
"Do you want to continue?",
title="Confirm Swap",
)
if confirm == "Yes":
asset_bundle_dir = (
Path(database_file_path).parent.parent / "AssetBundle"
)
sg.popup_quick_message(
"Please wait, this may take a couple of minutes. There will be a popup when completed",
auto_close_duration=2, keep_on_top=False
)
if perform_set_swap(
Path(swap_file),
database_cursor,
database_connection,
asset_bundle_dir,
backup_directory,
user_save_changes_path,
):
sg.popup_ok(
"Set swap completed successfully!\n\n"
"Backups saved to:\n" + str(backup_directory) + "\n\n"
"Launch MTG Arena to see your changes.",
title="Success",
)
else:
sg.popup_error(
"Set swap failed. Please check your swap file and try again."
)
if swap_event == "-SPIDERMAN-":
if not database_file_path:
sg.popup_error(
"Please select a database first", auto_close_duration=3
)
continue
try:
spiderman_localizations(database_cursor, database_connection, get_resource_path("TempLocalizations.csv"))
sg.popup_auto_close(
"Spiderman localizations applied successfully!",
auto_close_duration=2,
)
except Exception as e:
sg.popup_error(f"Error applying localizations: {e}")
finally:
swap_window.close()
# Handle database and save directory selection
if event == "-SELECT_DATABASE-":
database_file_path = open_file_dialog(
"Select your Raw_CardDatabase mtga file in Raw Folder",
"mtga files",
"*.mtga",
)
try:
# Initialize database connection and load cards
database_cursor, database_connection, database_file_path = (
database_manager.create_database_connection(database_file_path)
)
all_cards_formatted = list(
map(
format_card_display,
sorted(
database_cursor.execute(
get_cards_query
).fetchall()
),
)
)
displayed_cards = all_cards_formatted
except (
database_manager.sqlite3.OperationalError,
database_manager.sqlite3.DatabaseError,
TypeError,
):
sg.popup_error(
"Missing or incorrect database selected", auto_close_duration=3
)
# Select image save directory
image_save_directory = open_directory_dialog(
"Select a folder to save images to"
)
# Save configuration to file
if image_save_directory and database_file_path:
with open(user_config_file_path, "w") as config_file:
user_config["SavePath"] = str(Path(image_save_directory).as_posix())
user_config["DatabasePath"] = str(Path(database_file_path).as_posix())
config_file.write(sg.json.dumps(user_config, indent=4))
# Configure Unity version and update GUI
configure_unity_version(database_file_path, "2022.3.42f1")
main_window["-CARD_LIST-"].update(displayed_cards)
main_window["-CHANGE_ASSETS-"].update(
"Change Sleeves, Avatars, etc.", disabled=False
)
main_window["-SET_SWAPPER-"].update(disabled=False)
main_window["DATABASE_DISPLAY"].update(
"Database: " + (database_file_path if database_file_path else "None")
)
main_window["IMAGE_SAVE_DISPLAY"].update(
"Image Save Location: "
+ (image_save_directory if image_save_directory else "None")
)
asset_bundle_directory = (
os.path.dirname(database_file_path)[0:-3] + "AssetBundle"
)
if event == "-SEARCH_TOKENS-":
if database_cursor is not None:
window_tokens = create_search_tokens_window(database_cursor)
while True:
event_token, values_token = window_tokens.read()
if event_token == sg.WINDOW_CLOSED or event_token == "-CANCEL_BUTTON-":
break
elif event_token == "-SEARCH_BUTTON-":
artist_name = values_token["-SEARCH_INPUT-"]
# Perform search operation here
tokens = database_manager.get_tokens_by_artist(
artist_name, database_cursor
)
if tokens:
window_tokens["-RESULT_LIST-"].update(
values=[f"{name} - {art_id}" for name, art_id in tokens]
)
else:
window_tokens["-RESULT_LIST-"].update(
values=["No tokens found."]
)
elif event_token == "-RESULT_LIST-":
selected_token = values_token["-RESULT_LIST-"][0]
token_card = MTGACard(
"", "", "", "", selected_token.split(" - ")[1]
)
image_data_list, texture_data_list, matching_file = (
get_card_texture_data(
token_card, database_file_path, ret_matching=True
)
)
if image_data_list:
display_texture_bytes = convert_texture_to_bytes(
image_data_list[0]
)
token_card.image = display_texture_bytes
else:
print("No texture found.")
token_editor_layout = [
[
sg.Button(
"Change image",
key="-CHANGE_ASSET_IMAGE-",
),
sg.Button(
"Set aspect ratio to",
key="-SET_ASPECT_RATIO-",
),
sg.Input(
"Width",
key="-ASPECT_WIDTH-",
size=(5, 1),
),
sg.Input(
"Height",
key="-ASPECT_HEIGHT-",
size=(5, 1),
),
sg.Button("Save", key="-SAVE_ASSET-"),
],
[
sg.Image(
source=display_texture_bytes,
key="-ASSET_IMAGE-",
)
],
]
# Show the token editor window
token_editor_window = sg.Window(
"Edit Token",
token_editor_layout,
modal=True,
finalize=True,
grab_anywhere=True,
relative_location=(0, 0),
)
while True:
event, values = token_editor_window.read()
if event == sg.WINDOW_CLOSED:
break
if event == "-CHANGE_ASSET_IMAGE-":
new_image_path = open_file_dialog(
"Select your new image", "image files", "*.png"
)
if new_image_path not in ("", None):
# Create backup of original image
backup_image_path = f"{os.path.join(image_save_directory, token_card.art_id)}-token_backup.png"
save_image_to_file(
texture_data_list[0].image, backup_image_path, True
)
unity_environment = load_unity_bundle(
os.path.join(asset_bundle_directory, matching_file)
)
# Replace the texture with new image
texture_data = extract_textures_from_bundle(
unity_environment
)[0]
replace_texture_in_bundle(
texture_data,
new_image_path,
os.path.join(asset_bundle_directory, matching_file),
unity_environment,
)
# Backup the NEW asset bundle file after changes
shutil.copy(
os.path.join(asset_bundle_directory, matching_file),
backup_directory / f"MOD_{matching_file}",
)
display_texture_bytes = convert_texture_to_bytes(
texture_data.image
)
# Update display with new image
token_editor_window["-ASSET_IMAGE-"].update(
source=display_texture_bytes
)
token_card.image = texture_data.image
sg.popup_auto_close(
"Image changed successfully!", auto_close_duration=1
)
else:
sg.popup_error(
"Invalid image file", auto_close_duration=1
)
# Handle asset saving
if event == "-SAVE_ASSET-":
save_path = f"{os.path.join(image_save_directory, token_card.art_id)}-token.png"
save_image_to_file(token_card.image, save_path, True)
sg.popup_auto_close(
"Asset saved successfully!", auto_close_duration=1
)
else:
sg.popup_error("Please select a database first", auto_close_duration=3)
# Handle decklist loading
if event == "-LOAD_DECKLIST-":
cards_from_imported_deck = create_decklist_import_window()
main_window["-USE_DECKLIST-"].update(value=True)
event = "-USE_DECKLIST-"
values["-USE_DECKLIST-"] = True
if event == "-EXPORT_ALL_ARTS-":
artid_list = [
(card.split()[0], card.split()[4])
for card in filtered_search_results if card.split()[0] not in lands_set
]
export_directory = askdirectory(
title="Select folder to save exported arts",
initialdir=image_save_directory if image_save_directory else os.path.expanduser("~"),
)
if export_directory:
for name, artid in artid_list:
card = MTGACard(name, "", "", "", artid)
image_data_list, texture_data_list, matching_file = get_card_texture_data(
card, database_file_path, ret_matching=True
)
if image_data_list:
image_bytes = convert_texture_to_bytes(image_data_list[0])
image = Image.open(io.BytesIO(image_bytes))
save_path = os.path.join(export_directory, f"{name}.png")
image.save(save_path)
else:
print(f"No texture found for {name} ({artid})")
sg.popup_auto_close(
f"Exported {len(artid_list)} arts to {export_directory}", auto_close_duration=2
)
if event == "-UNLOCK_PARALLAX-":
grpid_list = [
card.split()[3]
for card in filtered_search_results
if card.split()[0]
not in lands_set
]
if sg.popup_yes_no("Are you sure you want to unlock Parallax Style for " + str(len(grpid_list)) + " cards?", title="Confirm") == "Yes":
if database_manager.unlock_parallax_style(
grpid_list, database_cursor, database_connection, user_save_changes_path
):
sg.popup_auto_close("Parallax style unlocked successfully!")
else:
sg.popup_auto_close(
"Failed to unlock parallax style, ensure that the database is not open in another program."
)
if event == "-LOAD_OLD_CHANGES-":
grpid_list = [
card.split()[3]
for card in filtered_search_results
if card.split()[0]
not in lands_set
]
save_grp_id_info(
grpid_list,
user_save_changes_path,
database_cursor,
database_connection,
asset_bundle_directory,
)
with open(user_save_changes_path, "r") as changes_file:
changes_data = json.load(changes_file)
with open("exported_changes.json", "w") as export_file:
json.dump(changes_data, export_file, indent=4)
sg.popup_auto_close(
"Exported changes to exported_changes.json", auto_close_duration=0.5
)
# Handle font export functionality
if event == "-EXPORT_FONTS-":
font_bundle_path = askopenfilename(
title="Select file that starts with 'Fonts_' in AssetBundle Folder"
)
font_export_directory = askdirectory(
initialdir=os.path.dirname(font_bundle_path),
title="Select folder to save fonts",
)
if font_bundle_path:
unity_environment = load_unity_bundle(font_bundle_path)
extracted_fonts = extract_fonts(unity_environment, font_export_directory)
# Handle change assets functionality (sleeves, avatars, etc.)
if event == "-CHANGE_ASSETS-":
if database_file_path and image_save_directory:
# Get the AssetBundle directory path
asset_bundle_directory = (
os.path.dirname(database_file_path)[0:-3] + "AssetBundle"
)
# Get list of asset bundle files (excluding card art)
asset_bundle_files = sorted(
[
bundle_file
for bundle_file in os.listdir(asset_bundle_directory)
if not any(
[
"CardArt" in bundle_file,
bundle_file.startswith("Bucket_Card.Sleeve"),
]
)
]
)
asset_bundle_files.append("resources.assets")
# Create asset browser window
asset_browser_layout = [
[sg.Text("Select a file to change/view the assets of")],
[sg.Text("Search for files by type")],
[sg.Input(size=(90, 1), enable_events=True, key="-ASSET_SEARCH-")],
[sg.Button("Export all images below", key="-EXPORT_ALL_ASSETS-")],
[
sg.Listbox(
asset_bundle_files,
size=(90, 40),
enable_events=True,
key="-ASSET_LIST-",
)
],
]
asset_browser_window = sg.Window(
"Asset Browser - Sleeves, Avatars, etc.",
asset_browser_layout,
modal=True,
grab_anywhere=True,
relative_location=(0, 0),
finalize=True,
)
# Asset browser event loop
while True:
asset_event, asset_values = asset_browser_window.read()
if asset_event in (sg.WIN_CLOSED, "Exit"):
break
# Handle search filtering
if asset_event == "-ASSET_SEARCH-" and asset_values["-ASSET_SEARCH-"]:
search_term = asset_values["-ASSET_SEARCH-"].lower()
filtered_files = [
file
for file in asset_bundle_files
if search_term in file.lower()
]
asset_browser_window["-ASSET_LIST-"].update(filtered_files)
elif (
asset_event == "-ASSET_SEARCH-"
and not asset_values["-ASSET_SEARCH-"]
):
asset_browser_window["-ASSET_LIST-"].update(asset_bundle_files)
# Handle export all assets
if asset_event == "-EXPORT_ALL_ASSETS-":
current_asset_list = asset_browser_window["-ASSET_LIST-"].Values
if (
sg.popup_yes_no(
f"Are you sure you want to export all images from these {len(current_asset_list)} file bundles?"
)
== "Yes"
):
if not os.path.exists(image_save_directory):
os.makedirs(image_save_directory)
for asset_file_name in current_asset_list:
try:
unity_environment = load_unity_bundle(
os.path.join(
asset_bundle_directory, asset_file_name
)
)
extracted = extract_textures_from_bundle(
unity_environment
)
for texture in extracted:
texture.image.save(
os.path.join(
image_save_directory,
f"{texture.m_Name}.png",
)
)
except Exception as e:
print(f"Error processing {asset_file_name}: {e}")
sg.popup_auto_close(
"All images exported successfully!", auto_close_duration=2
)
# Handle individual asset selection
if asset_event == "-ASSET_LIST-" and asset_values["-ASSET_LIST-"]:
selected_asset_file = asset_values["-ASSET_LIST-"][0]
try:
# Load the selected asset bundle
if "resources.assets" in selected_asset_file.lower():
unity_environment = load_unity_bundle(str(Path(asset_bundle_directory).parent.parent / "resources.assets"))
else:
unity_environment = load_unity_bundle(
os.path.join(asset_bundle_directory, selected_asset_file)
)
# Get all textures from the bundle
print(unity_environment)
texture_data_list = extract_textures_from_bundle(
unity_environment
)
print(f"Found {len(texture_data_list)} textures in {selected_asset_file}")
if texture_data_list:
# Create gallery view with thumbnails
images_per_row = 3
gallery_images = []
for i, texture in enumerate(texture_data_list):
# Create thumbnail for gallery
thumbnail_image = resize_image_for_gallery(
texture.image, (200, 200)
)
thumbnail_bytes = convert_texture_to_bytes(
thumbnail_image
)
gallery_images.append(
sg.Button(
image_data=thumbnail_bytes,
key=f"-GALLERY-IMG-{i}-",
pad=(5, 5),
tooltip=f"Click to view/edit image {i+1}",
)
)
# Arrange images in rows
gallery_rows = [
gallery_images[i : i + images_per_row]
for i in range(0, len(gallery_images), images_per_row)
]
# Create gallery layout
gallery_layout = [