CuraApplication.py 35 KB

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