CuraApplication.py 71 KB

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