CuraApplication.py 63 KB

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