/[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 466 by jonathan, Wed Mar 5 18:18:20 2003 UTC revision 1375 by bh, Tue Jul 8 10:53:05 2003 UTC
# Line 13  Functions to save a session to a file Line 13  Functions to save a session to a file
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
26    from Thuban.Model.data import DerivedShapeStore, ShapefileStore
27    
28  #  from Thuban.Model.xmlwriter import XMLWriter
 # one level of indention  
 #  
 TAB = "    "  
29    
30  def relative_filename(dir, filename):  def relative_filename(dir, filename):
31      """Return a filename relative to dir for the absolute file name absname.      """Return a filename relative to dir for the absolute file name absname.
# Line 42  def relative_filename(dir, filename): Line 39  def relative_filename(dir, filename):
39      else:      else:
40          return filename          return filename
41    
42  def escape(data):  
43      """Escape &, \", ', <, and > in a string of data.  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      data = string.replace(data, "&", "&amp;")      if not stores:
50      data = string.replace(data, "<", "&lt;")          return []
51      data = string.replace(data, ">", "&gt;")      processed = {}
52      data = string.replace(data, '"', "&quot;")      result = []
53      data = string.replace(data, "'", "&apos;")      todo = stores[:]
54      return data      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  class Saver:  
73    class SessionSaver(XMLWriter):
74    
75      """Class to serialize a session into an XML file.      """Class to serialize a session into an XML file.
76    
# Line 66  class Saver: Line 84  class Saver:
84    
85    
86      def __init__(self, session):      def __init__(self, session):
87            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 write(self, file_or_filename):      def get_id(self, obj):
93          """Write the session to a file.          """Return the id used in the thuban file for the object obj"""
94            return self.idmap.get(id(obj))
95          The argument may be either a file object or a filename. If it's  
96          a filename, the file will be opened for writing. Files of      def define_id(self, obj, value = None):
97          shapefiles will be stored as filenames relative to the directory          if value is None:
98          the file is stored in (as given by os.path.dirname(filename)) if              value = "D" + str(id(obj))
99          they have a common parent directory other than the root          self.idmap[id(obj)] = value
100          directory.          return value
   
         If the argument is a file object (which is determined by the  
         presence of a write method) all filenames will be absolut  
         filenames.  
         """  
101    
102          # keep track of how many levels of indentation to write      def has_id(self, obj):
103          self.indent_level = 0          return self.idmap.has_key(id(obj))
         # 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 = ""  
         else:  
             filename = file_or_filename  
             self.dir = os.path.dirname(filename)  
             self.file = open(filename, 'w')  
         self.write_header()  
         self.write_session(self.session)  
   
         assert(self.indent_level == 0)  
   
     def write_attribs(self, attrs):  
         for name, value in attrs.items():  
             self.file.write(' %s="%s"' % (escape(name), escape(value)))  
       
     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")  
104    
105          self.element_open = 1      def write(self, file_or_filename):
106            XMLWriter.write(self, file_or_filename)
         # 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.indent_level += 1  
   
     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))  
107    
108      def write_element(self, element, attrs = {}):          self.write_header("session", "thuban-0.9.dtd")
109          """write an element that won't need a closing tag"""          self.write_session(self.session)
110          self.open_element(element, attrs)          self.close()
         self.close_element(element)  
   
     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')  
111    
112      def write_session(self, session, attrs = None, namespaces = ()):      def write_session(self, session, attrs = None, namespaces = ()):
113          """Write the session and its contents          """Write the session and its contents
# Line 167  class Saver: Line 130  class Saver:
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 180  class Saver: Line 197  class Saver:
197          element, call write_layer for each layer contained in the map          element, call write_layer for each layer contained in the map
198          and finally call write_label_layer to write the label layer.          and finally call write_label_layer to write the label layer.
199          """          """
200          #write = self.file.write          self.open_element('map title="%s"' % self.encode(map.title))
         self.open_element('map title="%s"' % escape(map.title))  
201          self.write_projection(map.projection)          self.write_projection(map.projection)
202          for layer in map.Layers():          for layer in map.Layers():
203              self.write_layer(layer)              self.write_layer(layer)
# Line 192  class Saver: Line 208  class Saver:
208          """Write the projection.          """Write the projection.
209          """          """
210          if projection and len(projection.params) > 0:          if projection and len(projection.params) > 0:
211              self.open_element("projection")              self.open_element("projection", {"name": projection.GetName()})
212              for param in projection.params:              for param in projection.params:
213                  self.write_element('parameter value="%s"' % escape(param))                  self.write_element('parameter value="%s"' %
214                                       self.encode(param))
215              self.close_element("projection")              self.close_element("projection")
216    
217      def write_layer(self, layer, attrs = None):      def write_layer(self, layer, attrs = None):
# Line 204  class Saver: Line 221  class Saver:
221          given, should be a mapping from attribute names to attribute          given, should be a mapping from attribute names to attribute
222          values. The values should not be XML-escaped yet.          values. The values should not be XML-escaped yet.
223          """          """
         lc = layer.GetClassification()  
224    
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())]
230          attrs["stroke"]       = lc.GetDefaultLineColor().hex()  
231          attrs["stroke_width"] = str(lc.GetDefaultLineWidth())          if isinstance(layer, Layer):
232          attrs["fill"]         = lc.GetDefaultFill().hex()              attrs["shapestore"]   = self.get_id(layer.ShapeStore())
233    
234          self.open_element("layer", attrs)              lc = layer.GetClassification()
235          self.write_classification(layer)              attrs["stroke"] = lc.GetDefaultLineColor().hex()
236          self.close_element("layer")              attrs["stroke_width"] = str(lc.GetDefaultLineWidth())
237                attrs["fill"] = lc.GetDefaultFill().hex()
238    
239                self.open_element("layer", attrs)
240                self.write_projection(layer.GetProjection())
241                self.write_classification(layer)
242                self.close_element("layer")
243            elif isinstance(layer, RasterLayer):
244                attrs["filename"] = relative_filename(self.dir, layer.filename)
245                self.open_element("rasterlayer", attrs)
246                self.write_projection(layer.GetProjection())
247                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 228  class Saver: Line 257  class Saver:
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 237  class Saver: Line 265  class Saver:
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  #       self.open_element("clnull")              if isinstance(g, ClassGroupDefault):
270  #       write_class_data(lc.GetDefaultData())                  open_el  = 'clnull label="%s"' % self.encode(g.GetLabel())
271  #       self.close_element("clnull")                  close_el = 'clnull'
272                            elif isinstance(g, ClassGroupSingleton):
273          # just playing now with lambdas and dictionaries                  open_el  = 'clpoint label="%s" value="%s"' \
274                               % (self.encode(g.GetLabel()), str(g.GetValue()))
275          types = [[lambda p: 'clnull',                  close_el = 'clpoint'
276                    lambda p: 'clnull'],              elif isinstance(g, ClassGroupRange):
277                   [lambda p: 'clpoint value="%s"' %                  open_el  = 'clrange label="%s" range="%s"' \
278                               str(p.GetValue()),                            % (self.encode(g.GetLabel()), str(g.GetRange()))
279                    lambda p: 'clpoint'],                  close_el = 'clrange'
280                   [lambda p: 'clrange min="%s" max="%s"' %              else:
281                               (str(p.GetMin()),                  assert False, _("Unsupported group type in classification")
282                                (str(p.GetMax()))),                  continue
283                    lambda p: 'clrange']]  
284                data = g.GetProperties()
285          def write_class_group(group):              dict = {'stroke'      : data.GetLineColor().hex(),
286              type = -1                      'stroke_width': str(data.GetLineWidth()),
287              if isinstance(group, ClassGroupDefault): type = 0                      'fill'        : data.GetFill().hex()}
288              elif isinstance(group, ClassGroupSingleton): type = 1  
289              elif isinstance(group, ClassGroupRange): type = 2              self.open_element(open_el)
290              elif isinstance(group, ClassGroupMap):   type = 3              self.write_element("cldata", dict)
291              assert(type >= 0)              self.close_element(close_el)
   
             if type <= 2:  
                 data = group.GetProperties()  
                 dict = {'stroke'      : data.GetLineColor().hex(),  
                         'stroke_width': str(data.GetLineWidth()),  
                         'fill'        : data.GetFill().hex()}  
   
                 self.open_element(types[type][0](group))  
                 self.write_element("cldata", dict)  
                 self.close_element(types[type][1](group))  
             else: pass # XXX: we need to handle maps  
   
         for i in lc:  
             write_class_group(i)  
   
 #       for i in lc:  
 #           t = i.GetType()  
 #           self.open_element(types[t][0](i))  
 #           write_class_data(i)  
 #           self.close_element(types[t][1](i))  
   
 #       for p in lc:  
 #           type = p.GetType()  
 #           if p == ClassData.DEFAULT:  
 #               lopen = lclose = 'clnull'  
 #           elif p == ClassData.POINTS:  
 #               lopen = 'clpoint value="%s"' % escape(str(p.GetValue()))  
 #               lclose = 'clpoint'  
 #           elif p == ClassData.RANGES:  
 #               lopen = 'clrange min="%s" max="%s"'  
 #                   % (escape(str(p.GetMin())), escape(str(p.GetMax()))))  
 #               lclose = 'clrange'  
   
 #           self.open_element(lopen)  
 #           write_class_data(p)  
 #           self.close_element(lclose)  
               
 #       if lc.points != {}:  
 #           for p in lc.points.values():  
 #               self.open_element('clpoint value="%s"' %  
 #                   (escape(str(p.GetValue()))))  
 #               write_class_data(p)  
 #               self.close_element('clpoint')  
 #            
 #       if lc.ranges != []:  
 #           for p in lc.ranges:  
 #               self.open_element('clrange min="%s" max="%s"'  
 #                   % (escape(str(p.GetMin())), escape(str(p.GetMax()))))  
 #               write_class_data(p)  
 #               self.close_element('clrange')  
