conanfile.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. import os
  2. from io import StringIO
  3. from pathlib import Path
  4. from jinja2 import Template
  5. from conan import ConanFile
  6. from conan.tools.files import copy, rmdir, save, mkdir, rm, update_conandata
  7. from conan.tools.microsoft import unix_path
  8. from conan.tools.env import VirtualRunEnv, Environment, VirtualBuildEnv
  9. from conan.tools.scm import Version
  10. from conan.errors import ConanInvalidConfiguration, ConanException
  11. required_conan_version = ">=2.7.0"
  12. class CuraConan(ConanFile):
  13. name = "cura"
  14. license = "LGPL-3.0"
  15. author = "UltiMaker"
  16. url = "https://github.com/Ultimaker/cura"
  17. description = "3D printer / slicing GUI built on top of the Uranium framework"
  18. topics = ("conan", "python", "pyqt6", "qt", "qml", "3d-printing", "slicer")
  19. build_policy = "missing"
  20. exports = "LICENSE*", "*.jinja"
  21. settings = "os", "compiler", "build_type", "arch"
  22. generators = "VirtualPythonEnv"#, "VirtualRunEnv"
  23. # FIXME: Remove specific branch once merged to main
  24. python_requires = "translationextractor/[>=2.2.0]@ultimaker/cura_11622"
  25. options = {
  26. "enterprise": [True, False],
  27. "staging": [True, False],
  28. "cloud_api_version": ["ANY"],
  29. "display_name": ["ANY"], # TODO: should this be an option??
  30. "cura_debug_mode": [True, False], # FIXME: Use profiles
  31. "internal": [True, False],
  32. "enable_i18n": [True, False],
  33. }
  34. default_options = {
  35. "enterprise": False,
  36. "staging": False,
  37. "cloud_api_version": "1",
  38. "display_name": "UltiMaker Cura",
  39. "cura_debug_mode": False, # Not yet implemented
  40. "internal": False,
  41. "enable_i18n": False,
  42. }
  43. def set_version(self):
  44. if not self.version:
  45. self.version = self.conan_data["version"]
  46. @property
  47. def _i18n_options(self):
  48. return self.conf.get("user.i18n:options", default = {"extract": True, "build": True}, check_type = dict)
  49. @property
  50. def _app_name(self):
  51. if self.options.enterprise:
  52. return str(self.options.display_name) + " Enterprise"
  53. return str(self.options.display_name)
  54. @property
  55. def _urls(self):
  56. if self.options.staging:
  57. return "staging"
  58. return "default"
  59. @property
  60. def _root_dir(self):
  61. return Path(self.deploy_folder if hasattr(self, "deploy_folder") else self.source_folder)
  62. @property
  63. def _base_dir(self):
  64. return self._root_dir.joinpath("venv")
  65. @property
  66. def _share_dir(self):
  67. return self._base_dir.joinpath("share")
  68. @property
  69. def _script_dir(self):
  70. if self.settings.os == "Windows":
  71. return self._base_dir.joinpath("Scripts")
  72. return self._base_dir.joinpath("bin")
  73. @property
  74. def _site_packages(self):
  75. if self.settings.os == "Windows":
  76. return self._base_dir.joinpath("Lib", "site-packages")
  77. py_version = Version(self.dependencies["cpython"].ref.version)
  78. return self._base_dir.joinpath("lib", f"python{py_version.major}.{py_version.minor}", "site-packages")
  79. @property
  80. def _py_interp(self):
  81. py_interp = self._script_dir.joinpath(Path(self.deps_user_info["cpython"].python).name)
  82. if self.settings.os == "Windows":
  83. py_interp = Path(*[f'"{p}"' if " " in p else p for p in py_interp.parts])
  84. return py_interp
  85. @property
  86. def _pyinstaller_spec_arch(self):
  87. if self.settings.os == "Macos":
  88. if self.settings.arch == "armv8":
  89. return "'arm64'"
  90. return "'x86_64'"
  91. return "None"
  92. def _conan_installs(self):
  93. self.output.info("Collecting conan installs")
  94. conan_installs = {}
  95. # list of conan installs
  96. for dependency in self.dependencies.host.values():
  97. conan_installs[dependency.ref.name] = {
  98. "version": str(dependency.ref.version),
  99. "revision": dependency.ref.revision
  100. }
  101. return conan_installs
  102. def _python_installs(self):
  103. self.output.info("Collecting python installs")
  104. python_installs = {}
  105. outer = '"' if self.settings.os == "Windows" else "'"
  106. inner = "'" if self.settings.os == "Windows" else '"'
  107. buffer = StringIO()
  108. self.run(f"""python -c {outer}import importlib.metadata; print({inner};{inner}.join([(package.metadata[{inner}Name{inner}]+{inner},{inner}+ package.metadata[{inner}Version{inner}]) for package in importlib.metadata.distributions()])){outer}""",
  109. env = "virtual_python_env",
  110. stdout = buffer)
  111. packages = str(buffer.getvalue()).strip('\r\n').split(";")
  112. for package in packages:
  113. name, version = package.split(",")
  114. python_installs[name] = {"version": version}
  115. return python_installs
  116. def _generate_cura_version(self, location):
  117. with open(os.path.join(self.recipe_folder, "CuraVersion.py.jinja"), "r") as f:
  118. cura_version_py = Template(f.read())
  119. # If you want a specific Cura version to show up on the splash screen add the user configuration `user.cura:version=VERSION`
  120. # the global.conf, profile, package_info (of dependency) or via the cmd line `-c user.cura:version=VERSION`
  121. cura_version = Version(self.conf.get("user.cura:version", default = self.version, check_type = str))
  122. pre_tag = f"-{cura_version.pre}" if cura_version.pre else ""
  123. build_tag = f"+{cura_version.build}" if cura_version.build else ""
  124. internal_tag = f"+internal" if self.options.internal else ""
  125. cura_version = f"{cura_version.major}.{cura_version.minor}.{cura_version.patch}{pre_tag}{build_tag}{internal_tag}"
  126. self.output.info(f"Write CuraVersion.py to {self.recipe_folder}")
  127. with open(os.path.join(location, "CuraVersion.py"), "w") as f:
  128. f.write(cura_version_py.render(
  129. cura_app_name = self.name,
  130. cura_app_display_name = self._app_name,
  131. cura_version = cura_version,
  132. cura_version_full = self.version,
  133. cura_build_type = "Enterprise" if self.options.enterprise else "",
  134. cura_debug_mode = self.options.cura_debug_mode,
  135. cura_cloud_api_root = self.conan_data["urls"][self._urls]["cloud_api_root"],
  136. cura_cloud_api_version = self.options.cloud_api_version,
  137. cura_cloud_account_api_root = self.conan_data["urls"][self._urls]["cloud_account_api_root"],
  138. cura_marketplace_root = self.conan_data["urls"][self._urls]["marketplace_root"],
  139. cura_digital_factory_url = self.conan_data["urls"][self._urls]["digital_factory_url"],
  140. cura_latest_url=self.conan_data["urls"][self._urls]["cura_latest_url"],
  141. conan_installs=self._conan_installs(),
  142. python_installs=self._python_installs(),
  143. ))
  144. def _generate_pyinstaller_spec(self, location, entrypoint_location, icon_path, entitlements_file, cura_source_folder):
  145. pyinstaller_metadata = self.conan_data["pyinstaller"]
  146. datas = []
  147. for data in pyinstaller_metadata["datas"].values():
  148. if (not self.options.internal and data.get("internal", False)) or (not self.options.enterprise and data.get("enterprise_only", False)):
  149. continue
  150. if "oses" in data and self.settings.os not in data["oses"]:
  151. continue
  152. if "package" in data: # get the paths from conan package
  153. if data["package"] == self.name:
  154. src_path = str(Path(cura_source_folder, data["src"]))
  155. else:
  156. if data["package"] not in self.dependencies:
  157. raise ConanException(f"Required package {data["package"]} does not exist as a dependency")
  158. package_folder = self.dependencies[data["package"]].package_folder
  159. if package_folder is None:
  160. raise ConanException(f"Unable to find package_folder for {data["package"]}, check that it has not been skipped")
  161. src_path = os.path.join(self.dependencies[data["package"]].package_folder, data["src"])
  162. elif "root" in data: # get the paths relative from the install folder
  163. src_path = os.path.join(self.install_folder, data["root"], data["src"])
  164. else:
  165. raise ConanException("Misformatted conan data for pyinstaller datas, expected either package or root option")
  166. if not Path(src_path).exists():
  167. raise ConanException(f"Missing folder {src_path} for pyinstaller data {data}")
  168. datas.append((str(src_path), data["dst"]))
  169. binaries = []
  170. for binary in pyinstaller_metadata["binaries"].values():
  171. if "package" in binary: # get the paths from conan package
  172. src_path = os.path.join(self.dependencies[binary["package"]].package_folder, binary["src"])
  173. elif "root" in binary: # get the paths relative from the sourcefolder
  174. src_path = str(Path(self.source_folder, binary["root"], binary["src"]))
  175. if self.settings.os == "Windows":
  176. src_path = src_path.replace("\\", "\\\\")
  177. else:
  178. raise ConanException("Misformatted conan data for pyinstaller binaries, expected either package or root option")
  179. if not Path(src_path).exists():
  180. raise ConanException(f"Missing folder {src_path} for pyinstaller binary {binary}")
  181. for bin in Path(src_path).glob(binary["binary"] + "*[.exe|.dll|.so|.dylib|.so.]*"):
  182. binaries.append((str(bin), binary["dst"]))
  183. for bin in Path(src_path).glob(binary["binary"]):
  184. binaries.append((str(bin), binary["dst"]))
  185. # Make sure all Conan dependencies which are shared are added to the binary list for pyinstaller
  186. for _, dependency in self.dependencies.host.items():
  187. for bin_paths in dependency.cpp_info.bindirs:
  188. binaries.extend([(f"{p}", ".") for p in Path(bin_paths).glob("**/*.dll")])
  189. for lib_paths in dependency.cpp_info.libdirs:
  190. binaries.extend([(f"{p}", ".") for p in Path(lib_paths).glob("**/*.so*")])
  191. binaries.extend([(f"{p}", ".") for p in Path(lib_paths).glob("**/*.dylib*")])
  192. # Copy dynamic libs from lib path
  193. binaries.extend([(f"{p}", ".") for p in Path(self._base_dir.joinpath("lib")).glob("**/*.dylib*")])
  194. binaries.extend([(f"{p}", ".") for p in Path(self._base_dir.joinpath("lib")).glob("**/*.so*")])
  195. # Collect all dll's from PyQt6 and place them in the root
  196. binaries.extend([(f"{p}", ".") for p in Path(self._site_packages, "PyQt6", "Qt6").glob("**/*.dll")])
  197. with open(os.path.join(self.recipe_folder, "UltiMaker-Cura.spec.jinja"), "r") as f:
  198. pyinstaller = Template(f.read())
  199. version = self.conf.get("user.cura:version", default = self.version, check_type = str)
  200. cura_version = Version(version)
  201. with open(os.path.join(location, "UltiMaker-Cura.spec"), "w") as f:
  202. f.write(pyinstaller.render(
  203. name = str(self.options.display_name).replace(" ", "-"),
  204. display_name = self._app_name,
  205. entrypoint = entrypoint_location,
  206. datas = datas,
  207. binaries = binaries,
  208. venv_script_path = str(self._script_dir),
  209. hiddenimports = pyinstaller_metadata["hiddenimports"],
  210. collect_all = pyinstaller_metadata["collect_all"],
  211. icon = icon_path,
  212. entitlements_file = entitlements_file,
  213. osx_bundle_identifier = "'nl.ultimaker.cura'" if self.settings.os == "Macos" else "None",
  214. upx = str(self.settings.os == "Windows"),
  215. strip = False, # This should be possible on Linux and MacOS but, it can also cause issues on some distributions. Safest is to disable it for now
  216. target_arch = self._pyinstaller_spec_arch,
  217. macos = self.settings.os == "Macos",
  218. version = f"'{version}'",
  219. short_version = f"'{cura_version.major}.{cura_version.minor}.{cura_version.patch}'",
  220. ))
  221. def export(self):
  222. update_conandata(self, {"version": self.version})
  223. def export_sources(self):
  224. copy(self, "*", os.path.join(self.recipe_folder, "plugins"), os.path.join(self.export_sources_folder, "plugins"))
  225. copy(self, "*", os.path.join(self.recipe_folder, "resources"), os.path.join(self.export_sources_folder, "resources"), excludes = "*.mo")
  226. copy(self, "*", os.path.join(self.recipe_folder, "tests"), os.path.join(self.export_sources_folder, "tests"))
  227. copy(self, "*", os.path.join(self.recipe_folder, "cura"), os.path.join(self.export_sources_folder, "cura"), excludes="CuraVersion.py")
  228. copy(self, "*", os.path.join(self.recipe_folder, "packaging"), os.path.join(self.export_sources_folder, "packaging"))
  229. copy(self, "*", os.path.join(self.recipe_folder, ".run_templates"), os.path.join(self.export_sources_folder, ".run_templates"))
  230. copy(self, "cura_app.py", self.recipe_folder, self.export_sources_folder)
  231. def config_options(self):
  232. if self.settings.os == "Windows" and not self.conf.get("tools.microsoft.bash:path", check_type=str):
  233. del self.options.enable_i18n
  234. def validate(self):
  235. version = self.conf.get("user.cura:version", default = self.version, check_type = str)
  236. if version and Version(version) <= Version("4"):
  237. raise ConanInvalidConfiguration("Only versions 5+ are support")
  238. def requirements(self):
  239. for req in self.conan_data["requirements"]:
  240. if self.options.internal and "fdm_materials" in req:
  241. continue
  242. self.requires(req)
  243. if self.options.internal:
  244. for req in self.conan_data["requirements_internal"]:
  245. self.requires(req)
  246. if self.options.enterprise:
  247. for req in self.conan_data["requirements_enterprise"]:
  248. self.requires(req)
  249. self.requires("cpython/3.12.2")
  250. def build_requirements(self):
  251. if self.options.get_safe("enable_i18n", False):
  252. self.test_requires("gettext/0.21")
  253. def layout(self):
  254. self.folders.source = "."
  255. self.folders.build = "build"
  256. self.folders.generators = os.path.join(self.folders.build, "generators")
  257. self.cpp.package.libdirs = [os.path.join("site-packages", "cura")]
  258. self.cpp.package.bindirs = ["bin"]
  259. self.cpp.package.resdirs = ["resources", "plugins", "packaging"]
  260. def generate(self):
  261. copy(self, "cura_app.py", self.source_folder, str(self._script_dir))
  262. self._generate_cura_version(str(Path(self.source_folder, "cura")))
  263. # Copy CuraEngine.exe to bindirs of Virtual Python Environment
  264. curaengine = self.dependencies["curaengine"].cpp_info
  265. copy(self, "CuraEngine.exe", curaengine.bindirs[0], self.source_folder, keep_path = False)
  266. copy(self, "CuraEngine", curaengine.bindirs[0], self.source_folder, keep_path = False)
  267. # Copy the external plugins that we want to bundle with Cura
  268. if self.options.enterprise:
  269. rmdir(self, str(Path(self.source_folder, "plugins", "NativeCADplugin")))
  270. native_cad_plugin = self.dependencies["native_cad_plugin"].cpp_info
  271. copy(self, "*", native_cad_plugin.resdirs[0], str(Path(self.source_folder, "plugins", "NativeCADplugin")), keep_path = True)
  272. copy(self, "bundled_*.json", native_cad_plugin.resdirs[1], str(Path(self.source_folder, "resources", "bundled_packages")), keep_path = False)
  273. # Copy resources of cura_binary_data
  274. cura_binary_data = self.dependencies["cura_binary_data"].cpp_info
  275. copy(self, "*", cura_binary_data.resdirs[0], str(self._share_dir.joinpath("cura")), keep_path = True)
  276. copy(self, "*", cura_binary_data.resdirs[1], str(self._share_dir.joinpath("uranium")), keep_path = True)
  277. if self.settings.os == "Windows":
  278. copy(self, "*", cura_binary_data.resdirs[2], str(self._share_dir.joinpath("windows")), keep_path = True)
  279. for dependency in self.dependencies.host.values():
  280. for bindir in dependency.cpp_info.bindirs:
  281. copy(self, "*.dll", bindir, str(self._site_packages), keep_path = False)
  282. for libdir in dependency.cpp_info.libdirs:
  283. copy(self, "*.pyd", libdir, str(self._site_packages), keep_path = False)
  284. copy(self, "*.pyi", libdir, str(self._site_packages), keep_path = False)
  285. copy(self, "*.dylib", libdir, str(self._base_dir.joinpath("lib")), keep_path = False)
  286. # Copy materials (flat)
  287. rmdir(self, str(Path(self.source_folder, "resources", "materials")))
  288. fdm_materials = self.dependencies["fdm_materials"].cpp_info
  289. copy(self, "*", fdm_materials.resdirs[0], self.source_folder)
  290. # Copy internal resources
  291. if self.options.internal:
  292. cura_private_data = self.dependencies["cura_private_data"].cpp_info
  293. copy(self, "*", cura_private_data.resdirs[0], str(self._share_dir.joinpath("cura")))
  294. if self.options.get_safe("enable_i18n", False) and self._i18n_options["extract"]:
  295. vb = VirtualBuildEnv(self)
  296. vb.generate()
  297. # # FIXME: once m4, autoconf, automake are Conan V2 ready use self.win_bash and add gettext as base tool_requirement
  298. cpp_info = self.dependencies["gettext"].cpp_info
  299. pot = self.python_requires["translationextractor"].module.ExtractTranslations(self, cpp_info.bindirs[0])
  300. pot.generate()
  301. def build(self):
  302. if self.options.get_safe("enable_i18n", False) and self._i18n_options["build"]:
  303. for po_file in Path(self.source_folder, "resources", "i18n").glob("**/*.po"):
  304. mo_file = Path(self.build_folder, po_file.with_suffix('.mo').relative_to(self.source_folder))
  305. mo_file = mo_file.parent.joinpath("LC_MESSAGES", mo_file.name)
  306. mkdir(self, str(unix_path(self, Path(mo_file).parent)))
  307. cpp_info = self.dependencies["gettext"].cpp_info
  308. self.run(f"{cpp_info.bindirs[0]}/msgfmt {po_file} -o {mo_file} -f", env="conanbuild", ignore_errors=True)
  309. def deploy(self):
  310. ''' Note: this deploy step is actually used to prepare for building a Cura distribution with pyinstaller, which is not
  311. the original purpose in the Conan philosophy '''
  312. copy(self, "*", os.path.join(self.package_folder, self.cpp.package.resdirs[2]), os.path.join(self.deploy_folder, "packaging"), keep_path = True)
  313. # Copy resources of Cura (keep folder structure) needed by pyinstaller to determine the module structure
  314. copy(self, "*", os.path.join(self.package_folder, self.cpp_info.bindirs[0]), str(self._base_dir), keep_path = False)
  315. copy(self, "*", os.path.join(self.package_folder, self.cpp_info.libdirs[0]), str(self._site_packages.joinpath("cura")), keep_path = True)
  316. copy(self, "*", os.path.join(self.package_folder, self.cpp_info.resdirs[0]), str(self._share_dir.joinpath("cura", "resources")), keep_path = True)
  317. copy(self, "*", os.path.join(self.package_folder, self.cpp_info.resdirs[1]), str(self._share_dir.joinpath("cura", "plugins")), keep_path = True)
  318. # Copy the cura_resources resources from the package
  319. rm(self, "conanfile.py", os.path.join(self.package_folder, self.cpp.package.resdirs[0]))
  320. cura_resources = self.dependencies["cura_resources"].cpp_info
  321. for res_dir in cura_resources.resdirs:
  322. copy(self, "*", res_dir, str(self._share_dir.joinpath("cura", "resources", Path(res_dir).name)), keep_path = True)
  323. # Copy resources of Uranium (keep folder structure)
  324. uranium = self.dependencies["uranium"].cpp_info
  325. copy(self, "*", uranium.resdirs[0], str(self._share_dir.joinpath("uranium", "resources")), keep_path = True)
  326. copy(self, "*", uranium.resdirs[1], str(self._share_dir.joinpath("uranium", "plugins")), keep_path = True)
  327. copy(self, "*", uranium.libdirs[0], str(self._site_packages.joinpath("UM")), keep_path = True)
  328. entitlements_file = "'{}'".format(Path(self.deploy_folder, "packaging", "MacOS", "cura.entitlements"))
  329. self._generate_pyinstaller_spec(location = self.deploy_folder,
  330. entrypoint_location = "'{}'".format(os.path.join(self.package_folder, self.cpp_info.bindirs[0], self.conan_data["pyinstaller"]["runinfo"]["entrypoint"])).replace("\\", "\\\\"),
  331. icon_path = "'{}'".format(os.path.join(self.package_folder, self.cpp_info.resdirs[2], self.conan_data["pyinstaller"]["icon"][str(self.settings.os)])).replace("\\", "\\\\"),
  332. entitlements_file = entitlements_file if self.settings.os == "Macos" else "None",
  333. cura_source_folder = self.package_folder)
  334. def package(self):
  335. copy(self, "cura_app.py", src = self.source_folder, dst = os.path.join(self.package_folder, self.cpp.package.bindirs[0]))
  336. copy(self, "*", src = os.path.join(self.source_folder, "cura"), dst = os.path.join(self.package_folder, self.cpp.package.libdirs[0]))
  337. copy(self, "*", src = os.path.join(self.source_folder, "resources"), dst = os.path.join(self.package_folder, self.cpp.package.resdirs[0]))
  338. copy(self, "*.mo", os.path.join(self.build_folder, "resources"), os.path.join(self.package_folder, "resources"))
  339. copy(self, "*", src = os.path.join(self.source_folder, "plugins"), dst = os.path.join(self.package_folder, self.cpp.package.resdirs[1]))
  340. copy(self, "*", src = os.path.join(self.source_folder, "packaging"), dst = os.path.join(self.package_folder, self.cpp.package.resdirs[2]))
  341. copy(self, "pip_requirements_*.txt", src = self.generators_folder, dst = os.path.join(self.package_folder, self.cpp.package.resdirs[-1]))
  342. # Remove the fdm_materials from the package
  343. rmdir(self, os.path.join(self.package_folder, self.cpp.package.resdirs[0], "materials"))
  344. # Remove the cura_resources resources from the package
  345. rm(self, "conanfile.py", os.path.join(self.package_folder, self.cpp.package.resdirs[0]))
  346. cura_resources = self.dependencies["cura_resources"].cpp_info
  347. for res_dir in cura_resources.resdirs:
  348. rmdir(self, os.path.join(self.package_folder, self.cpp.package.resdirs[0], Path(res_dir).name))
  349. def package_info(self):
  350. self.runenv_info.append_path("PYTHONPATH", os.path.join(self.package_folder, "site-packages"))
  351. self.runenv_info.append_path("PYTHONPATH", os.path.join(self.package_folder, "plugins"))
  352. def package_id(self):
  353. self.info.options.rm_safe("enable_i18n")