/[thuban]/branches/WIP-pyshapelib-bramz/Thuban/Model/load.py
ViewVC logotype

Diff of /branches/WIP-pyshapelib-bramz/Thuban/Model/load.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 6 by bh, Tue Aug 28 15:41:52 2001 UTC revision 267 by bh, Thu Aug 22 10:25:30 2002 UTC
# Line 1  Line 1 
1  # Copyright (C) 2001 by Intevation GmbH  # Copyright (C) 2001, 2002 by Intevation GmbH
2  # Authors:  # Authors:
3  # Jan-Oliver Wagner <[email protected]>  # Jan-Oliver Wagner <[email protected]>
4    # Bernhard Herzog <[email protected]>
5  #  #
6  # This program is free software under the GPL (>=v2)  # This program is free software under the GPL (>=v2)
7  # Read the file COPYING coming with GRASS for details.  # Read the file COPYING coming with GRASS for details.
# Line 12  Parser for thuban session files. Line 13  Parser for thuban session files.
13  __version__ = "$Revision$"  __version__ = "$Revision$"
14    
15  import sys, string, os  import sys, string, os
16    
17    import xml.sax
18    import xml.sax.handler
19    from xml.sax import make_parser, ErrorHandler
20    
21  from Thuban.Model.session import Session  from Thuban.Model.session import Session
22  from Thuban.Model.map import Map  from Thuban.Model.map import Map
23  from Thuban.Model.layer import Layer  from Thuban.Model.layer import Layer
24  from Thuban.Model.color import Color  from Thuban.Model.color import Color
25  from Thuban.Model.proj import Projection  from Thuban.Model.proj import Projection
26    
 oldPython=0  
   
 if not sys.__dict__.has_key("version_info"):  
     # We can assume to have python 1.5.2 or lower here now  
     oldPython=1  
   
 if oldPython:  
     try:  
         from xml.sax.saxexts import make_parser  
         from xml.sax.saxlib import HandlerBase  
         from xml.sax import saxutils  
     except ImportError:  
         sys.stdout.write(("You need to have Python-XML installed or"  
                           " a modern Python!\n"  
                           "Check www.python.org/sigs/xml-sig/\n\n"))  
         raise  
 else:  
     # Do the python 2.0 standard xml thing and map it on the old names  
     import xml.sax  
     import xml.sax.handler  
     HandlerBase=xml.sax.handler.ContentHandler  
     from xml.sax import make_parser  
   
 class testSAXContentHandler(HandlerBase):  
 # SAX compliant  
     def characters(self, ch, start, length):  
         pass  
       
 def test_for_broken_SAX():  
     ch=testSAXContentHandler()  
     try:  
         xml.sax.parseString("""<?xml version="1.0"?>  
             <child1 name="paul">Text goes here</child1>  
         """,ch)  
     except TypeError:  
         return 1  
     return 0  
   
