/[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 894 by frank, Mon May 12 10:46: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]>
# 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    
16    # fix for people using python2.1
17    from __future__ import nested_scopes
18    
19  import os  import os
20  import string  import string
21    
# Line 20  import Thuban.Lib.fileutil Line 23  import Thuban.Lib.fileutil
23    
24  from Thuban.Model.color import Color  from Thuban.Model.color import Color
25    
26  from Thuban.Model.classification import *  from Thuban.Model.classification import \
27        ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, ClassGroupMap
28    
29  #  #
30  # one level of indention  # one level of indention
# Line 49  def escape(data): Line 53  def escape(data):
53      data = string.replace(data, "'", "&apos;")      data = string.replace(data, "'", "&apos;")
54      return data      return data
55    
56  class Saver:  class XMLWriter:
57        """Abstract XMLWriter.
     """Class to serialize a session into an XML file.  
58    
59      Applications built on top of Thuban may derive from this class and      Should be overridden to provide specific object saving functionality.
     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.  
60      """      """
61    
62        def __init__(self):
63      def __init__(self, session):          self.filename = None
64          self.session = session          pass
65    
66      def write(self, file_or_filename):      def write(self, file_or_filename):
67          """Write the session to a file.          """Write the session to a file.
# Line 76  class Saver: Line 74  class Saver:
74          directory.          directory.
75    
76          If the argument is a file object (which is determined by the          If the argument is a file object (which is determined by the
77          presence of a write method) all filenames will be absolut          presence of a write method) all filenames will be absolute
78          filenames.          filenames.
79          """          """
80    
# Line 90  class Saver: Line 88  class Saver:
88              self.file = file_or_filename              self.file = file_or_filename
89              self.dir = ""              self.dir = ""
90          else:          else:
91              filename = file_or_filename              self.filename = file_or_filename
92              self.dir = os.path.dirname(filename)              self.dir = os.path.dirname(self.filename)
93              self.file = open(filename, 'w')              self.file = open(self.filename, 'w')
94          self.write_header()  
95          self.write_session(self.session)      def close(self):
96            assert self.indent_level == 0
97            if self.filename is not None:
98                self.file.close()
99    
100          assert(self.indent_level == 0)      def write_header(self, doctype, system):
101            """Write the XML header"""
102            self.file.write('<?xml version="1.0" encoding="UTF-8"?>\n')
103            self.file.write('<!DOCTYPE %s SYSTEM "%s">\n' % (doctype, system))
104    
     def write_attribs(self, attrs):  
         for name, value in attrs.items():  
             self.file.write(' %s="%s"' % (escape(name), value))  
       
