/[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 440 by jonathan, Thu Feb 27 15:54:27 2003 UTC revision 2104 by bh, Fri Mar 12 12:19:15 2004 UTC
# Line 1  Line 1 
1  # Copyright (c) 2001, 2002 by Intevation GmbH  # Copyright (c) 2001, 2002, 2003, 2004 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]>
# 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, FIELDTYPE_STRING
26    from Thuban.Model.data import DerivedShapeStore, ShapefileStore
27    
28  #  from Thuban.Model.xmlwriter import XMLWriter
29  # one level of indention  from postgisdb import PostGISConnection, PostGISShapeStore
 #  
 TAB = "    "  
30    
31  def relative_filename(dir, filename):  def relative_filename(dir, filename):
32      """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 40  def relative_filename(dir, filename):
40      else:      else:
41          return filename          return filename
42    
43  def escape(data):  
44      """Escape &, \", ', <, and > in a string of data.  def unify_filename(filename):
45        """Return a 'unified' version of filename
46    
47        The .thuban files should be as platform independent as possible.
48        Since they must contain filenames the filenames have to unified. We
49        unify on unix-like filenames for now, which means we do nothing on a
50        posix system and simply replace backslashes with slashes on windows
51      """      """
52      data = string.replace(data, "&", "&amp;")      if os.name == "posix":
53      data = string.replace(data, "<", "&lt;")          return filename
54      data = string.replace(data, ">", "&gt;")      elif os.name == "nt":
55      data = string.replace(data, '"', "&quot;")          return "/".join(filename.split("\\"))
56      data = string.replace(data, "'", "&apos;")      else:
57      return data          raise RuntimeError("Unsupported platform for unify_filename: %s"
58                               % os.name)
59    
60    def sort_data_stores(stores):
61        """Return a topologically sorted version of the sequence of data containers
62    
63  class Saver:      The list is sorted so that data containers that depend on other data
64        containers have higher indexes than the containers they depend on.
65        """
66        if not stores:
67            return []
68        processed = {}
69        result = []
70        todo = stores[:]
71        while todo:
72            # It doesn't really matter which if the items of todo is
73            # processed next, but if we take the first one, the order is
74            # preserved to some degree which makes writing some of the test
75            # cases easier.
76            container = todo.pop(0)
77            if id(container) in processed:
78                continue
79            deps = [dep for dep in container.Dependencies()
80                        if id(dep) not in processed]
81            if deps:
82                todo.append(container)
83                todo.extend(deps)
84            else:
85                result.append(container)
86                processed[id(container)] = 1
87        return result
88    
89    
90    class SessionSaver(XMLWriter):
91    
92      """Class to serialize a session into an XML file.      """Class to serialize a session into an XML file.
93    
94      Applications built on top of Thuban may derive from this class and      Applications built on top of Thuban may derive from this class and
95      override or extend the methods to save additinal information. This      override or extend the methods to save additional information. This
96      additional information should take the form of additional attributes      additional information should take the form of additional attributes
97      or elements whose names are prefixed with a namespace. To define a      or elements whose names are prefixed with a namespace. To define a
98      namespace derived classes should extend the write_session method to      namespace derived classes should extend the write_session method to
# Line 66  class Saver: Line 101  class Saver:
101    
102    
103      def __init__(self, session):      def __init__(self, session):
104            XMLWriter.__init__(self)
105          self.session = session          self.session = session
106            # Map object ids to the ids used in the thuban files
107            self.idmap = {}
108    
109      def write(self, file_or_filename):      def get_id(self, obj):
110          """Write the session to a file.          """Return the id used in the thuban file for the object obj"""
111            return self.idmap.get(id(obj))
112          The argument may be either a file object or a filename. If it's  
113          a filename, the file will be opened for writing. Files of      def define_id(self, obj, value = None):
114          shapefiles will be stored as filenames relative to the directory          if value is None:
115          the file is stored in (as given by os.path.dirname(filename)) if              value = "D" + str(id(obj))
116          they have a common parent directory other than the root          self.idmap[id(obj)] = value
117          directory.          return value
118    
119          If the argument is a file object (which is determined by the      def has_id(self, obj):
120          presence of a write method) all filenames will be absolut          return self.idmap.has_key(id(obj))
121          filenames.  
122        def prepare_filename(self, filename):
123            """Return the string to use when writing filename to the thuban file
124    
125            The returned string is a unified version (only slashes as
126            directory separators, see unify_filename) of filename expressed
127            relative to the directory the .thuban file is written to.
128          """          """
129            return unify_filename(relative_filename(self.dir, filename))
130    
131          # keep track of how many levels of indentation to write      def write(self, file_or_filename):
132          self.indent_level = 0          XMLWriter.write(self, file_or_filename)
         # 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")  
   
         self.element_open = 1  
   
         # 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))  
133    
134      def write_element(self, element, attrs = {}):          self.write_header("session", "thuban-1.1.dtd")
135          """write an element that won't need a closing tag"""          self.write_session(self.session)
136          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')  
137    
138      def write_session(self, session, attrs = None, namespaces = ()):      def write_session(self, session, attrs = None, namespaces = ()):
139          """Write the session and its contents          """Write the session and its contents
# Line 167  class Saver: Line 156  class Saver:
156          attrs["title"] = session.title          attrs["title"] = session.title
157          for name, uri in namespaces:          for name, uri in namespaces:
158              attrs["xmlns:" + name] = uri              attrs["xmlns:" + name] = uri
159            # default name space
160            attrs["xmlns"] = \
161                   "http://thuban.intevation.org/dtds/thuban-1.1-dev.dtd"
162          self.open_element("session", attrs)          self.open_element("session", attrs)
163            self.write_db_connections(session)
164            self.write_data_containers(session)
165          for map in session.Maps():          for map in session.Maps():
166              self.write_map(map)              self.write_map(map)
167          self.close_element("session")          self.close_element("session")
168    
169        def write_db_connections(self, session):
170            for conn in session.DBConnections():
171                if isinstance(conn, PostGISConnection):
172                    self.write_element("dbconnection",
173                                       {"id": self.define_id(conn),
174                                        "dbtype": "postgis",
175                                        "host": conn.host,
176                                        "port": conn.port,
177                                        "user": conn.user,
178                                        "dbname": conn.dbname})
179                else:
180                    raise ValueError("Can't handle db connection %r" % conn)
181    
182        def write_data_containers(self, session):
183            containers = sort_data_stores(session.DataContainers())
184            for container in containers:
185                if isinstance(container, AutoTransientTable):
186                    # AutoTransientTable instances are invisible in the
187                    # thuban files. They're only used internally. To make
188                    # sure that containers depending on AutoTransientTable
189                    # instances refer to the right real containers we give
190                    # the AutoTransientTable instances the same id as the
191                    # source they depend on.
192                    self.define_id(container,
193                                   self.get_id(container.Dependencies()[0]))
194                    continue
195    
196                idvalue = self.define_id(container)
197                if isinstance(container, ShapefileStore):
198                    self.define_id(container.Table(), idvalue)
199                    filename = self.prepare_filename(container.FileName())
200                    self.write_element("fileshapesource",
201                                       {"id": idvalue, "filename": filename,
202                                        "filetype": "shapefile"})
203                elif isinstance(container, DerivedShapeStore):
204                    shapesource, table = container.Dependencies()
205                    self.write_element("derivedshapesource",
206                                       {"id": idvalue,
207                                        "shapesource": self.get_id(shapesource),
208                                        "table": self.get_id(table)})
209                elif isinstance(container, PostGISShapeStore):
210                    conn = container.DBConnection()
211                    self.write_element("dbshapesource",
212                                       {"id": idvalue,
213                                        "dbconn": self.get_id(conn),
214                                        "tablename": container.TableName(),
215                                        "id_column": container.IDColumn().name,
216                                        "geometry_column":
217                                          container.GeometryColumn().name,
218                                        })
219                elif isinstance(container, DBFTable):
220                    filename = self.prepare_filename(container.FileName())
221                    self.write_element("filetable",
222                                       {"id": idvalue,
223                                        "title": container.Title(),
224                                        "filename": filename,
225                                        "filetype": "DBF"})
226                elif isinstance(container, TransientJoinedTable):
227                    left, right = container.Dependencies()
228                    left_field = container.left_field
229                    right_field = container.right_field
230                    self.write_element("jointable",
231                                       {"id": idvalue,
232                                        "title": container.Title(),
233                                        "right": self.get_id(right),
234                                        "rightcolumn": right_field,
235                                        "left": self.get_id(left),
236                                        "leftcolumn": left_field,
237                                        "jointype": container.JoinType()})
238                else:
239                    raise ValueError("Can't handle container %r" % container)
240    
241    
242      def write_map(self, map):      def write_map(self, map):
243          """Write the map and its contents.          """Write the map and its contents.
244    
# Line 180  class Saver: Line 247  class Saver:
247          element, call write_layer for each layer contained in the map          element, call write_layer for each layer contained in the map
248          and finally call write_label_layer to write the label layer.          and finally call write_label_layer to write the label layer.
249          """          """
250          write = self.file.write          self.open_element('map title="%s"' % self.encode(map.title))
         self.open_element('map title="%s"' % escape(map.title))  
251          self.write_projection(map.projection)          self.write_projection(map.projection)
252          for layer in map.Layers():          for layer in map.Layers():
253              self.write_layer(layer)              self.write_layer(layer)
# Line 192  class Saver: Line 258  class Saver:
258          """Write the projection.          """Write the projection.
259          """          """
260          if projection and len(projection.params) > 0:          if projection and len(projection.params) > 0:
261              self.open_element("projection")              attrs = {"name": projection.GetName()}
262                epsg = projection.EPSGCode()
263                if epsg is not None:
264                    attrs["epsg"] = epsg
265                self.open_element("projection", attrs)
266              for param in projection.params:              for param in projection.params:
267                  self.write_element('parameter value="%s"' % escape(param))                  self.write_element('parameter value="%s"' %
268                                       self.encode(param))
269              self.close_element("projection")              self.close_element("projection")
270    
271      def write_layer(self, layer, attrs = None):      def write_layer(self, layer, attrs = None):
# Line 204  class Saver: Line 275  class Saver:
275          given, should be a mapping from attribute names to attribute          given, should be a mapping from attribute names to attribute
276          values. The values should not be XML-escaped yet.          values. The values should not be XML-escaped yet.
277          """          """
         lc = layer.GetClassification()  
278    
279          if attrs is None:          if attrs is None:
280              attrs = {}              attrs = {}
281    
282          attrs["title"]        = layer.title          attrs["title"]   = layer.title
283          attrs["filename"]     = relative_filename(self.dir, layer.filename)          attrs["visible"] = ("false", "true")[int(layer.Visible())]
284          attrs["stroke"]       = lc.GetDefaultStroke().hex()  
285          attrs["stroke_width"] = str(lc.GetDefaultStrokeWidth())          if isinstance(layer, Layer):
286          attrs["fill"]         = lc.GetDefaultFill().hex()              attrs["shapestore"]   = self.get_id(layer.ShapeStore())
287    
288          self.open_element("layer", attrs)              lc = layer.GetClassification()
289          self.write_classification(layer)              attrs["stroke"] = lc.GetDefaultLineColor().hex()
290          self.close_element("layer")              attrs["stroke_width"] = str(lc.GetDefaultLineWidth())
291                attrs["fill"] = lc.GetDefaultFill().hex()
292    
293                self.open_element("layer", attrs)
294                self.write_projection(layer.GetProjection())
295                self.write_classification(layer)
296                self.close_element("layer")
297            elif isinstance(layer, RasterLayer):
298                attrs["filename"] = self.prepare_filename(layer.filename)
299                self.open_element("rasterlayer", attrs)
300                self.write_projection(layer.GetProjection())
301                self.close_element("rasterlayer")
302    
303      def write_classification(self, layer, attrs = None):      def write_classification(self, layer, attrs = None):
304            """Write Classification information."""
305    
306          if attrs is None:          if attrs is None:
307              attrs = {}              attrs = {}
308    
309          lc = layer.GetClassification()          lc = layer.GetClassification()
310    
311          field = lc.GetField()          field = layer.GetClassificationColumn()
312    
313          #          #
314          # there isn't a classification of anything          # there isn't a classification of anything so do nothing
         # so don't do anything  
315          #          #
316          if field is None: return          if field is None: return
317    
318          attrs["field"] = field          attrs["field"] = field
319            attrs["field_type"] = str(layer.GetFieldType(field))
320          self.open_element("classification", attrs)          self.open_element("classification", attrs)
321    
322            for g in lc:
323  #       self.open_element("clnull")              if isinstance(g, ClassGroupDefault):
324  #       write_class_data(lc.GetDefaultData())                  open_el  = 'clnull label="%s"' % self.encode(g.GetLabel())
325  #       self.close_element("clnull")                  close_el = 'clnull'
326                            elif isinstance(g, ClassGroupSingleton):
327          # just playing now with lambdas and dictionaries                  if layer.GetFieldType(field) == FIELDTYPE_STRING:
328                        value = self.encode(g.GetValue())
329          types = [[lambda p: 'clnull',                  else:
330                    lambda p: 'clnull'],                      value = str(g.GetValue())
331                   [lambda p: 'clpoint value="%s"' %                  open_el  = 'clpoint label="%s" value="%s"' \
332                               str(p.GetValue()),                             % (self.encode(g.GetLabel()), value)
333                    lambda p: 'clpoint'],                  close_el = 'clpoint'
334                   [lambda p: 'clrange min="%s" max="%s"' %              elif isinstance(g, ClassGroupRange):
335                               (str(p.GetMin()),                  open_el  = 'clrange label="%s" range="%s"' \
336                                (str(p.GetMax()))),                            % (self.encode(g.GetLabel()), str(g.GetRange()))
337                    lambda p: 'clrange']]                  close_el = 'clrange'
338                else:
339          def write_class_group(group):                  assert False, _("Unsupported group type in classification")
340              type = -1                  continue
341              if isinstance(group, ClassGroupDefault): type = 0  
342              elif isinstance(group, ClassGroupSingleton): type = 1              data = g.GetProperties()
343              elif isinstance(group, ClassGroupRange): type = 2              dict = {'stroke'      : data.GetLineColor().hex(),
344              elif isinstance(group, ClassGroupMap):   type = 3                      'stroke_width': str(data.GetLineWidth()),
345              assert(type >= 0)                      'fill'        : data.GetFill().hex()}
346    
347              if type <= 2:              self.open_element(open_el)
348                  data = group.GetProperties()              self.write_element("cldata", dict)
349                  dict = {'stroke'      : data.GetStroke().hex(),              self.close_element(close_el)
                         'stroke_width': str(data.GetStrokeWidth()),  
                         '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')  
350    
351          self.close_element("classification")          self.close_element("classification")
352    
# Line 322  class Saver: Line 359  class Saver:
359              for label in labels:              for label in labels:
360                  self.write_element(('label x="%g" y="%g" text="%s"'                  self.write_element(('label x="%g" y="%g" text="%s"'
361                                      ' halign="%s" valign="%s"')                                      ' halign="%s" valign="%s"')
362                                  % (label.x, label.y, label.text, label.halign,                                  % (label.x, label.y,
363                                       self.encode(label.text),
364                                       label.halign,
365                                     label.valign))                                     label.valign))
366              self.close_element('labellayer')              self.close_element('labellayer')
367    
# Line 335  def save_session(session, file, saver_cl Line 374  def save_session(session, file, saver_cl
374    
375      The optional argument saver_class is the class to use to serialize      The optional argument saver_class is the class to use to serialize
376      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
377      Saver.      SessionSaver.
378    
379      If writing the session is successful call the session's      If writing the session is successful call the session's
380      UnsetModified method      UnsetModified method
381      """      """
382      if saver_class is None:      if saver_class is None:
383          saver_class = Saver          saver_class = SessionSaver
384      saver = saver_class(session)      saver = saver_class(session)
385      saver.write(file)      saver.write(file)
386    

Legend:
Removed from v.440  
changed lines
  Added in v.2104

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26