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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1219 - (hide annotations)
Mon Jun 16 17:42:54 2003 UTC (21 years, 8 months ago) by bh
Original Path: trunk/thuban/Thuban/Model/save.py
File MIME type: text/x-python
File size: 8478 byte(s)
Update to the layer interface: Direct access to the table,
shapetable, shapefile and filename attributes is now actively
deprecated by issuing deprecation warnings for all places where
this happens.

* Thuban/Model/layer.py (Layer.__getattr__): New. Implement access
to the instance variables table, shapetable, shapefile and
filename via __getattr__ so that we can issue a deprecation
warning.
(Layer.SetShapeStore): Don't set the deprecated instance variables
any more
(Layer.SetShapeStore): Don't use deprecated layer instance
variables
(Layer.Destroy): No need to explicitly remove the instance
variables any more
(Layer.GetFieldType, Layer.Shape): Don't use deprecated layer
instance variables

* Thuban/UI/classgen.py (ClassGenDialog.__init__)
(GenUniformPanel._OnRetrieve, GenUniquePanel._OnRetrieve)
(GenQuantilesPanel.GetList, GenQuantilesPanel.OnRetrieve): Don't
use deprecated layer instance variables

* Thuban/UI/classifier.py (Classifier.__init__): Don't use
deprecated layer instance variables

* Thuban/UI/identifyview.py (IdentifyListCtrl.selected_shape)
(IdentifyGridCtrl.selected_shape): Don't set the deprecated layer
instance variables

* Thuban/UI/tableview.py (LayerTableGrid.select_shapes): Don't use
deprecated layer instance variables

* Thuban/UI/mainwindow.py (MainWindow.LayerShowTable): Don't use
deprecated layer instance variables

* Thuban/Model/save.py (SessionSaver.write_layer): Don't use
deprecated layer instance variables

* Thuban/UI/renderer.py (MapRenderer.draw_shape_layer)
(MapRenderer.polygon_render_param): Don't use deprecated layer instance
variables

* test/runtests.py (main): Turn Thuban's deprecation warnings into
errors so that they're cought by the tests

* test/test_load.py (TestSingleLayer.test): Don't use deprecated
layer instance variables

