-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsatoru.py
15373 lines (12616 loc) · 549 KB
/
satoru.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/python
# Satoru - New Super Mario Bros. U Level Editor
# Version v0.1
# Copyright (C) 2009-2016 Treeki, Tempus, angelsl, JasonP27, Kinnay,
# MalStar1000, RoadrunnerWMC, MrRean, Grop
# This file is part of Satoru.
# Satoru 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.
# Satoru 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 Satoru. If not, see <http://www.gnu.org/licenses/>.
# satoru.py
# This is the main executable for Satoru
################################################################
################################################################
# Python version: sanity check
minimum = 3.5
import sys
currentRunningVersion = sys.version_info.major + (0.1 * sys.version_info.minor)
if currentRunningVersion < minimum:
errormsg = 'Please update your copy of Python to ' + str(minimum) + \
' or greater. Currently running on: ' + sys.version[:5]
raise Exception(errormsg)
# Stdlib imports
import base64
import importlib
import io
from math import floor as math_floor
import os
import os.path
import pickle
import struct
import subprocess
import threading
import time
import urllib.request
from xml.etree import ElementTree as etree
import zipfile
# nsmbulib
import nsmbulib.Object
import nsmbulib.Sarc
import nsmbulib.Tile
import nsmbulib.Tileset
import nsmbulib.Yaz0
import PIL.Image, PIL.ImageQt
# PyQt5: import, and error msg if not installed
try:
from PyQt5 import QtCore, QtGui, QtWidgets
except (ImportError, NameError):
errormsg = 'PyQt5 is not installed for this Python installation. Go online and download it.'
raise Exception(errormsg) from None
Qt = QtCore.Qt
# Local imports
import gibberish
import spritelib as SLib
import sprites
from strings import *
SatoruID = 'Satoru Level Editor by Treeki, Tempus, RoadrunnerWMC, MrRean and Grop'
SatoruVersion = '0.1'
SatoruVersionShort = 'v0.1 (a)'
UpdateURL = 'http://rvlution.net/satoru/updates.xml'
FileTypes = ''
FileTypes += 'Level Archives (*.sarc *.szs);;'
FileTypes += 'Compressed Level Archives (*.szs);;'
FileTypes += 'Uncompressed Level Archives (*.sarc);;'
FileTypes += 'All Files (*)'
if not hasattr(QtWidgets.QGraphicsItem, 'ItemSendsGeometryChanges'):
# enables itemChange being called on QGraphicsItem
QtWidgets.QGraphicsItem.ItemSendsGeometryChanges = QtWidgets.QGraphicsItem.GraphicsItemFlag(0x800)
# Globals
TileWidth = 60
generateStringsXML = False
app = None
mainWindow = None
settings = None
defaultStyle = None
defaultPalette = None
compressed = False
LevelNames = None
ObjDesc = None
SpriteCategories = None
SpriteListData = None
EntranceTypeNames = None
MainObjects = [] # Pa0
OneTilesetObjects = {}
OneTilesetHierarchy = {}
EmbeddedObjects = [] # Pa1/2/3
EmbeddedObjectsLoadedFrom = {} # (tilesetnum, objectnum): index
Area = None
Dirty = False
DirtyOverride = 0
AutoSaveDirty = False
OverrideSnapping = False
CurrentPaintType = -1
CurrentObject = -1
CurrentSprite = -1
CurrentLayer = 1
Layer0Shown = True
Layer1Shown = True
Layer2Shown = True
SpritesShown = True
SpriteImagesShown = True
RealViewEnabled = False
LocationsShown = True
CommentsShown = True
PathsShown = True
ObjectsFrozen = False
SpritesFrozen = False
EntrancesFrozen = False
LocationsFrozen = False
PathsFrozen = False
CommentsFrozen = False
PaintingEntrance = None
PaintingEntranceListIndex = None
NumberFont = None
GridType = None
RestoredFromAutoSave = False
AutoSavePath = ''
AutoSaveData = b''
AutoOpenScriptEnabled = False
CurrentLevelNameForAutoOpenScript = 'AAAAAAAAAAAAAAAAAAAAAAAAAA'
OBJECT_FROM_MAIN = 1
OBJECT_FROM_MEGA = 2
OBJECT_FROM_EMBED = 3
Pa0Path = ""
# Game enums
NewSuperMarioBrosU = 0
NewSuperLuigiU = 1
FileExtensions = {
NewSuperMarioBrosU: ('.szs', '.sarc'),
NewSuperLuigiU: ('.szs', '.sarc'),
}
FirstLevels = {
NewSuperMarioBrosU: '1-1',
NewSuperLuigiU: '1-1',
}
#####################################################################
############################# UI-THINGS #############################
#####################################################################
class SatoruSplashScreen(QtWidgets.QSplashScreen):
"""
Splash screen class for Satoru.
"""
cfgData = {}
currentDesc = ''
currentPos = 0
posLimit = 0
def __init__(self):
"""
Initializes the splash screen.
super().__init__(QPixmap) has to be called with the pixmap you want or
else transparency is messed up. self.setPixmap(QPixmap) doesn't seem to
work properly.
"""
self.loadCfg()
self.loadResources()
super().__init__(self.basePix)
def loadCfg(self):
"""
Loads the raw data from splash_config.txt
"""
cfgData = {}
with open('satorudata/splash_config.txt', encoding='utf-8') as cfg:
for line in cfg:
lsplit = line.replace('\n', '').split(':')
key = lsplit[0].lower()
value = ':'.join(lsplit[1:])
if value.lower() in ('true', 'false'):
value = value.lower() == 'true'
elif ',' in value:
value = value.split(',')
for i, entry in enumerate(value):
try:
value[i] = int(entry)
except ValueError: pass
if isinstance(value, str):
try:
value = int(value)
except ValueError: pass
cfgData[key] = value
self.cfgData = cfgData
def loadResources(self):
"""
Reads the info from self.cfgData and loads stuff
"""
self.basePix = QtGui.QPixmap(os.path.join('satorudata', self.cfgData['base_image']))
def loadFont(name):
fname = self.cfgData.get(name + '_font', 'sans-serif')
bold = self.cfgData.get(name + '_font_bold', False)
color = '#' + self.cfgData.get(name + '_font_color', '000000')
size = self.cfgData.get(name + '_font_size', 12)
weight = self.cfgData.get(name + '_font_weight', 12)
wLim = self.cfgData.get(name + '_wrap_limit', 1024)
position = self.cfgData.get(name + '_position', (0, 0))
centered = self.cfgData.get(name + '_centered', False)
font = QtGui.QFont()
font.setFamily(fname)
font.setBold(bold)
font.setPointSize(size)
font.setWeight(weight)
return font, position, color, centered, wLim
self.versionFontInfo = loadFont('version')
self.loadingFontInfo = loadFont('loading')
self.copyrightFontInfo = loadFont('copyright')
mNameL = self.cfgData.get('meter_left', '')
mNameM = self.cfgData.get('meter_mid', '')
mNameR = self.cfgData.get('meter_right', '')
self.meterPos = self.cfgData.get('meter_position', (0, 0))
self.meterWidth = self.cfgData.get('meter_width', 64)
self.meterL = QtGui.QPixmap(os.path.join('satorudata', mNameL))
self.meterM = QtGui.QPixmap(os.path.join('satorudata', mNameM))
self.meterR = QtGui.QPixmap(os.path.join('satorudata', mNameR))
def setProgressLimit(self, limit):
"""
Sets the maximum progress, used to calculate the progress bar
"""
self.posLimit = limit
def setProgress(self, desc, pos):
"""
Sets the current progress
"""
self.currentDesc = desc
self.currentPos = pos
self.repaint()
app.processEvents()
def drawContents(self, painter):
"""
Draws the contents of the splash screen
"""
painter.setRenderHint(painter.Antialiasing)
totalWidthSoFar = self.meterWidth * (self.currentPos / self.posLimit)
painter.drawPixmap(
self.meterPos[0],
self.meterPos[1],
min(self.meterL.width(), self.meterWidth * (self.currentPos / self.posLimit)),
self.meterL.height(),
self.meterL,
)
painter.drawTiledPixmap(
self.meterPos[0] + self.meterL.width(),
self.meterPos[1],
min(self.meterWidth - self.meterL.width() - self.meterR.width(), totalWidthSoFar - self.meterL.width()),
self.meterM.height(),
self.meterM,
)
painter.drawTiledPixmap(
self.meterPos[0] + self.meterWidth - self.meterR.width(),
self.meterPos[1],
totalWidthSoFar - self.meterWidth + self.meterR.width(),
self.meterR.height(),
self.meterR,
)
def drawText(text, font, position, color, centered, wLim):
"""
Draws some text
"""
rect = QtCore.QRectF(
position[0] - (wLim / 2 if centered else 0),
position[1],
wLim,
512,
)
flags = (Qt.AlignHCenter if centered else Qt.AlignLeft) | Qt.AlignTop | Qt.TextWordWrap
painter.save()
painter.setFont(font)
r, g, b = int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
painter.setPen(QtGui.QPen(QtGui.QColor(r, g, b)))
painter.drawText(rect, flags, text)
painter.restore()
drawText(SatoruVersionShort, *self.versionFontInfo)
drawText(self.currentDesc, *self.loadingFontInfo)
try:
with open('license_short.txt', 'r') as copyFile:
text = copyFile.read()
except FileNotFoundError:
# No idea why this happens sometimes.
text = 'LICENSE NOT FOUND'
drawText(text, *self.copyrightFontInfo)
class ChooseLevelNameDialog(QtWidgets.QDialog):
"""
Dialog which lets you choose a level from a list
"""
def __init__(self):
"""
Creates and initializes the dialog
"""
super().__init__()
self.setWindowTitle(trans.string('OpenFromNameDlg', 0))
self.setWindowIcon(GetIcon('open'))
LoadLevelNames()
self.currentlevel = None
# create the tree
tree = QtWidgets.QTreeWidget()
tree.setColumnCount(1)
tree.setHeaderHidden(True)
tree.setIndentation(16)
tree.currentItemChanged.connect(self.HandleItemChange)
tree.itemActivated.connect(self.HandleItemActivated)
# add items (LevelNames is effectively a big category)
tree.addTopLevelItems(self.ParseCategory(LevelNames))
# assign it to self.leveltree
self.leveltree = tree
# create the buttons
self.buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)
self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
# create the layout
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.leveltree)
layout.addWidget(self.buttonBox)
self.setLayout(layout)
self.layout = layout
self.setMinimumWidth(320) # big enough to fit "World 5: Freezeflame Volcano/Freezeflame Glacier"
self.setMinimumHeight(384)
def ParseCategory(self, items):
"""
Parses a XML category
"""
nodes = []
for item in items:
node = QtWidgets.QTreeWidgetItem()
node.setText(0, item[0])
# see if it's a category or a level
if isinstance(item[1], str):
# it's a level
node.setData(0, Qt.UserRole, item[1])
node.setToolTip(0, item[1] + '.szs')
else:
# it's a category
children = self.ParseCategory(item[1])
for cnode in children:
node.addChild(cnode)
node.setToolTip(0, item[0])
nodes.append(node)
return tuple(nodes)
def HandleItemChange(self, current, previous):
"""
Catch the selected level and enable/disable OK button as needed
"""
self.currentlevel = current.data(0, Qt.UserRole)
if self.currentlevel is None:
self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
else:
self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)
self.currentlevel = str(self.currentlevel)
def HandleItemActivated(self, item, column):
"""
Handle a doubleclick on a level
"""
self.currentlevel = item.data(0, Qt.UserRole)
if self.currentlevel is not None:
self.currentlevel = str(self.currentlevel)
self.accept()
class SatoruTheme():
"""
Class that represents a Satoru theme
"""
def __init__(self, file=None):
"""
Initializes the theme
"""
self.initAsClassic()
if file is not None: self.initFromFile(file)
def initAsClassic(self):
"""
Initializes the theme as the hardcoded Classic theme
"""
self.fileName = 'Classic'
self.formatver = 1.0
self.version = 1.0
self.themeName = trans.string('Themes', 0)
self.creator = trans.string('Themes', 1)
self.description = trans.string('Themes', 2)
self.iconCacheSm = {}
self.iconCacheLg = {}
self.style = None
# Add the colours # Descriptions:
self.colors = {
'bg': QtGui.QColor(119,136,153), # Main scene background fill
'comment_fill': QtGui.QColor(220,212,135,120), # Unselected comment fill
'comment_fill_s': QtGui.QColor(254,240,240,240), # Selected comment fill
'comment_lines': QtGui.QColor(192,192,192,120), # Unselected comment lines
'comment_lines_s': QtGui.QColor(220,212,135,240), # Selected comment lines
'depth_highlight': QtGui.QColor(243,243,21,191), # Tileset 3D effect highlight (NSMBU)
'entrance_fill': QtGui.QColor(190,0,0,120), # Unselected entrance fill
'entrance_fill_s': QtGui.QColor(190,0,0,240), # Selected entrance fill
'entrance_lines': QtGui.QColor(0,0,0), # Unselected entrance lines
'entrance_lines_s': QtGui.QColor(255,255,255), # Selected entrance lines
'grid': QtGui.QColor(255,255,255,100), # Grid
'location_fill': QtGui.QColor(114,42,188,70), # Unselected location fill
'location_fill_s': QtGui.QColor(170,128,215,100), # Selected location fill
'location_lines': QtGui.QColor(0,0,0), # Unselected location lines
'location_lines_s': QtGui.QColor(255,255,255), # Selected location lines
'location_text': QtGui.QColor(255,255,255), # Location text
'object_fill_s': QtGui.QColor(255,255,255,64), # Select object fill
'object_lines_s': QtGui.QColor(255,255,255), # Selected object lines
'overview_entrance': QtGui.QColor(255,0,0), # Overview entrance fill
'overview_location_fill': QtGui.QColor(114,42,188,50), # Overview location fill
'overview_location_lines': QtGui.QColor(0,0,0), # Overview location lines
'overview_object': QtGui.QColor(255,255,255), # Overview object fill
'overview_sprite': QtGui.QColor(0,92,196), # Overview sprite fill
'overview_viewbox': QtGui.QColor(0,0,255), # Overview background fill
'overview_zone_fill': QtGui.QColor(47,79,79,120), # Overview zone fill
'overview_zone_lines': QtGui.QColor(0,255,255), # Overview zone lines
'path_connector': QtGui.QColor(6,249,20), # Path node connecting lines
'path_fill': QtGui.QColor(6,249,20,120), # Unselected path node fill
'path_fill_s': QtGui.QColor(6,249,20,240), # Selected path node fill
'path_lines': QtGui.QColor(0,0,0), # Unselected path node lines
'path_lines_s': QtGui.QColor(255,255,255), # Selected path node lines
'smi': QtGui.QColor(255,255,255,80), # Sprite movement indicator
'sprite_fill_s': QtGui.QColor(255,255,255,64), # Selected sprite w/ image fill
'sprite_lines_s': QtGui.QColor(255,255,255), # Selected sprite w/ image lines
'spritebox_fill': QtGui.QColor(0,92,196,120), # Unselected sprite w/o image fill
'spritebox_fill_s': QtGui.QColor(0,92,196,240), # Selected sprite w/o image fill
'spritebox_lines': QtGui.QColor(0,0,0), # Unselected sprite w/o image fill
'spritebox_lines_s': QtGui.QColor(255,255,255), # Selected sprite w/o image fill
'zone_entrance_helper': QtGui.QColor(190,0,0,120), # Zone entrance-placement left border indicator
'zone_lines': QtGui.QColor(145,200,255,176), # Zone lines
'zone_corner': QtGui.QColor(255,255,255), # Zone grabbers/corners
'zone_dark_fill': QtGui.QColor(0,0,0,48), # Zone fill when dark
'zone_text': QtGui.QColor(44,64,84), # Zone text
}
def initFromFile(self, file):
"""
Initializes the theme from the file
"""
try:
zipf = zipfile.ZipFile(file, 'r')
zipfList = zipf.namelist()
except Exception:
# Can't load the data for some reason
return
try:
mainxmlfile = zipf.open('main.xml')
except KeyError:
# There's no main.xml in the file
return
# Create a XML ElementTree
try: maintree = etree.parse(mainxmlfile)
except Exception: return
root = maintree.getroot()
# Parse the attributes of the <theme> tag
if not self.parseMainXMLHead(root):
# The attributes are messed up
return
# Parse the other nodes
for node in root:
if node.tag.lower() == 'colors':
if 'file' not in node.attrib: continue
# Load the colors XML
try:
self.loadColorsXml(zipf.open(node.attrib['file']))
except Exception: continue
elif node.tag.lower() == 'stylesheet':
if 'file' not in node.attrib: continue
# Load the stylesheet
try:
self.loadStylesheet(zipf.open(node.attrib['file']))
except Exception: continue
elif node.tag.lower() == 'icons':
if not all(thing in node.attrib for thing in ['size', 'folder']): continue
foldername = node.attrib['folder']
big = node.attrib['size'].lower()[:2] == 'lg'
cache = self.iconCacheLg if big else self.iconCacheSm
# Load the icons
for iconfilename in zipfList:
iconname = iconfilename
if not iconname.startswith(foldername + '/'): continue
iconname = iconname[len(foldername)+1:]
if len(iconname) <= len('icon-.png'): continue
if not iconname.startswith('icon-') or not iconname.endswith('.png'): continue
iconname = iconname[len('icon-'): -len('.png')]
icodata = zipf.open(iconfilename).read()
pix = QtGui.QPixmap()
if not pix.loadFromData(icodata): continue
ico = QtGui.QIcon(pix)
cache[iconname] = ico
def parseMainXMLHead(self, root):
"""
Parses the main attributes of main.xml
"""
MaxSupportedXMLVersion = 1.0
# Check for required attributes
if root.tag.lower() != 'theme': return False
if 'format' in root.attrib:
formatver = root.attrib['format']
try: self.formatver = float(formatver)
except ValueError: return False
else: return False
if self.formatver > MaxSupportedXMLVersion: return False
if 'name' in root.attrib: self.themeName = root.attrib['name']
else: return False
# Check for optional attributes
self.creator = trans.string('Themes', 3)
self.description = trans.string('Themes', 4)
self.style = None
self.version = 1.0
if 'creator' in root.attrib: self.creator = root.attrib['creator']
if 'description' in root.attrib: self.description = root.attrib['description']
if 'style' in root.attrib: self.style = root.attrib['style']
if 'version' in root.attrib:
try: self.version = float(root.attrib['style'])
except ValueError: pass
return True
def loadColorsXml(self, file):
"""
Loads a colors.xml file
"""
try: tree = etree.parse(file)
except Exception: return
root = tree.getroot()
if root.tag.lower() != 'colors': return False
colorDict = {}
for colorNode in root:
if colorNode.tag.lower() != 'color': continue
if not all(thing in colorNode.attrib for thing in ['id', 'value']): continue
colorval = colorNode.attrib['value']
if colorval.startswith('#'): colorval = colorval[1:]
a = 255
try:
if len(colorval) == 3:
# RGB
r = int(colorval[0], 16)
g = int(colorval[1], 16)
b = int(colorval[2], 16)
elif len(colorval) == 4:
# RGBA
r = int(colorval[0], 16)
g = int(colorval[1], 16)
b = int(colorval[2], 16)
a = int(colorval[3], 16)
elif len(colorval) == 6:
# RRGGBB
r = int(colorval[0:2], 16)
g = int(colorval[2:4], 16)
b = int(colorval[4:6], 16)
elif len(colorval) == 8:
# RRGGBBAA
r = int(colorval[0:2], 16)
g = int(colorval[2:4], 16)
b = int(colorval[4:6], 16)
a = int(colorval[6:8], 16)
except ValueError: continue
colorobj = QtGui.QColor(r, g, b, a)
colorDict[colorNode.attrib['id']] = colorobj
# Merge dictionaries
self.colors.update(colorDict)
def loadStylesheet(self, file):
"""
Loads a stylesheet
"""
print(file)
def color(self, name):
"""
Returns a color
"""
return self.colors[name]
def GetIcon(self, name, big=False):
"""
Returns an icon
"""
cache = self.iconCacheLg if big else self.iconCacheSm
if name not in cache:
path = 'satorudata/ico/lg/icon-' if big else 'satorudata/ico/sm/icon-'
path += name
cache[name] = QtGui.QIcon(path)
return cache[name]
def ui(self):
"""
Returns the UI style
"""
return self.uiStyle
def toQColor(*args):
"""
Usage: toQColor(r, g, b[, a]) OR toQColor((r, g, b[, a]))
"""
if len(args) == 1: args = args[0]
r = args[0]
g = args[1]
b = args[2]
a = args[3] if len(args) == 4 else 255
return QtGui.QColor(r, g, b, a)
def SetAppStyle():
"""
Set the application window color
"""
global app
global theme
# Change the color if applicable
#if theme.color('ui') is not None: app.setPalette(QtGui.QPalette(theme.color('ui')))
# Change the style
styleKey = setting('uiStyle')
style = QtWidgets.QStyleFactory.create(styleKey)
app.setStyle(style)
def createHorzLine():
f = QtWidgets.QFrame()
f.setFrameStyle(QtWidgets.QFrame.HLine | QtWidgets.QFrame.Sunken)
return f
def createVertLine():
f = QtWidgets.QFrame()
f.setFrameStyle(QtWidgets.QFrame.VLine | QtWidgets.QFrame.Sunken)
return f
def LoadNumberFont():
"""
Creates a valid font we can use to display the item numbers
"""
global NumberFont
if NumberFont is not None: return
# this is a really crappy method, but I can't think of any other way
# normal Qt defines Q_WS_WIN and Q_WS_MAC but we don't have that here
s = QtCore.QSysInfo()
if hasattr(s, 'WindowsVersion'):
NumberFont = QtGui.QFont('Tahoma', (7/24) * TileWidth)
elif hasattr(s, 'MacintoshVersion'):
NumberFont = QtGui.QFont('Lucida Grande', (9/24) * TileWidth)
else:
NumberFont = QtGui.QFont('Sans', (8/24) * TileWidth)
def GetDefaultStyle():
"""
Stores a copy of the default app style upon launch, which can then be accessed later
"""
global defaultStyle, defaultPalette, app
if (defaultStyle, defaultPalette) != (None, None): return
defaultStyle = app.style()
defaultPalette = QtGui.QPalette(app.palette())
def GetIcon(name, big=False):
"""
Helper function to grab a specific icon
"""
return theme.GetIcon(name, big)
#####################################################################
########################### VERIFICATIONS ###########################
#####################################################################
def checkContent(data):
if not data.startswith(b'SARC'): return False
required = (b'course/', b'course1.bin')
return all([(r in data) for r in required])
def IsNSMBULevel(filename):
global compressed
"""
Does some basic checks to confirm that a file is a NSMBU level
"""
if not os.path.isfile(filename):
return False
with open(filename, 'rb') as f:
data = f.read()
if nsmbulib.Yaz0.isCompressed(data):
# Probably OK; decompressing it to actually check would
# take too long
return True
else:
return checkContent(data)
def SetDirty(noautosave=False):
global Dirty, DirtyOverride, AutoSaveDirty
if DirtyOverride > 0: return
if not noautosave: AutoSaveDirty = True
if Dirty: return
Dirty = True
try:
mainWindow.UpdateTitle()
except Exception:
pass
def MapPositionToZoneID(zones, x, y, useid=False):
"""
Returns the zone ID containing or nearest the specified position
"""
id = 0
minimumdist = -1
rval = -1
for zone in zones:
r = zone.ZoneRect
if r.contains(x,y) and useid: return zone.id
elif r.contains(x,y) and not useid: return id
xdist = 0
ydist = 0
if x <= r.left(): xdist = r.left() - x
if x >= r.right(): xdist = x - r.right()
if y <= r.top(): ydist = r.top() - y
if y >= r.bottom(): ydist = y - r.bottom()
dist = (xdist ** 2 + ydist ** 2) ** 0.5
if dist < minimumdist or minimumdist == -1:
minimumdist = dist
rval = zone.id
id += 1
return rval
def FilesAreMissing():
"""
Checks to see if any of the required files for Satoru are missing
"""
if not os.path.isdir('satorudata'):
QtWidgets.QMessageBox.warning(None, trans.string('Err_MissingFiles', 0), trans.string('Err_MissingFiles', 1))
return True
required = ['entrances.png', 'entrancetypes.txt', 'icon.png', 'levelnames.xml', 'overrides.png',
'spritedata.xml', 'tilesets.xml', 'about.png', 'spritecategories.xml']
missing = []
for check in required:
if not os.path.isfile('satorudata/' + check):
missing.append(check)
if len(missing) > 0:
QtWidgets.QMessageBox.warning(None, trans.string('Err_MissingFiles', 0), trans.string('Err_MissingFiles', 2, '[files]', ', '.join(missing)))
return True
return False
def isValidGamePath(check='ug'):
"""
Checks to see if the path for NSMBU contains a valid game
"""
if check == 'ug': check = gamedef.GetGamePath()
if check is None or check == '': return False
if not os.path.isdir(check): return False
if not (os.path.isfile(os.path.join(check, '1-1.szs')) or os.path.isfile(os.path.join(check, '1-1.sarc'))): return False
return True
#####################################################################
############################## LOADING ##############################
#####################################################################
def LoadTheme():
"""
Loads the theme
"""
global theme
id = setting('Theme')
if id is None: id = 'Classic'
if id != 'Classic':
path = str('satorudata\\themes\\'+id).replace('\\', '/')
with open(path, 'rb') as f:
theme = SatoruTheme(f)
else: theme = SatoruTheme()
def LoadLevelNames():
"""
Ensures that the level name info is loaded
"""
global LevelNames
# Parse the file
tree = etree.parse(GetPath('levelnames'))
root = tree.getroot()
# Parse the nodes (root acts like a large category)
LevelNames = LoadLevelNames_Category(root)
def LoadLevelNames_Category(node):
"""
Loads a LevelNames XML category
"""
cat = []
for child in node:
if child.tag.lower() == 'category':
cat.append((str(child.attrib['name']), LoadLevelNames_Category(child)))
elif child.tag.lower() == 'level':
cat.append((str(child.attrib['name']), str(child.attrib['file'])))
return tuple(cat)
def LoadObjDescriptions(reload_=False):
"""
Ensures that the object description is loaded
"""
global ObjDesc
if (ObjDesc is not None) and not reload_: return
paths, isPatch = gamedef.recursiveFiles('ts1_descriptions', True)
if isPatch:
new = []
new.append(trans.files['ts1_descriptions'])
for path in paths: new.append(path)
paths = new
ObjDesc = {}
for path in paths:
f = open(path)
raw = [x.strip() for x in f.readlines()]
f.close()
for line in raw:
w = line.split('=')
ObjDesc[int(w[0])] = w[1]
def LoadConstantLists():
"""
Loads some lists of constants
"""
global BgScrollRates
global BgScrollRateStrings
global ZoneThemeValues
global ZoneTerrainThemeValues
global Sprites
global SpriteCategories
BgScrollRates = [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0, 0.0, 1.2, 1.5, 2.0, 4.0]
BgScrollRateStrings = []
s = trans.stringList('BGDlg', 1)
for i in s:
BgScrollRateStrings.append(i)
ZoneThemeValues = trans.stringList('ZonesDlg', 1)
ZoneTerrainThemeValues = trans.stringList('ZonesDlg', 2)
Sprites = None
SpriteListData = None
def LoadSpriteData():
"""
Ensures that the sprite data info is loaded
"""
global Sprites
Sprites = [None] * 724
errors = []
errortext = []
# It works this way so that it can overwrite settings based on order of precedence
paths = []
paths.append((trans.files['spritedata'], None))
for pathtuple in gamedef.multipleRecursiveFiles('spritedata', 'spritenames'): paths.append(pathtuple)
for sdpath, snpath in paths:
# Add XML sprite data, if there is any
if sdpath not in (None, ''):
path = sdpath if isinstance(sdpath, str) else sdpath.path
tree = etree.parse(path)
root = tree.getroot()
for sprite in root:
if sprite.tag.lower() != 'sprite': continue
try: spriteid = int(sprite.attrib['id'])
except ValueError: continue
spritename = sprite.attrib['name']
notes = None
relatedObjFiles = None
if 'notes' in sprite.attrib:
notes = trans.string('SpriteDataEditor', 2, '[notes]', sprite.attrib['notes'])
if 'files' in sprite.attrib:
relatedObjFiles = trans.string('SpriteDataEditor', 8, '[list]', sprite.attrib['files'].replace(';', '<br>'))
sdef = SpriteDefinition()
sdef.id = spriteid
sdef.name = spritename
sdef.notes = notes
sdef.relatedObjFiles = relatedObjFiles
try:
sdef.loadFrom(sprite)
except Exception as e:
errors.append(str(spriteid))
errortext.append(str(e))
Sprites[spriteid] = sdef
# Add TXT sprite names, if there are any
# This code is only ever run when a custom
# gamedef is loaded, because spritenames.txt
# is a file only ever used by custom gamedefs.
if (snpath is not None) and (snpath.path is not None):
snfile = open(snpath.path)
data = snfile.read()