CuraApplication.py 103 KB

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