Browse Source

CURA-5164 The Preferences is not a singleton class anymore since in some point
several instances need to be created.

- In the ThreeMFWorkspaceReader we need to create some temporal
instances of Preferences that makes it not singleton anymore.

- The current preferences are kept in the Application class and so all
the calls to the preferences are changed to get the preferences from
Application.

- The method getInstance in Preferences is kept as deprecated since some
external plugins.

Diego Prado Gesto 6 years ago
parent
commit
43657010ba

+ 12 - 12
cura/CuraApplication.py

@@ -459,7 +459,7 @@ class CuraApplication(QtApplication):
             self._container_registry.loadAllMetadata()
 
         # set the setting version for Preferences
-        preferences = Preferences.getInstance()
+        preferences = self.getPreferences()
         preferences.addPreference("metadata/setting_version", 0)
         preferences.setValue("metadata/setting_version", self.SettingVersion) #Don't make it equal to the default so that the setting version always gets written to the file.
 
@@ -484,7 +484,7 @@ class CuraApplication(QtApplication):
         preferences.addPreference("view/filter_current_build_plate", False)
         preferences.addPreference("cura/sidebar_collapsed", False)
 
-        self._need_to_show_user_agreement = not Preferences.getInstance().getValue("general/accepted_user_agreement")
+        self._need_to_show_user_agreement = not self.getPreferences().getValue("general/accepted_user_agreement")
 
         for key in [
             "dialog_load_path",  # dialog_save_path is in LocalFileOutputDevicePlugin
@@ -546,7 +546,7 @@ class CuraApplication(QtApplication):
 
     def discardOrKeepProfileChanges(self):
         has_user_interaction = False
-        choice = Preferences.getInstance().getValue("cura/choice_on_profile_override")
+        choice = self.getPreferences().getValue("cura/choice_on_profile_override")
         if choice == "always_discard":
             # don't show dialog and DISCARD the profile
             self.discardOrKeepProfileChangesClosed("discard")
@@ -597,12 +597,12 @@ class CuraApplication(QtApplication):
 
     @pyqtSlot(str, result = QUrl)
     def getDefaultPath(self, key):
-        default_path = Preferences.getInstance().getValue("local_file/%s" % key)
+        default_path = self.getPreferences().getValue("local_file/%s" % key)
         return QUrl.fromLocalFile(default_path)
 
     @pyqtSlot(str, str)
     def setDefaultPath(self, key, default_path):
-        Preferences.getInstance().setValue("local_file/%s" % key, QUrl(default_path).toLocalFile())
+        self.getPreferences().setValue("local_file/%s" % key, QUrl(default_path).toLocalFile())
 
     ##  Handle loading of all plugin types (and the backend explicitly)
     #   \sa PluginRegistry
@@ -672,7 +672,7 @@ class CuraApplication(QtApplication):
         # Initialize setting visibility presets model
         self._setting_visibility_presets_model = SettingVisibilityPresetsModel(self)
         default_visibility_profile = self._setting_visibility_presets_model.getItem(0)
-        Preferences.getInstance().setDefault("general/visible_settings", ";".join(default_visibility_profile["settings"]))
+        self.getPreferences().setDefault("general/visible_settings", ";".join(default_visibility_profile["settings"]))
 
         # Detect in which mode to run and execute that mode
         if self._is_headless:
@@ -934,7 +934,7 @@ class CuraApplication(QtApplication):
                     # Default
                     self.getController().setActiveTool("TranslateTool")
 
-            if Preferences.getInstance().getValue("view/center_on_select"):
+            if self.getPreferences().getValue("view/center_on_select"):
                 self._center_after_select = True
         else:
             if self.getController().getActiveTool():
@@ -1329,15 +1329,15 @@ class CuraApplication(QtApplication):
         categories = list(set(categories))
         categories.sort()
         joined = ";".join(categories)
-        if joined != Preferences.getInstance().getValue("cura/categories_expanded"):
-            Preferences.getInstance().setValue("cura/categories_expanded", joined)
+        if joined != self.getPreferences().getValue("cura/categories_expanded"):
+            self.getPreferences().setValue("cura/categories_expanded", joined)
             self.expandedCategoriesChanged.emit()
 
     expandedCategoriesChanged = pyqtSignal()
 
     @pyqtProperty("QStringList", notify = expandedCategoriesChanged)
     def expandedCategories(self):
-        return Preferences.getInstance().getValue("cura/categories_expanded").split(";")
+        return self.getPreferences().getValue("cura/categories_expanded").split(";")
 
     @pyqtSlot()
     def mergeSelected(self):
@@ -1600,8 +1600,8 @@ class CuraApplication(QtApplication):
 
         self.fileLoaded.emit(filename)
         arrange_objects_on_load = (
-            not Preferences.getInstance().getValue("cura/use_multi_build_plate") or
-            not Preferences.getInstance().getValue("cura/not_arrange_objects_on_load"))
+            not self.getPreferences().getValue("cura/use_multi_build_plate") or
+            not self.getPreferences().getValue("cura/not_arrange_objects_on_load"))
         target_build_plate = self.getMultiBuildPlateModel().activeBuildPlate if arrange_objects_on_load else -1
 
         root = self.getController().getScene().getRoot()

