CuraApplication.py 107 KB

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