CuraApplication.py 56 KB

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