-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstartup.py
341 lines (282 loc) · 11.6 KB
/
startup.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
# ----------------------------------------------------------------------------
# Copyright (c) 2019-2020, Diego Garcia Huerta.
#
# Your use of this software as distributed in this GitHub repository, is
# governed by the BSD 3-clause License.
#
# Your use of the Shotgun Pipeline Toolkit is governed by the applicable license
# agreement between you and Autodesk / Shotgun.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------------------------------------------------
import cgitb
import hashlib
import os
import shutil
import sys
import sgtk
from sgtk.pipelineconfig_utils import get_sgtk_module_path
from sgtk.platform import LaunchInformation, SoftwareLauncher, SoftwareVersion
__author__ = "Diego Garcia Huerta"
__contact__ = "https://www.linkedin.com/in/diegogh/"
ENGINE_NAME = "tk-krita"
APPLICATION_NAME = "Krita"
logger = sgtk.LogManager.get_logger(__name__)
# Let's enable cool and detailed tracebacks
cgitb.enable(format="text")
def resolve_path(path):
"""
Returns a path by resolving variables, user name, symbolic links, etc...
"""
return reduce(
lambda x, f: f(x),
(
os.path.expanduser,
os.path.expandvars,
os.path.abspath,
os.path.realpath,
os.path.normpath,
),
path,
)
def sha256(fname):
"""
Calculates the hash of a file, used to compare small files.
"""
hash_sha256 = hashlib.sha256()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest()
def samefile(file1, file2):
"""
Returns true if two files have the same hash.
"""
return sha256(file1) == sha256(file2)
# based on:
# https://stackoverflow.com/questions/38876945/copying-and-merging-directories-excluding-certain-extensions # noqa: B950
def copytree_multi(src, dst, symlinks=False, ignore=None):
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
if not os.path.isdir(dst):
os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree_multi(srcname, dstname, symlinks, ignore)
else:
if os.path.exists(dstname):
if not samefile(srcname, dstname):
os.unlink(dstname)
shutil.copy2(srcname, dstname)
logger.info("File copied: %s" % dstname)
else:
# same file, so ignore the copy
logger.info("Same file, skipping: %s" % dstname)
pass
else:
shutil.copy2(srcname, dstname)
except (IOError, os.error) as why:
errors.append((srcname, dstname, str(why)))
except shutil.Error as err:
errors.extend(err.args[0])
try:
shutil.copystat(src, dst)
except WindowsError:
pass
except OSError as why:
errors.extend((src, dst, str(why)))
if errors:
raise shutil.Error(errors)
def ensure_scripts_up_to_date(engine_scripts_path, scripts_folder):
logger.info("Updating scripts...: %s" % engine_scripts_path)
logger.info(" scripts_folder: %s" % scripts_folder)
copytree_multi(engine_scripts_path, scripts_folder)
return True
class KritaLauncher(SoftwareLauncher):
"""
Handles launching application executables. Automatically starts up
the shotgun engine with the current context in the new session
of the application.
"""
# Named regex strings to insert into the executable template paths when
# matching against supplied versions and products. Similar to the glob
# strings, these allow us to alter the regex matching for any of the
# variable components of the path in one place
COMPONENT_REGEX_LOOKUP = {
"platform": r"\(x86\)|\(x64\)",
"platform_version": r"\(x86\)|\(x64\)",
}
# This dictionary defines a list of executable template strings for each
# of the supported operating systems. The templates are used for both
# globbing and regex matches by replacing the named format placeholders
# with an appropriate glob or regex string.
# Worse case we use to a env variable "$KRITA_BIN" so it can be
# configured externally
EXECUTABLE_TEMPLATES = {
"darwin": ["$KRITA_BIN", "/Applications/krita.app/Contents/MacOS/krita"],
"win32": [
"$KRITA_BIN",
"C:/Program Files/Krita {platform_version}/bin/krita.exe",
"C:/Program Files {platform}/Krita {platform_version}/bin/krita.exe",
],
"linux": ["$KRITA_BIN", "/usr/bin/krita"],
}
# These are possible locations for the scripts path collected from several
# sources, krita docs, krita installation in different OSs.
# Worse case we use to a env variable "$KRITA_RESOURCES_PATH" so it can be
# configured externally
USER_PLUGINS_ROOT_PATH = {
"darwin": [
"$KRITA_RESOURCES_PATH",
r"~/Library/Application Support/krita",
r"~/Library/Preferences/krita",
],
"win32": ["$KRITA_RESOURCES_PATH", r"%APPDATA%\krita"],
"linux": [
"$KRITA_RESOURCES_PATH",
r"~/.local/share/krita",
r"~/.var/app/org.kde.krita/data/krita",
r"~/.config/krita",
],
}
def prepare_launch(self, exec_path, args, file_to_open=None):
"""
Prepares an environment to launch in that will automatically
load Toolkit and the engine when the application starts.
:param str exec_path: Path to application executable to launch.
:param str args: Command line arguments as strings.
:param str file_to_open: (optional) Full path name of a file to open on
launch.
:returns: :class:`LaunchInformation` instance
"""
required_env = {}
resources_plugins_path = os.path.join(
self.disk_location, "resources", "extensions"
)
# Run the engine's init.py file when the application starts up
startup_path = os.path.join(self.disk_location, "startup", "init.py")
required_env["SGTK_KRITA_ENGINE_STARTUP"] = startup_path.replace("\\", "/")
# Prepare the launch environment with variables required by the
# classic bootstrap approach.
self.logger.debug(
"Preparing %s Launch via Toolkit Classic methodology ..." % APPLICATION_NAME
)
required_env["SGTK_ENGINE"] = ENGINE_NAME
required_env["SGTK_CONTEXT"] = sgtk.context.serialize(self.context)
required_env["SGTK_MODULE_PATH"] = get_sgtk_module_path()
if file_to_open:
# Add the file name to open to the launch environment
required_env["SGTK_FILE_TO_OPEN"] = file_to_open
# figure out where the shotgun bridge extension should be copied
user_plugins_root_paths = self.USER_PLUGINS_ROOT_PATH.get(
"darwin"
if sgtk.util.is_macos()
else "win32"
if sgtk.util.is_windows()
else "linux"
if sgtk.util.is_linux()
else []
)
if not user_plugins_root_paths:
raise NotImplementedError
scripts_synced = False
for user_plugins_root_path in user_plugins_root_paths:
user_plugins_root_path = resolve_path(user_plugins_root_path)
if os.path.exists(user_plugins_root_path):
user_plugins_path = os.path.join(user_plugins_root_path, "pykrita")
if not os.path.exists(user_plugins_path):
os.makedirs(user_plugins_path)
ensure_scripts_up_to_date(resources_plugins_path, user_plugins_path)
scripts_synced = True
if not scripts_synced:
raise sgtk.TankError(
"Could not find the resources path for Krita. Searched here: %s"
% user_plugins_root_paths
)
return LaunchInformation(path=exec_path, environ=required_env)
def _icon_from_engine(self):
"""
Use the default engine icon as the application does not supply
an icon in their software directory structure.
:returns: Full path to application icon as a string or None.
"""
# the engine icon
engine_icon = os.path.join(self.disk_location, "icon_256.png")
return engine_icon
def scan_software(self):
"""
Scan the filesystem for the application executables.
:return: A list of :class:`SoftwareVersion` objects.
"""
self.logger.debug("Scanning for %s executables..." % APPLICATION_NAME)
supported_sw_versions = []
for sw_version in self._find_software():
supported_sw_versions.append(sw_version)
return supported_sw_versions
def _find_software(self):
"""
Find executables in the default install locations.
"""
# all the executable templates for the current OS
executable_templates = self.EXECUTABLE_TEMPLATES.get(
"darwin"
if sgtk.util.is_macos()
else "win32"
if sgtk.util.is_windows()
else "linux"
if sgtk.util.is_linux()
else []
)
# all the discovered executables
found = False
sw_versions = []
for executable_template in executable_templates:
self.logger.debug("PreProcessing template %s.", executable_template)
executable_template = os.path.expanduser(executable_template)
executable_template = os.path.expandvars(executable_template)
self.logger.debug("Processing template %s.", executable_template)
executable_matches = self._glob_and_match(
executable_template, self.COMPONENT_REGEX_LOOKUP
)
# Extract all products from that executable.
for (executable_path, key_dict) in executable_matches:
# extract the matched keys form the key_dict (default to None
# if not included)
self.logger.debug(
"Processing executable_path: %s | dict %s",
executable_path,
key_dict,
)
# no way to extract the version from this application, so no
# version is available to display
executable_version = " "
sw_versions.append(
SoftwareVersion(
executable_version,
APPLICATION_NAME,
executable_path,
self._icon_from_engine(),
)
)
# TBR DGH060520
# break here if you found one executable, at least until we
# find a way to track different versions of Krita.
# Note that kritarunner is one of them but way too convoluted
# for what is really worth. I welcome other ideas!
found = True
break
if found:
break
return sw_versions