-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClashMusicGui.py
454 lines (363 loc) · 17.4 KB
/
ClashMusicGui.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
""" Corporate Clash Music.JSON editor GUI """
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import ast, builtins, glob, json, os, pathlib, requests, subprocess, sys, traceback
from windows.UIMainWindow import Ui_MainWindow
from windows.UIOverridePicker import Ui_OverrideUI
from windows.UICompileDialog import Ui_CompilingDialog
from windows.UIFilePicker import Ui_FileSelectDial
from Settings import Settings
class ClashMusicGui(QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
super(ClashMusicGui, self).__init__(*args, **kwargs)
builtins.base = self
# Get the path to the Documents library
from sys import platform
import ctypes.wintypes
buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
ctypes.windll.shell32.SHGetFolderPathW(None, 5, None, 0, buf)
print(f"Found windows documents library at {buf.value}")
builtins.userfiles = os.path.join(buf.value, 'OpenToontownTools', 'ClashResourcePackEditor')
if not os.path.exists(userfiles):
pathlib.Path(userfiles).mkdir(parents = True, exist_ok = True)
self.setupSettings()
self.setupUi(self)
self.root = None
self.identifierToLabel = {
'default': {},
'halloween': {},
'christmas': {},
'april-fools': {}
}
self.overrides = {
'halloween': {},
'christmas': {},
'april-fools': {}
}
# load the music.json
self.defaultJson = self.getDefaultJson()
i = 0
for music in self.defaultJson['default']:
# Add a row
rowPos = self.tableWidget.rowCount()
self.tableWidget.insertRow(rowPos)
# Set the first column as the music name
self.tableWidget.setItem(rowPos, 0, QTableWidgetItem(music))
# Create the second column widget
# This widget includes a horizontal layout with 2 items
# a browse button, and the label
widget = QWidget();
# Create the Browse button
browseBtn = QPushButton()
browseBtn.setText("Browse")
browseBtn.setMaximumSize(QSize(60, 34))
# Bind it to a lambda event to pop up a file browser
browseBtn.pressed.connect(lambda i = music: self.selectMusicFile(i))
# Create the label
lbl = QLabel();
# By default, we show the default song
lbl.setText(str(self.defaultJson['default'][music]))
# Add the label to a list of labels for later editing
self.identifierToLabel['default'][music] = lbl
# Make a horizontal layout to put them together
horLay = QHBoxLayout(widget)
horLay.addWidget(browseBtn)
horLay.addWidget(lbl)
horLay.setContentsMargins(0, 0, 0, 0);
widget.setLayout(horLay)
# Set the widget as the contents of the second column
self.tableWidget.setCellWidget(i, 1, widget)
i += 1
# bind the save button to write music.json
self.saveButton.pressed.connect(self.saveFile)
# bind the compile button to build the .mf
self.compileButton.pressed.connect(self.compileMultifile)
self.addOverrideButton_HA.pressed.connect(lambda: self.selectOverride('halloween'))
self.addOverrideButton_WI.pressed.connect(lambda: self.selectOverride('christmas'))
self.addOverrideButton_AF.pressed.connect(lambda: self.selectOverride('april-fools'))
self.optionsBrowsePandaPath.pressed.connect(self.browseForPanda)
self.label_3.setText(settings['panda-path'])
self.browseForRoot()
if not self.root:
sys.exit()
# Clash doesn't have any pack info yet, so we disable this tab for now
self.tabWidget.setTabEnabled(4, False)
# We are done setting up the window
# Now show it
self.show()
def getDefaultJson(self):
print("Downloading latest music.json file")
try:
req = requests.get('https://raw.githubusercontent.com/OpenToontownTools/ClashMusicGUI/master/music.json')
print("Download complete")
with open('default.json', 'w') as cache:
cache.writelines(req.text)
return req.json()
except:
QMessageBox.warning(self, "Clash Resource Pack Editor",
"Unable to download latest default music.json file\nCheck your internet connection.\nUsing latest cached download.")
print("using cached version")
return json.load(open('default.json'))
def setupSettings(self):
builtins.settings = Settings(f'{userfiles}/config.ott')
if 'panda-path' not in settings:
settings['panda-path'] = 'None'
def selectOverride(self, holiday: str):
self.dial = OverridePopup()
self.dial.buttonBox.accepted.connect(lambda: self.addOverride(holiday, self.dial.listWidget.selectedItems()))
for music in self.defaultJson['default']:
if not music in self.identifierToLabel[holiday]:
self.dial.listWidget.addItem(QListWidgetItem(music))
self.dial.exec_()
def addOverride(self, holiday: str, musics):
for music in musics:
identifier = music.text()
self.addOverrideToTable(holiday, identifier, 'None')
self.dial.close()
def addOverrideToTable(self, holiday, identifier: str, file: str):
# todo:put the defualt stuff here too
tables = {
'halloween': self.overrideTable_HA,
'christmas': self.overrideTable_WI,
'april-fools': self.overrideTable_AF
}
table = tables[holiday]
rowPos = table.rowCount()
table.insertRow(rowPos)
# Set the first column as the music name
table.setItem(rowPos, 0, QTableWidgetItem(identifier))
# Create the second column widget
# This widget includes a horizontal layout with 2 items
# a browse button, and the label
widget = QWidget();
# Create the Browse button
browseBtn = QPushButton()
browseBtn.setText('Browse')
browseBtn.setMaximumSize(QSize(60, 34))
# Bind it to a lambda event to pop up a file browser
browseBtn.pressed.connect(lambda i = identifier: self.selectMusicFile(i, holiday))
# Create the label
lbl = QLabel();
# Set the text as the file(s)
lbl.setText(str(file))
# Add the label to a list of labels for later editing
self.identifierToLabel[holiday][identifier] = lbl
# Make a horizontal layout to put them together
horLay = QHBoxLayout(widget)
horLay.addWidget(browseBtn)
horLay.addWidget(lbl)
if holiday != 'default':
removeBtn = QPushButton()
removeBtn.setText('Remove')
removeBtn.setMaximumSize(QSize(60, 34))
removeBtn.pressed.connect(lambda i = identifier: self.removeOverride(i, holiday))
horLay.addWidget(removeBtn)
horLay.setContentsMargins(0, 0, 0, 0);
widget.setLayout(horLay)
# Set the widget as the contents of the second column
table.setCellWidget(rowPos, 1, widget)
def browseForRoot(self):
lastpath = settings['last-path'] if 'last-path' in settings else ""
path = QFileDialog.getExistingDirectory(self, "Browse for Root Directory", lastpath)
self.root = path
if not self.root: return
settings['last-path'] = path
self.rootDisplay.setText(path)
# Detect existing music.json file
try:
if os.path.exists(f'{self.root}/audio/music.json'):
# If it exists, open and do everything
with open(f'{self.root}/audio/music.json') as jsonfile:
data = json.load(jsonfile)
if 'default' in data:
for identifier in data['default']:
self.updateLabel('default', identifier, data['default'][identifier])
for holiday in ['halloween', 'christmas', 'april-fools']:
if holiday in data:
for identifier in data[holiday]:
self.addOverrideToTable(holiday, identifier, data[holiday][identifier])
except Exception as e:
# if theres an error loading, pop up an issue
# we can reuse compiledialog since its perfect for what we need
dial = CompileDialog()
tb = traceback.format_exc().replace("\n", "<br>").replace(" ", " ")
dial.output.setText(f'<h1>Error loading music.json</h1><br><h3>{e}</h3><br><br><h3>Traceback:</h3>{tb}')
dial.buttonBox.setEnabled(True)
dial.buttonBox.accepted.connect(lambda: subprocess.run(
['explorer.exe', '/select,', os.path.normpath(self.root) + f'\\audio\\music.json']))
dial.exec_()
sys.exit()
def updateLabel(self, holiday, identifier, text):
# self.identifierToLabel[holiday][identifier].setText(text)
if holiday == 'default':
if text == self.defaultJson[holiday][identifier]:
self.identifierToLabel[holiday][identifier].setText(text)
else:
self.identifierToLabel[holiday][identifier].setText(f"<i>{text}</i>")
else:
self.identifierToLabel[holiday][identifier].setText(text)
def removeOverride(self, identifier, holiday):
self.updateLabel(holiday, identifier, 'None')
tables = {
'halloween': self.overrideTable_HA,
'christmas': self.overrideTable_WI,
'april-fools': self.overrideTable_AF
}
table = tables[holiday]
rowNum = -1
for row in range(table.rowCount()):
idCol = table.item(row, 0)
if idCol.text() == identifier:
print(f'found identifier on row {row}')
rowNum = row
break
table.removeRow(rowNum)
del self.identifierToLabel[holiday][identifier]
def saveFile(self):
# If the user hasn't selected a root, we tell them they need to
if not self.root:
QMessageBox.warning(self, "ClashMusicGui",
"You need to specify a pack root!\nClick the '...' button in the bottom left")
return
with open(f'{self.root}/audio/music.json', 'w') as output:
data = {
# This doesn't work right now, it prevents the file from loading in clash for some reason
# '_OpenToontownTools': "This file was generated using the Clash Music GUI. https://github.com/OpenToontownTools/ClashMusicGUI",
'default': {},
'halloween': {},
'christmas': {},
'april-fools': {}
}
tables = {
'default': self.tableWidget,
'halloween': self.overrideTable_HA,
'christmas': self.overrideTable_WI,
'april-fools': self.overrideTable_AF
}
for holiday in tables:
for row in range(tables[holiday].rowCount()):
identifier = tables[holiday].item(row, 0).text()
file = self.identifierToLabel[holiday][identifier].text().replace('<i>', '').replace('</i>', '')
if '[' in file:
file = ast.literal_eval(file)
if file != self.defaultJson['default'][identifier] or holiday != 'default':
data[holiday][identifier] = file
for type in ['default', 'halloween', 'christmas', 'april-fools']:
if len(data[type]) == 0:
del data[type]
output.writelines(json.dumps(data, indent = 4, sort_keys = True))
QMessageBox.information(self, "Corporate Clash music.json Editor", "Saved!")
def compileMultifile(self):
if not os.path.exists(settings['panda-path']):
QMessageBox.warning(self, "ClashMusicGui", "You need to select your Panda3D directory in the OPTIONS tab!")
return
self.saveFile()
packname, _ = QInputDialog.getText(self, "Pack File Name", "Enter a pack filename",
text = os.path.basename(self.root))
args = [
f"{settings['panda-path']}/bin/multify.exe",
'-c', f'-f{packname}.mf']
# Include all folders / files inside the root
for path in glob.glob(f'{self.root}/*'):
# except for .mf files - its likely a previous compiled verison
if os.path.splitext(path)[1] == '.mf':
continue
args.append(os.path.basename(path))
process = subprocess.run(args, shell = True, cwd = self.root, stderr = subprocess.PIPE,
universal_newlines = True)
dial = CompileDialog()
print(process.stderr)
out = process.stderr.replace('\n', '<br>')
dial.output.setText(
f'<h2>Command Args</h2>{process.args}<br><h2>Output</h2>{out}<br><h2>Compiling Finished!</h2>')
dial.buttonBox.setEnabled(True)
dial.buttonBox.accepted.connect(
lambda: subprocess.run(['explorer.exe', '/select,', os.path.normpath(self.root) + f'\\{packname}.mf']))
dial.exec_()
def selectMusicFile(self, identifier: str, holiday: str = 'default'):
# If the user hasn't selected a root, we tell them they need to
if not self.root:
QMessageBox.warning(self, "ClashMusicGui",
"You need to specify a pack root!\nClick the '...' button in the bottom left")
return
dial = FileSelector(identifier = identifier, holiday = holiday)
# exec_ returns 0 if the user his cancel, we want to know that
res = dial.exec_()
if dial.getSelectedMusic() and res:
self.updateLabel(holiday, identifier, dial.getSelectedMusic())
def browseForPanda(self):
settings['panda-path'] = QFileDialog.getExistingDirectory(self, "Browse for Panda3D Root Directory", "C:/")
self.label_3.setText(settings['panda-path'])
class OverridePopup(QDialog, Ui_OverrideUI):
def __init__(self, *args, **kwargs):
super(OverridePopup, self).__init__(*args, **kwargs)
self.setupUi(self)
self.show()
class CompileDialog(QDialog, Ui_CompilingDialog):
def __init__(self, *args, **kwargs):
super(CompileDialog, self).__init__(*args, **kwargs)
self.setupUi(self)
self.setWindowFlags(Qt.Window | Qt.WindowMinimizeButtonHint)
self.show()
class FileSelector(QDialog, Ui_FileSelectDial):
def __init__(self, identifier, holiday, *args, **kwargs):
super(FileSelector, self).__init__(*args, **kwargs)
self.setupUi(self)
self.setWindowFlags(Qt.Window | Qt.WindowMinimizeButtonHint)
self.identifier = identifier
self.holiday = holiday
self.selectedMusic = None
self.pushButton.pressed.connect(self.manualInput)
# Browse Button
self.pushButton_2.pressed.connect(self.browseForFile)
# Set as none
self.pushButton_4.pressed.connect(self.disableTrack)
self.show()
def disableTrack(self):
""" Sets the selected music as the NONE string, which clash can read """
self.selectedMusic = 'None'
self.selectedLabel.setText('DISABLED')
def setSelectedMusic(self, music: str):
self.selectedMusic = music
self.selectedLabel.setText(self.selectedMusic)
def getSelectedMusic(self):
return self.selectedMusic
def manualInput(self):
path, _ = QInputDialog.getText(self, "Manual Input", "Enter music location(s)")
if path:
self.setSelectedMusic(path)
def browseForFile(self):
# to allow the user to select multiple files, we use getopenfilenames
path, _ = QFileDialog.getOpenFileNames(self, "Browse for OGG file(s)", base.root, "OGG Audio Files (*.ogg)")
# The user has selected more than one file
if len(path) > 1:
newpath = []
for p in path:
# Make sure the song is INSIDE of the content pack
if not p.startswith(base.root):
dial = QMessageBox(self)
dial.setWindowTitle("ClashMusicGui")
dial.setText("You need to select a file inside the content pack!")
dial.exec_()
return
newpath.append(p.replace(base.root + '/', ''))
path = str(newpath)
# The user has selected one file
if len(path) == 1:
path = path[0]
if not path.startswith(base.root):
dial = QMessageBox(self)
dial.setWindowTitle("ClashMusicGui")
dial.setText("You need to select a file inside the content pack!")
dial.exec_()
return
path = path.replace(base.root + '/', '')
# The user selected nothing, so we cancel
if len(path) == 0:
return
self.setSelectedMusic(path)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = ClashMusicGui()
app.exec_()