/[thuban]/branches/WIP-pyshapelib-bramz/Thuban/UI/renderer.py
ViewVC logotype

Diff of /branches/WIP-pyshapelib-bramz/Thuban/UI/renderer.py

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

revision 1298 by jonathan, Tue Jun 24 18:00:26 2003 UTC revision 2712 by bernhard, Sun Oct 15 23:27:05 2006 UTC
# Line 1  Line 1 
1  # Copyright (c) 2001, 2002, 2003 by Intevation GmbH  # Copyright (c) 2001-2006 by Intevation GmbH
2  # Authors:  # Authors:
3  # Bernhard Herzog <[email protected]>  # Bernhard Herzog <[email protected]> (2001-2003)
4  # Jonathan Coles <[email protected]>  # Jonathan Coles <[email protected]> (2003)
5  # Frank Koormann <[email protected]>  # Frank Koormann <[email protected]> (2003)
6    # Jan-Oliver Wagner <[email protected]> (2003-2005)
7  #  #
8  # This program is free software under the GPL (>=v2)  # This program is free software under the GPL (>=v2)
9  # Read the file COPYING coming with Thuban for details.  # Read the file COPYING coming with Thuban for details.
10    
11    from __future__ import generators
12    
13  __version__ = "$Revision$"  __version__ = "$Revision$"
14    # $Source$
15    # $Id$
16    
17  import cStringIO  import cStringIO
18    
19    import array
20    
21    import traceback
22    
23  from Thuban import _  from Thuban import _
24    
25  from wxPython.wx import wxMemoryDC, wxEmptyBitmap, \  import wx
     wxPoint, wxRect, wxPen, wxBrush, wxFont, \  
     wxTRANSPARENT_PEN, wxTRANSPARENT_BRUSH, \  
     wxBLACK_PEN, wxRED_PEN, wxBLACK, \  
     wxSOLID, wxCROSS_HATCH, wxSWISS, wxNORMAL, \  
     wxBitmap, wxImageFromBitmap, wxBitmapFromImage, \  
     wxImageFromStream, wxBITMAP_TYPE_BMP  
26    
27  from wxproj import draw_polygon_shape, draw_polygon_init  from wxproj import draw_polygon_shape, draw_polygon_init
28    
# Line 27  from Thuban.UI.common import Color2wxCol Line 30  from Thuban.UI.common import Color2wxCol
30  from Thuban.UI.classifier import ClassDataPreviewer  from Thuban.UI.classifier import ClassDataPreviewer
31  from Thuban.UI.scalebar import ScaleBar  from Thuban.UI.scalebar import ScaleBar
32    
33  from Thuban.Model.layer import Layer, RasterLayer, \  from Thuban.Model.data import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \
34       SHAPETYPE_POLYGON, SHAPETYPE_ARC, SHAPETYPE_POINT       SHAPETYPE_POINT, RAW_SHAPEFILE
 from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \  
      ALIGN_LEFT, ALIGN_RIGHT, ALIGN_BASELINE  
35    
36  from Thuban.Model.classification import Classification  from Thuban.Model.color import Transparent
 from Thuban.Model.color import Color  
37  import Thuban.Model.resource  import Thuban.Model.resource
38    
39  if Thuban.Model.resource.has_gdal_support():  from baserenderer import BaseRenderer
     from gdalwarp import ProjectRasterFile  
   
 class MapRenderer:  
40    
41      """Class to render a map onto a wxDC"""  from math import floor
   
     honor_visibility = 1  
42    
43      def __init__(self, dc, scale, offset, resolution = 72.0,  from types import StringType
                  honor_visibility = None):  
         """Inititalize the renderer.  
   
         dc -- the wxPython DC to render on  
         scale, offset -- the scale factor and translation to convert  
                 between projected coordinates and the DC coordinates  
   
         resolution -- the assumed resolution of the DC. Used to convert  
                 absolute lengths like font sizes to DC coordinates  
   
         honor_visibility -- boolean. If true, honor the visibility flag  
                 of the layers, otherwise draw all layers. If None, use  
                 the renderer's default.  
         """  
         # resolution in pixel/inch  
   
         self.dc = dc  
         self.scale = scale  
         self.offset = offset  
         if honor_visibility is not None:  
             self.honor_visibility = honor_visibility  
         # store the resolution in pixel/point because it's more useful  
         # later.  
         self.resolution = resolution / 72.0  
   
     def render_map(self, map):  
         self.map = map  
         seenRaster = True  
