CuraApplication.py 61 KB

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