-
Notifications
You must be signed in to change notification settings - Fork 8
/
__init__.py
1905 lines (1449 loc) · 67.8 KB
/
__init__.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
import time
import json
import re
import os
import subprocess
import sys
from xml.sax.saxutils import escape
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from .classes import *
from .editor import *
from . import widgets
from .utils import *
DCC = os.getenv("RIG_BUILDER_DCC") or "maya"
ParentWindow = None
if DCC == "maya":
import maya.cmds as cmds
import maya.OpenMayaUI as omui
import maya.OpenMaya as om
from shiboken2 import wrapInstance
ParentWindow = wrapInstance(int(omui.MQtUtil.mainWindow()), QMainWindow)
updateFilesThread = None
def sendToServer(module):
'''
Send module to server with SVN, Git, Perforce or other VCS.
'''
module.sendToServer() # rewrite file on server
return True
def updateFilesFromServer():
def update():
'''
Update files from server with SVN, Git, Perforce or other VCS.
'''
pass
global updateFilesThread
if not updateFilesThread or not updateFilesThread.isRunning():
updateFilesThread = MyThread(update)
updateFilesThread.start()
class MyThread(QThread):
def __init__(self, runFunction):
super().__init__()
self.runFunction = runFunction
def run(self):
self.runFunction()
class AttributesWidget(QWidget):
def __init__(self, moduleItem, attributes, *, mainWindow=None, **kwargs):
super().__init__(**kwargs)
self.mainWindow = mainWindow
self.moduleItem = moduleItem
self._attributeAndWidgets = [] # [attribute, nameWidget, templateWidget]
layout = QGridLayout()
layout.setDefaultPositioning(2, Qt.Horizontal)
layout.setColumnStretch(1, 1)
self.setLayout(layout)
def executor(cmd, env=None):
envUI = self.mainWindow.getEnvUI()
Module.env = envUI # update environment for runtime modules
localEnv = dict(envUI)
localEnv.update(self.moduleItem.module.getEnv())
localEnv.update(env or {})
with captureOutput(self.mainWindow.logWidget):
try:
exec(cmd, localEnv)
except Exception as e:
print("Error: "+str(e))
self.mainWindow.showLog()
else:
if cmd: # in case command is specified, no command can be used for obtaining completions
self.updateWidgets()
self.updateWidgetStyles()
return localEnv
for idx, a in enumerate(attributes):
templateWidget = widgets.TemplateWidgets[a.template()](executor=executor)
nameWidget = QLabel(a.name())
self._attributeAndWidgets.append((a, nameWidget, templateWidget))
self.updateWidget(idx)
self.updateWidgetStyle(idx)
templateWidget.somethingChanged.connect(lambda idx=idx: self.widgetOnChange(idx))
nameWidget.setAlignment(Qt.AlignRight)
nameWidget.setStyleSheet("QLabel:hover:!pressed{ background-color: #666666; }")
nameWidget.contextMenuEvent = lambda event, idx=idx: self.nameContextMenuEvent(event, idx)
layout.addWidget(nameWidget)
layout.addWidget(templateWidget)
layout.addWidget(QLabel())
layout.setRowStretch(layout.rowCount(), 1)
def connectionMenu(self, menu, module, attrWidgetIndex, path="/"):
attr, _, _ = self._attributeAndWidgets[attrWidgetIndex]
subMenu = QMenu(module.name())
for a in module.attributes():
if a.template() == attr.template() and a.name(): # skip empty names as well
subMenu.addAction(a.name(), Callback(self.connectAttr, path+module.name()+"/"+a.name(), attrWidgetIndex))
for ch in module.children():
self.connectionMenu(subMenu, ch, attrWidgetIndex, path+module.name()+"/")
if subMenu.actions():
menu.addMenu(subMenu)
def nameContextMenuEvent(self, event, attrWidgetIndex):
attr, _, _ = self._attributeAndWidgets[attrWidgetIndex]
menu = QMenu(self)
if self.moduleItem and self.moduleItem.parent():
makeConnectionMenu = menu.addMenu("Make connection")
for a in self.moduleItem.module.parent().attributes():
if a.template() == attr.template() and a.name(): # skip empty names as well
makeConnectionMenu.addAction(a.name(), Callback(self.connectAttr, "/"+a.name(), attrWidgetIndex))
for ch in self.moduleItem.module.parent().children():
if ch is not self.moduleItem.module:
self.connectionMenu(makeConnectionMenu, ch, attrWidgetIndex)
if attr.connect():
menu.addAction("Break connection", Callback(self.disconnectAttr, attrWidgetIndex))
menu.addSeparator()
menu.addAction("Edit data", Callback(self.editData, attrWidgetIndex))
menu.addSeparator()
menu.addAction("Edit expression", Callback(self.editExpression, attrWidgetIndex))
if attr.expression():
menu.addAction("Evaluate expression", Callback(self.updateWidget, attrWidgetIndex))
menu.addAction("Clear expression", Callback(self.clearExpression, attrWidgetIndex))
menu.addSeparator()
menu.addAction("Expose", Callback(self.exposeAttr, attrWidgetIndex))
menu.addSeparator()
menu.addAction("Reset", Callback(self.resetAttr, attrWidgetIndex))
menu.popup(event.globalPos())
def _wrapper(f):
def inner(self, attrWidgetIndex, *args, **kwargs):
attr, _, widget = self._attributeAndWidgets[attrWidgetIndex]
with captureOutput(self.mainWindow.logWidget):
try:
return f(self, attrWidgetIndex, *args, **kwargs)
except Exception as e:
print("Error: {}.{}: {}".format(self.moduleItem.module.name(), attr.name(), str(e)))
if type(e) == AttributeResolverError:
widget.blockSignals(True)
widget.setJsonData(attr.localData())
widget.blockSignals(False)
self.mainWindow.showLog()
return inner
@_wrapper
def widgetOnChange(self, attrWidgetIndex):
attr, _, widget = self._attributeAndWidgets[attrWidgetIndex]
widgetData = widget.getJsonData()
attr.setData(widgetData) # implicitly push
previousData = {id(a):a.localData() for a in self.moduleItem.module.attributes()}
modifiedAttrs = []
for otherAttr in self.moduleItem.module.attributes():
otherAttr.pull()
if otherAttr.localData() != previousData[id(otherAttr)]:
modifiedAttrs.append(otherAttr)
for idx, (otherAttr, _, otherWidget) in enumerate(self._attributeAndWidgets): # update attributes' widgets
if otherAttr in modifiedAttrs:
with blockedWidgetContext(otherWidget) as w:
w.setJsonData(otherAttr.localData())
self.updateWidgetStyle(idx)
if id(attr) not in modifiedAttrs: # update the modification style anyway
self.updateWidgetStyle(attrWidgetIndex)
@_wrapper
def updateWidget(self, attrWidgetIndex):
attr, _, widget = self._attributeAndWidgets[attrWidgetIndex]
with blockedWidgetContext(widget) as w:
w.setJsonData(attr.data()) # pull data
def updateWidgets(self):
for i in range(len(self._attributeAndWidgets)):
self.updateWidget(i)
def updateWidgetStyle(self, attrWidgetIndex):
attr, nameWidget, widget = self._attributeAndWidgets[attrWidgetIndex]
style = ""
tooltip = []
if attr.connect():
tooltip.append("Connect: "+attr.connect())
if attr.expression():
tooltip.append("Expression:\n" + attr.expression())
if attr.connect() and not attr.expression(): # only connection
style = "TemplateWidget { border: 4px solid #6e6e39; background-color: #6e6e39 }"
elif attr.expression() and not attr.connect(): # only expression
style = "TemplateWidget { border: 4px solid #632094; background-color: #632094 }"
elif attr.expression() and attr.connect(): # both
style = "TemplateWidget { border: 4px solid rgb(0,0,0,0); background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2:0, stop: 0 #6e6e39, stop: 1 #632094);}"
nameWidget.setText(attr.name()+("*" if attr.modified() else ""))
widget.setStyleSheet(style)
widget.setToolTip("\n".join(tooltip))
def updateWidgetStyles(self):
for i in range(len(self._attributeAndWidgets)):
self.updateWidgetStyle(i)
def exposeAttr(self, attrWidgetIndex):
attr, _, _ = self._attributeAndWidgets[attrWidgetIndex]
if not self.moduleItem.module.parent():
QMessageBox.warning(self, "Rig Builder", "Can't expose attribute to parent: no parent module")
return
if self.moduleItem.module.parent().findAttribute(attr.name()):
QMessageBox.warning(self, "Rig Builder", "Can't expose attribute to parent: attribute already exists")
return
doUsePrefix = QMessageBox.question(self, "Rig Builder", "Use prefix for the exposed attribute name?", QMessageBox.Yes and QMessageBox.No, QMessageBox.Yes) == QMessageBox.Yes
prefix = self.moduleItem.module.name() + "_" if doUsePrefix else ""
expAttr = attr.copy()
expAttr.setName(prefix + expAttr.name())
self.moduleItem.module.parent().addAttribute(expAttr)
self.connectAttr("/"+expAttr.name(), attrWidgetIndex)
@_wrapper
def editData(self, attrWidgetIndex):
def save(data):
@AttributesWidget._wrapper
def _save(_, attrWidgetIndex):
attr.setData(data[0]) # use [0] because data is a list
self.updateWidget(attrWidgetIndex)
self.updateWidgetStyle(attrWidgetIndex)
_save(self, attrWidgetIndex)
attr, _, _ = self._attributeAndWidgets[attrWidgetIndex]
w = widgets.EditJsonDialog(attr.localData(), title="Edit data")
w.saved.connect(save)
w.show()
def editExpression(self, attrWidgetIndex):
def save(text):
attr.setExpression(text)
self.updateWidgets()
self.updateWidgetStyle(attrWidgetIndex)
attr, _, _ = self._attributeAndWidgets[attrWidgetIndex]
words = set(self.mainWindow.getEnvUI().keys()) | set(self.moduleItem.module.getEnv().keys())
placeholder = '# Example: value = ch("../someAttr") + 1 or data["items"] = [1,2,3]'
w = widgets.EditTextDialog(attr.expression(), title="Edit expression for '{}'".format(attr.name()), placeholder=placeholder, words=words, python=True)
w.saved.connect(save)
w.show()
def clearExpression(self, attrWidgetIndex):
attr, _, _ = self._attributeAndWidgets[attrWidgetIndex]
attr.setExpression("")
self.updateWidgetStyle(attrWidgetIndex)
def resetAttr(self, attrWidgetIndex):
attr, _, _ = self._attributeAndWidgets[attrWidgetIndex]
tmp = widgets.TemplateWidgets[attr.template()]()
attr.setConnect("")
attr.setData(tmp.getDefaultData())
self.updateWidget(attrWidgetIndex)
self.updateWidgetStyle(attrWidgetIndex)
def disconnectAttr(self, attrWidgetIndex):
attr, _, _ = self._attributeAndWidgets[attrWidgetIndex]
attr.setConnect("")
self.updateWidgetStyle(attrWidgetIndex)
def connectAttr(self, connect, attrWidgetIndex):
attr, _, _ = self._attributeAndWidgets[attrWidgetIndex]
attr.setConnect(connect)
self.updateWidget(attrWidgetIndex)
self.updateWidgetStyle(attrWidgetIndex)
class AttributesTabWidget(QTabWidget):
def __init__(self, moduleItem, *, mainWindow=None, **kwargs):
super().__init__(**kwargs)
self.mainWindow = mainWindow
self.moduleItem = moduleItem
self.tabsAttributes = {}
self._attributesWidget = None
self.searchAndReplaceDialog = SearchReplaceDialog(["In all tabs"])
self.searchAndReplaceDialog.onReplace.connect(self.onReplace)
self.currentChanged.connect(self.tabChanged)
self.updateTabs()
def contextMenuEvent(self, event):
menu = QMenu(self)
if self.moduleItem:
menu.addAction("Edit attributes", self.editAttributes)
menu.addSeparator()
menu.addAction("Replace in values", self.searchAndReplaceDialog.exec_)
menu.popup(event.globalPos())
def editAttributes(self):
dialog = EditAttributesDialog(self.moduleItem, self.currentIndex(), parent=mainWindow)
dialog.exec_()
self.mainWindow.codeEditorWidget.updateState()
self.updateTabs()
def onReplace(self, old, new, opts):
def replaceStringInData(data, old, new):
try:
return json.loads(json.dumps(data).replace(old,new))
except ValueError:
return data
if opts.get("In all tabs"):
attributes = []
for attrs in self.tabsAttributes.values(): # merge all attributes
attributes.extend(attrs)
else:
attributes = self.tabsAttributes[self.tabText(self.currentIndex())]
for attr in attributes:
v = replaceStringInData(attr.get(), old, new)
attr.set(v)
self.updateTabs()
def tabChanged(self, idx):
if self.count() == 0:
return
idx = clamp(idx, 0, self.count()-1)
title = self.tabText(idx)
scrollArea = self.widget(idx)
self._attributesWidget = AttributesWidget(self.moduleItem, self.tabsAttributes[title], mainWindow=self.mainWindow)
scrollArea.setWidget(self._attributesWidget)
self.setCurrentIndex(idx)
def updateTabs(self):
oldIndex = self.currentIndex()
oldCount = self.count()
self._attributesWidget = None
self.tabsAttributes.clear()
if not self.moduleItem:
return
self.blockSignals(True)
tabTitlesInOrder = []
for a in self.moduleItem.module.attributes():
if a.category() not in self.tabsAttributes:
self.tabsAttributes[a.category()] = []
tabTitlesInOrder.append(a.category())
self.tabsAttributes[a.category()].append(a)
for t in tabTitlesInOrder:
scrollArea = QScrollArea() # empty, in tabChanged actual widget is set
scrollArea.setWidgetResizable(True)
self.addTab(scrollArea, t) # add new tabs in front of the old ones
# remove previous tabs
for _ in range(oldCount):
w = self.widget(0)
if w:
w.deleteLater()
self.removeTab(0)
if self.count() == 1:
self.tabBar().hide()
else:
self.tabBar().show()
self.tabChanged(oldIndex)
self.blockSignals(False)
def updateWidgetStyles(self):
if self._attributesWidget:
self._attributesWidget.updateWidgetStyles()
class ModuleListDialog(QDialog):
moduleSelected = Signal(str) # file path
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.setWindowTitle("Module Selector")
layout = QVBoxLayout()
self.setLayout(layout)
gridLayout = QGridLayout()
gridLayout.setDefaultPositioning(2, Qt.Horizontal)
self.updateSourceWidget = QComboBox()
self.updateSourceWidget.addItems(["All", "Server", "Local", "None"])
self.updateSourceWidget.setCurrentIndex({"all":0, "server": 1, "local": 2, "": 3}[Module.UpdateSource])
self.updateSourceWidget.currentIndexChanged.connect(lambda _=None: self.updateSource())
self.modulesFromWidget = QComboBox()
self.modulesFromWidget.addItems(["Server", "Local"])
self.modulesFromWidget.currentIndexChanged.connect(lambda _=None: self.maskChanged())
self.maskWidget = QLineEdit()
self.maskWidget.textChanged.connect(self.maskChanged)
gridLayout.addWidget(QLabel("Update source"))
gridLayout.addWidget(self.updateSourceWidget)
gridLayout.addWidget(QLabel("Modules from"))
gridLayout.addWidget(self.modulesFromWidget)
gridLayout.addWidget(QLabel("Filter"))
gridLayout.addWidget(self.maskWidget)
self.treeWidget = QTreeWidget()
self.treeWidget.setHeaderLabels(["Module", "Modification time"])
self.treeWidget.itemActivated.connect(self.treeItemActivated)
self.treeWidget.header().setSectionResizeMode(QHeaderView.ResizeToContents)
self.treeWidget.setSortingEnabled(True)
self.treeWidget.sortItems(1, Qt.AscendingOrder)
self.treeWidget.contextMenuEvent = self.treeContextMenuEvent
self.loadingLabel = QLabel("Pulling modules from server...")
self.loadingLabel.hide()
layout.addLayout(gridLayout)
layout.addWidget(self.treeWidget)
layout.addWidget(self.loadingLabel)
self.maskWidget.setFocus()
def showEvent(self, event):
pos = self.mapToParent(self.mapFromGlobal(QCursor.pos()))
self.setGeometry(pos.x(), pos.y(), 600, 400)
# update files from server
self.loadingLabel.show()
updateFilesFromServer()
def f():
Module.updateUidsCache()
self.loadingLabel.hide()
self.maskChanged()
updateFilesThread.finished.connect(f)
self.maskWidget.setFocus()
def treeContextMenuEvent(self, event):
menu = QMenu(self)
menu.addAction("Locate", self.browseModuleDirectory)
menu.popup(event.globalPos())
def browseModuleDirectory(self):
for item in self.treeWidget.selectedItems():
if item.childCount() == 0: # files only
subprocess.call("explorer /select,\"{}\"".format(os.path.normpath(item.filePath)))
def treeItemActivated(self, item, _):
if item.childCount() == 0:
self.moduleSelected.emit(item.filePath)
self.done(0)
def updateSource(self):
updateSource = self.updateSourceWidget.currentIndex()
UpdateSourceFromInt = {0: "all", 1: "server", 2: "local", 3: ""}
Module.UpdateSource = UpdateSourceFromInt[updateSource]
def maskChanged(self):
def findChildByText(text, parent, column=0):
for i in range(parent.childCount()):
ch = parent.child(i)
if text == ch.text(column):
return ch
modulesFrom = self.modulesFromWidget.currentIndex()
modulesDirectory = RigBuilderPath+"\\modules" if modulesFrom == 0 else RigBuilderLocalPath+"\\modules"
modules = list(Module.ServerUids.values()) if modulesFrom == 0 else list(Module.LocalUids.values())
modules = sorted(modules)
self.treeWidget.clear()
mask = self.maskWidget.text().split() # split by spaces, '/folder mask /other mask'
# make tree dict from module files
for f in modules:
relativePath = os.path.relpath(f, modulesDirectory)
relativeDir = os.path.dirname(relativePath)
name, _ = os.path.splitext(os.path.basename(f))
okMask = True
dirMask = "/"+relativePath.replace("\\", "/")+"/"
for m in mask:
if not re.search(re.escape(m), dirMask, re.IGNORECASE):
okMask = False
break
if not okMask:
continue
dirItem = self.treeWidget.invisibleRootItem()
if relativeDir:
for p in relativeDir.split("\\"):
ch = findChildByText(p, dirItem)
if ch:
dirItem = ch
else:
ch = QTreeWidgetItem([p, ""])
font = ch.font(0)
font.setBold(True)
ch.setForeground(0, QColor(130, 130, 230))
ch.setFont(0, font)
dirItem.addChild(ch)
dirItem.setExpanded(True if mask else False)
dirItem = ch
modtime = time.strftime("%Y/%m/%d %H:%M", time.localtime(os.path.getmtime(f)))
item = QTreeWidgetItem([name, modtime])
item.filePath = f
dirItem.addChild(item)
dirItem.setExpanded(True if mask else False)
class ModuleItem(QTreeWidgetItem):
def __init__(self, module, **kwargs):
super().__init__(**kwargs)
self.module = module
self.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled)
def clone(self):
item = ModuleItem(self.module.copy())
for i in range(self.childCount()):
item.addChild(self.child(i).clone())
return item
def data(self, column, role):
if column == 0: # name
if role == Qt.EditRole:
return self.module.name()
elif role == Qt.DisplayRole:
return self.module.name() + ("*" if self.module.modified() else " ")
elif role == Qt.ForegroundRole:
isParentMuted = False
isParentReferenced = False
parent = self.parent()
while parent:
isParentMuted = isParentMuted or parent.module.muted()
isParentReferenced = isParentReferenced or parent.module.uid()
parent = parent.parent()
color = QColor(200, 200, 200)
if isParentReferenced:
color = QColor(140, 140, 180)
if self.module.muted() or isParentMuted:
color = QColor(100, 100, 100)
return color
elif role == Qt.BackgroundRole:
if not re.match("\\w*", self.module.name()):
return QColor(170, 50, 50)
itemParent = self.parent()
if itemParent and len([ch for ch in itemParent.module.children() if ch.name() == self.module.name()]) > 1:
return QColor(170, 50, 50)
return super().data(column, role)
elif column == 1: # path
if role == Qt.DisplayRole:
return self.module.relativePathString().replace("\\", "/") + " "
elif role == Qt.EditRole:
return "(not editable)"
elif role == Qt.FontRole:
font = QFont()
font.setItalic(True)
return font
elif role == Qt.ForegroundRole:
return QColor(125, 125, 125)
elif column == 2: # source
source = ""
if self.module.loadedFromLocal():
source = "local"
elif self.module.loadedFromServer():
source = "server"
if role == Qt.DisplayRole:
return source + " "
elif role == Qt.EditRole:
return "(not editable)"
elif role == Qt.ForegroundRole:
if source == "local":
return QColor(120, 220, 120)
elif source == "server":
return QColor(120, 120, 120)
elif column == 3: # uid
if role == Qt.DisplayRole:
return self.module.uid()[:8]
elif role == Qt.EditRole:
return "(not editable)"
elif role == Qt.ForegroundRole:
return QColor(125, 125, 170)
else:
return super().data(column, role)
def setData(self, column, role, value):
if column == 0:
if role == Qt.EditRole:
newName = replaceSpecialChars(value).strip()
if self.parent():
existingNames = set([ch.name() for ch in self.parent().module.children() if ch is not self.module])
newName = findUniqueName(newName, existingNames)
connections = self._saveConnections(self.module) # rename in connections
self.module.setName(newName)
self.treeWidget().resizeColumnToContents(column)
self._updateConnections(connections)
else:
return super().setData(column, role, value)
def _saveConnections(self, currentModule):
connections = []
for a in currentModule.attributes():
connections.append({"attr":a, "module": currentModule, "connections":a.listConnections()})
for ch in currentModule.children():
connections += self._saveConnections(ch)
return connections
def _updateConnections(self, connections):
for data in connections:
srcAttr = data["attr"]
module = data["module"]
for a in data["connections"]:
c = module.path().replace(a.module().path(inclusive=False), "") + "/" + srcAttr.name()
a.setConnect(c) # update connection path
class TreeWidget(QTreeWidget):
def __init__(self, *, mainWindow=None, **kwargs):
super().__init__(**kwargs)
self.mainWindow = mainWindow
self.dragItems = [] # using in drag & drop
self.moduleListDialog = ModuleListDialog()
self.moduleListDialog.moduleSelected.connect(self.addModuleFromBrowser)
self.setHeaderLabels(["Name", "Path", "Source", "UID"])
self.setSelectionMode(QAbstractItemView.ExtendedSelection) # ExtendedSelection
self.header().setSectionResizeMode(QHeaderView.ResizeToContents)
self.setDragEnabled(True)
self.setDragDropMode(QAbstractItemView.InternalMove)
self.setDropIndicatorShown(True)
self.setAcceptDrops(True)
self.setIndentation(30)
def paintEvent(self, event):
super().paintEvent(event)
label = "Press TAB to load modules"
fontMetrics = QFontMetrics(self.font())
viewport = self.viewport()
painter = QPainter(viewport)
painter.setPen(QColor(90,90,90))
painter.drawText(viewport.width() - fontMetrics.width(label)-10, viewport.height()-10, label)
def dragEnterEvent(self, event):
super().dragEnterEvent(event)
if event.mimeData().hasUrls():
event.accept()
elif event.mouseButtons() == Qt.MiddleButton:
self.dragItems = self.selectedItems()
else:
event.ignore()
def dragMoveEvent(self, event):
super().dragMoveEvent(event)
if event.mimeData().hasUrls():
event.setDropAction(Qt.CopyAction)
def dropEvent(self, event):
super().dropEvent(event)
if event.mimeData().hasUrls():
event.setDropAction(Qt.CopyAction)
for url in event.mimeData().urls():
path = url.toLocalFile()
with captureOutput(self.mainWindow.logWidget):
try:
m = Module.loadFromFile(path)
m.update()
self.addTopLevelItem(self.makeItemFromModule(m))
except ET.ParseError as e:
print(e)
print("Error '{}': invalid module".format(path))
self.mainWindow.showLog()
else:
for item in self.dragItems:
if item.module.parent(): # remove from old parent
item.module.parent().removeChild(item.module)
newParent = item.parent()
if newParent:
if newParent.module.findChild(item.module.name()):
existingNames = set([ch.name() for ch in newParent.module.children()])
item.module.setName(findUniqueName(item.module.name(), existingNames))
idx = newParent.indexOfChild(item)
newParent.module.insertChild(idx, item.module)
newParent.emitDataChanged()
self.dragItems = []
def makeItemFromModule(self, module):
item = ModuleItem(module)
for ch in module.children():
item.addChild(self.makeItemFromModule(ch))
return item
def contextMenuEvent(self, event):
self.mainWindow.menu.popup(event.globalPos())
def sendModuleToServer(self):
selectedItems = self.selectedItems()
if not selectedItems:
return
msg = "\n".join([item.module.name() for item in selectedItems])
if QMessageBox.question(self, "Rig Builder", "Send modules to server?\n"+msg, QMessageBox.Yes and QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes:
return
for item in selectedItems:
if item.module.loadedFromLocal():
if sendToServer(item.module):
QMessageBox.information(self, "Rig Builder", "Module '{}' has successfully been sent to server".format(item.module.name()))
else:
QMessageBox.warning(self, "Rig Builder", "Can't send '{}' to server.\nIt works for local modules only!".format(item.module.name()))
def insertModule(self):
m = Module()
m.setName("module")
item = self.makeItemFromModule(m)
sel = self.selectedItems()
if sel:
sel[0].addChild(item)
sel[0].module.addChild(item.module)
else:
self.addTopLevelItem(item)
def importModule(self):
sceneDir = RigBuilderLocalPath + "/modules"
if DCC == "maya":
sceneDir = os.path.dirname(om.MFileIO.currentFile())
filePath, _ = QFileDialog.getOpenFileName(mainWindow, "Import", sceneDir, "*.xml")
if not filePath:
return
Module.updateUidsCache()
try:
m = Module.loadFromFile(filePath)
m.update()
self.addTopLevelItem(self.makeItemFromModule(m))
except ET.ParseError:
print("Error '{}': invalid module".format(filePath))
self.mainWindow.showLog()
def saveModule(self):
selectedItems = self.selectedItems()
if not selectedItems:
return
msg = "\n".join(["{} -> {}".format(item.module.name(), item.module.getSavePath() or "N/A") for item in selectedItems])
if QMessageBox.question(self, "Rig Builder", "Save modules?\n"+msg, QMessageBox.Yes and QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes:
return
for item in selectedItems:
outputPath = item.module.getSavePath()
if not outputPath:
outputPath, _ = QFileDialog.getSaveFileName(mainWindow, "Save "+item.module.name(), RigBuilderLocalPath+"/modules/"+item.module.name(), "*.xml")
if outputPath:
dirname = os.path.dirname(outputPath)
if not os.path.exists(dirname):
os.makedirs(dirname)
try:
item.module.saveToFile(outputPath)
except Exception as e:
QMessageBox.critical(self, "Rig Builder", "Can't save module '{}': {}".format(item.module.name(), str(e)))
else:
item.emitDataChanged() # path changed
self.mainWindow.attributesTabWidget.updateWidgetStyles()
def saveAsModule(self):
for item in self.selectedItems():
outputDir = os.path.dirname(item.module.filePath()) or RigBuilderLocalPath+"/modules"
outputPath, _ = QFileDialog.getSaveFileName(mainWindow, "Save as "+item.module.name(), outputDir + "/" +item.module.name(), "*.xml")
if outputPath:
try:
item.module.saveToFile(outputPath, newUid=True)
except Exception as e:
QMessageBox.critical(self, "Rig Builder", "Can't save module '{}': {}".format(item.module.name(), str(e)))
else:
item.emitDataChanged() # path and uid changed
self.mainWindow.attributesTabWidget.updateWidgetStyles()
def embedModule(self):
selectedItems = self.selectedItems()
if not selectedItems:
return
msg = "\n".join([item.module.name() for item in selectedItems])
if QMessageBox.question(self, "Rig Builder", "Embed modules?\n"+msg, QMessageBox.Yes and QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes:
return
for item in selectedItems:
item.module.embed()
item.emitDataChanged() # path and uid changed
def updateModule(self):
selectedItems = self.selectedItems()
if not selectedItems:
return
Module.updateUidsCache()
msg = "\n".join([item.module.name() for item in selectedItems])
if QMessageBox.question(self, "Rig Builder", "Update modules?\n"+msg, QMessageBox.Yes and QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes:
return
for item in selectedItems:
if not item.module.uid():
QMessageBox.warning(self, "Rig Builder", "Can't update module '{}': no uid".format(item.module.name()))
continue
item.module.update()
newItem = self.makeItemFromModule(item.module)
expanded = item.isExpanded()
if item.parent():
parent = item.parent()
idx = parent.indexOfChild(item)
parent.removeChild(item)
parent.insertChild(idx, newItem)
parent.module.removeChild(item.module)
parent.module.insertChild(idx, newItem.module)
else:
parent = self.invisibleRootItem()
idx = parent.indexOfChild(item)
parent.removeChild(item)
parent.insertChild(idx, newItem)
newItem.setExpanded(expanded)
newItem.setSelected(True)
def muteModule(self):
for item in self.selectedItems():
if item.module.muted():
item.module.unmute()
else:
item.module.mute()
item.emitDataChanged()
def duplicateModule(self):
newItems = []
for item in self.selectedItems():
newItem = self.makeItemFromModule(item.module.copy())
if item.parent():
existingNames = set([ch.name() for ch in item.parent().module.children()])
newItem.module.setName(findUniqueName(item.module.name(), existingNames))
parent = item.parent()
if parent:
parent.addChild(newItem)
parent.module.addChild(newItem.module)
else:
self.addTopLevelItem(newItem)
newItems.append(newItem)
self.clearSelection()
for item in newItems:
item.setSelected(True)
def removeModule(self):
selectedItems = self.selectedItems()
if not selectedItems:
return
msg = "\n".join([item.module.name() for item in selectedItems])
if QMessageBox.question(self, "Rig Builder", "Remove modules?\n"+msg, QMessageBox.Yes and QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes:
return
for item in selectedItems:
parent = item.parent()
if parent:
parent.removeChild(item)
parent.module.removeChild(item.module)
parent.emitDataChanged()
else:
self.invisibleRootItem().removeChild(item)
def addModuleFromBrowser(self, modulePath):
m = Module.loadFromFile(modulePath)
m.update()
self.addTopLevelItem(self.makeItemFromModule(m))
# add to recent modules
recentModules = self.mainWindow.infoWidget.recentModules
for rm in list(recentModules):
if rm.uid() == m.uid(): # remove the previous one
recentModules.remove(rm)
break
recentModules.insert(0, m)
if len(recentModules) > 10:
recentModules.pop()