CuraApplication.py 112 KB

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