CuraApplication.py 101 KB

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