PackageModel.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import re
  4. from typing import Any, cast, Dict, List, Optional
  5. from PyQt6.QtCore import pyqtProperty, QObject, pyqtSignal, pyqtSlot
  6. from PyQt6.QtQml import QQmlEngine
  7. from cura.CuraApplication import CuraApplication
  8. from cura.CuraPackageManager import CuraPackageManager
  9. from cura.Settings.CuraContainerRegistry import CuraContainerRegistry # To get names of materials we're compatible with.
  10. from UM.i18n import i18nCatalog # To translate placeholder names if data is not present.
  11. from UM.PluginRegistry import PluginRegistry
  12. catalog = i18nCatalog("cura")
  13. class PackageModel(QObject):
  14. """
  15. Represents a package, containing all the relevant information to be displayed about a package.
  16. """
  17. def __init__(self, package_data: Dict[str, Any], section_title: Optional[str] = None, parent: Optional[QObject] = None) -> None:
  18. """
  19. Constructs a new model for a single package.
  20. :param package_data: The data received from the Marketplace API about the package to create.
  21. :param section_title: If the packages are to be categorized per section provide the section_title
  22. :param parent: The parent QML object that controls the lifetime of this model (normally a PackageList).
  23. """
  24. super().__init__(parent)
  25. QQmlEngine.setObjectOwnership(self, QQmlEngine.ObjectOwnership.CppOwnership)
  26. self._package_manager: CuraPackageManager = cast(CuraPackageManager, CuraApplication.getInstance().getPackageManager())
  27. self._plugin_registry: PluginRegistry = CuraApplication.getInstance().getPluginRegistry()
  28. self._package_id = package_data.get("package_id", "UnknownPackageId")
  29. self._package_type = package_data.get("package_type", "")
  30. self._is_bundled = package_data.get("is_bundled", False)
  31. self._icon_url = package_data.get("icon_url", "")
  32. self._marketplace_url = package_data.get("marketplace_url", "")
  33. self._display_name = package_data.get("display_name", catalog.i18nc("@label:property", "Unknown Package"))
  34. tags = package_data.get("tags", [])
  35. self._is_checked_by_ultimaker = (self._package_type == "plugin" and "verified" in tags) or (
  36. self._package_type == "material" and "certified" in tags)
  37. self._package_version = package_data.get("package_version", "") # Display purpose, no need for 'UM.Version'.
  38. self._package_info_url = package_data.get("website", "") # Not to be confused with 'download_url'.
  39. self._download_count = package_data.get("download_count", 0)
  40. self._description = package_data.get("description", "")
  41. self._formatted_description = self._format(self._description)
  42. self._download_url = package_data.get("download_url", "")
  43. self._release_notes = package_data.get("release_notes", "") # Not used yet, propose to add to description?
  44. subdata = package_data.get("data", {})
  45. self._technical_data_sheet = self._findLink(subdata, "technical_data_sheet")
  46. self._safety_data_sheet = self._findLink(subdata, "safety_data_sheet")
  47. self._where_to_buy = self._findLink(subdata, "where_to_buy")
  48. self._compatible_printers = self._getCompatiblePrinters(subdata)
  49. self._compatible_support_materials = self._getCompatibleSupportMaterials(subdata)
  50. self._is_compatible_material_station = self._isCompatibleMaterialStation(subdata)
  51. self._is_compatible_air_manager = self._isCompatibleAirManager(subdata)
  52. author_data = package_data.get("author", {})
  53. self._author_name = author_data.get("display_name", catalog.i18nc("@label:property", "Unknown Author"))
  54. self._author_info_url = author_data.get("website", "")
  55. if not self._icon_url or self._icon_url == "":
  56. self._icon_url = author_data.get("icon_url", "")
  57. self._can_update = False
  58. self._section_title = section_title
  59. self.sdk_version = package_data.get("sdk_version_semver", "")
  60. # Note that there's a lot more info in the package_data than just these specified here.
  61. self.enablePackageTriggered.connect(self._plugin_registry.enablePlugin)
  62. self.disablePackageTriggered.connect(self._plugin_registry.disablePlugin)
  63. self._plugin_registry.pluginsEnabledOrDisabledChanged.connect(self.stateManageButtonChanged)
  64. self._package_manager.packageInstalled.connect(lambda pkg_id: self._packageInstalled(pkg_id))
  65. self._package_manager.packageUninstalled.connect(lambda pkg_id: self._packageInstalled(pkg_id))
  66. self._package_manager.packageInstallingFailed.connect(lambda pkg_id: self._packageInstalled(pkg_id))
  67. self._package_manager.packagesWithUpdateChanged.connect(self._processUpdatedPackages)
  68. self._is_busy = False
  69. self._is_missing_package_information = False
  70. @classmethod
  71. def fromIncompletePackageInformation(cls, display_name: str, package_version: str,
  72. package_type: str) -> "PackageModel":
  73. description = ""
  74. match package_type:
  75. case "material":
  76. description = catalog.i18nc("@label:label Ultimaker Marketplace is a brand name, don't translate",
  77. "The material package associated with the Cura project could not be found on the Ultimaker Marketplace. Use the partial material profile definition stored in the Cura project file at your own risk.")
  78. case "plugin":
  79. description = catalog.i18nc("@label:label Ultimaker Marketplace is a brand name, don't translate",
  80. "The plugin associated with the Cura project could not be found on the Ultimaker Marketplace. As the plugin may be required to slice the project it might not be possible to correctly slice the file.")
  81. package_data = {
  82. "display_name": display_name,
  83. "package_version": package_version,
  84. "package_type": package_type,
  85. "description": description,
  86. }
  87. package_model = cls(package_data)
  88. package_model.setIsMissingPackageInformation(True)
  89. return package_model
  90. @pyqtSlot()
  91. def _processUpdatedPackages(self):
  92. self.setCanUpdate(self._package_manager.checkIfPackageCanUpdate(self._package_id))
  93. def __del__(self):
  94. self._package_manager.packagesWithUpdateChanged.disconnect(self._processUpdatedPackages)
  95. def __eq__(self, other: object) -> bool:
  96. if isinstance(other, PackageModel):
  97. return other == self
  98. elif isinstance(other, str):
  99. return other == self._package_id
  100. else:
  101. return False
  102. def __repr__(self) -> str:
  103. return f"<{self._package_id} : {self._package_version} : {self._section_title}>"
  104. def _findLink(self, subdata: Dict[str, Any], link_type: str) -> str:
  105. """
  106. Searches the package data for a link of a certain type.
  107. The links are not in a fixed path in the package data. We need to iterate over the available links to find them.
  108. :param subdata: The "data" element in the package data, which should contain links.
  109. :param link_type: The type of link to find.
  110. :return: A URL of where the link leads, or an empty string if there is no link of that type in the package data.
  111. """
  112. links = subdata.get("links", [])
  113. for link in links:
  114. if link.get("type", "") == link_type:
  115. return link.get("url", "")
  116. else:
  117. return "" # No link with the correct type was found.
  118. def _format(self, text: str) -> str:
  119. """
  120. Formats a user-readable block of text for display.
  121. :return: A block of rich text with formatting embedded.
  122. """
  123. # Turn all in-line hyperlinks into actual links.
  124. url_regex = re.compile(r"(((http|https)://)[a-zA-Z0-9@:%.\-_+~#?&/=]{2,256}\.[a-z]{2,12}(/[a-zA-Z0-9@:%.\-_+~#?&/=]*)?)")
  125. text = re.sub(url_regex, r'<a href="\1">\1</a>', text)
  126. # Turn newlines into <br> so that they get displayed as newlines when rendering as rich text.
  127. text = text.replace("\n", "<br>")
  128. return text
  129. def _getCompatiblePrinters(self, subdata: Dict[str, Any]) -> List[str]:
  130. """
  131. Gets the list of printers that this package provides material compatibility with.
  132. Any printer is listed, even if it's only for a single nozzle on a single material in the package.
  133. :param subdata: The "data" element in the package data, which should contain this compatibility information.
  134. :return: A list of printer names that this package provides material compatibility with.
  135. """
  136. result = set()
  137. for material in subdata.get("materials", []):
  138. for compatibility in material.get("compatibility", []):
  139. printer_name = compatibility.get("machine_name")
  140. if printer_name is None:
  141. continue # Missing printer name information. Skip this one.
  142. for subcompatibility in compatibility.get("compatibilities", []):
  143. if subcompatibility.get("hardware_compatible", False):
  144. result.add(printer_name)
  145. break
  146. return list(sorted(result))
  147. def _getCompatibleSupportMaterials(self, subdata: Dict[str, Any]) -> List[str]:
  148. """
  149. Gets the list of support materials that the materials in this package are compatible with.
  150. Since the materials are individually encoded as keys in the API response, only PVA and Breakaway are currently
  151. supported.
  152. :param subdata: The "data" element in the package data, which should contain this compatibility information.
  153. :return: A list of support materials that the materials in this package are compatible with.
  154. """
  155. result = set()
  156. container_registry = CuraContainerRegistry.getInstance()
  157. try:
  158. pva_name = container_registry.findContainersMetadata(id = "ultimaker_pva")[0].get("name", "Ultimaker PVA")
  159. except IndexError:
  160. pva_name = "Ultimaker PVA"
  161. try:
  162. breakaway_name = container_registry.findContainersMetadata(id = "ultimaker_bam")[0].get("name", "Ultimaker Breakaway")
  163. except IndexError:
  164. breakaway_name = "Ultimaker Breakaway"
  165. for material in subdata.get("materials", []):
  166. if material.get("pva_compatible", False):
  167. result.add(pva_name)
  168. if material.get("breakaway_compatible", False):
  169. result.add(breakaway_name)
  170. return list(sorted(result))
  171. def _isCompatibleMaterialStation(self, subdata: Dict[str, Any]) -> bool:
  172. """
  173. Finds out if this package provides any material that is compatible with the material station.
  174. :param subdata: The "data" element in the package data, which should contain this compatibility information.
  175. :return: Whether this package provides any material that is compatible with the material station.
  176. """
  177. for material in subdata.get("materials", []):
  178. for compatibility in material.get("compatibility", []):
  179. if compatibility.get("material_station_optimized", False):
  180. return True
  181. return False
  182. def _isCompatibleAirManager(self, subdata: Dict[str, Any]) -> bool:
  183. """
  184. Finds out if this package provides any material that is compatible with the air manager.
  185. :param subdata: The "data" element in the package data, which should contain this compatibility information.
  186. :return: Whether this package provides any material that is compatible with the air manager.
  187. """
  188. for material in subdata.get("materials", []):
  189. for compatibility in material.get("compatibility", []):
  190. if compatibility.get("air_manager_optimized", False):
  191. return True
  192. return False
  193. @pyqtProperty(str, constant = True)
  194. def packageId(self) -> str:
  195. return self._package_id
  196. @pyqtProperty(str, constant=True)
  197. def marketplaceURL(self)-> str:
  198. return self._marketplace_url
  199. @pyqtProperty(str, constant = True)
  200. def packageType(self) -> str:
  201. return self._package_type
  202. @pyqtProperty(str, constant = True)
  203. def iconUrl(self) -> str:
  204. return self._icon_url
  205. @pyqtProperty(str, constant = True)
  206. def displayName(self) -> str:
  207. return self._display_name
  208. @pyqtProperty(bool, constant = True)
  209. def isCheckedByUltimaker(self):
  210. return self._is_checked_by_ultimaker
  211. @pyqtProperty(str, constant = True)
  212. def packageVersion(self) -> str:
  213. return self._package_version
  214. @pyqtProperty(str, constant = True)
  215. def packageInfoUrl(self) -> str:
  216. return self._package_info_url
  217. @pyqtProperty(int, constant = True)
  218. def downloadCount(self) -> str:
  219. return self._download_count
  220. @pyqtProperty(str, constant = True)
  221. def description(self) -> str:
  222. return self._description
  223. @pyqtProperty(str, constant = True)
  224. def formattedDescription(self) -> str:
  225. return self._formatted_description
  226. @pyqtProperty(str, constant = True)
  227. def authorName(self) -> str:
  228. return self._author_name
  229. @pyqtProperty(str, constant = True)
  230. def authorInfoUrl(self) -> str:
  231. return self._author_info_url
  232. @pyqtProperty(str, constant = True)
  233. def sectionTitle(self) -> Optional[str]:
  234. return self._section_title
  235. @pyqtProperty(str, constant = True)
  236. def technicalDataSheet(self) -> str:
  237. return self._technical_data_sheet
  238. @pyqtProperty(str, constant = True)
  239. def safetyDataSheet(self) -> str:
  240. return self._safety_data_sheet
  241. @pyqtProperty(str, constant = True)
  242. def whereToBuy(self) -> str:
  243. return self._where_to_buy
  244. @pyqtProperty("QStringList", constant = True)
  245. def compatiblePrinters(self) -> List[str]:
  246. return self._compatible_printers
  247. @pyqtProperty("QStringList", constant = True)
  248. def compatibleSupportMaterials(self) -> List[str]:
  249. return self._compatible_support_materials
  250. @pyqtProperty(bool, constant = True)
  251. def isCompatibleMaterialStation(self) -> bool:
  252. return self._is_compatible_material_station
  253. @pyqtProperty(bool, constant = True)
  254. def isCompatibleAirManager(self) -> bool:
  255. return self._is_compatible_air_manager
  256. @pyqtProperty(bool, constant = True)
  257. def isBundled(self) -> bool:
  258. return self._is_bundled
  259. def setDownloadUrl(self, download_url):
  260. self._download_url = download_url
  261. # --- manage buttons signals ---
  262. stateManageButtonChanged = pyqtSignal()
  263. installPackageTriggered = pyqtSignal(str, str)
  264. uninstallPackageTriggered = pyqtSignal(str)
  265. updatePackageTriggered = pyqtSignal(str, str)
  266. enablePackageTriggered = pyqtSignal(str)
  267. disablePackageTriggered = pyqtSignal(str)
  268. busyChanged = pyqtSignal()
  269. @pyqtSlot()
  270. def install(self):
  271. self.setBusy(True)
  272. self.installPackageTriggered.emit(self.packageId, self._download_url)
  273. @pyqtSlot()
  274. def update(self):
  275. self.setBusy(True)
  276. self.updatePackageTriggered.emit(self.packageId, self._download_url)
  277. @pyqtSlot()
  278. def uninstall(self):
  279. self.uninstallPackageTriggered.emit(self.packageId)
  280. @pyqtProperty(bool, notify= busyChanged)
  281. def busy(self):
  282. """
  283. Property indicating that some kind of upgrade is active.
  284. """
  285. return self._is_busy
  286. @pyqtSlot()
  287. def enable(self):
  288. self.enablePackageTriggered.emit(self.packageId)
  289. @pyqtSlot()
  290. def disable(self):
  291. self.disablePackageTriggered.emit(self.packageId)
  292. def setBusy(self, value: bool):
  293. if self._is_busy != value:
  294. self._is_busy = value
  295. try:
  296. self.busyChanged.emit()
  297. except RuntimeError:
  298. pass
  299. def _packageInstalled(self, package_id: str) -> None:
  300. if self._package_id != package_id:
  301. return
  302. self.setBusy(False)
  303. try:
  304. self.stateManageButtonChanged.emit()
  305. except RuntimeError:
  306. pass
  307. @pyqtProperty(bool, notify = stateManageButtonChanged)
  308. def isInstalled(self) -> bool:
  309. return self._package_id in self._package_manager.getAllInstalledPackageIDs()
  310. @pyqtProperty(bool, notify = stateManageButtonChanged)
  311. def isToBeInstalled(self) -> bool:
  312. return self._package_id in self._package_manager.getPackagesToInstall()
  313. @pyqtProperty(bool, notify = stateManageButtonChanged)
  314. def isActive(self) -> bool:
  315. return not self._package_id in self._plugin_registry.getDisabledPlugins()
  316. @pyqtProperty(bool, notify = stateManageButtonChanged)
  317. def canDowngrade(self) -> bool:
  318. """Flag if the installed package can be downgraded to a bundled version"""
  319. return self._package_manager.canDowngrade(self._package_id)
  320. def setCanUpdate(self, value: bool) -> None:
  321. self._can_update = value
  322. self.stateManageButtonChanged.emit()
  323. @pyqtProperty(bool, fset = setCanUpdate, notify = stateManageButtonChanged)
  324. def canUpdate(self) -> bool:
  325. """Flag indicating if the package can be updated"""
  326. return self._can_update
  327. isMissingPackageInformationChanged = pyqtSignal()
  328. def setIsMissingPackageInformation(self, isMissingPackageInformation: bool) -> None:
  329. self._is_missing_package_information = isMissingPackageInformation
  330. self.isMissingPackageInformationChanged.emit()
  331. @pyqtProperty(bool, notify=isMissingPackageInformationChanged)
  332. def isMissingPackageInformation(self) -> bool:
  333. """Flag indicating if the package can be updated"""
  334. return self._is_missing_package_information