CuraApplication.py 63 KB

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