CuraApplication.py 80 KB

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