CuraApplication.py 81 KB

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