+ 2 - 2
cura/Machines/Models/SettingVisibilityPresetsModel.py

@@ -8,9 +8,9 @@ from configparser import ConfigParser
 
 from PyQt5.QtCore import pyqtProperty, Qt, pyqtSignal, pyqtSlot
 
+from UM.Application import Application
 from UM.Logger import Logger
 from UM.Qt.ListModel import ListModel
-from UM.Preferences import Preferences
 from UM.Resources import Resources
 from UM.MimeTypeDatabase import MimeTypeDatabase, MimeTypeNotFoundError
 
@@ -33,7 +33,7 @@ class SettingVisibilityPresetsModel(ListModel):
         basic_item = self.items[1]
         basic_visibile_settings = ";".join(basic_item["settings"])
 
-        self._preferences = Preferences.getInstance()
+        self._preferences = Application.getInstance().getPreferences()
         # Preference to store which preset is currently selected
         self._preferences.addPreference("cura/active_setting_visibility_preset", "basic")
         # Preference that stores the "custom" set so it can always be restored (even after a restart)

+ 2 - 3
cura/ObjectsModel.py

@@ -8,7 +8,6 @@ from UM.Qt.ListModel import ListModel
 from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
 from UM.Scene.SceneNode import SceneNode
 from UM.Scene.Selection import Selection
-from UM.Preferences import Preferences
 from UM.i18n import i18nCatalog
 
 catalog = i18nCatalog("cura")
@@ -20,7 +19,7 @@ class ObjectsModel(ListModel):
         super().__init__()
 
         Application.getInstance().getController().getScene().sceneChanged.connect(self._updateDelayed)
-        Preferences.getInstance().preferenceChanged.connect(self._updateDelayed)
+        Application.getInstance().getPreferences().preferenceChanged.connect(self._updateDelayed)
 
         self._update_timer = QTimer()
         self._update_timer.setInterval(100)
@@ -38,7 +37,7 @@ class ObjectsModel(ListModel):
 
     def _update(self, *args):
         nodes = []
-        filter_current_build_plate = Preferences.getInstance().getValue("view/filter_current_build_plate")
+        filter_current_build_plate = Application.getInstance().getPreferences().getValue("view/filter_current_build_plate")
         active_build_plate_number = self._build_plate_number
         group_nr = 1
         for node in DepthFirstIterator(Application.getInstance().getController().getScene().getRoot()):

+ 4 - 5
cura/PlatformPhysics.py

@@ -8,7 +8,6 @@ from UM.Scene.SceneNode import SceneNode
 from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
 from UM.Math.Vector import Vector
 from UM.Scene.Selection import Selection
-from UM.Preferences import Preferences
 
 from cura.Scene.ConvexHullDecorator import ConvexHullDecorator
 
