CuraApplication.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from UM.Qt.QtApplication import QtApplication
  4. from UM.Scene.SceneNode import SceneNode
  5. from UM.Scene.Camera import Camera
  6. from UM.Scene.Platform import Platform as Scene_Platform
  7. from UM.Math.Vector import Vector
  8. from UM.Math.Quaternion import Quaternion
  9. from UM.Math.AxisAlignedBox import AxisAlignedBox
  10. from UM.Resources import Resources
  11. from UM.Scene.ToolHandle import ToolHandle
  12. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  13. from UM.Mesh.ReadMeshJob import ReadMeshJob
  14. from UM.Logger import Logger
  15. from UM.Preferences import Preferences
  16. from UM.Platform import Platform
  17. from UM.JobQueue import JobQueue
  18. from UM.SaveFile import SaveFile
  19. from UM.Scene.Selection import Selection
  20. from UM.Scene.GroupDecorator import GroupDecorator
  21. from UM.Settings.Validator import Validator
  22. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  23. from UM.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
  24. from UM.Operations.GroupedOperation import GroupedOperation
  25. from UM.Operations.SetTransformOperation import SetTransformOperation
  26. from cura.SetParentOperation import SetParentOperation
  27. from UM.Settings.SettingDefinition import SettingDefinition, DefinitionPropertyType
  28. from UM.Settings.ContainerRegistry import ContainerRegistry
  29. from UM.i18n import i18nCatalog
  30. from . import PlatformPhysics
  31. from . import BuildVolume
  32. from . import CameraAnimation
  33. from . import PrintInformation
  34. from . import CuraActions
  35. from . import MultiMaterialDecorator
  36. from . import ZOffsetDecorator
  37. from . import CuraSplashScreen
  38. from . import CameraImageProvider
  39. from . import MachineActionManager
  40. import cura.Settings
  41. from PyQt5.QtCore import pyqtSlot, QUrl, pyqtSignal, pyqtProperty, QEvent, Q_ENUMS
  42. from PyQt5.QtGui import QColor, QIcon
  43. from PyQt5.QtWidgets import QMessageBox
  44. from PyQt5.QtQml import qmlRegisterUncreatableType, qmlRegisterSingletonType, qmlRegisterType
  45. import platform
  46. import sys
  47. import os.path
  48. import numpy
  49. import copy
  50. import urllib
  51. numpy.seterr(all="ignore")
  52. #WORKAROUND: GITHUB-88 GITHUB-385 GITHUB-612
  53. if Platform.isLinux(): # Needed for platform.linux_distribution, which is not available on Windows and OSX
  54. # For Ubuntu: https://bugs.launchpad.net/ubuntu/+source/python-qt4/+bug/941826
  55. if platform.linux_distribution()[0] in ("Ubuntu", ): # TODO: Needs a "if X11_GFX == 'nvidia'" here. The workaround is only needed on Ubuntu+NVidia drivers. Other drivers are not affected, but fine with this fix.
  56. import ctypes
  57. from ctypes.util import find_library
  58. ctypes.CDLL(find_library('GL'), ctypes.RTLD_GLOBAL)
  59. try:
  60. from cura.CuraVersion import CuraVersion, CuraBuildType
  61. except ImportError:
  62. CuraVersion = "master" # [CodeStyle: Reflecting imported value]
  63. CuraBuildType = ""
  64. class CuraApplication(QtApplication):
  65. class ResourceTypes:
  66. QmlFiles = Resources.UserType + 1
  67. Firmware = Resources.UserType + 2
  68. QualityInstanceContainer = Resources.UserType + 3
  69. MaterialInstanceContainer = Resources.UserType + 4
  70. VariantInstanceContainer = Resources.UserType + 5
  71. UserInstanceContainer = Resources.UserType + 6
  72. MachineStack = Resources.UserType + 7
  73. ExtruderStack = Resources.UserType + 8
  74. Q_ENUMS(ResourceTypes)
  75. def __init__(self):
  76. Resources.addSearchPath(os.path.join(QtApplication.getInstallPrefix(), "share", "cura", "resources"))
  77. if not hasattr(sys, "frozen"):
  78. Resources.addSearchPath(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "resources"))
  79. self._open_file_queue = [] # Files to open when plug-ins are loaded.
  80. # Need to do this before ContainerRegistry tries to load the machines
  81. SettingDefinition.addSupportedProperty("settable_per_mesh", DefinitionPropertyType.Any, default = True)
  82. SettingDefinition.addSupportedProperty("settable_per_extruder", DefinitionPropertyType.Any, default = True)
  83. SettingDefinition.addSupportedProperty("settable_per_meshgroup", DefinitionPropertyType.Any, default = True)
  84. SettingDefinition.addSupportedProperty("settable_globally", DefinitionPropertyType.Any, default = True)
  85. SettingDefinition.addSettingType("extruder", int, str, Validator)
  86. ## Add the 4 types of profiles to storage.
  87. Resources.addStorageType(self.ResourceTypes.QualityInstanceContainer, "quality")
  88. Resources.addStorageType(self.ResourceTypes.VariantInstanceContainer, "variants")
  89. Resources.addStorageType(self.ResourceTypes.MaterialInstanceContainer, "materials")
  90. Resources.addStorageType(self.ResourceTypes.UserInstanceContainer, "user")
  91. Resources.addStorageType(self.ResourceTypes.ExtruderStack, "extruders")
  92. Resources.addStorageType(self.ResourceTypes.MachineStack, "machine_instances")
  93. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.QualityInstanceContainer)
  94. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.VariantInstanceContainer)
  95. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MaterialInstanceContainer)
  96. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.UserInstanceContainer)
  97. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.ExtruderStack)
  98. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MachineStack)
  99. ## Initialise the version upgrade manager with Cura's storage paths.
  100. import UM.VersionUpgradeManager #Needs to be here to prevent circular dependencies.
  101. self._version_upgrade_manager = UM.VersionUpgradeManager.VersionUpgradeManager(
  102. {
  103. ("quality", UM.Settings.InstanceContainer.Version): (self.ResourceTypes.QualityInstanceContainer, "application/x-uranium-instancecontainer"),
  104. ("machine_stack", UM.Settings.ContainerStack.Version): (self.ResourceTypes.MachineStack, "application/x-uranium-containerstack"),
  105. ("preferences", UM.Preferences.Version): (Resources.Preferences, "application/x-uranium-preferences")
  106. }
  107. )
  108. self._machine_action_manager = MachineActionManager.MachineActionManager()
  109. self._machine_manager = None # This is initialized on demand.
  110. super().__init__(name = "cura", version = CuraVersion, buildtype = CuraBuildType)
  111. self.setWindowIcon(QIcon(Resources.getPath(Resources.Images, "cura-icon.png")))
  112. self.setRequiredPlugins([
  113. "CuraEngineBackend",
  114. "MeshView",
  115. "LayerView",
  116. "STLReader",
  117. "SelectionTool",
  118. "CameraTool",
  119. "GCodeWriter",
  120. "LocalFileOutputDevice"
  121. ])
  122. self._physics = None
  123. self._volume = None
  124. self._platform = None
  125. self._output_devices = {}
  126. self._print_information = None
  127. self._previous_active_tool = None
  128. self._platform_activity = False
  129. self._scene_bounding_box = AxisAlignedBox.Null
  130. self._job_name = None
  131. self._center_after_select = False
  132. self._camera_animation = None
  133. self._cura_actions = None
  134. self._started = False
  135. self._message_box_callback = None
  136. self._message_box_callback_arguments = []
  137. self._i18n_catalog = i18nCatalog("cura")
  138. self.getController().getScene().sceneChanged.connect(self.updatePlatformActivity)
  139. self.getController().toolOperationStopped.connect(self._onToolOperationStopped)
  140. Resources.addType(self.ResourceTypes.QmlFiles, "qml")
  141. Resources.addType(self.ResourceTypes.Firmware, "firmware")
  142. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading machines..."))
  143. # Add empty variant, material and quality containers.
  144. # Since they are empty, they should never be serialized and instead just programmatically created.
  145. # We need them to simplify the switching between materials.
  146. empty_container = ContainerRegistry.getInstance().getEmptyInstanceContainer()
  147. empty_variant_container = copy.deepcopy(empty_container)
  148. empty_variant_container._id = "empty_variant"
  149. empty_variant_container.addMetaDataEntry("type", "variant")
  150. ContainerRegistry.getInstance().addContainer(empty_variant_container)
  151. empty_material_container = copy.deepcopy(empty_container)
  152. empty_material_container._id = "empty_material"
  153. empty_material_container.addMetaDataEntry("type", "material")
  154. ContainerRegistry.getInstance().addContainer(empty_material_container)
  155. empty_quality_container = copy.deepcopy(empty_container)
  156. empty_quality_container._id = "empty_quality"
  157. empty_quality_container.addMetaDataEntry("type", "quality")
  158. ContainerRegistry.getInstance().addContainer(empty_quality_container)
  159. ContainerRegistry.getInstance().load()
  160. Preferences.getInstance().addPreference("cura/active_mode", "simple")
  161. Preferences.getInstance().addPreference("cura/recent_files", "")
  162. Preferences.getInstance().addPreference("cura/categories_expanded", "")
  163. Preferences.getInstance().addPreference("cura/jobname_prefix", True)
  164. Preferences.getInstance().addPreference("view/center_on_select", True)
  165. Preferences.getInstance().addPreference("mesh/scale_to_fit", True)
  166. Preferences.getInstance().addPreference("mesh/scale_tiny_meshes", True)
  167. Preferences.getInstance().setDefault("local_file/last_used_type", "text/x-gcode")
  168. Preferences.getInstance().setDefault("general/visible_settings", """
  169. machine_settings
  170. resolution
  171. layer_height
  172. shell
  173. wall_thickness
  174. top_bottom_thickness
  175. infill
  176. infill_sparse_density
  177. material
  178. material_print_temperature
  179. material_bed_temperature
  180. material_diameter
  181. material_flow
  182. retraction_enable
  183. speed
  184. speed_print
  185. speed_travel
  186. acceleration_print
  187. acceleration_travel
  188. jerk_print
  189. jerk_travel
  190. travel
  191. cooling
  192. cool_fan_enabled
  193. support
  194. support_enable
  195. support_type
  196. support_roof_density
  197. platform_adhesion
  198. adhesion_type
  199. brim_width
  200. raft_airgap
  201. layer_0_z_overlap
  202. raft_surface_layers
  203. meshfix
  204. blackmagic
  205. print_sequence
  206. infill_mesh
  207. dual
  208. experimental
  209. """.replace("\n", ";").replace(" ", ""))
  210. JobQueue.getInstance().jobFinished.connect(self._onJobFinished)
  211. self.applicationShuttingDown.connect(self.saveSettings)
  212. self.engineCreatedSignal.connect(self._onEngineCreated)
  213. self._recent_files = []
  214. files = Preferences.getInstance().getValue("cura/recent_files").split(";")
  215. for f in files:
  216. if not os.path.isfile(f):
  217. continue
  218. self._recent_files.append(QUrl.fromLocalFile(f))
  219. def _onEngineCreated(self):
  220. self._engine.addImageProvider("camera", CameraImageProvider.CameraImageProvider())
  221. ## A reusable dialogbox
  222. #
  223. showMessageBox = pyqtSignal(str, str, str, str, int, int, arguments = ["title", "text", "informativeText", "detailedText", "buttons", "icon"])
  224. def messageBox(self, title, text, informativeText = "", detailedText = "", buttons = QMessageBox.Ok, icon = QMessageBox.NoIcon, callback = None, callback_arguments = []):
  225. self._message_box_callback = callback
  226. self._message_box_callback_arguments = callback_arguments
  227. self.showMessageBox.emit(title, text, informativeText, detailedText, buttons, icon)
  228. @pyqtSlot(int)
  229. def messageBoxClosed(self, button):
  230. if self._message_box_callback:
  231. self._message_box_callback(button, *self._message_box_callback_arguments)
  232. self._message_box_callback = None
  233. self._message_box_callback_arguments = []
  234. showPrintMonitor = pyqtSignal(bool, arguments = ["show"])
  235. ## Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
  236. #
  237. # Note that the AutoSave plugin also calls this method.
  238. def saveSettings(self):
  239. if not self._started: # Do not do saving during application start
  240. return
  241. for instance in ContainerRegistry.getInstance().findInstanceContainers():
  242. if not instance.isDirty():
  243. continue
  244. try:
  245. data = instance.serialize()
  246. except NotImplementedError:
  247. continue
  248. except Exception:
  249. Logger.logException("e", "An exception occurred when serializing container %s", instance.getId())
  250. continue
  251. mime_type = ContainerRegistry.getMimeTypeForContainer(type(instance))
  252. file_name = urllib.parse.quote_plus(instance.getId()) + "." + mime_type.preferredSuffix
  253. instance_type = instance.getMetaDataEntry("type")
  254. path = None
  255. if instance_type == "material":
  256. path = Resources.getStoragePath(self.ResourceTypes.MaterialInstanceContainer, file_name)
  257. elif instance_type == "quality":
  258. path = Resources.getStoragePath(self.ResourceTypes.QualityInstanceContainer, file_name)
  259. elif instance_type == "user":
  260. path = Resources.getStoragePath(self.ResourceTypes.UserInstanceContainer, file_name)
  261. elif instance_type == "variant":
  262. path = Resources.getStoragePath(self.ResourceTypes.VariantInstanceContainer, file_name)
  263. if path:
  264. with SaveFile(path, "wt", -1, "utf-8") as f:
  265. f.write(data)
  266. for stack in ContainerRegistry.getInstance().findContainerStacks():
  267. if not stack.isDirty():
  268. continue
  269. try:
  270. data = stack.serialize()
  271. except NotImplementedError:
  272. continue
  273. except Exception:
  274. Logger.logException("e", "An exception occurred when serializing container %s", instance.getId())
  275. continue
  276. mime_type = ContainerRegistry.getMimeTypeForContainer(type(stack))
  277. file_name = urllib.parse.quote_plus(stack.getId()) + "." + mime_type.preferredSuffix
  278. stack_type = stack.getMetaDataEntry("type", None)
  279. path = None
  280. if not stack_type or stack_type == "machine":
  281. path = Resources.getStoragePath(self.ResourceTypes.MachineStack, file_name)
  282. elif stack_type == "extruder_train":
  283. path = Resources.getStoragePath(self.ResourceTypes.ExtruderStack, file_name)
  284. if path:
  285. with SaveFile(path, "wt", -1, "utf-8") as f:
  286. f.write(data)
  287. @pyqtSlot(result = QUrl)
  288. def getDefaultPath(self):
  289. return QUrl.fromLocalFile(os.path.expanduser("~/"))
  290. ## Handle loading of all plugin types (and the backend explicitly)
  291. # \sa PluginRegistery
  292. def _loadPlugins(self):
  293. self._plugin_registry.addType("profile_reader", self._addProfileReader)
  294. self._plugin_registry.addType("profile_writer", self._addProfileWriter)
  295. self._plugin_registry.addPluginLocation(os.path.join(QtApplication.getInstallPrefix(), "lib", "cura"))
  296. if not hasattr(sys, "frozen"):
  297. self._plugin_registry.addPluginLocation(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "plugins"))
  298. self._plugin_registry.loadPlugin("ConsoleLogger")
  299. self._plugin_registry.loadPlugin("CuraEngineBackend")
  300. self._plugin_registry.loadPlugins()
  301. if self.getBackend() == None:
  302. raise RuntimeError("Could not load the backend plugin!")
  303. self._plugins_loaded = True
  304. def addCommandLineOptions(self, parser):
  305. super().addCommandLineOptions(parser)
  306. parser.add_argument("file", nargs="*", help="Files to load after starting the application.")
  307. parser.add_argument("--debug", dest="debug-mode", action="store_true", default=False, help="Enable detailed crash reports.")
  308. def run(self):
  309. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Setting up scene..."))
  310. controller = self.getController()
  311. controller.setActiveView("SolidView")
  312. controller.setCameraTool("CameraTool")
  313. controller.setSelectionTool("SelectionTool")
  314. t = controller.getTool("TranslateTool")
  315. if t:
  316. t.setEnabledAxis([ToolHandle.XAxis, ToolHandle.YAxis,ToolHandle.ZAxis])
  317. Selection.selectionChanged.connect(self.onSelectionChanged)
  318. root = controller.getScene().getRoot()
  319. self._platform = Scene_Platform(root)
  320. self._volume = BuildVolume.BuildVolume(root)
  321. self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
  322. self._physics = PlatformPhysics.PlatformPhysics(controller, self._volume)
  323. camera = Camera("3d", root)
  324. camera.setPosition(Vector(-80, 250, 700))
  325. camera.setPerspective(True)
  326. camera.lookAt(Vector(0, 0, 0))
  327. controller.getScene().setActiveCamera("3d")
  328. self.getController().getTool("CameraTool").setOrigin(Vector(0, 100, 0))
  329. self._camera_animation = CameraAnimation.CameraAnimation()
  330. self._camera_animation.setCameraTool(self.getController().getTool("CameraTool"))
  331. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading interface..."))
  332. # Initialise extruder so as to listen to global container stack changes before the first global container stack is set.
  333. cura.Settings.ExtruderManager.getInstance()
  334. qmlRegisterSingletonType(cura.Settings.MachineManager, "Cura", 1, 0, "MachineManager", self.getMachineManager)
  335. qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, "MachineActionManager", self.getMachineActionManager)
  336. self.setMainQml(Resources.getPath(self.ResourceTypes.QmlFiles, "Cura.qml"))
  337. self._qml_import_paths.append(Resources.getPath(self.ResourceTypes.QmlFiles))
  338. self.initializeEngine()
  339. if self._engine.rootObjects:
  340. self.closeSplash()
  341. for file in self.getCommandLineOption("file", []):
  342. self._openFile(file)
  343. for file_name in self._open_file_queue: #Open all the files that were queued up while plug-ins were loading.
  344. self._openFile(file_name)
  345. self._started = True
  346. self.exec_()
  347. def getMachineManager(self, *args):
  348. if self._machine_manager is None:
  349. self._machine_manager = cura.Settings.MachineManager.createMachineManager()
  350. return self._machine_manager
  351. ## Get the machine action manager
  352. # We ignore any *args given to this, as we also register the machine manager as qml singleton.
  353. # It wants to give this function an engine and script engine, but we don't care about that.
  354. def getMachineActionManager(self, *args):
  355. return self._machine_action_manager
  356. ## Handle Qt events
  357. def event(self, event):
  358. if event.type() == QEvent.FileOpen:
  359. if self._plugins_loaded:
  360. self._openFile(event.file())
  361. else:
  362. self._open_file_queue.append(event.file())
  363. return super().event(event)
  364. ## Get print information (duration / material used)
  365. def getPrintInformation(self):
  366. return self._print_information
  367. ## Registers objects for the QML engine to use.
  368. #
  369. # \param engine The QML engine.
  370. def registerObjects(self, engine):
  371. engine.rootContext().setContextProperty("Printer", self)
  372. engine.rootContext().setContextProperty("CuraApplication", self)
  373. self._print_information = PrintInformation.PrintInformation()
  374. engine.rootContext().setContextProperty("PrintInformation", self._print_information)
  375. self._cura_actions = CuraActions.CuraActions(self)
  376. engine.rootContext().setContextProperty("CuraActions", self._cura_actions)
  377. qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")
  378. qmlRegisterType(cura.Settings.ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")
  379. qmlRegisterType(cura.Settings.ContainerSettingsModel, "Cura", 1, 0, "ContainerSettingsModel")
  380. qmlRegisterType(cura.Settings.MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
  381. qmlRegisterSingletonType(cura.Settings.ContainerManager, "Cura", 1, 0, "ContainerManager", cura.Settings.ContainerManager.createContainerManager)
  382. qmlRegisterSingletonType(QUrl.fromLocalFile(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")), "Cura", 1, 0, "Actions")
  383. engine.rootContext().setContextProperty("ExtruderManager", cura.Settings.ExtruderManager.getInstance())
  384. for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
  385. type_name = os.path.splitext(os.path.basename(path))[0]
  386. if type_name in ("Cura", "Actions"):
  387. continue
  388. qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
  389. def onSelectionChanged(self):
  390. if Selection.hasSelection():
  391. if not self.getController().getActiveTool():
  392. if self._previous_active_tool:
  393. self.getController().setActiveTool(self._previous_active_tool)
  394. self._previous_active_tool = None
  395. else:
  396. self.getController().setActiveTool("TranslateTool")
  397. if Preferences.getInstance().getValue("view/center_on_select"):
  398. self._center_after_select = True
  399. else:
  400. if self.getController().getActiveTool():
  401. self._previous_active_tool = self.getController().getActiveTool().getPluginId()
  402. self.getController().setActiveTool(None)
  403. else:
  404. self._previous_active_tool = None
  405. def _onToolOperationStopped(self, event):
  406. if self._center_after_select:
  407. self._center_after_select = False
  408. self._camera_animation.setStart(self.getController().getTool("CameraTool").getOrigin())
  409. self._camera_animation.setTarget(Selection.getSelectedObject(0).getWorldPosition())
  410. self._camera_animation.start()
  411. requestAddPrinter = pyqtSignal()
  412. activityChanged = pyqtSignal()
  413. sceneBoundingBoxChanged = pyqtSignal()
  414. @pyqtProperty(bool, notify = activityChanged)
  415. def getPlatformActivity(self):
  416. return self._platform_activity
  417. @pyqtProperty(str, notify = sceneBoundingBoxChanged)
  418. def getSceneBoundingBoxString(self):
  419. 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()}
  420. def updatePlatformActivity(self, node = None):
  421. count = 0
  422. scene_bounding_box = None
  423. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  424. if type(node) is not SceneNode or not node.getMeshData():
  425. continue
  426. count += 1
  427. if not scene_bounding_box:
  428. scene_bounding_box = node.getBoundingBox()
  429. else:
  430. other_bb = node.getBoundingBox()
  431. if other_bb is not None:
  432. scene_bounding_box = scene_bounding_box + node.getBoundingBox()
  433. if not scene_bounding_box:
  434. scene_bounding_box = AxisAlignedBox.Null
  435. if repr(self._scene_bounding_box) != repr(scene_bounding_box):
  436. self._scene_bounding_box = scene_bounding_box
  437. self.sceneBoundingBoxChanged.emit()
  438. self._platform_activity = True if count > 0 else False
  439. self.activityChanged.emit()
  440. # Remove all selected objects from the scene.
  441. @pyqtSlot()
  442. def deleteSelection(self):
  443. if not self.getController().getToolsEnabled():
  444. return
  445. op = GroupedOperation()
  446. nodes = Selection.getAllSelectedObjects()
  447. for node in nodes:
  448. op.addOperation(RemoveSceneNodeOperation(node))
  449. op.push()
  450. pass
  451. ## Remove an object from the scene.
  452. # Note that this only removes an object if it is selected.
  453. @pyqtSlot("quint64")
  454. def deleteObject(self, object_id):
  455. if not self.getController().getToolsEnabled():
  456. return
  457. node = self.getController().getScene().findObject(object_id)
  458. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  459. node = Selection.getSelectedObject(0)
  460. if node:
  461. if node.getParent():
  462. group_node = node.getParent()
  463. if not group_node.callDecoration("isGroup"):
  464. op = RemoveSceneNodeOperation(node)
  465. else:
  466. while group_node.getParent().callDecoration("isGroup"):
  467. group_node = group_node.getParent()
  468. op = RemoveSceneNodeOperation(group_node)
  469. op.push()
  470. ## Create a number of copies of existing object.
  471. @pyqtSlot("quint64", int)
  472. def multiplyObject(self, object_id, count):
  473. node = self.getController().getScene().findObject(object_id)
  474. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  475. node = Selection.getSelectedObject(0)
  476. if node:
  477. op = GroupedOperation()
  478. for _ in range(count):
  479. if node.getParent() and node.getParent().callDecoration("isGroup"):
  480. new_node = copy.deepcopy(node.getParent()) #Copy the group node.
  481. new_node.callDecoration("recomputeConvexHull")
  482. op.addOperation(AddSceneNodeOperation(new_node,node.getParent().getParent()))
  483. else:
  484. new_node = copy.deepcopy(node)
  485. new_node.callDecoration("recomputeConvexHull")
  486. op.addOperation(AddSceneNodeOperation(new_node, node.getParent()))
  487. op.push()
  488. ## Center object on platform.
  489. @pyqtSlot("quint64")
  490. def centerObject(self, object_id):
  491. node = self.getController().getScene().findObject(object_id)
  492. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  493. node = Selection.getSelectedObject(0)
  494. if not node:
  495. return
  496. if node.getParent() and node.getParent().callDecoration("isGroup"):
  497. node = node.getParent()
  498. if node:
  499. op = SetTransformOperation(node, Vector())
  500. op.push()
  501. ## Delete all nodes containing mesh data in the scene.
  502. @pyqtSlot()
  503. def deleteAll(self):
  504. Logger.log("i", "Clearing scene")
  505. if not self.getController().getToolsEnabled():
  506. return
  507. nodes = []
  508. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  509. if type(node) is not SceneNode:
  510. continue
  511. if not node.getMeshData() and not node.callDecoration("isGroup"):
  512. continue # Node that doesnt have a mesh and is not a group.
  513. if node.getParent() and node.getParent().callDecoration("isGroup"):
  514. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  515. nodes.append(node)
  516. if nodes:
  517. op = GroupedOperation()
  518. for node in nodes:
  519. op.addOperation(RemoveSceneNodeOperation(node))
  520. op.push()
  521. ## Reset all translation on nodes with mesh data.
  522. @pyqtSlot()
  523. def resetAllTranslation(self):
  524. Logger.log("i", "Resetting all scene translations")
  525. nodes = []
  526. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  527. if type(node) is not SceneNode:
  528. continue
  529. if not node.getMeshData() and not node.callDecoration("isGroup"):
  530. continue # Node that doesnt have a mesh and is not a group.
  531. if node.getParent() and node.getParent().callDecoration("isGroup"):
  532. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  533. nodes.append(node)
  534. if nodes:
  535. op = GroupedOperation()
  536. for node in nodes:
  537. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  538. op.addOperation(SetTransformOperation(node, Vector(0,0,0)))
  539. op.push()
  540. ## Reset all transformations on nodes with mesh data.
  541. @pyqtSlot()
  542. def resetAll(self):
  543. Logger.log("i", "Resetting all scene transformations")
  544. nodes = []
  545. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  546. if type(node) is not SceneNode:
  547. continue
  548. if not node.getMeshData() and not node.callDecoration("isGroup"):
  549. continue # Node that doesnt have a mesh and is not a group.
  550. if node.getParent() and node.getParent().callDecoration("isGroup"):
  551. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  552. nodes.append(node)
  553. if nodes:
  554. op = GroupedOperation()
  555. for node in nodes:
  556. # Ensure that the object is above the build platform
  557. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  558. op.addOperation(SetTransformOperation(node, Vector(0,0,0), Quaternion(), Vector(1, 1, 1)))
  559. op.push()
  560. ## Reload all mesh data on the screen from file.
  561. @pyqtSlot()
  562. def reloadAll(self):
  563. Logger.log("i", "Reloading all loaded mesh data.")
  564. nodes = []
  565. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  566. if type(node) is not SceneNode or not node.getMeshData():
  567. continue
  568. nodes.append(node)
  569. if not nodes:
  570. return
  571. for node in nodes:
  572. file_name = node.getMeshData().getFileName()
  573. if file_name:
  574. job = ReadMeshJob(file_name)
  575. job._node = node
  576. job.finished.connect(self._reloadMeshFinished)
  577. job.start()
  578. else:
  579. Logger.log("w", "Unable to reload data because we don't have a filename.")
  580. ## Get logging data of the backend engine
  581. # \returns \type{string} Logging data
  582. @pyqtSlot(result = str)
  583. def getEngineLog(self):
  584. log = ""
  585. for entry in self.getBackend().getLog():
  586. log += entry.decode()
  587. return log
  588. recentFilesChanged = pyqtSignal()
  589. @pyqtProperty("QVariantList", notify = recentFilesChanged)
  590. def recentFiles(self):
  591. return self._recent_files
  592. @pyqtSlot("QStringList")
  593. def setExpandedCategories(self, categories):
  594. categories = list(set(categories))
  595. categories.sort()
  596. joined = ";".join(categories)
  597. if joined != Preferences.getInstance().getValue("cura/categories_expanded"):
  598. Preferences.getInstance().setValue("cura/categories_expanded", joined)
  599. self.expandedCategoriesChanged.emit()
  600. expandedCategoriesChanged = pyqtSignal()
  601. @pyqtProperty("QStringList", notify = expandedCategoriesChanged)
  602. def expandedCategories(self):
  603. return Preferences.getInstance().getValue("cura/categories_expanded").split(";")
  604. @pyqtSlot()
  605. def mergeSelected(self):
  606. self.groupSelected()
  607. try:
  608. group_node = Selection.getAllSelectedObjects()[0]
  609. except Exception as e:
  610. Logger.log("d", "mergeSelected: Exception:", e)
  611. return
  612. multi_material_decorator = MultiMaterialDecorator.MultiMaterialDecorator()
  613. group_node.addDecorator(multi_material_decorator)
  614. # Reset the position of each node
  615. for node in group_node.getChildren():
  616. new_position = node.getMeshData().getCenterPosition()
  617. new_position = new_position.scale(node.getScale())
  618. node.setPosition(new_position)
  619. # Use the previously found center of the group bounding box as the new location of the group
  620. group_node.setPosition(group_node.getBoundingBox().center)
  621. @pyqtSlot()
  622. def groupSelected(self):
  623. # Create a group-node
  624. group_node = SceneNode()
  625. group_decorator = GroupDecorator()
  626. group_node.addDecorator(group_decorator)
  627. group_node.setParent(self.getController().getScene().getRoot())
  628. group_node.setSelectable(True)
  629. center = Selection.getSelectionCenter()
  630. group_node.setPosition(center)
  631. group_node.setCenterPosition(center)
  632. # Move selected nodes into the group-node
  633. Selection.applyOperation(SetParentOperation, group_node)
  634. # Deselect individual nodes and select the group-node instead
  635. for node in group_node.getChildren():
  636. Selection.remove(node)
  637. Selection.add(group_node)
  638. @pyqtSlot()
  639. def ungroupSelected(self):
  640. selected_objects = Selection.getAllSelectedObjects().copy()
  641. for node in selected_objects:
  642. if node.callDecoration("isGroup"):
  643. op = GroupedOperation()
  644. group_parent = node.getParent()
  645. children = node.getChildren().copy()
  646. for child in children:
  647. # Set the parent of the children to the parent of the group-node
  648. op.addOperation(SetParentOperation(child, group_parent))
  649. # Add all individual nodes to the selection
  650. Selection.add(child)
  651. op.push()
  652. # Note: The group removes itself from the scene once all its children have left it,
  653. # see GroupDecorator._onChildrenChanged
  654. def _createSplashScreen(self):
  655. return CuraSplashScreen.CuraSplashScreen()
  656. def _onActiveMachineChanged(self):
  657. pass
  658. fileLoaded = pyqtSignal(str)
  659. def _onFileLoaded(self, job):
  660. node = job.getResult()
  661. if node != None:
  662. self.fileLoaded.emit(job.getFileName())
  663. node.setSelectable(True)
  664. node.setName(os.path.basename(job.getFileName()))
  665. op = AddSceneNodeOperation(node, self.getController().getScene().getRoot())
  666. op.push()
  667. self.getController().getScene().sceneChanged.emit(node) #Force scene change.
  668. def _onJobFinished(self, job):
  669. if type(job) is not ReadMeshJob or not job.getResult():
  670. return
  671. f = QUrl.fromLocalFile(job.getFileName())
  672. if f in self._recent_files:
  673. self._recent_files.remove(f)
  674. self._recent_files.insert(0, f)
  675. if len(self._recent_files) > 10:
  676. del self._recent_files[10]
  677. pref = ""
  678. for path in self._recent_files:
  679. pref += path.toLocalFile() + ";"
  680. Preferences.getInstance().setValue("cura/recent_files", pref)
  681. self.recentFilesChanged.emit()
  682. def _reloadMeshFinished(self, job):
  683. # TODO; This needs to be fixed properly. We now make the assumption that we only load a single mesh!
  684. job._node.setMeshData(job.getResult().getMeshData())
  685. def _openFile(self, file):
  686. job = ReadMeshJob(os.path.abspath(file))
  687. job.finished.connect(self._onFileLoaded)
  688. job.start()
  689. def _addProfileReader(self, profile_reader):
  690. # TODO: Add the profile reader to the list of plug-ins that can be used when importing profiles.
  691. pass
  692. def _addProfileWriter(self, profile_writer):
  693. pass
  694. @pyqtSlot("QSize")
  695. def setMinimumWindowSize(self, size):
  696. self.getMainWindow().setMinimumSize(size)