CuraApplication.py 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import copy
  4. import os
  5. import sys
  6. import time
  7. from typing import cast, TYPE_CHECKING, Optional
  8. import numpy
  9. from PyQt5.QtCore import QObject, QTimer, QUrl, pyqtSignal, pyqtProperty, QEvent, Q_ENUMS
  10. from PyQt5.QtGui import QColor, QIcon
  11. from PyQt5.QtWidgets import QMessageBox
  12. from PyQt5.QtQml import qmlRegisterUncreatableType, qmlRegisterSingletonType, qmlRegisterType
  13. from UM.Scene.SceneNode import SceneNode
  14. from UM.Scene.Camera import Camera
  15. from UM.Math.Vector import Vector
  16. from UM.Math.Quaternion import Quaternion
  17. from UM.Math.AxisAlignedBox import AxisAlignedBox
  18. from UM.Math.Matrix import Matrix
  19. from UM.Platform import Platform
  20. from UM.Resources import Resources
  21. from UM.Scene.ToolHandle import ToolHandle
  22. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  23. from UM.Mesh.ReadMeshJob import ReadMeshJob
  24. from UM.Logger import Logger
  25. from UM.Preferences import Preferences
  26. from UM.Qt.QtApplication import QtApplication #The class we're inheriting from.
  27. from UM.View.SelectionPass import SelectionPass #For typing.
  28. from UM.Scene.Selection import Selection
  29. from UM.Scene.GroupDecorator import GroupDecorator
  30. from UM.Settings.ContainerStack import ContainerStack
  31. from UM.Settings.InstanceContainer import InstanceContainer
  32. from UM.Settings.Validator import Validator
  33. from UM.Message import Message
  34. from UM.i18n import i18nCatalog
  35. from UM.Workspace.WorkspaceReader import WorkspaceReader
  36. from UM.Decorators import deprecated
  37. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  38. from UM.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
  39. from UM.Operations.GroupedOperation import GroupedOperation
  40. from UM.Operations.SetTransformOperation import SetTransformOperation
  41. from cura.Arranging.Arrange import Arrange
  42. from cura.Arranging.ArrangeObjectsJob import ArrangeObjectsJob
  43. from cura.Arranging.ArrangeObjectsAllBuildPlatesJob import ArrangeObjectsAllBuildPlatesJob
  44. from cura.Arranging.ShapeArray import ShapeArray
  45. from cura.MultiplyObjectsJob import MultiplyObjectsJob
  46. from cura.Scene.ConvexHullDecorator import ConvexHullDecorator
  47. from cura.Operations.SetParentOperation import SetParentOperation
  48. from cura.Scene.SliceableObjectDecorator import SliceableObjectDecorator
  49. from cura.Scene.BlockSlicingDecorator import BlockSlicingDecorator
  50. from cura.Scene.BuildPlateDecorator import BuildPlateDecorator
  51. from cura.Scene.CuraSceneNode import CuraSceneNode
  52. from cura.Scene.CuraSceneController import CuraSceneController
  53. from UM.Settings.SettingDefinition import SettingDefinition, DefinitionPropertyType
  54. from UM.Settings.ContainerRegistry import ContainerRegistry
  55. from UM.Settings.SettingFunction import SettingFunction
  56. from cura.Settings.MachineNameValidator import MachineNameValidator
  57. from cura.Machines.Models.BuildPlateModel import BuildPlateModel
  58. from cura.Machines.Models.NozzleModel import NozzleModel
  59. from cura.Machines.Models.QualityProfilesDropDownMenuModel import QualityProfilesDropDownMenuModel
  60. from cura.Machines.Models.CustomQualityProfilesDropDownMenuModel import CustomQualityProfilesDropDownMenuModel
  61. from cura.Machines.Models.MultiBuildPlateModel import MultiBuildPlateModel
  62. from cura.Machines.Models.MaterialManagementModel import MaterialManagementModel
  63. from cura.Machines.Models.GenericMaterialsModel import GenericMaterialsModel
  64. from cura.Machines.Models.BrandMaterialsModel import BrandMaterialsModel
  65. from cura.Machines.Models.QualityManagementModel import QualityManagementModel
  66. from cura.Machines.Models.QualitySettingsModel import QualitySettingsModel
  67. from cura.Machines.Models.MachineManagementModel import MachineManagementModel
  68. from cura.Machines.Models.SettingVisibilityPresetsModel import SettingVisibilityPresetsModel
  69. from cura.Machines.MachineErrorChecker import MachineErrorChecker
  70. from cura.Settings.SettingInheritanceManager import SettingInheritanceManager
  71. from cura.Settings.SimpleModeSettingsManager import SimpleModeSettingsManager
  72. from cura.Machines.VariantManager import VariantManager
  73. from .SingleInstance import SingleInstance
  74. from .AutoSave import AutoSave
  75. from . import PlatformPhysics
  76. from . import BuildVolume
  77. from . import CameraAnimation
  78. from . import PrintInformation
  79. from . import CuraActions
  80. from cura.Scene import ZOffsetDecorator
  81. from . import CuraSplashScreen
  82. from . import CameraImageProvider
  83. from . import MachineActionManager
  84. from cura.TaskManagement.OnExitCallbackManager import OnExitCallbackManager
  85. from cura.Settings.MachineManager import MachineManager
  86. from cura.Settings.ExtruderManager import ExtruderManager
  87. from cura.Settings.UserChangesModel import UserChangesModel
  88. from cura.Settings.ExtrudersModel import ExtrudersModel
  89. from cura.Settings.MaterialSettingsVisibilityHandler import MaterialSettingsVisibilityHandler
  90. from cura.Settings.ContainerManager import ContainerManager
  91. from cura.Settings.SidebarCustomMenuItemsModel import SidebarCustomMenuItemsModel
  92. from cura.ObjectsModel import ObjectsModel
  93. from UM.FlameProfiler import pyqtSlot
  94. if TYPE_CHECKING:
  95. from plugins.SliceInfoPlugin.SliceInfo import SliceInfo
  96. numpy.seterr(all = "ignore")
  97. try:
  98. from cura.CuraVersion import CuraVersion, CuraBuildType, CuraDebugMode
  99. except ImportError:
  100. CuraVersion = "master" # [CodeStyle: Reflecting imported value]
  101. CuraBuildType = ""
  102. CuraDebugMode = False
  103. class CuraApplication(QtApplication):
  104. # SettingVersion represents the set of settings available in the machine/extruder definitions.
  105. # You need to make sure that this version number needs to be increased if there is any non-backwards-compatible
  106. # changes of the settings.
  107. SettingVersion = 5
  108. Created = False
  109. class ResourceTypes:
  110. QmlFiles = Resources.UserType + 1
  111. Firmware = Resources.UserType + 2
  112. QualityInstanceContainer = Resources.UserType + 3
  113. QualityChangesInstanceContainer = Resources.UserType + 4
  114. MaterialInstanceContainer = Resources.UserType + 5
  115. VariantInstanceContainer = Resources.UserType + 6
  116. UserInstanceContainer = Resources.UserType + 7
  117. MachineStack = Resources.UserType + 8
  118. ExtruderStack = Resources.UserType + 9
  119. DefinitionChangesContainer = Resources.UserType + 10
  120. SettingVisibilityPreset = Resources.UserType + 11
  121. Q_ENUMS(ResourceTypes)
  122. def __init__(self, *args, **kwargs):
  123. super().__init__(name = "cura",
  124. version = CuraVersion,
  125. buildtype = CuraBuildType,
  126. is_debug_mode = CuraDebugMode,
  127. tray_icon_name = "cura-icon-32.png",
  128. **kwargs)
  129. self.default_theme = "cura-light"
  130. self._boot_loading_time = time.time()
  131. self._on_exit_callback_manager = OnExitCallbackManager(self)
  132. # Variables set from CLI
  133. self._files_to_open = []
  134. self._use_single_instance = False
  135. self._trigger_early_crash = False # For debug only
  136. self._single_instance = None
  137. self._cura_package_manager = None
  138. self._machine_action_manager = None
  139. self.empty_container = None
  140. self.empty_definition_changes_container = None
  141. self.empty_variant_container = None
  142. self.empty_material_container = None
  143. self.empty_quality_container = None
  144. self.empty_quality_changes_container = None
  145. self._variant_manager = None
  146. self._material_manager = None
  147. self._quality_manager = None
  148. self._machine_manager = None
  149. self._extruder_manager = None
  150. self._container_manager = None
  151. self._object_manager = None
  152. self._build_plate_model = None
  153. self._multi_build_plate_model = None
  154. self._setting_visibility_presets_model = None
  155. self._setting_inheritance_manager = None
  156. self._simple_mode_settings_manager = None
  157. self._cura_scene_controller = None
  158. self._machine_error_checker = None
  159. self._quality_profile_drop_down_menu_model = None
  160. self._custom_quality_profile_drop_down_menu_model = None
  161. self._physics = None
  162. self._volume = None
  163. self._output_devices = {}
  164. self._print_information = None
  165. self._previous_active_tool = None
  166. self._platform_activity = False
  167. self._scene_bounding_box = AxisAlignedBox.Null
  168. self._center_after_select = False
  169. self._camera_animation = None
  170. self._cura_actions = None
  171. self.started = False
  172. self._message_box_callback = None
  173. self._message_box_callback_arguments = []
  174. self._preferred_mimetype = ""
  175. self._i18n_catalog = None
  176. self._currently_loading_files = []
  177. self._non_sliceable_extensions = []
  178. self._additional_components = {} # Components to add to certain areas in the interface
  179. self._open_file_queue = [] # A list of files to open (after the application has started)
  180. self._update_platform_activity_timer = None
  181. self._need_to_show_user_agreement = True
  182. self._sidebar_custom_menu_items = [] # type: list # Keeps list of custom menu items for the side bar
  183. self._plugins_loaded = False
  184. # Backups
  185. self._auto_save = None
  186. self._save_data_enabled = True
  187. from cura.Settings.CuraContainerRegistry import CuraContainerRegistry
  188. self._container_registry_class = CuraContainerRegistry
  189. from cura.CuraPackageManager import CuraPackageManager
  190. self._package_manager_class = CuraPackageManager
  191. # Adds command line options to the command line parser. This should be called after the application is created and
  192. # before the pre-start.
  193. def addCommandLineOptions(self):
  194. super().addCommandLineOptions()
  195. self._cli_parser.add_argument("--help", "-h",
  196. action = "store_true",
  197. default = False,
  198. help = "Show this help message and exit.")
  199. self._cli_parser.add_argument("--single-instance",
  200. dest = "single_instance",
  201. action = "store_true",
  202. default = False)
  203. # >> For debugging
  204. # Trigger an early crash, i.e. a crash that happens before the application enters its event loop.
  205. self._cli_parser.add_argument("--trigger-early-crash",
  206. dest = "trigger_early_crash",
  207. action = "store_true",
  208. default = False,
  209. help = "FOR TESTING ONLY. Trigger an early crash to show the crash dialog.")
  210. self._cli_parser.add_argument("file", nargs = "*", help = "Files to load after starting the application.")
  211. def parseCliOptions(self):
  212. super().parseCliOptions()
  213. if self._cli_args.help:
  214. self._cli_parser.print_help()
  215. sys.exit(0)
  216. self._use_single_instance = self._cli_args.single_instance
  217. self._trigger_early_crash = self._cli_args.trigger_early_crash
  218. for filename in self._cli_args.file:
  219. self._files_to_open.append(os.path.abspath(filename))
  220. def initialize(self) -> None:
  221. self.__addExpectedResourceDirsAndSearchPaths() # Must be added before init of super
  222. super().initialize()
  223. self.__sendCommandToSingleInstance()
  224. self.__initializeSettingDefinitionsAndFunctions()
  225. self.__addAllResourcesAndContainerResources()
  226. self.__addAllEmptyContainers()
  227. self.__setLatestResouceVersionsForVersionUpgrade()
  228. self._machine_action_manager = MachineActionManager.MachineActionManager(self)
  229. self._machine_action_manager.initialize()
  230. self.change_log_url = "https://ultimaker.com/ultimaker-cura-latest-features"
  231. def __sendCommandToSingleInstance(self):
  232. self._single_instance = SingleInstance(self, self._files_to_open)
  233. # If we use single instance, try to connect to the single instance server, send commands, and then exit.
  234. # If we cannot find an existing single instance server, this is the only instance, so just keep going.
  235. if self._use_single_instance:
  236. if self._single_instance.startClient():
  237. Logger.log("i", "Single instance commands were sent, exiting")
  238. sys.exit(0)
  239. # Adds expected directory names and search paths for Resources.
  240. def __addExpectedResourceDirsAndSearchPaths(self):
  241. # this list of dir names will be used by UM to detect an old cura directory
  242. for dir_name in ["extruders", "machine_instances", "materials", "plugins", "quality", "quality_changes", "user", "variants"]:
  243. Resources.addExpectedDirNameInData(dir_name)
  244. Resources.addSearchPath(os.path.join(self._app_install_dir, "share", "cura", "resources"))
  245. if not hasattr(sys, "frozen"):
  246. resource_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "resources")
  247. Resources.addSearchPath(resource_path)
  248. # Adds custom property types, settings types, and extra operators (functions) that need to be registered in
  249. # SettingDefinition and SettingFunction.
  250. def __initializeSettingDefinitionsAndFunctions(self):
  251. # Need to do this before ContainerRegistry tries to load the machines
  252. SettingDefinition.addSupportedProperty("settable_per_mesh", DefinitionPropertyType.Any, default = True, read_only = True)
  253. SettingDefinition.addSupportedProperty("settable_per_extruder", DefinitionPropertyType.Any, default = True, read_only = True)
  254. # this setting can be changed for each group in one-at-a-time mode
  255. SettingDefinition.addSupportedProperty("settable_per_meshgroup", DefinitionPropertyType.Any, default = True, read_only = True)
  256. SettingDefinition.addSupportedProperty("settable_globally", DefinitionPropertyType.Any, default = True, read_only = True)
  257. # From which stack the setting would inherit if not defined per object (handled in the engine)
  258. # AND for settings which are not settable_per_mesh:
  259. # which extruder is the only extruder this setting is obtained from
  260. SettingDefinition.addSupportedProperty("limit_to_extruder", DefinitionPropertyType.Function, default = "-1", depends_on = "value")
  261. # For settings which are not settable_per_mesh and not settable_per_extruder:
  262. # A function which determines the glabel/meshgroup value by looking at the values of the setting in all (used) extruders
  263. SettingDefinition.addSupportedProperty("resolve", DefinitionPropertyType.Function, default = None, depends_on = "value")
  264. SettingDefinition.addSettingType("extruder", None, str, Validator)
  265. SettingDefinition.addSettingType("optional_extruder", None, str, None)
  266. SettingDefinition.addSettingType("[int]", None, str, None)
  267. SettingFunction.registerOperator("extruderValues", ExtruderManager.getExtruderValues)
  268. SettingFunction.registerOperator("extruderValue", ExtruderManager.getExtruderValue)
  269. SettingFunction.registerOperator("resolveOrValue", ExtruderManager.getResolveOrValue)
  270. SettingFunction.registerOperator("defaultExtruderPosition", ExtruderManager.getDefaultExtruderPosition)
  271. # Adds all resources and container related resources.
  272. def __addAllResourcesAndContainerResources(self) -> None:
  273. Resources.addStorageType(self.ResourceTypes.QualityInstanceContainer, "quality")
  274. Resources.addStorageType(self.ResourceTypes.QualityChangesInstanceContainer, "quality_changes")
  275. Resources.addStorageType(self.ResourceTypes.VariantInstanceContainer, "variants")
  276. Resources.addStorageType(self.ResourceTypes.MaterialInstanceContainer, "materials")
  277. Resources.addStorageType(self.ResourceTypes.UserInstanceContainer, "user")
  278. Resources.addStorageType(self.ResourceTypes.ExtruderStack, "extruders")
  279. Resources.addStorageType(self.ResourceTypes.MachineStack, "machine_instances")
  280. Resources.addStorageType(self.ResourceTypes.DefinitionChangesContainer, "definition_changes")
  281. Resources.addStorageType(self.ResourceTypes.SettingVisibilityPreset, "setting_visibility")
  282. self._container_registry.addResourceType(self.ResourceTypes.QualityInstanceContainer, "quality")
  283. self._container_registry.addResourceType(self.ResourceTypes.QualityChangesInstanceContainer, "quality_changes")
  284. self._container_registry.addResourceType(self.ResourceTypes.VariantInstanceContainer, "variant")
  285. self._container_registry.addResourceType(self.ResourceTypes.MaterialInstanceContainer, "material")
  286. self._container_registry.addResourceType(self.ResourceTypes.UserInstanceContainer, "user")
  287. self._container_registry.addResourceType(self.ResourceTypes.ExtruderStack, "extruder_train")
  288. self._container_registry.addResourceType(self.ResourceTypes.MachineStack, "machine")
  289. self._container_registry.addResourceType(self.ResourceTypes.DefinitionChangesContainer, "definition_changes")
  290. Resources.addType(self.ResourceTypes.QmlFiles, "qml")
  291. Resources.addType(self.ResourceTypes.Firmware, "firmware")
  292. # Adds all empty containers.
  293. def __addAllEmptyContainers(self) -> None:
  294. # Add empty variant, material and quality containers.
  295. # Since they are empty, they should never be serialized and instead just programmatically created.
  296. # We need them to simplify the switching between materials.
  297. empty_container = self._container_registry.getEmptyInstanceContainer()
  298. self.empty_container = empty_container
  299. empty_definition_changes_container = copy.deepcopy(empty_container)
  300. empty_definition_changes_container.setMetaDataEntry("id", "empty_definition_changes")
  301. empty_definition_changes_container.setMetaDataEntry("type", "definition_changes")
  302. self._container_registry.addContainer(empty_definition_changes_container)
  303. self.empty_definition_changes_container = empty_definition_changes_container
  304. empty_variant_container = copy.deepcopy(empty_container)
  305. empty_variant_container.setMetaDataEntry("id", "empty_variant")
  306. empty_variant_container.setMetaDataEntry("type", "variant")
  307. self._container_registry.addContainer(empty_variant_container)
  308. self.empty_variant_container = empty_variant_container
  309. empty_material_container = copy.deepcopy(empty_container)
  310. empty_material_container.setMetaDataEntry("id", "empty_material")
  311. empty_material_container.setMetaDataEntry("type", "material")
  312. self._container_registry.addContainer(empty_material_container)
  313. self.empty_material_container = empty_material_container
  314. empty_quality_container = copy.deepcopy(empty_container)
  315. empty_quality_container.setMetaDataEntry("id", "empty_quality")
  316. empty_quality_container.setName("Not Supported")
  317. empty_quality_container.setMetaDataEntry("quality_type", "not_supported")
  318. empty_quality_container.setMetaDataEntry("type", "quality")
  319. empty_quality_container.setMetaDataEntry("supported", False)
  320. self._container_registry.addContainer(empty_quality_container)
  321. self.empty_quality_container = empty_quality_container
  322. empty_quality_changes_container = copy.deepcopy(empty_container)
  323. empty_quality_changes_container.setMetaDataEntry("id", "empty_quality_changes")
  324. empty_quality_changes_container.setMetaDataEntry("type", "quality_changes")
  325. empty_quality_changes_container.setMetaDataEntry("quality_type", "not_supported")
  326. self._container_registry.addContainer(empty_quality_changes_container)
  327. self.empty_quality_changes_container = empty_quality_changes_container
  328. # Initializes the version upgrade manager with by providing the paths for each resource type and the latest
  329. # versions.
  330. def __setLatestResouceVersionsForVersionUpgrade(self):
  331. self._version_upgrade_manager.setCurrentVersions(
  332. {
  333. ("quality", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.QualityInstanceContainer, "application/x-uranium-instancecontainer"),
  334. ("quality_changes", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.QualityChangesInstanceContainer, "application/x-uranium-instancecontainer"),
  335. ("machine_stack", ContainerStack.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.MachineStack, "application/x-cura-globalstack"),
  336. ("extruder_train", ContainerStack.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.ExtruderStack, "application/x-cura-extruderstack"),
  337. ("preferences", Preferences.Version * 1000000 + self.SettingVersion): (Resources.Preferences, "application/x-uranium-preferences"),
  338. ("user", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.UserInstanceContainer, "application/x-uranium-instancecontainer"),
  339. ("definition_changes", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.DefinitionChangesContainer, "application/x-uranium-instancecontainer"),
  340. ("variant", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.VariantInstanceContainer, "application/x-uranium-instancecontainer"),
  341. }
  342. )
  343. # Runs preparations that needs to be done before the starting process.
  344. def startSplashWindowPhase(self):
  345. super().startSplashWindowPhase()
  346. self.setWindowIcon(QIcon(Resources.getPath(Resources.Images, "cura-icon.png")))
  347. self.setRequiredPlugins([
  348. # Misc.:
  349. "ConsoleLogger",
  350. "CuraEngineBackend",
  351. "UserAgreement",
  352. "FileLogger",
  353. "XmlMaterialProfile",
  354. "Toolbox",
  355. "PrepareStage",
  356. "MonitorStage",
  357. "LocalFileOutputDevice",
  358. "LocalContainerProvider",
  359. # Views:
  360. "SimpleView",
  361. "SimulationView",
  362. "SolidView",
  363. # Readers & Writers:
  364. "GCodeWriter",
  365. "STLReader",
  366. # Tools:
  367. "CameraTool",
  368. "MirrorTool",
  369. "RotateTool",
  370. "ScaleTool",
  371. "SelectionTool",
  372. "TranslateTool",
  373. ])
  374. self._i18n_catalog = i18nCatalog("cura")
  375. self._update_platform_activity_timer = QTimer()
  376. self._update_platform_activity_timer.setInterval(500)
  377. self._update_platform_activity_timer.setSingleShot(True)
  378. self._update_platform_activity_timer.timeout.connect(self.updatePlatformActivity)
  379. self.getController().getScene().sceneChanged.connect(self.updatePlatformActivityDelayed)
  380. self.getController().toolOperationStopped.connect(self._onToolOperationStopped)
  381. self.getController().contextMenuRequested.connect(self._onContextMenuRequested)
  382. self.getCuraSceneController().activeBuildPlateChanged.connect(self.updatePlatformActivityDelayed)
  383. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading machines..."))
  384. with self._container_registry.lockFile():
  385. self._container_registry.loadAllMetadata()
  386. # set the setting version for Preferences
  387. preferences = self.getPreferences()
  388. preferences.addPreference("metadata/setting_version", 0)
  389. preferences.setValue("metadata/setting_version", self.SettingVersion) #Don't make it equal to the default so that the setting version always gets written to the file.
  390. preferences.addPreference("cura/active_mode", "simple")
  391. preferences.addPreference("cura/categories_expanded", "")
  392. preferences.addPreference("cura/jobname_prefix", True)
  393. preferences.addPreference("cura/select_models_on_load", False)
  394. preferences.addPreference("view/center_on_select", False)
  395. preferences.addPreference("mesh/scale_to_fit", False)
  396. preferences.addPreference("mesh/scale_tiny_meshes", True)
  397. preferences.addPreference("cura/dialog_on_project_save", True)
  398. preferences.addPreference("cura/asked_dialog_on_project_save", False)
  399. preferences.addPreference("cura/choice_on_profile_override", "always_ask")
  400. preferences.addPreference("cura/choice_on_open_project", "always_ask")
  401. preferences.addPreference("cura/use_multi_build_plate", False)
  402. preferences.addPreference("cura/currency", "€")
  403. preferences.addPreference("cura/material_settings", "{}")
  404. preferences.addPreference("view/invert_zoom", False)
  405. preferences.addPreference("view/filter_current_build_plate", False)
  406. preferences.addPreference("cura/sidebar_collapsed", False)
  407. self._need_to_show_user_agreement = not self.getPreferences().getValue("general/accepted_user_agreement")
  408. for key in [
  409. "dialog_load_path", # dialog_save_path is in LocalFileOutputDevicePlugin
  410. "dialog_profile_path",
  411. "dialog_material_path"]:
  412. preferences.addPreference("local_file/%s" % key, os.path.expanduser("~/"))
  413. preferences.setDefault("local_file/last_used_type", "text/x-gcode")
  414. self.applicationShuttingDown.connect(self.saveSettings)
  415. self.engineCreatedSignal.connect(self._onEngineCreated)
  416. self.globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  417. self._onGlobalContainerChanged()
  418. self.getCuraSceneController().setActiveBuildPlate(0) # Initialize
  419. CuraApplication.Created = True
  420. def _onEngineCreated(self):
  421. self._qml_engine.addImageProvider("camera", CameraImageProvider.CameraImageProvider())
  422. @pyqtProperty(bool)
  423. def needToShowUserAgreement(self):
  424. return self._need_to_show_user_agreement
  425. def setNeedToShowUserAgreement(self, set_value = True):
  426. self._need_to_show_user_agreement = set_value
  427. # DO NOT call this function to close the application, use checkAndExitApplication() instead which will perform
  428. # pre-exit checks such as checking for in-progress USB printing, etc.
  429. def closeApplication(self):
  430. Logger.log("i", "Close application")
  431. main_window = self.getMainWindow()
  432. if main_window is not None:
  433. main_window.close()
  434. else:
  435. self.exit(0)
  436. # This function first performs all upon-exit checks such as USB printing that is in progress.
  437. # Use this to close the application.
  438. @pyqtSlot()
  439. def checkAndExitApplication(self) -> None:
  440. self._on_exit_callback_manager.resetCurrentState()
  441. self._on_exit_callback_manager.triggerNextCallback()
  442. @pyqtSlot(result = bool)
  443. def getIsAllChecksPassed(self) -> bool:
  444. return self._on_exit_callback_manager.getIsAllChecksPassed()
  445. def getOnExitCallbackManager(self) -> "OnExitCallbackManager":
  446. return self._on_exit_callback_manager
  447. def triggerNextExitCheck(self) -> None:
  448. self._on_exit_callback_manager.triggerNextCallback()
  449. showConfirmExitDialog = pyqtSignal(str, arguments = ["message"])
  450. def setConfirmExitDialogCallback(self, callback):
  451. self._confirm_exit_dialog_callback = callback
  452. @pyqtSlot(bool)
  453. def callConfirmExitDialogCallback(self, yes_or_no: bool):
  454. self._confirm_exit_dialog_callback(yes_or_no)
  455. ## Signal to connect preferences action in QML
  456. showPreferencesWindow = pyqtSignal()
  457. ## Show the preferences window
  458. @pyqtSlot()
  459. def showPreferences(self):
  460. self.showPreferencesWindow.emit()
  461. ## A reusable dialogbox
  462. #
  463. showMessageBox = pyqtSignal(str, str, str, str, int, int, arguments = ["title", "text", "informativeText", "detailedText", "buttons", "icon"])
  464. def messageBox(self, title, text, informativeText = "", detailedText = "", buttons = QMessageBox.Ok, icon = QMessageBox.NoIcon, callback = None, callback_arguments = []):
  465. self._message_box_callback = callback
  466. self._message_box_callback_arguments = callback_arguments
  467. self.showMessageBox.emit(title, text, informativeText, detailedText, buttons, icon)
  468. showDiscardOrKeepProfileChanges = pyqtSignal()
  469. def discardOrKeepProfileChanges(self):
  470. has_user_interaction = False
  471. choice = self.getPreferences().getValue("cura/choice_on_profile_override")
  472. if choice == "always_discard":
  473. # don't show dialog and DISCARD the profile
  474. self.discardOrKeepProfileChangesClosed("discard")
  475. elif choice == "always_keep":
  476. # don't show dialog and KEEP the profile
  477. self.discardOrKeepProfileChangesClosed("keep")
  478. elif not self._is_headless:
  479. # ALWAYS ask whether to keep or discard the profile
  480. self.showDiscardOrKeepProfileChanges.emit()
  481. has_user_interaction = True
  482. return has_user_interaction
  483. @pyqtSlot(str)
  484. def discardOrKeepProfileChangesClosed(self, option):
  485. global_stack = self.getGlobalContainerStack()
  486. if option == "discard":
  487. for extruder in global_stack.extruders.values():
  488. extruder.userChanges.clear()
  489. global_stack.userChanges.clear()
  490. # if the user decided to keep settings then the user settings should be re-calculated and validated for errors
  491. # before slicing. To ensure that slicer uses right settings values
  492. elif option == "keep":
  493. for extruder in global_stack.extruders.values():
  494. extruder.userChanges.update()
  495. global_stack.userChanges.update()
  496. @pyqtSlot(int)
  497. def messageBoxClosed(self, button):
  498. if self._message_box_callback:
  499. self._message_box_callback(button, *self._message_box_callback_arguments)
  500. self._message_box_callback = None
  501. self._message_box_callback_arguments = []
  502. showPrintMonitor = pyqtSignal(bool, arguments = ["show"])
  503. def setSaveDataEnabled(self, enabled: bool) -> None:
  504. self._save_data_enabled = enabled
  505. # Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
  506. def saveSettings(self):
  507. if not self.started or not self._save_data_enabled:
  508. # Do not do saving during application start or when data should not be safed on quit.
  509. return
  510. ContainerRegistry.getInstance().saveDirtyContainers()
  511. self.savePreferences()
  512. def saveStack(self, stack):
  513. ContainerRegistry.getInstance().saveContainer(stack)
  514. @pyqtSlot(str, result = QUrl)
  515. def getDefaultPath(self, key):
  516. default_path = self.getPreferences().getValue("local_file/%s" % key)
  517. return QUrl.fromLocalFile(default_path)
  518. @pyqtSlot(str, str)
  519. def setDefaultPath(self, key, default_path):
  520. self.getPreferences().setValue("local_file/%s" % key, QUrl(default_path).toLocalFile())
  521. ## Handle loading of all plugin types (and the backend explicitly)
  522. # \sa PluginRegistry
  523. def _loadPlugins(self):
  524. self._plugin_registry.addType("profile_reader", self._addProfileReader)
  525. self._plugin_registry.addType("profile_writer", self._addProfileWriter)
  526. if Platform.isLinux():
  527. lib_suffixes = {"", "64", "32", "x32"} #A few common ones on different distributions.
  528. else:
  529. lib_suffixes = {""}
  530. for suffix in lib_suffixes:
  531. self._plugin_registry.addPluginLocation(os.path.join(QtApplication.getInstallPrefix(), "lib" + suffix, "cura"))
  532. if not hasattr(sys, "frozen"):
  533. self._plugin_registry.addPluginLocation(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "plugins"))
  534. self._plugin_registry.loadPlugin("ConsoleLogger")
  535. self._plugin_registry.loadPlugin("CuraEngineBackend")
  536. self._plugin_registry.loadPlugins()
  537. if self.getBackend() is None:
  538. raise RuntimeError("Could not load the backend plugin!")
  539. self._plugins_loaded = True
  540. def run(self):
  541. super().run()
  542. container_registry = self._container_registry
  543. Logger.log("i", "Initializing variant manager")
  544. self._variant_manager = VariantManager(container_registry)
  545. self._variant_manager.initialize()
  546. Logger.log("i", "Initializing material manager")
  547. from cura.Machines.MaterialManager import MaterialManager
  548. self._material_manager = MaterialManager(container_registry, parent = self)
  549. self._material_manager.initialize()
  550. Logger.log("i", "Initializing quality manager")
  551. from cura.Machines.QualityManager import QualityManager
  552. self._quality_manager = QualityManager(container_registry, parent = self)
  553. self._quality_manager.initialize()
  554. Logger.log("i", "Initializing machine manager")
  555. self._machine_manager = MachineManager(self)
  556. Logger.log("i", "Initializing container manager")
  557. self._container_manager = ContainerManager(self)
  558. Logger.log("i", "Initializing machine error checker")
  559. self._machine_error_checker = MachineErrorChecker(self)
  560. self._machine_error_checker.initialize()
  561. # Check if we should run as single instance or not. If so, set up a local socket server which listener which
  562. # coordinates multiple Cura instances and accepts commands.
  563. if self._use_single_instance:
  564. self.__setUpSingleInstanceServer()
  565. # Setup scene and build volume
  566. root = self.getController().getScene().getRoot()
  567. self._volume = BuildVolume.BuildVolume(self, root)
  568. Arrange.build_volume = self._volume
  569. # initialize info objects
  570. self._print_information = PrintInformation.PrintInformation(self)
  571. self._cura_actions = CuraActions.CuraActions(self)
  572. # Initialize setting visibility presets model
  573. self._setting_visibility_presets_model = SettingVisibilityPresetsModel(self)
  574. default_visibility_profile = self._setting_visibility_presets_model.getItem(0)
  575. self.getPreferences().setDefault("general/visible_settings", ";".join(default_visibility_profile["settings"]))
  576. # Detect in which mode to run and execute that mode
  577. if self._is_headless:
  578. self.runWithoutGUI()
  579. else:
  580. self.runWithGUI()
  581. self.started = True
  582. self.initializationFinished.emit()
  583. Logger.log("d", "Booting Cura took %s seconds", time.time() - self._boot_loading_time)
  584. # For now use a timer to postpone some things that need to be done after the application and GUI are
  585. # initialized, for example opening files because they may show dialogs which can be closed due to incomplete
  586. # GUI initialization.
  587. self._post_start_timer = QTimer(self)
  588. self._post_start_timer.setInterval(1000)
  589. self._post_start_timer.setSingleShot(True)
  590. self._post_start_timer.timeout.connect(self._onPostStart)
  591. self._post_start_timer.start()
  592. self._auto_save = AutoSave(self)
  593. self._auto_save.initialize()
  594. self.exec_()
  595. def __setUpSingleInstanceServer(self):
  596. if self._use_single_instance:
  597. self._single_instance.startServer()
  598. def _onPostStart(self):
  599. for file_name in self._files_to_open:
  600. self.callLater(self._openFile, file_name)
  601. for file_name in self._open_file_queue: # Open all the files that were queued up while plug-ins were loading.
  602. self.callLater(self._openFile, file_name)
  603. initializationFinished = pyqtSignal()
  604. ## Run Cura without GUI elements and interaction (server mode).
  605. def runWithoutGUI(self):
  606. self.closeSplash()
  607. ## Run Cura with GUI (desktop mode).
  608. def runWithGUI(self):
  609. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Setting up scene..."))
  610. controller = self.getController()
  611. t = controller.getTool("TranslateTool")
  612. if t:
  613. t.setEnabledAxis([ToolHandle.XAxis, ToolHandle.YAxis, ToolHandle.ZAxis])
  614. Selection.selectionChanged.connect(self.onSelectionChanged)
  615. # Set default background color for scene
  616. self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
  617. # Initialize platform physics
  618. self._physics = PlatformPhysics.PlatformPhysics(controller, self._volume)
  619. # Initialize camera
  620. root = controller.getScene().getRoot()
  621. camera = Camera("3d", root)
  622. camera.setPosition(Vector(-80, 250, 700))
  623. camera.setPerspective(True)
  624. camera.lookAt(Vector(0, 0, 0))
  625. controller.getScene().setActiveCamera("3d")
  626. # Initialize camera tool
  627. camera_tool = controller.getTool("CameraTool")
  628. camera_tool.setOrigin(Vector(0, 100, 0))
  629. camera_tool.setZoomRange(0.1, 2000)
  630. # Initialize camera animations
  631. self._camera_animation = CameraAnimation.CameraAnimation()
  632. self._camera_animation.setCameraTool(self.getController().getTool("CameraTool"))
  633. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading interface..."))
  634. # Initialize QML engine
  635. self.setMainQml(Resources.getPath(self.ResourceTypes.QmlFiles, "Cura.qml"))
  636. self._qml_import_paths.append(Resources.getPath(self.ResourceTypes.QmlFiles))
  637. self.initializeEngine()
  638. # Initialize UI state
  639. controller.setActiveStage("PrepareStage")
  640. controller.setActiveView("SolidView")
  641. controller.setCameraTool("CameraTool")
  642. controller.setSelectionTool("SelectionTool")
  643. # Hide the splash screen
  644. self.closeSplash()
  645. @pyqtSlot(result = QObject)
  646. def getSettingVisibilityPresetsModel(self, *args) -> SettingVisibilityPresetsModel:
  647. return self._setting_visibility_presets_model
  648. def getMachineErrorChecker(self, *args) -> MachineErrorChecker:
  649. return self._machine_error_checker
  650. def getMachineManager(self, *args) -> MachineManager:
  651. if self._machine_manager is None:
  652. self._machine_manager = MachineManager(self)
  653. return self._machine_manager
  654. def getExtruderManager(self, *args):
  655. if self._extruder_manager is None:
  656. self._extruder_manager = ExtruderManager()
  657. return self._extruder_manager
  658. def getVariantManager(self, *args):
  659. return self._variant_manager
  660. @pyqtSlot(result = QObject)
  661. def getMaterialManager(self, *args):
  662. return self._material_manager
  663. @pyqtSlot(result = QObject)
  664. def getQualityManager(self, *args):
  665. return self._quality_manager
  666. def getObjectsModel(self, *args):
  667. if self._object_manager is None:
  668. self._object_manager = ObjectsModel.createObjectsModel()
  669. return self._object_manager
  670. @pyqtSlot(result = QObject)
  671. def getMultiBuildPlateModel(self, *args):
  672. if self._multi_build_plate_model is None:
  673. self._multi_build_plate_model = MultiBuildPlateModel(self)
  674. return self._multi_build_plate_model
  675. @pyqtSlot(result = QObject)
  676. def getBuildPlateModel(self, *args):
  677. if self._build_plate_model is None:
  678. self._build_plate_model = BuildPlateModel(self)
  679. return self._build_plate_model
  680. def getCuraSceneController(self, *args):
  681. if self._cura_scene_controller is None:
  682. self._cura_scene_controller = CuraSceneController.createCuraSceneController()
  683. return self._cura_scene_controller
  684. def getSettingInheritanceManager(self, *args):
  685. if self._setting_inheritance_manager is None:
  686. self._setting_inheritance_manager = SettingInheritanceManager.createSettingInheritanceManager()
  687. return self._setting_inheritance_manager
  688. ## Get the machine action manager
  689. # We ignore any *args given to this, as we also register the machine manager as qml singleton.
  690. # It wants to give this function an engine and script engine, but we don't care about that.
  691. def getMachineActionManager(self, *args):
  692. return self._machine_action_manager
  693. def getSimpleModeSettingsManager(self, *args):
  694. if self._simple_mode_settings_manager is None:
  695. self._simple_mode_settings_manager = SimpleModeSettingsManager()
  696. return self._simple_mode_settings_manager
  697. ## Handle Qt events
  698. def event(self, event):
  699. if event.type() == QEvent.FileOpen:
  700. if self._plugins_loaded:
  701. self._openFile(event.file())
  702. else:
  703. self._open_file_queue.append(event.file())
  704. return super().event(event)
  705. def getAutoSave(self):
  706. return self._auto_save
  707. ## Get print information (duration / material used)
  708. def getPrintInformation(self):
  709. return self._print_information
  710. def getQualityProfilesDropDownMenuModel(self, *args, **kwargs):
  711. if self._quality_profile_drop_down_menu_model is None:
  712. self._quality_profile_drop_down_menu_model = QualityProfilesDropDownMenuModel(self)
  713. return self._quality_profile_drop_down_menu_model
  714. def getCustomQualityProfilesDropDownMenuModel(self, *args, **kwargs):
  715. if self._custom_quality_profile_drop_down_menu_model is None:
  716. self._custom_quality_profile_drop_down_menu_model = CustomQualityProfilesDropDownMenuModel(self)
  717. return self._custom_quality_profile_drop_down_menu_model
  718. ## Registers objects for the QML engine to use.
  719. #
  720. # \param engine The QML engine.
  721. def registerObjects(self, engine):
  722. super().registerObjects(engine)
  723. # global contexts
  724. engine.rootContext().setContextProperty("Printer", self)
  725. engine.rootContext().setContextProperty("CuraApplication", self)
  726. engine.rootContext().setContextProperty("PrintInformation", self._print_information)
  727. engine.rootContext().setContextProperty("CuraActions", self._cura_actions)
  728. qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")
  729. qmlRegisterSingletonType(CuraSceneController, "Cura", 1, 0, "SceneController", self.getCuraSceneController)
  730. qmlRegisterSingletonType(ExtruderManager, "Cura", 1, 0, "ExtruderManager", self.getExtruderManager)
  731. qmlRegisterSingletonType(MachineManager, "Cura", 1, 0, "MachineManager", self.getMachineManager)
  732. qmlRegisterSingletonType(SettingInheritanceManager, "Cura", 1, 0, "SettingInheritanceManager", self.getSettingInheritanceManager)
  733. qmlRegisterSingletonType(SimpleModeSettingsManager, "Cura", 1, 0, "SimpleModeSettingsManager", self.getSimpleModeSettingsManager)
  734. qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, "MachineActionManager", self.getMachineActionManager)
  735. qmlRegisterSingletonType(ObjectsModel, "Cura", 1, 0, "ObjectsModel", self.getObjectsModel)
  736. qmlRegisterType(BuildPlateModel, "Cura", 1, 0, "BuildPlateModel")
  737. qmlRegisterType(MultiBuildPlateModel, "Cura", 1, 0, "MultiBuildPlateModel")
  738. qmlRegisterType(InstanceContainer, "Cura", 1, 0, "InstanceContainer")
  739. qmlRegisterType(ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")
  740. qmlRegisterType(GenericMaterialsModel, "Cura", 1, 0, "GenericMaterialsModel")
  741. qmlRegisterType(BrandMaterialsModel, "Cura", 1, 0, "BrandMaterialsModel")
  742. qmlRegisterType(MaterialManagementModel, "Cura", 1, 0, "MaterialManagementModel")
  743. qmlRegisterType(QualityManagementModel, "Cura", 1, 0, "QualityManagementModel")
  744. qmlRegisterType(MachineManagementModel, "Cura", 1, 0, "MachineManagementModel")
  745. qmlRegisterSingletonType(QualityProfilesDropDownMenuModel, "Cura", 1, 0,
  746. "QualityProfilesDropDownMenuModel", self.getQualityProfilesDropDownMenuModel)
  747. qmlRegisterSingletonType(CustomQualityProfilesDropDownMenuModel, "Cura", 1, 0,
  748. "CustomQualityProfilesDropDownMenuModel", self.getCustomQualityProfilesDropDownMenuModel)
  749. qmlRegisterType(NozzleModel, "Cura", 1, 0, "NozzleModel")
  750. qmlRegisterType(MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
  751. qmlRegisterType(SettingVisibilityPresetsModel, "Cura", 1, 0, "SettingVisibilityPresetsModel")
  752. qmlRegisterType(QualitySettingsModel, "Cura", 1, 0, "QualitySettingsModel")
  753. qmlRegisterType(MachineNameValidator, "Cura", 1, 0, "MachineNameValidator")
  754. qmlRegisterType(UserChangesModel, "Cura", 1, 0, "UserChangesModel")
  755. qmlRegisterSingletonType(ContainerManager, "Cura", 1, 0, "ContainerManager", ContainerManager.getInstance)
  756. qmlRegisterType(SidebarCustomMenuItemsModel, "Cura", 1, 0, "SidebarCustomMenuItemsModel")
  757. # As of Qt5.7, it is necessary to get rid of any ".." in the path for the singleton to work.
  758. actions_url = QUrl.fromLocalFile(os.path.abspath(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")))
  759. qmlRegisterSingletonType(actions_url, "Cura", 1, 0, "Actions")
  760. for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
  761. type_name = os.path.splitext(os.path.basename(path))[0]
  762. if type_name in ("Cura", "Actions"):
  763. continue
  764. # Ignore anything that is not a QML file.
  765. if not path.endswith(".qml"):
  766. continue
  767. qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
  768. def onSelectionChanged(self):
  769. if Selection.hasSelection():
  770. if self.getController().getActiveTool():
  771. # If the tool has been disabled by the new selection
  772. if not self.getController().getActiveTool().getEnabled():
  773. # Default
  774. self.getController().setActiveTool("TranslateTool")
  775. else:
  776. if self._previous_active_tool:
  777. self.getController().setActiveTool(self._previous_active_tool)
  778. if not self.getController().getActiveTool().getEnabled():
  779. self.getController().setActiveTool("TranslateTool")
  780. self._previous_active_tool = None
  781. else:
  782. # Default
  783. self.getController().setActiveTool("TranslateTool")
  784. if self.getPreferences().getValue("view/center_on_select"):
  785. self._center_after_select = True
  786. else:
  787. if self.getController().getActiveTool():
  788. self._previous_active_tool = self.getController().getActiveTool().getPluginId()
  789. self.getController().setActiveTool(None)
  790. def _onToolOperationStopped(self, event):
  791. if self._center_after_select and Selection.getSelectedObject(0) is not None:
  792. self._center_after_select = False
  793. self._camera_animation.setStart(self.getController().getTool("CameraTool").getOrigin())
  794. self._camera_animation.setTarget(Selection.getSelectedObject(0).getWorldPosition())
  795. self._camera_animation.start()
  796. def _onGlobalContainerChanged(self):
  797. if self._global_container_stack is not None:
  798. machine_file_formats = [file_type.strip() for file_type in self._global_container_stack.getMetaDataEntry("file_formats").split(";")]
  799. new_preferred_mimetype = ""
  800. if machine_file_formats:
  801. new_preferred_mimetype = machine_file_formats[0]
  802. if new_preferred_mimetype != self._preferred_mimetype:
  803. self._preferred_mimetype = new_preferred_mimetype
  804. self.preferredOutputMimetypeChanged.emit()
  805. requestAddPrinter = pyqtSignal()
  806. activityChanged = pyqtSignal()
  807. sceneBoundingBoxChanged = pyqtSignal()
  808. preferredOutputMimetypeChanged = pyqtSignal()
  809. @pyqtProperty(bool, notify = activityChanged)
  810. def platformActivity(self):
  811. return self._platform_activity
  812. @pyqtProperty(str, notify=preferredOutputMimetypeChanged)
  813. def preferredOutputMimetype(self):
  814. return self._preferred_mimetype
  815. @pyqtProperty(str, notify = sceneBoundingBoxChanged)
  816. def getSceneBoundingBoxString(self):
  817. return self._i18n_catalog.i18nc("@info 'width', 'depth' and 'height' are variable names that must NOT be translated; just translate the format of ##x##x## mm.", "%(width).1f x %(depth).1f x %(height).1f mm") % {'width' : self._scene_bounding_box.width.item(), 'depth': self._scene_bounding_box.depth.item(), 'height' : self._scene_bounding_box.height.item()}
  818. def updatePlatformActivityDelayed(self, node = None):
  819. if node is not None and (node.getMeshData() is not None or node.callDecoration("getLayerData")):
  820. self._update_platform_activity_timer.start()
  821. ## Update scene bounding box for current build plate
  822. def updatePlatformActivity(self, node = None):
  823. count = 0
  824. scene_bounding_box = None
  825. is_block_slicing_node = False
  826. active_build_plate = self.getMultiBuildPlateModel().activeBuildPlate
  827. print_information = self.getPrintInformation()
  828. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  829. if (
  830. not issubclass(type(node), CuraSceneNode) or
  831. (not node.getMeshData() and not node.callDecoration("getLayerData")) or
  832. (node.callDecoration("getBuildPlateNumber") != active_build_plate)):
  833. continue
  834. if node.callDecoration("isBlockSlicing"):
  835. is_block_slicing_node = True
  836. count += 1
  837. # After clicking the Undo button, if the build plate empty the project name needs to be set
  838. if print_information.baseName == '':
  839. print_information.setBaseName(node.getName())
  840. if not scene_bounding_box:
  841. scene_bounding_box = node.getBoundingBox()
  842. else:
  843. other_bb = node.getBoundingBox()
  844. if other_bb is not None:
  845. scene_bounding_box = scene_bounding_box + node.getBoundingBox()
  846. if print_information:
  847. print_information.setPreSliced(is_block_slicing_node)
  848. if not scene_bounding_box:
  849. scene_bounding_box = AxisAlignedBox.Null
  850. if repr(self._scene_bounding_box) != repr(scene_bounding_box):
  851. self._scene_bounding_box = scene_bounding_box
  852. self.sceneBoundingBoxChanged.emit()
  853. self._platform_activity = True if count > 0 else False
  854. self.activityChanged.emit()
  855. # Remove all selected objects from the scene.
  856. @pyqtSlot()
  857. @deprecated("Moved to CuraActions", "2.6")
  858. def deleteSelection(self):
  859. if not self.getController().getToolsEnabled():
  860. return
  861. removed_group_nodes = []
  862. op = GroupedOperation()
  863. nodes = Selection.getAllSelectedObjects()
  864. for node in nodes:
  865. op.addOperation(RemoveSceneNodeOperation(node))
  866. group_node = node.getParent()
  867. if group_node and group_node.callDecoration("isGroup") and group_node not in removed_group_nodes:
  868. remaining_nodes_in_group = list(set(group_node.getChildren()) - set(nodes))
  869. if len(remaining_nodes_in_group) == 1:
  870. removed_group_nodes.append(group_node)
  871. op.addOperation(SetParentOperation(remaining_nodes_in_group[0], group_node.getParent()))
  872. op.addOperation(RemoveSceneNodeOperation(group_node))
  873. op.push()
  874. ## Remove an object from the scene.
  875. # Note that this only removes an object if it is selected.
  876. @pyqtSlot("quint64")
  877. @deprecated("Use deleteSelection instead", "2.6")
  878. def deleteObject(self, object_id):
  879. if not self.getController().getToolsEnabled():
  880. return
  881. node = self.getController().getScene().findObject(object_id)
  882. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  883. node = Selection.getSelectedObject(0)
  884. if node:
  885. op = GroupedOperation()
  886. op.addOperation(RemoveSceneNodeOperation(node))
  887. group_node = node.getParent()
  888. if group_node:
  889. # Note that at this point the node has not yet been deleted
  890. if len(group_node.getChildren()) <= 2 and group_node.callDecoration("isGroup"):
  891. op.addOperation(SetParentOperation(group_node.getChildren()[0], group_node.getParent()))
  892. op.addOperation(RemoveSceneNodeOperation(group_node))
  893. op.push()
  894. ## Create a number of copies of existing object.
  895. # \param object_id
  896. # \param count number of copies
  897. # \param min_offset minimum offset to other objects.
  898. @pyqtSlot("quint64", int)
  899. @deprecated("Use CuraActions::multiplySelection", "2.6")
  900. def multiplyObject(self, object_id, count, min_offset = 8):
  901. node = self.getController().getScene().findObject(object_id)
  902. if not node:
  903. node = Selection.getSelectedObject(0)
  904. while node.getParent() and node.getParent().callDecoration("isGroup"):
  905. node = node.getParent()
  906. job = MultiplyObjectsJob([node], count, min_offset)
  907. job.start()
  908. return
  909. ## Center object on platform.
  910. @pyqtSlot("quint64")
  911. @deprecated("Use CuraActions::centerSelection", "2.6")
  912. def centerObject(self, object_id):
  913. node = self.getController().getScene().findObject(object_id)
  914. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  915. node = Selection.getSelectedObject(0)
  916. if not node:
  917. return
  918. if node.getParent() and node.getParent().callDecoration("isGroup"):
  919. node = node.getParent()
  920. if node:
  921. op = SetTransformOperation(node, Vector())
  922. op.push()
  923. ## Select all nodes containing mesh data in the scene.
  924. @pyqtSlot()
  925. def selectAll(self):
  926. if not self.getController().getToolsEnabled():
  927. return
  928. Selection.clear()
  929. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  930. if not isinstance(node, SceneNode):
  931. continue
  932. if not node.getMeshData() and not node.callDecoration("isGroup"):
  933. continue # Node that doesnt have a mesh and is not a group.
  934. if node.getParent() and node.getParent().callDecoration("isGroup") or node.getParent().callDecoration("isSliceable"):
  935. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  936. if not node.isSelectable():
  937. continue # i.e. node with layer data
  938. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  939. continue # i.e. node with layer data
  940. Selection.add(node)
  941. ## Reset all translation on nodes with mesh data.
  942. @pyqtSlot()
  943. def resetAllTranslation(self):
  944. Logger.log("i", "Resetting all scene translations")
  945. nodes = []
  946. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  947. if not isinstance(node, SceneNode):
  948. continue
  949. if not node.getMeshData() and not node.callDecoration("isGroup"):
  950. continue # Node that doesnt have a mesh and is not a group.
  951. if node.getParent() and node.getParent().callDecoration("isGroup"):
  952. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  953. if not node.isSelectable():
  954. continue # i.e. node with layer data
  955. nodes.append(node)
  956. if nodes:
  957. op = GroupedOperation()
  958. for node in nodes:
  959. # Ensure that the object is above the build platform
  960. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  961. if node.getBoundingBox():
  962. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  963. else:
  964. center_y = 0
  965. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0)))
  966. op.push()
  967. ## Reset all transformations on nodes with mesh data.
  968. @pyqtSlot()
  969. def resetAll(self):
  970. Logger.log("i", "Resetting all scene transformations")
  971. nodes = []
  972. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  973. if not isinstance(node, SceneNode):
  974. continue
  975. if not node.getMeshData() and not node.callDecoration("isGroup"):
  976. continue # Node that doesnt have a mesh and is not a group.
  977. if node.getParent() and node.getParent().callDecoration("isGroup"):
  978. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  979. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  980. continue # i.e. node with layer data
  981. nodes.append(node)
  982. if nodes:
  983. op = GroupedOperation()
  984. for node in nodes:
  985. # Ensure that the object is above the build platform
  986. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  987. if node.getBoundingBox():
  988. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  989. else:
  990. center_y = 0
  991. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0), Quaternion(), Vector(1, 1, 1)))
  992. op.push()
  993. ## Arrange all objects.
  994. @pyqtSlot()
  995. def arrangeObjectsToAllBuildPlates(self):
  996. nodes = []
  997. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  998. if not isinstance(node, SceneNode):
  999. continue
  1000. if not node.getMeshData() and not node.callDecoration("isGroup"):
  1001. continue # Node that doesnt have a mesh and is not a group.
  1002. if node.getParent() and node.getParent().callDecoration("isGroup"):
  1003. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  1004. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1005. continue # i.e. node with layer data
  1006. # Skip nodes that are too big
  1007. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1008. nodes.append(node)
  1009. job = ArrangeObjectsAllBuildPlatesJob(nodes)
  1010. job.start()
  1011. self.getCuraSceneController().setActiveBuildPlate(0) # Select first build plate
  1012. # Single build plate
  1013. @pyqtSlot()
  1014. def arrangeAll(self):
  1015. nodes = []
  1016. active_build_plate = self.getMultiBuildPlateModel().activeBuildPlate
  1017. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1018. if not isinstance(node, SceneNode):
  1019. continue
  1020. if not node.getMeshData() and not node.callDecoration("isGroup"):
  1021. continue # Node that doesnt have a mesh and is not a group.
  1022. if node.getParent() and node.getParent().callDecoration("isGroup"):
  1023. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  1024. if not node.isSelectable():
  1025. continue # i.e. node with layer data
  1026. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1027. continue # i.e. node with layer data
  1028. if node.callDecoration("getBuildPlateNumber") == active_build_plate:
  1029. # Skip nodes that are too big
  1030. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1031. nodes.append(node)
  1032. self.arrange(nodes, fixed_nodes = [])
  1033. ## Arrange a set of nodes given a set of fixed nodes
  1034. # \param nodes nodes that we have to place
  1035. # \param fixed_nodes nodes that are placed in the arranger before finding spots for nodes
  1036. def arrange(self, nodes, fixed_nodes):
  1037. min_offset = self.getBuildVolume().getEdgeDisallowedSize() + 2 # Allow for some rounding errors
  1038. job = ArrangeObjectsJob(nodes, fixed_nodes, min_offset = max(min_offset, 8))
  1039. job.start()
  1040. ## Reload all mesh data on the screen from file.
  1041. @pyqtSlot()
  1042. def reloadAll(self):
  1043. Logger.log("i", "Reloading all loaded mesh data.")
  1044. nodes = []
  1045. has_merged_nodes = False
  1046. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1047. if not isinstance(node, CuraSceneNode) or not node.getMeshData() :
  1048. if node.getName() == "MergedMesh":
  1049. has_merged_nodes = True
  1050. continue
  1051. nodes.append(node)
  1052. if not nodes:
  1053. return
  1054. for node in nodes:
  1055. file_name = node.getMeshData().getFileName()
  1056. if file_name:
  1057. job = ReadMeshJob(file_name)
  1058. job._node = node
  1059. job.finished.connect(self._reloadMeshFinished)
  1060. if has_merged_nodes:
  1061. job.finished.connect(self.updateOriginOfMergedMeshes)
  1062. job.start()
  1063. else:
  1064. Logger.log("w", "Unable to reload data because we don't have a filename.")
  1065. ## Get logging data of the backend engine
  1066. # \returns \type{string} Logging data
  1067. @pyqtSlot(result = str)
  1068. def getEngineLog(self):
  1069. log = ""
  1070. for entry in self.getBackend().getLog():
  1071. log += entry.decode()
  1072. return log
  1073. @pyqtSlot("QStringList")
  1074. def setExpandedCategories(self, categories):
  1075. categories = list(set(categories))
  1076. categories.sort()
  1077. joined = ";".join(categories)
  1078. if joined != self.getPreferences().getValue("cura/categories_expanded"):
  1079. self.getPreferences().setValue("cura/categories_expanded", joined)
  1080. self.expandedCategoriesChanged.emit()
  1081. expandedCategoriesChanged = pyqtSignal()
  1082. @pyqtProperty("QStringList", notify = expandedCategoriesChanged)
  1083. def expandedCategories(self):
  1084. return self.getPreferences().getValue("cura/categories_expanded").split(";")
  1085. @pyqtSlot()
  1086. def mergeSelected(self):
  1087. self.groupSelected()
  1088. try:
  1089. group_node = Selection.getAllSelectedObjects()[0]
  1090. except Exception as e:
  1091. Logger.log("e", "mergeSelected: Exception: %s", e)
  1092. return
  1093. meshes = [node.getMeshData() for node in group_node.getAllChildren() if node.getMeshData()]
  1094. # Compute the center of the objects
  1095. object_centers = []
  1096. # Forget about the translation that the original objects have
  1097. zero_translation = Matrix(data=numpy.zeros(3))
  1098. for mesh, node in zip(meshes, group_node.getChildren()):
  1099. transformation = node.getLocalTransformation()
  1100. transformation.setTranslation(zero_translation)
  1101. transformed_mesh = mesh.getTransformed(transformation)
  1102. center = transformed_mesh.getCenterPosition()
  1103. if center is not None:
  1104. object_centers.append(center)
  1105. if object_centers and len(object_centers) > 0:
  1106. middle_x = sum([v.x for v in object_centers]) / len(object_centers)
  1107. middle_y = sum([v.y for v in object_centers]) / len(object_centers)
  1108. middle_z = sum([v.z for v in object_centers]) / len(object_centers)
  1109. offset = Vector(middle_x, middle_y, middle_z)
  1110. else:
  1111. offset = Vector(0, 0, 0)
  1112. # Move each node to the same position.
  1113. for mesh, node in zip(meshes, group_node.getChildren()):
  1114. transformation = node.getLocalTransformation()
  1115. transformation.setTranslation(zero_translation)
  1116. transformed_mesh = mesh.getTransformed(transformation)
  1117. # Align the object around its zero position
  1118. # and also apply the offset to center it inside the group.
  1119. node.setPosition(-transformed_mesh.getZeroPosition() - offset)
  1120. # Use the previously found center of the group bounding box as the new location of the group
  1121. group_node.setPosition(group_node.getBoundingBox().center)
  1122. group_node.setName("MergedMesh") # add a specific name to distinguish this node
  1123. ## Updates origin position of all merged meshes
  1124. # \param jobNode \type{Job} empty object which passed which is required by JobQueue
  1125. def updateOriginOfMergedMeshes(self, jobNode):
  1126. group_nodes = []
  1127. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1128. if isinstance(node, CuraSceneNode) and node.getName() == "MergedMesh":
  1129. #checking by name might be not enough, the merged mesh should has "GroupDecorator" decorator
  1130. for decorator in node.getDecorators():
  1131. if isinstance(decorator, GroupDecorator):
  1132. group_nodes.append(node)
  1133. break
  1134. for group_node in group_nodes:
  1135. meshes = [node.getMeshData() for node in group_node.getAllChildren() if node.getMeshData()]
  1136. # Compute the center of the objects
  1137. object_centers = []
  1138. # Forget about the translation that the original objects have
  1139. zero_translation = Matrix(data=numpy.zeros(3))
  1140. for mesh, node in zip(meshes, group_node.getChildren()):
  1141. transformation = node.getLocalTransformation()
  1142. transformation.setTranslation(zero_translation)
  1143. transformed_mesh = mesh.getTransformed(transformation)
  1144. center = transformed_mesh.getCenterPosition()
  1145. if center is not None:
  1146. object_centers.append(center)
  1147. if object_centers and len(object_centers) > 0:
  1148. middle_x = sum([v.x for v in object_centers]) / len(object_centers)
  1149. middle_y = sum([v.y for v in object_centers]) / len(object_centers)
  1150. middle_z = sum([v.z for v in object_centers]) / len(object_centers)
  1151. offset = Vector(middle_x, middle_y, middle_z)
  1152. else:
  1153. offset = Vector(0, 0, 0)
  1154. # Move each node to the same position.
  1155. for mesh, node in zip(meshes, group_node.getChildren()):
  1156. transformation = node.getLocalTransformation()
  1157. transformation.setTranslation(zero_translation)
  1158. transformed_mesh = mesh.getTransformed(transformation)
  1159. # Align the object around its zero position
  1160. # and also apply the offset to center it inside the group.
  1161. node.setPosition(-transformed_mesh.getZeroPosition() - offset)
  1162. # Use the previously found center of the group bounding box as the new location of the group
  1163. group_node.setPosition(group_node.getBoundingBox().center)
  1164. @pyqtSlot()
  1165. def groupSelected(self):
  1166. # Create a group-node
  1167. group_node = CuraSceneNode()
  1168. group_decorator = GroupDecorator()
  1169. group_node.addDecorator(group_decorator)
  1170. group_node.addDecorator(ConvexHullDecorator())
  1171. group_node.addDecorator(BuildPlateDecorator(self.getMultiBuildPlateModel().activeBuildPlate))
  1172. group_node.setParent(self.getController().getScene().getRoot())
  1173. group_node.setSelectable(True)
  1174. center = Selection.getSelectionCenter()
  1175. group_node.setPosition(center)
  1176. group_node.setCenterPosition(center)
  1177. # Remove nodes that are directly parented to another selected node from the selection so they remain parented
  1178. selected_nodes = Selection.getAllSelectedObjects().copy()
  1179. for node in selected_nodes:
  1180. if node.getParent() in selected_nodes and not node.getParent().callDecoration("isGroup"):
  1181. Selection.remove(node)
  1182. # Move selected nodes into the group-node
  1183. Selection.applyOperation(SetParentOperation, group_node)
  1184. # Deselect individual nodes and select the group-node instead
  1185. for node in group_node.getChildren():
  1186. Selection.remove(node)
  1187. Selection.add(group_node)
  1188. @pyqtSlot()
  1189. def ungroupSelected(self):
  1190. selected_objects = Selection.getAllSelectedObjects().copy()
  1191. for node in selected_objects:
  1192. if node.callDecoration("isGroup"):
  1193. op = GroupedOperation()
  1194. group_parent = node.getParent()
  1195. children = node.getChildren().copy()
  1196. for child in children:
  1197. # Ungroup only 1 level deep
  1198. if child.getParent() != node:
  1199. continue
  1200. # Set the parent of the children to the parent of the group-node
  1201. op.addOperation(SetParentOperation(child, group_parent))
  1202. # Add all individual nodes to the selection
  1203. Selection.add(child)
  1204. op.push()
  1205. # Note: The group removes itself from the scene once all its children have left it,
  1206. # see GroupDecorator._onChildrenChanged
  1207. def _createSplashScreen(self):
  1208. if self._is_headless:
  1209. return None
  1210. return CuraSplashScreen.CuraSplashScreen()
  1211. def _onActiveMachineChanged(self):
  1212. pass
  1213. fileLoaded = pyqtSignal(str)
  1214. fileCompleted = pyqtSignal(str)
  1215. def _reloadMeshFinished(self, job):
  1216. # TODO; This needs to be fixed properly. We now make the assumption that we only load a single mesh!
  1217. job_result = job.getResult()
  1218. if len(job_result) == 0:
  1219. Logger.log("e", "Reloading the mesh failed.")
  1220. return
  1221. mesh_data = job_result[0].getMeshData()
  1222. if not mesh_data:
  1223. Logger.log("w", "Could not find a mesh in reloaded node.")
  1224. return
  1225. job._node.setMeshData(mesh_data)
  1226. def _openFile(self, filename):
  1227. self.readLocalFile(QUrl.fromLocalFile(filename))
  1228. def _addProfileReader(self, profile_reader):
  1229. # TODO: Add the profile reader to the list of plug-ins that can be used when importing profiles.
  1230. pass
  1231. def _addProfileWriter(self, profile_writer):
  1232. pass
  1233. @pyqtSlot("QSize")
  1234. def setMinimumWindowSize(self, size):
  1235. main_window = self.getMainWindow()
  1236. if main_window:
  1237. main_window.setMinimumSize(size)
  1238. def getBuildVolume(self):
  1239. return self._volume
  1240. additionalComponentsChanged = pyqtSignal(str, arguments = ["areaId"])
  1241. @pyqtProperty("QVariantMap", notify = additionalComponentsChanged)
  1242. def additionalComponents(self):
  1243. return self._additional_components
  1244. ## Add a component to a list of components to be reparented to another area in the GUI.
  1245. # The actual reparenting is done by the area itself.
  1246. # \param area_id \type{str} Identifying name of the area to which the component should be reparented
  1247. # \param component \type{QQuickComponent} The component that should be reparented
  1248. @pyqtSlot(str, "QVariant")
  1249. def addAdditionalComponent(self, area_id, component):
  1250. if area_id not in self._additional_components:
  1251. self._additional_components[area_id] = []
  1252. self._additional_components[area_id].append(component)
  1253. self.additionalComponentsChanged.emit(area_id)
  1254. @pyqtSlot(str)
  1255. def log(self, msg):
  1256. Logger.log("d", msg)
  1257. openProjectFile = pyqtSignal(QUrl, arguments = ["project_file"]) # Emitted when a project file is about to open.
  1258. @pyqtSlot(QUrl, bool)
  1259. def readLocalFile(self, file, skip_project_file_check = False):
  1260. if not file.isValid():
  1261. return
  1262. scene = self.getController().getScene()
  1263. for node in DepthFirstIterator(scene.getRoot()):
  1264. if node.callDecoration("isBlockSlicing"):
  1265. self.deleteAll()
  1266. break
  1267. if not skip_project_file_check and self.checkIsValidProjectFile(file):
  1268. self.callLater(self.openProjectFile.emit, file)
  1269. return
  1270. if self.getPreferences().getValue("cura/select_models_on_load"):
  1271. Selection.clear()
  1272. f = file.toLocalFile()
  1273. extension = os.path.splitext(f)[1]
  1274. extension = extension.lower()
  1275. filename = os.path.basename(f)
  1276. if len(self._currently_loading_files) > 0:
  1277. # If a non-slicable file is already being loaded, we prevent loading of any further non-slicable files
  1278. if extension in self._non_sliceable_extensions:
  1279. message = Message(
  1280. self._i18n_catalog.i18nc("@info:status",
  1281. "Only one G-code file can be loaded at a time. Skipped importing {0}",
  1282. filename), title = self._i18n_catalog.i18nc("@info:title", "Warning"))
  1283. message.show()
  1284. return
  1285. # If file being loaded is non-slicable file, then prevent loading of any other files
  1286. extension = os.path.splitext(self._currently_loading_files[0])[1]
  1287. extension = extension.lower()
  1288. if extension in self._non_sliceable_extensions:
  1289. message = Message(
  1290. self._i18n_catalog.i18nc("@info:status",
  1291. "Can't open any other file if G-code is loading. Skipped importing {0}",
  1292. filename), title = self._i18n_catalog.i18nc("@info:title", "Error"))
  1293. message.show()
  1294. return
  1295. self._currently_loading_files.append(f)
  1296. if extension in self._non_sliceable_extensions:
  1297. self.deleteAll(only_selectable = False)
  1298. job = ReadMeshJob(f)
  1299. job.finished.connect(self._readMeshFinished)
  1300. job.start()
  1301. def _readMeshFinished(self, job):
  1302. nodes = job.getResult()
  1303. file_name = job.getFileName()
  1304. file_name_lower = file_name.lower()
  1305. file_extension = file_name_lower.split(".")[-1]
  1306. self._currently_loading_files.remove(file_name)
  1307. self.fileLoaded.emit(file_name)
  1308. target_build_plate = self.getMultiBuildPlateModel().activeBuildPlate
  1309. root = self.getController().getScene().getRoot()
  1310. fixed_nodes = []
  1311. for node_ in DepthFirstIterator(root):
  1312. if node_.callDecoration("isSliceable") and node_.callDecoration("getBuildPlateNumber") == target_build_plate:
  1313. fixed_nodes.append(node_)
  1314. global_container_stack = self.getGlobalContainerStack()
  1315. machine_width = global_container_stack.getProperty("machine_width", "value")
  1316. machine_depth = global_container_stack.getProperty("machine_depth", "value")
  1317. arranger = Arrange.create(x = machine_width, y = machine_depth, fixed_nodes = fixed_nodes)
  1318. min_offset = 8
  1319. default_extruder_position = self.getMachineManager().defaultExtruderPosition
  1320. default_extruder_id = self._global_container_stack.extruders[default_extruder_position].getId()
  1321. select_models_on_load = self.getPreferences().getValue("cura/select_models_on_load")
  1322. for original_node in nodes:
  1323. # Create a CuraSceneNode just if the original node is not that type
  1324. if isinstance(original_node, CuraSceneNode):
  1325. node = original_node
  1326. else:
  1327. node = CuraSceneNode()
  1328. node.setMeshData(original_node.getMeshData())
  1329. #Setting meshdata does not apply scaling.
  1330. if(original_node.getScale() != Vector(1.0, 1.0, 1.0)):
  1331. node.scale(original_node.getScale())
  1332. node.setSelectable(True)
  1333. node.setName(os.path.basename(file_name))
  1334. self.getBuildVolume().checkBoundsAndUpdate(node)
  1335. is_non_sliceable = "." + file_extension in self._non_sliceable_extensions
  1336. if is_non_sliceable:
  1337. self.callLater(lambda: self.getController().setActiveView("SimulationView"))
  1338. block_slicing_decorator = BlockSlicingDecorator()
  1339. node.addDecorator(block_slicing_decorator)
  1340. else:
  1341. sliceable_decorator = SliceableObjectDecorator()
  1342. node.addDecorator(sliceable_decorator)
  1343. scene = self.getController().getScene()
  1344. # If there is no convex hull for the node, start calculating it and continue.
  1345. if not node.getDecorator(ConvexHullDecorator):
  1346. node.addDecorator(ConvexHullDecorator())
  1347. for child in node.getAllChildren():
  1348. if not child.getDecorator(ConvexHullDecorator):
  1349. child.addDecorator(ConvexHullDecorator())
  1350. if file_extension != "3mf":
  1351. if node.callDecoration("isSliceable"):
  1352. # Only check position if it's not already blatantly obvious that it won't fit.
  1353. if node.getBoundingBox() is None or self._volume.getBoundingBox() is None or node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1354. # Find node location
  1355. offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = min_offset)
  1356. # If a model is to small then it will not contain any points
  1357. if offset_shape_arr is None and hull_shape_arr is None:
  1358. Message(self._i18n_catalog.i18nc("@info:status", "The selected model was too small to load."),
  1359. title=self._i18n_catalog.i18nc("@info:title", "Warning")).show()
  1360. return
  1361. # Step is for skipping tests to make it a lot faster. it also makes the outcome somewhat rougher
  1362. arranger.findNodePlacement(node, offset_shape_arr, hull_shape_arr, step = 10)
  1363. # This node is deep copied from some other node which already has a BuildPlateDecorator, but the deepcopy
  1364. # of BuildPlateDecorator produces one that's associated with build plate -1. So, here we need to check if
  1365. # the BuildPlateDecorator exists or not and always set the correct build plate number.
  1366. build_plate_decorator = node.getDecorator(BuildPlateDecorator)
  1367. if build_plate_decorator is None:
  1368. build_plate_decorator = BuildPlateDecorator(target_build_plate)
  1369. node.addDecorator(build_plate_decorator)
  1370. build_plate_decorator.setBuildPlateNumber(target_build_plate)
  1371. op = AddSceneNodeOperation(node, scene.getRoot())
  1372. op.push()
  1373. node.callDecoration("setActiveExtruder", default_extruder_id)
  1374. scene.sceneChanged.emit(node)
  1375. if select_models_on_load:
  1376. Selection.add(node)
  1377. self.fileCompleted.emit(file_name)
  1378. def addNonSliceableExtension(self, extension):
  1379. self._non_sliceable_extensions.append(extension)
  1380. @pyqtSlot(str, result=bool)
  1381. def checkIsValidProjectFile(self, file_url):
  1382. """
  1383. Checks if the given file URL is a valid project file.
  1384. """
  1385. file_path = QUrl(file_url).toLocalFile()
  1386. workspace_reader = self.getWorkspaceFileHandler().getReaderForFile(file_path)
  1387. if workspace_reader is None:
  1388. return False # non-project files won't get a reader
  1389. try:
  1390. result = workspace_reader.preRead(file_path, show_dialog=False)
  1391. return result == WorkspaceReader.PreReadResult.accepted
  1392. except Exception as e:
  1393. Logger.logException("e", "Could not check file %s", file_url)
  1394. return False
  1395. def _onContextMenuRequested(self, x: float, y: float) -> None:
  1396. # Ensure we select the object if we request a context menu over an object without having a selection.
  1397. if not Selection.hasSelection():
  1398. node = self.getController().getScene().findObject(cast(SelectionPass, self.getRenderer().getRenderPass("selection")).getIdAtPosition(x, y))
  1399. if node:
  1400. parent = node.getParent()
  1401. while(parent and parent.callDecoration("isGroup")):
  1402. node = parent
  1403. parent = node.getParent()
  1404. Selection.add(node)
  1405. @pyqtSlot()
  1406. def showMoreInformationDialogForAnonymousDataCollection(self):
  1407. cast(SliceInfo, self._plugin_registry.getPluginObject("SliceInfoPlugin")).showMoreInfoDialog()
  1408. def addSidebarCustomMenuItem(self, menu_item: list) -> None:
  1409. self._sidebar_custom_menu_items.append(menu_item)
  1410. def getSidebarCustomMenuItems(self) -> list:
  1411. return self._sidebar_custom_menu_items