WorkspaceDialog.py 18 KB

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