-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathcontrol.py
1218 lines (931 loc) · 40.5 KB
/
control.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 json
import time
import collections
# Dependencies
import pyblish.logic
# Local libraries
from . import util, models, version, settings
from .vendor.Qt5 import QtCore
qtproperty = util.qtConstantProperty
class Controller(QtCore.QObject):
"""Communicate with QML"""
# Signals
info = QtCore.Signal(str, arguments=["message"])
error = QtCore.Signal(str, arguments=["message"])
show = QtCore.Signal()
hide = QtCore.Signal()
firstRun = QtCore.Signal()
collecting = QtCore.Signal()
validating = QtCore.Signal()
extracting = QtCore.Signal()
integrating = QtCore.Signal()
repairing = QtCore.Signal()
stopping = QtCore.Signal()
saving = QtCore.Signal()
initialising = QtCore.Signal()
acting = QtCore.Signal()
acted = QtCore.Signal()
# A plug-in/instance pair is about to be processed
about_to_process = QtCore.Signal(object, object)
changed = QtCore.Signal()
ready = QtCore.Signal()
saved = QtCore.Signal()
finished = QtCore.Signal()
initialised = QtCore.Signal()
commented = QtCore.Signal()
commenting = QtCore.Signal(str, arguments=["comment"])
state_changed = QtCore.Signal(str, arguments=["state"])
# Statically expose these members to the QML run-time.
itemModel = qtproperty(lambda self: self.data["models"]["item"])
itemProxy = qtproperty(lambda self: self.data["proxies"]["item"])
recordProxy = qtproperty(lambda self: self.data["proxies"]["record"])
errorProxy = qtproperty(lambda self: self.data["proxies"]["error"])
instanceProxy = qtproperty(lambda self: self.data["proxies"]["instance"])
pluginProxy = qtproperty(lambda self: self.data["proxies"]["plugin"])
resultModel = qtproperty(lambda self: self.data["models"]["result"])
resultProxy = qtproperty(lambda self: self.data["proxies"]["result"])
def __init__(self, host, parent=None, targets=None):
super(Controller, self).__init__(parent)
# Connection to host
self.host = host
self.targets = targets or []
self.data = {
"models": {
"item": models.ItemModel(),
"result": models.ResultModel(),
},
"comment": "",
"firstRun": True,
}
self.data.update({
"proxies": {
"item": models.ProxyModel(self.data["models"]["item"]),
"instance": models.ProxyModel(
self.data["models"]["item"],
includes={"itemType": ["instance"]}),
"plugin": models.ProxyModel(
self.data["models"]["item"],
includes={"itemType": "plugin"},
excludes={"hasCompatible": [False]}),
# Terminal
"result": models.ProxyModel(
self.data["models"]["result"],
excludes={"levelname": ["DEBUG"]}),
# Perspective
"record": models.ProxyModel(
self.data["models"]["result"],
includes={"type": ["record"]}),
"error": models.ProxyModel(
self.data["models"]["result"],
includes={"type": ["error"]})
},
"state": {
"is_running": False,
"readyCount": 0,
"current": None,
"all": list(),
"testPassed": False,
}
})
# Install state machine
# ---------------------
# This is what enables complex combinations of state
# to appear as one, such that one may register interest in
# e.g. a "finished" state, when "finished" may actually be
# a combination of multiple child states.
self.machine = self.setup_statemachine()
self.info.connect(self.on_info)
self.error.connect(self.on_error)
self.finished.connect(self.on_finished)
self.ready.connect(self.on_ready)
self.show.connect(self.on_show)
# NOTE: Listeners to this signal are run in the main thread
self.about_to_process.connect(self.on_about_to_process,
QtCore.Qt.QueuedConnection)
self.state_changed.connect(self.on_state_changed)
self.commenting.connect(self.on_commenting)
def on_show(self):
self.host.emit("pyblishQmlShown")
def dispatch(self, func, *args, **kwargs):
return getattr(self.host, func)(*args, **kwargs)
def setup_statemachine(self):
"""Setup and start state machine"""
machine = QtCore.QStateMachine()
# _______________
# | |
# | |
# | |
# |_______________|
#
group = util.QState("group", QtCore.QState.ParallelStates, machine)
# _______________
# | ____ ____ |
# || |---| ||
# ||____|---|____||
# |_______________| - Parallell State
#
visibility = util.QState("visibility", group)
hidden = util.QState("hidden", visibility)
visible = util.QState("visible", visibility)
# _______________
# | ____ ____ |
# || |---| ||
# ||____|---|____||
# |_______________| - Parallell State
#
operation = util.QState("operation", group)
ready = util.QState("ready", operation)
collecting = util.QState("collecting", operation)
validating = util.QState("validating", operation)
extracting = util.QState("extracting", operation)
integrating = util.QState("integrating", operation)
finished = util.QState("finished", operation)
repairing = util.QState("repairing", operation)
initialising = util.QState("initialising", operation)
stopping = util.QState("stopping", operation)
stopped = util.QState("stopped", operation)
saving = util.QState("saving", operation)
# _______________
# | ____ ____ |
# || |---| ||
# ||____|---|____||
# |_______________| - Parallell State
#
errored = util.QState("errored", group)
clean = util.QState("clean", errored)
dirty = util.QState("dirty", errored)
# _______________
# | ____ ____ |
# || |---| ||
# ||____|---|____||
# |_______________| - Parallell State
# States that block the underlying GUI
suspended = util.QState("suspended", group)
alive = util.QState("alive", suspended)
acting = util.QState("acting", suspended)
acted = QtCore.QHistoryState(operation)
acted.setDefaultState(ready)
# _______________
# | ____ ____ |
# || |---| ||
# ||____|---|____||
# |_______________|
# | ____ ____ |
# || |---| ||
# ||____|---|____||
# |_______________|
#
hidden.addTransition(self.show, visible)
visible.addTransition(self.hide, hidden)
ready.addTransition(self.acting, acting)
ready.addTransition(self.validating, validating)
ready.addTransition(self.initialising, initialising)
ready.addTransition(self.repairing, repairing)
ready.addTransition(self.saving, saving)
saving.addTransition(self.saved, ready)
collecting.addTransition(self.initialised, ready)
collecting.addTransition(self.stopping, stopping)
validating.addTransition(self.stopping, stopping)
validating.addTransition(self.finished, finished)
validating.addTransition(self.extracting, extracting)
extracting.addTransition(self.stopping, stopping)
extracting.addTransition(self.finished, finished)
extracting.addTransition(self.integrating, integrating)
integrating.addTransition(self.stopping, stopping)
integrating.addTransition(self.finished, finished)
finished.addTransition(self.initialising, initialising)
finished.addTransition(self.acting, acting)
initialising.addTransition(self.collecting, collecting)
stopping.addTransition(self.acted, acted)
stopping.addTransition(self.finished, finished)
dirty.addTransition(self.initialising, clean)
clean.addTransition(self.changed, dirty)
alive.addTransition(self.acting, acting)
acting.addTransition(self.acted, acted)
# Set initial states
for compound, state in {machine: group,
visibility: hidden,
operation: ready,
errored: clean,
suspended: alive}.items():
compound.setInitialState(state)
# Make connections
for state in (hidden,
visible,
ready,
collecting,
validating,
extracting,
integrating,
finished,
repairing,
initialising,
stopping,
saving,
stopped,
dirty,
clean,
acting,
alive,
acted):
state.entered.connect(
lambda state=state: self.state_changed.emit(state.name))
machine.start()
return machine
@QtCore.Slot(result=str)
def comment(self):
"""Return first line of comment"""
return self.data["comment"]
@QtCore.Property(str, notify=state_changed)
def state(self):
return self.data["state"]["current"]
@QtCore.Property(bool, notify=commented)
def hasComment(self):
return True if self.data["comment"] else False
@QtCore.Property(bool, constant=True)
def commentEnabled(self):
return "comment" in self.host.cached_context.data
@property
def states(self):
return self.data["state"]["all"]
@QtCore.Slot(result=float)
def time(self):
return time.time()
def iterator(self, plugins, context):
"""Primary iterator
CAUTION: THIS RUNS IN A SEPARATE THREAD
This is the brains of publishing. It handles logic related
to which plug-in to process with which Instance or Context,
in addition to stopping when necessary.
"""
test = pyblish.logic.registered_test()
state = {
"nextOrder": None,
"ordersWithError": set()
}
signals = {
pyblish.api.ValidatorOrder: self.validating,
pyblish.api.ExtractorOrder: self.extracting,
pyblish.api.IntegratorOrder: self.integrating,
}
for plug, instance in iterator(plugins, context):
if instance is not None and not instance.data.get("publish", True):
continue
state["nextOrder"] = plug.order
for order in list(signals.keys()):
if pyblish.lib.inrange(plug.order, order):
signals.pop(order).emit()
if not self.data["state"]["is_running"]:
return StopIteration("Stopped")
if test(**state):
self.data["state"]["testPassed"] = False
return StopIteration("Stopped due to %s" % test(**state))
self.data["state"]["testPassed"] = True
try:
# Notify GUI before commencing remote processing
self.about_to_process.emit(plug, instance)
result = self.host.process(plug, context, instance)
except Exception as e:
return StopIteration("Unknown error: %s" % e)
else:
# Make note of the order at which the
# potential error error occured.
has_error = result["error"] is not None
if has_error:
state["ordersWithError"].add(plug.order)
yield result
@QtCore.Slot(int, result="QVariant")
def getPluginActions(self, index):
"""Return actions from plug-in at `index`
Arguments:
index (int): Index at which item is located in model
"""
index = self.data["proxies"]["plugin"].mapToSource(
self.data["proxies"]["plugin"].index(
index, 0, QtCore.QModelIndex())).row()
item = self.data["models"]["item"].items[index]
# Inject reference to the original index
actions = [
dict(action, **{"index": index})
for action in item.actions
]
# Context specific actions
for action in list(actions):
if action["on"] == "failed" and not item.hasError:
actions.remove(action)
if action["on"] == "succeeded" and not item.succeeded:
actions.remove(action)
if action["on"] == "processed" and not item.processed:
actions.remove(action)
if action["on"] == "notProcessed" and item.processed:
actions.remove(action)
# Discard empty categories, separators
remaining_actions = list()
index = 0
try:
action = actions[index]
except IndexError:
pass
else:
while action:
try:
action = actions[index]
except IndexError:
break
isempty = False
if action["__type__"] in ("category", "separator"):
try:
next_ = actions[index + 1]
if next_["__type__"] != "action":
isempty = True
except IndexError:
isempty = True
if not isempty:
remaining_actions.append(action)
index += 1
return remaining_actions
@QtCore.Slot(str)
def runPluginAction(self, action):
if "acting" in self.states:
return self.error.emit("Busy")
elif not any(state in self.states
for state in ["ready",
"finished"]):
return self.error.emit("Busy")
action = json.loads(action)
def run():
util.echo("Running with states.. %s" % self.states)
self.acting.emit()
self.data["state"]["is_running"] = True
item = self.data["models"]["item"].items[action["index"]]
context = self.host.context()
plugins = self.host.discover()
plugin = next(x for x in plugins if x.id == item.id)
result = self.host.process(**{
"context": context,
"plugin": plugin,
"instance": None,
"action": action["id"]
})
return result
def on_finished(result):
util.echo("Finished, finishing up..")
models = self.data["models"]
self.data["state"]["is_running"] = False
self.acted.emit()
# Inform GUI of success or failure
plugin = models["item"].plugins[result["plugin"]["id"]]
plugin.actionPending = False
plugin.actionHasError = not result["success"]
# Allow running action upon action, without resetting
models["result"].update_with_result(result)
self.info.emit("Success" if result["success"] else "Failed")
util.echo("Finished with states.. %s" % self.states)
util.defer(run, callback=on_finished)
@QtCore.Slot(int)
def toggleInstance(self, index):
models = self.data["models"]
proxies = self.data["proxies"]
qindex = proxies["instance"].index(index, 0, QtCore.QModelIndex())
source_qindex = self.data["proxies"]["instance"].mapToSource(qindex)
source_index = source_qindex.row()
item = models["item"].items[source_index]
if item.optional:
self.__toggle_item(models["item"], source_index)
else:
self.error.emit("Cannot toggle")
@QtCore.Slot(bool, str)
def toggleSection(self, checkState, sectionLabel):
model = self.data["models"]["item"]
# Get all items' current toggle state
states = set()
for item in model.items:
if item.itemType == "instance" and sectionLabel == item.category:
if item.optional:
states.add(item.isToggled)
if item.itemType == "plugin" and sectionLabel == item.verb:
if item.optional:
states.add(item.isToggled)
if len(states) == 1:
# Use items' states instead of section state if all optional items
# are the same state.
checkState = not states.pop()
for item in model.items:
if item.itemType == "instance" and sectionLabel == item.category:
if item.isToggled != checkState and item.optional:
self.__toggle_item(model, model.items.index(item))
if item.itemType == "plugin" and sectionLabel == item.verb:
if item.isToggled != checkState and item.optional:
self.__toggle_item(model, model.items.index(item))
@QtCore.Slot(bool, str)
def hideSection(self, hideState, sectionLabel):
model = self.data["models"]["item"]
for item in model.items:
if item.itemType == "instance" and sectionLabel == item.category:
self.__hide_item(model, model.items.index(item), hideState)
if item.itemType == "plugin" and item.verb == sectionLabel:
self.__hide_item(model, model.items.index(item), hideState)
if item.itemType == "section" and item.name == sectionLabel:
self.__hide_item(model, model.items.index(item), hideState)
@QtCore.Slot(int, result="QVariant")
def pluginData(self, index):
models = self.data["models"]
proxies = self.data["proxies"]
qindex = proxies["plugin"].index(index, 0, QtCore.QModelIndex())
source_qindex = proxies["plugin"].mapToSource(qindex)
source_index = source_qindex.row()
return self.__item_data(models["item"], source_index)
@QtCore.Slot(int, result="QVariant")
def instanceData(self, index):
models = self.data["models"]
proxies = self.data["proxies"]
qindex = proxies["instance"].index(index, 0, QtCore.QModelIndex())
source_qindex = proxies["instance"].mapToSource(qindex)
source_index = source_qindex.row()
return self.__item_data(models["item"], source_index)
@QtCore.Slot(int)
def togglePlugin(self, index):
models = self.data["models"]
proxies = self.data["proxies"]
qindex = proxies["plugin"].index(index, 0, QtCore.QModelIndex())
source_qindex = proxies["plugin"].mapToSource(qindex)
source_index = source_qindex.row()
item = models["item"].items[source_index]
if item.optional:
self.__toggle_item(self.data["models"]["item"], source_index)
else:
self.error.emit("Cannot toggle")
@QtCore.Slot(str, str, str, str)
def exclude(self, target, operation, role, value):
"""Exclude a `role` of `value` at `target`
Arguments:
target (str): Destination proxy model
operation (str): "add" or "remove" exclusion
role (str): Role to exclude
value (str): Value of `role` to exclude
"""
target = {"result": self.data["proxies"]["result"],
"instance": self.data["proxies"]["instance"],
"plugin": self.data["proxies"]["plugin"]}[target]
if operation == "add":
target.add_exclusion(role, value)
elif operation == "remove":
target.remove_exclusion(role, value)
else:
raise TypeError("operation must be either `add` or `remove`")
@QtCore.Slot()
def save(self):
# Deprecated
return
def __item_data(self, model, index):
"""Return item data as dict"""
item = model.items[index]
data = {
"name": item.name,
"data": item.data,
"doc": getattr(item, "doc", None),
"path": getattr(item, "path", None),
}
return data
def __hide_item(self, model, index, hideState):
item = model.items[index]
item.isHidden = hideState
def __toggle_item(self, model, index):
if "ready" not in self.states:
return self.error.emit("Not ready")
item = model.items[index]
new_value = not item.isToggled
old_value = item.isToggled
if item.itemType == "plugin":
self.host.emit("pluginToggled",
plugin=item.id,
new_value=new_value,
old_value=old_value)
if item.itemType == "instance":
self.host.emit("instanceToggled",
instance=item.id,
new_value=new_value,
old_value=old_value)
item.isToggled = new_value
self.data["models"]["item"].update_compatibility()
def echo(self, data):
"""Append `data` to result model"""
self.data["models"]["result"].add_item(data)
def comment_sync(self, comment):
"""Update comments to host and notify subscribers"""
self.host.update(key="comment", value=comment)
self.host.emit("commented", comment=comment)
def is_ready(self):
count = self.data["state"]["readyCount"]
util.wait(self.ready, 1000)
return self.data["state"]["readyCount"] == count + 1
# Event handlers
def on_commenting(self, comment):
"""The user is entering a comment"""
def update():
context = self.host.cached_context
context.data["comment"] = comment
self.data["comment"] = comment
# Notify subscribers of the comment
self.comment_sync(comment)
self.commented.emit()
# Update local cache a little later
util.schedule(update, 100, channel="commenting")
def on_about_to_process(self, plugin, instance):
"""Reflect currently running pair in GUI"""
if instance is None:
instance_item = self.data["models"]["item"].instances[0]
else:
instance_item = self.data["models"]["item"].instances[instance.id]
plugin_item = self.data["models"]["item"].plugins[plugin.id]
for section in self.data["models"]["item"].sections:
if section.name == plugin_item.verb:
section.isProcessing = True
if section.name == instance_item.category:
section.isProcessing = True
instance_item.isProcessing = True
plugin_item.isProcessing = True
def on_state_changed(self, state):
util.echo("Entering state: \"%s\"" % state)
if state == "ready":
self.ready.emit()
self.data["state"]["current"] = state
self.data["state"]["all"] = list(
s.name for s in self.machine.configuration()
)
def on_ready(self):
self.data["state"]["readyCount"] += 1
def on_finished(self):
self.data["models"]["item"].reset_status()
self.echo({
"type": "message",
"message": "Finished"
})
def on_error(self, message):
"""An error has occurred"""
util.echo(message)
def on_info(self, message):
"""A message was sent"""
self.echo({
"type": "message",
"message": message
})
# Slots
@QtCore.Slot()
def stop(self):
self.data["state"]["is_running"] = False
self.stopping.emit()
@QtCore.Slot()
def reset(self):
"""Request that host re-discovers plug-ins and re-processes selectors
A reset completely flushes the state of the GUI and reverts
back to how it was when it first got launched.
Pipeline:
______________ ____________ ______________
| | | | | |
| host.reset() |-->| on_reset() |-->| on_context() |--
|______________| |____________| |______________| |
_______________ __________ _______________ |
| | | | | | |
| on_finished() |<--| on_run() |<--| on_discover() |<--
|_______________| |__________| |_______________|
"""
if not any(state in self.states for state in ("ready", "finished")):
return self.error.emit("Not ready")
self.initialising.emit()
util.timer("resetting..")
stats = {"requestCount": self.host.stats()["totalRequestCount"]}
# Clear models
self.data["models"]["item"].reset()
self.data["models"]["result"].reset()
def on_finished(plugins, context):
# Compute compatibility
for plugin in self.data["models"]["item"].plugins:
if plugin.instanceEnabled:
instances = pyblish.logic.instances_by_plugin(context,
plugin)
plugin.compatibleInstances = list(i.id for i in instances)
else:
plugin.compatibleInstances = [context.id]
self.data["models"]["item"].reorder(context)
# Report statistics
stats["requestCount"] -= self.host.stats()["totalRequestCount"]
util.timer_end("resetting..", "Spent %.2f ms resetting")
util.echo("Made %i requests during reset."
% abs(stats["requestCount"]))
# Reset Context
context_item = self.data["models"]["item"].instances[0]
context_item.hasError = False
context_item.succeeded = False
context_item.processed = False
context_item.isProcessing = False
context_item.currentProgress = 0
context_item.label = context.data.get("label")
self.initialised.emit()
self.data["models"]["item"].update_compatibility()
# Remember comment across resets
comment = self.data["comment"]
if comment:
print("Installing local comment..")
self.host.cached_context.data["comment"] = comment
else:
print("No local comment, reading from context..")
comment = self.host.cached_context.data.get("comment", "")
self.data["comment"] = comment
# Notify subscribers of the comment
self.comment_sync(comment)
first_run = self.data["firstRun"]
if first_run:
self.firstRun.emit()
self.data["firstRun"] = False
self.host.emit("reset", context=None)
# Hidden sections
for section in self.data["models"]["item"].sections:
if section.name in settings.HiddenSections:
self.hideSection(True, section.name)
# Run selected procedure on first run
if first_run:
if self.data.get('autoPublish'):
print("Starting auto-publish at first run..")
util.schedule(self.publish, 1)
elif self.data.get('autoValidate'):
print("Starting auto-validate at first run..")
util.schedule(self.validate, 1)
def on_run(plugins):
"""Fetch instances in their current state, right after reset"""
util.defer(self.host.context,
callback=lambda context: on_finished(plugins, context))
def on_discover(plugins, context):
collectors = list()
# For backwards compatibility check for existance of
# "plugins_by_targets" method.
if hasattr(pyblish.api, "plugins_by_targets"):
plugins = pyblish.api.plugins_by_targets(plugins, self.targets)
for plugin in plugins:
self.data["models"]["item"].add_plugin(plugin.to_json())
# Sort out which of these are Collectors
if not pyblish.lib.inrange(
number=plugin.order,
base=pyblish.api.Collector.order):
continue
if not plugin.active:
continue
collectors.append(plugin)
self.collecting.emit()
self.run(collectors, context,
callback=on_run,
callback_args=[plugins])
def on_context(context):
context.data["pyblishQmlVersion"] = version
context.data["targets"] = ", ".join(self.targets)
self.data["models"]["item"].add_context(context.to_json())
self.data["models"]["result"].add_context(context.to_json())
util.defer(
self.host.discover,
callback=lambda plugins: on_discover(plugins, context)
)
def on_reset():
util.defer(self.host.context, callback=on_context)
util.defer(self.host.reset, callback=on_reset)
@QtCore.Slot()
def publish(self):
"""Start asynchonous publishing
Publishing takes into account all available and currently
toggled plug-ins and instances.
"""
def get_data():
model = self.data["models"]["item"]
# Communicate with host to retrieve current plugins and instances
# This can potentially take a very long time; it is run
# asynchronously and initiates processing once complete.
host_plugins = dict((p.id, p) for p in self.host.cached_discover)
host_context = dict((i.id, i) for i in self.host.cached_context)
plugins = list()
instances = list()
for plugin in models.ItemIterator(model.plugins):
# Exclude Collectors
if pyblish.lib.inrange(
number=plugin.order,
base=pyblish.api.Collector.order):
continue
plugins.append(host_plugins[plugin.id])
for instance in models.ItemIterator(model.instances):
instances.append(host_context[instance.id])
return plugins, instances
def on_data_received(args):
self.run(*args, callback=on_finished)
def on_finished():
self.host.emit("published", context=None)
if not self.data["state"]["testPassed"]:
# Possible stopped on validation fail or the extraction has
# been interrupted. Depend on the continual processing test.
return
# If there are instance that has error after the test passed,
# prompt publish failed message to footer.
model = self.data["models"]["item"]
for instance in models.ItemIterator(model.instances):
if instance.hasError:
self.info.emit("Published, with errors..")
break
util.defer(get_data, callback=on_data_received)
@QtCore.Slot()
def validate(self):
"""Start asynchonous validation
Validation only takes into account currently available
and toggled Validators, and leaves all else behind.
"""
def get_data():
model = self.data["models"]["item"]
# Communicate with host to retrieve current plugins and instances
# This can potentially take a very long time; it is run
# asynchronously and initiates processing once complete.
host_plugins = dict((p.id, p) for p in self.host.cached_discover)
host_context = dict((i.id, i) for i in self.host.cached_context)
plugins = list()
instances = list()
for plugin in models.ItemIterator(model.plugins):
# Consider Validators only.
if not pyblish.lib.inrange(plugin.order,
base=pyblish.api.Validator.order):
continue
plugins.append(host_plugins[plugin.id])
for instance in models.ItemIterator(model.instances):
instances.append(host_context[instance.id])
return plugins, instances
def on_data_received(args):
self.run(*args, callback=on_finished)
def on_finished():
self.host.emit("validated", context=None)
util.defer(get_data, callback=on_data_received)
def run(self, plugins, context, callback=None, callback_args=None):
"""Commence asynchronous tasks
This method runs through the provided `plugins` in