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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26