forked from jedypod/nuke-config
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknob_scripter.py
3372 lines (2917 loc) · 145 KB
/
knob_scripter.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 nuke
from nukescripts import panels
import os
import sys
import json
import re
import platform
import subprocess
import traceback
import string
from functools import partial
from threading import Event, Thread
from nuketools.QtUtils import *
#Symlinks on windows...
if os.name == "nt":
def symlink_ms(source, link_name):
import ctypes
csl = ctypes.windll.kernel32.CreateSymbolicLinkW
csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
csl.restype = ctypes.c_ubyte
flags = 1 if os.path.isdir(source) else 0
try:
if csl(link_name, source.replace('/', '\\'), flags) == 0:
raise ctypes.WinError()
except:
pass
os.symlink = symlink_ms
if nuke.NUKE_VERSION_MAJOR < 11:
from PySide import QtCore, QtGui, QtGui as QtWidgets
else:
from PySide2 import QtWidgets, QtGui, QtCore
KS_DIR = os.path.dirname(__file__)
icons_path = KS_DIR+"/knobscripter_icons/"
DebugMode = False
AllKnobScripters = [] # All open instances at a given time
PrefsPanel = ""
SnippetEditPanel = ""
class KnobScripter(QtWidgets.QDialog):
def __init__(self, node="", knob="knobChanged", _parent=QtWidgets.QApplication.activeWindow()):
super(KnobScripter,self).__init__(_parent)
# Autosave the other knobscripters and add this one
for ks in AllKnobScripters:
try:
ks.autosave()
except:
pass
if self not in AllKnobScripters:
AllKnobScripters.append(self)
self.nodeMode = (node != "")
if node == "":
self.node = nuke.toNode("root")
else:
self.node = node
self.isPane = False
self.knob = knob
self.show_labels = False # For the option to also display the knob labels on the knob dropdown
self.unsavedKnobs = {}
self.modifiedKnobs = set()
self.scrollPos = {}
self.cursorPos = {}
self.fontSize = 10
self.font = "Monospace"
self.tabSpaces = 4
self.windowDefaultSize = [500, 300]
self.color_scheme = "sublime" # Can be nuke or sublime
self.pinned = 1
self.toLoadKnob = True
self.frw_open = False # Find replace widget closed by default
self.icon_size = 17
self.btn_size = 24
self.qt_icon_size = QtCore.QSize(self.icon_size,self.icon_size)
self.qt_btn_size = QtCore.QSize(self.btn_size,self.btn_size)
self.origConsoleText = ""
self.nukeSE = self.findSE()
self.nukeSEOutput = self.findSEOutput(self.nukeSE)
self.nukeSEInput = self.findSEInput(self.nukeSE)
self.nukeSERunBtn = self.findSERunBtn(self.nukeSE)
self.scripts_dir = os.path.expandvars(os.path.expanduser("~/.nuke/KnobScripter_Scripts"))
self.current_folder = "scripts"
self.folder_index = 0
self.current_script = "Untitled.py"
self.current_script_modified = False
self.script_index = 0
self.toAutosave = False
# Load prefs
self.prefs_txt = os.path.expandvars(os.path.expanduser("~/.nuke/KnobScripter_Prefs.txt"))
self.loadedPrefs = self.loadPrefs()
if self.loadedPrefs != []:
try:
if "font_size" in self.loadedPrefs:
self.fontSize = self.loadedPrefs['font_size']
self.windowDefaultSize = [self.loadedPrefs['window_default_w'], self.loadedPrefs['window_default_h']]
self.tabSpaces = self.loadedPrefs['tab_spaces']
self.pinned = self.loadedPrefs['pin_default']
if "font" in self.loadedPrefs:
self.font = self.loadedPrefs['font']
if "color_scheme" in self.loadedPrefs:
self.color_scheme = self.loadedPrefs['color_scheme']
if "show_labels" in self.loadedPrefs:
self.show_labels = self.loadedPrefs['show_labels']
except TypeError:
log("KnobScripter: Failed to load preferences.")
# Load snippets
self.snippets_txt_path = os.path.expandvars(os.path.expanduser("~/.nuke/KnobScripter_Snippets.txt"))
self.snippets = self.loadSnippets(maxDepth=5)
# Current state of script (loaded when exiting node mode)
self.state_txt_path = os.path.expandvars(os.path.expanduser("~/.nuke/KnobScripter_State.txt"))
# Init UI
self.initUI()
# Talk to Nuke's Script Editor
self.setSEOutputEvent() # Make the output windowS listen!
self.clearConsole()
def initUI(self):
''' Initializes the tool UI'''
#-------------------
# 1. MAIN WINDOW
#-------------------
self.resize(self.windowDefaultSize[0],self.windowDefaultSize[1])
self.setWindowTitle("KnobScripter - %s %s" % (self.node.fullName(),self.knob))
self.setObjectName( "com.adrianpueyo.knobscripter" )
self.move(QtGui.QCursor().pos() - QtCore.QPoint(32,74))
#---------------------
# 2. TOP BAR
#---------------------
# ---
# 2.1. Left buttons
self.change_btn = QtWidgets.QToolButton()
#self.exit_node_btn.setIcon(QtGui.QIcon(KS_DIR+"/KnobScripter/icons/icons8-delete-26.png"))
self.change_btn.setIcon(QtGui.QIcon(icons_path+"icon_pick.png"))
self.change_btn.setIconSize(self.qt_icon_size)
self.change_btn.setFixedSize(self.qt_btn_size)
self.change_btn.setToolTip("Change to node if selected. Otherwise, change to Script Mode.")
self.change_btn.clicked.connect(self.changeClicked)
# ---
# 2.2.A. Node mode UI
self.exit_node_btn = QtWidgets.QToolButton()
self.exit_node_btn.setIcon(QtGui.QIcon(icons_path+"icon_exitnode.png"))
self.exit_node_btn.setIconSize(self.qt_icon_size)
self.exit_node_btn.setFixedSize(self.qt_btn_size)
self.exit_node_btn.setToolTip("Exit the node, and change to Script Mode.")
self.exit_node_btn.clicked.connect(self.exitNodeMode)
self.current_node_label_node = QtWidgets.QLabel(" Node:")
self.current_node_label_name = QtWidgets.QLabel(self.node.fullName())
self.current_node_label_name.setStyleSheet("font-weight:bold;")
self.current_knob_label = QtWidgets.QLabel("Knob: ")
self.current_knob_dropdown = QtWidgets.QComboBox()
self.current_knob_dropdown.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
self.updateKnobDropdown()
self.current_knob_dropdown.currentIndexChanged.connect(lambda: self.loadKnobValue(False,updateDict=True))
# Layout
self.node_mode_bar_layout = QtWidgets.QHBoxLayout()
self.node_mode_bar_layout.addWidget(self.exit_node_btn)
self.node_mode_bar_layout.addSpacing(2)
self.node_mode_bar_layout.addWidget(self.current_node_label_node)
self.node_mode_bar_layout.addWidget(self.current_node_label_name)
self.node_mode_bar_layout.addSpacing(2)
self.node_mode_bar_layout.addWidget(self.current_knob_dropdown)
self.node_mode_bar = QtWidgets.QWidget()
self.node_mode_bar.setLayout(self.node_mode_bar_layout)
self.node_mode_bar_layout.setContentsMargins(0,0,0,0)
# ---
# 2.2.B. Script mode UI
self.script_label = QtWidgets.QLabel("Script: ")
self.current_folder_dropdown = QtWidgets.QComboBox()
self.current_folder_dropdown.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
self.current_folder_dropdown.currentIndexChanged.connect(self.folderDropdownChanged)
#self.current_folder_dropdown.setEditable(True)
#self.current_folder_dropdown.lineEdit().setReadOnly(True)
#self.current_folder_dropdown.lineEdit().setAlignment(Qt.AlignRight)
self.current_script_dropdown = QtWidgets.QComboBox()
self.current_script_dropdown.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
self.updateFoldersDropdown()
self.updateScriptsDropdown()
self.current_script_dropdown.currentIndexChanged.connect(self.scriptDropdownChanged)
# Layout
self.script_mode_bar_layout = QtWidgets.QHBoxLayout()
self.script_mode_bar_layout.addWidget(self.script_label)
self.script_mode_bar_layout.addSpacing(2)
self.script_mode_bar_layout.addWidget(self.current_folder_dropdown)
self.script_mode_bar_layout.addWidget(self.current_script_dropdown)
self.script_mode_bar = QtWidgets.QWidget()
self.script_mode_bar.setLayout(self.script_mode_bar_layout)
self.script_mode_bar_layout.setContentsMargins(0,0,0,0)
# ---
# 2.3. File-system buttons
# Refresh dropdowns
self.refresh_btn = QtWidgets.QToolButton()
self.refresh_btn.setIcon(QtGui.QIcon(icons_path+"icon_refresh.png"))
self.refresh_btn.setIconSize(QtCore.QSize(50,50))
self.refresh_btn.setIconSize(self.qt_icon_size)
self.refresh_btn.setFixedSize(self.qt_btn_size)
self.refresh_btn.setToolTip("Refresh the dropdowns.\nShortcut: F5")
self.refresh_btn.setShortcut('F5')
self.refresh_btn.clicked.connect(self.refreshClicked)
# Reload script
self.reload_btn = QtWidgets.QToolButton()
self.reload_btn.setIcon(QtGui.QIcon(icons_path+"icon_download.png"))
self.reload_btn.setIconSize(QtCore.QSize(50,50))
self.reload_btn.setIconSize(self.qt_icon_size)
self.reload_btn.setFixedSize(self.qt_btn_size)
self.reload_btn.setToolTip("Reload the current script. Will overwrite any changes made to it.\nShortcut: Ctrl+R")
self.reload_btn.setShortcut('Ctrl+R')
self.reload_btn.clicked.connect(self.reloadClicked)
# Save script
self.save_btn = QtWidgets.QToolButton()
self.save_btn.setIcon(QtGui.QIcon(icons_path+"icon_save.png"))
self.save_btn.setIconSize(QtCore.QSize(50,50))
self.save_btn.setIconSize(self.qt_icon_size)
self.save_btn.setFixedSize(self.qt_btn_size)
self.save_btn.setToolTip("Save the script into the selected knob or python file.\nShortcut: Ctrl+S")
self.save_btn.setShortcut('Ctrl+S')
self.save_btn.clicked.connect(self.saveClicked)
# Layout
self.top_file_bar_layout = QtWidgets.QHBoxLayout()
self.top_file_bar_layout.addWidget(self.refresh_btn)
self.top_file_bar_layout.addWidget(self.reload_btn)
self.top_file_bar_layout.addWidget(self.save_btn)
# ---
# 2.4. Right Side buttons
# Run script
self.run_script_button = QtWidgets.QToolButton()
self.run_script_button.setIcon(QtGui.QIcon(icons_path+"icon_run.png"))
self.run_script_button.setIconSize(self.qt_icon_size)
#self.run_script_button.setIconSize(self.qt_icon_size)
self.run_script_button.setFixedSize(self.qt_btn_size)
self.run_script_button.setToolTip("Execute the current selection on the KnobScripter, or the whole script if no selection.\nShortcut: Ctrl+Enter")
self.run_script_button.clicked.connect(self.runScript)
# Clear console
self.clear_console_button = QtWidgets.QToolButton()
self.clear_console_button.setIcon(QtGui.QIcon(icons_path+"icon_clearConsole.png"))
self.clear_console_button.setIconSize(QtCore.QSize(50,50))
self.clear_console_button.setIconSize(self.qt_icon_size)
self.clear_console_button.setFixedSize(self.qt_btn_size)
self.clear_console_button.setToolTip("Clear the text in the console window.\nShortcut: Click Backspace on the console.")
self.clear_console_button.clicked.connect(self.clearConsole)
# FindReplace button
self.find_button = QtWidgets.QToolButton()
self.find_button.setIcon(QtGui.QIcon(icons_path+"icon_search.png"))
self.find_button.setIconSize(self.qt_icon_size)
self.find_button.setFixedSize(self.qt_btn_size)
self.find_button.setToolTip("Call the snippets by writing the shortcut and pressing Tab.\nShortcut: Ctrl+F")
self.find_button.setShortcut('Ctrl+F')
#self.find_button.setMaximumWidth(self.find_button.fontMetrics().boundingRect("Find").width() + 20)
self.find_button.setCheckable(True)
self.find_button.setFocusPolicy(QtCore.Qt.NoFocus)
self.find_button.clicked[bool].connect(self.toggleFRW)
if self.frw_open:
self.find_button.toggle()
# Snippets
self.snippets_button = QtWidgets.QToolButton()
self.snippets_button.setIcon(QtGui.QIcon(icons_path+"icon_snippets.png"))
self.snippets_button.setIconSize(QtCore.QSize(50,50))
self.snippets_button.setIconSize(self.qt_icon_size)
self.snippets_button.setFixedSize(self.qt_btn_size)
self.snippets_button.setToolTip("Call the snippets by writing the shortcut and pressing Tab.")
self.snippets_button.clicked.connect(self.openSnippets)
# PIN
'''
self.pin_button = QtWidgets.QPushButton("P")
self.pin_button.setCheckable(True)
if self.pinned:
self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
self.pin_button.toggle()
self.pin_button.setToolTip("Toggle 'Always On Top'. Keeps the KnobScripter on top of all other windows.")
self.pin_button.setFocusPolicy(QtCore.Qt.NoFocus)
self.pin_button.setFixedSize(self.qt_btn_size)
self.pin_button.clicked[bool].connect(self.pin)
'''
# Prefs
self.createPrefsMenu()
self.prefs_button = QtWidgets.QPushButton()
self.prefs_button.setIcon(QtGui.QIcon(icons_path+"icon_prefs.png"))
self.prefs_button.setIconSize(self.qt_icon_size)
self.prefs_button.setFixedSize(QtCore.QSize(self.btn_size+10,self.btn_size))
#self.prefs_button.clicked.connect(self.openPrefs)
self.prefs_button.setMenu(self.prefsMenu)
self.prefs_button.setStyleSheet("text-align:left;padding-left:2px;")
#self.prefs_button.setMaximumWidth(self.prefs_button.fontMetrics().boundingRect("Prefs").width() + 12)
# Layout
self.top_right_bar_layout = QtWidgets.QHBoxLayout()
self.top_right_bar_layout.addWidget(self.run_script_button)
self.top_right_bar_layout.addWidget(self.clear_console_button)
self.top_right_bar_layout.addWidget(self.find_button)
##self.top_right_bar_layout.addWidget(self.snippets_button)
##self.top_right_bar_layout.addWidget(self.pin_button)
#self.top_right_bar_layout.addSpacing(10)
self.top_right_bar_layout.addWidget(self.prefs_button)
# ---
# Layout
self.top_layout = QtWidgets.QHBoxLayout()
self.top_layout.setContentsMargins(0,0,0,0)
#self.top_layout.setSpacing(10)
self.top_layout.addWidget(self.change_btn)
self.top_layout.addWidget(self.node_mode_bar)
self.top_layout.addWidget(self.script_mode_bar)
self.node_mode_bar.setVisible(False)
#self.top_layout.addSpacing(10)
self.top_layout.addLayout(self.top_file_bar_layout)
self.top_layout.addStretch()
self.top_layout.addLayout(self.top_right_bar_layout)
#----------------------
# 3. SCRIPTING SECTION
#----------------------
# Splitter
self.splitter = QtWidgets.QSplitter(Qt.Vertical)
# Output widget
self.script_output = ScriptOutputWidget(parent=self)
self.script_output.setReadOnly(1)
self.script_output.setAcceptRichText(0)
self.script_output.setTabStopWidth(self.script_output.tabStopWidth() / 4)
self.script_output.setFocusPolicy(Qt.ClickFocus)
self.script_output.setAutoFillBackground( 0 )
self.script_output.installEventFilter(self)
# Script Editor
self.script_editor = KnobScripterTextEditMain(self, self.script_output)
self.script_editor.setMinimumHeight(30)
self.script_editor.setStyleSheet('background:#282828;color:#EEE;') # Main Colors
self.script_editor.textChanged.connect(self.setModified)
self.highlighter = KSScriptEditorHighlighter(self.script_editor.document(), self)
self.script_editor.cursorPositionChanged.connect(self.setTextSelection)
self.script_editor_font = QtGui.QFont()
self.script_editor_font.setFamily(self.font)
self.script_editor_font.setStyleHint(QtGui.QFont.Monospace)
self.script_editor_font.setFixedPitch(True)
self.script_editor_font.setPointSize(self.fontSize)
self.script_editor.setFont(self.script_editor_font)
self.script_editor.setTabStopWidth(self.tabSpaces * QtGui.QFontMetrics(self.script_editor_font).width(' '))
# Add input and output to splitter
self.splitter.addWidget(self.script_output)
self.splitter.addWidget(self.script_editor)
self.splitter.setStretchFactor(0,0)
# FindReplace widget
self.frw = FindReplaceWidget(self)
self.frw.setVisible(self.frw_open)
# ---
# Layout
self.scripting_layout = QtWidgets.QVBoxLayout()
self.scripting_layout.setContentsMargins(0,0,0,0)
self.scripting_layout.setSpacing(0)
self.scripting_layout.addWidget(self.splitter)
self.scripting_layout.addWidget(self.frw)
#---------------
# MASTER LAYOUT
#---------------
self.master_layout = QtWidgets.QVBoxLayout()
self.master_layout.setSpacing(5)
self.master_layout.setContentsMargins(8,8,8,8)
self.master_layout.addLayout(self.top_layout)
self.master_layout.addLayout(self.scripting_layout)
##self.master_layout.addLayout(self.bottom_layout)
self.setLayout(self.master_layout)
#----------------
# MAIN WINDOW UI
#----------------
size_policy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.setSizePolicy(size_policy)
self.setMinimumWidth(160)
if self.pinned:
self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
# Set default values based on mode
if self.nodeMode:
self.current_knob_dropdown.blockSignals(True)
self.node_mode_bar.setVisible(True)
self.script_mode_bar.setVisible(False)
self.setCurrentKnob(self.knob)
self.loadKnobValue(check = False)
self.setKnobModified(False)
self.current_knob_dropdown.blockSignals(False)
self.splitter.setSizes([0,1])
else:
self.exitNodeMode()
self.script_editor.setFocus()
# Preferences submenus
def createPrefsMenu(self):
# Actions
self.echoAct = QtWidgets.QAction("Echo python commands", self, checkable=True, statusTip="Toggle nuke's 'Echo all python commands to ScriptEditor'", triggered=self.toggleEcho)
if nuke.toNode("preferences").knob("echoAllCommands").value():
self.echoAct.toggle()
self.pinAct = QtWidgets.QAction("Always on top", self, checkable=True, statusTip="Keeps the KnobScripter window always on top or not.", triggered=self.togglePin)
if self.pinned:
self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
self.pinAct.toggle()
self.snippetsAct = QtWidgets.QAction("Snippets", self, statusTip="Open the Snippets editor.", triggered=self.openSnippets)
self.snippetsAct.setIcon(QtGui.QIcon(icons_path+"icon_snippets.png"))
#self.snippetsAct = QtWidgets.QAction("Keywords", self, statusTip="Add custom keywords.", triggered=self.openSnippets) #TODO THIS
self.prefsAct = QtWidgets.QAction("Preferences", self, statusTip="Open the Preferences panel.", triggered=self.openPrefs)
self.prefsAct.setIcon(QtGui.QIcon(icons_path+"icon_prefs.png"))
# Menus
self.prefsMenu = QtWidgets.QMenu("Preferences")
self.prefsMenu.addAction(self.echoAct)
self.prefsMenu.addAction(self.pinAct)
self.prefsMenu.addSeparator()
self.prefsMenu.addAction(self.snippetsAct)
self.prefsMenu.addAction(self.prefsAct)
def initEcho(self):
''' Initializes the echo chechable QAction based on nuke's state '''
echo_knob = nuke.toNode("preferences").knob("echoAllCommands")
self.echoAct.setChecked(echo_knob.value())
def toggleEcho(self):
''' Toggle the "Echo python commands" from Nuke '''
echo_knob = nuke.toNode("preferences").knob("echoAllCommands")
echo_knob.setValue(self.echoAct.isChecked())
def togglePin(self):
''' Toggle "always on top" based on the submenu button '''
self.pin(self.pinAct.isChecked())
# Node Mode
def updateKnobDropdown(self):
''' Populate knob dropdown list '''
self.current_knob_dropdown.clear() # First remove all items
defaultKnobs = ["knobChanged", "onCreate", "onScriptLoad", "onScriptSave", "onScriptClose", "onDestroy",
"updateUI", "autolabel", "beforeRender", "beforeFrameRender", "afterFrameRender", "afterRender"]
permittedKnobClasses = ["PyScript_Knob", "PythonCustomKnob"]
counter = 0
for i in self.node.knobs():
if i not in defaultKnobs and self.node.knob(i).Class() in permittedKnobClasses:
if self.show_labels:
i_full = "{} ({})".format(self.node.knob(i).label(), i)
else:
i_full = i
if i in self.unsavedKnobs.keys():
self.current_knob_dropdown.addItem(i_full+"(*)", i)
else:
self.current_knob_dropdown.addItem(i_full, i)
counter += 1
if counter > 0:
self.current_knob_dropdown.insertSeparator(counter)
counter += 1
self.current_knob_dropdown.insertSeparator(counter)
counter += 1
for i in self.node.knobs():
if i in defaultKnobs:
if i in self.unsavedKnobs.keys():
self.current_knob_dropdown.addItem(i+"(*)", i)
else:
self.current_knob_dropdown.addItem(i, i)
counter += 1
return
def loadKnobValue(self, check=True, updateDict=False):
''' Get the content of the knob value and populate the editor '''
if self.toLoadKnob == False:
return
dropdown_value = self.current_knob_dropdown.itemData(self.current_knob_dropdown.currentIndex()) # knobChanged...
try:
obtained_knobValue = str(self.node[dropdown_value].value())
obtained_scrollValue = 0
edited_knobValue = self.script_editor.toPlainText()
except:
error_message = QtWidgets.QMessageBox.information(None, "", "Unable to find %s.%s"%(self.node.name(),dropdown_value))
error_message.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
error_message.exec_()
return
# If there were changes to the previous knob, update the dictionary
if updateDict==True:
self.unsavedKnobs[self.knob] = edited_knobValue
self.scrollPos[self.knob] = self.script_editor.verticalScrollBar().value()
prev_knob = self.knob # knobChanged...
self.knob = self.current_knob_dropdown.itemData(self.current_knob_dropdown.currentIndex()) # knobChanged...
if check and obtained_knobValue != edited_knobValue:
msgBox = QtWidgets.QMessageBox()
msgBox.setText("The Script Editor has been modified.")
msgBox.setInformativeText("Do you want to overwrite the current code on this editor?")
msgBox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
msgBox.setIcon(QtWidgets.QMessageBox.Question)
msgBox.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
msgBox.setDefaultButton(QtWidgets.QMessageBox.Yes)
reply = msgBox.exec_()
if reply == QtWidgets.QMessageBox.No:
self.setCurrentKnob(prev_knob)
return
# If order comes from a dropdown update, update value from dictionary if possible, otherwise update normally
self.setWindowTitle("KnobScripter - %s %s" % (self.node.name(), self.knob))
if updateDict:
if self.knob in self.unsavedKnobs:
if self.unsavedKnobs[self.knob] == obtained_knobValue:
self.script_editor.setPlainText(obtained_knobValue)
self.setKnobModified(False)
else:
obtained_knobValue = self.unsavedKnobs[self.knob]
self.script_editor.setPlainText(obtained_knobValue)
self.setKnobModified(True)
else:
self.script_editor.setPlainText(obtained_knobValue)
self.setKnobModified(False)
if self.knob in self.scrollPos:
obtained_scrollValue = self.scrollPos[self.knob]
else:
self.script_editor.setPlainText(obtained_knobValue)
cursor = self.script_editor.textCursor()
self.script_editor.setTextCursor(cursor)
self.script_editor.verticalScrollBar().setValue(obtained_scrollValue)
return
def loadAllKnobValues(self):
''' Load all knobs button's function '''
if len(self.unsavedKnobs)>=1:
msgBox = QtWidgets.QMessageBox()
msgBox.setText("Do you want to reload all python and callback knobs?")
msgBox.setInformativeText("Unsaved changes on this editor will be lost.")
msgBox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
msgBox.setIcon(QtWidgets.QMessageBox.Question)
msgBox.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
msgBox.setDefaultButton(QtWidgets.QMessageBox.Yes)
reply = msgBox.exec_()
if reply == QtWidgets.QMessageBox.No:
return
self.unsavedKnobs = {}
return
def saveKnobValue(self, check=True):
''' Save the text from the editor to the node's knobChanged knob '''
dropdown_value = self.current_knob_dropdown.itemData(self.current_knob_dropdown.currentIndex())
try:
obtained_knobValue = str(self.node[dropdown_value].value())
self.knob = dropdown_value
except:
error_message = QtWidgets.QMessageBox.information(None, "", "Unable to find %s.%s"%(self.node.name(),dropdown_value))
error_message.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
error_message.exec_()
return
edited_knobValue = self.script_editor.toPlainText()
if check and obtained_knobValue != edited_knobValue:
msgBox = QtWidgets.QMessageBox()
msgBox.setText("Do you want to overwrite %s.%s?"%(self.node.name(),dropdown_value))
msgBox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
msgBox.setIcon(QtWidgets.QMessageBox.Question)
msgBox.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
msgBox.setDefaultButton(QtWidgets.QMessageBox.Yes)
reply = msgBox.exec_()
if reply == QtWidgets.QMessageBox.No:
return
self.node[dropdown_value].setValue(edited_knobValue)
self.setKnobModified(modified = False, knob = dropdown_value, changeTitle = True)
nuke.tcl("modified 1")
if self.knob in self.unsavedKnobs:
del self.unsavedKnobs[self.knob]
return
def saveAllKnobValues(self, check=True):
''' Save all knobs button's function '''
if self.updateUnsavedKnobs() > 0 and check:
msgBox = QtWidgets.QMessageBox()
msgBox.setText("Do you want to save all modified python and callback knobs?")
msgBox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
msgBox.setIcon(QtWidgets.QMessageBox.Question)
msgBox.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
msgBox.setDefaultButton(QtWidgets.QMessageBox.Yes)
reply = msgBox.exec_()
if reply == QtWidgets.QMessageBox.No:
return
saveErrors = 0
savedCount = 0
for k in self.unsavedKnobs.copy():
try:
self.node.knob(k).setValue(self.unsavedKnobs[k])
del self.unsavedKnobs[k]
savedCount += 1
nuke.tcl("modified 1")
except:
saveErrors+=1
if saveErrors > 0:
errorBox = QtWidgets.QMessageBox()
errorBox.setText("Error saving %s knob%s." % (str(saveErrors),int(saveErrors>1)*"s"))
errorBox.setIcon(QtWidgets.QMessageBox.Warning)
errorBox.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
errorBox.setDefaultButton(QtWidgets.QMessageBox.Yes)
reply = errorBox.exec_()
else:
log("KnobScripter: %s knobs saved" % str(savedCount))
return
def setCurrentKnob(self, knobToSet):
''' Set current knob '''
KnobDropdownItems = []
for i in range(self.current_knob_dropdown.count()):
if self.current_knob_dropdown.itemData(i) is not None:
KnobDropdownItems.append(self.current_knob_dropdown.itemData(i))
else:
KnobDropdownItems.append("---")
if knobToSet in KnobDropdownItems:
index = KnobDropdownItems.index(knobToSet)
self.current_knob_dropdown.setCurrentIndex(index)
return
def updateUnsavedKnobs(self, first_time=False):
''' Clear unchanged knobs from the dict and return the number of unsaved knobs '''
if not self.node:
# Node has been deleted, so simply return 0. Who cares.
return 0
edited_knobValue = self.script_editor.toPlainText()
self.unsavedKnobs[self.knob] = edited_knobValue
if len(self.unsavedKnobs) > 0:
for k in self.unsavedKnobs.copy():
if self.node.knob(k):
if str(self.node.knob(k).value()) == str(self.unsavedKnobs[k]):
del self.unsavedKnobs[k]
else:
del self.unsavedKnobs[k]
# Set appropriate knobs modified...
knobs_dropdown = self.current_knob_dropdown
all_knobs = [knobs_dropdown.itemData(i) for i in range(knobs_dropdown.count())]
for key in all_knobs:
if key in self.unsavedKnobs.keys():
self.setKnobModified(modified = True, knob = key, changeTitle = False)
else:
self.setKnobModified(modified = False, knob = key, changeTitle = False)
return len(self.unsavedKnobs)
def setKnobModified(self, modified = True, knob = "", changeTitle = True):
''' Sets the current knob modified, title and whatever else we need '''
if knob == "":
knob = self.knob
if modified:
self.modifiedKnobs.add(knob)
else:
self.modifiedKnobs.discard(knob)
if changeTitle:
title_modified_string = " [modified]"
windowTitle = self.windowTitle().split(title_modified_string)[0]
if modified == True:
windowTitle += title_modified_string
self.setWindowTitle(windowTitle)
try:
knobs_dropdown = self.current_knob_dropdown
kd_index = knobs_dropdown.currentIndex()
kd_data = knobs_dropdown.itemData(kd_index)
if self.show_labels and i not in defaultKnobs:
kd_data = "{} ({})".format(self.node.knob(kd_data).label(), kd_data)
if modified == False:
knobs_dropdown.setItemText(kd_index, kd_data)
else:
knobs_dropdown.setItemText(kd_index, kd_data+"(*)")
except:
pass
# Script Mode
def updateFoldersDropdown(self):
''' Populate folders dropdown list '''
self.current_folder_dropdown.blockSignals(True)
self.current_folder_dropdown.clear() # First remove all items
defaultFolders = ["scripts"]
scriptFolders = []
counter = 0
for f in defaultFolders:
self.makeScriptFolder(f)
self.current_folder_dropdown.addItem(f+"/", f)
counter += 1
try:
scriptFolders = sorted([f for f in os.listdir(self.scripts_dir) if os.path.isdir(os.path.join(self.scripts_dir, f))]) # Accepts symlinks!!!
except:
log("Couldn't read any script folders.")
for f in scriptFolders:
fname = f.split("/")[-1]
if fname in defaultFolders:
continue
self.current_folder_dropdown.addItem(fname+"/", fname)
counter += 1
#print scriptFolders
if counter > 0:
self.current_folder_dropdown.insertSeparator(counter)
counter += 1
#self.current_folder_dropdown.insertSeparator(counter)
#counter += 1
self.current_folder_dropdown.addItem("New", "create new")
self.current_folder_dropdown.addItem("Open...", "open in browser")
self.current_folder_dropdown.addItem("Add custom", "add custom path")
self.folder_index = self.current_folder_dropdown.currentIndex()
self.current_folder = self.current_folder_dropdown.itemData(self.folder_index)
self.current_folder_dropdown.blockSignals(False)
return
def updateScriptsDropdown(self):
''' Populate py scripts dropdown list '''
self.current_script_dropdown.blockSignals(True)
self.current_script_dropdown.clear() # First remove all items
QtWidgets.QApplication.processEvents()
log("# Updating scripts dropdown...")
log("scripts dir:"+self.scripts_dir)
log("current folder:"+self.current_folder)
log("previous current script:"+self.current_script)
#current_folder = self.current_folder_dropdown.itemData(self.current_folder_dropdown.currentIndex())
current_folder_path = os.path.join(self.scripts_dir,self.current_folder)
defaultScripts = ["Untitled.py"]
found_scripts = []
counter = 0
dir_list = os.listdir(current_folder_path) # All files and folders inside of the folder
try:
found_scripts = sorted([f for f in dir_list if f.endswith(".py")])
found_temp_scripts = [f for f in dir_list if f.endswith(".py.autosave")]
except:
log("Couldn't find any scripts in the selected folder.")
if not len(found_scripts):
for s in defaultScripts:
if s+".autosave" in found_temp_scripts:
self.current_script_dropdown.addItem(s+"(*)",s)
else:
self.current_script_dropdown.addItem(s,s)
counter += 1
else:
for s in defaultScripts:
if s+".autosave" in found_temp_scripts:
self.current_script_dropdown.addItem(s+"(*)",s)
elif s in found_scripts:
self.current_script_dropdown.addItem(s,s)
for s in found_scripts:
if s in defaultScripts:
continue
sname = s.split("/")[-1]
if s+".autosave" in found_temp_scripts:
self.current_script_dropdown.addItem(sname+"(*)", sname)
else:
self.current_script_dropdown.addItem(sname, sname)
counter += 1
##else: #Add the found scripts to the dropdown
if counter > 0:
counter += 1
self.current_script_dropdown.insertSeparator(counter)
counter += 1
self.current_script_dropdown.insertSeparator(counter)
self.current_script_dropdown.addItem("New", "create new")
self.current_script_dropdown.addItem("Duplicate", "create duplicate")
self.current_script_dropdown.addItem("Delete", "delete script")
self.current_script_dropdown.addItem("Open", "open in browser")
#self.script_index = self.current_script_dropdown.currentIndex()
self.script_index = 0
self.current_script = self.current_script_dropdown.itemData(self.script_index)
log("Finished updating scripts dropdown.")
log("current_script:"+self.current_script)
self.current_script_dropdown.blockSignals(False)
return
def makeScriptFolder(self, name = "scripts"):
folder_path = os.path.join(self.scripts_dir,name)
if not os.path.exists(folder_path):
try:
os.makedirs(folder_path)
return True
except:
print "Couldn't create the scripting folders.\nPlease check your OS write permissions."
return False
def makeScriptFile(self, name = "Untitled.py", folder = "scripts", empty = True):
script_path = os.path.join(self.scripts_dir, self.current_folder, name)
if not os.path.isfile(script_path):
try:
self.current_script_file = open(script_path, 'w')
return True
except:
print "Couldn't create the scripting folders.\nPlease check your OS write permissions."
return False
def setCurrentFolder(self, folderName):
''' Set current folder ON THE DROPDOWN ONLY'''
folderList = [self.current_folder_dropdown.itemData(i) for i in range(self.current_folder_dropdown.count())]
if folderName in folderList:
index = folderList.index(folderName)
self.current_folder_dropdown.setCurrentIndex(index)
self.current_folder = folderName
self.folder_index = self.current_folder_dropdown.currentIndex()
self.current_folder = self.current_folder_dropdown.itemData(self.folder_index)
return
def setCurrentScript(self, scriptName):
''' Set current script ON THE DROPDOWN ONLY '''
scriptList = [self.current_script_dropdown.itemData(i) for i in range(self.current_script_dropdown.count())]
if scriptName in scriptList:
index = scriptList.index(scriptName)
self.current_script_dropdown.setCurrentIndex(index)
self.current_script = scriptName
self.script_index = self.current_script_dropdown.currentIndex()
self.current_script = self.current_script_dropdown.itemData(self.script_index)
return
def loadScriptContents(self, check = False, pyOnly = False, folder=""):
''' Get the contents of the selected script and populate the editor '''
log("# About to load script contents now.")
obtained_scrollValue = 0
obtained_cursorPosValue = [0,0] #Position, anchor
if folder == "":
folder = self.current_folder
script_path = os.path.join(self.scripts_dir, folder, self.current_script)
script_path_temp = script_path + ".autosave"
if (self.current_folder+"/"+self.current_script) in self.scrollPos:
obtained_scrollValue = self.scrollPos[self.current_folder+"/"+self.current_script]
if (self.current_folder+"/"+self.current_script) in self.cursorPos:
obtained_cursorPosValue = self.cursorPos[self.current_folder+"/"+self.current_script]
# 1: If autosave exists and pyOnly is false, load it
if os.path.isfile(script_path_temp) and not pyOnly:
log("Loading .py.autosave file\n---")
with open(script_path_temp, 'r') as script:
content = script.read()
self.script_editor.setPlainText(content)
self.setScriptModified(True)
self.script_editor.verticalScrollBar().setValue(obtained_scrollValue)
# 2: Try to load the .py as first priority, if it exists
elif os.path.isfile(script_path):
log("Loading .py file\n---")
with open(script_path, 'r') as script:
content = script.read()
current_text = self.script_editor.toPlainText().encode("utf8")
if check and current_text != content and current_text.strip() != "":
msgBox = QtWidgets.QMessageBox()
msgBox.setText("The script has been modified.")
msgBox.setInformativeText("Do you want to overwrite the current code on this editor?")
msgBox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
msgBox.setIcon(QtWidgets.QMessageBox.Question)
msgBox.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
msgBox.setDefaultButton(QtWidgets.QMessageBox.Yes)
reply = msgBox.exec_()
if reply == QtWidgets.QMessageBox.No:
return
# Clear trash
if os.path.isfile(script_path_temp):
os.remove(script_path_temp)
log("Removed "+script_path_temp)
self.setScriptModified(False)
self.script_editor.setPlainText(content)
self.script_editor.verticalScrollBar().setValue(obtained_scrollValue)
self.setScriptModified(False)
self.loadScriptState()
self.setScriptState()
# 3: If .py doesn't exist... only then stick to the autosave
elif os.path.isfile(script_path_temp):
with open(script_path_temp, 'r') as script:
content = script.read()
msgBox = QtWidgets.QMessageBox()
msgBox.setText("The .py file hasn't been found.")
msgBox.setInformativeText("Do you want to clear the current code on this editor?")
msgBox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
msgBox.setIcon(QtWidgets.QMessageBox.Question)
msgBox.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
msgBox.setDefaultButton(QtWidgets.QMessageBox.Yes)
reply = msgBox.exec_()
if reply == QtWidgets.QMessageBox.No:
return
# Clear trash
os.remove(script_path_temp)
log("Removed "+script_path_temp)
self.script_editor.setPlainText("")
self.updateScriptsDropdown()
self.loadScriptContents(check=False)
self.loadScriptState()
self.setScriptState()
else:
content = ""
self.script_editor.setPlainText(content)
self.setScriptModified(False)
if self.current_folder+"/"+self.current_script in self.scrollPos:
del self.scrollPos[self.current_folder+"/"+self.current_script]
if self.current_folder+"/"+self.current_script in self.cursorPos:
del self.cursorPos[self.current_folder+"/"+self.current_script]
self.setWindowTitle("KnobScripter - %s/%s" % (self.current_folder, self.current_script))
return
def saveScriptContents(self, temp = True):
''' Save the current contents of the editor into the python file. If temp == True, saves a .py.autosave file '''
log("\n# About to save script contents now.")
log("Temp mode is: "+str(temp))
log("self.current_folder: "+self.current_folder)
log("self.current_script: "+self.current_script)
script_path = os.path.join(self.scripts_dir, self.current_folder, self.current_script)
script_path_temp = script_path + ".autosave"
orig_content = ""
content = self.script_editor.toPlainText().encode('utf8')
if temp == True:
if os.path.isfile(script_path):
with open(script_path, 'r') as script:
orig_content = script.read()
elif content == "" and os.path.isfile(script_path_temp): #If script path doesn't exist and autosave does but the script is empty...
os.remove(script_path_temp)
return
if content != orig_content:
with open(script_path_temp, 'w') as script:
script.write(content)
else:
if os.path.isfile(script_path_temp):
os.remove(script_path_temp)
log("Nothing to save")
return
else:
with open(script_path, 'w') as script:
script.write(self.script_editor.toPlainText().encode('utf8'))
# Clear trash
if os.path.isfile(script_path_temp):
os.remove(script_path_temp)
log("Removed "+script_path_temp)
self.setScriptModified(False)
self.saveScrollValue()
self.saveCursorPosValue()
log("Saved "+script_path+"\n---")
return
def deleteScript(self, check = True, folder=""):
''' Get the contents of the selected script and populate the editor '''
log("# About to delete the .py and/or autosave script now.")
if folder == "":
folder = self.current_folder
script_path = os.path.join(self.scripts_dir, folder, self.current_script)
script_path_temp = script_path + ".autosave"
if check:
msgBox = QtWidgets.QMessageBox()
msgBox.setText("You're about to delete this script.")
msgBox.setInformativeText("Are you sure you want to delete {}?".format(self.current_script))
msgBox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
msgBox.setIcon(QtWidgets.QMessageBox.Question)
msgBox.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
msgBox.setDefaultButton(QtWidgets.QMessageBox.No)
reply = msgBox.exec_()
if reply == QtWidgets.QMessageBox.No:
return False
if os.path.isfile(script_path_temp):
os.remove(script_path_temp)
log("Removed "+script_path_temp)
if os.path.isfile(script_path):
os.remove(script_path)
log("Removed "+script_path)