44    
45          if self.scale == 0:  from Thuban.version import versions
             return  
46    
47          #  if Thuban.Model.resource.has_gdal_support():
48          # This is only a good optimization if there is only one      from gdalwarp import ProjectRasterFile
         # raster layer and the image covers the entire window (as  
         # it currently does). We note if there is a raster layer  
         # and only begin drawing layers once we have drawn it.  
         # That way we avoid drawing layers that won't be seen.  
         #  
         if Thuban.Model.resource.has_gdal_support():  
             for layer in map.Layers():  
                 if isinstance(layer, RasterLayer) and layer.Visible():  
                     seenRaster = False  
                     break  
   
         for layer in map.Layers():  
             # if honor_visibility is true, only draw visible layers,  
             # otherwise draw all layers  
             if not self.honor_visibility or layer.Visible():  
                 if isinstance(layer, Layer) and seenRaster:  
                     self.draw_shape_layer(layer)  
                 elif isinstance(layer, RasterLayer) \  
                     and Thuban.Model.resource.has_gdal_support():  
                     self.draw_raster_layer(layer)  
                     seenRaster = True  
   
         self.draw_label_layer(map.LabelLayer())  
   
     def draw_shape_layer(self, layer):  
         scale = self.scale  
         offx, offy = self.offset  
49    
50          map_proj = self.map.projection  verbose = 0 # whether to talk more on stdout
         layer_proj = layer.projection  
51    
52          shapetype = layer.ShapeType()  # Map the strings used for the format parameter of the draw_raster_data
53    # method to the appropriate wxWindows constants
54    raster_format_map = {
55        "BMP": wx.BITMAP_TYPE_BMP,
56        "JPEG": wx.BITMAP_TYPE_JPEG,
57        "PNG": wx.BITMAP_TYPE_PNG,
58        "TIFF": wx.BITMAP_TYPE_TIF,
59        "GIF": wx.BITMAP_TYPE_GIF,
60        }
61    
62          brush = wxTRANSPARENT_BRUSH  class MapRenderer(BaseRenderer):
         pen   = wxTRANSPARENT_PEN  
63    
64          old_prop = None      """Class to render a map onto a wxDC"""
         old_group = None  
         lc = layer.GetClassification()  
         field = lc.GetField()  
         defaultGroup = lc.GetDefaultGroup()  
65    
66        TRANSPARENT_PEN = wx.TRANSPARENT_PEN
67        TRANSPARENT_BRUSH = wx.TRANSPARENT_BRUSH
68    
69          if shapetype != SHAPETYPE_POINT:      def make_point(self, x, y):
70              polygon_render_param = self.polygon_render_param(layer)          return wx.Point(int(round(x)), int(round(y)))
71    
72          if shapetype == SHAPETYPE_POINT:      def tools_for_property(self, prop):
73              draw_func = lambda i: \          fill = prop.GetFill()
74                     self.draw_point_shape(layer, i)          if fill is Transparent:
75                brush = self.TRANSPARENT_BRUSH
76          else:          else:
77              draw_func = lambda i: \              brush = wx.Brush(Color2wxColour(fill), wx.SOLID)
                    self.draw_polygon_shape(polygon_render_param, i, pen, brush)  
   
         table = layer.ShapeStore().Table()  
         for i in self.layer_ids(layer):  
   
             if field is None:  
                 group = defaultGroup  
             else:  
                 record = table.ReadRowAsDict(i)  
                 assert record is not None  
                 group = lc.FindGroup(record[field])  
   
   
             if not group.IsVisible():  
                 continue  
   
   
             # don't recreate new objects if they are the same as before  
             if group is not old_group:  
                 old_group = group  
   
                 prop = group.GetProperties()  
   
                 if prop != old_prop:  
                     old_prop = prop  
   
                     if shapetype == SHAPETYPE_ARC:  
                         fill = Color.Transparent  
                     else:  
                         fill = prop.GetFill()  
