CuraApplication.py 112 KB

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