CuraApplication.py 56 KB

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