forked from jbowensii/MoriaModCreator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdef_creator_view.py
More file actions
1674 lines (1406 loc) · 70.4 KB
/
def_creator_view.py
File metadata and controls
1674 lines (1406 loc) · 70.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
"""Create DEF view — generates .def files by comparing modded vs original game files.
Algorithm:
1. User selects two folders: modded game files and original game files
2. Auto-converts any .uasset files to JSON using UAssetGUI
3. Matches files by name between both folders
4. For each matched pair, parses the UAssetAPI JSON (Exports[0].Table.Data[])
5. Walks each row's Value property list recursively, comparing primitives,
arrays, and structs to find differences
6. Groups differences by leaf property name (e.g. all MaxStackSize changes)
7. Generates one .def XML file per property group per JSON file
8. Shows a preview/edit window; user can edit before saving
"""
import json
import logging
import os
import shutil
import subprocess
import tempfile
import threading
import re
from pathlib import Path
import customtkinter as ctk
from src.config import (
get_utilities_dir, get_game_install_path, get_default_definitions_dir,
get_prebuilt_modfiles_dir,
)
from src.constants import UE_VERSION, RETOC_UE_VERSION, UASSETGUI_EXE, RETOC_EXE
from src.ui.shared_utils import get_jsondata_dir, get_retoc_dir
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Pure diff logic (no UI dependency, testable)
# ---------------------------------------------------------------------------
def _extract_uasset_data(json_obj):
"""Smartly extracts Data from a UAssetAPI JSON object."""
exports = json_obj.get("Exports", [])
# 1. Standardní DataTable
for exp in exports:
if "Table" in exp and "Data" in exp["Table"]:
return exp["Table"]["Data"]
# 2. CurveTable Export
for exp in exports:
if exp.get("$type", "").startswith("CurveTableExport"):
data = exp.get("Data")
if isinstance(data, list):
return data
# 3. Samostatné assety (DataAsset, CurveFloat atd.)
for exp in exports:
if "Data" in exp and isinstance(exp["Data"], list):
obj_name = exp.get("ObjectName", "DefaultAsset")
if obj_name.startswith("Default__"):
obj_name = obj_name.replace("Default__", "")
return [{"Name": obj_name, "Value": exp["Data"]}]
return None
def _format_value(val):
"""Format a property value for display in .def XML."""
if isinstance(val, bool):
return "True" if val else "False"
str_val = str(val)
if str_val.startswith('+'):
try:
num = float(str_val)
if num.is_integer():
return str(int(num))
return str(num)
except ValueError:
pass
if isinstance(val, float) and val.is_integer():
return str(int(val))
return str_val
def _extract_context(props_list, prop_name=""):
"""Try to find a meaningful context label (e.g. item name) near the property."""
context_keys = (
"Item", "Resource", "Material", "ItemTemplate", "ItemTag",
"Tag", "GameplayTag", "DropItem", "ResultItem", "Reward", "Loot"
)
for prop in props_list:
if not isinstance(prop, dict):
continue
name = prop.get("Name", "")
if name not in context_keys:
continue
val = prop.get("Value")
if isinstance(val, dict):
for key in ("AssetPath", "ObjectName", "TagName", "Name"):
if key in val:
inner = val[key]
if isinstance(inner, dict) and "AssetName" in inner:
asset = inner["AssetName"]
return asset.split("/")[-1].split(".")[0]
if isinstance(inner, str):
return inner
elif isinstance(val, str):
return val
return None
def _compare_properties(mod_props, orig_props, current_path=""):
"""Recursively compare two UAssetAPI property lists and return changes."""
changes = []
if not (isinstance(mod_props, list) and isinstance(orig_props, list)):
return changes
orig_dict = {}
for o in orig_props:
if isinstance(o, dict) and "Name" in o:
orig_dict[o["Name"]] = o
for m in mod_props:
if not isinstance(m, dict):
continue
type_str = m.get("$type", "")
if "Name" not in m:
continue
prop_name = m["Name"]
new_path = f"{current_path}.{prop_name}" if current_path else prop_name
o = orig_dict.get(prop_name)
# --- TADY ZAČÍNÁ TA ZMĚNĚNÁ ČÁST ---
is_missing = (o is None)
is_null = (isinstance(o, dict) and o.get("Value") is None)
if is_missing or is_null:
val = m.get("Value")
str_val = _format_value(val) if not isinstance(val, (list, dict)) else ""
# Všechno, co chybí nebo je null, přidáme rovnou jako <add_property> i s JSONem
changes.append({
"type": "add",
"property": new_path,
"value": str_val,
"old_value": "New Property (was null)",
"context": _extract_context(orig_props, prop_name),
"json_data": json.dumps(m, indent=2),
})
continue
# --- TADY ZMĚNĚNÁ ČÁST KONČÍ ---
# (Zde u tebe v kódu normálně pokračují další věci jako elif "ArrayPropertyData" atd. - ty tam samozřejmě nech)
if "GameplayTagContainerPropertyData" in type_str:
container_prop = current_path.split(".")[-1] if current_path else prop_name
m_tags = m.get("Value", [])
o_tags = o.get("Value", [])
if m_tags != o_tags:
m_set = set(m_tags) if isinstance(m_tags, list) else set()
o_set = set(o_tags) if isinstance(o_tags, list) else set()
removed = o_set - m_set
added = m_set - o_set
for tag in sorted(removed):
changes.append({
"type": "delete",
"property": container_prop,
"value": tag,
"old_value": tag,
"context": _extract_context(orig_props, prop_name),
})
for tag in sorted(added):
changes.append({
"type": "add_tag",
"property": container_prop,
"value": tag,
"old_value": "(new tag)",
"context": _extract_context(orig_props, prop_name),
})
elif "ArrayPropertyData" in type_str or "SetPropertyData" in type_str:
m_list = m.get("Value", []) or []
o_list = o.get("Value", []) or []
for i in range(max(len(m_list), len(o_list))):
arr_path = f"{new_path}[{i}]"
m_val = m_list[i] if i < len(m_list) else None
o_val = o_list[i] if i < len(o_list) else None
if m_val and not o_val:
if isinstance(m_val, dict):
added_context = _extract_context(m_val.get("Value", []))
changes.append({
"type": "add",
"property": new_path,
"value": "",
"old_value": "Added to Array",
"context": added_context,
"json_data": json.dumps(m_val, indent=2)
})
elif not m_val and o_val:
if isinstance(o_val, dict):
o_name = o_val.get("Name", f"[{i}]")
o_display = o_val.get("Value", o_name)
removed_context = _extract_context(o_val.get("Value", []))
changes.append({
"type": "remove",
"property": arr_path,
"value": "(removed)",
"old_value": _format_value(o_display) if not isinstance(o_display, (list, dict)) else o_name,
"context": removed_context,
})
elif m_val and o_val:
if isinstance(m_val, dict) and isinstance(o_val, dict):
changes.extend(_compare_properties(
m_val.get("Value", []), o_val.get("Value", []), arr_path
))
elif "StructPropertyData" in type_str:
m_val = m.get("Value", []) or []
o_val = o.get("Value", []) or []
if isinstance(m_val, list) and isinstance(o_val, list):
changes.extend(_compare_properties(m_val, o_val, new_path))
elif isinstance(m_val, dict) and isinstance(o_val, dict):
for k in set(m_val.keys()).union(o_val.keys()):
if k in ("$type", "Name"): continue
v_m = m_val.get(k)
v_o = o_val.get(k)
if v_m != v_o:
changes.append({
"type": "change",
"property": f"{new_path}.{k}",
"value": _format_value(v_m) if not isinstance(v_m, (list, dict)) else str(v_m)[:100],
"old_value": _format_value(v_o) if not isinstance(v_o, (list, dict)) else str(v_o)[:100],
"context": _extract_context(orig_props, prop_name),
})
else:
primitive_types = (
"IntPropertyData", "BoolPropertyData", "FloatPropertyData",
"EnumPropertyData", "NamePropertyData", "StrPropertyData",
"BytePropertyData", "TextPropertyData",
"ObjectPropertyData", "SoftObjectPropertyData",
)
if any(pt in type_str for pt in primitive_types):
m_val = m.get("Value")
o_val = o.get("Value")
if m_val != o_val:
context = _extract_context(orig_props, prop_name)
changes.append({
"type": "change",
"property": new_path,
"value": _format_value(m_val),
"old_value": _format_value(o_val),
"context": context,
})
else:
m_val = m.get("Value")
o_val = o.get("Value")
if m_val != o_val:
if isinstance(m_val, list) and isinstance(o_val, list):
for i in range(max(len(m_val), len(o_val))):
sub_m = m_val[i] if i < len(m_val) else None
sub_o = o_val[i] if i < len(o_val) else None
if isinstance(sub_m, dict) and isinstance(sub_o, dict):
if "Value" in sub_m and isinstance(sub_m["Value"], list):
changes.extend(_compare_properties(
sub_m.get("Value", []),
sub_o.get("Value", []),
f"{new_path}[{i}]",
))
else:
for k in set(sub_m.keys()).union(sub_o.keys()):
if k in ("$type", "Name"): continue
v_m = sub_m.get(k)
v_o = sub_o.get(k)
if v_m != v_o:
changes.append({
"type": "change",
"property": f"{new_path}[{i}].{k}",
"value": _format_value(v_m) if not isinstance(v_m, (list, dict)) else str(v_m)[:100],
"old_value": _format_value(v_o) if not isinstance(v_o, (list, dict)) else str(v_o)[:100],
"context": _extract_context(orig_props, prop_name),
})
elif sub_m != sub_o:
changes.append({
"type": "change",
"property": f"{new_path}[{i}]",
"value": _format_value(sub_m) if sub_m is not None else "(removed)",
"old_value": _format_value(sub_o) if sub_o is not None else "(new)",
"context": _extract_context(orig_props, prop_name),
})
elif isinstance(m_val, dict) and isinstance(o_val, dict):
for k in set(m_val.keys()).union(o_val.keys()):
if k in ("$type", "Name"): continue
v_m = m_val.get(k)
v_o = o_val.get(k)
if v_m != v_o:
changes.append({
"type": "change",
"property": f"{new_path}.{k}",
"value": _format_value(v_m) if not isinstance(v_m, (list, dict)) else str(v_m)[:100],
"old_value": _format_value(v_o) if not isinstance(v_o, (list, dict)) else str(v_o)[:100],
"context": _extract_context(orig_props, prop_name),
})
else:
changes.append({
"type": "change",
"property": new_path,
"value": _format_value(m_val) if not isinstance(m_val, (list, dict)) else str(m_val)[:100],
"old_value": _format_value(o_val) if not isinstance(o_val, (list, dict)) else str(o_val)[:100],
"context": _extract_context(orig_props, prop_name),
})
return changes
def find_differences(orig_data, mod_data):
differences = []
orig_dict = {item.get("Name"): item for item in orig_data}
mod_dict = {item.get("Name"): item for item in mod_data}
for mod_item in mod_data:
item_name = mod_item.get("Name")
orig_item = orig_dict.get(item_name)
orig_props = orig_item.get("Value", []) if orig_item else []
diffs = _compare_properties(mod_item.get("Value", []), orig_props)
for diff in diffs:
diff["item"] = item_name
differences.append(diff)
for orig_item in orig_data:
item_name = orig_item.get("Name")
if item_name and item_name not in mod_dict:
differences.append({
"type": "remove",
"item": item_name,
"property": "(entire row)",
"value": "(deleted)",
"old_value": "Row existed in original",
"context": None,
})
return differences
def group_diffs_by_property(differences):
grouped = {}
for diff in differences:
prop_key = diff["property"].split(".")[-1].split("[")[0]
grouped.setdefault(prop_key, []).append(diff)
return grouped
def _get_existing_description(base_filename):
"""Najde description v existujícím .ini/.def (včetně podadresářů)."""
import xml.etree.ElementTree as ET
if not base_filename:
return None
def _read_ini_description(ini_file: Path):
try:
content = ini_file.read_text(encoding="utf-8")
match = re.search(r"(?im)^\s*Description\s*=\s*(.+?)\s*$", content)
if match:
return match.group(1).strip()
except OSError:
return None
return None
def _read_def_description(def_file: Path):
try:
tree = ET.parse(def_file)
desc_el = tree.getroot().find("description")
if desc_el is not None and desc_el.text:
return desc_el.text.strip()
except (OSError, ET.ParseError):
return None
return None
# 1) Preferujeme .def podle jména (typické pro per-file descriptions).
defs_dir = get_default_definitions_dir()
if defs_dir.exists():
for def_file in defs_dir.rglob(f"{base_filename}.def"):
desc = _read_def_description(def_file)
if desc:
return desc
# 2) Fallback na .ini stejného jména (mod-level description).
prebuilt_dir = get_prebuilt_modfiles_dir()
for search_dir in (prebuilt_dir, defs_dir):
if search_dir.exists():
ini_file = search_dir / f"{base_filename}.ini"
if ini_file.exists():
desc = _read_ini_description(ini_file)
if desc:
return desc
return None
def generate_def_xml(diffs, mod_path, title, author, description,
change_note="", include_comments=False, base_filename=""):
# Zkusíme najít starý popis, pokud nebyl zadán nový nebo pokud chceme prioritu
existing_desc = _get_existing_description(base_filename) if base_filename else None
final_description = existing_desc if existing_desc else description
lines = [
"<?xml version='1.0' encoding='UTF-8'?>",
"<definition>",
f" <title>{title}</title>",
f" <author>{author}</author>",
f" <description>{final_description}</description>", # Použijeme nalezený nebo původní
f' <mod file="{mod_path}">',
]
for diff in diffs:
diff_type = diff.get("type", "change")
if include_comments:
item_info = diff["item"]
if diff.get("context"):
item_info += f": {diff['context']}"
if diff_type == "add":
old_text = "Added"
elif diff_type == "delete":
old_text = f"Delete tag {diff['value']}"
elif diff_type == "add_tag":
old_text = f"Add tag {diff['value']}"
elif diff_type == "remove":
old_text = "Removed"
else:
old_text = f"was {diff['old_value']}"
comment = f"{change_note} - {item_info}" if change_note else item_info
lines.append(f" <!-- {comment} ({old_text}) -->")
if diff_type == "delete":
lines.append(f' <delete item="{diff["item"]}" '
f'property="{diff["property"]}" '
f'value="{diff["value"]}" />')
elif diff_type == "add_tag":
lines.append(f' <change item="{diff["item"]}" '
f'property="{diff["property"]}" '
f'value="{diff["value"]}" />')
elif diff_type == "add":
lines.append(f' <change item="{diff["item"]}" '
f'property="{diff["property"]}" '
f'value="{diff["value"]}">')
lines.append(f' <add_property item="{diff["item"]}">'
f'<![CDATA[{diff.get("json_data", "")}]]>'
f'</add_property>')
lines.append(' </change>')
elif diff_type == "remove":
lines.append(f' <!-- ROW DELETED: {diff["item"]} '
f'property="{diff["property"]}" -->')
else:
lines.append(f' <change item="{diff["item"]}" '
f'property="{diff["property"]}" '
f'value="{diff["value"]}" />')
lines.append(" </mod>")
lines.append("</definition>")
return "\n".join(lines)
def _detect_category(mod_file_path: str) -> str:
normalized = mod_file_path.replace("\\", "/")
filename = normalized.rsplit("/", 1)[-1]
basename = filename.rsplit(".", 1)[0]
_CATEGORY_MAP = {
"DT_Armor": "Items", "DT_Consumables": "Items", "DT_ConstructionRecipes": "Building",
"DT_Constructions": "Building", "DT_ConstructionStabilities": "Building",
"DT_Items": "Items", "DT_ItemRecipes": "Items", "DT_ItemTint": "Effects",
"DT_Loot": "Loot", "DT_MonumentData": "Monuments", "DT_Moria_Flora": "Flora",
"DT_Ores": "Items", "DT_RecipeBundles": "Trade", "DT_SettlementLevelData": "Settlement",
"DT_Storage": "Storage", "DT_Tools": "Items", "DT_TradeGoods": "Trade",
"DT_Weapons": "Items", "DT_WorldLevelData": "Settlement",
}
if basename in _CATEGORY_MAP: return _CATEGORY_MAP[basename]
for prefix, category in _CATEGORY_MAP.items():
if basename.startswith(prefix): return category
if basename.startswith("GE_") or basename.startswith("Curve_"): return "Buffs"
if basename.startswith("Properties_"): return "Ores"
parts = [p for p in normalized.split("/") if p]
if len(parts) >= 2: return parts[-2]
return "Misc"
def generate_ini_content(title, author, description, category_files):
lines = [
"[ModInfo]", f"Title = {title}", f"Authors = {author}",
f"Description = {description}", "", "[Paths]",
]
for category, filenames in sorted(category_files.items()):
cat_lower = category.lower()
for fname in sorted(filenames):
lines.append(f"{cat_lower}|{fname.lower()} = true")
lines.append(f"{cat_lower} = true")
lines.append("")
lines.append("[Settings]")
lines.append("include_secrets = False")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# View
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# INI Editor Popup Window (with HTML Helpers & Split Fields)
# ---------------------------------------------------------------------------
class IniEditorWindow(ctk.CTkToplevel):
"""Popup window to edit the generated .ini file with split fields and HTML helpers."""
def __init__(self, parent, ini_path: Path):
super().__init__(parent)
self.title(f"Edit Mod Configuration: {ini_path.name}")
self.geometry("900x700")
self.ini_path = ini_path
self.rest_content = "" # Sem si schováme [Paths] a [Settings]
self.transient(parent.winfo_toplevel())
self.grab_set()
self.grid_rowconfigure(3, weight=1)
self.grid_columnconfigure(0, weight=1)
info_text = "Edit your mod's metadata. The technical paths are safely hidden and will be saved automatically."
ctk.CTkLabel(self, text=info_text, font=ctk.CTkFont(weight="bold")).grid(
row=0, column=0, pady=(10, 5), padx=10, sticky="w"
)
# --- Mod Info Sekce (Title a Author) ---
header_frame = ctk.CTkFrame(self, fg_color="transparent")
header_frame.grid(row=1, column=0, sticky="ew", padx=10, pady=5)
ctk.CTkLabel(header_frame, text="Mod Name:", width=80, anchor="w", font=ctk.CTkFont(weight="bold")).pack(side="left")
self.title_entry = ctk.CTkEntry(header_frame, width=300)
self.title_entry.pack(side="left", padx=5)
ctk.CTkLabel(header_frame, text="Author:", width=60, anchor="w", font=ctk.CTkFont(weight="bold")).pack(side="left", padx=(20, 0))
self.author_entry = ctk.CTkEntry(header_frame, width=300)
self.author_entry.pack(side="left", padx=5)
# --- HTML Helper Toolbar (Lišta pro Description) ---
toolbar = ctk.CTkFrame(self, fg_color="transparent")
toolbar.grid(row=2, column=0, sticky="ew", padx=10, pady=(15, 5))
ctk.CTkLabel(toolbar, text="Description:", width=80, anchor="w", font=ctk.CTkFont(weight="bold")).pack(side="left")
helpers = [
("Header 1", "<h1>", "</h1>"),
("Header 2", "<h2>", "</h2>"),
("Bold", "<b>", "</b>"),
("Italic", "<i>", "</i>"),
("Underline", "<u>", "</u>"),
("Paragraph", "<p>", "</p>"),
("Line Break", "<br>", ""),
]
for text, open_tag, close_tag in helpers:
ctk.CTkButton(
toolbar, text=text, width=80, height=24,
command=lambda o=open_tag, c=close_tag: self._wrap_text(o, c)
).pack(side="left", padx=2)
ctk.CTkButton(
toolbar, text="Insert Table", width=100, height=24, fg_color="#1565C0",
command=self._insert_table_template
).pack(side="left", padx=(15, 2))
# --- Textový Editor pro Description ---
self.desc_textbox = ctk.CTkTextbox(self, font=ctk.CTkFont(family="Consolas", size=14))
self.desc_textbox.grid(row=3, column=0, sticky="nsew", padx=10, pady=5)
# --- Spodní ovládací tlačítka ---
btn_frame = ctk.CTkFrame(self, fg_color="transparent")
btn_frame.grid(row=4, column=0, pady=10)
ctk.CTkButton(
btn_frame, text="Save & Close", fg_color="#2E7D32", hover_color="#1B5E20",
command=self._save_ini
).pack(side="left", padx=10)
ctk.CTkButton(
btn_frame, text="Cancel (Discard)", fg_color="#C62828", hover_color="#b71c1c",
command=self.destroy
).pack(side="left", padx=10)
# --- Načtení dat ze souboru ---
self._load_ini_data()
def _load_ini_data(self):
"""Robustnější načítání, které zvládne text hned za rovnítkem i bez odsazení."""
try:
with open(self.ini_path, "r", encoding="utf-8") as f:
lines = f.readlines()
desc_lines = []
rest_lines = []
in_desc = False
in_rest = False
for line in lines:
stripped = line.strip()
# Detekce technických sekcí - vše odtud dolů schováme
if stripped.startswith("[Paths]") or stripped.startswith("[Settings]"):
in_rest = True
in_desc = False
if in_rest:
rest_lines.append(line)
continue
# Čtení názvu a autora
if stripped.startswith("Title") and "=" in stripped:
self.title_entry.insert(0, stripped.split("=", 1)[1].strip())
continue
elif stripped.startswith("Authors") and "=" in stripped:
self.author_entry.insert(0, stripped.split("=", 1)[1].strip())
continue
# Čtení Description
if stripped.startswith("Description") and "=" in stripped:
in_desc = True
val = stripped.split("=", 1)[1].strip()
if val:
desc_lines.append(val)
continue
# Pokud jsme v sekci popisu a řádek nezačíná novou sekcí []
# přidáme ho do popisu (i když není odsazený mezerami)
if in_desc and not stripped.startswith("["):
# Pokud narazíme na prázdný řádek, přidáme ho taky
desc_lines.append(stripped)
# Vložení popisu do textboxu (spojíme řádky)
self.desc_textbox.insert("1.0", "\n".join(desc_lines))
# Uložení zbytku souboru
self.rest_content = "".join(rest_lines)
except Exception as e:
self.desc_textbox.insert("1.0", f"Chyba při načítání souboru:\n{e}")
# --- Pomocné funkce pro HTML ---
def _wrap_text(self, open_tag, close_tag):
"""Obalí výběr nebo funguje jako tupý vkladač začátku/konce."""
# Získáme přístup k textovému poli
txt = self.desc_textbox._textbox
# 1. Pokusíme se o obalení vybraného textu
try:
start = txt.index("sel.first")
end = txt.index("sel.last")
sel_text = txt.get(start, end)
txt.delete(start, end)
txt.insert(start, f"{open_tag}{sel_text}{close_tag}")
# Vrátíme označení na text uvnitř tagů
new_start = txt.index(f"{start} + {len(open_tag)}c")
new_end = txt.index(f"{new_start} + {len(sel_text)}c")
txt.tag_add("sel", new_start, new_end)
self.desc_textbox.focus_set()
return # Hotovo, končíme
except:
# Pokud není výběr, pokračujeme k vkládání tagů
pass
# 2. Scénář bez výběru (Přepínač/Vkladač)
cursor = txt.index("insert")
# Pokud tag nemá konec (Line Break), prostě ho vložíme
if not close_tag:
txt.insert(cursor, open_tag)
else:
# Zjistíme, co je před kurzorem (posledních 100 znaků na řádku)
line_content = txt.get("insert linestart", "insert")
# Pokud už tam otevírací tag je a není tam uzavírací, dáme uzavírací
if open_tag in line_content and close_tag not in line_content.split(open_tag)[-1]:
txt.insert(cursor, close_tag)
else:
# Jinak vložíme otevírací
txt.insert(cursor, open_tag)
self.desc_textbox.focus_set()
def _insert_table_template(self):
table_html = (
'\n<table cellpadding="6" cellspacing="0" border="0">\n'
'<tr>\n'
'<td><b>Category</b></td>\n'
'<td><b>Value</b></td>\n'
'</tr>\n'
'<tr>\n'
'<td>Item 1</td>\n'
'<td>999</td>\n'
'</tr>\n'
'</table>\n'
)
cursor = self.desc_textbox.index("insert")
self.desc_textbox.insert(cursor, table_html)
# --- Ukládání ---
def _save_ini(self):
"""Sestaví INI zpátky dohromady, naformátuje popis a uloží ho."""
title = self.title_entry.get().strip()
author = self.author_entry.get().strip()
raw_desc = self.desc_textbox.get("1.0", "end-1c")
# Automatické formátování popisu (odsazení o 4 mezery)
formatted_desc_lines = []
for line in raw_desc.splitlines():
stripped = line.strip()
if stripped == "":
formatted_desc_lines.append("")
else:
formatted_desc_lines.append(" " + stripped)
desc_final = "\n".join(formatted_desc_lines)
# Poskládání finálního souboru
final_content = (
f"[ModInfo]\n"
f"Title = {title}\n"
f"Authors = {author}\n"
f"Description =\n{desc_final}\n\n"
f"{self.rest_content}"
)
try:
with open(self.ini_path, "w", encoding="utf-8") as f:
f.write(final_content)
self.destroy()
except Exception as e:
self.desc_textbox.insert("end", f"\n\n[ERROR SAVING]: {e}")
class DefCreatorView(ctk.CTkFrame):
"""Advanced-mode view for generating .def files from modded vs original game files."""
def __init__(self, parent, on_status_message=None, on_back=None, **kwargs):
super().__init__(parent, fg_color="transparent", **kwargs)
self._on_status = on_status_message
self._on_back = on_back
self._mod_folder = ""
self._orig_folder = ""
self._generated_files: dict[str, str] = {}
self._generated_categories: dict[str, str] = {}
self._include_comments = ctk.BooleanVar(value=False)
self._scan_thread = None
self._current_preview_file = None
self._mod_entry = None
self._orig_entry = None
self._title_entry = None
self._author_entry = None
self._desc_entry = None
self._note_entry = None
self._found_properties = []
self._create_ui()
# ------------------------------------------------------------------
# UI construction
# ------------------------------------------------------------------
def _create_ui(self):
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
scroll = ctk.CTkScrollableFrame(self, fg_color="transparent")
scroll.grid(row=0, column=0, sticky="nsew", padx=10, pady=10)
scroll.grid_columnconfigure(1, weight=1)
row = 0
title = ctk.CTkLabel(
scroll, text="Create DEF Files",
font=ctk.CTkFont(size=20, weight="bold"),
text_color=("#333", "#ddd"),
)
title.grid(row=row, column=0, columnspan=3, sticky="w", pady=(0, 5))
row += 1
subtitle = ctk.CTkLabel(
scroll,
text="Compare modded game files against originals to generate .def definition files.",
text_color="gray",
)
subtitle.grid(row=row, column=0, columnspan=3, sticky="w", pady=(0, 15))
row += 1
row = self._create_section_header(scroll, "Folder Selection", ("#E65100", "#FF9800"), row)
ctk.CTkLabel(scroll, text="Modded Files Folder:", anchor="w", width=160).grid(
row=row, column=0, sticky="w", pady=3
)
self._mod_entry = ctk.CTkEntry(scroll, placeholder_text="Select folder with modded .json or .uasset files...")
self._mod_entry.grid(row=row, column=1, sticky="ew", padx=5, pady=3)
ctk.CTkButton(scroll, text="Browse...", width=90, command=self._browse_mod_folder).grid(
row=row, column=2, pady=3
)
row += 1
ctk.CTkLabel(scroll, text="Original Files Folder:", anchor="w", width=160).grid(
row=row, column=0, sticky="w", pady=3
)
self._orig_entry = ctk.CTkEntry(scroll, placeholder_text="Select folder with original game .json files...")
default_orig = get_jsondata_dir()
if default_orig.exists():
self._orig_entry.insert(0, str(default_orig))
self._orig_folder = str(default_orig)
self._orig_entry.grid(row=row, column=1, sticky="ew", padx=5, pady=3)
ctk.CTkButton(scroll, text="Browse...", width=90, command=self._browse_orig_folder).grid(
row=row, column=2, pady=3
)
row += 1
row = self._create_section_header(scroll, "DEF File Metadata", "#4CAF50", row)
for label_text, attr_name, default, placeholder in [
("Title:", "_title_entry", "My Mod", "Enter mod title..."),
("Author:", "_author_entry", "", "Enter author name..."),
("Description:", "_desc_entry", "", "Enter mod description..."),
]:
ctk.CTkLabel(scroll, text=label_text, anchor="w", width=160).grid(
row=row, column=0, sticky="w", pady=3
)
entry = ctk.CTkEntry(scroll, placeholder_text=placeholder)
if default:
entry.insert(0, default)
entry.grid(row=row, column=1, columnspan=2, sticky="ew", pady=3)
if attr_name == "_title_entry": self._title_entry = entry
elif attr_name == "_author_entry": self._author_entry = entry
elif attr_name == "_desc_entry": self._desc_entry = entry
row += 1
cb = ctk.CTkCheckBox(
scroll,
text="Include comments in generated .def files",
variable=self._include_comments,
)
cb.grid(row=row, column=0, columnspan=3, sticky="w", pady=(5, 10))
row += 1
btn_frame = ctk.CTkFrame(scroll, fg_color="transparent")
btn_frame.grid(row=row, column=0, columnspan=3, sticky="ew", pady=(5, 10))
row += 1
ctk.CTkButton(
btn_frame, text="Scan & Compare",
width=140, height=36,
fg_color=("#2E7D32", "#1B5E20"),
hover_color=("#1B5E20", "#0D3610"),
font=ctk.CTkFont(size=13, weight="bold"),
command=self._scan_and_compare,
).pack(side="left", padx=(0, 10))
ctk.CTkButton(
btn_frame, text="Save All .def Files",
width=140, height=36,
fg_color=("#1565C0", "#0D47A1"),
hover_color=("#0D47A1", "#082D69"),
font=ctk.CTkFont(size=13, weight="bold"),
command=self._save_all_files,
).pack(side="left", padx=(0, 10))
ctk.CTkButton(
btn_frame, text="Edit Existing .ini",
width=140, height=36,
fg_color=("#F57C00", "#E65100"), # Oranžová barva pro odlišení
hover_color=("#E65100", "#BF360C"),
font=ctk.CTkFont(size=13, weight="bold"),
command=self._edit_existing_ini,
).pack(side="left", padx=(0, 10))
# Uložíme si tlačítko do self.edit_def_btn, abychom ho mohli měnit
self.edit_def_btn = ctk.CTkButton(
btn_frame, text="Edit Existing .def",
width=140, height=36,
fg_color=("#8E24AA", "#6A1B9A"), # Původní fialová
hover_color=("#6A1B9A", "#4A148C"),
font=ctk.CTkFont(size=13, weight="bold"),
command=self._handle_edit_def_click, # Změníme na obslužnou funkci
)
self.edit_def_btn.pack(side="left", padx=(0, 10))
# Pomocná proměnná pro sledování cesty k externímu souboru
self._current_external_def_path = None
row = self._create_section_header(scroll, "Log", "#2196F3", row)
self._log_box = ctk.CTkTextbox(scroll, height=160, font=ctk.CTkFont(family="Consolas", size=14))
self._log_box.grid(row=row, column=0, columnspan=3, sticky="ew", pady=(0, 10))
self._log_box.configure(state="disabled")
row += 1
# --- SEKCE PRO DESCRIPTION EDITOR ---
row = self._create_section_header(scroll, "Step 2: Assign Descriptions", "#E91E63", row)
self._desc_editor_frame = ctk.CTkFrame(scroll, fg_color=("#dbdbdb", "#2b2b2b"))
self._desc_editor_frame.grid(row=row, column=0, columnspan=3, sticky="ew", pady=10, padx=5)
row += 1
edit_row = ctk.CTkFrame(self._desc_editor_frame, fg_color="transparent")
edit_row.pack(fill="x", padx=10, pady=10)
# Přidej parametr 'command', který zavolá naši novou funkci
self._prop_selector = ctk.CTkComboBox(
edit_row,
values=["(Scan first...)"],
width=200,
command=self._on_property_selected # <--- Tohle je klíčové
)
self._prop_selector.pack(side="left", padx=5)
self._desc_entry_field = ctk.CTkEntry(edit_row, placeholder_text="Type description here...", width=400)
self._desc_entry_field.pack(side="left", fill="x", expand=True, padx=5)
self._apply_btn = ctk.CTkButton(edit_row, text="Apply to All", width=100, fg_color="#1565C0", command=self._apply_description)
self._apply_btn.pack(side="left", padx=5)
# --- Section: Preview / Edit ---
row = self._create_section_header(scroll, "Preview / Edit", "#9C27B0", row)
preview_frame = ctk.CTkFrame(scroll, fg_color="transparent")
preview_frame.grid(row=row, column=0, columnspan=3, sticky="ew", pady=(0, 5))
preview_frame.grid_columnconfigure(0, weight=1)
row += 1
selector_row = ctk.CTkFrame(preview_frame, fg_color="transparent")
selector_row.pack(fill="x", pady=(0, 5))
ctk.CTkLabel(selector_row, text="File:", width=40).pack(side="left")
self._file_selector = ctk.CTkComboBox(
selector_row, values=["(no files generated yet)"],
command=self._on_file_selected, width=500,
)
self._file_selector.pack(side="left", fill="x", expand=True, padx=5)
self._file_count_label = ctk.CTkLabel(selector_row, text="0 files", text_color="gray")
self._file_count_label.pack(side="right", padx=5)
self._preview_box = ctk.CTkTextbox(
preview_frame, height=350,
font=ctk.CTkFont(family="Consolas", size=14),
)
self._preview_box.pack(fill="both", expand=True)
self._current_preview_file = None
def _create_section_header(self, parent, text, color, row):
header = ctk.CTkLabel(
parent, text=text,
font=ctk.CTkFont(size=15, weight="bold"),
text_color=color,
)
header.grid(row=row, column=0, columnspan=3, sticky="w", pady=(15, 2))
row += 1
sep = ctk.CTkFrame(parent, height=2, fg_color=color)
sep.grid(row=row, column=0, columnspan=3, sticky="ew", pady=(0, 8))
return row + 1
def _browse_mod_folder(self):
folder = ctk.filedialog.askdirectory(title="Select Modded Files Folder")
if folder:
folder = os.path.normpath(folder)
self._mod_folder = folder
self._mod_entry.delete(0, "end")
self._mod_entry.insert(0, folder)
def _browse_orig_folder(self):
folder = ctk.filedialog.askdirectory(title="Select Original Game Files Folder")
if folder:
folder = os.path.normpath(folder)
self._orig_folder = folder
self._orig_entry.delete(0, "end")
self._orig_entry.insert(0, folder)
# ------------------------------------------------------------------
# Logging
# ------------------------------------------------------------------
def _log(self, msg):
def _append():
self._log_box.configure(state="normal")
self._log_box.insert("end", msg + "\n")
self._log_box.see("end")
self._log_box.configure(state="disabled")
if threading.current_thread() is threading.main_thread():
_append()
else:
self.after(0, _append)
def _clear_log(self):
self._log_box.configure(state="normal")
self._log_box.delete("1.0", "end")
self._log_box.configure(state="disabled")
def _set_status(self, msg):
if self._on_status:
self._on_status(msg)