78    
79            stroke = prop.GetLineColor()
80            if stroke is Transparent:
81                pen = self.TRANSPARENT_PEN
82            else:
83                pen = wx.Pen(Color2wxColour(stroke), prop.GetLineWidth(), wx.SOLID)
84            return pen, brush
85    
86                      if fill is Color.Transparent:      def low_level_renderer(self, layer):
87                          brush = wxTRANSPARENT_BRUSH          """Override inherited method to provide more efficient renderers
                     else:  
                         color = Color2wxColour(fill)  
                         brush = wxBrush(color, wxSOLID)  
88    
89                      stroke = prop.GetLineColor()          If the underlying data format is not a shapefile or the layer
90                      stroke_width = prop.GetLineWidth()          contains points shapes, simply use what the inherited method
91                      if stroke is Color.Transparent:          returns.
92                          pen = wxTRANSPARENT_PEN  
93                      else:          Otherwise, i.e. for arc and polygon use the more efficient
94                          color = Color2wxColour(stroke)          wxproj.draw_polygon_shape and its corresponding parameter
95                          pen = wxPen(color, stroke_width, wxSOLID)          created with wxproj.draw_polygon_init.
96            """
97            if (layer.ShapeStore().RawShapeFormat() == RAW_SHAPEFILE
98                and layer.ShapeType() in (SHAPETYPE_ARC, SHAPETYPE_POLYGON)):
99                offx, offy = self.offset
100                x = lambda a, b, c, d: None
101                #return (True, x, None)
102                return (True, draw_polygon_shape,
103                        draw_polygon_init(layer.ShapeStore().Shapefile(),
104                                          self.dc, self.map.projection,
105                                          layer.projection,
106                                          self.scale, -self.scale, offx, offy))
107            else:
108                return BaseRenderer.low_level_renderer(self, layer)
109    
110                      if shapetype == SHAPETYPE_POINT:      def label_font(self):
111                          self.dc.SetBrush(brush)          return wx.Font(int(round(self.resolution * 10)), wx.SWISS, wx.NORMAL,
112                          self.dc.SetPen(pen)                        wx.NORMAL)
113    
114        def projected_raster_layer(self, layer, srcProj, dstProj, extents,
115                                   resolution, dimensions, options):
116            """Returns a raster layer image in projected space
117    
118              draw_func(i)          Based on a given filename.  This method must be implemented in
119            classes derived from BaseRenderer.
120            """
121    
122      def draw_raster_layer(self, layer):          ret = None
         data = None  
         offx, offy = self.offset  
         width, height = self.dc.GetSizeTuple()  
123    
124          inProj = ""          if Thuban.Model.resource.has_gdal_support():
         proj = layer.GetProjection()  
         if proj is not None:  
             for p in proj.GetAllParameters():  
                 inProj += "+" + p + " "  
125    
126          outProj = ""              if versions['wxPython-tuple'] < (2,5,3):
127          proj = self.map.GetProjection()                  options = options | 4  # INVERT_MASK_BITS
128          if proj is not None:                  options = options & ~2 # ALPHA_MASK not supported
129              for p in proj.GetAllParameters():  
130                  outProj += "+" + p + " "              try:
131                    if verbose > 0:
132                        print "doing ProjectRasterFile '%s' -> '%s'" % \
133                                    (srcProj, dstProj)
134                        print "extents:", extents, "resolution:", resolution
135                        print "dimensions:", dimensions, "options:", options
136                    ret = ProjectRasterFile(layer.GetImageFilename(),
137                                            srcProj, dstProj,
138                                            extents, resolution, dimensions,
139                                            options)
140                except (MemoryError, IOError, AttributeError, ValueError):
141                    # Why does this catch AttributeError and ValueError?
142                    # FIXME: The exception should be communicated to the user
143                    # better.
144                    traceback.print_exc()
145    
146            return ret
147    
148        def draw_raster_data(self, x,y, data, format = 'BMP', opacity=1.0):
149    
150            mask = None
151            alpha = None
152            width = data[0]
153            height = data[1]
154            image_data, mask_data, alpha_data = data[2]
155    
156            if versions['wxPython-tuple'] < (2,5,3):
157                alpha_data = None
158    
159            if format == 'RAW':
160                image = wx.EmptyImage(width, height)
161                image.SetData(image_data)
162                if mask_data is not None:
163                    mask = wx.BitmapFromBits(mask_data, width, height, 1)
164                    mask = wx.Mask(mask)
165                elif alpha_data is not None:
166                    # alpha_data is already in the right format
167                    alpha = alpha_data
168    
         xmin = (0 - offx) / self.scale  
         ymin = (offy - height) / self.scale  
         xmax = (width - offx) / self.scale  
         ymax = (offy - 0) / self.scale  
   
         try:  
             data = ProjectRasterFile(  
                 layer.GetImageFilename(),  
                 inProj,  
                 outProj,  
                 (xmin, ymin, xmax, ymax),  
                 "", (width, height))  
         except IOError, (strerr):  
             print strerr  
         except (AttributeError, ValueError):  
             pass  
