CuraApplication.py 80 KB

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