1 bh 454 # Copyright (c) 2001, 2002, 2003 by Intevation GmbH
2 bh 6 # Authors:
3     # Jan-Oliver Wagner <[email protected]>
4     # Bernhard Herzog <[email protected]>
5 jonathan 414 # Jonathan Coles <[email protected]>
6 bh 6 #
7     # This program is free software under the GPL (>=v2)
8     # Read the file COPYING coming with Thuban for details.
9    
10     """
11     Functions to save a session to a file
12     """
13    
14     __version__ = "$Revision$"
15    
16     import os
17    
18 bh 201 import Thuban.Lib.fileutil
19 bh 6
20 jonathan 932 from Thuban.Model.color import Color
21     from Thuban.Model.layer import Layer, RasterLayer
22    
23 jonathan 876 from Thuban.Model.classification import \
24     ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, ClassGroupMap
25 jonathan 429
26 jonathan 1160 from Thuban.Model.xmlwriter import XMLWriter
27 jonathan 366
28 bh 201 def relative_filename(dir, filename):
29     """Return a filename relative to dir for the absolute file name absname.
30    
31     This is almost the same as the function in fileutil, except that dir
32     can be an empty string in which case filename will be returned
33     unchanged.
34     """
35     if dir:
36     return Thuban.Lib.fileutil.relative_filename(dir, filename)
37     else:
38     return filename
39    
40 jonathan 710 class SessionSaver(XMLWriter):
41 bh 268
42 jonathan 697 """Class to serialize a session into an XML file.
43    
44     Applications built on top of Thuban may derive from this class and
45     override or extend the methods to save additional information. This
46     additional information should take the form of additional attributes
47     or elements whose names are prefixed with a namespace. To define a
48     namespace derived classes should extend the write_session method to
49     pass the namespaces to the default implementation.
50     """
51    
52    
53     def __init__(self, session):
54 jonathan 710 XMLWriter.__init__(self)
55 jonathan 697 self.session = session
56    
57     def write(self, file_or_filename):
58 jonathan 710 XMLWriter.write(self, file_or_filename)
59 jonathan 697
60     self.write_header("session", "thuban.dtd")
61     self.write_session(self.session)
62     self.close()
63    
64 bh 268 def write_session(self, session, attrs = None, namespaces = ()):
65     """Write the session and its contents
66    
67     By default, write a session element with the title attribute and
68     call write_map for each map contained in the session.
69    
70     The optional argument attrs is for additional attributes and, if
71     given, should be a mapping from attribute names to attribute
72     values. The values should not be XML-escaped yet.
73    
74     The optional argument namespaces, if given, should be a sequence
75     of (name, URI) pairs. The namespaces are written as namespace
76     attributes into the session element. This is mainly useful for
77     derived classes that need to store additional information in a
78     thuban session file.
79     """
80     if attrs is None:
81     attrs = {}
82     attrs["title"] = session.title
83     for name, uri in namespaces:
84     attrs["xmlns:" + name] = uri
85 jonathan 366 self.open_element("session", attrs)
86 bh 268 for map in session.Maps():
87     self.write_map(map)
88 jonathan 366 self.close_element("session")
89 bh 268
90     def write_map(self, map):
91     """Write the map and its contents.
92    
93     By default, write a map element element with the title
94     attribute, call write_projection to write the projection
95     element, call write_layer for each layer contained in the map
96     and finally call write_label_layer to write the label layer.
97     """
98 jonathan 876 self.open_element('map title="%s"' % self.encode(map.title))
99 bh 268 self.write_projection(map.projection)
100     for layer in map.Layers():
101     self.write_layer(layer)
102     self.write_label_layer(map.LabelLayer())
103 jonathan 366 self.close_element('map')
104 bh 6
105 bh 268 def write_projection(self, projection):
106     """Write the projection.
107     """
108     if projection and len(projection.params) > 0:
109 jonathan 876 self.open_element("projection", {"name": projection.GetName()})
110 bh 268 for param in projection.params:
111 jonathan 876 self.write_element('parameter value="%s"' %
112     self.encode(param))
113 jonathan 366 self.close_element("projection")
114 bh 268
115     def write_layer(self, layer, attrs = None):
116     """Write the layer.
117    
118     The optional argument attrs is for additional attributes and, if
119     given, should be a mapping from attribute names to attribute
120     values. The values should not be XML-escaped yet.
121     """
122 jonathan 391
123 bh 268 if attrs is None:
124     attrs = {}
125 jonathan 429
126     attrs["title"] = layer.title
127 jonathan 773 attrs["visible"] = ("false", "true")[int(layer.Visible())]
128 bh 268
129 jonathan 932 if isinstance(layer, Layer):
130 bh 1219 attrs["filename"] = relative_filename(self.dir,
131     layer.ShapeStore().FileName())
132 jonathan 740
133 jonathan 932 lc = layer.GetClassification()
134     attrs["stroke"] = lc.GetDefaultLineColor().hex()
135     attrs["stroke_width"] = str(lc.GetDefaultLineWidth())
136     attrs["fill"] = lc.GetDefaultFill().hex()
137 jonathan 740
138 jonathan 932 self.open_element("layer", attrs)
139     self.write_projection(layer.GetProjection())
140     self.write_classification(layer)
141     self.close_element("layer")
142 jonathan 740
143 jonathan 932 elif isinstance(layer, RasterLayer):
144 bh 1219 attrs["filename"] = relative_filename(self.dir, layer.filename)
145 jonathan 932 self.open_element("rasterlayer", attrs)
146     self.write_projection(layer.GetProjection())
147     self.close_element("rasterlayer")
148    
149 jonathan 366 def write_classification(self, layer, attrs = None):
150     if attrs is None:
151     attrs = {}
152    
153 jonathan 414 lc = layer.GetClassification()
154 jonathan 366
155 jonathan 429 field = lc.GetField()
156 jonathan 366
157     #
158     # there isn't a classification of anything
159     # so don't do anything
160     #
161     if field is None: return
162    
163     attrs["field"] = field
164 jonathan 466 attrs["field_type"] = str(lc.GetFieldType())
165 jonathan 366 self.open_element("classification", attrs)
166    
167 jonathan 429
168 jonathan 876 types = [[lambda p: 'clnull label="%s"' % self.encode(p.GetLabel()),
169 jonathan 440 lambda p: 'clnull'],
170 jonathan 683 [lambda p: 'clpoint label="%s" value="%s"' %
171 jonathan 876 (self.encode(p.GetLabel()), str(p.GetValue())),
172 jonathan 440 lambda p: 'clpoint'],
173 jonathan 876 [lambda p: 'clrange label="%s" range="%s"' %
174     (self.encode(p.GetLabel()),
175     str(p.GetRange())),
176 jonathan 440 lambda p: 'clrange']]
177 jonathan 429
178 jonathan 440 def write_class_group(group):
179     type = -1
180     if isinstance(group, ClassGroupDefault): type = 0
181     elif isinstance(group, ClassGroupSingleton): type = 1
182     elif isinstance(group, ClassGroupRange): type = 2
183     elif isinstance(group, ClassGroupMap): type = 3
184 jonathan 605 assert type >= 0
185 jonathan 366
186 jonathan 440 if type <= 2:
187     data = group.GetProperties()
188 jonathan 466 dict = {'stroke' : data.GetLineColor().hex(),
189     'stroke_width': str(data.GetLineWidth()),
190 jonathan 440 '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 jonathan 429 for i in lc:
198 jonathan 440 write_class_group(i)
199 jonathan 429
200 jonathan 366 self.close_element("classification")
201    
202 bh 268 def write_label_layer(self, layer):
203     """Write the label layer.
204     """
205     labels = layer.Labels()
206 bh 6 if labels:
207 jonathan 366 self.open_element('labellayer')
208 bh 6 for label in labels:
209 jonathan 366 self.write_element(('label x="%g" y="%g" text="%s"'
210     ' halign="%s" valign="%s"')
211 jonathan 876 % (label.x, label.y,
212     self.encode(label.text),
213     label.halign,
214 bh 268 label.valign))
215 jonathan 366 self.close_element('labellayer')
216 bh 6
217 bh 268
218    
219     def save_session(session, file, saver_class = None):
220     """Save the session session to a file.
221    
222     The file argument may either be a filename or an open file object.
223    
224     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
226 jonathan 697 SessionSaver.
227 bh 268
228     If writing the session is successful call the session's
229     UnsetModified method
230     """
231     if saver_class is None:
232 jonathan 697 saver_class = SessionSaver
233 bh 268 saver = saver_class(session)
234     saver.write(file)
235    
236 bh 6 # after a successful save consider the session unmodified.
237     session.UnsetModified()

Properties

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26