File: load.py

package info (click to toggle)
thuban 1.2.2-14
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 9,176 kB
  • sloc: python: 30,410; ansic: 6,181; xml: 4,234; cpp: 1,595; makefile: 145
file content (697 lines) | stat: -rw-r--r-- 28,940 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
# Copyright (C) 2001, 2002, 2003, 2004, 2005, 2007 by Intevation GmbH
# Authors:
# Jan-Oliver Wagner <jan@intevation.de>
# Bernhard Herzog <bh@intevation.de>
# Jonathan Coles <jonathan@intevation.de>
# Frank Koormann <frank@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with GRASS for details.

"""
Parser for thuban session files.
"""

__version__ = "$Revision: 2837 $"

import string, os

import xml.sax
import xml.sax.handler
from xml.sax import make_parser, ErrorHandler, SAXNotRecognizedException

from Thuban import _

from Thuban.Model.table import FIELDTYPE_INT, FIELDTYPE_DOUBLE, \
     FIELDTYPE_STRING

from Thuban.Model.color import Color, Transparent

from Thuban.Model.session import Session
from Thuban.Model.map import Map
from Thuban.Model.layer import Layer, RasterLayer
from Thuban.Model.proj import Projection
from Thuban.Model.range import Range
from Thuban.Model.classification import Classification, \
    ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, \
    ClassGroupPattern, ClassGroupMap, \
    ClassGroupProperties
from Thuban.Model.data import DerivedShapeStore, ShapefileStore
from Thuban.Model.table import DBFTable
from Thuban.Model.transientdb import TransientJoinedTable

from Thuban.Model.xmlreader import XMLReader
import resource

import postgisdb

class LoadError(Exception):

    """Exception raised when the thuban file is corrupted

    Not all cases of corrupted thuban files will lead to this exception
    but those that are found by checks in the loading code itself are. 
    """


class LoadCancelled(Exception):

    """Exception raised to indicate that loading was interrupted by the user"""


def parse_color(color):
    """Return the color object for the string color.

    Color may be either 'None' or of the form '#RRGGBB' in the usual
    HTML color notation
    """
    color = string.strip(color)
    if color == "None":
        result = Transparent
    elif color[0] == '#':
        if len(color) == 7:
            r = string.atoi(color[1:3], 16) / 255.0
            g = string.atoi(color[3:5], 16) / 255.0
            b = string.atoi(color[5:7], 16) / 255.0
            result = Color(r, g, b)
        else:
            raise ValueError(_("Invalid hexadecimal color specification %s")
                             % color)
    else:
        raise ValueError(_("Invalid color specification %s") % color)
    return result

class AttrDesc:

    def __init__(self, name, required = False, default = "",
                 conversion = None):
        if not isinstance(name, tuple):
            fullname = (None, name)
        else:
            fullname = name
            name = name[1]
        self.name = name
        self.fullname = fullname
        self.required = required
        self.default = default
        self.conversion = conversion

        # set by the SessionLoader's check_attrs method
        self.value = None


