WorkspaceDialog.py 21 KB

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