CuraApplication.py 67 KB

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