-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathui.py
More file actions
472 lines (392 loc) · 17.6 KB
/
ui.py
File metadata and controls
472 lines (392 loc) · 17.6 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
from PyQt6 import QtGui, QtWidgets, QtCore
from xml.etree import ElementTree
import os
import globals_
from dirty import setting
def LoadTheme():
"""
Loads the theme
"""
globals_.theme = ReggieTheme(setting("Theme", "Classic"))
class ReggieTheme:
"""
Class that represents a Reggie theme
"""
def __init__(self, folder=None):
"""
Initializes the theme
"""
self.initAsClassic()
if folder and folder != "Classic": self.initFromFolder(folder)
def initAsClassic(self):
"""
Initializes the theme as the hardcoded Classic theme
"""
self.fileName = 'Classic'
self.styleSheet = ''
self.formatver = 1.0
self.version = 1.0
self.themeName = globals_.trans.string('Themes', 0)
self.creator = globals_.trans.string('Themes', 1)
self.description = globals_.trans.string('Themes', 2)
self.iconCacheSm = {}
self.iconCacheLg = {}
self.style = None
self.forceUiColor = False
self.forceStyleSheet = False
self.useRoundedRectangles = True
self.overridesFile = os.path.join('reggiedata', 'overrides.png')
# Add the colors # 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
'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
'object_lines_r': QtGui.QColor(0, 148, 255), # Clicked object corner
'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 initFromFolder(self, folder):
"""
Initializes the theme from the folder
"""
folder = os.path.join('reggiedata', 'themes', folder)
fileList = os.listdir(folder)
# Create a XML ElementTree
maintree = ElementTree.parse(os.path.join(folder, 'main.xml'))
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
self.loadColorsXml(os.path.join(folder, node.attrib['file']))
elif node.tag.lower() == 'qss':
if 'file' not in node.attrib: continue
# Load the style sheet
self.loadStyleSheet(os.path.join(folder, node.attrib['file']))
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 fileList:
iconname = iconfilename
if not iconname.startswith(foldername + os.sep): 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')]
with open(os.path.join(folder, iconfilename), "rb") as inf:
icodata = inf.read()
pix = QtGui.QPixmap()
if not pix.loadFromData(icodata): continue
ico = QtGui.QIcon(pix)
cache[iconname] = ico
elif node.tag.lower() == 'overrides':
fn = node.attrib['file']
if not fn.endswith('.png'):
continue
filename = os.path.join(folder, fn)
if not os.path.isfile(filename):
continue
self.overridesFile = filename
## # Add some overview colors if they weren't specified
## fallbacks = {
## 'overview_entrance': 'entrance_fill',
## 'overview_location_fill': 'location_fill',
## 'overview_location_lines': 'location_lines',
## 'overview_sprite': 'sprite_fill',
## 'overview_zone_lines': 'zone_lines',
## }
## for index in fallbacks:
## if (index not in colors) and (fallbacks[index] in colors): colors[index] = colors[fallbacks[index]]
##
## # Use the new colors dict to overwrite values in self.colors
## for index in colors:
## self.colors[index] = colors[index]
def parseMainXMLHead(self, root):
"""
Parses the main attributes of main.xml
"""
MaxSupportedXMLVersion = 1.0
self.styleSheet = ''
# 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 = root.get("creator", globals_.trans.string("Themes", 3))
self.description = root.get("description", globals_.trans.string("Themes", 4))
self.style = root.get("style")
self.forceUiColor = root.get("forceUiColor", "false") == "true"
self.forceStyleSheet = root.get("forceStyleSheet", "false") == "true"
self.useRoundedRectangles = root.get("useRoundedRectangles", "true") == "true"
try:
self.version = float(root.get("version", "1.0"))
except ValueError:
self.version = 1.0
return True
def loadColorsXml(self, file):
"""
Loads a colors.xml file
"""
try:
tree = ElementTree.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 style.qss file
"""
with open(file, 'r', encoding='utf-8') as inf:
style = inf.read()
self.styleSheet = style
def color(self, name):
"""
Returns a color
"""
try:
return self.colors[name]
except KeyError:
return None
def GetIcon(self, name, big=False):
"""
Returns an icon
"""
cache = self.iconCacheLg if big else self.iconCacheSm
if name not in cache:
path = os.path.join('reggiedata', 'ico', 'lg' if big else 'sm', 'icon-')
path += name
cache[name] = QtGui.QIcon(path)
return cache[name]
class IconsOnlyTabBar(QtWidgets.QTabBar):
"""
A QTabBar subclass that is designed to only display icons.
On macOS Mojave (and probably other versions around there),
QTabWidget tabs are way too wide when only displaying icons.
This ultimately causes the Reggie palette itself to have a really
high minimum width.
This subclass limits tab widths to fix the problem.
"""
def tabSizeHint(self, index):
res = super(IconsOnlyTabBar, self).tabSizeHint(index)
if globals_.app.style().metaObject().className() == 'QMacStyle':
res.setWidth(res.height() * 2)
return res
# Related functions
def SetAppStyle(styleKey=''):
"""
Set the application window color
"""
# Change the color if applicable
if globals_.theme.color('ui') is not None and not globals_.theme.forceStyleSheet:
globals_.app.setPalette(QtGui.QPalette(globals_.theme.color('ui')))
# Change the style
if not styleKey: styleKey = setting('uiStyle', "Fusion")
style = QtWidgets.QStyleFactory.create(styleKey)
globals_.app.setStyle(style)
# Apply the style sheet, if exists
if globals_.theme.styleSheet:
globals_.app.setStyleSheet(globals_.theme.styleSheet)
# Manually set the background color
if globals_.theme.forceUiColor and not globals_.theme.forceStyleSheet:
color = globals_.theme.color('ui').getRgb()
bgColor = "#%02x%02x%02x" % tuple(map(lambda x: x // 2, color[:3]))
globals_.app.setStyleSheet("""
QListView, QTreeWidget, QLineEdit, QDoubleSpinBox, QSpinBox, QTextEdit, QPlainTextEdit{
background-color: %s;
}""" % bgColor)
def GetIcon(name, big=False):
"""
Helper function to grab a specific icon
"""
return globals_.theme.GetIcon(name, big)
def createHorzLine():
f = QtWidgets.QFrame()
f.setFrameStyle(QtWidgets.QFrame.Shape.HLine | QtWidgets.QFrame.Shadow.Sunken)
return f
def createVertLine():
f = QtWidgets.QFrame()
f.setFrameStyle(QtWidgets.QFrame.Shape.VLine | QtWidgets.QFrame.Shadow.Sunken)
return f
def LoadNumberFont():
"""
Creates a valid font we can use to display the item numbers
"""
if globals_.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'):
globals_.NumberFont = QtGui.QFont('Tahoma', 7)
elif hasattr(s, 'MacintoshVersion'):
globals_.NumberFont = QtGui.QFont('Lucida Grande', 9)
else:
globals_.NumberFont = QtGui.QFont('Sans', 8)
def clipStr(text, idealWidth, font=None):
"""
Returns a shortened string, or None if it need not be shortened
"""
if font is None: font = QtGui.QFont()
width = QtGui.QFontMetrics(font).horizontalAdvance(text)
if width <= idealWidth: return None
# note that Qt has a builtin function for this:
# QFontMetricsF::elidedText(text, Qt.TextElideMode.ElideNone, idealWidth)
while width > idealWidth:
text = text[:-1]
width = QtGui.QFontMetrics(font).horizontalAdvance(text)
return text
class HexSpinBox(QtWidgets.QSpinBox):
class HexValidator(QtGui.QValidator):
def __init__(self, min, max):
QtGui.QValidator.__init__(self)
self.valid = set('0123456789abcdef')
self.min = min
self.max = max
def validate(self, input, pos):
try:
input = str(input).lower()
except Exception:
return (self.State.Invalid, input, pos)
valid = self.valid
for char in input:
if char not in valid:
return (self.State.Invalid, input, pos)
try:
value = int(input, 16)
except ValueError:
# If value == '' it raises ValueError
return (self.State.Invalid, input, pos)
if value < self.min or value > self.max:
return (self.State.Intermediate, input, pos)
return (self.State.Acceptable, input, pos)
def __init__(self, format='%04X', *args):
self.format = format
QtWidgets.QSpinBox.__init__(self, *args)
self.validator = self.HexValidator(self.minimum(), self.maximum())
def setMinimum(self, value):
self.validator.min = value
QtWidgets.QSpinBox.setMinimum(self, value)
def setMaximum(self, value):
self.validator.max = value
QtWidgets.QSpinBox.setMaximum(self, value)
def setRange(self, min, max):
self.validator.min = min
self.validator.max = max
QtWidgets.QSpinBox.setMinimum(self, min)
QtWidgets.QSpinBox.setMaximum(self, max)
def validate(self, text, pos):
return self.validator.validate(text, pos)
def textFromValue(self, value):
return self.format % value
def valueFromText(self, value):
return int(str(value), 16)
class ListWidgetWithToolTipSignal(QtWidgets.QListWidget):
"""
A QtWidgets.QListWidget that includes a signal that
is emitted when a tooltip is about to be shown. Useful
for making tooltips that update every time you show
them.
"""
toolTipAboutToShow = QtCore.pyqtSignal(QtWidgets.QListWidgetItem)
def viewportEvent(self, e):
"""
Handles viewport events
"""
if e.type() == e.Type.ToolTip:
item = self.itemFromIndex(self.indexAt(e.pos()))
if item is not None:
self.toolTipAboutToShow.emit(item)
return super().viewportEvent(e)