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

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

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

revision 822 by jonathan, Mon May 5 18:20:28 2003 UTC revision 1221 by jonathan, Tue Jun 17 15:24:45 2003 UTC
# Line 1  Line 1 
1  # Copyright (c) 2001, 2002, 2003 by Intevation GmbH  # Copyright (c) 2001, 2002, 2003 by Intevation GmbH
2  # Authors:  # Authors:
3  # Bernhard Herzog <[email protected]>  # Bernhard Herzog <[email protected]>
4    # Frank Koormann <[email protected]>
5  #  #
6  # This program is free software under the GPL (>=v2)  # This program is free software under the GPL (>=v2)
7  # Read the file COPYING coming with Thuban for details.  # Read the file COPYING coming with Thuban for details.
# Line 11  Classes for display of a map and interac Line 12  Classes for display of a map and interac
12    
13  __version__ = "$Revision$"  __version__ = "$Revision$"
14    
15    from Thuban import _
16    
17  import sys  import sys
18    import os.path
19    
20  from math import hypot  from math import hypot
21    
# Line 19  from wxPython.wx import wxWindow,\ Line 23  from wxPython.wx import wxWindow,\
23       wxPaintDC, wxColour, wxClientDC, wxINVERT, wxTRANSPARENT_BRUSH, wxFont,\       wxPaintDC, wxColour, wxClientDC, wxINVERT, wxTRANSPARENT_BRUSH, wxFont,\
24       EVT_PAINT, EVT_LEFT_DOWN, EVT_LEFT_UP, EVT_MOTION, EVT_LEAVE_WINDOW, \       EVT_PAINT, EVT_LEFT_DOWN, EVT_LEFT_UP, EVT_MOTION, EVT_LEAVE_WINDOW, \
25       wxBITMAP_TYPE_XPM, wxBeginBusyCursor, wxEndBusyCursor, wxCursor, \       wxBITMAP_TYPE_XPM, wxBeginBusyCursor, wxEndBusyCursor, wxCursor, \
26       wxImageFromBitmap       wxImageFromBitmap, wxPlatform
27    
28    # Export related stuff
29    if wxPlatform == '__WXMSW__':
30        from wxPython.wx import wxMetaFileDC
31    from wxPython.wx import wxFileDialog, wxSAVE, wxOVERWRITE_PROMPT, wxID_OK
32    
33  from wxPython import wx  from wxPython import wx
34    
35  from wxproj import point_in_polygon_shape, shape_centroid  from wxproj import point_in_polygon_shape, shape_centroid
36    
   
37  from Thuban.Model.messages import MAP_PROJECTION_CHANGED, \  from Thuban.Model.messages import MAP_PROJECTION_CHANGED, \
38         LAYER_PROJECTION_CHANGED, \
39       MAP_LAYERS_CHANGED, LAYER_CHANGED, LAYER_VISIBILITY_CHANGED       MAP_LAYERS_CHANGED, LAYER_CHANGED, LAYER_VISIBILITY_CHANGED
40  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \
41       SHAPETYPE_POINT       SHAPETYPE_POINT
# Line 39  from Thuban.Model.color import Color Line 47  from Thuban.Model.color import Color
47  import resource  import resource
48    
49  from selection import Selection  from selection import Selection
50  from renderer import ScreenRenderer, PrinterRender  from renderer import ScreenRenderer, ExportRenderer, PrinterRenderer
51    
52  import labeldialog  import labeldialog
53    
54  from messages import LAYER_SELECTED, SHAPES_SELECTED, VIEW_POSITION  from messages import LAYER_SELECTED, SHAPES_SELECTED, VIEW_POSITION, \
55                         SCALE_CHANGED
56    
57    
58  #  #
# Line 223  class LabelTool(Tool): Line 232  class LabelTool(Tool):
232          self.view.LabelShapeAt(event.m_x, event.m_y)          self.view.LabelShapeAt(event.m_x, event.m_y)
233    
234    
   
   
235  class MapPrintout(wx.wxPrintout):  class MapPrintout(wx.wxPrintout):
236    
237      """      """
238      wxPrintout class for printing Thuban maps      wxPrintout class for printing Thuban maps
239      """      """
240    
241      def __init__(self, map):      def __init__(self, canvas, map, region, selected_layer, selected_shapes):
242          wx.wxPrintout.__init__(self)          wx.wxPrintout.__init__(self)
243            self.canvas = canvas
244          self.map = map          self.map = map
245            self.region = region
246            self.selected_layer = selected_layer
247            self.selected_shapes = selected_shapes
248    
249      def GetPageInfo(self):      def GetPageInfo(self):
250          return (1, 1, 1, 1)          return (1, 1, 1, 1)
# Line 247  class MapPrintout(wx.wxPrintout): Line 258  class MapPrintout(wx.wxPrintout):
258    
259      def draw_on_dc(self, dc):      def draw_on_dc(self, dc):
260          width, height = self.GetPageSizePixels()          width, height = self.GetPageSizePixels()
261          llx, lly, urx, ury = self.map.ProjectedBoundingBox()          scale, offset, mapregion = OutputTransform(self.canvas.scale,
262          scalex = width / (urx - llx)                                                     self.canvas.offset,
263          scaley = height / (ury - lly)                                                     self.canvas.GetSizeTuple(),
264          scale = min(scalex, scaley)                                                     self.GetPageSizePixels())
         offx = 0.5 * (width - (urx + llx) * scale)  
         offy = 0.5 * (height + (ury + lly) * scale)  
   
