WorkspaceDialog.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. # Copyright (c) 2022 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt6.QtCore import pyqtSignal, QObject, pyqtProperty, QCoreApplication, QUrl
  4. from PyQt6.QtGui import QDesktopServices
  5. from typing import List, Optional, Dict, cast
  6. from cura.Machines.Models.MachineListModel import MachineListModel
  7. from cura.Machines.Models.IntentTranslations import intent_translations
  8. from cura.Settings.GlobalStack import GlobalStack
  9. from UM.Application import Application
  10. from UM.FlameProfiler import pyqtSlot
  11. from UM.i18n import i18nCatalog
  12. from UM.Logger import Logger
  13. from UM.Message import Message
  14. from UM.PluginRegistry import PluginRegistry
  15. from UM.Settings.ContainerRegistry import ContainerRegistry
  16. import os
  17. import threading
  18. import time
  19. from cura.CuraApplication import CuraApplication
  20. i18n_catalog = i18nCatalog("cura")
  21. class WorkspaceDialog(QObject):
  22. showDialogSignal = pyqtSignal()
  23. def __init__(self, parent = None) -> None:
  24. super().__init__(parent)
  25. self._component = None
  26. self._context = None
  27. self._view = None
  28. self._qml_url = "WorkspaceDialog.qml"
  29. self._lock = threading.Lock()
  30. self._default_strategy = None
  31. self._result = {
  32. "machine": self._default_strategy,
  33. "quality_changes": self._default_strategy,
  34. "definition_changes": self._default_strategy,
  35. "material": self._default_strategy,
  36. }
  37. self._override_machine = None
  38. self._visible = False
  39. self.showDialogSignal.connect(self.__show)
  40. self._has_quality_changes_conflict = False
  41. self._has_definition_changes_conflict = False
  42. self._has_machine_conflict = False
  43. self._has_material_conflict = False
  44. self._has_visible_settings_field = False
  45. self._num_visible_settings = 0
  46. self._num_user_settings = 0
  47. self._active_mode = ""
  48. self._quality_name = ""
  49. self._num_settings_overridden_by_quality_changes = 0
  50. self._quality_type = ""
  51. self._intent_name = ""
  52. self._machine_name = ""
  53. self._machine_type = ""
  54. self._variant_type = ""
  55. self._material_labels = []
  56. self._extruders = []
  57. self._objects_on_plate = False
  58. self._is_printer_group = False
  59. self._updatable_machines_model = MachineListModel(self, listenToChanges=False)
  60. self._missing_package_metadata: List[Dict[str, str]] = []
  61. self._plugin_registry: PluginRegistry = CuraApplication.getInstance().getPluginRegistry()
  62. self._install_missing_package_dialog: Optional[QObject] = None
  63. self._is_abstract_machine = False
  64. self._is_networked_machine = False
  65. machineConflictChanged = pyqtSignal()
  66. qualityChangesConflictChanged = pyqtSignal()
  67. materialConflictChanged = pyqtSignal()
  68. numVisibleSettingsChanged = pyqtSignal()
  69. activeModeChanged = pyqtSignal()
  70. qualityNameChanged = pyqtSignal()
  71. hasVisibleSettingsFieldChanged = pyqtSignal()
  72. numSettingsOverridenByQualityChangesChanged = pyqtSignal()
  73. qualityTypeChanged = pyqtSignal()
  74. intentNameChanged = pyqtSignal()
  75. machineNameChanged = pyqtSignal()
  76. updatableMachinesChanged = pyqtSignal()
  77. isAbstractMachineChanged = pyqtSignal()
  78. isNetworkedChanged = pyqtSignal()
  79. materialLabelsChanged = pyqtSignal()
  80. objectsOnPlateChanged = pyqtSignal()
  81. numUserSettingsChanged = pyqtSignal()
  82. machineTypeChanged = pyqtSignal()
  83. variantTypeChanged = pyqtSignal()
  84. extrudersChanged = pyqtSignal()
  85. isPrinterGroupChanged = pyqtSignal()
  86. missingPackagesChanged = pyqtSignal()
  87. @pyqtProperty(bool, notify = isPrinterGroupChanged)
  88. def isPrinterGroup(self) -> bool:
  89. return self._is_printer_group
  90. def setIsPrinterGroup(self, value: bool):
  91. if value != self._is_printer_group:
  92. self._is_printer_group = value
  93. self.isPrinterGroupChanged.emit()
  94. @pyqtProperty(str, notify=variantTypeChanged)
  95. def variantType(self) -> str:
  96. return self._variant_type
  97. def setVariantType(self, variant_type: str) -> None:
  98. if self._variant_type != variant_type:
  99. self._variant_type = variant_type
  100. self.variantTypeChanged.emit()
  101. @pyqtProperty(str, notify=machineTypeChanged)
  102. def machineType(self) -> str:
  103. return self._machine_type
  104. def setMachineType(self, machine_type: str) -> None:
  105. self._machine_type = machine_type
  106. self.machineTypeChanged.emit()
  107. def setNumUserSettings(self, num_user_settings: int) -> None:
  108. if self._num_user_settings != num_user_settings:
  109. self._num_user_settings = num_user_settings
  110. self.numVisibleSettingsChanged.emit()
  111. @pyqtProperty(int, notify=numUserSettingsChanged)
  112. def numUserSettings(self) -> int:
  113. return self._num_user_settings
  114. @pyqtProperty(bool, notify=objectsOnPlateChanged)
  115. def hasObjectsOnPlate(self) -> bool:
  116. return self._objects_on_plate
  117. def setHasObjectsOnPlate(self, objects_on_plate):
  118. if self._objects_on_plate != objects_on_plate:
  119. self._objects_on_plate = objects_on_plate
  120. self.objectsOnPlateChanged.emit()
  121. @pyqtProperty("QVariantList", notify = materialLabelsChanged)
  122. def materialLabels(self) -> List[str]:
  123. return self._material_labels
  124. def setMaterialLabels(self, material_labels: List[str]) -> None:
  125. if self._material_labels != material_labels:
  126. self._material_labels = material_labels
  127. self.materialLabelsChanged.emit()
  128. @pyqtProperty("QVariantList", notify=extrudersChanged)
  129. def extruders(self):
  130. return self._extruders
  131. def setExtruders(self, extruders):
  132. if self._extruders != extruders:
  133. self._extruders = extruders
  134. self.extrudersChanged.emit()
  135. @pyqtProperty(str, notify = machineNameChanged)
  136. def machineName(self) -> str:
  137. return self._machine_name
  138. def setMachineName(self, machine_name: str) -> None:
  139. if self._machine_name != machine_name:
  140. self._machine_name = machine_name
  141. self.machineNameChanged.emit()
  142. @pyqtProperty(QObject, notify = updatableMachinesChanged)
  143. def updatableMachinesModel(self) -> MachineListModel:
  144. return cast(MachineListModel, self._updatable_machines_model)
  145. def setUpdatableMachines(self, updatable_machines: List[GlobalStack]) -> None:
  146. self._updatable_machines_model.set_machines_filter(updatable_machines)
  147. self.updatableMachinesChanged.emit()
  148. @pyqtProperty(bool, notify = isAbstractMachineChanged)
  149. def isAbstractMachine(self) -> bool:
  150. return self._is_abstract_machine
  151. @pyqtSlot(bool)
  152. def setIsAbstractMachine(self, is_abstract_machine: bool) -> None:
  153. self._is_abstract_machine = is_abstract_machine
  154. self.isAbstractMachineChanged.emit()
  155. @pyqtProperty(bool, notify = isNetworkedChanged)
  156. def isNetworked(self) -> bool:
  157. return self._is_networked_machine
  158. @pyqtSlot(bool)
  159. def setIsNetworkedMachine(self, is_networked_machine: bool) -> None:
  160. self._is_networked_machine = is_networked_machine
  161. self.isNetworkedChanged.emit()
  162. @pyqtProperty(str, notify=qualityTypeChanged)
  163. def qualityType(self) -> str:
  164. return self._quality_type
  165. def setQualityType(self, quality_type: str) -> None:
  166. if self._quality_type != quality_type:
  167. self._quality_type = quality_type
  168. self.qualityTypeChanged.emit()
  169. @pyqtProperty(int, notify=numSettingsOverridenByQualityChangesChanged)
  170. def numSettingsOverridenByQualityChanges(self) -> int:
  171. return self._num_settings_overridden_by_quality_changes
  172. def setNumSettingsOverriddenByQualityChanges(self, num_settings_overridden_by_quality_changes: int) -> None:
  173. self._num_settings_overridden_by_quality_changes = num_settings_overridden_by_quality_changes
  174. self.numSettingsOverridenByQualityChangesChanged.emit()
  175. @pyqtProperty(str, notify=qualityNameChanged)
  176. def qualityName(self) -> str:
  177. return self._quality_name
  178. def setQualityName(self, quality_name: str) -> None:
  179. if self._quality_name != quality_name:
  180. self._quality_name = quality_name
  181. self.qualityNameChanged.emit()
  182. @pyqtProperty(str, notify = intentNameChanged)
  183. def intentName(self) -> str:
  184. return self._intent_name
  185. def setIntentName(self, intent_name: str) -> None:
  186. if self._intent_name != intent_name:
  187. try:
  188. self._intent_name = intent_translations[intent_name]["name"]
  189. except:
  190. self._intent_name = intent_name.title()
  191. self.intentNameChanged.emit()
  192. if not self._intent_name:
  193. self._intent_name = intent_translations["default"]["name"]
  194. self.intentNameChanged.emit()
  195. @pyqtProperty(str, notify=activeModeChanged)
  196. def activeMode(self) -> str:
  197. return self._active_mode
  198. def setActiveMode(self, active_mode: int) -> None:
  199. if active_mode == 0:
  200. self._active_mode = i18n_catalog.i18nc("@title:tab", "Recommended")
  201. else:
  202. self._active_mode = i18n_catalog.i18nc("@title:tab", "Custom")
  203. self.activeModeChanged.emit()
  204. @pyqtProperty(bool, notify = hasVisibleSettingsFieldChanged)
  205. def hasVisibleSettingsField(self) -> bool:
  206. return self._has_visible_settings_field
  207. def setHasVisibleSettingsField(self, has_visible_settings_field: bool) -> None:
  208. self._has_visible_settings_field = has_visible_settings_field
  209. self.hasVisibleSettingsFieldChanged.emit()
  210. @pyqtProperty(int, constant = True)
  211. def totalNumberOfSettings(self) -> int:
  212. general_definition_containers = ContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")
  213. if not general_definition_containers:
  214. return 0
  215. return len(general_definition_containers[0].getAllKeys())
  216. @pyqtProperty(int, notify = numVisibleSettingsChanged)
  217. def numVisibleSettings(self) -> int:
  218. return self._num_visible_settings
  219. def setNumVisibleSettings(self, num_visible_settings: int) -> None:
  220. if self._num_visible_settings != num_visible_settings:
  221. self._num_visible_settings = num_visible_settings
  222. self.numVisibleSettingsChanged.emit()
  223. @pyqtProperty(bool, notify = machineConflictChanged)
  224. def machineConflict(self) -> bool:
  225. return self._has_machine_conflict
  226. @pyqtProperty(bool, notify=qualityChangesConflictChanged)
  227. def qualityChangesConflict(self) -> bool:
  228. return self._has_quality_changes_conflict
  229. @pyqtProperty(bool, notify=materialConflictChanged)
  230. def materialConflict(self) -> bool:
  231. return self._has_material_conflict
  232. @pyqtSlot(str, str)
  233. def setResolveStrategy(self, key: str, strategy: Optional[str]) -> None:
  234. if key in self._result:
  235. self._result[key] = strategy
  236. def getMachineToOverride(self) -> str:
  237. return self._override_machine
  238. @pyqtSlot(str)
  239. def setMachineToOverride(self, machine_name: str) -> None:
  240. self._override_machine = machine_name
  241. @pyqtSlot()
  242. def closeBackend(self) -> None:
  243. """Close the backend: otherwise one could end up with "Slicing..."""
  244. Application.getInstance().getBackend().close()
  245. def setMaterialConflict(self, material_conflict: bool) -> None:
  246. if self._has_material_conflict != material_conflict:
  247. self._has_material_conflict = material_conflict
  248. self.materialConflictChanged.emit()
  249. def setMachineConflict(self, machine_conflict: bool) -> None:
  250. if self._has_machine_conflict != machine_conflict:
  251. self._has_machine_conflict = machine_conflict
  252. self.machineConflictChanged.emit()
  253. def setQualityChangesConflict(self, quality_changes_conflict: bool) -> None:
  254. if self._has_quality_changes_conflict != quality_changes_conflict:
  255. self._has_quality_changes_conflict = quality_changes_conflict
  256. self.qualityChangesConflictChanged.emit()
  257. def setMissingPackagesMetadata(self, missing_package_metadata: List[Dict[str, str]]) -> None:
  258. self._missing_package_metadata = missing_package_metadata
  259. self.missingPackagesChanged.emit()
  260. @pyqtProperty("QVariantList", notify=missingPackagesChanged)
  261. def missingPackages(self) -> List[Dict[str, str]]:
  262. return self._missing_package_metadata
  263. @pyqtSlot()
  264. def installMissingPackages(self) -> None:
  265. marketplace_plugin = PluginRegistry.getInstance().getPluginObject("Marketplace")
  266. if not marketplace_plugin:
  267. Logger.warning("Could not show dialog to install missing plug-ins. Is Marketplace plug-in not available?")
  268. marketplace_plugin.showInstallMissingPackageDialog(self._missing_package_metadata, self.showMissingMaterialsWarning) # type: ignore
  269. def getResult(self) -> Dict[str, Optional[str]]:
  270. if "machine" in self._result and self.updatableMachinesModel.count <= 1:
  271. self._result["machine"] = None
  272. if "quality_changes" in self._result and not self._has_quality_changes_conflict:
  273. self._result["quality_changes"] = None
  274. if "material" in self._result and not self._has_material_conflict:
  275. self._result["material"] = None
  276. # If the machine needs to be re-created, the definition_changes should also be re-created.
  277. # If the machine strategy is None, it means that there is no name conflict with existing ones. In this case
  278. # new definitions changes are created
  279. if "machine" in self._result:
  280. if self._result["machine"] == "new" or self._result["machine"] is None and self._result["definition_changes"] is None:
  281. self._result["definition_changes"] = "new"
  282. return self._result
  283. def _createViewFromQML(self) -> None:
  284. three_mf_reader_path = PluginRegistry.getInstance().getPluginPath("3MFReader")
  285. if three_mf_reader_path:
  286. path = os.path.join(three_mf_reader_path, self._qml_url)
  287. self._view = CuraApplication.getInstance().createQmlComponent(path, {"manager": self})
  288. def show(self) -> None:
  289. # Emit signal so the right thread actually shows the view.
  290. if threading.current_thread() != threading.main_thread():
  291. self._lock.acquire()
  292. # Reset the result
  293. self._result = {
  294. "machine": self._default_strategy,
  295. "quality_changes": self._default_strategy,
  296. "definition_changes": self._default_strategy,
  297. "material": self._default_strategy,
  298. }
  299. self._visible = True
  300. self.showDialogSignal.emit()
  301. @pyqtSlot()
  302. def notifyClosed(self) -> None:
  303. """Used to notify the dialog so the lock can be released."""
  304. self._result = {} # The result should be cleared before hide, because after it is released the main thread lock
  305. self._visible = False
  306. try:
  307. self._lock.release()
  308. except:
  309. pass
  310. def hide(self) -> None:
  311. self._visible = False
  312. self._view.hide()
  313. try:
  314. self._lock.release()
  315. except:
  316. pass
  317. @pyqtSlot(bool)
  318. def _onVisibilityChanged(self, visible: bool) -> None:
  319. if not visible:
  320. try:
  321. self._lock.release()
  322. except:
  323. pass
  324. @pyqtSlot()
  325. def onOkButtonClicked(self) -> None:
  326. self._view.hide()
  327. self.hide()
  328. @pyqtSlot()
  329. def onCancelButtonClicked(self) -> None:
  330. self._result = {}
  331. self._view.hide()
  332. self.hide()
  333. def waitForClose(self) -> None:
  334. """Block thread until the dialog is closed."""
  335. if self._visible:
  336. if threading.current_thread() != threading.main_thread():
  337. self._lock.acquire()
  338. self._lock.release()
  339. else:
  340. # If this is not run from a separate thread, we need to ensure that the events are still processed.
  341. while self._visible:
  342. time.sleep(1 / 50)
  343. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  344. @pyqtSlot()
  345. def showMissingMaterialsWarning(self) -> None:
  346. result_message = Message(
  347. i18n_catalog.i18nc("@info:status",
  348. "Some of the packages used in the project file are currently not installed in Cura, this might produce undesirable print results. We highly recommend installing the all required packages from the Marketplace."),
  349. lifetime=0,
  350. title=i18n_catalog.i18nc("@info:title", "Some required packages are not installed"),
  351. message_type=Message.MessageType.WARNING
  352. )
  353. result_message.addAction(
  354. "learn_more",
  355. name=i18n_catalog.i18nc("@action:button", "Learn more"),
  356. icon="",
  357. description=i18n_catalog.i18nc("@label", "Learn more about project packages."),
  358. button_align=Message.ActionButtonAlignment.ALIGN_LEFT,
  359. button_style=Message.ActionButtonStyle.LINK
  360. )
  361. result_message.addAction(
  362. "install_packages",
  363. name=i18n_catalog.i18nc("@action:button", "Install Packages"),
  364. icon="",
  365. description=i18n_catalog.i18nc("@label", "Install missing packages from project file."),
  366. button_align=Message.ActionButtonAlignment.ALIGN_RIGHT,
  367. button_style=Message.ActionButtonStyle.DEFAULT
  368. )
  369. result_message.actionTriggered.connect(self._onMessageActionTriggered)
  370. result_message.show()
  371. def _onMessageActionTriggered(self, message: Message, sync_message_action: str) -> None:
  372. if sync_message_action == "install_materials":
  373. self.installMissingPackages()
  374. message.hide()
  375. elif sync_message_action == "learn_more":
  376. QDesktopServices.openUrl(QUrl("https://support.ultimaker.com/hc/en-us/articles/360011968360-Using-the-Ultimaker-Marketplace"))
  377. def __show(self) -> None:
  378. if self._view is None:
  379. self._createViewFromQML()
  380. if self._view:
  381. self._view.show()