-
Notifications
You must be signed in to change notification settings - Fork 12
/
engine.py
1915 lines (1574 loc) · 71.6 KB
/
engine.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
# Copyright (c) 2021 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the Shotgun Pipeline Toolkit Source Code License. All rights
# not expressly granted therein are reserved by Shotgun Software Inc.
"""
A Toolkit engine for Flame
"""
from __future__ import absolute_import
import os
import pwd
import re
import sys
import uuid
import sgtk.util.pickle as pickle
import logging
import logging.handlers
import pprint
import traceback
import socket
import tempfile
import sgtk
from sgtk import TankError
LOG_CHANNEL = "sgtk.tk-flame"
class FlameEngine(sgtk.platform.Engine):
"""
The engine class. This wraps around a series of callbacks in Flame (so called hooks).
The Flame engine is a bit different than other engines.
Because Flame doesn't have an API, we cannot call Flame, but Flame will call out
to the toolkit code. This means that the normal register_command approach won't
work inside of Flame - instead, the engine introduces a different scheme of callbacks
that apps can register to ensure that they cen do stuff.
For apps, the main entry points are register_export_hook and register_batch_hook.
For more information, see below.
"""
# the name of the folder in the engine which we should register
# with Flame to trigger various hooks to run.
FLAME_HOOKS_FOLDER = "flame_hooks"
# our default log file to write to
SGTK_LOG_FILE = "tk-flame.log"
# a 'plan B' safe log file that we call fall back on in case
# the default log file cannot be accessed
SGTK_LOG_FILE_SAFE = "/tmp/tk-flame.log"
# define constants for the various modes the engine can execute in
(ENGINE_MODE_DCC, ENGINE_MODE_PRELAUNCH, ENGINE_MODE_BACKBURNER) = list(range(3))
@property
def host_info(self):
"""
:returns: A dictionary with information about the application hosting this engine.
The returned dictionary is of the following form on success:
{
"name": "Flame",
"version": "2018.3.pr84",
}
The returned dictionary is of following form on an error preventing
the version identification.
{
"name": "Flame",
"version": "unknown"
}
"""
host_info = {"name": "Flame", "version": "unknown"}
try:
# The 'SHOTGUN_FLAME_VERSION' environment variable comes from Flame plugin
# The 'TOOLKIT_FLAME_VERSION' environment variable comes from Flame classic config
if "SHOTGUN_FLAME_VERSION" in os.environ:
host_info["version"] = os.environ.get(
"SHOTGUN_FLAME_VERSION", "unknown"
)
elif "TOOLKIT_FLAME_VERSION" in os.environ:
host_info["version"] = os.environ.get(
"TOOLKIT_FLAME_VERSION", "unknown"
)
except:
# Fallback to initialization value above
pass
return host_info
def __init__(self, *args, **kwargs):
"""
Overridden constructor where we init some things which
need to be defined very early on in the engine startup.
"""
# to support use cases where the flame engine isn't started via
# the multi-launchapp chain, make sure that hooks that the engine
# implements are registered.
flame_hooks_folder = os.path.join(self.disk_location, self.FLAME_HOOKS_FOLDER)
sgtk.util.append_path_to_env_var("DL_PYTHON_HOOK_PATH", flame_hooks_folder)
self.log_debug("Added to hook path: %s" % flame_hooks_folder)
# the path to the associated python executable
self._python_executable_path = None
self._log_file = None
# version of Flame we are running
try:
import flame
self.set_version_info(
major_version_str=flame.get_version_major(),
minor_version_str=flame.get_version_minor(),
full_version_str=flame.get_version(),
patch_version_str=flame.get_version_patch(),
)
# If we get to here, the install root can only be /opt/Autodesk
self._install_root = "/opt/Autodesk"
except:
self._flame_version = None
self._install_root = None
# set the current engine mode. The mode contains information about
# how the engine was started - it can be executed either before the
# actual DCC starts up (pre-launch), in the DCC itself or on the
# backburner farm. This means that there are three distinct bootstrap
# scripts which can launch the engine (all contained within the engine itself).
# these bootstrap scripts all set an environment variable called
# TOOLKIT_FLAME_ENGINE_MODE which defines the desired engine mode.
engine_mode_str = os.environ.get("TOOLKIT_FLAME_ENGINE_MODE", "DCC")
if engine_mode_str == "PRE_LAUNCH":
self._engine_mode = self.ENGINE_MODE_PRELAUNCH
elif engine_mode_str == "BACKBURNER":
self._engine_mode = self.ENGINE_MODE_BACKBURNER
elif engine_mode_str == "DCC":
self._engine_mode = self.ENGINE_MODE_DCC
else:
raise TankError(
"Unknown launch mode '%s' defined in "
"environment variable TOOLKIT_FLAME_ENGINE_MODE!" % engine_mode_str
)
# Transcoder, thumbnail generator and local movie generator will be
# initialized on first request for them since, in order to know which
# type we will need, we need to wait for the Flame API to be loaded
# completely.
#
self._transcoder = None
self._thumbnail_generator = None
self._local_movie_generator = None
self._cmdjob_supports_plugin_name = None
super(FlameEngine, self).__init__(*args, **kwargs)
def pre_app_init(self):
"""
Engine construction/setup done before any apps are initialized
"""
# set up a custom exception trap for the engine.
# it will log the exception and if possible also
# display it in a UI
sys.excepthook = sgtk_exception_trap
# now start the proper init
self.log_debug("%s: Initializing..." % self)
# maintain a list of export options
self._registered_export_instances = {}
self._export_sessions = {}
self._registered_batch_instances = []
# maintain the export cache
self._export_info = None
if self.has_ui:
# tell QT to interpret C strings as utf-8
from sgtk.platform.qt import QtCore
utf8 = QtCore.QTextCodec.codecForName("utf-8")
QtCore.QTextCodec.setCodecForCStrings(utf8)
# Assuming we're in a new enough version of Flame (2018.3+) we'll
# be able to link the Flame project to our SG project. This will
# ensure that is a use launches Flame's plugin-based Flow Production Tracking
# integration that they will be bootstrapped into the correct
# project and won't be prompted to choose an SG project to link to.
#
# NOTE: We only take the initiative here and create the project
# link if this is a classic config launch of Flame. One quick way
# to knwo that is to just refer to the environment, where we know
# that the classic startup script sets some variables.
if "TOOLKIT_ENGINE_NAME" in os.environ:
try:
import flame
except Exception:
self.logger.debug(
"Was unable to import the flame Python module. As a result, "
"the Flame project will not be linked to associated Flow Production Tracking "
"project using the Flame Python API. This shouldn't cause "
"any problems in the current session, but it does mean "
"that the user might be prompted to link this project to a "
"Flow Production Tracking project if they launch Flame using the Toolkit "
"plugin and open this same Flame project."
)
else:
try:
current_flame_project = flame.project.current_project
current_flame_project.shotgun_project_name = (
self.context.project.get("name")
)
except Exception:
self.logger.debug(
"Was unable to set the current Flame project's "
"shotgun_project_name property. This shouldn't cause "
"any problems in the current session, but it does mean "
"that the user might be prompted to link this project to a "
"Flow Production Tracking project if they launch Flame using the Toolkit "
"plugin and open this same Flame project."
)
else:
self.logger.debug(
"Successfully linked the Flame project to its associated "
"Flow Production Tracking project."
)
def _initialize_logging(self, install_root):
"""
Set up logging for the engine
:param install_root: path to flame install root
"""
# standard flame log file
std_log_file = os.path.join(install_root, "log", self.SGTK_LOG_FILE)
# test if we can write to the default log file
if os.access(os.path.dirname(std_log_file), os.W_OK):
self._log_file = std_log_file
using_safe_log_file = False
else:
# cannot rotate file in this directory, write to tmp instead.
self._log_file = self.SGTK_LOG_FILE_SAFE
using_safe_log_file = True
# Set up a rotating logger with 4MiB max file size
if using_safe_log_file:
rotating = logging.handlers.RotatingFileHandler(
self._log_file, maxBytes=4 * 1024 * 1024, backupCount=10
)
else:
rotating = logging.handlers.RotatingFileHandler(
self._log_file, maxBytes=0, backupCount=50, delay=True
)
# Always rotate. Current user might not have the correct permission to open this file
if os.path.exists(self._log_file):
rotating.doRollover() # Will open file after roll over
rotating.setFormatter(
logging.Formatter(
"%(asctime)s [%(levelname)s] PID %(process)d: %(message)s"
)
)
# create a global logging object
logger = logging.getLogger(LOG_CHANNEL)
logger.propagate = False
# clear any existing handlers
logger.handlers = []
logger.addHandler(rotating)
if self.get_setting("debug_logging"):
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
# now that we have a logger, we can warn about a non-std log file :)
if using_safe_log_file:
logger.error(
"Cannot write to standard log file location %s! Please check "
"the filesystem permissions. As a fallback, logs will be "
"written to %s instead.",
std_log_file,
log_file,
)
@property
def log_file(self):
return self._log_file
def set_python_executable(self, python_path):
"""
Specifies the path to the associated python process.
This is typically populated as part of the engine startup.
:param python_path: path to python, as string
"""
self._python_executable_path = python_path
self.log_debug(
"This engine is running python interpreter '%s'"
% self._python_executable_path
)
def set_version_info(
self,
major_version_str,
minor_version_str,
full_version_str,
patch_version_str="0",
):
"""
Specifies which version of Flame this engine is running.
This is typically populated as part of the engine startup.
:param major_version_str: Major version number as string
:param minor_version_str: Minor version number as string
:param patch_version_str: Patch version number as string
:param full_version_str: Full version number as string
"""
self._flame_version = {
"full": full_version_str,
"major": major_version_str,
"minor": minor_version_str,
"patch": patch_version_str,
}
self.log_debug(
"This engine is running with Flame version '%s'" % self._flame_version
)
def set_install_root(self, install_root):
"""
Specifies where the flame installation is located.
this may be '/usr/discreet', '/opt/Autodesk' etc.
:param install_root: root path to flame installation
"""
if self._install_root and self._install_root != install_root:
# cannot call this multiple times
raise TankError("Cannot call set_install_root multiple times!")
self.log_debug("Flame install root is '%s'" % self._install_root)
self._install_root = install_root
self._initialize_logging(install_root)
def _get_commands_matching_setting(self, setting):
"""
This expects a list of dictionaries in the form:
{name: "command-name", app_instance: "instance-name", display_name: "Display Name" }
The app_instance value will match a particular app instance associated with
the engine. The name is the menu name of the command to run when the engine starts up. The
display_name is the menu display name of the command to run.
If name is '' then all commands from the given app instance are returned.
If display_name is not present, name will be used instead.
:returns A list of tuples for all commands that match the given setting.
Each tuple will be in the form:
(instance_name, display_name, command_name, callback)
"""
# return a dictionary grouping all the commands by instance name
commands_by_instance = {}
for (name, value) in self.commands.items():
app_instance = value["properties"].get("app")
if app_instance:
instance_name = app_instance.instance_name
else:
# A command without an app instance in the context menu is
# actually coming from the engine, so we'll use the engine
# name instead.
instance_name = "tk-flame"
commands_by_instance.setdefault(instance_name, []).append(
(name, value["callback"])
)
# go through the values from the setting and return any matching commands
ret_value = []
setting_value = self.get_setting(setting, [])
for command in setting_value:
command_name = command["name"]
instance_name = command["app_instance"]
display_name = command.get("display_name", command_name)
instance_commands = commands_by_instance.get(instance_name)
if instance_commands is None:
continue
for (name, callback) in instance_commands:
# add the command if the name from the settings is '' or the name matches
if not command_name or (command_name == name):
ret_value.append((instance_name, display_name, name, callback))
return ret_value
def post_app_init(self):
"""
Do any initialization after apps have been loaded
"""
self.log_debug("%s: Running post app init..." % self)
# only run the startup commands when in DCC mode
if self._engine_mode != self.ENGINE_MODE_DCC:
return
# run any commands registered via run_at_startup
commands_to_start = self._get_commands_matching_setting("run_at_startup")
for (instance_name, command_name, callback) in commands_to_start:
self.log_debug(
"Running at startup: (%s, %s)" % (instance_name, command_name)
)
callback()
def destroy_engine(self):
"""
Called when the engine is being destroyed
"""
self.log_debug("%s: Destroying..." % self)
# Remove the current engine python hooks from the flame python hooks path
env_var_sep = ":"
env_var_name = "DL_PYTHON_HOOK_PATH"
flame_hooks_folder = os.path.join(self.disk_location, self.FLAME_HOOKS_FOLDER)
paths = os.environ.get(env_var_name, "").split(env_var_sep)
paths = [path for path in paths if path != flame_hooks_folder]
os.environ[env_var_name] = env_var_sep.join(paths)
self.log_debug("Removed to hook paths: %s" % flame_hooks_folder)
# Close every app windows
self.close_windows()
@property
def flame_main_window(self):
"""
Returns the Flame's main window
:return: Widget representing the flame's main window.
"""
from sgtk.platform.qt import QtGui
for w in QtGui.QApplication.topLevelWidgets():
if w.objectName() == "CF Main Window":
self.log_debug("Found Flame main window (%s)" % w.windowTitle())
return w
return None
@property
def python_executable(self):
"""
Returns the python executable associated with this engine
:returns: path to python, e.g. '/opt/Autodesk/python/<flame version>/bin/python'
"""
if self._python_executable_path is None:
raise TankError(
"Python executable has not been defined for this engine instance!"
)
return self._python_executable_path
@property
def preset_version(self):
"""
Returns the preset version required for the currently executing
version of Flame. Preset xml files in Flame all have a version number
to denote which generation of the file format they implement. If you are using
an old preset with a new version of Flame, a warning message appears.
:returns: Preset version, as string, e.g. '5'
"""
if self._flame_version is None:
raise TankError(
"Cannot determine preset version - No Flame DCC version specified!"
)
if self.is_version_less_than("2016.1"):
# for version 2016 before ext 1, export preset is v5
return "5"
if self.is_version_less_than("2017"):
# flame 2016 extension 1 and above.
return "6"
# flame 2017 and above
#
# Note: Flame 2017 uses preset 7, however further adjustments to the actual
# preset format used is required in individual apps - for the time being,
# the preset version is held at v6, ensuring that app apps operate correctly,
# but generating a warning message at startup.
#
return "7"
@property
def export_presets_root(self):
"""
The location where flame export presets are located
:returns: Path as string
"""
# If possible use the Flame python API to get the presets location
try:
import flame
if "PyExporter" in dir(flame):
return flame.PyExporter.get_presets_base_dir(
flame.PyExporter.PresetVisibility.Shotgun
)
except:
pass
if self.is_version_less_than("2017"):
# flame 2016 presets structure
return os.path.join(
self.install_root, "presets", self.flame_version, "export", "presets"
)
# flame 2017+ presets structure (note the extra flame folder)
return os.path.join(
self.install_root,
"presets",
self.flame_version,
"export",
"presets",
"flame",
)
@staticmethod
def _get_full_preset_path(preset_path, preset_type):
"""
Convert a path to a preset that can be incomplete to an absolute path.
:param preset_path: Path to a preset to find.
:param preset_type: Type of preset to look for.
:returns: Absolute path to the preset.
"""
if not os.path.isabs(preset_path):
import flame
presets_dir = flame.PyExporter.get_presets_dir(
flame.PyExporter.PresetVisibility.Shotgun, preset_type
)
preset_path = os.path.join(presets_dir, preset_path)
return preset_path
@property
def thumbnails_preset_path(self):
"""
The location of the flame export preset to use to generate thumbnails.
:returns: Path as string
"""
import flame
return self._get_full_preset_path(
self.get_setting("thumbnails_preset_path"),
flame.PyExporter.PresetType.Image_Sequence,
)
@property
def previews_preset_path(self):
"""
The location of the flame export preset to use to generate previews.
:returns: Path as string
"""
import flame
return self._get_full_preset_path(
self.get_setting("previews_preset_path"), flame.PyExporter.PresetType.Movie
)
@property
def local_movies_preset_path(self):
"""
The location of the flame export preset to use to generate local movies.
Local movies are linked to assets in Flow Production Tracking thru the "Path to Movie"
field but are not uploaded on the server.
:returns: Path as string
"""
import flame
return self._get_full_preset_path(
self.get_setting("local_movies_preset_path"),
flame.PyExporter.PresetType.Movie,
)
@property
def wiretap_tools_root(self):
"""
The location of wiretap tool
:returns: Path as string
"""
return os.path.join(self.install_root, "wiretap", "tools", self.flame_version)
def _is_version_less_than(self, major, minor, patch):
"""
Compares the given version numbers with the current
flame version and returns False if the given version is
greater than the current version.
Example:
- Flame: '2016.1.0.278', version str: '2016.1' => False
- Flame: '2016', version str: '2016.1' => True
:param version_str: Version to run comparison against
"""
if int(self.flame_major_version) != int(major):
return int(self.flame_major_version) < int(major)
if int(self.flame_minor_version) != int(minor):
return int(self.flame_minor_version) < int(minor)
if int(self.flame_patch_version) != int(patch):
return int(self.flame_patch_version) < int(patch)
# Same version
return False
def is_version_less_than(self, version_str):
"""
Compares the given version string with the current
flame version and returns False if the given version is
greater than the current version.
Example:
- Flame: '2016.1.0.278', version str: '2016.1' => False
- Flame: '2016', version str: '2016.1' => True
:param version_str: Version to run comparison against
"""
major_ver = 0
minor_ver = 0
patch_ver = 0
chunks = version_str.split(".")
nb_chunks = len(chunks)
if nb_chunks > 0:
if chunks[0].isdigit():
major_ver = int(chunks[0])
if nb_chunks > 1:
if chunks[1].isdigit():
minor_ver = int(chunks[1])
if nb_chunks > 2:
if chunks[2].isdigit():
patch_ver = int(chunks[2])
return self._is_version_less_than(major_ver, minor_ver, patch_ver)
@property
def flame_major_version(self):
"""
Returns Flame's major version number as a string.
:returns: String (e.g. '2016')
"""
if self._flame_version is None:
raise TankError("No Flame DCC version specified!")
return self._flame_version["major"]
@property
def flame_minor_version(self):
"""
Returns Flame's minor version number as a string.
:returns: String (e.g. '2')
"""
if self._flame_version is None:
raise TankError("No Flame DCC version specified!")
return self._flame_version["minor"]
@property
def flame_patch_version(self):
"""
Returns Flame's patch version number as a string.
:returns: String (e.g. '2')
"""
if self._flame_version is None:
raise TankError("No Flame DCC version specified!")
return self._flame_version["patch"]
@property
def flame_version(self):
"""
Returns Flame's full version number as a string.
:returns: String (e.g. '2016.1.0.278')
"""
if self._flame_version is None:
raise TankError("No Flame DCC version specified!")
return self._flame_version["full"]
@property
def install_root(self):
"""
The location where flame is installed.
This may be '/usr/discreet', '/opt/Autodesk' etc.
:returns: Path as string
"""
return self._install_root
@property
def has_ui(self):
"""
Property to determine if the current environment has access to a UI or not
"""
# check if there is a UI. With Flame, we may run the engine in bootstrap
# mode or on the farm - in this case, there is no access to UI. If inside the
# DCC UI environment, pyside support is available.
has_ui = False
try:
from sgtk.platform.qt import QtCore
if QtCore.QCoreApplication.instance():
# there is an active application
has_ui = True
except:
pass
return has_ui
def show_panel(self, panel_id, title, bundle, widget_class, *args, **kwargs):
"""
Override the base show_panel to create a non-modal dialog that will stay on
top of the Flame interface
"""
if not self.has_ui:
self.log_error(
"Sorry, this environment does not support UI display! Cannot show "
"the requested panel '%s'." % title
)
return None
from sgtk.platform.qt import QtCore
# create the dialog:
dialog, widget = self._create_dialog_with_widget(
title, bundle, widget_class, *args, **kwargs
)
dialog.setWindowFlags(
dialog.windowFlags()
| QtCore.Qt.WindowStaysOnTopHint & ~QtCore.Qt.WindowCloseButtonHint
)
# show the dialog
dialog.show()
# lastly, return the instantiated widget
return widget
def _get_dialog_parent(self):
"""
Get the QWidget parent for all dialogs created through :meth:`show_dialog`
:meth:`show_modal`.
Can be overriden in derived classes to return the QWidget to be used as the parent
for all TankQDialog's.
:return: QT Parent window (:class:`PySide.QtGui.QWidget`)
"""
w = self.flame_main_window
return w if w else super(FlameEngine, self)._get_dialog_parent()
def show_dialog(self, title, bundle, widget_class, *args, **kwargs):
"""
Shows a non-modal dialog window in a way suitable for this engine.
The engine will attempt to parent the dialog nicely to the host application.
The dialog will be created with a standard Toolkit window title bar where
the title will be displayed.
.. note:: In some cases, it is necessary to hide the standard Toolkit title
bar. You can do this by adding a property to the widget class you are
displaying::
@property
def hide_tk_title_bar(self):
"Tell the system to not show the standard toolkit toolbar"
return True
**Notes for engine developers**
Qt dialog & widget management can be quite tricky in different engines/applications.
Because of this, Sgtk provides a few overridable methods with the idea being that when
developing a new engine, you only need to override the minimum amount necessary.
Making use of these methods in the correct way allows the base Engine class to manage the
lifetime of the dialogs and widgets efficiently and safely without you having to worry
about it.
The methods available are listed here in the hierarchy in which they are called::
show_dialog()/show_modal()
_create_dialog_with_widget()
_get_dialog_parent()
_create_widget()
_create_dialog()
For example, if you just need to make sure that all dialogs use a specific parent widget
then you only need to override _get_dialog_parent() (e.g. the tk-maya engine).
However, if you need to implement a two-stage creation then you may need to re-implement
show_dialog() and show_modal() to call _create_widget() and _create_dialog() directly rather
than using the helper method _create_dialog_with_widget() (e.g. the tk-3dsmax engine).
Finally, if the application you are writing an engine for is Qt based then you may not need
to override any of these methods (e.g. the tk-nuke engine).
:param title: The title of the window. This will appear in the Toolkit title bar.
:param bundle: The app, engine or framework object that is associated with this window
:param widget_class: The class of the UI to be constructed. This must derive from QWidget.
:type widget_class: :class:`PySide.QtGui.QWidget`
Additional parameters specified will be passed through to the widget_class constructor.
:returns: the created widget_class instance
"""
if not self.has_ui:
self.log_error(
"Sorry, this environment does not support UI display! Cannot show "
"the requested window '%s'." % title
)
return None
from sgtk.platform.qt import QtCore
# create the dialog:
dialog, widget = self._create_dialog_with_widget(
title, bundle, widget_class, *args, **kwargs
)
dialog.setWindowFlags(
dialog.windowFlags()
| QtCore.Qt.WindowStaysOnTopHint & ~QtCore.Qt.WindowCloseButtonHint
)
# show the dialog
dialog.show()
# lastly, return the instantiated widget
return widget
def close_windows(self):
"""
Closes the various windows (dialogs, panels, etc.) opened by the engine.
"""
# Make a copy of the list of Tank dialogs that have been created by the engine and
# are still opened since the original list will be updated when each dialog is closed.
opened_dialog_list = self.created_qt_dialogs[:]
# Loop through the list of opened Tank dialogs.
for dialog in opened_dialog_list:
dialog_window_title = dialog.windowTitle()
try:
# Close the dialog and let its close callback remove it from the
# original dialog list.
#
self.log_debug("Closing dialog %s." % dialog_window_title)
dialog.close()
except Exception as exception:
self.log_error(
"Cannot close dialog %s: %s" % (dialog_window_title, exception)
)
@staticmethod
def log_debug(msg):
"""
Log a debug message
:param msg: The debug message to log
"""
logging.getLogger(LOG_CHANNEL).debug(msg)
@staticmethod
def log_info(msg):
"""
Log some info
:param msg: The info message to log
"""
logging.getLogger(LOG_CHANNEL).info(msg)
@staticmethod
def log_warning(msg):
"""
Log a warning
:param msg: The warning message to log
"""
logging.getLogger(LOG_CHANNEL).warning(msg)
@staticmethod
def log_error(msg):
"""
Log an error
:param msg: The error message to log
"""
logging.getLogger(LOG_CHANNEL).error(msg)
################################################################################################
# Engine Bootstrap
#
def pre_dcc_launch_phase(self):
"""
Special bootstrap method used to set up the Flame environment.
This is designed to execute before Flame has launched, as part of the
bootstrapping process.
This method assumes that it is being executed inside a Flame python
and is called from the app_launcher script which ensures such an environment.
The bootstrapper will first import the wiretap API and setup other settings.
It then attempts to execute the pre-DCC project creation process, utilizing
both wiretap and QT (setup project UI) for this.
Finally, it will return the command line args to pass to Flame as it is being
launched.
:returns: arguments to pass to the app launch process
"""
if self.get_setting("debug_logging"):
# enable Flame hooks debug
os.environ["DL_DEBUG_PYTHON_HOOKS"] = "1"
# see if we can launch into batch mode. We only do this when in a
# shot context and if there is a published batch file in Flow Production Tracking
#
# For now, hard code the logic of how to detect which batch file to load up.
# TODO: in the future, we may want to expose this in a hook - but it is arguably
# pretty advanced customization :)
#
# Current logic: Find the latest batch publish belonging to the context
if self.context.entity:
# we have a current context to lock on to!
# try to see if we can find the latest batch publish
publish_type = sgtk.util.get_published_file_entity_type(self.sgtk)
if publish_type == "PublishedFile":
type_link_field = "published_file_type.PublishedFileType.code"
else:
type_link_field = "tank_type.TankType.code"
sg_data = self.shotgun.find_one(
publish_type,
[
[
type_link_field,
"is",
self.get_setting("flame_batch_publish_type"),
],
["entity", "is", self.context.entity],
],
["path"],
order=[{"field_name": "created_at", "direction": "desc"}],
)
if sg_data:
# we have a batch file published for this context!
batch_file_path = sg_data["path"]["local_path"]
if os.path.exists(batch_file_path):
self.log_debug("Setting auto startup file '%s'" % batch_file_path)
os.environ["DL_BATCH_START_WITH_SETUP"] = batch_file_path
# add Flame hooks for this engine
flame_hooks_folder = os.path.join(self.disk_location, self.FLAME_HOOKS_FOLDER)
sgtk.util.append_path_to_env_var("DL_PYTHON_HOOK_PATH", flame_hooks_folder)
self.log_debug("Added to hook path: %s" % flame_hooks_folder)
# now that we have a wiretap library, call out and initialize the project
# automatically