/[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 414 by jonathan, Wed Feb 19 16:52:23 2003 UTC
# Line 2  Line 2 
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
22    
23    #
24    # one level of indention
25    #
26    TAB = "    "
27    
28  def relative_filename(dir, filename):  def relative_filename(dir, filename):
29      """Return a filename relative to dir for the absolute file name absname.      """Return a filename relative to dir for the absolute file name absname.
30    
# Line 51  class Saver: Line 59  class Saver:
59      pass the namespaces to the default implementation.      pass the namespaces to the default implementation.
60      """      """
61    
62    
63      def __init__(self, session):      def __init__(self, session):
64          self.session = session          self.session = session
65    
# Line 68  class Saver: Line 77  class Saver:
77          presence of a write method) all filenames will be absolut          presence of a write method) all filenames will be absolut
78          filenames.          filenames.
79          """          """
80    
81            # keep track of how many levels of indentation to write
82            self.indent_level = 0
83            # track whether an element is currently open. see open_element().
84            self.element_open = 0
85    
86          if hasattr(file_or_filename, "write"):          if hasattr(file_or_filename, "write"):
87              # it's a file object              # it's a file object
88              self.file = file_or_filename              self.file = file_or_filename
# Line 79  class Saver: Line 94  class Saver:
94          self.write_header()          self.write_header()
95          self.write_session(self.session)          self.write_session(self.session)
96    
97      def write_element(self, element, attrs, empty = 0, indentation = ""):          if self.indent_level != 0:
98          # Helper function to write an element open tag with attributes              raise ValueError("indent_level still positive!")
99          self.file.write("%s<%s" % (indentation, element))  
100        def write_attribs(self, attrs):
101          for name, value in attrs.items():          for name, value in attrs.items():
102                if isinstance(value, Color):
103                    value = value.hex()
104                else:
105                    value = str(value)
106              self.file.write(' %s="%s"' % (escape(name), escape(value)))              self.file.write(' %s="%s"' % (escape(name), escape(value)))
107          if empty:      
108        def open_element(self, element, attrs = {}):
109    
110            #
111            # we note when an element is opened so that if two open_element()
112            # calls are made successively we can end the currently open
113            # tag and will later write a proper close tag. otherwise,
114            # if a close_element() call is made directly after an open_element()
115            # call we will close the tag with a />
116            #
117            if self.element_open == 1:
118                self.file.write(">\n")
119    
120            self.element_open = 1
121    
122            # Helper function to write an element open tag with attributes
123            self.file.write("%s<%s" % (TAB*self.indent_level, element))
124            self.write_attribs(attrs)
125    
126            self.indent_level += 1
127    
128        def close_element(self, element):
129            self.indent_level -= 1
130            if self.indent_level < 0:
131                raise ValueError("close_element called too many times!")
132    
133            # see open_element() for an explanation
134            if self.element_open == 1:
135                self.element_open = 0
136              self.file.write("/>\n")              self.file.write("/>\n")
137          else:          else:
138              self.file.write(">\n")              self.file.write("%s</%s>\n" % (TAB*self.indent_level, element))
139    
140        def write_element(self, element, attrs = {}):
141            """write an element that won't need a closing tag"""
142            self.open_element(element, attrs)
143            self.close_element(element)
144    
145      def write_header(self):      def write_header(self):
146          """Write the XML header"""          """Write the XML header"""
147          write = self.file.write          self.file.write('<?xml version="1.0" encoding="UTF-8"?>\n')
148          write('<?xml version="1.0" encoding="UTF-8"?>\n')          self.file.write('<!DOCTYPE session SYSTEM "thuban.dtd">\n')
         write('<!DOCTYPE session SYSTEM "thuban.dtd">\n')  
149    
150      def write_session(self, session, attrs = None, namespaces = ()):      def write_session(self, session, attrs = None, namespaces = ()):
151          """Write the session and its contents          """Write the session and its contents
# Line 116  class Saver: Line 168  class Saver:
168          attrs["title"] = session.title          attrs["title"] = session.title
169          for name, uri in namespaces:          for name, uri in namespaces:
170              attrs["xmlns:" + name] = uri              attrs["xmlns:" + name] = uri
171          self.write_element("session", attrs)          self.open_element("session", attrs)
172          for map in session.Maps():          for map in session.Maps():
173              self.write_map(map)              self.write_map(map)
174          self.file.write('</session>\n')          self.close_element("session")
175    
176      def write_map(self, map):      def write_map(self, map):
177          """Write the map and its contents.          """Write the map and its contents.
# Line 130  class Saver: Line 182  class Saver:
182          and finally call write_label_layer to write the label layer.          and finally call write_label_layer to write the label layer.
183          """          """
184          write = self.file.write          write = self.file.write
185          write('\t<map title="%s">\n' % escape(map.title))          self.open_element('map title="%s"' % escape(map.title))
186          self.write_projection(map.projection)          self.write_projection(map.projection)
187          for layer in map.Layers():          for layer in map.Layers():
188              self.write_layer(layer)              self.write_layer(layer)
189          self.write_label_layer(map.LabelLayer())          self.write_label_layer(map.LabelLayer())
190          write('\t</map>\n')          self.close_element('map')
191    
192      def write_projection(self, projection):      def write_projection(self, projection):
193          """Write the projection.          """Write the projection.
194          """          """
195          if projection and len(projection.params) > 0:          if projection and len(projection.params) > 0:
196              self.file.write('\t\t<projection>\n')              self.open_element("projection")
197              for param in projection.params:              for param in projection.params:
198                  self.file.write('\t\t\t<parameter value="%s"/>\n'                  self.write_element('parameter value="%s"' % escape(param))
199                                  % escape(param))              self.close_element("projection")
             self.file.write('\t\t</projection>\n')  
