cura_app.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2019 Ultimaker B.V.
  3. # Cura is released under the terms of the LGPLv3 or higher.
  4. import argparse
  5. import faulthandler
  6. import os
  7. import sys
  8. from UM.Platform import Platform
  9. from cura.ApplicationMetadata import CuraAppName
  10. parser = argparse.ArgumentParser(prog = "cura",
  11. add_help = False)
  12. parser.add_argument("--debug",
  13. action="store_true",
  14. default = False,
  15. help = "Turn on the debug mode by setting this option."
  16. )
  17. known_args = vars(parser.parse_known_args()[0])
  18. if not known_args["debug"]:
  19. def get_cura_dir_path():
  20. if Platform.isWindows():
  21. appdata_path = os.getenv("APPDATA")
  22. if not appdata_path: #Defensive against the environment variable missing (should never happen).
  23. appdata_path = "."
  24. return os.path.join(appdata_path, CuraAppName)
  25. elif Platform.isLinux():
  26. return os.path.expanduser("~/.local/share/" + CuraAppName)
  27. elif Platform.isOSX():
  28. return os.path.expanduser("~/Library/Logs/" + CuraAppName)
  29. # Do not redirect stdout and stderr to files if we are running CLI.
  30. if hasattr(sys, "frozen") and "cli" not in os.path.basename(sys.argv[0]).lower():
  31. dirpath = get_cura_dir_path()
  32. os.makedirs(dirpath, exist_ok = True)
  33. sys.stdout = open(os.path.join(dirpath, "stdout.log"), "w", encoding = "utf-8")
  34. sys.stderr = open(os.path.join(dirpath, "stderr.log"), "w", encoding = "utf-8")
  35. # WORKAROUND: GITHUB-88 GITHUB-385 GITHUB-612
  36. if Platform.isLinux(): # Needed for platform.linux_distribution, which is not available on Windows and OSX
  37. # For Ubuntu: https://bugs.launchpad.net/ubuntu/+source/python-qt4/+bug/941826
  38. # The workaround is only needed on Ubuntu+NVidia drivers. Other drivers are not affected, but fine with this fix.
  39. try:
  40. import ctypes
  41. from ctypes.util import find_library
  42. libGL = find_library("GL")
  43. ctypes.CDLL(libGL, ctypes.RTLD_GLOBAL)
  44. except:
  45. # GLES-only systems (e.g. ARM Mali) do not have libGL, ignore error
  46. pass
  47. # When frozen, i.e. installer version, don't let PYTHONPATH mess up the search path for DLLs.
  48. if Platform.isWindows() and hasattr(sys, "frozen"):
  49. try:
  50. del os.environ["PYTHONPATH"]
  51. except KeyError:
  52. pass
  53. # GITHUB issue #6194: https://github.com/Ultimaker/Cura/issues/6194
  54. # With AppImage 2 on Linux, the current working directory will be somewhere in /tmp/<rand>/usr, which is owned
  55. # by root. For some reason, QDesktopServices.openUrl() requires to have a usable current working directory,
  56. # otherwise it doesn't work. This is a workaround on Linux that before we call QDesktopServices.openUrl(), we
  57. # switch to a directory where the user has the ownership.
  58. if Platform.isLinux() and hasattr(sys, "frozen"):
  59. os.chdir(os.path.expanduser("~"))
  60. # WORKAROUND: GITHUB-704 GITHUB-708
  61. # It looks like setuptools creates a .pth file in
  62. # the default /usr/lib which causes the default site-packages
  63. # to be inserted into sys.path before PYTHONPATH.
  64. # This can cause issues such as having libsip loaded from
  65. # the system instead of the one provided with Cura, which causes
  66. # incompatibility issues with libArcus
  67. if "PYTHONPATH" in os.environ.keys(): # If PYTHONPATH is used
  68. PYTHONPATH = os.environ["PYTHONPATH"].split(os.pathsep) # Get the value, split it..
  69. PYTHONPATH.reverse() # and reverse it, because we always insert at 1
  70. for PATH in PYTHONPATH: # Now beginning with the last PATH
  71. PATH_real = os.path.realpath(PATH) # Making the the path "real"
  72. if PATH_real in sys.path: # This should always work, but keep it to be sure..
  73. sys.path.remove(PATH_real)
  74. sys.path.insert(1, PATH_real) # Insert it at 1 after os.curdir, which is 0.
  75. def exceptHook(hook_type, value, traceback):
  76. from cura.CrashHandler import CrashHandler
  77. from cura.CuraApplication import CuraApplication
  78. has_started = False
  79. if CuraApplication.Created:
  80. has_started = CuraApplication.getInstance().started
  81. #
  82. # When the exception hook is triggered, the QApplication may not have been initialized yet. In this case, we don't
  83. # have an QApplication to handle the event loop, which is required by the Crash Dialog.
  84. # The flag "CuraApplication.Created" is set to True when CuraApplication finishes its constructor call.
  85. #
  86. # Before the "started" flag is set to True, the Qt event loop has not started yet. The event loop is a blocking
  87. # call to the QApplication.exec_(). In this case, we need to:
  88. # 1. Remove all scheduled events so no more unnecessary events will be processed, such as loading the main dialog,
  89. # loading the machine, etc.
  90. # 2. Start the Qt event loop with exec_() and show the Crash Dialog.
  91. #
  92. # If the application has finished its initialization and was running fine, and then something causes a crash,
  93. # we run the old routine to show the Crash Dialog.
  94. #
  95. from PyQt5.Qt import QApplication
  96. if CuraApplication.Created:
  97. _crash_handler = CrashHandler(hook_type, value, traceback, has_started)
  98. if CuraApplication.splash is not None:
  99. CuraApplication.splash.close()
  100. if not has_started:
  101. CuraApplication.getInstance().removePostedEvents(None)
  102. _crash_handler.early_crash_dialog.show()
  103. sys.exit(CuraApplication.getInstance().exec_())
  104. else:
  105. _crash_handler.show()
  106. else:
  107. application = QApplication(sys.argv)
  108. application.removePostedEvents(None)
  109. _crash_handler = CrashHandler(hook_type, value, traceback, has_started)
  110. # This means the QtApplication could be created and so the splash screen. Then Cura closes it
  111. if CuraApplication.splash is not None:
  112. CuraApplication.splash.close()
  113. _crash_handler.early_crash_dialog.show()
  114. sys.exit(application.exec_())
  115. # Set exception hook to use the crash dialog handler
  116. sys.excepthook = exceptHook
  117. # Enable dumping traceback for all threads
  118. if sys.stderr:
  119. faulthandler.enable(file = sys.stderr, all_threads = True)
  120. else:
  121. faulthandler.enable(file = sys.stdout, all_threads = True)
  122. # Workaround for a race condition on certain systems where there
  123. # is a race condition between Arcus and PyQt. Importing Arcus
  124. # first seems to prevent Sip from going into a state where it
  125. # tries to create PyQt objects on a non-main thread.
  126. import Arcus #@UnusedImport
  127. import Savitar #@UnusedImport
  128. from cura.CuraApplication import CuraApplication
  129. # WORKAROUND: CURA-6739
  130. # The CTM file loading module in Trimesh requires the OpenCTM library to be dynamically loaded. It uses
  131. # ctypes.util.find_library() to find libopenctm.dylib, but this doesn't seem to look in the ".app" application folder
  132. # on Mac OS X. Adding the search path to environment variables such as DYLD_LIBRARY_PATH and DYLD_FALLBACK_LIBRARY_PATH
  133. # makes it work. The workaround here uses DYLD_FALLBACK_LIBRARY_PATH.
  134. if Platform.isOSX() and getattr(sys, "frozen", False):
  135. old_env = os.environ.get("DYLD_FALLBACK_LIBRARY_PATH", "")
  136. # This is where libopenctm.so is in the .app folder.
  137. search_path = os.path.join(CuraApplication.getInstallPrefix(), "MacOS")
  138. path_list = old_env.split(":")
  139. if search_path not in path_list:
  140. path_list.append(search_path)
  141. os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = ":".join(path_list)
  142. import trimesh.exchange.load
  143. os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = old_env
  144. # WORKAROUND: CURA-6739
  145. # Similar CTM file loading fix for Linux, but NOTE THAT this doesn't work directly with Python 3.5.7. There's a fix
  146. # for ctypes.util.find_library() in Python 3.6 and 3.7. That fix makes sure that find_library() will check
  147. # LD_LIBRARY_PATH. With Python 3.5, that fix needs to be backported to make this workaround work.
  148. if Platform.isLinux() and getattr(sys, "frozen", False):
  149. old_env = os.environ.get("LD_LIBRARY_PATH", "")
  150. # This is where libopenctm.so is in the AppImage.
  151. search_path = os.path.join(CuraApplication.getInstallPrefix(), "bin")
  152. path_list = old_env.split(":")
  153. if search_path not in path_list:
  154. path_list.append(search_path)
  155. os.environ["LD_LIBRARY_PATH"] = ":".join(path_list)
  156. import trimesh.exchange.load
  157. os.environ["LD_LIBRARY_PATH"] = old_env
  158. app = CuraApplication()
  159. app.run()