/[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 1189 by jonathan, Thu Jun 12 17:01:13 2003 UTC revision 1940 by bh, Tue Nov 11 18:27:39 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  import os.path
17    import weakref
18    
19  import Thuban  import Thuban
20  from Thuban import _  from Thuban import _
# Line 26  PROJ_EXT = ".proj" Line 34  PROJ_EXT = ".proj"
34    
35  has_gdal_support = lambda: False  has_gdal_support = lambda: False
36  try:  try:
37        # first try to see if our extension module is there. if it
38        # wasn't even compiled, we obviously don't have gdal support.
39        import gdalwarp
40    
41        # now try to import the python extension. if this doesn't
42        # exist then we can't do anything.
43      import gdal      import gdal
44    
45      """Return True if the gdal library is available."""      """Return True if the gdal library is available."""
46      has_gdal_support = lambda: True      has_gdal_support = lambda: True
47  except ImportError:  except ImportError:
48      pass      pass
49    
50  def read_proj_file(filename):  projfile_cache = weakref.WeakValueDictionary()
51      """Read a single .proj file and return a ProjFile object.  
52        def clear_proj_file_cache():
53      Raises IOError if the file cannot be opened.      """Clear the cache of ProjFile objects maintained by read_proj_file.
54      Raises OSError if the file cannot be read.  
55      Raises SAXParseException if the file is not valid XML.      This function is probably only useful for the test suite.
56      """      """
57        projfile_cache.clear()
58    
59    def read_proj_file(filename):
60        """Read a .proj file and return a ProjFile object and warnings
61    
62        The return value is a tuple with the ProjFile object and a list of
63        strings with warnings messages that might have been generated by the
64        proj file parser.
65    
66        The objects returned cached so that reading the same file
67        (identified by its absolute name) several times yields the same
68        ProjFile object. The cache uses weak references so the objects will
69        be removed from the cache once the last reference an object in the
70        cache is removed.
71    
72      handler = ProjFileReader()      Raises IOError if the file cannot be opened, OSError if the file
73      handler.read(filename)      cannot be read and SAXParseException if the file is not valid XML.
74      return handler.GetProjFile()      """
75        filename = os.path.abspath(filename)
76        if filename in projfile_cache:
77            return projfile_cache[filename], []
78        else:
79            handler = ProjFileReader()
80            handler.read(filename)
81            proj_file = handler.GetProjFile()
82            projfile_cache[filename] = proj_file
83            return proj_file, handler.GetWarnings()
84    
85  def write_proj_file(pf):  def write_proj_file(pf):
86      """Write a single .proj file      """Write a single .proj file
# Line 53  def write_proj_file(pf): Line 91  def write_proj_file(pf):
91      saver = ProjFileSaver(pf)      saver = ProjFileSaver(pf)
92      saver.write(pf.GetFilename())      saver.write(pf.GetFilename())
93    
94  def get_proj_files(dir):  #
95      """Read all .proj files in the given directory and  # Constants for the get_system_proj_file function
96      return a list of ProjFile objects.  #
97      """  
98    # The default projection file with a few predefined projections
99      list = []  DEFAULT_PROJ_FILE = "defaults.proj"
100      try:  
101          dirlist = os.listdir(dir)  # The epsg projections.
102      except OSError:  EPSG_PROJ_FILE = "epsg.proj"
103          pass # if we can't get a directory listing just return []  
104      else:  # Deprecated EPSG projections.
105          for file in filter(lambda s: s.endswith(PROJ_EXT), dirlist):  EPSG_DEPRECATED_PROJ_FILE = "epsg-deprecated.proj"
106              try:  
107                  filename = os.path.join(dir, file)  def get_system_proj_file(filename):
108                  list.append(read_proj_file(filename))      """Return the projections from the indicated file and a list with warnings
109              except (OSError, IOError, SAXParseException):  
110                  pass # just move onto the next file      The filename argument should be the name of a file in the directory
111        with Thuban's default projection files (Resources/Projections/). If
112      return list      possible callers should not use hardwired string literal for the
113        name to avoid unnecessary duplication. Instead they should use one
114  def get_system_proj_files():      of the predefined constants, currently DEFAULT_PROJ_FILE,
115      """Return a list of ProjFile objects from files that are      EPSG_PROJ_FILE or EPSG_DEPRECATED_PROJ_FILE.
116      supplied by Thuban.  
117        The return value is a tuple with the projections in a ProjFile
118        object and a list of strings with warning messages. The warnings
119        list is usually empty but may contain messages about ignored errors.
120    
121      If no files could not be opened return a list with one      If the file could could not be opened return an empty projection
122      empty projection file set to store data in the default file.      file object set to store data in the indicated default file.
123      """      """
124      filename = os.path.join(projdir, "defaults.proj")      fullname = os.path.join(projdir, filename)
125      try:      try:
126          return [read_proj_file(filename)]          return read_proj_file(fullname)
127      except (OSError, IOError, SAXParseException):      except (OSError, IOError, SAXParseException), val:
128          return [ProjFile(filename)]          msg = _('Could not read "%s": %s') % (fullname, str(val))
129            return ProjFile(fullname), [msg]
130  def get_user_proj_files():  
131      """Return a list of ProjFile objects from files that are user-defined.  def get_user_proj_file():
132        """Return the user's projections and a list with warnings
133    
134        The projections read from the user's thuban projection file (usually
135        in ~/.thuban/user.proj). The return value is a tuple with the
136        projections in a ProjFile object and a list of strings with warning
137        messages. The warnings list is usually empty but may contain
138        messages about ignored errors.
139    
140      If no files could not be opened return a list with one      If the file could could not be opened return an empty projection
141      empty projection file set to store data in the default file.      file object set to store data in the default file.
142      """      """
   
