Repository navigation
Expand file tree
/
Copy patheditor.py
More file actions
7108 lines (6428 loc) · 316 KB
/
Copy patheditor.py
File metadata and controls
7108 lines (6428 loc) · 316 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
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2026 Nexxus Drako Multimedia
"""Mod editor for Let's Make a Soccer Team! (PS2): one window with a tab
per kind of data (stage 5 in GOALS.md).
Each tab edits through a writer in SRC/, using the same functions as that
writer's `set` command, and takes the fields' names and allowed values
from the writer (pbdata.edit_spec), so the editor keeps no layout of its
own. Fields with no name yet are shown read-only.
Edits are saved to a mod folder, each file under its path in DAT/, and
files from outside DATA.CVM under disc/:
mod/PARAM/PBDATA_EU.PAC an edited DAT/PARAM/PBDATA_EU.PAC
mod/disc/SLES_541.51 an edited ISO/SLES_541.51
mod/editor.log the command line equivalent of every save
mod/build.json the Build disc dialog's paths and options
The editor reads a file from the mod folder when it is there and from
DAT/ (or ISO/) otherwise, so edits build up over several sessions. Each
save is written next to its target as <name>.new and then replaces it, so
a failed save leaves the old file. The folder's layout matches
patch_disc.py's targets: PARAM/PBDATA_EU.PAC=mod/PARAM/PBDATA_EU.PAC and
disc:SLES_541.51=mod/disc/SLES_541.51.
File > Build disc (Ctrl+B) writes a modded disc image, an xdelta patch,
or both, optionally with patch_disc.py's switches: a button per edition,
a box per group that opens to its switches (patch_disc.EDITIONS, GROUPS;
DOC/LMASTER_MOD.md#the-switch-levels), named in the command at the
highest levels that fit (patch_disc.mod_names). `patch_disc.py patch ...
--copies` puts the mod folder on a copy of the original, and `vcdiff.py
make` compares the two. For a patch on its own that image is temporary
(<patch>.building.iso, removed after). It shows their output and logs
both commands. The original must be the Redump dump for a patch others
can apply.
Tabs:
People players, managers and scouts (pbdata.py; DOC/PBDATA_FORMAT.md).
A change to a player's rank, main position or nationality
that changes the ranking (entries 2 and 3) also writes
mod/disc/SLES_541.51, as `pbdata.py set --sles` does.
Clubs club records (PLRESOURCESIM.PAC entry 3) and the computer
teams' squads (OTEAMMEMBER.TBB), through initteam.py
(DOC/INITTEAM_FORMAT.md). Refuses a player already in another
squad, a shirt number twice in one squad, and a manager who
already has a club, which `initteam.py info` would flag.
New club the player's new club by league and team style
(TEAM_INIT_DATA.TBB, teaminit.py; DOC/TEAMINIT_FORMAT.md):
squad, rival-only records, staff, scouts, youth team,
candidate lists and the rival club, as pwkTeam_Init2 reads them.
Season the starting divisions by league, with last season's table,
swapping two league clubs' places (initteam.py swap;
DOC/INITTEAM_FORMAT.md#swapping-clubs), and each first
division's size, in the range leaguesize.py allows; a size
change also rewrites the three schedule packs and their .HED
and the leagues' club counts in REGULATION.TBB and
CLUBRESULT.TBB, which the Regulations tab then reads again,
and adds the club ranking's rows for a size it has none for
(CLUB_RANK_SYSTEM.TBB, which the Club ranking tab reads again)
(leaguesize.py build --over;
DOC/SCHEDULE_FORMAT.md#where-the-clubs-come-from).
National calendar
when the national squads are called up and released, and
which call-ups are for a finals tournament, in each year of
the 4-year cycle (SCHEDULE_LIST.TBB, natcal.py set;
DOC/PARAM_DIR.md#schedule_listtbb-the-national-team-calendar).
The national-match flag follows the national cups' schedule
and is shown only; a calendar natcal.check refuses can't be
saved. --copies carries it into PRELOAD/SIMLOCALMEM0-6.PAC.
Free agents
the players without a club at the start of a career
(PLRESOURCESIM.PAC entry 15, plrsim.py setfree;
DOC/PLRESOURCESIM_FORMAT.md). Refuses a player already in the
list or in a club's squad. Shares the pack with the Clubs tab:
each saves its edits onto the file as it is then.
Player links
the clubs each player is affiliated with, each scout's
exclusive and semi-exclusive players, and the good and bad
combinations of players and managers (PLRESOURCESIM.PAC
entries 5 and 11-14, plrsim.py setgroup;
DOC/PLRESOURCESIM_FORMAT.md#writing-the-streams). Each list
keeps its entry's size; an edit that no longer fits is
refused. Shares the pack with the Clubs and Free agents tabs.
Nations & stadiums
each nation's UEFA rank and points (nations 1-52) and world
rating (INITNATIDATA.TBB, initteam.py setnation), and each
stadium's roof, level and capacity, with the clubs that use
it (STADIUM_DATA.TBB, initteam.py setstadium;
DOC/INITTEAM_FORMAT.md). The Clubs, New club and Stadiums
tabs read the stadiums again after a save.
Stadiums each of the 119 grounds' look and advert boards
(STADIUM/BUILD_STADIUM.TBB, stadium.py setlook and setboards;
DOC/STADIUM_DIR.md#editing): built like another stadium (its
model, parts and crowd set; the boards stay its own) and its
12 boards, values 1-205. Shows the model, the roof, level and
capacity (edited in Nations & stadiums), the clubs whose
record names it and the rival's ground.
Overseas bases
what a club base costs to set up in each of the 13 overseas
regions (PLRESOURCESIM.PAC entry 1, plrsim.py setbranch;
DOC/PLRESOURCESIM_FORMAT.md#entry-1-overseas-branches), named
from MES.PAC, with the investment steps and upkeep that
follow from it. Shares the pack with the Clubs, Free agents
and Player links tabs.
Regulations
each schedule's match rules, win bonus, prizes and places
(REGULATION.TBB, regulation.py set; DOC/REGULATION_FORMAT.md),
named from the schedule packs, and how each reports a final
place: league, cup or not ranked, and the third-place match
(CLUBRESULT.TBB, clubresult.py set;
DOC/CLUBRESULT_FORMAT.md), with the names a cup's places
get. The club counts are shown, not edited (they must match
the schedule; the Season tab sets them), and the squad's
copy follows the squad. Money shows in pounds.
Club ranking
the club ranking's tables (CLUB_RANK_SYSTEM.TBB, clubrank.py
set; DOC/PARAM_DIR.md#club_rank_systemtbb-the-club-rankings-tables):
the points each competition gives for each final place, the
world rank points by club rank for clubs outside nations
1-52, and the club rank each position in a nation or division
gets, with the positions each rank reaches. The nation groups
and the year-end leagues are not edited.
Training the training tables (TRAINING_LIST.TBB, training.py set;
DOC/TRAINING_FORMAT.md): pick a table, then a row (a practice,
camp type, pitch position, equipment item or growth type), and
edit its value for each ability, its fatigue or each age.
Columns the game doesn't read are shown, not edited.
Camps the training camps (CAMP_LIST.TBB, camp.py set;
DOC/CAMP_FORMAT.md): each camp's town, description and the
clubs of its area, and its camp type, the one field edited,
with what that type trains (from the Training tab, as the
retail game reads it and with the LMASTER camp-types fix).
Tours the clubs a tour can play, by region (TOUR_LIST.TBB, tour.py
set; DOC/PARAM_DIR.md#tour_listtbb-tour-opponents-by-region):
each pair's club and region, at most 40 clubs a region.
Facilities the facility records (PLRESOURCECOMMON.PAC entry 0,
plrcommon.py set; DOC/PLRESOURCECOMMON_FORMAT.md): pick a
table (sites, equipment, club houses, stadiums, adverts), then
a record, and edit its build costs, upkeep, build times and
stadium capacities. Money shows in pounds.
PR events
the Publicity Department's 46 events, kept in the executable
(clubevent.py set; DOC/CLUBEVENT_FORMAT.md): when each is
offered, its cost, its chance of success in each business
cycle and what success brings, named from MES.PAC. Writes
mod/disc/SLES_541.51, which the People and Kits tabs also
write: a save reads it again first.
Tactics the tactics screen's eight Set Formation presets
(TACTICS_FORMATION_SET.TBB, formset.py set;
DOC/PARAM_DIR.md#tactics_formation_settbb-tactics-presets):
seven team tactics and a formation each. Build disc's
--copies carries them into the PRELOAD/TACTICS* packs.
Kits every club's home and away kits (UNIFORM_LIST.TBB) and the
keeper kits made from the outfield kit for your club, the rival
and the VS teams (UNIFORM_GK.TBB), through uniform.py
(DOC/UNIFORM_FORMAT.md). Colours show as swatches. A licensed
club's descriptors (numbers, name, collar, captain mark) are
written to both copies, the executable's (mod/disc/SLES_541.51,
which the game draws from) and PLPACK_HOME/AWAY.PAC, as
`uniform.py setexe` and `setlicence` do.
Crests the club editor's crest and flag tables (EDIT_EMBLEM.TBB,
EDIT_FLAG.TBB, emblem.py set; DOC/EMBLEM_DIR.md#editing):
the starting, rival and sample crests field by field (parts,
mask, layer keys, colours as swatches, -1/-2/-3 the club's
own), the starting crests' samples and first colours, the
base, pattern and accessory presets, the layer accessories
and the flag patterns and crest placements.
Player editor the tables the player editor makes a new player
from (EDIT_PLAYER.TBB, emblem.py set;
DOC/EMBLEM_DIR.md#edit_playertbb), one row at a time: base
abilities by position and nation, personality and growth
ranges, the editor choices' overrides.
Text message text in MES.PAC, one message in all 7 language slots,
found by category, text or id (mbb.py; DOC/MBB_FORMAT.md). A
file that outgrows its slot makes MES.PAC grow and moves the
later files; Build disc then also updates the executable's
index of them.
Comments the detail screens' comment lines for players, managers,
coaches and scouts: the data tables of the PSCCOMMON.PAC
scripts the game runs (sqb.py settable;
DOC/SQB_FORMAT.md#the-detail-screen-comments), with each
message number's text. --copies carries the pack into
PRELOAD/STATIONFILE.PAC.
Log the commands the saves stood for, as written to editor.log.
Usage:
python SRC/editor.py open [<mod folder>] [--dat DAT] [--iso ISO] # default: mod
"""
import contextlib
import datetime
import io
import os
import struct
import subprocess
import sys
import threading
import tkinter as tk
from tkinter import font as tkfont, messagebox, ttk
import initteam
import leaguesize
import mbb
import natcal
import pac
import patch_disc
import pbdata
import plrcommon
import plrsim
import camp
import clubevent
import clubrank
import clubresult
import emblem
import formset
import regulation
import sqb
import stadium
import tour
import training
import teaminit
import uniform
SLES = "SLES_541.51"
MOD_OWN_FILES = ("editor.log", "build.json") # the editor's files, not the game's
WINDOW = (1280, 720)
LIST_MIN = 360 # the narrowest the list gets when a page needs room
BARS_PER_LINE = 8
# --- the mod folder ----------------------------------------------------------
def shown_path(path):
"""A path as the log gives it: relative to the current folder when it is
inside it, with forward slashes."""
rel = os.path.relpath(path)
return (path if rel.startswith("..") else rel).replace("\\", "/")
class Mod:
def __init__(self, root, dat="DAT", iso="ISO"):
self.root, self.dat, self.iso = root, dat, iso
def source(self, rel):
"""The file to read for DAT/<rel>: the mod's copy if there is one."""
mine = os.path.join(self.root, rel)
return mine if os.path.exists(mine) else os.path.join(self.dat, rel)
def target(self, rel):
return os.path.join(self.root, rel)
def disc_source(self, name):
mine = os.path.join(self.root, "disc", name)
return mine if os.path.exists(mine) else os.path.join(self.iso, name)
def disc_target(self, name):
return os.path.join(self.root, "disc", name)
def log(self, lines):
os.makedirs(self.root, exist_ok=True)
with open(os.path.join(self.root, "editor.log"), "a", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n\n")
def targets(self):
"""[(patch_disc.py target, file)] for every edited file in the
folder: <path under DAT>=file, and disc:<name>=file for disc/."""
out = []
for folder, dirs, files in os.walk(self.root):
# A <name>.new folder is a save in progress, like a .new file.
dirs[:] = sorted(d for d in dirs if not d.endswith(".new"))
rel_dir = os.path.relpath(folder, self.root).replace("\\", "/")
for name in sorted(files):
if (rel_dir == "." and name in MOD_OWN_FILES) or name.endswith(".new"):
continue
rel = name if rel_dir == "." else rel_dir + "/" + name
path = os.path.join(folder, name)
if rel.startswith("disc/"):
out.append(("disc:" + rel[len("disc/"):], path))
else:
out.append((rel, path))
return out
def quote(arg):
return subprocess.list2cmdline([arg])
# --- widgets -----------------------------------------------------------------
class Scrolled:
"""A frame inside a canvas with scroll bars. The frame fills the canvas's
width, or keeps its own when it is wider; then the horizontal bar
scrolls it (or Shift and the mouse wheel)."""
def __init__(self, parent):
self.outer = ttk.Frame(parent)
self.canvas = tk.Canvas(self.outer, highlightthickness=0)
vbar = ttk.Scrollbar(self.outer, orient="vertical", command=self.canvas.yview)
hbar = ttk.Scrollbar(self.outer, orient="horizontal", command=self.canvas.xview)
self.canvas.configure(yscrollcommand=vbar.set, xscrollcommand=hbar.set)
self.outer.rowconfigure(0, weight=1)
self.outer.columnconfigure(0, weight=1)
self.canvas.grid(row=0, column=0, sticky="nsew")
vbar.grid(row=0, column=1, sticky="ns")
hbar.grid(row=1, column=0, sticky="ew")
self.inner = ttk.Frame(self.canvas)
self.window = self.canvas.create_window(0, 0, window=self.inner, anchor="nw")
self.inner.bind("<Configure>", lambda e: self._fit())
self.canvas.bind("<Configure>", lambda e: self._fit())
self.canvas.bind("<Enter>", lambda e: self._bind_wheel(True))
self.canvas.bind("<Leave>", lambda e: self._bind_wheel(False))
def _fit(self):
width = max(self.canvas.winfo_width(), self.inner.winfo_reqwidth())
self.canvas.itemconfigure(self.window, width=width)
self.canvas.configure(scrollregion=(0, 0, width, self.inner.winfo_reqheight()))
def _bind_wheel(self, on):
for seq, fn in (("<MouseWheel>", self._wheel), ("<Shift-MouseWheel>", self._hwheel)):
if on:
self.canvas.bind_all(seq, fn)
else:
self.canvas.unbind_all(seq)
def _wheel(self, event):
self.canvas.yview_scroll(-event.delta // 120, "units")
def _hwheel(self, event):
self.canvas.xview_scroll(-event.delta // 120, "units")
def clear(self):
for w in self.inner.winfo_children():
w.destroy()
self.canvas.xview_moveto(0)
self.canvas.yview_moveto(0)
def value_input(parent, spec, label, get, apply):
"""A drop-down for ("choice", [values]) or a spin box for ("range",
low, high[, step]). label(v) is a value's text, get() the current value, and
apply(text, revert) is called with the new value's text when it
changes; it calls revert() to put the old value back."""
var = tk.StringVar()
values = [label(v) for v in spec[1]] if spec[0] == "choice" else None
def commit(event=None):
if values is not None and var.get() in values:
# A drop-down entry stands for its value, whatever its label
# looks like ("A4 red 4" is colour 3).
text = str(spec[1][values.index(var.get())])
else:
text = var.get().split()[0] if var.get().strip() else ""
if text != str(get()):
apply(text, lambda: var.set(label(get())))
if spec[0] == "choice":
width = max(4, min(30, max(len(v) for v in values) + 1))
w = ttk.Combobox(parent, textvariable=var, values=values, state="readonly",
width=width, height=20)
w.bind("<<ComboboxSelected>>", commit)
else:
lo, hi = spec[1], spec[2]
step = spec[3] if len(spec) > 3 else 1
w = ttk.Spinbox(parent, textvariable=var, from_=lo, to=hi, increment=step,
width=max(4, len(str(hi)) + 2), command=commit)
w.bind("<Return>", commit)
w.bind("<FocusOut>", commit)
var.set(label(get()))
return w
def replace_new(temps):
"""Move each written <file>.new over its target."""
for tmp, final in temps:
os.replace(tmp, final)
def remove_new(temps):
"""Remove the .new files of a save that failed."""
for tmp, _ in temps:
if os.path.exists(tmp):
os.remove(tmp)
def log_lines(title, commands, temps, report="", moved="each .new file"):
"""The editor.log entry for one save."""
lines = ["# %s %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), title)]
lines += [" ".join(c) for c in commands]
lines.append("# then %s replaces %s" % (moved, ", ".join(shown_path(f) for _, f in temps)))
lines += ["# " + line for line in report.splitlines()]
return lines
# --- tabs --------------------------------------------------------------------
class Tab:
"""One kind of data. A tab loads its files from the mod folder (or
DAT/), keeps its edits in memory and writes them on save."""
title = ""
def __init__(self, app):
self.app = app
self.frame = ttk.Frame(app.notebook)
def load(self):
pass
def dirty(self):
return False
def save(self):
pass
def changed(self, what):
"""Another tab saved or loaded something this one shows: "squads"
(OTEAMMEMBER.TBB), "people" (the People tab's records) or
"schedules" (the Season tab's size change, which also writes
REGULATION.TBB, CLUBRESULT.TBB and, for a size the club ranking
has no row for, CLUB_RANK_SYSTEM.TBB) or "stadiums"
(STADIUM_DATA.TBB, from the Nations & stadiums tab)."""
pass
PBDATA = "PARAM/PBDATA_EU.PAC"
OTEAM = "PARAM/OTEAMMEMBER.TBB"
MES = "MESSAGE/MES.PAC"
COMMON = "PARAM/PLRESOURCECOMMON.PAC"
KIND_TITLES = ("Players", "Managers", "Scouts")
LIST_LIMIT = 500
# How the People tab lays out each kind's fields. Fields not listed here
# go under "Other", so a newly named field in pbdata.py still shows.
GROUPS = {
"players": (
("Basics", ("name", "nation", "age", "height", "weight", "leg", "shirt", "face",
"rank", "position", "req_status")),
("Personality and condition", (
"tone", "dissatis", "professionalism", "pressure", "loyalty", "star",
"moti_type", "cond_type", "potential", "growth", "travel", "injury_res",
"recovery", "foul_avoid", "weak_foot", "policy", "adapt", "intelligence",
"ball_touch", "dribble_style", "explodetype")),
("Play", ("style", "skills", "tendency", "flags")),
("Kit style", ("sleeves", "wristband", "gloves", "gk_cap", "gk_gloves", "gk_pants",
"boots")),
("Abilities", ("ability",)),
),
"managers": (
("Basics", ("name", "nation", "age", "rank", "job", "face", "req_status",
"appeartype", "real_name", "model_pattern")),
("Policies", ("comptype", "moti_type", "select_policy", "match_policy", "training_policy",
"rest_policy", "policy", "policy_range", "policy_best")),
("Tactics", ("formation", "attacking", "possession", "centre_side", "left_right",
"press_line", "press", "offside", "attack_pattern")),
("Drills (training menu items)", ("manager_drill", "coach_drill")),
("Abilities", ("ability",)),
),
"scouts": (
("Basics", ("name", "nation", "age", "rank", "face", "req_status", "appeartype",
"real_name")),
("Special searches", ("search",)),
("Abilities", ("ability",)),
),
}
LABELS = {
"req_status": "required status", "dissatis": "dissatisfaction", "star": "star quality",
"moti_type": "motivation type", "cond_type": "condition type",
"injury_res": "injury resistance", "foul_avoid": "foul avoidance",
"adapt": "adaptability", "gk_gloves": "GK gloves", "gk_pants": "GK pants",
"style": "play styles", "position": "positions", "real_name": "real name",
}
POSITION_ITEMS = ("main", "2nd", "3rd")
def bar_lines(title, bars):
"""Detail-screen bars, BARS_PER_LINE to a line, under a 13-column title."""
cells = ["%-5s %2d" % b for b in bars]
return ["%-13s%s" % (title if i == 0 else "", " ".join(cells[i:i + BARS_PER_LINE]))
for i in range(0, len(cells), BARS_PER_LINE)]
class PeopleTab(Tab):
title = "People"
def __init__(self, app):
super().__init__(app)
self.db = None
self.records = None
self.changes = {} # (kind, index, "field[.i]") -> text, in edit order
self.current = None # the Record on the right
self.widgets = []
bar = ttk.Frame(self.frame)
bar.pack(fill="x", padx=6, pady=6)
ttk.Label(bar, text="Show").pack(side="left")
self.kind_var = tk.StringVar(value=KIND_TITLES[0])
kind = ttk.Combobox(bar, textvariable=self.kind_var, values=KIND_TITLES,
state="readonly", width=10)
kind.pack(side="left", padx=(4, 12))
kind.bind("<<ComboboxSelected>>", lambda e: self.kind_changed())
ttk.Label(bar, text="Name or id").pack(side="left")
self.find_var = tk.StringVar()
find = ttk.Entry(bar, textvariable=self.find_var, width=22)
find.pack(side="left", padx=(4, 12))
find.bind("<Return>", lambda e: self.refresh_list())
ttk.Label(bar, text="Nationality").pack(side="left")
self.nation_var = tk.StringVar(value="any")
self.nation_box = ttk.Combobox(bar, textvariable=self.nation_var, state="readonly",
width=20)
self.nation_box.pack(side="left", padx=(4, 12))
self.nation_box.bind("<<ComboboxSelected>>", lambda e: self.refresh_list())
self.club_label = ttk.Label(bar, text="Club")
self.club_label.pack(side="left")
self.club_var = tk.StringVar(value="any")
self.club_box = ttk.Combobox(bar, textvariable=self.club_var, state="readonly",
width=24)
self.club_box.pack(side="left", padx=(4, 12))
self.club_box.bind("<<ComboboxSelected>>", lambda e: self.refresh_list())
ttk.Button(bar, text="Search", command=self.refresh_list).pack(side="left")
self.count_label = ttk.Label(bar, text="")
self.count_label.pack(side="left", padx=12)
panes = self.panes = ttk.PanedWindow(self.frame, orient="horizontal")
panes.pack(fill="both", expand=True, padx=6, pady=(0, 6))
left = ttk.Frame(panes)
cols = ("id", "name", "nation", "age", "what", "club")
self.tree = ttk.Treeview(left, columns=cols, show="headings", selectmode="browse")
for c, text, width in zip(cols, ("Id", "Name", "Nationality", "Age", "Position", "Club"),
(60, 150, 110, 40, 90, 140)):
self.tree.heading(c, text=text)
self.tree.column(c, width=width, stretch=c in ("name", "club"))
self.tree.tag_configure("edited", foreground="#b03000")
sb = ttk.Scrollbar(left, orient="vertical", command=self.tree.yview)
self.tree.configure(yscrollcommand=sb.set)
sb.pack(side="right", fill="y")
self.tree.pack(side="left", fill="both", expand=True)
self.tree.bind("<<TreeviewSelect>>", lambda e: self.select())
panes.add(left, weight=2)
self.detail = Scrolled(panes)
panes.add(self.detail.outer, weight=3)
# loading
def load(self, done=None):
"""Read the database and the names in a thread; the window stays
responsive while it takes a few seconds."""
self.app.status("Loading the player database...")
self.records = None
self.tree.delete(*self.tree.get_children())
self.frame.configure(cursor="watch")
result = {}
def work():
try:
mod = self.app.mod
path = mod.source(PBDATA)
db = pbdata.PbData(path)
if not db.data:
raise ValueError("%s has no records" % path)
result["records"] = {k: list(db.records(k)) for k in pbdata.KINDS}
mes = mod.source(MES)
# nation_names reads PLRESOURCECOMMON.PAC next to the path it
# is given, so give it that pack's own path (the mod's copy of
# PBDATA_EU.PAC may be on its own).
result["nations"] = pbdata.nation_names(mod.source(COMMON), mes)
teams = initteam.team_names(mes, 1)
squads = initteam.OteamMembers(mod.source(OTEAM)).squads
result["club_of"] = {m.player: (team, m) for team, s in squads.items() for m in s}
result["teams"] = teams
result["db"], result["path"] = db, path
except Exception as e: # shown in the window, not lost in a thread
result["error"] = e
thread = threading.Thread(target=work, daemon=True)
thread.start()
def poll():
if thread.is_alive():
self.frame.after(100, poll)
return
self.frame.configure(cursor="")
if "error" in result:
self.app.status("Couldn't load the player database: %s" % result["error"])
messagebox.showerror("People", "Couldn't load the player database:\n%s"
% result["error"])
return
self.loaded(result)
if done:
self.app.status(done)
poll()
def loaded(self, result):
self.db, self.path = result["db"], result["path"]
self.records, self.nations = result["records"], result["nations"]
self.club_of, self.teams = result["club_of"], result["teams"]
self.changes = {}
self.nation_box["values"] = ["any"] + [pbdata.value_label("players", "nation", n, self.nations)
for n in range(1, pbdata.NATION_COUNT + 1)]
clubs = sorted({team for team, _ in self.club_of.values()})
self.club_box["values"] = ["any"] + [self.team_label(t) for t in clubs]
self.refresh_list()
self.app.status("%s: %d players, %d managers, %d scouts" % (
shown_path(self.path), *(len(self.records[k]) for k in pbdata.KINDS)))
self.app.update_title()
self.app.notify(self, "people")
def changed(self, what):
"""The Clubs tab saved the squads: refresh which club each player
is in, for the list, the club filter and the notes."""
if what != "squads" or self.records is None:
return
squads = initteam.OteamMembers(self.app.mod.source(OTEAM)).squads
self.club_of = {m.player: (team, m) for team, s in squads.items() for m in s}
self.refresh_list()
if self.current is not None:
self.show(self.current)
def team_label(self, team):
return "%d %s" % (team, self.teams.get(team, ""))
# the list
@property
def kind(self):
return pbdata.KINDS[KIND_TITLES.index(self.kind_var.get())]
def kind_changed(self):
players = self.kind == "players"
self.club_box.configure(state="readonly" if players else "disabled")
if not players:
self.club_var.set("any")
self.tree.heading("what", text="Position" if players else
("Job" if self.kind == "managers" else "Status"))
self.refresh_list()
def matches(self, r, find, nation, club):
if find:
if find.isdigit():
if str(r.db_id) != find and str(r.index) != find:
return False
elif find.lower() not in r.name.lower():
return False
if nation is not None and r.fields["nation"] != nation:
return False
if club is not None and self.club_of.get(r.index, (None,))[0] != club:
return False
return True
def refresh_list(self):
if self.records is None:
return
find = self.find_var.get().strip()
nation = None if self.nation_var.get() == "any" else int(self.nation_var.get().split()[0])
club = None if self.club_var.get() == "any" else int(self.club_var.get().split()[0])
found = [r for r in self.records[self.kind] if self.matches(r, find, nation, club)]
self.tree.delete(*self.tree.get_children())
for r in found[:LIST_LIMIT]:
self.tree.insert("", "end", iid=str(r.db_id), values=self.row(r),
tags=("edited",) if self.edited(r) else ())
self.count_label.configure(text="%d found%s" % (
len(found), ", showing the first %d" % LIST_LIMIT if len(found) > LIST_LIMIT else ""))
def row(self, r):
f = r.fields
nation = self.nations.get(f["nation"], str(f["nation"]))
if r.kind == "players":
what = "/".join(pbdata.position_name(p) for p in f["position"] if p != 13)
club = self.club_of.get(r.index)
club = self.teams.get(club[0], str(club[0])) if club else ""
elif r.kind == "managers":
what, club = pbdata.listed(pbdata.JOB_NAMES, f["job"]), ""
else:
what, club = str(f["req_status"]), ""
return (r.db_id, r.name, nation, f["age"], what, club)
def edited(self, r):
return r.encode() != r.raw
# the detail panel
def select(self):
sel = self.tree.selection()
if not sel:
return
kind, index = pbdata.parse_id(sel[0])
self.show(self.records[kind][index])
def show(self, r):
self.current = r
self.detail.clear()
box = self.detail.inner
ttk.Label(box, text="%d %s" % (r.db_id, r.name), font=self.app.title_font
).pack(anchor="w", padx=8, pady=(8, 2))
for note in self.notes(r):
ttk.Label(box, text=note, foreground="#555", wraplength=560, justify="left"
).pack(anchor="w", padx=8)
listed = set()
groups = list(GROUPS[r.kind])
for _, names in groups:
listed.update(names)
other = tuple(f[0] for f in pbdata.FIELDS[r.kind] if f[0] not in listed)
if other:
groups.append(("Other (fields with no name yet are read-only)", other))
for title, names in groups:
frame = ttk.LabelFrame(box, text=title)
frame.pack(fill="x", padx=8, pady=6)
if names == ("ability",):
self.ability_grid(frame, r)
else:
for row, fname in enumerate(names):
self.field_row(frame, r, fname, row)
self.derived = ttk.Label(box, text="", justify="left", font="TkFixedFont")
self.derived.pack(anchor="w", padx=8, pady=(4, 12))
self.update_derived()
self.fit_detail()
def fit_detail(self):
"""Move the divider left when the page is wider than its pane, down
to LIST_MIN for the list. Dragging it back is up to the user."""
self.frame.update_idletasks()
need = self.detail.inner.winfo_reqwidth() + 24 # and the scroll bar
have = self.detail.outer.winfo_width()
if need > have > 1:
pos = self.panes.sashpos(0)
self.panes.sashpos(0, max(LIST_MIN, pos - (need - have)))
def notes(self, r):
out = []
if r.kind == "players":
club = self.club_of.get(r.index)
if club:
team, m = club
out.append("In %s's squad (OTEAMMEMBER.TBB): the game shows the age %d and "
"shirt %d from there, not the age and shirt below "
"(DOC/INITTEAM_FORMAT.md)." % (self.team_label(team), m.age, m.shirt))
if r.index < pbdata.RANKED:
out.append("Rank, main position and nationality decide this player's place in "
"the ranking. Saving a change to them re-sorts it and writes "
"disc/SLES_541.51 too (DOC/PBDATA_FORMAT.md#entries-2-and-3).")
return out
def field_row(self, frame, r, fname, row):
text = LABELS.get(fname, fname.replace("_", " "))
ttk.Label(frame, text=text).grid(row=row, column=0, sticky="nw", padx=(6, 12), pady=2)
cell = ttk.Frame(frame)
cell.grid(row=row, column=1, sticky="w", pady=2)
if fname == "name":
self.name_entry(cell, r)
return
_, _, _, count, _ = pbdata.field_spec(r.kind, fname)
if count == 1:
self.value_widget(cell, r, fname, None).pack(side="left")
return
for i in range(count):
label = POSITION_ITEMS[i] if fname == "position" else pbdata.item_label(r.kind, fname, i)
item = ttk.Frame(cell)
item.grid(row=i // 4 if count > 5 else 0, column=i % 4 if count > 5 else i,
sticky="w", padx=(0, 10))
ttk.Label(item, text=label, foreground="#555").pack(side="left", padx=(0, 4))
self.value_widget(item, r, fname, i).pack(side="left")
def ability_grid(self, frame, r):
values = r.fields["ability"]
cols = 4
for i in range(len(values)):
item = ttk.Frame(frame)
item.grid(row=i // cols, column=i % cols, sticky="e", padx=(6, 10), pady=1)
ttk.Label(item, text="%d %s" % (i, pbdata.item_label(r.kind, "ability", i))
).pack(side="left", padx=(0, 4))
self.value_widget(item, r, "ability", i).pack(side="left")
def name_entry(self, cell, r):
var = tk.StringVar(value=r.name)
entry = ttk.Entry(cell, textvariable=var, width=22)
entry.pack(side="left")
ttk.Label(cell, text="up to %d characters" % (pbdata.NAME_LEN - 1),
foreground="#555").pack(side="left", padx=6)
def commit(event=None):
if var.get() != r.name:
self.commit(r, "name", None, var.get(), lambda: var.set(r.name))
entry.bind("<Return>", commit)
entry.bind("<FocusOut>", commit)
def value_widget(self, parent, r, fname, index):
"""The widget for one value: a drop-down for listed values, a spin
box for a range, check boxes for a bit mask, a label if read-only."""
spec = pbdata.edit_spec(r.kind, fname)
def get():
return r.fields[fname] if index is None else r.fields[fname][index]
if spec is None:
return ttk.Label(parent, text=str(get()), foreground="#777")
if spec[0] == "bits":
return self.bit_boxes(parent, r, fname)
return value_input(parent, spec,
lambda v: pbdata.value_label(r.kind, fname, v, self.nations), get,
lambda text, revert: self.commit(r, fname, index, text, revert))
def bit_boxes(self, parent, r, fname):
frame = ttk.Frame(parent)
bits = []
def revert():
for b, v in enumerate(bits):
v.set(r.fields[fname] >> b & 1)
def commit():
mask = sum(1 << b for b, v in enumerate(bits) if v.get())
self.commit(r, fname, None, str(mask), revert)
for b, name in enumerate(pbdata.SKILLS):
v = tk.IntVar(value=r.fields[fname] >> b & 1)
bits.append(v)
ttk.Checkbutton(frame, text=name, variable=v, command=commit).grid(
row=b // 4, column=b % 4, sticky="w", padx=(0, 10))
return frame
def commit(self, r, fname, index, text, revert):
"""Apply one edit with pbdata.apply_value, as `pbdata.py set` does.
A refused value is put back with revert() before the error shows, so
the dialog taking the focus can't commit it again."""
if fname != "name":
try:
text = str(int(text)) # "08" -> "8"; apply_value reads base 0
except ValueError:
pass
try:
old, new = pbdata.apply_value(r, fname, index, text)
except ValueError as e:
revert()
self.app.status("%d %s: %s" % (r.db_id, r.name, e))
messagebox.showerror("People", "%d %s: %s" % (r.db_id, r.name, e))
return False
key = fname if index is None else "%s.%d" % (fname, index)
self.changes.pop((r.kind, r.index, key), None) # keep edit order
self.changes[r.kind, r.index, key] = text
self.app.status("%d %s: %s %s -> %s" % (r.db_id, r.name, key, old, new))
iid = str(r.db_id)
if self.tree.exists(iid):
self.tree.item(iid, values=self.row(r), tags=("edited",) if self.edited(r) else ())
if fname == "name":
self.show(r)
else:
self.update_derived()
self.app.update_title()
return True
def update_derived(self):
r = self.current
if r is None:
return
ab = r.fields["ability"]
if r.kind == "players":
gk = r.fields["position"][0] == 0
lines = bar_lines("Screen bars", pbdata.bars(ab, gk))
lines += ["Positions " + pbdata.aptitude_grid(
pbdata.aptitude(ab, r.fields["position"])[1]),
" (levels 0-4, forwards first, left centre right)"]
elif r.kind == "managers":
role = pbdata.JOB_ROLE.get(r.fields["job"], "manager")
lines = ["Screen bars as %s" % role] + bar_lines(
"", pbdata.staff_bars(ab, role))
else:
lines = bar_lines("Screen bars", pbdata.average_bars(ab, pbdata.SCOUT_BARS))
self.derived.configure(text="\n".join(lines))
# saving
def dirty(self):
return bool(self.changes)
def save(self):
"""Write the edited pack to the mod folder, and the executable too
when the ranking changes. Returns False if nothing was written."""
if not self.changes:
return True
mod = self.app.mod
players = self.records["players"]
out = mod.target(PBDATA)
# The ranking changes when a rank, main position or nationality edit
# moves a player or changes a group's size; either way the pack's
# entries 2 and 3 and the executable's group table must follow.
sles = None
sles_in = mod.disc_source(SLES)
try:
entry2, _, table = pbdata.build_ranking(players, self.db.entry2)
if entry2 != self.db.entry2 or table != pbdata.sles_group_table(sles_in)[1]:
sles = (sles_in, mod.disc_target(SLES))
except (ValueError, OSError) as e:
messagebox.showerror("People", "Can't save: %s" % e)
return False
os.makedirs(os.path.dirname(out), exist_ok=True)
if sles:
os.makedirs(os.path.dirname(sles[1]), exist_ok=True)
temps = [(out + ".new", out)] + ([(sles[1] + ".new", sles[1])] if sles else [])
report = io.StringIO()
try:
with contextlib.redirect_stdout(report):
pbdata.write_pack(temps[0][0], self.db, self.records,
(sles[0], temps[1][0]) if sles else None)
except (SystemExit, ValueError, OSError) as e:
remove_new(temps)
messagebox.showerror("People", "Can't save: %s" % e)
return False
replace_new(temps)
args = []
last = None
for (kind, index, key), text in self.changes.items():
r = self.records[kind][index]
if (kind, index) != last:
args.append(str(r.db_id))
last = (kind, index)
args.append(quote("%s=%s" % (key, text)))
records = len({(k, i) for k, i, _ in self.changes})
cmd = ["python", "SRC/pbdata.py", "set", quote(shown_path(self.path)),
quote(shown_path(temps[0][0]))] + args
if sles:
cmd += ["--sles", quote(shown_path(sles[0])), quote(shown_path(temps[1][0]))]
lines = log_lines("People: %d changes in %d records" % (len(self.changes), records),
[cmd], temps, report.getvalue())
mod.log(lines)
self.app.write_log(lines)
done = "Saved %s%s: %d changes in %d records" % (
shown_path(out), " and " + shown_path(sles[1]) if sles else "",
len(self.changes), records)
# Read the saved pack back: its entries 2 and 3 are the base for the
# next save, and a bad write shows here rather than in the game.
self.changes = {}
self.current = None
self.detail.clear()
self.load(done)
return True
SIMPAC = "PARAM/PLRESOURCESIM.PAC"
STADIUMS = "PARAM/STADIUM_DATA.TBB"
TEAM_LABELS = {
"world_rank": "world rank points", "foreign": "foreign players (policy row)",
"newface": "new faces (policy)", "search_region": "search region (policy row)",
"money": "transfer money factor", "list_state": "listed under state",
"list_city": "listed under city",
}
SQUAD_FIELDS = ("player", "age", "shirt", "contract")
class ClubsTab(Tab):
"""Club records (PLRESOURCESIM.PAC entry 3) and computer-team squads
(OTEAMMEMBER.TBB), through initteam.py's set_team_field and set_member,
as `initteam.py setteam` and `set` do."""
title = "Clubs"
def __init__(self, app):
super().__init__(app)
self.ot = self.db = None
self.squad_changes = {} # (team, slot, field) -> value, in edit order
self.team_changes = {} # (team, field) -> value
self.current = None # the team on the right
bar = ttk.Frame(self.frame)
bar.pack(fill="x", padx=6, pady=6)
ttk.Label(bar, text="Name or id").pack(side="left")
self.find_var = tk.StringVar()
find = ttk.Entry(bar, textvariable=self.find_var, width=22)
find.pack(side="left", padx=(4, 12))
find.bind("<Return>", lambda e: self.refresh_list())
ttk.Button(bar, text="Search", command=self.refresh_list).pack(side="left")
self.count_label = ttk.Label(bar, text="")
self.count_label.pack(side="left", padx=12)
panes = self.panes = ttk.PanedWindow(self.frame, orient="horizontal")
panes.pack(fill="both", expand=True, padx=6, pady=(0, 6))
left = ttk.Frame(panes)
cols = ("id", "name", "rank", "world", "squad")
self.tree = ttk.Treeview(left, columns=cols, show="headings", selectmode="browse")
for c, text, width in zip(cols, ("Id", "Club", "Rank", "World pts", "Squad"),
(50, 170, 50, 70, 50)):
self.tree.heading(c, text=text)
self.tree.column(c, width=width, stretch=c == "name")
self.tree.tag_configure("edited", foreground="#b03000")
sb = ttk.Scrollbar(left, orient="vertical", command=self.tree.yview)
self.tree.configure(yscrollcommand=sb.set)
sb.pack(side="right", fill="y")
self.tree.pack(side="left", fill="both", expand=True)
self.tree.bind("<<TreeviewSelect>>", lambda e: self.select())
panes.add(left, weight=1)
self.detail = Scrolled(panes)
panes.add(self.detail.outer, weight=3)
# loading
def load(self, done=None):
mod = self.app.mod
try:
self.ot_path, self.db_path = mod.source(OTEAM), mod.source(SIMPAC)
self.ot = initteam.OteamMembers(self.ot_path)
self.db = initteam.TeamDb(self.db_path)
mes = mod.source(MES)
self.teams = initteam.team_names(mes, 1)
self.names = {cat: initteam.category_names(mes, cat)
for cat in set(initteam.TEAM_NAME_CATEGORIES.values())}
self.stadiums = initteam.StadiumData(mod.source(STADIUMS))