169          else:          else:
170              if data is not None:              stream = cStringIO.StringIO(image_data)
171                  stream = cStringIO.StringIO(data)              image = wx.ImageFromStream(stream, raster_format_map[format])
                 image = wxImageFromStream(stream, wxBITMAP_TYPE_BMP)  
                 bitmap = wxBitmapFromImage(image)  
                 self.dc.BeginDrawing()  
                 self.dc.DrawBitmap(bitmap, 0, 0)  
                 self.dc.EndDrawing()  
172    
173      def layer_ids(self, layer):              if mask_data is not None:
174          """Return the shape ids of the given layer that have to be drawn.                  stream = cStringIO.StringIO(mask_data)
175                    mask = wx.ImageFromStream(stream, raster_format_map[format])
176                    mask = wx.Mask(wx.BitmapFromImage(mask, 1))
177                elif alpha_data is not None:
178                    stream = cStringIO.StringIO(alpha_data)
179                    alpha = wx.ImageFromStream(stream, raster_format_map[format])
180                    alpha = alpha.GetData() #[:] # XXX: do we need to copy this?
181                elif image.HasAlpha():
182                    alpha = image.GetAlphaData()
183    
184          The default implementation simply returns all ids in the layer.          #
185          Override in derived classes to be more precise.          # scale down the alpha values the opacity level using a string
186          """          # translation table for efficiency.
187          return range(layer.NumShapes())          #
188            if alpha is not None:
189      def polygon_render_param(self, layer):              if opacity == 0:
190          """Return the low-lever render parameter for the layer"""                  return
191          offx, offy = self.offset              elif opacity == 1:
192          return draw_polygon_init(layer.ShapeStore().Shapefile(), self.dc,                  a = alpha
193                                   self.map.projection,              else:
194                                   layer.projection,                  tr = [int(i*opacity) for i in range(256)]
195                                   self.scale, -self.scale,                  table = array.array('B', tr).tostring()
196                                   offx, offy)                  a = alpha.translate(table)
   
     def draw_polygon_shape(self, draw_polygon_info, index, pen, brush):  
         draw_polygon_shape(draw_polygon_info, index, pen, brush)  
   
     def projected_points(self, layer, index):  
         proj = self.map.GetProjection()  
         if proj is not None:  
             forward = proj.Forward  
         else:  
             forward = None  
         proj = layer.GetProjection()  
         if proj is not None:  
             inverse = proj.Inverse  
         else:  
             inverse = None  
         shape = layer.Shape(index)  
         points = []  
         scale = self.scale  
         offx, offy = self.offset  
         for x, y in shape.Points():  
             if inverse:  
                 x, y = inverse(x, y)  
             if forward:  
                 x, y = forward(x, y)  
             points.append(wxPoint(x * scale + offx,  
                                   -y * scale + offy))  
         return points  
   
     def draw_arc_shape(self, layer, index):  
         points = self.projected_points(layer, index)  
         self.dc.DrawLines(points)  
   
     def draw_point_shape(self, layer, index):  
         pp = self.projected_points(layer, index)  
   
         if len(pp) == 0: return # ignore Null Shapes which have no points  
   
         p = pp[0]  
         radius = self.resolution * 5  
         self.dc.DrawEllipse(p.x - radius, p.y - radius, 2*radius, 2*radius)  
197    
198      def draw_label_layer(self, layer):              image.SetAlphaData(a)
         scale = self.scale  
         offx, offy = self.offset  
199    
200          font = wxFont(self.resolution * 10, wxSWISS, wxNORMAL, wxNORMAL)          bitmap = wx.BitmapFromImage(image)
         self.dc.SetFont(font)  