@@ -36,8 +35,8 @@ class PlatformPhysics:
         self._max_overlap_checks = 10  # How many times should we try to find a new spot per tick?
         self._minimum_gap = 2  # It is a minimum distance (in mm) between two models, applicable for small models
 
-        Preferences.getInstance().addPreference("physics/automatic_push_free", True)
-        Preferences.getInstance().addPreference("physics/automatic_drop_down", True)
+        Application.getInstance().getPreferences().addPreference("physics/automatic_push_free", True)
+        Application.getInstance().getPreferences().addPreference("physics/automatic_drop_down", True)
 
     def _onSceneChanged(self, source):
         if not source.getMeshData():
@@ -71,7 +70,7 @@ class PlatformPhysics:
             # Move it downwards if bottom is above platform
             move_vector = Vector()
 
-            if Preferences.getInstance().getValue("physics/automatic_drop_down") and not (node.getParent() and node.getParent().callDecoration("isGroup") or node.getParent() != root) and node.isEnabled(): #If an object is grouped, don't move it down
+            if Application.getInstance().getPreferences().getValue("physics/automatic_drop_down") and not (node.getParent() and node.getParent().callDecoration("isGroup") or node.getParent() != root) and node.isEnabled(): #If an object is grouped, don't move it down
                 z_offset = node.callDecoration("getZOffset") if node.getDecorator(ZOffsetDecorator.ZOffsetDecorator) else 0
                 move_vector = move_vector.set(y = -bbox.bottom + z_offset)
 
@@ -80,7 +79,7 @@ class PlatformPhysics:
                 node.addDecorator(ConvexHullDecorator())
 
             # only push away objects if this node is a printing mesh
-            if not node.callDecoration("isNonPrintingMesh") and Preferences.getInstance().getValue("physics/automatic_push_free"):
+            if not node.callDecoration("isNonPrintingMesh") and Application.getInstance().getPreferences().getValue("physics/automatic_push_free"):
                 # Check for collisions between convex hulls
                 for other_node in BreadthFirstIterator(root):
                     # Ignore root, ourselves and anything that is not a normal SceneNode.

+ 3 - 4
cura/PrintInformation.py

@@ -12,7 +12,6 @@ from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty, pyqtSlot
 
 from UM.i18n import i18nCatalog
 from UM.Logger import Logger
-from UM.Preferences import Preferences
 from UM.Qt.Duration import Duration
 from UM.Scene.SceneNode import SceneNode
 
@@ -80,7 +79,7 @@ class PrintInformation(QObject):
         self._application.workspaceLoaded.connect(self.setProjectName)
         self._multi_build_plate_model.activeBuildPlateChanged.connect(self._onActiveBuildPlateChanged)
 
-        Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
+        self._application.getInstance().getPreferences().preferenceChanged.connect(self._onPreferencesChanged)
 
         self._application.getMachineManager().rootMaterialChanged.connect(self._onActiveMaterialsChanged)
         self._onActiveMaterialsChanged()
@@ -208,7 +207,7 @@ class PrintInformation(QObject):
         self._material_costs[build_plate_number] = []
         self._material_names[build_plate_number] = []
 
-        material_preference_values = json.loads(Preferences.getInstance().getValue("cura/material_settings"))
+        material_preference_values = json.loads(self._application.getInstance().getPreferences().getValue("cura/material_settings"))
 
         extruder_stacks = global_stack.extruders
         for position, extruder_stack in extruder_stacks.items():
@@ -299,7 +298,7 @@ class PrintInformation(QObject):
         self._setAbbreviatedMachineName()
         if self._pre_sliced:
             self._job_name = catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
-        elif Preferences.getInstance().getValue("cura/jobname_prefix"):
+        elif self._application.getInstance().getPreferences().getValue("cura/jobname_prefix"):
             # Don't add abbreviation if it already has the exact same abbreviation.
             if base_name.startswith(self._abbr_machine + "_"):
                 self._job_name = base_name

