CuraApplication.py 81 KB

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