/[thuban]/trunk/thuban/Thuban/Model/layer.py
ViewVC logotype

Diff of /trunk/thuban/Thuban/Model/layer.py

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

revision 828 by jonathan, Tue May 6 12:06:12 2003 UTC revision 1338 by jonathan, Tue Jul 1 16:10:00 2003 UTC
# Line 9  Line 9 
9  __version__ = "$Revision$"  __version__ = "$Revision$"
10    
11  from math import log, ceil  from math import log, ceil
12    import warnings
13    
14  from Thuban import _  from Thuban import _
   
15  import shapelib, shptree  import shapelib, shptree
16    
17  from messages import LAYER_PROJECTION_CHANGED, LAYER_VISIBILITY_CHANGED, \  from messages import LAYER_PROJECTION_CHANGED, LAYER_VISIBILITY_CHANGED, \
18       LAYER_CHANGED       LAYER_CHANGED, LAYER_SHAPESTORE_REPLACED
   
 from color import Color  
19    
20  import classification  import classification
21    
22    from color import Transparent, Black
23  from base import TitledObject, Modifiable  from base import TitledObject, Modifiable
24    
25    import resource
26    
27    
28  class Shape:  class Shape:
29    
# Line 74  class BaseLayer(TitledObject, Modifiable Line 75  class BaseLayer(TitledObject, Modifiable
75    
76      """Base class for the layers."""      """Base class for the layers."""
77    
78      def __init__(self, title, visible = True):      def __init__(self, title, visible = True, projection = None):
79          """Initialize the layer.          """Initialize the layer.
80    
81          title -- the title          title -- the title
# Line 83  class BaseLayer(TitledObject, Modifiable Line 84  class BaseLayer(TitledObject, Modifiable
84          TitledObject.__init__(self, title)          TitledObject.__init__(self, title)
85          Modifiable.__init__(self)          Modifiable.__init__(self)
86          self.visible = visible          self.visible = visible
87            self.projection = projection
88    
89      def Visible(self):      def Visible(self):
90          """Return true if layer is visible"""          """Return true if layer is visible"""
# Line 93  class BaseLayer(TitledObject, Modifiable Line 95  class BaseLayer(TitledObject, Modifiable
95          self.visible = visible          self.visible = visible
96          self.issue(LAYER_VISIBILITY_CHANGED, self)          self.issue(LAYER_VISIBILITY_CHANGED, self)
97    
98        def HasClassification(self):
99            """Determine if this layer support classifications."""
100            return False
101    
102        def HasShapes(self):
103            """Determine if this layer supports shapes."""
104            return False
105    
106        def GetProjection(self):
107            """Return the layer's projection."""
108            return self.projection
109    
110        def SetProjection(self, projection):
111            """Set the layer's projection"""
112            self.projection = projection
113            self.changed(LAYER_PROJECTION_CHANGED, self)
114    
115  class Layer(BaseLayer):  class Layer(BaseLayer):
116    
# Line 101  class Layer(BaseLayer): Line 119  class Layer(BaseLayer):
119      All children of the layer have the same type.      All children of the layer have the same type.
120    
121      A layer has fill and stroke colors. Colors should be instances of      A layer has fill and stroke colors. Colors should be instances of
122      Color. They can also be None, indicating no fill or no stroke.      Color. They can also be Transparent, indicating no fill or no stroke.
123    
124      The layer objects send the following events, all of which have the      The layer objects send the following events, all of which have the
125      layer object as parameter:      layer object as parameter:
# Line 111  class Layer(BaseLayer): Line 129  class Layer(BaseLayer):
129      """      """
130    
131      def __init__(self, title, data, projection = None,      def __init__(self, title, data, projection = None,
132                   fill = Color.Transparent,                   fill = Transparent,
133                   stroke = Color.Black,                   stroke = Black,
134                   lineWidth = 1,                   lineWidth = 1,
135                   visible = True):                   visible = True):
136          """Initialize the layer.          """Initialize the layer.
# Line 122  class Layer(BaseLayer): Line 140  class Layer(BaseLayer):
140          projection -- the projection object. Its Inverse method is          projection -- the projection object. Its Inverse method is
141                 assumed to map the layer's coordinates to lat/long                 assumed to map the layer's coordinates to lat/long
142                 coordinates                 coordinates
143          fill -- the fill color or Color.Transparent if the shapes are          fill -- the fill color or Transparent if the shapes are
144                  not filled                  not filled
145          stroke -- the stroke color or Color.Transparent if the shapes          stroke -- the stroke color or Transparent if the shapes
146                  are not stroked                  are not stroked
147          visible -- boolean. If true the layer is visible.          visible -- boolean. If true the layer is visible.
148    
149          colors are expected to be instances of Color class          colors are expected to be instances of Color class
150          """          """
151          BaseLayer.__init__(self, title, visible = visible)          BaseLayer.__init__(self, title,
152                                     visible = visible,
153          self.projection = projection                                   projection = projection)
154    
155          #          #
156          # this is really important so that when the classification class          # this is really important so that when the classification class
157          # tries to set its parent layer the variable will exist          # tries to set its parent layer the variable will exist
158          #          #
159          self.__classification = None          self.__classification = None
         self.__setClassLock = False  
