CuraApplication.py 78 KB

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