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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1160 by jonathan, Thu Jun 12 12:40:43 2003 UTC revision 1417 by bh, Tue Jul 15 08:43:53 2003 UTC
# Line 17  import os Line 17  import os
17    
18  import Thuban.Lib.fileutil  import Thuban.Lib.fileutil
19    
 from Thuban.Model.color import Color  
20  from Thuban.Model.layer import Layer, RasterLayer  from Thuban.Model.layer import Layer, RasterLayer
21    
22  from Thuban.Model.classification import \  from Thuban.Model.classification import \
23      ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, ClassGroupMap      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  from Thuban.Model.xmlwriter import XMLWriter
29    
# Line 37  def relative_filename(dir, filename): Line 39  def relative_filename(dir, filename):
39      else:      else:
40          return filename          return filename
41    
42    
43    def sort_data_stores(stores):
44        """Return a topologically sorted version of the sequence of data containers
45    
46        The list is sorted so that data containers that depend on other data
47        containers have higher indexes than the containers they depend on.
48        """
49        if not stores:
50            return []
51        processed = {}
52        result = []
53        todo = stores[:]
54        while todo:
55            # It doesn't really matter which if the items of todo is
56            # processed next, but if we take the first one, the order is
57            # preserved to some degree which makes writing some of the test
58            # cases easier.
59            container = todo.pop(0)
60            if id(container) in processed:
61                continue
62            deps = [dep for dep in container.Dependencies()
63                        if id(dep) not in processed]
64            if deps:
65                todo.append(container)
66                todo.extend(deps)
67            else:
68                result.append(container)
69                processed[id(container)] = 1
70        return result
71    
72    
73  class SessionSaver(XMLWriter):  class SessionSaver(XMLWriter):
74    
75      """Class to serialize a session into an XML file.      """Class to serialize a session into an XML file.
# Line 53  class SessionSaver(XMLWriter): Line 86  class SessionSaver(XMLWriter):
86      def __init__(self, session):      def __init__(self, session):
87          XMLWriter.__init__(self)          XMLWriter.__init__(self)
88          self.session = session          self.session = session
89            # Map object ids to the ids used in the thuban files
90            self.idmap = {}
91    
92        def get_id(self, obj):
93            """Return the id used in the thuban file for the object obj"""
94            return self.idmap.get(id(obj))
95    
96        def define_id(self, obj, value = None):
97            if value is None:
98                value = "D" + str(id(obj))
99            self.idmap[id(obj)] = value
100            return value
101    
102        def has_id(self, obj):
103            return self.idmap.has_key(id(obj))
104    
105      def write(self, file_or_filename):      def write(self, file_or_filename):
106          XMLWriter.write(self, file_or_filename)          XMLWriter.write(self, file_or_filename)
107    
108          self.write_header("session", "thuban.dtd")          self.write_header("session", "thuban-0.9.dtd")
109          self.write_session(self.session)          self.write_session(self.session)
110          self.close()          self.close()
111    
# Line 82  class SessionSaver(XMLWriter): Line 130  class SessionSaver(XMLWriter):
130          attrs["title"] = session.title          attrs["title"] = session.title
131          for name, uri in namespaces:          for name, uri in namespaces:
132              attrs["xmlns:" + name] = uri              attrs["xmlns:" + name] = uri
133            # default name space
134            attrs["xmlns"] = \
135                   "http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd"
136          self.open_element("session", attrs)          self.open_element("session", attrs)
137            self.write_data_containers(session)
138          for map in session.Maps():          for map in session.Maps():
139              self.write_map(map)              self.write_map(map)
140          self.close_element("session")          self.close_element("session")
141    
142        def write_data_containers(self, session):
143            containers = sort_data_stores(session.DataContainers())
144            for container in containers:
145                if isinstance(container, AutoTransientTable):
146                    # AutoTransientTable instances are invisible in the
147                    # thuban files. They're only used internally. To make
148                    # sure that containers depending on AutoTransientTable
149                    # instances refer to the right real containers we give
150                    # the AutoTransientTable instances the same id as the
151                    # source they depend on.
152                    self.define_id(container,
153                                   self.get_id(container.Dependencies()[0]))
154                    continue
155    
156                idvalue = self.define_id(container)
157                if isinstance(container, ShapefileStore):
158                    self.define_id(container.Table(), idvalue)
159                    filename = relative_filename(self.dir, container.FileName())
160                    self.write_element("fileshapesource",
161                                       {"id": idvalue, "filename": filename,
162                                        "filetype": "shapefile"})
163                elif isinstance(container, DerivedShapeStore):
164                    shapesource, table = container.Dependencies()
165                    self.write_element("derivedshapesource",
166                                       {"id": idvalue,
167                                        "shapesource": self.get_id(shapesource),
168                                        "table": self.get_id(table)})
169                elif isinstance(container, DBFTable):
170                    filename = relative_filename(self.dir, container.FileName())
171                    self.write_element("filetable",
172                                       {"id": idvalue,
173                                        "title": container.Title(),
174                                        "filename": filename,
175                                        "filetype": "DBF"})
176                elif isinstance(container, TransientJoinedTable):
177                    left, right = container.Dependencies()
178                    left_field = container.left_field
179                    right_field = container.right_field
180                    self.write_element("jointable",
181                                       {"id": idvalue,
182                                        "title": container.Title(),
183                                        "right": self.get_id(right),
184                                        "rightcolumn": right_field,
185                                        "left": self.get_id(left),
186                                        "leftcolumn": left_field,
187                                        "jointype": container.JoinType()})
188                else:
189                    raise ValueError("Can't handle container %r" % container)
190    
191    
192      def write_map(self, map):      def write_map(self, map):
193          """Write the map and its contents.          """Write the map and its contents.
194    
# Line 123  class SessionSaver(XMLWriter): Line 225  class SessionSaver(XMLWriter):
225          if attrs is None:          if attrs is None:
226              attrs = {}              attrs = {}
227    
228          attrs["title"]        = layer.title          attrs["title"]   = layer.title
229          attrs["filename"]     = relative_filename(self.dir, layer.filename)          attrs["visible"] = ("false", "true")[int(layer.Visible())]
         attrs["visible"]      = ("false", "true")[int(layer.Visible())]  
