cura_app.py 9.4 KB

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