PackageModel.py 16 KB

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