/[thuban]/branches/WIP-pyshapelib-bramz/Thuban/Model/resource.py
ViewVC logotype

Diff of /branches/WIP-pyshapelib-bramz/Thuban/Model/resource.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 875 by jonathan, Fri May 9 16:31:39 2003 UTC revision 1964 by bh, Wed Nov 19 19:48:47 2003 UTC
# Line 5  Line 5 
5  # This program is free software under the GPL (>=v2)  # This program is free software under the GPL (>=v2)
6  # Read the file COPYING coming with Thuban for details.  # Read the file COPYING coming with Thuban for details.
7    
8    """Handle resources loaded from files such as projections"""
9    
10    __version__ = "$Revision$"
11    # $Source$
12    # $Id$
13    
14    
15  import os  import os
16    import os.path
17    import weakref
18    import traceback
19    
20  import Thuban  import Thuban
21  from Thuban import _  from Thuban import _
22    
23  from Thuban.Model.load import XMLReader  from Thuban.Lib.fileutil import get_application_dir
24  from Thuban.Model.save import XMLWriter  
25    from Thuban.Model.xmlreader import XMLReader
26    from Thuban.Model.xmlwriter import XMLWriter
27  from Thuban.Model.proj import Projection, ProjFile  from Thuban.Model.proj import Projection, ProjFile
28  from xml.sax import SAXParseException  from xml.sax import SAXParseException
29    
30  projdir = \  projdir = \
31          os.path.join(Thuban.__path__[0], os.pardir, "Resources", "Projections")          os.path.join(Thuban.__path__[0], os.pardir, "Resources", "Projections")
32    
 usrdir  = os.path.expanduser("~/.thuban")  
