CuraApplication.py 111 KB

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