CuraApplication.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt5.QtNetwork import QLocalServer
  4. from PyQt5.QtNetwork import QLocalSocket
  5. from UM.Qt.QtApplication import QtApplication
  6. from UM.Scene.SceneNode import SceneNode
  7. from UM.Scene.Camera import Camera
  8. from UM.Math.Vector import Vector
  9. from UM.Math.Quaternion import Quaternion
  10. from UM.Math.AxisAlignedBox import AxisAlignedBox
  11. from UM.Math.Matrix import Matrix
  12. from UM.Resources import Resources
  13. from UM.Scene.ToolHandle import ToolHandle
  14. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  15. from UM.Mesh.ReadMeshJob import ReadMeshJob
  16. from UM.Logger import Logger
  17. from UM.Preferences import Preferences
  18. from UM.SaveFile import SaveFile
  19. from UM.Scene.Selection import Selection
  20. from UM.Scene.GroupDecorator import GroupDecorator
  21. from UM.Settings.ContainerStack import ContainerStack
  22. from UM.Settings.InstanceContainer import InstanceContainer
  23. from UM.Settings.Validator import Validator
  24. from UM.Message import Message
  25. from UM.i18n import i18nCatalog
  26. from UM.Workspace.WorkspaceReader import WorkspaceReader
  27. from UM.Decorators import deprecated
  28. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  29. from UM.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
  30. from UM.Operations.GroupedOperation import GroupedOperation
  31. from UM.Operations.SetTransformOperation import SetTransformOperation
  32. from cura.Arrange import Arrange
  33. from cura.ShapeArray import ShapeArray
  34. from cura.ConvexHullDecorator import ConvexHullDecorator
  35. from cura.SetParentOperation import SetParentOperation
  36. from cura.SliceableObjectDecorator import SliceableObjectDecorator
  37. from cura.BlockSlicingDecorator import BlockSlicingDecorator
  38. from cura.ArrangeObjectsJob import ArrangeObjectsJob
  39. from cura.MultiplyObjectsJob import MultiplyObjectsJob
  40. from UM.Settings.SettingDefinition import SettingDefinition, DefinitionPropertyType
  41. from UM.Settings.ContainerRegistry import ContainerRegistry
  42. from UM.Settings.SettingFunction import SettingFunction
  43. from cura.Settings.MachineNameValidator import MachineNameValidator
  44. from cura.Settings.ProfilesModel import ProfilesModel
  45. from cura.Settings.MaterialsModel import MaterialsModel
  46. from cura.Settings.QualityAndUserProfilesModel import QualityAndUserProfilesModel
  47. from cura.Settings.SettingInheritanceManager import SettingInheritanceManager
  48. from cura.Settings.UserProfilesModel import UserProfilesModel
  49. from cura.Settings.SimpleModeSettingsManager import SimpleModeSettingsManager
  50. from . import PlatformPhysics
  51. from . import BuildVolume
  52. from . import CameraAnimation
  53. from . import PrintInformation
  54. from . import CuraActions
  55. from . import ZOffsetDecorator
  56. from . import CuraSplashScreen
  57. from . import CameraImageProvider
  58. from . import MachineActionManager
  59. from cura.Settings.MachineManager import MachineManager
  60. from cura.Settings.MaterialManager import MaterialManager
  61. from cura.Settings.ExtruderManager import ExtruderManager
  62. from cura.Settings.UserChangesModel import UserChangesModel
  63. from cura.Settings.ExtrudersModel import ExtrudersModel
  64. from cura.Settings.ContainerSettingsModel import ContainerSettingsModel
  65. from cura.Settings.MaterialSettingsVisibilityHandler import MaterialSettingsVisibilityHandler
  66. from cura.Settings.QualitySettingsModel import QualitySettingsModel
  67. from cura.Settings.ContainerManager import ContainerManager
  68. from cura.Settings.GlobalStack import GlobalStack
  69. from cura.Settings.ExtruderStack import ExtruderStack
  70. from PyQt5.QtCore import QUrl, pyqtSignal, pyqtProperty, QEvent, Q_ENUMS
  71. from UM.FlameProfiler import pyqtSlot
  72. from PyQt5.QtGui import QColor, QIcon
  73. from PyQt5.QtWidgets import QMessageBox
  74. from PyQt5.QtQml import qmlRegisterUncreatableType, qmlRegisterSingletonType, qmlRegisterType
  75. import sys
  76. import os.path
  77. import numpy
  78. import copy
  79. import urllib.parse
  80. import os
  81. import argparse
  82. import json
  83. numpy.seterr(all="ignore")
  84. MYPY = False
  85. if not MYPY:
  86. try:
  87. from cura.CuraVersion import CuraVersion, CuraBuildType
  88. except ImportError:
  89. CuraVersion = "master" # [CodeStyle: Reflecting imported value]
  90. CuraBuildType = ""
  91. class CuraApplication(QtApplication):
  92. # SettingVersion represents the set of settings available in the machine/extruder definitions.
  93. # You need to make sure that this version number needs to be increased if there is any non-backwards-compatible
  94. # changes of the settings.
  95. SettingVersion = 3
  96. class ResourceTypes:
  97. QmlFiles = Resources.UserType + 1
  98. Firmware = Resources.UserType + 2
  99. QualityInstanceContainer = Resources.UserType + 3
  100. MaterialInstanceContainer = Resources.UserType + 4
  101. VariantInstanceContainer = Resources.UserType + 5
  102. UserInstanceContainer = Resources.UserType + 6
  103. MachineStack = Resources.UserType + 7
  104. ExtruderStack = Resources.UserType + 8
  105. DefinitionChangesContainer = Resources.UserType + 9
  106. Q_ENUMS(ResourceTypes)
  107. # FIXME: This signal belongs to the MachineManager, but the CuraEngineBackend plugin requires on it.
  108. # Because plugins are initialized before the ContainerRegistry, putting this signal in MachineManager
  109. # will make it initialized before ContainerRegistry does, and it won't find the active machine, thus
  110. # Cura will always show the Add Machine Dialog upon start.
  111. stacksValidationFinished = pyqtSignal() # Emitted whenever a validation is finished
  112. projectFileLoaded = pyqtSignal(str) # Emitted whenever a project file is loaded
  113. def __init__(self):
  114. # this list of dir names will be used by UM to detect an old cura directory
  115. for dir_name in ["extruders", "machine_instances", "materials", "plugins", "quality", "user", "variants"]:
  116. Resources.addExpectedDirNameInData(dir_name)
  117. Resources.addSearchPath(os.path.join(QtApplication.getInstallPrefix(), "share", "cura", "resources"))
  118. if not hasattr(sys, "frozen"):
  119. Resources.addSearchPath(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "resources"))
  120. self._open_file_queue = [] # Files to open when plug-ins are loaded.
  121. # Need to do this before ContainerRegistry tries to load the machines
  122. SettingDefinition.addSupportedProperty("settable_per_mesh", DefinitionPropertyType.Any, default = True, read_only = True)
  123. SettingDefinition.addSupportedProperty("settable_per_extruder", DefinitionPropertyType.Any, default = True, read_only = True)
  124. # this setting can be changed for each group in one-at-a-time mode
  125. SettingDefinition.addSupportedProperty("settable_per_meshgroup", DefinitionPropertyType.Any, default = True, read_only = True)
  126. SettingDefinition.addSupportedProperty("settable_globally", DefinitionPropertyType.Any, default = True, read_only = True)
  127. # From which stack the setting would inherit if not defined per object (handled in the engine)
  128. # AND for settings which are not settable_per_mesh:
  129. # which extruder is the only extruder this setting is obtained from
  130. SettingDefinition.addSupportedProperty("limit_to_extruder", DefinitionPropertyType.Function, default = "-1", depends_on = "value")
  131. # For settings which are not settable_per_mesh and not settable_per_extruder:
  132. # A function which determines the glabel/meshgroup value by looking at the values of the setting in all (used) extruders
  133. SettingDefinition.addSupportedProperty("resolve", DefinitionPropertyType.Function, default = None, depends_on = "value")
  134. SettingDefinition.addSettingType("extruder", None, str, Validator)
  135. SettingDefinition.addSettingType("optional_extruder", None, str, None)
  136. SettingDefinition.addSettingType("[int]", None, str, None)
  137. SettingFunction.registerOperator("extruderValues", ExtruderManager.getExtruderValues)
  138. SettingFunction.registerOperator("extruderValue", ExtruderManager.getExtruderValue)
  139. SettingFunction.registerOperator("resolveOrValue", ExtruderManager.getResolveOrValue)
  140. ## Add the 4 types of profiles to storage.
  141. Resources.addStorageType(self.ResourceTypes.QualityInstanceContainer, "quality")
  142. Resources.addStorageType(self.ResourceTypes.VariantInstanceContainer, "variants")
  143. Resources.addStorageType(self.ResourceTypes.MaterialInstanceContainer, "materials")
  144. Resources.addStorageType(self.ResourceTypes.UserInstanceContainer, "user")
  145. Resources.addStorageType(self.ResourceTypes.ExtruderStack, "extruders")
  146. Resources.addStorageType(self.ResourceTypes.MachineStack, "machine_instances")
  147. Resources.addStorageType(self.ResourceTypes.DefinitionChangesContainer, "definition_changes")
  148. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.QualityInstanceContainer)
  149. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.VariantInstanceContainer)
  150. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MaterialInstanceContainer)
  151. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.UserInstanceContainer)
  152. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.ExtruderStack)
  153. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MachineStack)
  154. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.DefinitionChangesContainer)
  155. ## Initialise the version upgrade manager with Cura's storage paths.
  156. import UM.VersionUpgradeManager #Needs to be here to prevent circular dependencies.
  157. UM.VersionUpgradeManager.VersionUpgradeManager.getInstance().setCurrentVersions(
  158. {
  159. ("quality_changes", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.QualityInstanceContainer, "application/x-uranium-instancecontainer"),
  160. ("machine_stack", ContainerStack.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.MachineStack, "application/x-cura-globalstack"),
  161. ("extruder_train", ContainerStack.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.ExtruderStack, "application/x-cura-extruderstack"),
  162. ("preferences", Preferences.Version * 1000000 + self.SettingVersion): (Resources.Preferences, "application/x-uranium-preferences"),
  163. ("user", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.UserInstanceContainer, "application/x-uranium-instancecontainer"),
  164. ("definition_changes", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.DefinitionChangesContainer, "application/x-uranium-instancecontainer"),
  165. }
  166. )
  167. self._currently_loading_files = []
  168. self._non_sliceable_extensions = []
  169. self._machine_action_manager = MachineActionManager.MachineActionManager()
  170. self._machine_manager = None # This is initialized on demand.
  171. self._material_manager = None
  172. self._setting_inheritance_manager = None
  173. self._simple_mode_settings_manager = None
  174. self._additional_components = {} # Components to add to certain areas in the interface
  175. super().__init__(name = "cura", version = CuraVersion, buildtype = CuraBuildType,
  176. tray_icon_name = "cura-icon-32.png")
  177. self.default_theme = "cura-light"
  178. self.setWindowIcon(QIcon(Resources.getPath(Resources.Images, "cura-icon.png")))
  179. self.setRequiredPlugins([
  180. "CuraEngineBackend",
  181. "SolidView",
  182. "LayerView",
  183. "STLReader",
  184. "SelectionTool",
  185. "CameraTool",
  186. "GCodeWriter",
  187. "LocalFileOutputDevice",
  188. "TranslateTool",
  189. "FileLogger",
  190. "XmlMaterialProfile",
  191. "PluginBrowser"
  192. ])
  193. self._physics = None
  194. self._volume = None
  195. self._output_devices = {}
  196. self._print_information = None
  197. self._previous_active_tool = None
  198. self._platform_activity = False
  199. self._scene_bounding_box = AxisAlignedBox.Null
  200. self._job_name = None
  201. self._center_after_select = False
  202. self._camera_animation = None
  203. self._cura_actions = None
  204. self._started = False
  205. self._message_box_callback = None
  206. self._message_box_callback_arguments = []
  207. self._preferred_mimetype = ""
  208. self._i18n_catalog = i18nCatalog("cura")
  209. self.getController().getScene().sceneChanged.connect(self.updatePlatformActivity)
  210. self.getController().toolOperationStopped.connect(self._onToolOperationStopped)
  211. self.getController().contextMenuRequested.connect(self._onContextMenuRequested)
  212. Resources.addType(self.ResourceTypes.QmlFiles, "qml")
  213. Resources.addType(self.ResourceTypes.Firmware, "firmware")
  214. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading machines..."))
  215. # Add empty variant, material and quality containers.
  216. # Since they are empty, they should never be serialized and instead just programmatically created.
  217. # We need them to simplify the switching between materials.
  218. empty_container = ContainerRegistry.getInstance().getEmptyInstanceContainer()
  219. empty_variant_container = copy.deepcopy(empty_container)
  220. empty_variant_container._id = "empty_variant"
  221. empty_variant_container.addMetaDataEntry("type", "variant")
  222. ContainerRegistry.getInstance().addContainer(empty_variant_container)
  223. empty_material_container = copy.deepcopy(empty_container)
  224. empty_material_container._id = "empty_material"
  225. empty_material_container.addMetaDataEntry("type", "material")
  226. ContainerRegistry.getInstance().addContainer(empty_material_container)
  227. empty_quality_container = copy.deepcopy(empty_container)
  228. empty_quality_container._id = "empty_quality"
  229. empty_quality_container.setName("Not Supported")
  230. empty_quality_container.addMetaDataEntry("quality_type", "normal")
  231. empty_quality_container.addMetaDataEntry("type", "quality")
  232. ContainerRegistry.getInstance().addContainer(empty_quality_container)
  233. empty_quality_changes_container = copy.deepcopy(empty_container)
  234. empty_quality_changes_container._id = "empty_quality_changes"
  235. empty_quality_changes_container.addMetaDataEntry("type", "quality_changes")
  236. ContainerRegistry.getInstance().addContainer(empty_quality_changes_container)
  237. with ContainerRegistry.getInstance().lockFile():
  238. ContainerRegistry.getInstance().load()
  239. # set the setting version for Preferences
  240. preferences = Preferences.getInstance()
  241. preferences.addPreference("metadata/setting_version", 0)
  242. preferences.setValue("metadata/setting_version", self.SettingVersion) #Don't make it equal to the default so that the setting version always gets written to the file.
  243. preferences.addPreference("cura/active_mode", "simple")
  244. preferences.addPreference("cura/categories_expanded", "")
  245. preferences.addPreference("cura/jobname_prefix", True)
  246. preferences.addPreference("view/center_on_select", False)
  247. preferences.addPreference("mesh/scale_to_fit", False)
  248. preferences.addPreference("mesh/scale_tiny_meshes", True)
  249. preferences.addPreference("cura/dialog_on_project_save", True)
  250. preferences.addPreference("cura/asked_dialog_on_project_save", False)
  251. preferences.addPreference("cura/choice_on_profile_override", "always_ask")
  252. preferences.addPreference("cura/choice_on_open_project", "always_ask")
  253. preferences.addPreference("cura/currency", "€")
  254. preferences.addPreference("cura/material_settings", "{}")
  255. preferences.addPreference("view/invert_zoom", False)
  256. for key in [
  257. "dialog_load_path", # dialog_save_path is in LocalFileOutputDevicePlugin
  258. "dialog_profile_path",
  259. "dialog_material_path"]:
  260. preferences.addPreference("local_file/%s" % key, os.path.expanduser("~/"))
  261. preferences.setDefault("local_file/last_used_type", "text/x-gcode")
  262. preferences.setDefault("general/visible_settings", """
  263. machine_settings
  264. resolution
  265. layer_height
  266. shell
  267. wall_thickness
  268. top_bottom_thickness
  269. z_seam_x
  270. z_seam_y
  271. infill
  272. infill_sparse_density
  273. gradual_infill_steps
  274. material
  275. material_print_temperature
  276. material_bed_temperature
  277. material_diameter
  278. material_flow
  279. retraction_enable
  280. speed
  281. speed_print
  282. speed_travel
  283. acceleration_print
  284. acceleration_travel
  285. jerk_print
  286. jerk_travel
  287. travel
  288. cooling
  289. cool_fan_enabled
  290. support
  291. support_enable
  292. support_extruder_nr
  293. support_type
  294. platform_adhesion
  295. adhesion_type
  296. adhesion_extruder_nr
  297. brim_width
  298. raft_airgap
  299. layer_0_z_overlap
  300. raft_surface_layers
  301. dual
  302. prime_tower_enable
  303. prime_tower_size
  304. prime_tower_position_x
  305. prime_tower_position_y
  306. meshfix
  307. blackmagic
  308. print_sequence
  309. infill_mesh
  310. cutting_mesh
  311. experimental
  312. """.replace("\n", ";").replace(" ", ""))
  313. self.applicationShuttingDown.connect(self.saveSettings)
  314. self.engineCreatedSignal.connect(self._onEngineCreated)
  315. self.globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  316. self._onGlobalContainerChanged()
  317. self._plugin_registry.addSupportedPluginExtension("curaplugin", "Cura Plugin")
  318. def _onEngineCreated(self):
  319. self._engine.addImageProvider("camera", CameraImageProvider.CameraImageProvider())
  320. ## The "Quit" button click event handler.
  321. @pyqtSlot()
  322. def closeApplication(self):
  323. Logger.log("i", "Close application")
  324. self._main_window.close()
  325. ## A reusable dialogbox
  326. #
  327. showMessageBox = pyqtSignal(str, str, str, str, int, int, arguments = ["title", "text", "informativeText", "detailedText", "buttons", "icon"])
  328. def messageBox(self, title, text, informativeText = "", detailedText = "", buttons = QMessageBox.Ok, icon = QMessageBox.NoIcon, callback = None, callback_arguments = []):
  329. self._message_box_callback = callback
  330. self._message_box_callback_arguments = callback_arguments
  331. self.showMessageBox.emit(title, text, informativeText, detailedText, buttons, icon)
  332. showDiscardOrKeepProfileChanges = pyqtSignal()
  333. def discardOrKeepProfileChanges(self):
  334. has_user_interaction = False
  335. choice = Preferences.getInstance().getValue("cura/choice_on_profile_override")
  336. if choice == "always_discard":
  337. # don't show dialog and DISCARD the profile
  338. self.discardOrKeepProfileChangesClosed("discard")
  339. elif choice == "always_keep":
  340. # don't show dialog and KEEP the profile
  341. self.discardOrKeepProfileChangesClosed("keep")
  342. else:
  343. # ALWAYS ask whether to keep or discard the profile
  344. self.showDiscardOrKeepProfileChanges.emit()
  345. has_user_interaction = True
  346. return has_user_interaction
  347. onDiscardOrKeepProfileChangesClosed = pyqtSignal() # Used to notify other managers that the dialog was closed
  348. @pyqtSlot(str)
  349. def discardOrKeepProfileChangesClosed(self, option):
  350. if option == "discard":
  351. global_stack = self.getGlobalContainerStack()
  352. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  353. extruder.getTop().clear()
  354. global_stack.getTop().clear()
  355. # if the user decided to keep settings then the user settings should be re-calculated and validated for errors
  356. # before slicing. To ensure that slicer uses right settings values
  357. elif option == "keep":
  358. global_stack = self.getGlobalContainerStack()
  359. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  360. user_extruder_container = extruder.getTop()
  361. if user_extruder_container:
  362. user_extruder_container.update()
  363. user_global_container = global_stack.getTop()
  364. if user_global_container:
  365. user_global_container.update()
  366. # notify listeners that quality has changed (after user selected discard or keep)
  367. self.onDiscardOrKeepProfileChangesClosed.emit()
  368. self.getMachineManager().activeQualityChanged.emit()
  369. @pyqtSlot(int)
  370. def messageBoxClosed(self, button):
  371. if self._message_box_callback:
  372. self._message_box_callback(button, *self._message_box_callback_arguments)
  373. self._message_box_callback = None
  374. self._message_box_callback_arguments = []
  375. showPrintMonitor = pyqtSignal(bool, arguments = ["show"])
  376. ## Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
  377. #
  378. # Note that the AutoSave plugin also calls this method.
  379. def saveSettings(self):
  380. if not self._started: # Do not do saving during application start
  381. return
  382. # Lock file for "more" atomically loading and saving to/from config dir.
  383. with ContainerRegistry.getInstance().lockFile():
  384. for instance in ContainerRegistry.getInstance().findInstanceContainers():
  385. if not instance.isDirty():
  386. continue
  387. try:
  388. data = instance.serialize()
  389. except NotImplementedError:
  390. continue
  391. except Exception:
  392. Logger.logException("e", "An exception occurred when serializing container %s", instance.getId())
  393. continue
  394. mime_type = ContainerRegistry.getMimeTypeForContainer(type(instance))
  395. file_name = urllib.parse.quote_plus(instance.getId()) + "." + mime_type.preferredSuffix
  396. instance_type = instance.getMetaDataEntry("type")
  397. path = None
  398. if instance_type == "material":
  399. path = Resources.getStoragePath(self.ResourceTypes.MaterialInstanceContainer, file_name)
  400. elif instance_type == "quality" or instance_type == "quality_changes":
  401. path = Resources.getStoragePath(self.ResourceTypes.QualityInstanceContainer, file_name)
  402. elif instance_type == "user":
  403. path = Resources.getStoragePath(self.ResourceTypes.UserInstanceContainer, file_name)
  404. elif instance_type == "variant":
  405. path = Resources.getStoragePath(self.ResourceTypes.VariantInstanceContainer, file_name)
  406. elif instance_type == "definition_changes":
  407. path = Resources.getStoragePath(self.ResourceTypes.DefinitionChangesContainer, file_name)
  408. if path:
  409. instance.setPath(path)
  410. with SaveFile(path, "wt") as f:
  411. f.write(data)
  412. for stack in ContainerRegistry.getInstance().findContainerStacks():
  413. self.saveStack(stack)
  414. def saveStack(self, stack):
  415. if not stack.isDirty():
  416. return
  417. try:
  418. data = stack.serialize()
  419. except NotImplementedError:
  420. return
  421. except Exception:
  422. Logger.logException("e", "An exception occurred when serializing container %s", stack.getId())
  423. return
  424. mime_type = ContainerRegistry.getMimeTypeForContainer(type(stack))
  425. file_name = urllib.parse.quote_plus(stack.getId()) + "." + mime_type.preferredSuffix
  426. path = None
  427. if isinstance(stack, GlobalStack):
  428. path = Resources.getStoragePath(self.ResourceTypes.MachineStack, file_name)
  429. elif isinstance(stack, ExtruderStack):
  430. path = Resources.getStoragePath(self.ResourceTypes.ExtruderStack, file_name)
  431. else:
  432. path = Resources.getStoragePath(Resources.ContainerStacks, file_name)
  433. stack.setPath(path)
  434. with SaveFile(path, "wt") as f:
  435. f.write(data)
  436. @pyqtSlot(str, result = QUrl)
  437. def getDefaultPath(self, key):
  438. default_path = Preferences.getInstance().getValue("local_file/%s" % key)
  439. return QUrl.fromLocalFile(default_path)
  440. @pyqtSlot(str, str)
  441. def setDefaultPath(self, key, default_path):
  442. Preferences.getInstance().setValue("local_file/%s" % key, QUrl(default_path).toLocalFile())
  443. @classmethod
  444. def getStaticVersion(cls):
  445. return CuraVersion
  446. ## Handle loading of all plugin types (and the backend explicitly)
  447. # \sa PluginRegistery
  448. def _loadPlugins(self):
  449. self._plugin_registry.addType("profile_reader", self._addProfileReader)
  450. self._plugin_registry.addType("profile_writer", self._addProfileWriter)
  451. self._plugin_registry.addPluginLocation(os.path.join(QtApplication.getInstallPrefix(), "lib", "cura"))
  452. if not hasattr(sys, "frozen"):
  453. self._plugin_registry.addPluginLocation(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "plugins"))
  454. self._plugin_registry.loadPlugin("ConsoleLogger")
  455. self._plugin_registry.loadPlugin("CuraEngineBackend")
  456. self._plugin_registry.loadPlugins()
  457. if self.getBackend() is None:
  458. raise RuntimeError("Could not load the backend plugin!")
  459. self._plugins_loaded = True
  460. @classmethod
  461. def addCommandLineOptions(self, parser):
  462. super().addCommandLineOptions(parser)
  463. parser.add_argument("file", nargs="*", help="Files to load after starting the application.")
  464. parser.add_argument("--single-instance", action="store_true", default=False)
  465. # Set up a local socket server which listener which coordinates single instances Curas and accepts commands.
  466. def _setUpSingleInstanceServer(self):
  467. if self.getCommandLineOption("single_instance", False):
  468. self.__single_instance_server = QLocalServer()
  469. self.__single_instance_server.newConnection.connect(self._singleInstanceServerNewConnection)
  470. self.__single_instance_server.listen("ultimaker-cura")
  471. def _singleInstanceServerNewConnection(self):
  472. Logger.log("i", "New connection recevied on our single-instance server")
  473. remote_cura_connection = self.__single_instance_server.nextPendingConnection()
  474. if remote_cura_connection is not None:
  475. def readCommands():
  476. line = remote_cura_connection.readLine()
  477. while len(line) != 0: # There is also a .canReadLine()
  478. try:
  479. payload = json.loads(str(line, encoding="ASCII").strip())
  480. command = payload["command"]
  481. # Command: Remove all models from the build plate.
  482. if command == "clear-all":
  483. self.deleteAll()
  484. # Command: Load a model file
  485. elif command == "open":
  486. self._openFile(payload["filePath"])
  487. # WARNING ^ this method is async and we really should wait until
  488. # the file load is complete before processing more commands.
  489. # Command: Activate the window and bring it to the top.
  490. elif command == "focus":
  491. # Operating systems these days prevent windows from moving around by themselves.
  492. # 'alert' or flashing the icon in the taskbar is the best thing we do now.
  493. self.getMainWindow().alert(0)
  494. # Command: Close the socket connection. We're done.
  495. elif command == "close-connection":
  496. remote_cura_connection.close()
  497. else:
  498. Logger.log("w", "Received an unrecognized command " + str(command))
  499. except json.decoder.JSONDecodeError as ex:
  500. Logger.log("w", "Unable to parse JSON command in _singleInstanceServerNewConnection(): " + repr(ex))
  501. line = remote_cura_connection.readLine()
  502. remote_cura_connection.readyRead.connect(readCommands)
  503. ## Perform any checks before creating the main application.
  504. #
  505. # This should be called directly before creating an instance of CuraApplication.
  506. # \returns \type{bool} True if the whole Cura app should continue running.
  507. @classmethod
  508. def preStartUp(cls):
  509. # Peek the arguments and look for the 'single-instance' flag.
  510. parser = argparse.ArgumentParser(prog="cura") # pylint: disable=bad-whitespace
  511. CuraApplication.addCommandLineOptions(parser)
  512. parsed_command_line = vars(parser.parse_args())
  513. if "single_instance" in parsed_command_line and parsed_command_line["single_instance"]:
  514. Logger.log("i", "Checking for the presence of an ready running Cura instance.")
  515. single_instance_socket = QLocalSocket()
  516. Logger.log("d", "preStartUp(): full server name: " + single_instance_socket.fullServerName())
  517. single_instance_socket.connectToServer("ultimaker-cura")
  518. single_instance_socket.waitForConnected()
  519. if single_instance_socket.state() == QLocalSocket.ConnectedState:
  520. Logger.log("i", "Connection has been made to the single-instance Cura socket.")
  521. # Protocol is one line of JSON terminated with a carriage return.
  522. # "command" field is required and holds the name of the command to execute.
  523. # Other fields depend on the command.
  524. payload = {"command": "clear-all"}
  525. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  526. payload = {"command": "focus"}
  527. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  528. if len(parsed_command_line["file"]) != 0:
  529. for filename in parsed_command_line["file"]:
  530. payload = {"command": "open", "filePath": filename}
  531. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  532. payload = {"command": "close-connection"}
  533. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  534. single_instance_socket.flush()
  535. single_instance_socket.waitForDisconnected()
  536. return False
  537. return True
  538. def run(self):
  539. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Setting up scene..."))
  540. self._setUpSingleInstanceServer()
  541. controller = self.getController()
  542. controller.setActiveView("SolidView")
  543. controller.setCameraTool("CameraTool")
  544. controller.setSelectionTool("SelectionTool")
  545. t = controller.getTool("TranslateTool")
  546. if t:
  547. t.setEnabledAxis([ToolHandle.XAxis, ToolHandle.YAxis,ToolHandle.ZAxis])
  548. Selection.selectionChanged.connect(self.onSelectionChanged)
  549. root = controller.getScene().getRoot()
  550. # The platform is a child of BuildVolume
  551. self._volume = BuildVolume.BuildVolume(root)
  552. # Set the build volume of the arranger to the used build volume
  553. Arrange.build_volume = self._volume
  554. self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
  555. self._physics = PlatformPhysics.PlatformPhysics(controller, self._volume)
  556. camera = Camera("3d", root)
  557. camera.setPosition(Vector(-80, 250, 700))
  558. camera.setPerspective(True)
  559. camera.lookAt(Vector(0, 0, 0))
  560. controller.getScene().setActiveCamera("3d")
  561. camera_tool = self.getController().getTool("CameraTool")
  562. camera_tool.setOrigin(Vector(0, 100, 0))
  563. camera_tool.setZoomRange(0.1, 200000)
  564. self._camera_animation = CameraAnimation.CameraAnimation()
  565. self._camera_animation.setCameraTool(self.getController().getTool("CameraTool"))
  566. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading interface..."))
  567. # Initialise extruder so as to listen to global container stack changes before the first global container stack is set.
  568. ExtruderManager.getInstance()
  569. qmlRegisterSingletonType(MachineManager, "Cura", 1, 0, "MachineManager", self.getMachineManager)
  570. qmlRegisterSingletonType(MaterialManager, "Cura", 1, 0, "MaterialManager", self.getMaterialManager)
  571. qmlRegisterSingletonType(SettingInheritanceManager, "Cura", 1, 0, "SettingInheritanceManager",
  572. self.getSettingInheritanceManager)
  573. qmlRegisterSingletonType(SimpleModeSettingsManager, "Cura", 1, 2, "SimpleModeSettingsManager",
  574. self.getSimpleModeSettingsManager)
  575. qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, "MachineActionManager", self.getMachineActionManager)
  576. self.setMainQml(Resources.getPath(self.ResourceTypes.QmlFiles, "Cura.qml"))
  577. self._qml_import_paths.append(Resources.getPath(self.ResourceTypes.QmlFiles))
  578. self.initializeEngine()
  579. if self._engine.rootObjects:
  580. self.closeSplash()
  581. for file in self.getCommandLineOption("file", []):
  582. self._openFile(file)
  583. for file_name in self._open_file_queue: #Open all the files that were queued up while plug-ins were loading.
  584. self._openFile(file_name)
  585. self._started = True
  586. self.exec_()
  587. def getMachineManager(self, *args):
  588. if self._machine_manager is None:
  589. self._machine_manager = MachineManager.createMachineManager()
  590. return self._machine_manager
  591. def getMaterialManager(self, *args):
  592. if self._material_manager is None:
  593. self._material_manager = MaterialManager.createMaterialManager()
  594. return self._material_manager
  595. def getSettingInheritanceManager(self, *args):
  596. if self._setting_inheritance_manager is None:
  597. self._setting_inheritance_manager = SettingInheritanceManager.createSettingInheritanceManager()
  598. return self._setting_inheritance_manager
  599. ## Get the machine action manager
  600. # We ignore any *args given to this, as we also register the machine manager as qml singleton.
  601. # It wants to give this function an engine and script engine, but we don't care about that.
  602. def getMachineActionManager(self, *args):
  603. return self._machine_action_manager
  604. def getSimpleModeSettingsManager(self, *args):
  605. if self._simple_mode_settings_manager is None:
  606. self._simple_mode_settings_manager = SimpleModeSettingsManager()
  607. return self._simple_mode_settings_manager
  608. ## Handle Qt events
  609. def event(self, event):
  610. if event.type() == QEvent.FileOpen:
  611. if self._plugins_loaded:
  612. self._openFile(event.file())
  613. else:
  614. self._open_file_queue.append(event.file())
  615. return super().event(event)
  616. ## Get print information (duration / material used)
  617. def getPrintInformation(self):
  618. return self._print_information
  619. ## Registers objects for the QML engine to use.
  620. #
  621. # \param engine The QML engine.
  622. def registerObjects(self, engine):
  623. super().registerObjects(engine)
  624. engine.rootContext().setContextProperty("Printer", self)
  625. engine.rootContext().setContextProperty("CuraApplication", self)
  626. self._print_information = PrintInformation.PrintInformation()
  627. engine.rootContext().setContextProperty("PrintInformation", self._print_information)
  628. self._cura_actions = CuraActions.CuraActions(self)
  629. engine.rootContext().setContextProperty("CuraActions", self._cura_actions)
  630. qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")
  631. qmlRegisterType(ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")
  632. qmlRegisterType(ContainerSettingsModel, "Cura", 1, 0, "ContainerSettingsModel")
  633. qmlRegisterSingletonType(ProfilesModel, "Cura", 1, 0, "ProfilesModel", ProfilesModel.createProfilesModel)
  634. qmlRegisterType(MaterialsModel, "Cura", 1, 0, "MaterialsModel")
  635. qmlRegisterType(QualityAndUserProfilesModel, "Cura", 1, 0, "QualityAndUserProfilesModel")
  636. qmlRegisterType(UserProfilesModel, "Cura", 1, 0, "UserProfilesModel")
  637. qmlRegisterType(MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
  638. qmlRegisterType(QualitySettingsModel, "Cura", 1, 0, "QualitySettingsModel")
  639. qmlRegisterType(MachineNameValidator, "Cura", 1, 0, "MachineNameValidator")
  640. qmlRegisterType(UserChangesModel, "Cura", 1, 1, "UserChangesModel")
  641. qmlRegisterSingletonType(ContainerManager, "Cura", 1, 0, "ContainerManager", ContainerManager.createContainerManager)
  642. # As of Qt5.7, it is necessary to get rid of any ".." in the path for the singleton to work.
  643. actions_url = QUrl.fromLocalFile(os.path.abspath(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")))
  644. qmlRegisterSingletonType(actions_url, "Cura", 1, 0, "Actions")
  645. engine.rootContext().setContextProperty("ExtruderManager", ExtruderManager.getInstance())
  646. for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
  647. type_name = os.path.splitext(os.path.basename(path))[0]
  648. if type_name in ("Cura", "Actions"):
  649. continue
  650. # Ignore anything that is not a QML file.
  651. if not path.endswith(".qml"):
  652. continue
  653. qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
  654. def onSelectionChanged(self):
  655. if Selection.hasSelection():
  656. if self.getController().getActiveTool():
  657. # If the tool has been disabled by the new selection
  658. if not self.getController().getActiveTool().getEnabled():
  659. # Default
  660. self.getController().setActiveTool("TranslateTool")
  661. else:
  662. if self._previous_active_tool:
  663. self.getController().setActiveTool(self._previous_active_tool)
  664. if not self.getController().getActiveTool().getEnabled():
  665. self.getController().setActiveTool("TranslateTool")
  666. self._previous_active_tool = None
  667. else:
  668. # Default
  669. self.getController().setActiveTool("TranslateTool")
  670. if Preferences.getInstance().getValue("view/center_on_select"):
  671. self._center_after_select = True
  672. else:
  673. if self.getController().getActiveTool():
  674. self._previous_active_tool = self.getController().getActiveTool().getPluginId()
  675. self.getController().setActiveTool(None)
  676. def _onToolOperationStopped(self, event):
  677. if self._center_after_select and Selection.getSelectedObject(0) is not None:
  678. self._center_after_select = False
  679. self._camera_animation.setStart(self.getController().getTool("CameraTool").getOrigin())
  680. self._camera_animation.setTarget(Selection.getSelectedObject(0).getWorldPosition())
  681. self._camera_animation.start()
  682. def _onGlobalContainerChanged(self):
  683. if self._global_container_stack is not None:
  684. machine_file_formats = [file_type.strip() for file_type in self._global_container_stack.getMetaDataEntry("file_formats").split(";")]
  685. new_preferred_mimetype = ""
  686. if machine_file_formats:
  687. new_preferred_mimetype = machine_file_formats[0]
  688. if new_preferred_mimetype != self._preferred_mimetype:
  689. self._preferred_mimetype = new_preferred_mimetype
  690. self.preferredOutputMimetypeChanged.emit()
  691. requestAddPrinter = pyqtSignal()
  692. activityChanged = pyqtSignal()
  693. sceneBoundingBoxChanged = pyqtSignal()
  694. preferredOutputMimetypeChanged = pyqtSignal()
  695. @pyqtProperty(bool, notify = activityChanged)
  696. def platformActivity(self):
  697. return self._platform_activity
  698. @pyqtProperty(str, notify=preferredOutputMimetypeChanged)
  699. def preferredOutputMimetype(self):
  700. return self._preferred_mimetype
  701. @pyqtProperty(str, notify = sceneBoundingBoxChanged)
  702. def getSceneBoundingBoxString(self):
  703. return self._i18n_catalog.i18nc("@info 'width', 'depth' and 'height' are variable names that must NOT be translated; just translate the format of ##x##x## mm.", "%(width).1f x %(depth).1f x %(height).1f mm") % {'width' : self._scene_bounding_box.width.item(), 'depth': self._scene_bounding_box.depth.item(), 'height' : self._scene_bounding_box.height.item()}
  704. def updatePlatformActivity(self, node = None):
  705. count = 0
  706. scene_bounding_box = None
  707. is_block_slicing_node = False
  708. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  709. if type(node) is not SceneNode or (not node.getMeshData() and not node.callDecoration("getLayerData")):
  710. continue
  711. if node.callDecoration("isBlockSlicing"):
  712. is_block_slicing_node = True
  713. count += 1
  714. if not scene_bounding_box:
  715. scene_bounding_box = node.getBoundingBox()
  716. else:
  717. other_bb = node.getBoundingBox()
  718. if other_bb is not None:
  719. scene_bounding_box = scene_bounding_box + node.getBoundingBox()
  720. print_information = self.getPrintInformation()
  721. if print_information:
  722. print_information.setPreSliced(is_block_slicing_node)
  723. if not scene_bounding_box:
  724. scene_bounding_box = AxisAlignedBox.Null
  725. if repr(self._scene_bounding_box) != repr(scene_bounding_box) and scene_bounding_box.isValid():
  726. self._scene_bounding_box = scene_bounding_box
  727. self.sceneBoundingBoxChanged.emit()
  728. self._platform_activity = True if count > 0 else False
  729. self.activityChanged.emit()
  730. # Remove all selected objects from the scene.
  731. @pyqtSlot()
  732. @deprecated("Moved to CuraActions", "2.6")
  733. def deleteSelection(self):
  734. if not self.getController().getToolsEnabled():
  735. return
  736. removed_group_nodes = []
  737. op = GroupedOperation()
  738. nodes = Selection.getAllSelectedObjects()
  739. for node in nodes:
  740. op.addOperation(RemoveSceneNodeOperation(node))
  741. group_node = node.getParent()
  742. if group_node and group_node.callDecoration("isGroup") and group_node not in removed_group_nodes:
  743. remaining_nodes_in_group = list(set(group_node.getChildren()) - set(nodes))
  744. if len(remaining_nodes_in_group) == 1:
  745. removed_group_nodes.append(group_node)
  746. op.addOperation(SetParentOperation(remaining_nodes_in_group[0], group_node.getParent()))
  747. op.addOperation(RemoveSceneNodeOperation(group_node))
  748. op.push()
  749. ## Remove an object from the scene.
  750. # Note that this only removes an object if it is selected.
  751. @pyqtSlot("quint64")
  752. @deprecated("Use deleteSelection instead", "2.6")
  753. def deleteObject(self, object_id):
  754. if not self.getController().getToolsEnabled():
  755. return
  756. node = self.getController().getScene().findObject(object_id)
  757. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  758. node = Selection.getSelectedObject(0)
  759. if node:
  760. op = GroupedOperation()
  761. op.addOperation(RemoveSceneNodeOperation(node))
  762. group_node = node.getParent()
  763. if group_node:
  764. # Note that at this point the node has not yet been deleted
  765. if len(group_node.getChildren()) <= 2 and group_node.callDecoration("isGroup"):
  766. op.addOperation(SetParentOperation(group_node.getChildren()[0], group_node.getParent()))
  767. op.addOperation(RemoveSceneNodeOperation(group_node))
  768. op.push()
  769. ## Create a number of copies of existing object.
  770. # \param object_id
  771. # \param count number of copies
  772. # \param min_offset minimum offset to other objects.
  773. @pyqtSlot("quint64", int)
  774. @deprecated("Use CuraActions::multiplySelection", "2.6")
  775. def multiplyObject(self, object_id, count, min_offset = 8):
  776. node = self.getController().getScene().findObject(object_id)
  777. if not node:
  778. node = Selection.getSelectedObject(0)
  779. while node.getParent() and node.getParent().callDecoration("isGroup"):
  780. node = node.getParent()
  781. job = MultiplyObjectsJob([node], count, min_offset)
  782. job.start()
  783. return
  784. ## Center object on platform.
  785. @pyqtSlot("quint64")
  786. @deprecated("Use CuraActions::centerSelection", "2.6")
  787. def centerObject(self, object_id):
  788. node = self.getController().getScene().findObject(object_id)
  789. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  790. node = Selection.getSelectedObject(0)
  791. if not node:
  792. return
  793. if node.getParent() and node.getParent().callDecoration("isGroup"):
  794. node = node.getParent()
  795. if node:
  796. op = SetTransformOperation(node, Vector())
  797. op.push()
  798. ## Select all nodes containing mesh data in the scene.
  799. @pyqtSlot()
  800. def selectAll(self):
  801. if not self.getController().getToolsEnabled():
  802. return
  803. Selection.clear()
  804. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  805. if type(node) is not SceneNode:
  806. continue
  807. if not node.getMeshData() and not node.callDecoration("isGroup"):
  808. continue # Node that doesnt have a mesh and is not a group.
  809. if node.getParent() and node.getParent().callDecoration("isGroup"):
  810. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  811. if not node.isSelectable():
  812. continue # i.e. node with layer data
  813. Selection.add(node)
  814. ## Delete all nodes containing mesh data in the scene.
  815. @pyqtSlot()
  816. def deleteAll(self):
  817. Logger.log("i", "Clearing scene")
  818. if not self.getController().getToolsEnabled():
  819. return
  820. nodes = []
  821. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  822. if type(node) is not SceneNode:
  823. continue
  824. if (not node.getMeshData() and not node.callDecoration("getLayerData")) and not node.callDecoration("isGroup"):
  825. continue # Node that doesnt have a mesh and is not a group.
  826. if node.getParent() and node.getParent().callDecoration("isGroup"):
  827. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  828. nodes.append(node)
  829. if nodes:
  830. op = GroupedOperation()
  831. for node in nodes:
  832. op.addOperation(RemoveSceneNodeOperation(node))
  833. op.push()
  834. Selection.clear()
  835. ## Reset all translation on nodes with mesh data.
  836. @pyqtSlot()
  837. def resetAllTranslation(self):
  838. Logger.log("i", "Resetting all scene translations")
  839. nodes = []
  840. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  841. if type(node) is not SceneNode:
  842. continue
  843. if not node.getMeshData() and not node.callDecoration("isGroup"):
  844. continue # Node that doesnt have a mesh and is not a group.
  845. if node.getParent() and node.getParent().callDecoration("isGroup"):
  846. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  847. if not node.isSelectable():
  848. continue # i.e. node with layer data
  849. nodes.append(node)
  850. if nodes:
  851. op = GroupedOperation()
  852. for node in nodes:
  853. # Ensure that the object is above the build platform
  854. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  855. if node.getBoundingBox():
  856. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  857. else:
  858. center_y = 0
  859. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0)))
  860. op.push()
  861. ## Reset all transformations on nodes with mesh data.
  862. @pyqtSlot()
  863. def resetAll(self):
  864. Logger.log("i", "Resetting all scene transformations")
  865. nodes = []
  866. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  867. if type(node) is not SceneNode:
  868. continue
  869. if not node.getMeshData() and not node.callDecoration("isGroup"):
  870. continue # Node that doesnt have a mesh and is not a group.
  871. if node.getParent() and node.getParent().callDecoration("isGroup"):
  872. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  873. if not node.isSelectable():
  874. continue # i.e. node with layer data
  875. nodes.append(node)
  876. if nodes:
  877. op = GroupedOperation()
  878. for node in nodes:
  879. # Ensure that the object is above the build platform
  880. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  881. if node.getBoundingBox():
  882. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  883. else:
  884. center_y = 0
  885. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0), Quaternion(), Vector(1, 1, 1)))
  886. op.push()
  887. ## Arrange all objects.
  888. @pyqtSlot()
  889. def arrangeAll(self):
  890. nodes = []
  891. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  892. if type(node) is not SceneNode:
  893. continue
  894. if not node.getMeshData() and not node.callDecoration("isGroup"):
  895. continue # Node that doesnt have a mesh and is not a group.
  896. if node.getParent() and node.getParent().callDecoration("isGroup"):
  897. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  898. if not node.isSelectable():
  899. continue # i.e. node with layer data
  900. # Skip nodes that are too big
  901. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  902. nodes.append(node)
  903. self.arrange(nodes, fixed_nodes = [])
  904. ## Arrange Selection
  905. @pyqtSlot()
  906. def arrangeSelection(self):
  907. nodes = Selection.getAllSelectedObjects()
  908. # What nodes are on the build plate and are not being moved
  909. fixed_nodes = []
  910. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  911. if type(node) is not SceneNode:
  912. continue
  913. if not node.getMeshData() and not node.callDecoration("isGroup"):
  914. continue # Node that doesnt have a mesh and is not a group.
  915. if node.getParent() and node.getParent().callDecoration("isGroup"):
  916. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  917. if not node.isSelectable():
  918. continue # i.e. node with layer data
  919. if node in nodes: # exclude selected node from fixed_nodes
  920. continue
  921. fixed_nodes.append(node)
  922. self.arrange(nodes, fixed_nodes)
  923. ## Arrange a set of nodes given a set of fixed nodes
  924. # \param nodes nodes that we have to place
  925. # \param fixed_nodes nodes that are placed in the arranger before finding spots for nodes
  926. def arrange(self, nodes, fixed_nodes):
  927. job = ArrangeObjectsJob(nodes, fixed_nodes)
  928. job.start()
  929. ## Reload all mesh data on the screen from file.
  930. @pyqtSlot()
  931. def reloadAll(self):
  932. Logger.log("i", "Reloading all loaded mesh data.")
  933. nodes = []
  934. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  935. if type(node) is not SceneNode or not node.getMeshData():
  936. continue
  937. nodes.append(node)
  938. if not nodes:
  939. return
  940. for node in nodes:
  941. file_name = node.getMeshData().getFileName()
  942. if file_name:
  943. job = ReadMeshJob(file_name)
  944. job._node = node
  945. job.finished.connect(self._reloadMeshFinished)
  946. job.start()
  947. else:
  948. Logger.log("w", "Unable to reload data because we don't have a filename.")
  949. ## Get logging data of the backend engine
  950. # \returns \type{string} Logging data
  951. @pyqtSlot(result = str)
  952. def getEngineLog(self):
  953. log = ""
  954. for entry in self.getBackend().getLog():
  955. log += entry.decode()
  956. return log
  957. @pyqtSlot("QStringList")
  958. def setExpandedCategories(self, categories):
  959. categories = list(set(categories))
  960. categories.sort()
  961. joined = ";".join(categories)
  962. if joined != Preferences.getInstance().getValue("cura/categories_expanded"):
  963. Preferences.getInstance().setValue("cura/categories_expanded", joined)
  964. self.expandedCategoriesChanged.emit()
  965. expandedCategoriesChanged = pyqtSignal()
  966. @pyqtProperty("QStringList", notify = expandedCategoriesChanged)
  967. def expandedCategories(self):
  968. return Preferences.getInstance().getValue("cura/categories_expanded").split(";")
  969. @pyqtSlot()
  970. def mergeSelected(self):
  971. self.groupSelected()
  972. try:
  973. group_node = Selection.getAllSelectedObjects()[0]
  974. except Exception as e:
  975. Logger.log("d", "mergeSelected: Exception:", e)
  976. return
  977. meshes = [node.getMeshData() for node in group_node.getAllChildren() if node.getMeshData()]
  978. # Compute the center of the objects
  979. object_centers = []
  980. # Forget about the translation that the original objects have
  981. zero_translation = Matrix(data=numpy.zeros(3))
  982. for mesh, node in zip(meshes, group_node.getChildren()):
  983. transformation = node.getLocalTransformation()
  984. transformation.setTranslation(zero_translation)
  985. transformed_mesh = mesh.getTransformed(transformation)
  986. center = transformed_mesh.getCenterPosition()
  987. if center is not None:
  988. object_centers.append(center)
  989. if object_centers and len(object_centers) > 0:
  990. middle_x = sum([v.x for v in object_centers]) / len(object_centers)
  991. middle_y = sum([v.y for v in object_centers]) / len(object_centers)
  992. middle_z = sum([v.z for v in object_centers]) / len(object_centers)
  993. offset = Vector(middle_x, middle_y, middle_z)
  994. else:
  995. offset = Vector(0, 0, 0)
  996. # Move each node to the same position.
  997. for mesh, node in zip(meshes, group_node.getChildren()):
  998. transformation = node.getLocalTransformation()
  999. transformation.setTranslation(zero_translation)
  1000. transformed_mesh = mesh.getTransformed(transformation)
  1001. # Align the object around its zero position
  1002. # and also apply the offset to center it inside the group.
  1003. node.setPosition(-transformed_mesh.getZeroPosition() - offset)
  1004. # Use the previously found center of the group bounding box as the new location of the group
  1005. group_node.setPosition(group_node.getBoundingBox().center)
  1006. @pyqtSlot()
  1007. def groupSelected(self):
  1008. # Create a group-node
  1009. group_node = SceneNode()
  1010. group_decorator = GroupDecorator()
  1011. group_node.addDecorator(group_decorator)
  1012. group_node.addDecorator(ConvexHullDecorator())
  1013. group_node.setParent(self.getController().getScene().getRoot())
  1014. group_node.setSelectable(True)
  1015. center = Selection.getSelectionCenter()
  1016. group_node.setPosition(center)
  1017. group_node.setCenterPosition(center)
  1018. # Move selected nodes into the group-node
  1019. Selection.applyOperation(SetParentOperation, group_node)
  1020. # Deselect individual nodes and select the group-node instead
  1021. for node in group_node.getChildren():
  1022. Selection.remove(node)
  1023. Selection.add(group_node)
  1024. @pyqtSlot()
  1025. def ungroupSelected(self):
  1026. selected_objects = Selection.getAllSelectedObjects().copy()
  1027. for node in selected_objects:
  1028. if node.callDecoration("isGroup"):
  1029. op = GroupedOperation()
  1030. group_parent = node.getParent()
  1031. children = node.getChildren().copy()
  1032. for child in children:
  1033. # Set the parent of the children to the parent of the group-node
  1034. op.addOperation(SetParentOperation(child, group_parent))
  1035. # Add all individual nodes to the selection
  1036. Selection.add(child)
  1037. op.push()
  1038. # Note: The group removes itself from the scene once all its children have left it,
  1039. # see GroupDecorator._onChildrenChanged
  1040. def _createSplashScreen(self):
  1041. return CuraSplashScreen.CuraSplashScreen()
  1042. def _onActiveMachineChanged(self):
  1043. pass
  1044. fileLoaded = pyqtSignal(str)
  1045. def _reloadMeshFinished(self, job):
  1046. # TODO; This needs to be fixed properly. We now make the assumption that we only load a single mesh!
  1047. mesh_data = job.getResult()[0].getMeshData()
  1048. if mesh_data:
  1049. job._node.setMeshData(mesh_data)
  1050. else:
  1051. Logger.log("w", "Could not find a mesh in reloaded node.")
  1052. def _openFile(self, filename):
  1053. self.readLocalFile(QUrl.fromLocalFile(filename))
  1054. def _addProfileReader(self, profile_reader):
  1055. # TODO: Add the profile reader to the list of plug-ins that can be used when importing profiles.
  1056. pass
  1057. def _addProfileWriter(self, profile_writer):
  1058. pass
  1059. @pyqtSlot("QSize")
  1060. def setMinimumWindowSize(self, size):
  1061. self.getMainWindow().setMinimumSize(size)
  1062. def getBuildVolume(self):
  1063. return self._volume
  1064. additionalComponentsChanged = pyqtSignal(str, arguments = ["areaId"])
  1065. @pyqtProperty("QVariantMap", notify = additionalComponentsChanged)
  1066. def additionalComponents(self):
  1067. return self._additional_components
  1068. ## Add a component to a list of components to be reparented to another area in the GUI.
  1069. # The actual reparenting is done by the area itself.
  1070. # \param area_id \type{str} Identifying name of the area to which the component should be reparented
  1071. # \param component \type{QQuickComponent} The component that should be reparented
  1072. @pyqtSlot(str, "QVariant")
  1073. def addAdditionalComponent(self, area_id, component):
  1074. if area_id not in self._additional_components:
  1075. self._additional_components[area_id] = []
  1076. self._additional_components[area_id].append(component)
  1077. self.additionalComponentsChanged.emit(area_id)
  1078. @pyqtSlot(str)
  1079. def log(self, msg):
  1080. Logger.log("d", msg)
  1081. @pyqtSlot(QUrl)
  1082. def readLocalFile(self, file):
  1083. if not file.isValid():
  1084. return
  1085. scene = self.getController().getScene()
  1086. for node in DepthFirstIterator(scene.getRoot()):
  1087. if node.callDecoration("isBlockSlicing"):
  1088. self.deleteAll()
  1089. break
  1090. f = file.toLocalFile()
  1091. extension = os.path.splitext(f)[1]
  1092. filename = os.path.basename(f)
  1093. if len(self._currently_loading_files) > 0:
  1094. # If a non-slicable file is already being loaded, we prevent loading of any further non-slicable files
  1095. if extension.lower() in self._non_sliceable_extensions:
  1096. message = Message(
  1097. self._i18n_catalog.i18nc("@info:status",
  1098. "Only one G-code file can be loaded at a time. Skipped importing {0}",
  1099. filename), title = self._i18n_catalog.i18nc("@info:title", "Warning"))
  1100. message.show()
  1101. return
  1102. # If file being loaded is non-slicable file, then prevent loading of any other files
  1103. extension = os.path.splitext(self._currently_loading_files[0])[1]
  1104. if extension.lower() in self._non_sliceable_extensions:
  1105. message = Message(
  1106. self._i18n_catalog.i18nc("@info:status",
  1107. "Can't open any other file if G-code is loading. Skipped importing {0}",
  1108. filename), title = self._i18n_catalog.i18nc("@info:title", "Error"))
  1109. message.show()
  1110. return
  1111. self._currently_loading_files.append(f)
  1112. if extension in self._non_sliceable_extensions:
  1113. self.deleteAll()
  1114. job = ReadMeshJob(f)
  1115. job.finished.connect(self._readMeshFinished)
  1116. job.start()
  1117. def _readMeshFinished(self, job):
  1118. nodes = job.getResult()
  1119. filename = job.getFileName()
  1120. self._currently_loading_files.remove(filename)
  1121. root = self.getController().getScene().getRoot()
  1122. arranger = Arrange.create(scene_root = root)
  1123. min_offset = 8
  1124. self.fileLoaded.emit(filename)
  1125. for node in nodes:
  1126. node.setSelectable(True)
  1127. node.setName(os.path.basename(filename))
  1128. extension = os.path.splitext(filename)[1]
  1129. if extension.lower() in self._non_sliceable_extensions:
  1130. self.getController().setActiveView("LayerView")
  1131. view = self.getController().getActiveView()
  1132. view.resetLayerData()
  1133. view.setLayer(9999999)
  1134. view.calculateMaxLayers()
  1135. block_slicing_decorator = BlockSlicingDecorator()
  1136. node.addDecorator(block_slicing_decorator)
  1137. else:
  1138. sliceable_decorator = SliceableObjectDecorator()
  1139. node.addDecorator(sliceable_decorator)
  1140. scene = self.getController().getScene()
  1141. # If there is no convex hull for the node, start calculating it and continue.
  1142. if not node.getDecorator(ConvexHullDecorator):
  1143. node.addDecorator(ConvexHullDecorator())
  1144. for child in node.getAllChildren():
  1145. if not child.getDecorator(ConvexHullDecorator):
  1146. child.addDecorator(ConvexHullDecorator())
  1147. if node.callDecoration("isSliceable"):
  1148. # Only check position if it's not already blatantly obvious that it won't fit.
  1149. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1150. # Find node location
  1151. offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = min_offset)
  1152. # If a model is to small then it will not contain any points
  1153. if offset_shape_arr is None and hull_shape_arr is None:
  1154. Message(self._i18n_catalog.i18nc("@info:status", "The selected model was too small to load."),
  1155. title=self._i18n_catalog.i18nc("@info:title", "Warning")).show()
  1156. return
  1157. # Step is for skipping tests to make it a lot faster. it also makes the outcome somewhat rougher
  1158. node, _ = arranger.findNodePlacement(node, offset_shape_arr, hull_shape_arr, step = 10)
  1159. op = AddSceneNodeOperation(node, scene.getRoot())
  1160. op.push()
  1161. scene.sceneChanged.emit(node)
  1162. def addNonSliceableExtension(self, extension):
  1163. self._non_sliceable_extensions.append(extension)
  1164. @pyqtSlot(str, result=bool)
  1165. def checkIsValidProjectFile(self, file_url):
  1166. """
  1167. Checks if the given file URL is a valid project file.
  1168. """
  1169. try:
  1170. file_path = QUrl(file_url).toLocalFile()
  1171. workspace_reader = self.getWorkspaceFileHandler().getReaderForFile(file_path)
  1172. if workspace_reader is None:
  1173. return False # non-project files won't get a reader
  1174. result = workspace_reader.preRead(file_path, show_dialog=False)
  1175. return result == WorkspaceReader.PreReadResult.accepted
  1176. except Exception as e:
  1177. Logger.log("e", "Could not check file %s: %s", file_url, e)
  1178. return False
  1179. def _onContextMenuRequested(self, x: float, y: float) -> None:
  1180. # Ensure we select the object if we request a context menu over an object without having a selection.
  1181. if not Selection.hasSelection():
  1182. node = self.getController().getScene().findObject(self.getRenderer().getRenderPass("selection").getIdAtPosition(x, y))
  1183. if node:
  1184. while(node.getParent() and node.getParent().callDecoration("isGroup")):
  1185. node = node.getParent()
  1186. Selection.add(node)