33    
34  PROJ_EXT = ".proj"  PROJ_EXT = ".proj"
35    
36  def ReadProjFile(filename):  # Determine the status of GDAL support. If GDAL is supported
37      """Read a single .proj file and return a ProjFile object.  # gdal_support_status will be set to the empty string, otherwise to a
38        # string with information why it isn't supported
39      Raises IOError if the file cannot be opened.  #
40      Raises OSError if the file cannot be read.  # GDAL is supported if we can import both the thuban specific gdalwarp
41      Raises SAXParseException if the file is not valid XML.  # module and the GDAL python bindings.
42    for _module in ("gdalwarp", "gdal"):
43        try:
44            __import__(_module)
45        except ImportError, val:
46            gdal_support_status = (_("No GDAL support because module '%s'"
47                                     " cannot be imported. Python exception: '%s'")
48                                   % (_module, str(val)))
49            break
50    else:
51        gdal_support_status = ""
52    
53    def has_gdal_support():
54        return gdal_support_status == ""
55    
56    
57    projfile_cache = weakref.WeakValueDictionary()
58    
59    def clear_proj_file_cache():
60        """Clear the cache of ProjFile objects maintained by read_proj_file.
61    
62        This function is probably only useful for the test suite.
63      """      """
64        projfile_cache.clear()
65    
66    def read_proj_file(filename):
67        """Read a .proj file and return a ProjFile object and warnings
68    
69      handler = ProjFileReader()      The return value is a tuple with the ProjFile object and a list of
70      handler.read(filename)      strings with warnings messages that might have been generated by the
71      return handler.GetProjFile()      proj file parser.
72    
73        The objects returned cached so that reading the same file
74        (identified by its absolute name) several times yields the same
75        ProjFile object. The cache uses weak references so the objects will
76        be removed from the cache once the last reference an object in the
77        cache is removed.
78    
79  def WriteProjFile(pf):      Raises IOError if the file cannot be opened, OSError if the file
80        cannot be read and SAXParseException if the file is not valid XML.
81        """
82        filename = os.path.abspath(filename)
83        if filename in projfile_cache:
84            return projfile_cache[filename], []
85        else:
86            handler = ProjFileReader()
87            handler.read(filename)
88            proj_file = handler.GetProjFile()
89            projfile_cache[filename] = proj_file
90            return proj_file, handler.GetWarnings()
91    
92    def write_proj_file(pf):
93      """Write a single .proj file      """Write a single .proj file
94    
95      Raises IOError if the file cannot be written.      Raises IOError if the file cannot be written.
# Line 42  def WriteProjFile(pf): Line 98  def WriteProjFile(pf):
98      saver = ProjFileSaver(pf)      saver = ProjFileSaver(pf)
99      saver.write(pf.GetFilename())      saver.write(pf.GetFilename())
100    
101  def GetProjFiles(dir):  #
102      """Read all .proj files in the given directory and  # Constants for the get_system_proj_file function
103      return a list of ProjFile objects.  #
104      """  
105    # The default projection file with a few predefined projections
106      list = []  DEFAULT_PROJ_FILE = "defaults.proj"
107      try:  
108          dirlist = os.listdir(dir)  # The epsg projections.
109      except OSError:  EPSG_PROJ_FILE = "epsg.proj"
110          pass # if we can't get a directory listing just return []  
111      else:  # Deprecated EPSG projections.
112          for file in filter(lambda s: s.endswith(PROJ_EXT), dirlist):  EPSG_DEPRECATED_PROJ_FILE = "epsg-deprecated.proj"
113              try:  
114                  filename = os.path.join(dir, file)  def get_system_proj_file(filename):
115                  list.append(ReadProjFile(filename))      """Return the projections from the indicated file and a list with warnings
116              except (OSError, IOError, SAXParseException):  
117                  pass # just move onto the next file      The filename argument should be the name of a file in the directory
118        with Thuban's default projection files (Resources/Projections/). If
119      return list      possible callers should not use hardwired string literal for the
120        name to avoid unnecessary duplication. Instead they should use one
121  def GetSystemProjFiles():      of the predefined constants, currently DEFAULT_PROJ_FILE,
122      """Return a list of ProjFile objects from files that are      EPSG_PROJ_FILE or EPSG_DEPRECATED_PROJ_FILE.
123      supplied by Thuban.  
124        The return value is a tuple with the projections in a ProjFile
125        object and a list of strings with warning messages. The warnings
126        list is usually empty but may contain messages about ignored errors.
127    
128      If no files could not be opened return a list with one      If the file could could not be opened return an empty projection
129      empty projection file set to store data in the default file.      file object set to store data in the indicated default file.
130      """      """
131      filename = os.path.join(projdir, "defaults.proj")      fullname = os.path.join(projdir, filename)
132      try:      try:
133          return [ReadProjFile(filename)]          return read_proj_file(fullname)
134      except (OSError, IOError, SAXParseException):      except (OSError, IOError, SAXParseException), val:
135          return [ProjFile(filename)]          msg = _('Could not read "%s": %s') % (fullname, str(val))
136            return ProjFile(fullname), [msg]
137    
138    def get_user_proj_file():
139        """Return the user's projections and a list with warnings
140    
141        The projections read from the user's thuban projection file (usually
142        in ~/.thuban/user.proj). The return value is a tuple with the
143        projections in a ProjFile object and a list of strings with warning
144        messages. The warnings list is usually empty but may contain
145        messages about ignored errors.
146    
147  def GetUserProjFiles():      If the file could could not be opened return an empty projection
148      """Return a list of ProjFile objects from files that are user-defined.      file object set to store data in the default file.
   
     If no files could not be opened return a list with one  
     empty projection file set to store data in the default file.  
