CuraApplication.py 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761
  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
  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", #You want to be able to read the log if something goes wrong.
  348. "CuraEngineBackend", #Cura is useless without this one since you can't slice.
  349. "UserAgreement", #Our lawyers want every user to see this at least once.
  350. "FileLogger", #You want to be able to read the log if something goes wrong.
  351. "XmlMaterialProfile", #Cura crashes without this one.
  352. "Toolbox", #This contains the interface to enable/disable plug-ins, so if you disable it you can't enable it back.
  353. "PrepareStage", #Cura is useless without this one since you can't load models.
  354. "MonitorStage", #Major part of Cura's functionality.
  355. "LocalFileOutputDevice", #Major part of Cura's functionality.
  356. "LocalContainerProvider", #Cura is useless without any profiles or setting definitions.
  357. # Views:
  358. "SimpleView", #Dependency of SolidView.
  359. "SolidView", #Displays models. Cura is useless without it.
  360. # Readers & Writers:
  361. "GCodeWriter", #Cura is useless if it can't write its output.
  362. "STLReader", #Most common model format, so disabling this makes Cura 90% useless.
  363. "3MFWriter", #Required for writing project files.
  364. # Tools:
  365. "CameraTool", #Needed to see the scene. Cura is useless without it.
  366. "SelectionTool", #Dependency of the rest of the tools.
  367. "TranslateTool", #You'll need this for almost every print.
  368. ])
  369. self._i18n_catalog = i18nCatalog("cura")
  370. self._update_platform_activity_timer = QTimer()
  371. self._update_platform_activity_timer.setInterval(500)
  372. self._update_platform_activity_timer.setSingleShot(True)
  373. self._update_platform_activity_timer.timeout.connect(self.updatePlatformActivity)
  374. self.getController().getScene().sceneChanged.connect(self.updatePlatformActivityDelayed)
  375. self.getController().toolOperationStopped.connect(self._onToolOperationStopped)
  376. self.getController().contextMenuRequested.connect(self._onContextMenuRequested)
  377. self.getCuraSceneController().activeBuildPlateChanged.connect(self.updatePlatformActivityDelayed)
  378. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading machines..."))
  379. with self._container_registry.lockFile():
  380. self._container_registry.loadAllMetadata()
  381. # set the setting version for Preferences
  382. preferences = self.getPreferences()
  383. preferences.addPreference("metadata/setting_version", 0)
  384. 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.
  385. preferences.addPreference("cura/active_mode", "simple")
  386. preferences.addPreference("cura/categories_expanded", "")
  387. preferences.addPreference("cura/jobname_prefix", True)
  388. preferences.addPreference("cura/select_models_on_load", False)
  389. preferences.addPreference("view/center_on_select", False)
  390. preferences.addPreference("mesh/scale_to_fit", False)
  391. preferences.addPreference("mesh/scale_tiny_meshes", True)
  392. preferences.addPreference("cura/dialog_on_project_save", True)
  393. preferences.addPreference("cura/asked_dialog_on_project_save", False)
  394. preferences.addPreference("cura/choice_on_profile_override", "always_ask")
  395. preferences.addPreference("cura/choice_on_open_project", "always_ask")
  396. preferences.addPreference("cura/use_multi_build_plate", False)
  397. preferences.addPreference("cura/currency", "€")
  398. preferences.addPreference("cura/material_settings", "{}")
  399. preferences.addPreference("view/invert_zoom", False)
  400. preferences.addPreference("view/filter_current_build_plate", False)
  401. preferences.addPreference("cura/sidebar_collapsed", False)
  402. preferences.addPreference("cura/favorite_materials", "")
  403. preferences.addPreference("cura/expanded_brands", "")
  404. preferences.addPreference("cura/expanded_types", "")
  405. self._need_to_show_user_agreement = not preferences.getValue("general/accepted_user_agreement")
  406. for key in [
  407. "dialog_load_path", # dialog_save_path is in LocalFileOutputDevicePlugin
  408. "dialog_profile_path",
  409. "dialog_material_path"]:
  410. preferences.addPreference("local_file/%s" % key, os.path.expanduser("~/"))
  411. preferences.setDefault("local_file/last_used_type", "text/x-gcode")
  412. self.applicationShuttingDown.connect(self.saveSettings)
  413. self.engineCreatedSignal.connect(self._onEngineCreated)
  414. self.getCuraSceneController().setActiveBuildPlate(0) # Initialize
  415. CuraApplication.Created = True
  416. def _onEngineCreated(self):
  417. self._qml_engine.addImageProvider("print_job_preview", PrintJobPreviewImageProvider.PrintJobPreviewImageProvider())
  418. @pyqtProperty(bool)
  419. def needToShowUserAgreement(self) -> bool:
  420. return self._need_to_show_user_agreement
  421. def setNeedToShowUserAgreement(self, set_value = True) -> None:
  422. self._need_to_show_user_agreement = set_value
  423. # DO NOT call this function to close the application, use checkAndExitApplication() instead which will perform
  424. # pre-exit checks such as checking for in-progress USB printing, etc.
  425. def closeApplication(self) -> None:
  426. Logger.log("i", "Close application")
  427. main_window = self.getMainWindow()
  428. if main_window is not None:
  429. main_window.close()
  430. else:
  431. self.exit(0)
  432. # This function first performs all upon-exit checks such as USB printing that is in progress.
  433. # Use this to close the application.
  434. @pyqtSlot()
  435. def checkAndExitApplication(self) -> None:
  436. self._on_exit_callback_manager.resetCurrentState()
  437. self._on_exit_callback_manager.triggerNextCallback()
  438. @pyqtSlot(result = bool)
  439. def getIsAllChecksPassed(self) -> bool:
  440. return self._on_exit_callback_manager.getIsAllChecksPassed()
  441. def getOnExitCallbackManager(self) -> "OnExitCallbackManager":
  442. return self._on_exit_callback_manager
  443. def triggerNextExitCheck(self) -> None:
  444. self._on_exit_callback_manager.triggerNextCallback()
  445. showConfirmExitDialog = pyqtSignal(str, arguments = ["message"])
  446. def setConfirmExitDialogCallback(self, callback: Callable) -> None:
  447. self._confirm_exit_dialog_callback = callback
  448. @pyqtSlot(bool)
  449. def callConfirmExitDialogCallback(self, yes_or_no: bool) -> None:
  450. self._confirm_exit_dialog_callback(yes_or_no)
  451. ## Signal to connect preferences action in QML
  452. showPreferencesWindow = pyqtSignal()
  453. ## Show the preferences window
  454. @pyqtSlot()
  455. def showPreferences(self) -> None:
  456. self.showPreferencesWindow.emit()
  457. @override(Application)
  458. def getGlobalContainerStack(self) -> Optional["GlobalStack"]:
  459. return self._global_container_stack
  460. @override(Application)
  461. def setGlobalContainerStack(self, stack: "GlobalStack") -> None:
  462. super().setGlobalContainerStack(stack)
  463. ## A reusable dialogbox
  464. #
  465. showMessageBox = pyqtSignal(str, str, str, str, int, int, arguments = ["title", "text", "informativeText", "detailedText", "buttons", "icon"])
  466. def messageBox(self, title, text, informativeText = "", detailedText = "", buttons = QMessageBox.Ok, icon = QMessageBox.NoIcon, callback = None, callback_arguments = []):
  467. self._message_box_callback = callback
  468. self._message_box_callback_arguments = callback_arguments
  469. self.showMessageBox.emit(title, text, informativeText, detailedText, buttons, icon)
  470. showDiscardOrKeepProfileChanges = pyqtSignal()
  471. def discardOrKeepProfileChanges(self) -> bool:
  472. has_user_interaction = False
  473. choice = self.getPreferences().getValue("cura/choice_on_profile_override")
  474. if choice == "always_discard":
  475. # don't show dialog and DISCARD the profile
  476. self.discardOrKeepProfileChangesClosed("discard")
  477. elif choice == "always_keep":
  478. # don't show dialog and KEEP the profile
  479. self.discardOrKeepProfileChangesClosed("keep")
  480. elif not self._is_headless:
  481. # ALWAYS ask whether to keep or discard the profile
  482. self.showDiscardOrKeepProfileChanges.emit()
  483. has_user_interaction = True
  484. return has_user_interaction
  485. @pyqtSlot(str)
  486. def discardOrKeepProfileChangesClosed(self, option: str) -> None:
  487. global_stack = self.getGlobalContainerStack()
  488. if option == "discard":
  489. for extruder in global_stack.extruders.values():
  490. extruder.userChanges.clear()
  491. global_stack.userChanges.clear()
  492. # if the user decided to keep settings then the user settings should be re-calculated and validated for errors
  493. # before slicing. To ensure that slicer uses right settings values
  494. elif option == "keep":
  495. for extruder in global_stack.extruders.values():
  496. extruder.userChanges.update()
  497. global_stack.userChanges.update()
  498. @pyqtSlot(int)
  499. def messageBoxClosed(self, button):
  500. if self._message_box_callback:
  501. self._message_box_callback(button, *self._message_box_callback_arguments)
  502. self._message_box_callback = None
  503. self._message_box_callback_arguments = []
  504. showPrintMonitor = pyqtSignal(bool, arguments = ["show"])
  505. def setSaveDataEnabled(self, enabled: bool) -> None:
  506. self._save_data_enabled = enabled
  507. # Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
  508. def saveSettings(self):
  509. if not self.started or not self._save_data_enabled:
  510. # Do not do saving during application start or when data should not be saved on quit.
  511. return
  512. ContainerRegistry.getInstance().saveDirtyContainers()
  513. self.savePreferences()
  514. def saveStack(self, stack):
  515. ContainerRegistry.getInstance().saveContainer(stack)
  516. @pyqtSlot(str, result = QUrl)
  517. def getDefaultPath(self, key):
  518. default_path = self.getPreferences().getValue("local_file/%s" % key)
  519. return QUrl.fromLocalFile(default_path)
  520. @pyqtSlot(str, str)
  521. def setDefaultPath(self, key, default_path):
  522. self.getPreferences().setValue("local_file/%s" % key, QUrl(default_path).toLocalFile())
  523. ## Handle loading of all plugin types (and the backend explicitly)
  524. # \sa PluginRegistry
  525. def _loadPlugins(self):
  526. self._plugin_registry.addType("profile_reader", self._addProfileReader)
  527. self._plugin_registry.addType("profile_writer", self._addProfileWriter)
  528. if Platform.isLinux():
  529. lib_suffixes = {"", "64", "32", "x32"} #A few common ones on different distributions.
  530. else:
  531. lib_suffixes = {""}
  532. for suffix in lib_suffixes:
  533. self._plugin_registry.addPluginLocation(os.path.join(QtApplication.getInstallPrefix(), "lib" + suffix, "cura"))
  534. if not hasattr(sys, "frozen"):
  535. self._plugin_registry.addPluginLocation(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "plugins"))
  536. self._plugin_registry.loadPlugin("ConsoleLogger")
  537. self._plugin_registry.loadPlugin("CuraEngineBackend")
  538. self._plugin_registry.loadPlugins()
  539. if self.getBackend() is None:
  540. raise RuntimeError("Could not load the backend plugin!")
  541. self._plugins_loaded = True
  542. def run(self):
  543. super().run()
  544. container_registry = self._container_registry
  545. Logger.log("i", "Initializing variant manager")
  546. self._variant_manager = VariantManager(container_registry)
  547. self._variant_manager.initialize()
  548. Logger.log("i", "Initializing material manager")
  549. from cura.Machines.MaterialManager import MaterialManager
  550. self._material_manager = MaterialManager(container_registry, parent = self)
  551. self._material_manager.initialize()
  552. Logger.log("i", "Initializing quality manager")
  553. from cura.Machines.QualityManager import QualityManager
  554. self._quality_manager = QualityManager(self, parent = self)
  555. self._quality_manager.initialize()
  556. Logger.log("i", "Initializing machine manager")
  557. self._machine_manager = MachineManager(self, parent = self)
  558. Logger.log("i", "Initializing container manager")
  559. self._container_manager = ContainerManager(self)
  560. Logger.log("i", "Initializing machine error checker")
  561. self._machine_error_checker = MachineErrorChecker(self)
  562. self._machine_error_checker.initialize()
  563. # Check if we should run as single instance or not. If so, set up a local socket server which listener which
  564. # coordinates multiple Cura instances and accepts commands.
  565. if self._use_single_instance:
  566. self.__setUpSingleInstanceServer()
  567. # Setup scene and build volume
  568. root = self.getController().getScene().getRoot()
  569. self._volume = BuildVolume.BuildVolume(self, root)
  570. Arrange.build_volume = self._volume
  571. # initialize info objects
  572. self._print_information = PrintInformation.PrintInformation(self)
  573. self._cura_actions = CuraActions.CuraActions(self)
  574. # Initialize setting visibility presets model.
  575. self._setting_visibility_presets_model = SettingVisibilityPresetsModel(self.getPreferences(), parent = self)
  576. # Initialize Cura API
  577. self._cura_API.initialize()
  578. # Detect in which mode to run and execute that mode
  579. if self._is_headless:
  580. self.runWithoutGUI()
  581. else:
  582. self.runWithGUI()
  583. self.started = True
  584. self.initializationFinished.emit()
  585. Logger.log("d", "Booting Cura took %s seconds", time.time() - self._boot_loading_time)
  586. # For now use a timer to postpone some things that need to be done after the application and GUI are
  587. # initialized, for example opening files because they may show dialogs which can be closed due to incomplete
  588. # GUI initialization.
  589. self._post_start_timer = QTimer(self)
  590. self._post_start_timer.setInterval(1000)
  591. self._post_start_timer.setSingleShot(True)
  592. self._post_start_timer.timeout.connect(self._onPostStart)
  593. self._post_start_timer.start()
  594. self._auto_save = AutoSave(self)
  595. self._auto_save.initialize()
  596. self.exec_()
  597. def __setUpSingleInstanceServer(self):
  598. if self._use_single_instance:
  599. self._single_instance.startServer()
  600. def _onPostStart(self):
  601. for file_name in self._files_to_open:
  602. self.callLater(self._openFile, file_name)
  603. for file_name in self._open_file_queue: # Open all the files that were queued up while plug-ins were loading.
  604. self.callLater(self._openFile, file_name)
  605. initializationFinished = pyqtSignal()
  606. ## Run Cura without GUI elements and interaction (server mode).
  607. def runWithoutGUI(self):
  608. self.closeSplash()
  609. ## Run Cura with GUI (desktop mode).
  610. def runWithGUI(self):
  611. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Setting up scene..."))
  612. controller = self.getController()
  613. t = controller.getTool("TranslateTool")
  614. if t:
  615. t.setEnabledAxis([ToolHandle.XAxis, ToolHandle.YAxis, ToolHandle.ZAxis])
  616. Selection.selectionChanged.connect(self.onSelectionChanged)
  617. # Set default background color for scene
  618. self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
  619. # Initialize platform physics
  620. self._physics = PlatformPhysics.PlatformPhysics(controller, self._volume)
  621. # Initialize camera
  622. root = controller.getScene().getRoot()
  623. camera = Camera("3d", root)
  624. diagonal = self.getBuildVolume().getDiagonalSize()
  625. if diagonal < 1: #No printer added yet. Set a default camera distance for normal-sized printers.
  626. diagonal = 375
  627. camera.setPosition(Vector(-80, 250, 700) * diagonal / 375)
  628. camera.setPerspective(True)
  629. camera.lookAt(Vector(0, 0, 0))
  630. controller.getScene().setActiveCamera("3d")
  631. # Initialize camera tool
  632. camera_tool = controller.getTool("CameraTool")
  633. camera_tool.setOrigin(Vector(0, 100, 0))
  634. camera_tool.setZoomRange(0.1, 2000)
  635. # Initialize camera animations
  636. self._camera_animation = CameraAnimation.CameraAnimation()
  637. self._camera_animation.setCameraTool(self.getController().getTool("CameraTool"))
  638. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading interface..."))
  639. # Initialize QML engine
  640. self.setMainQml(Resources.getPath(self.ResourceTypes.QmlFiles, "Cura.qml"))
  641. self._qml_import_paths.append(Resources.getPath(self.ResourceTypes.QmlFiles))
  642. self.initializeEngine()
  643. # Initialize UI state
  644. controller.setActiveStage("PrepareStage")
  645. controller.setActiveView("SolidView")
  646. controller.setCameraTool("CameraTool")
  647. controller.setSelectionTool("SelectionTool")
  648. # Hide the splash screen
  649. self.closeSplash()
  650. @pyqtSlot(result = QObject)
  651. def getSettingVisibilityPresetsModel(self, *args) -> SettingVisibilityPresetsModel:
  652. return self._setting_visibility_presets_model
  653. def getCuraFormulaFunctions(self, *args) -> "CuraFormulaFunctions":
  654. if self._cura_formula_functions is None:
  655. self._cura_formula_functions = CuraFormulaFunctions(self)
  656. return self._cura_formula_functions
  657. def getMachineErrorChecker(self, *args) -> MachineErrorChecker:
  658. return self._machine_error_checker
  659. def getMachineManager(self, *args) -> MachineManager:
  660. if self._machine_manager is None:
  661. self._machine_manager = MachineManager(self)
  662. return self._machine_manager
  663. def getExtruderManager(self, *args) -> ExtruderManager:
  664. if self._extruder_manager is None:
  665. self._extruder_manager = ExtruderManager()
  666. return self._extruder_manager
  667. def getVariantManager(self, *args) -> VariantManager:
  668. return self._variant_manager
  669. @pyqtSlot(result = QObject)
  670. def getMaterialManager(self, *args) -> "MaterialManager":
  671. return self._material_manager
  672. @pyqtSlot(result = QObject)
  673. def getQualityManager(self, *args) -> "QualityManager":
  674. return self._quality_manager
  675. def getObjectsModel(self, *args):
  676. if self._object_manager is None:
  677. self._object_manager = ObjectsModel.createObjectsModel()
  678. return self._object_manager
  679. @pyqtSlot(result = QObject)
  680. def getMultiBuildPlateModel(self, *args) -> MultiBuildPlateModel:
  681. if self._multi_build_plate_model is None:
  682. self._multi_build_plate_model = MultiBuildPlateModel(self)
  683. return self._multi_build_plate_model
  684. @pyqtSlot(result = QObject)
  685. def getBuildPlateModel(self, *args) -> BuildPlateModel:
  686. if self._build_plate_model is None:
  687. self._build_plate_model = BuildPlateModel(self)
  688. return self._build_plate_model
  689. def getCuraSceneController(self, *args) -> CuraSceneController:
  690. if self._cura_scene_controller is None:
  691. self._cura_scene_controller = CuraSceneController.createCuraSceneController()
  692. return self._cura_scene_controller
  693. def getSettingInheritanceManager(self, *args) -> SettingInheritanceManager:
  694. if self._setting_inheritance_manager is None:
  695. self._setting_inheritance_manager = SettingInheritanceManager.createSettingInheritanceManager()
  696. return self._setting_inheritance_manager
  697. ## Get the machine action manager
  698. # We ignore any *args given to this, as we also register the machine manager as qml singleton.
  699. # It wants to give this function an engine and script engine, but we don't care about that.
  700. def getMachineActionManager(self, *args):
  701. return self._machine_action_manager
  702. def getSimpleModeSettingsManager(self, *args):
  703. if self._simple_mode_settings_manager is None:
  704. self._simple_mode_settings_manager = SimpleModeSettingsManager()
  705. return self._simple_mode_settings_manager
  706. ## Handle Qt events
  707. def event(self, event):
  708. if event.type() == QEvent.FileOpen:
  709. if self._plugins_loaded:
  710. self._openFile(event.file())
  711. else:
  712. self._open_file_queue.append(event.file())
  713. return super().event(event)
  714. def getAutoSave(self):
  715. return self._auto_save
  716. ## Get print information (duration / material used)
  717. def getPrintInformation(self):
  718. return self._print_information
  719. def getQualityProfilesDropDownMenuModel(self, *args, **kwargs):
  720. if self._quality_profile_drop_down_menu_model is None:
  721. self._quality_profile_drop_down_menu_model = QualityProfilesDropDownMenuModel(self)
  722. return self._quality_profile_drop_down_menu_model
  723. def getCustomQualityProfilesDropDownMenuModel(self, *args, **kwargs):
  724. if self._custom_quality_profile_drop_down_menu_model is None:
  725. self._custom_quality_profile_drop_down_menu_model = CustomQualityProfilesDropDownMenuModel(self)
  726. return self._custom_quality_profile_drop_down_menu_model
  727. def getCuraAPI(self, *args, **kwargs) -> "CuraAPI":
  728. return self._cura_API
  729. ## Registers objects for the QML engine to use.
  730. #
  731. # \param engine The QML engine.
  732. def registerObjects(self, engine):
  733. super().registerObjects(engine)
  734. # global contexts
  735. engine.rootContext().setContextProperty("Printer", self)
  736. engine.rootContext().setContextProperty("CuraApplication", self)
  737. engine.rootContext().setContextProperty("PrintInformation", self._print_information)
  738. engine.rootContext().setContextProperty("CuraActions", self._cura_actions)
  739. engine.rootContext().setContextProperty("CuraSDKVersion", CuraSDKVersion)
  740. qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")
  741. qmlRegisterSingletonType(CuraSceneController, "Cura", 1, 0, "SceneController", self.getCuraSceneController)
  742. qmlRegisterSingletonType(ExtruderManager, "Cura", 1, 0, "ExtruderManager", self.getExtruderManager)
  743. qmlRegisterSingletonType(MachineManager, "Cura", 1, 0, "MachineManager", self.getMachineManager)
  744. qmlRegisterSingletonType(SettingInheritanceManager, "Cura", 1, 0, "SettingInheritanceManager", self.getSettingInheritanceManager)
  745. qmlRegisterSingletonType(SimpleModeSettingsManager, "Cura", 1, 0, "SimpleModeSettingsManager", self.getSimpleModeSettingsManager)
  746. qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, "MachineActionManager", self.getMachineActionManager)
  747. qmlRegisterType(NetworkMJPGImage, "Cura", 1, 0, "NetworkMJPGImage")
  748. qmlRegisterSingletonType(ObjectsModel, "Cura", 1, 0, "ObjectsModel", self.getObjectsModel)
  749. qmlRegisterType(BuildPlateModel, "Cura", 1, 0, "BuildPlateModel")
  750. qmlRegisterType(MultiBuildPlateModel, "Cura", 1, 0, "MultiBuildPlateModel")
  751. qmlRegisterType(InstanceContainer, "Cura", 1, 0, "InstanceContainer")
  752. qmlRegisterType(ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")
  753. qmlRegisterType(FavoriteMaterialsModel, "Cura", 1, 0, "FavoriteMaterialsModel")
  754. qmlRegisterType(GenericMaterialsModel, "Cura", 1, 0, "GenericMaterialsModel")
  755. qmlRegisterType(MaterialBrandsModel, "Cura", 1, 0, "MaterialBrandsModel")
  756. qmlRegisterType(QualityManagementModel, "Cura", 1, 0, "QualityManagementModel")
  757. qmlRegisterType(MachineManagementModel, "Cura", 1, 0, "MachineManagementModel")
  758. qmlRegisterSingletonType(QualityProfilesDropDownMenuModel, "Cura", 1, 0,
  759. "QualityProfilesDropDownMenuModel", self.getQualityProfilesDropDownMenuModel)
  760. qmlRegisterSingletonType(CustomQualityProfilesDropDownMenuModel, "Cura", 1, 0,
  761. "CustomQualityProfilesDropDownMenuModel", self.getCustomQualityProfilesDropDownMenuModel)
  762. qmlRegisterType(NozzleModel, "Cura", 1, 0, "NozzleModel")
  763. qmlRegisterType(MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
  764. qmlRegisterType(SettingVisibilityPresetsModel, "Cura", 1, 0, "SettingVisibilityPresetsModel")
  765. qmlRegisterType(QualitySettingsModel, "Cura", 1, 0, "QualitySettingsModel")
  766. qmlRegisterType(MachineNameValidator, "Cura", 1, 0, "MachineNameValidator")
  767. qmlRegisterType(UserChangesModel, "Cura", 1, 0, "UserChangesModel")
  768. qmlRegisterSingletonType(ContainerManager, "Cura", 1, 0, "ContainerManager", ContainerManager.getInstance)
  769. qmlRegisterType(SidebarCustomMenuItemsModel, "Cura", 1, 0, "SidebarCustomMenuItemsModel")
  770. from cura.API import CuraAPI
  771. qmlRegisterSingletonType(CuraAPI, "Cura", 1, 1, "API", self.getCuraAPI)
  772. # As of Qt5.7, it is necessary to get rid of any ".." in the path for the singleton to work.
  773. actions_url = QUrl.fromLocalFile(os.path.abspath(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")))
  774. qmlRegisterSingletonType(actions_url, "Cura", 1, 0, "Actions")
  775. for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
  776. type_name = os.path.splitext(os.path.basename(path))[0]
  777. if type_name in ("Cura", "Actions"):
  778. continue
  779. # Ignore anything that is not a QML file.
  780. if not path.endswith(".qml"):
  781. continue
  782. qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
  783. def onSelectionChanged(self):
  784. if Selection.hasSelection():
  785. if self.getController().getActiveTool():
  786. # If the tool has been disabled by the new selection
  787. if not self.getController().getActiveTool().getEnabled():
  788. # Default
  789. self.getController().setActiveTool("TranslateTool")
  790. else:
  791. if self._previous_active_tool:
  792. self.getController().setActiveTool(self._previous_active_tool)
  793. if not self.getController().getActiveTool().getEnabled():
  794. self.getController().setActiveTool("TranslateTool")
  795. self._previous_active_tool = None
  796. else:
  797. # Default
  798. self.getController().setActiveTool("TranslateTool")
  799. if self.getPreferences().getValue("view/center_on_select"):
  800. self._center_after_select = True
  801. else:
  802. if self.getController().getActiveTool():
  803. self._previous_active_tool = self.getController().getActiveTool().getPluginId()
  804. self.getController().setActiveTool(None)
  805. def _onToolOperationStopped(self, event):
  806. if self._center_after_select and Selection.getSelectedObject(0) is not None:
  807. self._center_after_select = False
  808. self._camera_animation.setStart(self.getController().getTool("CameraTool").getOrigin())
  809. self._camera_animation.setTarget(Selection.getSelectedObject(0).getWorldPosition())
  810. self._camera_animation.start()
  811. requestAddPrinter = pyqtSignal()
  812. activityChanged = pyqtSignal()
  813. sceneBoundingBoxChanged = pyqtSignal()
  814. @pyqtProperty(bool, notify = activityChanged)
  815. def platformActivity(self):
  816. return self._platform_activity
  817. @pyqtProperty(str, notify = sceneBoundingBoxChanged)
  818. def getSceneBoundingBoxString(self):
  819. 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()}
  820. def updatePlatformActivityDelayed(self, node = None):
  821. if node is not None and (node.getMeshData() is not None or node.callDecoration("getLayerData")):
  822. self._update_platform_activity_timer.start()
  823. ## Update scene bounding box for current build plate
  824. def updatePlatformActivity(self, node = None):
  825. count = 0
  826. scene_bounding_box = None
  827. is_block_slicing_node = False
  828. active_build_plate = self.getMultiBuildPlateModel().activeBuildPlate
  829. print_information = self.getPrintInformation()
  830. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  831. if (
  832. not issubclass(type(node), CuraSceneNode) or
  833. (not node.getMeshData() and not node.callDecoration("getLayerData")) or
  834. (node.callDecoration("getBuildPlateNumber") != active_build_plate)):
  835. continue
  836. if node.callDecoration("isBlockSlicing"):
  837. is_block_slicing_node = True
  838. count += 1
  839. # After clicking the Undo button, if the build plate empty the project name needs to be set
  840. if print_information.baseName == '':
  841. print_information.setBaseName(node.getName())
  842. if not scene_bounding_box:
  843. scene_bounding_box = node.getBoundingBox()
  844. else:
  845. other_bb = node.getBoundingBox()
  846. if other_bb is not None:
  847. scene_bounding_box = scene_bounding_box + node.getBoundingBox()
  848. if print_information:
  849. print_information.setPreSliced(is_block_slicing_node)
  850. if not scene_bounding_box:
  851. scene_bounding_box = AxisAlignedBox.Null
  852. if repr(self._scene_bounding_box) != repr(scene_bounding_box):
  853. self._scene_bounding_box = scene_bounding_box
  854. self.sceneBoundingBoxChanged.emit()
  855. self._platform_activity = True if count > 0 else False
  856. self.activityChanged.emit()
  857. # Remove all selected objects from the scene.
  858. @pyqtSlot()
  859. @deprecated("Moved to CuraActions", "2.6")
  860. def deleteSelection(self):
  861. if not self.getController().getToolsEnabled():
  862. return
  863. removed_group_nodes = []
  864. op = GroupedOperation()
  865. nodes = Selection.getAllSelectedObjects()
  866. for node in nodes:
  867. op.addOperation(RemoveSceneNodeOperation(node))
  868. group_node = node.getParent()
  869. if group_node and group_node.callDecoration("isGroup") and group_node not in removed_group_nodes:
  870. remaining_nodes_in_group = list(set(group_node.getChildren()) - set(nodes))
  871. if len(remaining_nodes_in_group) == 1:
  872. removed_group_nodes.append(group_node)
  873. op.addOperation(SetParentOperation(remaining_nodes_in_group[0], group_node.getParent()))
  874. op.addOperation(RemoveSceneNodeOperation(group_node))
  875. op.push()
  876. ## Remove an object from the scene.
  877. # Note that this only removes an object if it is selected.
  878. @pyqtSlot("quint64")
  879. @deprecated("Use deleteSelection instead", "2.6")
  880. def deleteObject(self, object_id):
  881. if not self.getController().getToolsEnabled():
  882. return
  883. node = self.getController().getScene().findObject(object_id)
  884. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  885. node = Selection.getSelectedObject(0)
  886. if node:
  887. op = GroupedOperation()
  888. op.addOperation(RemoveSceneNodeOperation(node))
  889. group_node = node.getParent()
  890. if group_node:
  891. # Note that at this point the node has not yet been deleted
  892. if len(group_node.getChildren()) <= 2 and group_node.callDecoration("isGroup"):
  893. op.addOperation(SetParentOperation(group_node.getChildren()[0], group_node.getParent()))
  894. op.addOperation(RemoveSceneNodeOperation(group_node))
  895. op.push()
  896. ## Create a number of copies of existing object.
  897. # \param object_id
  898. # \param count number of copies
  899. # \param min_offset minimum offset to other objects.
  900. @pyqtSlot("quint64", int)
  901. @deprecated("Use CuraActions::multiplySelection", "2.6")
  902. def multiplyObject(self, object_id, count, min_offset = 8):
  903. node = self.getController().getScene().findObject(object_id)
  904. if not node:
  905. node = Selection.getSelectedObject(0)
  906. while node.getParent() and node.getParent().callDecoration("isGroup"):
  907. node = node.getParent()
  908. job = MultiplyObjectsJob([node], count, min_offset)
  909. job.start()
  910. return
  911. ## Center object on platform.
  912. @pyqtSlot("quint64")
  913. @deprecated("Use CuraActions::centerSelection", "2.6")
  914. def centerObject(self, object_id):
  915. node = self.getController().getScene().findObject(object_id)
  916. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  917. node = Selection.getSelectedObject(0)
  918. if not node:
  919. return
  920. if node.getParent() and node.getParent().callDecoration("isGroup"):
  921. node = node.getParent()
  922. if node:
  923. op = SetTransformOperation(node, Vector())
  924. op.push()
  925. ## Select all nodes containing mesh data in the scene.
  926. @pyqtSlot()
  927. def selectAll(self):
  928. if not self.getController().getToolsEnabled():
  929. return
  930. Selection.clear()
  931. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  932. if not isinstance(node, SceneNode):
  933. continue
  934. if not node.getMeshData() and not node.callDecoration("isGroup"):
  935. continue # Node that doesnt have a mesh and is not a group.
  936. if node.getParent() and node.getParent().callDecoration("isGroup") or node.getParent().callDecoration("isSliceable"):
  937. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  938. if not node.isSelectable():
  939. continue # i.e. node with layer data
  940. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  941. continue # i.e. node with layer data
  942. Selection.add(node)
  943. ## Reset all translation on nodes with mesh data.
  944. @pyqtSlot()
  945. def resetAllTranslation(self):
  946. Logger.log("i", "Resetting all scene translations")
  947. nodes = []
  948. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  949. if not isinstance(node, SceneNode):
  950. continue
  951. if not node.getMeshData() and not node.callDecoration("isGroup"):
  952. continue # Node that doesnt have a mesh and is not a group.
  953. if node.getParent() and node.getParent().callDecoration("isGroup"):
  954. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  955. if not node.isSelectable():
  956. continue # i.e. node with layer data
  957. nodes.append(node)
  958. if nodes:
  959. op = GroupedOperation()
  960. for node in nodes:
  961. # Ensure that the object is above the build platform
  962. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  963. if node.getBoundingBox():
  964. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  965. else:
  966. center_y = 0
  967. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0)))
  968. op.push()
  969. ## Reset all transformations on nodes with mesh data.
  970. @pyqtSlot()
  971. def resetAll(self):
  972. Logger.log("i", "Resetting all scene transformations")
  973. nodes = []
  974. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  975. if not isinstance(node, SceneNode):
  976. continue
  977. if not node.getMeshData() and not node.callDecoration("isGroup"):
  978. continue # Node that doesnt have a mesh and is not a group.
  979. if node.getParent() and node.getParent().callDecoration("isGroup"):
  980. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  981. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  982. continue # i.e. node with layer data
  983. nodes.append(node)
  984. if nodes:
  985. op = GroupedOperation()
  986. for node in nodes:
  987. # Ensure that the object is above the build platform
  988. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  989. if node.getBoundingBox():
  990. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  991. else:
  992. center_y = 0
  993. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0), Quaternion(), Vector(1, 1, 1)))
  994. op.push()
  995. ## Arrange all objects.
  996. @pyqtSlot()
  997. def arrangeObjectsToAllBuildPlates(self):
  998. nodes = []
  999. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1000. if not isinstance(node, SceneNode):
  1001. continue
  1002. if not node.getMeshData() and not node.callDecoration("isGroup"):
  1003. continue # Node that doesnt have a mesh and is not a group.
  1004. if node.getParent() and node.getParent().callDecoration("isGroup"):
  1005. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  1006. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1007. continue # i.e. node with layer data
  1008. # Skip nodes that are too big
  1009. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1010. nodes.append(node)
  1011. job = ArrangeObjectsAllBuildPlatesJob(nodes)
  1012. job.start()
  1013. self.getCuraSceneController().setActiveBuildPlate(0) # Select first build plate
  1014. # Single build plate
  1015. @pyqtSlot()
  1016. def arrangeAll(self):
  1017. nodes = []
  1018. active_build_plate = self.getMultiBuildPlateModel().activeBuildPlate
  1019. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1020. if not isinstance(node, SceneNode):
  1021. continue
  1022. if not node.getMeshData() and not node.callDecoration("isGroup"):
  1023. continue # Node that doesnt have a mesh and is not a group.
  1024. if node.getParent() and node.getParent().callDecoration("isGroup"):
  1025. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  1026. if not node.isSelectable():
  1027. continue # i.e. node with layer data
  1028. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1029. continue # i.e. node with layer data
  1030. if node.callDecoration("getBuildPlateNumber") == active_build_plate:
  1031. # Skip nodes that are too big
  1032. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1033. nodes.append(node)
  1034. self.arrange(nodes, fixed_nodes = [])
  1035. ## Arrange a set of nodes given a set of fixed nodes
  1036. # \param nodes nodes that we have to place
  1037. # \param fixed_nodes nodes that are placed in the arranger before finding spots for nodes
  1038. def arrange(self, nodes, fixed_nodes):
  1039. min_offset = self.getBuildVolume().getEdgeDisallowedSize() + 2 # Allow for some rounding errors
  1040. job = ArrangeObjectsJob(nodes, fixed_nodes, min_offset = max(min_offset, 8))
  1041. job.start()
  1042. ## Reload all mesh data on the screen from file.
  1043. @pyqtSlot()
  1044. def reloadAll(self):
  1045. Logger.log("i", "Reloading all loaded mesh data.")
  1046. nodes = []
  1047. has_merged_nodes = False
  1048. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1049. if not isinstance(node, CuraSceneNode) or not node.getMeshData() :
  1050. if node.getName() == "MergedMesh":
  1051. has_merged_nodes = True
  1052. continue
  1053. nodes.append(node)
  1054. if not nodes:
  1055. return
  1056. for node in nodes:
  1057. file_name = node.getMeshData().getFileName()
  1058. if file_name:
  1059. job = ReadMeshJob(file_name)
  1060. job._node = node
  1061. job.finished.connect(self._reloadMeshFinished)
  1062. if has_merged_nodes:
  1063. job.finished.connect(self.updateOriginOfMergedMeshes)
  1064. job.start()
  1065. else:
  1066. Logger.log("w", "Unable to reload data because we don't have a filename.")
  1067. ## Get logging data of the backend engine
  1068. # \returns \type{string} Logging data
  1069. @pyqtSlot(result = str)
  1070. def getEngineLog(self):
  1071. log = ""
  1072. for entry in self.getBackend().getLog():
  1073. log += entry.decode()
  1074. return log
  1075. @pyqtSlot("QStringList")
  1076. def setExpandedCategories(self, categories):
  1077. categories = list(set(categories))
  1078. categories.sort()
  1079. joined = ";".join(categories)
  1080. if joined != self.getPreferences().getValue("cura/categories_expanded"):
  1081. self.getPreferences().setValue("cura/categories_expanded", joined)
  1082. self.expandedCategoriesChanged.emit()
  1083. expandedCategoriesChanged = pyqtSignal()
  1084. @pyqtProperty("QStringList", notify = expandedCategoriesChanged)
  1085. def expandedCategories(self):
  1086. return self.getPreferences().getValue("cura/categories_expanded").split(";")
  1087. @pyqtSlot()
  1088. def mergeSelected(self):
  1089. self.groupSelected()
  1090. try:
  1091. group_node = Selection.getAllSelectedObjects()[0]
  1092. except Exception as e:
  1093. Logger.log("e", "mergeSelected: Exception: %s", e)
  1094. return
  1095. meshes = [node.getMeshData() for node in group_node.getAllChildren() if node.getMeshData()]
  1096. # Compute the center of the objects
  1097. object_centers = []
  1098. # Forget about the translation that the original objects have
  1099. zero_translation = Matrix(data=numpy.zeros(3))
  1100. for mesh, node in zip(meshes, group_node.getChildren()):
  1101. transformation = node.getLocalTransformation()
  1102. transformation.setTranslation(zero_translation)
  1103. transformed_mesh = mesh.getTransformed(transformation)
  1104. center = transformed_mesh.getCenterPosition()
  1105. if center is not None:
  1106. object_centers.append(center)
  1107. if object_centers and len(object_centers) > 0:
  1108. middle_x = sum([v.x for v in object_centers]) / len(object_centers)
  1109. middle_y = sum([v.y for v in object_centers]) / len(object_centers)
  1110. middle_z = sum([v.z for v in object_centers]) / len(object_centers)
  1111. offset = Vector(middle_x, middle_y, middle_z)
  1112. else:
  1113. offset = Vector(0, 0, 0)
  1114. # Move each node to the same position.
  1115. for mesh, node in zip(meshes, group_node.getChildren()):
  1116. transformation = node.getLocalTransformation()
  1117. transformation.setTranslation(zero_translation)
  1118. transformed_mesh = mesh.getTransformed(transformation)
  1119. # Align the object around its zero position
  1120. # and also apply the offset to center it inside the group.
  1121. node.setPosition(-transformed_mesh.getZeroPosition() - offset)
  1122. # Use the previously found center of the group bounding box as the new location of the group
  1123. group_node.setPosition(group_node.getBoundingBox().center)
  1124. group_node.setName("MergedMesh") # add a specific name to distinguish this node
  1125. ## Updates origin position of all merged meshes
  1126. # \param jobNode \type{Job} empty object which passed which is required by JobQueue
  1127. def updateOriginOfMergedMeshes(self, jobNode):
  1128. group_nodes = []
  1129. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1130. if isinstance(node, CuraSceneNode) and node.getName() == "MergedMesh":
  1131. #checking by name might be not enough, the merged mesh should has "GroupDecorator" decorator
  1132. for decorator in node.getDecorators():
  1133. if isinstance(decorator, GroupDecorator):
  1134. group_nodes.append(node)
  1135. break
  1136. for group_node in group_nodes:
  1137. meshes = [node.getMeshData() for node in group_node.getAllChildren() if node.getMeshData()]
  1138. # Compute the center of the objects
  1139. object_centers = []
  1140. # Forget about the translation that the original objects have
  1141. zero_translation = Matrix(data=numpy.zeros(3))
  1142. for mesh, node in zip(meshes, group_node.getChildren()):
  1143. transformation = node.getLocalTransformation()
  1144. transformation.setTranslation(zero_translation)
  1145. transformed_mesh = mesh.getTransformed(transformation)
  1146. center = transformed_mesh.getCenterPosition()
  1147. if center is not None:
  1148. object_centers.append(center)
  1149. if object_centers and len(object_centers) > 0:
  1150. middle_x = sum([v.x for v in object_centers]) / len(object_centers)
  1151. middle_y = sum([v.y for v in object_centers]) / len(object_centers)
  1152. middle_z = sum([v.z for v in object_centers]) / len(object_centers)
  1153. offset = Vector(middle_x, middle_y, middle_z)
  1154. else:
  1155. offset = Vector(0, 0, 0)
  1156. # Move each node to the same position.
  1157. for mesh, node in zip(meshes, group_node.getChildren()):
  1158. transformation = node.getLocalTransformation()
  1159. transformation.setTranslation(zero_translation)
  1160. transformed_mesh = mesh.getTransformed(transformation)
  1161. # Align the object around its zero position
  1162. # and also apply the offset to center it inside the group.
  1163. node.setPosition(-transformed_mesh.getZeroPosition() - offset)
  1164. # Use the previously found center of the group bounding box as the new location of the group
  1165. group_node.setPosition(group_node.getBoundingBox().center)
  1166. @pyqtSlot()
  1167. def groupSelected(self):
  1168. # Create a group-node
  1169. group_node = CuraSceneNode()
  1170. group_decorator = GroupDecorator()
  1171. group_node.addDecorator(group_decorator)
  1172. group_node.addDecorator(ConvexHullDecorator())
  1173. group_node.addDecorator(BuildPlateDecorator(self.getMultiBuildPlateModel().activeBuildPlate))
  1174. group_node.setParent(self.getController().getScene().getRoot())
  1175. group_node.setSelectable(True)
  1176. center = Selection.getSelectionCenter()
  1177. group_node.setPosition(center)
  1178. group_node.setCenterPosition(center)
  1179. # Remove nodes that are directly parented to another selected node from the selection so they remain parented
  1180. selected_nodes = Selection.getAllSelectedObjects().copy()
  1181. for node in selected_nodes:
  1182. if node.getParent() in selected_nodes and not node.getParent().callDecoration("isGroup"):
  1183. Selection.remove(node)
  1184. # Move selected nodes into the group-node
  1185. Selection.applyOperation(SetParentOperation, group_node)
  1186. # Deselect individual nodes and select the group-node instead
  1187. for node in group_node.getChildren():
  1188. Selection.remove(node)
  1189. Selection.add(group_node)
  1190. @pyqtSlot()
  1191. def ungroupSelected(self):
  1192. selected_objects = Selection.getAllSelectedObjects().copy()
  1193. for node in selected_objects:
  1194. if node.callDecoration("isGroup"):
  1195. op = GroupedOperation()
  1196. group_parent = node.getParent()
  1197. children = node.getChildren().copy()
  1198. for child in children:
  1199. # Ungroup only 1 level deep
  1200. if child.getParent() != node:
  1201. continue
  1202. # Set the parent of the children to the parent of the group-node
  1203. op.addOperation(SetParentOperation(child, group_parent))
  1204. # Add all individual nodes to the selection
  1205. Selection.add(child)
  1206. op.push()
  1207. # Note: The group removes itself from the scene once all its children have left it,
  1208. # see GroupDecorator._onChildrenChanged
  1209. def _createSplashScreen(self):
  1210. if self._is_headless:
  1211. return None
  1212. return CuraSplashScreen.CuraSplashScreen()
  1213. def _onActiveMachineChanged(self):
  1214. pass
  1215. fileLoaded = pyqtSignal(str)
  1216. fileCompleted = pyqtSignal(str)
  1217. def _reloadMeshFinished(self, job):
  1218. # TODO; This needs to be fixed properly. We now make the assumption that we only load a single mesh!
  1219. job_result = job.getResult()
  1220. if len(job_result) == 0:
  1221. Logger.log("e", "Reloading the mesh failed.")
  1222. return
  1223. mesh_data = job_result[0].getMeshData()
  1224. if not mesh_data:
  1225. Logger.log("w", "Could not find a mesh in reloaded node.")
  1226. return
  1227. job._node.setMeshData(mesh_data)
  1228. def _openFile(self, filename):
  1229. self.readLocalFile(QUrl.fromLocalFile(filename))
  1230. def _addProfileReader(self, profile_reader):
  1231. # TODO: Add the profile reader to the list of plug-ins that can be used when importing profiles.
  1232. pass
  1233. def _addProfileWriter(self, profile_writer):
  1234. pass
  1235. @pyqtSlot("QSize")
  1236. def setMinimumWindowSize(self, size):
  1237. main_window = self.getMainWindow()
  1238. if main_window:
  1239. main_window.setMinimumSize(size)
  1240. def getBuildVolume(self):
  1241. return self._volume
  1242. additionalComponentsChanged = pyqtSignal(str, arguments = ["areaId"])
  1243. @pyqtProperty("QVariantMap", notify = additionalComponentsChanged)
  1244. def additionalComponents(self):
  1245. return self._additional_components
  1246. ## Add a component to a list of components to be reparented to another area in the GUI.
  1247. # The actual reparenting is done by the area itself.
  1248. # \param area_id \type{str} Identifying name of the area to which the component should be reparented
  1249. # \param component \type{QQuickComponent} The component that should be reparented
  1250. @pyqtSlot(str, "QVariant")
  1251. def addAdditionalComponent(self, area_id, component):
  1252. if area_id not in self._additional_components:
  1253. self._additional_components[area_id] = []
  1254. self._additional_components[area_id].append(component)
  1255. self.additionalComponentsChanged.emit(area_id)
  1256. @pyqtSlot(str)
  1257. def log(self, msg):
  1258. Logger.log("d", msg)
  1259. openProjectFile = pyqtSignal(QUrl, arguments = ["project_file"]) # Emitted when a project file is about to open.
  1260. @pyqtSlot(QUrl, bool)
  1261. def readLocalFile(self, file, skip_project_file_check = False):
  1262. if not file.isValid():
  1263. return
  1264. scene = self.getController().getScene()
  1265. for node in DepthFirstIterator(scene.getRoot()):
  1266. if node.callDecoration("isBlockSlicing"):
  1267. self.deleteAll()
  1268. break
  1269. if not skip_project_file_check and self.checkIsValidProjectFile(file):
  1270. self.callLater(self.openProjectFile.emit, file)
  1271. return
  1272. if self.getPreferences().getValue("cura/select_models_on_load"):
  1273. Selection.clear()
  1274. f = file.toLocalFile()
  1275. extension = os.path.splitext(f)[1]
  1276. extension = extension.lower()
  1277. filename = os.path.basename(f)
  1278. if len(self._currently_loading_files) > 0:
  1279. # If a non-slicable file is already being loaded, we prevent loading of any further non-slicable files
  1280. if extension in self._non_sliceable_extensions:
  1281. message = Message(
  1282. self._i18n_catalog.i18nc("@info:status",
  1283. "Only one G-code file can be loaded at a time. Skipped importing {0}",
  1284. filename), title = self._i18n_catalog.i18nc("@info:title", "Warning"))
  1285. message.show()
  1286. return
  1287. # If file being loaded is non-slicable file, then prevent loading of any other files
  1288. extension = os.path.splitext(self._currently_loading_files[0])[1]
  1289. extension = extension.lower()
  1290. if extension in self._non_sliceable_extensions:
  1291. message = Message(
  1292. self._i18n_catalog.i18nc("@info:status",
  1293. "Can't open any other file if G-code is loading. Skipped importing {0}",
  1294. filename), title = self._i18n_catalog.i18nc("@info:title", "Error"))
  1295. message.show()
  1296. return
  1297. self._currently_loading_files.append(f)
  1298. if extension in self._non_sliceable_extensions:
  1299. self.deleteAll(only_selectable = False)
  1300. job = ReadMeshJob(f)
  1301. job.finished.connect(self._readMeshFinished)
  1302. job.start()
  1303. def _readMeshFinished(self, job):
  1304. global_container_stack = self.getGlobalContainerStack()
  1305. if not global_container_stack:
  1306. Logger.log("w", "Can't load meshes before a printer is added.")
  1307. return
  1308. nodes = job.getResult()
  1309. file_name = job.getFileName()
  1310. file_name_lower = file_name.lower()
  1311. file_extension = file_name_lower.split(".")[-1]
  1312. self._currently_loading_files.remove(file_name)
  1313. self.fileLoaded.emit(file_name)
  1314. target_build_plate = self.getMultiBuildPlateModel().activeBuildPlate
  1315. root = self.getController().getScene().getRoot()
  1316. fixed_nodes = []
  1317. for node_ in DepthFirstIterator(root):
  1318. if node_.callDecoration("isSliceable") and node_.callDecoration("getBuildPlateNumber") == target_build_plate:
  1319. fixed_nodes.append(node_)
  1320. machine_width = global_container_stack.getProperty("machine_width", "value")
  1321. machine_depth = global_container_stack.getProperty("machine_depth", "value")
  1322. arranger = Arrange.create(x = machine_width, y = machine_depth, fixed_nodes = fixed_nodes)
  1323. min_offset = 8
  1324. default_extruder_position = self.getMachineManager().defaultExtruderPosition
  1325. default_extruder_id = self._global_container_stack.extruders[default_extruder_position].getId()
  1326. select_models_on_load = self.getPreferences().getValue("cura/select_models_on_load")
  1327. for original_node in nodes:
  1328. # Create a CuraSceneNode just if the original node is not that type
  1329. if isinstance(original_node, CuraSceneNode):
  1330. node = original_node
  1331. else:
  1332. node = CuraSceneNode()
  1333. node.setMeshData(original_node.getMeshData())
  1334. #Setting meshdata does not apply scaling.
  1335. if(original_node.getScale() != Vector(1.0, 1.0, 1.0)):
  1336. node.scale(original_node.getScale())
  1337. node.setSelectable(True)
  1338. node.setName(os.path.basename(file_name))
  1339. self.getBuildVolume().checkBoundsAndUpdate(node)
  1340. is_non_sliceable = "." + file_extension in self._non_sliceable_extensions
  1341. if is_non_sliceable:
  1342. self.callLater(lambda: self.getController().setActiveView("SimulationView"))
  1343. block_slicing_decorator = BlockSlicingDecorator()
  1344. node.addDecorator(block_slicing_decorator)
  1345. else:
  1346. sliceable_decorator = SliceableObjectDecorator()
  1347. node.addDecorator(sliceable_decorator)
  1348. scene = self.getController().getScene()
  1349. # If there is no convex hull for the node, start calculating it and continue.
  1350. if not node.getDecorator(ConvexHullDecorator):
  1351. node.addDecorator(ConvexHullDecorator())
  1352. for child in node.getAllChildren():
  1353. if not child.getDecorator(ConvexHullDecorator):
  1354. child.addDecorator(ConvexHullDecorator())
  1355. if file_extension != "3mf":
  1356. if node.callDecoration("isSliceable"):
  1357. # Only check position if it's not already blatantly obvious that it won't fit.
  1358. 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:
  1359. # Find node location
  1360. offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = min_offset)
  1361. # If a model is to small then it will not contain any points
  1362. if offset_shape_arr is None and hull_shape_arr is None:
  1363. Message(self._i18n_catalog.i18nc("@info:status", "The selected model was too small to load."),
  1364. title=self._i18n_catalog.i18nc("@info:title", "Warning")).show()
  1365. return
  1366. # Step is for skipping tests to make it a lot faster. it also makes the outcome somewhat rougher
  1367. arranger.findNodePlacement(node, offset_shape_arr, hull_shape_arr, step = 10)
  1368. # This node is deep copied from some other node which already has a BuildPlateDecorator, but the deepcopy
  1369. # of BuildPlateDecorator produces one that's associated with build plate -1. So, here we need to check if
  1370. # the BuildPlateDecorator exists or not and always set the correct build plate number.
  1371. build_plate_decorator = node.getDecorator(BuildPlateDecorator)
  1372. if build_plate_decorator is None:
  1373. build_plate_decorator = BuildPlateDecorator(target_build_plate)
  1374. node.addDecorator(build_plate_decorator)
  1375. build_plate_decorator.setBuildPlateNumber(target_build_plate)
  1376. op = AddSceneNodeOperation(node, scene.getRoot())
  1377. op.push()
  1378. node.callDecoration("setActiveExtruder", default_extruder_id)
  1379. scene.sceneChanged.emit(node)
  1380. if select_models_on_load:
  1381. Selection.add(node)
  1382. self.fileCompleted.emit(file_name)
  1383. def addNonSliceableExtension(self, extension):
  1384. self._non_sliceable_extensions.append(extension)
  1385. @pyqtSlot(str, result=bool)
  1386. def checkIsValidProjectFile(self, file_url):
  1387. """
  1388. Checks if the given file URL is a valid project file.
  1389. """
  1390. file_path = QUrl(file_url).toLocalFile()
  1391. workspace_reader = self.getWorkspaceFileHandler().getReaderForFile(file_path)
  1392. if workspace_reader is None:
  1393. return False # non-project files won't get a reader
  1394. try:
  1395. result = workspace_reader.preRead(file_path, show_dialog=False)
  1396. return result == WorkspaceReader.PreReadResult.accepted
  1397. except Exception as e:
  1398. Logger.logException("e", "Could not check file %s", file_url)
  1399. return False
  1400. def _onContextMenuRequested(self, x: float, y: float) -> None:
  1401. # Ensure we select the object if we request a context menu over an object without having a selection.
  1402. if not Selection.hasSelection():
  1403. node = self.getController().getScene().findObject(cast(SelectionPass, self.getRenderer().getRenderPass("selection")).getIdAtPosition(x, y))
  1404. if node:
  1405. parent = node.getParent()
  1406. while(parent and parent.callDecoration("isGroup")):
  1407. node = parent
  1408. parent = node.getParent()
  1409. Selection.add(node)
  1410. @pyqtSlot()
  1411. def showMoreInformationDialogForAnonymousDataCollection(self):
  1412. try:
  1413. slice_info = self._plugin_registry.getPluginObject("SliceInfoPlugin")
  1414. slice_info.showMoreInfoDialog()
  1415. except PluginNotFoundError:
  1416. Logger.log("w", "Plugin SliceInfo was not found, so not able to show the info dialog.")
  1417. def addSidebarCustomMenuItem(self, menu_item: dict) -> None:
  1418. self._sidebar_custom_menu_items.append(menu_item)
  1419. def getSidebarCustomMenuItems(self) -> list:
  1420. return self._sidebar_custom_menu_items