CuraApplication.py 44 KB

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