CuraApplication.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from PyQt5.QtNetwork import QLocalServer
  4. from PyQt5.QtNetwork import QLocalSocket
  5. from UM.Qt.QtApplication import QtApplication
  6. from UM.FileHandler.ReadFileJob import ReadFileJob
  7. from UM.Scene.SceneNode import SceneNode
  8. from UM.Scene.Camera import Camera
  9. from UM.Math.Vector import Vector
  10. from UM.Math.Quaternion import Quaternion
  11. from UM.Math.AxisAlignedBox import AxisAlignedBox
  12. from UM.Math.Matrix import Matrix
  13. from UM.Resources import Resources
  14. from UM.Scene.ToolHandle import ToolHandle
  15. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  16. from UM.Mesh.ReadMeshJob import ReadMeshJob
  17. from UM.Logger import Logger
  18. from UM.Preferences import Preferences
  19. from UM.JobQueue import JobQueue
  20. from UM.SaveFile import SaveFile
  21. from UM.Scene.Selection import Selection
  22. from UM.Scene.GroupDecorator import GroupDecorator
  23. from UM.Settings.ContainerStack import ContainerStack
  24. from UM.Settings.InstanceContainer import InstanceContainer
  25. from UM.Settings.Validator import Validator
  26. from UM.Message import Message
  27. from UM.i18n import i18nCatalog
  28. from UM.Workspace.WorkspaceReader import WorkspaceReader
  29. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  30. from UM.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
  31. from UM.Operations.GroupedOperation import GroupedOperation
  32. from UM.Operations.SetTransformOperation import SetTransformOperation
  33. from cura.Arrange import Arrange
  34. from cura.ShapeArray import ShapeArray
  35. from cura.ConvexHullDecorator import ConvexHullDecorator
  36. from cura.SetParentOperation import SetParentOperation
  37. from cura.SliceableObjectDecorator import SliceableObjectDecorator
  38. from cura.BlockSlicingDecorator import BlockSlicingDecorator
  39. from UM.Settings.SettingDefinition import SettingDefinition, DefinitionPropertyType
  40. from UM.Settings.ContainerRegistry import ContainerRegistry
  41. from UM.Settings.SettingFunction import SettingFunction
  42. from cura.Settings.MachineNameValidator import MachineNameValidator
  43. from cura.Settings.ProfilesModel import ProfilesModel
  44. from cura.Settings.QualityAndUserProfilesModel import QualityAndUserProfilesModel
  45. from cura.Settings.SettingInheritanceManager import SettingInheritanceManager
  46. from cura.Settings.UserProfilesModel import UserProfilesModel
  47. from . import PlatformPhysics
  48. from . import BuildVolume
  49. from . import CameraAnimation
  50. from . import PrintInformation
  51. from . import CuraActions
  52. from . import ZOffsetDecorator
  53. from . import CuraSplashScreen
  54. from . import CameraImageProvider
  55. from . import MachineActionManager
  56. from cura.Settings.MachineManager import MachineManager
  57. from cura.Settings.ExtruderManager import ExtruderManager
  58. from cura.Settings.UserChangesModel import UserChangesModel
  59. from cura.Settings.ExtrudersModel import ExtrudersModel
  60. from cura.Settings.ContainerSettingsModel import ContainerSettingsModel
  61. from cura.Settings.MaterialSettingsVisibilityHandler import MaterialSettingsVisibilityHandler
  62. from cura.Settings.QualitySettingsModel import QualitySettingsModel
  63. from cura.Settings.ContainerManager import ContainerManager
  64. from PyQt5.QtCore import QUrl, pyqtSignal, pyqtProperty, QEvent, Q_ENUMS
  65. from UM.FlameProfiler import pyqtSlot
  66. from PyQt5.QtGui import QColor, QIcon
  67. from PyQt5.QtWidgets import QMessageBox
  68. from PyQt5.QtQml import qmlRegisterUncreatableType, qmlRegisterSingletonType, qmlRegisterType
  69. import sys
  70. import os.path
  71. import numpy
  72. import copy
  73. import urllib.parse
  74. import os
  75. import argparse
  76. import json
  77. numpy.seterr(all="ignore")
  78. MYPY = False
  79. if not MYPY:
  80. try:
  81. from cura.CuraVersion import CuraVersion, CuraBuildType
  82. except ImportError:
  83. CuraVersion = "master" # [CodeStyle: Reflecting imported value]
  84. CuraBuildType = ""
  85. class CuraApplication(QtApplication):
  86. class ResourceTypes:
  87. QmlFiles = Resources.UserType + 1
  88. Firmware = Resources.UserType + 2
  89. QualityInstanceContainer = Resources.UserType + 3
  90. MaterialInstanceContainer = Resources.UserType + 4
  91. VariantInstanceContainer = Resources.UserType + 5
  92. UserInstanceContainer = Resources.UserType + 6
  93. MachineStack = Resources.UserType + 7
  94. ExtruderStack = Resources.UserType + 8
  95. Q_ENUMS(ResourceTypes)
  96. def __init__(self):
  97. Resources.addSearchPath(os.path.join(QtApplication.getInstallPrefix(), "share", "cura", "resources"))
  98. if not hasattr(sys, "frozen"):
  99. Resources.addSearchPath(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "resources"))
  100. self._open_file_queue = [] # Files to open when plug-ins are loaded.
  101. # Need to do this before ContainerRegistry tries to load the machines
  102. SettingDefinition.addSupportedProperty("settable_per_mesh", DefinitionPropertyType.Any, default = True, read_only = True)
  103. SettingDefinition.addSupportedProperty("settable_per_extruder", DefinitionPropertyType.Any, default = True, read_only = True)
  104. # this setting can be changed for each group in one-at-a-time mode
  105. SettingDefinition.addSupportedProperty("settable_per_meshgroup", DefinitionPropertyType.Any, default = True, read_only = True)
  106. SettingDefinition.addSupportedProperty("settable_globally", DefinitionPropertyType.Any, default = True, read_only = True)
  107. # From which stack the setting would inherit if not defined per object (handled in the engine)
  108. # AND for settings which are not settable_per_mesh:
  109. # which extruder is the only extruder this setting is obtained from
  110. SettingDefinition.addSupportedProperty("limit_to_extruder", DefinitionPropertyType.Function, default = "-1")
  111. # For settings which are not settable_per_mesh and not settable_per_extruder:
  112. # A function which determines the glabel/meshgroup value by looking at the values of the setting in all (used) extruders
  113. SettingDefinition.addSupportedProperty("resolve", DefinitionPropertyType.Function, default = None, depends_on = "value")
  114. SettingDefinition.addSettingType("extruder", None, str, Validator)
  115. SettingDefinition.addSettingType("[int]", None, str, None)
  116. SettingFunction.registerOperator("extruderValues", ExtruderManager.getExtruderValues)
  117. SettingFunction.registerOperator("extruderValue", ExtruderManager.getExtruderValue)
  118. SettingFunction.registerOperator("resolveOrValue", ExtruderManager.getResolveOrValue)
  119. ## Add the 4 types of profiles to storage.
  120. Resources.addStorageType(self.ResourceTypes.QualityInstanceContainer, "quality")
  121. Resources.addStorageType(self.ResourceTypes.VariantInstanceContainer, "variants")
  122. Resources.addStorageType(self.ResourceTypes.MaterialInstanceContainer, "materials")
  123. Resources.addStorageType(self.ResourceTypes.UserInstanceContainer, "user")
  124. Resources.addStorageType(self.ResourceTypes.ExtruderStack, "extruders")
  125. Resources.addStorageType(self.ResourceTypes.MachineStack, "machine_instances")
  126. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.QualityInstanceContainer)
  127. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.VariantInstanceContainer)
  128. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MaterialInstanceContainer)
  129. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.UserInstanceContainer)
  130. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.ExtruderStack)
  131. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MachineStack)
  132. ## Initialise the version upgrade manager with Cura's storage paths.
  133. import UM.VersionUpgradeManager #Needs to be here to prevent circular dependencies.
  134. UM.VersionUpgradeManager.VersionUpgradeManager.getInstance().setCurrentVersions(
  135. {
  136. ("quality", InstanceContainer.Version): (self.ResourceTypes.QualityInstanceContainer, "application/x-uranium-instancecontainer"),
  137. ("machine_stack", ContainerStack.Version): (self.ResourceTypes.MachineStack, "application/x-uranium-containerstack"),
  138. ("extruder_train", ContainerStack.Version): (self.ResourceTypes.ExtruderStack, "application/x-uranium-extruderstack"),
  139. ("preferences", Preferences.Version): (Resources.Preferences, "application/x-uranium-preferences"),
  140. ("user", InstanceContainer.Version): (self.ResourceTypes.UserInstanceContainer, "application/x-uranium-instancecontainer")
  141. }
  142. )
  143. self._currently_loading_files = []
  144. self._non_sliceable_extensions = []
  145. self._machine_action_manager = MachineActionManager.MachineActionManager()
  146. self._machine_manager = None # This is initialized on demand.
  147. self._setting_inheritance_manager = None
  148. self._additional_components = {} # Components to add to certain areas in the interface
  149. super().__init__(name = "cura", version = CuraVersion, buildtype = CuraBuildType)
  150. self.setWindowIcon(QIcon(Resources.getPath(Resources.Images, "cura-icon.png")))
  151. self.setRequiredPlugins([
  152. "CuraEngineBackend",
  153. "MeshView",
  154. "LayerView",
  155. "STLReader",
  156. "SelectionTool",
  157. "CameraTool",
  158. "GCodeWriter",
  159. "LocalFileOutputDevice"
  160. ])
  161. self._physics = None
  162. self._volume = None
  163. self._output_devices = {}
  164. self._print_information = None
  165. self._previous_active_tool = None
  166. self._platform_activity = False
  167. self._scene_bounding_box = AxisAlignedBox.Null
  168. self._job_name = None
  169. self._center_after_select = False
  170. self._camera_animation = None
  171. self._cura_actions = None
  172. self._started = False
  173. self._message_box_callback = None
  174. self._message_box_callback_arguments = []
  175. self._preferred_mimetype = ""
  176. self._i18n_catalog = i18nCatalog("cura")
  177. self.getController().getScene().sceneChanged.connect(self.updatePlatformActivity)
  178. self.getController().toolOperationStopped.connect(self._onToolOperationStopped)
  179. Resources.addType(self.ResourceTypes.QmlFiles, "qml")
  180. Resources.addType(self.ResourceTypes.Firmware, "firmware")
  181. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading machines..."))
  182. # Add empty variant, material and quality containers.
  183. # Since they are empty, they should never be serialized and instead just programmatically created.
  184. # We need them to simplify the switching between materials.
  185. empty_container = ContainerRegistry.getInstance().getEmptyInstanceContainer()
  186. empty_variant_container = copy.deepcopy(empty_container)
  187. empty_variant_container._id = "empty_variant"
  188. empty_variant_container.addMetaDataEntry("type", "variant")
  189. ContainerRegistry.getInstance().addContainer(empty_variant_container)
  190. empty_material_container = copy.deepcopy(empty_container)
  191. empty_material_container._id = "empty_material"
  192. empty_material_container.addMetaDataEntry("type", "material")
  193. ContainerRegistry.getInstance().addContainer(empty_material_container)
  194. empty_quality_container = copy.deepcopy(empty_container)
  195. empty_quality_container._id = "empty_quality"
  196. empty_quality_container.setName("Not Supported")
  197. empty_quality_container.addMetaDataEntry("quality_type", "normal")
  198. empty_quality_container.addMetaDataEntry("type", "quality")
  199. ContainerRegistry.getInstance().addContainer(empty_quality_container)
  200. empty_quality_changes_container = copy.deepcopy(empty_container)
  201. empty_quality_changes_container._id = "empty_quality_changes"
  202. empty_quality_changes_container.addMetaDataEntry("type", "quality_changes")
  203. ContainerRegistry.getInstance().addContainer(empty_quality_changes_container)
  204. with ContainerRegistry.getInstance().lockFile():
  205. ContainerRegistry.getInstance().load()
  206. Preferences.getInstance().addPreference("cura/active_mode", "simple")
  207. Preferences.getInstance().addPreference("cura/recent_files", "")
  208. Preferences.getInstance().addPreference("cura/categories_expanded", "")
  209. Preferences.getInstance().addPreference("cura/jobname_prefix", True)
  210. Preferences.getInstance().addPreference("view/center_on_select", False)
  211. Preferences.getInstance().addPreference("mesh/scale_to_fit", False)
  212. Preferences.getInstance().addPreference("mesh/scale_tiny_meshes", True)
  213. Preferences.getInstance().addPreference("cura/dialog_on_project_save", True)
  214. Preferences.getInstance().addPreference("cura/asked_dialog_on_project_save", False)
  215. Preferences.getInstance().addPreference("cura/choice_on_profile_override", "always_ask")
  216. Preferences.getInstance().addPreference("cura/choice_on_open_project", "always_ask")
  217. Preferences.getInstance().addPreference("cura/currency", "€")
  218. Preferences.getInstance().addPreference("cura/material_settings", "{}")
  219. Preferences.getInstance().addPreference("view/invert_zoom", False)
  220. for key in [
  221. "dialog_load_path", # dialog_save_path is in LocalFileOutputDevicePlugin
  222. "dialog_profile_path",
  223. "dialog_material_path"]:
  224. Preferences.getInstance().addPreference("local_file/%s" % key, os.path.expanduser("~/"))
  225. Preferences.getInstance().setDefault("local_file/last_used_type", "text/x-gcode")
  226. Preferences.getInstance().setDefault("general/visible_settings", """
  227. machine_settings
  228. resolution
  229. layer_height
  230. shell
  231. wall_thickness
  232. top_bottom_thickness
  233. z_seam_x
  234. z_seam_y
  235. infill
  236. infill_sparse_density
  237. material
  238. material_print_temperature
  239. material_bed_temperature
  240. material_diameter
  241. material_flow
  242. retraction_enable
  243. speed
  244. speed_print
  245. speed_travel
  246. acceleration_print
  247. acceleration_travel
  248. jerk_print
  249. jerk_travel
  250. travel
  251. cooling
  252. cool_fan_enabled
  253. support
  254. support_enable
  255. support_extruder_nr
  256. support_type
  257. support_interface_density
  258. platform_adhesion
  259. adhesion_type
  260. adhesion_extruder_nr
  261. brim_width
  262. raft_airgap
  263. layer_0_z_overlap
  264. raft_surface_layers
  265. dual
  266. prime_tower_enable
  267. prime_tower_size
  268. prime_tower_position_x
  269. prime_tower_position_y
  270. meshfix
  271. blackmagic
  272. print_sequence
  273. infill_mesh
  274. experimental
  275. """.replace("\n", ";").replace(" ", ""))
  276. JobQueue.getInstance().jobFinished.connect(self._onJobFinished)
  277. self.applicationShuttingDown.connect(self.saveSettings)
  278. self.engineCreatedSignal.connect(self._onEngineCreated)
  279. self.globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  280. self._onGlobalContainerChanged()
  281. self._recent_files = []
  282. files = Preferences.getInstance().getValue("cura/recent_files").split(";")
  283. for f in files:
  284. if not os.path.isfile(f):
  285. continue
  286. self._recent_files.append(QUrl.fromLocalFile(f))
  287. def _onEngineCreated(self):
  288. self._engine.addImageProvider("camera", CameraImageProvider.CameraImageProvider())
  289. ## A reusable dialogbox
  290. #
  291. showMessageBox = pyqtSignal(str, str, str, str, int, int, arguments = ["title", "text", "informativeText", "detailedText", "buttons", "icon"])
  292. def messageBox(self, title, text, informativeText = "", detailedText = "", buttons = QMessageBox.Ok, icon = QMessageBox.NoIcon, callback = None, callback_arguments = []):
  293. self._message_box_callback = callback
  294. self._message_box_callback_arguments = callback_arguments
  295. self.showMessageBox.emit(title, text, informativeText, detailedText, buttons, icon)
  296. showDiscardOrKeepProfileChanges = pyqtSignal()
  297. def discardOrKeepProfileChanges(self):
  298. choice = Preferences.getInstance().getValue("cura/choice_on_profile_override")
  299. if choice == "always_discard":
  300. # don't show dialog and DISCARD the profile
  301. self.discardOrKeepProfileChangesClosed("discard")
  302. elif choice == "always_keep":
  303. # don't show dialog and KEEP the profile
  304. self.discardOrKeepProfileChangesClosed("keep")
  305. else:
  306. # ALWAYS ask whether to keep or discard the profile
  307. self.showDiscardOrKeepProfileChanges.emit()
  308. @pyqtSlot(str)
  309. def discardOrKeepProfileChangesClosed(self, option):
  310. if option == "discard":
  311. global_stack = self.getGlobalContainerStack()
  312. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  313. extruder.getTop().clear()
  314. global_stack.getTop().clear()
  315. @pyqtSlot(int)
  316. def messageBoxClosed(self, button):
  317. if self._message_box_callback:
  318. self._message_box_callback(button, *self._message_box_callback_arguments)
  319. self._message_box_callback = None
  320. self._message_box_callback_arguments = []
  321. showPrintMonitor = pyqtSignal(bool, arguments = ["show"])
  322. ## Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
  323. #
  324. # Note that the AutoSave plugin also calls this method.
  325. def saveSettings(self):
  326. if not self._started: # Do not do saving during application start
  327. return
  328. # Lock file for "more" atomically loading and saving to/from config dir.
  329. with ContainerRegistry.getInstance().lockFile():
  330. for instance in ContainerRegistry.getInstance().findInstanceContainers():
  331. if not instance.isDirty():
  332. continue
  333. try:
  334. data = instance.serialize()
  335. except NotImplementedError:
  336. continue
  337. except Exception:
  338. Logger.logException("e", "An exception occurred when serializing container %s", instance.getId())
  339. continue
  340. mime_type = ContainerRegistry.getMimeTypeForContainer(type(instance))
  341. file_name = urllib.parse.quote_plus(instance.getId()) + "." + mime_type.preferredSuffix
  342. instance_type = instance.getMetaDataEntry("type")
  343. path = None
  344. if instance_type == "material":
  345. path = Resources.getStoragePath(self.ResourceTypes.MaterialInstanceContainer, file_name)
  346. elif instance_type == "quality" or instance_type == "quality_changes":
  347. path = Resources.getStoragePath(self.ResourceTypes.QualityInstanceContainer, file_name)
  348. elif instance_type == "user":
  349. path = Resources.getStoragePath(self.ResourceTypes.UserInstanceContainer, file_name)
  350. elif instance_type == "variant":
  351. path = Resources.getStoragePath(self.ResourceTypes.VariantInstanceContainer, file_name)
  352. elif instance_type == "definition_changes":
  353. path = Resources.getStoragePath(self.ResourceTypes.MachineStack, file_name)
  354. if path:
  355. instance.setPath(path)
  356. with SaveFile(path, "wt") as f:
  357. f.write(data)
  358. for stack in ContainerRegistry.getInstance().findContainerStacks():
  359. self.saveStack(stack)
  360. def saveStack(self, stack):
  361. if not stack.isDirty():
  362. return
  363. try:
  364. data = stack.serialize()
  365. except NotImplementedError:
  366. return
  367. except Exception:
  368. Logger.logException("e", "An exception occurred when serializing container %s", stack.getId())
  369. return
  370. mime_type = ContainerRegistry.getMimeTypeForContainer(type(stack))
  371. file_name = urllib.parse.quote_plus(stack.getId()) + "." + mime_type.preferredSuffix
  372. stack_type = stack.getMetaDataEntry("type", None)
  373. path = None
  374. if not stack_type or stack_type == "machine":
  375. path = Resources.getStoragePath(self.ResourceTypes.MachineStack, file_name)
  376. elif stack_type == "extruder_train":
  377. path = Resources.getStoragePath(self.ResourceTypes.ExtruderStack, file_name)
  378. if path:
  379. stack.setPath(path)
  380. with SaveFile(path, "wt") as f:
  381. f.write(data)
  382. @pyqtSlot(str, result = QUrl)
  383. def getDefaultPath(self, key):
  384. default_path = Preferences.getInstance().getValue("local_file/%s" % key)
  385. return QUrl.fromLocalFile(default_path)
  386. @pyqtSlot(str, str)
  387. def setDefaultPath(self, key, default_path):
  388. Preferences.getInstance().setValue("local_file/%s" % key, QUrl(default_path).toLocalFile())
  389. @classmethod
  390. def getStaticVersion(cls):
  391. return CuraVersion
  392. ## Handle loading of all plugin types (and the backend explicitly)
  393. # \sa PluginRegistery
  394. def _loadPlugins(self):
  395. self._plugin_registry.addType("profile_reader", self._addProfileReader)
  396. self._plugin_registry.addType("profile_writer", self._addProfileWriter)
  397. self._plugin_registry.addPluginLocation(os.path.join(QtApplication.getInstallPrefix(), "lib", "cura"))
  398. if not hasattr(sys, "frozen"):
  399. self._plugin_registry.addPluginLocation(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "plugins"))
  400. self._plugin_registry.loadPlugin("ConsoleLogger")
  401. self._plugin_registry.loadPlugin("CuraEngineBackend")
  402. self._plugin_registry.loadPlugins()
  403. if self.getBackend() == None:
  404. raise RuntimeError("Could not load the backend plugin!")
  405. self._plugins_loaded = True
  406. @classmethod
  407. def addCommandLineOptions(self, parser):
  408. super().addCommandLineOptions(parser)
  409. parser.add_argument("file", nargs="*", help="Files to load after starting the application.")
  410. parser.add_argument("--single-instance", action="store_true", default=False)
  411. # Set up a local socket server which listener which coordinates single instances Curas and accepts commands.
  412. def _setUpSingleInstanceServer(self):
  413. if self.getCommandLineOption("single_instance", False):
  414. self.__single_instance_server = QLocalServer()
  415. self.__single_instance_server.newConnection.connect(self._singleInstanceServerNewConnection)
  416. self.__single_instance_server.listen("ultimaker-cura")
  417. def _singleInstanceServerNewConnection(self):
  418. Logger.log("i", "New connection recevied on our single-instance server")
  419. remote_cura_connection = self.__single_instance_server.nextPendingConnection()
  420. if remote_cura_connection is not None:
  421. def readCommands():
  422. line = remote_cura_connection.readLine()
  423. while len(line) != 0: # There is also a .canReadLine()
  424. try:
  425. payload = json.loads(str(line, encoding="ASCII").strip())
  426. command = payload["command"]
  427. # Command: Remove all models from the build plate.
  428. if command == "clear-all":
  429. self.deleteAll()
  430. # Command: Load a model file
  431. elif command == "open":
  432. self._openFile(payload["filePath"])
  433. # WARNING ^ this method is async and we really should wait until
  434. # the file load is complete before processing more commands.
  435. # Command: Activate the window and bring it to the top.
  436. elif command == "focus":
  437. # Operating systems these days prevent windows from moving around by themselves.
  438. # 'alert' or flashing the icon in the taskbar is the best thing we do now.
  439. self.getMainWindow().alert(0)
  440. # Command: Close the socket connection. We're done.
  441. elif command == "close-connection":
  442. remote_cura_connection.close()
  443. else:
  444. Logger.log("w", "Received an unrecognized command " + str(command))
  445. except json.decoder.JSONDecodeError as ex:
  446. Logger.log("w", "Unable to parse JSON command in _singleInstanceServerNewConnection(): " + repr(ex))
  447. line = remote_cura_connection.readLine()
  448. remote_cura_connection.readyRead.connect(readCommands)
  449. ## Perform any checks before creating the main application.
  450. #
  451. # This should be called directly before creating an instance of CuraApplication.
  452. # \returns \type{bool} True if the whole Cura app should continue running.
  453. @classmethod
  454. def preStartUp(cls):
  455. # Peek the arguments and look for the 'single-instance' flag.
  456. parser = argparse.ArgumentParser(prog="cura") # pylint: disable=bad-whitespace
  457. CuraApplication.addCommandLineOptions(parser)
  458. parsed_command_line = vars(parser.parse_args())
  459. if "single_instance" in parsed_command_line and parsed_command_line["single_instance"]:
  460. Logger.log("i", "Checking for the presence of an ready running Cura instance.")
  461. single_instance_socket = QLocalSocket()
  462. Logger.log("d", "preStartUp(): full server name: " + single_instance_socket.fullServerName())
  463. single_instance_socket.connectToServer("ultimaker-cura")
  464. single_instance_socket.waitForConnected()
  465. if single_instance_socket.state() == QLocalSocket.ConnectedState:
  466. Logger.log("i", "Connection has been made to the single-instance Cura socket.")
  467. # Protocol is one line of JSON terminated with a carriage return.
  468. # "command" field is required and holds the name of the command to execute.
  469. # Other fields depend on the command.
  470. payload = {"command": "clear-all"}
  471. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  472. payload = {"command": "focus"}
  473. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  474. if len(parsed_command_line["file"]) != 0:
  475. for filename in parsed_command_line["file"]:
  476. payload = {"command": "open", "filePath": filename}
  477. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  478. payload = {"command": "close-connection"}
  479. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  480. single_instance_socket.flush()
  481. single_instance_socket.waitForDisconnected()
  482. return False
  483. return True
  484. def run(self):
  485. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Setting up scene..."))
  486. self._setUpSingleInstanceServer()
  487. controller = self.getController()
  488. controller.setActiveView("SolidView")
  489. controller.setCameraTool("CameraTool")
  490. controller.setSelectionTool("SelectionTool")
  491. t = controller.getTool("TranslateTool")
  492. if t:
  493. t.setEnabledAxis([ToolHandle.XAxis, ToolHandle.YAxis,ToolHandle.ZAxis])
  494. Selection.selectionChanged.connect(self.onSelectionChanged)
  495. root = controller.getScene().getRoot()
  496. # The platform is a child of BuildVolume
  497. self._volume = BuildVolume.BuildVolume(root)
  498. self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
  499. self._physics = PlatformPhysics.PlatformPhysics(controller, self._volume)
  500. camera = Camera("3d", root)
  501. camera.setPosition(Vector(-80, 250, 700))
  502. camera.setPerspective(True)
  503. camera.lookAt(Vector(0, 0, 0))
  504. controller.getScene().setActiveCamera("3d")
  505. self.getController().getTool("CameraTool").setOrigin(Vector(0, 100, 0))
  506. self._camera_animation = CameraAnimation.CameraAnimation()
  507. self._camera_animation.setCameraTool(self.getController().getTool("CameraTool"))
  508. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading interface..."))
  509. # Initialise extruder so as to listen to global container stack changes before the first global container stack is set.
  510. ExtruderManager.getInstance()
  511. qmlRegisterSingletonType(MachineManager, "Cura", 1, 0, "MachineManager", self.getMachineManager)
  512. qmlRegisterSingletonType(SettingInheritanceManager, "Cura", 1, 0, "SettingInheritanceManager",
  513. self.getSettingInheritanceManager)
  514. qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, "MachineActionManager", self.getMachineActionManager)
  515. self.setMainQml(Resources.getPath(self.ResourceTypes.QmlFiles, "Cura.qml"))
  516. self._qml_import_paths.append(Resources.getPath(self.ResourceTypes.QmlFiles))
  517. self.initializeEngine()
  518. if self._engine.rootObjects:
  519. self.closeSplash()
  520. for file in self.getCommandLineOption("file", []):
  521. self._openFile(file)
  522. for file_name in self._open_file_queue: #Open all the files that were queued up while plug-ins were loading.
  523. self._openFile(file_name)
  524. self._started = True
  525. self.exec_()
  526. def getMachineManager(self, *args):
  527. if self._machine_manager is None:
  528. self._machine_manager = MachineManager.createMachineManager()
  529. return self._machine_manager
  530. def getSettingInheritanceManager(self, *args):
  531. if self._setting_inheritance_manager is None:
  532. self._setting_inheritance_manager = SettingInheritanceManager.createSettingInheritanceManager()
  533. return self._setting_inheritance_manager
  534. ## Get the machine action manager
  535. # We ignore any *args given to this, as we also register the machine manager as qml singleton.
  536. # It wants to give this function an engine and script engine, but we don't care about that.
  537. def getMachineActionManager(self, *args):
  538. return self._machine_action_manager
  539. ## Handle Qt events
  540. def event(self, event):
  541. if event.type() == QEvent.FileOpen:
  542. if self._plugins_loaded:
  543. self._openFile(event.file())
  544. else:
  545. self._open_file_queue.append(event.file())
  546. return super().event(event)
  547. ## Get print information (duration / material used)
  548. def getPrintInformation(self):
  549. return self._print_information
  550. ## Registers objects for the QML engine to use.
  551. #
  552. # \param engine The QML engine.
  553. def registerObjects(self, engine):
  554. engine.rootContext().setContextProperty("Printer", self)
  555. engine.rootContext().setContextProperty("CuraApplication", self)
  556. self._print_information = PrintInformation.PrintInformation()
  557. engine.rootContext().setContextProperty("PrintInformation", self._print_information)
  558. self._cura_actions = CuraActions.CuraActions(self)
  559. engine.rootContext().setContextProperty("CuraActions", self._cura_actions)
  560. qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")
  561. qmlRegisterType(ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")
  562. qmlRegisterType(ContainerSettingsModel, "Cura", 1, 0, "ContainerSettingsModel")
  563. qmlRegisterSingletonType(ProfilesModel, "Cura", 1, 0, "ProfilesModel", ProfilesModel.createProfilesModel)
  564. qmlRegisterType(QualityAndUserProfilesModel, "Cura", 1, 0, "QualityAndUserProfilesModel")
  565. qmlRegisterType(UserProfilesModel, "Cura", 1, 0, "UserProfilesModel")
  566. qmlRegisterType(MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
  567. qmlRegisterType(QualitySettingsModel, "Cura", 1, 0, "QualitySettingsModel")
  568. qmlRegisterType(MachineNameValidator, "Cura", 1, 0, "MachineNameValidator")
  569. qmlRegisterType(UserChangesModel, "Cura", 1, 1, "UserChangesModel")
  570. qmlRegisterSingletonType(ContainerManager, "Cura", 1, 0, "ContainerManager", ContainerManager.createContainerManager)
  571. # As of Qt5.7, it is necessary to get rid of any ".." in the path for the singleton to work.
  572. actions_url = QUrl.fromLocalFile(os.path.abspath(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")))
  573. qmlRegisterSingletonType(actions_url, "Cura", 1, 0, "Actions")
  574. engine.rootContext().setContextProperty("ExtruderManager", ExtruderManager.getInstance())
  575. for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
  576. type_name = os.path.splitext(os.path.basename(path))[0]
  577. if type_name in ("Cura", "Actions"):
  578. continue
  579. qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
  580. ## Get the backend of the application (the program that does the heavy lifting).
  581. # The backend is also a QObject, which can be used from qml.
  582. # \returns Backend \type{Backend}
  583. @pyqtSlot(result = "QObject*")
  584. def getBackend(self):
  585. return self._backend
  586. def onSelectionChanged(self):
  587. if Selection.hasSelection():
  588. if self.getController().getActiveTool():
  589. # If the tool has been disabled by the new selection
  590. if not self.getController().getActiveTool().getEnabled():
  591. # Default
  592. self.getController().setActiveTool("TranslateTool")
  593. else:
  594. if self._previous_active_tool:
  595. self.getController().setActiveTool(self._previous_active_tool)
  596. if not self.getController().getActiveTool().getEnabled():
  597. self.getController().setActiveTool("TranslateTool")
  598. self._previous_active_tool = None
  599. else:
  600. # Default
  601. self.getController().setActiveTool("TranslateTool")
  602. if Preferences.getInstance().getValue("view/center_on_select"):
  603. self._center_after_select = True
  604. else:
  605. if self.getController().getActiveTool():
  606. self._previous_active_tool = self.getController().getActiveTool().getPluginId()
  607. self.getController().setActiveTool(None)
  608. def _onToolOperationStopped(self, event):
  609. if self._center_after_select and Selection.getSelectedObject(0) is not None:
  610. self._center_after_select = False
  611. self._camera_animation.setStart(self.getController().getTool("CameraTool").getOrigin())
  612. self._camera_animation.setTarget(Selection.getSelectedObject(0).getWorldPosition())
  613. self._camera_animation.start()
  614. def _onGlobalContainerChanged(self):
  615. if self._global_container_stack is not None:
  616. machine_file_formats = [file_type.strip() for file_type in self._global_container_stack.getMetaDataEntry("file_formats").split(";")]
  617. new_preferred_mimetype = ""
  618. if machine_file_formats:
  619. new_preferred_mimetype = machine_file_formats[0]
  620. if new_preferred_mimetype != self._preferred_mimetype:
  621. self._preferred_mimetype = new_preferred_mimetype
  622. self.preferredOutputMimetypeChanged.emit()
  623. requestAddPrinter = pyqtSignal()
  624. activityChanged = pyqtSignal()
  625. sceneBoundingBoxChanged = pyqtSignal()
  626. preferredOutputMimetypeChanged = pyqtSignal()
  627. @pyqtProperty(bool, notify = activityChanged)
  628. def platformActivity(self):
  629. return self._platform_activity
  630. @pyqtProperty(str, notify=preferredOutputMimetypeChanged)
  631. def preferredOutputMimetype(self):
  632. return self._preferred_mimetype
  633. @pyqtProperty(str, notify = sceneBoundingBoxChanged)
  634. def getSceneBoundingBoxString(self):
  635. 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()}
  636. def updatePlatformActivity(self, node = None):
  637. count = 0
  638. scene_bounding_box = None
  639. is_block_slicing_node = False
  640. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  641. if type(node) is not SceneNode or (not node.getMeshData() and not node.callDecoration("getLayerData")):
  642. continue
  643. if node.callDecoration("isBlockSlicing"):
  644. is_block_slicing_node = True
  645. count += 1
  646. if not scene_bounding_box:
  647. scene_bounding_box = node.getBoundingBox()
  648. else:
  649. other_bb = node.getBoundingBox()
  650. if other_bb is not None:
  651. scene_bounding_box = scene_bounding_box + node.getBoundingBox()
  652. print_information = self.getPrintInformation()
  653. if print_information:
  654. print_information.setPreSliced(is_block_slicing_node)
  655. if not scene_bounding_box:
  656. scene_bounding_box = AxisAlignedBox.Null
  657. if repr(self._scene_bounding_box) != repr(scene_bounding_box) and scene_bounding_box.isValid():
  658. self._scene_bounding_box = scene_bounding_box
  659. self.sceneBoundingBoxChanged.emit()
  660. self._platform_activity = True if count > 0 else False
  661. self.activityChanged.emit()
  662. # Remove all selected objects from the scene.
  663. @pyqtSlot()
  664. def deleteSelection(self):
  665. if not self.getController().getToolsEnabled():
  666. return
  667. removed_group_nodes = []
  668. op = GroupedOperation()
  669. nodes = Selection.getAllSelectedObjects()
  670. for node in nodes:
  671. op.addOperation(RemoveSceneNodeOperation(node))
  672. group_node = node.getParent()
  673. if group_node and group_node.callDecoration("isGroup") and group_node not in removed_group_nodes:
  674. remaining_nodes_in_group = list(set(group_node.getChildren()) - set(nodes))
  675. if len(remaining_nodes_in_group) == 1:
  676. removed_group_nodes.append(group_node)
  677. op.addOperation(SetParentOperation(remaining_nodes_in_group[0], group_node.getParent()))
  678. op.addOperation(RemoveSceneNodeOperation(group_node))
  679. op.push()
  680. ## Remove an object from the scene.
  681. # Note that this only removes an object if it is selected.
  682. @pyqtSlot("quint64")
  683. def deleteObject(self, object_id):
  684. if not self.getController().getToolsEnabled():
  685. return
  686. node = self.getController().getScene().findObject(object_id)
  687. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  688. node = Selection.getSelectedObject(0)
  689. if node:
  690. op = GroupedOperation()
  691. op.addOperation(RemoveSceneNodeOperation(node))
  692. group_node = node.getParent()
  693. if group_node:
  694. # Note that at this point the node has not yet been deleted
  695. if len(group_node.getChildren()) <= 2 and group_node.callDecoration("isGroup"):
  696. op.addOperation(SetParentOperation(group_node.getChildren()[0], group_node.getParent()))
  697. op.addOperation(RemoveSceneNodeOperation(group_node))
  698. op.push()
  699. ## Create a number of copies of existing object.
  700. # \param object_id
  701. # \param count number of copies
  702. # \param min_offset minimum offset to other objects.
  703. @pyqtSlot("quint64", int)
  704. def multiplyObject(self, object_id, count, min_offset = 8):
  705. node = self.getController().getScene().findObject(object_id)
  706. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  707. node = Selection.getSelectedObject(0)
  708. # If object is part of a group, multiply group
  709. current_node = node
  710. while current_node.getParent() and current_node.getParent().callDecoration("isGroup"):
  711. current_node = current_node.getParent()
  712. root = self.getController().getScene().getRoot()
  713. arranger = Arrange.create(scene_root = root)
  714. offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(current_node, min_offset = min_offset)
  715. nodes = arranger.findNodePlacements(current_node, offset_shape_arr, hull_shape_arr, count = count)
  716. if nodes:
  717. op = GroupedOperation()
  718. for new_node in nodes:
  719. op.addOperation(AddSceneNodeOperation(new_node, current_node.getParent()))
  720. op.push()
  721. ## Center object on platform.
  722. @pyqtSlot("quint64")
  723. def centerObject(self, object_id):
  724. node = self.getController().getScene().findObject(object_id)
  725. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  726. node = Selection.getSelectedObject(0)
  727. if not node:
  728. return
  729. if node.getParent() and node.getParent().callDecoration("isGroup"):
  730. node = node.getParent()
  731. if node:
  732. op = SetTransformOperation(node, Vector())
  733. op.push()
  734. ## Select all nodes containing mesh data in the scene.
  735. @pyqtSlot()
  736. def selectAll(self):
  737. if not self.getController().getToolsEnabled():
  738. return
  739. Selection.clear()
  740. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  741. if type(node) is not SceneNode:
  742. continue
  743. if not node.getMeshData() and not node.callDecoration("isGroup"):
  744. continue # Node that doesnt have a mesh and is not a group.
  745. if node.getParent() and node.getParent().callDecoration("isGroup"):
  746. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  747. if not node.isSelectable():
  748. continue # i.e. node with layer data
  749. Selection.add(node)
  750. ## Delete all nodes containing mesh data in the scene.
  751. @pyqtSlot()
  752. def deleteAll(self):
  753. Logger.log("i", "Clearing scene")
  754. if not self.getController().getToolsEnabled():
  755. return
  756. nodes = []
  757. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  758. if type(node) is not SceneNode:
  759. continue
  760. if (not node.getMeshData() and not node.callDecoration("getLayerData")) and not node.callDecoration("isGroup"):
  761. continue # Node that doesnt have a mesh and is not a group.
  762. if node.getParent() and node.getParent().callDecoration("isGroup"):
  763. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  764. nodes.append(node)
  765. if nodes:
  766. op = GroupedOperation()
  767. for node in nodes:
  768. op.addOperation(RemoveSceneNodeOperation(node))
  769. op.push()
  770. Selection.clear()
  771. ## Reset all translation on nodes with mesh data.
  772. @pyqtSlot()
  773. def resetAllTranslation(self):
  774. Logger.log("i", "Resetting all scene translations")
  775. nodes = []
  776. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  777. if type(node) is not SceneNode:
  778. continue
  779. if not node.getMeshData() and not node.callDecoration("isGroup"):
  780. continue # Node that doesnt have a mesh and is not a group.
  781. if node.getParent() and node.getParent().callDecoration("isGroup"):
  782. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  783. if not node.isSelectable():
  784. continue # i.e. node with layer data
  785. nodes.append(node)
  786. if nodes:
  787. op = GroupedOperation()
  788. for node in nodes:
  789. # Ensure that the object is above the build platform
  790. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  791. if node.getBoundingBox():
  792. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  793. else:
  794. center_y = 0
  795. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0)))
  796. op.push()
  797. ## Reset all transformations on nodes with mesh data.
  798. @pyqtSlot()
  799. def resetAll(self):
  800. Logger.log("i", "Resetting all scene transformations")
  801. nodes = []
  802. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  803. if type(node) is not SceneNode:
  804. continue
  805. if not node.getMeshData() and not node.callDecoration("isGroup"):
  806. continue # Node that doesnt have a mesh and is not a group.
  807. if node.getParent() and node.getParent().callDecoration("isGroup"):
  808. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  809. if not node.isSelectable():
  810. continue # i.e. node with layer data
  811. nodes.append(node)
  812. if nodes:
  813. op = GroupedOperation()
  814. for node in nodes:
  815. # Ensure that the object is above the build platform
  816. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  817. if node.getBoundingBox():
  818. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  819. else:
  820. center_y = 0
  821. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0), Quaternion(), Vector(1, 1, 1)))
  822. op.push()
  823. ## Arrange all objects.
  824. @pyqtSlot()
  825. def arrangeAll(self):
  826. nodes = []
  827. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  828. if type(node) is not SceneNode:
  829. continue
  830. if not node.getMeshData() and not node.callDecoration("isGroup"):
  831. continue # Node that doesnt have a mesh and is not a group.
  832. if node.getParent() and node.getParent().callDecoration("isGroup"):
  833. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  834. if not node.isSelectable():
  835. continue # i.e. node with layer data
  836. nodes.append(node)
  837. self.arrange(nodes, fixed_nodes = [])
  838. ## Arrange Selection
  839. @pyqtSlot()
  840. def arrangeSelection(self):
  841. nodes = Selection.getAllSelectedObjects()
  842. # What nodes are on the build plate and are not being moved
  843. fixed_nodes = []
  844. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  845. if type(node) is not SceneNode:
  846. continue
  847. if not node.getMeshData() and not node.callDecoration("isGroup"):
  848. continue # Node that doesnt have a mesh and is not a group.
  849. if node.getParent() and node.getParent().callDecoration("isGroup"):
  850. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  851. if not node.isSelectable():
  852. continue # i.e. node with layer data
  853. if node in nodes: # exclude selected node from fixed_nodes
  854. continue
  855. fixed_nodes.append(node)
  856. self.arrange(nodes, fixed_nodes)
  857. ## Arrange the nodes, given fixed nodes
  858. # \param nodes nodes that we have to place
  859. # \param fixed_nodes nodes that are placed in the arranger before finding spots for nodes
  860. def arrange(self, nodes, fixed_nodes):
  861. min_offset = 8
  862. arranger = Arrange.create(fixed_nodes = fixed_nodes)
  863. # Collect nodes to be placed
  864. nodes_arr = [] # fill with (size, node, offset_shape_arr, hull_shape_arr)
  865. for node in nodes:
  866. offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = min_offset)
  867. nodes_arr.append((offset_shape_arr.arr.shape[0] * offset_shape_arr.arr.shape[1], node, offset_shape_arr, hull_shape_arr))
  868. # Sort nodes biggest area first
  869. nodes_arr.sort(key = lambda item: item[0])
  870. nodes_arr.reverse()
  871. # Place nodes one at a time
  872. start_prio = 0
  873. for size, node, offset_shape_arr, hull_shape_arr in nodes_arr:
  874. # For performance reasons, we assume that when a location does not fit,
  875. # it will also not fit for the next object (while what can be untrue).
  876. # We also skip possibilities by slicing through the possibilities (step = 10)
  877. best_spot = arranger.bestSpot(offset_shape_arr, start_prio = start_prio, step = 10)
  878. x, y = best_spot.x, best_spot.y
  879. start_prio = best_spot.priority
  880. if x is not None: # We could find a place
  881. arranger.place(x, y, hull_shape_arr) # take place before the next one
  882. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  883. if node.getBoundingBox():
  884. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  885. else:
  886. center_y = 0
  887. op = GroupedOperation()
  888. op.addOperation(SetTransformOperation(node, Vector(x, center_y, y)))
  889. op.push()
  890. ## Reload all mesh data on the screen from file.
  891. @pyqtSlot()
  892. def reloadAll(self):
  893. Logger.log("i", "Reloading all loaded mesh data.")
  894. nodes = []
  895. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  896. if type(node) is not SceneNode or not node.getMeshData():
  897. continue
  898. nodes.append(node)
  899. if not nodes:
  900. return
  901. for node in nodes:
  902. file_name = node.getMeshData().getFileName()
  903. if file_name:
  904. job = ReadMeshJob(file_name)
  905. job._node = node
  906. job.finished.connect(self._reloadMeshFinished)
  907. job.start()
  908. else:
  909. Logger.log("w", "Unable to reload data because we don't have a filename.")
  910. ## Get logging data of the backend engine
  911. # \returns \type{string} Logging data
  912. @pyqtSlot(result = str)
  913. def getEngineLog(self):
  914. log = ""
  915. for entry in self.getBackend().getLog():
  916. log += entry.decode()
  917. return log
  918. recentFilesChanged = pyqtSignal()
  919. @pyqtProperty("QVariantList", notify = recentFilesChanged)
  920. def recentFiles(self):
  921. return self._recent_files
  922. @pyqtSlot("QStringList")
  923. def setExpandedCategories(self, categories):
  924. categories = list(set(categories))
  925. categories.sort()
  926. joined = ";".join(categories)
  927. if joined != Preferences.getInstance().getValue("cura/categories_expanded"):
  928. Preferences.getInstance().setValue("cura/categories_expanded", joined)
  929. self.expandedCategoriesChanged.emit()
  930. expandedCategoriesChanged = pyqtSignal()
  931. @pyqtProperty("QStringList", notify = expandedCategoriesChanged)
  932. def expandedCategories(self):
  933. return Preferences.getInstance().getValue("cura/categories_expanded").split(";")
  934. @pyqtSlot()
  935. def mergeSelected(self):
  936. self.groupSelected()
  937. try:
  938. group_node = Selection.getAllSelectedObjects()[0]
  939. except Exception as e:
  940. Logger.log("d", "mergeSelected: Exception:", e)
  941. return
  942. meshes = [node.getMeshData() for node in group_node.getAllChildren() if node.getMeshData()]
  943. # Compute the center of the objects
  944. object_centers = []
  945. # Forget about the translation that the original objects have
  946. zero_translation = Matrix(data=numpy.zeros(3))
  947. for mesh, node in zip(meshes, group_node.getChildren()):
  948. transformation = node.getLocalTransformation()
  949. transformation.setTranslation(zero_translation)
  950. transformed_mesh = mesh.getTransformed(transformation)
  951. center = transformed_mesh.getCenterPosition()
  952. object_centers.append(center)
  953. if object_centers and len(object_centers) > 0:
  954. middle_x = sum([v.x for v in object_centers]) / len(object_centers)
  955. middle_y = sum([v.y for v in object_centers]) / len(object_centers)
  956. middle_z = sum([v.z for v in object_centers]) / len(object_centers)
  957. offset = Vector(middle_x, middle_y, middle_z)
  958. else:
  959. offset = Vector(0, 0, 0)
  960. # Move each node to the same position.
  961. for mesh, node in zip(meshes, group_node.getChildren()):
  962. transformation = node.getLocalTransformation()
  963. transformation.setTranslation(zero_translation)
  964. transformed_mesh = mesh.getTransformed(transformation)
  965. # Align the object around its zero position
  966. # and also apply the offset to center it inside the group.
  967. node.setPosition(-transformed_mesh.getZeroPosition() - offset)
  968. # Use the previously found center of the group bounding box as the new location of the group
  969. group_node.setPosition(group_node.getBoundingBox().center)
  970. @pyqtSlot()
  971. def groupSelected(self):
  972. # Create a group-node
  973. group_node = SceneNode()
  974. group_decorator = GroupDecorator()
  975. group_node.addDecorator(group_decorator)
  976. group_node.setParent(self.getController().getScene().getRoot())
  977. group_node.setSelectable(True)
  978. center = Selection.getSelectionCenter()
  979. group_node.setPosition(center)
  980. group_node.setCenterPosition(center)
  981. # Move selected nodes into the group-node
  982. Selection.applyOperation(SetParentOperation, group_node)
  983. # Deselect individual nodes and select the group-node instead
  984. for node in group_node.getChildren():
  985. Selection.remove(node)
  986. Selection.add(group_node)
  987. @pyqtSlot()
  988. def ungroupSelected(self):
  989. selected_objects = Selection.getAllSelectedObjects().copy()
  990. for node in selected_objects:
  991. if node.callDecoration("isGroup"):
  992. op = GroupedOperation()
  993. group_parent = node.getParent()
  994. children = node.getChildren().copy()
  995. for child in children:
  996. # Set the parent of the children to the parent of the group-node
  997. op.addOperation(SetParentOperation(child, group_parent))
  998. # Add all individual nodes to the selection
  999. Selection.add(child)
  1000. op.push()
  1001. # Note: The group removes itself from the scene once all its children have left it,
  1002. # see GroupDecorator._onChildrenChanged
  1003. def _createSplashScreen(self):
  1004. return CuraSplashScreen.CuraSplashScreen()
  1005. def _onActiveMachineChanged(self):
  1006. pass
  1007. fileLoaded = pyqtSignal(str)
  1008. def _onJobFinished(self, job):
  1009. if (not isinstance(job, ReadMeshJob) and not isinstance(job, ReadFileJob)) or not job.getResult():
  1010. return
  1011. f = QUrl.fromLocalFile(job.getFileName())
  1012. if f in self._recent_files:
  1013. self._recent_files.remove(f)
  1014. self._recent_files.insert(0, f)
  1015. if len(self._recent_files) > 10:
  1016. del self._recent_files[10]
  1017. pref = ""
  1018. for path in self._recent_files:
  1019. pref += path.toLocalFile() + ";"
  1020. Preferences.getInstance().setValue("cura/recent_files", pref)
  1021. self.recentFilesChanged.emit()
  1022. def _reloadMeshFinished(self, job):
  1023. # TODO; This needs to be fixed properly. We now make the assumption that we only load a single mesh!
  1024. mesh_data = job.getResult()[0].getMeshData()
  1025. if mesh_data:
  1026. job._node.setMeshData(mesh_data)
  1027. else:
  1028. Logger.log("w", "Could not find a mesh in reloaded node.")
  1029. def _openFile(self, filename):
  1030. self.readLocalFile(QUrl.fromLocalFile(filename))
  1031. def _addProfileReader(self, profile_reader):
  1032. # TODO: Add the profile reader to the list of plug-ins that can be used when importing profiles.
  1033. pass
  1034. def _addProfileWriter(self, profile_writer):
  1035. pass
  1036. @pyqtSlot("QSize")
  1037. def setMinimumWindowSize(self, size):
  1038. self.getMainWindow().setMinimumSize(size)
  1039. def getBuildVolume(self):
  1040. return self._volume
  1041. additionalComponentsChanged = pyqtSignal(str, arguments = ["areaId"])
  1042. @pyqtProperty("QVariantMap", notify = additionalComponentsChanged)
  1043. def additionalComponents(self):
  1044. return self._additional_components
  1045. ## Add a component to a list of components to be reparented to another area in the GUI.
  1046. # The actual reparenting is done by the area itself.
  1047. # \param area_id \type{str} Identifying name of the area to which the component should be reparented
  1048. # \param component \type{QQuickComponent} The component that should be reparented
  1049. @pyqtSlot(str, "QVariant")
  1050. def addAdditionalComponent(self, area_id, component):
  1051. if area_id not in self._additional_components:
  1052. self._additional_components[area_id] = []
  1053. self._additional_components[area_id].append(component)
  1054. self.additionalComponentsChanged.emit(area_id)
  1055. @pyqtSlot(str)
  1056. def log(self, msg):
  1057. Logger.log("d", msg)
  1058. @pyqtSlot(QUrl)
  1059. def readLocalFile(self, file):
  1060. if not file.isValid():
  1061. return
  1062. scene = self.getController().getScene()
  1063. for node in DepthFirstIterator(scene.getRoot()):
  1064. if node.callDecoration("isBlockSlicing"):
  1065. self.deleteAll()
  1066. break
  1067. f = file.toLocalFile()
  1068. extension = os.path.splitext(f)[1]
  1069. filename = os.path.basename(f)
  1070. if len(self._currently_loading_files) > 0:
  1071. # If a non-slicable file is already being loaded, we prevent loading of any further non-slicable files
  1072. if extension.lower() in self._non_sliceable_extensions:
  1073. message = Message(
  1074. self._i18n_catalog.i18nc("@info:status",
  1075. "Only one G-code file can be loaded at a time. Skipped importing {0}",
  1076. filename))
  1077. message.show()
  1078. return
  1079. # If file being loaded is non-slicable file, then prevent loading of any other files
  1080. extension = os.path.splitext(self._currently_loading_files[0])[1]
  1081. if extension.lower() in self._non_sliceable_extensions:
  1082. message = Message(
  1083. self._i18n_catalog.i18nc("@info:status",
  1084. "Can't open any other file if G-code is loading. Skipped importing {0}",
  1085. filename))
  1086. message.show()
  1087. return
  1088. self._currently_loading_files.append(f)
  1089. if extension in self._non_sliceable_extensions:
  1090. self.deleteAll()
  1091. job = ReadMeshJob(f)
  1092. job.finished.connect(self._readMeshFinished)
  1093. job.start()
  1094. def _readMeshFinished(self, job):
  1095. nodes = job.getResult()
  1096. filename = job.getFileName()
  1097. self._currently_loading_files.remove(filename)
  1098. root = self.getController().getScene().getRoot()
  1099. arranger = Arrange.create(scene_root = root)
  1100. min_offset = 8
  1101. for node in nodes:
  1102. node.setSelectable(True)
  1103. node.setName(os.path.basename(filename))
  1104. extension = os.path.splitext(filename)[1]
  1105. if extension.lower() in self._non_sliceable_extensions:
  1106. self.getController().setActiveView("LayerView")
  1107. view = self.getController().getActiveView()
  1108. view.resetLayerData()
  1109. view.setLayer(9999999)
  1110. view.calculateMaxLayers()
  1111. block_slicing_decorator = BlockSlicingDecorator()
  1112. node.addDecorator(block_slicing_decorator)
  1113. else:
  1114. sliceable_decorator = SliceableObjectDecorator()
  1115. node.addDecorator(sliceable_decorator)
  1116. scene = self.getController().getScene()
  1117. # If there is no convex hull for the node, start calculating it and continue.
  1118. if not node.getDecorator(ConvexHullDecorator):
  1119. node.addDecorator(ConvexHullDecorator())
  1120. # find node location
  1121. offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = min_offset)
  1122. # step is for skipping tests to make it a lot faster. it also makes the outcome somewhat rougher
  1123. nodes = arranger.findNodePlacements(node, offset_shape_arr, hull_shape_arr, count = 1, step = 10)
  1124. for new_node in nodes:
  1125. op = AddSceneNodeOperation(new_node, scene.getRoot())
  1126. op.push()
  1127. scene.sceneChanged.emit(node)
  1128. def addNonSliceableExtension(self, extension):
  1129. self._non_sliceable_extensions.append(extension)
  1130. @pyqtSlot(str, result=bool)
  1131. def checkIsValidProjectFile(self, file_url):
  1132. """
  1133. Checks if the given file URL is a valid project file.
  1134. """
  1135. file_path = QUrl(file_url).toLocalFile()
  1136. workspace_reader = self.getWorkspaceFileHandler().getReaderForFile(file_path)
  1137. if workspace_reader is None:
  1138. return False # non-project files won't get a reader
  1139. result = workspace_reader.preRead(file_path, show_dialog=False)
  1140. return result == WorkspaceReader.PreReadResult.accepted