CuraApplication.py 63 KB

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