CuraApplication.py 66 KB

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