Package nuke :: Module callbacks
[hide private]
[frames] | no frames]

Source Code for Module nuke.callbacks

  1  # callbacks.py 
  2  # 
  3  # Callbacks from Nuke to user-defined Python. 
  4  # Nuke actually calls "nuke.onCreate()" but users will normally use 
  5  # the default versions of these functions and use "nuke.addOnCreate()" 
  6  # to add to the list of callbacks that the default calls. 
  7   
  8  import types 
  9  import nuke 
 10   
 11   
12 -def _addCallback(dict, call, args, kwargs, nodeClass, node=None):
13 if not callable(call): 14 raise ValueError("call must be a callable") 15 if type(args) != types.TupleType: 16 args = (args,) 17 if type(kwargs) != types.DictType: 18 raise ValueError("kwargs must be a dictionary") 19 if dict.has_key(nodeClass): 20 list = dict[nodeClass] 21 # make it appear only once in list 22 try: 23 list.remove((call,args,kwargs,node)) 24 except: 25 pass 26 list.append((call,args,kwargs,node)) 27 else: 28 dict[nodeClass] = [(call,args,kwargs,node)]
29
30 -def _removeCallback(dict, call, args, kwargs, nodeClass, node=None):
31 if type(args) != types.TupleType: 32 args = (args,) 33 if dict.has_key(nodeClass): 34 list = dict[nodeClass] 35 try: 36 list.remove((call,args,kwargs,node)) 37 except: 38 pass
39
40 -def _doCallbacks(dict, node=None):
41 list = dict.get(nuke.thisClass()) 42 node = nuke.thisNode() 43 if list: 44 for f in list: 45 if f[3] == None or f[3] is node: 46 f[0](*f[1],**f[2]) 47 list = dict.get('*') 48 if list: 49 for f in list: 50 if f[3] == None or f[3] is node: 51 f[0](*f[1],**f[2])
52 53 onUserCreates={}
54 -def addOnUserCreate(call, args=(), kwargs={}, nodeClass='*'):
55 """Add code to execute when user creates a node""" 56 _addCallback(onUserCreates, call, args, kwargs, nodeClass)
57 -def removeOnUserCreate(call, args=(), kwargs={}, nodeClass='*'):
58 """Remove a previously-added callback with the same arguments.""" 59 _removeCallback(onUserCreates, call, args, kwargs, nodeClass)
60 -def onUserCreate():
61 _doCallbacks(onUserCreates) 62 if not len(onUserCreates): nuke.tcl("OnCreate")
63 64 onCreates={}
65 -def addOnCreate(call, args=(), kwargs={}, nodeClass='*'):
66 """Add code to execute when a node is created or undeleted""" 67 _addCallback(onCreates, call, args, kwargs, nodeClass)
68 -def removeOnCreate(call, args=(), kwargs={}, nodeClass='*'):
69 """Remove a previously-added callback with the same arguments.""" 70 _removeCallback(onCreates, call, args, kwargs, nodeClass)
71 -def onCreate():
72 _doCallbacks(onCreates)
73 74 onScriptLoads={}
75 -def addOnScriptLoad(call, args=(), kwargs={}, nodeClass='Root'):
76 """Add code to execute when a script is loaded""" 77 _addCallback(onScriptLoads, call, args, kwargs, nodeClass)
78 -def removeOnScriptLoad(call, args=(), kwargs={}, nodeClass='Root'):
79 """Remove a previously-added callback with the same arguments.""" 80 _removeCallback(onScriptLoads, call, args, kwargs, nodeClass)
81 -def onScriptLoad():
82 _doCallbacks(onScriptLoads)
83 84 onScriptSaves={}
85 -def addOnScriptSave(call, args=(), kwargs={}, nodeClass='Root'):
86 """Add code to execute before a script is saved""" 87 _addCallback(onScriptSaves, call, args, kwargs, nodeClass)
88 -def removeOnScriptSave(call, args=(), kwargs={}, nodeClass='Root'):
89 """Remove a previously-added callback with the same arguments.""" 90 _removeCallback(onScriptSaves, call, args, kwargs, nodeClass)
91 -def onScriptSave():
92 _doCallbacks(onScriptSaves)
93 94 onScriptCloses={}
95 -def addOnScriptClose(call, args=(), kwargs={}, nodeClass='Root'):
96 """Add code to execute before a script is closed""" 97 _addCallback(onScriptCloses, call, args, kwargs, nodeClass)
98 -def removeOnScriptClose(call, args=(), kwargs={}, nodeClass='Root'):
99 """Remove a previously-added callback with the same arguments.""" 100 _removeCallback(onScriptCloses, call, args, kwargs, nodeClass)
101 -def onScriptClose():
102 _doCallbacks(onScriptCloses)
103 104 onDestroys={}
105 -def addOnDestroy(call, args=(), kwargs={}, nodeClass='*'):
106 """Add code to execute when a node is destroyed""" 107 _addCallback(onDestroys, call, args, kwargs, nodeClass)
108 -def removeOnDestroy(call, args=(), kwargs={}, nodeClass='*'):
109 """Remove a previously-added callback with the same arguments.""" 110 _removeCallback(onDestroys, call, args, kwargs, nodeClass)
111 -def onDestroy():
112 _doCallbacks(onDestroys)
113 114 knobChangeds={}
115 -def addKnobChanged(call, args=(), kwargs={}, nodeClass='*', node=None):
116 """Add code to execute when the user changes a knob 117 The knob is availble in nuke.thisKnob() and the node in nuke.thisNode(). 118 This is also called with dummy knobs when the control panel is opened 119 or when the inputs to the node changes. The purpose is to update other 120 knobs in the control panel. Use addUpdateUI() for changes that 121 should happen even when the panel is closed.""" 122 _addCallback(knobChangeds, call, args, kwargs, nodeClass, node)
123 -def removeKnobChanged(call, args=(), kwargs={}, nodeClass='*', node=None):
124 """Remove a previously-added callback with the same arguments.""" 125 _removeCallback(knobChangeds, call, args, kwargs, nodeClass, node)
126 -def knobChanged():
127 _doCallbacks(knobChangeds)
128 129 updateUIs={}
130 -def addUpdateUI(call, args=(), kwargs={}, nodeClass='*'):
131 """Add code to execute on every node when things change. This is done 132 during idle, you cannot rely on it being done before it starts updating 133 the viewer""" 134 _addCallback(updateUIs, call, args, kwargs, nodeClass)
135 -def removeUpdateUI(call, args=(), kwargs={}, nodeClass='*'):
136 """Remove a previously-added callback with the same arguments.""" 137 _removeCallback(updateUIs, call, args, kwargs, nodeClass)
138 -def updateUI():
139 _doCallbacks(updateUIs)
140 141 # autolabel is somewhat different due to it returning a string 142 autolabels={}
143 -def addAutolabel(call, args=(), kwargs={}, nodeClass='*'):
144 """Add code to execute on every node to produce the text to draw on it 145 in the DAG. Any value other than None is converted to a string and used 146 as the text. None indicates that previously-added functions should 147 be tried""" 148 _addCallback(autolabels, call, args, kwargs, nodeClass)
149 -def removeAutolabel(call, args=(), kwargs={}, nodeClass='*'):
150 """Remove a previously-added callback with the same arguments.""" 151 _removeCallback(autolabels, call, args, kwargs, nodeClass)
152 -def autolabel():
153 list = autolabels.get(nuke.thisClass()) 154 if list: 155 for f in list[::-1]: 156 s = f[0](*f[1],**f[2]) 157 if s != None: return s 158 list = autolabels.get('*') 159 if list: 160 for f in list[::-1]: 161 s = f[0](*f[1],**f[2]) 162 if s != None: return s
163 164 # Normal rendering callbacks 165 beforeRenders={}
166 -def addBeforeRender(call, args=(), kwargs={}, nodeClass='Write'):
167 """Add code to execute before starting any renders""" 168 _addCallback(beforeRenders, call, args, kwargs, nodeClass)
169 -def removeBeforeRender(call, args=(), kwargs={}, nodeClass='Write'):
170 """Remove a previously-added callback with the same arguments.""" 171 _removeCallback(beforeRenders, call, args, kwargs, nodeClass)
172 -def beforeRender():
173 _doCallbacks(beforeRenders)
174 175 beforeFrameRenders={}
176 -def addBeforeFrameRender(call, args=(), kwargs={}, nodeClass='Write'):
177 """Add code to execute before each frame of a render""" 178 _addCallback(beforeFrameRenders, call, args, kwargs, nodeClass)
179 -def removeBeforeFrameRender(call, args=(), kwargs={}, nodeClass='Write'):
180 """Remove a previously-added callback with the same arguments.""" 181 _removeCallback(beforeFrameRenders, call, args, kwargs, nodeClass)
182 -def beforeFrameRender():
183 _doCallbacks(beforeFrameRenders)
184 185 afterFrameRenders={}
186 -def addAfterFrameRender(call, args=(), kwargs={}, nodeClass='Write'):
187 """Add code to execute after each frame of a render""" 188 _addCallback(afterFrameRenders, call, args, kwargs, nodeClass)
189 -def removeAfterFrameRender(call, args=(), kwargs={}, nodeClass='Write'):
190 """Remove a previously-added callback with the same arguments.""" 191 _removeCallback(afterFrameRenders, call, args, kwargs, nodeClass)
192 -def afterFrameRender():
193 _doCallbacks(afterFrameRenders)
194 195 afterRenders={}
196 -def addAfterRender(call, args=(), kwargs={}, nodeClass='Write'):
197 """Add code to execute after any renders""" 198 _addCallback(afterRenders, call, args, kwargs, nodeClass)
199 -def removeAfterRender(call, args=(), kwargs={}, nodeClass='Write'):
200 """Remove a previously-added callback with the same arguments.""" 201 _removeCallback(afterRenders, call, args, kwargs, nodeClass)
202 -def afterRender():
203 _doCallbacks(afterRenders)
204 205 renderProgresses={}
206 -def addRenderProgress(call, args=(), kwargs={}, nodeClass='Write'):
207 """Add code to execute when the progress bar updates during any renders""" 208 _addCallback(renderProgresses, call, args, kwargs, nodeClass)
209 -def removeRenderProgress(call, args=(), kwargs={}, nodeClass='Write'):
210 """Remove a previously-added callback with the same arguments.""" 211 _removeCallback(renderProgresses, call, args, kwargs, nodeClass)
212 -def renderProgress():
213 _doCallbacks(renderProgresses)
214 215 # Callbacks for internal use only 216 _beforeRecordings={}
217 -def addBeforeRecording(call, args=(), kwargs={}, nodeClass='Viewer'):
218 """Add code to execute before viewer recording""" 219 _addCallback(_beforeRecordings, call, args, kwargs, nodeClass)
220 -def removeBeforeRecording(call, args=(), kwargs={}, nodeClass='Viewer'):
221 """Remove a previously-added callback with the same arguments.""" 222 _removeCallback(_beforeRecordings, call, args, kwargs, nodeClass)
223 -def beforeRecording():
224 _doCallbacks(_beforeRecordings)
225 226 _afterRecordings={}
227 -def addAfterRecording(call, args=(), kwargs={}, nodeClass='Viewer'):
228 """Add code to execute after viewer recording""" 229 _addCallback(_afterRecordings, call, args, kwargs, nodeClass)
230 -def removeAfterRecording(call, args=(), kwargs={}, nodeClass='Viewer'):
231 """Remove a previously-added callback with the same arguments.""" 232 _removeCallback(_afterRecordings, call, args, kwargs, nodeClass)
233 -def afterRecording():
234 _doCallbacks(_afterRecordings)
235 236 _beforeReplays={}
237 -def addBeforeReplay(call, args=(), kwargs={}, nodeClass='Viewer'):
238 """Add code to execute before viewer replay""" 239 _addCallback(_beforeReplays, call, args, kwargs, nodeClass)
240 -def removeBeforeReplay(call, args=(), kwargs={}, nodeClass='Viewer'):
241 """Remove a previously-added callback with the same arguments.""" 242 _removeCallback(_beforeReplays, call, args, kwargs, nodeClass)
243 -def beforeReplay():
244 _doCallbacks(_beforeReplays)
245 246 _afterReplays={}
247 -def addAfterReplay(call, args=(), kwargs={}, nodeClass='Viewer'):
248 """Add code to execute after viewer replay""" 249 _addCallback(_afterReplays, call, args, kwargs, nodeClass)
250 -def removeAfterReplay(call, args=(), kwargs={}, nodeClass='Viewer'):
251 """Remove a previously-added callback with the same arguments.""" 252 _removeCallback(_afterReplays, call, args, kwargs, nodeClass)
253 -def afterReplay():
254 _doCallbacks(_afterReplays)
255 256 # Special functions to perform background callbacks as these have no node as 257 # context.
258 -def _addBackgroundCallback(list, call, args, kwargs):
259 if not callable(call): 260 raise ValueError("call must be a callable") 261 if type(args) != types.TupleType: 262 args = (args,) 263 if type(kwargs) != types.DictType: 264 raise ValueError("kwargs must be a dictionary") 265 # make it appear only once in list 266 try: 267 list.remove((call,args,kwargs)) 268 except: 269 pass 270 list.append((call,args,kwargs))
271
272 -def _removeBackgroundCallback(list, call, args, kwargs):
273 if type(args) != types.TupleType: 274 args = (args,) 275 try: 276 list.remove((call,args,kwargs)) 277 except: 278 pass
279
280 -def _doBackgroundCallbacks(list, context):
281 for f in list: 282 f[0](context, *f[1],**f[2])
283 284 # Background rendering callbacks 285 beforeBackgroundRenders=[]
286 -def addBeforeBackgroundRender(call, args=(), kwargs={}):
287 """Add code to execute before starting any background renders. 288 The call must be in the form of: 289 def foo(context): 290 pass 291 292 The context object that will be passed in is a dictionary containing the following elements: 293 id => The identifier for the task that's about to begin 294 295 Please be aware that the current Nuke context will not make sense in the callback (e.g. nuke.thisNode will return a random node). 296 """ 297 _addBackgroundCallback(beforeBackgroundRenders, call, args, kwargs)
298 -def removeBeforeBackgroundRender(call, args=(), kwargs={}):
299 """Remove a previously-added callback with the same arguments.""" 300 _removeBackgroundCallback(beforeBackgroundRenders, call, args, kwargs)
301 -def beforeBackgroundRender(context):
302 _doBackgroundCallbacks(beforeBackgroundRenders, context)
303 304 # There is no logical place for this to be called at the moment, so don't expose it. 305 #def addBeforeBackgroundFrameRender(call, args=(), kwargs={}): 306 # """Add code to execute before each frame of a background render""" 307 # _addBackgroundCallback(beforeBackgroundFrameRenders, call, args, kwargs) 308 #def removeBeforeBackgroundFrameRender(call, args=(), kwargs={}): 309 # """Remove a previously-added callback with the same arguments.""" 310 # _removeBackgroundCallback(beforeBackgroundFrameRenders, call, args, kwargs) 311 #def beforeBackgroundFrameRender(): 312 # _doBackgroundCallbacks(beforeBackgroundFrameRenders) 313 314 afterBackgroundFrameRenders=[]
315 -def addAfterBackgroundFrameRender(call, args=(), kwargs={}):
316 """Add code to execute after each frame of a background render. 317 The call must be in the form of: 318 def foo(context): 319 pass 320 321 The context object that will be passed in is a dictionary containing the following elements: 322 id => The identifier for the task that's making progress 323 frame => the current frame number being rendered 324 numFrames => the total number of frames that is being rendered 325 frameProgress => the number of frames rendered so far. 326 327 Please be aware that the current Nuke context will not make sense in the callback (e.g. nuke.thisNode will return a random node). 328 """ 329 _addBackgroundCallback(afterBackgroundFrameRenders, call, args, kwargs)
330 -def removeAfterBackgroundFrameRender(call, args=(), kwargs={}):
331 """Remove a previously-added callback with the same arguments.""" 332 _removeBackgroundCallback(afterBackgroundFrameRenders, call, args, kwargs)
333 -def afterBackgroundFrameRender(context):
334 _doBackgroundCallbacks(afterBackgroundFrameRenders, context)
335 336 afterBackgroundRenders=[]
337 -def addAfterBackgroundRender(call, args=(), kwargs={}):
338 """Add code to execute after any background renders. 339 The call must be in the form of: 340 def foo(context): 341 pass 342 343 The context object that will be passed in is a dictionary containing the following elements: 344 id => The identifier for the task that's ended 345 346 Please be aware that the current Nuke context will not make sense in the callback (e.g. nuke.thisNode will return a random node). 347 """ 348 _addBackgroundCallback(afterBackgroundRenders, call, args, kwargs)
349 -def removeAfterBackgroundRender(call, args=(), kwargs={}):
350 """Remove a previously-added callback with the same arguments.""" 351 _removeBackgroundCallback(afterBackgroundRenders, call, args, kwargs)
352 -def afterBackgroundRender(context):
353 _doBackgroundCallbacks(afterBackgroundRenders, context)
354 355 # filenameFilter is somewhat different due to it returning a string 356 filenameFilters={}
357 -def addFilenameFilter(call, args=(), kwargs={}, nodeClass='*'):
358 """Add a function to modify filenames before Nuke passes them to 359 the operating system. The first argument to the function is the 360 filename, and it should return the new filename. None is the same as 361 returning the string unchanged. All added functions are called 362 in backwards order.""" 363 _addCallback(filenameFilters, call, args, kwargs, nodeClass)
364 -def removeFilenameFilter(call, args=(), kwargs={}, nodeClass='*'):
365 """Remove a previously-added callback with the same arguments.""" 366 _removeCallback(filenameFilters, call, args, kwargs, nodeClass)
367
368 -def filenameFilter(filename):
369 import __main__ 370 list = filenameFilters.get(nuke.thisClass()) 371 if list: 372 for f in list[::-1]: 373 s = f[0](filename,*f[1],**f[2]) 374 if s != None: filename = s 375 list = filenameFilters.get('*') 376 if list: 377 for f in list[::-1]: 378 s = f[0](filename,*f[1],**f[2]) 379 if s != None: filename = s 380 if not len(filenameFilters): 381 # For back-compatibility allow user to define a filenameFix() function: 382 if __main__.__dict__.has_key('filenameFix'): 383 return __main__.__dict__['filenameFix'](filename) 384 # For even further back-compatibility let them define a tcl filename_fix function: 385 return nuke.tcl("filename_fix",filename) 386 return filename
387 388 validateFilenames={}
389 -def addValidateFilename(call, args=(), kwargs={}, nodeClass='Write'):
390 """Add a function to validate a filename in Write nodes. The first argument 391 is the filename and it should return a Boolean as to whether the filename is valid 392 or not. If a callback is provided, it will control whether the Render button of Write nodes 393 and the Execute button of WriteGeo nodes is enabled or not.""" 394 _addCallback(validateFilenames, call, args, kwargs, nodeClass)
395 -def removeFilenameValidate(call, args=(), kwargs={}, nodeClass='Write'):
396 """Remove a previously-added callback.""" 397 _removeCallback(validateFilenames, call, args, kwargs, nodeClass)
398 -def validateFilename(filename):
399 import __main__ 400 list = validateFilenames.get(nuke.thisClass()) 401 valid = True 402 403 if list: 404 for f in list: 405 b = f[0](filename) 406 if b == False: valid = False 407 list = validateFilenames.get('*') 408 if list: 409 for f in list: 410 b = f[0](filename) 411 if b == False: valid = False 412 return valid
413 414
415 -def _doAutoSaveCallbacks( filters, filename ):
416 import __main__ 417 list = filters.get( 'Root' ) 418 if list: 419 for f in list: 420 s = f[0](filename) 421 filename = s 422 423 return filename
424 425 autoSaveFilters={}
426 -def addAutoSaveFilter(filter):
427 """addAutoSaveFilter(filter) -> None 428 429 Add a function to modify the autosave filename before Nuke saves the current script on an autosave timeout. 430 431 Look at rollingAutoSave.py in the nukescripts directory for an example of using the auto save filters. 432 433 @param filter: A filter function. The first argument to the filter is the current autosave filename. 434 The filter should return the filename to save the autosave to.""" 435 _addCallback(autoSaveFilters, filter, (), {}, 'Root')
436
437 -def removeAutoSaveFilter(filter):
438 """Remove a previously-added callback with the same arguments.""" 439 _removeCallback(autoSaveFilters, call, (), {}, 'Root')
440
441 -def autoSaveFilter(filename):
442 """Internal function. Use addAutoSaveFilter to add a callback""" 443 return _doAutoSaveCallbacks( autoSaveFilters, filename )
444 445 446 autoSaveRestoreFilters={}
447 -def addAutoSaveRestoreFilter(filter):
448 """addAutoSaveRestoreFilter(filter) -> None 449 450 Add a function to modify the autosave restore file before Nuke attempts to restores the autosave file. 451 452 Look at rollingAutoSave.py in the nukescripts directory for an example of using the auto save filters. 453 454 @param filter: A filter function. The first argument to the filter is the current autosave filename. 455 This function should return the filename to load autosave from or it should return None if the autosave file should be ignored.""" 456 _addCallback(autoSaveRestoreFilters, filter, (), {}, 'Root')
457
458 -def removeAutoSaveRestoreFilter(filter):
459 """Remove a previously-added callback with the same arguments.""" 460 _removeCallback(autoSaveRestoreFilters, filter, (), {}, 'Root')
461
462 -def autoSaveRestoreFilter(filename):
463 """Internal function. Use addAutoSaveRestoreFilter to add a callback""" 464 return _doAutoSaveCallbacks( autoSaveRestoreFilters, filename )
465 466 autoSaveDeleteFilters={}
467 -def addAutoSaveDeleteFilter(filter):
468 """addAutoSaveDeleteFilter(filter) -> None 469 470 Add a function to modify the autosave filename before Nuke attempts delete the autosave file. 471 472 Look at rollingAutoSave.py in the nukescripts directory for an example of using the auto save filters. 473 474 @param filter: A filter function. The first argument to the filter is the current autosave filename. 475 This function should return the filename to delete or return None if no file should be deleted.""" 476 _addCallback(autoSaveDeleteFilters, filter, (), {}, 'Root')
477
478 -def removeAutoSaveDeleteFilter(filter):
479 """Remove a previously-added callback with the same arguments.""" 480 _removeCallback(autoSaveDeleteFilters, filter, (), {}, 'Root')
481
482 -def autoSaveDeleteFilter(filename):
483 """Internal function. Use addAutoSaveDeleteFilter to add a callback""" 484 return _doAutoSaveCallbacks( autoSaveDeleteFilters, filename )
485