-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtkCore.py
More file actions
380 lines (312 loc) · 12.7 KB
/
tkCore.py
File metadata and controls
380 lines (312 loc) · 12.7 KB
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
"""
------------------------- LICENCE INFORMATION -------------------------------
This file is part of Toonkit Module Lite, Python Maya library and module.
Authors : Cyril GIBAUD - Toonkit, Stephane Bonnot - Parallel Dev
Copyright (C) 2014-2017 Toonkit
http://toonkit-studio.com/
Toonkit Module Lite is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Toonkit Module Lite is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Toonkit Module Lite. If not, see <http://www.gnu.org/licenses/>
-------------------------------------------------------------------------------
ASCII Text font "Ivrit" (http://patorjk.com/software/taag)
"""
__author__ = "Cyril GIBAUD - Toonkit"
import inspect
import time
import sys
from functools import partial, wraps
from timeit import timeit
try: basestring
except: basestring=str
import traceback
from . import tkLogger
from .tkToolOptions.ToonkitCore import ToonkitCore
if sys.version_info[0] >= 3:
import queue
else:
import Queue as queue
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
____ _ _
/ ___|___ _ __ ___| |_ __ _ _ __ | |_ ___
| | / _ \| '_ \/ __| __/ _` | '_ \| __/ __|
| |__| (_) | | | \__ \ || (_| | | | | |_\__ \
\____\___/|_| |_|___/\__\__,_|_| |_|\__|___/
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
TOOL = None
PROJECT = None
OPERATORS = ["==", "!=", ">", "<"]
LINESEP = "\n"
LOG_INDENT = 2
LAST_STACK = queue.Queue()
LOG_DEPTH = 0
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
____ _
| _ \ ___ ___ ___ _ __ __ _| |_ ___ _ __ ___
| | | |/ _ \/ __/ _ \| '__/ _` | __/ _ \| '__/ __|
| |_| | __/ (_| (_) | | | (_| | || (_) | | \__ \
|____/ \___|\___\___/|_| \__,_|\__\___/|_| |___/
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
def verbosed(func):
"""logLevel/debug decorator"""
@wraps(func)
def wrapper(*args, **kwargs):
if not tkLogger.VERBOSED:
return func(*args, **kwargs)
global LOG_DEPTH
LOG_DEPTH += 1
indent = " " * ((LOG_DEPTH - 1) * LOG_INDENT)
#inspect for arguments
argspec = inspect.getargspec(func)
defaultArguments = list(reversed(list(zip(reversed(argspec.args), reversed(argspec.defaults or [])))))
all_kwargs = kwargs.copy()
for arg, value in defaultArguments:
if arg not in kwargs:
all_kwargs[arg] = value
#Format arguments
argsList = []
for arg in args:
argsList.append("\"{}\"".format(arg) if isinstance(arg, basestring) else str(arg))
for key, value in all_kwargs.items():
argsList.append(("{0}=\"{1}\"" if isinstance(value, basestring) else "{0}={1}").format(key, value))
tkLogger.debug(indent + "< {0}.{1}({2})".format(func.__module__, func.__name__, ",".join(argsList)))
#Actual function call
start = time.time()
try:
rslt = func(*args, **kwargs)
except Exception as e:
end = time.time()
duration = end - start
tkLogger.debug(indent + "> {0}.{1} took {2:.4f}s and Failed.".format(func.__module__, func.__name__, duration))
raise e
end = time.time()
duration = end - start
tkLogger.debug(indent + "> {0}.{1} took {2:.4f}s and returned '{3}'".format(func.__module__, func.__name__, duration, rslt))
LOG_DEPTH -= 1
return rslt
return wrapper
def catchexp(func):
"""traceback catcher decorator"""
@wraps(func)
def wrapper(self, *args, **kwargs):
try:
rslt = func(self, *args, **kwargs)
except Exception as e:
LAST_STACK.put(traceback.format_exc())
raise e
return rslt
return wrapper
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
____ _ _
| _ \(_) ___| |_
| | | | |/ __| __|
| |_| | | (__| |_
|____/|_|\___|\__|
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
@verbosed
def getReversedDict(inDict):
reversedDict = {}
for key, value in inDict.items():
if not value in reversedDict:
reversedDict[value] = key
return reversedDict
@verbosed
def getFromDefaults(inDict, inKey, inLastDefault, *args):
"""
Get a value from the first dictionary actually implementing the given key
:param inDict: The first dictionary to look into
:type inDict: dict
:param inKey: The key to look for
:type inKey: object
:param inLastDefault: The default value if key can't be found anywhere
:type inLastDefault: object
:param *args: a list of dictionaries to look for the key, in order
:type *args: list(dict)
:return: The value
:rtype: object
"""
if inKey in inDict:
return inDict[inKey]
for defaultDict in args:
if inKey in defaultDict:
return defaultDict[inKey]
return inLastDefault
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
____ _ _
/ ___|| |_ _ __(_)_ __ __ _
| |__ | __|| '__| | '_ \ / _` |
\___ || |_ | | | | | | | (_| |
|____||\__||_| |_|_| |_|\__, |
|___/
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
STRING_SEPARATORS = [";", ","]
def reduceStr(inStr, inMaxLength=500, inCutStr = " ... "):
if not isinstance(inStr, basestring):
inStr = str(inStr)
if len(inStr) <= inMaxLength:
return inStr
maxLen = inMaxLength - len(inCutStr)
return inStr[:int(maxLen/2)] + inCutStr + inStr[-int(maxLen/2):]
def smartSplit(inScripsPath, inSeparators=STRING_SEPARATORS):
scripts = []
if isinstance(inScripsPath, (list, tuple)):
scripts = []
for script in inScripsPath:
scripts += smartSplit(script)
elif isinstance(inScripsPath, basestring) and len(inScripsPath) > 0:
currentSeparator=None
for sep in inSeparators:
if sep in inScripsPath:
currentSeparator = sep
break
if not currentSeparator is None:
scripts = [x.strip(" ") for x in inScripsPath.split(currentSeparator)]
else:
scripts = [inScripsPath.strip(" ")]
return scripts
def smartJoin(*args, **kwargs):
"""
kwargs should contain 'inSep'
"""
inSep = kwargs.get("inSep", " ")
return inSep.join([str(o) for o in args])
def reduceStr(inStr, inMaxLength=500, inCutStr = " ... "):
if not isinstance(inStr, basestring):
inStr = str(inStr)
if len(inStr) <= inMaxLength:
return inStr
maxLen = inMaxLength - len(inCutStr)
return inStr[:int(maxLen/2)] + inCutStr + inStr[-int(maxLen/2):]
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
_____ _ _
|_ _|__ ___| |_(_)_ __ __ _
| |/ _ \/ __| __| | '_ \ / _` |
| | __/\__ \ |_| | | | | (_| |
|_|\___||___/\__|_|_| |_|\__, |
|___/
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
def timeThem(*args, **kwargs):
"""
Benchmarks any callable passed in arguments, calling it with the remaining arguments (all functions must all accept these remaining given arguments and named arguments)
Takes "inNumber" as an hidden named argument for the number of calls (bigger values, =~100 are more accurate but longer of course...)
Example:
timeThem(objExists, melObjExists, pmObjExists, apiObjExists, "sphere1", inNumber=10)
objExists, melObjExists, pmObjExists and apiObjExists are functions that takes a string and tells if an object exists
Outputs:
objExists : 0.6530 returns 'False' (bool)
melObjExists : 1.0602 ( *1.62) returns '0' (int)
pmObjExists : 1.6226 ( *2.48) returns 'False' (bool)
apiObjExists : 0.7104 ( *1.09) returns 'False' (bool)
"""
funcs = []
funcArgs = list(args[:])
#filter arguments
for arg in args:
if callable(arg):
funcs.append(arg)
funcArgs.remove(arg)
key = "inNumber"
inNumber=10
if key in kwargs:
inNumber = kwargs[key]
del kwargs[key]
durations = []
refTime = 0.0
for func in funcs:
retVal = func(*funcArgs, **kwargs)
duration = timeit(partial(func, *funcArgs, **kwargs), number=inNumber)
comparison = ""
if refTime <= 0.0:
refTime = duration
else:
comparison = " ( *{:.2f})".format(duration / refTime)
print("{: <16} : {:.4f}".format(func.__name__, duration) + comparison + " returns '{}' ({})".format(retVal, type(retVal).__name__))
durations.append(duration)
return durations
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
_____ _ _
| ____|_ ____ _(_)_ __ ___ _ __ _ __ ___ ___ _ __ | |_
| _| | '_ \ \ / / | '__/ _ \| '_ \| '_ ` _ \ / _ \ '_ \| __|
| |___| | | \ V /| | | | (_) | | | | | | | | | __/ | | | |_
|_____|_| |_|\_/ |_|_| \___/|_| |_|_| |_| |_|\___|_| |_|\__|
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
@verbosed
def getTool():
global TOOL
if not TOOL:
TOOL = ToonkitCore()
return TOOL
@verbosed
def getProject(dccName="Dcc", inName=None):
global PROJECT
global TOOL
"""Get a project object (current one if no name given)
Note : includes a late import of "tkProject" because we have circular dependencies
"""
from .tkProjects.tkProject import tkProject
if not PROJECT:
dcc = getDcc(dccName)()
PROJECT = tkProject.getClass(inName or getTool().options["project"], getTool().options["alternateProjectsPath"].split(","))(inDCC = dcc, inName=inName)
return PROJECT
@verbosed
def setProject(dccName="Dcc", inName=None):
global PROJECT
if PROJECT and PROJECT.name == inName:
tkLogger.debug("Project {} is already set !".format(inName))
return PROJECT
oldProject = PROJECT
if PROJECT and dccName == "Dcc":
dcc = PROJECT.dcc
else:
dcc = getDcc(dccName)()
PROJECT = None
try:
newProj = getProject(dccName=dcc.name, inName=inName)
except Exception as e:
tkLogger.warning(str(e))
newProj = None
if newProj and newProj.name == inName:
PROJECT = newProj
TOOL.options["project"] = newProj.name
dcc.syncDCCProject()
else:
tkLogger.error("No project matching name '{}', unable to initialize tkProject ({}). Old project returned.".format(inName, newProj))
del newProj
if oldProject == None:
tkLogger.warning("No old project found, Default used!")
oldProject = getProject("maya", "default")
dcc.syncDCCProject()
PROJECT = oldProject
return PROJECT
@verbosed
def resetProject():
global PROJECT
PROJECT = None
@verbosed
def getProjects():
return ["demo"]
@verbosed
def getDcc(dccName):
dccMod = None
if sys.version_info >= (2,7):
import importlib
try:
dccMod = importlib.import_module("{0}Geter".format(dccName))
except Exception as e:
tkLogger.warning(str(e))
dccMod = importlib.import_module("Toonkit_Core.DccGeter")
dccName = "Dcc"
else:
try:
dccMod = __import__("{0}Geter".format(dccName))
except Exception as e:
tkLogger.warning(str(e))
dccMod = __import__("DccGeter")
dccName = "Dcc"
return getattr(dccMod, dccName + "Geter")