-
Notifications
You must be signed in to change notification settings - Fork 3
/
W_hotboxManager.py
3819 lines (2895 loc) · 122 KB
/
W_hotboxManager.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
# ----------------------------------------------------------------------------------------------------------
# Wouter Gilsing
version = "1.9"
releaseDate = "March 28 2021"
# - modules
import nuke
# Choose between PySide and PySide2 based on Nuke version
if nuke.NUKE_VERSION_MAJOR < 11:
from PySide import QtCore, QtGui, QtGui as QtWidgets
else:
from PySide2 import QtGui, QtCore, QtWidgets
import os
import shutil
import re
import string
import colorsys
import tempfile
import tarfile
import base64
from datetime import datetime as dt
from webbrowser import open as openURL
import W_hotbox
preferencesNode = nuke.toNode("preferences")
class HotboxManager(QtWidgets.QWidget):
def __init__(self, path=""):
super(HotboxManager, self).__init__()
# - main widget
# parent to main nuke interface
self.setParent(QtWidgets.QApplication.instance().activeWindow())
self.setWindowFlags(QtCore.Qt.Tool)
self.setWindowTitle("W_hotbox Manager - %s" % path)
self.setMinimumWidth(1000)
self.setMinimumHeight(400)
# - colors
self.activeColor = "#3a3a3a"
self.lockedColor = "#262626"
self.rootLocation = path.replace("\\", "/")
# - create folders
# If the manager is launched for the default repository, make sure the current archive exists.
preferencesLocation = getHotBoxLocation()
if self.rootLocation == preferencesLocation:
for subFolder in [
"",
"Single",
"Multiple",
"All",
"Single/No Selection",
"Rules",
"Templates",
]:
subFolderPath = self.rootLocation + subFolder
if not os.path.isdir(subFolderPath):
try:
os.mkdir(subFolderPath)
except:
pass
self.templateLocation = self.rootLocation + "Templates/"
# - left column - classes list
self.classesListLayout = QtWidgets.QVBoxLayout()
# scope dropdown
self.scopeComboBox = QtWidgets.QComboBox()
self.scopeComboBoxItems = ["Single", "Multiple", "All", "Rules"]
self.scopeComboBox.addItems(self.scopeComboBoxItems)
self.scopeComboBox.insertSeparator(3)
self.scopeComboBox.currentIndexChanged.connect(self.buildClassesList)
# list column
self.classesList = QListWidgetCustom(self)
self.classesList.setFixedWidth(150)
self.classesListLayout.addWidget(self.scopeComboBox)
self.classesListLayout.addWidget(self.classesList)
# buttons
self.classesListButtonsLayout = QtWidgets.QVBoxLayout()
self.classesListAddButton = QLabelButton("add", self.classesList)
self.classesListRemoveButton = QLabelButton("remove", self.classesList)
self.classesListRenameButton = QLabelButton("rename", self.classesList)
# connect
self.classesListAddButton.clicked.connect(self.addClass)
self.classesListRemoveButton.clicked.connect(self.removeClass)
self.classesListRenameButton.clicked.connect(self.renameClass)
# assemble layout
self.classesListButtonsLayout.addStretch()
self.classesListButtonsLayout.addWidget(self.classesListAddButton)
self.classesListButtonsLayout.addWidget(self.classesListRemoveButton)
self.classesListButtonsLayout.addWidget(self.classesListRenameButton)
self.classesListButtonsLayout.addStretch()
# - right column - hotbox items tree
self.hotboxItemsTree = QTreeViewCustom(self)
self.hotboxItemsTree.setFixedWidth(150)
self.rootPath = getHotBoxLocation()
self.classesList.itemSelectionChanged.connect(self.hotboxItemsTree.populateTree)
# actions
self.hotboxItemsTreeButtonsLayout = QtWidgets.QVBoxLayout()
self.hotboxItemsTreeAddButton = QLabelButton("add", self.hotboxItemsTree)
self.hotboxItemsTreeAddFolderButton = QLabelButton(
"addFolder", self.hotboxItemsTree
)
self.hotboxItemsTreeRemoveButton = QLabelButton("remove", self.hotboxItemsTree)
self.hotboxItemsTreeDuplicateButton = QLabelButton(
"duplicate", self.hotboxItemsTree
)
self.hotboxItemsTreeCopyButton = QLabelButton("copy", self.hotboxItemsTree)
self.hotboxItemsTreePasteButton = QLabelButton("paste", self.hotboxItemsTree)
self.hotboxItemsTreeMoveUp = QLabelButton("moveUp", self.hotboxItemsTree)
self.hotboxItemsTreeMoveDown = QLabelButton("moveDown", self.hotboxItemsTree)
self.hotboxItemsTreeMoveUpLevel = QLabelButton(
"moveUpLevel", self.hotboxItemsTree
)
# connect
self.hotboxItemsTreeAddButton.clicked.connect(self.hotboxItemsTree.addItem)
self.hotboxItemsTreeAddFolderButton.clicked.connect(
lambda: self.hotboxItemsTree.addItem(True)
)
self.hotboxItemsTreeRemoveButton.clicked.connect(
self.hotboxItemsTree.removeItem
)
self.hotboxItemsTreeDuplicateButton.clicked.connect(
self.hotboxItemsTree.duplicateItem
)
self.hotboxItemsTreeCopyButton.clicked.connect(self.hotboxItemsTree.copyItem)
self.hotboxItemsTreePasteButton.clicked.connect(self.hotboxItemsTree.pasteItem)
self.hotboxItemsTreeMoveUp.clicked.connect(
lambda: self.hotboxItemsTree.moveItem(0)
)
self.hotboxItemsTreeMoveDown.clicked.connect(
lambda: self.hotboxItemsTree.moveItem(1)
)
self.hotboxItemsTreeMoveUpLevel.clicked.connect(
lambda: self.hotboxItemsTree.moveItem(2)
)
# assemble layout
self.hotboxItemsTreeButtonsLayout.addStretch()
self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeAddButton)
self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeAddFolderButton)
self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeRemoveButton)
self.hotboxItemsTreeButtonsLayout.addSpacing(25)
self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeMoveUp)
self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeMoveDown)
self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeMoveUpLevel)
self.hotboxItemsTreeButtonsLayout.addSpacing(25)
self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeCopyButton)
self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreePasteButton)
self.hotboxItemsTreeButtonsLayout.addWidget(self.hotboxItemsTreeDuplicateButton)
self.hotboxItemsTreeButtonsLayout.addStretch()
# - import/export
# create buttons
self.clipboardArchive = QtWidgets.QCheckBox("Clipboard")
self.importArchiveButton = QtWidgets.QPushButton("Import Archive")
self.exportArchiveButton = QtWidgets.QPushButton("Export Archive")
self.importArchiveButton.setMaximumWidth(100)
self.exportArchiveButton.setMaximumWidth(100)
# tooltips
tooltip = "Make use of the clipboard to import/export an archive, rather than saving a file to disk."
self.clipboardArchive.setToolTip(tooltip)
tooltip = "Import a button archive. This will append the current set of buttons and overwrite any buttons with the same name."
self.importArchiveButton.setToolTip(tooltip)
tooltip = "Export the current set of buttons as an archive."
self.exportArchiveButton.setToolTip(tooltip)
# wire up
self.importArchiveButton.clicked.connect(self.importHotboxArchive)
self.exportArchiveButton.clicked.connect(self.exportHotboxArchive)
# assemble
self.archiveButtonsLayout = QtWidgets.QHBoxLayout()
self.archiveButtonsLayout.addStretch()
self.archiveButtonsLayout.addWidget(self.clipboardArchive)
self.archiveButtonsLayout.addWidget(self.importArchiveButton)
self.archiveButtonsLayout.addWidget(self.exportArchiveButton)
# - scriptEditor
self.ignoreSave = False
self.loadedScript = None
self.scriptEditorLayout = QtWidgets.QVBoxLayout()
# buttons
self.scriptEditorButtonsLayout = QtWidgets.QHBoxLayout()
self.scriptEditorTemplateButton = QtWidgets.QToolButton()
self.scriptEditorTemplateButton.setText("Templates ")
self.scriptEditorTemplateButton.setPopupMode(QtWidgets.QToolButton.InstantPopup)
self.exitTemplateModeButton = QtWidgets.QPushButton("Exit template mode")
self.exitTemplateModeButton.setStyleSheet("color: #f7931e")
self.exitTemplateModeButton.setVisible(False)
self.scriptEditorImportButton = QtWidgets.QPushButton("Import")
self.scriptEditorImportButton.clicked.connect(self.importScriptEditor)
self.scriptEditorTemplateMenu = ScriptEditorTemplateMenu(self)
self.scriptEditorTemplateButton.setMenu(self.scriptEditorTemplateMenu)
self.exitTemplateModeButton.clicked.connect(self.toggleTemplateMode)
self.scriptEditorTemplateButtons = [
self.exitTemplateModeButton,
self.scriptEditorTemplateButton,
]
self.scriptEditorButtonsLayout.addStretch()
for button in self.scriptEditorTemplateButtons + [
self.scriptEditorImportButton
]:
self.scriptEditorButtonsLayout.addWidget(button)
self.scriptEditorButtonsLayout.addStretch()
# name
self.scriptEditorNameLayout = QtWidgets.QHBoxLayout()
self.scriptEditorNameLabel = QtWidgets.QLabel("Name")
self.scriptEditorName = ScriptEditorNameWidget()
self.scriptEditorName.setAlignment(QtCore.Qt.AlignLeft)
self.scriptEditorName.editingFinished.connect(self.saveScriptEditor)
# color swatches
self.colorSwatchButtonLabel = QtWidgets.QLabel("Button")
self.colorSwatchButton = ColorSwatch("#525252")
self.colorSwatchTextLabel = QtWidgets.QLabel("Text")
self.colorSwatchText = ColorSwatch("#eeeeee")
self.colorSwatchButton.setChild(self.colorSwatchText)
# wire up color swatches
self.colorSwatchButton.save.connect(self.saveScriptEditor)
self.colorSwatchText.save.connect(self.saveScriptEditor)
self.scriptEditorNameWidgets = [
self.scriptEditorNameLabel,
self.scriptEditorName,
self.colorSwatchButtonLabel,
self.colorSwatchButton,
self.colorSwatchTextLabel,
self.colorSwatchText,
]
# rules
self.rulesFlagCheckbox = QtWidgets.QCheckBox("Ignore classes")
self.rulesFlagCheckbox.setLayoutDirection(QtCore.Qt.RightToLeft)
self.rulesFlagCheckbox.stateChanged.connect(lambda: self.saveScriptEditor())
# label to make sure the checkbox is aligned to the right
self.rulesFlagLabel = QtWidgets.QLabel("")
self.rulesFlagWidgets = [self.rulesFlagCheckbox, self.rulesFlagLabel]
for widget in self.rulesFlagWidgets:
widget.setVisible(False)
# assemble layout
for widget in self.rulesFlagWidgets + self.scriptEditorNameWidgets:
self.scriptEditorNameLayout.addWidget(widget)
# script
self.scriptEditorScript = ScriptEditorWidget()
self.scriptEditorScript.setMinimumHeight(200)
self.scriptEditorScript.setMinimumWidth(500)
self.scriptEditorScript.save.connect(self.saveScriptEditor)
ScriptEditorHighlighter(self.scriptEditorScript.document())
scriptEditorFont = QtGui.QFont()
scriptEditorFont.setFamily("Courier")
scriptEditorFont.setStyleHint(QtGui.QFont.Monospace)
scriptEditorFont.setFixedPitch(True)
scriptEditorFont.setPointSize(
preferencesNode.knob("hotboxScriptEditorFontSize").value()
)
self.scriptEditorScript.setFont(scriptEditorFont)
self.scriptEditorScript.setTabStopWidth(
4 * QtGui.QFontMetrics(scriptEditorFont).width(" ")
)
# assemble
self.scriptEditorLayout.addLayout(self.archiveButtonsLayout)
self.scriptEditorLayout.addLayout(self.scriptEditorNameLayout)
self.scriptEditorLayout.addWidget(self.scriptEditorScript)
self.scriptEditorLayout.addLayout(self.scriptEditorButtonsLayout)
# - main buttons
self.mainButtonLayout = QtWidgets.QHBoxLayout()
self.aboutButton = QtWidgets.QPushButton("?")
self.aboutButton.clicked.connect(self.openAboutDialog)
self.aboutButton.setMaximumWidth(20)
self.mainCloseButton = QtWidgets.QPushButton("Close")
self.mainCloseButton.clicked.connect(self.closeManager)
self.mainButtonLayout.addWidget(self.aboutButton)
self.mainButtonLayout.addStretch()
self.mainButtonLayout.addWidget(self.mainCloseButton)
# - main layout
self.mainLayout = QtWidgets.QHBoxLayout()
self.mainLayout.addLayout(self.classesListButtonsLayout)
self.mainLayout.addLayout(self.classesListLayout)
self.mainLayout.addLayout(self.hotboxItemsTreeButtonsLayout)
self.mainLayout.addWidget(self.hotboxItemsTree)
self.mainLayout.addLayout(self.scriptEditorLayout)
# - layouts
self.masterLayout = QtWidgets.QVBoxLayout()
self.masterLayout.addLayout(self.mainLayout)
self.masterLayout.addLayout(self.mainButtonLayout)
self.setLayout(self.masterLayout)
# - move to center of the screen
self.adjustSize()
screenRes = QtWidgets.QDesktopWidget().screenGeometry()
self.move(
QtCore.QPoint(screenRes.width() // 2, screenRes.height() // 2)
- QtCore.QPoint((self.width() // 2), (self.height() // 2))
)
# - set values
self.enableScriptEditor(False, False)
self.scopeComboBox.setCurrentIndex(1)
self.scopeComboBox.setCurrentIndex(0)
self.scopeComboBoxLastIndex = 0
# - set hotbox to current selection
launchMode = preferencesNode.knob("hotboxOpenManagerOptions").value()
launchMode = launchMode.replace("Contextual", "Single/Multiple")
launchMode = launchMode.split("/")
found = False
# contextual
if len(launchMode) > 1:
selection = nuke.selectedNodes()
classes = sorted(set([node.Class() for node in selection]))
# single/multiple
self.scopeComboBox.setCurrentIndex(len(classes) > 1)
for index in range(self.classesList.count()):
itemClasses = self.classesList.item(index).text().split("-")
if all([nodeClass in itemClasses for nodeClass in classes]):
self.classesList.setCurrentRow(index)
found = True
break
if len(launchMode) == 2:
found = True
else:
found *= bool(selection)
# all or rules (2 or 4)
if not found:
item = launchMode[-1]
index = (int(item == "Rules") * 2) + 2
self.scopeComboBox.setCurrentIndex(index)
# - classes list
def buildClassesList(self, selectItem=None):
"""
Populate classes list with items.
"""
# if restore based on index, save current index before clearing the widget.
if isinstance(selectItem, bool) and selectItem:
itemIndex = self.classesList.currentRow()
self.mode = self.scopeComboBox.currentText()
self.contextual = self.mode not in ["All", "Templates"]
# turn this variable on, to prevent the itemChanged signal from emitting
self.classesList.buildClassesList = True
# clear selection
self.classesList.clearSelection()
# clear items tree
self.hotboxItemsTree.clearTree()
# clear list
self.classesList.clear()
# disable scripteditor
self.enableScriptEditor(False, False)
self.path = self.rootLocation + self.mode
# color
color = self.activeColor
# disable if templates or all mode
if self.contextual:
self.classesList.setEnabled()
else:
self.classesList.setEnabled(False)
if self.contextual:
# sort items found on disk
allItems = sorted(os.listdir(self.path), key=lambda s: s.lower())
allItems = [
folder
for folder in allItems
if os.path.isdir(self.path + "/" + folder)
and folder[0] not in [".", "_"]
]
# add items
self.classesList.addItems(allItems)
# add checkbox to item if in rule mode
if self.mode == "Rules":
checkedStates = [QtCore.Qt.Unchecked, QtCore.Qt.Checked]
for index in range(self.classesList.count()):
item = self.classesList.item(index)
itemText = item.text()
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
# check if supposed to be enabled according to name
checkedState = itemText[-1] != "_"
item.setCheckState(checkedStates[checkedState])
if not checkedState:
item.setText(itemText[:-1])
self.toggleRulesMode(False)
# populate buttons tree
self.hotboxItemsTree.populateTree()
# restore selection
if selectItem:
# select based on string
if isinstance(selectItem, str):
foundItems = self.classesList.findItems(
selectItem, QtCore.Qt.MatchExactly
)
if foundItems:
self.classesList.setCurrentItem(foundItems[0])
# select based on index
if isinstance(selectItem, bool):
allItems = self.classesList.count() - 1
itemIndex = min(allItems, itemIndex)
self.classesList.setCurrentRow(itemIndex)
# turn this variable back off
self.classesList.buildClassesList = False
def addClass(self):
"""
Add a new nodeclass
"""
defaultName = "NewClass"
if self.mode == "Rules":
defaultName = "NewRule"
name = defaultName
# in case name allready exists
counter = 1
while os.path.isdir(self.path + "/" + name):
name = defaultName + str(counter)
counter += 1
# create folder on disk
folderPath = "/".join([self.path, name])
os.mkdir(folderPath)
# create rule file
if self.mode == "Rules":
ruleFile = open(folderPath + "/_rule.py", "w")
ruleFile.write(FileHeader("0", rule=True).getHeader())
ruleFile.close()
self.buildClassesList(name)
self.renameClass(True)
def removeClass(self, className=None):
"""
Remove the selected nodeclass
"""
if className:
selectedClass = className
else:
selectedClass = self.getSelectedClass()
if not selectedClass:
return
# move to old folder
oldFolder = "/".join([self.path, "_old"])
if not os.path.isdir(oldFolder):
os.mkdir(oldFolder)
shutil.move(
self.path + "/" + selectedClass,
self.path
+ "/_old/"
+ selectedClass
+ "_"
+ dt.now().strftime("%Y%m%d%H%M%S"),
)
self.buildClassesList(True)
def renameClass(self, new=False):
"""
Rename the selected nodeclass
"""
selectedClass = self.getSelectedClass()
if not selectedClass:
return
# kill any existing instances
global renameDialogInstance
if renameDialogInstance != None:
renameDialogInstance.closeRenameDialog()
# spawn new
renameDialogInstance = RenameDialog(selectedClass, new)
renameDialogInstance.show()
def getSelectedClass(self):
"""
Return the name of the selected class
"""
if not self.classesList.itemSelected():
return None
selectedItem = self.classesList.currentItem()
selectedClass = selectedItem.text()
# if rule, check if item enabled
if self.mode == "Rules":
selectedClass += "_" * (1 - bool(selectedItem.checkState()))
return selectedClass
# --------------------------------------------------------------------------------------------------
# scriptEditor
# --------------------------------------------------------------------------------------------------
def loadScriptEditor(self, rule=False):
"""
Fill the fields of the the script editor with the information read from the currently selected
file.
"""
self.scriptEditorScript.savedText = ""
# check if items selected
itemsSelected = True
if not rule:
itemsSelected = bool(self.hotboxItemsTree.selectedItems)
if itemsSelected:
if not rule:
self.selectedItem = self.hotboxItemsTree.selectedItems[0]
self.loadedScript = self.selectedItem.path
# if rule mode
else:
item = self.classesList.currentItem()
itemState = 1 - bool(item.checkState())
self.loadedScript = "/".join(
[self.path, item.text() + "_" * itemState, "_rule.py"]
)
# if item (not submenu)
if self.loadedScript.endswith(".py"):
self.enableScriptEditor()
if not rule:
# set attributes
name = getAttributeFromFile(self.loadedScript)
self.scriptEditorName.setText(name)
# make sure the colorswatches will remain disabled in template mode
if not self.exitTemplateModeButton.isVisible():
textColor = getAttributeFromFile(self.loadedScript, "textColor")
self.colorSwatchText.setColor(
textColor, adjustChild=False, indirect=True
)
color = getAttributeFromFile(self.loadedScript, "color")
self.colorSwatchButton.setColor(
color, adjustChild=False, indirect=True
)
# rule
else:
ignoreClasses = int(
getAttributeFromFile(self.loadedScript, "ignore classes")
)
self.ignoreSave = True
self.rulesFlagCheckbox.setChecked(ignoreClasses)
self.ignoreSave = False
# set script
text = getScriptFromFile(self.loadedScript)
self.scriptEditorScript.setPlainText(text)
self.scriptEditorScript.updateSavedText()
# if submenu
else:
# set name
self.scriptEditorName.setText(
open(self.loadedScript + "/_name.json").read()
)
self.enableScriptEditor(False, True)
else:
self.loadedScript = None
self.enableScriptEditor(False, False)
def enableScriptEditor(self, editor=True, name=True):
"""
Enable/Disable widgets based on selection.
"""
colors = [self.activeColor, self.lockedColor]
# script
self.scriptEditorScript.setReadOnly(1 - editor)
self.scriptEditorImportButton.setEnabled(editor)
self.scriptEditorScript.setStyleSheet("background:%s" % colors[1 - editor])
if not editor:
self.scriptEditorScript.clear()
# make sure the buttons are colorswatches are always disabled in template mode
editor = editor * (1 - self.exitTemplateModeButton.isVisible())
for colorSwatch in [
self.colorSwatchButton,
self.colorSwatchText,
self.colorSwatchButtonLabel,
self.colorSwatchTextLabel,
]:
colorSwatch.setEnabled(editor)
# name
self.scriptEditorName.setReadOnly(1 - name)
self.scriptEditorNameLabel.setEnabled(name)
self.scriptEditorName.setStyleSheet("background:%s" % colors[1 - name])
if not name:
self.scriptEditorName.clear()
# template button
self.scriptEditorTemplateMenu.enableMenuItems()
def importScriptEditor(self):
"""
Set the current content of the script editor by importing an existing file.
"""
if self.scriptEditorImportButton.isEnabled():
importFile = nuke.getFilename("select file to import", "*.py *.json")
# replace tabs with spaces
text = open(importFile).read().replace("\t", " " * 4)
self.scriptEditorScript.setPlainText(text)
self.scriptEditorScript.setFocus()
def saveScriptEditor(self, template=False):
"""
Save the current content of the script editor
"""
# dont save whenever this function is triggered while ignoreSave is on.
if self.ignoreSave:
return
rule = self.rulesFlagCheckbox.isVisible()
if not self.scriptEditorName.isReadOnly():
name = self.scriptEditorName.text()
if template:
path = getFirstAvailableFilePath(self.templateLocation)
path += ".py"
else:
path = self.loadedScript
# file
if path.endswith(".py"):
text = self.scriptEditorScript.toPlainText()
if not rule:
# header
color = self.colorSwatchButton.isNonDefault(True)
textColor = self.colorSwatchText.isNonDefault(True)
newFileContent = (
FileHeader(name, color, textColor).getHeader() + text
)
else:
newFileContent = (
FileHeader(
int(self.rulesFlagCheckbox.isChecked()), rule=True
).getHeader()
+ text
)
# save to disk
currentFile = open(path, "w")
currentFile.write(newFileContent)
currentFile.close()
# change save status
self.scriptEditorScript.updateSavedText()
# menu
else:
# save to disk
currentFile = open(self.loadedScript + "/_name.json", "w")
currentFile.write(name)
currentFile.close()
if not rule:
self.selectedItem.setText(name)
if template:
# update template menu
if path.startswith(self.templateLocation):
self.scriptEditorTemplateMenu.initMenu()
# --------------------------------------------------------------------------------------------------
# Rules mode
# --------------------------------------------------------------------------------------------------
def toggleRulesMode(self, mode=True):
"""
Toggle rule mode on and off.
"""
# if triggered by item selection
if mode:
if self.mode != "Rules":
return
# apply change
for index, widgetList in enumerate(
[self.rulesFlagWidgets, self.scriptEditorNameWidgets][:: mode * 2 - 1]
):
for widget in widgetList:
widget.setVisible(1 - index)
if mode:
self.loadScriptEditor(rule=True)
# --------------------------------------------------------------------------------------------------
# Template mode
# --------------------------------------------------------------------------------------------------
def toggleTemplateMode(self):
"""
Toggle template mode on and off.
"""
# check whether entering or leaving template mode.
enter = True
if self.exitTemplateModeButton.isVisible():
enter = False
# switch between template dropdown and 'Exit template mode' buttons.
self.scriptEditorTemplateButton.setVisible(1 - enter)
self.exitTemplateModeButton.setVisible(enter)
# store current selection
if enter:
# scope
self.lastSelectedScopeIndex = self.scopeComboBox.currentIndex()
# class
selectedClassItem = self.classesList.currentItem()
if selectedClassItem:
self.lastSelectedClassIndex = self.classesList.indexFromItem(
selectedClassItem
)
else:
self.lastSelectedClassIndex = None
# item
selectedItemIndexes = self.hotboxItemsTree.selectedIndexes()
if selectedItemIndexes:
self.lastSelectedItemIndex = selectedItemIndexes[0]
else:
self.lastSelectedItemIndex = None
for index in range(self.scopeComboBox.count())[::-1]:
self.scopeComboBox.removeItem(index)
# refill scopeComboBox
if enter:
# change items of scopeCombobox to 'Templates'
self.scopeComboBox.addItems(["Templates"])
self.scopeComboBox.setCurrentIndex(0)
self.scopeComboBox.setEditable(False)
else:
# update template menu
self.scriptEditorTemplateMenu.initMenu()
# change items of scopeCombobox to 'Single/Multiple/All'
self.scopeComboBox.addItems(self.scopeComboBoxItems)
# disable menu
# restore last selection
# scope
self.scopeComboBox.setCurrentIndex(self.lastSelectedScopeIndex)
# class
if self.lastSelectedClassIndex:
lastSelectedClassItem = self.classesList.itemFromIndex(
self.lastSelectedClassIndex
)
self.classesList.setCurrentItem(lastSelectedClassItem)
# item
if self.lastSelectedItemIndex:
self.hotboxItemsTree.setCurrentIndex(self.lastSelectedItemIndex)
# make sure the template menu is properly enabled/disabled
# this should would automatically, but fails when nothing is selected.
self.scriptEditorTemplateMenu.enableMenuItems()
# --------------------------------------------------------------------------------------------------
# import/export functions
# --------------------------------------------------------------------------------------------------
# export
def exportHotboxArchive(self):
"""
A method to export a set of buttons to an external archive.
"""
archiveLocation = tempfile.mkstemp()[1]
# write to zip
with tarfile.open(archiveLocation, "w:gz") as tar:
tar.add(self.rootLocation, arcname=os.path.basename(self.rootLocation))
# ----------------------------------------------------------------------------------------------
# file
# ----------------------------------------------------------------------------------------------
if not self.clipboardArchive.isChecked():
# save to file
exportFileLocation = nuke.getFilename("Export Archive", "*.hotbox")
if exportFileLocation == None:
return
if not exportFileLocation.endswith(".hotbox"):
exportFileLocation += ".hotbox"
shutil.copy(archiveLocation, exportFileLocation)
nuke.message(
"Successfully exported archive to \n{}".format(exportFileLocation)
)
# ----------------------------------------------------------------------------------------------
# clipboard
# ----------------------------------------------------------------------------------------------
else:
# nuke 13
if nuke.NUKE_VERSION_MAJOR > 12:
# read from file
with open(archiveLocation, "rb") as tar:
archiveContent = tar.read()
# convert bytes to text
encodedArchive = str(base64.b64encode(archiveContent))
encodedArchive = encodedArchive[2:-1]
# nuke 12 and older
else:
# read from file
with open(archiveLocation) as tar:
archiveContent = tar.read()
encodedArchive = base64.b64encode(archiveContent)
# save to clipboard
QtWidgets.QApplication.clipboard().setText(encodedArchive)
def indexArchive(self, location, dict=False):
if dict:
fileList = {}
else:
fileList = []
for root, b, files in os.walk(location):
root = root.replace("\\", "/")
level = root.replace(location, "")
if "/_" not in level and "/." not in level:
newLevel = level
if "_name.json" in files:
readName = open(root + "/_name.json").read()
if "/" in readName:
readName = newLevel.replace("/", "**BACKSLASH**")
newLevel = "/".join(level.split("/")[:-1]) + "/" + readName
for file in files:
if not file.startswith("."):
newFile = file
if len(file) == 6:
openFile = open(root + "/" + file).readlines()
nameTag = "# NAME: "
for line in openFile:
if line.startswith(nameTag):
newFile = line.split(nameTag)[-1].replace("\n", "")
if "/" in newFile:
newFile = newFile.replace("/", "**BACKSLASH**")
if dict:
fileList[newLevel + "/" + newFile] = level + "/" + file
else:
fileList.append(
[level + "/" + file, newLevel + "/" + newFile]
)
return fileList
# import
def importHotboxArchive(self):
"""
A method to import a set of buttons to append the current archive with.
If you're actually reading this, I apologise in advance for what's coming.
I had trouble getting the code to work on Windows and it turned out it had to do with
(back)slashes. I ended up trowing in a lot of ".replace('\\','/')". I works, but it
turned kinda messy...
"""