CuraApplication.py 62 KB

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