[gedit-latex/doc-prefs: 2/3] remove propertyfile interface, specialise prefs to documentprefs



commit 7fb57b0036cf31d05c36959f82417399155d90e6
Author: John Stowers <john stowers gmail com>
Date:   Tue Aug 16 11:50:43 2011 +1200

    remove propertyfile interface, specialise prefs to documentprefs

 latex/latex/__init__.py       |   76 ----------------------------
 latex/latex/actions.py        |   16 +-----
 latex/latex/editor.py         |   32 ++++++------
 latex/preferences/__init__.py |  109 +++++++++++++++++++++++++++++++++++++++++
 4 files changed, 126 insertions(+), 107 deletions(-)
---
diff --git a/latex/latex/__init__.py b/latex/latex/__init__.py
index 906cf92..1b4fd67 100644
--- a/latex/latex/__init__.py
+++ b/latex/latex/__init__.py
@@ -30,80 +30,4 @@ class LaTeXSource(object):
         self.source = source
         self.packages = packages
 
-
-from logging import getLogger
-
-# TODO: use ElementTree
-from xml.dom import minidom
-from xml.parsers.expat import ExpatError
-
-from ..base.file import File
-
-
-class PropertyFile(dict):
-    """
-    A property file is a hidden XML file that holds meta data for exactly one file.
-    It can be used to store the master file of a LaTeX document fragment.
-    """
-
-    __log = getLogger("PropertyFile")
-
-    # TODO: insert value as TEXT node
-
-    def __init__(self, file):
-        """
-        Create or load the property file for a given File
-        """
-        self.__file = File("%s/.%s.properties.xml" % (file.dirname, file.basename))
-
-        try:
-            self.__dom = minidom.parse(self.__file.path)
-
-            for property_node in self.__dom.getElementsByTagName("property"):
-                k = property_node.getAttribute("key")
-                v = property_node.getAttribute("value")
-                self.__setitem__(k, v)
-
-        except IOError:
-            self.__log.debug("File %s not found, creating empty one" % self.__file)
-
-            self.__dom = minidom.getDOMImplementation().createDocument(None, "properties", None)
-
-        except ExpatError, e:
-            self.__log.error("Error parsing %s: %s" % (self.__file, e))
-
-
-    def __find_node(self, k):
-        for node in self.__dom.getElementsByTagName("property"):
-            if node.getAttribute("key") == str(k):
-                return node
-        raise KeyError
-
-    def __getitem__(self, k):
-        return self.__find_node(k).getAttribute("value")
-
-    def __setitem__(self, k, v):
-        try:
-            self.__find_node(k).setAttribute("value", str(v))
-        except KeyError:
-            node = self.__dom.createElement("property")
-            node.setAttribute("key", str(k))
-            node.setAttribute("value", str(v))
-            self.__dom.documentElement.appendChild(node)
-
-    def save(self):
-        filename = self.__file.path
-
-        if self.__file.exists:
-            mode = "w"
-        else:
-            mode = "a"
-
-        try:
-            f = open(filename, mode)
-            f.write(self.__dom.toxml())
-            f.close()
-            self.__log.debug("Saved to %s" % filename)
-        except IOError, e:
-            self.__log.error("Error saving %s: %s" % (filename, e))
 # ex:ts=4:et:
diff --git a/latex/latex/actions.py b/latex/latex/actions.py
index 188752c..d5394f8 100644
--- a/latex/latex/actions.py
+++ b/latex/latex/actions.py
@@ -38,7 +38,7 @@ from .parser import LaTeXParser, Node
 from .dialogs import UseBibliographyDialog, InsertGraphicsDialog, InsertTableDialog, \
                     InsertListingDialog, BuildImageDialog, SaveAsTemplateDialog, \
                     NewDocumentDialog, ChooseMasterDialog
-from . import LaTeXSource, PropertyFile
+from . import LaTeXSource
 
 class LaTeXAction(Action):
     extensions = Preferences().get("latex-extensions").split(",")
@@ -111,19 +111,7 @@ class LaTeXChooseMasterAction(LaTeXAction):
         editor = context.active_editor
         assert type(editor) is LaTeXEditor
 
-        file = editor._file        # FIXME: access to private member
-
-        # load property file
-        property_file = PropertyFile(file)
-
-        master_filename = ChooseMasterDialog().run(file.dirname)
-        if master_filename:
-            # relativize the master filename
-            master_filename = File(master_filename).relativize(file.dirname, True)
-
-            property_file["MasterFilename"] = master_filename
-            property_file.save()
-
+        editor.choose_master_file()
 
 class LaTeXCloseEnvironmentAction(LaTeXIconAction):
     _log = getLogger("LaTeXCloseEnvironmentAction")
diff --git a/latex/latex/editor.py b/latex/latex/editor.py
index b35e431..2673895 100644
--- a/latex/latex/editor.py
+++ b/latex/latex/editor.py
@@ -44,8 +44,8 @@ from validator import LaTeXValidator
 
 from dialogs import ChooseMasterDialog
 
-from . import LaTeXSource, PropertyFile
-from ..preferences import Preferences
+from . import LaTeXSource
+from ..preferences import Preferences, DocumentPreferences
 
 
 class LaTeXEditor(Editor, IIssueHandler):
@@ -72,7 +72,7 @@ class LaTeXEditor(Editor, IIssueHandler):
         self._file = file
         self._context = context
 
-        self._preferences = Preferences()
+        self._preferences = DocumentPreferences(self._file)
         self._preferences.connect("preferences-changed", self._on_preferences_changed)
 
         self.register_marker_type("latex-error", self._preferences.get("error-background-color"))
