CuraApplication.py 69 KB

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