CuraApplication.py 19 KB

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