1 |
# Copyright (c) 2001, 2002 by Intevation GmbH |
# Copyright (c) 2001, 2002, 2003 by Intevation GmbH |
2 |
# Authors: |
# Authors: |
3 |
# Jan-Oliver Wagner <[email protected]> |
# Jan-Oliver Wagner <[email protected]> |
4 |
# Bernhard Herzog <[email protected]> |
# Bernhard Herzog <[email protected]> |
5 |
|
# Jonathan Coles <[email protected]> |
6 |
# |
# |
7 |
# This program is free software under the GPL (>=v2) |
# This program is free software under the GPL (>=v2) |
8 |
# Read the file COPYING coming with Thuban for details. |
# Read the file COPYING coming with Thuban for details. |
13 |
|
|
14 |
__version__ = "$Revision$" |
__version__ = "$Revision$" |
15 |
|
|
16 |
|
# fix for people using python2.1 |
17 |
|
from __future__ import nested_scopes |
18 |
|
|
19 |
import os |
import os |
20 |
import string |
import string |
21 |
|
|
23 |
|
|
24 |
from Thuban.Model.color import Color |
from Thuban.Model.color import Color |
25 |
|
|
26 |
|
from Thuban.Model.classification import \ |
27 |
|
ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, ClassGroupMap |
28 |
|
|
29 |
# |
# |
30 |
# one level of indention |
# one level of indention |
31 |
# |
# |
53 |
data = string.replace(data, "'", "'") |
data = string.replace(data, "'", "'") |
54 |
return data |
return data |
55 |
|
|
56 |
class Saver: |
class XMLWriter: |
57 |
|
"""Abstract XMLWriter. |
|
"""Class to serialize a session into an XML file. |
|
58 |
|
|
59 |
Applications built on top of Thuban may derive from this class and |
Should be overridden to provide specific object saving functionality. |
|
override or extend the methods to save additinal information. This |
|
|
additional information should take the form of additional attributes |
|
|
or elements whose names are prefixed with a namespace. To define a |
|
|
namespace derived classes should extend the write_session method to |
|
|
pass the namespaces to the default implementation. |
|
60 |
""" |
""" |
61 |
|
|
62 |
|
def __init__(self): |
63 |
def __init__(self, session): |
self.filename = None |
64 |
self.session = session |
pass |
65 |
|
|
66 |
def write(self, file_or_filename): |
def write(self, file_or_filename): |
67 |
"""Write the session to a file. |
"""Write the session to a file. |
74 |
directory. |
directory. |
75 |
|
|
76 |
If the argument is a file object (which is determined by the |
If the argument is a file object (which is determined by the |
77 |
presence of a write method) all filenames will be absolut |
presence of a write method) all filenames will be absolute |
78 |
filenames. |
filenames. |
79 |
""" |
""" |
80 |
|
|
88 |
self.file = file_or_filename |
self.file = file_or_filename |
89 |
self.dir = "" |
self.dir = "" |
90 |
else: |
else: |
91 |
filename = file_or_filename |
self.filename = file_or_filename |
92 |
self.dir = os.path.dirname(filename) |
self.dir = os.path.dirname(self.filename) |
93 |
self.file = open(filename, 'w') |
self.file = open(self.filename, 'w') |
94 |
self.write_header() |
|
95 |
self.write_session(self.session) |
def close(self): |
96 |
|
assert self.indent_level == 0 |
97 |
|
if self.filename is not None: |
98 |
|
self.file.close() |
99 |
|
|
100 |
if self.indent_level != 0: |
def write_header(self, doctype, system): |
101 |
raise ValueError("indent_level still positive!") |
"""Write the XML header""" |
102 |
|
self.file.write('<?xml version="1.0" encoding="UTF-8"?>\n') |
103 |
|
self.file.write('<!DOCTYPE %s SYSTEM "%s">\n' % (doctype, system)) |
104 |
|
|
|
def write_attribs(self, attrs): |
|
|
for name, value in attrs.items(): |
|
|
if isinstance(value, Color): |
|
|
value = value.hex() |
|
|
else: |
|
|
value = str(value) |
|
|
self.file.write(' %s="%s"' % (escape(name), escape(value))) |
|
|
|
|
105 |
def open_element(self, element, attrs = {}): |
def open_element(self, element, attrs = {}): |
106 |
|
|
107 |
# |
# |
118 |
|
|
119 |
# Helper function to write an element open tag with attributes |
# Helper function to write an element open tag with attributes |
120 |
self.file.write("%s<%s" % (TAB*self.indent_level, element)) |
self.file.write("%s<%s" % (TAB*self.indent_level, element)) |
121 |
self.write_attribs(attrs) |
self.__write_attribs(attrs) |
122 |
|
|
123 |
self.indent_level += 1 |
self.indent_level += 1 |
124 |
|
|
125 |
def close_element(self, element): |
def close_element(self, element): |
126 |
self.indent_level -= 1 |
self.indent_level -= 1 |
127 |
if self.indent_level < 0: |
assert self.indent_level >= 0 |
|
raise ValueError("close_element called too many times!") |
|
128 |
|
|
129 |
# see open_element() for an explanation |
# see open_element() for an explanation |
130 |
if self.element_open == 1: |
if self.element_open == 1: |
138 |
self.open_element(element, attrs) |
self.open_element(element, attrs) |
139 |
self.close_element(element) |
self.close_element(element) |
140 |
|
|
141 |
def write_header(self): |
def __write_attribs(self, attrs): |
142 |
"""Write the XML header""" |
for name, value in attrs.items(): |
143 |
self.file.write('<?xml version="1.0" encoding="UTF-8"?>\n') |
self.file.write(' %s="%s"' % (self.encode(name), |
144 |
self.file.write('<!DOCTYPE session SYSTEM "thuban.dtd">\n') |
self.encode(value))) |
145 |
|
|
146 |
|
def encode(self, str): |
147 |
|
"""Assume that str is in Latin1, escape it, and encode it in UTF-8. |
148 |
|
|
149 |
|
If str is None, return None |
150 |
|
""" |
151 |
|
|
152 |
|
if str is not None: |
153 |
|
return unicode(escape(str),'latin1').encode("utf8") |
154 |
|
#return escape(str).encode("utf8") |
155 |
|
else: |
156 |
|
return None |
157 |
|
|
158 |
|
class SessionSaver(XMLWriter): |
159 |
|
|
160 |
|
"""Class to serialize a session into an XML file. |
161 |
|
|
162 |
|
Applications built on top of Thuban may derive from this class and |
163 |
|
override or extend the methods to save additional information. This |
164 |
|
additional information should take the form of additional attributes |
165 |
|
or elements whose names are prefixed with a namespace. To define a |
166 |
|
namespace derived classes should extend the write_session method to |
167 |
|
pass the namespaces to the default implementation. |
168 |
|
""" |
169 |
|
|
170 |
|
|
171 |
|
def __init__(self, session): |
172 |
|
XMLWriter.__init__(self) |
173 |
|
self.session = session |
174 |
|
|
175 |
|
def write(self, file_or_filename): |
176 |
|
XMLWriter.write(self, file_or_filename) |
177 |
|
|
178 |
|
self.write_header("session", "thuban.dtd") |
179 |
|
self.write_session(self.session) |
180 |
|
self.close() |
181 |
|
|
182 |
def write_session(self, session, attrs = None, namespaces = ()): |
def write_session(self, session, attrs = None, namespaces = ()): |
183 |
"""Write the session and its contents |
"""Write the session and its contents |
213 |
element, call write_layer for each layer contained in the map |
element, call write_layer for each layer contained in the map |
214 |
and finally call write_label_layer to write the label layer. |
and finally call write_label_layer to write the label layer. |
215 |
""" |
""" |
216 |
write = self.file.write |
self.open_element('map title="%s"' % self.encode(map.title)) |
|
self.open_element('map title="%s"' % escape(map.title)) |
|
217 |
self.write_projection(map.projection) |
self.write_projection(map.projection) |
218 |
for layer in map.Layers(): |
for layer in map.Layers(): |
219 |
self.write_layer(layer) |
self.write_layer(layer) |
224 |
"""Write the projection. |
"""Write the projection. |
225 |
""" |
""" |
226 |
if projection and len(projection.params) > 0: |
if projection and len(projection.params) > 0: |
227 |
self.open_element("projection") |
self.open_element("projection", {"name": projection.GetName()}) |
228 |
for param in projection.params: |
for param in projection.params: |
229 |
self.write_element('parameter value="%s"' % escape(param)) |
self.write_element('parameter value="%s"' % |
230 |
|
self.encode(param)) |
231 |
self.close_element("projection") |
self.close_element("projection") |
232 |
|
|
233 |
def write_layer(self, layer, attrs = None): |
def write_layer(self, layer, attrs = None): |
237 |
given, should be a mapping from attribute names to attribute |
given, should be a mapping from attribute names to attribute |
238 |
values. The values should not be XML-escaped yet. |
values. The values should not be XML-escaped yet. |
239 |
""" |
""" |
240 |
lc = layer.classification |
lc = layer.GetClassification() |
241 |
|
|
242 |
if attrs is None: |
if attrs is None: |
243 |
attrs = {} |
attrs = {} |
244 |
attrs["title"] = layer.title |
|
245 |
attrs["filename"] = relative_filename(self.dir, layer.filename) |
attrs["title"] = layer.title |
246 |
attrs["stroke_width"] = str(lc.GetDefaultStrokeWidth()) |
attrs["filename"] = relative_filename(self.dir, layer.filename) |
247 |
fill = lc.GetDefaultFill() |
attrs["stroke"] = lc.GetDefaultLineColor().hex() |
248 |
if fill is None: |
attrs["stroke_width"] = str(lc.GetDefaultLineWidth()) |
249 |
attrs["fill"] = "None" |
attrs["fill"] = lc.GetDefaultFill().hex() |
250 |
else: |
attrs["visible"] = ("false", "true")[int(layer.Visible())] |
|
attrs["fill"] = fill.hex() |
|
|
stroke = lc.GetDefaultStroke() |
|
|
if stroke is None: |
|
|
attrs["stroke"] = "None" |
|
|
else: |
|
|
attrs["stroke"] = stroke.hex() |
|
251 |
|
|
252 |
self.open_element("layer", attrs) |
self.open_element("layer", attrs) |
253 |
|
|
254 |
|
proj = layer.GetProjection() |
255 |
|
if proj is not None: |
256 |
|
self.write_projection(proj) |
257 |
|
|
258 |
self.write_classification(layer) |
self.write_classification(layer) |
259 |
|
|
260 |
self.close_element("layer") |
self.close_element("layer") |
261 |
|
|
262 |
def write_classification(self, layer, attrs = None): |
def write_classification(self, layer, attrs = None): |
263 |
if attrs is None: |
if attrs is None: |
264 |
attrs = {} |
attrs = {} |
265 |
|
|
266 |
lc = layer.classification |
lc = layer.GetClassification() |
267 |
|
|
268 |
field = lc.field |
field = lc.GetField() |
269 |
|
|
270 |
# |
# |
271 |
# there isn't a classification of anything |
# there isn't a classification of anything |
274 |
if field is None: return |
if field is None: return |
275 |
|
|
276 |
attrs["field"] = field |
attrs["field"] = field |
277 |
|
attrs["field_type"] = str(lc.GetFieldType()) |
278 |
self.open_element("classification", attrs) |
self.open_element("classification", attrs) |
279 |
|
|
280 |
def write_class_data(data): |
|
281 |
dict = {'stroke' : data.GetStroke(), |
types = [[lambda p: 'clnull label="%s"' % self.encode(p.GetLabel()), |
282 |
'stroke_width': data.GetStrokeWidth(), |
lambda p: 'clnull'], |
283 |
'fill' : data.GetFill()} |
[lambda p: 'clpoint label="%s" value="%s"' % |
284 |
self.write_element("cldata", dict) |
(self.encode(p.GetLabel()), str(p.GetValue())), |
285 |
|
lambda p: 'clpoint'], |
286 |
self.open_element("clnull") |
[lambda p: 'clrange label="%s" range="%s"' % |
287 |
write_class_data(lc.GetDefaultData()) |
(self.encode(p.GetLabel()), |
288 |
self.close_element("clnull") |
str(p.GetRange())), |
289 |
|
lambda p: 'clrange']] |
290 |
if lc.points != {}: |
|
291 |
for value, data in lc.points.items(): |
def write_class_group(group): |
292 |
self.open_element('clpoint value="%s"' % (escape(str(value)))) |
type = -1 |
293 |
write_class_data(data) |
if isinstance(group, ClassGroupDefault): type = 0 |
294 |
self.close_element('clpoint') |
elif isinstance(group, ClassGroupSingleton): type = 1 |
295 |
|
elif isinstance(group, ClassGroupRange): type = 2 |
296 |
if lc.ranges != []: |
elif isinstance(group, ClassGroupMap): type = 3 |
297 |
for p in lc.ranges: |
assert type >= 0 |
298 |
self.open_element('clrange min="%s" max="%s"' |
|
299 |
% (escape(str(p[0])), escape(str(p[1])))) |
if type <= 2: |
300 |
write_class_data(p[2]) |
data = group.GetProperties() |
301 |
self.close_element('clrange') |
dict = {'stroke' : data.GetLineColor().hex(), |
302 |
|
'stroke_width': str(data.GetLineWidth()), |
303 |
|
'fill' : data.GetFill().hex()} |
304 |
|
|
305 |
|
self.open_element(types[type][0](group)) |
306 |
|
self.write_element("cldata", dict) |
307 |
|
self.close_element(types[type][1](group)) |
308 |
|
else: pass # XXX: we need to handle maps |
309 |
|
|
310 |
|
for i in lc: |
311 |
|
write_class_group(i) |
312 |
|
|
313 |
self.close_element("classification") |
self.close_element("classification") |
314 |
|
|
321 |
for label in labels: |
for label in labels: |
322 |
self.write_element(('label x="%g" y="%g" text="%s"' |
self.write_element(('label x="%g" y="%g" text="%s"' |
323 |
' halign="%s" valign="%s"') |
' halign="%s" valign="%s"') |
324 |
% (label.x, label.y, label.text, label.halign, |
% (label.x, label.y, |
325 |
|
self.encode(label.text), |
326 |
|
label.halign, |
327 |
label.valign)) |
label.valign)) |
328 |
self.close_element('labellayer') |
self.close_element('labellayer') |
329 |
|
|
336 |
|
|
337 |
The optional argument saver_class is the class to use to serialize |
The optional argument saver_class is the class to use to serialize |
338 |
the session. By default or if it's None, the saver class will be |
the session. By default or if it's None, the saver class will be |
339 |
Saver. |
SessionSaver. |
340 |
|
|
341 |
If writing the session is successful call the session's |
If writing the session is successful call the session's |
342 |
UnsetModified method |
UnsetModified method |
343 |
""" |
""" |
344 |
if saver_class is None: |
if saver_class is None: |
345 |
saver_class = Saver |
saver_class = SessionSaver |
346 |
saver = saver_class(session) |
saver = saver_class(session) |
347 |
saver.write(file) |
saver.write(file) |
348 |
|
|