CuraApplication.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. #Type hinting.
  4. from typing import Dict
  5. from PyQt5.QtCore import QObject
  6. from PyQt5.QtNetwork import QLocalServer
  7. from PyQt5.QtNetwork import QLocalSocket
  8. from UM.Qt.QtApplication import QtApplication
  9. from UM.Scene.SceneNode import SceneNode
  10. from UM.Scene.Camera import Camera
  11. from UM.Math.Vector import Vector
  12. from UM.Math.Quaternion import Quaternion
  13. from UM.Math.AxisAlignedBox import AxisAlignedBox
  14. from UM.Math.Matrix import Matrix
  15. from UM.Platform import Platform
  16. from UM.Resources import Resources
  17. from UM.Scene.ToolHandle import ToolHandle
  18. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  19. from UM.Mesh.ReadMeshJob import ReadMeshJob
  20. from UM.Logger import Logger
  21. from UM.Preferences import Preferences
  22. from UM.Scene.Selection import Selection
  23. from UM.Scene.GroupDecorator import GroupDecorator
  24. from UM.Settings.ContainerStack import ContainerStack
  25. from UM.Settings.InstanceContainer import InstanceContainer
  26. from UM.Settings.Validator import Validator
  27. from UM.Message import Message
  28. from UM.i18n import i18nCatalog
  29. from UM.Workspace.WorkspaceReader import WorkspaceReader
  30. from UM.Decorators import deprecated
  31. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  32. from UM.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
  33. from UM.Operations.GroupedOperation import GroupedOperation
  34. from UM.Operations.SetTransformOperation import SetTransformOperation
  35. from cura.Arranging.Arrange import Arrange
  36. from cura.Arranging.ArrangeObjectsJob import ArrangeObjectsJob
  37. from cura.Arranging.ArrangeObjectsAllBuildPlatesJob import ArrangeObjectsAllBuildPlatesJob
  38. from cura.Arranging.ShapeArray import ShapeArray
  39. from cura.MultiplyObjectsJob import MultiplyObjectsJob
  40. from cura.Scene.ConvexHullDecorator import ConvexHullDecorator
  41. from cura.Operations.SetParentOperation import SetParentOperation
  42. from cura.Scene.SliceableObjectDecorator import SliceableObjectDecorator
  43. from cura.Scene.BlockSlicingDecorator import BlockSlicingDecorator
  44. from cura.Scene.BuildPlateDecorator import BuildPlateDecorator
  45. from cura.Scene.CuraSceneNode import CuraSceneNode
  46. from cura.Scene.CuraSceneController import CuraSceneController
  47. from UM.Settings.SettingDefinition import SettingDefinition, DefinitionPropertyType
  48. from UM.Settings.ContainerRegistry import ContainerRegistry
  49. from UM.Settings.SettingFunction import SettingFunction
  50. from cura.Settings.MachineNameValidator import MachineNameValidator
  51. from cura.Machines.Models.BuildPlateModel import BuildPlateModel
  52. from cura.Machines.Models.NozzleModel import NozzleModel
  53. from cura.Machines.Models.QualityProfilesDropDownMenuModel import QualityProfilesDropDownMenuModel
  54. from cura.Machines.Models.CustomQualityProfilesDropDownMenuModel import CustomQualityProfilesDropDownMenuModel
  55. from cura.Machines.Models.MultiBuildPlateModel import MultiBuildPlateModel
  56. from cura.Machines.Models.MaterialManagementModel import MaterialManagementModel
  57. from cura.Machines.Models.GenericMaterialsModel import GenericMaterialsModel
  58. from cura.Machines.Models.BrandMaterialsModel import BrandMaterialsModel
  59. from cura.Machines.Models.QualityManagementModel import QualityManagementModel
  60. from cura.Machines.Models.QualitySettingsModel import QualitySettingsModel
  61. from cura.Machines.Models.MachineManagementModel import MachineManagementModel
  62. from cura.Settings.SettingInheritanceManager import SettingInheritanceManager
  63. from cura.Settings.SimpleModeSettingsManager import SimpleModeSettingsManager
  64. from cura.Machines.VariantManager import VariantManager
  65. from . import PlatformPhysics
  66. from . import BuildVolume
  67. from . import CameraAnimation
  68. from . import PrintInformation
  69. from . import CuraActions
  70. from cura.Scene import ZOffsetDecorator
  71. from . import CuraSplashScreen
  72. from . import CameraImageProvider
  73. from . import MachineActionManager
  74. from cura.Settings.MachineManager import MachineManager
  75. from cura.Settings.ExtruderManager import ExtruderManager
  76. from cura.Settings.UserChangesModel import UserChangesModel
  77. from cura.Settings.ExtrudersModel import ExtrudersModel
  78. from cura.Settings.MaterialSettingsVisibilityHandler import MaterialSettingsVisibilityHandler
  79. from cura.Settings.ContainerManager import ContainerManager
  80. from cura.ObjectsModel import ObjectsModel
  81. from PyQt5.QtCore import QUrl, pyqtSignal, pyqtProperty, QEvent, Q_ENUMS
  82. from UM.FlameProfiler import pyqtSlot
  83. from PyQt5.QtGui import QColor, QIcon
  84. from PyQt5.QtWidgets import QMessageBox
  85. from PyQt5.QtQml import qmlRegisterUncreatableType, qmlRegisterSingletonType, qmlRegisterType
  86. from configparser import ConfigParser
  87. import sys
  88. import os.path
  89. import numpy
  90. import copy
  91. import os
  92. import argparse
  93. import json
  94. numpy.seterr(all="ignore")
  95. MYPY = False
  96. if not MYPY:
  97. try:
  98. from cura.CuraVersion import CuraVersion, CuraBuildType, CuraDebugMode
  99. except ImportError:
  100. CuraVersion = "master" # [CodeStyle: Reflecting imported value]
  101. CuraBuildType = ""
  102. CuraDebugMode = False
  103. class CuraApplication(QtApplication):
  104. # SettingVersion represents the set of settings available in the machine/extruder definitions.
  105. # You need to make sure that this version number needs to be increased if there is any non-backwards-compatible
  106. # changes of the settings.
  107. SettingVersion = 4
  108. Created = False
  109. class ResourceTypes:
  110. QmlFiles = Resources.UserType + 1
  111. Firmware = Resources.UserType + 2
  112. QualityInstanceContainer = Resources.UserType + 3
  113. MaterialInstanceContainer = Resources.UserType + 4
  114. VariantInstanceContainer = Resources.UserType + 5
  115. UserInstanceContainer = Resources.UserType + 6
  116. MachineStack = Resources.UserType + 7
  117. ExtruderStack = Resources.UserType + 8
  118. DefinitionChangesContainer = Resources.UserType + 9
  119. Q_ENUMS(ResourceTypes)
  120. # FIXME: This signal belongs to the MachineManager, but the CuraEngineBackend plugin requires on it.
  121. # Because plugins are initialized before the ContainerRegistry, putting this signal in MachineManager
  122. # will make it initialized before ContainerRegistry does, and it won't find the active machine, thus
  123. # Cura will always show the Add Machine Dialog upon start.
  124. stacksValidationFinished = pyqtSignal() # Emitted whenever a validation is finished
  125. def __init__(self, **kwargs):
  126. # this list of dir names will be used by UM to detect an old cura directory
  127. for dir_name in ["extruders", "machine_instances", "materials", "plugins", "quality", "user", "variants"]:
  128. Resources.addExpectedDirNameInData(dir_name)
  129. Resources.addSearchPath(os.path.join(QtApplication.getInstallPrefix(), "share", "cura", "resources"))
  130. if not hasattr(sys, "frozen"):
  131. Resources.addSearchPath(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "resources"))
  132. self._use_gui = True
  133. self._open_file_queue = [] # Files to open when plug-ins are loaded.
  134. # Need to do this before ContainerRegistry tries to load the machines
  135. SettingDefinition.addSupportedProperty("settable_per_mesh", DefinitionPropertyType.Any, default = True, read_only = True)
  136. SettingDefinition.addSupportedProperty("settable_per_extruder", DefinitionPropertyType.Any, default = True, read_only = True)
  137. # this setting can be changed for each group in one-at-a-time mode
  138. SettingDefinition.addSupportedProperty("settable_per_meshgroup", DefinitionPropertyType.Any, default = True, read_only = True)
  139. SettingDefinition.addSupportedProperty("settable_globally", DefinitionPropertyType.Any, default = True, read_only = True)
  140. # From which stack the setting would inherit if not defined per object (handled in the engine)
  141. # AND for settings which are not settable_per_mesh:
  142. # which extruder is the only extruder this setting is obtained from
  143. SettingDefinition.addSupportedProperty("limit_to_extruder", DefinitionPropertyType.Function, default = "-1", depends_on = "value")
  144. # For settings which are not settable_per_mesh and not settable_per_extruder:
  145. # A function which determines the glabel/meshgroup value by looking at the values of the setting in all (used) extruders
  146. SettingDefinition.addSupportedProperty("resolve", DefinitionPropertyType.Function, default = None, depends_on = "value")
  147. SettingDefinition.addSettingType("extruder", None, str, Validator)
  148. SettingDefinition.addSettingType("optional_extruder", None, str, None)
  149. SettingDefinition.addSettingType("[int]", None, str, None)
  150. SettingFunction.registerOperator("extruderValues", ExtruderManager.getExtruderValues)
  151. SettingFunction.registerOperator("extruderValue", ExtruderManager.getExtruderValue)
  152. SettingFunction.registerOperator("resolveOrValue", ExtruderManager.getResolveOrValue)
  153. ## Add the 4 types of profiles to storage.
  154. Resources.addStorageType(self.ResourceTypes.QualityInstanceContainer, "quality")
  155. Resources.addStorageType(self.ResourceTypes.VariantInstanceContainer, "variants")
  156. Resources.addStorageType(self.ResourceTypes.MaterialInstanceContainer, "materials")
  157. Resources.addStorageType(self.ResourceTypes.UserInstanceContainer, "user")
  158. Resources.addStorageType(self.ResourceTypes.ExtruderStack, "extruders")
  159. Resources.addStorageType(self.ResourceTypes.MachineStack, "machine_instances")
  160. Resources.addStorageType(self.ResourceTypes.DefinitionChangesContainer, "definition_changes")
  161. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.QualityInstanceContainer, "quality")
  162. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.QualityInstanceContainer, "quality_changes")
  163. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.VariantInstanceContainer, "variant")
  164. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MaterialInstanceContainer, "material")
  165. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.UserInstanceContainer, "user")
  166. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.ExtruderStack, "extruder_train")
  167. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MachineStack, "machine")
  168. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.DefinitionChangesContainer, "definition_changes")
  169. ## Initialise the version upgrade manager with Cura's storage paths.
  170. # Needs to be here to prevent circular dependencies.
  171. import UM.VersionUpgradeManager
  172. UM.VersionUpgradeManager.VersionUpgradeManager.getInstance().setCurrentVersions(
  173. {
  174. ("quality_changes", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.QualityInstanceContainer, "application/x-uranium-instancecontainer"),
  175. ("machine_stack", ContainerStack.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.MachineStack, "application/x-cura-globalstack"),
  176. ("extruder_train", ContainerStack.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.ExtruderStack, "application/x-cura-extruderstack"),
  177. ("preferences", Preferences.Version * 1000000 + self.SettingVersion): (Resources.Preferences, "application/x-uranium-preferences"),
  178. ("user", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.UserInstanceContainer, "application/x-uranium-instancecontainer"),
  179. ("definition_changes", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.DefinitionChangesContainer, "application/x-uranium-instancecontainer"),
  180. }
  181. )
  182. self._currently_loading_files = []
  183. self._non_sliceable_extensions = []
  184. self._machine_action_manager = MachineActionManager.MachineActionManager()
  185. self._machine_manager = None # This is initialized on demand.
  186. self._extruder_manager = None
  187. self._material_manager = None
  188. self._object_manager = None
  189. self._build_plate_model = None
  190. self._multi_build_plate_model = None
  191. self._setting_inheritance_manager = None
  192. self._simple_mode_settings_manager = None
  193. self._cura_scene_controller = None
  194. self._additional_components = {} # Components to add to certain areas in the interface
  195. super().__init__(name = "cura",
  196. version = CuraVersion,
  197. buildtype = CuraBuildType,
  198. is_debug_mode = CuraDebugMode,
  199. tray_icon_name = "cura-icon-32.png",
  200. **kwargs)
  201. # FOR TESTING ONLY
  202. if kwargs["parsed_command_line"].get("trigger_early_crash", False):
  203. assert not "This crash is triggered by the trigger_early_crash command line argument."
  204. self._variant_manager = None
  205. self.default_theme = "cura-light"
  206. self.setWindowIcon(QIcon(Resources.getPath(Resources.Images, "cura-icon.png")))
  207. self.setRequiredPlugins([
  208. "CuraEngineBackend",
  209. "UserAgreement",
  210. "SolidView",
  211. "SimulationView",
  212. "STLReader",
  213. "SelectionTool",
  214. "CameraTool",
  215. "GCodeWriter",
  216. "LocalFileOutputDevice",
  217. "TranslateTool",
  218. "FileLogger",
  219. "XmlMaterialProfile",
  220. "PluginBrowser",
  221. "PrepareStage",
  222. "MonitorStage"
  223. ])
  224. self._physics = None
  225. self._volume = None
  226. self._output_devices = {}
  227. self._print_information = None
  228. self._previous_active_tool = None
  229. self._platform_activity = False
  230. self._scene_bounding_box = AxisAlignedBox.Null
  231. self._job_name = None
  232. self._center_after_select = False
  233. self._camera_animation = None
  234. self._cura_actions = None
  235. self.started = False
  236. self._message_box_callback = None
  237. self._message_box_callback_arguments = []
  238. self._preferred_mimetype = ""
  239. self._i18n_catalog = i18nCatalog("cura")
  240. self.getController().getScene().sceneChanged.connect(self.updatePlatformActivity)
  241. self.getController().toolOperationStopped.connect(self._onToolOperationStopped)
  242. self.getController().contextMenuRequested.connect(self._onContextMenuRequested)
  243. self.getCuraSceneController().activeBuildPlateChanged.connect(self.updatePlatformActivity)
  244. Resources.addType(self.ResourceTypes.QmlFiles, "qml")
  245. Resources.addType(self.ResourceTypes.Firmware, "firmware")
  246. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading machines..."))
  247. # Add empty variant, material and quality containers.
  248. # Since they are empty, they should never be serialized and instead just programmatically created.
  249. # We need them to simplify the switching between materials.
  250. empty_container = ContainerRegistry.getInstance().getEmptyInstanceContainer()
  251. self.empty_container = empty_container
  252. empty_definition_changes_container = copy.deepcopy(empty_container)
  253. empty_definition_changes_container.setMetaDataEntry("id", "empty_definition_changes")
  254. empty_definition_changes_container.addMetaDataEntry("type", "definition_changes")
  255. ContainerRegistry.getInstance().addContainer(empty_definition_changes_container)
  256. self.empty_definition_changes_container = empty_definition_changes_container
  257. empty_variant_container = copy.deepcopy(empty_container)
  258. empty_variant_container.setMetaDataEntry("id", "empty_variant")
  259. empty_variant_container.addMetaDataEntry("type", "variant")
  260. ContainerRegistry.getInstance().addContainer(empty_variant_container)
  261. self.empty_variant_container = empty_variant_container
  262. empty_material_container = copy.deepcopy(empty_container)
  263. empty_material_container.setMetaDataEntry("id", "empty_material")
  264. empty_material_container.addMetaDataEntry("type", "material")
  265. ContainerRegistry.getInstance().addContainer(empty_material_container)
  266. self.empty_material_container = empty_material_container
  267. empty_quality_container = copy.deepcopy(empty_container)
  268. empty_quality_container.setMetaDataEntry("id", "empty_quality")
  269. empty_quality_container.setName("Not Supported")
  270. empty_quality_container.addMetaDataEntry("quality_type", "not_supported")
  271. empty_quality_container.addMetaDataEntry("type", "quality")
  272. empty_quality_container.addMetaDataEntry("supported", False)
  273. ContainerRegistry.getInstance().addContainer(empty_quality_container)
  274. self.empty_quality_container = empty_quality_container
  275. empty_quality_changes_container = copy.deepcopy(empty_container)
  276. empty_quality_changes_container.setMetaDataEntry("id", "empty_quality_changes")
  277. empty_quality_changes_container.addMetaDataEntry("type", "quality_changes")
  278. empty_quality_changes_container.addMetaDataEntry("quality_type", "not_supported")
  279. ContainerRegistry.getInstance().addContainer(empty_quality_changes_container)
  280. self.empty_quality_changes_container = empty_quality_changes_container
  281. with ContainerRegistry.getInstance().lockFile():
  282. ContainerRegistry.getInstance().loadAllMetadata()
  283. # set the setting version for Preferences
  284. preferences = Preferences.getInstance()
  285. preferences.addPreference("metadata/setting_version", 0)
  286. preferences.setValue("metadata/setting_version", self.SettingVersion) #Don't make it equal to the default so that the setting version always gets written to the file.
  287. preferences.addPreference("cura/active_mode", "simple")
  288. preferences.addPreference("cura/categories_expanded", "")
  289. preferences.addPreference("cura/jobname_prefix", True)
  290. preferences.addPreference("view/center_on_select", False)
  291. preferences.addPreference("mesh/scale_to_fit", False)
  292. preferences.addPreference("mesh/scale_tiny_meshes", True)
  293. preferences.addPreference("cura/dialog_on_project_save", True)
  294. preferences.addPreference("cura/asked_dialog_on_project_save", False)
  295. preferences.addPreference("cura/choice_on_profile_override", "always_ask")
  296. preferences.addPreference("cura/choice_on_open_project", "always_ask")
  297. preferences.addPreference("cura/not_arrange_objects_on_load", False)
  298. preferences.addPreference("cura/use_multi_build_plate", False)
  299. preferences.addPreference("cura/currency", "€")
  300. preferences.addPreference("cura/material_settings", "{}")
  301. preferences.addPreference("view/invert_zoom", False)
  302. preferences.addPreference("view/filter_current_build_plate", False)
  303. preferences.addPreference("cura/sidebar_collapsed", False)
  304. self._need_to_show_user_agreement = not Preferences.getInstance().getValue("general/accepted_user_agreement")
  305. for key in [
  306. "dialog_load_path", # dialog_save_path is in LocalFileOutputDevicePlugin
  307. "dialog_profile_path",
  308. "dialog_material_path"]:
  309. preferences.addPreference("local_file/%s" % key, os.path.expanduser("~/"))
  310. preferences.setDefault("local_file/last_used_type", "text/x-gcode")
  311. setting_visibily_preset_names = self.getVisibilitySettingPresetTypes()
  312. preferences.setDefault("general/visible_settings_preset", setting_visibily_preset_names)
  313. preset_setting_visibility_choice = Preferences.getInstance().getValue("general/preset_setting_visibility_choice")
  314. default_preset_visibility_group_name = "Basic"
  315. if preset_setting_visibility_choice == "" or preset_setting_visibility_choice is None:
  316. if preset_setting_visibility_choice not in setting_visibily_preset_names:
  317. preset_setting_visibility_choice = default_preset_visibility_group_name
  318. visible_settings = self.getVisibilitySettingPreset(settings_preset_name = preset_setting_visibility_choice)
  319. preferences.setDefault("general/visible_settings", visible_settings)
  320. preferences.setDefault("general/preset_setting_visibility_choice", preset_setting_visibility_choice)
  321. self.applicationShuttingDown.connect(self.saveSettings)
  322. self.engineCreatedSignal.connect(self._onEngineCreated)
  323. self.globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  324. self._onGlobalContainerChanged()
  325. self._plugin_registry.addSupportedPluginExtension("curaplugin", "Cura Plugin")
  326. self.getCuraSceneController().setActiveBuildPlate(0) # Initialize
  327. self._quality_profile_drop_down_menu_model = None
  328. self._custom_quality_profile_drop_down_menu_model = None
  329. CuraApplication.Created = True
  330. @pyqtSlot(str, result = str)
  331. def getVisibilitySettingPreset(self, settings_preset_name) -> str:
  332. result = self._loadPresetSettingVisibilityGroup(settings_preset_name)
  333. formatted_preset_settings = self._serializePresetSettingVisibilityData(result)
  334. return formatted_preset_settings
  335. ## Serialise the given preset setting visibitlity group dictionary into a string which is concatenated by ";"
  336. #
  337. def _serializePresetSettingVisibilityData(self, settings_data: dict) -> str:
  338. result_string = ""
  339. for key in settings_data:
  340. result_string += key + ";"
  341. for value in settings_data[key]:
  342. result_string += value + ";"
  343. return result_string
  344. ## Load the preset setting visibility group with the given name
  345. #
  346. def _loadPresetSettingVisibilityGroup(self, visibility_preset_name) -> Dict[str, str]:
  347. preset_dir = Resources.getPath(Resources.PresetSettingVisibilityGroups)
  348. result = {}
  349. right_preset_found = False
  350. for item in os.listdir(preset_dir):
  351. file_path = os.path.join(preset_dir, item)
  352. if not os.path.isfile(file_path):
  353. continue
  354. parser = ConfigParser(allow_no_value = True) # accept options without any value,
  355. try:
  356. parser.read([file_path])
  357. if not parser.has_option("general", "name"):
  358. continue
  359. if parser["general"]["name"] == visibility_preset_name:
  360. right_preset_found = True
  361. for section in parser.sections():
  362. if section == 'general':
  363. continue
  364. else:
  365. section_settings = []
  366. for option in parser[section].keys():
  367. section_settings.append(option)
  368. result[section] = section_settings
  369. if right_preset_found:
  370. break
  371. except Exception as e:
  372. Logger.log("e", "Failed to load setting visibility preset %s: %s", file_path, str(e))
  373. return result
  374. ## Check visibility setting preset folder and returns available types
  375. #
  376. def getVisibilitySettingPresetTypes(self):
  377. preset_dir = Resources.getPath(Resources.PresetSettingVisibilityGroups)
  378. result = {}
  379. for item in os.listdir(preset_dir):
  380. file_path = os.path.join(preset_dir, item)
  381. if not os.path.isfile(file_path):
  382. continue
  383. parser = ConfigParser(allow_no_value=True) # accept options without any value,
  384. try:
  385. parser.read([file_path])
  386. if not parser.has_option("general", "name") and not parser.has_option("general", "weight"):
  387. continue
  388. result[parser["general"]["weight"]] = parser["general"]["name"]
  389. except Exception as e:
  390. Logger.log("e", "Failed to load setting preset %s: %s", file_path, str(e))
  391. return result
  392. def _onEngineCreated(self):
  393. self._engine.addImageProvider("camera", CameraImageProvider.CameraImageProvider())
  394. @pyqtProperty(bool)
  395. def needToShowUserAgreement(self):
  396. return self._need_to_show_user_agreement
  397. def setNeedToShowUserAgreement(self, set_value = True):
  398. self._need_to_show_user_agreement = set_value
  399. ## The "Quit" button click event handler.
  400. @pyqtSlot()
  401. def closeApplication(self):
  402. Logger.log("i", "Close application")
  403. main_window = self.getMainWindow()
  404. if main_window is not None:
  405. main_window.close()
  406. else:
  407. self.exit(0)
  408. ## Signal to connect preferences action in QML
  409. showPreferencesWindow = pyqtSignal()
  410. ## Show the preferences window
  411. @pyqtSlot()
  412. def showPreferences(self):
  413. self.showPreferencesWindow.emit()
  414. ## A reusable dialogbox
  415. #
  416. showMessageBox = pyqtSignal(str, str, str, str, int, int, arguments = ["title", "text", "informativeText", "detailedText", "buttons", "icon"])
  417. def messageBox(self, title, text, informativeText = "", detailedText = "", buttons = QMessageBox.Ok, icon = QMessageBox.NoIcon, callback = None, callback_arguments = []):
  418. self._message_box_callback = callback
  419. self._message_box_callback_arguments = callback_arguments
  420. self.showMessageBox.emit(title, text, informativeText, detailedText, buttons, icon)
  421. showDiscardOrKeepProfileChanges = pyqtSignal()
  422. def discardOrKeepProfileChanges(self):
  423. has_user_interaction = False
  424. choice = Preferences.getInstance().getValue("cura/choice_on_profile_override")
  425. if choice == "always_discard":
  426. # don't show dialog and DISCARD the profile
  427. self.discardOrKeepProfileChangesClosed("discard")
  428. elif choice == "always_keep":
  429. # don't show dialog and KEEP the profile
  430. self.discardOrKeepProfileChangesClosed("keep")
  431. elif self._use_gui:
  432. # ALWAYS ask whether to keep or discard the profile
  433. self.showDiscardOrKeepProfileChanges.emit()
  434. has_user_interaction = True
  435. return has_user_interaction
  436. @pyqtSlot(str)
  437. def discardOrKeepProfileChangesClosed(self, option):
  438. if option == "discard":
  439. global_stack = self.getGlobalContainerStack()
  440. for extruder in self._extruder_manager.getMachineExtruders(global_stack.getId()):
  441. extruder.getTop().clear()
  442. global_stack.getTop().clear()
  443. # if the user decided to keep settings then the user settings should be re-calculated and validated for errors
  444. # before slicing. To ensure that slicer uses right settings values
  445. elif option == "keep":
  446. global_stack = self.getGlobalContainerStack()
  447. for extruder in self._extruder_manager.getMachineExtruders(global_stack.getId()):
  448. user_extruder_container = extruder.getTop()
  449. if user_extruder_container:
  450. user_extruder_container.update()
  451. user_global_container = global_stack.getTop()
  452. if user_global_container:
  453. user_global_container.update()
  454. # notify listeners that quality has changed (after user selected discard or keep)
  455. self.getMachineManager().activeQualityChanged.emit()
  456. @pyqtSlot(int)
  457. def messageBoxClosed(self, button):
  458. if self._message_box_callback:
  459. self._message_box_callback(button, *self._message_box_callback_arguments)
  460. self._message_box_callback = None
  461. self._message_box_callback_arguments = []
  462. showPrintMonitor = pyqtSignal(bool, arguments = ["show"])
  463. ## Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
  464. #
  465. # Note that the AutoSave plugin also calls this method.
  466. def saveSettings(self):
  467. if not self.started: # Do not do saving during application start
  468. return
  469. ContainerRegistry.getInstance().saveDirtyContainers()
  470. def saveStack(self, stack):
  471. ContainerRegistry.getInstance().saveContainer(stack)
  472. @pyqtSlot(str, result = QUrl)
  473. def getDefaultPath(self, key):
  474. default_path = Preferences.getInstance().getValue("local_file/%s" % key)
  475. return QUrl.fromLocalFile(default_path)
  476. @pyqtSlot(str, str)
  477. def setDefaultPath(self, key, default_path):
  478. Preferences.getInstance().setValue("local_file/%s" % key, QUrl(default_path).toLocalFile())
  479. @classmethod
  480. def getStaticVersion(cls):
  481. return CuraVersion
  482. ## Handle loading of all plugin types (and the backend explicitly)
  483. # \sa PluginRegistery
  484. def _loadPlugins(self):
  485. self._plugin_registry.addType("profile_reader", self._addProfileReader)
  486. self._plugin_registry.addType("profile_writer", self._addProfileWriter)
  487. if Platform.isLinux():
  488. lib_suffixes = {"", "64", "32", "x32"} #A few common ones on different distributions.
  489. else:
  490. lib_suffixes = {""}
  491. for suffix in lib_suffixes:
  492. self._plugin_registry.addPluginLocation(os.path.join(QtApplication.getInstallPrefix(), "lib" + suffix, "cura"))
  493. if not hasattr(sys, "frozen"):
  494. self._plugin_registry.addPluginLocation(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "plugins"))
  495. self._plugin_registry.loadPlugin("ConsoleLogger")
  496. self._plugin_registry.loadPlugin("CuraEngineBackend")
  497. self._plugin_registry.loadPlugins()
  498. if self.getBackend() is None:
  499. raise RuntimeError("Could not load the backend plugin!")
  500. self._plugins_loaded = True
  501. @classmethod
  502. def addCommandLineOptions(self, parser, parsed_command_line = {}):
  503. super().addCommandLineOptions(parser, parsed_command_line = parsed_command_line)
  504. parser.add_argument("file", nargs="*", help="Files to load after starting the application.")
  505. parser.add_argument("--single-instance", action="store_true", default=False)
  506. # Set up a local socket server which listener which coordinates single instances Curas and accepts commands.
  507. def _setUpSingleInstanceServer(self):
  508. if self.getCommandLineOption("single_instance", False):
  509. self.__single_instance_server = QLocalServer()
  510. self.__single_instance_server.newConnection.connect(self._singleInstanceServerNewConnection)
  511. self.__single_instance_server.listen("ultimaker-cura")
  512. def _singleInstanceServerNewConnection(self):
  513. Logger.log("i", "New connection recevied on our single-instance server")
  514. remote_cura_connection = self.__single_instance_server.nextPendingConnection()
  515. if remote_cura_connection is not None:
  516. def readCommands():
  517. line = remote_cura_connection.readLine()
  518. while len(line) != 0: # There is also a .canReadLine()
  519. try:
  520. payload = json.loads(str(line, encoding="ASCII").strip())
  521. command = payload["command"]
  522. # Command: Remove all models from the build plate.
  523. if command == "clear-all":
  524. self.deleteAll()
  525. # Command: Load a model file
  526. elif command == "open":
  527. self._openFile(payload["filePath"])
  528. # WARNING ^ this method is async and we really should wait until
  529. # the file load is complete before processing more commands.
  530. # Command: Activate the window and bring it to the top.
  531. elif command == "focus":
  532. # Operating systems these days prevent windows from moving around by themselves.
  533. # 'alert' or flashing the icon in the taskbar is the best thing we do now.
  534. self.getMainWindow().alert(0)
  535. # Command: Close the socket connection. We're done.
  536. elif command == "close-connection":
  537. remote_cura_connection.close()
  538. else:
  539. Logger.log("w", "Received an unrecognized command " + str(command))
  540. except json.decoder.JSONDecodeError as ex:
  541. Logger.log("w", "Unable to parse JSON command in _singleInstanceServerNewConnection(): " + repr(ex))
  542. line = remote_cura_connection.readLine()
  543. remote_cura_connection.readyRead.connect(readCommands)
  544. ## Perform any checks before creating the main application.
  545. #
  546. # This should be called directly before creating an instance of CuraApplication.
  547. # \returns \type{bool} True if the whole Cura app should continue running.
  548. @classmethod
  549. def preStartUp(cls, parser = None, parsed_command_line = {}):
  550. # Peek the arguments and look for the 'single-instance' flag.
  551. if not parser:
  552. parser = argparse.ArgumentParser(prog = "cura", add_help = False) # pylint: disable=bad-whitespace
  553. CuraApplication.addCommandLineOptions(parser, parsed_command_line = parsed_command_line)
  554. # Important: It is important to keep this line here!
  555. # In Uranium we allow to pass unknown arguments to the final executable or script.
  556. parsed_command_line.update(vars(parser.parse_known_args()[0]))
  557. if parsed_command_line["single_instance"]:
  558. Logger.log("i", "Checking for the presence of an ready running Cura instance.")
  559. single_instance_socket = QLocalSocket()
  560. Logger.log("d", "preStartUp(): full server name: " + single_instance_socket.fullServerName())
  561. single_instance_socket.connectToServer("ultimaker-cura")
  562. single_instance_socket.waitForConnected()
  563. if single_instance_socket.state() == QLocalSocket.ConnectedState:
  564. Logger.log("i", "Connection has been made to the single-instance Cura socket.")
  565. # Protocol is one line of JSON terminated with a carriage return.
  566. # "command" field is required and holds the name of the command to execute.
  567. # Other fields depend on the command.
  568. payload = {"command": "clear-all"}
  569. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  570. payload = {"command": "focus"}
  571. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  572. if len(parsed_command_line["file"]) != 0:
  573. for filename in parsed_command_line["file"]:
  574. payload = {"command": "open", "filePath": filename}
  575. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  576. payload = {"command": "close-connection"}
  577. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  578. single_instance_socket.flush()
  579. single_instance_socket.waitForDisconnected()
  580. return False
  581. return True
  582. def preRun(self):
  583. # Last check for unknown commandline arguments
  584. parser = self.getCommandlineParser()
  585. parser.add_argument("--help", "-h",
  586. action='store_true',
  587. default = False,
  588. help = "Show this help message and exit."
  589. )
  590. parsed_args = vars(parser.parse_args()) # This won't allow unknown arguments
  591. if parsed_args["help"]:
  592. parser.print_help()
  593. sys.exit(0)
  594. def run(self):
  595. self.preRun()
  596. container_registry = ContainerRegistry.getInstance()
  597. self._variant_manager = VariantManager(container_registry)
  598. self._variant_manager.initialize()
  599. from cura.Machines.MaterialManager import MaterialManager
  600. self._material_manager = MaterialManager(container_registry, parent = self)
  601. self._material_manager.initialize()
  602. from cura.Machines.QualityManager import QualityManager
  603. self._quality_manager = QualityManager(container_registry, parent = self)
  604. self._quality_manager.initialize()
  605. self._machine_manager = MachineManager(self)
  606. # Check if we should run as single instance or not
  607. self._setUpSingleInstanceServer()
  608. # Setup scene and build volume
  609. root = self.getController().getScene().getRoot()
  610. self._volume = BuildVolume.BuildVolume(self.getController().getScene().getRoot())
  611. Arrange.build_volume = self._volume
  612. # initialize info objects
  613. self._print_information = PrintInformation.PrintInformation()
  614. self._cura_actions = CuraActions.CuraActions(self)
  615. # Detect in which mode to run and execute that mode
  616. if self.getCommandLineOption("headless", False):
  617. self.runWithoutGUI()
  618. else:
  619. self.runWithGUI()
  620. # Pre-load files if requested
  621. for file_name in self.getCommandLineOption("file", []):
  622. self._openFile(file_name)
  623. for file_name in self._open_file_queue: # Open all the files that were queued up while plug-ins were loading.
  624. self._openFile(file_name)
  625. self.started = True
  626. self.exec_()
  627. ## Run Cura without GUI elements and interaction (server mode).
  628. def runWithoutGUI(self):
  629. self._use_gui = False
  630. self.closeSplash()
  631. ## Run Cura with GUI (desktop mode).
  632. def runWithGUI(self):
  633. self._use_gui = True
  634. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Setting up scene..."))
  635. controller = self.getController()
  636. # Initialize UI state
  637. controller.setActiveStage("PrepareStage")
  638. controller.setActiveView("SolidView")
  639. controller.setCameraTool("CameraTool")
  640. controller.setSelectionTool("SelectionTool")
  641. t = controller.getTool("TranslateTool")
  642. if t:
  643. t.setEnabledAxis([ToolHandle.XAxis, ToolHandle.YAxis, ToolHandle.ZAxis])
  644. Selection.selectionChanged.connect(self.onSelectionChanged)
  645. # Set default background color for scene
  646. self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
  647. # Initialize platform physics
  648. self._physics = PlatformPhysics.PlatformPhysics(controller, self._volume)
  649. # Initialize camera
  650. root = controller.getScene().getRoot()
  651. camera = Camera("3d", root)
  652. camera.setPosition(Vector(-80, 250, 700))
  653. camera.setPerspective(True)
  654. camera.lookAt(Vector(0, 0, 0))
  655. controller.getScene().setActiveCamera("3d")
  656. # Initialize camera tool
  657. camera_tool = controller.getTool("CameraTool")
  658. camera_tool.setOrigin(Vector(0, 100, 0))
  659. camera_tool.setZoomRange(0.1, 200000)
  660. # Initialize camera animations
  661. self._camera_animation = CameraAnimation.CameraAnimation()
  662. self._camera_animation.setCameraTool(self.getController().getTool("CameraTool"))
  663. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading interface..."))
  664. # Initialize QML engine
  665. self.setMainQml(Resources.getPath(self.ResourceTypes.QmlFiles, "Cura.qml"))
  666. self._qml_import_paths.append(Resources.getPath(self.ResourceTypes.QmlFiles))
  667. self.initializeEngine()
  668. # Make sure the correct stage is activated after QML is loaded
  669. controller.setActiveStage("PrepareStage")
  670. # Hide the splash screen
  671. self.closeSplash()
  672. def hasGui(self):
  673. return self._use_gui
  674. def getMachineManager(self, *args) -> MachineManager:
  675. if self._machine_manager is None:
  676. self._machine_manager = MachineManager(self)
  677. return self._machine_manager
  678. def getExtruderManager(self, *args):
  679. if self._extruder_manager is None:
  680. self._extruder_manager = ExtruderManager.createExtruderManager()
  681. return self._extruder_manager
  682. def getVariantManager(self, *args):
  683. return self._variant_manager
  684. @pyqtSlot(result = QObject)
  685. def getMaterialManager(self, *args):
  686. return self._material_manager
  687. @pyqtSlot(result = QObject)
  688. def getQualityManager(self, *args):
  689. return self._quality_manager
  690. def getObjectsModel(self, *args):
  691. if self._object_manager is None:
  692. self._object_manager = ObjectsModel.createObjectsModel()
  693. return self._object_manager
  694. @pyqtSlot(result = QObject)
  695. def getMultiBuildPlateModel(self, *args):
  696. if self._multi_build_plate_model is None:
  697. self._multi_build_plate_model = MultiBuildPlateModel(self)
  698. return self._multi_build_plate_model
  699. @pyqtSlot(result = QObject)
  700. def getBuildPlateModel(self, *args):
  701. if self._build_plate_model is None:
  702. self._build_plate_model = BuildPlateModel(self)
  703. return self._build_plate_model
  704. def getCuraSceneController(self, *args):
  705. if self._cura_scene_controller is None:
  706. self._cura_scene_controller = CuraSceneController.createCuraSceneController()
  707. return self._cura_scene_controller
  708. def getSettingInheritanceManager(self, *args):
  709. if self._setting_inheritance_manager is None:
  710. self._setting_inheritance_manager = SettingInheritanceManager.createSettingInheritanceManager()
  711. return self._setting_inheritance_manager
  712. ## Get the machine action manager
  713. # We ignore any *args given to this, as we also register the machine manager as qml singleton.
  714. # It wants to give this function an engine and script engine, but we don't care about that.
  715. def getMachineActionManager(self, *args):
  716. return self._machine_action_manager
  717. def getSimpleModeSettingsManager(self, *args):
  718. if self._simple_mode_settings_manager is None:
  719. self._simple_mode_settings_manager = SimpleModeSettingsManager()
  720. return self._simple_mode_settings_manager
  721. ## Handle Qt events
  722. def event(self, event):
  723. if event.type() == QEvent.FileOpen:
  724. if self._plugins_loaded:
  725. self._openFile(event.file())
  726. else:
  727. self._open_file_queue.append(event.file())
  728. return super().event(event)
  729. ## Get print information (duration / material used)
  730. def getPrintInformation(self):
  731. return self._print_information
  732. def getQualityProfilesDropDownMenuModel(self, *args, **kwargs):
  733. if self._quality_profile_drop_down_menu_model is None:
  734. self._quality_profile_drop_down_menu_model = QualityProfilesDropDownMenuModel(self)
  735. return self._quality_profile_drop_down_menu_model
  736. def getCustomQualityProfilesDropDownMenuModel(self, *args, **kwargs):
  737. if self._custom_quality_profile_drop_down_menu_model is None:
  738. self._custom_quality_profile_drop_down_menu_model = CustomQualityProfilesDropDownMenuModel(self)
  739. return self._custom_quality_profile_drop_down_menu_model
  740. ## Registers objects for the QML engine to use.
  741. #
  742. # \param engine The QML engine.
  743. def registerObjects(self, engine):
  744. super().registerObjects(engine)
  745. # global contexts
  746. engine.rootContext().setContextProperty("Printer", self)
  747. engine.rootContext().setContextProperty("CuraApplication", self)
  748. engine.rootContext().setContextProperty("PrintInformation", self._print_information)
  749. engine.rootContext().setContextProperty("CuraActions", self._cura_actions)
  750. qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")
  751. qmlRegisterSingletonType(CuraSceneController, "Cura", 1, 0, "SceneController", self.getCuraSceneController)
  752. qmlRegisterSingletonType(ExtruderManager, "Cura", 1, 0, "ExtruderManager", self.getExtruderManager)
  753. qmlRegisterSingletonType(MachineManager, "Cura", 1, 0, "MachineManager", self.getMachineManager)
  754. qmlRegisterSingletonType(SettingInheritanceManager, "Cura", 1, 0, "SettingInheritanceManager", self.getSettingInheritanceManager)
  755. qmlRegisterSingletonType(SimpleModeSettingsManager, "Cura", 1, 0, "SimpleModeSettingsManager", self.getSimpleModeSettingsManager)
  756. qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, "MachineActionManager", self.getMachineActionManager)
  757. qmlRegisterSingletonType(ObjectsModel, "Cura", 1, 0, "ObjectsModel", self.getObjectsModel)
  758. qmlRegisterType(BuildPlateModel, "Cura", 1, 0, "BuildPlateModel")
  759. qmlRegisterType(MultiBuildPlateModel, "Cura", 1, 0, "MultiBuildPlateModel")
  760. qmlRegisterType(InstanceContainer, "Cura", 1, 0, "InstanceContainer")
  761. qmlRegisterType(ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")
  762. qmlRegisterType(GenericMaterialsModel, "Cura", 1, 0, "GenericMaterialsModel")
  763. qmlRegisterType(BrandMaterialsModel, "Cura", 1, 0, "BrandMaterialsModel")
  764. qmlRegisterType(MaterialManagementModel, "Cura", 1, 0, "MaterialManagementModel")
  765. qmlRegisterType(QualityManagementModel, "Cura", 1, 0, "QualityManagementModel")
  766. qmlRegisterType(MachineManagementModel, "Cura", 1, 0, "MachineManagementModel")
  767. qmlRegisterSingletonType(QualityProfilesDropDownMenuModel, "Cura", 1, 0,
  768. "QualityProfilesDropDownMenuModel", self.getQualityProfilesDropDownMenuModel)
  769. qmlRegisterSingletonType(CustomQualityProfilesDropDownMenuModel, "Cura", 1, 0,
  770. "CustomQualityProfilesDropDownMenuModel", self.getCustomQualityProfilesDropDownMenuModel)
  771. qmlRegisterType(NozzleModel, "Cura", 1, 0, "NozzleModel")
  772. qmlRegisterType(MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
  773. qmlRegisterType(QualitySettingsModel, "Cura", 1, 0, "QualitySettingsModel")
  774. qmlRegisterType(MachineNameValidator, "Cura", 1, 0, "MachineNameValidator")
  775. qmlRegisterType(UserChangesModel, "Cura", 1, 0, "UserChangesModel")
  776. qmlRegisterSingletonType(ContainerManager, "Cura", 1, 0, "ContainerManager", ContainerManager.createContainerManager)
  777. # As of Qt5.7, it is necessary to get rid of any ".." in the path for the singleton to work.
  778. actions_url = QUrl.fromLocalFile(os.path.abspath(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")))
  779. qmlRegisterSingletonType(actions_url, "Cura", 1, 0, "Actions")
  780. for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
  781. type_name = os.path.splitext(os.path.basename(path))[0]
  782. if type_name in ("Cura", "Actions"):
  783. continue
  784. # Ignore anything that is not a QML file.
  785. if not path.endswith(".qml"):
  786. continue
  787. qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
  788. def onSelectionChanged(self):
  789. if Selection.hasSelection():
  790. if self.getController().getActiveTool():
  791. # If the tool has been disabled by the new selection
  792. if not self.getController().getActiveTool().getEnabled():
  793. # Default
  794. self.getController().setActiveTool("TranslateTool")
  795. else:
  796. if self._previous_active_tool:
  797. self.getController().setActiveTool(self._previous_active_tool)
  798. if not self.getController().getActiveTool().getEnabled():
  799. self.getController().setActiveTool("TranslateTool")
  800. self._previous_active_tool = None
  801. else:
  802. # Default
  803. self.getController().setActiveTool("TranslateTool")
  804. if Preferences.getInstance().getValue("view/center_on_select"):
  805. self._center_after_select = True
  806. else:
  807. if self.getController().getActiveTool():
  808. self._previous_active_tool = self.getController().getActiveTool().getPluginId()
  809. self.getController().setActiveTool(None)
  810. def _onToolOperationStopped(self, event):
  811. if self._center_after_select and Selection.getSelectedObject(0) is not None:
  812. self._center_after_select = False
  813. self._camera_animation.setStart(self.getController().getTool("CameraTool").getOrigin())
  814. self._camera_animation.setTarget(Selection.getSelectedObject(0).getWorldPosition())
  815. self._camera_animation.start()
  816. def _onGlobalContainerChanged(self):
  817. if self._global_container_stack is not None:
  818. machine_file_formats = [file_type.strip() for file_type in self._global_container_stack.getMetaDataEntry("file_formats").split(";")]
  819. new_preferred_mimetype = ""
  820. if machine_file_formats:
  821. new_preferred_mimetype = machine_file_formats[0]
  822. if new_preferred_mimetype != self._preferred_mimetype:
  823. self._preferred_mimetype = new_preferred_mimetype
  824. self.preferredOutputMimetypeChanged.emit()
  825. requestAddPrinter = pyqtSignal()
  826. activityChanged = pyqtSignal()
  827. sceneBoundingBoxChanged = pyqtSignal()
  828. preferredOutputMimetypeChanged = pyqtSignal()
  829. @pyqtProperty(bool, notify = activityChanged)
  830. def platformActivity(self):
  831. return self._platform_activity
  832. @pyqtProperty(str, notify=preferredOutputMimetypeChanged)
  833. def preferredOutputMimetype(self):
  834. return self._preferred_mimetype
  835. @pyqtProperty(str, notify = sceneBoundingBoxChanged)
  836. def getSceneBoundingBoxString(self):
  837. return self._i18n_catalog.i18nc("@info 'width', 'depth' and 'height' are variable names that must NOT be translated; just translate the format of ##x##x## mm.", "%(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()}
  838. ## Update scene bounding box for current build plate
  839. def updatePlatformActivity(self, node = None):
  840. count = 0
  841. scene_bounding_box = None
  842. is_block_slicing_node = False
  843. active_build_plate = self.getMultiBuildPlateModel().activeBuildPlate
  844. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  845. if (
  846. not issubclass(type(node), CuraSceneNode) or
  847. (not node.getMeshData() and not node.callDecoration("getLayerData")) or
  848. (node.callDecoration("getBuildPlateNumber") != active_build_plate)):
  849. continue
  850. if node.callDecoration("isBlockSlicing"):
  851. is_block_slicing_node = True
  852. count += 1
  853. if not scene_bounding_box:
  854. scene_bounding_box = node.getBoundingBox()
  855. else:
  856. other_bb = node.getBoundingBox()
  857. if other_bb is not None:
  858. scene_bounding_box = scene_bounding_box + node.getBoundingBox()
  859. print_information = self.getPrintInformation()
  860. if print_information:
  861. print_information.setPreSliced(is_block_slicing_node)
  862. if not scene_bounding_box:
  863. scene_bounding_box = AxisAlignedBox.Null
  864. if repr(self._scene_bounding_box) != repr(scene_bounding_box):
  865. self._scene_bounding_box = scene_bounding_box
  866. self.sceneBoundingBoxChanged.emit()
  867. self._platform_activity = True if count > 0 else False
  868. self.activityChanged.emit()
  869. # Remove all selected objects from the scene.
  870. @pyqtSlot()
  871. @deprecated("Moved to CuraActions", "2.6")
  872. def deleteSelection(self):
  873. if not self.getController().getToolsEnabled():
  874. return
  875. removed_group_nodes = []
  876. op = GroupedOperation()
  877. nodes = Selection.getAllSelectedObjects()
  878. for node in nodes:
  879. op.addOperation(RemoveSceneNodeOperation(node))
  880. group_node = node.getParent()
  881. if group_node and group_node.callDecoration("isGroup") and group_node not in removed_group_nodes:
  882. remaining_nodes_in_group = list(set(group_node.getChildren()) - set(nodes))
  883. if len(remaining_nodes_in_group) == 1:
  884. removed_group_nodes.append(group_node)
  885. op.addOperation(SetParentOperation(remaining_nodes_in_group[0], group_node.getParent()))
  886. op.addOperation(RemoveSceneNodeOperation(group_node))
  887. op.push()
  888. ## Remove an object from the scene.
  889. # Note that this only removes an object if it is selected.
  890. @pyqtSlot("quint64")
  891. @deprecated("Use deleteSelection instead", "2.6")
  892. def deleteObject(self, object_id):
  893. if not self.getController().getToolsEnabled():
  894. return
  895. node = self.getController().getScene().findObject(object_id)
  896. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  897. node = Selection.getSelectedObject(0)
  898. if node:
  899. op = GroupedOperation()
  900. op.addOperation(RemoveSceneNodeOperation(node))
  901. group_node = node.getParent()
  902. if group_node:
  903. # Note that at this point the node has not yet been deleted
  904. if len(group_node.getChildren()) <= 2 and group_node.callDecoration("isGroup"):
  905. op.addOperation(SetParentOperation(group_node.getChildren()[0], group_node.getParent()))
  906. op.addOperation(RemoveSceneNodeOperation(group_node))
  907. op.push()
  908. ## Create a number of copies of existing object.
  909. # \param object_id
  910. # \param count number of copies
  911. # \param min_offset minimum offset to other objects.
  912. @pyqtSlot("quint64", int)
  913. @deprecated("Use CuraActions::multiplySelection", "2.6")
  914. def multiplyObject(self, object_id, count, min_offset = 8):
  915. node = self.getController().getScene().findObject(object_id)
  916. if not node:
  917. node = Selection.getSelectedObject(0)
  918. while node.getParent() and node.getParent().callDecoration("isGroup"):
  919. node = node.getParent()
  920. job = MultiplyObjectsJob([node], count, min_offset)
  921. job.start()
  922. return
  923. ## Center object on platform.
  924. @pyqtSlot("quint64")
  925. @deprecated("Use CuraActions::centerSelection", "2.6")
  926. def centerObject(self, object_id):
  927. node = self.getController().getScene().findObject(object_id)
  928. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  929. node = Selection.getSelectedObject(0)
  930. if not node:
  931. return
  932. if node.getParent() and node.getParent().callDecoration("isGroup"):
  933. node = node.getParent()
  934. if node:
  935. op = SetTransformOperation(node, Vector())
  936. op.push()
  937. ## Select all nodes containing mesh data in the scene.
  938. @pyqtSlot()
  939. def selectAll(self):
  940. if not self.getController().getToolsEnabled():
  941. return
  942. Selection.clear()
  943. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  944. if not isinstance(node, SceneNode):
  945. continue
  946. if not node.getMeshData() and not node.callDecoration("isGroup"):
  947. continue # Node that doesnt have a mesh and is not a group.
  948. if node.getParent() and node.getParent().callDecoration("isGroup"):
  949. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  950. if not node.isSelectable():
  951. continue # i.e. node with layer data
  952. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  953. continue # i.e. node with layer data
  954. Selection.add(node)
  955. ## Delete all nodes containing mesh data in the scene.
  956. # \param only_selectable. Set this to False to delete objects from all build plates
  957. @pyqtSlot()
  958. def deleteAll(self, only_selectable = True):
  959. Logger.log("i", "Clearing scene")
  960. if not self.getController().getToolsEnabled():
  961. return
  962. nodes = []
  963. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  964. if not isinstance(node, SceneNode):
  965. continue
  966. if (not node.getMeshData() and not node.callDecoration("getLayerData")) and not node.callDecoration("isGroup"):
  967. continue # Node that doesnt have a mesh and is not a group.
  968. if only_selectable and not node.isSelectable():
  969. continue
  970. if not node.callDecoration("isSliceable") and not node.callDecoration("getLayerData") and not node.callDecoration("isGroup"):
  971. continue # Only remove nodes that are selectable.
  972. if node.getParent() and node.getParent().callDecoration("isGroup"):
  973. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  974. nodes.append(node)
  975. if nodes:
  976. op = GroupedOperation()
  977. for node in nodes:
  978. op.addOperation(RemoveSceneNodeOperation(node))
  979. # Reset the print information
  980. self.getController().getScene().sceneChanged.emit(node)
  981. op.push()
  982. Selection.clear()
  983. ## Reset all translation on nodes with mesh data.
  984. @pyqtSlot()
  985. def resetAllTranslation(self):
  986. Logger.log("i", "Resetting all scene translations")
  987. nodes = []
  988. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  989. if not isinstance(node, SceneNode):
  990. continue
  991. if not node.getMeshData() and not node.callDecoration("isGroup"):
  992. continue # Node that doesnt have a mesh and is not a group.
  993. if node.getParent() and node.getParent().callDecoration("isGroup"):
  994. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  995. if not node.isSelectable():
  996. continue # i.e. node with layer data
  997. nodes.append(node)
  998. if nodes:
  999. op = GroupedOperation()
  1000. for node in nodes:
  1001. # Ensure that the object is above the build platform
  1002. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  1003. if node.getBoundingBox():
  1004. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  1005. else:
  1006. center_y = 0
  1007. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0)))
  1008. op.push()
  1009. ## Reset all transformations on nodes with mesh data.
  1010. @pyqtSlot()
  1011. def resetAll(self):
  1012. Logger.log("i", "Resetting all scene transformations")
  1013. nodes = []
  1014. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1015. if not isinstance(node, SceneNode):
  1016. continue
  1017. if not node.getMeshData() and not node.callDecoration("isGroup"):
  1018. continue # Node that doesnt have a mesh and is not a group.
  1019. if node.getParent() and node.getParent().callDecoration("isGroup"):
  1020. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  1021. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1022. continue # i.e. node with layer data
  1023. nodes.append(node)
  1024. if nodes:
  1025. op = GroupedOperation()
  1026. for node in nodes:
  1027. # Ensure that the object is above the build platform
  1028. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  1029. if node.getBoundingBox():
  1030. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  1031. else:
  1032. center_y = 0
  1033. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0), Quaternion(), Vector(1, 1, 1)))
  1034. op.push()
  1035. ## Arrange all objects.
  1036. @pyqtSlot()
  1037. def arrangeObjectsToAllBuildPlates(self):
  1038. nodes = []
  1039. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1040. if not isinstance(node, SceneNode):
  1041. continue
  1042. if not node.getMeshData() and not node.callDecoration("isGroup"):
  1043. continue # Node that doesnt have a mesh and is not a group.
  1044. if node.getParent() and node.getParent().callDecoration("isGroup"):
  1045. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  1046. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1047. continue # i.e. node with layer data
  1048. # Skip nodes that are too big
  1049. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1050. nodes.append(node)
  1051. job = ArrangeObjectsAllBuildPlatesJob(nodes)
  1052. job.start()
  1053. self.getCuraSceneController().setActiveBuildPlate(0) # Select first build plate
  1054. # Single build plate
  1055. @pyqtSlot()
  1056. def arrangeAll(self):
  1057. nodes = []
  1058. active_build_plate = self.getMultiBuildPlateModel().activeBuildPlate
  1059. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1060. if not isinstance(node, SceneNode):
  1061. continue
  1062. if not node.getMeshData() and not node.callDecoration("isGroup"):
  1063. continue # Node that doesnt have a mesh and is not a group.
  1064. if node.getParent() and node.getParent().callDecoration("isGroup"):
  1065. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  1066. if not node.isSelectable():
  1067. continue # i.e. node with layer data
  1068. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1069. continue # i.e. node with layer data
  1070. if node.callDecoration("getBuildPlateNumber") == active_build_plate:
  1071. # Skip nodes that are too big
  1072. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1073. nodes.append(node)
  1074. self.arrange(nodes, fixed_nodes = [])
  1075. ## Arrange Selection
  1076. @pyqtSlot()
  1077. def arrangeSelection(self):
  1078. nodes = Selection.getAllSelectedObjects()
  1079. # What nodes are on the build plate and are not being moved
  1080. fixed_nodes = []
  1081. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1082. if not isinstance(node, SceneNode):
  1083. continue
  1084. if not node.getMeshData() and not node.callDecoration("isGroup"):
  1085. continue # Node that doesnt have a mesh and is not a group.
  1086. if node.getParent() and node.getParent().callDecoration("isGroup"):
  1087. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  1088. if not node.isSelectable():
  1089. continue # i.e. node with layer data
  1090. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1091. continue # i.e. node with layer data
  1092. if node in nodes: # exclude selected node from fixed_nodes
  1093. continue
  1094. fixed_nodes.append(node)
  1095. self.arrange(nodes, fixed_nodes)
  1096. ## Arrange a set of nodes given a set of fixed nodes
  1097. # \param nodes nodes that we have to place
  1098. # \param fixed_nodes nodes that are placed in the arranger before finding spots for nodes
  1099. def arrange(self, nodes, fixed_nodes):
  1100. job = ArrangeObjectsJob(nodes, fixed_nodes)
  1101. job.start()
  1102. ## Reload all mesh data on the screen from file.
  1103. @pyqtSlot()
  1104. def reloadAll(self):
  1105. Logger.log("i", "Reloading all loaded mesh data.")
  1106. nodes = []
  1107. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1108. if not isinstance(node, CuraSceneNode) or not node.getMeshData():
  1109. continue
  1110. nodes.append(node)
  1111. if not nodes:
  1112. return
  1113. for node in nodes:
  1114. file_name = node.getMeshData().getFileName()
  1115. if file_name:
  1116. job = ReadMeshJob(file_name)
  1117. job._node = node
  1118. job.finished.connect(self._reloadMeshFinished)
  1119. job.start()
  1120. else:
  1121. Logger.log("w", "Unable to reload data because we don't have a filename.")
  1122. ## Get logging data of the backend engine
  1123. # \returns \type{string} Logging data
  1124. @pyqtSlot(result = str)
  1125. def getEngineLog(self):
  1126. log = ""
  1127. for entry in self.getBackend().getLog():
  1128. log += entry.decode()
  1129. return log
  1130. @pyqtSlot("QStringList")
  1131. def setExpandedCategories(self, categories):
  1132. categories = list(set(categories))
  1133. categories.sort()
  1134. joined = ";".join(categories)
  1135. if joined != Preferences.getInstance().getValue("cura/categories_expanded"):
  1136. Preferences.getInstance().setValue("cura/categories_expanded", joined)
  1137. self.expandedCategoriesChanged.emit()
  1138. expandedCategoriesChanged = pyqtSignal()
  1139. @pyqtProperty("QStringList", notify = expandedCategoriesChanged)
  1140. def expandedCategories(self):
  1141. return Preferences.getInstance().getValue("cura/categories_expanded").split(";")
  1142. @pyqtSlot()
  1143. def mergeSelected(self):
  1144. self.groupSelected()
  1145. try:
  1146. group_node = Selection.getAllSelectedObjects()[0]
  1147. except Exception as e:
  1148. Logger.log("d", "mergeSelected: Exception:", e)
  1149. return
  1150. meshes = [node.getMeshData() for node in group_node.getAllChildren() if node.getMeshData()]
  1151. # Compute the center of the objects
  1152. object_centers = []
  1153. # Forget about the translation that the original objects have
  1154. zero_translation = Matrix(data=numpy.zeros(3))
  1155. for mesh, node in zip(meshes, group_node.getChildren()):
  1156. transformation = node.getLocalTransformation()
  1157. transformation.setTranslation(zero_translation)
  1158. transformed_mesh = mesh.getTransformed(transformation)
  1159. center = transformed_mesh.getCenterPosition()
  1160. if center is not None:
  1161. object_centers.append(center)
  1162. if object_centers and len(object_centers) > 0:
  1163. middle_x = sum([v.x for v in object_centers]) / len(object_centers)
  1164. middle_y = sum([v.y for v in object_centers]) / len(object_centers)
  1165. middle_z = sum([v.z for v in object_centers]) / len(object_centers)
  1166. offset = Vector(middle_x, middle_y, middle_z)
  1167. else:
  1168. offset = Vector(0, 0, 0)
  1169. # Move each node to the same position.
  1170. for mesh, node in zip(meshes, group_node.getChildren()):
  1171. transformation = node.getLocalTransformation()
  1172. transformation.setTranslation(zero_translation)
  1173. transformed_mesh = mesh.getTransformed(transformation)
  1174. # Align the object around its zero position
  1175. # and also apply the offset to center it inside the group.
  1176. node.setPosition(-transformed_mesh.getZeroPosition() - offset)
  1177. # Use the previously found center of the group bounding box as the new location of the group
  1178. group_node.setPosition(group_node.getBoundingBox().center)
  1179. @pyqtSlot()
  1180. def groupSelected(self):
  1181. # Create a group-node
  1182. group_node = CuraSceneNode()
  1183. group_decorator = GroupDecorator()
  1184. group_node.addDecorator(group_decorator)
  1185. group_node.addDecorator(ConvexHullDecorator())
  1186. group_node.addDecorator(BuildPlateDecorator(self.getMultiBuildPlateModel().activeBuildPlate))
  1187. group_node.setParent(self.getController().getScene().getRoot())
  1188. group_node.setSelectable(True)
  1189. center = Selection.getSelectionCenter()
  1190. group_node.setPosition(center)
  1191. group_node.setCenterPosition(center)
  1192. # Move selected nodes into the group-node
  1193. Selection.applyOperation(SetParentOperation, group_node)
  1194. # Deselect individual nodes and select the group-node instead
  1195. for node in group_node.getChildren():
  1196. Selection.remove(node)
  1197. Selection.add(group_node)
  1198. @pyqtSlot()
  1199. def ungroupSelected(self):
  1200. selected_objects = Selection.getAllSelectedObjects().copy()
  1201. for node in selected_objects:
  1202. if node.callDecoration("isGroup"):
  1203. op = GroupedOperation()
  1204. group_parent = node.getParent()
  1205. children = node.getChildren().copy()
  1206. for child in children:
  1207. # Set the parent of the children to the parent of the group-node
  1208. op.addOperation(SetParentOperation(child, group_parent))
  1209. # Add all individual nodes to the selection
  1210. Selection.add(child)
  1211. op.push()
  1212. # Note: The group removes itself from the scene once all its children have left it,
  1213. # see GroupDecorator._onChildrenChanged
  1214. def _createSplashScreen(self):
  1215. run_headless = self.getCommandLineOption("headless", False)
  1216. if run_headless:
  1217. return None
  1218. return CuraSplashScreen.CuraSplashScreen()
  1219. def _onActiveMachineChanged(self):
  1220. pass
  1221. fileLoaded = pyqtSignal(str)
  1222. fileCompleted = pyqtSignal(str)
  1223. def _reloadMeshFinished(self, job):
  1224. # TODO; This needs to be fixed properly. We now make the assumption that we only load a single mesh!
  1225. mesh_data = job.getResult()[0].getMeshData()
  1226. if mesh_data:
  1227. job._node.setMeshData(mesh_data)
  1228. else:
  1229. Logger.log("w", "Could not find a mesh in reloaded node.")
  1230. def _openFile(self, filename):
  1231. self.readLocalFile(QUrl.fromLocalFile(filename))
  1232. def _addProfileReader(self, profile_reader):
  1233. # TODO: Add the profile reader to the list of plug-ins that can be used when importing profiles.
  1234. pass
  1235. def _addProfileWriter(self, profile_writer):
  1236. pass
  1237. @pyqtSlot("QSize")
  1238. def setMinimumWindowSize(self, size):
  1239. self.getMainWindow().setMinimumSize(size)
  1240. def getBuildVolume(self):
  1241. return self._volume
  1242. additionalComponentsChanged = pyqtSignal(str, arguments = ["areaId"])
  1243. @pyqtProperty("QVariantMap", notify = additionalComponentsChanged)
  1244. def additionalComponents(self):
  1245. return self._additional_components
  1246. ## Add a component to a list of components to be reparented to another area in the GUI.
  1247. # The actual reparenting is done by the area itself.
  1248. # \param area_id \type{str} Identifying name of the area to which the component should be reparented
  1249. # \param component \type{QQuickComponent} The component that should be reparented
  1250. @pyqtSlot(str, "QVariant")
  1251. def addAdditionalComponent(self, area_id, component):
  1252. if area_id not in self._additional_components:
  1253. self._additional_components[area_id] = []
  1254. self._additional_components[area_id].append(component)
  1255. self.additionalComponentsChanged.emit(area_id)
  1256. @pyqtSlot(str)
  1257. def log(self, msg):
  1258. Logger.log("d", msg)
  1259. @pyqtSlot(QUrl)
  1260. def readLocalFile(self, file):
  1261. if not file.isValid():
  1262. return
  1263. scene = self.getController().getScene()
  1264. for node in DepthFirstIterator(scene.getRoot()):
  1265. if node.callDecoration("isBlockSlicing"):
  1266. self.deleteAll()
  1267. break
  1268. f = file.toLocalFile()
  1269. extension = os.path.splitext(f)[1]
  1270. filename = os.path.basename(f)
  1271. if len(self._currently_loading_files) > 0:
  1272. # If a non-slicable file is already being loaded, we prevent loading of any further non-slicable files
  1273. if extension.lower() in self._non_sliceable_extensions:
  1274. message = Message(
  1275. self._i18n_catalog.i18nc("@info:status",
  1276. "Only one G-code file can be loaded at a time. Skipped importing {0}",
  1277. filename), title = self._i18n_catalog.i18nc("@info:title", "Warning"))
  1278. message.show()
  1279. return
  1280. # If file being loaded is non-slicable file, then prevent loading of any other files
  1281. extension = os.path.splitext(self._currently_loading_files[0])[1]
  1282. if extension.lower() in self._non_sliceable_extensions:
  1283. message = Message(
  1284. self._i18n_catalog.i18nc("@info:status",
  1285. "Can't open any other file if G-code is loading. Skipped importing {0}",
  1286. filename), title = self._i18n_catalog.i18nc("@info:title", "Error"))
  1287. message.show()
  1288. return
  1289. self._currently_loading_files.append(f)
  1290. if extension in self._non_sliceable_extensions:
  1291. self.deleteAll(only_selectable = False)
  1292. job = ReadMeshJob(f)
  1293. job.finished.connect(self._readMeshFinished)
  1294. job.start()
  1295. def _readMeshFinished(self, job):
  1296. nodes = job.getResult()
  1297. filename = job.getFileName()
  1298. self._currently_loading_files.remove(filename)
  1299. self.fileLoaded.emit(filename)
  1300. arrange_objects_on_load = (
  1301. not Preferences.getInstance().getValue("cura/use_multi_build_plate") or
  1302. not Preferences.getInstance().getValue("cura/not_arrange_objects_on_load"))
  1303. target_build_plate = self.getMultiBuildPlateModel().activeBuildPlate if arrange_objects_on_load else -1
  1304. root = self.getController().getScene().getRoot()
  1305. fixed_nodes = []
  1306. for node_ in DepthFirstIterator(root):
  1307. if node_.callDecoration("isSliceable") and node_.callDecoration("getBuildPlateNumber") == target_build_plate:
  1308. fixed_nodes.append(node_)
  1309. arranger = Arrange.create(fixed_nodes = fixed_nodes)
  1310. min_offset = 8
  1311. default_extruder_position = self.getMachineManager().defaultExtruderPosition
  1312. default_extruder_id = self._global_container_stack.extruders[default_extruder_position].getId()
  1313. for original_node in nodes:
  1314. # Create a CuraSceneNode just if the original node is not that type
  1315. if isinstance(original_node, CuraSceneNode):
  1316. node = original_node
  1317. else:
  1318. node = CuraSceneNode()
  1319. node.setMeshData(original_node.getMeshData())
  1320. #Setting meshdata does not apply scaling.
  1321. if(original_node.getScale() != Vector(1.0, 1.0, 1.0)):
  1322. node.scale(original_node.getScale())
  1323. node.setSelectable(True)
  1324. node.setName(os.path.basename(filename))
  1325. self.getBuildVolume().checkBoundsAndUpdate(node)
  1326. extension = os.path.splitext(filename)[1]
  1327. if extension.lower() in self._non_sliceable_extensions:
  1328. self.callLater(lambda: self.getController().setActiveView("SimulationView"))
  1329. block_slicing_decorator = BlockSlicingDecorator()
  1330. node.addDecorator(block_slicing_decorator)
  1331. else:
  1332. sliceable_decorator = SliceableObjectDecorator()
  1333. node.addDecorator(sliceable_decorator)
  1334. scene = self.getController().getScene()
  1335. # If there is no convex hull for the node, start calculating it and continue.
  1336. if not node.getDecorator(ConvexHullDecorator):
  1337. node.addDecorator(ConvexHullDecorator())
  1338. for child in node.getAllChildren():
  1339. if not child.getDecorator(ConvexHullDecorator):
  1340. child.addDecorator(ConvexHullDecorator())
  1341. if arrange_objects_on_load:
  1342. if node.callDecoration("isSliceable"):
  1343. # Only check position if it's not already blatantly obvious that it won't fit.
  1344. if node.getBoundingBox() is None or self._volume.getBoundingBox() is None or node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1345. # Find node location
  1346. offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = min_offset)
  1347. # If a model is to small then it will not contain any points
  1348. if offset_shape_arr is None and hull_shape_arr is None:
  1349. Message(self._i18n_catalog.i18nc("@info:status", "The selected model was too small to load."),
  1350. title=self._i18n_catalog.i18nc("@info:title", "Warning")).show()
  1351. return
  1352. # Step is for skipping tests to make it a lot faster. it also makes the outcome somewhat rougher
  1353. node, _ = arranger.findNodePlacement(node, offset_shape_arr, hull_shape_arr, step = 10)
  1354. # This node is deep copied from some other node which already has a BuildPlateDecorator, but the deepcopy
  1355. # of BuildPlateDecorator produces one that's associated with build plate -1. So, here we need to check if
  1356. # the BuildPlateDecorator exists or not and always set the correct build plate number.
  1357. build_plate_decorator = node.getDecorator(BuildPlateDecorator)
  1358. if build_plate_decorator is None:
  1359. build_plate_decorator = BuildPlateDecorator(target_build_plate)
  1360. node.addDecorator(build_plate_decorator)
  1361. build_plate_decorator.setBuildPlateNumber(target_build_plate)
  1362. op = AddSceneNodeOperation(node, scene.getRoot())
  1363. op.push()
  1364. node.callDecoration("setActiveExtruder", default_extruder_id)
  1365. scene.sceneChanged.emit(node)
  1366. self.fileCompleted.emit(filename)
  1367. def addNonSliceableExtension(self, extension):
  1368. self._non_sliceable_extensions.append(extension)
  1369. @pyqtSlot(str, result=bool)
  1370. def checkIsValidProjectFile(self, file_url):
  1371. """
  1372. Checks if the given file URL is a valid project file.
  1373. """
  1374. file_path = QUrl(file_url).toLocalFile()
  1375. workspace_reader = self.getWorkspaceFileHandler().getReaderForFile(file_path)
  1376. if workspace_reader is None:
  1377. return False # non-project files won't get a reader
  1378. try:
  1379. result = workspace_reader.preRead(file_path, show_dialog=False)
  1380. return result == WorkspaceReader.PreReadResult.accepted
  1381. except Exception as e:
  1382. Logger.logException("e", "Could not check file %s: %s", file_url)
  1383. return False
  1384. def _onContextMenuRequested(self, x: float, y: float) -> None:
  1385. # Ensure we select the object if we request a context menu over an object without having a selection.
  1386. if not Selection.hasSelection():
  1387. node = self.getController().getScene().findObject(self.getRenderer().getRenderPass("selection").getIdAtPosition(x, y))
  1388. if node:
  1389. while(node.getParent() and node.getParent().callDecoration("isGroup")):
  1390. node = node.getParent()
  1391. Selection.add(node)