CuraApplication.py 66 KB

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