143      usrdir  = get_application_dir()      usrdir  = get_application_dir()
144      filename = os.path.join(usrdir, "user.proj")      filename = os.path.join(usrdir, "user.proj")
145      try:      try:
146          return [read_proj_file(filename)]          return read_proj_file(filename)
147      except (OSError, IOError, SAXParseException):      except (OSError, IOError, SAXParseException), val:
148          return [ProjFile(filename)]          msg = _('Could not read "%s": %s') % (filename, str(val))
149            return ProjFile(filename), [msg]
150    
151    
152  class ProjFileReader(XMLReader):  class ProjFileReader(XMLReader):
153    
154      def __init__(self):      def __init__(self):
155          XMLReader.__init__(self)          XMLReader.__init__(self)
156          self.__pf = ProjFile("")          self.projfile = ProjFile("")
157            self.warnings = []
158    
159          XMLReader.AddDispatchers(self,          XMLReader.AddDispatchers(self,
160              {'projection': ("start_projection", "end_projection"),              {'projection': ("start_projection", "end_projection"),
161               'parameter':  ("start_parameter", None)})               'parameter':  ("start_parameter", None)})
162                
163      def read(self, file_or_filename):      def read(self, file_or_filename):
164          XMLReader.read(self, file_or_filename)          XMLReader.read(self, file_or_filename)
165    
166          self.__pf.SetFilename(XMLReader.GetFilename(self))          self.projfile.SetFilename(XMLReader.GetFilename(self))
167            
168      def start_projection(self, name, qname, attrs):      def start_projection(self, name, qname, attrs):
169          self.params = []          self.params = []
170          self.name = self.encode(attrs.get((None, 'name'), _("Unknown")))          name = self.encode(attrs.get((None, 'name')))
171            if name is None:
172                name = _("Unknown")
173            self.name = name
174            self.epsg = self.encode(attrs.get((None, 'epsg')))
175    
176      def end_projection(self, name, qname):      def end_projection(self, name, qname):
177          self.__pf.Add(Projection(self.params, self.name))          try:
178                proj = Projection(self.params, self.name, epsg = self.epsg)
179            except IOError, val:
180                self.warnings.append(_('Error in projection "%s": %s')
181                                     % (self.name, str(val)))
182            else:
183                self.projfile.Add(proj)
184    
185      def start_parameter(self, name, qname, attrs):      def start_parameter(self, name, qname, attrs):
186          s = attrs.get((None, 'value'))          s = attrs.get((None, 'value'))
# Line 128  class ProjFileReader(XMLReader): Line 188  class ProjFileReader(XMLReader):
188          self.params.append(s)          self.params.append(s)
189    
190      def GetProjFile(self):      def GetProjFile(self):
191          return self.__pf          return self.projfile
192    
193        def GetWarnings(self):
194            """Return the list of warning messages that may have been produced"""
195            return self.warnings
196    
197    
198  class ProjFileSaver(XMLWriter):  class ProjFileSaver(XMLWriter):
199    
# Line 139  class ProjFileSaver(XMLWriter): Line 204  class ProjFileSaver(XMLWriter):
204      def write(self, file_or_filename):      def write(self, file_or_filename):
205          XMLWriter.write(self, file_or_filename)          XMLWriter.write(self, file_or_filename)
206    
207          self.write_header("projfile", "projfile.dtd")          self.write_header("projectionlist", "projfile.dtd")
208          self.write_projfile(self.__pf)          self.write_projfile(self.__pf)
209          self.close()          self.close()
210    
# Line 148  class ProjFileSaver(XMLWriter): Line 213  class ProjFileSaver(XMLWriter):
213          self.open_element("projectionlist")          self.open_element("projectionlist")
214    
215          for p in pf.GetProjections():          for p in pf.GetProjections():
216              self.open_element("projection", {"name": p.GetName()})              attrs = {"name": p.GetName()}
217                if p.EPSGCode():
218                    attrs["epsg"] = p.EPSGCode()
219                self.open_element("projection", attrs)
220    
221              for param in p.GetAllParameters():              for param in p.GetAllParameters():
222                  self.write_element("parameter", {"value": param})                  self.write_element("parameter", {"value": param})

Legend:
Removed from v.1189  
changed lines
  Added in v.1940

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26