-
Notifications
You must be signed in to change notification settings - Fork 4
/
chameleon.py
executable file
·1752 lines (1380 loc) · 50.2 KB
/
chameleon.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Needs Python >= 3.3, PyQt4
# Copyright 2013 Unvanquished Development
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from PyQt5 import QtCore, QtGui, QtWidgets
from PIL import Image
from io import BytesIO
import copy
import math
import os
import pickle
import platform
import shutil
import subprocess
import sys
import tempfile
import zipfile
class Static():
APP_TITLE = "Chameleon"
GAME_TITLE = "Unvanquished"
PREVIEW_WIDTH = 128
PREVIEW_HEIGHT = 128
# no dot
TEXTURE_CRUNCH_EXTENSION = ("crn", "dds", "ktx")
TEXTURE_EXTENSIONS = ("tga", "png", "jpg", "jpeg", "webp") + TEXTURE_CRUNCH_EXTENSION
MAP_FILE_EXTENSION = ".map"
RULE_FILE_EXTENSION = ".rules"
QtCore.QCoreApplication.setApplicationName("Chameleon")
standardConfigParentDir = os.path.dirname(QtCore.QStandardPaths.standardLocations(QtCore.QStandardPaths.AppConfigLocation)[0])
standardApplicationParentDir = os.path.dirname(QtCore.QStandardPaths.standardLocations(QtCore.QStandardPaths.ApplicationsLocation)[0])
standardDataParentDir = os.path.dirname(QtCore.QStandardPaths.standardLocations(QtCore.QStandardPaths.AppDataLocation)[0])
standardCacheParentDir = os.path.dirname(QtCore.QStandardPaths.standardLocations(QtCore.QStandardPaths.CacheLocation)[0])
old_settings_dir = None
if platform.system() == "Windows":
old_settings_dir = os.path.join(os.path.expandvars("%APPDATA%", APP_TITLE))
# "My Games" is not a Microsoft standard but a de facto standard,
# there is no environement variable and the name is not expected to be localized.
DEFAULT_HOMEPATH = os.path.join(os.path.expandvars("%CSIDL_MYDOCUMENTS%"), "My Games", GAME_TITLE)
DEFAULT_BASEPATH = os.path.join(os.path.expandvars("%PROGRAMFILES%"), GAME_TITLE)
# Qt is broken and uses a disposable place (Local App Data) to save configuration,
# The data folder is correct anyway.
SETTINGS_DIR = os.path.join(standardDataParentDir, APP_TITLE)
# There is no distinction between configuration and data on Windows anyway.
DATA_DIR = SETTINGS_DIR
CACHE_DIR = os.path.join(standardCacheParentDir, APP_TITLE)
elif platform.system() == "Darwin":
DEFAULT_HOMEPATH = os.path.join(standardDataParentDir, GAME_TITLE)
DEFAULT_BASEPATH = os.path.join(standardApplicationParentDir, GAME_TITLE + ".app", "Contents", "MacOS")
SETTINGS_DIR = os.path.join(standardConfigParentDir, APP_TITLE)
DATA_DIR = os.path.join(standardDataParentDir, APP_TITLE)
CACHE_DIR = os.path.join(standardCacheParentDir, APP_TITLE)
else: # Assume Linux or other Posix system.
old_settings_dir = os.path.join(os.path.expandvars("${HOME}"), "." + APP_TITLE.lower())
DEFAULT_HOMEPATH = os.path.join(standardDataParentDir, GAME_TITLE.lower())
DEFAULT_BASEPATH = os.path.join(DEFAULT_HOMEPATH, "base")
SETTINGS_DIR = os.path.join(standardConfigParentDir, APP_TITLE.lower())
DATA_DIR = os.path.join(standardDataParentDir, APP_TITLE.lower())
CACHE_DIR = os.path.join(standardCacheParentDir, APP_TITLE.lower())
DEFAULT_PAKDIR = "pkg"
os.makedirs(os.path.dirname(SETTINGS_DIR), exist_ok=True)
os.makedirs(os.path.dirname(CACHE_DIR), exist_ok=True)
if old_settings_dir:
# What if it fails?
if os.path.isdir(old_settings_dir) and not os.path.exists(SETTINGS_DIR):
for file_name in [ "shader_cache.dat" ]:
old_file_path = os.path.join(old_settings_dir, file_name)
new_file_path = os.path.join(CACHE_DIR, file_name)
if os.path.exists(old_file_path) and not os.path.exists(new_file_path):
os.makedirs(CACHE_DIR, exist_ok=True)
shutil.move(old_file_path, new_file_path)
for file_name in [ "session.dat" ]:
old_file_path = os.path.join(old_settings_dir, file_name)
new_file_path = os.path.join(DATA_DIR, file_name)
if os.path.exists(old_file_path) and not os.path.exists(new_file_path):
os.makedirs(DATA_DIR, exist_ok=True)
shutil.move(old_file_path, new_file_path)
shutil.move(old_settings_dir, SETTINGS_DIR)
# Exceptions uncatched on purpose.
os.makedirs(SETTINGS_DIR, exist_ok=True)
os.makedirs(CACHE_DIR, exist_ok=True)
SHADER_CACHE_FILE = os.path.join(CACHE_DIR, "shader_cache.dat")
SESSION_FILE = os.path.join(DATA_DIR, "session.dat")
@staticmethod
def progressDialog():
pd = QtWidgets.QProgressDialog("Loading available shaders ...", None, 0, 1)
pd.show()
return pd
class Session():
def __init__(self, model):
self.model = model
self.lastmap = None
self.lastmapdir = None
self.lastrules = None
self.lastrulesdir = None
self.lastshadersets = None
self.shaderpickergeom = None
def saveSession(self, path):
with open(path, "wb") as f:
state = self.__dict__.copy()
del state["model"]
pickle.dump(state, f)
def restoreSession(self, path):
with open(path, "rb") as f:
state = pickle.load(f)
self.__dict__.update(state)
def getLastMap(self):
return self.lastmap
def getLastMapDir(self):
if self.lastmapdir != None:
return self.lastmapdir
homepath = self.model.shaders.getHomepath()
if homepath != None:
return homepath
else:
return Static.DEFAULT_HOMEPATH
def getLastRules(self):
return self.lastrules
def getLastRulesDir(self):
if self.lastrulesdir != None:
return self.lastrulesdir
else:
return Static.SETTINGS_DIR
def getLastShaderSets(self):
return self.lastshadersets
def getShaderPickerGeometry(self):
return self.shaderpickergeom
def setLastMap(self, path):
if os.path.isfile(path):
self.lastmap = path
dir_ = path.rsplit(os.sep, 1)[0]
if os.path.isdir(dir_):
self.lastmapdir = dir_
def setLastRules(self, path):
if os.path.isfile(path):
self.lastrules = path
dir_ = path.rsplit(os.sep, 1)[0]
if os.path.isdir(dir_):
self.lastrulesdir = dir_
def setLastShaderSets(self, names):
self.lastshadersets = names
def setShaderPickerGeometry(self, geom):
self.shaderpickergeom = geom
# TODO: Allow setting of long floats in shader table
class ShaderTableModel(QtCore.QAbstractTableModel):
def __init__(self, model):
QtCore.QAbstractTableModel.__init__(self)
self.model = model
self.headers = \
[
"Count",
"Old Shader",
"Old Size",
"Old Preview",
"New Preview",
"New Size",
"New Shader",
"H Scale",
"V Scale",
"Rotation"
]
self.columns = len(self.headers)
self.h2c = dict() # header -> column
for col in range(len(self.headers)):
self.h2c[self.headers[col]] = col
def reset(self):
self.beginResetModel()
self.endResetModel()
def markChanged(self, row, newOnly):
if newOnly:
begin = 4
else:
begin = 0
self.dataChanged.emit(self.index(row, begin), self.index(row, self.columns - 1))
def rowCount(self, index = None):
return self.model.map.distinctShaders()
def columnCount(self, index = None):
return self.columns
def headerData(self, section, direction, role = QtCore.Qt.DisplayRole):
if direction == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.headers[section]
else:
return QtCore.QAbstractTableModel.headerData(self, section, direction, role)
def flags(self, index):
if index.column() in (7, 8, 9):
return QtCore.Qt.ItemFlags(int(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable))
else:
return QtCore.Qt.ItemFlags(int(QtCore.Qt.ItemIsEnabled))
def setData(self, index, value, role = QtCore.Qt.EditRole):
if role != QtCore.Qt.EditRole:
return False
shader = self.model.map.indexToShader(index.row())
if shader not in self.model.rules:
return False
row = index.row()
col = index.column()
if col == 7:
self.model.rules.setHScale(shader, value)
self.dataChanged.emit(index, index)
elif col == 8:
self.model.rules.setVScale(shader, value)
self.dataChanged.emit(index, index)
elif col == 9:
self.model.rules.setRotation(shader, value)
self.markChanged(row, True)
else:
return False
return True
def data(self, index, role):
row = index.row()
col = index.column()
if not index.isValid() \
or row not in range(self.rowCount()) \
or col not in range(self.columnCount()):
return None
shader = self.model.map.indexToShader(row)
# preview images
if col in (3, 4):
if col == 3:
preview = self.model.shaders.getPreview(shader)
else: # col == 4
if shader in self.model.rules:
new_shader = self.model.rules.getNewShader(shader)
hscale = self.model.rules.getHScale(shader)
vscale = self.model.rules.getVScale(shader)
rot = self.model.rules.getRotation(shader)
preview = self.model.shaders.getPreview(new_shader, shader, hscale, vscale, rot)
else:
preview = self.model.shaders.getPreview()
if role == QtCore.Qt.DecorationRole:
return preview
elif role == QtCore.Qt.SizeHintRole:
return QtCore.QSize(preview.width(), preview.height())
else:
return None
if role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole):
if col == 0:
return str(self.model.map.appearance(shader))
elif col == 1:
return shader
elif col == 2:
return self.model.shaders.getResolution(shader)
elif col == 5:
if shader in self.model.rules:
new_shader = self.model.rules.getNewShader(shader)
return self.model.shaders.getResolution(new_shader)
elif col == 6:
if shader in self.model.rules:
return self.model.rules.getNewShader(shader)
elif col == 7:
if shader in self.model.rules:
return self.model.rules.getHScale(shader)
elif col == 8:
if shader in self.model.rules:
return self.model.rules.getVScale(shader)
elif col == 9:
if shader in self.model.rules:
return self.model.rules.getRotation(shader)
return None
class ShaderSourcesWizzard(QtWidgets.QWizard):
def __init__(self, model):
QtWidgets.QWizard.__init__(self)
self.model = model
old_basepath = self.model.shaders.getBasepath()
old_homepath = self.model.shaders.getHomepath()
old_pakdir = self.model.shaders.getPakdir()
if old_basepath == None:
basepath = Static.DEFAULT_BASEPATH
else:
basepath = old_basepath
if old_homepath == None:
homepath = Static.DEFAULT_HOMEPATH
else:
homepath = old_homepath
if old_pakdir == None:
pakdir = Static.DEFAULT_PAKDIR
else:
pakdir = old_pakdir
self.basepathField = QtWidgets.QLineEdit(basepath)
self.homepathField = QtWidgets.QLineEdit(homepath)
self.pakdirField = QtWidgets.QLineEdit(pakdir)
self.setWindowTitle("Chameleon - Settings")
self.addPage(self.ShaderSourcesWizzardPage1(self))
def accept(self):
self.model.loadShaders(Static.progressDialog(), self.basepathField.text(), self.homepathField.text(), self.pakdirField.text())
self.close()
# TODO: add wizzard pages for 1) select mods 2) select sources
class ShaderSourcesWizzardPage1(QtWidgets.QWizardPage):
def __init__(self, parent):
QtWidgets.QWizardPage.__init__(self, parent)
self.parent = parent
layout = QtWidgets.QFormLayout()
layout.addWidget(QtWidgets.QLabel("Game settings"))
layout.addRow("Basepath", parent.basepathField)
layout.addRow("Homepath", parent.homepathField)
layout.addRow("Pakdir", parent.pakdirField)
self.setLayout(layout)
def validatePage(self):
# TODO: validatePage doesn't work
basepath = os.path.expandvars(self.parent.basepathField.text())
homepath = os.path.expandvars(self.parent.homepathField.text())
pakdir = os.path.expandvars(self.parent.pakdirField.text())
# pakdir can be empty
if os.path.isdir(basepath) and os.path.isdir(homepath):
return True
else:
return False
class ShaderPickerListModel(QtCore.QAbstractListModel):
def __init__(self, model, shaders):
QtCore.QAbstractListModel.__init__(self)
self.model = model
self.shaders = shaders
def rowCount(self, index = None):
return len(self.shaders)
def data(self, index, role):
shader = self.shaders[index.row()]
if role == QtCore.Qt.DecorationRole:
return self.model.shaders.getPreview(shader)
elif role == QtCore.Qt.DisplayRole:
return shader.split("/", 1)[-1]
class ShaderPicker(QtWidgets.QDialog):
def __init__(self, view, model, old_shader):
QtWidgets.QDialog.__init__(self)
self.view = view
self.model = model
self.old_shader = old_shader
self.clear = False
self.selected_shaders = list()
if old_shader in self.model.rules:
self.new_shader = self.model.rules.getNewShader(old_shader)
else:
self.new_shader = None
self.accepted = False
self.setname2item = dict()
# configure window
self.setWindowTitle("Pick a replacement for " + self.old_shader)
# create widgets
self.old_data_label = QtWidgets.QLabel(self.old_shader + "\n" + self.model.shaders.getResolution(self.old_shader), self)
self.old_data_label.setAlignment(QtCore.Qt.AlignRight)
self.old_data_label.setMinimumWidth(256)
self.old_data_label.setMaximumWidth(256)
self.old_preview_label = QtWidgets.QLabel(self)
self.old_preview_label.setMinimumSize(Static.PREVIEW_WIDTH, Static.PREVIEW_HEIGHT)
self.old_preview_label.setAlignment(QtCore.Qt.AlignRight)
self.old_preview_label.setPixmap(self.model.shaders.getPreview(old_shader))
self.new_preview_label = QtWidgets.QLabel(self)
self.new_preview_label.setMinimumSize(Static.PREVIEW_WIDTH, Static.PREVIEW_HEIGHT)
self.new_preview_label.setAlignment(QtCore.Qt.AlignLeft)
self.new_preview_label.setPixmap(self.model.shaders.getPreview(self.new_shader))
if self.new_shader != None:
self.new_data_label = QtWidgets.QLabel(self.new_shader + "\n" + self.model.shaders.getResolution(self.new_shader), self)
else:
self.new_data_label = QtWidgets.QLabel(self)
self.new_data_label.setAlignment(QtCore.Qt.AlignLeft)
self.new_data_label.setMinimumWidth(256)
self.new_data_label.setMaximumWidth(256)
self.set_list = QtWidgets.QListWidget(self)
self.set_list.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.set_list.setMinimumWidth(180)
self.set_list.setMaximumWidth(180)
for setname in self.model.shaders.getSets():
item = QtWidgets.QListWidgetItem(setname)
self.set_list.addItem(item)
self.setname2item[setname] = item
self.shader_list = QtWidgets.QListView(self)
self.shader_list.setViewMode(QtWidgets.QListView.IconMode)
self.replace_button = QtWidgets.QPushButton("Replace", self)
self.cancel_button = QtWidgets.QPushButton("Cancel", self)
self.clear_button = QtWidgets.QPushButton("Clear", self)
# assemble layout
toplayout = QtWidgets.QHBoxLayout()
toplayout.addWidget(self.old_data_label)
toplayout.addWidget(self.old_preview_label)
toplayout.addWidget(self.new_preview_label)
toplayout.addWidget(self.new_data_label)
centerlayout = QtWidgets.QHBoxLayout()
centerlayout.addWidget(self.set_list)
centerlayout.addWidget(self.shader_list)
bottomlayout = QtWidgets.QHBoxLayout()
bottomlayout.addWidget(self.replace_button)
bottomlayout.addWidget(self.cancel_button)
bottomlayout.addWidget(self.clear_button)
rootlayout = QtWidgets.QVBoxLayout()
rootlayout.addLayout(toplayout)
rootlayout.addLayout(centerlayout)
rootlayout.addLayout(bottomlayout)
self.setLayout(rootlayout)
# connect signals
self.set_list.itemSelectionChanged.connect(self.__handleSelectedSets)
self.shader_list.clicked.connect(self.__handleClickedShader)
self.replace_button.clicked.connect(self.__handleReplace)
self.cancel_button.clicked.connect(self.__handleCancel)
self.clear_button.clicked.connect(self.__handleClear)
# restore selected sets
lastsets = self.view.session.getLastShaderSets()
if lastsets != None:
selection = QtCore.QItemSelection()
for setname in lastsets:
if setname in self.setname2item:
index = self.set_list.indexFromItem(self.setname2item[setname])
selection.select(index, index)
self.set_list.selectionModel().select(selection, QtCore.QItemSelectionModel.Select)
# restore geometry
geom = self.view.session.getShaderPickerGeometry()
if geom != None:
self.restoreGeometry(geom)
def getNewShader(self):
if self.accepted:
return self.new_shader
else:
return None
def getClear(self):
return self.clear
def resizeEvent(self, event):
self.shader_list.reset()
def __handleSelectedSets(self):
setnames = [setname.text() for setname in self.set_list.selectedItems()]
setnames.sort()
self.view.session.setLastShaderSets(setnames)
self.selected_shaders.clear()
for setname in setnames:
for shader in self.model.shaders.getShadersForSet(setname):
self.selected_shaders.append(shader)
self.__showShaders(self.selected_shaders)
def __handleClickedShader(self, index):
try:
shader = self.selected_shaders[index.row()]
except IndexError:
return
self.new_shader = shader
self.new_data_label.setText(self.new_shader + "\n" + self.model.shaders.getResolution(shader))
self.new_preview_label.setPixmap(self.model.shaders.getPreview(shader))
def __showShaders(self, shaders):
self.shader_list.setModel(ShaderPickerListModel(self.model, shaders))
def __handleReplace(self):
self.accepted = True
self.close()
def __handleCancel(self):
self.close()
def __handleClear(self):
self.clear = True
self.close()
def closeEvent(self, event):
self.close()
def close(self):
self.view.session.setShaderPickerGeometry(self.saveGeometry())
QtWidgets.QDialog.close(self)
class View(QtWidgets.QMainWindow):
def __init__(self, model):
QtWidgets.QWidget.__init__(self)
self.model = model
self.session = Session(model)
self.trigger = QtCore.pyqtSignal()
# configure window
self.setWindowTitle(Static.APP_TITLE)
# create widgets
self.menuMap = QtWidgets.QMenu("Map", self)
self.actionOpenMap = self.menuMap.addAction("Open map", self.__handleOpenMap, "Ctrl+O")
self.actionSaveMap = self.menuMap.addAction("Save map", self.__handleSaveMap, "Ctrl+S")
self.actionSaveMap.setEnabled(False)
self.menuRules = QtWidgets.QMenu("Rules", self)
self.actionOpenRules = self.menuRules.addAction("Import rules", self.__handleOpenRules, "Ctrl+I")
self.actionSaveRules = self.menuRules.addAction("Export rules", self.__handleSaveRules, "Ctrl+E")
self.actionSaveRules.setEnabled(False)
self.actionClearRules = self.menuRules.addAction("Clear rules", self.__handleClearRules)
self.actionClearRules.setEnabled(False)
self.menuShaders = QtWidgets.QMenu("Shaders", self)
self.actionReloadShaders = self.menuShaders.addAction("Reload shaders", self.__handleReloadShaders, "Ctrl+R")
self.actionSettings = self.menuShaders.addAction("Set shader sources", self.__handleSettings)
self.statusLabel = QtWidgets.QLabel("", self)
self.tableView = QtWidgets.QTableView()
self.tableModel = ShaderTableModel(self.model)
self.tableView.setModel(self.tableModel)
# assemble layout
menubar = QtWidgets.QMenuBar()
menubar.addMenu(self.menuMap)
menubar.addMenu(self.menuRules)
menubar.addMenu(self.menuShaders)
bottomlayout = QtWidgets.QHBoxLayout()
bottomlayout.addWidget(self.statusLabel)
rootlayout = QtWidgets.QVBoxLayout()
rootlayout.addWidget(self.tableView)
rootlayout.addLayout(bottomlayout)
centerWidget = QtWidgets.QWidget()
centerWidget.setLayout(rootlayout)
self.setMenuBar(menubar)
self.setCentralWidget(centerWidget)
# connect signals
self.tableView.clicked.connect(self.__handleTableClicked)
def setStatus(self, status):
"Called by Model.* to display stuff in the status bar."
self.statusLabel.setText(status)
def askSettings(self):
"Called by __main__ to show configuration dialog."
sw = ShaderSourcesWizzard(self.model)
sw.exec_()
self.__updateTable()
def restoreSession(self):
"Tries to read session data from filesystem."
try:
self.session.restoreSession(Static.SESSION_FILE)
except FileNotFoundError:
return False
except BaseException as e:
print("Failed to read session file " + Static.SESSION_FILE + ": " + str(e), file = sys.stderr)
return False
else:
return True
def closeEvent(self, event):
try:
self.session.saveSession(Static.SESSION_FILE)
except BaseException as e:
print("Failed to save session file " + Static.SESSION_FILE + ": " + str(e), file = sys.stderr)
QtWidgets.QWidget.closeEvent(self, event)
def keyPressEvent(self, event):
if event.modifiers() & QtCore.Qt.ControlModifier:
if event.key() == QtCore.Qt.Key_O:
self.__handleOpenMap()
elif event.key() == QtCore.Qt.Key_S:
self.__handleSaveMap()
def __updateRulesButton(self):
if self.model.rules.empty():
self.actionSaveRules.setEnabled(False)
self.actionClearRules.setEnabled(False)
else:
self.actionSaveRules.setEnabled(True)
self.actionClearRules.setEnabled(True)
def __updateTable(self, rowOrShader = None, newOnly = True):
if rowOrShader == None:
self.tableModel.reset()
self.tableView.resizeRowsToContents()
else:
if type(rowOrShader) == str:
row = self.model.map.shaderToIndex(rowOrShader)
if row == None:
return
else:
row = rowOrShader
self.tableModel.markChanged(row, newOnly)
self.tableView.resizeColumnsToContents()
def __handleTableClicked(self, index):
if index.column() == 4: # new old_shader preview
old_shader = self.model.map.indexToShader(index.row())
picker = ShaderPicker(self, self.model, old_shader)
picker.exec_()
new_shader = picker.getNewShader()
clear = picker.getClear()
if clear:
self.model.rules.delRule(old_shader)
elif new_shader != None:
self.model.rules.addRule(old_shader, new_shader)
else:
return
self.__updateTable(old_shader)
self.__updateRulesButton()
def __handleOpenMap(self):
path, _filter = QtWidgets.QFileDialog.getOpenFileName(
self,
"Choose a map",
self.session.getLastMapDir(),
"*" + Static.MAP_FILE_EXTENSION
)
if path != "":
self.model.openMap(path)
self.session.setLastMap(path)
self.setWindowTitle(Static.APP_TITLE + " - " + os.path.basename(path))
self.actionSaveMap.setEnabled(True)
self.__updateTable()
def __handleSaveMap(self):
path, _filter = QtWidgets.QFileDialog.getSaveFileName(
self, "Choose a destination",
self.session.getLastMapDir(),
"*" + Static.MAP_FILE_EXTENSION
)
if path != "":
if not path.endswith(Static.MAP_FILE_EXTENSION):
path += Static.MAP_FILE_EXTENSION
self.model.saveMap(path)
def __handleOpenRules(self):
path, _filter = QtWidgets.QFileDialog.getOpenFileName(
self,
"Choose a rules file",
self.session.getLastRulesDir(),
"*" + Static.RULE_FILE_EXTENSION)
if path != "":
self.model.openRules(path)
self.session.setLastRules(path)
self.__updateRulesButton()
self.__updateTable()
def __handleClearRules(self):
self.model.rules.clear()
self.__updateRulesButton()
self.__updateTable()
self.setStatus("Rules cleared.")
def __handleSaveRules(self):
path, _filter = QtWidgets.QFileDialog.getSaveFileName(
self,
"Choose a destination",
self.session.getLastRulesDir(),
"*" + Static.RULE_FILE_EXTENSION
)
if path != "":
if not path.endswith(Static.RULE_FILE_EXTENSION):
path += Static.RULE_FILE_EXTENSION
self.model.saveRules(path)
def __handleReloadShaders(self):
self.model.reloadShaders(Static.progressDialog())
self.__updateTable()
def __handleSettings(self):
self.askSettings()
class Shaders():
def __init__(self):
self.basepath = None
self.homepath = None
self.pakdir = None
self.shader_sources = list() # dirs/pk3s inside self.basepath/self.homepath
self.shaders = dict() # shader name -> property -> value
painter = QtGui.QPainter()
# build NO PREVIEW image
self.pixmap_not_found = QtGui.QPixmap(128, 128)
self.pixmap_not_found.fill(QtCore.Qt.black)
painter.begin(self.pixmap_not_found)
painter.setPen(QtCore.Qt.red)
painter.drawText(QtCore.QPointF(24, 67), "NOT FOUND")
painter.end()
# build UNSUPPORTED image
self.pixmap_unsupported = QtGui.QPixmap(128, 128)
self.pixmap_unsupported.fill(QtCore.Qt.black)
painter.begin(self.pixmap_unsupported)
painter.setPen(QtCore.Qt.yellow)
painter.drawText(QtCore.QPointF(13, 67), "UNSUPPORTED")
painter.end()
# build REPLACE image
self.pixmap_replace = QtGui.QPixmap(128, 128)
self.pixmap_replace.fill(QtCore.Qt.black)
painter.begin(self.pixmap_replace)
painter.setPen(QtCore.Qt.white)
painter.drawText(QtCore.QPointF(32, 67), "REPLACE")
painter.end()
def __contains__(self, shader):
return shader in self.shaders
def __len__(self):
return len(self.shaders)
def emtpy(self):
return len(self) == 0
def writeCache(self, path):
with open(path, "wb") as f:
state = (self.basepath, self.homepath, self.shader_sources, self.shaders)
pickle.dump(state, f)
def readCache(self, path):
with open(path, "rb") as f:
state = pickle.load(f)
(self.basepath, self.homepath, self.shader_sources, self.shaders) = state
def getPath(self, shader):
if shader in self.shaders and not self.shaders[shader]["is_shader"]:
return self.shaders[shader]["path"]
else:
return ""
def getPreviewScale(self, shader):
if shader in self.shaders:
if self.shaders[shader]["is_shader"]:
preview_source = self.shaders[shader]["preview_source"]
if preview_source in self.shaders \
and not self.shaders[preview_source]["is_shader"]: # prevent recursion
return self.getPreviewScale(preview_source)
else:
return 1.0
else:
return self.shaders[shader]["preview_scale"]
else:
return 1.0
def getPreview(self, shader = None, old_shader = None, hscale = None, vscale = None, rot = None):
if shader == None:
return self.pixmap_replace
elif shader in self.shaders:
if self.shaders[shader]["is_shader"]:
preview_source = self.shaders[shader]["preview_source"]
if preview_source in self.shaders \
and not self.shaders[preview_source]["is_shader"]: # prevent recursion
return self.getPreview(preview_source, old_shader, hscale, vscale, rot)
else:
return self.pixmap_not_found
else:
if self.shaders[shader]["width"] == self.shaders[shader]["height"] == 0:
return self.pixmap_unsupported
else:
if old_shader in self.shaders and hscale != None and vscale != None and rot != None:
scale = self.getPreviewScale(shader) / self.getPreviewScale(old_shader)
hscale /= scale
vscale /= scale
trans_scale = QtGui.QTransform().scale(hscale, vscale)
trans_rot = QtGui.QTransform().rotate(rot)
preview = self.convertQByteArrayToQPixmap(self.shaders[shader]["preview"])
return preview.transformed(trans_scale).transformed(trans_rot)
else:
preview = self.convertQByteArrayToQPixmap(self.shaders[shader]["preview"])
return preview
else:
return self.pixmap_not_found
def getWidth(self, shader):
if shader in self.shaders:
if self.shaders[shader]["is_shader"]:
preview_source = self.shaders[shader]["preview_source"]
if preview_source in self.shaders \
and not self.shaders[preview_source]["is_shader"]: # prevent recursion
return self.getWidth(preview_source)
else:
return 0
else:
return self.shaders[shader]["width"]
else:
return 0
def getHeight(self, shader):
if shader in self.shaders:
if self.shaders[shader]["is_shader"]:
preview_source = self.shaders[shader]["preview_source"]
if preview_source in self.shaders \
and not self.shaders[preview_source]["is_shader"]: # prevent recursion
return self.getHeight(preview_source)
else:
return 0
else:
return self.shaders[shader]["height"]
else:
return 0
def sizeKnown(self, shader):
return self.getWidth(shader) > 0 and self.getHeight(shader) > 0
def getResolution(self, shader):
return str(self.getWidth(shader)) + " x " + str(self.getHeight(shader))
def loadShaders(self, pd, basepath, homepath, pakdir, reload = False):
"Updates self.basepath and self.homepath and loads shader data from disk if the pathes have changed."
if self.basepath != basepath or self.homepath != homepath or reload:
necessary = True
else:
necessary = False
self.basepath = basepath
self.homepath = homepath
self.pakdir = pakdir
if necessary:
self.__updateShaderSources(pd)
self.__updateShaderData(pd)
return necessary
def reloadShaders(self, pd):
"Reloads shader data from disk."
self.loadShaders(pd, self.basepath, self.homepath, self.pakdir, True)
def getBasepath(self):
return self.basepath
def getHomepath(self):
return self.homepath
def getPakdir(self):
return self.pakdir
# TODO: cache getSets answer?
def getSets(self):
sets = set()
for shader in self.shaders.keys():
sets.add(shader.split("/", 1)[0])
sorted_sets = list(sets)
sorted_sets.sort()
return sorted_sets
# TODO: cache getShadersForSets answer?
def getShadersForSet(self, setname):
shaders = [shader for shader in self.shaders.keys() if shader.startswith(setname + "/")]
shaders.sort()
return shaders
def __updateShaderSources(self, pd):
"""Writes pathes of mod directories and their pak files/dirs inside self.basepath
and self.homepath into self.shader_sources."""
self.shader_sources.clear()
for path in (self.basepath, self.homepath):
if path != None:
path = os.path.expanduser(path).rstrip(os.sep)
if not os.path.isdir(path):
continue
mods = list()
for node in os.listdir(path):
if self.pakdir in ["", node]:
if os.path.isdir(path + os.sep + node):