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. |
14 |
__version__ = "$Revision$" |
__version__ = "$Revision$" |
15 |
|
|
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.color import Color |
21 |
|
from Thuban.Model.layer import Layer, RasterLayer |
22 |
|
|
23 |
# |
from Thuban.Model.classification import \ |
24 |
# one level of indention |
ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, ClassGroupMap |
25 |
# |
|
26 |
TAB = " " |
from Thuban.Model.xmlwriter import XMLWriter |
27 |
|
|
28 |
def relative_filename(dir, filename): |
def relative_filename(dir, filename): |
29 |
"""Return a filename relative to dir for the absolute file name absname. |
"""Return a filename relative to dir for the absolute file name absname. |
37 |
else: |
else: |
38 |
return filename |
return filename |
39 |
|
|
40 |
def escape(data): |
class SessionSaver(XMLWriter): |
|
"""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 |
|
|
|
|
|
class Saver: |
|
41 |
|
|
42 |
"""Class to serialize a session into an XML file. |
"""Class to serialize a session into an XML file. |
43 |
|
|
44 |
Applications built on top of Thuban may derive from this class and |
Applications built on top of Thuban may derive from this class and |
45 |
override or extend the methods to save additinal information. This |
override or extend the methods to save additional information. This |
46 |
additional information should take the form of additional attributes |
additional information should take the form of additional attributes |
47 |
or elements whose names are prefixed with a namespace. To define a |
or elements whose names are prefixed with a namespace. To define a |
48 |
namespace derived classes should extend the write_session method to |
namespace derived classes should extend the write_session method to |
51 |
|
|
52 |
|
|
53 |
def __init__(self, session): |
def __init__(self, session): |
54 |
|
XMLWriter.__init__(self) |
55 |
self.session = session |
self.session = session |
56 |
|
|
57 |
def write(self, file_or_filename): |
def write(self, file_or_filename): |
58 |
"""Write the session to a file. |
XMLWriter.write(self, file_or_filename) |
|
|
|
|
The argument may be either a file object or a filename. If it's |
|
|
a filename, the file will be opened for writing. Files of |
|
|
shapefiles will be stored as filenames relative to the directory |
|
|
the file is stored in (as given by os.path.dirname(filename)) if |
|
|
they have a common parent directory other than the root |
|
|
directory. |
|
|
|
|
|
If the argument is a file object (which is determined by the |
|
|
presence of a write method) all filenames will be absolut |
|
|
filenames. |
|
|
""" |
|
|
|
|
|
self.indent_level = 0 |
|
59 |
|
|
60 |
if hasattr(file_or_filename, "write"): |
self.write_header("session", "thuban.dtd") |
|
# it's a file object |
|
|
self.file = file_or_filename |
|
|
self.dir = "" |
|
|
else: |
|
|
filename = file_or_filename |
|
|
self.dir = os.path.dirname(filename) |
|
|
self.file = open(filename, 'w') |
|
|
self.write_header() |
|
61 |
self.write_session(self.session) |
self.write_session(self.session) |
62 |
|
self.close() |
|
if self.indent_level != 0: |
|
|
raise ValueError("indent_level still positive!") |
|
|
|
|
|
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))) |
|
|
|
|
|
def open_element(self, element, attrs = {}): |
|
|
# Helper function to write an element open tag with attributes |
|
|
self.file.write("%s<%s" % (TAB*self.indent_level, element)) |
|
|
self.write_attribs(attrs) |
|
|
self.file.write(">\n") |
|
|
|
|
|
self.indent_level += 1 |
|
|
|
|
|
def close_element(self, element): |
|
|
self.indent_level -= 1 |
|
|
if self.indent_level < 0: |
|
|
raise ValueError("close_element called too many times!") |
|
|
self.file.write("%s</%s>\n" % (TAB*self.indent_level, element)) |
|
|
|
|
|
def write_element(self, element, attrs = {}): |
|
|
# Helper function to write an element open tag with attributes |
|
|
self.file.write("%s<%s" % (TAB*self.indent_level, element)) |
|
|
self.write_attribs(attrs) |
|
|
self.file.write("/>\n") |
|
|
|
|
|
def write_header(self): |
|
|
"""Write the XML header""" |
|
|
self.file.write('<?xml version="1.0" encoding="UTF-8"?>\n') |
|
|
self.file.write('<!DOCTYPE session SYSTEM "thuban.dtd">\n') |
|
63 |
|
|
64 |
def write_session(self, session, attrs = None, namespaces = ()): |
def write_session(self, session, attrs = None, namespaces = ()): |
65 |
"""Write the session and its contents |
"""Write the session and its contents |
95 |
element, call write_layer for each layer contained in the map |
element, call write_layer for each layer contained in the map |
96 |
and finally call write_label_layer to write the label layer. |
and finally call write_label_layer to write the label layer. |
97 |
""" |
""" |
98 |
write = self.file.write |
self.open_element('map title="%s"' % self.encode(map.title)) |
|
self.open_element('map title="%s"' % escape(map.title)) |
|
99 |
self.write_projection(map.projection) |
self.write_projection(map.projection) |
100 |
for layer in map.Layers(): |
for layer in map.Layers(): |
101 |
self.write_layer(layer) |
self.write_layer(layer) |
106 |
"""Write the projection. |
"""Write the projection. |
107 |
""" |
""" |
108 |
if projection and len(projection.params) > 0: |
if projection and len(projection.params) > 0: |
109 |
self.open_element("projection") |
self.open_element("projection", {"name": projection.GetName()}) |
110 |
for param in projection.params: |
for param in projection.params: |
111 |
self.write_element('parameter value="%s"' % escape(param)) |
self.write_element('parameter value="%s"' % |
112 |
|
self.encode(param)) |
113 |
self.close_element("projection") |
self.close_element("projection") |
114 |
|
|
115 |
def write_layer(self, layer, attrs = None): |
def write_layer(self, layer, attrs = None): |
119 |
given, should be a mapping from attribute names to attribute |
given, should be a mapping from attribute names to attribute |
120 |
values. The values should not be XML-escaped yet. |
values. The values should not be XML-escaped yet. |
121 |
""" |
""" |
122 |
|
|
123 |
if attrs is None: |
if attrs is None: |
124 |
attrs = {} |
attrs = {} |
125 |
attrs["title"] = layer.title |
|
126 |
attrs["filename"] = relative_filename(self.dir, layer.filename) |
attrs["title"] = layer.title |
127 |
attrs["stroke_width"] = str(layer.stroke_width) |
attrs["visible"] = ("false", "true")[int(layer.Visible())] |
128 |
fill = layer.fill |
|
129 |
if fill is None: |
if isinstance(layer, Layer): |
130 |
attrs["fill"] = "None" |
attrs["filename"] = relative_filename(self.dir, |
131 |
else: |
layer.ShapeStore().FileName()) |
132 |
attrs["fill"] = fill.hex() |
|
133 |
stroke = layer.stroke |
lc = layer.GetClassification() |
134 |
if stroke is None: |
attrs["stroke"] = lc.GetDefaultLineColor().hex() |
135 |
attrs["stroke"] = "None" |
attrs["stroke_width"] = str(lc.GetDefaultLineWidth()) |
136 |
else: |
attrs["fill"] = lc.GetDefaultFill().hex() |
137 |
attrs["stroke"] = stroke.hex() |
|
138 |
|
self.open_element("layer", attrs) |
139 |
self.open_element("layer", attrs) |
self.write_projection(layer.GetProjection()) |
140 |
self.write_classification(layer) |
self.write_classification(layer) |
141 |
self.close_element("layer") |
self.close_element("layer") |
142 |
|
|
143 |
|
elif isinstance(layer, RasterLayer): |
144 |
|
attrs["filename"] = relative_filename(self.dir, layer.filename) |
145 |
|
self.open_element("rasterlayer", attrs) |
146 |
|
self.write_projection(layer.GetProjection()) |
147 |
|
self.close_element("rasterlayer") |
148 |
|
|
149 |
def write_classification(self, layer, attrs = None): |
def write_classification(self, layer, attrs = None): |
150 |
if attrs is None: |
if attrs is None: |
151 |
attrs = {} |
attrs = {} |
152 |
|
|
153 |
lc = layer.classification |
lc = layer.GetClassification() |
154 |
|
|
155 |
field = lc.field |
field = lc.GetField() |
156 |
|
|
157 |
# |
# |
158 |
# there isn't a classification of anything |
# there isn't a classification of anything |
161 |
if field is None: return |
if field is None: return |
162 |
|
|
163 |
attrs["field"] = field |
attrs["field"] = field |
164 |
|
attrs["field_type"] = str(lc.GetFieldType()) |
165 |
self.open_element("classification", attrs) |
self.open_element("classification", attrs) |
166 |
|
|
167 |
if lc.NullData is not None: |
|
168 |
self.open_element("clnull") |
types = [[lambda p: 'clnull label="%s"' % self.encode(p.GetLabel()), |
169 |
self.write_element("cldata", lc.NullData) |
lambda p: 'clnull'], |
170 |
self.close_element("clnull") |
[lambda p: 'clpoint label="%s" value="%s"' % |
171 |
|
(self.encode(p.GetLabel()), str(p.GetValue())), |
172 |
if lc.points != {}: |
lambda p: 'clpoint'], |
173 |
for value, data in lc.points.items(): |
[lambda p: 'clrange label="%s" range="%s"' % |
174 |
self.open_element('clpoint value="%s"' % (escape(str(value)))) |
(self.encode(p.GetLabel()), |
175 |
self.write_element("cldata", data) |
str(p.GetRange())), |
176 |
self.close_element('clpoint') |
lambda p: 'clrange']] |
177 |
|
|
178 |
if lc.ranges != []: |
def write_class_group(group): |
179 |
for p in lc.ranges: |
type = -1 |
180 |
self.open_element('clrange min="%s" max="%s"' |
if isinstance(group, ClassGroupDefault): type = 0 |
181 |
% (escape(str(p[0])), escape(str(p[1])))) |
elif isinstance(group, ClassGroupSingleton): type = 1 |
182 |
self.write_element("cldata", p[2]) |
elif isinstance(group, ClassGroupRange): type = 2 |
183 |
self.close_element('clrange') |
elif isinstance(group, ClassGroupMap): type = 3 |
184 |
|
assert type >= 0 |
185 |
|
|
186 |
|
if type <= 2: |
187 |
|
data = group.GetProperties() |
188 |
|
dict = {'stroke' : data.GetLineColor().hex(), |
189 |
|
'stroke_width': str(data.GetLineWidth()), |
190 |
|
'fill' : data.GetFill().hex()} |
191 |
|
|
192 |
|
self.open_element(types[type][0](group)) |
193 |
|
self.write_element("cldata", dict) |
194 |
|
self.close_element(types[type][1](group)) |
195 |
|
else: pass # XXX: we need to handle maps |
196 |
|
|
197 |
|
for i in lc: |
198 |
|
write_class_group(i) |
199 |
|
|
200 |
self.close_element("classification") |
self.close_element("classification") |
201 |
|
|
208 |
for label in labels: |
for label in labels: |
209 |
self.write_element(('label x="%g" y="%g" text="%s"' |
self.write_element(('label x="%g" y="%g" text="%s"' |
210 |
' halign="%s" valign="%s"') |
' halign="%s" valign="%s"') |
211 |
% (label.x, label.y, label.text, label.halign, |
% (label.x, label.y, |
212 |
|
self.encode(label.text), |
213 |
|
label.halign, |
214 |
label.valign)) |
label.valign)) |
215 |
self.close_element('labellayer') |
self.close_element('labellayer') |
216 |
|
|
223 |
|
|
224 |
The optional argument saver_class is the class to use to serialize |
The optional argument saver_class is the class to use to serialize |
225 |
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 |
226 |
Saver. |
SessionSaver. |
227 |
|
|
228 |
If writing the session is successful call the session's |
If writing the session is successful call the session's |
229 |
UnsetModified method |
UnsetModified method |
230 |
""" |
""" |
231 |
if saver_class is None: |
if saver_class is None: |
232 |
saver_class = Saver |
saver_class = SessionSaver |
233 |
saver = saver_class(session) |
saver = saver_class(session) |
234 |
saver.write(file) |
saver.write(file) |
235 |
|
|