CuraApplication.py 89 KB

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