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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1940 - (hide annotations)
Tue Nov 11 18:27:39 2003 UTC (21 years, 3 months ago) by bh
Original Path: trunk/thuban/Thuban/Model/resource.py
File MIME type: text/x-python
File size: 7148 byte(s)
(EPSG_DEPRECATED_PROJ_FILE): New.
Constant for the file woth deprecated epsg projections
(get_system_proj_file): Update doc-string

1 jonathan 696 # Copyright (c) 2003 by Intevation GmbH
2     # Authors:
3     # Jonathan Coles <[email protected]>
4     #
5     # This program is free software under the GPL (>=v2)
6     # Read the file COPYING coming with Thuban for details.
7    
8 bh 1542 """Handle resources loaded from files such as projections"""
9    
10     __version__ = "$Revision$"
11     # $Source$
12     # $Id$
13    
14    
15 jonathan 696 import os
16 frank 1132 import os.path
17 bh 1830 import weakref
18 frank 1132
19 jonathan 696 import Thuban
20 jonathan 875 from Thuban import _
21    
22 frank 1149 from Thuban.Lib.fileutil import get_application_dir
23    
24 jonathan 1161 from Thuban.Model.xmlreader import XMLReader
25     from Thuban.Model.xmlwriter import XMLWriter
26 jonathan 696 from Thuban.Model.proj import Projection, ProjFile
27 jonathan 727 from xml.sax import SAXParseException
28 jonathan 696
29     projdir = \
30     os.path.join(Thuban.__path__[0], os.pardir, "Resources", "Projections")
31    
32    
33     PROJ_EXT = ".proj"
34    
35 jonathan 1161 has_gdal_support = lambda: False
36     try:
37 jonathan 1230 # 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 jonathan 1161 import gdal
44 jonathan 1230
45 jonathan 1161 """Return True if the gdal library is available."""
46     has_gdal_support = lambda: True
47     except ImportError:
48     pass
49    
50 bh 1830 projfile_cache = weakref.WeakValueDictionary()
51    
52     def clear_proj_file_cache():
53     """Clear the cache of ProjFile objects maintained by read_proj_file.
54    
55     This function is probably only useful for the test suite.
56     """
57     projfile_cache.clear()
58    
59 jonathan 1161 def read_proj_file(filename):
60 bh 1786 """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 bh 1830 proj file parser.
65 bh 1786
66 bh 1830 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 bh 1786 Raises IOError if the file cannot be opened, OSError if the file
73     cannot be read and SAXParseException if the file is not valid XML.
74 jonathan 718 """
75 bh 1830 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 jonathan 696
85 jonathan 1161 def write_proj_file(pf):
86 jonathan 727 """Write a single .proj file
87    
88     Raises IOError if the file cannot be written.
89     """
90    
91 jonathan 696 saver = ProjFileSaver(pf)
92 jonathan 739 saver.write(pf.GetFilename())
93 jonathan 696
94 bh 1940 #
95     # Constants for the get_system_proj_file function
96     #
97 jonathan 696
98 bh 1940 # The default projection file with a few predefined projections
99 bh 1933 DEFAULT_PROJ_FILE = "defaults.proj"
100 bh 1940
101     # The epsg projections.
102 bh 1933 EPSG_PROJ_FILE = "epsg.proj"
103 jonathan 696
104 bh 1940 # Deprecated EPSG projections.
105     EPSG_DEPRECATED_PROJ_FILE = "epsg-deprecated.proj"
106    
107 bh 1933 def get_system_proj_file(filename):
108     """Return the projections from the indicated file and a list with warnings
109 jonathan 696
110 bh 1933 The filename argument should be the name of a file in the directory
111     with Thuban's default projection files (Resources/Projections/). If
112     possible callers should not use hardwired string literal for the
113     name to avoid unnecessary duplication. Instead they should use one
114 bh 1940 of the predefined constants, currently DEFAULT_PROJ_FILE,
115     EPSG_PROJ_FILE or EPSG_DEPRECATED_PROJ_FILE.
116 bh 1933
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 bh 1786 If the file could could not be opened return an empty projection
122 bh 1933 file object set to store data in the indicated default file.
123 jonathan 696 """
124 bh 1933 fullname = os.path.join(projdir, filename)
125 jonathan 727 try:
126 bh 1933 return read_proj_file(fullname)
127 bh 1786 except (OSError, IOError, SAXParseException), val:
128 bh 1933 msg = _('Could not read "%s": %s') % (fullname, str(val))
129     return ProjFile(fullname), [msg]
130 jonathan 696
131 bh 1786 def get_user_proj_file():
132     """Return the user's projections and a list with warnings
133 jonathan 696
134 bh 1786 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 the file could could not be opened return an empty projection
141     file object set to store data in the default file.
142 jonathan 727 """
143 jonathan 1189 usrdir = get_application_dir()
144 jonathan 727 filename = os.path.join(usrdir, "user.proj")
145     try:
146 bh 1786 return read_proj_file(filename)
147 jan 1791 except (OSError, IOError, SAXParseException), val:
148 bh 1786 msg = _('Could not read "%s": %s') % (filename, str(val))
149     return ProjFile(filename), [msg]
150 jonathan 727
151 bh 1786
152 jonathan 709 class ProjFileReader(XMLReader):
153 jonathan 696
154 jonathan 709 def __init__(self):
155     XMLReader.__init__(self)
156 bh 1786 self.projfile = ProjFile("")
157     self.warnings = []
158 jonathan 709
159     XMLReader.AddDispatchers(self,
160     {'projection': ("start_projection", "end_projection"),
161     'parameter': ("start_parameter", None)})
162 bh 1786
163 jonathan 709 def read(self, file_or_filename):
164     XMLReader.read(self, file_or_filename)
165    
166 bh 1786 self.projfile.SetFilename(XMLReader.GetFilename(self))
167    
168 jonathan 696 def start_projection(self, name, qname, attrs):
169     self.params = []
170 bh 1786 name = self.encode(attrs.get((None, 'name')))
171     if name is None:
172     name = _("Unknown")
173     self.name = name
174 bh 1816 self.epsg = self.encode(attrs.get((None, 'epsg')))
175 jonathan 696
176     def end_projection(self, name, qname):
177 bh 1786 try:
178 bh 1816 proj = Projection(self.params, self.name, epsg = self.epsg)
179 bh 1786 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 jonathan 696
185     def start_parameter(self, name, qname, attrs):
186     s = attrs.get((None, 'value'))
187     s = str(s) # we can't handle unicode in proj
188     self.params.append(s)
189    
190     def GetProjFile(self):
191 bh 1786 return self.projfile
192 jonathan 696
193 bh 1786 def GetWarnings(self):
194     """Return the list of warning messages that may have been produced"""
195     return self.warnings
196    
197    
198 jonathan 709 class ProjFileSaver(XMLWriter):
199 jonathan 696
200     def __init__(self, pf):
201 jonathan 709 XMLWriter.__init__(self)
202     self.__pf = pf
203 jonathan 696
204     def write(self, file_or_filename):
205 jonathan 709 XMLWriter.write(self, file_or_filename)
206 jonathan 696
207 bh 1755 self.write_header("projectionlist", "projfile.dtd")
208 jonathan 709 self.write_projfile(self.__pf)
209 jonathan 696 self.close()
210    
211     def write_projfile(self, pf):
212    
213     self.open_element("projectionlist")
214    
215     for p in pf.GetProjections():
216 bh 1816 attrs = {"name": p.GetName()}
217     if p.EPSGCode():
218     attrs["epsg"] = p.EPSGCode()
219     self.open_element("projection", attrs)
220 jonathan 696
221 jonathan 709 for param in p.GetAllParameters():
222 jonathan 696 self.write_element("parameter", {"value": param})
223    
224     self.close_element("projection")
225    
226     self.close_element("projectionlist")
227    
228    

Properties

Name Value
svn:eol-style native
svn:keywords Author Date Id Revision

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26