CuraApplication.py 87 KB

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