200    
201      def write_layer(self, layer, attrs = None):      def write_layer(self, layer, attrs = None):
202          """Write the layer.          """Write the layer.
# Line 154  class Saver: Line 205  class Saver:
205          given, should be a mapping from attribute names to attribute          given, should be a mapping from attribute names to attribute
206          values. The values should not be XML-escaped yet.          values. The values should not be XML-escaped yet.
207          """          """
208            lc = layer.GetClassification()
209    
210          if attrs is None:          if attrs is None:
211              attrs = {}              attrs = {}
212          attrs["title"] = layer.title          attrs["title"] = layer.title
213          attrs["filename"] = relative_filename(self.dir, layer.filename)          attrs["filename"] = relative_filename(self.dir, layer.filename)
214          attrs["stroke_width"] = str(layer.stroke_width)          attrs["stroke"] = lc.GetDefaultStroke().hex()
215          fill = layer.fill          attrs["stroke_width"] = str(lc.GetDefaultStrokeWidth())
216          if fill is None:          attrs["fill"] = lc.GetDefaultFill().hex()
217              attrs["fill"] = "None"  
218          else:          #fill = lc.GetDefaultFill()
219              attrs["fill"] = fill.hex()          #if fill is None:
220          stroke = layer.stroke              #attrs["fill"] = "None"
221          if stroke is None:          #else:
222              attrs["stroke"] = "None"              #attrs["fill"] = fill.hex()
223          else:  
224              attrs["stroke"] = stroke.hex()  
225          self.write_element("layer", attrs, empty = 1, indentation = "\t\t")          #stroke = lc.GetDefaultStroke()
226            #if stroke is None:
227                #attrs["stroke"] = "None"
228            #else:
229                #attrs["stroke"] = stroke.hex()
230    
231            self.open_element("layer", attrs)
232            self.write_classification(layer)
233            self.close_element("layer")
234    
235        def write_classification(self, layer, attrs = None):
236            if attrs is None:
237                attrs = {}
238    
239            lc = layer.GetClassification()
240    
241            field = lc.field
242    
243            #
244            # there isn't a classification of anything
245            # so don't do anything
246            #
247            if field is None: return
248    
249            attrs["field"] = field
250            self.open_element("classification", attrs)
251    
252            def write_class_data(data):
253                dict = {'stroke'      : data.GetStroke().hex(),
254                        'stroke_width': str(data.GetStrokeWidth()),
255                        'fill'        : data.GetFill().hex()}
256                self.write_element("cldata", dict)
257    
258            self.open_element("clnull")
259            write_class_data(lc.GetDefaultData())
260            self.close_element("clnull")
261                
262            if lc.points != {}:
263                for p in lc.points.values():
264                    self.open_element('clpoint value="%s"' %
265                        (escape(str(p.GetValue()))))
266                    write_class_data(p)
267                    self.close_element('clpoint')
268              
269            if lc.ranges != []:
270                for p in lc.ranges:
271                    self.open_element('clrange min="%s" max="%s"'
272                        % (escape(str(p.GetMin())), escape(str(p.GetMax()))))
273                    write_class_data(p)
274                    self.close_element('clrange')
275    
276            self.close_element("classification")
277    
278      def write_label_layer(self, layer):      def write_label_layer(self, layer):
279          """Write the label layer.          """Write the label layer.
280          """          """
281          labels = layer.Labels()          labels = layer.Labels()
282          if labels:          if labels:
283              self.file.write('\t\t<labellayer>\n')              self.open_element('labellayer')
284              for label in labels:              for label in labels:
285                  self.file.write(('\t\t\t<label x="%g" y="%g" text="%s"'                  self.write_element(('label x="%g" y="%g" text="%s"'
286                                   ' halign="%s" valign="%s"/>\n')                                      ' halign="%s" valign="%s"')
287                                  % (label.x, label.y, label.text, label.halign,                                  % (label.x, label.y, label.text, label.halign,
288                                     label.valign))                                     label.valign))
289              self.file.write('\t\t</labellayer>\n')              self.close_element('labellayer')
290    
291    
292    

Legend:
Removed from v.268  
changed lines
  Added in v.414

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26