13 |
|
|
14 |
__version__ = "$Revision$" |
__version__ = "$Revision$" |
15 |
|
|
|
# fix for people using python2.1 |
|
|
from __future__ import nested_scopes |
|
|
|
|
16 |
import os |
import os |
|
import string |
|
17 |
|
|
18 |
import Thuban.Lib.fileutil |
import Thuban.Lib.fileutil |
19 |
|
|
20 |
from Thuban.Model.color import Color |
from Thuban.Model.layer import Layer, RasterLayer |
21 |
|
|
22 |
from Thuban.Model.classification import * |
from Thuban.Model.classification import \ |
23 |
|
ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, ClassGroupMap |
24 |
|
from Thuban.Model.transientdb import AutoTransientTable, TransientJoinedTable |
25 |
|
from Thuban.Model.table import DBFTable, FIELDTYPE_STRING |
26 |
|
from Thuban.Model.data import DerivedShapeStore, ShapefileStore |
27 |
|
|
28 |
# |
from Thuban.Model.xmlwriter import XMLWriter |
29 |
# one level of indention |
from postgisdb import PostGISConnection, PostGISShapeStore |
|
# |
|
|
TAB = " " |
|
30 |
|
|
31 |
def relative_filename(dir, filename): |
def relative_filename(dir, filename): |
32 |
"""Return a filename relative to dir for the absolute file name absname. |
"""Return a filename relative to dir for the absolute file name absname. |
40 |
else: |
else: |
41 |
return filename |
return filename |
42 |
|
|
|
def escape(data): |
|
|
"""Escape &, \", ', <, and > in a string of data. |
|
|
""" |
|
|
data = string.replace(data, "&", "&") |
|
|
data = string.replace(data, "<", "<") |
|
|
data = string.replace(data, ">", ">") |
|
|
data = string.replace(data, '"', """) |
|
|
data = string.replace(data, "'", "'") |
|
|
return data |
|
43 |
|
|
44 |
class XMLWriter: |
def sort_data_stores(stores): |
45 |
"""Abstract XMLWriter. |
"""Return a topologically sorted version of the sequence of data containers |
46 |
|
|
47 |
Should be overridden to provide specific object saving functionality. |
The list is sorted so that data containers that depend on other data |
48 |
|
containers have higher indexes than the containers they depend on. |
49 |
""" |
""" |
50 |
|
if not stores: |
51 |
def __init__(self): |
return [] |
52 |
self.filename = None |
processed = {} |
53 |
pass |
result = [] |
54 |
|
todo = stores[:] |
55 |
def write(self, file_or_filename): |
while todo: |
56 |
"""Write the session to a file. |
# It doesn't really matter which if the items of todo is |
57 |
|
# processed next, but if we take the first one, the order is |
58 |
The argument may be either a file object or a filename. If it's |
# preserved to some degree which makes writing some of the test |
59 |
a filename, the file will be opened for writing. Files of |
# cases easier. |
60 |
shapefiles will be stored as filenames relative to the directory |
container = todo.pop(0) |
61 |
the file is stored in (as given by os.path.dirname(filename)) if |
if id(container) in processed: |
62 |
they have a common parent directory other than the root |
continue |
63 |
directory. |
deps = [dep for dep in container.Dependencies() |
64 |
|
if id(dep) not in processed] |
65 |
If the argument is a file object (which is determined by the |
if deps: |
66 |
presence of a write method) all filenames will be absolute |
todo.append(container) |
67 |
filenames. |
todo.extend(deps) |
|
""" |
|
|
|
|
|
# keep track of how many levels of indentation to write |
|
|
self.indent_level = 0 |
|
|
# track whether an element is currently open. see open_element(). |
|
|
self.element_open = 0 |
|
|
|
|
|
if hasattr(file_or_filename, "write"): |
|
|
# it's a file object |
|
|
self.file = file_or_filename |
|
|
self.dir = "" |
|
68 |
else: |
else: |
69 |
self.filename = file_or_filename |
result.append(container) |
70 |
self.dir = os.path.dirname(self.filename) |
processed[id(container)] = 1 |
71 |
self.file = open(self.filename, 'w') |
return result |
|
|
|
|
def close(self): |
|
|
assert self.indent_level == 0 |
|
|
if self.filename is not None: |
|
|
self.file.close() |
|
|
|
|
|
def write_header(self, doctype, system): |
|
|
"""Write the XML header""" |
|
|
self.file.write('<?xml version="1.0" encoding="UTF-8"?>\n') |
|
|
self.file.write('<!DOCTYPE %s SYSTEM "%s">\n' % (doctype, system)) |
|
|
|
|
|
def open_element(self, element, attrs = {}): |
|
|
|
|
|
# |
|
|
# we note when an element is opened so that if two open_element() |
|
|
# calls are made successively we can end the currently open |
|
|
# tag and will later write a proper close tag. otherwise, |
|
|
# if a close_element() call is made directly after an open_element() |
|
|
# call we will close the tag with a /> |
|
|
# |
|
|
if self.element_open == 1: |
|
|
self.file.write(">\n") |
|
|
|
|
|
self.element_open = 1 |
|
|
|
|
|
# Helper function to write an element open tag with attributes |
|
|
self.file.write("%s<%s" % (TAB*self.indent_level, element)) |
|
|
self.__write_attribs(attrs) |
|
72 |
|
|
|
self.indent_level += 1 |
|
73 |
|
|
|
def close_element(self, element): |
|
|
self.indent_level -= 1 |
|
|
assert self.indent_level >= 0 |
|
|
|
|
|
# see open_element() for an explanation |
|
|
if self.element_open == 1: |
|
|
self.element_open = 0 |
|
|
self.file.write("/>\n") |
|
|
else: |
|
|
self.file.write("%s</%s>\n" % (TAB*self.indent_level, element)) |
|
|
|
|
|
def write_element(self, element, attrs = {}): |
|
|
"""write an element that won't need a closing tag""" |
|
|
self.open_element(element, attrs) |
|
|
self.close_element(element) |
|
|
|
|
|
def __write_attribs(self, attrs): |
|
|
for name, value in attrs.items(): |
|
|
self.file.write(' %s="%s"' % (escape(name), escape(value))) |
|
|
|
|
74 |
class SessionSaver(XMLWriter): |
class SessionSaver(XMLWriter): |
75 |
|
|
76 |
"""Class to serialize a session into an XML file. |
"""Class to serialize a session into an XML file. |
87 |
def __init__(self, session): |
def __init__(self, session): |
88 |
XMLWriter.__init__(self) |
XMLWriter.__init__(self) |
89 |
self.session = session |
self.session = session |
90 |
|
# Map object ids to the ids used in the thuban files |
91 |
|
self.idmap = {} |
92 |
|
|
93 |
|
def get_id(self, obj): |
94 |
|
"""Return the id used in the thuban file for the object obj""" |
95 |
|
return self.idmap.get(id(obj)) |
96 |
|
|
97 |
|
def define_id(self, obj, value = None): |
98 |
|
if value is None: |
99 |
|
value = "D" + str(id(obj)) |
100 |
|
self.idmap[id(obj)] = value |
101 |
|
return value |
102 |
|
|
103 |
|
def has_id(self, obj): |
104 |
|
return self.idmap.has_key(id(obj)) |
105 |
|
|
106 |
def write(self, file_or_filename): |
def write(self, file_or_filename): |
107 |
XMLWriter.write(self, file_or_filename) |
XMLWriter.write(self, file_or_filename) |
108 |
|
|
109 |
self.write_header("session", "thuban.dtd") |
self.write_header("session", "thuban-0.9.dtd") |
110 |
self.write_session(self.session) |
self.write_session(self.session) |
111 |
self.close() |
self.close() |
112 |
|
|
131 |
attrs["title"] = session.title |
attrs["title"] = session.title |
132 |
for name, uri in namespaces: |
for name, uri in namespaces: |
133 |
attrs["xmlns:" + name] = uri |
attrs["xmlns:" + name] = uri |
134 |
|
# default name space |
135 |
|
attrs["xmlns"] = \ |
136 |
|
"http://thuban.intevation.org/dtds/thuban-0.9.dtd" |
137 |
self.open_element("session", attrs) |
self.open_element("session", attrs) |
138 |
|
self.write_db_connections(session) |
139 |
|
self.write_data_containers(session) |
140 |
for map in session.Maps(): |
for map in session.Maps(): |
141 |
self.write_map(map) |
self.write_map(map) |
142 |
self.close_element("session") |
self.close_element("session") |
143 |
|
|
144 |
|
def write_db_connections(self, session): |
145 |
|
for conn in session.DBConnections(): |
146 |
|
if isinstance(conn, PostGISConnection): |
147 |
|
self.write_element("dbconnection", |
148 |
|
{"id": self.define_id(conn), |
149 |
|
"dbtype": "postgis", |
150 |
|
"host": conn.host, |
151 |
|
"port": conn.port, |
152 |
|
"user": conn.user, |
153 |
|
"dbname": conn.dbname}) |
154 |
|
else: |
155 |
|
raise ValueError("Can't handle db connection %r" % conn) |
156 |
|
|
157 |
|
def write_data_containers(self, session): |
158 |
|
containers = sort_data_stores(session.DataContainers()) |
159 |
|
for container in containers: |
160 |
|
if isinstance(container, AutoTransientTable): |
161 |
|
# AutoTransientTable instances are invisible in the |
162 |
|
# thuban files. They're only used internally. To make |
163 |
|
# sure that containers depending on AutoTransientTable |
164 |
|
# instances refer to the right real containers we give |
165 |
|
# the AutoTransientTable instances the same id as the |
166 |
|
# source they depend on. |
167 |
|
self.define_id(container, |
168 |
|
self.get_id(container.Dependencies()[0])) |
169 |
|
continue |
170 |
|
|
171 |
|
idvalue = self.define_id(container) |
172 |
|
if isinstance(container, ShapefileStore): |
173 |
|
self.define_id(container.Table(), idvalue) |
174 |
|
filename = relative_filename(self.dir, container.FileName()) |
175 |
|
self.write_element("fileshapesource", |
176 |
|
{"id": idvalue, "filename": filename, |
177 |
|
"filetype": "shapefile"}) |
178 |
|
elif isinstance(container, DerivedShapeStore): |
179 |
|
shapesource, table = container.Dependencies() |
180 |
|
self.write_element("derivedshapesource", |
181 |
|
{"id": idvalue, |
182 |
|
"shapesource": self.get_id(shapesource), |
183 |
|
"table": self.get_id(table)}) |
184 |
|
elif isinstance(container, PostGISShapeStore): |
185 |
|
conn = container.DBConnection() |
186 |
|
self.write_element("dbshapesource", |
187 |
|
{"id": idvalue, |
188 |
|
"dbconn": self.get_id(conn), |
189 |
|
"tablename": container.TableName()}) |
190 |
|
elif isinstance(container, DBFTable): |
191 |
|
filename = relative_filename(self.dir, container.FileName()) |
192 |
|
self.write_element("filetable", |
193 |
|
{"id": idvalue, |
194 |
|
"title": container.Title(), |
195 |
|
"filename": filename, |
196 |
|
"filetype": "DBF"}) |
197 |
|
elif isinstance(container, TransientJoinedTable): |
198 |
|
left, right = container.Dependencies() |
199 |
|
left_field = container.left_field |
200 |
|
right_field = container.right_field |
201 |
|
self.write_element("jointable", |
202 |
|
{"id": idvalue, |
203 |
|
"title": container.Title(), |
204 |
|
"right": self.get_id(right), |
205 |
|
"rightcolumn": right_field, |
206 |
|
"left": self.get_id(left), |
207 |
|
"leftcolumn": left_field, |
208 |
|
"jointype": container.JoinType()}) |
209 |
|
else: |
210 |
|
raise ValueError("Can't handle container %r" % container) |
211 |
|
|
212 |
|
|
213 |
def write_map(self, map): |
def write_map(self, map): |
214 |
"""Write the map and its contents. |
"""Write the map and its contents. |
215 |
|
|
218 |
element, call write_layer for each layer contained in the map |
element, call write_layer for each layer contained in the map |
219 |
and finally call write_label_layer to write the label layer. |
and finally call write_label_layer to write the label layer. |
220 |
""" |
""" |
221 |
self.open_element('map title="%s"' % escape(map.title)) |
self.open_element('map title="%s"' % self.encode(map.title)) |
222 |
self.write_projection(map.projection) |
self.write_projection(map.projection) |
223 |
for layer in map.Layers(): |
for layer in map.Layers(): |
224 |
self.write_layer(layer) |
self.write_layer(layer) |
229 |
"""Write the projection. |
"""Write the projection. |
230 |
""" |
""" |
231 |
if projection and len(projection.params) > 0: |
if projection and len(projection.params) > 0: |
232 |
self.open_element("projection") |
self.open_element("projection", {"name": projection.GetName()}) |
233 |
for param in projection.params: |
for param in projection.params: |
234 |
self.write_element('parameter value="%s"' % escape(param)) |
self.write_element('parameter value="%s"' % |
235 |
|
self.encode(param)) |
236 |
self.close_element("projection") |
self.close_element("projection") |
237 |
|
|
238 |
def write_layer(self, layer, attrs = None): |
def write_layer(self, layer, attrs = None): |
242 |
given, should be a mapping from attribute names to attribute |
given, should be a mapping from attribute names to attribute |
243 |
values. The values should not be XML-escaped yet. |
values. The values should not be XML-escaped yet. |
244 |
""" |
""" |
|
lc = layer.GetClassification() |
|
245 |
|
|
246 |
if attrs is None: |
if attrs is None: |
247 |
attrs = {} |
attrs = {} |
248 |
|
|
249 |
attrs["title"] = layer.title |
attrs["title"] = layer.title |
250 |
attrs["filename"] = relative_filename(self.dir, layer.filename) |
attrs["visible"] = ("false", "true")[int(layer.Visible())] |
|
attrs["stroke"] = lc.GetDefaultLineColor().hex() |
|
|
attrs["stroke_width"] = str(lc.GetDefaultLineWidth()) |
|
|
attrs["fill"] = lc.GetDefaultFill().hex() |
|
|
|
|
|
self.open_element("layer", attrs) |
|
251 |
|
|
252 |
proj = layer.GetProjection() |
if isinstance(layer, Layer): |
253 |
if proj is not None: |
attrs["shapestore"] = self.get_id(layer.ShapeStore()) |
|
self.write_projection(proj) |
|
254 |
|
|
255 |
self.write_classification(layer) |
lc = layer.GetClassification() |
256 |
|
attrs["stroke"] = lc.GetDefaultLineColor().hex() |
257 |
self.close_element("layer") |
attrs["stroke_width"] = str(lc.GetDefaultLineWidth()) |
258 |
|
attrs["fill"] = lc.GetDefaultFill().hex() |
259 |
|
|
260 |
|
self.open_element("layer", attrs) |
261 |
|
self.write_projection(layer.GetProjection()) |
262 |
|
self.write_classification(layer) |
263 |
|
self.close_element("layer") |
264 |
|
elif isinstance(layer, RasterLayer): |
265 |
|
attrs["filename"] = relative_filename(self.dir, layer.filename) |
266 |
|
self.open_element("rasterlayer", attrs) |
267 |
|
self.write_projection(layer.GetProjection()) |
268 |
|
self.close_element("rasterlayer") |
269 |
|
|
270 |
def write_classification(self, layer, attrs = None): |
def write_classification(self, layer, attrs = None): |
271 |
|
"""Write Classification information.""" |
272 |
|
|
273 |
if attrs is None: |
if attrs is None: |
274 |
attrs = {} |
attrs = {} |
275 |
|
|
276 |
lc = layer.GetClassification() |
lc = layer.GetClassification() |
277 |
|
|
278 |
field = lc.GetField() |
field = layer.GetClassificationColumn() |
279 |
|
|
280 |
# |
# |
281 |
# there isn't a classification of anything |
# there isn't a classification of anything so do nothing |
|
# so don't do anything |
|
282 |
# |
# |
283 |
if field is None: return |
if field is None: return |
284 |
|
|
285 |
attrs["field"] = field |
attrs["field"] = field |
286 |
attrs["field_type"] = str(lc.GetFieldType()) |
attrs["field_type"] = str(layer.GetFieldType(field)) |
287 |
self.open_element("classification", attrs) |
self.open_element("classification", attrs) |
288 |
|
|
289 |
|
for g in lc: |
290 |
types = [[lambda p: 'clnull label="%s"' % p.GetLabel(), |
if isinstance(g, ClassGroupDefault): |
291 |
lambda p: 'clnull'], |
open_el = 'clnull label="%s"' % self.encode(g.GetLabel()) |
292 |
[lambda p: 'clpoint label="%s" value="%s"' % |
close_el = 'clnull' |
293 |
(p.GetLabel(), str(p.GetValue())), |
elif isinstance(g, ClassGroupSingleton): |
294 |
lambda p: 'clpoint'], |
if layer.GetFieldType(field) == FIELDTYPE_STRING: |
295 |
[lambda p: 'clrange label="%s" min="%s" max="%s"' % |
value = self.encode(g.GetValue()) |
296 |
(p.GetLabel(), |
else: |
297 |
str(p.GetMin()), (str(p.GetMax()))), |
value = str(g.GetValue()) |
298 |
lambda p: 'clrange']] |
open_el = 'clpoint label="%s" value="%s"' \ |
299 |
|
% (self.encode(g.GetLabel()), value) |
300 |
def write_class_group(group): |
close_el = 'clpoint' |
301 |
type = -1 |
elif isinstance(g, ClassGroupRange): |
302 |
if isinstance(group, ClassGroupDefault): type = 0 |
open_el = 'clrange label="%s" range="%s"' \ |
303 |
elif isinstance(group, ClassGroupSingleton): type = 1 |
% (self.encode(g.GetLabel()), str(g.GetRange())) |
304 |
elif isinstance(group, ClassGroupRange): type = 2 |
close_el = 'clrange' |
305 |
elif isinstance(group, ClassGroupMap): type = 3 |
else: |
306 |
assert type >= 0 |
assert False, _("Unsupported group type in classification") |
307 |
|
continue |
308 |
if type <= 2: |
|
309 |
data = group.GetProperties() |
data = g.GetProperties() |
310 |
dict = {'stroke' : data.GetLineColor().hex(), |
dict = {'stroke' : data.GetLineColor().hex(), |
311 |
'stroke_width': str(data.GetLineWidth()), |
'stroke_width': str(data.GetLineWidth()), |
312 |
'fill' : data.GetFill().hex()} |
'fill' : data.GetFill().hex()} |
313 |
|
|
314 |
self.open_element(types[type][0](group)) |
self.open_element(open_el) |
315 |
self.write_element("cldata", dict) |
self.write_element("cldata", dict) |
316 |
self.close_element(types[type][1](group)) |
self.close_element(close_el) |
|
else: pass # XXX: we need to handle maps |
|
|
|
|
|
for i in lc: |
|
|
write_class_group(i) |
|
317 |
|
|
318 |
self.close_element("classification") |
self.close_element("classification") |
319 |
|
|
326 |
for label in labels: |
for label in labels: |
327 |
self.write_element(('label x="%g" y="%g" text="%s"' |
self.write_element(('label x="%g" y="%g" text="%s"' |
328 |
' halign="%s" valign="%s"') |
' halign="%s" valign="%s"') |
329 |
% (label.x, label.y, label.text, label.halign, |
% (label.x, label.y, |
330 |
|
self.encode(label.text), |
331 |
|
label.halign, |
332 |
label.valign)) |
label.valign)) |
333 |
self.close_element('labellayer') |
self.close_element('labellayer') |
334 |
|
|