CuraApplication.py 85 KB

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