/[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 683 by jonathan, Tue Apr 15 21:54:56 2003 UTC revision 920 by bh, Fri May 16 17:37:29 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
17  import string  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
 from Thuban.Model.classification import *  
23    
24  #  #
25  # one level of indention  # one level of indention
# Line 52  def escape(data): Line 48  def escape(data):
48      data = string.replace(data, "'", "'")      data = string.replace(data, "'", "'")
49      return data      return data
50    
51  class Saver:  class XMLWriter:
52        """Abstract XMLWriter.
     """Class to serialize a session into an XML file.  
53    
54      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 additional 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 79  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 93  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')
         self.write_header()  
         self.write_session(self.session)  
89    
90        def close(self):
91          assert self.indent_level == 0          assert self.indent_level == 0
92            if self.filename is not None:
93                self.file.close()
94    
95        def write_header(self, doctype, system):
96            """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():  
             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 121  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    
# 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 214  class Saver: Line 238  class Saver:
238          attrs["stroke"]       = lc.GetDefaultLineColor().hex()          attrs["stroke"]       = lc.GetDefaultLineColor().hex()
239          attrs["stroke_width"] = str(lc.GetDefaultLineWidth())          attrs["stroke_width"] = str(lc.GetDefaultLineWidth())
240          attrs["fill"]         = lc.GetDefaultFill().hex()          attrs["fill"]         = lc.GetDefaultFill().hex()
241            attrs["visible"]      = ("false", "true")[int(layer.Visible())]
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):
# Line 238  class Saver: Line 269  class Saver:
269          self.open_element("classification", attrs)          self.open_element("classification", attrs)
270    
271    
272  #       self.open_element("clnull")          types = [[lambda p: 'clnull label="%s"' % self.encode(p.GetLabel()),
 #       write_class_data(lc.GetDefaultData())  
 #       self.close_element("clnull")  
               
         # just playing now with lambdas and dictionaries  
   
         types = [[lambda p: 'clnull label="%s"' % p.GetLabel(),  
273                    lambda p: 'clnull'],                    lambda p: 'clnull'],
274                   [lambda p: 'clpoint label="%s" value="%s"' %                   [lambda p: 'clpoint label="%s" value="%s"' %
275                               (p.GetLabel(), str(p.GetValue())),                               (self.encode(p.GetLabel()), str(p.GetValue())),
276                    lambda p: 'clpoint'],                    lambda p: 'clpoint'],
277                   [lambda p: 'clrange label="%s" min="%s" max="%s"' %                   [lambda p: 'clrange label="%s" range="%s"' %
278                               (p.GetLabel(),                               (self.encode(p.GetLabel()),
279                                str(p.GetMin()), (str(p.GetMax()))),                                str(p.GetRange())),
280                    lambda p: 'clrange']]                    lambda p: 'clrange']]
281    
282          def write_class_group(group):          def write_class_group(group):
# Line 276  class Saver: Line 301  class Saver:
301          for i in lc:          for i in lc:
302              write_class_group(i)              write_class_group(i)
303    
 #       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')  
   
304          self.close_element("classification")          self.close_element("classification")
305    
306      def write_label_layer(self, layer):      def write_label_layer(self, layer):
# Line 323  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 336  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.683  
changed lines
  Added in v.920

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26