CuraApplication.py 79 KB

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