CuraApplication.py 17 KB

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