/[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 466 by jonathan, Wed Mar 5 18:18:20 2003 UTC revision 773 by jonathan, Tue Apr 29 14:34:23 2003 UTC
# Line 52  def escape(data): Line 52  def escape(data):
52      data = string.replace(data, "'", "'")      data = string.replace(data, "'", "'")
53      return data      return data
54    
55  class Saver:  class XMLWriter:
56        """Abstract XMLWriter.
57    
58      """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 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.  
59      """      """
60    
61        def __init__(self):
62      def __init__(self, session):          self.filename = None
63          self.session = session          pass
64    
65      def write(self, file_or_filename):      def write(self, file_or_filename):
66          """Write the session to a file.          """Write the session to a file.
# Line 79  class Saver: Line 73  class Saver:
73          directory.          directory.
74    
75          If the argument is a file object (which is determined by the          If the argument is a file object (which is determined by the
76          presence of a write method) all filenames will be absolut          presence of a write method) all filenames will be absolute
77          filenames.          filenames.
78          """          """
79    
# Line 93  class Saver: Line 87  class Saver:
87              self.file = file_or_filename              self.file = file_or_filename
88              self.dir = ""              self.dir = ""
89          else:          else:
90              filename = file_or_filename              self.filename = file_or_filename
91              self.dir = os.path.dirname(filename)              self.dir = os.path.dirname(self.filename)
92              self.file = open(filename, 'w')              self.file = open(self.filename, 'w')
93          self.write_header()  
94          self.write_session(self.session)      def close(self):
95            assert self.indent_level == 0
96            if self.filename is not None:
97                self.file.close()
98    
99          assert(self.indent_level == 0)      def write_header(self, doctype, system):
100            """Write the XML header"""
101            self.file.write('<?xml version="1.0" encoding="UTF-8"?>\n')
102            self.file.write('<!DOCTYPE %s SYSTEM "%s">\n' % (doctype, system))
103    
     def write_attribs(self, attrs):  
         for name, value in attrs.items():  
             self.file.write(' %s="%s"' % (escape(name), escape(value)))  
       
104      def open_element(self, element, attrs = {}):      def open_element(self, element, attrs = {}):
105    
106          #          #
# Line 121  class Saver: Line 117  class Saver:
117    
118          # Helper function to write an element open tag with attributes          # Helper function to write an element open tag with attributes
119          self.file.write("%s<%s" % (TAB*self.indent_level, element))          self.file.write("%s<%s" % (TAB*self.indent_level, element))
120          self.write_attribs(attrs)          self.__write_attribs(attrs)
121    
122          self.indent_level += 1          self.indent_level += 1
123    
124      def close_element(self, element):      def close_element(self, element):
125          self.indent_level -= 1          self.indent_level -= 1
126          assert(self.indent_level >= 0)          assert self.indent_level >= 0
127    
128          # see open_element() for an explanation          # see open_element() for an explanation
129          if self.element_open == 1:          if self.element_open == 1:
# Line 141  class Saver: Line 137  class Saver:
137          self.open_element(element, attrs)          self.open_element(element, attrs)
138          self.close_element(element)          self.close_element(element)
139    
140      def write_header(self):      def __write_attribs(self, attrs):
141          """Write the XML header"""          for name, value in attrs.items():
142          self.file.write('<?xml version="1.0" encoding="UTF-8"?>\n')              self.file.write(' %s="%s"' % (escape(name), escape(value)))
143          self.file.write('<!DOCTYPE session SYSTEM "thuban.dtd">\n')      
144    class SessionSaver(XMLWriter):
145    
146        """Class to serialize a session into an XML file.
147    
148        Applications built on top of Thuban may derive from this class and
149        override or extend the methods to save additional information. This
150        additional information should take the form of additional attributes
151        or elements whose names are prefixed with a namespace. To define a
152        namespace derived classes should extend the write_session method to
153        pass the namespaces to the default implementation.
154        """
155    
156    
157        def __init__(self, session):
158            XMLWriter.__init__(self)
159            self.session = session
160    
161        def write(self, file_or_filename):
162            XMLWriter.write(self, file_or_filename)
163    
164            self.write_header("session", "thuban.dtd")
165            self.write_session(self.session)
166            self.close()
167    
168      def write_session(self, session, attrs = None, namespaces = ()):      def write_session(self, session, attrs = None, namespaces = ()):
169          """Write the session and its contents          """Write the session and its contents
# Line 180  class Saver: Line 199  class Saver:
199          element, call write_layer for each layer contained in the map          element, call write_layer for each layer contained in the map
200          and finally call write_label_layer to write the label layer.          and finally call write_label_layer to write the label layer.
201          """          """
         #write = self.file.write  
202          self.open_element('map title="%s"' % escape(map.title))          self.open_element('map title="%s"' % escape(map.title))
203          self.write_projection(map.projection)          self.write_projection(map.projection)
204          for layer in map.Layers():          for layer in map.Layers():
# Line 192  class Saver: Line 210  class Saver:
210          """Write the projection.          """Write the projection.
211          """          """
212          if projection and len(projection.params) > 0:          if projection and len(projection.params) > 0:
213              self.open_element("projection")              self.open_element("projection",
214                                  {"name": escape(projection.GetName())})
215              for param in projection.params:              for param in projection.params:
216                  self.write_element('parameter value="%s"' % escape(param))                  self.write_element('parameter value="%s"' % escape(param))
217              self.close_element("projection")              self.close_element("projection")
# Line 214  class Saver: Line 233  class Saver:
233          attrs["stroke"]       = lc.GetDefaultLineColor().hex()          attrs["stroke"]       = lc.GetDefaultLineColor().hex()
234          attrs["stroke_width"] = str(lc.GetDefaultLineWidth())          attrs["stroke_width"] = str(lc.GetDefaultLineWidth())
235          attrs["fill"]         = lc.GetDefaultFill().hex()          attrs["fill"]         = lc.GetDefaultFill().hex()
236            attrs["visible"]      = ("false", "true")[int(layer.Visible())]
237    
238          self.open_element("layer", attrs)          self.open_element("layer", attrs)
239    
240            proj = layer.GetProjection()
241            if proj is not None:
242                self.write_projection(proj)
243    
244          self.write_classification(layer)          self.write_classification(layer)
245    
246          self.close_element("layer")          self.close_element("layer")
247    
248      def write_classification(self, layer, attrs = None):      def write_classification(self, layer, attrs = None):
# Line 238  class Saver: Line 264  class Saver:
264          self.open_element("classification", attrs)          self.open_element("classification", attrs)
265    
266    
267  #       self.open_element("clnull")          types = [[lambda p: 'clnull label="%s"' % p.GetLabel(),
 #       write_class_data(lc.GetDefaultData())  
 #       self.close_element("clnull")  
               
         # just playing now with lambdas and dictionaries  
   
         types = [[lambda p: 'clnull',  
268                    lambda p: 'clnull'],                    lambda p: 'clnull'],
269                   [lambda p: 'clpoint value="%s"' %                   [lambda p: 'clpoint label="%s" value="%s"' %
270                               str(p.GetValue()),                               (p.GetLabel(), str(p.GetValue())),
271                    lambda p: 'clpoint'],                    lambda p: 'clpoint'],
272                   [lambda p: 'clrange min="%s" max="%s"' %                   [lambda p: 'clrange label="%s" min="%s" max="%s"' %
273                               (str(p.GetMin()),                               (p.GetLabel(),
274                                (str(p.GetMax()))),                                str(p.GetMin()), (str(p.GetMax()))),
275                    lambda p: 'clrange']]                    lambda p: 'clrange']]
276    
277          def write_class_group(group):          def write_class_group(group):
# Line 260  class Saver: Line 280  class Saver:
280              elif isinstance(group, ClassGroupSingleton): type = 1              elif isinstance(group, ClassGroupSingleton): type = 1
281              elif isinstance(group, ClassGroupRange): type = 2              elif isinstance(group, ClassGroupRange): type = 2
282              elif isinstance(group, ClassGroupMap):   type = 3              elif isinstance(group, ClassGroupMap):   type = 3
283              assert(type >= 0)              assert type >= 0
284    
285              if type <= 2:              if type <= 2:
286                  data = group.GetProperties()                  data = group.GetProperties()
# Line 276  class Saver: Line 296  class Saver:
296          for i in lc:          for i in lc:
297              write_class_group(i)              write_class_group(i)
298    
 #       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')  
   
299          self.close_element("classification")          self.close_element("classification")
300    
301      def write_label_layer(self, layer):      def write_label_layer(self, layer):
# Line 336  def save_session(session, file, saver_cl Line 320  def save_session(session, file, saver_cl
320    
321      The optional argument saver_class is the class to use to serialize      The optional argument saver_class is the class to use to serialize
322      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
323      Saver.      SessionSaver.
324    
325      If writing the session is successful call the session's      If writing the session is successful call the session's
326      UnsetModified method      UnsetModified method
327      """      """
328      if saver_class is None:      if saver_class is None:
329          saver_class = Saver          saver_class = SessionSaver
330      saver = saver_class(session)      saver = saver_class(session)
331      saver.write(file)      saver.write(file)
332    

Legend:
Removed from v.466  
changed lines
  Added in v.773

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26