+ 14 - 15
cura/Settings/MachineManager.py

@@ -16,7 +16,6 @@ from UM.FlameProfiler import pyqtSlot
 from UM import Util
 
 from UM.Application import Application
-from UM.Preferences import Preferences
 from UM.Logger import Logger
 from UM.Message import Message
 
@@ -97,12 +96,12 @@ class MachineManager(QObject):
         ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeStackChanged)
         self.activeStackChanged.connect(self.activeStackValueChanged)
 
-        Preferences.getInstance().addPreference("cura/active_machine", "")
+        self._application.getPreferences().addPreference("cura/active_machine", "")
 
         self._global_event_keys = set()
 
         self._printer_output_devices = []  # type: List[PrinterOutputDevice]
-        Application.getInstance().getOutputDeviceManager().outputDevicesChanged.connect(self._onOutputDevicesChanged)
+        self._application.getOutputDeviceManager().outputDevicesChanged.connect(self._onOutputDevicesChanged)
         # There might already be some output devices by the time the signal is connected
         self._onOutputDevicesChanged()
 
@@ -163,7 +162,7 @@ class MachineManager(QObject):
     rootMaterialChanged = pyqtSignal()
 
     def setInitialActiveMachine(self) -> None:
-        active_machine_id = Preferences.getInstance().getValue("cura/active_machine")
+        active_machine_id = self._application.getPreferences().getValue("cura/active_machine")
         if active_machine_id != "" and ContainerRegistry.getInstance().findContainerStacksMetadata(id = active_machine_id):
             # An active machine was saved, so restore it.
             self.setActiveMachine(active_machine_id)
@@ -172,7 +171,7 @@ class MachineManager(QObject):
 
     def _onOutputDevicesChanged(self) -> None:
         self._printer_output_devices = []
-        for printer_output_device in Application.getInstance().getOutputDeviceManager().getOutputDevices():
+        for printer_output_device in self._application.getOutputDeviceManager().getOutputDevices():
             if isinstance(printer_output_device, PrinterOutputDevice):
                 self._printer_output_devices.append(printer_output_device)
 
@@ -239,7 +238,7 @@ class MachineManager(QObject):
                 extruder_stack.containersChanged.disconnect(self._onContainersChanged)
 
         # Update the local global container stack reference
-        self._global_container_stack = Application.getInstance().getGlobalContainerStack()
+        self._global_container_stack = self._application.getGlobalContainerStack()
         if self._global_container_stack:
             self.updateDefaultExtruder()
             self.updateNumberExtrudersEnabled()
@@ -247,7 +246,7 @@ class MachineManager(QObject):
 
         # after switching the global stack we reconnect all the signals and set the variant and material references
         if self._global_container_stack:
-            Preferences.getInstance().setValue("cura/active_machine", self._global_container_stack.getId())
+            self._application.getPreferences().setValue("cura/active_machine", self._global_container_stack.getId())
 
             self._global_container_stack.nameChanged.connect(self._onMachineNameChanged)
             self._global_container_stack.containersChanged.connect(self._onContainersChanged)
@@ -271,7 +270,7 @@ class MachineManager(QObject):
 
             if self._global_container_stack.getId() in self.machine_extruder_material_update_dict:
                 for func in self.machine_extruder_material_update_dict[self._global_container_stack.getId()]:
-                    Application.getInstance().callLater(func)
+                    self._application.callLater(func)
                 del self.machine_extruder_material_update_dict[self._global_container_stack.getId()]
 
         self.activeQualityGroupChanged.emit()
@@ -361,7 +360,7 @@ class MachineManager(QObject):
         global_stack = containers[0]
         ExtruderManager.getInstance().setActiveExtruderIndex(0)  # Switch to first extruder
         self._global_container_stack = global_stack
-        Application.getInstance().setGlobalContainerStack(global_stack)
+        self._application.setGlobalContainerStack(global_stack)
         ExtruderManager.getInstance()._globalContainerStackChanged()
         self._initMachineState(containers[0])
         self._onGlobalContainerChanged()
