-
Notifications
You must be signed in to change notification settings - Fork 13
/
engine.py
1818 lines (1507 loc) · 69.1 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) 2019 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.
import logging
import os
import subprocess
import sys
import tempfile
import threading
import uuid
import re
from contextlib import contextmanager
import sgtk
from sgtk.util.filesystem import ensure_folder_exists
try:
from tank_vendor import sgutils
except ImportError:
from tank_vendor import six as sgutils
class PhotoshopCCEngine(sgtk.platform.Engine):
"""
A Photoshop CC engine for Shotgun Toolkit.
"""
# the maximum size for a generated thumbnail
MAX_THUMB_SIZE = 512
SHOTGUN_ADOBE_PORT = os.environ.get("SHOTGUN_ADOBE_PORT")
SHOTGUN_ADOBE_APPID = os.environ.get("SHOTGUN_ADOBE_APPID")
# Backwards compatibility added to support tk-photoshop environment vars.
# https://community.shotgridsoftware.com/t/adobe-engine-crashing-on-long-operations/8329
SHOTGUN_ADOBE_HEARTBEAT_INTERVAL = os.environ.get(
"SHOTGUN_ADOBE_HEARTBEAT_INTERVAL",
os.environ.get(
"SGTK_PHOTOSHOP_HEARTBEAT_INTERVAL",
1.0,
),
)
SHOTGUN_ADOBE_HEARTBEAT_TOLERANCE = os.environ.get(
"SHOTGUN_ADOBE_HEARTBEAT_TOLERANCE",
os.environ.get(
"SGTK_PHOTOSHOP_HEARTBEAT_TOLERANCE",
2,
),
)
SHOTGUN_ADOBE_NETWORK_DEBUG = (
"SGTK_PHOTOSHOP_NETWORK_DEBUG" in os.environ
or "SHOTGUN_ADOBE_NETWORK_DEBUG" in os.environ
)
TEST_SCRIPT_BASENAME = "run_tests.py"
PY_TO_JS_LOG_LEVEL_MAPPING = {
"CRITICAL": "error",
"ERROR": "error",
"WARNING": "warn",
"INFO": "info",
"DEBUG": "debug",
}
_COMMAND_UID_COUNTER = 0
_LOCK = threading.Lock()
_FAILED_PINGS = 0
_CONTEXT_CACHE = dict()
_CHECK_CONNECTION_TIMER = None
_CONTEXT_CHANGES_DISABLED = False
_DIALOG_PARENT = None
_WIN32_PHOTOSHOP_MAIN_HWND = None
_PROXY_WIN_HWND = None
_HEARTBEAT_DISABLED = False
_PROJECT_CONTEXT = None
_CONTEXT_CACHE_KEY = "photoshopcc_context_cache"
_HAS_CHECKED_CONTEXT_POST_LAUNCH = False
############################################################################
# context changing
def post_context_change(self, old_context, new_context):
"""
Runs after a context change has occurred. This will trigger the
new state to be sent to the Adobe CC host application.
:param old_context: The previous context.
:param new_context: The current context.
"""
# keep track of schema load for the current project to make sure we
# aren't trying to use sg globals prior to load
self.__schema_loaded = False
# get the project id to supply to sg globals
if new_context.project:
project_id = new_context.project["id"]
else:
project_id = None
# callback to set the schema loaded flag
def _on_schema_loaded():
self.__schema_loaded = True
# tell sg globals to load the schema for the current project. sg globals
# will run the callback immediately if already cached so this is likely
# very quick.
self.__shotgun_globals.run_on_schema_loaded(
_on_schema_loaded, project_id=project_id
)
# go ahead and start the process of sending the current state back to js
self.__send_state()
# If the context is set in the environment, then we'll update it with
# the new one. This will mean that a CEP extension restart will come
# back up with the same context that it went down with. We have to set
# this in ExtendScript, because it's the parent process of any CEP and
# Python processes that get spawned. By setting it at the top, it'll be
# propagated down to any of Photoshop's subprocesses.
if "TANK_CONTEXT" in os.environ:
self.adobe.dollar.setenv("TANK_CONTEXT", new_context.serialize())
############################################################################
# engine initialization
def pre_app_init(self):
"""
Sets up the engine into an operational state. This method called before
any apps are loaded.
"""
# import and keep a handle on the bundled python module
self.__tk_photoshopcc = self.import_module("tk_photoshopcc")
# constant command uid lookups for these special commands
self.__jump_to_sg_command_id = self.__get_command_uid()
self.__jump_to_fs_command_id = self.__get_command_uid()
# get the adobe instance. it may have been initialized already by a
# previous instance of the engine. if not, initialize a new one.
self._adobe = self.__tk_photoshopcc.AdobeBridge.get_or_create(
identifier=self.instance_name,
port=self.SHOTGUN_ADOBE_PORT,
logger=self.logger,
network_debug=self.SHOTGUN_ADOBE_NETWORK_DEBUG,
)
self.logger.debug("Network debug logging is %s" % self._adobe.network_debug)
self.logger.debug("%s: Initializing..." % (self,))
# connect to all the adobe bridge signals
self.adobe.logging_received.connect(self._handle_logging)
self.adobe.command_received.connect(self._handle_command)
self.adobe.active_document_changed.connect(self._handle_active_document_change)
self.adobe.run_tests_request_received.connect(self._run_tests)
self.adobe.state_requested.connect(self.__send_state)
# in order to use frameworks, they have to be imported via
# import_module. so they're exposed in the bundled python. keep a handle
# on them for reuse.
self.__shotgun_data = self.__tk_photoshopcc.shotgun_data
self.__shotgun_globals = self.__tk_photoshopcc.shotgun_globals
self.__settings = self.__tk_photoshopcc.shotgun_settings
# import here since the engine is responsible for defining Qt.
from sgtk.platform.qt import QtCore
# create a data retriever for async querying of sg data
self.__sg_data = self.__shotgun_data.ShotgunDataRetriever(
QtCore.QCoreApplication.instance()
)
# get outselves a settings manager where we can store metadata.
self.__settings_manager = self.__settings.UserSettings(self)
# connect the retriever signals
self.__sg_data.work_completed.connect(self.__on_worker_signal)
self.__sg_data.work_failure.connect(self.__on_worker_failure)
# context request uids. we keep track of these to make sure we're only
# processing the current requests.
self.__context_find_uid = None
self.__context_thumb_uid = None
# keep track if sg global schema has been cached
self.__schema_loaded = False
# start the retriever thread
self.__sg_data.start()
# keep a list of handles on the launched dialogs
self.__qt_dialogs = []
def post_app_init(self):
"""
Runs after all apps have been initialized.
"""
if not self.adobe.event_processor:
try:
from sgtk.platform.qt import QtGui
self.adobe.event_processor = QtGui.QApplication.processEvents
except ImportError:
pass
self.__setup_connection_timer()
self.__send_state()
# forward the log file path back to the js side. this is used to direct
# clients to the file in the event of an error
log_file = sgtk.LogManager().base_file_handler.baseFilename
self.adobe.send_log_file_path(log_file)
# If there's more than one document open at the time that the engine is
# started up, then we're in a situation where we very likely were restarted.
# In that case, we need to try to retrieve a stored cache of serialized
# context objects from our settings manager. This will allow us to
# prepopulate our in-memory context cache with the contexts that were
# known prior to the extension restart.
if len(list(self.adobe.app.documents)) > 1:
self.logger.debug("Multiple documents found, loading stored context cache.")
serial_cache = self.__settings_manager.retrieve(
self._CONTEXT_CACHE_KEY,
dict(),
self.__settings_manager.SCOPE_PROJECT,
)
for key, value in serial_cache.items():
self._CONTEXT_CACHE[key] = sgtk.Context.deserialize(value)
else:
# If there are fewer than 2 documents open, we don't need the stored
# cache, regardless of whether this is a restart situation or a fresh
# launch of PS. In that case, we take the opportunity to clear anything
# that might exist in the stored cache, as it's data we don't need.
self.logger.debug("Single document found, clearing stored context cache.")
self.__settings_manager.store(
self._CONTEXT_CACHE_KEY,
dict(),
)
def destroy_engine(self):
"""
Called when the engine should tear down itself and all its apps.
"""
self.logger.debug("Destroying engine...")
# Set our parent widget back to being owned by the window manager
# instead of Photoshop's application window.
if self._PROXY_WIN_HWND and sys.platform == "win32":
self.__tk_photoshopcc.win_32_api.SetParent(self._PROXY_WIN_HWND, 0)
# No longer poll for new messages from this engine.
if self._CHECK_CONNECTION_TIMER:
self._CHECK_CONNECTION_TIMER.stop()
# We're going to hide and force the garbage collection of any dialogs
# that we know about. This will stop memory leaks, and is also prudent
# since we're severing the socket.io connection that will allow them
# to function properly.
dialogs_still_opened = self.created_qt_dialogs[:]
for dialog in dialogs_still_opened:
dialog.close()
# Gracefully stop our data retriever. This call will block until the
# currently-processing request has completed.
self.__sg_data.stop()
# Disconnect from the server.
self.adobe.disconnect()
# Disconnect the signals in case there are references to this engine
# out there. without disconnecting, it will still respond to signals
# from the adobe bridge.
self.adobe.logging_received.disconnect(self._handle_logging)
self.adobe.command_received.disconnect(self._handle_command)
self.adobe.active_document_changed.disconnect(
self._handle_active_document_change
)
self.adobe.run_tests_request_received.disconnect(self._run_tests)
self.adobe.state_requested.disconnect(self.__send_state)
def post_qt_init(self):
"""
Called externally once a ``QApplication`` has been created and completes
the engine setup process.
"""
# We need to have the RPC API call processEvents during its response
# wait loop. This will keep that loop from blocking the UI thread.
from sgtk.platform.qt import QtGui
self.adobe.event_processor = QtGui.QApplication.processEvents
# Since this is running in our own Qt event loop, we'll use the bundled
# dark look and feel. breaking encapsulation to do so.
self.logger.debug("Initializing default styling...")
self._initialize_dark_look_and_feel()
# Sets up the heartbeat timer to run asynchronously.
self.__setup_connection_timer(force=True)
def register_command(self, name, callback, properties=None):
"""
Registers a new command with the engine. For Adobe RPC purposes,
a "uid" property is added to the command's properties.
"""
properties = properties or dict()
properties["uid"] = self.__get_command_uid()
return super(PhotoshopCCEngine, self).register_command(
name,
callback,
properties,
)
def export_as_jpeg(
self, document=None, output_path=None, max_size=2048, quality=12
):
"""
Export a Jpeg image from the given document or from the current document.
:param document: The document to generate a thumbnail for. Assumes the
active document if ``None`` is supplied.
:param output_path: The output file path to write the thumbnail. If
``None`` is supplied, the method will write to a temp file.
:param int max_size: The maximum width and height of the exported image.
:param int quality: The Jpeg quality of the exported image.
:returns: The full path to the exported image.
:raises: RuntimeError if the document or its size can't be retrieved.
"""
adobe = self.adobe
# Get some current values so we can restore them.
original_ruler_units = adobe.app.preferences.rulerUnits
original_dialog_mode = adobe.app.displayDialogs
# If no output_path was given, use a temp file.
jpeg_pub_path = output_path or os.path.join(
tempfile.gettempdir(), "%s_sgtk.jpg" % uuid.uuid4().hex
)
with self.context_changes_disabled():
try:
# Set unit system to pixels:
adobe.app.preferences.rulerUnits = adobe.Units.PIXELS
# Disable dialogs.
adobe.app.displayDialogs = adobe.DialogModes.NO
try:
active_doc = document or adobe.app.activeDocument
except RuntimeError as e:
# Exceptions reported by Photoshop CEP through the RPC API
# are pretty useless, so catch the error, raise our own exception
# but still log the original exception for debug purpose.
self.logger.debug(
"Unable to retrieve a document: %s" % e,
exc_info=True, # Get traceback automatically
)
raise RuntimeError("Unable to retrieve a document")
orig_name = active_doc.name
width_str = str(active_doc.width.value)
height_str = str(active_doc.height.value)
# Get a temp document name so we can manipulate the document without
# affecting the original docuement.
name, sfx = os.path.splitext(orig_name)
# a "." is included in the extension returned by splitext
jpeg_name = "%s_tkjpeg%s" % (name, sfx)
# Find the doc size in pixels
# Note: this doesn't handle measurements other than pixels.
doc_width = doc_height = 0
# It seems we used to get back "<size> px" but now we receive back
# just a number, so let's have the " px" bit optional.
exp = re.compile("^(?P<value>[0-9]+)( px)?$")
mo = exp.match(width_str)
if mo:
doc_width = int(mo.group("value"))
mo = exp.match(height_str)
if mo:
doc_height = int(mo.group("value"))
jpeg_width = jpeg_height = 0
if doc_width and doc_height:
max_sz = max(doc_width, doc_height)
if max_sz > max_size:
scale = min(float(max_size) / float(max_sz), 1.0)
jpeg_width = max(min(int(doc_width * scale), doc_width), 1)
jpeg_height = max(min(int(doc_height * scale), doc_height), 1)
else:
raise RuntimeError(
"Unable to retrieve document size from %s x %s "
% (
width_str,
height_str,
)
)
# Get a file object from Photoshop for this path and the current
# jpg save options:
jpeg_file = adobe.File(jpeg_pub_path)
jpeg_options = adobe.JPEGSaveOptions()
jpeg_options.quality = quality
# duplicate the original doc:
save_options = adobe.SaveOptions.DONOTSAVECHANGES
jpeg_doc = active_doc.duplicate(jpeg_name)
try:
# Flatten image:
jpeg_doc.flatten()
# Convert to eight bits
jpeg_doc.bitsPerChannel = adobe.BitsPerChannelType.EIGHT
# Resize if needed:
if jpeg_width and jpeg_height:
jpeg_doc.resizeImage(
"%d px" % jpeg_width, "%d px" % jpeg_height
)
# Save:
jpeg_doc.saveAs(jpeg_file, jpeg_options, True)
finally:
# Close the doc:
jpeg_doc.close(save_options)
finally:
# Set units back to original
adobe.app.preferences.rulerUnits = original_ruler_units
# Set dialog mode back to original.
adobe.app.displayDialogs = original_dialog_mode
return jpeg_pub_path
def generate_thumbnail(self, document=None, output_path=None):
"""
Try to generate a thumbnail for an open document.
If a thumbnail can be generated, the output path will be returned. If
no thumbnail can be created, ``None`` will be returned.
:param document: The document to generate a thumbnail for. Assumes the
active document if ``None`` is supplied.
:param output_path: The output file path to write the thumbnail. If
``None`` supplied, the method will write to a temp file.
:returns: Full path the thumbnail file, or None.
"""
jpeg_path = None
try:
jpeg_path = self.export_as_jpeg(
document,
output_path,
max_size=self.MAX_THUMB_SIZE,
quality=3, # Default quality value for Photoshop Jpeg option
)
except Exception as e:
# Log the error for debug purpose.
self.logger.warning(
"Couldn't generate thumbnail: %s" % e,
exc_info=True, # include traceback
)
return jpeg_path
def save(self, document):
"""
Save the document in place
"""
if document.saved:
# since Photoshop 24.1.0, saving an already saved file triggers errors
return
with self.context_changes_disabled():
# remember the active document so that we can restore it.
previous_active_document = self.adobe.app.activeDocument
# make the document being processed the active document
self.adobe.app.activeDocument = document
document.save()
# restore the active document
self.adobe.app.activeDocument = previous_active_document
def save_to_path(self, document, path):
"""
Save the document to the supplied path.
"""
# TODO: more logic is needed here to save account for different file
# options. By default, the file will always be saved to a PDF.
with self.context_changes_disabled():
# remember the active document so that we can restore it.
previous_active_document = self.adobe.app.activeDocument
# make the document being processed the active document
self.adobe.app.activeDocument = document
(_, ext) = os.path.splitext(path)
ext = ext.lower()
# first, check if file is .psb since it is processed using the adobe bridge
if ext == ".psb":
self.adobe.save_as_psb(path)
# restore the active document
self.adobe.app.activeDocument = previous_active_document
return
# the following extensions follow the same pattern of defining options
# that will be supplied to the document's saveAs method
if ext == ".bmp":
save_options = self.adobe.BMPSaveOptions()
elif ext == ".dcs":
# DCS1_SaveOptions is not used for ".dcs" files, DCS2_SaveOptions is used instead
save_options = self.adobe.DCS2_SaveOptions()
elif ext == ".eps":
save_options = self.adobe.EPSSaveOptions()
elif ext == ".gif":
save_options = self.adobe.GIFSaveOptions()
elif ext in [".jpg", ".jpeg"]:
save_options = self.adobe.JPEGSaveOptions()
# the default quality for jpg is 3, so we set it to the maximum: 12
save_options.quality = 12
elif ext == ".pdf":
save_options = self.adobe.PDFSaveOptions()
elif ext in [".pict", ".pct", ".pic"]:
# PICTResourceSaveOptions is skipped for now, need a way to differentiate PICT
# files from PICT resource files
save_options = self.adobe.PICTFileSaveOptions()
elif ext == ".pixar":
save_options = self.adobe.PixarSaveOptions()
elif ext == ".png":
save_options = self.adobe.PNGSaveOptions()
elif ext == ".psd":
save_options = self.adobe.PhotoshopSaveOptions()
elif ext == ".raw":
save_options = self.adobe.RawSaveOptions()
elif ext in [".sgi", ".rgb", ".rgba", ".bw", ".int", ".inta"]:
save_options = self.adobe.SGIRGBSaveOptions()
elif ext in [".tga", ".targa"]:
save_options = self.adobe.TargaSaveOptions()
elif ext in [".tif", ".tiff"]:
save_options = self.adobe.TiffSaveOptions()
else:
# default value
save_options = self.adobe.PhotoshopSaveOptions()
# Photoshop won't ensure that the folder is created when saving, so we must make sure it exists
ensure_folder_exists(os.path.dirname(path))
document.saveAs(self.adobe.File(path), save_options)
# restore the active document
self.adobe.app.activeDocument = previous_active_document
def save_as(self, document):
"""
Launch a Qt file browser to select a file, then save the supplied
document to that path.
:param document: The document to save.
"""
from sgtk.platform.qt import QtGui
try:
doc_path = document.fullName.fsName
except RuntimeError:
doc_path = None
# photoshop doesn't appear to have a "save as" dialog accessible via
# python. so open our own Qt file dialog.
file_dialog = QtGui.QFileDialog(
parent=self._get_dialog_parent(),
caption="Save As",
directory=doc_path,
filter="Photoshop Documents (*.psd)",
)
file_dialog.setLabelText(QtGui.QFileDialog.Accept, "Save")
file_dialog.setLabelText(QtGui.QFileDialog.Reject, "Cancel")
file_dialog.setOption(QtGui.QFileDialog.DontResolveSymlinks)
file_dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog)
if not file_dialog.exec_():
return
path = file_dialog.selectedFiles()[0]
if path:
self.save_to_path(document, path)
@property
def host_info(self):
"""
Returns information about the application hosting this engine.
:returns: A {"name": application name, "version": application version}
dictionary.
"""
if not self.adobe:
# Don't error out if the bridge was not yet started
return ("Adobe Photoshop", "unknown")
version = self.adobe.app.version
# app.version just returns 18.1.1 which is not what users see in the UI
# extract a more meaningful version from the systemInformation property
# which gives something like:
# Adobe Photoshop Version: 2017.1.1 20170425.r.252 2017/04/25:23:00:00 CL 1113967 x64\rNumber of .....
# and use it instead if available.
m = re.search("Version:\s+([\.0-9]+)", self.adobe.app.systemInformation)
if m:
version = m.group(1)
return {
"name": self.adobe.app.name,
"version": version,
}
def _initialize_dark_look_and_feel(self):
"""
Override the base engine method.
Apply specific styling for this DCC.
"""
from sgtk.platform.qt import QtGui
# Initialize the SG Toolkit style to the application.
super()._initialize_dark_look_and_feel()
# Apply specific styling
app = QtGui.QApplication.instance()
app_palette = app.palette()
# The default placeholder text for this DCC is black, let's set it back to
# the text color (as it was in Qt5), but with the current placeholder
# text alpha value.
new_placeholder_text_color = app_palette.text().color()
placeholder_text_color = app_palette.placeholderText().color()
new_placeholder_text_color.setAlpha(placeholder_text_color.alpha())
app_palette.setColor(QtGui.QPalette.PlaceholderText, new_placeholder_text_color)
# Set the palette back with the specific styling
app.setPalette(app_palette)
############################################################################
# RPC
def _check_connection(self):
"""Make sure we are still connected to the adobe cc product."""
# If we're in a disabled state, then we don't do anything here. This
# is controlled by the heartbeat_disabled context manager provided
# by this engine.
if self._HEARTBEAT_DISABLED:
return
try:
self.adobe.ping()
except Exception:
if self._FAILED_PINGS >= self.SHOTGUN_ADOBE_HEARTBEAT_TOLERANCE:
from sgtk.platform.qt import QtCore
QtCore.QCoreApplication.instance().quit()
else:
self._FAILED_PINGS += 1
else:
self._FAILED_PINGS = 0
# Will allow queued up messages (like logging calls)
# to be handled on the Python end.
self.adobe.process_new_messages()
# We also have a one-time check we need to make after the timer is
# started. In the event that the user opened a document before the
# integration completed its initialization, we need to make sure
# that the context is correct. Since we rely of Photoshop sending
# an event on active document change to control our context, if that
# occurred before we were listening then we likely missed it and
# need to make sure we're not in a stale state.
#
# Note: This is occurring in the timer here because the context
# change can only occur once the engine initialization process has
# completed. As such, we can rely on the timer to delay its execution
# until we're in a state where the context change will succeed.
if not self._HAS_CHECKED_CONTEXT_POST_LAUNCH:
if sgtk.platform.current_engine():
self.logger.debug(
"Engine initialization complete -- checking active "
"document context..."
)
active_document_path = self.adobe.get_active_document_path()
if active_document_path:
self.logger.debug(
"There is an active document. Checking to see if a "
"context change is required."
)
self._handle_active_document_change(active_document_path)
else:
self.logger.debug(
"There is no active document, so there is no need to change context."
)
self._HAS_CHECKED_CONTEXT_POST_LAUNCH = True
else:
self.logger.debug(
"Engine initialization has not completed -- waiting to "
"check the active document context..."
)
def _emit_log_message(self, handler, record):
"""
Called by the engine whenever a new log message is available.
All log messages from the toolkit logging namespace will be passed to
this method.
:param handler: Log handler that this message was dispatched from
:type handler: :class:`~python.logging.LogHandler`
:param record: Std python logging record
:type record: :class:`~python.logging.LogRecord`
"""
# If the _adobe attribute is set, then we can forward logging calls
# back to the js process via rpc.
if hasattr(self, "_adobe"):
level = self.PY_TO_JS_LOG_LEVEL_MAPPING[record.levelname]
# log the message back to js via rpc
self.adobe.log_message(level, record.message)
# prior to the _adobe attribute being set, we rely on the js process
# handling stdout and logging it.
else:
# we don't use the handler's format method here because the adobe
# side expects a certain format.
msg_str = "[%s]: %s" % (record.levelname, record.message)
sys.stdout.write(msg_str)
sys.stdout.flush()
def _handle_active_document_change(self, active_document_path):
"""
Gets the active document from the host application, determines which
context it belongs to, and changes to that context.
:param str active_document_path: The path to the new active document.
:returns: True if the context changed, False if it did not.
"""
# If the config says to not change context on active document change, then
# we don't do anything here.
if not self.get_setting("automatic_context_switch"):
self.logger.debug(
"Engine setting automatic_context_switch is false. Not changing context."
)
return
# Make sure we have a properly-encoded string for the path. We can
# possibly get a file path/name that contains unicode, and we don't
# want to deal with that later on.
active_document_path = sgutils.ensure_str(active_document_path)
# This will be True if the context_changes_disabled context manager is
# used. We're just in a temporary state of not allowing context changes,
# which is useful when an app is doing a lot of Photoshop work that
# might be triggering active document changes that we don't want to
# result in PTR context changes.
with self.heartbeat_disabled():
if self._CONTEXT_CHANGES_DISABLED:
self.logger.debug(
"Engine is in 'no context changes' mode. Not changing context."
)
return False
if active_document_path:
self.logger.debug("New active document is %s" % active_document_path)
else:
self.logger.debug(
"New active document check failed. This is likely due to the "
"new active document being in an unsaved state."
)
return False
cached_context = self.__get_from_context_cache(active_document_path)
if cached_context:
context = cached_context
self.logger.debug("Document found in context cache: %r" % context)
else:
try:
context = sgtk.sgtk_from_path(
active_document_path
).context_from_path(
active_document_path,
previous_context=self.context,
)
self.add_to_context_cache(active_document_path, context)
except Exception:
self.logger.debug(
"Unable to determine context from path. Setting the Project context."
)
# clear the context finding task ids so that any tasks that
# finish won't send data to js.
self.__context_find_uid = None
self.__context_thumb_uid = None
# We go to the project context if this is a file outside of
# PTR control.
if self._PROJECT_CONTEXT is None:
self._PROJECT_CONTEXT = sgtk.Context(
tk=self.context.sgtk,
project=self.context.project,
)
context = self._PROJECT_CONTEXT
if not context.project:
self.logger.debug(
"New context doesn't have a Project entity. Not changing "
"context."
)
return False
if context and context != self.context:
self.adobe.context_about_to_change()
sgtk.platform.change_context(context)
return True
return False
def _handle_command(self, uid):
"""
Handles an RPC engine command execution request.
:param int uid: The unique id of the engine command to run.
"""
self.logger.debug("Handling command request for uid: %s" % (uid,))
with self.heartbeat_disabled():
from sgtk.platform.qt import QtGui
if uid == self.__jump_to_fs_command_id:
# jump to fs special command triggered
self._jump_to_fs()
elif uid == self.__jump_to_sg_command_id:
# jump to sg special command triggered
self._jump_to_sg()
else:
# a registered command was triggered
for command in self.commands.values():
if command.get("properties", dict()).get("uid") == uid:
self.logger.debug(
"Executing callback for command: %s" % (command,)
)
result = command["callback"]()
if isinstance(result, QtGui.QWidget):
# if the callback returns a widget, keep a handle on it
self.__qt_dialogs.append(result)
def _handle_logging(self, level, message):
"""
Handles an RPC logging request.
:param str level: One of "debug", "info", "warning", or "error".
:param str message: The log message.
"""
# manually create a record to log to the standard file handler.
# we format it to match the regular logs, but tack on the '.js' to
# indicate that it came from javascript.
record = logging.makeLogRecord(
{
"levelname": level.upper(),
"name": "%s.js" % (self.logger.name,),
"msg": message,
}
)
# forward this message to the base file handler so that it is logged
# appropriately.
if sgtk.LogManager().base_file_handler:
sgtk.LogManager().base_file_handler.handle(record)
def _run_tests(self):
"""
Runs the test suite for the tk-photoshopcc bundle.
"""
# If we don't know what the tests root directory path is
# via the environment, then we shouldn't be here.
try:
tests_root = os.environ["SHOTGUN_ADOBE_TESTS_ROOT"]
except KeyError:
self.logger.error(
"The SHOTGUN_ADOBE_TESTS_ROOT environment variable "
"must be set to the root directory of the tests to be "
"run. Not running tests!"
)
return
else:
# Make sure we can find the run_tests.py file within the root
# that was specified in the environment.
self.logger.debug("Test root path found. Looking for run_tests.py.")
test_module = os.path.join(tests_root, self.TEST_SCRIPT_BASENAME)
if not os.path.exists(test_module):
self.logger.error(
"Unable to find run_tests.py in the directory "
"specified by the SHOTGUN_ADOBE_TESTS_ROOT "
"environment variable. Not running tests!"
)
return
self.logger.debug("Found run_tests.py. Importing to run tests.")
try:
# We need to prepend to sys.path. We'll set it back to
# what it was before once we're done running the tests.
original_sys_path = sys.path
python_root = os.path.abspath(
os.path.join(os.path.dirname(__file__), "python")
)
sys.path = [tests_root, python_root] + sys.path
import run_tests
# The run_tests.py module should make available a run_tests
# function. We need to run that, giving it the engine pointer
# so that it can use that for logging purposes.
run_tests.run_tests(self)
except Exception as exc:
# If we got an unhandled exception, then something went very
# wrong in the test suite. We'll just trap that and print it
# as an error without letting it bubble up any farther.
import traceback
self.logger.error(
"Tests raised the following:\n%s" % traceback.format_exc(exc)
)
finally:
# Reset sys.path back to what it was before we started.
sys.path = original_sys_path
############################################################################
# properties
@property
def adobe(self):
"""
The handle to the Adobe RPC API.
"""
return self._adobe
@property
def app_id(self):
"""
The runtime app id. This will be a string -- something like
PHSP for Photoshop, or AEFT for After Effect.
"""
return self.SHOTGUN_ADOBE_APPID
@property
def context_change_allowed(self):
"""
Specifies that context changes are allowed by the engine.
"""
return True
############################################################################
# context manager
@contextmanager
def context_changes_disabled(self):
"""
A context manager that disables context changes on enter, and enables
them on exit. This is useful in apps that might be performing operations
that require changes in the active document that don't want to trigger
a context change.
"""
self._CONTEXT_CHANGES_DISABLED = True
yield
self._CONTEXT_CHANGES_DISABLED = False
@contextmanager
def heartbeat_disabled(self):
"""
A context manager that disables the heartbeat and message processing
timer on enter, and restarts it on exit.
"""
try:
self.logger.debug("Pausing heartbeat...")
self._HEARTBEAT_DISABLED = True
except Exception as e: