CuraApplication.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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
  7. from UM.Math.Vector import Vector
  8. from UM.Math.Matrix import Matrix
  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.WriteMeshJob import WriteMeshJob
  13. from UM.Mesh.ReadMeshJob import ReadMeshJob
  14. from UM.Logger import Logger
  15. from UM.Preferences import Preferences
  16. from UM.Message import Message
  17. from UM.PluginRegistry import PluginRegistry
  18. from UM.Scene.BoxRenderer import BoxRenderer
  19. from UM.Scene.Selection import Selection
  20. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  21. from UM.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
  22. from UM.Operations.GroupedOperation import GroupedOperation
  23. from UM.Operations.SetTransformOperation import SetTransformOperation
  24. from UM.i18n import i18nCatalog
  25. from . import PlatformPhysics
  26. from . import BuildVolume
  27. from . import CameraAnimation
  28. from . import PrintInformation
  29. from PyQt5.QtCore import pyqtSlot, QUrl, Qt, pyqtSignal, pyqtProperty
  30. from PyQt5.QtGui import QColor
  31. import platform
  32. import sys
  33. import os.path
  34. import numpy
  35. numpy.seterr(all="ignore")
  36. class CuraApplication(QtApplication):
  37. def __init__(self):
  38. Resources.addResourcePath(os.path.join(QtApplication.getInstallPrefix(), "share", "cura"))
  39. if not hasattr(sys, "frozen"):
  40. Resources.addResourcePath(os.path.join(os.path.abspath(os.path.dirname(__file__)), ".."))
  41. super().__init__(name = "cura", version = "15.05.90")
  42. self.setRequiredPlugins([
  43. "CuraEngineBackend",
  44. "MeshView",
  45. "LayerView",
  46. "STLReader",
  47. "SelectionTool",
  48. "CameraTool",
  49. "GCodeWriter",
  50. "LocalFileStorage"
  51. ])
  52. self._physics = None
  53. self._volume = None
  54. self._platform = None
  55. self._output_devices = {}
  56. self._print_information = None
  57. self._i18n_catalog = None
  58. self.activeMachineChanged.connect(self._onActiveMachineChanged)
  59. Preferences.getInstance().addPreference("cura/active_machine", "")
  60. Preferences.getInstance().addPreference("cura/active_mode", "simple")
  61. ## Handle loading of all plugin types (and the backend explicitly)
  62. # \sa PluginRegistery
  63. def _loadPlugins(self):
  64. self._plugin_registry.addPluginLocation(os.path.join(QtApplication.getInstallPrefix(), "lib", "cura"))
  65. if not hasattr(sys, "frozen"):
  66. self._plugin_registry.addPluginLocation(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "plugins"))
  67. self._plugin_registry.loadPlugins({ "type": "logger"})
  68. self._plugin_registry.loadPlugins({ "type": "storage_device" })
  69. self._plugin_registry.loadPlugins({ "type": "view" })
  70. self._plugin_registry.loadPlugins({ "type": "mesh_reader" })
  71. self._plugin_registry.loadPlugins({ "type": "mesh_writer" })
  72. self._plugin_registry.loadPlugins({ "type": "tool" })
  73. self._plugin_registry.loadPlugins({ "type": "extension" })
  74. self._plugin_registry.loadPlugin("CuraEngineBackend")
  75. def addCommandLineOptions(self, parser):
  76. parser.add_argument("file", nargs="*", help="Files to load after starting the application.")
  77. def run(self):
  78. self._i18n_catalog = i18nCatalog("cura");
  79. self.addOutputDevice("local_file", {
  80. "id": "local_file",
  81. "function": self._writeToLocalFile,
  82. "description": self._i18n_catalog.i18nc("Save button tooltip", "Save to Disk"),
  83. "icon": "save",
  84. "priority": 0
  85. })
  86. self.showSplashMessage(self._i18n_catalog.i18nc("Splash screen message", "Setting up scene..."))
  87. controller = self.getController()
  88. controller.setActiveView("MeshView")
  89. controller.setCameraTool("CameraTool")
  90. controller.setSelectionTool("SelectionTool")
  91. t = controller.getTool("TranslateTool")
  92. if t:
  93. t.setEnabledAxis([ToolHandle.XAxis, ToolHandle.ZAxis])
  94. Selection.selectionChanged.connect(self.onSelectionChanged)
  95. root = controller.getScene().getRoot()
  96. self._platform = Platform(root)
  97. self._volume = BuildVolume.BuildVolume(root)
  98. self.getRenderer().setLightPosition(Vector(0, 150, 0))
  99. self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
  100. self._physics = PlatformPhysics.PlatformPhysics(controller, self._volume)
  101. camera = Camera("3d", root)
  102. camera.setPosition(Vector(-150, 150, 300))
  103. camera.setPerspective(True)
  104. camera.lookAt(Vector(0, 0, 0))
  105. self._camera_animation = CameraAnimation.CameraAnimation()
  106. self._camera_animation.setCameraTool(self.getController().getTool("CameraTool"))
  107. controller.getScene().setActiveCamera("3d")
  108. self.showSplashMessage(self._i18n_catalog.i18nc("Splash screen message", "Loading interface..."))
  109. self.setMainQml(Resources.getPath(Resources.QmlFilesLocation, "Cura.qml"))
  110. self.initializeEngine()
  111. self.getStorageDevice("LocalFileStorage").removableDrivesChanged.connect(self._removableDrivesChanged)
  112. if self.getMachines():
  113. active_machine_pref = Preferences.getInstance().getValue("cura/active_machine")
  114. if active_machine_pref:
  115. for machine in self.getMachines():
  116. if machine.getName() == active_machine_pref:
  117. self.setActiveMachine(machine)
  118. if not self.getActiveMachine():
  119. self.setActiveMachine(self.getMachines()[0])
  120. else:
  121. self.requestAddPrinter.emit()
  122. self._removableDrivesChanged()
  123. if self._engine.rootObjects:
  124. self.closeSplash()
  125. for file in self.getCommandLineOption("file", []):
  126. job = ReadMeshJob(os.path.abspath(file))
  127. job.start()
  128. self.exec_()
  129. def registerObjects(self, engine):
  130. engine.rootContext().setContextProperty("Printer", self)
  131. self._print_information = PrintInformation.PrintInformation()
  132. engine.rootContext().setContextProperty("PrintInformation", self._print_information)
  133. def onSelectionChanged(self):
  134. if Selection.hasSelection():
  135. if not self.getController().getActiveTool():
  136. self.getController().setActiveTool("TranslateTool")
  137. self._camera_animation.setStart(self.getController().getTool("CameraTool").getOrigin())
  138. self._camera_animation.setTarget(Selection.getSelectedObject(0).getWorldPosition())
  139. self._camera_animation.start()
  140. else:
  141. if self.getController().getActiveTool():
  142. self.getController().setActiveTool(None)
  143. requestAddPrinter = pyqtSignal()
  144. ## Remove an object from the scene
  145. @pyqtSlot("quint64")
  146. def deleteObject(self, object_id):
  147. object = self.getController().getScene().findObject(object_id)
  148. if object:
  149. op = RemoveSceneNodeOperation(object)
  150. op.push()
  151. ## Create a number of copies of existing object.
  152. @pyqtSlot("quint64", int)
  153. def multiplyObject(self, object_id, count):
  154. node = self.getController().getScene().findObject(object_id)
  155. if node:
  156. op = GroupedOperation()
  157. for i in range(count):
  158. new_node = SceneNode()
  159. new_node.setMeshData(node.getMeshData())
  160. new_node.setScale(node.getScale())
  161. new_node.translate(Vector((i + 1) * node.getBoundingBox().width, 0, 0))
  162. new_node.setSelectable(True)
  163. op.addOperation(AddSceneNodeOperation(new_node, node.getParent()))
  164. op.push()
  165. ## Center object on platform.
  166. @pyqtSlot("quint64")
  167. def centerObject(self, object_id):
  168. node = self.getController().getScene().findObject(object_id)
  169. if node:
  170. transform = node.getLocalTransformation()
  171. transform.setTranslation(Vector(0, 0, 0))
  172. op = SetTransformOperation(node, transform)
  173. op.push()
  174. ## Delete all mesh data on the scene.
  175. @pyqtSlot()
  176. def deleteAll(self):
  177. nodes = []
  178. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  179. if type(node) is not SceneNode or not node.getMeshData():
  180. continue
  181. nodes.append(node)
  182. if nodes:
  183. op = GroupedOperation()
  184. for node in nodes:
  185. op.addOperation(RemoveSceneNodeOperation(node))
  186. op.push()
  187. ## Reset all translation on nodes with mesh data.
  188. @pyqtSlot()
  189. def resetAllTranslation(self):
  190. nodes = []
  191. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  192. if type(node) is not SceneNode or not node.getMeshData():
  193. continue
  194. nodes.append(node)
  195. if nodes:
  196. op = GroupedOperation()
  197. for node in nodes:
  198. transform = node.getLocalTransformation()
  199. transform.setTranslation(Vector(0, 0, 0))
  200. op.addOperation(SetTransformOperation(node, transform))
  201. op.push()
  202. ## Reset all transformations on nodes with mesh data.
  203. @pyqtSlot()
  204. def resetAll(self):
  205. nodes = []
  206. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  207. if type(node) is not SceneNode or not node.getMeshData():
  208. continue
  209. nodes.append(node)
  210. if nodes:
  211. op = GroupedOperation()
  212. for node in nodes:
  213. transform = Matrix()
  214. op.addOperation(SetTransformOperation(node, transform))
  215. op.push()
  216. ## Reload all mesh data on the screen from file.
  217. @pyqtSlot()
  218. def reloadAll(self):
  219. nodes = []
  220. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  221. if type(node) is not SceneNode or not node.getMeshData():
  222. continue
  223. nodes.append(node)
  224. if nodes:
  225. file_name = node.getMeshData().getFileName()
  226. job = ReadMeshJob(file_name)
  227. job.finished.connect(lambda j: node.setMeshData(j.getResult()))
  228. job.start()
  229. ## Get logging data of the backend engine
  230. # \returns \type{string} Logging data
  231. @pyqtSlot(result=str)
  232. def getEngineLog(self):
  233. log = ""
  234. for entry in self.getBackend().getLog():
  235. log += entry.decode()
  236. return log
  237. outputDevicesChanged = pyqtSignal()
  238. @pyqtProperty("QVariantMap", notify = outputDevicesChanged)
  239. def outputDevices(self):
  240. return self._output_devices
  241. @pyqtProperty("QStringList", notify = outputDevicesChanged)
  242. def outputDeviceNames(self):
  243. return self._output_devices.keys()
  244. @pyqtSlot(str, result = "QVariant")
  245. def getSettingValue(self, key):
  246. if not self.getActiveMachine():
  247. return None
  248. return self.getActiveMachine().getSettingValueByKey(key)
  249. ## Change setting by key value pair
  250. @pyqtSlot(str, "QVariant")
  251. def setSettingValue(self, key, value):
  252. if not self.getActiveMachine():
  253. return
  254. self.getActiveMachine().setSettingValueByKey(key, value)
  255. ## Add an output device that can be written to.
  256. #
  257. # \param id \type{string} The identifier used to identify the device.
  258. # \param device \type{StorageDevice} A dictionary of device information.
  259. # It should contains the following:
  260. # - function: A function to be called when trying to write to the device. Will be passed the device id as first parameter.
  261. # - description: A translated string containing a description of what happens when writing to the device.
  262. # - icon: The icon to use to represent the device.
  263. # - priority: The priority of the device. The device with the highest priority will be used as the default device.
  264. def addOutputDevice(self, id, device):
  265. self._output_devices[id] = device
  266. self.outputDevicesChanged.emit()
  267. ## Remove output device
  268. # \param id \type{string} The identifier used to identify the device.
  269. # \sa PrinterApplication::addOutputDevice()
  270. def removeOutputDevice(self, id):
  271. if id in self._output_devices:
  272. del self._output_devices[id]
  273. self.outputDevicesChanged.emit()
  274. @pyqtSlot(str)
  275. def writeToOutputDevice(self, device):
  276. self._output_devices[device]["function"](device)
  277. writeToLocalFileRequested = pyqtSignal()
  278. def _writeToLocalFile(self, device):
  279. self.writeToLocalFileRequested.emit()
  280. def _writeToSD(self, device):
  281. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  282. if type(node) is not SceneNode or not node.getMeshData():
  283. continue
  284. try:
  285. path = self.getStorageDevice("LocalFileStorage").getRemovableDrives()[device]
  286. except KeyError:
  287. Logger.log("e", "Tried to write to unknown SD card %s", device)
  288. return
  289. filename = os.path.join(path, node.getName()[0:node.getName().rfind(".")] + ".gcode")
  290. job = WriteMeshJob(filename, node.getMeshData())
  291. job._sdcard = device
  292. job.start()
  293. job.finished.connect(self._onWriteToSDFinished)
  294. return
  295. def _removableDrivesChanged(self):
  296. drives = self.getStorageDevice("LocalFileStorage").getRemovableDrives()
  297. for drive in drives:
  298. if drive not in self._output_devices:
  299. self.addOutputDevice(drive, {
  300. "id": drive,
  301. "function": self._writeToSD,
  302. "description": self._i18n_catalog.i18nc("Save button tooltip. {0} is sd card name", "Save to SD Card {0}".format(drive)),
  303. "icon": "save_sd",
  304. "priority": 1
  305. })
  306. drives_to_remove = []
  307. for device in self._output_devices:
  308. if device not in drives:
  309. if self._output_devices[device]["function"] == self._writeToSD:
  310. drives_to_remove.append(device)
  311. for drive in drives_to_remove:
  312. self.removeOutputDevice(drive)
  313. def _onActiveMachineChanged(self):
  314. machine = self.getActiveMachine()
  315. if machine:
  316. Preferences.getInstance().setValue("cura/active_machine", machine.getName())
  317. self._volume.setWidth(machine.getSettingValueByKey("machine_width"))
  318. self._volume.setHeight(machine.getSettingValueByKey("machine_height"))
  319. self._volume.setDepth(machine.getSettingValueByKey("machine_depth"))
  320. disallowed_areas = machine.getSettingValueByKey("machine_disallowed_areas")
  321. areas = []
  322. if disallowed_areas:
  323. for area in disallowed_areas:
  324. polygon = []
  325. polygon.append(Vector(area[0][0], 0.2, area[0][1]))
  326. polygon.append(Vector(area[1][0], 0.2, area[1][1]))
  327. polygon.append(Vector(area[2][0], 0.2, area[2][1]))
  328. polygon.append(Vector(area[3][0], 0.2, area[3][1]))
  329. areas.append(polygon)
  330. self._volume.setDisallowedAreas(areas)
  331. self._volume.rebuild()
  332. if self.getController().getTool("ScaleTool"):
  333. self.getController().getTool("ScaleTool").setMaximumBounds(self._volume.getBoundingBox())
  334. offset = machine.getSettingValueByKey("machine_platform_offset")
  335. if offset:
  336. self._platform.setPosition(Vector(offset[0], offset[1], offset[2]))
  337. else:
  338. self._platform.setPosition(Vector(0.0, 0.0, 0.0))
  339. def _onWriteToSDFinished(self, job):
  340. message = Message(self._i18n_catalog.i18nc("Saved to SD message, {0} is sdcard, {1} is filename", "Saved to SD Card {0} as {1}").format(job._sdcard, job.getFileName()))
  341. message.addAction(
  342. "eject",
  343. self._i18n_catalog.i18nc("Message action", "Eject"),
  344. "eject",
  345. self._i18n_catalog.i18nc("Message action tooltip, {0} is sdcard", "Eject SD Card {0}".format(job._sdcard))
  346. )
  347. message._sdcard = job._sdcard
  348. message.actionTriggered.connect(self._onMessageActionTriggered)
  349. message.show()
  350. def _onMessageActionTriggered(self, message, action):
  351. if action == "eject":
  352. self.getStorageDevice("LocalFileStorage").ejectRemovableDrive(message._sdcard)