CuraApplication.py 63 KB

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