/[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 929 by jonathan, Tue May 20 15:22:42 2003 UTC revision 1427 by jonathan, Wed Jul 16 13:22:48 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    
 import gdal  
 from gdalconst import GA_ReadOnly  
   
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, CLASS_CHANGED
   
 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 101  class BaseLayer(TitledObject, Modifiable Line 99  class BaseLayer(TitledObject, Modifiable
99          """Determine if this layer support classifications."""          """Determine if this layer support classifications."""
100          return False          return False
101    
102        def HasShapes(self):
103            """Determine if this layer supports shapes."""
104            return False
105    
106      def GetProjection(self):      def GetProjection(self):
107          """Return the layer's projection."""          """Return the layer's projection."""
108          return self.projection          return self.projection
# Line 117  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 127  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 138  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    
# Line 150  class Layer(BaseLayer): Line 152  class Layer(BaseLayer):
152                                   visible = visible,                                   visible = visible,
153                                   projection = projection)                                   projection = projection)
154    
         #  
         # this is really important so that when the classification class  
         # tries to set its parent layer the variable will exist  
         #  
155          self.__classification = None          self.__classification = None
156          self.__setClassLock = False          self.store = None
157    
158          self.SetShapeStore(data)          self.SetShapeStore(data)
159    
160            self.SetClassificationField(None)
161          self.SetClassification(None)          self.SetClassification(None)
162    
163          self.__classification.SetDefaultLineColor(stroke)          self.__classification.SetDefaultLineColor(stroke)
164          self.__classification.SetDefaultLineWidth(lineWidth)          self.__classification.SetDefaultLineWidth(lineWidth)
165          self.__classification.SetDefaultFill(fill)          self.__classification.SetDefaultFill(fill)
         self.__classification.SetLayer(self)  
166    
167          self.UnsetModified()          self.UnsetModified()
168    
169        def __getattr__(self, attr):
170            """Access to some attributes for backwards compatibility
171    
172            The attributes implemented here are now held by the shapestore
173            if at all. For backwards compatibility pretend that they are
174            still there but issue a DeprecationWarning when they are
175            accessed.
176            """
177            if attr in ("table", "shapetable"):
178                value = self.store.Table()
179            elif attr == "shapefile":
180                value = self.store.Shapefile()
181            elif attr == "filename":
182                value = self.store.FileName()
183            else:
184                raise AttributeError, attr
185            warnings.warn("The Layer attribute %r is deprecated."
186                          " It's value can be accessed through the shapestore"
187                          % attr, DeprecationWarning, stacklevel = 2)
188            return value
189    
190      def SetShapeStore(self, store):      def SetShapeStore(self, store):
191            # Set the classification to None if there is a classification
192            # and the new shapestore doesn't have a table with a suitable
193            # column, i.e one with the same name and type as before
194            # FIXME: Maybe we should keep it the same if the type is
195            # compatible enough such as FIELDTYPE_DOUBLE and FIELDTYPE_INT
196            if self.__classification is not None:
197                fieldname = self.classificationField
198                fieldtype = self.GetFieldType(fieldname)
199                table = store.Table()
200                if (fieldname is not None
201                    and (not table.HasColumn(fieldname)
202                         or table.Column(fieldname).type != fieldtype)):
203                    self.SetClassification(None)
204    
205          self.store = store          self.store = store
206          self.shapefile = self.store.Shapefile()          shapefile = self.store.Shapefile()
         self.shapetable = self.store.Table()  
         self.filename = self.store.filename  
         self.table = self.shapetable  
207    
208          numshapes, shapetype, mins, maxs = self.shapefile.info()          numshapes, shapetype, mins, maxs = shapefile.info()
209          self.numshapes = numshapes          self.numshapes = numshapes
210          self.shapetype = shapelib_shapetypes[shapetype]          self.shapetype = shapelib_shapetypes[shapetype]
211    
# Line 196  class Layer(BaseLayer): Line 225  class Layer(BaseLayer):
225          else:          else:
226              maxdepth = int(ceil(log(self.numshapes / 4.0) / log(4)))              maxdepth = int(ceil(log(self.numshapes / 4.0) / log(4)))
227    
228          self.shapetree = shptree.SHPTree(self.shapefile.cobject(), 2,          self.shapetree = shptree.SHPTree(shapefile.cobject(), 2,
229                                           maxdepth)                                           maxdepth)
230          if self.__classification is not None:          self.changed(LAYER_SHAPESTORE_REPLACED, self)
             fieldname = self.__classification.GetField()  
             if fieldname is not None and \  
                not self.store.Table().HasColumn(fieldname):  
                 self.SetClassification(None)  
         self.changed(LAYER_CHANGED, self)  
231    
232      def ShapeStore(self):      def ShapeStore(self):
233          return self.store          return self.store
234    
235      def Destroy(self):      def Destroy(self):
236          BaseLayer.Destroy(self)          BaseLayer.Destroy(self)
237          self.SetClassification(None)          if self.__classification is not None:
238                self.__classification.Unsubscribe(CLASS_CHANGED, self.ClassChanged)
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 267  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          if self.table.HasColumn(fieldName):          if self.store:
296              return self.table.Column(fieldName).type              table = self.store.Table()
297                if table.HasColumn(fieldName):
298                    return table.Column(fieldName).type
299          return None          return None
300    
301        def HasShapes(self):
302            return True
303    
304      def NumShapes(self):      def NumShapes(self):
305          """Return the number of shapes in the layer"""          """Return the number of shapes in the layer"""
306          return self.numshapes          return self.numshapes
# Line 283  class Layer(BaseLayer): Line 313  class Layer(BaseLayer):
313    
314      def Shape(self, index):      def Shape(self, index):
315          """Return the shape with index index"""          """Return the shape with index index"""
316          shape = self.shapefile.read_object(index)          shape = self.store.Shapefile().read_object(index)
317    
318          if self.shapetype == SHAPETYPE_POINT:          if self.shapetype == SHAPETYPE_POINT:
319              points = shape.vertices()              points = shape.vertices()
# Line 309  class Layer(BaseLayer): Line 339  class Layer(BaseLayer):
339    
340          return self.shapetree.find_shapes((left, bottom), (right, top))          return self.shapetree.find_shapes((left, bottom), (right, top))
341    
342        def GetClassificationField(self):
343            return self.classificationField
344    
345        def SetClassificationField(self, field):
346            """Set the field to classifiy on, or None. If field is not None
347            and the field does not exist in the table, raise a ValueError.
348            """
349            if field:
350                fieldType = self.GetFieldType(field)
351                if fieldType is None:
352                    raise ValueError()
353            self.classificationField = field
354    
355      def HasClassification(self):      def HasClassification(self):
356          return True          return True
357    
# Line 316  class Layer(BaseLayer): Line 359  class Layer(BaseLayer):
359          return self.__classification          return self.__classification
360    
361      def SetClassification(self, clazz):      def SetClassification(self, clazz):
362          """Set the classification to 'clazz'          """Set the classification used by this layer to 'clazz'
363    
364          If 'clazz' is None a default classification is created          If 'clazz' is None a default classification is created.
         """  
365    
366          # prevent infinite recursion when calling SetLayer()          This issues a LAYER_CHANGED event.
367          if self.__setClassLock: return          """
368    
369          self.__setClassLock = True          if self.__classification is not None:
370                self.__classification.Unsubscribe(CLASS_CHANGED, self.ClassChanged)
371    
372          if clazz is None:          if clazz is None:
373              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  
374    
375          self.changed(LAYER_CHANGED, self)          self.__classification = clazz
376            self.__classification.Subscribe(CLASS_CHANGED, self.ClassChanged)
377    
378          self.__setClassLock = False          self.ClassChanged()
379    
380      def ClassChanged(self):      def ClassChanged(self):
381          """Called from the classification object when it has changed."""          """Called from the classification object when it has changed."""
# Line 349  class Layer(BaseLayer): Line 384  class Layer(BaseLayer):
384      def TreeInfo(self):      def TreeInfo(self):
385          items = []          items = []
386    
387            items.append(_("Filename: %s") % self.ShapeStore().FileName())
388    
389          if self.Visible():          if self.Visible():
390              items.append(_("Shown"))              items.append(_("Shown"))
391          else:          else:
# Line 371  class Layer(BaseLayer): Line 408  class Layer(BaseLayer):
408          return (_("Layer '%s'") % self.Title(), items)          return (_("Layer '%s'") % self.Title(), items)
409    
410    
411    if resource.has_gdal_support():
412        import gdal
413        from gdalconst import GA_ReadOnly
414    
415  class RasterLayer(BaseLayer):  class RasterLayer(BaseLayer):
416    
417      def __init__(self, title, filename, projection = None, visible = True):      def __init__(self, title, filename, projection = None, visible = True):
# Line 384  class RasterLayer(BaseLayer): Line 425  class RasterLayer(BaseLayer):
425                        the source image is in.                        the source image is in.
426    
427          visible -- True is the layer should initially be visible.          visible -- True is the layer should initially be visible.
428    
429            Throws IOError if the filename is invalid or points to a file that
430            is not in a format GDAL can use.
431          """          """
432    
433          BaseLayer.__init__(self, title, visible = visible)          BaseLayer.__init__(self, title, visible = visible)
# Line 393  class RasterLayer(BaseLayer): Line 437  class RasterLayer(BaseLayer):
437    
438          self.bbox = -1          self.bbox = -1
439    
440          self.UnsetModified()          if resource.has_gdal_support():
441                #
442                # temporarily open the file so that GDAL can test if it's valid.
443                #
444                dataset = gdal.Open(self.filename, GA_ReadOnly)
445    
446                if dataset is None:
447                    raise IOError()
448    
449            self.UnsetModified()
450    
451      def BoundingBox(self):      def BoundingBox(self):
452          """Return the layer's bounding box in the intrinsic coordinate system.          """Return the layer's bounding box in the intrinsic coordinate system.
453    
454          If the layer has no shapes, return None.          If the there is no support for images, or the file cannot
455            be read, or there is no geographics information available, return None.
456          """          """
457            if not resource.has_gdal_support():
458                return None
459    
460          if self.bbox == -1:          if self.bbox == -1:
461              dataset = gdal.Open(self.filename, GA_ReadOnly)              dataset = gdal.Open(self.filename, GA_ReadOnly)
462              if dataset is None:              if dataset is None:
463                  self.bbox = None                  self.bbox = None
464              else:              else:
465                  left, bottom = self.__CalcCorner(dataset,                  geotransform = dataset.GetGeoTransform()
466                                                   0, dataset.RasterYSize)                  if geotransform is None:
467                  right, top   = self.__CalcCorner(dataset,                      return None
468                                                   dataset.RasterXSize, 0)  
469                    x = 0
470                    y = dataset.RasterYSize
471                    left = geotransform[0] +        \
472                           geotransform[1] * x +    \
473                           geotransform[2] * y
474    
475                    bottom = geotransform[3] +      \
476                             geotransform[4] * x +  \
477                             geotransform[5] * y
478    
479                    x = dataset.RasterXSize
480                    y = 0
481                    right = geotransform[0] +       \
482                            geotransform[1] * x +   \
483                            geotransform[2] * y
484    
485                    top = geotransform[3] +         \
486                          geotransform[4] * x +     \
487                          geotransform[5] * y
488    
489                  self.bbox = (left, bottom, right, top)                  self.bbox = (left, bottom, right, top)
490    
491          return self.bbox          return self.bbox
492    
     def __CalcCorner(self, dataset, x, y):  
         geotransform = dataset.GetGeoTransform()  
         return geotransform[0] + geotransform[1] * x + geotransform[2] * y, \  
                geotransform[3] + geotransform[4] * x + geotransform[5] * y  
   
493      def LatLongBoundingBox(self):      def LatLongBoundingBox(self):
494          bbox = self.BoundingBox()          bbox = self.BoundingBox()
495          if bbox is not None:          if bbox is None:
             llx, lly, urx, ury = bbox  
             if self.projection is not None:  
                 llx, lly = self.projection.Inverse(llx, lly)  
                 urx, ury = self.projection.Inverse(urx, ury)  
             return llx, lly, urx, ury  
         else:  
496              return None              return None
497    
498            llx, lly, urx, ury = bbox
499            if self.projection is not None:
500                llx, lly = self.projection.Inverse(llx, lly)
501                urx, ury = self.projection.Inverse(urx, ury)
502    
503            return llx, lly, urx, ury
504    
505      def GetImageFilename(self):      def GetImageFilename(self):
506          return self.filename          return self.filename
507    
508      def TreeInfo(self):      def TreeInfo(self):
509          items = []          items = []
510    
511            items.append(_("Filename: %s") % self.GetImageFilename())
512    
513          if self.Visible():          if self.Visible():
514              items.append(_("Shown"))              items.append(_("Shown"))
515          else:          else:
516              items.append(_("Hidden"))              items.append(_("Hidden"))
         items.append(_("Shapes: %d") % self.NumShapes())  
517    
518          bbox = self.LatLongBoundingBox()          bbox = self.LatLongBoundingBox()
519          if bbox is not None:          if bbox is not None:

Legend:
Removed from v.929  
changed lines
  Added in v.1427

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26