/[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 429 by jonathan, Mon Feb 24 18:46:51 2003 UTC revision 1160 by jonathan, Thu Jun 12 12:40:43 2003 UTC
# Line 1  Line 1 
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]>
# Line 14  Functions to save a session to a file Line 14  Functions to save a session to a file
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 *  from Thuban.Model.classification import \
24        ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, ClassGroupMap
25    
26  #  from Thuban.Model.xmlwriter import XMLWriter
 # one level of indention  
 #  
 TAB = "    "  
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.
# Line 39  def relative_filename(dir, filename): Line 37  def relative_filename(dir, filename):
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, "&", "&amp;")  
     data = string.replace(data, "<", "&lt;")  
     data = string.replace(data, ">", "&gt;")  
     data = string.replace(data, '"', "&quot;")  
     data = string.replace(data, "'", "&apos;")  
     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
# Line 63  class Saver: Line 51  class Saver:
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.  
         """  
59    
60          # keep track of how many levels of indentation to write          self.write_header("session", "thuban.dtd")
         self.indent_level = 0  
         # 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()  
61          self.write_session(self.session)          self.write_session(self.session)
62            self.close()
         assert(self.indent_level == 0)  
   
     def write_attribs(self, attrs):  
         for name, value in attrs.items():  
             self.file.write(' %s="%s"' % (escape(name), 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))  
   
     def write_element(self, element, attrs = {}):  
         """write an element that won't need a closing tag"""  
         self.open_element(element, attrs)  
         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')  
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
# Line 177  class Saver: Line 95  class Saver:
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)
# Line 189  class Saver: Line 106  class Saver:
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):
# Line 201  class Saver: Line 119  class Saver:
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          """          """
         lc = layer.GetClassification()  
122    
123          if attrs is None:          if attrs is None:
124              attrs = {}              attrs = {}
125    
126          attrs["title"]        = layer.title          attrs["title"]        = layer.title
127          attrs["filename"]     = relative_filename(self.dir, layer.filename)          attrs["filename"]     = relative_filename(self.dir, layer.filename)
128          attrs["stroke"]       = lc.GetDefaultStroke().hex()          attrs["visible"]      = ("false", "true")[int(layer.Visible())]
129          attrs["stroke_width"] = str(lc.GetDefaultStrokeWidth())  
130          attrs["fill"]         = lc.GetDefaultFill().hex()          if isinstance(layer, Layer):
131    
132          self.open_element("layer", attrs)              lc = layer.GetClassification()
133          self.write_classification(layer)              attrs["stroke"]       = lc.GetDefaultLineColor().hex()
134          self.close_element("layer")              attrs["stroke_width"] = str(lc.GetDefaultLineWidth())
135                attrs["fill"]         = lc.GetDefaultFill().hex()
136    
137                self.open_element("layer", attrs)
138                self.write_projection(layer.GetProjection())
139                self.write_classification(layer)
140                self.close_element("layer")
141    
142            elif isinstance(layer, RasterLayer):
143    
144                self.open_element("rasterlayer", attrs)
145                self.write_projection(layer.GetProjection())
146                self.close_element("rasterlayer")
147    
148      def write_classification(self, layer, attrs = None):      def write_classification(self, layer, attrs = None):
149          if attrs is None:          if attrs is None:
# Line 231  class Saver: Line 160  class Saver:
160          if field is None: return          if field is None: return
161    
162          attrs["field"] = field          attrs["field"] = field
163            attrs["field_type"] = str(lc.GetFieldType())
164          self.open_element("classification", attrs)          self.open_element("classification", attrs)
165    
166    
167  #       self.open_element("clnull")          types = [[lambda p: 'clnull label="%s"' % self.encode(p.GetLabel()),
168  #       write_class_data(lc.GetDefaultData())                    lambda p: 'clnull'],
169  #       self.close_element("clnull")                   [lambda p: 'clpoint label="%s" value="%s"' %
170                                             (self.encode(p.GetLabel()), str(p.GetValue())),
171          # just playing now with lambdas and dictionaries                    lambda p: 'clpoint'],
172                     [lambda p: 'clrange label="%s" range="%s"' %
173          types = {ClassData.DEFAULT:                               (self.encode(p.GetLabel()),
174                       [lambda p: 'clnull',                                str(p.GetRange())),
175                        lambda p: 'clnull'],                    lambda p: 'clrange']]
176                   ClassData.POINT:  
177                       [lambda p: 'clpoint value="%s"' %          def write_class_group(group):
178                                   str(p.GetValue()),              type = -1
179                        lambda p: 'clpoint'],              if isinstance(group, ClassGroupDefault): type = 0
180                   ClassData.RANGE:              elif isinstance(group, ClassGroupSingleton): type = 1
181                       [lambda p: 'clrange min="%s" max="%s"' %              elif isinstance(group, ClassGroupRange): type = 2
182                                   (str(p.GetMin()),              elif isinstance(group, ClassGroupMap):   type = 3
183                                    (str(p.GetMax()))),              assert type >= 0
184                        lambda p: 'clrange']}  
185                if type <= 2:
186          def write_class_data(data):                  data = group.GetProperties()
187              dict = {'stroke'      : data.GetStroke().hex(),                  dict = {'stroke'      : data.GetLineColor().hex(),
188                      'stroke_width': str(data.GetStrokeWidth()),                          'stroke_width': str(data.GetLineWidth()),
189                      'fill'        : data.GetFill().hex()}                          'fill'        : data.GetFill().hex()}
190              t = data.GetType()  
191              self.open_element(types[t][0](data))                  self.open_element(types[type][0](group))
192              self.write_element("cldata", dict)                  self.write_element("cldata", dict)
193              self.close_element(types[t][1](data))                  self.close_element(types[type][1](group))
194                else: pass # XXX: we need to handle maps
195    
196          for i in lc:          for i in lc:
197              write_class_data(i)              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')  
198    
199          self.close_element("classification")          self.close_element("classification")
200    
# Line 312  class Saver: Line 207  class Saver:
207              for label in labels:              for label in labels:
208                  self.write_element(('label x="%g" y="%g" text="%s"'                  self.write_element(('label x="%g" y="%g" text="%s"'
209                                      ' halign="%s" valign="%s"')                                      ' halign="%s" valign="%s"')
210                                  % (label.x, label.y, label.text, label.halign,                                  % (label.x, label.y,
211                                       self.encode(label.text),
212                                       label.halign,
213                                     label.valign))                                     label.valign))
214              self.close_element('labellayer')              self.close_element('labellayer')
215    
# Line 325  def save_session(session, file, saver_cl Line 222  def save_session(session, file, saver_cl
222    
223      The optional argument saver_class is the class to use to serialize      The optional argument saver_class is the class to use to serialize
224      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
225      Saver.      SessionSaver.
226    
227      If writing the session is successful call the session's      If writing the session is successful call the session's
228      UnsetModified method      UnsetModified method
229      """      """
230      if saver_class is None:      if saver_class is None:
231          saver_class = Saver          saver_class = SessionSaver
232      saver = saver_class(session)      saver = saver_class(session)
233      saver.write(file)      saver.write(file)
234    

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26