CuraApplication.py 44 KB

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