CuraApplication.py 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  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.QtNetwork import QLocalServer
  6. from PyQt5.QtNetwork import QLocalSocket
  7. from UM.Qt.QtApplication import QtApplication
  8. from UM.Scene.SceneNode import SceneNode
  9. from UM.Scene.Camera import Camera
  10. from UM.Math.Vector import Vector
  11. from UM.Math.Quaternion import Quaternion
  12. from UM.Math.AxisAlignedBox import AxisAlignedBox
  13. from UM.Math.Matrix import Matrix
  14. from UM.Platform import Platform
  15. from UM.Resources import Resources
  16. from UM.Scene.ToolHandle import ToolHandle
  17. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  18. from UM.Mesh.ReadMeshJob import ReadMeshJob
  19. from UM.Logger import Logger
  20. from UM.Preferences import Preferences
  21. from UM.Scene.Selection import Selection
  22. from UM.Scene.GroupDecorator import GroupDecorator
  23. from UM.Settings.ContainerStack import ContainerStack
  24. from UM.Settings.InstanceContainer import InstanceContainer
  25. from UM.Settings.Validator import Validator
  26. from UM.Message import Message
  27. from UM.i18n import i18nCatalog
  28. from UM.Workspace.WorkspaceReader import WorkspaceReader
  29. from UM.Decorators import deprecated
  30. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  31. from UM.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
  32. from UM.Operations.GroupedOperation import GroupedOperation
  33. from UM.Operations.SetTransformOperation import SetTransformOperation
  34. from cura.Arranging.Arrange import Arrange
  35. from cura.Arranging.ArrangeObjectsJob import ArrangeObjectsJob
  36. from cura.Arranging.ArrangeObjectsAllBuildPlatesJob import ArrangeObjectsAllBuildPlatesJob
  37. from cura.Arranging.ShapeArray import ShapeArray
  38. from cura.MultiplyObjectsJob import MultiplyObjectsJob
  39. from cura.Scene.ConvexHullDecorator import ConvexHullDecorator
  40. from cura.Operations.SetParentOperation import SetParentOperation
  41. from cura.Scene.SliceableObjectDecorator import SliceableObjectDecorator
  42. from cura.Scene.BlockSlicingDecorator import BlockSlicingDecorator
  43. from cura.Scene.BuildPlateDecorator import BuildPlateDecorator
  44. from cura.Scene.CuraSceneNode import CuraSceneNode
  45. from cura.Scene.CuraSceneController import CuraSceneController
  46. from UM.Settings.SettingDefinition import SettingDefinition, DefinitionPropertyType
  47. from UM.Settings.ContainerRegistry import ContainerRegistry
  48. from UM.Settings.SettingFunction import SettingFunction
  49. from cura.Settings.MachineNameValidator import MachineNameValidator
  50. from cura.Machines.Models.NozzleModel import NozzleModel
  51. from cura.Settings.ProfilesModel import ProfilesModel, NewQualityProfilesModel, NewCustomQualityProfilesModel
  52. from cura.Settings.MaterialsModel import MaterialsModel, BrandMaterialsModel, GenericMaterialsModel
  53. from cura.Settings.QualityAndUserProfilesModel import QualityAndUserProfilesModel
  54. from cura.Settings.SettingInheritanceManager import SettingInheritanceManager
  55. from cura.Settings.UserProfilesModel import UserProfilesModel
  56. from cura.Settings.SimpleModeSettingsManager import SimpleModeSettingsManager
  57. from cura.Machines.VariantManager import VariantManager
  58. from . import PlatformPhysics
  59. from . import BuildVolume
  60. from . import CameraAnimation
  61. from . import PrintInformation
  62. from . import CuraActions
  63. from cura.Scene import ZOffsetDecorator
  64. from . import CuraSplashScreen
  65. from . import CameraImageProvider
  66. from . import MachineActionManager
  67. from cura.Settings.MachineManager import MachineManager
  68. from cura.Settings.MaterialManager import MaterialManager
  69. from cura.Settings.ExtruderManager import ExtruderManager
  70. from cura.Settings.UserChangesModel import UserChangesModel
  71. from cura.Settings.ExtrudersModel import ExtrudersModel
  72. from cura.Settings.ContainerSettingsModel import ContainerSettingsModel
  73. from cura.Settings.MaterialSettingsVisibilityHandler import MaterialSettingsVisibilityHandler
  74. from cura.Settings.QualitySettingsModel import QualitySettingsModel
  75. from cura.Settings.ContainerManager import ContainerManager
  76. from cura.ObjectsModel import ObjectsModel
  77. from cura.BuildPlateModel import BuildPlateModel
  78. from PyQt5.QtCore import QUrl, pyqtSignal, pyqtProperty, QEvent, Q_ENUMS
  79. from UM.FlameProfiler import pyqtSlot
  80. from PyQt5.QtGui import QColor, QIcon
  81. from PyQt5.QtWidgets import QMessageBox
  82. from PyQt5.QtQml import qmlRegisterUncreatableType, qmlRegisterSingletonType, qmlRegisterType
  83. from configparser import ConfigParser
  84. import sys
  85. import os.path
  86. import numpy
  87. import copy
  88. import os
  89. import argparse
  90. import json
  91. numpy.seterr(all="ignore")
  92. MYPY = False
  93. if not MYPY:
  94. try:
  95. from cura.CuraVersion import CuraVersion, CuraBuildType, CuraDebugMode
  96. except ImportError:
  97. CuraVersion = "master" # [CodeStyle: Reflecting imported value]
  98. CuraBuildType = ""
  99. CuraDebugMode = False
  100. class CuraApplication(QtApplication):
  101. # SettingVersion represents the set of settings available in the machine/extruder definitions.
  102. # You need to make sure that this version number needs to be increased if there is any non-backwards-compatible
  103. # changes of the settings.
  104. SettingVersion = 4
  105. Created = False
  106. class ResourceTypes:
  107. QmlFiles = Resources.UserType + 1
  108. Firmware = Resources.UserType + 2
  109. QualityInstanceContainer = Resources.UserType + 3
  110. MaterialInstanceContainer = Resources.UserType + 4
  111. VariantInstanceContainer = Resources.UserType + 5
  112. UserInstanceContainer = Resources.UserType + 6
  113. MachineStack = Resources.UserType + 7
  114. ExtruderStack = Resources.UserType + 8
  115. DefinitionChangesContainer = Resources.UserType + 9
  116. Q_ENUMS(ResourceTypes)
  117. # FIXME: This signal belongs to the MachineManager, but the CuraEngineBackend plugin requires on it.
  118. # Because plugins are initialized before the ContainerRegistry, putting this signal in MachineManager
  119. # will make it initialized before ContainerRegistry does, and it won't find the active machine, thus
  120. # Cura will always show the Add Machine Dialog upon start.
  121. stacksValidationFinished = pyqtSignal() # Emitted whenever a validation is finished
  122. def __init__(self, **kwargs):
  123. # this list of dir names will be used by UM to detect an old cura directory
  124. for dir_name in ["extruders", "machine_instances", "materials", "plugins", "quality", "user", "variants"]:
  125. Resources.addExpectedDirNameInData(dir_name)
  126. Resources.addSearchPath(os.path.join(QtApplication.getInstallPrefix(), "share", "cura", "resources"))
  127. if not hasattr(sys, "frozen"):
  128. Resources.addSearchPath(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "resources"))
  129. self._use_gui = True
  130. self._open_file_queue = [] # Files to open when plug-ins are loaded.
  131. # Need to do this before ContainerRegistry tries to load the machines
  132. SettingDefinition.addSupportedProperty("settable_per_mesh", DefinitionPropertyType.Any, default = True, read_only = True)
  133. SettingDefinition.addSupportedProperty("settable_per_extruder", DefinitionPropertyType.Any, default = True, read_only = True)
  134. # this setting can be changed for each group in one-at-a-time mode
  135. SettingDefinition.addSupportedProperty("settable_per_meshgroup", DefinitionPropertyType.Any, default = True, read_only = True)
  136. SettingDefinition.addSupportedProperty("settable_globally", DefinitionPropertyType.Any, default = True, read_only = True)
  137. # From which stack the setting would inherit if not defined per object (handled in the engine)
  138. # AND for settings which are not settable_per_mesh:
  139. # which extruder is the only extruder this setting is obtained from
  140. SettingDefinition.addSupportedProperty("limit_to_extruder", DefinitionPropertyType.Function, default = "-1", depends_on = "value")
  141. # For settings which are not settable_per_mesh and not settable_per_extruder:
  142. # A function which determines the glabel/meshgroup value by looking at the values of the setting in all (used) extruders
  143. SettingDefinition.addSupportedProperty("resolve", DefinitionPropertyType.Function, default = None, depends_on = "value")
  144. SettingDefinition.addSettingType("extruder", None, str, Validator)
  145. SettingDefinition.addSettingType("optional_extruder", None, str, None)
  146. SettingDefinition.addSettingType("[int]", None, str, None)
  147. SettingFunction.registerOperator("extruderValues", ExtruderManager.getExtruderValues)
  148. SettingFunction.registerOperator("extruderValue", ExtruderManager.getExtruderValue)
  149. SettingFunction.registerOperator("resolveOrValue", ExtruderManager.getResolveOrValue)
  150. ## Add the 4 types of profiles to storage.
  151. Resources.addStorageType(self.ResourceTypes.QualityInstanceContainer, "quality")
  152. Resources.addStorageType(self.ResourceTypes.VariantInstanceContainer, "variants")
  153. Resources.addStorageType(self.ResourceTypes.MaterialInstanceContainer, "materials")
  154. Resources.addStorageType(self.ResourceTypes.UserInstanceContainer, "user")
  155. Resources.addStorageType(self.ResourceTypes.ExtruderStack, "extruders")
  156. Resources.addStorageType(self.ResourceTypes.MachineStack, "machine_instances")
  157. Resources.addStorageType(self.ResourceTypes.DefinitionChangesContainer, "definition_changes")
  158. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.QualityInstanceContainer, "quality")
  159. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.QualityInstanceContainer, "quality_changes")
  160. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.VariantInstanceContainer, "variant")
  161. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MaterialInstanceContainer, "material")
  162. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.UserInstanceContainer, "user")
  163. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.ExtruderStack, "extruder_train")
  164. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MachineStack, "machine")
  165. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.DefinitionChangesContainer, "definition_changes")
  166. ## Initialise the version upgrade manager with Cura's storage paths.
  167. # Needs to be here to prevent circular dependencies.
  168. import UM.VersionUpgradeManager
  169. UM.VersionUpgradeManager.VersionUpgradeManager.getInstance().setCurrentVersions(
  170. {
  171. ("quality_changes", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.QualityInstanceContainer, "application/x-uranium-instancecontainer"),
  172. ("machine_stack", ContainerStack.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.MachineStack, "application/x-cura-globalstack"),
  173. ("extruder_train", ContainerStack.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.ExtruderStack, "application/x-cura-extruderstack"),
  174. ("preferences", Preferences.Version * 1000000 + self.SettingVersion): (Resources.Preferences, "application/x-uranium-preferences"),
  175. ("user", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.UserInstanceContainer, "application/x-uranium-instancecontainer"),
  176. ("definition_changes", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.DefinitionChangesContainer, "application/x-uranium-instancecontainer"),
  177. }
  178. )
  179. self._currently_loading_files = []
  180. self._non_sliceable_extensions = []
  181. self._machine_action_manager = MachineActionManager.MachineActionManager()
  182. self._machine_manager = None # This is initialized on demand.
  183. self._extruder_manager = None
  184. self._material_manager = None
  185. self._object_manager = None
  186. self._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._additional_components = {} # Components to add to certain areas in the interface
  191. super().__init__(name = "cura",
  192. version = CuraVersion,
  193. buildtype = CuraBuildType,
  194. is_debug_mode = CuraDebugMode,
  195. tray_icon_name = "cura-icon-32.png",
  196. **kwargs)
  197. # FOR TESTING ONLY
  198. if kwargs["parsed_command_line"].get("trigger_early_crash", False):
  199. assert not "This crash is triggered by the trigger_early_crash command line argument."
  200. # new stuff
  201. self._variant_manager = VariantManager(ContainerRegistry.getInstance())
  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._new_quality_profile_model = None
  325. self._new_custom_quality_profile_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. onDiscardOrKeepProfileChangesClosed = pyqtSignal() # Used to notify other managers that the dialog was closed
  434. @pyqtSlot(str)
  435. def discardOrKeepProfileChangesClosed(self, option):
  436. if option == "discard":
  437. global_stack = self.getGlobalContainerStack()
  438. for extruder in self._extruder_manager.getMachineExtruders(global_stack.getId()):
  439. extruder.getTop().clear()
  440. global_stack.getTop().clear()
  441. # if the user decided to keep settings then the user settings should be re-calculated and validated for errors
  442. # before slicing. To ensure that slicer uses right settings values
  443. elif option == "keep":
  444. global_stack = self.getGlobalContainerStack()
  445. for extruder in self._extruder_manager.getMachineExtruders(global_stack.getId()):
  446. user_extruder_container = extruder.getTop()
  447. if user_extruder_container:
  448. user_extruder_container.update()
  449. user_global_container = global_stack.getTop()
  450. if user_global_container:
  451. user_global_container.update()
  452. # notify listeners that quality has changed (after user selected discard or keep)
  453. self.onDiscardOrKeepProfileChangesClosed.emit()
  454. self.getMachineManager().activeQualityChanged.emit()
  455. @pyqtSlot(int)
  456. def messageBoxClosed(self, button):
  457. if self._message_box_callback:
  458. self._message_box_callback(button, *self._message_box_callback_arguments)
  459. self._message_box_callback = None
  460. self._message_box_callback_arguments = []
  461. showPrintMonitor = pyqtSignal(bool, arguments = ["show"])
  462. ## Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
  463. #
  464. # Note that the AutoSave plugin also calls this method.
  465. def saveSettings(self):
  466. if not self.started: # Do not do saving during application start
  467. return
  468. ContainerRegistry.getInstance().saveDirtyContainers()
  469. def saveStack(self, stack):
  470. ContainerRegistry.getInstance().saveContainer(stack)
  471. @pyqtSlot(str, result = QUrl)
  472. def getDefaultPath(self, key):
  473. default_path = Preferences.getInstance().getValue("local_file/%s" % key)
  474. return QUrl.fromLocalFile(default_path)
  475. @pyqtSlot(str, str)
  476. def setDefaultPath(self, key, default_path):
  477. Preferences.getInstance().setValue("local_file/%s" % key, QUrl(default_path).toLocalFile())
  478. @classmethod
  479. def getStaticVersion(cls):
  480. return CuraVersion
  481. ## Handle loading of all plugin types (and the backend explicitly)
  482. # \sa PluginRegistery
  483. def _loadPlugins(self):
  484. self._plugin_registry.addType("profile_reader", self._addProfileReader)
  485. self._plugin_registry.addType("profile_writer", self._addProfileWriter)
  486. if Platform.isLinux():
  487. lib_suffixes = {"", "64", "32", "x32"} #A few common ones on different distributions.
  488. else:
  489. lib_suffixes = {""}
  490. for suffix in lib_suffixes:
  491. self._plugin_registry.addPluginLocation(os.path.join(QtApplication.getInstallPrefix(), "lib" + suffix, "cura"))
  492. if not hasattr(sys, "frozen"):
  493. self._plugin_registry.addPluginLocation(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "plugins"))
  494. self._plugin_registry.loadPlugin("ConsoleLogger")
  495. self._plugin_registry.loadPlugin("CuraEngineBackend")
  496. self._plugin_registry.loadPlugins()
  497. if self.getBackend() is None:
  498. raise RuntimeError("Could not load the backend plugin!")
  499. self._plugins_loaded = True
  500. @classmethod
  501. def addCommandLineOptions(self, parser, parsed_command_line = {}):
  502. super().addCommandLineOptions(parser, parsed_command_line = parsed_command_line)
  503. parser.add_argument("file", nargs="*", help="Files to load after starting the application.")
  504. parser.add_argument("--single-instance", action="store_true", default=False)
  505. # Set up a local socket server which listener which coordinates single instances Curas and accepts commands.
  506. def _setUpSingleInstanceServer(self):
  507. if self.getCommandLineOption("single_instance", False):
  508. self.__single_instance_server = QLocalServer()
  509. self.__single_instance_server.newConnection.connect(self._singleInstanceServerNewConnection)
  510. self.__single_instance_server.listen("ultimaker-cura")
  511. def _singleInstanceServerNewConnection(self):
  512. Logger.log("i", "New connection recevied on our single-instance server")
  513. remote_cura_connection = self.__single_instance_server.nextPendingConnection()
  514. if remote_cura_connection is not None:
  515. def readCommands():
  516. line = remote_cura_connection.readLine()
  517. while len(line) != 0: # There is also a .canReadLine()
  518. try:
  519. payload = json.loads(str(line, encoding="ASCII").strip())
  520. command = payload["command"]
  521. # Command: Remove all models from the build plate.
  522. if command == "clear-all":
  523. self.deleteAll()
  524. # Command: Load a model file
  525. elif command == "open":
  526. self._openFile(payload["filePath"])
  527. # WARNING ^ this method is async and we really should wait until
  528. # the file load is complete before processing more commands.
  529. # Command: Activate the window and bring it to the top.
  530. elif command == "focus":
  531. # Operating systems these days prevent windows from moving around by themselves.
  532. # 'alert' or flashing the icon in the taskbar is the best thing we do now.
  533. self.getMainWindow().alert(0)
  534. # Command: Close the socket connection. We're done.
  535. elif command == "close-connection":
  536. remote_cura_connection.close()
  537. else:
  538. Logger.log("w", "Received an unrecognized command " + str(command))
  539. except json.decoder.JSONDecodeError as ex:
  540. Logger.log("w", "Unable to parse JSON command in _singleInstanceServerNewConnection(): " + repr(ex))
  541. line = remote_cura_connection.readLine()
  542. remote_cura_connection.readyRead.connect(readCommands)
  543. ## Perform any checks before creating the main application.
  544. #
  545. # This should be called directly before creating an instance of CuraApplication.
  546. # \returns \type{bool} True if the whole Cura app should continue running.
  547. @classmethod
  548. def preStartUp(cls, parser = None, parsed_command_line = {}):
  549. # Peek the arguments and look for the 'single-instance' flag.
  550. if not parser:
  551. parser = argparse.ArgumentParser(prog = "cura", add_help = False) # pylint: disable=bad-whitespace
  552. CuraApplication.addCommandLineOptions(parser, parsed_command_line = parsed_command_line)
  553. # Important: It is important to keep this line here!
  554. # In Uranium we allow to pass unknown arguments to the final executable or script.
  555. parsed_command_line.update(vars(parser.parse_known_args()[0]))
  556. if parsed_command_line["single_instance"]:
  557. Logger.log("i", "Checking for the presence of an ready running Cura instance.")
  558. single_instance_socket = QLocalSocket()
  559. Logger.log("d", "preStartUp(): full server name: " + single_instance_socket.fullServerName())
  560. single_instance_socket.connectToServer("ultimaker-cura")
  561. single_instance_socket.waitForConnected()
  562. if single_instance_socket.state() == QLocalSocket.ConnectedState:
  563. Logger.log("i", "Connection has been made to the single-instance Cura socket.")
  564. # Protocol is one line of JSON terminated with a carriage return.
  565. # "command" field is required and holds the name of the command to execute.
  566. # Other fields depend on the command.
  567. payload = {"command": "clear-all"}
  568. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  569. payload = {"command": "focus"}
  570. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  571. if len(parsed_command_line["file"]) != 0:
  572. for filename in parsed_command_line["file"]:
  573. payload = {"command": "open", "filePath": filename}
  574. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  575. payload = {"command": "close-connection"}
  576. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
  577. single_instance_socket.flush()
  578. single_instance_socket.waitForDisconnected()
  579. return False
  580. return True
  581. def getVariantManager(self):
  582. return self._variant_manager
  583. def preRun(self):
  584. # Last check for unknown commandline arguments
  585. parser = self.getCommandlineParser()
  586. parser.add_argument("--help", "-h",
  587. action='store_true',
  588. default = False,
  589. help = "Show this help message and exit."
  590. )
  591. parsed_args = vars(parser.parse_args()) # This won't allow unknown arguments
  592. if parsed_args["help"]:
  593. parser.print_help()
  594. sys.exit(0)
  595. def run(self):
  596. self.preRun()
  597. container_registry = ContainerRegistry.getInstance()
  598. self._variant_manager.initialize()
  599. from cura.Machines.MaterialManager import MaterialManager
  600. self._material_manager = MaterialManager(container_registry)
  601. self._material_manager.initialize()
  602. from cura.Machines.QualityManager import QualityManager
  603. self._quality_manager = QualityManager(container_registry)
  604. self._quality_manager.initialize()
  605. # Check if we should run as single instance or not
  606. self._setUpSingleInstanceServer()
  607. # Setup scene and build volume
  608. root = self.getController().getScene().getRoot()
  609. self._volume = BuildVolume.BuildVolume(self.getController().getScene().getRoot())
  610. Arrange.build_volume = self._volume
  611. # initialize info objects
  612. self._print_information = PrintInformation.PrintInformation()
  613. self._cura_actions = CuraActions.CuraActions(self)
  614. # Detect in which mode to run and execute that mode
  615. if self.getCommandLineOption("headless", False):
  616. self.runWithoutGUI()
  617. else:
  618. self.runWithGUI()
  619. # Pre-load files if requested
  620. for file_name in self.getCommandLineOption("file", []):
  621. self._openFile(file_name)
  622. for file_name in self._open_file_queue: # Open all the files that were queued up while plug-ins were loading.
  623. self._openFile(file_name)
  624. self.started = True
  625. self.exec_()
  626. ## Run Cura without GUI elements and interaction (server mode).
  627. def runWithoutGUI(self):
  628. self._use_gui = False
  629. self.closeSplash()
  630. ## Run Cura with GUI (desktop mode).
  631. def runWithGUI(self):
  632. self._use_gui = True
  633. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Setting up scene..."))
  634. controller = self.getController()
  635. # Initialize UI state
  636. controller.setActiveStage("PrepareStage")
  637. controller.setActiveView("SolidView")
  638. controller.setCameraTool("CameraTool")
  639. controller.setSelectionTool("SelectionTool")
  640. t = controller.getTool("TranslateTool")
  641. if t:
  642. t.setEnabledAxis([ToolHandle.XAxis, ToolHandle.YAxis, ToolHandle.ZAxis])
  643. Selection.selectionChanged.connect(self.onSelectionChanged)
  644. # Set default background color for scene
  645. self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
  646. # Initialize platform physics
  647. self._physics = PlatformPhysics.PlatformPhysics(controller, self._volume)
  648. # Initialize camera
  649. root = controller.getScene().getRoot()
  650. camera = Camera("3d", root)
  651. camera.setPosition(Vector(-80, 250, 700))
  652. camera.setPerspective(True)
  653. camera.lookAt(Vector(0, 0, 0))
  654. controller.getScene().setActiveCamera("3d")
  655. # Initialize camera tool
  656. camera_tool = controller.getTool("CameraTool")
  657. camera_tool.setOrigin(Vector(0, 100, 0))
  658. camera_tool.setZoomRange(0.1, 200000)
  659. # Initialize camera animations
  660. self._camera_animation = CameraAnimation.CameraAnimation()
  661. self._camera_animation.setCameraTool(self.getController().getTool("CameraTool"))
  662. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading interface..."))
  663. # Initialize QML engine
  664. self.setMainQml(Resources.getPath(self.ResourceTypes.QmlFiles, "Cura.qml"))
  665. self._qml_import_paths.append(Resources.getPath(self.ResourceTypes.QmlFiles))
  666. self.initializeEngine()
  667. # Make sure the correct stage is activated after QML is loaded
  668. controller.setActiveStage("PrepareStage")
  669. # Hide the splash screen
  670. self.closeSplash()
  671. def hasGui(self):
  672. return self._use_gui
  673. def getMachineManager(self, *args) -> MachineManager:
  674. if self._machine_manager is None:
  675. self._machine_manager = MachineManager.createMachineManager()
  676. return self._machine_manager
  677. def getExtruderManager(self, *args):
  678. if self._extruder_manager is None:
  679. self._extruder_manager = ExtruderManager.createExtruderManager()
  680. return self._extruder_manager
  681. def getMaterialManager(self, *args):
  682. if self._material_manager is None:
  683. self._material_manager = MaterialManager.createMaterialManager()
  684. return self._material_manager
  685. def getObjectsModel(self, *args):
  686. if self._object_manager is None:
  687. self._object_manager = ObjectsModel.createObjectsModel()
  688. return self._object_manager
  689. def getBuildPlateModel(self, *args):
  690. if self._build_plate_model is None:
  691. self._build_plate_model = BuildPlateModel.createBuildPlateModel()
  692. return self._build_plate_model
  693. def getCuraSceneController(self, *args):
  694. if self._cura_scene_controller is None:
  695. self._cura_scene_controller = CuraSceneController.createCuraSceneController()
  696. return self._cura_scene_controller
  697. def getSettingInheritanceManager(self, *args):
  698. if self._setting_inheritance_manager is None:
  699. self._setting_inheritance_manager = SettingInheritanceManager.createSettingInheritanceManager()
  700. return self._setting_inheritance_manager
  701. ## Get the machine action manager
  702. # We ignore any *args given to this, as we also register the machine manager as qml singleton.
  703. # It wants to give this function an engine and script engine, but we don't care about that.
  704. def getMachineActionManager(self, *args):
  705. return self._machine_action_manager
  706. def getSimpleModeSettingsManager(self, *args):
  707. if self._simple_mode_settings_manager is None:
  708. self._simple_mode_settings_manager = SimpleModeSettingsManager()
  709. return self._simple_mode_settings_manager
  710. ## Handle Qt events
  711. def event(self, event):
  712. if event.type() == QEvent.FileOpen:
  713. if self._plugins_loaded:
  714. self._openFile(event.file())
  715. else:
  716. self._open_file_queue.append(event.file())
  717. return super().event(event)
  718. ## Get print information (duration / material used)
  719. def getPrintInformation(self):
  720. return self._print_information
  721. def getNewQualityProfileModel(self, *args, **kwargs):
  722. if self._new_quality_profile_model is None:
  723. self._new_quality_profile_model = NewQualityProfilesModel(self)
  724. return self._new_quality_profile_model
  725. def getNewCustomQualityProfilesModel(self, *args, **kwargs):
  726. if self._new_custom_quality_profile_model is None:
  727. self._new_custom_quality_profile_model = NewCustomQualityProfilesModel(self)
  728. return self._new_custom_quality_profile_model
  729. ## Registers objects for the QML engine to use.
  730. #
  731. # \param engine The QML engine.
  732. def registerObjects(self, engine):
  733. super().registerObjects(engine)
  734. # global contexts
  735. engine.rootContext().setContextProperty("Printer", self)
  736. engine.rootContext().setContextProperty("CuraApplication", self)
  737. engine.rootContext().setContextProperty("PrintInformation", self._print_information)
  738. engine.rootContext().setContextProperty("CuraActions", self._cura_actions)
  739. qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")
  740. qmlRegisterSingletonType(CuraSceneController, "Cura", 1, 2, "SceneController", self.getCuraSceneController)
  741. qmlRegisterSingletonType(ExtruderManager, "Cura", 1, 0, "ExtruderManager", self.getExtruderManager)
  742. qmlRegisterSingletonType(MachineManager, "Cura", 1, 0, "MachineManager", self.getMachineManager)
  743. qmlRegisterSingletonType(MaterialManager, "Cura", 1, 0, "MaterialManager", self.getMaterialManager)
  744. qmlRegisterSingletonType(SettingInheritanceManager, "Cura", 1, 0, "SettingInheritanceManager", self.getSettingInheritanceManager)
  745. qmlRegisterSingletonType(SimpleModeSettingsManager, "Cura", 1, 2, "SimpleModeSettingsManager", self.getSimpleModeSettingsManager)
  746. qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, "MachineActionManager", self.getMachineActionManager)
  747. qmlRegisterSingletonType(ObjectsModel, "Cura", 1, 2, "ObjectsModel", self.getObjectsModel)
  748. qmlRegisterSingletonType(BuildPlateModel, "Cura", 1, 2, "BuildPlateModel", self.getBuildPlateModel)
  749. qmlRegisterType(InstanceContainer, "Cura", 1, 0, "InstanceContainer")
  750. qmlRegisterType(ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")
  751. qmlRegisterType(ContainerSettingsModel, "Cura", 1, 0, "ContainerSettingsModel")
  752. qmlRegisterSingletonType(ProfilesModel, "Cura", 1, 0, "ProfilesModel", ProfilesModel.createProfilesModel)
  753. qmlRegisterType(GenericMaterialsModel, "Cura", 1, 0, "GenericMaterialsModel")
  754. qmlRegisterType(BrandMaterialsModel, "Cura", 1, 0, "BrandMaterialsModel")
  755. qmlRegisterSingletonType(NewQualityProfilesModel, "Cura", 1, 0, "NewQualityProfilesModel", self.getNewQualityProfileModel)
  756. qmlRegisterSingletonType(NewCustomQualityProfilesModel, "Cura", 1, 0, "NewCustomQualityProfilesModel", self.getNewCustomQualityProfilesModel)
  757. qmlRegisterType(NozzleModel, "Cura", 1, 0, "NozzleModel")
  758. qmlRegisterType(MaterialsModel, "Cura", 1, 0, "MaterialsModel")
  759. qmlRegisterType(QualityAndUserProfilesModel, "Cura", 1, 0, "QualityAndUserProfilesModel")
  760. qmlRegisterType(UserProfilesModel, "Cura", 1, 0, "UserProfilesModel")
  761. qmlRegisterType(MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
  762. qmlRegisterType(QualitySettingsModel, "Cura", 1, 0, "QualitySettingsModel")
  763. qmlRegisterType(MachineNameValidator, "Cura", 1, 0, "MachineNameValidator")
  764. qmlRegisterType(UserChangesModel, "Cura", 1, 1, "UserChangesModel")
  765. qmlRegisterSingletonType(ContainerManager, "Cura", 1, 0, "ContainerManager", ContainerManager.createContainerManager)
  766. # As of Qt5.7, it is necessary to get rid of any ".." in the path for the singleton to work.
  767. actions_url = QUrl.fromLocalFile(os.path.abspath(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")))
  768. qmlRegisterSingletonType(actions_url, "Cura", 1, 0, "Actions")
  769. for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
  770. type_name = os.path.splitext(os.path.basename(path))[0]
  771. if type_name in ("Cura", "Actions"):
  772. continue
  773. # Ignore anything that is not a QML file.
  774. if not path.endswith(".qml"):
  775. continue
  776. qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
  777. def onSelectionChanged(self):
  778. if Selection.hasSelection():
  779. if self.getController().getActiveTool():
  780. # If the tool has been disabled by the new selection
  781. if not self.getController().getActiveTool().getEnabled():
  782. # Default
  783. self.getController().setActiveTool("TranslateTool")
  784. else:
  785. if self._previous_active_tool:
  786. self.getController().setActiveTool(self._previous_active_tool)
  787. if not self.getController().getActiveTool().getEnabled():
  788. self.getController().setActiveTool("TranslateTool")
  789. self._previous_active_tool = None
  790. else:
  791. # Default
  792. self.getController().setActiveTool("TranslateTool")
  793. if Preferences.getInstance().getValue("view/center_on_select"):
  794. self._center_after_select = True
  795. else:
  796. if self.getController().getActiveTool():
  797. self._previous_active_tool = self.getController().getActiveTool().getPluginId()
  798. self.getController().setActiveTool(None)
  799. def _onToolOperationStopped(self, event):
  800. if self._center_after_select and Selection.getSelectedObject(0) is not None:
  801. self._center_after_select = False
  802. self._camera_animation.setStart(self.getController().getTool("CameraTool").getOrigin())
  803. self._camera_animation.setTarget(Selection.getSelectedObject(0).getWorldPosition())
  804. self._camera_animation.start()
  805. def _onGlobalContainerChanged(self):
  806. if self._global_container_stack is not None:
  807. machine_file_formats = [file_type.strip() for file_type in self._global_container_stack.getMetaDataEntry("file_formats").split(";")]
  808. new_preferred_mimetype = ""
  809. if machine_file_formats:
  810. new_preferred_mimetype = machine_file_formats[0]
  811. if new_preferred_mimetype != self._preferred_mimetype:
  812. self._preferred_mimetype = new_preferred_mimetype
  813. self.preferredOutputMimetypeChanged.emit()
  814. requestAddPrinter = pyqtSignal()
  815. activityChanged = pyqtSignal()
  816. sceneBoundingBoxChanged = pyqtSignal()
  817. preferredOutputMimetypeChanged = pyqtSignal()
  818. @pyqtProperty(bool, notify = activityChanged)
  819. def platformActivity(self):
  820. return self._platform_activity
  821. @pyqtProperty(str, notify=preferredOutputMimetypeChanged)
  822. def preferredOutputMimetype(self):
  823. return self._preferred_mimetype
  824. @pyqtProperty(str, notify = sceneBoundingBoxChanged)
  825. def getSceneBoundingBoxString(self):
  826. 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()}
  827. ## Update scene bounding box for current build plate
  828. def updatePlatformActivity(self, node = None):
  829. count = 0
  830. scene_bounding_box = None
  831. is_block_slicing_node = False
  832. active_build_plate = self.getBuildPlateModel().activeBuildPlate
  833. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  834. if (
  835. not issubclass(type(node), CuraSceneNode) or
  836. (not node.getMeshData() and not node.callDecoration("getLayerData")) or
  837. (node.callDecoration("getBuildPlateNumber") != active_build_plate)):
  838. continue
  839. if node.callDecoration("isBlockSlicing"):
  840. is_block_slicing_node = True
  841. count += 1
  842. if not scene_bounding_box:
  843. scene_bounding_box = node.getBoundingBox()
  844. else:
  845. other_bb = node.getBoundingBox()
  846. if other_bb is not None:
  847. scene_bounding_box = scene_bounding_box + node.getBoundingBox()
  848. print_information = self.getPrintInformation()
  849. if print_information:
  850. print_information.setPreSliced(is_block_slicing_node)
  851. if not scene_bounding_box:
  852. scene_bounding_box = AxisAlignedBox.Null
  853. if repr(self._scene_bounding_box) != repr(scene_bounding_box):
  854. self._scene_bounding_box = scene_bounding_box
  855. self.sceneBoundingBoxChanged.emit()
  856. self._platform_activity = True if count > 0 else False
  857. self.activityChanged.emit()
  858. # Remove all selected objects from the scene.
  859. @pyqtSlot()
  860. @deprecated("Moved to CuraActions", "2.6")
  861. def deleteSelection(self):
  862. if not self.getController().getToolsEnabled():
  863. return
  864. removed_group_nodes = []
  865. op = GroupedOperation()
  866. nodes = Selection.getAllSelectedObjects()
  867. for node in nodes:
  868. op.addOperation(RemoveSceneNodeOperation(node))
  869. group_node = node.getParent()
  870. if group_node and group_node.callDecoration("isGroup") and group_node not in removed_group_nodes:
  871. remaining_nodes_in_group = list(set(group_node.getChildren()) - set(nodes))
  872. if len(remaining_nodes_in_group) == 1:
  873. removed_group_nodes.append(group_node)
  874. op.addOperation(SetParentOperation(remaining_nodes_in_group[0], group_node.getParent()))
  875. op.addOperation(RemoveSceneNodeOperation(group_node))
  876. op.push()
  877. ## Remove an object from the scene.
  878. # Note that this only removes an object if it is selected.
  879. @pyqtSlot("quint64")
  880. @deprecated("Use deleteSelection instead", "2.6")
  881. def deleteObject(self, object_id):
  882. if not self.getController().getToolsEnabled():
  883. return
  884. node = self.getController().getScene().findObject(object_id)
  885. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  886. node = Selection.getSelectedObject(0)
  887. if node:
  888. op = GroupedOperation()
  889. op.addOperation(RemoveSceneNodeOperation(node))
  890. group_node = node.getParent()
  891. if group_node:
  892. # Note that at this point the node has not yet been deleted
  893. if len(group_node.getChildren()) <= 2 and group_node.callDecoration("isGroup"):
  894. op.addOperation(SetParentOperation(group_node.getChildren()[0], group_node.getParent()))
  895. op.addOperation(RemoveSceneNodeOperation(group_node))
  896. op.push()
  897. ## Create a number of copies of existing object.
  898. # \param object_id
  899. # \param count number of copies
  900. # \param min_offset minimum offset to other objects.
  901. @pyqtSlot("quint64", int)
  902. @deprecated("Use CuraActions::multiplySelection", "2.6")
  903. def multiplyObject(self, object_id, count, min_offset = 8):
  904. node = self.getController().getScene().findObject(object_id)
  905. if not node:
  906. node = Selection.getSelectedObject(0)
  907. while node.getParent() and node.getParent().callDecoration("isGroup"):
  908. node = node.getParent()
  909. job = MultiplyObjectsJob([node], count, min_offset)
  910. job.start()
  911. return
  912. ## Center object on platform.
  913. @pyqtSlot("quint64")
  914. @deprecated("Use CuraActions::centerSelection", "2.6")
  915. def centerObject(self, object_id):
  916. node = self.getController().getScene().findObject(object_id)
  917. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  918. node = Selection.getSelectedObject(0)
  919. if not node:
  920. return
  921. if node.getParent() and node.getParent().callDecoration("isGroup"):
  922. node = node.getParent()
  923. if node:
  924. op = SetTransformOperation(node, Vector())
  925. op.push()
  926. ## Select all nodes containing mesh data in the scene.
  927. @pyqtSlot()
  928. def selectAll(self):
  929. if not self.getController().getToolsEnabled():
  930. return
  931. Selection.clear()
  932. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  933. if not isinstance(node, SceneNode):
  934. continue
  935. if not node.getMeshData() and not node.callDecoration("isGroup"):
  936. continue # Node that doesnt have a mesh and is not a group.
  937. if node.getParent() and node.getParent().callDecoration("isGroup"):
  938. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  939. if not node.isSelectable():
  940. continue # i.e. node with layer data
  941. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  942. continue # i.e. node with layer data
  943. Selection.add(node)
  944. ## Delete all nodes containing mesh data in the scene.
  945. # \param only_selectable. Set this to False to delete objects from all build plates
  946. @pyqtSlot()
  947. def deleteAll(self, only_selectable = True):
  948. Logger.log("i", "Clearing scene")
  949. if not self.getController().getToolsEnabled():
  950. return
  951. nodes = []
  952. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  953. if not isinstance(node, SceneNode):
  954. continue
  955. if (not node.getMeshData() and not node.callDecoration("getLayerData")) and not node.callDecoration("isGroup"):
  956. continue # Node that doesnt have a mesh and is not a group.
  957. if only_selectable and not node.isSelectable():
  958. continue
  959. if not node.callDecoration("isSliceable") and not node.callDecoration("getLayerData") and not node.callDecoration("isGroup"):
  960. continue # Only remove nodes that are selectable.
  961. if node.getParent() and node.getParent().callDecoration("isGroup"):
  962. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  963. nodes.append(node)
  964. if nodes:
  965. op = GroupedOperation()
  966. for node in nodes:
  967. op.addOperation(RemoveSceneNodeOperation(node))
  968. # Reset the print information
  969. self.getController().getScene().sceneChanged.emit(node)
  970. op.push()
  971. Selection.clear()
  972. ## Reset all translation on nodes with mesh data.
  973. @pyqtSlot()
  974. def resetAllTranslation(self):
  975. Logger.log("i", "Resetting all scene translations")
  976. nodes = []
  977. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  978. if not isinstance(node, SceneNode):
  979. continue
  980. if not node.getMeshData() and not node.callDecoration("isGroup"):
  981. continue # Node that doesnt have a mesh and is not a group.
  982. if node.getParent() and node.getParent().callDecoration("isGroup"):
  983. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  984. if not node.isSelectable():
  985. continue # i.e. node with layer data
  986. nodes.append(node)
  987. if nodes:
  988. op = GroupedOperation()
  989. for node in nodes:
  990. # Ensure that the object is above the build platform
  991. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  992. if node.getBoundingBox():
  993. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  994. else:
  995. center_y = 0
  996. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0)))
  997. op.push()
  998. ## Reset all transformations on nodes with mesh data.
  999. @pyqtSlot()
  1000. def resetAll(self):
  1001. Logger.log("i", "Resetting all scene transformations")
  1002. nodes = []
  1003. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1004. if not isinstance(node, SceneNode):
  1005. continue
  1006. if not node.getMeshData() and not node.callDecoration("isGroup"):
  1007. continue # Node that doesnt have a mesh and is not a group.
  1008. if node.getParent() and node.getParent().callDecoration("isGroup"):
  1009. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  1010. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1011. continue # i.e. node with layer data
  1012. nodes.append(node)
  1013. if nodes:
  1014. op = GroupedOperation()
  1015. for node in nodes:
  1016. # Ensure that the object is above the build platform
  1017. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  1018. if node.getBoundingBox():
  1019. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  1020. else:
  1021. center_y = 0
  1022. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0), Quaternion(), Vector(1, 1, 1)))
  1023. op.push()
  1024. ## Arrange all objects.
  1025. @pyqtSlot()
  1026. def arrangeObjectsToAllBuildPlates(self):
  1027. nodes = []
  1028. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1029. if not isinstance(node, SceneNode):
  1030. continue
  1031. if not node.getMeshData() and not node.callDecoration("isGroup"):
  1032. continue # Node that doesnt have a mesh and is not a group.
  1033. if node.getParent() and node.getParent().callDecoration("isGroup"):
  1034. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  1035. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1036. continue # i.e. node with layer data
  1037. # Skip nodes that are too big
  1038. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1039. nodes.append(node)
  1040. job = ArrangeObjectsAllBuildPlatesJob(nodes)
  1041. job.start()
  1042. self.getCuraSceneController().setActiveBuildPlate(0) # Select first build plate
  1043. # Single build plate
  1044. @pyqtSlot()
  1045. def arrangeAll(self):
  1046. nodes = []
  1047. active_build_plate = self.getBuildPlateModel().activeBuildPlate
  1048. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1049. if not isinstance(node, SceneNode):
  1050. continue
  1051. if not node.getMeshData() and not node.callDecoration("isGroup"):
  1052. continue # Node that doesnt have a mesh and is not a group.
  1053. if node.getParent() and node.getParent().callDecoration("isGroup"):
  1054. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  1055. if not node.isSelectable():
  1056. continue # i.e. node with layer data
  1057. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1058. continue # i.e. node with layer data
  1059. if node.callDecoration("getBuildPlateNumber") == active_build_plate:
  1060. # Skip nodes that are too big
  1061. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1062. nodes.append(node)
  1063. self.arrange(nodes, fixed_nodes = [])
  1064. ## Arrange Selection
  1065. @pyqtSlot()
  1066. def arrangeSelection(self):
  1067. nodes = Selection.getAllSelectedObjects()
  1068. # What nodes are on the build plate and are not being moved
  1069. fixed_nodes = []
  1070. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1071. if not isinstance(node, SceneNode):
  1072. continue
  1073. if not node.getMeshData() and not node.callDecoration("isGroup"):
  1074. continue # Node that doesnt have a mesh and is not a group.
  1075. if node.getParent() and node.getParent().callDecoration("isGroup"):
  1076. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  1077. if not node.isSelectable():
  1078. continue # i.e. node with layer data
  1079. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1080. continue # i.e. node with layer data
  1081. if node in nodes: # exclude selected node from fixed_nodes
  1082. continue
  1083. fixed_nodes.append(node)
  1084. self.arrange(nodes, fixed_nodes)
  1085. ## Arrange a set of nodes given a set of fixed nodes
  1086. # \param nodes nodes that we have to place
  1087. # \param fixed_nodes nodes that are placed in the arranger before finding spots for nodes
  1088. def arrange(self, nodes, fixed_nodes):
  1089. job = ArrangeObjectsJob(nodes, fixed_nodes)
  1090. job.start()
  1091. ## Reload all mesh data on the screen from file.
  1092. @pyqtSlot()
  1093. def reloadAll(self):
  1094. Logger.log("i", "Reloading all loaded mesh data.")
  1095. nodes = []
  1096. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1097. if not isinstance(node, CuraSceneNode) or not node.getMeshData():
  1098. continue
  1099. nodes.append(node)
  1100. if not nodes:
  1101. return
  1102. for node in nodes:
  1103. file_name = node.getMeshData().getFileName()
  1104. if file_name:
  1105. job = ReadMeshJob(file_name)
  1106. job._node = node
  1107. job.finished.connect(self._reloadMeshFinished)
  1108. job.start()
  1109. else:
  1110. Logger.log("w", "Unable to reload data because we don't have a filename.")
  1111. ## Get logging data of the backend engine
  1112. # \returns \type{string} Logging data
  1113. @pyqtSlot(result = str)
  1114. def getEngineLog(self):
  1115. log = ""
  1116. for entry in self.getBackend().getLog():
  1117. log += entry.decode()
  1118. return log
  1119. @pyqtSlot("QStringList")
  1120. def setExpandedCategories(self, categories):
  1121. categories = list(set(categories))
  1122. categories.sort()
  1123. joined = ";".join(categories)
  1124. if joined != Preferences.getInstance().getValue("cura/categories_expanded"):
  1125. Preferences.getInstance().setValue("cura/categories_expanded", joined)
  1126. self.expandedCategoriesChanged.emit()
  1127. expandedCategoriesChanged = pyqtSignal()
  1128. @pyqtProperty("QStringList", notify = expandedCategoriesChanged)
  1129. def expandedCategories(self):
  1130. return Preferences.getInstance().getValue("cura/categories_expanded").split(";")
  1131. @pyqtSlot()
  1132. def mergeSelected(self):
  1133. self.groupSelected()
  1134. try:
  1135. group_node = Selection.getAllSelectedObjects()[0]
  1136. except Exception as e:
  1137. Logger.log("d", "mergeSelected: Exception:", e)
  1138. return
  1139. meshes = [node.getMeshData() for node in group_node.getAllChildren() if node.getMeshData()]
  1140. # Compute the center of the objects
  1141. object_centers = []
  1142. # Forget about the translation that the original objects have
  1143. zero_translation = Matrix(data=numpy.zeros(3))
  1144. for mesh, node in zip(meshes, group_node.getChildren()):
  1145. transformation = node.getLocalTransformation()
  1146. transformation.setTranslation(zero_translation)
  1147. transformed_mesh = mesh.getTransformed(transformation)
  1148. center = transformed_mesh.getCenterPosition()
  1149. if center is not None:
  1150. object_centers.append(center)
  1151. if object_centers and len(object_centers) > 0:
  1152. middle_x = sum([v.x for v in object_centers]) / len(object_centers)
  1153. middle_y = sum([v.y for v in object_centers]) / len(object_centers)
  1154. middle_z = sum([v.z for v in object_centers]) / len(object_centers)
  1155. offset = Vector(middle_x, middle_y, middle_z)
  1156. else:
  1157. offset = Vector(0, 0, 0)
  1158. # Move each node to the same position.
  1159. for mesh, node in zip(meshes, group_node.getChildren()):
  1160. transformation = node.getLocalTransformation()
  1161. transformation.setTranslation(zero_translation)
  1162. transformed_mesh = mesh.getTransformed(transformation)
  1163. # Align the object around its zero position
  1164. # and also apply the offset to center it inside the group.
  1165. node.setPosition(-transformed_mesh.getZeroPosition() - offset)
  1166. # Use the previously found center of the group bounding box as the new location of the group
  1167. group_node.setPosition(group_node.getBoundingBox().center)
  1168. @pyqtSlot()
  1169. def groupSelected(self):
  1170. # Create a group-node
  1171. group_node = CuraSceneNode()
  1172. group_decorator = GroupDecorator()
  1173. group_node.addDecorator(group_decorator)
  1174. group_node.addDecorator(ConvexHullDecorator())
  1175. group_node.addDecorator(BuildPlateDecorator(self.getBuildPlateModel().activeBuildPlate))
  1176. group_node.setParent(self.getController().getScene().getRoot())
  1177. group_node.setSelectable(True)
  1178. center = Selection.getSelectionCenter()
  1179. group_node.setPosition(center)
  1180. group_node.setCenterPosition(center)
  1181. # Move selected nodes into the group-node
  1182. Selection.applyOperation(SetParentOperation, group_node)
  1183. # Deselect individual nodes and select the group-node instead
  1184. for node in group_node.getChildren():
  1185. Selection.remove(node)
  1186. Selection.add(group_node)
  1187. @pyqtSlot()
  1188. def ungroupSelected(self):
  1189. selected_objects = Selection.getAllSelectedObjects().copy()
  1190. for node in selected_objects:
  1191. if node.callDecoration("isGroup"):
  1192. op = GroupedOperation()
  1193. group_parent = node.getParent()
  1194. children = node.getChildren().copy()
  1195. for child in children:
  1196. # Set the parent of the children to the parent of the group-node
  1197. op.addOperation(SetParentOperation(child, group_parent))
  1198. # Add all individual nodes to the selection
  1199. Selection.add(child)
  1200. op.push()
  1201. # Note: The group removes itself from the scene once all its children have left it,
  1202. # see GroupDecorator._onChildrenChanged
  1203. def _createSplashScreen(self):
  1204. run_headless = self.getCommandLineOption("headless", False)
  1205. if run_headless:
  1206. return None
  1207. return CuraSplashScreen.CuraSplashScreen()
  1208. def _onActiveMachineChanged(self):
  1209. pass
  1210. fileLoaded = pyqtSignal(str)
  1211. fileCompleted = pyqtSignal(str)
  1212. def _reloadMeshFinished(self, job):
  1213. # TODO; This needs to be fixed properly. We now make the assumption that we only load a single mesh!
  1214. mesh_data = job.getResult()[0].getMeshData()
  1215. if mesh_data:
  1216. job._node.setMeshData(mesh_data)
  1217. else:
  1218. Logger.log("w", "Could not find a mesh in reloaded node.")
  1219. def _openFile(self, filename):
  1220. self.readLocalFile(QUrl.fromLocalFile(filename))
  1221. def _addProfileReader(self, profile_reader):
  1222. # TODO: Add the profile reader to the list of plug-ins that can be used when importing profiles.
  1223. pass
  1224. def _addProfileWriter(self, profile_writer):
  1225. pass
  1226. @pyqtSlot("QSize")
  1227. def setMinimumWindowSize(self, size):
  1228. self.getMainWindow().setMinimumSize(size)
  1229. def getBuildVolume(self):
  1230. return self._volume
  1231. additionalComponentsChanged = pyqtSignal(str, arguments = ["areaId"])
  1232. @pyqtProperty("QVariantMap", notify = additionalComponentsChanged)
  1233. def additionalComponents(self):
  1234. return self._additional_components
  1235. ## Add a component to a list of components to be reparented to another area in the GUI.
  1236. # The actual reparenting is done by the area itself.
  1237. # \param area_id \type{str} Identifying name of the area to which the component should be reparented
  1238. # \param component \type{QQuickComponent} The component that should be reparented
  1239. @pyqtSlot(str, "QVariant")
  1240. def addAdditionalComponent(self, area_id, component):
  1241. if area_id not in self._additional_components:
  1242. self._additional_components[area_id] = []
  1243. self._additional_components[area_id].append(component)
  1244. self.additionalComponentsChanged.emit(area_id)
  1245. @pyqtSlot(str)
  1246. def log(self, msg):
  1247. Logger.log("d", msg)
  1248. @pyqtSlot(QUrl)
  1249. def readLocalFile(self, file):
  1250. if not file.isValid():
  1251. return
  1252. scene = self.getController().getScene()
  1253. for node in DepthFirstIterator(scene.getRoot()):
  1254. if node.callDecoration("isBlockSlicing"):
  1255. self.deleteAll()
  1256. break
  1257. f = file.toLocalFile()
  1258. extension = os.path.splitext(f)[1]
  1259. filename = os.path.basename(f)
  1260. if len(self._currently_loading_files) > 0:
  1261. # If a non-slicable file is already being loaded, we prevent loading of any further non-slicable files
  1262. if extension.lower() in self._non_sliceable_extensions:
  1263. message = Message(
  1264. self._i18n_catalog.i18nc("@info:status",
  1265. "Only one G-code file can be loaded at a time. Skipped importing {0}",
  1266. filename), title = self._i18n_catalog.i18nc("@info:title", "Warning"))
  1267. message.show()
  1268. return
  1269. # If file being loaded is non-slicable file, then prevent loading of any other files
  1270. extension = os.path.splitext(self._currently_loading_files[0])[1]
  1271. if extension.lower() in self._non_sliceable_extensions:
  1272. message = Message(
  1273. self._i18n_catalog.i18nc("@info:status",
  1274. "Can't open any other file if G-code is loading. Skipped importing {0}",
  1275. filename), title = self._i18n_catalog.i18nc("@info:title", "Error"))
  1276. message.show()
  1277. return
  1278. self._currently_loading_files.append(f)
  1279. if extension in self._non_sliceable_extensions:
  1280. self.deleteAll(only_selectable = False)
  1281. job = ReadMeshJob(f)
  1282. job.finished.connect(self._readMeshFinished)
  1283. job.start()
  1284. def _readMeshFinished(self, job):
  1285. nodes = job.getResult()
  1286. filename = job.getFileName()
  1287. self._currently_loading_files.remove(filename)
  1288. self.fileLoaded.emit(filename)
  1289. arrange_objects_on_load = (
  1290. not Preferences.getInstance().getValue("cura/use_multi_build_plate") or
  1291. not Preferences.getInstance().getValue("cura/not_arrange_objects_on_load"))
  1292. target_build_plate = self.getBuildPlateModel().activeBuildPlate if arrange_objects_on_load else -1
  1293. root = self.getController().getScene().getRoot()
  1294. fixed_nodes = []
  1295. for node_ in DepthFirstIterator(root):
  1296. if node_.callDecoration("isSliceable") and node_.callDecoration("getBuildPlateNumber") == target_build_plate:
  1297. fixed_nodes.append(node_)
  1298. arranger = Arrange.create(fixed_nodes = fixed_nodes)
  1299. min_offset = 8
  1300. for original_node in nodes:
  1301. # Create a CuraSceneNode just if the original node is not that type
  1302. node = original_node if isinstance(original_node, CuraSceneNode) else CuraSceneNode()
  1303. node.setMeshData(original_node.getMeshData())
  1304. node.setSelectable(True)
  1305. node.setName(os.path.basename(filename))
  1306. self.getBuildVolume().checkBoundsAndUpdate(node)
  1307. extension = os.path.splitext(filename)[1]
  1308. if extension.lower() in self._non_sliceable_extensions:
  1309. self.callLater(lambda: self.getController().setActiveView("SimulationView"))
  1310. block_slicing_decorator = BlockSlicingDecorator()
  1311. node.addDecorator(block_slicing_decorator)
  1312. else:
  1313. sliceable_decorator = SliceableObjectDecorator()
  1314. node.addDecorator(sliceable_decorator)
  1315. scene = self.getController().getScene()
  1316. # If there is no convex hull for the node, start calculating it and continue.
  1317. if not node.getDecorator(ConvexHullDecorator):
  1318. node.addDecorator(ConvexHullDecorator())
  1319. for child in node.getAllChildren():
  1320. if not child.getDecorator(ConvexHullDecorator):
  1321. child.addDecorator(ConvexHullDecorator())
  1322. if arrange_objects_on_load:
  1323. if node.callDecoration("isSliceable"):
  1324. # Only check position if it's not already blatantly obvious that it won't fit.
  1325. 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:
  1326. # Find node location
  1327. offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = min_offset)
  1328. # If a model is to small then it will not contain any points
  1329. if offset_shape_arr is None and hull_shape_arr is None:
  1330. Message(self._i18n_catalog.i18nc("@info:status", "The selected model was too small to load."),
  1331. title=self._i18n_catalog.i18nc("@info:title", "Warning")).show()
  1332. return
  1333. # Step is for skipping tests to make it a lot faster. it also makes the outcome somewhat rougher
  1334. node, _ = arranger.findNodePlacement(node, offset_shape_arr, hull_shape_arr, step = 10)
  1335. # This node is deep copied from some other node which already has a BuildPlateDecorator, but the deepcopy
  1336. # of BuildPlateDecorator produces one that's associated with build plate -1. So, here we need to check if
  1337. # the BuildPlateDecorator exists or not and always set the correct build plate number.
  1338. build_plate_decorator = node.getDecorator(BuildPlateDecorator)
  1339. if build_plate_decorator is None:
  1340. build_plate_decorator = BuildPlateDecorator(target_build_plate)
  1341. node.addDecorator(build_plate_decorator)
  1342. build_plate_decorator.setBuildPlateNumber(target_build_plate)
  1343. op = AddSceneNodeOperation(node, scene.getRoot())
  1344. op.push()
  1345. scene.sceneChanged.emit(node)
  1346. self.fileCompleted.emit(filename)
  1347. def addNonSliceableExtension(self, extension):
  1348. self._non_sliceable_extensions.append(extension)
  1349. @pyqtSlot(str, result=bool)
  1350. def checkIsValidProjectFile(self, file_url):
  1351. """
  1352. Checks if the given file URL is a valid project file.
  1353. """
  1354. file_path = QUrl(file_url).toLocalFile()
  1355. workspace_reader = self.getWorkspaceFileHandler().getReaderForFile(file_path)
  1356. if workspace_reader is None:
  1357. return False # non-project files won't get a reader
  1358. try:
  1359. result = workspace_reader.preRead(file_path, show_dialog=False)
  1360. return result == WorkspaceReader.PreReadResult.accepted
  1361. except Exception as e:
  1362. Logger.log("e", "Could not check file %s: %s", file_url, e)
  1363. return False
  1364. def _onContextMenuRequested(self, x: float, y: float) -> None:
  1365. # Ensure we select the object if we request a context menu over an object without having a selection.
  1366. if not Selection.hasSelection():
  1367. node = self.getController().getScene().findObject(self.getRenderer().getRenderPass("selection").getIdAtPosition(x, y))
  1368. if node:
  1369. while(node.getParent() and node.getParent().callDecoration("isGroup")):
  1370. node = node.getParent()
  1371. Selection.add(node)