class SessionLoader(XMLReader):

    def __init__(self, db_connection_callback = None, 
                       shapefile_callback = None):
        """Inititialize the Sax handler."""
        XMLReader.__init__(self)

        self.db_connection_callback = db_connection_callback
        self.shapefile_callback = shapefile_callback
        self.theSession = None
        self.aMap = None
        self.aLayer = None

        # Map ids used in the thuban file to the corresponding objects
        # in the session
        self.idmap = {}

        dispatchers = {
            'session'       : ("start_session",        "end_session"),

            'dbconnection': ("start_dbconnection", None),

            'dbshapesource': ("start_dbshapesource", None),
            'fileshapesource': ("start_fileshapesource", None),
            'derivedshapesource': ("start_derivedshapesource", None),
            'filetable': ("start_filetable", None),
            'jointable': ("start_jointable", None),

            'map'           : ("start_map",            "end_map"),
            'projection'    : ("start_projection",     "end_projection"),
            'parameter'     : ("start_parameter",      None),
            'layer'         : ("start_layer",          "end_layer"),
            'rasterlayer'   : ("start_rasterlayer",    "end_rasterlayer"),
            'classification': ("start_classification", "end_classification"),
            'clnull'        : ("start_clnull",         "end_clnull"),
            'clpoint'       : ("start_clpoint",        "end_clpoint"),
            'clrange'       : ("start_clrange",        "end_clrange"),
            'clpattern'     : ("start_clpattern",      "end_clpattern"),
            'cldata'        : ("start_cldata",         "end_cldata"),
            'table'         : ("start_table",          "end_table"),
            'labellayer'    : ("start_labellayer",     None),
            'label'         : ("start_label",          None)}

        # all dispatchers should be used for the 0.8 and 0.9 namespaces too
        for xmlns in ("http://thuban.intevation.org/dtds/thuban-0.8.dtd",
                      "http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd",
                      "http://thuban.intevation.org/dtds/thuban-0.9.dtd",
                      "http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd",
                      "http://thuban.intevation.org/dtds/thuban-1.0rc1.dtd",
                      "http://thuban.intevation.org/dtds/thuban-1.0.0.dtd",
                      "http://thuban.intevation.org/dtds/thuban-1.1-dev.dtd",
                      "http://thuban.intevation.org/dtds/thuban-1.2.1.dtd"):
            for key, value in dispatchers.items():
                dispatchers[(xmlns, key)] = value

        XMLReader.AddDispatchers(self, dispatchers)

    def Destroy(self):
        """Clear all instance variables to cut cyclic references.

        The GC would have collected the loader eventually but it can
        happen that it doesn't run at all until Thuban is closed (2.3
        but not 2.2 tries a bit harder and forces a collection when the
        interpreter terminates)
        """
        self.__dict__.clear()

    def start_session(self, name, qname, attrs):
        self.theSession = Session(self.encode(attrs.get((None, 'title'),
                                                        None)))

    def end_session(self, name, qname):
        pass

    def check_attrs(self, element, attrs, descr):
        """Check and convert some of the attributes of an element

        Parameters:
           element -- The element name
           attrs -- The attrs mapping as passed to the start_* methods
           descr -- Sequence of attribute descriptions (AttrDesc instances)

        Return a dictionary containig normalized versions of the
        attributes described in descr. The keys of that dictionary are
        the name attributes of the attribute descriptions. The attrs
        dictionary will not be modified.

        If the attribute is required, i.e. the 'required' attribute of
        the descrtiption is true, but it is not in attrs, raise a
        LoadError.

        If the attribute has a default value and it is not present in
        attrs, use that default value as the value in the returned dict.

        The value is converted before putting it into the returned dict.
        The following conversions are available:

           'filename' -- The attribute is a filename.

                         If the filename is a relative name, interpret
                         it relative to the directory containing the
                         .thuban file and make it an absolute name

           'shapestore' -- The attribute is the ID of a shapestore
                           defined earlier in the .thuban file. Look it
                           up self.idmap

           'table' -- The attribute is the ID of a table or shapestore
                      defined earlier in the .thuban file. Look it up
                      self.idmap. If it's the ID of a shapestore the
                      value will be the table of the shapestore.

           'idref' -- The attribute is the id of an object defined
                      earlier in the .thuban file. Look it up self.idmap

           'ascii' -- The attribute is converted to a bytestring with
                      ascii encoding.

           a callable -- The attribute value is passed to the callable
                         and the return value is used as the converted
                         value

        If no conversion is specified for an attribute it is converted
        with self.encode.
        """
        normalized = {}

        for d in descr:
            if d.required and not attrs.has_key(d.fullname):
                raise LoadError("Element %s requires an attribute %r"
                                % (element, d.name))
            value = attrs.get(d.fullname, d.default)

            if d.conversion in ("idref", "shapesource"):
                if value in self.idmap:
                    value = self.idmap[value]
                else:
                    raise LoadError("Element %s requires an already defined ID"
                                    " in attribute %r"
                                    % (element, d.name))
            elif d.conversion == "table":
                if value in self.idmap:
                    value = self.idmap[value]
                    if isinstance(value, ShapefileStore):
                        value = value.Table()
                else:
                    raise LoadError("Element %s requires an already defined ID"
                                    " in attribute %r"
                                    % (element, d.name))
            elif d.conversion == "filename":
                value = os.path.abspath(os.path.join(self.GetDirectory(),
                                                     self.encode(value)))
            elif d.conversion == "ascii":
                value = value.encode("ascii")
            elif d.conversion:
                # Assume it's a callable
                value = d.conversion(value)
            else:
               value = self.encode(value)

            normalized[d.name] = value
        return normalized

    def open_shapefile(self, filename):
        """Open shapefile, with alternative path handling.
         
           If a shapefile cannot be opened and an IOError is raised, check for
           an alternative. This alternative can be specified interactively by
           the user or taken from a list of (potential) locations, depending on
           the callback implementation.
            
           The alternative is rechecked. If taken from a list the user
           has to confirm the alternative.
        """

        # Flag if the alternative path was specified interactively / from list.
        from_list = 0
        while 1:
            try: 
                store = self.theSession.OpenShapefile(filename)
                if from_list:
                    # A valid path has been guessed from a list
                    # Let the user confirm - or select an alternative.
                    filename, from_list = self.shapefile_callback(
                                            filename, "check")
                    if filename is None:
                        # Selection cancelled
                        raise LoadCancelled
                    elif store.FileName() == filename:
                        # Proposed file has been accepted
                        break
                    else:
                        # the filename has been changed, try the new file
                        pass
                else:
                    break
            except IOError:
                if self.shapefile_callback is not None:
                    filename, from_list = self.shapefile_callback(
                                            filename, 
                                            mode = "search", 
                                            second_try = from_list)
                    if filename is None:
                        raise LoadCancelled
                else:
                    raise
        return store

    def start_dbconnection(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("id", True),
                                  AttrDesc("dbtype", True),
                                  AttrDesc("host", False, ""),
                                  AttrDesc("port", False, ""),
                                  AttrDesc("user", False, ""),
                                  AttrDesc("dbname", True)])
        ID = attrs["id"]
        dbtype = attrs["dbtype"]
        if dbtype != "postgis":
            raise LoadError("dbtype %r not supported" % filetype)

        del attrs["id"]
        del attrs["dbtype"]

        # Try to open the connection and if it fails ask the user for
        # the correct parameters repeatedly.
        # FIXME: it would be better not to insist on getting a
        # connection here. We should handle this more like the raster
        # images where the layers etc still are created but are not
        # drawn in case Thuban can't use the data for various reasons
        while 1:
            try:
                conn = postgisdb.PostGISConnection(**attrs)
                break
            except postgisdb.ConnectionError, val:
                if self.db_connection_callback is not None:
                    attrs = self.db_connection_callback(attrs, str(val))
                    if attrs is None:
                        raise LoadCancelled
                else:
                    raise

        self.idmap[ID] = conn
        self.theSession.AddDBConnection(conn)

    def start_dbshapesource(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("id", True),
                                  AttrDesc("dbconn", True,
                                           conversion = "idref"),
                                  AttrDesc("tablename", True,
                                           conversion = "ascii"),
                                  # id_column and geometry_column were
                                  # newly introduced with thuban-1.1.dtd
                                  # where they're required.  Since we
                                  # support the older formats too we
                                  # have them optional here.
                                  AttrDesc("id_column", False, "gid",
                                           conversion = "ascii"),
                                  AttrDesc("geometry_column", False,
                                           conversion = "ascii")])
        # The default value of geometry_column to use when instantiating
        # the db shapestore is None which we currently can't easily use
        # in check_attrs
        geometry_column = attrs["geometry_column"]
        if not geometry_column:
            geometry_column = None
        dbopen = self.theSession.OpenDBShapeStore
        self.idmap[attrs["id"]] = dbopen(attrs["dbconn"], attrs["tablename"],
                                         id_column = attrs["id_column"],
                                         geometry_column=geometry_column)

    def start_fileshapesource(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                  [AttrDesc("id", True),
                                   AttrDesc("filename", True,
                                            conversion = "filename"),
                                   AttrDesc("filetype", True)])
        ID = attrs["id"]
        filename = attrs["filename"]
        filetype = attrs["filetype"]
        if filetype != "shapefile":
            raise LoadError("shapesource filetype %r not supported" % filetype)
        self.idmap[ID] = self.open_shapefile(filename)

    def start_derivedshapesource(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("id", True),
                                  AttrDesc("shapesource", True,
                                           conversion = "shapesource"),
                                  AttrDesc("table", True, conversion="table")])
        store = DerivedShapeStore(attrs["shapesource"], attrs["table"])
        self.theSession.AddShapeStore(store)
        self.idmap[attrs["id"]] = store

    def start_filetable(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("id", True),
                                  AttrDesc("title", True),
                                  AttrDesc("filename", True,
                                           conversion = "filename"),
                                  AttrDesc("filetype")])
        filetype = attrs["filetype"]
        if filetype != "DBF":
            raise LoadError("shapesource filetype %r not supported" % filetype)
        table = DBFTable(attrs["filename"])
        table.SetTitle(attrs["title"])
        self.idmap[attrs["id"]] = self.theSession.AddTable(table)

    def start_jointable(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("id", True),
                                  AttrDesc("title", True),
                                  AttrDesc("left", True, conversion="table"),
                                  AttrDesc("leftcolumn", True),
                                  AttrDesc("right", True, conversion="table"),
                                  AttrDesc("rightcolumn", True),

                                  # jointype is required for file
                                  # version 0.9 but this attribute
                                  # wasn't in the 0.8 version because of
                                  # an oversight so we assume it's
                                  # optional since we want to handle
                                  # both file format versions here.
                                  AttrDesc("jointype", False,
                                           default="INNER")])

        jointype = attrs["jointype"]
        if jointype == "LEFT OUTER":
            outer_join = True
        elif jointype == "INNER":
            outer_join = False
        else:
            raise LoadError("jointype %r not supported" % jointype )
        table = TransientJoinedTable(self.theSession.TransientDB(),
                                     attrs["left"], attrs["leftcolumn"],
                                     attrs["right"], attrs["rightcolumn"],
                                     outer_join = outer_join)
        table.SetTitle(attrs["title"])
        self.idmap[attrs["id"]] = self.theSession.AddTable(table)

    def start_map(self, name, qname, attrs):
        """Start a map."""
        self.aMap = Map(self.encode(attrs.get((None, 'title'), None)))

    def end_map(self, name, qname):
        self.theSession.AddMap(self.aMap)
        self.aMap = None

    def start_projection(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("name", conversion=self.encode),
                                  AttrDesc("epsg", default=None,
                                           conversion=self.encode)])
        self.projection_name = attrs["name"]
        self.projection_epsg = attrs["epsg"]
        self.projection_params = [ ]

    def end_projection(self, name, qname):
        if self.aLayer is not None:
            obj = self.aLayer
        elif self.aMap is not None:
            obj = self.aMap
        else:
            assert False, "projection tag out of context"
            pass

        obj.SetProjection(Projection(self.projection_params,
                                     self.projection_name,
                                     epsg = self.projection_epsg))

    def start_parameter(self, name, qname, attrs):
        s = attrs.get((None, 'value'))
        s = str(s) # we can't handle unicode in proj
        self.projection_params.append(s)

    def start_layer(self, name, qname, attrs, layer_class = Layer):
        """Start a layer

        Instantiate a layer of class layer_class from the attributes in
        attrs which may be a dictionary as well as the normal SAX attrs
        object and bind it to self.aLayer.
        """
        title = self.encode(attrs.get((None, 'title'), ""))
        filename = attrs.get((None, 'filename'), "")
        filename = os.path.join(self.GetDirectory(), filename)
        filename = self.encode(filename)
        visible  = self.encode(attrs.get((None, 'visible'), "true")) != "false"
        fill = parse_color(attrs.get((None, 'fill'), "None"))
        stroke = parse_color(attrs.get((None, 'stroke'), "#000000"))
        stroke_width = int(attrs.get((None, 'stroke_width'), "1"))
        if attrs.has_key((None, "shapestore")):
            store = self.idmap[attrs[(None, "shapestore")]]
        else:
            store = self.open_shapefile(filename)

        self.aLayer = layer_class(title, store,
                                  fill = fill, stroke = stroke,
                                  lineWidth = stroke_width,
                                  visible = visible)

    def end_layer(self, name, qname):
        self.aMap.AddLayer(self.aLayer)
        self.aLayer = None

    def start_rasterlayer(self, name, qname, attrs, layer_class = RasterLayer):
        title = self.encode(attrs.get((None, 'title'), ""))
        filename = attrs.get((None, 'filename'), "")
        filename = os.path.join(self.GetDirectory(), filename)
        filename = self.encode(filename)
        visible  = self.encode(attrs.get((None, 'visible'), "true")) != "false"
        opacity  = float(attrs.get((None, 'opacity'), "1"))
        masktype = str(attrs.get((None, 'masktype'), "alpha"))

        masktypes = {"none": layer_class.MASK_NONE,
                     "bit":  layer_class.MASK_BIT,
                     "alpha": layer_class.MASK_ALPHA}

        self.aLayer = layer_class(title, filename, 
                                  visible = visible,
                                  opacity = opacity,
                                  masktype = masktypes[masktype])

    def end_rasterlayer(self, name, qname):
        self.aMap.AddLayer(self.aLayer)
        self.aLayer = None

    def start_classification(self, name, qname, attrs):
        # field and field_type are optional because the classification
        # can also be empty, ie. have only a default.
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("field", False),
                                  AttrDesc("field_type", False)])

        field = attrs["field"]
        fieldType = attrs["field_type"]

        if field == "": return # no need to set classification column.

        dbFieldType = self.aLayer.GetFieldType(field)

        if fieldType != dbFieldType:
            raise ValueError(_("xml field type differs from database!"))

        # setup conversion routines depending on the kind of data
        # we will be seeing later on
        if fieldType == FIELDTYPE_STRING:
            self.conv = str
        elif fieldType == FIELDTYPE_INT:
            self.conv = lambda p: int(float(p))
        elif fieldType == FIELDTYPE_DOUBLE:
            self.conv = float

        self.aLayer.SetClassificationColumn(field)

    def end_classification(self, name, qname): 
        pass

    def start_clnull(self, name, qname, attrs):
        self.cl_group = ClassGroupDefault()
        self.cl_group.SetLabel(self.encode(attrs.get((None, 'label'), "")))
        self.cl_prop = ClassGroupProperties()

    def end_clnull(self, name, qname):
        self.cl_group.SetProperties(self.cl_prop)
        self.aLayer.GetClassification().SetDefaultGroup(self.cl_group)
        del self.cl_group, self.cl_prop

    def start_clpoint(self, name, qname, attrs):
        attrib_value = attrs.get((None, 'value'), "0")

        field = self.aLayer.GetClassificationColumn()
        if self.aLayer.GetFieldType(field) == FIELDTYPE_STRING:
            value = self.encode(attrib_value)
        else:
            value = self.conv(attrib_value)
        self.cl_group = ClassGroupSingleton(value)
        self.cl_group.SetLabel(self.encode(attrs.get((None, 'label'), "")))
        self.cl_prop = ClassGroupProperties()


    def end_clpoint(self, name, qname):
        self.cl_group.SetProperties(self.cl_prop)
        self.aLayer.GetClassification().AppendGroup(self.cl_group)
        del self.cl_group, self.cl_prop

    def start_clrange(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("range", False, None),
                                  AttrDesc("min", False, None),
                                  AttrDesc("max", False, None)])

        range = attrs['range']
        # for backward compatibility (min/max are not saved)
        min   = attrs['min']
        max   = attrs['max']

        try:
            if range is not None:
                self.cl_group = ClassGroupRange(Range(range))
            elif min is not None and max is not None:
                self.cl_group = ClassGroupRange((self.conv(min), 
                                                 self.conv(max)))
            else:
                self.cl_group = ClassGroupRange(Range(None))

        except ValueError:
            raise ValueError(_("Classification range is not a number!"))

        self.cl_group.SetLabel(attrs.get((None, 'label'), ""))
        self.cl_prop = ClassGroupProperties()


    def end_clrange(self, name, qname):
        self.cl_group.SetProperties(self.cl_prop)
        self.aLayer.GetClassification().AppendGroup(self.cl_group)
        del self.cl_group, self.cl_prop


    def start_clpattern(self, name, qname, attrs):
        pattern = attrs.get((None, 'pattern'), "")

        self.cl_group = ClassGroupPattern(self.encode(pattern))
        self.cl_group.SetLabel(self.encode(attrs.get((None, 'label'), "")))
        self.cl_prop = ClassGroupProperties()

    def end_clpattern(self, name, qname):
        self.cl_group.SetProperties(self.cl_prop)
        self.aLayer.GetClassification().AppendGroup(self.cl_group)
        del self.cl_group, self.cl_prop


    def start_cldata(self, name, qname, attrs):
        self.cl_prop.SetLineColor(
            parse_color(attrs.get((None, 'stroke'), "None")))
        self.cl_prop.SetLineWidth(
            int(attrs.get((None, 'stroke_width'), "0")))
        self.cl_prop.SetSize(int(attrs.get((None, 'size'), "5")))
        self.cl_prop.SetFill(parse_color(attrs.get((None, 'fill'), "None")))

    def end_cldata(self, name, qname):
        pass

    def start_labellayer(self, name, qname, attrs):
        self.aLayer = self.aMap.LabelLayer()

    def start_label(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("x", True, conversion = float),
                                  AttrDesc("y", True, conversion = float),
                                  AttrDesc("text", True),
                                  AttrDesc("halign", True,
                                           conversion = "ascii"),
                                  AttrDesc("valign", True,
                                           conversion = "ascii")])
        x = attrs['x']
        y = attrs['y']
        text = attrs['text']
        halign = attrs['halign']
        valign = attrs['valign']
        if halign not in ("left", "center", "right"):
            raise LoadError("Unsupported halign value %r" % halign)
        if valign not in ("top", "center", "bottom"):
            raise LoadError("Unsupported valign value %r" % valign)
        self.aLayer.AddLabel(x, y, text, halign = halign, valign = valign)

    def characters(self, chars):
        pass


def load_session(filename, db_connection_callback = None, 
                           shapefile_callback = None):
    """Load a Thuban session from the file object file

    The db_connection_callback, if given should be a callable object
    that can be called like this:
       db_connection_callback(params, message)

    where params is a dictionary containing the known connection
    parameters and message is a string with a message why the connection
    failed. db_connection_callback should return a new dictionary with
    corrected and perhaps additional parameters like a password or None
    to indicate that the user cancelled.
    """
    handler = SessionLoader(db_connection_callback, shapefile_callback)
    handler.read(filename)

    session = handler.theSession
    # Newly loaded session aren't modified
    session.UnsetModified()

    handler.Destroy()

    return session