WorkspaceDialog.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. @pyqtSlot(bool)
  246. def setDropToBuildPlateForModel(self, drop_to_buildplate: bool) -> None:
  247. CuraApplication.getInstance().getWorkplaceDropToBuildplate(drop_to_buildplate)
  248. def setMaterialConflict(self, material_conflict: bool) -> None:
  249. if self._has_material_conflict != material_conflict:
  250. self._has_material_conflict = material_conflict
  251. self.materialConflictChanged.emit()
  252. def setMachineConflict(self, machine_conflict: bool) -> None:
  253. if self._has_machine_conflict != machine_conflict:
  254. self._has_machine_conflict = machine_conflict
  255. self.machineConflictChanged.emit()
  256. def setQualityChangesConflict(self, quality_changes_conflict: bool) -> None:
  257. if self._has_quality_changes_conflict != quality_changes_conflict:
  258. self._has_quality_changes_conflict = quality_changes_conflict
  259. self.qualityChangesConflictChanged.emit()
  260. def setMissingPackagesMetadata(self, missing_package_metadata: List[Dict[str, str]]) -> None:
  261. self._missing_package_metadata = missing_package_metadata
  262. self.missingPackagesChanged.emit()
  263. @pyqtProperty("QVariantList", notify=missingPackagesChanged)
  264. def missingPackages(self) -> List[Dict[str, str]]:
  265. return self._missing_package_metadata
  266. @pyqtSlot()
  267. def installMissingPackages(self) -> None:
  268. marketplace_plugin = PluginRegistry.getInstance().getPluginObject("Marketplace")
  269. if not marketplace_plugin:
  270. Logger.warning("Could not show dialog to install missing plug-ins. Is Marketplace plug-in not available?")
  271. marketplace_plugin.showInstallMissingPackageDialog(self._missing_package_metadata, self.showMissingMaterialsWarning) # type: ignore
  272. def getResult(self) -> Dict[str, Optional[str]]:
  273. if "machine" in self._result and self.updatableMachinesModel.count <= 1:
  274. self._result["machine"] = None
  275. if "quality_changes" in self._result and not self._has_quality_changes_conflict:
  276. self._result["quality_changes"] = None
  277. if "material" in self._result and not self._has_material_conflict:
  278. self._result["material"] = None
  279. # If the machine needs to be re-created, the definition_changes should also be re-created.
  280. # If the machine strategy is None, it means that there is no name conflict with existing ones. In this case
  281. # new definitions changes are created
  282. if "machine" in self._result:
  283. if self._result["machine"] == "new" or self._result["machine"] is None and self._result["definition_changes"] is None:
  284. self._result["definition_changes"] = "new"
  285. return self._result
  286. def _createViewFromQML(self) -> None:
  287. three_mf_reader_path = PluginRegistry.getInstance().getPluginPath("3MFReader")
  288. if three_mf_reader_path:
  289. path = os.path.join(three_mf_reader_path, self._qml_url)
  290. self._view = CuraApplication.getInstance().createQmlComponent(path, {"manager": self})
  291. def show(self) -> None:
  292. # Emit signal so the right thread actually shows the view.
  293. if threading.current_thread() != threading.main_thread():
  294. self._lock.acquire()
  295. # Reset the result
  296. self._result = {
  297. "machine": self._default_strategy,
  298. "quality_changes": self._default_strategy,
  299. "definition_changes": self._default_strategy,
  300. "material": self._default_strategy,
  301. }
  302. self._visible = True
  303. self.showDialogSignal.emit()
  304. @pyqtSlot()
  305. def notifyClosed(self) -> None:
  306. """Used to notify the dialog so the lock can be released."""
  307. self._result = {} # The result should be cleared before hide, because after it is released the main thread lock
  308. self._visible = False
  309. try:
  310. self._lock.release()
  311. except:
  312. pass
  313. def hide(self) -> None:
  314. self._visible = False
  315. self._view.hide()
  316. try:
  317. self._lock.release()
  318. except:
  319. pass
  320. @pyqtSlot(bool)
  321. def _onVisibilityChanged(self, visible: bool) -> None:
  322. if not visible:
  323. try:
  324. self._lock.release()
  325. except:
  326. pass
  327. @pyqtSlot()
  328. def onOkButtonClicked(self) -> None:
  329. self._view.hide()
  330. self.hide()
  331. @pyqtSlot()
  332. def onCancelButtonClicked(self) -> None:
  333. self._result = {}
  334. self._view.hide()
  335. self.hide()
  336. def waitForClose(self) -> None:
  337. """Block thread until the dialog is closed."""
  338. if self._visible:
  339. if threading.current_thread() != threading.main_thread():
  340. self._lock.acquire()
  341. self._lock.release()
  342. else:
  343. # If this is not run from a separate thread, we need to ensure that the events are still processed.
  344. while self._visible:
  345. time.sleep(1 / 50)
  346. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  347. @pyqtSlot()
  348. def showMissingMaterialsWarning(self) -> None:
  349. result_message = Message(
  350. i18n_catalog.i18nc("@info:status",
  351. "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."),
  352. lifetime=0,
  353. title=i18n_catalog.i18nc("@info:title", "Some required packages are not installed"),
  354. message_type=Message.MessageType.WARNING
  355. )
  356. result_message.addAction(
  357. "learn_more",
  358. name=i18n_catalog.i18nc("@action:button", "Learn more"),
  359. icon="",
  360. description=i18n_catalog.i18nc("@label", "Learn more about project packages."),
  361. button_align=Message.ActionButtonAlignment.ALIGN_LEFT,
  362. button_style=Message.ActionButtonStyle.LINK
  363. )
  364. result_message.addAction(
  365. "install_packages",
  366. name=i18n_catalog.i18nc("@action:button", "Install Packages"),
  367. icon="",
  368. description=i18n_catalog.i18nc("@label", "Install missing packages from project file."),
  369. button_align=Message.ActionButtonAlignment.ALIGN_RIGHT,
  370. button_style=Message.ActionButtonStyle.DEFAULT
  371. )
  372. result_message.actionTriggered.connect(self._onMessageActionTriggered)
  373. result_message.show()
  374. def _onMessageActionTriggered(self, message: Message, sync_message_action: str) -> None:
  375. if sync_message_action == "install_materials":
  376. self.installMissingPackages()
  377. message.hide()
  378. elif sync_message_action == "learn_more":
  379. QDesktopServices.openUrl(QUrl("https://support.ultimaker.com/hc/en-us/articles/360011968360-Using-the-Ultimaker-Marketplace"))
  380. def __show(self) -> None:
  381. if self._view is None:
  382. self._createViewFromQML()
  383. if self._view:
  384. self._view.show()