230    
231          if isinstance(layer, Layer):          if isinstance(layer, Layer):
232                attrs["shapestore"]   = self.get_id(layer.ShapeStore())
233    
234              lc = layer.GetClassification()              lc = layer.GetClassification()
235              attrs["stroke"]       = lc.GetDefaultLineColor().hex()              attrs["stroke"] = lc.GetDefaultLineColor().hex()
236              attrs["stroke_width"] = str(lc.GetDefaultLineWidth())              attrs["stroke_width"] = str(lc.GetDefaultLineWidth())
237              attrs["fill"]         = lc.GetDefaultFill().hex()              attrs["fill"] = lc.GetDefaultFill().hex()
238    
239              self.open_element("layer", attrs)              self.open_element("layer", attrs)
240              self.write_projection(layer.GetProjection())              self.write_projection(layer.GetProjection())
241              self.write_classification(layer)              self.write_classification(layer)
242              self.close_element("layer")              self.close_element("layer")
   
243          elif isinstance(layer, RasterLayer):          elif isinstance(layer, RasterLayer):
244                attrs["filename"] = relative_filename(self.dir, layer.filename)
245              self.open_element("rasterlayer", attrs)              self.open_element("rasterlayer", attrs)
246              self.write_projection(layer.GetProjection())              self.write_projection(layer.GetProjection())
247              self.close_element("rasterlayer")              self.close_element("rasterlayer")
248    
249      def write_classification(self, layer, attrs = None):      def write_classification(self, layer, attrs = None):
250            """Write Classification information."""
251    
252          if attrs is None:          if attrs is None:
253              attrs = {}              attrs = {}
254    
# Line 154  class SessionSaver(XMLWriter): Line 257  class SessionSaver(XMLWriter):
257          field = lc.GetField()          field = lc.GetField()
258    
259          #          #
260          # there isn't a classification of anything          # there isn't a classification of anything so do nothing
         # so don't do anything  
261          #          #
262          if field is None: return          if field is None: return
263    
# Line 163  class SessionSaver(XMLWriter): Line 265  class SessionSaver(XMLWriter):
265          attrs["field_type"] = str(lc.GetFieldType())          attrs["field_type"] = str(lc.GetFieldType())
266          self.open_element("classification", attrs)          self.open_element("classification", attrs)
267    
268            for g in lc:
269          types = [[lambda p: 'clnull label="%s"' % self.encode(p.GetLabel()),              if isinstance(g, ClassGroupDefault):
270                    lambda p: 'clnull'],                  open_el  = 'clnull label="%s"' % self.encode(g.GetLabel())
271                   [lambda p: 'clpoint label="%s" value="%s"' %                  close_el = 'clnull'
272                               (self.encode(p.GetLabel()), str(p.GetValue())),              elif isinstance(g, ClassGroupSingleton):
273                    lambda p: 'clpoint'],                  if lc.GetFieldType() == FIELDTYPE_STRING:
274                   [lambda p: 'clrange label="%s" range="%s"' %                      value = self.encode(g.GetValue())
275                               (self.encode(p.GetLabel()),                  else:
276                                str(p.GetRange())),                      value = str(g.GetValue())
277                    lambda p: 'clrange']]                  open_el  = 'clpoint label="%s" value="%s"' \
278                               % (self.encode(g.GetLabel()), value)
279          def write_class_group(group):                  close_el = 'clpoint'
280              type = -1              elif isinstance(g, ClassGroupRange):
281              if isinstance(group, ClassGroupDefault): type = 0                  open_el  = 'clrange label="%s" range="%s"' \
282              elif isinstance(group, ClassGroupSingleton): type = 1                            % (self.encode(g.GetLabel()), str(g.GetRange()))
283              elif isinstance(group, ClassGroupRange): type = 2                  close_el = 'clrange'
284              elif isinstance(group, ClassGroupMap):   type = 3              else:
285              assert type >= 0                  assert False, _("Unsupported group type in classification")
286                    continue
287              if type <= 2:  
288                  data = group.GetProperties()              data = g.GetProperties()
289                  dict = {'stroke'      : data.GetLineColor().hex(),              dict = {'stroke'      : data.GetLineColor().hex(),
290                          'stroke_width': str(data.GetLineWidth()),                      'stroke_width': str(data.GetLineWidth()),
291                          'fill'        : data.GetFill().hex()}                      'fill'        : data.GetFill().hex()}
292    
293                  self.open_element(types[type][0](group))              self.open_element(open_el)
294                  self.write_element("cldata", dict)              self.write_element("cldata", dict)
295                  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)  
296    
297          self.close_element("classification")          self.close_element("classification")
298    

Legend:
Removed from v.1160  
changed lines
  Added in v.1417

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26