CuraApplication.py 80 KB

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