forked from dbr/tabtabtab-nuke
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tabtabtab.py
575 lines (443 loc) · 17.2 KB
/
tabtabtab.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
"""Alternative "tab node creator thingy" for The Foundry's Nuke
homepage: https://github.com/dbr/tabtabtab-nuke
license: http://unlicense.org/
"""
__version__ = "1.8-dev"
import os
import sys
try:
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import Qt
except ImportError:
try:
from PySide import QtCore, QtGui, QtGui as QtWidgets
from PySide.QtCore import Qt
except ImportError:
import sip
for mod in ("QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant"):
sip.setapi(mod, 2)
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
QtCore.Signal = QtCore.pyqtSignal
def find_menu_items(menu, _path = None):
"""Extracts items from a given Nuke menu
Returns a list of strings, with the path to each item
Ignores divider lines and hidden items (ones like "@;&CopyBranch" for shift+k)
>>> found = find_menu_items(nuke.menu("Nodes"))
>>> found.sort()
>>> found[:5]
['3D/Axis', '3D/Camera', '3D/CameraTracker', '3D/DepthGenerator', '3D/Geometry/Card']
"""
import nuke
found = []
mi = menu.items()
for i in mi:
if isinstance(i, nuke.Menu):
# Sub-menu, recurse
mname = i.name().replace("&", "")
subpath = "/".join(x for x in (_path, mname) if x is not None)
if "ToolSets/Delete" in subpath:
# Remove all ToolSets delete commands
continue
sub_found = find_menu_items(menu = i, _path = subpath)
found.extend(sub_found)
elif isinstance(i, nuke.MenuItem):
if i.name() == "":
# Skip dividers
continue
if i.name().startswith("@;"):
# Skip hidden items
continue
subpath = "/".join(x for x in (_path, i.name()) if x is not None)
found.append({'menuobj': i, 'menupath': subpath})
return found
def nonconsec_find(needle, haystack, anchored = False):
"""checks if each character of "needle" can be found in order (but not
necessarily consecutivly) in haystack.
For example, "mm" can be found in "matchmove", but not "move2d"
"m2" can be found in "move2d", but not "matchmove"
>>> nonconsec_find("m2", "move2d")
True
>>> nonconsec_find("m2", "matchmove")
False
Anchored ensures the first letter matches
>>> nonconsec_find("atch", "matchmove", anchored = False)
True
>>> nonconsec_find("atch", "matchmove", anchored = True)
False
>>> nonconsec_find("match", "matchmove", anchored = True)
True
If needle starts with a string, non-consecutive searching is disabled:
>>> nonconsec_find(" mt", "matchmove", anchored = True)
False
>>> nonconsec_find(" ma", "matchmove", anchored = True)
True
>>> nonconsec_find(" oe", "matchmove", anchored = False)
False
>>> nonconsec_find(" ov", "matchmove", anchored = False)
True
"""
if "[" not in needle:
haystack = haystack.rpartition(" [")[0]
if len(haystack) == 0 and len(needle) > 0:
# "a" is not in ""
return False
elif len(needle) == 0 and len(haystack) > 0:
# "" is in "blah"
return True
elif len(needle) == 0 and len(haystack) == 0:
# ..?
return True
# Turn haystack into list of characters (as strings are immutable)
haystack = [hay for hay in str(haystack)]
if needle.startswith(" "):
# "[space]abc" does consecutive search for "abc" in "abcdef"
if anchored:
if "".join(haystack).startswith(needle.lstrip(" ")):
return True
else:
if needle.lstrip(" ") in "".join(haystack):
return True
if anchored:
if needle[0] != haystack[0]:
return False
else:
# First letter matches, remove it for further matches
needle = needle[1:]
del haystack[0]
for needle_atom in needle:
try:
needle_pos = haystack.index(needle_atom)
except ValueError:
return False
else:
# Dont find string in same pos or backwards again
del haystack[:needle_pos + 1]
return True
class NodeWeights(object):
def __init__(self, fname = None):
self.fname = fname
self._weights = {}
self._successful_load = False
def load(self):
if self.fname is None:
return
def _load_internal():
import json
if not os.path.isfile(self.fname):
print "Weight file does not exist"
return
f = open(self.fname)
self._weights = json.load(f)
f.close()
# Catch any errors, print traceback and continue
try:
_load_internal()
self._successful_load = True
except Exception:
print "Error loading node weights"
import traceback
traceback.print_exc()
self._successful_load = False
def save(self):
if self.fname is None:
print "Not saving node weights, no file specified"
return
if not self._successful_load:
# Avoid clobbering existing weights file on load error
print "Not writing weights file because %r previously failed to load" % (
self.fname)
return
def _save_internal():
import json
ndir = os.path.dirname(self.fname)
if not os.path.isdir(ndir):
try:
os.makedirs(ndir)
except OSError, e:
if e.errno != 17: # errno 17 is "already exists"
raise
f = open(self.fname, "w")
# TODO: Limit number of saved items to some sane number
json.dump(self._weights, fp = f)
f.close()
# Catch any errors, print traceback and continue
try:
_save_internal()
except Exception:
print "Error saving node weights"
import traceback
traceback.print_exc()
def get(self, k, default = 0):
if len(self._weights.values()) == 0:
maxval = 1.0
else:
maxval = max(self._weights.values())
maxval = max(1, maxval)
maxval = float(maxval)
return self._weights.get(k, default) / maxval
def increment(self, key):
self._weights.setdefault(key, 0)
self._weights[key] += 1
class NodeModel(QtCore.QAbstractListModel):
def __init__(self, mlist, weights, num_items = 15, filtertext = ""):
super(NodeModel, self).__init__()
self.weights = weights
self.num_items = num_items
self._all = mlist
self._filtertext = filtertext
# _items is the list of objects to be shown, update sets this
self._items = []
self.update()
def set_filter(self, filtertext):
self._filtertext = filtertext
self.update()
def update(self):
filtertext = self._filtertext.lower()
# Two spaces as a shortcut for [
filtertext = filtertext.replace(" ", "[")
scored = []
for n in self._all:
# Turn "3D/Shader/Phong" into "Phong [3D/Shader]"
menupath = n['menupath'].replace("&", "")
uiname = "%s [%s]" % (menupath.rpartition("/")[2], menupath.rpartition("/")[0])
if nonconsec_find(filtertext, uiname.lower(), anchored=True):
# Matches, get weighting and add to list of stuff
score = self.weights.get(n['menupath'])
scored.append({
'text': uiname,
'menupath': n['menupath'],
'menuobj': n['menuobj'],
'score': score})
# Store based on scores (descending), then alphabetically
s = sorted(scored, key = lambda k: (-k['score'], k['text']))
self._items = s
self.modelReset.emit()
def rowCount(self, parent = QtCore.QModelIndex()):
return min(self.num_items, len(self._items))
def data(self, index, role = Qt.DisplayRole):
if role == Qt.DisplayRole:
# Return text to display
raw = self._items[index.row()]['text']
return raw
elif role == Qt.DecorationRole:
weight = self._items[index.row()]['score']
hue = 0.4
sat = weight
if index.row() % 2 == 0:
col = QtGui.QColor.fromHsvF(hue, sat, 0.9)
else:
col = QtGui.QColor.fromHsvF(hue, sat, 0.8)
pix = QtGui.QPixmap(6, 12)
pix.fill(col)
return pix
elif role == Qt.BackgroundRole:
return
weight = self._items[index.row()]['score']
hue = 0.4
sat = weight ** 2 # gamma saturation to make faster falloff
sat = min(1.0, sat)
if index.row() % 2 == 0:
return QtGui.QColor.fromHsvF(hue, sat, 0.9)
else:
return QtGui.QColor.fromHsvF(hue, sat, 0.8)
else:
# Ignore other roles
return None
def getorig(self, selected):
# TODO: Is there a way to get this via data()? There's no
# Qt.DataRole or something (only DisplayRole)
if len(selected) > 0:
# Get first selected index
selected = selected[0]
else:
# Nothing selected, get first index
selected = self.index(0)
# TODO: Maybe check for IndexError?
selected_data = self._items[selected.row()]
return selected_data
class TabyLineEdit(QtWidgets.QLineEdit):
pressed_arrow = QtCore.Signal(str)
cancelled = QtCore.Signal()
def event(self, event):
"""Make tab trigger returnPressed
Also emit signals for the up/down arrows, and escape.
"""
is_keypress = event.type() == QtCore.QEvent.KeyPress
if is_keypress and event.key() == QtCore.Qt.Key_Tab:
# Can't access tab key in keyPressedEvent
self.returnPressed.emit()
return True
elif is_keypress and event.key() == QtCore.Qt.Key_Up:
# These could be done in keyPressedEvent, but.. this is already here
self.pressed_arrow.emit("up")
return True
elif is_keypress and event.key() == QtCore.Qt.Key_Down:
self.pressed_arrow.emit("down")
return True
elif is_keypress and event.key() == QtCore.Qt.Key_Escape:
self.cancelled.emit()
return True
else:
return super(TabyLineEdit, self).event(event)
class TabTabTabWidget(QtWidgets.QDialog):
def __init__(self, on_create = None, parent = None, winflags = None):
super(TabTabTabWidget, self).__init__(parent = parent)
if winflags is not None:
self.setWindowFlags(winflags)
self.setMinimumSize(200, 300)
self.setMaximumSize(200, 300)
# Store callback
self.cb_on_create = on_create
# Input box
self.input = TabyLineEdit()
# Node weighting
self.weights = NodeWeights(os.path.expanduser("~/.nuke/tabtabtab_weights.json"))
self.weights.load() # weights.save() called in close method
import nuke
nodes = find_menu_items(nuke.menu("Nodes")) + find_menu_items(nuke.menu("Nuke"))
# List of stuff, and associated model
self.things_model = NodeModel(nodes, weights = self.weights)
self.things = QtWidgets.QListView()
self.things.setModel(self.things_model)
# Add input and items to layout
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.input)
layout.addWidget(self.things)
# Remove margins
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
# Update on text change
self.input.textChanged.connect(self.update)
# Reset selection on text change
self.input.textChanged.connect(lambda: self.move_selection(where="first"))
self.move_selection(where = "first") # Set initial selection
# Create node when enter/tab is pressed, or item is clicked
self.input.returnPressed.connect(self.create)
self.things.clicked.connect(self.create)
# When esc pressed, close
self.input.cancelled.connect(self.close)
# Up and down arrow handling
self.input.pressed_arrow.connect(self.move_selection)
def under_cursor(self):
def clamp(val, mi, ma):
return max(min(val, ma), mi)
# Get cursor position, and screen dimensions on active screen
cursor = QtGui.QCursor().pos()
screen = QtWidgets.QDesktopWidget().screenGeometry(cursor)
# Get window position so cursor is just over text input
xpos = cursor.x() - (self.width()/2)
ypos = cursor.y() - 13
# Clamp window location to prevent it going offscreen
xpos = clamp(xpos, screen.left(), screen.right() - self.width())
ypos = clamp(ypos, screen.top(), screen.bottom() - (self.height()-13))
# Move window
self.move(xpos, ypos)
def move_selection(self, where):
if where not in ["first", "up", "down"]:
raise ValueError("where should be either 'first', 'up', 'down', not %r" % (
where))
first = where == "first"
up = where == "up"
down = where == "down"
if first:
self.things.setCurrentIndex(self.things_model.index(0))
return
cur = self.things.currentIndex()
if up:
new = cur.row() - 1
if new < 0:
new = self.things_model.rowCount() - 1
elif down:
new = cur.row() + 1
count = self.things_model.rowCount()
if new > count-1:
new = 0
self.things.setCurrentIndex(self.things_model.index(new))
def event(self, event):
"""Close when window becomes inactive (click outside of window)
"""
if event.type() == QtCore.QEvent.WindowDeactivate:
self.close()
return True
else:
return super(TabTabTabWidget, self).event(event)
def update(self, text):
"""On text change, selects first item and updates filter text
"""
self.things.setCurrentIndex(self.things_model.index(0))
self.things_model.set_filter(text)
def show(self):
"""Select all the text in the input (which persists between
show()'s)
Allows typing over previously created text, and [tab][tab] to
create previously created node (instead of the most popular)
"""
# Load the weights everytime the panel is shown, to prevent
# overwritting weights from other Nuke instances
self.weights.load()
# Select all text to allow overwriting
self.input.selectAll()
self.input.setFocus()
super(TabTabTabWidget, self).show()
def close(self):
"""Save weights when closing
"""
self.weights.save()
super(TabTabTabWidget, self).close()
def create(self):
# Get selected item
selected = self.things.selectedIndexes()
if len(selected) == 0:
return
thing = self.things_model.getorig(selected)
# Store the full UI name of the created node, so it is the
# active node on the next [tab]. Prefix it with space,
# to disable substring matching
if thing['text'].startswith(" "):
prev_string = thing['text']
else:
prev_string = " %s" % thing['text']
self.input.setText(prev_string)
# Create node, increment weight and close
self.cb_on_create(thing = thing)
self.weights.increment(thing['menupath'])
self.close()
_tabtabtab_instance = None
def main():
global _tabtabtab_instance
if _tabtabtab_instance is not None:
# TODO: Is there a better way of doing this? If a
# TabTabTabWidget is instanced, it goes out of scope at end of
# function and disappers instantly. This seems like a
# reasonable "workaround"
_tabtabtab_instance.under_cursor()
_tabtabtab_instance.show()
_tabtabtab_instance.raise_()
return
def on_create(thing):
try:
thing['menuobj'].invoke()
except ImportError:
print "Error creating %s" % thing
t = TabTabTabWidget(on_create = on_create, winflags = Qt.FramelessWindowHint)
# Make dialog appear under cursor, as Nuke's builtin one does
t.under_cursor()
# Show, and make front-most window (mostly for OS X)
t.show()
t.raise_()
# Keep the TabTabTabWidget alive, but don't keep an extra
# reference to it, otherwise Nuke segfaults on exit. Hacky.
# https://github.com/dbr/tabtabtab-nuke/issues/4
import weakref
_tabtabtab_instance = weakref.proxy(t)
if __name__ == '__main__':
try:
import nuke
m_edit = nuke.menu("Nuke").findItem("Edit")
m_edit.addCommand("Tabtabtab", main, "Tab")
except ImportError:
# For testing outside Nuke
app = QtGui.QApplication(sys.argv)
main()
app.exec_()