CuraApplication.py 59 KB

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