CuraApplication.py 109 KB

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