201    
202          map_proj = self.map.projection          if mask is not None:
203          if map_proj is not None:              bitmap.SetMask(mask)
             forward = map_proj.Forward  
         else:  
             forward = None  
204    
205          for label in layer.Labels():          self.dc.DrawBitmap(bitmap, int(round(x)), int(round(y)), True)
             x = label.x  
             y = label.y  
             text = label.text  
             if forward:  
                 x, y = forward(x, y)  
             x = x * scale + offx  
             y = -y * scale + offy  
             width, height = self.dc.GetTextExtent(text)  
             if label.halign == ALIGN_LEFT:  
                 # nothing to be done  
                 pass  
             elif label.halign == ALIGN_RIGHT:  
                 x = x - width  
             elif label.halign == ALIGN_CENTER:  
                 x = x - width/2  
             if label.valign == ALIGN_TOP:  
                 # nothing to be done  
                 pass  
             elif label.valign == ALIGN_BOTTOM:  
                 y = y - height  
             elif label.valign == ALIGN_CENTER:  
                 y = y - height/2  
             self.dc.DrawText(text, x, y)  
206    
207    
208  class ScreenRenderer(MapRenderer):  class ScreenRenderer(MapRenderer):
209    
210      # On the screen we want to see only visible layers by default      # On the screen we want to see only visible layers by default
211      honor_visibility = 1      honor_visibility = 1
212        
213      def RenderMap(self, map, region, selected_layer, selected_shapes):      def RenderMap(self, selected_layer, selected_shapes):
214          """Render the map.          """Render the map.
215    
216          Only the given region (a tuple in window coordinates as returned          Only the given region (a tuple in window coordinates as returned
# Line 334  class ScreenRenderer(MapRenderer): Line 218  class ScreenRenderer(MapRenderer):
218          shapes given by the ids in selected_shapes in the          shapes given by the ids in selected_shapes in the
219          selected_layer.          selected_layer.
220          """          """
         self.update_region = region  
221          self.selected_layer = selected_layer          self.selected_layer = selected_layer
222          self.selected_shapes = selected_shapes          self.selected_shapes = selected_shapes
223          self.render_map(map)          self.render_map()
224    
225      def draw_shape_layer(self, layer):      def RenderMapIncrementally(self):
226          MapRenderer.draw_shape_layer(self, layer)          """Render the map.
227          if layer is self.selected_layer and self.selected_shapes:  
228              pen = wxPen(wxBLACK, 3, wxSOLID)          Only the given region (a tuple in window coordinates as returned
229              brush = wxBrush(wxBLACK, wxCROSS_HATCH)          by a wxrect's asTuple method) needs to be redrawn. Highlight the
230            shapes given by the ids in selected_shapes in the
231              shapetype = layer.ShapeType()          selected_layer.
232              if shapetype == SHAPETYPE_POLYGON:          """
233                  offx, offy = self.offset          return self.render_map_incrementally()
                 renderparam = self.polygon_render_param(layer)  
                 func = self.draw_polygon_shape  
                 args = (pen, brush)  
             elif shapetype == SHAPETYPE_ARC:  
                 renderparam = self.polygon_render_param(layer)  
                 func = self.draw_polygon_shape  
                 args = (pen, None)  
             elif shapetype == SHAPETYPE_POINT:  
                 renderparam = layer  
                 self.dc.SetBrush(brush)  
                 self.dc.SetPen(pen)  
                 func = self.draw_point_shape  
                 args = ()  
             else:  
                 raise TypeError(_("Unhandled shape type %s") % shapetype)  
234    
235              for index in self.selected_shapes:      def draw_selection_incrementally(self, layer, selected_shapes):
236                  func(renderparam, index, *args)          """Draw the selected shapes in a emphasized way (i.e.
237            with a special pen and brush.
238            The drawing is performed incrementally, that means every
239            n shapes, the user can have interactions with the map.
240            n is currently fixed to 500.
241    
242            layer -- the layer where the shapes belong to.
243            selected_shapes -- a list of the shape-ids representing the
244                               selected shapes for the given layer.
245            """
246            pen = wx.Pen(wx.BLACK, 3, wx.SOLID)
247            brush = wx.Brush(wx.BLACK, wx.CROSS_HATCH)
248    
249            shapetype = layer.ShapeType()
250            useraw, func, param = self.low_level_renderer(layer)
251            args = (pen, brush)
252    
253            # for point shapes we need to find out the properties
254            # to determine the size. Based on table and field,
255            # we can find out the properties for object - see below.
256            if shapetype == SHAPETYPE_POINT:
257                lc = layer.GetClassification()
258                field = layer.GetClassificationColumn()
259                table = layer.ShapeStore().Table()
260    
261            count = 0
262            for index in selected_shapes:
263                count += 1
264                shape = layer.Shape(index)
265    
266                # Get the size of the specific property for this
267                # point
268                if shapetype == SHAPETYPE_POINT:
269                    if field is not None:
270                        value = table.ReadValue(shape.ShapeID(), field)
271                        group = lc.FindGroup(value)
272                        size = group.GetProperties().GetSize()
273                    else:
274                        size = lc.GetDefaultGroup().GetProperties().GetSize()
275                    args = (pen, brush, size)
276    
277                if useraw:
278                    data = shape.RawData()
279                else:
280                    data = shape.Points()
281                func(param, data, *args)
282                if count % 500 == 0:
283                    yield True
284    
285      def layer_ids(self, layer):      def layer_shapes(self, layer):
286          """Return the shapeids covered by the region that has to be redrawn          """Return the shapeids covered by the region that has to be redrawn
287    
288          Call the layer's ShapesInRegion method to determine the ids so          Call the layer's ShapesInRegion method to determine the ids so
# Line 389  class ScreenRenderer(MapRenderer): Line 303  class ScreenRenderer(MapRenderer):
303          offx, offy = self.offset          offx, offy = self.offset
304          xs = []          xs = []
305          ys = []          ys = []
306          x, y, width, height = self.update_region          x, y, width, height = self.region
307          for winx, winy in ((x, y), (x + width, y),          for winx, winy in ((x, y), (x + width, y),
308                             (x + width, y + height), (x, y + height)):                             (x + width, y + height), (x, y + height)):
309              px = (winx - offx) / scale              px = (winx - offx) / scale
# Line 409  class ScreenRenderer(MapRenderer): Line 323  class ScreenRenderer(MapRenderer):
323  class ExportRenderer(ScreenRenderer):  class ExportRenderer(ScreenRenderer):
324    
325      honor_visibility = 1      honor_visibility = 1
326        
327      def RenderMap(self, map, region, mapregion,      def __init__(self, *args, **kw):
328                    selected_layer, selected_shapes ):          """Initialize the ExportRenderer.
329    
330            In addition to all parameters of the the ScreenRender
331            constructor, this class requires and additional keyword argument
332            destination_region with a tuple (minx, miny, maxx, maxy) giving
333            the region in dc coordinates which is to contain the map.
334            """
335            self.destination_region = kw["destination_region"]
336            del kw["destination_region"]
337            ScreenRenderer.__init__(self, *args, **kw)
338    
339        def RenderMap(self, selected_layer, selected_shapes):
340          """Render the map.          """Render the map.
341    
342          The rendering device has been specified during initialisation.          The rendering device has been specified during initialisation.
343          The device border distance was set in Thuban.UI.view.OutputTranform().          The device border distance was set in
344                    Thuban.UI.viewport.output_transform().
345    
346          RenderMap renders a frame set (one page frame, one around          RenderMap renders a frame set (one page frame, one around
347          legend/scalebar and one around the map), the map, the legend and the          legend/scalebar and one around the map), the map, the legend and
348          scalebar on the given DC. The map is rendered with the region displayed          the scalebar on the given DC. The map is rendered with the
349          in the canvas view, centered on the area available for map display.          region displayed in the canvas view, centered on the area
350            available for map display.
351          """          """
352            
         self.update_region = region  
353          self.selected_layer = selected_layer          self.selected_layer = selected_layer
354          self.selected_shapes = selected_shapes          self.selected_shapes = selected_shapes
355    
356          # Get some dimensions          # Get some dimensions
357          llx, lly, urx, ury = region          llx, lly, urx, ury = self.region
358          self.mapregion = mapregion          mminx, mminy, mmaxx, mmaxy = self.destination_region
         mminx, mminy, mmaxx, mmaxy = self.mapregion  
359    
360          # Manipulate the offset to position the map          # Manipulate the offset to position the map
361          offx, offy = self.offset          offx, offy = self.offset
362          # 1. Shift to corner of map drawing area          # 1. Shift to corner of map drawing area
363          offx = offx + mminx          offx = offx + mminx
364          offy = offy + mminy          offy = offy + mminy
365    
366          # 2. Center the map on the map drawing area:          # 2. Center the map on the map drawing area:
367          # region identifies the region on the canvas view:          # region identifies the region on the canvas view:
368          # center of map drawing area - half the size of region: rendering origin          # center of map drawing area - half the size of region: rendering origin
369          self.shiftx = (mmaxx - mminx)*0.5 - (urx - llx)*0.5          self.shiftx = (mmaxx - mminx)*0.5 - (urx - llx)*0.5
370          self.shifty = (mmaxy - mminy)*0.5 - (ury - lly)*0.5          self.shifty = (mmaxy - mminy)*0.5 - (ury - lly)*0.5
371    
372          self.offset = (offx+self.shiftx, offy+self.shifty)          self.offset = (offx+self.shiftx, offy+self.shifty)
373            self.region = (llx + self.shiftx, lly + self.shifty, urx, ury)
374    
375          # Draw the map          # Draw the map
376          self.dc.BeginDrawing()          self.dc.BeginDrawing()
377          self.dc.DestroyClippingRegion()          self.dc.DestroyClippingRegion()
378          self.dc.SetClippingRegion(mminx+self.shiftx, mminy+self.shifty,          self.dc.SetClippingRegion(mminx+self.shiftx, mminy+self.shifty,
379                                    urx, ury)                                    urx, ury)
380          self.render_map(map)          self.render_map()
381          self.dc.EndDrawing()          self.dc.EndDrawing()
382    
383          # Draw the rest (frames, legend, scalebar)          # Draw the rest (frames, legend, scalebar)
# Line 459  class ExportRenderer(ScreenRenderer): Line 385  class ExportRenderer(ScreenRenderer):
385          self.dc.DestroyClippingRegion()          self.dc.DestroyClippingRegion()
386    
387          # Force the font for Legend drawing          # Force the font for Legend drawing
388          font = wxFont(self.resolution * 10, wxSWISS, wxNORMAL, wxNORMAL)          font = wx.Font(self.resolution * 10, wx.SWISS, wx.NORMAL, wx.NORMAL)
389          self.dc.SetFont(font)          self.dc.SetFont(font)
390    
391          self.render_frame(region)          self.render_frame()
392          self.render_legend(map)          self.render_legend()
393          self.render_scalebar(map)          self.render_scalebar()
394          self.dc.EndDrawing()          self.dc.EndDrawing()
395    
396      def render_frame(self, region):      def render_frame(self):
397          """Render the frames for map and legend/scalebar."""          """Render the frames for map and legend/scalebar."""
398    
399          dc = self.dc          dc = self.dc
400          dc.SetPen(wxBLACK_PEN)          dc.SetPen(wx.BLACK_PEN)
401          dc.SetBrush(wxTRANSPARENT_BRUSH)          dc.SetBrush(wx.TRANSPARENT_BRUSH)
402    
403          # Dimension stuff          # Dimension stuff
404          width, height = dc.GetSizeTuple()          width, height = dc.GetSizeTuple()
405          mminx, mminy, mmaxx, mmaxy = self.mapregion          mminx, mminy, mmaxx, mmaxy = self.destination_region
406    
407          # Page Frame          # Page Frame
408          dc.DrawRectangle(15,15,width-30, (mmaxy-mminy)+10)          dc.DrawRectangle(15,15,width-30, (mmaxy-mminy)+10)
409            
410          # Map Frame          # Map Frame
411          llx, lly, urx, ury = region          llx, lly, urx, ury = self.region
412          dc.DrawRectangle(mminx + self.shiftx, mminy + self.shifty, urx, ury)          dc.DrawRectangle(mminx + self.shiftx, mminy + self.shifty, urx, ury)
413            
414          # Legend Frame          # Legend Frame
415          dc.DrawRectangle(mmaxx+10,mminy,(width-20) - (mmaxx+10), mmaxy-mminy)          dc.DrawRectangle(mmaxx+10,mminy,(width-20) - (mmaxx+10), mmaxy-mminy)
416    
# Line 492  class ExportRenderer(ScreenRenderer): Line 418  class ExportRenderer(ScreenRenderer):
418          dc.SetClippingRegion(mmaxx+10,mminy,          dc.SetClippingRegion(mmaxx+10,mminy,
419                               (width-20) - (mmaxx+10), mmaxy-mminy)                               (width-20) - (mmaxx+10), mmaxy-mminy)
420    
421      def render_legend(self, map):      def render_legend(self):
422          """Render the legend on the Map."""          """Render the legend on the Map."""
423    
424          previewer = ClassDataPreviewer()          previewer = ClassDataPreviewer()
425          dc = self.dc          dc = self.dc
426          dc.SetPen(wxBLACK_PEN)          dc.SetPen(wx.BLACK_PEN)
427          dc.SetBrush(wxTRANSPARENT_BRUSH)          dc.SetBrush(wx.TRANSPARENT_BRUSH)
428    
429          # Dimension stuff          # Dimension stuff
430          width, height = dc.GetSizeTuple()          width, height = dc.GetSizeTuple()
431          mminx, mminy, mmaxx, mmaxy = self.mapregion          mminx, mminy, mmaxx, mmaxy = self.destination_region
432          textwidth, textheight = dc.GetTextExtent("0")          textwidth, textheight = dc.GetTextExtent("0")
433          iconwidth  = textheight          iconwidth  = textheight
434          iconheight = textheight          iconheight = textheight
435          stepy = textheight+3          stepy = textheight+3
436          dx = 10          dx = 10
437          posx = mmaxx + 10 + 5   # 10 pix distance mapframe/legend frame,          posx = mmaxx + 10 + 5   # 10 pix distance mapframe/legend frame,
438                                  # 5 pix inside legend frame                                  # 5 pix inside legend frame
439          posy = mminy + 5        # 5 pix inside legend frame          posy = mminy + 5        # 5 pix inside legend frame
440            
441          # Render the legend          # Render the legend
442          dc.SetTextForeground(wxBLACK)          dc.SetTextForeground(wx.BLACK)
443          if map.HasLayers():          if self.map.HasLayers():
444              for l in map.Layers():              layers = self.map.Layers()[:]
445                layers.reverse()
446                for l in layers:
447                  if l.Visible():                  if l.Visible():
448                      # Render title                      # Render title
449                      dc.DrawText(l.Title(), posx, posy)                      dc.DrawText(l.Title(), posx, posy)
# Line 526  class ExportRenderer(ScreenRenderer): Line 454  class ExportRenderer(ScreenRenderer):
454                          shapeType = l.ShapeType()                          shapeType = l.ShapeType()
455                          for g in clazz:                          for g in clazz:
456                              if g.IsVisible():                              if g.IsVisible():
457                                  previewer.Draw(dc,                                  previewer.Draw(dc,
458                                      wxRect(posx+dx, posy,                                      wx.Rect(posx+dx, posy,
459                                             iconwidth, iconheight),                                             iconwidth, iconheight),
460                                      g.GetProperties(), shapeType)                                      g.GetProperties(), shapeType)
461                                  dc.DrawText(g.GetDisplayText(),                                  dc.DrawText(g.GetDisplayText(),
462                                              posx+2*dx+iconwidth, posy)                                              posx+2*dx+iconwidth, posy)
463                                  posy+=stepy                                  posy+=stepy
464            
465      def render_scalebar(self, map):      def render_scalebar(self):
466          """Render the scalebar."""          """Render the scalebar."""
467    
468          scalebar = ScaleBar(map)          scalebar = ScaleBar(self.map)
469    
470          # Dimension stuff          # Dimension stuff
471          width, height = self.dc.GetSizeTuple()          width, height = self.dc.GetSizeTuple()
472          mminx, mminy, mmaxx, mmaxy = self.mapregion          mminx, mminy, mmaxx, mmaxy = self.destination_region
473          
474          # Render the scalebar          # Render the scalebar
475          scalebar.DrawScaleBar(self.scale, self.dc,          scalebar.DrawScaleBar(self.scale, self.dc,
476                               (mmaxx+10+5, mmaxy-25),                               (mmaxx+10+5, mmaxy-25),
477                               ((width-15-5) - (mmaxx+10+5),20)                               ((width-15-5) - (mmaxx+10+5),20)
478                              )                              )

Legend:
Removed from v.1298  
changed lines
  Added in v.2712

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26