/[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 696 by jonathan, Wed Apr 16 16:39:49 2003 UTC revision 1816 by bh, Mon Oct 13 15:53:56 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    
18  import Thuban  import Thuban
19  from Thuban.Model.load import XMLProcessor, load_xmlfile  from Thuban import _
20  from Thuban.Model.save import XMLSaver  
21    from Thuban.Lib.fileutil import get_application_dir
22    
23    from Thuban.Model.xmlreader import XMLReader
24    from Thuban.Model.xmlwriter import XMLWriter
25  from Thuban.Model.proj import Projection, ProjFile  from Thuban.Model.proj import Projection, ProjFile
26    from xml.sax import SAXParseException
27    
28  projdir = \  projdir = \
29          os.path.join(Thuban.__path__[0], os.pardir, "Resources", "Projections")          os.path.join(Thuban.__path__[0], os.pardir, "Resources", "Projections")
30    
 usrdir  = os.path.expanduser("~/.thuban")  
31    
32  PROJ_EXT = ".proj"  PROJ_EXT = ".proj"
33    
34  def ReadProjFile(filename):  has_gdal_support = lambda: False
35      """Read a single .proj file and return a ProjFile object."""  try:
36        # first try to see if our extension module is there. if it
37        # wasn't even compiled, we obviously don't have gdal support.
38        import gdalwarp
39    
40        # now try to import the python extension. if this doesn't
41        # exist then we can't do anything.
42        import gdal
43    
44        """Return True if the gdal library is available."""
45        has_gdal_support = lambda: True
46    except ImportError:
47        pass
48    
49    def read_proj_file(filename):
50        """Read a .proj file and return a ProjFile object and warnings
51    
52        The return value is a tuple with the ProjFile object and a list of
53        strings with warnings messages that might have been generated by the
54        proj ifle parser.
55    
56      projs = []      Raises IOError if the file cannot be opened, OSError if the file
57      try:      cannot be read and SAXParseException if the file is not valid XML.
58          handler = ProjFileReader(filename)      """
59        handler = ProjFileReader()
60        handler.read(filename)
61        return handler.GetProjFile(), handler.GetWarnings()
62    
63          load_xmlfile(filename, handler)  def write_proj_file(pf):
64          pf = handler.GetProjFile()      """Write a single .proj file
     except OSError:  
         pass  
65    
66      return pf      Raises IOError if the file cannot be written.
67        """
68    
 def WriteProjFile(pf):  
69      saver = ProjFileSaver(pf)      saver = ProjFileSaver(pf)
70      saver.write(pf.GetFileName())      saver.write(pf.GetFilename())
71    
 def GetProjections(dir):  
     """Read all .proj files in the given directory and  
     return a list of ProjFile objects.  
     """  
72    
73      list = []  def get_system_proj_file():
74        """Return the standard projections and a list with warnings
75    
76        The projections read from the default thuban projection file
77        (usually in Resources/Projections/defaults.proj). The return value
78        is a tuple with the projections in a ProjFile object and a list of
79        strings with warning messages. The warnings list is usually empty
80        but may contain messages about ignored errors.
81    
82        If the file could could not be opened return an empty projection
83        file object set to store data in the default file.
84        """
85        filename = os.path.join(projdir, "defaults.proj")
86      try:      try:
87          for file in filter(lambda s: s.endswith(PROJ_EXT), os.listdir(dir)):          return read_proj_file(filename)
88              filename = os.path.join(dir, file)      except (OSError, IOError, SAXParseException), val:
89              list.extend(ReadProjFile(filename))          msg = _('Could not read "%s": %s') % (filename, str(val))
90      except OSError:          return ProjFile(filename), [msg]
91          pass  
92    def get_user_proj_file():
93      return list      """Return the user's projections and a list with warnings
94    
95  def GetSuppliedProjections():      The projections read from the user's thuban projection file (usually
96      """Return a list of ProjFile objects from files that are      in ~/.thuban/user.proj). The return value is a tuple with the
97      supplied by Thuban.      projections in a ProjFile object and a list of strings with warning
98        messages. The warnings list is usually empty but may contain
99        messages about ignored errors.
100    
101        If the file could could not be opened return an empty projection
102        file object set to store data in the default file.
103      """      """
104      return GetProjections(projdir)      usrdir  = get_application_dir()
105        filename = os.path.join(usrdir, "user.proj")
106        try:
107            return read_proj_file(filename)
108        except (OSError, IOError, SAXParseException), val:
109            msg = _('Could not read "%s": %s') % (filename, str(val))
110            return ProjFile(filename), [msg]
111    
112    
113    class ProjFileReader(XMLReader):
114    
115        def __init__(self):
116            XMLReader.__init__(self)
117            self.projfile = ProjFile("")
118            self.warnings = []
119    
120            XMLReader.AddDispatchers(self,
121                {'projection': ("start_projection", "end_projection"),
122                 'parameter':  ("start_parameter", None)})
123    
124        def read(self, file_or_filename):
125            XMLReader.read(self, file_or_filename)
126    
127            self.projfile.SetFilename(XMLReader.GetFilename(self))
128    
 def GetUserProjections():  
     """Return a list of ProjFile objects from files that are user-defined."""  
     return GetProjections(usrdir)  
   
 class ProjFileReader(XMLProcessor):  
   
     def __init__(self, filename):  
         XMLProcessor.__init__(self, os.path.dirname(filename))  
           
         self.pf = ProjFile(filename)  
           
