CuraApplication.py 61 KB

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