-
Notifications
You must be signed in to change notification settings - Fork 48
/
lib.py
384 lines (283 loc) · 11 KB
/
lib.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
import os
import sys
import contextlib
from .. import io, api, style
from ..vendor import qtawesome
from ..vendor.Qt import QtWidgets, QtCore, QtGui
self = sys.modules[__name__]
self._jobs = dict()
self._path = os.path.dirname(__file__)
def resource(*path):
path = os.path.join(self._path, "_res", *path)
return path.replace("\\", "/")
@contextlib.contextmanager
def application():
app = QtWidgets.QApplication.instance()
if not app:
print("Starting new QApplication..")
app = QtWidgets.QApplication(sys.argv)
yield app
app.exec_()
else:
print("Using existing QApplication..")
yield app
def defer(delay, func):
"""Append artificial delay to `func`
This aids in keeping the GUI responsive, but complicates logic
when producing tests. To combat this, the environment variable ensures
that every operation is synchonous.
Arguments:
delay (float): Delay multiplier; default 1, 0 means no delay
func (callable): Any callable
"""
delay *= float(os.getenv("PYBLISH_DELAY", 1))
if delay > 0:
return QtCore.QTimer.singleShot(delay, func)
else:
return func()
def schedule(func, time, channel="default"):
"""Run `func` at a later `time` in a dedicated `channel`
Given an arbitrary function, call this function after a given
timeout. It will ensure that only one "job" is running within
the given channel at any one time and cancel any currently
running job if a new job is submitted before the timeout.
"""
try:
self._jobs[channel].stop()
except (AttributeError, KeyError):
pass
timer = QtCore.QTimer()
timer.setSingleShot(True)
timer.timeout.connect(func)
timer.start(time)
self._jobs[channel] = timer
@contextlib.contextmanager
def dummy():
"""Dummy context manager
Usage:
>> with some_context() if False else dummy():
.. pass
"""
yield
def iter_model_rows(model,
column,
include_root=False):
"""Iterate over all row indices in a model"""
indices = [QtCore.QModelIndex()] # start iteration at root
for index in indices:
# Add children to the iterations
child_rows = model.rowCount(index)
for child_row in range(child_rows):
child_index = model.index(child_row, column, index)
indices.append(child_index)
if not include_root and not index.isValid():
continue
yield index
@contextlib.contextmanager
def preserve_expanded_rows(tree_view,
column=0,
role=QtCore.Qt.DisplayRole):
"""Preserves expanded row in QTreeView by column's data role.
This function is created to maintain the expand vs collapse status of
the model items. When refresh is triggered the items which are expanded
will stay expanded and vise versa.
Arguments:
tree_view (QWidgets.QTreeView): the tree view which is
nested in the application
column (int): the column to retrieve the data from
role (int): the role which dictates what will be returned
Returns:
None
"""
model = tree_view.model()
expanded = set()
for index in iter_model_rows(model,
column=column,
include_root=False):
if tree_view.isExpanded(index):
value = index.data(role)
expanded.add(value)
try:
yield
finally:
if not expanded:
return
for index in iter_model_rows(model,
column=column,
include_root=False):
value = index.data(role)
state = value in expanded
if state:
tree_view.expand(index)
else:
tree_view.collapse(index)
@contextlib.contextmanager
def preserve_selection(tree_view,
column=0,
role=QtCore.Qt.DisplayRole,
current_index=True):
"""Preserves row selection in QTreeView by column's data role.
This function is created to maintain the selection status of
the model items. When refresh is triggered the items which are expanded
will stay expanded and vise versa.
tree_view (QWidgets.QTreeView): the tree view nested in the application
column (int): the column to retrieve the data from
role (int): the role which dictates what will be returned
Returns:
None
"""
model = tree_view.model()
selection_model = tree_view.selectionModel()
flags = selection_model.Select | selection_model.Rows
if current_index:
current_index_value = tree_view.currentIndex().data(role)
else:
current_index_value = None
selected_rows = selection_model.selectedRows()
if not selected_rows:
yield
return
selected = set(row.data(role) for row in selected_rows)
try:
yield
finally:
if not selected:
return
# Go through all indices, select the ones with similar data
for index in iter_model_rows(model,
column=column,
include_root=False):
value = index.data(role)
state = value in selected
if state:
tree_view.scrollTo(index) # Ensure item is visible
selection_model.select(index, flags)
if current_index_value and value == current_index_value:
selection_model.setCurrentIndex(index,
selection_model.NoUpdate)
FAMILY_ICON_COLOR = "#0091B2"
FAMILY_CONFIG_CACHE = {}
GROUP_CONFIG_CACHE = {}
def get_family_cached_config(name):
"""Get value from config with fallback to default"""
# We assume the default fallback key in the config is `__default__`
config = FAMILY_CONFIG_CACHE
return config.get(name, config.get("__default__", None))
def refresh_family_config_cache():
"""Get the family configurations from the database
The configuration must be stored on the project under `config`.
For example:
{
"config": {
"families": [
{"name": "avalon.camera", label: "Camera", "icon": "photo"},
{"name": "avalon.anim", label: "Animation", "icon": "male"},
]
}
}
It is possible to override the default behavior and set specific families
checked. For example we only want the families imagesequence and camera
to be visible in the Loader.
# This will turn every item off
api.data["familyStateDefault"] = False
# Only allow the imagesequence and camera
api.data["familyStateToggled"] = ["imagesequence", "camera"]
"""
# Update the icons from the project configuration
project = io.find_one({"type": "project"},
projection={"config.families": True})
assert project, "Project not found!"
families = project["config"].get("families", [])
families = {family["name"]: family for family in families}
# Check if any family state are being overwritten by the configuration
default_state = api.data.get("familiesStateDefault", True)
toggled = set(api.data.get("familiesStateToggled", []))
# Replace icons with a Qt icon we can use in the user interfaces
default_icon = qtawesome.icon("fa.folder", color=FAMILY_ICON_COLOR)
for name, family in families.items():
# Set family icon
icon = family.get("icon", None)
if icon:
family["icon"] = qtawesome.icon("fa.{}".format(icon),
color=FAMILY_ICON_COLOR)
else:
family["icon"] = default_icon
# Update state
state = not default_state if name in toggled else default_state
family["state"] = state
# Default configuration
families["__default__"] = {"icon": default_icon}
FAMILY_CONFIG_CACHE.clear()
FAMILY_CONFIG_CACHE.update(families)
return families
def refresh_group_config_cache():
"""Get subset group configurations from the database
The 'group' configuration must be stored in the project `config` field.
See schema `config-1.0.json`
"""
# Subset group item's default icon and order
default_group_icon = qtawesome.icon("fa.object-group",
color=style.colors.default)
default_group_config = {"icon": default_group_icon,
"order": 0}
# Get pre-defined group name and apperance from project config
project = io.find_one({"type": "project"},
projection={"config.groups": True})
assert project, "Project not found!"
group_configs = project["config"].get("groups", [])
# Build pre-defined group configs
groups = dict()
for config in group_configs:
name = config["name"]
icon = "fa." + config.get("icon", "object-group")
color = config.get("color", style.colors.default)
order = float(config.get("order", 0))
groups[name] = {"icon": qtawesome.icon(icon, color=color),
"order": order}
# Default configuration
groups["__default__"] = default_group_config
GROUP_CONFIG_CACHE.clear()
GROUP_CONFIG_CACHE.update(groups)
return groups
def get_active_group_config(asset_id, include_predefined=False):
"""Collect all active groups from each subset"""
predefineds = GROUP_CONFIG_CACHE.copy()
default_group_config = predefineds.pop("__default__")
_orders = set([0]) # default order zero included
for config in predefineds.values():
_orders.add(config["order"])
# Remap order to list index
orders = sorted(_orders)
# Collect groups from subsets
group_names = set(io.distinct("data.subsetGroup",
{"type": "subset", "parent": asset_id}))
if include_predefined:
# Ensure all predefined group configs will be included
group_names.update(predefineds.keys())
groups = list()
for name in group_names:
# Get group config
config = predefineds.get(name, default_group_config)
# Base order
remapped_order = orders.index(config["order"])
data = {
"name": name,
"icon": config["icon"],
"_order": remapped_order,
}
groups.append(data)
# Sort by tuple (base_order, name)
# If there are multiple groups in same order, will sorted by name.
ordered = sorted(groups, key=lambda dat: (dat.pop("_order"), dat["name"]))
total = len(ordered)
order_temp = "%0{}d".format(len(str(total)))
# Update sorted order to config
for index, data in enumerate(ordered):
order = index
inverse_order = total - order
data.update({
# Format orders into fixed length string for groups sorting
"order": order_temp % order,
"inverseOrder": order_temp % inverse_order,
})
return ordered