105      def open_element(self, element, attrs = {}):      def open_element(self, element, attrs = {}):
106    
107          #          #
# Line 118  class Saver: Line 118  class Saver:
118    
119          # Helper function to write an element open tag with attributes          # Helper function to write an element open tag with attributes
120          self.file.write("%s<%s" % (TAB*self.indent_level, element))          self.file.write("%s<%s" % (TAB*self.indent_level, element))
121          self.write_attribs(attrs)          self.__write_attribs(attrs)
122    
123          self.indent_level += 1          self.indent_level += 1
124    
125      def close_element(self, element):      def close_element(self, element):
126          self.indent_level -= 1          self.indent_level -= 1
127          assert(self.indent_level >= 0)          assert self.indent_level >= 0
128    
129          # see open_element() for an explanation          # see open_element() for an explanation
130          if self.element_open == 1:          if self.element_open == 1:
# Line 138  class Saver: Line 138  class Saver:
138          self.open_element(element, attrs)          self.open_element(element, attrs)
139          self.close_element(element)          self.close_element(element)
140    
141      def write_header(self):      def __write_attribs(self, attrs):
142          """Write the XML header"""          for name, value in attrs.items():
143          self.file.write('<?xml version="1.0" encoding="UTF-8"?>\n')              self.file.write(' %s="%s"' % (self.encode(name),
144          self.file.write('<!DOCTYPE session SYSTEM "thuban.dtd">\n')                                            self.encode(value)))
145        
146        def encode(self, str):
147            """Assume that str is in Latin1, escape it, and encode it in UTF-8.
148            
149            If str is None, return None
150            """
151    
152            if str is not None:
153                return unicode(escape(str),'latin1').encode("utf8")
154            else:
155                return None
156    
157    class SessionSaver(XMLWriter):
158    
159        """Class to serialize a session into an XML file.
160    
161        Applications built on top of Thuban may derive from this class and
162        override or extend the methods to save additional information. This
163        additional information should take the form of additional attributes
164        or elements whose names are prefixed with a namespace. To define a
165        namespace derived classes should extend the write_session method to
166        pass the namespaces to the default implementation.
167        """
168    
169    
170        def __init__(self, session):
171            XMLWriter.__init__(self)
172            self.session = session
173    
174        def write(self, file_or_filename):
175            XMLWriter.write(self, file_or_filename)
176    
177            self.write_header("session", "thuban.dtd")
178            self.write_session(self.session)
179            self.close()
180    
181      def write_session(self, session, attrs = None, namespaces = ()):      def write_session(self, session, attrs = None, namespaces = ()):
182          """Write the session and its contents          """Write the session and its contents
# Line 177  class Saver: Line 212  class Saver:
212          element, call write_layer for each layer contained in the map          element, call write_layer for each layer contained in the map
213          and finally call write_label_layer to write the label layer.          and finally call write_label_layer to write the label layer.
214          """          """
215          write = self.file.write          self.open_element('map title="%s"' % self.encode(map.title))
         self.open_element('map title="%s"' % escape(map.title))  
