/[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 391 by jonathan, Mon Feb 10 15:26:11 2003 UTC revision 920 by bh, Fri May 16 17:37:29 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]>
5    # Jonathan Coles <[email protected]>
6  #  #
7  # This program is free software under the GPL (>=v2)  # This program is free software under the GPL (>=v2)
8  # Read the file COPYING coming with Thuban for details.  # Read the file COPYING coming with Thuban for details.
# Line 17  import string Line 18  import string
18    
19  import Thuban.Lib.fileutil  import Thuban.Lib.fileutil
20    
21  from Thuban.Model.color import Color  from Thuban.Model.classification import \
22        ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, ClassGroupMap
23    
24  #  #
25  # one level of indention  # one level of indention
# Line 46  def escape(data): Line 48  def escape(data):
48      data = string.replace(data, "'", "&apos;")      data = string.replace(data, "'", "&apos;")
49      return data      return data
50    
51  class Saver:  class XMLWriter:
52        """Abstract XMLWriter.
53    
54      """Class to serialize a session into an XML file.      Should be overridden to provide specific object saving functionality.
   
     Applications built on top of Thuban may derive from this class and  
     override or extend the methods to save additinal information. This  
     additional information should take the form of additional attributes  
     or elements whose names are prefixed with a namespace. To define a  
     namespace derived classes should extend the write_session method to  
     pass the namespaces to the default implementation.  
55      """      """
56    
57        def __init__(self):
58      def __init__(self, session):          self.filename = None
59          self.session = session          pass
60    
61      def write(self, file_or_filename):      def write(self, file_or_filename):
62          """Write the session to a file.          """Write the session to a file.
# Line 73  class Saver: Line 69  class Saver:
69          directory.          directory.
70    
71          If the argument is a file object (which is determined by the          If the argument is a file object (which is determined by the
72          presence of a write method) all filenames will be absolut          presence of a write method) all filenames will be absolute
73          filenames.          filenames.
74          """          """
75    
# Line 87  class Saver: Line 83  class Saver:
83              self.file = file_or_filename              self.file = file_or_filename
84              self.dir = ""              self.dir = ""
85          else:          else:
86              filename = file_or_filename              self.filename = file_or_filename
87              self.dir = os.path.dirname(filename)              self.dir = os.path.dirname(self.filename)
88              self.file = open(filename, 'w')              self.file = open(self.filename, 'w')
89          self.write_header()  
90          self.write_session(self.session)      def close(self):
91            assert self.indent_level == 0
92            if self.filename is not None:
93                self.file.close()
94    
95          if self.indent_level != 0:      def write_header(self, doctype, system):
96              raise ValueError("indent_level still positive!")          """Write the XML header"""
97            self.file.write('<?xml version="1.0" encoding="UTF-8"?>\n')
98            self.file.write('<!DOCTYPE %s SYSTEM "%s">\n' % (doctype, system))
99    
     def write_attribs(self, attrs):  
         for name, value in attrs.items():  
             if isinstance(value, Color):  
                 value = value.hex()  
             else:  
                 value = str(value)  
             self.file.write(' %s="%s"' % (escape(name), escape(value)))  
       
100      def open_element(self, element, attrs = {}):      def open_element(self, element, attrs = {}):
101    
102          #          #
# Line 120  class Saver: Line 113  class Saver:
113    
114          # Helper function to write an element open tag with attributes          # Helper function to write an element open tag with attributes
115          self.file.write("%s<%s" % (TAB*self.indent_level, element))          self.file.write("%s<%s" % (TAB*self.indent_level, element))
116          self.write_attribs(attrs)          self.__write_attribs(attrs)
117    
118          self.indent_level += 1          self.indent_level += 1
119    
120      def close_element(self, element):      def close_element(self, element):
121          self.indent_level -= 1          self.indent_level -= 1
122          if self.indent_level < 0:          assert self.indent_level >= 0
             raise ValueError("close_element called too many times!")  
