forked from adrianpueyo/KnobScripter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknob_scripter.py
2208 lines (1932 loc) · 97 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
# -*- coding: utf-8 -*-
"""KnobScripter 3 by Adrian Pueyo - Complete python script editor for Nuke.
This is the main KnobScripter module, which defines the classes necessary
to create the floating and docked KnobScripters. Also handles the main
initialization and menu creation in Nuke.
adrianpueyo.com
"""
import os
import json
import io
from nukescripts import panels
import nuke
import re
import subprocess
import platform
from webbrowser import open as open_url
import logging
import datetime
# Symlinks on windows.
if os.name == "nt" and nuke.NUKE_VERSION_MAJOR < 13:
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 AttributeError:
pass
os.symlink = symlink_ms
try:
if nuke.NUKE_VERSION_MAJOR < 11:
from PySide import QtCore, QtGui, QtGui as QtWidgets
from PySide.QtCore import Qt
else:
from PySide2 import QtWidgets, QtGui, QtCore
from PySide2.QtCore import Qt
except ImportError:
from Qt import QtCore, QtGui, QtWidgets
PrefsPanel = ""
SnippetEditPanel = ""
CodeGalleryPanel = ""
now = datetime.datetime.now()
christmas = (now.month == 12 and now.day > 15) or (now.month == 1 and now.day < 15)
# ks imports
from KnobScripter.info import __version__, __date__
from KnobScripter import config, prefs, utils, dialogs, widgets, ksscripteditormain
from KnobScripter import snippets, codegallery, script_output, findreplace, content
# logging.basicConfig(level=logging.DEBUG)
nuke.tprint('KnobScripter v{0}, built {1}.\n'
'Copyright (c) 2016-{2} Adrian Pueyo.'
' All Rights Reserved.'.format(__version__, __date__, __date__.split(" ")[-1]))
# logging.debug('Initializing KnobScripter')
# Init config.script_editor_font (will be overwritten once reading the prefs)
prefs.load_prefs()
def is_blink_knob(knob):
"""
Args:
knob (nuke.Knob): Any Nuke Knob.
Returns:
bool: True if knob is Blink type, False otherwise
"""
node = knob.node()
kn = knob.name()
if kn in ["kernelSource"] and node.Class() in ["BlinkScript"]:
return True
else:
return False
class KnobScripterWidget(QtWidgets.QDialog):
""" Main KnobScripter Widget, which is defined as a floating QDialog by default.
Attributes:
node (nuke.Node, optional): Node on which this KnobScripter widget will run.
knob (nuke.Knob, optional): Knob on which this KnobScripter widget will run.
is_pane (bool, optional): Utility variable for KnobScripterPane.
_parent (QWidget, optional): Parent widget.
"""
def __init__(self, node="", knob="", is_pane=False, _parent=QtWidgets.QApplication.activeWindow()):
super(KnobScripterWidget, self).__init__(_parent)
# Autosave the other knobscripters and add this one
for ks in config.all_knobscripters:
if hasattr(ks, 'autosave'):
ks.autosave()
if self not in config.all_knobscripters:
config.all_knobscripters.append(self)
self.nodeMode = (node != "")
if node == "":
self.node = nuke.toNode("root")
else:
self.node = node
if knob == "":
if "kernelSource" in self.node.knobs() and self.node.Class() == "BlinkScript":
knob = "kernelSource"
else:
knob = "knobChanged"
self.knob = knob
self._parent = _parent
self.isPane = is_pane
self.show_labels = False # For the option to also display the knob labels on the knob dropdown
self.unsaved_knobs = {}
self.modifiedKnobs = set()
self.py_scroll_positions = {}
self.py_cursor_positions = {}
self.py_state_dict = {}
#self.knob_scroll_positions = {}
#self.knob_cursor_positions = {}
self.current_node_state_dict = {}
self.to_load_knob = True
self.frw_open = False # Find replace widget closed by default
self.omit_se_console_text = ""
self.nukeSE = utils.findSE()
self.nukeSEOutput = utils.findSEConsole(self.nukeSE)
self.nukeSEInput = utils.findSEInput(self.nukeSE)
self.nukeSERunBtn = utils.findSERunBtn(self.nukeSE)
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
self.runInContext = config.prefs["ks_run_in_context"] # Experimental, python only
self.code_language = None
self.current_knob_modified = False # Convenience variable holding if the current script_editor is modified
self.defaultKnobs = ["knobChanged", "onCreate", "onScriptLoad", "onScriptSave", "onScriptClose", "onDestroy",
"updateUI", "autolabel", "beforeRender", "beforeFrameRender", "afterFrameRender",
"afterRender"]
self.python_knob_classes = ["PyScript_Knob", "PythonCustomKnob"]
# Load prefs
# self.loadedPrefs = self.loadPrefs()
# Load snippets
content.all_snippets = snippets.load_snippets_dict()
# Init UI
self.initUI()
self.setWindowIcon(QtGui.QIcon(config.KS_ICON_PATH))
utils.setSEConsoleChanged()
self.omit_se_console_text = self.nukeSEOutput.document().toPlainText()
self.clearConsole()
#print(self.py_state_dict) # We need to update it!!!!
def initUI(self):
""" Initializes the tool UI"""
# -------------------
# 1. MAIN WINDOW
# -------------------
self.resize(config.prefs["ks_default_size"][0], config.prefs["ks_default_size"][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 = widgets.APToolButton("pick")
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 = widgets.APToolButton("exitnode")
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, update_dict=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_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 = widgets.APToolButton("refresh")
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 = widgets.APToolButton("download")
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 = widgets.APToolButton("save")
if not self.isPane:
self.save_btn.setShortcut('Ctrl+S')
self.save_btn.setToolTip("Save the script into the selected knob or python file.\nShortcut: Ctrl+S")
else:
self.save_btn.setToolTip("Save the script into the selected knob or python file.")
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
# Python: Run script
self.run_script_button = widgets.APToolButton("run")
self.run_script_button.setToolTip(
"Execute the current selection on the KnobScripter, or the whole script if no selection.\n"
"Shortcut: Ctrl+Enter")
self.run_script_button.clicked.connect(self.runScript)
# Python: Clear console
self.clear_console_button = widgets.APToolButton("clear_console")
self.clear_console_button.setToolTip(
"Clear the text in the console window.\nShortcut: Ctrl+Backspace, or click+Backspace on the console.")
self.clear_console_button.setShortcut('Ctrl+Backspace')
self.clear_console_button.clicked.connect(self.clearConsole)
# Blink: Save & Compile
self.save_recompile_button = widgets.APToolButton("play")
self.save_recompile_button.setToolTip(
"Save the blink code and recompile the Blinkscript node.\nShortcut: Ctrl+Enter")
self.save_recompile_button.clicked.connect(self.blinkSaveRecompile)
# Blink: Backups
self.createBlinkBackupsMenu()
self.backup_button = QtWidgets.QPushButton()
self.backup_button.setIcon(QtGui.QIcon(os.path.join(config.ICONS_DIR, "icon_backups.png")))
self.backup_button.setIconSize(QtCore.QSize(config.prefs["qt_icon_size"], config.prefs["qt_icon_size"]))
self.backup_button.setFixedSize(QtCore.QSize(config.prefs["qt_btn_size"], config.prefs["qt_btn_size"]))
self.backup_button.setToolTip("Blink: Enable and retrieve auto-saves of the code.")
self.backup_button.setMenu(self.blink_menu)
# self.backup_button.setFixedSize(QtCore.QSize(self.btn_size+10,self.btn_size))
self.backup_button.setStyleSheet("text-align:left;padding-left:2px;")
# self.backup_button.clicked.connect(self.blinkBackup) #TODO: whatever this does
# FindReplace button
self.find_button = widgets.APToolButton("search")
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.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()
# Gallery
self.codegallery_button = widgets.APToolButton("enter")
self.codegallery_button.setToolTip("Open the code gallery panel.")
self.codegallery_button.clicked.connect(lambda: self.open_multipanel(tab="code_gallery"))
# Snippets
self.snippets_button = widgets.APToolButton("snippets")
self.snippets_button.setToolTip("Call the snippets by writing the shortcut and pressing Tab.")
self.snippets_button.clicked.connect(lambda: self.open_multipanel(tab="snippet_editor"))
# Prefs
self.createPrefsMenu()
self.prefs_button = QtWidgets.QPushButton()
self.prefs_button.setIcon(QtGui.QIcon(os.path.join(config.ICONS_DIR, "icon_prefs.png")))
self.prefs_button.setIconSize(QtCore.QSize(config.prefs["qt_icon_size"], config.prefs["qt_icon_size"]))
self.prefs_button.setFixedSize(QtCore.QSize(config.prefs["qt_btn_size"] + 10, config.prefs["qt_btn_size"]))
self.prefs_button.setMenu(self.prefsMenu)
self.prefs_button.setStyleSheet("text-align:left;padding-left:2px;")
# 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.save_recompile_button)
self.top_right_bar_layout.addWidget(self.clear_console_button)
self.top_right_bar_layout.addWidget(self.backup_button)
self.top_right_bar_layout.addWidget(self.codegallery_button)
self.top_right_bar_layout.addWidget(self.find_button)
# self.top_right_bar_layout.addWidget(self.snippets_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 = script_output.ScriptOutputWidget(parent=self)
self.script_output.setReadOnly(1)
self.script_output.setAcceptRichText(0)
if config.prefs["se_tab_spaces"] != 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 = ksscripteditormain.KSScriptEditorMain(self, self.script_output)
self.script_editor.setMinimumHeight(30)
self.script_editor.textChanged.connect(self.setModified)
self.script_editor.set_code_language("python")
self.script_editor.cursorPositionChanged.connect(self.setTextSelection)
if config.prefs["se_tab_spaces"] != 0:
self.script_editor.setTabStopWidth(
config.prefs["se_tab_spaces"] * QtGui.QFontMetrics(config.script_editor_font).horizontalAdvance(' '))
# 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 = findreplace.FindReplaceWidget(self.script_editor, 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.setLayout(self.master_layout)
# ----------------
# MAIN WINDOW UI
# ----------------
size_policy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.setSizePolicy(size_policy)
self.setMinimumWidth(160)
# 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)
# Load stored state of knobs
self.loadKnobState()
state_dict = self.current_node_state_dict
if "open_knob" in state_dict and state_dict["open_knob"] in self.node.knobs():
self.knob = state_dict["open_knob"]
elif "kernelSource" in self.node.knobs() and self.node.Class() == "BlinkScript":
self.knob = "kernelSource"
else:
self.knob = "knobChanged"
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.runInContextAct = QtWidgets.QAction("Run in context (beta)", self, checkable=True,
statusTip="When inside a node, run the code replacing "
"nuke.thisNode() to the node's name, etc.",
triggered=self.toggleRunInContext)
self.runInContextAct.setChecked(self.runInContext)
self.helpAct = QtWidgets.QAction("&User Guide (pdf)", self, statusTip="Open the KnobScripter 3 User Guide in your browser.",
shortcut="F1", triggered=self.showHelp)
self.videotutAct = QtWidgets.QAction("Video Tutorial", self, statusTip="Link to the KnobScripter 3 tutorial in your browser.",
triggered=self.showVideotut)
self.nukepediaAct = QtWidgets.QAction("Show in Nukepedia", self,
statusTip="Open the KnobScripter download page on Nukepedia.",
triggered=self.showInNukepedia)
self.githubAct = QtWidgets.QAction("Show in GitHub", self, statusTip="Open the KnobScripter repo on GitHub.",
triggered=self.showInGithub)
self.snippetsAct = QtWidgets.QAction("Snippets", self, statusTip="Open the Snippets editor.",
triggered=lambda: self.open_multipanel(tab="snippet_editor"))
self.snippetsAct.setIcon(QtGui.QIcon(os.path.join(config.ICONS_DIR, "icon_snippets.png")))
self.prefsAct = QtWidgets.QAction("Preferences", self, statusTip="Open the Preferences panel.",
triggered=lambda: self.open_multipanel(tab="ks_prefs"))
self.prefsAct.setIcon(QtGui.QIcon(os.path.join(config.ICONS_DIR, "icon_prefs.png")))
# Menus
self.prefsMenu = QtWidgets.QMenu("Preferences")
self.prefsMenu.addAction(self.echoAct)
self.prefsMenu.addAction(self.runInContextAct)
self.prefsMenu.addSeparator()
self.prefsMenu.addAction(self.nukepediaAct)
self.prefsMenu.addAction(self.githubAct)
self.prefsMenu.addSeparator()
self.prefsMenu.addAction(self.helpAct)
self.prefsMenu.addAction(self.videotutAct)
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 toggleRunInContext(self):
""" Toggles preference to replace everything needed so that code can be run in proper context
of its node and knob."""
self.setRunInContext(not self.runInContext)
@staticmethod
def showInNukepedia():
open_url("http://www.nukepedia.com/python/ui/knobscripter")
@staticmethod
def showInGithub():
open_url("https://github.com/adrianpueyo/KnobScripter")
@staticmethod
def showHelp():
open_url("https://adrianpueyo.com/ks3-docs")
@staticmethod
def showVideotut():
open_url("https://adrianpueyo.com/ks3-video")
# Blink Backups menu
def createBlinkBackupsMenu(self):
# Actions
# TODO On opening the blink menu, show the .blink file name (../name.blink) in grey and update the checkboxes
self.blink_autoSave_act = QtWidgets.QAction("Auto-save to disk on compile", self, checkable=True,
statusTip="Auto-save code backup on disk every time you save it",
triggered=self.blink_toggle_autosave_action)
self.blink_autoSave_act.setChecked(config.prefs["ks_blink_autosave_on_compile"])
# self.blinkBackups_createFile_act = QtWidgets.QAction("Create .blink scratch file",
self.blink_load_act = QtWidgets.QAction("Load .blink", self, statusTip="Load the .blink code.",
triggered=self.blink_load_triggered)
self.blink_save_act = QtWidgets.QAction("Save .blink", self, statusTip="Save the .blink code.",
triggered=self.blink_save_triggered)
self.blink_versionup_act = QtWidgets.QAction("Version Up", self, statusTip="Version up the .blink file.",
triggered=self.blink_versionup_triggered)
self.blink_browse_act = QtWidgets.QAction("Browse...", self, statusTip="Browse to the blink file's directory.",
triggered=self.blink_browse_action)
self.blink_filename_info_act = QtWidgets.QAction("No file specified.", self,
statusTip="Displays the filename specified "
"in the kernelSourceFile knob.")
self.blink_filename_info_act.setEnabled(False)
# Menus
self.blink_menu = QtWidgets.QMenu("Blink")
self.blink_menu.addAction(self.blink_autoSave_act)
self.blink_menu.addSeparator()
self.blink_menu.addAction(self.blink_filename_info_act)
self.blink_menu.addAction(self.blink_load_act)
self.blink_menu.addAction(self.blink_save_act)
self.blink_menu.addAction(self.blink_versionup_act)
self.blink_menu.addAction(self.blink_browse_act)
self.blink_menu.aboutToShow.connect(self.blink_menu_refresh)
# TODO: Checkbox autosave should be enabled or disabled by default based on preferences...
# Node Mode
def updateKnobDropdown(self):
""" Populate knob dropdown list """
self.current_knob_dropdown.clear() # First remove all items
counter = 0
for i in self.node.knobs():
k = self.node.knob(i)
if i not in self.defaultKnobs and self.node.knob(i).Class() in self.python_knob_classes:
if is_blink_knob(k):
i_full = "Blinkscript Code (kernelSource)"
elif self.show_labels:
i_full = "{} ({})".format(self.node.knob(i).label(), i)
else:
i_full = i
if i in self.unsaved_knobs.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 self.defaultKnobs:
if i in self.unsaved_knobs.keys():
self.current_knob_dropdown.addItem(i + "(*)", i)
else:
self.current_knob_dropdown.addItem(i, i)
counter += 1
return
def loadKnobValue(self, check=True, update_dict=False):
""" Get the content of the knob value and populate the editor """
if not self.to_load_knob:
return
dropdown_value = self.current_knob_dropdown.itemData(
self.current_knob_dropdown.currentIndex()) # knobChanged...
knob_language = self.knobLanguage(self.node, dropdown_value)
try:
# If blinkscript, use getValue.
if knob_language == "blink":
obtained_knob_value = self.node[dropdown_value].getValue()
elif knob_language == "python":
obtained_knob_value = self.node[dropdown_value].value()
logging.debug(obtained_knob_value)
logging.debug(type(obtained_knob_value))
else: # TODO: knob language is None -> try to get the expression for tcl???
return
obtained_scroll_value = 0
edited_knob_value = self.script_editor.toPlainText()
except:
try:
error_message = QtWidgets.QMessageBox.information(None, "", "Unable to find %s.%s" % (
self.node.name(), dropdown_value))
except:
error_message = QtWidgets.QMessageBox.information(None, "",
"Unable to find the node's {}".format(dropdown_value))
# error_message.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
error_message.exec_()
return
# If there were changes to the previous knob, update the dictionary
if update_dict is True:
if obtained_knob_value != edited_knob_value:
self.unsaved_knobs[self.knob] = edited_knob_value
self.saveKnobState()
prev_knob = self.knob # knobChanged...
self.knob = self.current_knob_dropdown.itemData(self.current_knob_dropdown.currentIndex()) # knobChanged...
if check and obtained_knob_value != edited_knob_value:
msg_box = QtWidgets.QMessageBox()
msg_box.setText("The Script Editor has been modified.")
msg_box.setInformativeText("Do you want to overwrite the current code on this editor?")
msg_box.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
msg_box.setIcon(QtWidgets.QMessageBox.Question)
msg_box.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
msg_box.setDefaultButton(QtWidgets.QMessageBox.Yes)
reply = msg_box.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))
self.script_editor.blockSignals(True)
if update_dict:
if self.knob in self.unsaved_knobs:
if self.unsaved_knobs[self.knob] == obtained_knob_value: #first is str, second is bytes
self.script_editor.setPlainText(obtained_knob_value)
self.setKnobModified(False)
else:
obtained_knob_value = self.unsaved_knobs[self.knob]
self.script_editor.setPlainText(obtained_knob_value)
self.setKnobModified(True)
else:
self.script_editor.setPlainText(obtained_knob_value)
self.setKnobModified(False)
else:
self.script_editor.setPlainText(obtained_knob_value)
self.setCodeLanguage(knob_language)
self.script_editor.blockSignals(False)
self.loadKnobState() # Loads cursor and scroll values
self.setKnobState() # Sets cursor and scroll values
self.script_editor.setFocus()
self.script_editor.verticalScrollBar().setValue(1)
return
def loadAllKnobValues(self):
""" Load all knobs button's function """
if len(self.unsaved_knobs) >= 1:
msg_box = QtWidgets.QMessageBox()
msg_box.setText("Do you want to reload all python and callback knobs?")
msg_box.setInformativeText("Unsaved changes on this editor will be lost.")
msg_box.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
msg_box.setIcon(QtWidgets.QMessageBox.Question)
msg_box.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
msg_box.setDefaultButton(QtWidgets.QMessageBox.Yes)
reply = msg_box.exec_()
if reply == QtWidgets.QMessageBox.No:
return
self.unsaved_knobs = {}
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_knob_value = self.getKnobValue(dropdown_value)
# If blinkscript, use getValue.
# if dropdown_value == "kernelSource" and self.node.Class()=="BlinkScript":
# obtained_knob_value = str(self.node[dropdown_value].getValue())
# else:
# obtained_knob_value = 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_knob_value = self.script_editor.toPlainText() # string()
if check and obtained_knob_value != edited_knob_value:
msg_box = QtWidgets.QMessageBox()
msg_box.setText("Do you want to overwrite %s.%s?" % (self.node.name(), dropdown_value))
msg_box.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
msg_box.setIcon(QtWidgets.QMessageBox.Question)
msg_box.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
msg_box.setDefaultButton(QtWidgets.QMessageBox.Yes)
reply = msg_box.exec_()
if reply == QtWidgets.QMessageBox.No:
return
# Save the value if it's Blinkscript code
if dropdown_value == "kernelSource" and self.node.Class() == "BlinkScript":
nuke.tcl('''knob {}.kernelSource "{}"'''.format(self.node.fullName(),
edited_knob_value.replace('"', '\\"').replace('[', '\[')))
else:
if nuke.NUKE_VERSION_MAJOR < 13:
self.node[dropdown_value].setValue(edited_knob_value.encode("utf8"))
else:
self.node[dropdown_value].setValue(edited_knob_value)
self.setKnobModified(modified=False, knob=dropdown_value, change_title=True)
nuke.tcl("modified 1")
if self.knob in self.unsaved_knobs:
del self.unsaved_knobs[self.knob]
return
def saveAllKnobValues(self, check=True):
""" Save all knobs button's function """
if self.updateUnsavedKnobs() > 0 and check:
msg_box = QtWidgets.QMessageBox()
msg_box.setText("Do you want to save all modified python and callback knobs?")
msg_box.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
msg_box.setIcon(QtWidgets.QMessageBox.Question)
msg_box.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
msg_box.setDefaultButton(QtWidgets.QMessageBox.Yes)
reply = msg_box.exec_()
if reply == QtWidgets.QMessageBox.No:
return
save_errors = 0
saved_count = 0
for k in self.unsaved_knobs.copy():
try:
if nuke.NUKE_VERSION_MAJOR < 13:
self.node.knob(k).setValue(self.unsaved_knobs[k].encode("utf8"))
else:
self.node.knob(k).setValue(self.unsaved_knobs[k])
del self.unsaved_knobs[k]
saved_count += 1
nuke.tcl("modified 1")
except:
save_errors += 1
if save_errors > 0:
error_box = QtWidgets.QMessageBox()
error_box.setText("Error saving %s knob%s." % (str(save_errors), int(save_errors > 1) * "s"))
error_box.setIcon(QtWidgets.QMessageBox.Warning)
error_box.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
error_box.setDefaultButton(QtWidgets.QMessageBox.Yes)
error_box.exec_()
else:
logging.debug("KnobScripter: %s knobs saved" % str(saved_count))
return
def setCurrentKnob(self, knob_to_set):
""" Set current knob """
knob_dropdown_items = []
for i in range(self.current_knob_dropdown.count()):
if self.current_knob_dropdown.itemData(i) is not None:
knob_dropdown_items.append(self.current_knob_dropdown.itemData(i))
else:
knob_dropdown_items.append("---")
if knob_to_set in knob_dropdown_items:
index = knob_dropdown_items.index(knob_to_set)
self.current_knob_dropdown.setCurrentIndex(index)
return True
return False
def updateUnsavedKnobs(self):
""" 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_knob_value = self.script_editor.toPlainText() # string()
self.unsaved_knobs[self.knob] = edited_knob_value
if len(self.unsaved_knobs) > 0:
for k in self.unsaved_knobs.copy():
if self.node.knob(k):
if self.getKnobValue(k) == self.unsaved_knobs[k]:
del self.unsaved_knobs[k]
else:
del self.unsaved_knobs[k]
# Set appropriate knobs modified...
knobs_dropdown = self.current_knob_dropdown
all_knobs = [knobs_dropdown.itemData(i) for i in range(knobs_dropdown.count())]
all_knobs = list(filter(None, all_knobs))
for key in all_knobs:
if key in self.unsaved_knobs.keys():
self.setKnobModified(modified=True, knob=key, change_title=False)
else:
self.setKnobModified(modified=False, knob=key, change_title=False)
return len(self.unsaved_knobs)
def getKnobValue(self, knob=""):
"""
Returns the relevant value of the knob:
For python knobs, uses value
For blinkscript, getValue
For others, gets the expression
"""
if knob == "":
knob = self.knob
if knob == "kernelSource" and self.node.Class() == "BlinkScript":
return self.node[knob].getValue()
else:
return self.node[knob].value()
# TODO: Return expression otherwise
def setKnobModified(self, modified=True, knob="", change_title=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 change_title:
title_modified_string = " [modified]"
window_title = self.windowTitle().split(title_modified_string)[0]
if modified:
window_title += title_modified_string
self.current_knob_modified = modified
self.setWindowTitle(window_title)
try:
knobs_dropdown = self.current_knob_dropdown
kd_index = knobs_dropdown.currentIndex()
kd_data = knobs_dropdown.itemData(kd_index)
if self.show_labels and kd_data not in self.defaultKnobs:
if kd_data == "kernelSource" and self.node.Class() == "BlinkScript":
kd_data = "Blinkscript Code (kernelSource)"
else:
kd_data = "{} ({})".format(self.node.knob(kd_data).label(), kd_data)
if not modified:
knobs_dropdown.setItemText(kd_index, kd_data)
else:
knobs_dropdown.setItemText(kd_index, kd_data + "(*)")
except:
pass
def knobLanguage(self, node, knob_name="knobChanged"):
""" Given a node and a knob name, guesses the appropriate code language """
if knob_name not in node.knobs():
return None
if knob_name == "kernelSource" and node.Class() == "BlinkScript":
return "blink"
elif knob_name in self.defaultKnobs or node.knob(knob_name).Class() in self.python_knob_classes:
return "python"
else:
return None
def setCodeLanguage(self, code_language="python"):
"""Performs all UI changes neccesary for editing a different language! Syntax highlighter, menu buttons, etc.
Args:
code_language (str, Optional): Language to change to. Can be "python","blink" or None
"""
# 1. Allow for string or int, 0 being "no language", 1 "python", 2 "blink"
code_language_list = [None, "python", "blink"]
if code_language is None:
new_code_language = code_language
elif isinstance(code_language, str) and code_language.lower() in code_language_list:
new_code_language = code_language.lower()
elif isinstance(code_language, int) and code_language_list[code_language]:
new_code_language = code_language_list[code_language]
else:
return False
# 2. Syntax highlighter
self.script_editor.set_code_language(new_code_language)
self.code_language = new_code_language
# 3. Menus
self.run_script_button.setVisible(code_language != "blink")
self.clear_console_button.setVisible(code_language != "blink")
self.save_recompile_button.setVisible(code_language == "blink")
self.backup_button.setVisible(code_language == "blink")
def loadKnobState(self):
"""
Loads the state of the knobs from the place where it's stored file inside the SE directory's root.
"""
prefs_state = config.prefs["ks_save_knob_state"]
if prefs_state == 0: # Do not save
logging.debug("Not loading the knob state dictionary (chosen in preferences).")
elif prefs_state == 1: # Saved in memory
full_knob_state_dict = config.knob_state_dict
nk_path = utils.nk_saved_path()
node_fullname = self.node.fullName()
if nk_path in full_knob_state_dict:
if node_fullname in full_knob_state_dict[nk_path]:
self.current_node_state_dict = config.knob_state_dict[nk_path][node_fullname]
elif prefs_state == 2: # Saved to disk
if not os.path.isfile(config.knob_state_txt_path):
return False
else:
full_knob_state_dict = {}
with open(config.knob_state_txt_path, "r") as f:
full_knob_state_dict = json.load(f)
nk_path = utils.nk_saved_path()
node_fullname = self.node.fullName()
if nk_path in full_knob_state_dict:
if node_fullname in full_knob_state_dict[nk_path]:
self.current_node_state_dict = full_knob_state_dict[nk_path][node_fullname]
def setKnobState(self):
"""
Sets the saved knob state from self.current_node_state_dict into the current knob's script if applicable
"""
nk_path = utils.nk_saved_path()
node_fullname = self.node.fullName()
logging.debug("knob is "+self.knob)
# current_node_state_dict: {"cursor_pos":{},"scroll_pos":{},"open_knob"=None}
node_state_dict = self.current_node_state_dict
if "cursor_pos" in node_state_dict:
if self.knob in node_state_dict["cursor_pos"]:
cursor = self.script_editor.textCursor()
cursor.setPosition(int(node_state_dict["cursor_pos"][self.knob][1]),
QtGui.QTextCursor.MoveAnchor)
cursor.setPosition(int(node_state_dict["cursor_pos"][self.knob][0]),
QtGui.QTextCursor.KeepAnchor)
self.script_editor.setTextCursor(cursor)
if "scroll_pos" in node_state_dict:
if self.knob in node_state_dict["scroll_pos"]:
logging.debug("Scroll value found: "+str(node_state_dict["scroll_pos"][self.knob]))
self.script_editor.verticalScrollBar().setValue(
int(node_state_dict["scroll_pos"][self.knob]))
def saveKnobState(self):
""" Stores the current state of the script """
logging.debug("About to save knob state...")
# 1. Save state in own dict
# 1.1. Save scroll value in own dict
if "scroll_pos" not in self.current_node_state_dict:
self.current_node_state_dict["scroll_pos"] = {}
self.current_node_state_dict["scroll_pos"][self.knob] = self.script_editor.verticalScrollBar().value()
# 1.2. Save cursor value in own dict
if "cursor_pos" not in self.current_node_state_dict:
self.current_node_state_dict["cursor_pos"] = {}
self.current_node_state_dict["cursor_pos"][self.knob] = [self.script_editor.textCursor().position(),
self.script_editor.textCursor().anchor()]
# 1.3. Save current open knob in own dict
self.current_node_state_dict["open_knob"] = self.knob
logging.debug("Current knob state dict for this knob...:")
logging.debug(self.current_node_state_dict)
# 2. Get full dict...
prefs_state = config.prefs["ks_save_knob_state"]
logging.debug("prefs state for knobs: "+str(prefs_state))
if prefs_state == 0: # Do not save
logging.debug("Not saving the script state dictionary (chosen in preferences).")
return
if prefs_state == 1: # Saved in memory
full_knob_state_dict = config.knob_state_dict
elif prefs_state == 2: # Saved to disk
full_knob_state_dict = {}
if os.path.isfile(config.knob_state_txt_path):
with open(config.knob_state_txt_path, "r") as f:
full_knob_state_dict = json.load(f)
else: