CuraApplication.py 84 KB

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