CuraApplication.py 54 KB

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