CuraApplication.py 61 KB

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