129      def start_projection(self, name, qname, attrs):      def start_projection(self, name, qname, attrs):
130          self.params = []          self.params = []
131          self.name = attrs.get((None, 'name'), "Unknown")          name = self.encode(attrs.get((None, 'name')))
132      XMLProcessor.start_dispatcher['projection'] = "start_projection"          if name is None:
133                name = _("Unknown")
134            self.name = name
135            self.epsg = self.encode(attrs.get((None, 'epsg')))
136    
137      def end_projection(self, name, qname):      def end_projection(self, name, qname):
138          self.pf.Add(Projection(self.params, self.name))          try:
139      XMLProcessor.end_dispatcher['projection'] = "end_projection"              proj = Projection(self.params, self.name, epsg = self.epsg)
140            except IOError, val:
141                self.warnings.append(_('Error in projection "%s": %s')
142                                     % (self.name, str(val)))
143            else:
144                self.projfile.Add(proj)
145    
146      def start_parameter(self, name, qname, attrs):      def start_parameter(self, name, qname, attrs):
147          s = attrs.get((None, 'value'))          s = attrs.get((None, 'value'))
148          s = str(s) # we can't handle unicode in proj          s = str(s) # we can't handle unicode in proj
149          self.params.append(s)          self.params.append(s)
     XMLProcessor.start_dispatcher['parameter'] = "start_parameter"  
150    
151      def GetProjFile(self):      def GetProjFile(self):
152          return self.pf          return self.projfile
153    
154        def GetWarnings(self):
155            """Return the list of warning messages that may have been produced"""
156            return self.warnings
157    
158    
159  class ProjFileSaver(XMLSaver):  class ProjFileSaver(XMLWriter):
160    
161      def __init__(self, pf):      def __init__(self, pf):
162          XMLSaver.__init__(self)          XMLWriter.__init__(self)
163          self.pf = pf          self.__pf = pf
164    
165      def write(self, file_or_filename):      def write(self, file_or_filename):
166          XMLSaver.write(self, file_or_filename)          XMLWriter.write(self, file_or_filename)
167    
168          self.write_header("projfile", "thuban.dtd")          self.write_header("projectionlist", "projfile.dtd")
169          self.write_projfile(self.pf)          self.write_projfile(self.__pf)
170          self.close()          self.close()
171    
172      def write_projfile(self, pf):      def write_projfile(self, pf):
# Line 105  class ProjFileSaver(XMLSaver): Line 174  class ProjFileSaver(XMLSaver):
174          self.open_element("projectionlist")          self.open_element("projectionlist")
175    
176          for p in pf.GetProjections():          for p in pf.GetProjections():
177              self.open_element("projection", {"name": p.GetName()})              attrs = {"name": p.GetName()}
178                if p.EPSGCode():
179                    attrs["epsg"] = p.EPSGCode()
180                self.open_element("projection", attrs)
181    
182              for param in p.GetParameters():              for param in p.GetAllParameters():
183                  self.write_element("parameter", {"value": param})                  self.write_element("parameter", {"value": param})
184    
185              self.close_element("projection")              self.close_element("projection")

Legend:
Removed from v.696  
changed lines
  Added in v.1816

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26