CuraApplication.py 61 KB

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