CuraApplication.py 81 KB

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