PackageModel.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt5.QtCore import pyqtProperty, QObject, pyqtSignal
  4. import re
  5. from typing import Any, Dict, List, Optional, Union
  6. from cura.Settings.CuraContainerRegistry import CuraContainerRegistry # To get names of materials we're compatible with.
  7. from UM.Logger import Logger
  8. from UM.i18n import i18nCatalog # To translate placeholder names if data is not present.
  9. catalog = i18nCatalog("cura")
  10. class PackageModel(QObject):
  11. """
  12. Represents a package, containing all the relevant information to be displayed about a package.
  13. Effectively this behaves like a glorified named tuple, but as a QObject so that its properties can be obtained from
  14. QML. The model can also be constructed directly from a response received by the API.
  15. """
  16. def __init__(self, package_data: Dict[str, Any], section_title: Optional[str] = None, parent: Optional[QObject] = None) -> None:
  17. """
  18. Constructs a new model for a single package.
  19. :param package_data: The data received from the Marketplace API about the package to create.
  20. :param section_title: If the packages are to be categorized per section provide the section_title
  21. :param parent: The parent QML object that controls the lifetime of this model (normally a PackageList).
  22. """
  23. super().__init__(parent)
  24. self._package_id = package_data.get("package_id", "UnknownPackageId")
  25. self._package_type = package_data.get("package_type", "")
  26. self._is_installed = package_data.get("is_installed", False)
  27. self._is_active = package_data.get("is_active", False)
  28. self._is_bundled = package_data.get("is_bundled", False)
  29. self._icon_url = package_data.get("icon_url", "")
  30. self._display_name = package_data.get("display_name", catalog.i18nc("@label:property", "Unknown Package"))
  31. tags = package_data.get("tags", [])
  32. self._is_checked_by_ultimaker = (self._package_type == "plugin" and "verified" in tags) or (self._package_type == "material" and "certified" in tags)
  33. self._package_version = package_data.get("package_version", "") # Display purpose, no need for 'UM.Version'.
  34. self._package_info_url = package_data.get("website", "") # Not to be confused with 'download_url'.
  35. self._download_count = package_data.get("download_count", 0)
  36. self._description = package_data.get("description", "")
  37. self._formatted_description = self._format(self._description)
  38. self.download_url = package_data.get("download_url", "")
  39. self._release_notes = package_data.get("release_notes", "") # Not used yet, propose to add to description?
  40. subdata = package_data.get("data", {})
  41. self._technical_data_sheet = self._findLink(subdata, "technical_data_sheet")
  42. self._safety_data_sheet = self._findLink(subdata, "safety_data_sheet")
  43. self._where_to_buy = self._findLink(subdata, "where_to_buy")
  44. self._compatible_printers = self._getCompatiblePrinters(subdata)
  45. self._compatible_support_materials = self._getCompatibleSupportMaterials(subdata)
  46. self._is_compatible_material_station = self._isCompatibleMaterialStation(subdata)
  47. self._is_compatible_air_manager = self._isCompatibleAirManager(subdata)
  48. author_data = package_data.get("author", {})
  49. self._author_name = author_data.get("display_name", catalog.i18nc("@label:property", "Unknown Author"))
  50. self._author_info_url = author_data.get("website", "")
  51. if not self._icon_url or self._icon_url == "":
  52. self._icon_url = author_data.get("icon_url", "")
  53. self._is_installing = False
  54. self._is_recently_managed = False
  55. self._can_update = False
  56. self._is_updating = False
  57. self._is_enabling = 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. def __eq__(self, other: Union[str, "PackageModel"]):
  62. if isinstance(other, PackageModel):
  63. return other == self
  64. else:
  65. return other == self._package_id
  66. def __repr__(self):
  67. return f"<{self._package_id} : {self._package_version} : {self._section_title}>"
  68. def _findLink(self, subdata: Dict[str, Any], link_type: str) -> str:
  69. """
  70. Searches the package data for a link of a certain type.
  71. The links are not in a fixed path in the package data. We need to iterate over the available links to find them.
  72. :param subdata: The "data" element in the package data, which should contain links.
  73. :param link_type: The type of link to find.
  74. :return: A URL of where the link leads, or an empty string if there is no link of that type in the package data.
  75. """
  76. links = subdata.get("links", [])
  77. for link in links:
  78. if link.get("type", "") == link_type:
  79. return link.get("url", "")
  80. else:
  81. return "" # No link with the correct type was found.
  82. def _format(self, text: str) -> str:
  83. """
  84. Formats a user-readable block of text for display.
  85. :return: A block of rich text with formatting embedded.
  86. """
  87. # Turn all in-line hyperlinks into actual links.
  88. url_regex = re.compile(r"(((http|https)://)[a-zA-Z0-9@:%.\-_+~#?&/=]{2,256}\.[a-z]{2,12}(/[a-zA-Z0-9@:%.\-_+~#?&/=]*)?)")
  89. text = re.sub(url_regex, r'<a href="\1">\1</a>', text)
  90. # Turn newlines into <br> so that they get displayed as newlines when rendering as rich text.
  91. text = text.replace("\n", "<br>")
  92. return text
  93. def _getCompatiblePrinters(self, subdata: Dict[str, Any]) -> List[str]:
  94. """
  95. Gets the list of printers that this package provides material compatibility with.
  96. Any printer is listed, even if it's only for a single nozzle on a single material in the package.
  97. :param subdata: The "data" element in the package data, which should contain this compatibility information.
  98. :return: A list of printer names that this package provides material compatibility with.
  99. """
  100. result = set()
  101. for material in subdata.get("materials", []):
  102. for compatibility in material.get("compatibility", []):
  103. printer_name = compatibility.get("machine_name")
  104. if printer_name is None:
  105. continue # Missing printer name information. Skip this one.
  106. for subcompatibility in compatibility.get("compatibilities", []):
  107. if subcompatibility.get("hardware_compatible", False):
  108. result.add(printer_name)
  109. break
  110. return list(sorted(result))
  111. def _getCompatibleSupportMaterials(self, subdata: Dict[str, Any]) -> List[str]:
  112. """
  113. Gets the list of support materials that the materials in this package are compatible with.
  114. Since the materials are individually encoded as keys in the API response, only PVA and Breakaway are currently
  115. supported.
  116. :param subdata: The "data" element in the package data, which should contain this compatibility information.
  117. :return: A list of support materials that the materials in this package are compatible with.
  118. """
  119. result = set()
  120. container_registry = CuraContainerRegistry.getInstance()
  121. try:
  122. pva_name = container_registry.findContainersMetadata(id = "ultimaker_pva")[0].get("name", "Ultimaker PVA")
  123. except IndexError:
  124. pva_name = "Ultimaker PVA"
  125. try:
  126. breakaway_name = container_registry.findContainersMetadata(id = "ultimaker_bam")[0].get("name", "Ultimaker Breakaway")
  127. except IndexError:
  128. breakaway_name = "Ultimaker Breakaway"
  129. for material in subdata.get("materials", []):
  130. if material.get("pva_compatible", False):
  131. result.add(pva_name)
  132. if material.get("breakaway_compatible", False):
  133. result.add(breakaway_name)
  134. return list(sorted(result))
  135. def _isCompatibleMaterialStation(self, subdata: Dict[str, Any]) -> bool:
  136. """
  137. Finds out if this package provides any material that is compatible with the material station.
  138. :param subdata: The "data" element in the package data, which should contain this compatibility information.
  139. :return: Whether this package provides any material that is compatible with the material station.
  140. """
  141. for material in subdata.get("materials", []):
  142. for compatibility in material.get("compatibility", []):
  143. if compatibility.get("material_station_optimized", False):
  144. return True
  145. return False
  146. def _isCompatibleAirManager(self, subdata: Dict[str, Any]) -> bool:
  147. """
  148. Finds out if this package provides any material that is compatible with the air manager.
  149. :param subdata: The "data" element in the package data, which should contain this compatibility information.
  150. :return: Whether this package provides any material that is compatible with the air manager.
  151. """
  152. for material in subdata.get("materials", []):
  153. for compatibility in material.get("compatibility", []):
  154. if compatibility.get("air_manager_optimized", False):
  155. return True
  156. return False
  157. @pyqtProperty(str, constant = True)
  158. def packageId(self) -> str:
  159. return self._package_id
  160. @pyqtProperty(str, constant = True)
  161. def packageType(self) -> str:
  162. return self._package_type
  163. @pyqtProperty(str, constant=True)
  164. def iconUrl(self):
  165. return self._icon_url
  166. @pyqtProperty(str, constant = True)
  167. def displayName(self) -> str:
  168. return self._display_name
  169. @pyqtProperty(bool, constant = True)
  170. def isCheckedByUltimaker(self):
  171. return self._is_checked_by_ultimaker
  172. @pyqtProperty(str, constant=True)
  173. def packageVersion(self):
  174. return self._package_version
  175. @pyqtProperty(str, constant=True)
  176. def packageInfoUrl(self):
  177. return self._package_info_url
  178. @pyqtProperty(int, constant=True)
  179. def downloadCount(self):
  180. return self._download_count
  181. @pyqtProperty(str, constant=True)
  182. def description(self):
  183. return self._description
  184. @pyqtProperty(str, constant = True)
  185. def formattedDescription(self) -> str:
  186. return self._formatted_description
  187. @pyqtProperty(str, constant=True)
  188. def authorName(self):
  189. return self._author_name
  190. @pyqtProperty(str, constant=True)
  191. def authorInfoUrl(self):
  192. return self._author_info_url
  193. @pyqtProperty(str, constant = True)
  194. def sectionTitle(self) -> Optional[str]:
  195. return self._section_title
  196. @pyqtProperty(str, constant = True)
  197. def technicalDataSheet(self) -> str:
  198. return self._technical_data_sheet
  199. @pyqtProperty(str, constant = True)
  200. def safetyDataSheet(self) -> str:
  201. return self._safety_data_sheet
  202. @pyqtProperty(str, constant = True)
  203. def whereToBuy(self) -> str:
  204. return self._where_to_buy
  205. @pyqtProperty("QStringList", constant = True)
  206. def compatiblePrinters(self) -> List[str]:
  207. return self._compatible_printers
  208. @pyqtProperty("QStringList", constant = True)
  209. def compatibleSupportMaterials(self) -> List[str]:
  210. return self._compatible_support_materials
  211. @pyqtProperty(bool, constant = True)
  212. def isCompatibleMaterialStation(self) -> bool:
  213. return self._is_compatible_material_station
  214. @pyqtProperty(bool, constant = True)
  215. def isCompatibleAirManager(self) -> bool:
  216. return self._is_compatible_air_manager
  217. # --- manage buttons signals ---
  218. stateManageButtonChanged = pyqtSignal()
  219. installPackageTriggered = pyqtSignal(str)
  220. uninstallPackageTriggered = pyqtSignal(str)
  221. updatePackageTriggered = pyqtSignal(str)
  222. enablePackageTriggered = pyqtSignal(str)
  223. disablePackageTriggered = pyqtSignal(str)
  224. # --- enabling ---
  225. @pyqtProperty(str, notify = stateManageButtonChanged)
  226. def stateManageEnableButton(self) -> str:
  227. if self._is_enabling:
  228. return "busy"
  229. if self._is_recently_managed:
  230. return "hidden"
  231. if self._package_type == "material":
  232. if self._is_bundled: # TODO: Check if a bundled material can/should be un-/install en-/disabled
  233. return "secondary"
  234. return "hidden"
  235. if not self._is_installed:
  236. return "hidden"
  237. if self._is_installed and self._is_active:
  238. return "secondary"
  239. return "primary"
  240. @property
  241. def is_enabling(self) -> bool:
  242. return self._is_enabling
  243. @is_enabling.setter
  244. def is_enabling(self, value: bool) -> None:
  245. if value != self._is_enabling:
  246. self._is_enabling = value
  247. self.stateManageButtonChanged.emit()
  248. # --- Installing ---
  249. @pyqtProperty(str, notify = stateManageButtonChanged)
  250. def stateManageInstallButton(self) -> str:
  251. if self._is_installing:
  252. return "busy"
  253. if self._is_recently_managed:
  254. return "hidden"
  255. if self._is_installed:
  256. if self._is_bundled:
  257. return "hidden"
  258. else:
  259. return "secondary"
  260. else:
  261. return "primary"
  262. @property
  263. def is_recently_managed(self) -> bool:
  264. return self._is_recently_managed
  265. @is_recently_managed.setter
  266. def is_recently_managed(self, value: bool) -> None:
  267. if value != self._is_recently_managed:
  268. self._is_recently_managed = value
  269. self.stateManageButtonChanged.emit()
  270. @property
  271. def is_installing(self) -> bool:
  272. return self._is_installing
  273. @is_installing.setter
  274. def is_installing(self, value: bool) -> None:
  275. if value != self._is_installing:
  276. self._is_installing = value
  277. self.stateManageButtonChanged.emit()
  278. # --- Updating ---
  279. @pyqtProperty(str, notify = stateManageButtonChanged)
  280. def stateManageUpdateButton(self) -> str:
  281. if self._is_updating:
  282. return "busy"
  283. if self._can_update:
  284. return "primary"
  285. return "hidden"
  286. @property
  287. def is_updating(self) -> bool:
  288. return self._is_updating
  289. @is_updating.setter
  290. def is_updating(self, value: bool) -> None:
  291. if value != self._is_updating:
  292. self._is_updating = value
  293. self.stateManageButtonChanged.emit()
  294. @property
  295. def can_update(self) -> bool:
  296. return self._can_update
  297. @can_update.setter
  298. def can_update(self, value: bool) -> None:
  299. if value != self._can_update:
  300. self._can_update = value
  301. self.stateManageButtonChanged.emit()
  302. # ----
  303. # isInstalledChanged = pyqtSignal()
  304. #
  305. # @pyqtProperty(bool, notify = isInstalledChanged)
  306. # def isInstalled(self):
  307. # return self._is_installed
  308. #
  309. # isEnabledChanged = pyqtSignal()
  310. #
  311. #
  312. #f
  313. # @pyqtProperty(bool, notify = isEnabledChanged)
  314. # def isEnabled(self) -> bool:
  315. # return self._is_active
  316. #
  317. #
  318. #
  319. # isManageEnableStateChanged = pyqtSignalf()
  320. #
  321. # @pyqtProperty(str, notify = isManageEnableStateChanged)
  322. # def isManageEnableState(self) -> str:
  323. # if self.isEnabling:
  324. # return "busy"
  325. # if self.
  326. #
  327. # manageEnableStateChanged = pyqtSignal()
  328. #
  329. # @pyqtProperty(str, notify = manageEnableStateChanged)
  330. # def manageEnableState(self) -> str:
  331. # # TODO: Handle manual installed packages
  332. # if self._is_installed:
  333. # if self._is_active:
  334. # return "secondary"
  335. # else:
  336. # return "primary"
  337. # else:
  338. # return "hidden"
  339. #
  340. # manageInstallStateChanged = pyqtSignal()
  341. #
  342. # def setManageInstallState(self, value: bool) -> None:
  343. # if value != self._is_installed:
  344. # self._is_installed = value
  345. # self.manageInstallStateChanged.emit()
  346. # self.manageEnableStateChanged.emit()
  347. #
  348. # @pyqtProperty(str, notify = manageInstallStateChanged)
  349. # def manageInstallState(self) -> str:
  350. # if self._is_installed:
  351. # if self._is_bundled:
  352. # return "hidden"
  353. # else:
  354. # return "secondary"
  355. # else:
  356. # return "primary"
  357. #
  358. # manageUpdateStateChanged = pyqtSignal()
  359. #
  360. # @pyqtProperty(str, notify = manageUpdateStateChanged)
  361. # def manageUpdateState(self) -> str:
  362. # if self._can_update:
  363. # return "primary"
  364. # return "hidden"
  365. #