CuraApplication.py 78 KB

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