cura_app.py 10 KB

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