CuraApplication.py 55 KB

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