265          resx, resy = self.GetPPIPrinter()          resx, resy = self.GetPPIPrinter()
266          renderer = PrinterRender(dc, scale, (offx, offy), resolution = resx)          renderer = PrinterRenderer(dc, scale, offset, resolution = resy)
267          renderer.RenderMap(self.map)          x, y, width, height = self.region
268          return wx.true          canvas_scale = self.canvas.scale
269            renderer.RenderMap(self.map,
270                               (0,0,
271                                    (width/canvas_scale)*scale,
272                                    (height/canvas_scale)*scale),
273                                    mapregion,
274                               self.selected_layer, self.selected_shapes)
275            return True
276    
277    
278  class MapCanvas(wxWindow, Publisher):  class MapCanvas(wxWindow, Publisher):
# Line 277  class MapCanvas(wxWindow, Publisher): Line 292  class MapCanvas(wxWindow, Publisher):
292      delegated_methods = {"SelectLayer": "selection",      delegated_methods = {"SelectLayer": "selection",
293                           "SelectShapes": "selection",                           "SelectShapes": "selection",
294                           "SelectedLayer": "selection",                           "SelectedLayer": "selection",
295                           "HasSelectedLayer": "selection"}                           "HasSelectedLayer": "selection",
296                             "HasSelectedShapes": "selection",
297                             "SelectedShapes": "selection"}
298    
299      def __init__(self, parent, winid):      def __init__(self, parent, winid):
300          wxWindow.__init__(self, parent, winid)          wxWindow.__init__(self, parent, winid)
# Line 286  class MapCanvas(wxWindow, Publisher): Line 303  class MapCanvas(wxWindow, Publisher):
303          # the map displayed in this canvas. Set with SetMap()          # the map displayed in this canvas. Set with SetMap()
304          self.map = None          self.map = None
305    
306            # current map projection. should only differ from map.projection
307            # when the map's projection is changing and we need access to the
308            # old projection.
309            self.current_map_proj = None
310    
311          # scale and offset describe the transformation from projected          # scale and offset describe the transformation from projected
312          # coordinates to window coordinates.          # coordinates to window coordinates.
313          self.scale = 1.0          self.scale = 1.0
# Line 361  class MapCanvas(wxWindow, Publisher): Line 383  class MapCanvas(wxWindow, Publisher):
383          dc = wxPaintDC(self)          dc = wxPaintDC(self)
384          clear = self.map is None or not self.map.HasLayers()          clear = self.map is None or not self.map.HasLayers()
385    
386          #wxBeginBusyCursor()          wxBeginBusyCursor()
387            try:
388          if not clear:              if not clear:
             try:  
