CuraApplication.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  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. @pyqtSlot(str)
  348. def discardOrKeepProfileChangesClosed(self, option):
  349. if option == "discard":
  350. global_stack = self.getGlobalContainerStack()
  351. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  352. extruder.getTop().clear()
  353. global_stack.getTop().clear()
  354. # if the user decided to keep settings then the user settings should be re-calculated and validated for errors
  355. # before slicing. To ensure that slicer uses right settings values
  356. elif option == "keep":
  357. global_stack = self.getGlobalContainerStack()
  358. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  359. user_extruder_container = extruder.getTop()
  360. if user_extruder_container:
  361. user_extruder_container.update()
  362. user_global_container = global_stack.getTop()
  363. if user_global_container:
  364. user_global_container.update()
  365. # notify listeners that quality has changed (after user selected discard or keep)
  366. self.getMachineManager().activeQualityChanged.emit()
  367. @pyqtSlot(int)
  368. def messageBoxClosed(self, button):
  369. if self._message_box_callback:
  370. self._message_box_callback(button, *self._message_box_callback_arguments)
  371. self._message_box_callback = None
  372. self._message_box_callback_arguments = []
  373. showPrintMonitor = pyqtSignal(bool, arguments = ["show"])
  374. ## Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
  375. #
  376. # Note that the AutoSave plugin also calls this method.
  377. def saveSettings(self):
  378. if not self._started: # Do not do saving during application start
  379. return
  380. # Lock file for "more" atomically loading and saving to/from config dir.
  381. with ContainerRegistry.getInstance().lockFile():
  382. for instance in ContainerRegistry.getInstance().findInstanceContainers():
  383. if not instance.isDirty():
  384. continue
  385. try:
  386. data = instance.serialize()
  387. except NotImplementedError:
  388. continue
  389. except Exception:
  390. Logger.logException("e", "An exception occurred when serializing container %s", instance.getId())
  391. continue
  392. mime_type = ContainerRegistry.getMimeTypeForContainer(type(instance))
  393. file_name = urllib.parse.quote_plus(instance.getId()) + "." + mime_type.preferredSuffix
  394. instance_type = instance.getMetaDataEntry("type")
  395. path = None
  396. if instance_type == "material":
  397. path = Resources.getStoragePath(self.ResourceTypes.MaterialInstanceContainer, file_name)
  398. elif instance_type == "quality" or instance_type == "quality_changes":
  399. path = Resources.getStoragePath(self.ResourceTypes.QualityInstanceContainer, file_name)
  400. elif instance_type == "user":
  401. path = Resources.getStoragePath(self.ResourceTypes.UserInstanceContainer, file_name)
  402. elif instance_type == "variant":
  403. path = Resources.getStoragePath(self.ResourceTypes.VariantInstanceContainer, file_name)
  404. elif instance_type == "definition_changes":
  405. path = Resources.getStoragePath(self.ResourceTypes.DefinitionChangesContainer, file_name)
  406. if path:
  407. instance.setPath(path)
  408. with SaveFile(path, "wt") as f:
  409. f.write(data)
  410. for stack in ContainerRegistry.getInstance().findContainerStacks():
  411. self.saveStack(stack)
  412. def saveStack(self, stack):
  413. if not stack.isDirty():
  414. return
  415. try:
  416. data = stack.serialize()
  417. except NotImplementedError:
  418. return
  419. except Exception:
  420. Logger.logException("e", "An exception occurred when serializing container %s", stack.getId())
  421. return
  422. mime_type = ContainerRegistry.getMimeTypeForContainer(type(stack))
  423. file_name = urllib.parse.quote_plus(stack.getId()) + "." + mime_type.preferredSuffix
  424. path = None
  425. if isinstance(stack, GlobalStack):
  426. path = Resources.getStoragePath(self.ResourceTypes.MachineStack, file_name)
  427. elif isinstance(stack, ExtruderStack):
  428. path = Resources.getStoragePath(self.ResourceTypes.ExtruderStack, file_name)
  429. else:
  430. path = Resources.getStoragePath(Resources.ContainerStacks, file_name)
  431. stack.setPath(path)
  432. with SaveFile(path, "wt") as f:
  433. f.write(data)
  434. @pyqtSlot(str, result = QUrl)
  435. def getDefaultPath(self, key):
  436. default_path = Preferences.getInstance().getValue("local_file/%s" % key)
  437. return QUrl.fromLocalFile(default_path)
  438. @pyqtSlot(str, str)
  439. def setDefaultPath(self, key, default_path):
  440. Preferences.getInstance().setValue("local_file/%s" % key, QUrl(default_path).toLocalFile())
  441. @classmethod
  442. def getStaticVersion(cls):
  443. return CuraVersion
  444. ## Handle loading of all plugin types (and the backend explicitly)
  445. # \sa PluginRegistery
  446. def _loadPlugins(self):
  447. self._plugin_registry.addType("profile_reader", self._addProfileReader)
  448. self._plugin_registry.addType("profile_writer", self._addProfileWriter)
  449. self._plugin_registry.addPluginLocation(os.path.join(QtApplication.getInstallPrefix(), "lib", "cura"))
  450. if not hasattr(sys, "frozen"):
  451. self._plugin_registry.addPluginLocation(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "plugins"))
  452. self._plugin_registry.loadPlugin("ConsoleLogger")
  453. self._plugin_registry.loadPlugin("CuraEngineBackend")
  454. self._plugin_registry.loadPlugins()
  455. if self.getBackend() is None:
  456. raise RuntimeError("Could not load the backend plugin!")
  457. self._plugins_loaded = True
  458. @classmethod
  459. def addCommandLineOptions(self, parser):
  460. super().addCommandLineOptions(parser)
  461. parser.add_argument("file", nargs="*", help="Files to load after starting the application.")
  462. parser.add_argument("--single-instance", action="store_true", default=False)
  463. # Set up a local socket server which listener which coordinates single instances Curas and accepts commands.
  464. def _setUpSingleInstanceServer(self):
  465. if self.getCommandLineOption("single_instance", False):
  466. self.__single_instance_server = QLocalServer()
  467. self.__single_instance_server.newConnection.connect(self._singleInstanceServerNewConnection)
  468. self.__single_instance_server.listen("ultimaker-cura")
  469. def _singleInstanceServerNewConnection(self):
  470. Logger.log("i", "New connection recevied on our single-instance server")
  471. remote_cura_connection = self.__single_instance_server.nextPendingConnection()
  472. if remote_cura_connection is not None:
  473. def readCommands():
  474. line = remote_cura_connection.readLine()
  475. while len(line) != 0: # There is also a .canReadLine()
  476. try:
  477. payload = json.loads(str(line, encoding="ASCII").strip())
  478. command = payload["command"]
  479. # Command: Remove all models from the build plate.
  480. if command == "clear-all":
  481. self.deleteAll()
  482. # Command: Load a model file
  483. elif command == "open":
  484. self._openFile(payload["filePath"])
  485. # WARNING ^ this method is async and we really should wait until
  486. # the file load is complete before processing more commands.
  487. # Command: Activate the window and bring it to the top.
  488. elif command == "focus":
  489. # Operating systems these days prevent windows from moving around by themselves.
  490. # 'alert' or flashing the icon in the taskbar is the best thing we do now.
  491. self.getMainWindow().alert(0)
  492. # Command: Close the socket connection. We're done.
  493. elif command == "close-connection":
  494. remote_cura_connection.close()
  495. else:
  496. Logger.log("w", "Received an unrecognized command " + str(command))
  497. except json.decoder.JSONDecodeError as ex:
  498. Logger.log("w", "Unable to parse JSON command in _singleInstanceServerNewConnection(): " + repr(ex))
  499. line = remote_cura_connection.readLine()
  500. remote_cura_connection.readyRead.connect(readCommands)
  501. ## Perform any checks before creating the main application.
  502. #
  503. # This should be called directly before creating an instance of CuraApplication.
  504. # \returns \type{bool} True if the whole Cura app should continue running.
  505. @classmethod
  506. def preStartUp(cls):
  507. # Peek the arguments and look for the 'single-instance' flag.
  508. parser = argparse.ArgumentParser(prog="cura") # pylint: disable=bad-whitespace
  509. CuraApplication.addCommandLineOptions(parser)
  510. parsed_command_line = vars(parser.parse_args())
  511. if "single_instance" in parsed_command_line and parsed_command_line["single_instance"]:
  512. Logger.log("i", "Checking for the presence of an ready running Cura instance.")
  513. single_instance_socket = QLocalSocket()
  514. Logger.log("d", "preStartUp(): full server name: " + single_instance_socket.fullServerName())
  515. single_instance_socket.connectToServer("ultimaker-cura")
  516. single_instance_socket.waitForConnected()
  517. if single_instance_socket.state() == QLocalSocket.ConnectedState:
  518. Logger.log("i", "Connection has been made to the single-instance Cura socket.")
  519. # Protocol is one line of JSON terminated with a carriage return.
  520. # "command" field is required and holds the name of the command to execute.
  521. # Other fields depend on the command.
  522. payload = {"command": "clear-all"}
  523. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  524. payload = {"command": "focus"}
  525. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  526. if len(parsed_command_line["file"]) != 0:
  527. for filename in parsed_command_line["file"]:
  528. payload = {"command": "open", "filePath": filename}
  529. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  530. payload = {"command": "close-connection"}
  531. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  532. single_instance_socket.flush()
  533. single_instance_socket.waitForDisconnected()
  534. return False
  535. return True
  536. def run(self):
  537. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Setting up scene..."))
  538. self._setUpSingleInstanceServer()
  539. controller = self.getController()
  540. controller.setActiveView("SolidView")
  541. controller.setCameraTool("CameraTool")
  542. controller.setSelectionTool("SelectionTool")
  543. t = controller.getTool("TranslateTool")
  544. if t:
  545. t.setEnabledAxis([ToolHandle.XAxis, ToolHandle.YAxis,ToolHandle.ZAxis])
  546. Selection.selectionChanged.connect(self.onSelectionChanged)
  547. root = controller.getScene().getRoot()
  548. # The platform is a child of BuildVolume
  549. self._volume = BuildVolume.BuildVolume(root)
  550. # Set the build volume of the arranger to the used build volume
  551. Arrange.build_volume = self._volume
  552. self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
  553. self._physics = PlatformPhysics.PlatformPhysics(controller, self._volume)
  554. camera = Camera("3d", root)
  555. camera.setPosition(Vector(-80, 250, 700))
  556. camera.setPerspective(True)
  557. camera.lookAt(Vector(0, 0, 0))
  558. controller.getScene().setActiveCamera("3d")
  559. camera_tool = self.getController().getTool("CameraTool")
  560. camera_tool.setOrigin(Vector(0, 100, 0))
  561. camera_tool.setZoomRange(0.1, 200000)
  562. self._camera_animation = CameraAnimation.CameraAnimation()
  563. self._camera_animation.setCameraTool(self.getController().getTool("CameraTool"))
  564. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading interface..."))
  565. # Initialise extruder so as to listen to global container stack changes before the first global container stack is set.
  566. ExtruderManager.getInstance()
  567. qmlRegisterSingletonType(MachineManager, "Cura", 1, 0, "MachineManager", self.getMachineManager)
  568. qmlRegisterSingletonType(MaterialManager, "Cura", 1, 0, "MaterialManager", self.getMaterialManager)
  569. qmlRegisterSingletonType(SettingInheritanceManager, "Cura", 1, 0, "SettingInheritanceManager",
  570. self.getSettingInheritanceManager)
  571. qmlRegisterSingletonType(SimpleModeSettingsManager, "Cura", 1, 2, "SimpleModeSettingsManager",
  572. self.getSimpleModeSettingsManager)
  573. qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, "MachineActionManager", self.getMachineActionManager)
  574. self.setMainQml(Resources.getPath(self.ResourceTypes.QmlFiles, "Cura.qml"))
  575. self._qml_import_paths.append(Resources.getPath(self.ResourceTypes.QmlFiles))
  576. self.initializeEngine()
  577. if self._engine.rootObjects:
  578. self.closeSplash()
  579. for file in self.getCommandLineOption("file", []):
  580. self._openFile(file)
  581. for file_name in self._open_file_queue: #Open all the files that were queued up while plug-ins were loading.
  582. self._openFile(file_name)
  583. self._started = True
  584. self.exec_()
  585. def getMachineManager(self, *args):
  586. if self._machine_manager is None:
  587. self._machine_manager = MachineManager.createMachineManager()
  588. return self._machine_manager
  589. def getMaterialManager(self, *args):
  590. if self._material_manager is None:
  591. self._material_manager = MaterialManager.createMaterialManager()
  592. return self._material_manager
  593. def getSettingInheritanceManager(self, *args):
  594. if self._setting_inheritance_manager is None:
  595. self._setting_inheritance_manager = SettingInheritanceManager.createSettingInheritanceManager()
  596. return self._setting_inheritance_manager
  597. ## Get the machine action manager
  598. # We ignore any *args given to this, as we also register the machine manager as qml singleton.
  599. # It wants to give this function an engine and script engine, but we don't care about that.
  600. def getMachineActionManager(self, *args):
  601. return self._machine_action_manager
  602. def getSimpleModeSettingsManager(self, *args):
  603. if self._simple_mode_settings_manager is None:
  604. self._simple_mode_settings_manager = SimpleModeSettingsManager()
  605. return self._simple_mode_settings_manager
  606. ## Handle Qt events
  607. def event(self, event):
  608. if event.type() == QEvent.FileOpen:
  609. if self._plugins_loaded:
  610. self._openFile(event.file())
  611. else:
  612. self._open_file_queue.append(event.file())
  613. return super().event(event)
  614. ## Get print information (duration / material used)
  615. def getPrintInformation(self):
  616. return self._print_information
  617. ## Registers objects for the QML engine to use.
  618. #
  619. # \param engine The QML engine.
  620. def registerObjects(self, engine):
  621. super().registerObjects(engine)
  622. engine.rootContext().setContextProperty("Printer", self)
  623. engine.rootContext().setContextProperty("CuraApplication", self)
  624. self._print_information = PrintInformation.PrintInformation()
  625. engine.rootContext().setContextProperty("PrintInformation", self._print_information)
  626. self._cura_actions = CuraActions.CuraActions(self)
  627. engine.rootContext().setContextProperty("CuraActions", self._cura_actions)
  628. qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")
  629. qmlRegisterType(ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")
  630. qmlRegisterType(ContainerSettingsModel, "Cura", 1, 0, "ContainerSettingsModel")
  631. qmlRegisterSingletonType(ProfilesModel, "Cura", 1, 0, "ProfilesModel", ProfilesModel.createProfilesModel)
  632. qmlRegisterType(MaterialsModel, "Cura", 1, 0, "MaterialsModel")
  633. qmlRegisterType(QualityAndUserProfilesModel, "Cura", 1, 0, "QualityAndUserProfilesModel")
  634. qmlRegisterType(UserProfilesModel, "Cura", 1, 0, "UserProfilesModel")
  635. qmlRegisterType(MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
  636. qmlRegisterType(QualitySettingsModel, "Cura", 1, 0, "QualitySettingsModel")
  637. qmlRegisterType(MachineNameValidator, "Cura", 1, 0, "MachineNameValidator")
  638. qmlRegisterType(UserChangesModel, "Cura", 1, 1, "UserChangesModel")
  639. qmlRegisterSingletonType(ContainerManager, "Cura", 1, 0, "ContainerManager", ContainerManager.createContainerManager)
  640. # As of Qt5.7, it is necessary to get rid of any ".." in the path for the singleton to work.
  641. actions_url = QUrl.fromLocalFile(os.path.abspath(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")))
  642. qmlRegisterSingletonType(actions_url, "Cura", 1, 0, "Actions")
  643. engine.rootContext().setContextProperty("ExtruderManager", ExtruderManager.getInstance())
  644. for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
  645. type_name = os.path.splitext(os.path.basename(path))[0]
  646. if type_name in ("Cura", "Actions"):
  647. continue
  648. # Ignore anything that is not a QML file.
  649. if not path.endswith(".qml"):
  650. continue
  651. qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
  652. def onSelectionChanged(self):
  653. if Selection.hasSelection():
  654. if self.getController().getActiveTool():
  655. # If the tool has been disabled by the new selection
  656. if not self.getController().getActiveTool().getEnabled():
  657. # Default
  658. self.getController().setActiveTool("TranslateTool")
  659. else:
  660. if self._previous_active_tool:
  661. self.getController().setActiveTool(self._previous_active_tool)
  662. if not self.getController().getActiveTool().getEnabled():
  663. self.getController().setActiveTool("TranslateTool")
  664. self._previous_active_tool = None
  665. else:
  666. # Default
  667. self.getController().setActiveTool("TranslateTool")
  668. if Preferences.getInstance().getValue("view/center_on_select"):
  669. self._center_after_select = True
  670. else:
  671. if self.getController().getActiveTool():
  672. self._previous_active_tool = self.getController().getActiveTool().getPluginId()
  673. self.getController().setActiveTool(None)
  674. def _onToolOperationStopped(self, event):
  675. if self._center_after_select and Selection.getSelectedObject(0) is not None:
  676. self._center_after_select = False
  677. self._camera_animation.setStart(self.getController().getTool("CameraTool").getOrigin())
  678. self._camera_animation.setTarget(Selection.getSelectedObject(0).getWorldPosition())
  679. self._camera_animation.start()
  680. def _onGlobalContainerChanged(self):
  681. if self._global_container_stack is not None:
  682. machine_file_formats = [file_type.strip() for file_type in self._global_container_stack.getMetaDataEntry("file_formats").split(";")]
  683. new_preferred_mimetype = ""
  684. if machine_file_formats:
  685. new_preferred_mimetype = machine_file_formats[0]
  686. if new_preferred_mimetype != self._preferred_mimetype:
  687. self._preferred_mimetype = new_preferred_mimetype
  688. self.preferredOutputMimetypeChanged.emit()
  689. requestAddPrinter = pyqtSignal()
  690. activityChanged = pyqtSignal()
  691. sceneBoundingBoxChanged = pyqtSignal()
  692. preferredOutputMimetypeChanged = pyqtSignal()
  693. @pyqtProperty(bool, notify = activityChanged)
  694. def platformActivity(self):
  695. return self._platform_activity
  696. @pyqtProperty(str, notify=preferredOutputMimetypeChanged)
  697. def preferredOutputMimetype(self):
  698. return self._preferred_mimetype
  699. @pyqtProperty(str, notify = sceneBoundingBoxChanged)
  700. def getSceneBoundingBoxString(self):
  701. 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()}
  702. def updatePlatformActivity(self, node = None):
  703. count = 0
  704. scene_bounding_box = None
  705. is_block_slicing_node = False
  706. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  707. if type(node) is not SceneNode or (not node.getMeshData() and not node.callDecoration("getLayerData")):
  708. continue
  709. if node.callDecoration("isBlockSlicing"):
  710. is_block_slicing_node = True
  711. count += 1
  712. if not scene_bounding_box:
  713. scene_bounding_box = node.getBoundingBox()
  714. else:
  715. other_bb = node.getBoundingBox()
  716. if other_bb is not None:
  717. scene_bounding_box = scene_bounding_box + node.getBoundingBox()
  718. print_information = self.getPrintInformation()
  719. if print_information:
  720. print_information.setPreSliced(is_block_slicing_node)
  721. if not scene_bounding_box:
  722. scene_bounding_box = AxisAlignedBox.Null
  723. if repr(self._scene_bounding_box) != repr(scene_bounding_box) and scene_bounding_box.isValid():
  724. self._scene_bounding_box = scene_bounding_box
  725. self.sceneBoundingBoxChanged.emit()
  726. self._platform_activity = True if count > 0 else False
  727. self.activityChanged.emit()
  728. # Remove all selected objects from the scene.
  729. @pyqtSlot()
  730. @deprecated("Moved to CuraActions", "2.6")
  731. def deleteSelection(self):
  732. if not self.getController().getToolsEnabled():
  733. return
  734. removed_group_nodes = []
  735. op = GroupedOperation()
  736. nodes = Selection.getAllSelectedObjects()
  737. for node in nodes:
  738. op.addOperation(RemoveSceneNodeOperation(node))
  739. group_node = node.getParent()
  740. if group_node and group_node.callDecoration("isGroup") and group_node not in removed_group_nodes:
  741. remaining_nodes_in_group = list(set(group_node.getChildren()) - set(nodes))
  742. if len(remaining_nodes_in_group) == 1:
  743. removed_group_nodes.append(group_node)
  744. op.addOperation(SetParentOperation(remaining_nodes_in_group[0], group_node.getParent()))
  745. op.addOperation(RemoveSceneNodeOperation(group_node))
  746. op.push()
  747. ## Remove an object from the scene.
  748. # Note that this only removes an object if it is selected.
  749. @pyqtSlot("quint64")
  750. @deprecated("Use deleteSelection instead", "2.6")
  751. def deleteObject(self, object_id):
  752. if not self.getController().getToolsEnabled():
  753. return
  754. node = self.getController().getScene().findObject(object_id)
  755. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  756. node = Selection.getSelectedObject(0)
  757. if node:
  758. op = GroupedOperation()
  759. op.addOperation(RemoveSceneNodeOperation(node))
  760. group_node = node.getParent()
  761. if group_node:
  762. # Note that at this point the node has not yet been deleted
  763. if len(group_node.getChildren()) <= 2 and group_node.callDecoration("isGroup"):
  764. op.addOperation(SetParentOperation(group_node.getChildren()[0], group_node.getParent()))
  765. op.addOperation(RemoveSceneNodeOperation(group_node))
  766. op.push()
  767. ## Create a number of copies of existing object.
  768. # \param object_id
  769. # \param count number of copies
  770. # \param min_offset minimum offset to other objects.
  771. @pyqtSlot("quint64", int)
  772. @deprecated("Use CuraActions::multiplySelection", "2.6")
  773. def multiplyObject(self, object_id, count, min_offset = 8):
  774. node = self.getController().getScene().findObject(object_id)
  775. if not node:
  776. node = Selection.getSelectedObject(0)
  777. while node.getParent() and node.getParent().callDecoration("isGroup"):
  778. node = node.getParent()
  779. job = MultiplyObjectsJob([node], count, min_offset)
  780. job.start()
  781. return
  782. ## Center object on platform.
  783. @pyqtSlot("quint64")
  784. @deprecated("Use CuraActions::centerSelection", "2.6")
  785. def centerObject(self, object_id):
  786. node = self.getController().getScene().findObject(object_id)
  787. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  788. node = Selection.getSelectedObject(0)
  789. if not node:
  790. return
  791. if node.getParent() and node.getParent().callDecoration("isGroup"):
  792. node = node.getParent()
  793. if node:
  794. op = SetTransformOperation(node, Vector())
  795. op.push()
  796. ## Select all nodes containing mesh data in the scene.
  797. @pyqtSlot()
  798. def selectAll(self):
  799. if not self.getController().getToolsEnabled():
  800. return
  801. Selection.clear()
  802. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  803. if type(node) is not SceneNode:
  804. continue
  805. if not node.getMeshData() and not node.callDecoration("isGroup"):
  806. continue # Node that doesnt have a mesh and is not a group.
  807. if node.getParent() and node.getParent().callDecoration("isGroup"):
  808. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  809. if not node.isSelectable():
  810. continue # i.e. node with layer data
  811. Selection.add(node)
  812. ## Delete all nodes containing mesh data in the scene.
  813. @pyqtSlot()
  814. def deleteAll(self):
  815. Logger.log("i", "Clearing scene")
  816. if not self.getController().getToolsEnabled():
  817. return
  818. nodes = []
  819. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  820. if type(node) is not SceneNode:
  821. continue
  822. if (not node.getMeshData() and not node.callDecoration("getLayerData")) and not node.callDecoration("isGroup"):
  823. continue # Node that doesnt have a mesh and is not a group.
  824. if node.getParent() and node.getParent().callDecoration("isGroup"):
  825. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  826. nodes.append(node)
  827. if nodes:
  828. op = GroupedOperation()
  829. for node in nodes:
  830. op.addOperation(RemoveSceneNodeOperation(node))
  831. op.push()
  832. Selection.clear()
  833. ## Reset all translation on nodes with mesh data.
  834. @pyqtSlot()
  835. def resetAllTranslation(self):
  836. Logger.log("i", "Resetting all scene translations")
  837. nodes = []
  838. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  839. if type(node) is not SceneNode:
  840. continue
  841. if not node.getMeshData() and not node.callDecoration("isGroup"):
  842. continue # Node that doesnt have a mesh and is not a group.
  843. if node.getParent() and node.getParent().callDecoration("isGroup"):
  844. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  845. if not node.isSelectable():
  846. continue # i.e. node with layer data
  847. nodes.append(node)
  848. if nodes:
  849. op = GroupedOperation()
  850. for node in nodes:
  851. # Ensure that the object is above the build platform
  852. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  853. if node.getBoundingBox():
  854. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  855. else:
  856. center_y = 0
  857. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0)))
  858. op.push()
  859. ## Reset all transformations on nodes with mesh data.
  860. @pyqtSlot()
  861. def resetAll(self):
  862. Logger.log("i", "Resetting all scene transformations")
  863. nodes = []
  864. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  865. if type(node) is not SceneNode:
  866. continue
  867. if not node.getMeshData() and not node.callDecoration("isGroup"):
  868. continue # Node that doesnt have a mesh and is not a group.
  869. if node.getParent() and node.getParent().callDecoration("isGroup"):
  870. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  871. if not node.isSelectable():
  872. continue # i.e. node with layer data
  873. nodes.append(node)
  874. if nodes:
  875. op = GroupedOperation()
  876. for node in nodes:
  877. # Ensure that the object is above the build platform
  878. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  879. if node.getBoundingBox():
  880. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  881. else:
  882. center_y = 0
  883. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0), Quaternion(), Vector(1, 1, 1)))
  884. op.push()
  885. ## Arrange all objects.
  886. @pyqtSlot()
  887. def arrangeAll(self):
  888. nodes = []
  889. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  890. if type(node) is not SceneNode:
  891. continue
  892. if not node.getMeshData() and not node.callDecoration("isGroup"):
  893. continue # Node that doesnt have a mesh and is not a group.
  894. if node.getParent() and node.getParent().callDecoration("isGroup"):
  895. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  896. if not node.isSelectable():
  897. continue # i.e. node with layer data
  898. # Skip nodes that are too big
  899. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  900. nodes.append(node)
  901. self.arrange(nodes, fixed_nodes = [])
  902. ## Arrange Selection
  903. @pyqtSlot()
  904. def arrangeSelection(self):
  905. nodes = Selection.getAllSelectedObjects()
  906. # What nodes are on the build plate and are not being moved
  907. fixed_nodes = []
  908. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  909. if type(node) is not SceneNode:
  910. continue
  911. if not node.getMeshData() and not node.callDecoration("isGroup"):
  912. continue # Node that doesnt have a mesh and is not a group.
  913. if node.getParent() and node.getParent().callDecoration("isGroup"):
  914. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  915. if not node.isSelectable():
  916. continue # i.e. node with layer data
  917. if node in nodes: # exclude selected node from fixed_nodes
  918. continue
  919. fixed_nodes.append(node)
  920. self.arrange(nodes, fixed_nodes)
  921. ## Arrange a set of nodes given a set of fixed nodes
  922. # \param nodes nodes that we have to place
  923. # \param fixed_nodes nodes that are placed in the arranger before finding spots for nodes
  924. def arrange(self, nodes, fixed_nodes):
  925. job = ArrangeObjectsJob(nodes, fixed_nodes)
  926. job.start()
  927. ## Reload all mesh data on the screen from file.
  928. @pyqtSlot()
  929. def reloadAll(self):
  930. Logger.log("i", "Reloading all loaded mesh data.")
  931. nodes = []
  932. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  933. if type(node) is not SceneNode or not node.getMeshData():
  934. continue
  935. nodes.append(node)
  936. if not nodes:
  937. return
  938. for node in nodes:
  939. file_name = node.getMeshData().getFileName()
  940. if file_name:
  941. job = ReadMeshJob(file_name)
  942. job._node = node
  943. job.finished.connect(self._reloadMeshFinished)
  944. job.start()
  945. else:
  946. Logger.log("w", "Unable to reload data because we don't have a filename.")
  947. ## Get logging data of the backend engine
  948. # \returns \type{string} Logging data
  949. @pyqtSlot(result = str)
  950. def getEngineLog(self):
  951. log = ""
  952. for entry in self.getBackend().getLog():
  953. log += entry.decode()
  954. return log
  955. @pyqtSlot("QStringList")
  956. def setExpandedCategories(self, categories):
  957. categories = list(set(categories))
  958. categories.sort()
  959. joined = ";".join(categories)
  960. if joined != Preferences.getInstance().getValue("cura/categories_expanded"):
  961. Preferences.getInstance().setValue("cura/categories_expanded", joined)
  962. self.expandedCategoriesChanged.emit()
  963. expandedCategoriesChanged = pyqtSignal()
  964. @pyqtProperty("QStringList", notify = expandedCategoriesChanged)
  965. def expandedCategories(self):
  966. return Preferences.getInstance().getValue("cura/categories_expanded").split(";")
  967. @pyqtSlot()
  968. def mergeSelected(self):
  969. self.groupSelected()
  970. try:
  971. group_node = Selection.getAllSelectedObjects()[0]
  972. except Exception as e:
  973. Logger.log("d", "mergeSelected: Exception:", e)
  974. return
  975. meshes = [node.getMeshData() for node in group_node.getAllChildren() if node.getMeshData()]
  976. # Compute the center of the objects
  977. object_centers = []
  978. # Forget about the translation that the original objects have
  979. zero_translation = Matrix(data=numpy.zeros(3))
  980. for mesh, node in zip(meshes, group_node.getChildren()):
  981. transformation = node.getLocalTransformation()
  982. transformation.setTranslation(zero_translation)
  983. transformed_mesh = mesh.getTransformed(transformation)
  984. center = transformed_mesh.getCenterPosition()
  985. if center is not None:
  986. object_centers.append(center)
  987. if object_centers and len(object_centers) > 0:
  988. middle_x = sum([v.x for v in object_centers]) / len(object_centers)
  989. middle_y = sum([v.y for v in object_centers]) / len(object_centers)
  990. middle_z = sum([v.z for v in object_centers]) / len(object_centers)
  991. offset = Vector(middle_x, middle_y, middle_z)
  992. else:
  993. offset = Vector(0, 0, 0)
  994. # Move each node to the same position.
  995. for mesh, node in zip(meshes, group_node.getChildren()):
  996. transformation = node.getLocalTransformation()
  997. transformation.setTranslation(zero_translation)
  998. transformed_mesh = mesh.getTransformed(transformation)
  999. # Align the object around its zero position
  1000. # and also apply the offset to center it inside the group.
  1001. node.setPosition(-transformed_mesh.getZeroPosition() - offset)
  1002. # Use the previously found center of the group bounding box as the new location of the group
  1003. group_node.setPosition(group_node.getBoundingBox().center)
  1004. @pyqtSlot()
  1005. def groupSelected(self):
  1006. # Create a group-node
  1007. group_node = SceneNode()
  1008. group_decorator = GroupDecorator()
  1009. group_node.addDecorator(group_decorator)
  1010. group_node.addDecorator(ConvexHullDecorator())
  1011. group_node.setParent(self.getController().getScene().getRoot())
  1012. group_node.setSelectable(True)
  1013. center = Selection.getSelectionCenter()
  1014. group_node.setPosition(center)
  1015. group_node.setCenterPosition(center)
  1016. # Move selected nodes into the group-node
  1017. Selection.applyOperation(SetParentOperation, group_node)
  1018. # Deselect individual nodes and select the group-node instead
  1019. for node in group_node.getChildren():
  1020. Selection.remove(node)
  1021. Selection.add(group_node)
  1022. @pyqtSlot()
  1023. def ungroupSelected(self):
  1024. selected_objects = Selection.getAllSelectedObjects().copy()
  1025. for node in selected_objects:
  1026. if node.callDecoration("isGroup"):
  1027. op = GroupedOperation()
  1028. group_parent = node.getParent()
  1029. children = node.getChildren().copy()
  1030. for child in children:
  1031. # Set the parent of the children to the parent of the group-node
  1032. op.addOperation(SetParentOperation(child, group_parent))
  1033. # Add all individual nodes to the selection
  1034. Selection.add(child)
  1035. op.push()
  1036. # Note: The group removes itself from the scene once all its children have left it,
  1037. # see GroupDecorator._onChildrenChanged
  1038. def _createSplashScreen(self):
  1039. return CuraSplashScreen.CuraSplashScreen()
  1040. def _onActiveMachineChanged(self):
  1041. pass
  1042. fileLoaded = pyqtSignal(str)
  1043. def _reloadMeshFinished(self, job):
  1044. # TODO; This needs to be fixed properly. We now make the assumption that we only load a single mesh!
  1045. mesh_data = job.getResult()[0].getMeshData()
  1046. if mesh_data:
  1047. job._node.setMeshData(mesh_data)
  1048. else:
  1049. Logger.log("w", "Could not find a mesh in reloaded node.")
  1050. def _openFile(self, filename):
  1051. self.readLocalFile(QUrl.fromLocalFile(filename))
  1052. def _addProfileReader(self, profile_reader):
  1053. # TODO: Add the profile reader to the list of plug-ins that can be used when importing profiles.
  1054. pass
  1055. def _addProfileWriter(self, profile_writer):
  1056. pass
  1057. @pyqtSlot("QSize")
  1058. def setMinimumWindowSize(self, size):
  1059. self.getMainWindow().setMinimumSize(size)
  1060. def getBuildVolume(self):
  1061. return self._volume
  1062. additionalComponentsChanged = pyqtSignal(str, arguments = ["areaId"])
  1063. @pyqtProperty("QVariantMap", notify = additionalComponentsChanged)
  1064. def additionalComponents(self):
  1065. return self._additional_components
  1066. ## Add a component to a list of components to be reparented to another area in the GUI.
  1067. # The actual reparenting is done by the area itself.
  1068. # \param area_id \type{str} Identifying name of the area to which the component should be reparented
  1069. # \param component \type{QQuickComponent} The component that should be reparented
  1070. @pyqtSlot(str, "QVariant")
  1071. def addAdditionalComponent(self, area_id, component):
  1072. if area_id not in self._additional_components:
  1073. self._additional_components[area_id] = []
  1074. self._additional_components[area_id].append(component)
  1075. self.additionalComponentsChanged.emit(area_id)
  1076. @pyqtSlot(str)
  1077. def log(self, msg):
  1078. Logger.log("d", msg)
  1079. @pyqtSlot(QUrl)
  1080. def readLocalFile(self, file):
  1081. if not file.isValid():
  1082. return
  1083. scene = self.getController().getScene()
  1084. for node in DepthFirstIterator(scene.getRoot()):
  1085. if node.callDecoration("isBlockSlicing"):
  1086. self.deleteAll()
  1087. break
  1088. f = file.toLocalFile()
  1089. extension = os.path.splitext(f)[1]
  1090. filename = os.path.basename(f)
  1091. if len(self._currently_loading_files) > 0:
  1092. # If a non-slicable file is already being loaded, we prevent loading of any further non-slicable files
  1093. if extension.lower() in self._non_sliceable_extensions:
  1094. message = Message(
  1095. self._i18n_catalog.i18nc("@info:status",
  1096. "Only one G-code file can be loaded at a time. Skipped importing {0}",
  1097. filename), title = self._i18n_catalog.i18nc("@info:title", "Warning"))
  1098. message.show()
  1099. return
  1100. # If file being loaded is non-slicable file, then prevent loading of any other files
  1101. extension = os.path.splitext(self._currently_loading_files[0])[1]
  1102. if extension.lower() in self._non_sliceable_extensions:
  1103. message = Message(
  1104. self._i18n_catalog.i18nc("@info:status",
  1105. "Can't open any other file if G-code is loading. Skipped importing {0}",
  1106. filename), title = self._i18n_catalog.i18nc("@info:title", "Error"))
  1107. message.show()
  1108. return
  1109. self._currently_loading_files.append(f)
  1110. if extension in self._non_sliceable_extensions:
  1111. self.deleteAll()
  1112. job = ReadMeshJob(f)
  1113. job.finished.connect(self._readMeshFinished)
  1114. job.start()
  1115. def _readMeshFinished(self, job):
  1116. nodes = job.getResult()
  1117. filename = job.getFileName()
  1118. self._currently_loading_files.remove(filename)
  1119. root = self.getController().getScene().getRoot()
  1120. arranger = Arrange.create(scene_root = root)
  1121. min_offset = 8
  1122. self.fileLoaded.emit(filename)
  1123. for node in nodes:
  1124. node.setSelectable(True)
  1125. node.setName(os.path.basename(filename))
  1126. extension = os.path.splitext(filename)[1]
  1127. if extension.lower() in self._non_sliceable_extensions:
  1128. self.getController().setActiveView("LayerView")
  1129. view = self.getController().getActiveView()
  1130. view.resetLayerData()
  1131. view.setLayer(9999999)
  1132. view.calculateMaxLayers()
  1133. block_slicing_decorator = BlockSlicingDecorator()
  1134. node.addDecorator(block_slicing_decorator)
  1135. else:
  1136. sliceable_decorator = SliceableObjectDecorator()
  1137. node.addDecorator(sliceable_decorator)
  1138. scene = self.getController().getScene()
  1139. # If there is no convex hull for the node, start calculating it and continue.
  1140. if not node.getDecorator(ConvexHullDecorator):
  1141. node.addDecorator(ConvexHullDecorator())
  1142. for child in node.getAllChildren():
  1143. if not child.getDecorator(ConvexHullDecorator):
  1144. child.addDecorator(ConvexHullDecorator())
  1145. if node.callDecoration("isSliceable"):
  1146. # Only check position if it's not already blatantly obvious that it won't fit.
  1147. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1148. # Find node location
  1149. offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = min_offset)
  1150. # If a model is to small then it will not contain any points
  1151. if offset_shape_arr is None and hull_shape_arr is None:
  1152. Message(self._i18n_catalog.i18nc("@info:status", "The selected model was too small to load."),
  1153. title=self._i18n_catalog.i18nc("@info:title", "Warning")).show()
  1154. return
  1155. # Step is for skipping tests to make it a lot faster. it also makes the outcome somewhat rougher
  1156. node, _ = arranger.findNodePlacement(node, offset_shape_arr, hull_shape_arr, step = 10)
  1157. op = AddSceneNodeOperation(node, scene.getRoot())
  1158. op.push()
  1159. scene.sceneChanged.emit(node)
  1160. def addNonSliceableExtension(self, extension):
  1161. self._non_sliceable_extensions.append(extension)
  1162. @pyqtSlot(str, result=bool)
  1163. def checkIsValidProjectFile(self, file_url):
  1164. """
  1165. Checks if the given file URL is a valid project file.
  1166. """
  1167. try:
  1168. file_path = QUrl(file_url).toLocalFile()
  1169. workspace_reader = self.getWorkspaceFileHandler().getReaderForFile(file_path)
  1170. if workspace_reader is None:
  1171. return False # non-project files won't get a reader
  1172. result = workspace_reader.preRead(file_path, show_dialog=False)
  1173. return result == WorkspaceReader.PreReadResult.accepted
  1174. except Exception as e:
  1175. Logger.log("e", "Could not check file %s: %s", file_url, e)
  1176. return False
  1177. def _onContextMenuRequested(self, x: float, y: float) -> None:
  1178. # Ensure we select the object if we request a context menu over an object without having a selection.
  1179. if not Selection.hasSelection():
  1180. node = self.getController().getScene().findObject(self.getRenderer().getRenderPass("selection").getIdAtPosition(x, y))
  1181. if node:
  1182. while(node.getParent() and node.getParent().callDecoration("isGroup")):
  1183. node = node.getParent()
  1184. Selection.add(node)