CuraApplication.py 103 KB

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