216          self.write_projection(map.projection)          self.write_projection(map.projection)
217          for layer in map.Layers():          for layer in map.Layers():
218              self.write_layer(layer)              self.write_layer(layer)
# Line 189  class Saver: Line 223  class Saver:
223          """Write the projection.          """Write the projection.
224          """          """
225          if projection and len(projection.params) > 0:          if projection and len(projection.params) > 0:
226              self.open_element("projection")              self.open_element("projection", {"name": projection.GetName()})
227              for param in projection.params:              for param in projection.params:
228                  self.write_element('parameter value="%s"' % escape(param))                  self.write_element('parameter value="%s"' %
229                                       self.encode(param))
230              self.close_element("projection")              self.close_element("projection")
231    
232      def write_layer(self, layer, attrs = None):      def write_layer(self, layer, attrs = None):
# Line 208  class Saver: Line 243  class Saver:
243    
244          attrs["title"]        = layer.title          attrs["title"]        = layer.title
245          attrs["filename"]     = relative_filename(self.dir, layer.filename)          attrs["filename"]     = relative_filename(self.dir, layer.filename)
246          attrs["stroke"]       = lc.GetDefaultStroke().hex()          attrs["stroke"]       = lc.GetDefaultLineColor().hex()
247          attrs["stroke_width"] = str(lc.GetDefaultStrokeWidth())          attrs["stroke_width"] = str(lc.GetDefaultLineWidth())
248          attrs["fill"]         = lc.GetDefaultFill().hex()          attrs["fill"]         = lc.GetDefaultFill().hex()
249            attrs["visible"]      = ("false", "true")[int(layer.Visible())]
250    
251          self.open_element("layer", attrs)          self.open_element("layer", attrs)
252    
253            proj = layer.GetProjection()
254            if proj is not None:
255                self.write_projection(proj)
256    
257          self.write_classification(layer)          self.write_classification(layer)
258    
259          self.close_element("layer")          self.close_element("layer")
260    
261      def write_classification(self, layer, attrs = None):      def write_classification(self, layer, attrs = None):
# Line 231  class Saver: Line 273  class Saver:
273          if field is None: return          if field is None: return
274    
275          attrs["field"] = field          attrs["field"] = field
276            attrs["field_type"] = str(lc.GetFieldType())
277          self.open_element("classification", attrs)          self.open_element("classification", attrs)
278    
279    
280  #       self.open_element("clnull")          types = [[lambda p: 'clnull label="%s"' % self.encode(p.GetLabel()),
281  #       write_class_data(lc.GetDefaultData())                    lambda p: 'clnull'],
282  #       self.close_element("clnull")                   [lambda p: 'clpoint label="%s" value="%s"' %
283                                             (self.encode(p.GetLabel()), str(p.GetValue())),
284          # just playing now with lambdas and dictionaries                    lambda p: 'clpoint'],
285                     [lambda p: 'clrange label="%s" range="%s"' %
286          types = {ClassData.DEFAULT:                               (self.encode(p.GetLabel()),
287                       [lambda p: 'clnull',                                str(p.GetRange())),
288                        lambda p: 'clnull'],                    lambda p: 'clrange']]
289                   ClassData.POINT:  
290                       [lambda p: 'clpoint value="%s"' %          def write_class_group(group):
291                                   str(p.GetValue()),              type = -1
292                        lambda p: 'clpoint'],              if isinstance(group, ClassGroupDefault): type = 0
293                   ClassData.RANGE:              elif isinstance(group, ClassGroupSingleton): type = 1
294                       [lambda p: 'clrange min="%s" max="%s"' %              elif isinstance(group, ClassGroupRange): type = 2
295                                   (str(p.GetMin()),              elif isinstance(group, ClassGroupMap):   type = 3
296                                    (str(p.GetMax()))),              assert type >= 0
297                        lambda p: 'clrange']}  
298                if type <= 2:
299          def write_class_data(data):                  data = group.GetProperties()
300              dict = {'stroke'      : data.GetStroke().hex(),                  dict = {'stroke'      : data.GetLineColor().hex(),
301                      'stroke_width': str(data.GetStrokeWidth()),                          'stroke_width': str(data.GetLineWidth()),
302                      'fill'        : data.GetFill().hex()}                          'fill'        : data.GetFill().hex()}
303              t = data.GetType()  
304              self.open_element(types[t][0](data))                  self.open_element(types[type][0](group))
305              self.write_element("cldata", dict)                  self.write_element("cldata", dict)
306              self.close_element(types[t][1](data))                  self.close_element(types[type][1](group))
307                else: pass # XXX: we need to handle maps
308    
309          for i in lc:          for i in lc:
310              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')  
311    
312          self.close_element("classification")          self.close_element("classification")
313    
# Line 312  class Saver: Line 320  class Saver:
320              for label in labels:              for label in labels:
321                  self.write_element(('label x="%g" y="%g" text="%s"'                  self.write_element(('label x="%g" y="%g" text="%s"'
322                                      ' halign="%s" valign="%s"')                                      ' halign="%s" valign="%s"')
323                                  % (label.x, label.y, label.text, label.halign,                                  % (label.x, label.y,
324                                       self.encode(label.text),
325                                       label.halign,
326                                     label.valign))                                     label.valign))
327              self.close_element('labellayer')              self.close_element('labellayer')
328    
# Line 325  def save_session(session, file, saver_cl Line 335  def save_session(session, file, saver_cl
335    
336      The optional argument saver_class is the class to use to serialize      The optional argument saver_class is the class to use to serialize
337      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
338      Saver.      SessionSaver.
339    
340      If writing the session is successful call the session's      If writing the session is successful call the session's
341      UnsetModified method      UnsetModified method
342      """      """
343      if saver_class is None:      if saver_class is None:
344          saver_class = Saver          saver_class = SessionSaver
345      saver = saver_class(session)      saver = saver_class(session)
346      saver.write(file)      saver.write(file)
347    

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26