160    
161          self.SetShapeStore(data)          self.SetShapeStore(data)
162    
# Line 148  class Layer(BaseLayer): Line 165  class Layer(BaseLayer):
165          self.__classification.SetDefaultLineColor(stroke)          self.__classification.SetDefaultLineColor(stroke)
166          self.__classification.SetDefaultLineWidth(lineWidth)          self.__classification.SetDefaultLineWidth(lineWidth)
167          self.__classification.SetDefaultFill(fill)          self.__classification.SetDefaultFill(fill)
         self.__classification.SetLayer(self)  
168    
169          self.UnsetModified()          self.UnsetModified()
170    
171        def __getattr__(self, attr):
172            """Access to some attributes for backwards compatibility
173    
174            The attributes implemented here are now held by the shapestore
175            if at all. For backwards compatibility pretend that they are
176            still there but issue a DeprecationWarning when they are
177            accessed.
178            """
179            if attr in ("table", "shapetable"):
180                value = self.store.Table()
181            elif attr == "shapefile":
182                value = self.store.Shapefile()
183            elif attr == "filename":
184                value = self.store.FileName()
185            else:
186                raise AttributeError, attr
187            warnings.warn("The Layer attribute %r is deprecated."
188                          " It's value can be accessed through the shapestore"
189                          % attr, DeprecationWarning, stacklevel = 2)
190            return value
191    
192      def SetShapeStore(self, store):      def SetShapeStore(self, store):
193          self.store = store          self.store = store
194          self.shapefile = self.store.Shapefile()          shapefile = self.store.Shapefile()
         self.shapetable = self.store.Table()  
         self.filename = self.store.filename  
         self.table = self.shapetable  