@@ -835,7 +834,7 @@ class MachineManager(QObject):
     ##  Set the amount of extruders on the active machine (global stack)
     #   \param extruder_count int the number of extruders to set
     def setActiveMachineExtruderCount(self, extruder_count: int) -> None:
-        extruder_manager = Application.getInstance().getExtruderManager()
+        extruder_manager = self._application.getExtruderManager()
 
         definition_changes_container = self._global_container_stack.definitionChanges
         if not self._global_container_stack or definition_changes_container == self._empty_definition_changes_container:
@@ -852,7 +851,7 @@ class MachineManager(QObject):
         self.correctExtruderSettings()
 
         # Check to see if any objects are set to print with an extruder that will no longer exist
-        root_node = Application.getInstance().getController().getScene().getRoot()
+        root_node = self._application.getController().getScene().getRoot()
         for node in DepthFirstIterator(root_node):
             if node.getMeshData():
                 extruder_nr = node.callDecoration("getActiveExtruderPosition")
@@ -885,7 +884,7 @@ class MachineManager(QObject):
                 global_user_container.removeInstance(setting_key)
 
         # Signal that the global stack has changed
-        Application.getInstance().globalContainerStackChanged.emit()
+        self._application.globalContainerStackChanged.emit()
         self.forceUpdateAllSettings()
 
     @pyqtSlot(int, result = QObject)
@@ -1117,7 +1116,7 @@ class MachineManager(QObject):
     def _setGlobalVariant(self, container_node):
         self._global_container_stack.variant = container_node.getContainer()
         if not self._global_container_stack.variant:
-            self._global_container_stack.variant = Application.getInstance().empty_variant_container
+            self._global_container_stack.variant = self._application.empty_variant_container
 
     def _setMaterial(self, position, container_node = None):
         if container_node and container_node.getContainer():
@@ -1359,7 +1358,7 @@ class MachineManager(QObject):
             self._setQualityGroup(quality_group)
 
         # See if we need to show the Discard or Keep changes screen
-        if not no_dialog and self.hasUserSettings and Preferences.getInstance().getValue("cura/active_mode") == 1:
+        if not no_dialog and self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
             self._application.discardOrKeepProfileChanges()
 
     @pyqtProperty(QObject, fset = setQualityGroup, notify = activeQualityGroupChanged)
@@ -1373,7 +1372,7 @@ class MachineManager(QObject):
             self._setQualityChangesGroup(quality_changes_group)
 
         # See if we need to show the Discard or Keep changes screen
-        if not no_dialog and self.hasUserSettings and Preferences.getInstance().getValue("cura/active_mode") == 1:
+        if not no_dialog and self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
             self._application.discardOrKeepProfileChanges()
 
     @pyqtSlot()

+ 2 - 2
plugins/3MFReader/ThreeMFWorkspaceReader.py

@@ -456,7 +456,7 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
                 num_visible_settings = len(visible_settings_string.split(";"))
             active_mode = temp_preferences.getValue("cura/active_mode")
             if not active_mode:
-                active_mode = Preferences.getInstance().getValue("cura/active_mode")
+                active_mode = Application.getInstance().getPreferences().getValue("cura/active_mode")
         except KeyError:
             # If there is no preferences file, it's not a workspace, so notify user of failure.
             Logger.log("w", "File %s is not a valid workspace.", file_name)
@@ -575,7 +575,7 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
         temp_preferences.deserialize(serialized)
 
         # Copy a number of settings from the temp preferences to the global
-        global_preferences = Preferences.getInstance()
+        global_preferences = application.getInstance().getPreferences()
 
         visible_settings = temp_preferences.getValue("general/visible_settings")
         if visible_settings is None:

+ 1 - 1
plugins/3MFWriter/ThreeMFWorkspaceWriter.py

@@ -51,7 +51,7 @@ class ThreeMFWorkspaceWriter(WorkspaceWriter):
                 self._writeContainerToArchive(container, archive)
 
         # Write preferences to archive
