PackageModel.py 17 KB

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