/[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 268 by bh, Thu Aug 22 10:25:43 2002 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.classification import \
22        ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, ClassGroupMap
23    
24    #
25    # one level of indention
26    #
27    TAB = "    "
28    
29  def relative_filename(dir, filename):  def relative_filename(dir, filename):
30      """Return a filename relative to dir for the absolute file name absname.      """Return a filename relative to dir for the absolute file name absname.
31    
# Line 39  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, session):      def __init__(self):
58          self.session = session          self.filename = None
59            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 65  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    
76            # keep track of how many levels of indentation to write
77            self.indent_level = 0
78            # track whether an element is currently open. see open_element().
79            self.element_open = 0
80    
81          if hasattr(file_or_filename, "write"):          if hasattr(file_or_filename, "write"):
82              # it's a file object              # it's a file object
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        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    
100        def open_element(self, element, attrs = {}):
101    
102            #
103            # we note when an element is opened so that if two open_element()
104            # calls are made successively we can end the currently open
105            # tag and will later write a proper close tag. otherwise,
106            # if a close_element() call is made directly after an open_element()
107            # call we will close the tag with a />
108            #
109            if self.element_open == 1:
110                self.file.write(">\n")
111    
112            self.element_open = 1
113    
     def write_element(self, element, attrs, empty = 0, indentation = ""):  
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" % (indentation, element))          self.file.write("%s<%s" % (TAB*self.indent_level, element))
116          for name, value in attrs.items():          self.__write_attribs(attrs)
117              self.file.write(' %s="%s"' % (escape(name), escape(value)))  
118          if empty:          self.indent_level += 1
119    
120        def close_element(self, element):
121            self.indent_level -= 1
122            assert self.indent_level >= 0
123    
124            # see open_element() for an explanation
125            if self.element_open == 1:
126                self.element_open = 0
127              self.file.write("/>\n")              self.file.write("/>\n")
128          else:          else:
129              self.file.write(">\n")              self.file.write("%s</%s>\n" % (TAB*self.indent_level, element))
130    
131        def write_element(self, element, attrs = {}):
132            """write an element that won't need a closing tag"""
133            self.open_element(element, attrs)
134            self.close_element(element)
135    
136        def __write_attribs(self, attrs):
137            for name, value in attrs.items():
138                self.file.write(' %s="%s"' % (self.encode(name),
139                                              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      def write_header(self):  
149          """Write the XML header"""  class SessionSaver(XMLWriter):
150          write = self.file.write  
151          write('<?xml version="1.0" encoding="UTF-8"?>\n')      """Class to serialize a session into an XML file.
152          write('<!DOCTYPE session SYSTEM "thuban.dtd">\n')  
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 116  class Saver: Line 191  class Saver:
191          attrs["title"] = session.title          attrs["title"] = session.title
192          for name, uri in namespaces:          for name, uri in namespaces:
193              attrs["xmlns:" + name] = uri              attrs["xmlns:" + name] = uri
194          self.write_element("session", attrs)          self.open_element("session", attrs)
195          for map in session.Maps():          for map in session.Maps():
196              self.write_map(map)              self.write_map(map)
197          self.file.write('</session>\n')          self.close_element("session")
198    
199      def write_map(self, map):      def write_map(self, map):
200          """Write the map and its contents.          """Write the map and its contents.
# Line 129  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))
         write('\t<map title="%s">\n' % 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)
211          self.write_label_layer(map.LabelLayer())          self.write_label_layer(map.LabelLayer())
212          write('\t</map>\n')          self.close_element('map')
213    
214      def write_projection(self, projection):      def write_projection(self, projection):
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.file.write('\t\t<projection>\n')              self.open_element("projection", {"name": projection.GetName()})
219              for param in projection.params:              for param in projection.params:
220                  self.file.write('\t\t\t<parameter value="%s"/>\n'                  self.write_element('parameter value="%s"' %
221                                  % escape(param))                                     self.encode(param))
222              self.file.write('\t\t</projection>\n')              self.close_element("projection")
223    
224      def write_layer(self, layer, attrs = None):      def write_layer(self, layer, attrs = None):
225          """Write the layer.          """Write the layer.
# Line 154  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.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(layer.stroke_width)          attrs["filename"]     = relative_filename(self.dir, layer.filename)
238          fill = layer.fill          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())]
242              attrs["fill"] = fill.hex()  
243          stroke = layer.stroke          self.open_element("layer", attrs)
244          if stroke is None:  
245              attrs["stroke"] = "None"          proj = layer.GetProjection()
246          else:          if proj is not None:
247              attrs["stroke"] = stroke.hex()              self.write_projection(proj)
248          self.write_element("layer", attrs, empty = 1, indentation = "\t\t")  
249            self.write_classification(layer)
250    
251            self.close_element("layer")
252    
253        def write_classification(self, layer, attrs = None):
254            if attrs is None:
255                attrs = {}
256    
257            lc = layer.GetClassification()
258    
259            field = lc.GetField()
260    
261            #
262            # there isn't a classification of anything
263            # so don't do anything
264            #
265            if field is None: return
266    
267            attrs["field"] = field
268            attrs["field_type"] = str(lc.GetFieldType())
269            self.open_element("classification", attrs)
270    
271    
272            types = [[lambda p: 'clnull label="%s"' % self.encode(p.GetLabel()),
273                      lambda p: 'clnull'],
274                     [lambda p: 'clpoint label="%s" value="%s"' %
275                                 (self.encode(p.GetLabel()), str(p.GetValue())),
276                      lambda p: 'clpoint'],
277                     [lambda p: 'clrange label="%s" range="%s"' %
278                                 (self.encode(p.GetLabel()),
279                                  str(p.GetRange())),
280                      lambda p: 'clrange']]
281    
282            def write_class_group(group):
283                type = -1
284                if isinstance(group, ClassGroupDefault): type = 0
285                elif isinstance(group, ClassGroupSingleton): type = 1
286                elif isinstance(group, ClassGroupRange): type = 2
287                elif isinstance(group, ClassGroupMap):   type = 3
288                assert type >= 0
289    
290                if type <= 2:
291                    data = group.GetProperties()
292                    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")
305    
306      def write_label_layer(self, layer):      def write_label_layer(self, layer):
307          """Write the label layer.          """Write the label layer.
308          """          """
309          labels = layer.Labels()          labels = layer.Labels()
310          if labels:          if labels:
311              self.file.write('\t\t<labellayer>\n')              self.open_element('labellayer')
312              for label in labels:              for label in labels:
313                  self.file.write(('\t\t\t<label x="%g" y="%g" text="%s"'                  self.write_element(('label x="%g" y="%g" text="%s"'
314                                   ' halign="%s" valign="%s"/>\n')                                      ' 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.file.write('\t\t</labellayer>\n')              self.close_element('labellayer')
320    
321    
322    
# Line 193  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.268  
changed lines
  Added in v.920

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26