149      """      """
150        usrdir  = get_application_dir()
151      filename = os.path.join(usrdir, "user.proj")      filename = os.path.join(usrdir, "user.proj")
152      try:      try:
153          return [ReadProjFile(filename)]          return read_proj_file(filename)
154      except (OSError, IOError, SAXParseException):      except (OSError, IOError, SAXParseException), val:
155          return [ProjFile(filename)]          msg = _('Could not read "%s": %s') % (filename, str(val))
156            return ProjFile(filename), [msg]
157    
158    
159  class ProjFileReader(XMLReader):  class ProjFileReader(XMLReader):
160    
161      def __init__(self):      def __init__(self):
162          XMLReader.__init__(self)          XMLReader.__init__(self)
163          self.__pf = ProjFile("")          self.projfile = ProjFile("")
164            self.warnings = []
165    
166          XMLReader.AddDispatchers(self,          XMLReader.AddDispatchers(self,
167              {'projection': ("start_projection", "end_projection"),              {'projection': ("start_projection", "end_projection"),
168               'parameter':  ("start_parameter", None)})               'parameter':  ("start_parameter", None)})
169                
170      def read(self, file_or_filename):      def read(self, file_or_filename):
171          XMLReader.read(self, file_or_filename)          XMLReader.read(self, file_or_filename)
172    
173          self.__pf.SetFilename(XMLReader.GetFilename(self))          self.projfile.SetFilename(XMLReader.GetFilename(self))
174            
175      def start_projection(self, name, qname, attrs):      def start_projection(self, name, qname, attrs):
176          self.params = []          self.params = []
177          self.name = self.encode(attrs.get((None, 'name'), _("Unknown")))          name = self.encode(attrs.get((None, 'name')))
178            if name is None:
179                name = _("Unknown")
180            self.name = name
181            self.epsg = self.encode(attrs.get((None, 'epsg')))
182    
183      def end_projection(self, name, qname):      def end_projection(self, name, qname):
184          self.__pf.Add(Projection(self.params, self.name))          try:
185                proj = Projection(self.params, self.name, epsg = self.epsg)
186            except IOError, val:
187                self.warnings.append(_('Error in projection "%s": %s')
188                                     % (self.name, str(val)))
189            else:
190                self.projfile.Add(proj)
191    
192      def start_parameter(self, name, qname, attrs):      def start_parameter(self, name, qname, attrs):
193          s = attrs.get((None, 'value'))          s = attrs.get((None, 'value'))
# Line 116  class ProjFileReader(XMLReader): Line 195  class ProjFileReader(XMLReader):
195          self.params.append(s)          self.params.append(s)
196    
197      def GetProjFile(self):      def GetProjFile(self):
198          return self.__pf          return self.projfile
199    
200        def GetWarnings(self):
201            """Return the list of warning messages that may have been produced"""
202            return self.warnings
203    
204    
205  class ProjFileSaver(XMLWriter):  class ProjFileSaver(XMLWriter):
# Line 128  class ProjFileSaver(XMLWriter): Line 211  class ProjFileSaver(XMLWriter):
211      def write(self, file_or_filename):      def write(self, file_or_filename):
212          XMLWriter.write(self, file_or_filename)          XMLWriter.write(self, file_or_filename)
213    
214          self.write_header("projfile", "projfile.dtd")          self.write_header("projectionlist", "projfile.dtd")
215          self.write_projfile(self.__pf)          self.write_projfile(self.__pf)
216          self.close()          self.close()
217    
# Line 137  class ProjFileSaver(XMLWriter): Line 220  class ProjFileSaver(XMLWriter):
220          self.open_element("projectionlist")          self.open_element("projectionlist")
221    
222          for p in pf.GetProjections():          for p in pf.GetProjections():
223              self.open_element("projection", {"name": p.GetName()})              attrs = {"name": p.GetName()}
224                if p.EPSGCode():
225                    attrs["epsg"] = p.EPSGCode()
226                self.open_element("projection", attrs)
227    
228              for param in p.GetAllParameters():              for param in p.GetAllParameters():
229                  self.write_element("parameter", {"value": param})                  self.write_element("parameter", {"value": param})

Legend:
Removed from v.875  
changed lines
  Added in v.1964

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26