CuraApplication.py 53 KB

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