27    
28  def parse_color(color):  def parse_color(color):
29      """      """Return the color object for the string color.
30      Return the color object for the string color. Color may be either  
31      'None' or of the form '#RRGGBB' in the usual HTML color notation      Color may be either 'None' or of the form '#RRGGBB' in the usual
32        HTML color notation
33      """      """
34      color = string.strip(color)      color = string.strip(color)
35      if color == "None":      if color == "None":
# Line 79  def parse_color(color): Line 48  def parse_color(color):
48      return result      return result
49    
50    
51  class ProcessSession(HandlerBase):  class ProcessSession(xml.sax.handler.ContentHandler):
52    
53        # Dictionary mapping element names (or (URI, element name) pairs for
54        # documents using amespaces) to method names. The methods should
55        # accept the same parameters as the startElement (or startElementNS)
56        # methods. The start_dispatcher is used by the default startElement
57        # and startElementNS methods to call a method for the open tag of an
58        # element.
59        start_dispatcher = {}
60    
61        # end_dispatcher works just like start_dispatcher but it's used by
62        # endElement and endElementNS. The method whose names it maps to
63        # should accept the same parameters as endElement and endElementNS.
64        end_dispatcher = {}
65    
66    
67      def __init__(self, directory):      def __init__(self, directory):
68          """Inititialize the Sax handler.          """Inititialize the Sax handler.
69    
70          directory is the directory containing the session file. It's          The directory parameter should be the directory containing the
71          needed to interpret embedded relative filenames          session file. It's needed to interpret embedded relative
72            filenames.
73          """          """
74          self.directory = directory          self.directory = directory
75          self.chars = ''          self.chars = ''
# Line 93  class ProcessSession(HandlerBase): Line 77  class ProcessSession(HandlerBase):
77          self.aMap = None          self.aMap = None
78          self.aLayer = None          self.aLayer = None
79    
80      def startElement(self, name, attrs):      def startElementNS(self, name, qname, attrs):
81          if name == 'session':          """Call the method given for name in self.start_dispatcher
82              self.theSession = Session(attrs.get('title', None))          """
83          elif name == 'map':          if name[0] is None:
84              self.aMap = Map(attrs.get('title', None))              method_name = self.start_dispatcher.get(name[1])
85          elif name == 'projection':          else:
86              self.ProjectionParams = [ ]              # Dispatch with namespace
87          elif name == 'parameter':              method_name = self.start_dispatcher.get(name)
88              self.ProjectionParams.append(attrs.get('value', None))          if method_name is not None:
89          elif name == 'layer':              getattr(self, method_name)(name, qname, attrs)
90              title = attrs.get('title', "")  
91              filename = attrs.get('filename', "")      def endElementNS(self, name, qname):
92              filename = os.path.join(self.directory, filename)          """Call the method given for name in self.end_dispatcher
93              fill = parse_color(attrs.get('fill', "None"))          """
94              stroke = parse_color(attrs.get('stroke', "#000000"))          if name[0] is None:
95              self.aLayer = Layer(title, filename, fill = fill, stroke = stroke)              method_name = self.end_dispatcher.get(name[1])
96          elif name == 'table':          else:
97              print "table title: %s" % attrs.get('title', None)              # Dispatch with namespace
98          elif name == 'labellayer':              method_name = self.end_dispatcher.get(name)
99              self.aLayer = self.aMap.LabelLayer()          if method_name is not None:
100          elif name == 'label':              getattr(self, method_name)(name, qname)
101              x = float(attrs['x'])  
102              y = float(attrs['y'])      def start_session(self, name, qname, attrs):
103              text = attrs['text']          self.theSession = Session(attrs.get((None, 'title'), None))
104              halign = attrs['halign']      start_dispatcher['session'] = "start_session"
105              valign = attrs['valign']  
106              self.aLayer.AddLabel(x, y, text, halign = halign, valign = valign)      def end_session(self, name, qname):
107                    pass
108        end_dispatcher['session'] = "end_session"
109      if not oldPython and test_for_broken_SAX():  
110          # works with python 2.0, but is not SAX compliant      def start_map(self, name, qname, attrs):
111          def characters(self, ch):          """Start a map."""
112              self.my_characters(ch)          self.aMap = Map(attrs.get((None, 'title'), None))
113      else:      start_dispatcher['map'] = "start_map"
114          # SAX compliant  
115          def characters(self, ch, start, length):      def end_map(self, name, qname):
116              self.my_characters(ch[start:start+length])          self.theSession.AddMap(self.aMap)
117        end_dispatcher['map'] = "end_map"
118      def my_characters(self, ch):  
119          self.chars = self.chars + ch      def start_projection(self, name, qname, attrs):
120            self.ProjectionParams = [ ]
121      def endElement(self, name):      start_dispatcher['projection'] = "start_projection"
122          # If it's not a parameter element, ignore it  
123          if name == 'session':      def end_projection(self, name, qname):
124              #print "end of session"          self.aMap.SetProjection(Projection(self.ProjectionParams))
125              pass      end_dispatcher['projection'] = "end_projection"
126          if name == 'map':  
127              self.theSession.AddMap(self.aMap)      def start_parameter(self, name, qname, attrs):
128          if name == 'projection':          s = attrs.get((None, 'value'))
129              self.aMap.SetProjection(Projection(self.ProjectionParams))          s = str(s) # we can't handle unicode in proj
130          if name == 'layer':          self.ProjectionParams.append(s)
131              self.aMap.AddLayer(self.aLayer)      start_dispatcher['parameter'] = "start_parameter"
132          if name == 'table':  
133              #print "end of table"      def start_layer(self, name, qname, attrs, layer_class = Layer):
134              pass          """Start a layer
135    
136            Instantiate a layer of class layer_class from the attributes in
137            attrs which may be a dictionary as well as the normal SAX attrs
138            object and bind it to self.aLayer.
139            """
140            title = attrs.get((None, 'title'), "")
141            filename = attrs.get((None, 'filename'), "")
142            filename = os.path.join(self.directory, filename)
143            fill = parse_color(attrs.get((None, 'fill'), "None"))
144            stroke = parse_color(attrs.get((None, 'stroke'), "#000000"))
145            stroke_width = int(attrs.get((None, 'stroke_width'), "1"))
146            self.aLayer = layer_class(title, filename, fill = fill,
147                                      stroke = stroke, stroke_width = stroke_width)
148        start_dispatcher['layer'] = "start_layer"
149    
150        def end_layer(self, name, qname):
151            self.aMap.AddLayer(self.aLayer)
152        end_dispatcher['layer'] = "end_layer"
153    
154        def start_table(self, name, qname, attrs):
155            print "table title: %s" % attrs.get('title', None)
156        start_dispatcher['table'] = "start_table"
157    
158        def end_table(self, name, qname):
159            pass
160        end_dispatcher['table'] = "end_table"
161    
162        def start_labellayer(self, name, qname, attrs):
163            self.aLayer = self.aMap.LabelLayer()
164        start_dispatcher['labellayer'] = "start_labellayer"
165    
166        def start_label(self, name, qname, attrs):
167            x = float(attrs[(None, 'x')])
168            y = float(attrs[(None, 'y')])
169            text = attrs[(None, 'text')]
170            halign = attrs[(None, 'halign')]
171            valign = attrs[(None, 'valign')]
172            self.aLayer.AddLabel(x, y, text, halign = halign, valign = valign)
173        start_dispatcher['label'] = "start_label"
174    
175        def characters(self, chars):
176            pass
177    
178    
179  def load_session(filename):  def load_session(filename):
180      """Load a Thuban session from the file object file"""      """Load a Thuban session from the file object file"""
# Line 155  def load_session(filename): Line 182  def load_session(filename):
182      file = open(filename)      file = open(filename)
183      handler = ProcessSession(dir)      handler = ProcessSession(dir)
184    
185      if oldPython:      parser = make_parser()
186          parser = make_parser()      parser.setContentHandler(handler)
187          parser.setDocumentHandler(handler)      parser.setErrorHandler(ErrorHandler())
188          parser.setErrorHandler(saxutils.ErrorPrinter())      parser.setFeature(xml.sax.handler.feature_namespaces, 1)
189          parser.parseFile(file)      parser.parse(file)
190          parser.close()  
     else:  
         xml.sax.parse(file,handler)  
191      session = handler.theSession      session = handler.theSession
192      # Newly loaded session aren't modified      # Newly loaded session aren't modified
193      session.UnsetModified()      session.UnsetModified()
194    
195      return session      return session
196    
 if __name__ == "__main__":  
     # find out the command to run  
     if len(sys.argv) > 1:  
         print "usage: cat <file> | " + sys.argv[0]  
     else:  
         parseSession(sys.stdin)  

Legend:
Removed from v.6  
changed lines
  Added in v.267

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26