cura_app.py 11 KB

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