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

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

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

revision 1558 by bh, Thu Aug 7 17:31:54 2003 UTC revision 2710 by dpinte, Tue Oct 10 08:31:44 2006 UTC
# Line 1  Line 1 
1  # Copyright (c) 2001, 2002, 2003 by Intevation GmbH  # Copyright (c) 2001, 2002, 2003, 2004, 2005 by Intevation GmbH
2  # Authors:  # Authors:
3  # Bernhard Herzog <[email protected]>  # Bernhard Herzog <[email protected]>
4  # Jonathan Coles <[email protected]>  # Jonathan Coles <[email protected]>
5    # Silke Reimer <[email protected]>
6  #  #
7  # This program is free software under the GPL (>=v2)  # This program is free software under the GPL (>=v2)
8  # Read the file COPYING coming with Thuban for details.  # Read the file COPYING coming with Thuban for details.
9    
10  __version__ = "$Revision$"  __version__ = "$Revision$"
11    
12    import os
13  import warnings  import warnings
14    
15    from wxproj import point_in_polygon_shape, shape_centroid
16    
17  from Thuban import _  from Thuban import _
18    
19  from messages import LAYER_PROJECTION_CHANGED, LAYER_VISIBILITY_CHANGED, \  from messages import LAYER_PROJECTION_CHANGED, LAYER_VISIBILITY_CHANGED, \
# Line 20  import classification Line 24  import classification
24  from color import Transparent, Black  from color import Transparent, Black
25  from base import TitledObject, Modifiable  from base import TitledObject, Modifiable
26  from data import SHAPETYPE_POLYGON, SHAPETYPE_ARC, SHAPETYPE_POINT  from data import SHAPETYPE_POLYGON, SHAPETYPE_ARC, SHAPETYPE_POINT
27    from label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \
28         ALIGN_LEFT, ALIGN_RIGHT
29    
30  import resource  import resource
31    
32    from color import Color
33    
34  shapetype_names = {SHAPETYPE_POINT: "Point",  shapetype_names = {SHAPETYPE_POINT: "Point",
35                     SHAPETYPE_ARC: "Arc",                     SHAPETYPE_ARC: "Arc",
# Line 53  class BaseLayer(TitledObject, Modifiable Line 60  class BaseLayer(TitledObject, Modifiable
60          self.issue(LAYER_VISIBILITY_CHANGED, self)          self.issue(LAYER_VISIBILITY_CHANGED, self)
61    
62      def HasClassification(self):      def HasClassification(self):
63          """Determine if this layer support classifications."""          """Determine if this layer supports classifications."""
64          return False          return False
65    
66      def HasShapes(self):      def HasShapes(self):
# Line 65  class BaseLayer(TitledObject, Modifiable Line 72  class BaseLayer(TitledObject, Modifiable
72          return self.projection          return self.projection
73    
74      def SetProjection(self, projection):      def SetProjection(self, projection):
75          """Set the layer's projection"""          """Set the layer's projection."""
76          self.projection = projection          self.projection = projection
77          self.changed(LAYER_PROJECTION_CHANGED, self)          self.changed(LAYER_PROJECTION_CHANGED, self)
78    
79        def Type(self):
80            return "Unknown"
81    
82  class Layer(BaseLayer):  class Layer(BaseLayer):
83    
84      """Represent the information of one geodata file (currently a shapefile)      """Represent the information of one geodata file (currently a shapefile)
# Line 124  class Layer(BaseLayer): Line 134  class Layer(BaseLayer):
134    
135          self.UnsetModified()          self.UnsetModified()
136    
     def __getattr__(self, attr):  
         """Access to some attributes for backwards compatibility  
   
         The attributes implemented here are now held by the shapestore  
         if at all. For backwards compatibility pretend that they are  
         still there but issue a DeprecationWarning when they are  
         accessed.  
         """  
         if attr in ("table", "shapetable"):  
             value = self.store.Table()  
         elif attr == "shapefile":  
             value = self.store.Shapefile()  
         elif attr == "filename":  
             value = self.store.FileName()  
         else:  
             raise AttributeError, attr  
         warnings.warn("The Layer attribute %r is deprecated."  
                       " It's value can be accessed through the shapestore"  
                       % attr, DeprecationWarning, stacklevel = 2)  
         return value  
   
137      def SetShapeStore(self, store):      def SetShapeStore(self, store):
138          # Set the classification to None if there is a classification          # Set the classification to None if there is a classification
139          # and the new shapestore doesn't have a table with a suitable          # and the new shapestore doesn't have a table with a suitable
# Line 186  class Layer(BaseLayer): Line 175  class Layer(BaseLayer):
175          Return None, if the layer doesn't contain any shapes.          Return None, if the layer doesn't contain any shapes.
176          """          """
177          bbox = self.BoundingBox()          bbox = self.BoundingBox()
178          if bbox is not None:          if bbox is not None and self.projection is not None:
179              llx, lly, urx, ury = bbox              bbox = self.projection.InverseBBox(bbox)
180              if self.projection is not None:          return bbox
181                  llx, lly = self.projection.Inverse(llx, lly)  
182                  urx, ury = self.projection.Inverse(urx, ury)      def Type(self):
183              return llx, lly, urx, ury          return self.ShapeType();
         else:  
             return None  
184    
185      def ShapesBoundingBox(self, shapes):      def ShapesBoundingBox(self, shapes):
186          """Return a bounding box in lat/long coordinates for the given          """Return a bounding box in lat/long coordinates for the given
# Line 204  class Layer(BaseLayer): Line 191  class Layer(BaseLayer):
191    
192          if shapes is None or len(shapes) == 0: return None          if shapes is None or len(shapes) == 0: return None
193    
194          llx = []          xs = []
195          lly = []          ys = []
         urx = []  
         ury = []  
   
         if self.projection is not None:  
             inverse = lambda x, y: self.projection.Inverse(x, y)  
         else:  
             inverse = lambda x, y: (x, y)  
196    
197          for id in shapes:          for id in shapes:
198              left, bottom, right, top = self.Shape(id).compute_bbox()              bbox = self.Shape(id).compute_bbox()
199                if self.projection is not None:
200              left, bottom = inverse(left, bottom)                  bbox = self.projection.InverseBBox(bbox)
201              right, top   = inverse(right, top)              left, bottom, right, top = bbox
202                xs.append(left); xs.append(right)
203                ys.append(bottom); ys.append(top)
204    
205              llx.append(left)          return (min(xs), min(ys), max(xs), max(ys))
             lly.append(bottom)  
             urx.append(right)  
             ury.append(top)  
206    
         return (min(llx), min(lly), max(urx), max(ury))  
207    
208      def GetFieldType(self, fieldName):      def GetFieldType(self, fieldName):
209          if self.store:          if self.store:
# Line 253  class Layer(BaseLayer): Line 231  class Layer(BaseLayer):
231          """Return the shape with index index"""          """Return the shape with index index"""
232          return self.store.Shape(index)          return self.store.Shape(index)
233    
234      def ShapesInRegion(self, box):      def ShapesInRegion(self, bbox):
235          """Return the ids of the shapes that overlap the box.          """Return an iterable over the shapes that overlap the bounding box.
236    
237          Box is a tuple (left, bottom, right, top) in unprojected coordinates.          The bbox parameter should be the bounding box as a tuple in the
238            form (minx, miny, maxx, maxy) in unprojected coordinates.
239          """          """
         left, bottom, right, top = box  
   
240          if self.projection is not None:          if self.projection is not None:
241              left,  bottom = self.projection.Forward(left, bottom)              # Ensure that region lies within the layer's bounding box
242              right, top    = self.projection.Forward(right, top)              # Otherwise projection of the region would lead to incorrect
243                # values.
244          return self.store.ShapesInRegion((left, bottom, right, top))              clipbbox = self.__mangle_bounding_box(bbox)
245                bbox = self.projection.ForwardBBox(clipbbox)
246            return self.store.ShapesInRegion(bbox)
247    
248      def GetClassificationColumn(self):      def GetClassificationColumn(self):
249          return self.classification_column          return self.classification_column
# Line 326  class Layer(BaseLayer): Line 305  class Layer(BaseLayer):
305    
306          bbox = self.LatLongBoundingBox()          bbox = self.LatLongBoundingBox()
307          if bbox is not None:          if bbox is not None:
308              items.append(_("Extent (lat-lon): (%g, %g, %g, %g)") % bbox)              items.append(_("Extent (lat-lon): (%g, %g, %g, %g)") % tuple(bbox))
309          else:          else:
310              items.append(_("Extent (lat-lon):"))              items.append(_("Extent (lat-lon):"))
311          items.append(_("Shapetype: %s") % shapetype_names[self.ShapeType()])          items.append(_("Shapetype: %s") % shapetype_names[self.ShapeType()])
# Line 339  class Layer(BaseLayer): Line 318  class Layer(BaseLayer):
318    
319          return (_("Layer '%s'") % self.Title(), items)          return (_("Layer '%s'") % self.Title(), items)
320    
321        def __mangle_bounding_box(self, bbox):
322            # FIXME: This method doesn't make much sense.
323            # See RT #2845 which effectively says:
324            #
325            # If this method, which was originally called ClipBoundingBox,
326            # is supposed to do clipping it shouldn't return the parameter
327            # unchanged when it lies completely outside of the bounding box.
328            # It would be better to return None and return an empty list in
329            # ShapesInRegion (the only caller) in that case.
330            #
331            # This method was introduced to fix a bug that IIRC had
332            # something todo with projections and bounding boxes containing
333            # NaN or INF when the parameter to ShapesInRegion covered the
334            # entire earth or something similarly large).
335            bminx, bminy, bmaxx, bmaxy = bbox
336            lminx, lminy, lmaxx, lmaxy = self.LatLongBoundingBox()
337            if bminx > lmaxx or bmaxx < lminx:
338                left, right = bminx, bmaxx
339            else:
340                left = max(lminx, bminx)
341                right = min(lmaxx, bmaxx)
342            if bminy > lmaxy or bmaxy < lminy:
343                bottom, top = bminy, bmaxy
344            else:
345                bottom = max(lminy, bminy)
346                top = min(lmaxy, bmaxy)
347    
348            return (left, bottom, right, top)
349    
350        def GetLabelPosFromShape(self, cmap, shape_index):
351            '''
352            Return the label position parameters (x, y, halign, valign) from the
353            shape object
354            '''
355            proj = cmap.projection
356            if proj is not None:
357                map_proj = proj
358            else:
359                map_proj = None
360            proj = self.projection
361            if proj is not None:
362                layer_proj = proj
363            else:
364                layer_proj = None
365    
366            shapetype = self.ShapeType()
367            if shapetype == SHAPETYPE_POLYGON:
368                shapefile = self.ShapeStore().Shapefile().cobject()
369                x, y = shape_centroid(shapefile, shape_index,
370                                      map_proj, layer_proj, 1, 1, 0, 0)
371                if map_proj is not None:
372                    x, y = map_proj.Inverse(x, y)
373            else:
374                shape = self.Shape(shape_index)
375                if shapetype == SHAPETYPE_POINT:
376                    x, y = shape.Points()[0][0]
377                else:
378                    # assume SHAPETYPE_ARC
379                    points = shape.Points()[0]
380                    x, y = points[len(points) / 2]
381                if layer_proj is not None:
382                    x, y = layer_proj.Inverse(x, y)
383            if shapetype == SHAPETYPE_POINT:
384                halign = ALIGN_LEFT
385                valign = ALIGN_CENTER
386            elif shapetype == SHAPETYPE_POLYGON:
387                halign = ALIGN_CENTER
388                valign = ALIGN_CENTER
389            elif shapetype == SHAPETYPE_ARC:
390                halign = ALIGN_LEFT
391                valign = ALIGN_CENTER
392            
393            return (x, y, halign, valign)
394    
395    
396    
397  if resource.has_gdal_support():  if resource.has_gdal_support():
398      import gdal      import gdal
# Line 346  if resource.has_gdal_support(): Line 400  if resource.has_gdal_support():
400    
401  class RasterLayer(BaseLayer):  class RasterLayer(BaseLayer):
402    
403      def __init__(self, title, filename, projection = None, visible = True):      MASK_NONE  = 0
404        MASK_BIT   = 1
405        MASK_ALPHA = 2
406    
407        def __init__(self, title, filename, projection = None,
408                     visible = True, opacity = 1, masktype = MASK_BIT):
409          """Initialize the Raster Layer.          """Initialize the Raster Layer.
410    
411          title -- title for the layer.          title -- title for the layer.
# Line 365  class RasterLayer(BaseLayer): Line 424  class RasterLayer(BaseLayer):
424          BaseLayer.__init__(self, title, visible = visible)          BaseLayer.__init__(self, title, visible = visible)
425    
426          self.projection = projection          self.projection = projection
427          self.filename = filename          self.filename = os.path.abspath(filename)
428    
429          self.bbox = -1          self.bbox = -1
430    
431            self.mask_type = masktype
432            self.opacity = opacity
433    
434            self.image_info = None
435    
436          if resource.has_gdal_support():          if resource.has_gdal_support():
437              #              #
438              # temporarily open the file so that GDAL can test if it's valid.              # temporarily open the file so that GDAL can test if it's valid.
# Line 378  class RasterLayer(BaseLayer): Line 442  class RasterLayer(BaseLayer):
442              if dataset is None:              if dataset is None:
443                  raise IOError()                  raise IOError()
444    
445                #
446                # while we have the file, extract some basic information
447                # that we can display later
448                #
449                self.image_info = {}
450    
451                self.image_info["nBands"] = dataset.RasterCount
452                self.image_info["Size"] = (dataset.RasterXSize, dataset.RasterYSize)
453                self.image_info["Driver"] = dataset.GetDriver().ShortName
454    
455                # store some information about the individual bands
456                # [min_value, max_value]
457                a = self.image_info["BandData"] = []
458    
459                for i in range(1, dataset.RasterCount+1):
460                    band = dataset.GetRasterBand(i)
461                    a.append(band.ComputeRasterMinMax())
462    
463          self.UnsetModified()          self.UnsetModified()
464    
465      def BoundingBox(self):      def BoundingBox(self):
# Line 427  class RasterLayer(BaseLayer): Line 509  class RasterLayer(BaseLayer):
509          if bbox is None:          if bbox is None:
510              return None              return None
511    
         llx, lly, urx, ury = bbox  
512          if self.projection is not None:          if self.projection is not None:
513              llx, lly = self.projection.Inverse(llx, lly)              bbox = self.projection.InverseBBox(bbox)
514              urx, ury = self.projection.Inverse(urx, ury)  
515            return bbox
516    
517          return llx, lly, urx, ury      def Type(self):
518            return "Image"
519    
520      def GetImageFilename(self):      def GetImageFilename(self):
521          return self.filename          return self.filename
522    
523        def MaskType(self):
524            """Return True if the mask should be used when rendering the layer."""
525            return self.mask_type
526    
527        def SetMaskType(self, type):
528            """Set the type of mask to use.
529    
530            type can be one of MASK_NONE, MASK_BIT, MASK_ALPHA
531    
532            If the state changes, a LAYER_CHANGED message is sent.
533            """
534            if type not in (self.MASK_NONE, self.MASK_BIT, self.MASK_ALPHA):
535                raise ValueError("type is invalid")
536    
537            if type != self.mask_type:
538                self.mask_type = type
539                self.changed(LAYER_CHANGED, self)
540    
541        def Opacity(self):
542            """Return the level of opacity used in alpha blending.
543            """
544            return self.opacity
545    
546        def SetOpacity(self, op):
547            """Set the level of alpha opacity.
548    
549            0 <= op <= 1.
550    
551            The layer is fully opaque when op = 1.
552            """
553            if not (0 <= op <= 1):
554                raise ValueError("op out of range")
555    
556            if op != self.opacity:
557                self.opacity = op
558                self.changed(LAYER_CHANGED, self)
559    
560        def ImageInfo(self):
561            return self.image_info
562    
563      def TreeInfo(self):      def TreeInfo(self):
564          items = []          items = []
565    

Legend:
Removed from v.1558  
changed lines
  Added in v.2710

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26