PackageModel.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. @pyqtSlot()
  72. def _processUpdatedPackages(self):
  73. self.setCanUpdate(self._package_manager.checkIfPackageCanUpdate(self._package_id))
  74. def __del__(self):
  75. self._package_manager.packagesWithUpdateChanged.disconnect(self._processUpdatedPackages)
  76. def __eq__(self, other: object) -> bool:
  77. if isinstance(other, PackageModel):
  78. return other == self
  79. elif isinstance(other, str):
  80. return other == self._package_id
  81. else:
  82. return False
  83. def __repr__(self) -> str:
  84. return f"<{self._package_id} : {self._package_version} : {self._section_title}>"
  85. def _findLink(self, subdata: Dict[str, Any], link_type: str) -> str:
  86. """
  87. Searches the package data for a link of a certain type.
  88. The links are not in a fixed path in the package data. We need to iterate over the available links to find them.
  89. :param subdata: The "data" element in the package data, which should contain links.
  90. :param link_type: The type of link to find.
  91. :return: A URL of where the link leads, or an empty string if there is no link of that type in the package data.
  92. """
  93. links = subdata.get("links", [])
  94. for link in links:
  95. if link.get("type", "") == link_type:
  96. return link.get("url", "")
  97. else:
  98. return "" # No link with the correct type was found.
  99. def _format(self, text: str) -> str:
  100. """
  101. Formats a user-readable block of text for display.
  102. :return: A block of rich text with formatting embedded.
  103. """
  104. # Turn all in-line hyperlinks into actual links.
  105. url_regex = re.compile(r"(((http|https)://)[a-zA-Z0-9@:%.\-_+~#?&/=]{2,256}\.[a-z]{2,12}(/[a-zA-Z0-9@:%.\-_+~#?&/=]*)?)")
  106. text = re.sub(url_regex, r'<a href="\1">\1</a>', text)
  107. # Turn newlines into <br> so that they get displayed as newlines when rendering as rich text.
  108. text = text.replace("\n", "<br>")
  109. return text
  110. def _getCompatiblePrinters(self, subdata: Dict[str, Any]) -> List[str]:
  111. """
  112. Gets the list of printers that this package provides material compatibility with.
  113. Any printer is listed, even if it's only for a single nozzle on a single material in the package.
  114. :param subdata: The "data" element in the package data, which should contain this compatibility information.
  115. :return: A list of printer names that this package provides material compatibility with.
  116. """
  117. result = set()
  118. for material in subdata.get("materials", []):
  119. for compatibility in material.get("compatibility", []):
  120. printer_name = compatibility.get("machine_name")
  121. if printer_name is None:
  122. continue # Missing printer name information. Skip this one.
  123. for subcompatibility in compatibility.get("compatibilities", []):
  124. if subcompatibility.get("hardware_compatible", False):
  125. result.add(printer_name)
  126. break
  127. return list(sorted(result))
  128. def _getCompatibleSupportMaterials(self, subdata: Dict[str, Any]) -> List[str]:
  129. """
  130. Gets the list of support materials that the materials in this package are compatible with.
  131. Since the materials are individually encoded as keys in the API response, only PVA and Breakaway are currently
  132. supported.
  133. :param subdata: The "data" element in the package data, which should contain this compatibility information.
  134. :return: A list of support materials that the materials in this package are compatible with.
  135. """
  136. result = set()
  137. container_registry = CuraContainerRegistry.getInstance()
  138. try:
  139. pva_name = container_registry.findContainersMetadata(id = "ultimaker_pva")[0].get("name", "Ultimaker PVA")
  140. except IndexError:
  141. pva_name = "Ultimaker PVA"
  142. try:
  143. breakaway_name = container_registry.findContainersMetadata(id = "ultimaker_bam")[0].get("name", "Ultimaker Breakaway")
  144. except IndexError:
  145. breakaway_name = "Ultimaker Breakaway"
  146. for material in subdata.get("materials", []):
  147. if material.get("pva_compatible", False):
  148. result.add(pva_name)
  149. if material.get("breakaway_compatible", False):
  150. result.add(breakaway_name)
  151. return list(sorted(result))
  152. def _isCompatibleMaterialStation(self, subdata: Dict[str, Any]) -> bool:
  153. """
  154. Finds out if this package provides any material that is compatible with the material station.
  155. :param subdata: The "data" element in the package data, which should contain this compatibility information.
  156. :return: Whether this package provides any material that is compatible with the material station.
  157. """
  158. for material in subdata.get("materials", []):
  159. for compatibility in material.get("compatibility", []):
  160. if compatibility.get("material_station_optimized", False):
  161. return True
  162. return False
  163. def _isCompatibleAirManager(self, subdata: Dict[str, Any]) -> bool:
  164. """
  165. Finds out if this package provides any material that is compatible with the air manager.
  166. :param subdata: The "data" element in the package data, which should contain this compatibility information.
  167. :return: Whether this package provides any material that is compatible with the air manager.
  168. """
  169. for material in subdata.get("materials", []):
  170. for compatibility in material.get("compatibility", []):
  171. if compatibility.get("air_manager_optimized", False):
  172. return True
  173. return False
  174. @pyqtProperty(str, constant = True)
  175. def packageId(self) -> str:
  176. return self._package_id
  177. @pyqtProperty(str, constant=True)
  178. def marketplaceURL(self)-> str:
  179. return self._marketplace_url
  180. @pyqtProperty(str, constant = True)
  181. def packageType(self) -> str:
  182. return self._package_type
  183. @pyqtProperty(str, constant = True)
  184. def iconUrl(self) -> str:
  185. return self._icon_url
  186. @pyqtProperty(str, constant = True)
  187. def displayName(self) -> str:
  188. return self._display_name
  189. @pyqtProperty(bool, constant = True)
  190. def isCheckedByUltimaker(self):
  191. return self._is_checked_by_ultimaker
  192. @pyqtProperty(str, constant = True)
  193. def packageVersion(self) -> str:
  194. return self._package_version
  195. @pyqtProperty(str, constant = True)
  196. def packageInfoUrl(self) -> str:
  197. return self._package_info_url
  198. @pyqtProperty(int, constant = True)
  199. def downloadCount(self) -> str:
  200. return self._download_count
  201. @pyqtProperty(str, constant = True)
  202. def description(self) -> str:
  203. return self._description
  204. @pyqtProperty(str, constant = True)
  205. def formattedDescription(self) -> str:
  206. return self._formatted_description
  207. @pyqtProperty(str, constant = True)
  208. def authorName(self) -> str:
  209. return self._author_name
  210. @pyqtProperty(str, constant = True)
  211. def authorInfoUrl(self) -> str:
  212. return self._author_info_url
  213. @pyqtProperty(str, constant = True)
  214. def sectionTitle(self) -> Optional[str]:
  215. return self._section_title
  216. @pyqtProperty(str, constant = True)
  217. def technicalDataSheet(self) -> str:
  218. return self._technical_data_sheet
  219. @pyqtProperty(str, constant = True)
  220. def safetyDataSheet(self) -> str:
  221. return self._safety_data_sheet
  222. @pyqtProperty(str, constant = True)
  223. def whereToBuy(self) -> str:
  224. return self._where_to_buy
  225. @pyqtProperty("QStringList", constant = True)
  226. def compatiblePrinters(self) -> List[str]:
  227. return self._compatible_printers
  228. @pyqtProperty("QStringList", constant = True)
  229. def compatibleSupportMaterials(self) -> List[str]:
  230. return self._compatible_support_materials
  231. @pyqtProperty(bool, constant = True)
  232. def isCompatibleMaterialStation(self) -> bool:
  233. return self._is_compatible_material_station
  234. @pyqtProperty(bool, constant = True)
  235. def isCompatibleAirManager(self) -> bool:
  236. return self._is_compatible_air_manager
  237. @pyqtProperty(bool, constant = True)
  238. def isBundled(self) -> bool:
  239. return self._is_bundled
  240. def setDownloadUrl(self, download_url):
  241. self._download_url = download_url
  242. # --- manage buttons signals ---
  243. stateManageButtonChanged = pyqtSignal()
  244. installPackageTriggered = pyqtSignal(str, str)
  245. uninstallPackageTriggered = pyqtSignal(str)
  246. updatePackageTriggered = pyqtSignal(str, str)
  247. enablePackageTriggered = pyqtSignal(str)
  248. disablePackageTriggered = pyqtSignal(str)
  249. busyChanged = pyqtSignal()
  250. @pyqtSlot()
  251. def install(self):
  252. self.setBusy(True)
  253. self.installPackageTriggered.emit(self.packageId, self._download_url)
  254. @pyqtSlot()
  255. def update(self):
  256. self.setBusy(True)
  257. self.updatePackageTriggered.emit(self.packageId, self._download_url)
  258. @pyqtSlot()
  259. def uninstall(self):
  260. self.uninstallPackageTriggered.emit(self.packageId)
  261. @pyqtProperty(bool, notify= busyChanged)
  262. def busy(self):
  263. """
  264. Property indicating that some kind of upgrade is active.
  265. """
  266. return self._is_busy
  267. @pyqtSlot()
  268. def enable(self):
  269. self.enablePackageTriggered.emit(self.packageId)
  270. @pyqtSlot()
  271. def disable(self):
  272. self.disablePackageTriggered.emit(self.packageId)
  273. def setBusy(self, value: bool):
  274. if self._is_busy != value:
  275. self._is_busy = value
  276. try:
  277. self.busyChanged.emit()
  278. except RuntimeError:
  279. pass
  280. def _packageInstalled(self, package_id: str) -> None:
  281. if self._package_id != package_id:
  282. return
  283. self.setBusy(False)
  284. try:
  285. self.stateManageButtonChanged.emit()
  286. except RuntimeError:
  287. pass
  288. @pyqtProperty(bool, notify = stateManageButtonChanged)
  289. def isInstalled(self) -> bool:
  290. return self._package_id in self._package_manager.getAllInstalledPackageIDs()
  291. @pyqtProperty(bool, notify = stateManageButtonChanged)
  292. def isToBeInstalled(self) -> bool:
  293. return self._package_id in self._package_manager.getPackagesToInstall()
  294. @pyqtProperty(bool, notify = stateManageButtonChanged)
  295. def isActive(self) -> bool:
  296. return not self._package_id in self._plugin_registry.getDisabledPlugins()
  297. @pyqtProperty(bool, notify = stateManageButtonChanged)
  298. def canDowngrade(self) -> bool:
  299. """Flag if the installed package can be downgraded to a bundled version"""
  300. return self._package_manager.canDowngrade(self._package_id)
  301. def setCanUpdate(self, value: bool) -> None:
  302. self._can_update = value
  303. self.stateManageButtonChanged.emit()
  304. @pyqtProperty(bool, fset = setCanUpdate, notify = stateManageButtonChanged)
  305. def canUpdate(self) -> bool:
  306. """Flag indicating if the package can be updated"""
  307. return self._can_update