CuraApplication.py 46 KB

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