123    
124          # see open_element() for an explanation          # see open_element() for an explanation
125          if self.element_open == 1:          if self.element_open == 1:
# Line 141  class Saver: Line 133  class Saver:
133          self.open_element(element, attrs)          self.open_element(element, attrs)
134          self.close_element(element)          self.close_element(element)
135    
136      def write_header(self):      def __write_attribs(self, attrs):
137          """Write the XML header"""          for name, value in attrs.items():
138          self.file.write('<?xml version="1.0" encoding="UTF-8"?>\n')              self.file.write(' %s="%s"' % (self.encode(name),
139          self.file.write('<!DOCTYPE session SYSTEM "thuban.dtd">\n')                                            self.encode(value)))
140    
141        def encode(self, str):
142            """Return an XML-escaped and UTF-8 encoded copy of the string str.
143    
144            Assume that the argument is a bytestring in Latin 1.
145            """
146            return unicode(escape(str),'latin1').encode("utf8")
147    
148    
149    class SessionSaver(XMLWriter):
150    
151        """Class to serialize a session into an XML file.
152    
153        Applications built on top of Thuban may derive from this class and
154        override or extend the methods to save additional information. This
155        additional information should take the form of additional attributes
156        or elements whose names are prefixed with a namespace. To define a
157        namespace derived classes should extend the write_session method to
158        pass the namespaces to the default implementation.
159        """
160    
161    
162        def __init__(self, session):
163            XMLWriter.__init__(self)
164            self.session = session
165    
166        def write(self, file_or_filename):
167            XMLWriter.write(self, file_or_filename)
168    
169            self.write_header("session", "thuban.dtd")
170            self.write_session(self.session)
171            self.close()
172    
173      def write_session(self, session, attrs = None, namespaces = ()):      def write_session(self, session, attrs = None, namespaces = ()):
174          """Write the session and its contents          """Write the session and its contents
# Line 180  class Saver: Line 204  class Saver:
204          element, call write_layer for each layer contained in the map          element, call write_layer for each layer contained in the map
205          and finally call write_label_layer to write the label layer.          and finally call write_label_layer to write the label layer.
206          """          """
207          write = self.file.write          self.open_element('map title="%s"' % self.encode(map.title))
         self.open_element('map title="%s"' % escape(map.title))  
208          self.write_projection(map.projection)          self.write_projection(map.projection)
209          for layer in map.Layers():          for layer in map.Layers():
210              self.write_layer(layer)              self.write_layer(layer)
# Line 192  class Saver: Line 215  class Saver:
215          """Write the projection.          """Write the projection.
216          """          """
217          if projection and len(projection.params) > 0:          if projection and len(projection.params) > 0:
218              self.open_element("projection")              self.open_element("projection", {"name": projection.GetName()})
219              for param in projection.params:              for param in projection.params:
220                  self.write_element('parameter value="%s"' % escape(param))                  self.write_element('parameter value="%s"' %
221                                       self.encode(param))
222              self.close_element("projection")              self.close_element("projection")
223    
224      def write_layer(self, layer, attrs = None):      def write_layer(self, layer, attrs = None):
# Line 204  class Saver: Line 228  class Saver:
228          given, should be a mapping from attribute names to attribute          given, should be a mapping from attribute names to attribute
229          values. The values should not be XML-escaped yet.          values. The values should not be XML-escaped yet.
230          """          """
231          lc = layer.classification          lc = layer.GetClassification()
232    
233          if attrs is None:          if attrs is None:
234              attrs = {}              attrs = {}
235          attrs["title"] = layer.title  
236          attrs["filename"] = relative_filename(self.dir, layer.filename)          attrs["title"]        = layer.title
237          attrs["stroke_width"] = str(lc.GetDefaultStrokeWidth())          attrs["filename"]     = relative_filename(self.dir, layer.filename)
238          fill = lc.GetDefaultFill()          attrs["stroke"]       = lc.GetDefaultLineColor().hex()
239          if fill is None:          attrs["stroke_width"] = str(lc.GetDefaultLineWidth())
240              attrs["fill"] = "None"          attrs["fill"]         = lc.GetDefaultFill().hex()
241          else:          attrs["visible"]      = ("false", "true")[int(layer.Visible())]
             attrs["fill"] = fill.hex()  
         stroke = lc.GetDefaultStroke()  
         if stroke is None:  
             attrs["stroke"] = "None"  
         else:  
             attrs["stroke"] = stroke.hex()  
