CuraApplication.py 36 KB

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