WorkspaceDialog.py 21 KB

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