@@ -327,6 +327,14 @@ class LaTeXEditor(Editor, IIssueHandler):
 
             #print self._document.xml
 
+    def choose_master_file(self):
+        master_filename = ChooseMasterDialog().run(self._file.dirname)
+        if master_filename:
+            # relativize the master filename
+            master_filename = File(master_filename).relativize(self._file.dirname, True)
+            self._preferences.set("document-master-filename", master_filename)
+        return master_filename
+
     @property
     # returns(File)
     def __master_file(self):
@@ -335,31 +343,21 @@ class LaTeXEditor(Editor, IIssueHandler):
 
         @return: base.File
         """
-        # TODO: cache result
-
-        property_file = PropertyFile(self._file)
         try:
-            path = property_file["MasterFilename"]
+            path = self._preferences.get("document-master-filename")
             # the property file may contain absolute and relative paths
-            # because we switched in 0.2rc2
             if File.is_absolute(path):
                 self._log.debug("Path is absolute")
                 return File(path)
             else:
                 self._log.debug("Path is relative")
                 return File.create_from_relative_path(path, self._file.dirname)
-        except KeyError:        # master filename not found
-            # ask user
-            master_filename = ChooseMasterDialog().run(self._file.dirname)
+        except KeyError:
+            # master filename not found, ask user
+            master_filename = self.choose_master_file()
             if master_filename:
-                # relativize the master filename
-                master_filename = File(master_filename).relativize(self._file.dirname, True)
-
-                property_file["MasterFilename"] = master_filename
-                property_file.save()
                 return File.create_from_relative_path(master_filename, self._file.dirname)
             else:
-                # no master file chosen
                 return None
 
     def issue(self, issue):
diff --git a/latex/preferences/__init__.py b/latex/preferences/__init__.py
index 4f1ac0c..e380380 100644
--- a/latex/preferences/__init__.py
+++ b/latex/preferences/__init__.py
@@ -29,8 +29,81 @@ import logging
 
 from ..util import singleton
 
+# TODO: use ElementTree
+from xml.dom import minidom
+from xml.parsers.expat import ExpatError
+
+from ..base.file import File
+
 LOG = logging.getLogger(__name__)
 
+class _PropertyFile(dict):
+    """
+    A property file is a hidden XML file that holds meta data for exactly one file.
+    It can be used to store the master file of a LaTeX document fragment.
+    """
+
+    __log = logging.getLogger("PropertyFile")
+
+    # TODO: insert value as TEXT node
+
+    def __init__(self, file):
+        """
+        Create or load the property file for a given File
+        """
+        self.__file = File("%s/.%s.properties.xml" % (file.dirname, file.basename))
+
+        try:
+            self.__dom = minidom.parse(self.__file.path)
+
+            for property_node in self.__dom.getElementsByTagName("property"):
+                k = property_node.getAttribute("key")
+                v = property_node.getAttribute("value")
+                self.__setitem__(k, v)
+
+        except IOError:
+            self.__log.debug("File %s not found, creating empty one" % self.__file)
+
+            self.__dom = minidom.getDOMImplementation().createDocument(None, "properties", None)
+
+        except ExpatError, e:
+            self.__log.error("Error parsing %s: %s" % (self.__file, e))
+
+
+    def __find_node(self, k):
+        for node in self.__dom.getElementsByTagName("property"):
+            if node.getAttribute("key") == str(k):
+                return node
+        raise KeyError
+
+    def __getitem__(self, k):
+        return self.__find_node(k).getAttribute("value")
+
+    def __setitem__(self, k, v):
+        try:
+            self.__find_node(k).setAttribute("value", str(v))
+        except KeyError:
+            node = self.__dom.createElement("property")
+            node.setAttribute("key", str(k))
+            node.setAttribute("value", str(v))
+            self.__dom.documentElement.appendChild(node)
+
+    def save(self):
+        filename = self.__file.path
+
+        if self.__file.exists:
+            mode = "w"
+        else:
+            mode = "a"
+
+        try:
+            f = open(filename, mode)
+            f.write(self.__dom.toxml())
+            f.close()
+            self.__log.debug("Saved to %s" % filename)
+        except IOError, e:
+            self.__log.error("Error saving %s: %s" % (filename, e))
+
 class _Preferences(GObject.GObject):
 
     __gsignals__ = {
@@ -68,6 +141,42 @@ class Preferences(_Preferences):
         self._settings[key] = value
         self.emit("preferences-changed", str(key), str(value))
 
+class DocumentPreferences(_Preferences):
+    """
+    Similar to @Preferences, but treats keys starting with 'document-' differently
+    """
+
+    KEYS = dict([(k,True) for k in (
+        "document-master-filename",
+    )])
 
+    def __init__(self, file):
+        _Preferences.__init__(self)
+        self._sysprefs = Preferences()
+        self._sysprefs.connect("preferences-changed", self._on_prefs_changed)
+        self._file = file
+        self._pf = _PropertyFile(file)
+
+    def _on_prefs_changed(self, p, key, value):
+        self.emit("preferences-changed", key, value)
+
+    def _is_docpref(self,key):
+        return key.startswith("document-") and key in self.KEYS
+
+    def get(self, key):
+        if self._is_docpref(key):
+            LOG.debug("Get document pref")
+            return self._pf[key]
+        else:
+            return self._sysprefs.get(key)
+
+    def set(self, key, value):
+        if self._is_docpref(key):
+            LOG.debug("Set document pref")
+            self._pf[key] = value
+            self._pf.save()
+            self.emit("preferences-changed", key, value)
+        else:
+            self._sysprefs.set(key, value)
 
 # ex:ts=4:et:



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