/[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 610 by jonathan, Fri Apr 4 13:56:59 2003 UTC revision 967 by jonathan, Wed May 21 17:24:54 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
18    import os.path
19    
20  from math import hypot  from math import hypot
21    
22  from wxPython.wx import wxWindow,\  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, \
26         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       MAP_LAYERS_CHANGED, LAYER_CHANGED, LAYER_VISIBILITY_CHANGED       MAP_LAYERS_CHANGED, LAYER_CHANGED, LAYER_VISIBILITY_CHANGED
39  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \
# Line 32  from Thuban.Model.label import ALIGN_CEN Line 43  from Thuban.Model.label import ALIGN_CEN
43  from Thuban.Lib.connector import Publisher  from Thuban.Lib.connector import Publisher
44  from Thuban.Model.color import Color  from Thuban.Model.color import Color
45    
46    import resource
47    
48  from selection import Selection  from selection import Selection
49  from renderer import ScreenRenderer, PrinterRender  from renderer import ScreenRenderer, ExportRenderer, PrinterRenderer
50    
51  import labeldialog  import labeldialog
52    
53  from messages import LAYER_SELECTED, SHAPES_SELECTED, VIEW_POSITION  from messages import LAYER_SELECTED, SHAPES_SELECTED, VIEW_POSITION, \
54                         SCALE_CHANGED
55    
56    
57  #  #
# Line 217  class LabelTool(Tool): Line 231  class LabelTool(Tool):
231          self.view.LabelShapeAt(event.m_x, event.m_y)          self.view.LabelShapeAt(event.m_x, event.m_y)
232    
233    
   
   
234  class MapPrintout(wx.wxPrintout):  class MapPrintout(wx.wxPrintout):
235    
236      """      """
237      wxPrintout class for printing Thuban maps      wxPrintout class for printing Thuban maps
238      """      """
239    
240      def __init__(self, map):      def __init__(self, canvas, map, region, selected_layer, selected_shapes):
241          wx.wxPrintout.__init__(self)          wx.wxPrintout.__init__(self)
242            self.canvas = canvas
243          self.map = map          self.map = map
244            self.region = region
245            self.selected_layer = selected_layer
246            self.selected_shapes = selected_shapes
247    
248      def GetPageInfo(self):      def GetPageInfo(self):
249          return (1, 1, 1, 1)          return (1, 1, 1, 1)
# Line 241  class MapPrintout(wx.wxPrintout): Line 257  class MapPrintout(wx.wxPrintout):
257    
258      def draw_on_dc(self, dc):      def draw_on_dc(self, dc):
259          width, height = self.GetPageSizePixels()          width, height = self.GetPageSizePixels()
260          llx, lly, urx, ury = self.map.ProjectedBoundingBox()          scale, offset, mapregion = OutputTransform(self.canvas.scale,
261          scalex = width / (urx - llx)                                                     self.canvas.offset,
262          scaley = height / (ury - lly)                                                     self.canvas.GetSizeTuple(),
263          scale = min(scalex, scaley)                                                     self.GetPageSizePixels())
         offx = 0.5 * (width - (urx + llx) * scale)  
         offy = 0.5 * (height + (ury + lly) * scale)  
   
264          resx, resy = self.GetPPIPrinter()          resx, resy = self.GetPPIPrinter()
265          renderer = PrinterRender(dc, scale, (offx, offy), resolution = resx)          renderer = PrinterRenderer(dc, scale, offset, resolution = resy)
266          renderer.RenderMap(self.map)          x, y, width, height = self.region
267            canvas_scale = self.canvas.scale
268            renderer.RenderMap(self.map,
269                               (0,0,
270                                    (width/canvas_scale)*scale,
271                                    (height/canvas_scale)*scale),
272                                    mapregion,
273                               self.selected_layer, self.selected_shapes)
274          return wx.true          return wx.true
275    
276    
# Line 259  class MapCanvas(wxWindow, Publisher): Line 279  class MapCanvas(wxWindow, Publisher):
279      """A widget that displays a map and offers some interaction"""      """A widget that displays a map and offers some interaction"""
280    
281      # Some messages that can be subscribed/unsubscribed directly through      # Some messages that can be subscribed/unsubscribed directly through
282      # the MapCanvas come in fact from other objects. This is a map to      # the MapCanvas come in fact from other objects. This is a dict
283      # map those messages to the names of the instance variables they      # mapping those messages to the names of the instance variables they
284      # actually come from. This delegation is implemented in the      # actually come from. The delegation is implemented in the Subscribe
285      # Subscribe and unsubscribed methods      # and Unsubscribe methods
286      delegated_messages = {LAYER_SELECTED: "selection",      delegated_messages = {LAYER_SELECTED: "selection",
287                            SHAPES_SELECTED: "selection"}                            SHAPES_SELECTED: "selection"}
288    
# Line 271  class MapCanvas(wxWindow, Publisher): Line 291  class MapCanvas(wxWindow, Publisher):
291      delegated_methods = {"SelectLayer": "selection",      delegated_methods = {"SelectLayer": "selection",
292                           "SelectShapes": "selection",                           "SelectShapes": "selection",
293                           "SelectedLayer": "selection",                           "SelectedLayer": "selection",
294                           "HasSelectedLayer": "selection"}                           "HasSelectedLayer": "selection",
295                             "HasSelectedShapes": "selection",
296                             "SelectedShapes": "selection"}
297    
298      def __init__(self, parent, winid):      def __init__(self, parent, winid):
299          wxWindow.__init__(self, parent, winid)          wxWindow.__init__(self, parent, winid)
# Line 353  class MapCanvas(wxWindow, Publisher): Line 375  class MapCanvas(wxWindow, Publisher):
375    
376      def OnPaint(self, event):      def OnPaint(self, event):
377          dc = wxPaintDC(self)          dc = wxPaintDC(self)
378          if self.map is not None and self.map.HasLayers():          clear = self.map is None or not self.map.HasLayers()
379    
380            wxBeginBusyCursor()
381    
382            if not clear:
383              self.do_redraw()              self.do_redraw()
384          else:              try:
385                    pass
386                except:
387                    print "Error during drawing:", sys.exc_info()[0]
388                    clear = True
389    
390            if clear:
391              # If we've got no map or if the map is empty, simply clear              # If we've got no map or if the map is empty, simply clear
392              # the screen.              # the screen.
393    
# Line 367  class MapCanvas(wxWindow, Publisher): Line 399  class MapCanvas(wxWindow, Publisher):
399              dc.Clear()              dc.Clear()
400              dc.EndDrawing()              dc.EndDrawing()
401    
402            wxEndBusyCursor()
403    
404      def do_redraw(self):      def do_redraw(self):
405          # This should only be called if we have a non-empty map.          # This should only be called if we have a non-empty map.
406    
# Line 383  class MapCanvas(wxWindow, Publisher): Line 417  class MapCanvas(wxWindow, Publisher):
417              dc.BeginDrawing()              dc.BeginDrawing()
418    
419              # clear the background              # clear the background
420              dc.SetBrush(wx.wxWHITE_BRUSH)              #dc.SetBrush(wx.wxWHITE_BRUSH)
421              dc.SetPen(wx.wxTRANSPARENT_PEN)              #dc.SetPen(wx.wxTRANSPARENT_PEN)
422              dc.DrawRectangle(0, 0, width, height)              #dc.DrawRectangle(0, 0, width, height)
423                dc.SetBackground(wx.wxWHITE_BRUSH)
424                dc.Clear()
425    
426              selected_layer = self.selection.SelectedLayer()              selected_layer = self.selection.SelectedLayer()
427              selected_shapes = self.selection.SelectedShapes()              selected_shapes = self.selection.SelectedShapes()
# Line 410  class MapCanvas(wxWindow, Publisher): Line 446  class MapCanvas(wxWindow, Publisher):
446          clientdc.Blit(0, 0, width, height, dc, 0, 0)          clientdc.Blit(0, 0, width, height, dc, 0, 0)
447          clientdc.EndDrawing()          clientdc.EndDrawing()
448    
449        def Export(self):
450            if self.scale == 0:
451                return
452    
453            if hasattr(self, "export_path"):
454                export_path = self.export_path
455            else:
456                export_path="."
457            dlg = wxFileDialog(self, _("Export Map"), export_path, "",
458                               "Enhanced Metafile (*.wmf)|*.wmf",
459                               wxSAVE|wxOVERWRITE_PROMPT)
460            if dlg.ShowModal() == wxID_OK:
461                self.export_path = os.path.dirname(dlg.GetPath())
462                dc = wxMetaFileDC(dlg.GetPath())
463        
464                scale, offset, mapregion = OutputTransform(self.scale,
465                                                           self.offset,
466                                                           self.GetSizeTuple(),
467                                                           dc.GetSizeTuple())
468    
469                selected_layer = self.selection.SelectedLayer()
470                selected_shapes = self.selection.SelectedShapes()
471    
472                renderer = ExportRenderer(dc, scale, offset)
473    
474                # Pass the entire bitmap as update region to the renderer.
475                # We're redrawing the whole bitmap, after all.
476                width, height = self.GetSizeTuple()
477                renderer.RenderMap(self.map,
478                                    (0,0,
479                                        (width/self.scale)*scale,
480                                        (height/self.scale)*scale),
481                                    mapregion,
482                                    selected_layer, selected_shapes)
483                dc.EndDrawing()
484                dc.Close()
485            dlg.Destroy()
486            
487      def Print(self):      def Print(self):
488          printer = wx.wxPrinter()          printer = wx.wxPrinter()
489          printout = MapPrintout(self.map)          width, height = self.GetSizeTuple()
490            selected_layer = self.selection.SelectedLayer()
491            selected_shapes = self.selection.SelectedShapes()
492            
493            printout = MapPrintout(self, self.map, (0, 0, width, height),
494                                   selected_layer, selected_shapes)
495          printer.Print(self, printout, wx.true)          printer.Print(self, printout, wx.true)
496          printout.Destroy()          printout.Destroy()
497    
# Line 453  class MapCanvas(wxWindow, Publisher): Line 532  class MapCanvas(wxWindow, Publisher):
532    
533      def set_view_transform(self, scale, offset):      def set_view_transform(self, scale, offset):
534          self.scale = scale          self.scale = scale
535    
536          self.offset = offset          self.offset = offset
537          self.full_redraw()          self.full_redraw()
538            self.issue(SCALE_CHANGED, scale)
539    
540      def proj_to_win(self, x, y):      def proj_to_win(self, x, y):
541          """\          """\
542          Return the point in  window coords given by projected coordinates x y          Return the point in  window coords given by projected coordinates x y
543          """          """
544            if self.scale == 0:
545                return (0, 0)
546    
547          offx, offy = self.offset          offx, offy = self.offset
548          return (self.scale * x + offx, -self.scale * y + offy)          return (self.scale * x + offx, -self.scale * y + offy)
549    
# Line 467  class MapCanvas(wxWindow, Publisher): Line 551  class MapCanvas(wxWindow, Publisher):
551          """\          """\
552          Return the point in projected coordinates given by window coords x y          Return the point in projected coordinates given by window coords x y
553          """          """
554            if self.scale == 0:
555                return (0, 0)
556    
557          offx, offy = self.offset          offx, offy = self.offset
558          return ((x - offx) / self.scale, (offy - y) / self.scale)          return ((x - offx) / self.scale, (offy - y) / self.scale)
559    
# Line 479  class MapCanvas(wxWindow, Publisher): Line 566  class MapCanvas(wxWindow, Publisher):
566          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
567          llx, lly, urx, ury = rect          llx, lly, urx, ury = rect
568          if llx == urx or lly == ury:          if llx == urx or lly == ury:
569              # zero with or zero height. Do Nothing              # zero width or zero height. Do Nothing
570              return              return
571          scalex = width / (urx - llx)          scalex = width / (urx - llx)
572          scaley = height / (ury - lly)          scaley = height / (ury - lly)
# Line 498  class MapCanvas(wxWindow, Publisher): Line 585  class MapCanvas(wxWindow, Publisher):
585          if bbox is not None:          if bbox is not None:
586              self.FitRectToWindow(bbox)              self.FitRectToWindow(bbox)
587    
588        def FitLayerToWindow(self, layer):
589            """Fit the given layer to the window.
590    
591            Set the scale so that the layer fits exactly into the window and
592            center it in the window.
593            """
594            
595            bbox = layer.LatLongBoundingBox()
596            if bbox is not None:
597                proj = self.map.GetProjection()
598                if proj is not None:
599                    bbox = proj.ForwardBBox(bbox)
600    
601                if bbox is not None:
602                    self.FitRectToWindow(bbox)
603    
604        def FitSelectedToWindow(self):
605            layer = self.selection.SelectedLayer()
606            shapes = self.selection.SelectedShapes()
607    
608            bbox = layer.ShapesBoundingBox(shapes)
609            if bbox is not None:
610                proj = self.map.GetProjection()
611                if proj is not None:
612                    bbox = proj.ForwardBBox(bbox)
613    
614                if bbox is not None:
615                    self.FitRectToWindow(bbox)
616    
617      def ZoomFactor(self, factor, center = None):      def ZoomFactor(self, factor, center = None):
618          """Multiply the zoom by factor and center on center.          """Multiply the zoom by factor and center on center.
619    
# Line 505  class MapCanvas(wxWindow, Publisher): Line 621  class MapCanvas(wxWindow, Publisher):
621          that should be centered. If it is omitted, it defaults to the          that should be centered. If it is omitted, it defaults to the
622          center of the window          center of the window
623          """          """
624          width, height = self.GetSizeTuple()          if self.scale > 0:
625          scale = self.scale * factor              width, height = self.GetSizeTuple()
626          offx, offy = self.offset              scale = self.scale * factor
627          if center is not None:              offx, offy = self.offset
628              cx, cy = center              if center is not None:
629          else:                  cx, cy = center
630              cx = width / 2              else:
631              cy = height / 2                  cx = width / 2
632          offset = (factor * (offx - cx) + width / 2,                  cy = height / 2
633                    factor * (offy - cy) + height / 2)              offset = (factor * (offx - cx) + width / 2,
634          self.set_view_transform(scale, offset)                      factor * (offy - cy) + height / 2)
635                self.set_view_transform(scale, offset)
636    
637      def ZoomOutToRect(self, rect):      def ZoomOutToRect(self, rect):
638          """Zoom out to fit the currently visible region into rect.          """Zoom out to fit the currently visible region into rect.
# Line 561  class MapCanvas(wxWindow, Publisher): Line 678  class MapCanvas(wxWindow, Publisher):
678      def PanTool(self):      def PanTool(self):
679          """Start the pan tool"""          """Start the pan tool"""
680          self.SelectTool(PanTool(self))          self.SelectTool(PanTool(self))
681            #img = resource.GetImageResource("pan", wxBITMAP_TYPE_XPM)
682            #bmp = resource.GetBitmapResource("pan", wxBITMAP_TYPE_XPM)
683            #print bmp
684            #img = wxImageFromBitmap(bmp)
685            #print img
686            #cur = wxCursor(img)
687            #print cur
688            #self.SetCursor(cur)
689    
690      def IdentifyTool(self):      def IdentifyTool(self):
691          """Start the identify tool"""          """Start the identify tool"""
# Line 639  class MapCanvas(wxWindow, Publisher): Line 764  class MapCanvas(wxWindow, Publisher):
764          # Even when the window becomes larger some parts of the bitmap          # Even when the window becomes larger some parts of the bitmap
765          # could be reused.          # could be reused.
766          self.full_redraw()          self.full_redraw()
767            pass
768    
769      def shape_selected(self, layer, shape):      def shape_selected(self, layer, shape):
770          """Receiver for the SHAPES_SELECTED messages. Redraw the map."""          """Receiver for the SHAPES_SELECTED messages. Redraw the map."""
# Line 692  class MapCanvas(wxWindow, Publisher): Line 818  class MapCanvas(wxWindow, Publisher):
818              forward = None              forward = None
819    
820          scale = self.scale          scale = self.scale
821    
822            if scale == 0:
823                return None, None
824    
825          offx, offy = self.offset          offx, offy = self.offset
826    
827          if select_labels:          if select_labels:
# Line 884  class MapCanvas(wxWindow, Publisher): Line 1014  class MapCanvas(wxWindow, Publisher):
1014                      valign = ALIGN_CENTER                      valign = ALIGN_CENTER
1015                  label_layer.AddLabel(x, y, text,                  label_layer.AddLabel(x, y, text,
1016                                       halign = halign, valign = valign)                                       halign = halign, valign = valign)
1017    
1018    def OutputTransform(canvas_scale, canvas_offset, canvas_size, device_extend):
1019        """Calculate dimensions to transform canvas content to output device."""
1020        width, height = device_extend
1021    
1022        # Only 80 % of the with are available for the map
1023        width = width * 0.8
1024    
1025        # Define the distance of the map from DC border
1026        distance = 20
1027    
1028        if height < width:
1029            # landscape
1030            map_height = height - 2*distance
1031            map_width = map_height
1032        else:
1033            # portrait, recalibrate width (usually the legend width is too
1034            # small
1035            width = width * 0.9
1036            map_height = width - 2*distance
1037            map_width = map_height
1038        
1039        mapregion = (distance, distance,
1040                     distance+map_width, distance+map_height)
1041    
1042        canvas_width, canvas_height = canvas_size
1043        
1044        scalex = map_width / (canvas_width/canvas_scale)
1045        scaley = map_height / (canvas_height/canvas_scale)
1046        scale = min(scalex, scaley)
1047        canvas_offx, canvas_offy = canvas_offset
1048        offx = scale*canvas_offx/canvas_scale
1049        offy = scale*canvas_offy/canvas_scale
1050    
1051        return scale, (offx, offy), mapregion

Legend:
Removed from v.610  
changed lines
  Added in v.967

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26