389                  self.do_redraw()                  self.do_redraw()
390              except:                  try:
391                  print "Error during drawing:", sys.exc_info()[0]                      pass
392                  clear = True                  except:
393                        print "Error during drawing:", sys.exc_info()[0]
394          if clear:                      clear = True
395              # If we've got no map or if the map is empty, simply clear  
396              # the screen.              if clear:
397                    # If we've got no map or if the map is empty, simply clear
398              # XXX it's probably possible to get rid of this. The                  # the screen.
399              # background color of the window is already white and the  
400              # only thing we may have to do is to call self.Refresh()                  # XXX it's probably possible to get rid of this. The
401              # with a true argument in the right places.                  # background color of the window is already white and the
402              dc.BeginDrawing()                  # only thing we may have to do is to call self.Refresh()
403              dc.Clear()                  # with a true argument in the right places.
404              dc.EndDrawing()                  dc.BeginDrawing()
405                    dc.Clear()
406          #wxEndBusyCursor()                  dc.EndDrawing()
407            finally:
408                wxEndBusyCursor()
409    
410      def do_redraw(self):      def do_redraw(self):
411          # This should only be called if we have a non-empty map.          # This should only be called if we have a non-empty map.
# Line 429  class MapCanvas(wxWindow, Publisher): Line 452  class MapCanvas(wxWindow, Publisher):
452          clientdc.Blit(0, 0, width, height, dc, 0, 0)          clientdc.Blit(0, 0, width, height, dc, 0, 0)
453          clientdc.EndDrawing()          clientdc.EndDrawing()
454    
455        def Export(self):
456            if self.scale == 0:
457                return
458    
459            if hasattr(self, "export_path"):
460                export_path = self.export_path
461            else:
462                export_path="."
463            dlg = wxFileDialog(self, _("Export Map"), export_path, "",
464                               "Enhanced Metafile (*.wmf)|*.wmf",
465                               wxSAVE|wxOVERWRITE_PROMPT)
466            if dlg.ShowModal() == wxID_OK:
467                self.export_path = os.path.dirname(dlg.GetPath())
468                dc = wxMetaFileDC(dlg.GetPath())
469        
470                scale, offset, mapregion = OutputTransform(self.scale,
471                                                           self.offset,
472                                                           self.GetSizeTuple(),
473                                                           dc.GetSizeTuple())
474    
475                selected_layer = self.selection.SelectedLayer()
476                selected_shapes = self.selection.SelectedShapes()
477    
478                renderer = ExportRenderer(dc, scale, offset)
479    
480                # Pass the entire bitmap as update region to the renderer.
481                # We're redrawing the whole bitmap, after all.
482                width, height = self.GetSizeTuple()
483                renderer.RenderMap(self.map,
484                                    (0,0,
485                                        (width/self.scale)*scale,
486                                        (height/self.scale)*scale),
487                                    mapregion,
488                                    selected_layer, selected_shapes)
489                dc.EndDrawing()
490                dc.Close()
491            dlg.Destroy()
492            
493      def Print(self):      def Print(self):
494          printer = wx.wxPrinter()          printer = wx.wxPrinter()
495          printout = MapPrintout(self.map)          width, height = self.GetSizeTuple()
496          printer.Print(self, printout, wx.true)          selected_layer = self.selection.SelectedLayer()
497            selected_shapes = self.selection.SelectedShapes()
498            
499            printout = MapPrintout(self, self.map, (0, 0, width, height),
500                                   selected_layer, selected_shapes)
501            printer.Print(self, printout, True)
502          printout.Destroy()          printout.Destroy()
503    
504      def SetMap(self, map):      def SetMap(self, map):
# Line 442  class MapCanvas(wxWindow, Publisher): Line 508  class MapCanvas(wxWindow, Publisher):
508              for channel in redraw_channels:              for channel in redraw_channels:
509                  self.map.Unsubscribe(channel, self.full_redraw)                  self.map.Unsubscribe(channel, self.full_redraw)
510              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,
511                                   self.projection_changed)                                   self.map_projection_changed)
512                self.map.Unsubscribe(LAYER_PROJECTION_CHANGED,
513                                     self.layer_projection_changed)
514          self.map = map          self.map = map
515            self.current_map_proj = self.map.GetProjection()
516          self.selection.ClearSelection()          self.selection.ClearSelection()
517          if self.map is not None:          if self.map is not None:
518              for channel in redraw_channels:              for channel in redraw_channels:
519                  self.map.Subscribe(channel, self.full_redraw)                  self.map.Subscribe(channel, self.full_redraw)
520              self.map.Subscribe(MAP_PROJECTION_CHANGED, self.projection_changed)              self.map.Subscribe(MAP_PROJECTION_CHANGED, self.map_projection_changed)
521                self.map.Subscribe(LAYER_PROJECTION_CHANGED, self.layer_projection_changed)
522          self.FitMapToWindow()          self.FitMapToWindow()
523          # force a redraw. If map is not empty, it's already been called          # force a redraw. If map is not empty, it's already been called
524          # by FitMapToWindow but if map is empty it hasn't been called          # by FitMapToWindow but if map is empty it hasn't been called
# Line 466  class MapCanvas(wxWindow, Publisher): Line 536  class MapCanvas(wxWindow, Publisher):
536          self.bitmap = None          self.bitmap = None
537          self.redraw()          self.redraw()
538    
539      def projection_changed(self, *args):      def map_projection_changed(self, *args):
540          self.FitMapToWindow()  
541            proj = self.current_map_proj
542            self.current_map_proj = self.map.GetProjection()
543    
544            bbox = None
545    
546            if proj is not None and self.current_map_proj is not None:
547                width, height = self.GetSizeTuple()
548                llx, lly = self.win_to_proj(0, height)
549                urx, ury = self.win_to_proj(width, 0)
550                bbox = proj.Inverse(llx, lly) + proj.Inverse(urx, ury)
551                bbox = self.current_map_proj.ForwardBBox(bbox)
552    
553            if bbox is not None:
554                self.FitRectToWindow(bbox)
555            else:
556                self.FitMapToWindow()
557    
558            self.full_redraw()
559    
560        def layer_projection_changed(self, *args):
561          self.full_redraw()          self.full_redraw()
562    
563      def set_view_transform(self, scale, offset):      def set_view_transform(self, scale, offset):
564            # width/height of the projected bbox
565            llx, lly, urx, ury = bbox = self.map.ProjectedBoundingBox()
566            pwidth = float(urx - llx)
567            pheight = float(ury - lly)
568    
569            # width/height of the window
570            wwidth, wheight = self.GetSizeTuple()
571    
572            # The window's center in projected coordinates assuming the new
573            # scale/offset
574            pcenterx = (wwidth/2 - offset[0]) / scale
575            pcentery = (offset[1] - wheight/2) / scale
576    
577            # The window coordinates used when drawing the shapes must fit
578            # into 16bit signed integers.
579            max_len = max(pwidth, pheight)
580            if max_len:
581                max_scale = 32000.0 / max_len
582            else:
583                # FIXME: What to do in this case? The bbox is effectively
584                # empty so any scale should work.
585                max_scale = scale
586    
587            # The minimal scale is somewhat arbitrarily set to half that of
588            # the bbox fit into the window
589            scales = []
590            if pwidth:
591                scales.append(wwidth / pwidth)
592            if pheight:
593                scales.append(wheight / pheight)
594            if scales:
595                min_scale = 0.5 * min(scales)
596            else:
597                min_scale = scale
598    
599            if scale > max_scale:
600                scale = max_scale
601            elif scale < min_scale:
602                scale = min_scale
603    
604          self.scale = scale          self.scale = scale
605          self.offset = offset  
606            # determine new offset to preserve the center
607            self.offset = (wwidth/2 - scale * pcenterx,
608                           wheight/2 + scale * pcentery)
609          self.full_redraw()          self.full_redraw()
610            self.issue(SCALE_CHANGED, scale)
611    
612      def proj_to_win(self, x, y):      def proj_to_win(self, x, y):
613          """\          """\
614          Return the point in  window coords given by projected coordinates x y          Return the point in  window coords given by projected coordinates x y
615          """          """
616            if self.scale == 0:
617                return (0, 0)
618    
619          offx, offy = self.offset          offx, offy = self.offset
620          return (self.scale * x + offx, -self.scale * y + offy)          return (self.scale * x + offx, -self.scale * y + offy)
621    
# Line 486  class MapCanvas(wxWindow, Publisher): Line 623  class MapCanvas(wxWindow, Publisher):
623          """\          """\
624          Return the point in projected coordinates given by window coords x y          Return the point in projected coordinates given by window coords x y
625          """          """
626            if self.scale == 0:
627                return (0, 0)
628    
629          offx, offy = self.offset          offx, offy = self.offset
630          return ((x - offx) / self.scale, (offy - y) / self.scale)          return ((x - offx) / self.scale, (offy - y) / self.scale)
631    
# Line 529  class MapCanvas(wxWindow, Publisher): Line 669  class MapCanvas(wxWindow, Publisher):
669              proj = self.map.GetProjection()              proj = self.map.GetProjection()
670              if proj is not None:              if proj is not None:
671                  bbox = proj.ForwardBBox(bbox)                  bbox = proj.ForwardBBox(bbox)
672                  if bbox is not None:  
673                if bbox is not None:
674                    self.FitRectToWindow(bbox)
675    
676        def FitSelectedToWindow(self):
677            layer = self.selection.SelectedLayer()
678            shapes = self.selection.SelectedShapes()
679    
680            bbox = layer.ShapesBoundingBox(shapes)
681            if bbox is not None:
682                proj = self.map.GetProjection()
683                if proj is not None:
684                    bbox = proj.ForwardBBox(bbox)
685    
686                if bbox is not None:
687                    if len(shapes) == 1 and layer.ShapeType() == SHAPETYPE_POINT:
688                        self.ZoomFactor(1, self.proj_to_win(bbox[0], bbox[1]))
689                    else:
690                      self.FitRectToWindow(bbox)                      self.FitRectToWindow(bbox)
691    
692      def ZoomFactor(self, factor, center = None):      def ZoomFactor(self, factor, center = None):
# Line 539  class MapCanvas(wxWindow, Publisher): Line 696  class MapCanvas(wxWindow, Publisher):
696          that should be centered. If it is omitted, it defaults to the          that should be centered. If it is omitted, it defaults to the
697          center of the window          center of the window
698          """          """
699          width, height = self.GetSizeTuple()          if self.scale > 0:
700          scale = self.scale * factor              width, height = self.GetSizeTuple()
701          offx, offy = self.offset              scale = self.scale * factor
702          if center is not None:              offx, offy = self.offset
703              cx, cy = center              if center is not None:
704          else:                  cx, cy = center
705              cx = width / 2              else:
706              cy = height / 2                  cx = width / 2
707          offset = (factor * (offx - cx) + width / 2,                  cy = height / 2
708                    factor * (offy - cy) + height / 2)              offset = (factor * (offx - cx) + width / 2,
709          self.set_view_transform(scale, offset)                      factor * (offy - cy) + height / 2)
710                self.set_view_transform(scale, offset)
711    
712      def ZoomOutToRect(self, rect):      def ZoomOutToRect(self, rect):
713          """Zoom out to fit the currently visible region into rect.          """Zoom out to fit the currently visible region into rect.
# Line 735  class MapCanvas(wxWindow, Publisher): Line 893  class MapCanvas(wxWindow, Publisher):
893              forward = None              forward = None
894    
895          scale = self.scale          scale = self.scale
896    
897            if scale == 0:
898                return None, None
899    
900          offx, offy = self.offset          offx, offy = self.offset
901    
902          if select_labels:          if select_labels:
# Line 813  class MapCanvas(wxWindow, Publisher): Line 975  class MapCanvas(wxWindow, Publisher):
975    
976              if shapetype == SHAPETYPE_POLYGON:              if shapetype == SHAPETYPE_POLYGON:
977                  for i in shape_ids:                  for i in shape_ids:
978                      result = point_in_polygon_shape(layer.shapefile.cobject(),                      shapefile = layer.ShapeStore().Shapefile().cobject()
979                                                      i,                      result = point_in_polygon_shape(shapefile, i,
980                                                      filled, stroked,                                                      filled, stroked,
981                                                      map_proj, layer_proj,                                                      map_proj, layer_proj,
982                                                      scale, -scale, offx, offy,                                                      scale, -scale, offx, offy,
# Line 824  class MapCanvas(wxWindow, Publisher): Line 986  class MapCanvas(wxWindow, Publisher):
986                          break                          break
987              elif shapetype == SHAPETYPE_ARC:              elif shapetype == SHAPETYPE_ARC:
988                  for i in shape_ids:                  for i in shape_ids:
989                      result = point_in_polygon_shape(layer.shapefile.cobject(),                      shapefile = layer.ShapeStore().Shapefile().cobject()
990                        result = point_in_polygon_shape(shapefile,
991                                                      i, 0, 1,                                                      i, 0, 1,
992                                                      map_proj, layer_proj,                                                      map_proj, layer_proj,
993                                                      scale, -scale, offx, offy,                                                      scale, -scale, offx, offy,
# Line 886  class MapCanvas(wxWindow, Publisher): Line 1049  class MapCanvas(wxWindow, Publisher):
1049              # a label was selected              # a label was selected
1050              label_layer.RemoveLabel(shape_index)              label_layer.RemoveLabel(shape_index)
1051          elif layer is not None:          elif layer is not None:
1052              text = labeldialog.run_label_dialog(self, layer.table, shape_index)              text = labeldialog.run_label_dialog(self,
1053                                                    layer.ShapeStore().Table(),
1054                                                    shape_index)
1055              if text:              if text:
1056                  proj = self.map.projection                  proj = self.map.projection
1057                  if proj is not None:                  if proj is not None:
# Line 901  class MapCanvas(wxWindow, Publisher): Line 1066  class MapCanvas(wxWindow, Publisher):
1066    
1067                  shapetype = layer.ShapeType()                  shapetype = layer.ShapeType()
1068                  if shapetype == SHAPETYPE_POLYGON:                  if shapetype == SHAPETYPE_POLYGON:
1069                      x, y = shape_centroid(layer.shapefile.cobject(),                      shapefile = layer.ShapeStore().Shapefile().cobject()
1070                                            shape_index,                      x, y = shape_centroid(shapefile, shape_index,
1071                                            map_proj, layer_proj, 1, 1, 0, 0)                                            map_proj, layer_proj, 1, 1, 0, 0)
1072                      if map_proj is not None:                      if map_proj is not None:
1073                          x, y = map_proj.Inverse(x, y)                          x, y = map_proj.Inverse(x, y)
# Line 927  class MapCanvas(wxWindow, Publisher): Line 1092  class MapCanvas(wxWindow, Publisher):
1092                      valign = ALIGN_CENTER                      valign = ALIGN_CENTER
1093                  label_layer.AddLabel(x, y, text,                  label_layer.AddLabel(x, y, text,
1094                                       halign = halign, valign = valign)                                       halign = halign, valign = valign)
1095    
1096    def OutputTransform(canvas_scale, canvas_offset, canvas_size, device_extend):
1097        """Calculate dimensions to transform canvas content to output device."""
1098        width, height = device_extend
1099    
1100        # Only 80 % of the with are available for the map
1101        width = width * 0.8
1102    
1103        # Define the distance of the map from DC border
1104        distance = 20
1105    
1106        if height < width:
1107            # landscape
1108            map_height = height - 2*distance
1109            map_width = map_height
1110        else:
1111            # portrait, recalibrate width (usually the legend width is too
1112            # small
1113            width = width * 0.9
1114            map_height = width - 2*distance
1115            map_width = map_height
1116        
1117        mapregion = (distance, distance,
1118                     distance+map_width, distance+map_height)
1119    
1120        canvas_width, canvas_height = canvas_size
1121        
1122        scalex = map_width / (canvas_width/canvas_scale)
1123        scaley = map_height / (canvas_height/canvas_scale)
1124        scale = min(scalex, scaley)
1125        canvas_offx, canvas_offy = canvas_offset
1126        offx = scale*canvas_offx/canvas_scale
1127        offy = scale*canvas_offy/canvas_scale
1128    
1129        return scale, (offx, offy), mapregion

Legend:
Removed from v.822  
changed lines
  Added in v.1221

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26