CuraApplication.py 71 KB

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