Debian Codegraph @

src/App/FreeCADInit.py

raw
1 #***************************************************************************
2 #* Copyright (c) 2001,2002 Jürgen Riegel <[email protected]> *
3 #* *
4 #* This file is part of the FreeCAD CAx development system. *
5 #* *
6 #* This program is free software you can redistribute it and/or modify *
7 #* it under the terms of the GNU Lesser General Public License (LGPL) *
8 #* as published by the Free Software Foundation either version 2 of *
9 #* the License, or (at your option) any later version. *
10 #* for detail see the LICENCE text file. *
11 #* *
12 #* FreeCAD is distributed in the hope that it will be useful, *
13 #* but WITHOUT ANY WARRANTY without even the implied warranty of *
14 #* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 #* GNU Lesser General Public License for more details. *
16 #* *
17 #* You should have received a copy of the GNU Library General Public *
18 #* License along with FreeCAD if not, write to the Free Software *
19 #* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
20 #* USA *
21 #* *
22 #***************************************************************************/
23
24 # FreeCAD init module
25 #
26 # Gathering all the information to start FreeCAD.
27 # This is the second of three init scripts.
28 # The third one runs when the gui is up,
29
30 # imports the one and only
31 import FreeCAD
32
33 def removeFromPath(module_name):
34 """removes the module from the sys.path. The entry point for imports
35 will therefore always be FreeCAD.
36 eg.: from FreeCAD.Module.submodule import function"""
37 import sys
38 paths = sys.path
39 for path in paths:
40 if module_name in path:
41 sys.path.remove(path)
42 return
43 Wrn(module_name + " not found in sys.path\n")
44
45 def setupSearchPaths(PathExtension):
46 # DLL resolution in Python 3.8 on Windows has changed
47 import sys
48 if sys.platform == 'win32' and hasattr(os, "add_dll_directory"):
49 if "FREECAD_LIBPACK_BIN" in os.environ:
50 os.add_dll_directory(os.environ["FREECAD_LIBPACK_BIN"])
51 if "WINDIR" in os.environ:
52 os.add_dll_directory(os.environ["WINDIR"] + os.sep + "system32")
53 for path in PathExtension:
54 os.add_dll_directory(path)
55
56 PathEnvironment = PathExtension.pop(0) + os.pathsep
57 for path in PathExtension:
58 try:
59 PathEnvironment += path + os.pathsep
60 except UnicodeDecodeError:
61 Wrn('Filter invalid module path: u{}\n'.format(repr(path)))
62
63 # new paths must be prepended to avoid to load a wrong version of a library
64 try:
65 os.environ["PATH"] = PathEnvironment + os.environ["PATH"]
66 except UnicodeEncodeError:
67 Log('UnicodeEncodeError was raised when concatenating unicode string with PATH. Try to replace non-ascii chars...\n')
68 os.environ["PATH"] = PathEnvironment.encode(errors='replace') + os.environ["PATH"]
69 Log('done\n')
70 except KeyError:
71 os.environ["PATH"] = PathEnvironment
72
73 FreeCAD._importFromFreeCAD = removeFromPath
74
75
76 def InitApplications():
77 # Checking on FreeCAD module path ++++++++++++++++++++++++++++++++++++++++++
78 ModDir = FreeCAD.getHomePath()+'Mod'
79 ModDir = os.path.realpath(ModDir)
80 ExtDir = FreeCAD.getHomePath()+'Ext'
81 ExtDir = os.path.realpath(ExtDir)
82 BinDir = FreeCAD.getHomePath()+'bin'
83 BinDir = os.path.realpath(BinDir)
84 libpaths = []
85 LibDir = FreeCAD.getHomePath()+'lib'
86 LibDir = os.path.realpath(LibDir)
87 if os.path.exists(LibDir):
88 libpaths.append(LibDir)
89 Lib64Dir = FreeCAD.getHomePath()+'lib64'
90 Lib64Dir = os.path.realpath(Lib64Dir)
91 if os.path.exists(Lib64Dir):
92 libpaths.append(Lib64Dir)
93 LibPyDir = FreeCAD.getHomePath()+'lib-py3'
94 LibPyDir = os.path.realpath(LibPyDir)
95 if (os.path.exists(LibPyDir)):
96 libpaths.append(LibPyDir)
97 LibFcDir = FreeCAD.getLibraryDir()
98 LibFcDir = os.path.normpath(os.path.abspath(LibFcDir))
99 if (os.path.exists(LibFcDir) and not LibFcDir in libpaths):
100 libpaths.append(LibFcDir)
101 AddPath = FreeCAD.ConfigGet("AdditionalModulePaths").split(";") + \
102 FreeCAD.ConfigGet("AdditionalMacroPaths").split(";")
103 HomeMod = FreeCAD.getUserAppDataDir()+"Mod"
104 HomeMod = os.path.realpath(HomeMod)
105 MacroStd = App.getUserMacroDir(False)
106 MacroDir = App.getUserMacroDir(True)
107 MacroMod = os.path.realpath(MacroDir+"/Mod")
108 SystemWideMacroDir = FreeCAD.getHomePath()+'Macro'
109 SystemWideMacroDir = os.path.realpath(SystemWideMacroDir)
110 DisabledAddons = FreeCAD.ConfigGet("DisabledAddons").split(";")
111
112 #print FreeCAD.getHomePath()
113 if os.path.isdir(FreeCAD.getHomePath()+'src\\Tools'):
114 sys.path.append(FreeCAD.getHomePath()+'src\\Tools')
115
116 fallback_mods = {}
117 def update_mod_registry(mod_dict):
118 for mod_name, mod_path in mod_dict.items():
119 if mod_name in fallback_mods:
120 if mod_path not in fallback_mods[mod_name]:
121 fallback_mods[mod_name].append(mod_path)
122 else:
123 fallback_mods[mod_name] = [mod_path]
124
125 # Searching for module dirs +++++++++++++++++++++++++++++++++++++++++++++++++++
126 # Use dict to handle duplicated module names
127 ModDict = {}
128 if os.path.isdir(ModDir):
129 ModDirs = os.listdir(ModDir)
130 for i in ModDirs: ModDict[i.lower()] = os.path.join(ModDir,i)
131 else:
132 Wrn ("No modules found in " + ModDir + "\n")
133 update_mod_registry(ModDict)
134
135 # Search for additional modules in the home directory
136 if os.path.isdir(HomeMod):
137 HomeMods = os.listdir(HomeMod)
138 for i in HomeMods: ModDict[i.lower()] = os.path.join(HomeMod,i)
139 elif os.path.isdir(os.path.join(os.path.expanduser("~"),".FreeCAD","Mod")):
140 # Check if old location exists
141 Wrn ("User path has changed to " + FreeCAD.getUserAppDataDir() + ". Please move user modules and macros\n")
142 update_mod_registry(ModDict)
143
144 # Search for additional modules in the macro directory
145 if os.path.isdir(MacroMod):
146 MacroMods = os.listdir(MacroMod)
147 for i in MacroMods:
148 key = i.lower()
149 if key not in ModDict: ModDict[key] = os.path.join(MacroMod,i)
150 update_mod_registry(ModDict)
151
152 # Search for additional modules in command line
153 for i in AddPath:
154 if os.path.isdir(i): ModDict[i] = i
155 update_mod_registry(ModDict)
156
157 FreeCAD.__fallback_mods__ = fallback_mods
158 for name, entries in fallback_mods.items():
159 if len(entries) > 1:
160 Msg(f"{len(entries)} entries found for module '{name}': using the one in {entries[-1]}\n")
161
162 #AddModPaths = App.ParamGet("System parameter:AdditionalModulePaths")
163 #Err( AddModPaths)
164 # add also this path so that all modules search for libraries
165 # they depend on first here
166 PathExtension = []
167 PathExtension.append(BinDir)
168
169 # prepend all module paths to Python search path
170 Log('Init: Searching for modules...\n')
171
172
173 # to have all the module-paths available in FreeCADGuiInit.py:
174 FreeCAD.__ModDirs__ = list(ModDict.values())
175 FreeCAD.__MacroDirs__ = list({os.path.realpath(MacroDir), os.path.realpath(MacroStd), SystemWideMacroDir})
176
177 # this allows importing with:
178 # from FreeCAD.Module import package
179 FreeCAD.__path__ = [ModDir] + libpaths + [HomeMod]
180
181 # also add these directories to the sys.path to
182 # not change the old behaviour. once we have moved to
183 # proper python modules this can eventually be removed.
184 sys.path = [ModDir] + libpaths + [ExtDir] + sys.path
185
186 # The AddonManager may install additional Python packages in
187 # these paths:
188 import platform
189 major,minor,_ = platform.python_version_tuple()
190 vendor_path = os.path.join(
191 FreeCAD.getUserAppDataDir(), "AdditionalPythonPackages",f"py{major}{minor}"
192 )
193 if os.path.isdir(vendor_path):
194 sys.path.append(vendor_path)
195
196 additional_packages_path = os.path.join(FreeCAD.getUserAppDataDir(),"AdditionalPythonPackages")
197 if os.path.isdir(additional_packages_path):
198 sys.path.append(additional_packages_path)
199
200 def RunInitPy(Dir):
201 InstallFile = os.path.join(Dir,"Init.py")
202 if (os.path.exists(InstallFile)):
203 try:
204 with open(InstallFile, 'rt', encoding='utf-8') as f:
205 exec(compile(f.read(), InstallFile, 'exec'))
206 except Exception as inst:
207 Log('Init: Initializing ' + Dir + '... failed\n')
208 Log('-'*100+'\n')
209 Log(traceback.format_exc())
210 Log('-'*100+'\n')
211 Err('During initialization the error "' + str(inst) + '" occurred in ' + InstallFile + '\n')
212 Err('Please look into the log file for further information\n')
213 mod_name = os.path.normpath(Dir).split(os.path.sep)[-1].lower()
214 if hasattr(FreeCAD,"__failed_mods__"):
215 FreeCAD.__failed_mods__.append(mod_name)
216 else:
217 FreeCAD.__failed_mods__ = [mod_name]
218 if mod_name not in FreeCAD.__fallback_mods__:
219 Err("Could not evaluate module '" + mod_name + "' for fallbacks\n")
220 elif len(FreeCAD.__fallback_mods__[mod_name]) > 1:
221 new_path = os.path.normpath(FreeCAD.__fallback_mods__[mod_name][-2])
222 Err(f"A fallback module was found for module '{mod_name}': {new_path}\n")
223 Err(f"Rename or remove {os.path.normpath(Dir)} to use the fallback module\n")
224 else:
225 Log('Init: Initializing ' + Dir + '... done\n')
226 else:
227 Log('Init: Initializing ' + Dir + '(Init.py not found)... ignore\n')
228
229 def processMetadataFile(MetadataFile):
230 meta = FreeCAD.Metadata(MetadataFile)
231 if not meta.supportsCurrentFreeCAD():
232 Msg(f'NOTICE: {meta.Name} does not support this version of FreeCAD, so is being skipped\n')
233 return None
234 content = meta.Content
235 if "workbench" in content:
236 workbenches = content["workbench"]
237 for workbench in workbenches:
238 if not workbench.supportsCurrentFreeCAD():
239 Msg(f'NOTICE: {meta.Name} content item {workbench.Name} does not support this version of FreeCAD, so is being skipped\n')
240 return None
241 subdirectory = workbench.Name if not workbench.Subdirectory else workbench.Subdirectory
242 subdirectory = subdirectory.replace("/",os.path.sep)
243 subdirectory = os.path.join(Dir, subdirectory)
244 #classname = workbench.Classname
245 sys.path.insert(0,subdirectory)
246 PathExtension.append(subdirectory)
247 RunInitPy(subdirectory)
248
249 def tryProcessMetadataFile(MetadataFile):
250 try:
251 processMetadataFile(MetadataFile)
252 except Exception as exc:
253 Err(str(exc))
254
255 def checkIfAddonIsDisabled(Dir):
256 Name = os.path.basename(Dir)
257
258 if Name in DisabledAddons:
259 Msg(f'NOTICE: Addon "{Name}" disabled by presence of "--disable-addon {Name}" argument\n')
260 return True
261
262 stopFileName = "ALL_ADDONS_DISABLED"
263 stopFile = os.path.join(Dir, os.path.pardir, stopFileName)
264 if os.path.exists(stopFile):
265 Msg(f'NOTICE: Addon "{Dir}" disabled by presence of {stopFileName} stopfile\n')
266 return True
267
268 stopFileName = "ADDON_DISABLED"
269 stopFile = os.path.join(Dir, stopFileName)
270 if os.path.exists(stopFile):
271 Msg(f'NOTICE: Addon "{Dir}" disabled by presence of {stopFileName} stopfile\n')
272 return True
273
274 return False
275
276 for Dir in ModDict.values():
277 if Dir not in ['', 'CVS', '__init__.py']:
278 if checkIfAddonIsDisabled(Dir):
279 continue
280 sys.path.insert(0,Dir)
281 PathExtension.append(Dir)
282 MetadataFile = os.path.join(Dir, "package.xml")
283 if os.path.exists(MetadataFile):
284 tryProcessMetadataFile(MetadataFile)
285 else:
286 RunInitPy(Dir)
287
288 extension_modules = []
289
290 try:
291 import pkgutil
292 import importlib
293 import freecad
294 for _, freecad_module_name, freecad_module_ispkg in pkgutil.iter_modules(freecad.__path__, "freecad."):
295 if freecad_module_ispkg:
296 Log('Init: Initializing ' + freecad_module_name + '\n')
297 try:
298 # Check for a stopfile
299 stopFile = os.path.join(FreeCAD.getUserAppDataDir(), "Mod", freecad_module_name[8:], "ADDON_DISABLED")
300 if os.path.exists(stopFile):
301 Msg(f'NOTICE: Addon "{freecad_module_name}" disabled by presence of ADDON_DISABLED stopfile\n')
302 continue
303
304 # Make sure that package.xml (if present) does not exclude this version of FreeCAD
305 MetadataFile = os.path.join(FreeCAD.getUserAppDataDir(), "Mod", freecad_module_name[8:], "package.xml")
306 if os.path.exists(MetadataFile):
307 meta = FreeCAD.Metadata(MetadataFile)
308 if not meta.supportsCurrentFreeCAD():
309 Msg(f'NOTICE: Addon "{freecad_module_name}" does not support this version of FreeCAD, so is being skipped\n')
310 continue
311
312 freecad_module = importlib.import_module(freecad_module_name)
313 extension_modules += [freecad_module_name]
314 if any (module_name == 'init' for _, module_name, ispkg in pkgutil.iter_modules(freecad_module.__path__)):
315 importlib.import_module(freecad_module_name + '.init')
316 Log('Init: Initializing ' + freecad_module_name + '... done\n')
317 else:
318 Log('Init: No init module found in ' + freecad_module_name + ', skipping\n')
319 except Exception as inst:
320 Err('During initialization the error "' + str(inst) + '" occurred in ' + freecad_module_name + '\n')
321 Err('-'*80+'\n')
322 Err(traceback.format_exc())
323 Err('-'*80+'\n')
324 Log('Init: Initializing ' + freecad_module_name + '... failed\n')
325 Log('-'*80+'\n')
326 Log(traceback.format_exc())
327 Log('-'*80+'\n')
328 except ImportError as inst:
329 Err('During initialization the error "' + str(inst) + '" occurred\n')
330
331 Log("Using "+ModDir+" as module path!\n")
332 # In certain cases the PathExtension list can contain invalid strings. We concatenate them to a single string
333 # but check that the output is a valid string
334 setupSearchPaths(PathExtension)
335 path = os.environ["PATH"].split(os.pathsep)
336 Log("System path after init:\n")
337 for i in path:
338 Log(" " + i + "\n")
339 # add MacroDir to path (RFE #0000504)
340 sys.path.append(MacroStd)
341 sys.path.append(MacroDir)
342 # add SystemWideMacroDir to path
343 sys.path.append(SystemWideMacroDir)
344 # add special path for MacOSX (bug #0000307)
345 import platform
346 if len(platform.mac_ver()[0]) > 0:
347 sys.path.append(os.path.expanduser('~/Library/Application Support/FreeCAD/Mod'))
348
349 # some often used shortcuts (for lazy people like me ;-)
350 App = FreeCAD
351 Log = FreeCAD.Console.PrintLog
352 Msg = FreeCAD.Console.PrintMessage
353 Err = FreeCAD.Console.PrintError
354 Wrn = FreeCAD.Console.PrintWarning
355 Crt = FreeCAD.Console.PrintCritical
356 Ntf = FreeCAD.Console.PrintNotification
357 Tnf = FreeCAD.Console.PrintTranslatedNotification
358
359 #store the cmake variables
360 App.__cmake__ = cmake;
361
362 #store unit test names
363 App.__unit_test__ = []
364
365 Log ('Init: starting App::FreeCADInit.py\n')
366
367 try:
368 import sys,os,traceback,inspect
369 from datetime import datetime
370 except ImportError:
371 FreeCAD.Console.PrintError("\n\nSeems the python standard libs are not installed, bailing out!\n\n")
372 raise
373
374 class FCADLogger(object):
375 '''Convenient class for tagged logging.
376
377 Example usage:
378 >>> logger = FreeCAD.Logger('MyModule')
379 >>> logger.info('log test {}',1)
380 24.36053 <MyModule> <input>(1): test log 1
381
382 The default output format is:
383 <timestamp> <tag> <source file>(line number): message
384
385 The message is formatted using new style Python string formatting, e.g.
386 'test {}'.format(1). It is strongly recommended to not directly use
387 Python string formatting, but pass additional argument indirectly through
388 various logger print function, because the logger can skip string
389 evaluation in case the logging level is disabled. For more options,
390 please consult the docstring of __init__(), catch() and report().
391
392 To set/get logger level:
393 >>> FreeCAD.setLogLevel('MyModule','Trace')
394 >>> FreeCAD.getLogLevel('MyModule')
395 4
396
397 There are five predefined logger level, each corresponding to an integer
398 value, as shown below together with the corresponding logger print
399 method,
400 0: Error, Logger.error()
401 1: Warning, Logger.warn()
402 2: Message, Logger.msg() or info()
403 3: Log, Logger.log() or debug()
404 4: Trace, Logger.trace()
405
406 FreeCAD.setLogLevel() supports both text and integer value, which allows
407 you to define your own levels. The level set is persisted to user
408 configuration file.
409
410 By default any tag has a log level of 2 for release, and 3 for debug
411 build.
412 '''
413
414 _levels = { 'Error':0, 'error':0,
415 'Warning':1, 'warn':1,
416 'Message':2, 'msg':2, 'info':2,
417 'Log':3, 'log':3, 'debug':3,
418 'Trace':4, 'trace':4,}
419 _printer = [
420 FreeCAD.Console.PrintError,
421 FreeCAD.Console.PrintWarning,
422 FreeCAD.Console.PrintMessage,
423 FreeCAD.Console.PrintLog,
424 FreeCAD.Console.PrintLog ]
425
426 def __init__(self, tag, **kargs):
427 '''Construct a logger instance.
428
429 Supported arguments are their default values are,
430
431 * tag: a string tag for this logger. The log level of this logger can be
432 accessed using FreeCAD.getLogLevel(tag)/setLogLevel(tag,level).
433 All logger instance with the same tag shares the same level
434 setting.
435
436 * printTag (True): whether to print tag
437
438 * noUpdateUI (True): whether to update GUI when printing. This is useful
439 to show log output on lengthy operations. Be
440 careful though, this may allow unexpected user
441 interaction when the application is busy, which may
442 lead to crash
443
444 * timing (True): whether to print time stamp
445
446 * lineno (True): whether to print source file and line number
447
448 * parent (None): provide a parent logger, so that the log printing will
449 check for parent's log level in addition of its own
450
451 * title ('FreeCAD'): message box title used by report()
452 '''
453 self.tag = tag
454 self.laststamp = datetime.now()
455 for key,default in (('printTag',True),('noUpdateUI',True),
456 ('timing',True),('lineno',True),('parent',None),
457 ('title','FreeCAD')) :
458 setattr(self,key,kargs.get(key,default))
459
460 def _isEnabledFor(self,level):
461 '''Internal function to check for an integer log level.
462
463 * level: integer log level
464 '''
465
466 if self.parent and not self.parent._isEnabledFor(level):
467 return False
468 return FreeCAD.getLogLevel(self.tag) >= level
469
470 def isEnabledFor(self,level):
471 '''To check for an integer or text log level.
472
473 * level: integer or text log level
474 '''
475 if not isinstance(level,int):
476 level = self.__class__._levels[level]
477 return self._isEnabledFor(level)
478
479 def error(self,msg,*args,**kargs):
480 '''"Error" level log printer
481
482 * msg: message string. May contain new style Python string formatter.
483
484 This function accepts additional positional and keyword arguments,
485 which are forward to string.format() to generate the logging
486 message. It is strongly recommended to not directly use Python
487 string formatting, but pass additional arguments here, because the
488 printer can skip string evaluation in case the logging level is
489 disabled.
490 '''
491 if self._isEnabledFor(0):
492 frame = kargs.pop('frame',0)+1
493 self._log(0,msg,frame,args,kargs)
494
495 def warn(self,msg,*args,**kargs):
496 '''"Warning" level log printer
497
498 * msg: message string. May contain new style Python string formatter.
499
500 This function accepts additional positional and keyword arguments,
501 which are forward to string.format() to generate the logging
502 message. It is strongly recommended to not directly use Python
503 string formatting, but pass additional arguments here, because the
504 printer can skip string evaluation in case the logging level is
505 disabled.
506 '''
507 if self._isEnabledFor(1):
508 frame = kargs.pop('frame',0)+1
509 self._log(1,msg,frame,args,kargs)
510
511 def msg(self,msg,*args,**kargs):
512 '''"Message" level log printer
513
514 * msg: message string. May contain new style Python string formatter.
515
516 This function accepts additional positional and keyword arguments,
517 which are forward to string.format() to generate the logging
518 message. It is strongly recommended to not directly use Python
519 string formatting, but pass additional arguments here, because the
520 printer can skip string evaluation in case the logging level is
521 disabled.
522 '''
523 if self._isEnabledFor(2):
524 frame = kargs.pop('frame',0)+1
525 self._log(2,msg,frame,args,kargs)
526
527 info = msg
528
529 def log(self,msg,*args,**kargs):
530 '''"Log" level log printer
531
532 * msg: message string. May contain new style Python string formatter.
533
534 This function accepts additional positional and keyword arguments,
535 which are forward to string.format() to generate the logging
536 message. It is strongly recommended to not directly use Python
537 string formatting, but pass additional arguments here, because the
538 printer can skip string evaluation in case the logging level is
539 disabled.
540 '''
541 if self._isEnabledFor(3):
542 frame = kargs.pop('frame',0)+1
543 self._log(3,msg,frame,args,kargs)
544
545 debug = log
546
547 def trace(self,msg,*args,**kargs):
548 '''"Trace" level log printer
549
550 * msg: message string. May contain new style Python string formatter.
551
552 This function accepts additional positional and keyword arguments,
553 which are forward to string.format() to generate the logging
554 message. It is strongly recommended to not directly use Python
555 string formatting, but pass additional arguments here, because the
556 printer can skip string evaluation in case the logging level is
557 disabled.
558 '''
559 if self._isEnabledFor(4):
560 frame = kargs.pop('frame',0)+1
561 self._log(4,msg,frame,args,kargs)
562
563 def _log(self,level,msg,frame=0,args=(),kargs=None):
564 '''Internal log printing function.
565
566 * level: integer log level
567
568 * msg: message, may contain new style string format specifier
569
570 * frame (0): the calling frame for printing source file and line
571 number. For example, in case you have your own logging
572 function, and you want to show the callers source
573 location, then set frame to one.
574
575 * args: tuple for positional arguments to be passed to
576 string.format()
577
578 * kargs: dictionary for keyword arguments to be passed to
579 string.format()
580 '''
581
582 if (args or kargs) and isinstance(msg,str):
583 if not kargs:
584 msg = msg.format(*args)
585 else:
586 msg = msg.format(*args,**kargs)
587
588 prefix = ''
589
590 if self.timing:
591 now = datetime.now()
592 prefix += '{} '.format((now-self.laststamp).total_seconds())
593 self.laststamp = now
594
595 if self.printTag:
596 prefix += '<{}> '.format(self.tag)
597
598 if self.lineno:
599 try:
600 frame = sys._getframe(frame+1)
601 prefix += '{}({}): '.format(os.path.basename(
602 frame.f_code.co_filename),frame.f_lineno)
603 except Exception:
604 frame = inspect.stack()[frame+1]
605 prefix += '{}({}): '.format(os.path.basename(frame[1]),frame[2])
606
607 self.__class__._printer[level]('{}{}\n'.format(prefix,msg))
608
609 if not self.noUpdateUI and FreeCAD.GuiUp:
610 import FreeCADGui
611 try:
612 FreeCADGui.updateGui()
613 except Exception:
614 pass
615
616 def _catch(self,level,msg,func,args=None,kargs=None):
617 '''Internal function to log exception of any callable.
618
619 * level: integer log level
620
621 * msg: message string. Unlike _log(), this argument must not contain
622 any string formatter.
623
624 * func: a callable object
625
626 * args: tuple of positional arguments to be passed to func.
627
628 * kargs: dictionary of keyword arguments to be passed to func.
629 '''
630 try:
631 if not args:
632 args = []
633 if not kargs:
634 kargs = {}
635 return func(*args,**kargs)
636 except Exception:
637 if self._isEnabledFor(level):
638 self._log(level,msg+'\n'+traceback.format_exc(),frame=2)
639
640 def catch(self,msg,func,*args,**kargs):
641 '''Catch any exception from a function and print as "Error".
642
643 * msg: message string. Unlike log printer, this argument must not
644 contain any string formatter.
645
646 * func: a callable object
647
648 * args: tuple of positional arguments to be passed to func.
649
650 * kargs: dictionary of keyword arguments to be passed to func.
651 '''
652 return self._catch(0,msg,func,args,kargs)
653
654 def catchWarn(self,msg,func,*args,**kargs):
655 '''Catch any exception from a function and print as "Warning".
656
657 * msg: message string. Unlike log printer, this argument must not
658 contain any string formatter.
659
660 * func: a callable object
661
662 * args: tuple of positional arguments to be passed to func.
663
664 * kargs: dictionary of keyword arguments to be passed to func.
665 '''
666 return self._catch(1,msg,func,args,kargs)
667
668 def catchMsg(self,msg,func,*args,**kargs):
669 '''Catch any exception from a function and print as "Message".
670
671 * msg: message string. Unlike log printer, this argument must not
672 contain any string formatter.
673
674 * func: a callable object
675
676 * args: tuple of positional arguments to be passed to func.
677
678 * kargs: dictionary of keyword arguments to be passed to func.
679 '''
680 return self._catch(2,msg,func,args,kargs)
681
682 catchInfo = catchMsg
683
684 def catchLog(self,msg,func,*args,**kargs):
685 '''Catch any exception from a function and print as "Log".
686
687 * msg: message string. Unlike log printer, this argument must not
688 contain any string formatter.
689
690 * func: a callable object
691
692 * args: tuple of positional arguments to be passed to func.
693
694 * kargs: dictionary of keyword arguments to be passed to func.
695 '''
696 return self._catch(3,msg,func,args,kargs)
697
698 catchDebug = catchLog
699
700 def catchTrace(self,msg,func,*args,**kargs):
701 '''Catch any exception from a function and print as "Trace".
702
703 * msg: message string. Unlike log printer, this argument must not
704 contain any string formatter.
705
706 * func: a callable object
707
708 * args: tuple of positional arguments to be passed to func.
709
710 * kargs: dictionary of keyword arguments to be passed to func.
711 '''
712 return self._catch(4,msg,func,args,kargs)
713
714 def report(self,msg,func,*args,**kargs):
715 '''Catch any exception report it with a message box.
716
717 * msg: message string. Unlike log printer, this argument must not
718 contain any string formatter.
719
720 * func: a callable object
721
722 * args: tuple of positional arguments to be passed to func.
723
724 * kargs: dictionary of keyword arguments to be passed to func.
725 '''
726 try:
727 return func(*args,**kargs)
728 except Exception as e:
729 self.error(msg+'\n'+traceback.format_exc(),frame=1)
730 if FreeCAD.GuiUp:
731 import FreeCADGui,PySide
732 PySide.QtGui.QMessageBox.critical(
733 FreeCADGui.getMainWindow(),self.title,str(e))
734
735 FreeCAD.Logger = FCADLogger
736
737 # init every application by importing Init.py
738 try:
739 InitApplications()
740 except Exception as e:
741 Err('Error in InitApplications ' + str(e) + '\n')
742 Err('-'*80+'\n')
743 Err(traceback.format_exc())
744 Err('-'*80+'\n')
745
746 FreeCAD.addImportType("FreeCAD document (*.FCStd)","FreeCAD")
747
748 # set to no gui, is overwritten by InitGui
749 App.GuiUp = 0
750
751 # fmt: off
752 # fill up unit definitions
753
754 App.Units.NanoMetre = App.Units.Quantity('nm')
755 App.Units.MicroMetre = App.Units.Quantity('um')
756 App.Units.MilliMetre = App.Units.Quantity('mm')
757 App.Units.CentiMetre = App.Units.Quantity('cm')
758 App.Units.DeciMetre = App.Units.Quantity('dm')
759 App.Units.Metre = App.Units.Quantity('m')
760 App.Units.KiloMetre = App.Units.Quantity('km')
761
762 App.Units.MilliLiter = App.Units.Quantity('ml')
763 App.Units.Liter = App.Units.Quantity('l')
764
765 App.Units.Hertz = App.Units.Quantity('Hz')
766 App.Units.KiloHertz = App.Units.Quantity('kHz')
767 App.Units.MegaHertz = App.Units.Quantity('MHz')
768 App.Units.GigaHertz = App.Units.Quantity('GHz')
769 App.Units.TeraHertz = App.Units.Quantity('THz')
770
771 App.Units.MicroGram = App.Units.Quantity('ug')
772 App.Units.MilliGram = App.Units.Quantity('mg')
773 App.Units.Gram = App.Units.Quantity('g')
774 App.Units.KiloGram = App.Units.Quantity('kg')
775 App.Units.Ton = App.Units.Quantity('t')
776
777 App.Units.Second = App.Units.Quantity('s')
778 App.Units.Minute = App.Units.Quantity('min')
779 App.Units.Hour = App.Units.Quantity('h')
780
781 App.Units.Ampere = App.Units.Quantity('A')
782 App.Units.MilliAmpere = App.Units.Quantity('mA')
783 App.Units.KiloAmpere = App.Units.Quantity('kA')
784 App.Units.MegaAmpere = App.Units.Quantity('MA')
785
786 App.Units.Kelvin = App.Units.Quantity('K')
787 App.Units.MilliKelvin = App.Units.Quantity('mK')
788 App.Units.MicroKelvin = App.Units.Quantity('uK')
789
790 App.Units.MilliMole = App.Units.Quantity('mmol')
791 App.Units.Mole = App.Units.Quantity('mol')
792
793 App.Units.Candela = App.Units.Quantity('cd')
794
795 App.Units.Inch = App.Units.Quantity('in')
796 App.Units.Foot = App.Units.Quantity('ft')
797 App.Units.Thou = App.Units.Quantity('thou')
798 App.Units.Yard = App.Units.Quantity('yd')
799 App.Units.Mile = App.Units.Quantity('mi')
800
801 App.Units.SquareFoot = App.Units.Quantity('sqft')
802 App.Units.CubicFoot = App.Units.Quantity('cft')
803
804 App.Units.Pound = App.Units.Quantity('lb')
805 App.Units.Ounce = App.Units.Quantity('oz')
806 App.Units.Stone = App.Units.Quantity('st')
807 App.Units.Hundredweights= App.Units.Quantity('cwt')
808
809 App.Units.Newton = App.Units.Quantity('N')
810 App.Units.MilliNewton = App.Units.Quantity('mN')
811 App.Units.KiloNewton = App.Units.Quantity('kN')
812 App.Units.MegaNewton = App.Units.Quantity('MN')
813
814 App.Units.NewtonPerMeter = App.Units.Quantity('N/m')
815 App.Units.MilliNewtonPerMeter = App.Units.Quantity('mN/m')
816 App.Units.KiloNewtonPerMeter = App.Units.Quantity('kN/m')
817 App.Units.MegaNewtonPerMeter = App.Units.Quantity('MN/m')
818
819 App.Units.Pascal = App.Units.Quantity('Pa')
820 App.Units.KiloPascal = App.Units.Quantity('kPa')
821 App.Units.MegaPascal = App.Units.Quantity('MPa')
822 App.Units.GigaPascal = App.Units.Quantity('GPa')
823
824 App.Units.MilliBar = App.Units.Quantity('mbar')
825 App.Units.Bar = App.Units.Quantity('bar')
826
827 App.Units.PoundForce = App.Units.Quantity('lbf')
828 App.Units.Torr = App.Units.Quantity('Torr')
829 App.Units.mTorr = App.Units.Quantity('mTorr')
830 App.Units.yTorr = App.Units.Quantity('uTorr')
831
832 App.Units.PSI = App.Units.Quantity('psi')
833 App.Units.KSI = App.Units.Quantity('ksi')
834 App.Units.MPSI = App.Units.Quantity('Mpsi')
835
836 App.Units.Watt = App.Units.Quantity('W')
837 App.Units.MilliWatt = App.Units.Quantity('mW')
838 App.Units.KiloWatt = App.Units.Quantity('kW')
839 App.Units.VoltAmpere = App.Units.Quantity('VA')
840
841 App.Units.Volt = App.Units.Quantity('V')
842 App.Units.MilliVolt = App.Units.Quantity('mV')
843 App.Units.KiloVolt = App.Units.Quantity('kV')
844
845 App.Units.MegaSiemens = App.Units.Quantity('MS')
846 App.Units.KiloSiemens = App.Units.Quantity('kS')
847 App.Units.Siemens = App.Units.Quantity('S')
848 App.Units.MilliSiemens = App.Units.Quantity('mS')
849 App.Units.MicroSiemens = App.Units.Quantity('uS')
850
851 App.Units.Ohm = App.Units.Quantity('Ohm')
852 App.Units.KiloOhm = App.Units.Quantity('kOhm')
853 App.Units.MegaOhm = App.Units.Quantity('MOhm')
854
855 App.Units.Coulomb = App.Units.Quantity('C')
856
857 App.Units.Tesla = App.Units.Quantity('T')
858 App.Units.Gauss = App.Units.Quantity('G')
859
860 App.Units.Weber = App.Units.Quantity('Wb')
861
862 # disable Oersted because people need to input e.g. a field strength of
863 # 1 ampere per meter -> 1 A/m and not get the recalculation to Oersted
864 # App.Units.Oersted = App.Units.Quantity('Oe')
865
866 App.Units.PicoFarad = App.Units.Quantity('pF')
867 App.Units.NanoFarad = App.Units.Quantity('nF')
868 App.Units.MicroFarad = App.Units.Quantity('uF')
869 App.Units.MilliFarad = App.Units.Quantity('mF')
870 App.Units.Farad = App.Units.Quantity('F')
871
872 App.Units.NanoHenry = App.Units.Quantity('nH')
873 App.Units.MicroHenry = App.Units.Quantity('uH')
874 App.Units.MilliHenry = App.Units.Quantity('mH')
875 App.Units.Henry = App.Units.Quantity('H')
876
877 App.Units.Joule = App.Units.Quantity('J')
878 App.Units.MilliJoule = App.Units.Quantity('mJ')
879 App.Units.KiloJoule = App.Units.Quantity('kJ')
880 App.Units.NewtonMeter = App.Units.Quantity('Nm')
881 App.Units.VoltAmpereSecond = App.Units.Quantity('VAs')
882 App.Units.WattSecond = App.Units.Quantity('Ws')
883 App.Units.KiloWattHour = App.Units.Quantity('kWh')
884 App.Units.ElectronVolt = App.Units.Quantity('eV')
885 App.Units.KiloElectronVolt = App.Units.Quantity('keV')
886 App.Units.MegaElectronVolt = App.Units.Quantity('MeV')
887 App.Units.Calorie = App.Units.Quantity('cal')
888 App.Units.KiloCalorie = App.Units.Quantity('kcal')
889
890 App.Units.MPH = App.Units.Quantity('mi/h')
891 App.Units.KMH = App.Units.Quantity('km/h')
892
893 App.Units.Degree = App.Units.Quantity('deg')
894 App.Units.Radian = App.Units.Quantity('rad')
895 App.Units.Gon = App.Units.Quantity('gon')
896 App.Units.AngularMinute = App.Units.Quantity().AngularMinute
897 App.Units.AngularSecond = App.Units.Quantity().AngularSecond
898
899
900 # SI base units
901 # (length, weight, time, current, temperature, amount of substance, luminous intensity, angle)
902 App.Units.AmountOfSubstance = App.Units.Unit(0,0,0,0,0,1)
903 App.Units.ElectricCurrent = App.Units.Unit(0,0,0,1)
904 App.Units.Length = App.Units.Unit(1)
905 App.Units.LuminousIntensity = App.Units.Unit(0,0,0,0,0,0,1)
906 App.Units.Mass = App.Units.Unit(0,1)
907 App.Units.Temperature = App.Units.Unit(0,0,0,0,1)
908 App.Units.TimeSpan = App.Units.Unit(0,0,1)
909
910 # all other combined units
911 App.Units.Acceleration = App.Units.Unit(1,0,-2)
912 App.Units.Angle = App.Units.Unit(0,0,0,0,0,0,0,1)
913 App.Units.AngleOfFriction = App.Units.Unit(0,0,0,0,0,0,0,1)
914 App.Units.Area = App.Units.Unit(2)
915 App.Units.CompressiveStrength = App.Units.Unit(-1,1,-2)
916 App.Units.CurrentDensity = App.Units.Unit(-2,0,0,1)
917 App.Units.Density = App.Units.Unit(-3,1)
918 App.Units.DissipationRate = App.Units.Unit(2,0,-3)
919 App.Units.DynamicViscosity = App.Units.Unit(-1,1,-1)
920 App.Units.Frequency = App.Units.Unit(0,0,-1)
921 App.Units.MagneticFluxDensity = App.Units.Unit(0,1,-2,-1)
922 App.Units.Magnetization = App.Units.Unit(-1,0,0,1)
923 App.Units.ElectricalCapacitance = App.Units.Unit(-2,-1,4,2)
924 App.Units.ElectricalConductance = App.Units.Unit(-2,-1,3,2)
925 App.Units.ElectricalConductivity = App.Units.Unit(-3,-1,3,2)
926 App.Units.ElectricalInductance = App.Units.Unit(2,1,-2,-2)
927 App.Units.ElectricalResistance = App.Units.Unit(2,1,-3,-2)
928 App.Units.ElectricCharge = App.Units.Unit(0,0,1,1)
929 App.Units.ElectricPotential = App.Units.Unit(2,1,-3,-1)
930 App.Units.Force = App.Units.Unit(1,1,-2)
931 App.Units.HeatFlux = App.Units.Unit(0,1,-3,0,0)
932 App.Units.InverseArea = App.Units.Unit(-2)
933 App.Units.InverseLength = App.Units.Unit(-1)
934 App.Units.InverseVolume = App.Units.Unit(-3)
935 App.Units.KinematicViscosity = App.Units.Unit(2,0,-1)
936 App.Units.Pressure = App.Units.Unit(-1,1,-2)
937 App.Units.Power = App.Units.Unit(2,1,-3)
938 App.Units.ShearModulus = App.Units.Unit(-1,1,-2)
939 App.Units.SpecificEnergy = App.Units.Unit(2,0,-2)
940 App.Units.SpecificHeat = App.Units.Unit(2,0,-2,0,-1)
941 App.Units.Stiffness = App.Units.Unit(0,1,-2)
942 App.Units.Stress = App.Units.Unit(-1,1,-2)
943 App.Units.ThermalConductivity = App.Units.Unit(1,1,-3,0,-1)
944 App.Units.ThermalExpansionCoefficient = App.Units.Unit(0,0,0,0,-1)
945 App.Units.ThermalTransferCoefficient = App.Units.Unit(0,1,-3,0,-1)
946 App.Units.UltimateTensileStrength = App.Units.Unit(-1,1,-2)
947 App.Units.Velocity = App.Units.Unit(1,0,-1)
948 App.Units.VacuumPermittivity = App.Units.Unit(-3,-1,4,2)
949 App.Units.Volume = App.Units.Unit(3)
950 App.Units.VolumeFlowRate = App.Units.Unit(3,0,-1)
951 App.Units.VolumetricThermalExpansionCoefficient = App.Units.Unit(0,0,0,0,-1)
952 App.Units.Work = App.Units.Unit(2,1,-2)
953 App.Units.YieldStrength = App.Units.Unit(-1,1,-2)
954 App.Units.YoungsModulus = App.Units.Unit(-1,1,-2)
955 # fmt: on
956
957 # Add an enum for the different unit schemes
958 from enum import IntEnum
959
960 # The values must match with that of the
961 # C++ enum class UnitSystem
962 class Scheme(IntEnum):
963 Internal = 0
964 MKS = 1
965 Imperial = 2
966 ImperialDecimal = 3
967 Centimeter = 4
968 ImperialBuilding = 5
969 MmMin = 6
970 ImperialCivil = 7
971 FEM = 8
972 MeterDecimal = 9
973
974 App.Units.Scheme = Scheme
975
976 class NumberFormat(IntEnum):
977 Default = 0
978 Fixed = 1
979 Scientific = 2
980
981 App.Units.NumberFormat = NumberFormat
982
983 class ScaleType(IntEnum):
984 Other = -1
985 NoScaling = 0
986 NonUniformRight = 1
987 NonUniformLeft = 2
988 Uniform = 3
989
990 App.ScaleType = ScaleType
991
992 class PropertyType(IntEnum):
993 Prop_None = 0
994 Prop_ReadOnly = 1
995 Prop_Transient = 2
996 Prop_Hidden = 4
997 Prop_Output = 8
998 Prop_NoRecompute = 16
999 Prop_NoPersist = 32
1000
1001 App.PropertyType = PropertyType
1002
1003 class ReturnType(IntEnum):
1004 PyObject = 0
1005 DocObject = 1
1006 DocAndPyObject = 2
1007 Placement = 3
1008 Matrix = 4
1009 LinkAndPlacement = 5
1010 LinkAndMatrix = 6
1011
1012 App.ReturnType = ReturnType
1013
1014 def TrySetupTabCompletion():
1015 """Tries to setup readline-based tab-completion
1016
1017 Call this function only if you are in a tty-based REPL environment.
1018 """
1019 try:
1020 import readline
1021 import rlcompleter
1022 readline.parse_and_bind("tab: complete")
1023 except ImportError as exc:
1024 # Note: As there is no readline on Windows, we just ignore import errors here
1025 pass
1026
1027 # Note: just checking whether stdin is a TTY is not enough, as the GUI is set up only aftert this
1028 # script has run. And checking only the RunMode is not enough, as we are maybe not interactive.
1029 if App.ConfigGet('RunMode') == 'Cmd' and hasattr(sys.stdin, 'isatty') and sys.stdin.isatty():
1030 TrySetupTabCompletion()
1031
1032 # clean up namespace
1033 del InitApplications, TrySetupTabCompletion
1034
1035 Log ('Init: App::FreeCADInit.py done\n')