292    
293          self.close_element("classification")          self.close_element("classification")
294    
# Line 323  class Saver: Line 301  class Saver:
301              for label in labels:              for label in labels:
302                  self.write_element(('label x="%g" y="%g" text="%s"'                  self.write_element(('label x="%g" y="%g" text="%s"'
303                                      ' halign="%s" valign="%s"')                                      ' halign="%s" valign="%s"')
304                                  % (label.x, label.y, label.text, label.halign,                                  % (label.x, label.y,
305                                       self.encode(label.text),
306                                       label.halign,
307                                     label.valign))                                     label.valign))
308              self.close_element('labellayer')              self.close_element('labellayer')
309    
# Line 336  def save_session(session, file, saver_cl Line 316  def save_session(session, file, saver_cl
316    
317      The optional argument saver_class is the class to use to serialize      The optional argument saver_class is the class to use to serialize
318      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
319      Saver.      SessionSaver.
320    
321      If writing the session is successful call the session's      If writing the session is successful call the session's
322      UnsetModified method      UnsetModified method
323      """      """
324      if saver_class is None:      if saver_class is None:
325          saver_class = Saver          saver_class = SessionSaver
326      saver = saver_class(session)      saver = saver_class(session)
327      saver.write(file)      saver.write(file)
328    

Legend:
Removed from v.466  
changed lines
  Added in v.1375

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26