195    
196          numshapes, shapetype, mins, maxs = self.shapefile.info()          numshapes, shapetype, mins, maxs = shapefile.info()
197          self.numshapes = numshapes          self.numshapes = numshapes
198          self.shapetype = shapelib_shapetypes[shapetype]          self.shapetype = shapelib_shapetypes[shapetype]
199    
# Line 180  class Layer(BaseLayer): Line 213  class Layer(BaseLayer):
213          else:          else:
214              maxdepth = int(ceil(log(self.numshapes / 4.0) / log(4)))              maxdepth = int(ceil(log(self.numshapes / 4.0) / log(4)))
215    
216          self.shapetree = shptree.SHPTree(self.shapefile.cobject(), 2,          self.shapetree = shptree.SHPTree(shapefile.cobject(), 2,
217                                           maxdepth)                                           maxdepth)
218            # Set the classification to None if there is a classification
219            # and the new shapestore doesn't have a table with a suitable
220            # column, i.e one with the same name and type as before
221            # FIXME: Maybe we should keep it the same if the type is
222            # compatible enough such as FIELDTYPE_DOUBLE and FIELDTYPE_INT
223          if self.__classification is not None:          if self.__classification is not None:
224              fieldname = self.__classification.GetField()              fieldname = self.__classification.GetField()
225              if fieldname is not None and \              fieldtype = self.__classification.GetFieldType()
226                 not self.store.Table().field_info_by_name(fieldname):              table = self.store.Table()
227                if (fieldname is not None
228                    and (not table.HasColumn(fieldname)
229                         or table.Column(fieldname).type != fieldtype)):
230                  self.SetClassification(None)                  self.SetClassification(None)
231          self.changed(LAYER_CHANGED, self)          self.changed(LAYER_SHAPESTORE_REPLACED, self)
232    
233      def ShapeStore(self):      def ShapeStore(self):
234          return self.store          return self.store
235    
236      def Destroy(self):      def Destroy(self):
237          BaseLayer.Destroy(self)          BaseLayer.Destroy(self)
238          self.SetClassification(None)          self.GetClassification()._set_layer(None)
239    
240      def BoundingBox(self):      def BoundingBox(self):
241          """Return the layer's bounding box in the intrinsic coordinate system.          """Return the layer's bounding box in the intrinsic coordinate system.
# Line 251  class Layer(BaseLayer): Line 292  class Layer(BaseLayer):
292          return (min(llx), min(lly), max(urx), max(ury))          return (min(llx), min(lly), max(urx), max(ury))
293    
294      def GetFieldType(self, fieldName):      def GetFieldType(self, fieldName):
295          info = self.table.field_info_by_name(fieldName)          table = self.store.Table()
296          if info is not None:          if table.HasColumn(fieldName):
297              return info[0]              return table.Column(fieldName).type
298          else:          return None
299              return None  
300        def HasShapes(self):
301            return True
302    
303      def NumShapes(self):      def NumShapes(self):
304          """Return the number of shapes in the layer"""          """Return the number of shapes in the layer"""
# Line 269  class Layer(BaseLayer): Line 312  class Layer(BaseLayer):
312    
313      def Shape(self, index):      def Shape(self, index):
314          """Return the shape with index index"""          """Return the shape with index index"""
315          shape = self.shapefile.read_object(index)          shape = self.store.Shapefile().read_object(index)
316    
317          if self.shapetype == SHAPETYPE_POINT:          if self.shapetype == SHAPETYPE_POINT:
318              points = shape.vertices()              points = shape.vertices()
# Line 295  class Layer(BaseLayer): Line 338  class Layer(BaseLayer):
338    
339          return self.shapetree.find_shapes((left, bottom), (right, top))          return self.shapetree.find_shapes((left, bottom), (right, top))
340    
341      def GetProjection(self):      def HasClassification(self):
342          return self.projection          return True
   
     def SetProjection(self, projection):  
         """Set the layer's projection"""  
         self.projection = projection  
         self.changed(LAYER_PROJECTION_CHANGED, self)  
343    
344      def GetClassification(self):      def GetClassification(self):
345          return self.__classification          return self.__classification
346    
347      def SetClassification(self, clazz):      def SetClassification(self, clazz):
348          """Set the classification to 'clazz'          """Set the classification used by this layer to 'clazz'
349    
350          If 'clazz' is None a default classification is created          If 'clazz' is None a default classification is created.
         """  
351    
352          # prevent infinite recursion when calling SetLayer()          ValueError is raised if the classification's field name
353          if self.__setClassLock: return          and type are different (if they aren't None) than what
354            is in the shapestore. The Layer will not be changed in
355            this case.
356            """
357    
358          self.__setClassLock = True          old_class = self.__classification
359    
360          if clazz is None:          if clazz is None:
361              if self.__classification is not None:              clazz = classification.Classification()
                 self.__classification.SetLayer(None)  
             self.__classification = classification.Classification()  
         else:  
             self.__classification = clazz  
             try:  
                 self.__classification.SetLayer(self)  
             except ValueError:  
                 self.__setClassLock = False  
                 raise ValueError  
