CuraApplication.py 75 KB

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