cura_app.py 11 KB

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