CuraApplication.py 62 KB

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