CuraApplication.py 70 KB

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