362    
363          self.changed(LAYER_CHANGED, self)          try:
364                clazz._set_layer(self)
365    
366                # only change things after a successful call
367                if old_class is not None:
368                    old_class._set_layer(None)
369                self.__classification = clazz
370            except ValueError:
371                raise ValueError
372    
373          self.__setClassLock = False          # we don't need this since a message will be sent
374            # after calling _set_layer()
375            #self.changed(LAYER_CHANGED, self)
376    
377      def ClassChanged(self):      def ClassChanged(self):
378          """Called from the classification object when it has changed."""          """Called from the classification object when it has changed."""
# Line 340  class Layer(BaseLayer): Line 381  class Layer(BaseLayer):
381      def TreeInfo(self):      def TreeInfo(self):
382          items = []          items = []
383    
384            items.append(_("Filename: %s") % self.ShapeStore().FileName())
385    
386          if self.Visible():          if self.Visible():
387              items.append(_("Shown"))              items.append(_("Shown"))
388          else:          else:
# Line 362  class Layer(BaseLayer): Line 405  class Layer(BaseLayer):
405          return (_("Layer '%s'") % self.Title(), items)          return (_("Layer '%s'") % self.Title(), items)
406    
407    
408    if resource.has_gdal_support():
409        import gdal
410        from gdalconst import GA_ReadOnly
411    
412    class RasterLayer(BaseLayer):
413    
414        def __init__(self, title, filename, projection = None, visible = True):
415            """Initialize the Raster Layer.
416    
417            title -- title for the layer.
418    
419            filename -- file name of the source image.
420    
421            projection -- Projection object describing the projection which
422                          the source image is in.
423    
424            visible -- True is the layer should initially be visible.
425    
426            Throws IOError if the filename is invalid or points to a file that
427            is not in a format GDAL can use.
428            """
429    
430            BaseLayer.__init__(self, title, visible = visible)
431    
432            self.projection = projection
433            self.filename = filename
434    
435            self.bbox = -1
436    
437            if resource.has_gdal_support():
438                #
439                # temporarily open the file so that GDAL can test if it's valid.
440                #
441                dataset = gdal.Open(self.filename, GA_ReadOnly)
442    
443                if dataset is None:
444                    raise IOError()
445    
446            self.UnsetModified()
447    
448        def BoundingBox(self):
449            """Return the layer's bounding box in the intrinsic coordinate system.
450    
451            If the there is no support for images, or the file cannot
452            be read, or there is no geographics information available, return None.
453            """
454            if not resource.has_gdal_support():
455                return None
456    
457            if self.bbox == -1:
458                dataset = gdal.Open(self.filename, GA_ReadOnly)
459                if dataset is None:
460                    self.bbox = None
461                else:
462                    geotransform = dataset.GetGeoTransform()
463                    if geotransform is None:
464                        return None
465    
466                    x = 0
467                    y = dataset.RasterYSize
468                    left = geotransform[0] +        \
469                           geotransform[1] * x +    \
470                           geotransform[2] * y
471    
472                    bottom = geotransform[3] +      \
473                             geotransform[4] * x +  \
474                             geotransform[5] * y
475    
476                    x = dataset.RasterXSize
477                    y = 0
478                    right = geotransform[0] +       \
479                            geotransform[1] * x +   \
480                            geotransform[2] * y
481    
482                    top = geotransform[3] +         \
483                          geotransform[4] * x +     \
484                          geotransform[5] * y
485    
486                    self.bbox = (left, bottom, right, top)
487    
488            return self.bbox
489    
490        def LatLongBoundingBox(self):
491            bbox = self.BoundingBox()
492            if bbox is None:
493                return None
494    
495            llx, lly, urx, ury = bbox
496            if self.projection is not None:
497                llx, lly = self.projection.Inverse(llx, lly)
498                urx, ury = self.projection.Inverse(urx, ury)
499    
500            return llx, lly, urx, ury
501    
502        def GetImageFilename(self):
503            return self.filename
504    
505        def TreeInfo(self):
506            items = []
507    
508            items.append(_("Filename: %s") % self.GetImageFilename())
509    
510            if self.Visible():
511                items.append(_("Shown"))
512            else:
513                items.append(_("Hidden"))
514    
515            bbox = self.LatLongBoundingBox()
516            if bbox is not None:
517                items.append(_("Extent (lat-lon): (%g, %g, %g, %g)") % bbox)
518            else:
519                items.append(_("Extent (lat-lon):"))
520    
521            if self.projection and len(self.projection.params) > 0:
522                items.append((_("Projection"),
523                            [str(param) for param in self.projection.params]))
524    
525            return (_("Layer '%s'") % self.Title(), items)
526    

Legend:
Removed from v.828  
changed lines
  Added in v.1338

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26