CuraApplication.py 41 KB

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