242    
243          self.open_element("layer", attrs)          self.open_element("layer", attrs)
244    
245            proj = layer.GetProjection()
246            if proj is not None:
247                self.write_projection(proj)
248    
249          self.write_classification(layer)          self.write_classification(layer)
250    
251          self.close_element("layer")          self.close_element("layer")
252    
253      def write_classification(self, layer, attrs = None):      def write_classification(self, layer, attrs = None):
254          if attrs is None:          if attrs is None:
255              attrs = {}              attrs = {}
256    
257          lc = layer.classification          lc = layer.GetClassification()
258    
259          field = lc.field          field = lc.GetField()
260    
261          #          #
262          # there isn't a classification of anything          # there isn't a classification of anything
# Line 241  class Saver: Line 265  class Saver:
265          if field is None: return          if field is None: return
266    
267          attrs["field"] = field          attrs["field"] = field
268            attrs["field_type"] = str(lc.GetFieldType())
269          self.open_element("classification", attrs)          self.open_element("classification", attrs)
270    
271          def write_class_data(data):  
272              dict = {'stroke'      : data.GetStroke(),          types = [[lambda p: 'clnull label="%s"' % self.encode(p.GetLabel()),
273                      'stroke_width': data.GetStrokeWidth(),                    lambda p: 'clnull'],
274                      'fill'        : data.GetFill()}                   [lambda p: 'clpoint label="%s" value="%s"' %
275              self.write_element("cldata", dict)                               (self.encode(p.GetLabel()), str(p.GetValue())),
276                      lambda p: 'clpoint'],
277          self.open_element("clnull")                   [lambda p: 'clrange label="%s" range="%s"' %
278          write_class_data(lc.GetDefaultData())                               (self.encode(p.GetLabel()),
279          self.close_element("clnull")                                str(p.GetRange())),
280                                  lambda p: 'clrange']]
281          if lc.points != {}:  
282              for value, data in lc.points.items():          def write_class_group(group):
283                  self.open_element('clpoint value="%s"' % (escape(str(value))))              type = -1
284                  write_class_data(data)              if isinstance(group, ClassGroupDefault): type = 0
285                  self.close_element('clpoint')              elif isinstance(group, ClassGroupSingleton): type = 1
286                          elif isinstance(group, ClassGroupRange): type = 2
287          if lc.ranges != []:              elif isinstance(group, ClassGroupMap):   type = 3
288              for p in lc.ranges:              assert type >= 0
289                  self.open_element('clrange min="%s" max="%s"'  
290                      % (escape(str(p[0])), escape(str(p[1]))))              if type <= 2:
291                  write_class_data(p[2])                  data = group.GetProperties()
292                  self.close_element('clrange')                  dict = {'stroke'      : data.GetLineColor().hex(),
293                            'stroke_width': str(data.GetLineWidth()),
294                            'fill'        : data.GetFill().hex()}
295    
296                    self.open_element(types[type][0](group))
297                    self.write_element("cldata", dict)
298                    self.close_element(types[type][1](group))
299                else: pass # XXX: we need to handle maps
300    
301            for i in lc:
302                write_class_group(i)
303    
304          self.close_element("classification")          self.close_element("classification")
305    
# Line 277  class Saver: Line 312  class Saver:
312              for label in labels:              for label in labels:
313                  self.write_element(('label x="%g" y="%g" text="%s"'                  self.write_element(('label x="%g" y="%g" text="%s"'
314                                      ' halign="%s" valign="%s"')                                      ' halign="%s" valign="%s"')
315                                  % (label.x, label.y, label.text, label.halign,                                  % (label.x, label.y,
316                                       self.encode(label.text),
317                                       label.halign,
318                                     label.valign))                                     label.valign))
319              self.close_element('labellayer')              self.close_element('labellayer')
320    
# Line 290  def save_session(session, file, saver_cl Line 327  def save_session(session, file, saver_cl
327    
328      The optional argument saver_class is the class to use to serialize      The optional argument saver_class is the class to use to serialize
329      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
330      Saver.      SessionSaver.
331    
332      If writing the session is successful call the session's      If writing the session is successful call the session's
333      UnsetModified method      UnsetModified method
334      """      """
335      if saver_class is None:      if saver_class is None:
336          saver_class = Saver          saver_class = SessionSaver
337      saver = saver_class(session)      saver = saver_class(session)
338      saver.write(file)      saver.write(file)
339    

Legend:
Removed from v.391  
changed lines
  Added in v.920

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26