CuraApplication.py 81 KB

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