-        original_preferences = Preferences.getInstance() #Copy only the preferences that we use to the workspace.
+        original_preferences = Application.getInstance().getPreferences() #Copy only the preferences that we use to the workspace.
         temp_preferences = Preferences()
         for preference in {"general/visible_settings", "cura/active_mode", "cura/categories_expanded"}:
             temp_preferences.addPreference(preference, None)

+ 4 - 5
plugins/AutoSave/AutoSave.py

@@ -4,7 +4,6 @@
 from PyQt5.QtCore import QTimer
 
 from UM.Extension import Extension
-from UM.Preferences import Preferences
 from UM.Application import Application
 from UM.Resources import Resources
 from UM.Logger import Logger
@@ -14,14 +13,14 @@ class AutoSave(Extension):
     def __init__(self):
         super().__init__()
 
-        Preferences.getInstance().preferenceChanged.connect(self._triggerTimer)
+        Application.getInstance().getPreferences().preferenceChanged.connect(self._triggerTimer)
 
         self._global_stack = None
 
-        Preferences.getInstance().addPreference("cura/autosave_delay", 1000 * 10)
+        Application.getInstance().getPreferences().addPreference("cura/autosave_delay", 1000 * 10)
 
         self._change_timer = QTimer()
-        self._change_timer.setInterval(Preferences.getInstance().getValue("cura/autosave_delay"))
+        self._change_timer.setInterval(Application.getInstance().getPreferences().getValue("cura/autosave_delay"))
         self._change_timer.setSingleShot(True)
 
         self._saving = False
@@ -72,6 +71,6 @@ class AutoSave(Extension):
 
         Application.getInstance().saveSettings()
 
-        Preferences.getInstance().writeToFile(Resources.getStoragePath(Resources.Preferences, Application.getInstance().getApplicationName() + ".cfg"))
+        Application.getInstance().getPreferences().writeToFile(Resources.getStoragePath(Resources.Preferences, Application.getInstance().getApplicationName() + ".cfg"))
 
         self._saving = False

+ 4 - 5
plugins/ChangeLogPlugin/ChangeLog.py

@@ -3,7 +3,6 @@
 
 from UM.i18n import i18nCatalog
 from UM.Extension import Extension
-from UM.Preferences import Preferences
 from UM.Application import Application
 from UM.PluginRegistry import PluginRegistry
 from UM.Version import Version
@@ -29,7 +28,7 @@ class ChangeLog(Extension, QObject,):
 
         self._change_logs = None
         Application.getInstance().engineCreatedSignal.connect(self._onEngineCreated)
-        Preferences.getInstance().addPreference("general/latest_version_changelog_shown", "2.0.0") #First version of CURA with uranium
+        Application.getInstance().getPreferences().addPreference("general/latest_version_changelog_shown", "2.0.0") #First version of CURA with uranium
         self.addMenuItem(catalog.i18nc("@item:inmenu", "Show Changelog"), self.showChangelog)
 
     def getChangeLogs(self):
@@ -79,12 +78,12 @@ class ChangeLog(Extension, QObject,):
         if not self._current_app_version:
             return #We're on dev branch.
 
-        if Preferences.getInstance().getValue("general/latest_version_changelog_shown") == "master":
+        if Application.getInstance().getPreferences().getValue("general/latest_version_changelog_shown") == "master":
             latest_version_shown = Version("0.0.0")
         else:
-            latest_version_shown = Version(Preferences.getInstance().getValue("general/latest_version_changelog_shown"))
+            latest_version_shown = Version(Application.getInstance().getPreferences().getValue("general/latest_version_changelog_shown"))
 
-        Preferences.getInstance().setValue("general/latest_version_changelog_shown", Application.getInstance().getVersion())
+        Application.getInstance().getPreferences().setValue("general/latest_version_changelog_shown", Application.getInstance().getVersion())
 
         # Do not show the changelog when there is no global container stack
         # This implies we are running Cura for the first time.

Some files were not shown because too many files changed in this diff