[pitivi] preset: Reuse the logic which generates unique preset names



commit 7c0686fabe71727fd4d3542c5bac4451e761a974
Author: Alexandru Băluț <alexandru balut gmail com>
Date:   Thu May 21 16:34:28 2015 +0200

    preset: Reuse the logic which generates unique preset names
    
    Differential Revision: https://phabricator.freedesktop.org/D362
    Reviewed-by: Thibault Saunier <tsaunier gnome org>

 pitivi/preset.py              |   49 +++++++++++++++++++---------------------
 pitivi/project.py             |   16 +-----------
 pitivi/render.py              |   27 ++++++----------------
 tests/Makefile.am             |    1 -
 tests/test_preset.py          |   39 +++++++++++---------------------
 tests/test_projectsettings.py |   46 --------------------------------------
 6 files changed, 46 insertions(+), 132 deletions(-)
---
diff --git a/pitivi/preset.py b/pitivi/preset.py
index 558fa26..ca6842f 100644
--- a/pitivi/preset.py
+++ b/pitivi/preset.py
@@ -34,11 +34,6 @@ from pitivi.utils import system
 from pitivi.utils.loggable import Loggable
 
 
-# Presets created with this name by the app should have "volatile": True
-# so they cannot be saved.
-CUSTOM_PRESET_NAME = _("Custom")
-
-
 class DuplicatePresetNameException(Exception):
 
     """Raised when an operation would result in a duplicated preset name."""
@@ -104,7 +99,6 @@ class PresetManager(Loggable):
             self.savePreset(preset_name)
 
     def savePreset(self, preset_name):
-        assert preset_name != CUSTOM_PRESET_NAME
         if not os.path.exists(self.user_path):
             os.makedirs(self.user_path)
         try:
@@ -116,45 +110,46 @@ class PresetManager(Loggable):
         with open(file_path, "w") as fout:
             self._saveSection(fout, preset_name)
 
-    def _convertSectionNameToPresetName(self, section):
-        # A section name for a ConfigParser can have any name except "default"!
-        assert section != "default"
-        if section.rstrip("_").lower() == "default":
-            return section[:-1]
-        else:
-            return section
+    def getUniqueName(self, first=_("Custom"), second=_("Custom %d")):
+        name = first
+        i = 1
+        while self.hasPreset(name):
+            name = second % i
+            i += 1
+        return name
 
-    def _convertPresetNameToSectionName(self, preset):
-        if preset.rstrip("_").lower() == "default":
-            # We add an _ to allow the user to have a preset named "default".
-            return "%s_" % preset
-        else:
-            return preset
+    def getNewPresetName(self):
+        """Get a unique name for a new preset."""
+        return self.getUniqueName(_("New preset"), _("New preset %d"))
 
-    def createPreset(self, name, values):
+    def createPreset(self, name, values, volatile=False):
         """Create a new preset.
 
-        @param name: The name of the new preset.
+        @param name: The name of the new preset, must be unique.
         @type name: str
         @param values: The values of the new preset.
         @type values: dict
+        @param volatile: Whether the preset should not be saveable.
+        @type volatile: bool
         """
         if self.hasPreset(name):
             raise DuplicatePresetNameException(name)
+        if volatile:
+            values["volatile"] = True
         self._addPreset(name, values)
 
     def _addPreset(self, name, values):
