CuraApplication.py 79 KB

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