CuraApplication.py 44 KB

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