CuraApplication.py 68 KB

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