WorkspaceDialog.py 18 KB

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