-        """Add a new preset.
+        """Add a preset, overwriting the preset with the same name if it exists.
 
         @param name: The name of the new preset.
         @type name: str
         @param values: The values of the new preset.
         @type values: dict
         """
-        if name in self.presets:
-            del self.presets[name]
+        if self.hasPreset(name):
             for i, row in enumerate(self.ordered):
                 if row[0] == name:
+                    del self.presets[row[1]["name"]]
                     del self.ordered[i]
                     break
         self.presets[name] = values
@@ -278,7 +273,7 @@ class PresetManager(Loggable):
         self.ordered.prepend((name, values))
 
     def isSaveButtonSensitive(self):
-        """Check if the Save button should be sensitive"""
+        """Whether the Save button should be enabled"""
         if not self.cur_preset:
             return False
         if "volatile" in self.presets[self.cur_preset]:
@@ -297,9 +292,11 @@ class PresetManager(Loggable):
             return self._isCurrentPresetChanged()
 
     def isRemoveButtonSensitive(self):
-        """Check if the Remove button should be sensitive"""
+        """Whether the Remove button should be enabled"""
         if not self.cur_preset:
             return False
+        if "volatile" in self.presets[self.cur_preset]:
+            return False
         try:
             full_path = self.presets[self.cur_preset]["filepath"]
             (dir, name) = os.path.split(full_path)
diff --git a/pitivi/project.py b/pitivi/project.py
index ca80fcc..69d5e0b 100644
--- a/pitivi/project.py
+++ b/pitivi/project.py
@@ -1703,20 +1703,8 @@ class ProjectSettingsDialog():
         self.par_fraction_widget.set_sensitive(not dar_is_selected)
         self.par_combo.set_sensitive(not dar_is_selected)
 
-    @staticmethod
-    def _getUniquePresetName(mgr):
-        """Get a unique name for a new preset for the specified PresetManager.
-        """
-        existing_preset_names = list(mgr.getPresetNames())
-        preset_name = _("New preset")
-        i = 1
-        while preset_name in existing_preset_names:
-            preset_name = _("New preset %d") % i
-            i += 1
-        return preset_name
-
     def _addAudioPresetCb(self, unused_action, unused_param):
-        preset_name = self._getUniquePresetName(self.audio_presets)
+        preset_name = self.audio_presets.getNewPresetName()
         preset = {
             "channels": get_combo_value(self.channels_combo),
             "sample-rate": get_combo_value(self.sample_rate_combo),
@@ -1726,7 +1714,7 @@ class ProjectSettingsDialog():
         self._updateAudioPresetMenu()
 
     def _addVideoPresetCb(self, unused_action, unused_param):
-        preset_name = self._getUniquePresetName(self.video_presets)
+        preset_name = self.video_presets.getNewPresetName()
         preset = {
             "width": int(self.width_spinbutton.get_value()),
             "height": int(self.height_spinbutton.get_value()),
diff --git a/pitivi/render.py b/pitivi/render.py
index b824130..41b8b00 100644
--- a/pitivi/render.py
+++ b/pitivi/render.py
@@ -39,7 +39,6 @@ from gettext import gettext as _
 from pitivi import configure
 
 from pitivi.check import missing_soft_deps
-from pitivi.preset import CUSTOM_PRESET_NAME
 from pitivi.utils.loggable import Loggable
 from pitivi.utils.misc import show_user_manual, path_from_uri
 from pitivi.utils.ripple_update_group import RippleUpdateGroup
@@ -422,11 +421,10 @@ class RenderDialog(Loggable):
         self.bindHeight(self.render_presets)
         self.bindWidth(self.render_presets)
 
-        self.createVolatileCustomPreset(self.render_presets)
+        self.createVolatileCustomPreset()
 
-    def createVolatileCustomPreset(self, mgr):
-        mgr.prependPreset(CUSTOM_PRESET_NAME, {
-            "volatile": True,
+    def createVolatileCustomPreset(self):
+        preset = {
             "channels": int(get_combo_value(self.channels_combo)),
             "sample-rate": int(get_combo_value(self.sample_rate_combo)),
             "acodec": get_combo_value(self.audio_encoder_combo).get_name(),
@@ -436,7 +434,9 @@ class RenderDialog(Loggable):
                 int(get_combo_value(self.frame_rate_combo).num),
                 int(get_combo_value(self.frame_rate_combo).denom)),
             "height": self.project.videoheight,
-            "width": self.project.videowidth})
+            "width": self.project.videowidth}
+        name = self.render_presets.getUniqueName()
+        self.render_presets.createPreset(name, preset, volatile=True)
 
     def bindCombo(self, mgr, name, widget):
         if name == "container":
@@ -597,20 +597,8 @@ class RenderDialog(Loggable):
     def _updateRenderSaveButton(self, unused_in, button):
         button.set_sensitive(self.render_presets.isSaveButtonSensitive())
 
-    @staticmethod
-    def _getUniquePresetName(mgr):
-        """Get a unique name for a new preset for the specified PresetManager.
-        """
-        existing_preset_names = list(mgr.getPresetNames())
-        preset_name = _("New preset")
-        i = 1
-        while preset_name in existing_preset_names:
-            preset_name = _("New preset %d") % i
-            i += 1
-        return preset_name
-
     def _addRenderPresetButtonClickedCb(self, unused_button):
-        preset_name = self._getUniquePresetName(self.render_presets)
+        preset_name = self.render_presets.getNewPresetName()
         framerate = Gst.Fraction(int(get_combo_value(self.frame_rate_combo).num),
                                  int(get_combo_value(self.frame_rate_combo).denom))
         preset = {
@@ -624,7 +612,6 @@ class RenderDialog(Loggable):
             "width": 0,
         }
         self.render_presets.createPreset(preset_name, preset)
-
         self.render_presets.restorePreset(preset_name)
         self._updateRenderPresetButtons()
 
diff --git a/tests/Makefile.am b/tests/Makefile.am
index d1d972e..9ec09bc 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -13,7 +13,6 @@ tests =       \
        test_prefs.py \
        test_preset.py \
        test_project.py \
-       test_projectsettings.py \
        test_system.py \
        test_timeline_timeline.py \
        test_undo.py \
diff --git a/tests/test_preset.py b/tests/test_preset.py
index 1ae1ab7..7e56d3e 100644
--- a/tests/test_preset.py
+++ b/tests/test_preset.py
@@ -71,36 +71,11 @@ class TestPresetBasics(TestCase):
     def tearDown(self):
         clearPresetManagerPaths(self.manager)
 
-    def testConvertPresetNameToSectionName(self):
-        self.presetToSection = self.manager._convertPresetNameToSectionName
-        self.assertEqual("my preset", self.presetToSection('my preset'))
-        self.assertEqual("my preset_", self.presetToSection('my preset_'))
-        self.assertEqual("default_x_", self.presetToSection('default_x_'))
-
-        # Test that default_* preset names get a _ character at the end.
-        self.assertEqual("Default_", self.presetToSection('Default'))
-        self.assertEqual("defaulT__", self.presetToSection('defaulT_'))
-
-    def testConvertSectionNameToPresetName(self):
-        self.sectionToPreset = self.manager._convertSectionNameToPresetName
-        self.assertEqual("my preset", self.sectionToPreset('my preset'))
-        self.assertEqual("my preset_", self.sectionToPreset('my preset_'))
-        self.assertEqual("default_x_", self.sectionToPreset('default_x_'))
-
-        # Test that default_+ section names lose the last character.
-        self.assertEqual("Default", self.sectionToPreset('Default_'))
-        self.assertEqual("defaulT_", self.sectionToPreset('defaulT__'))
-
     def testAddPreset(self):
         self.manager.createPreset('preseT onE', {'name1': '1A'})
         self.assertRaises(DuplicatePresetNameException,
                           self.manager.createPreset, 'Preset One', {'name1': '2A'})
 
-    def testAddDuplicatePreset(self):
-        self.manager.createPreset('x', {})
-        self.assertRaises(
-            DuplicatePresetNameException, self.manager.createPreset, 'x', {})
-
     def testAddPresetWithNonAsciiName(self):
         unicode_name = "ソリッド・スネーク"
         self.manager.createPreset(unicode_name, {})
@@ -125,6 +100,20 @@ class TestPresetBasics(TestCase):
         self.manager.user_path = '/pitivi/non/existing/directory/2'
         self.manager.loadAll()
 
+    def testGetUniquePresetName(self):
+        name = self.manager.getNewPresetName()
+        self.assertEqual('New preset', name)
+
+        self.manager.createPreset(name, {})
+        new_preset1 = self.manager.getNewPresetName()
+        self.assertEqual('New preset 1', new_preset1)
+
+        # Intentionally add 'New preset 2' before 'New preset 1'.
+        self.manager.createPreset('New preset 2', {})
+        self.manager.createPreset('New preset 1', {})
+        new_preset3 = self.manager.getNewPresetName()
+        self.assertEqual('New preset 3', new_preset3)
+
 
 class TestAudioPresetsIO(TestCase):
 


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]