/[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 296 by bh, Fri Aug 30 16:10:45 2002 UTC revision 831 by jonathan, Tue May 6 12:07:21 2003 UTC
# Line 1  Line 1 
1  # Copyright (c) 2001, 2002 by Intevation GmbH  # Copyright (c) 2001, 2002, 2003 by Intevation GmbH
2  # Authors:  # Authors:
3  # Bernhard Herzog <[email protected]>  # Bernhard Herzog <[email protected]>
4  #  #
# Line 11  Classes for display of a map and interac Line 11  Classes for display of a map and interac
11    
12  __version__ = "$Revision$"  __version__ = "$Revision$"
13    
14    import sys
15    
16  from math import hypot  from math import hypot
17    
18  from wxPython.wx import wxWindow,\  from wxPython.wx import wxWindow,\
19       wxPaintDC, wxColour, wxClientDC, wxINVERT, wxTRANSPARENT_BRUSH, wxFont,\       wxPaintDC, wxColour, wxClientDC, wxINVERT, wxTRANSPARENT_BRUSH, wxFont,\
20       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, \
21         wxBITMAP_TYPE_XPM, wxBeginBusyCursor, wxEndBusyCursor, wxCursor, \
22         wxImageFromBitmap
23    
24    
25  from wxPython import wx  from wxPython import wx
# Line 24  from wxproj import point_in_polygon_shap Line 28  from wxproj import point_in_polygon_shap
28    
29    
30  from Thuban.Model.messages import MAP_PROJECTION_CHANGED, \  from Thuban.Model.messages import MAP_PROJECTION_CHANGED, \
31       LAYERS_CHANGED, LAYER_LEGEND_CHANGED, LAYER_VISIBILITY_CHANGED       MAP_LAYERS_CHANGED, LAYER_CHANGED, LAYER_VISIBILITY_CHANGED
32  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \
33       SHAPETYPE_POINT       SHAPETYPE_POINT
34  from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \  from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \
35       ALIGN_LEFT, ALIGN_RIGHT       ALIGN_LEFT, ALIGN_RIGHT
36  from Thuban.Lib.connector import Publisher  from Thuban.Lib.connector import Publisher
37    from Thuban.Model.color import Color
38    
39    import resource
40    
41    from selection import Selection
42  from renderer import ScreenRenderer, PrinterRender  from renderer import ScreenRenderer, PrinterRender
43    
44  import labeldialog  import labeldialog
45    
46  from messages import SELECTED_SHAPE, VIEW_POSITION  from messages import LAYER_SELECTED, SHAPES_SELECTED, VIEW_POSITION
47    
48    
49  #  #
# Line 256  class MapCanvas(wxWindow, Publisher): Line 264  class MapCanvas(wxWindow, Publisher):
264    
265      """A widget that displays a map and offers some interaction"""      """A widget that displays a map and offers some interaction"""
266    
267      def __init__(self, parent, winid, interactor):      # Some messages that can be subscribed/unsubscribed directly through
268        # the MapCanvas come in fact from other objects. This is a dict
269        # mapping those messages to the names of the instance variables they
270        # actually come from. The delegation is implemented in the Subscribe
271        # and Unsubscribe methods
272        delegated_messages = {LAYER_SELECTED: "selection",
273                              SHAPES_SELECTED: "selection"}
274    
275        # Methods delegated to some instance variables. The delegation is
276        # implemented in the __getattr__ method.
277        delegated_methods = {"SelectLayer": "selection",
278                             "SelectShapes": "selection",
279                             "SelectedLayer": "selection",
280                             "HasSelectedLayer": "selection",
281                             "HasSelectedShapes": "selection"}
282    
283        def __init__(self, parent, winid):
284          wxWindow.__init__(self, parent, winid)          wxWindow.__init__(self, parent, winid)
285          self.SetBackgroundColour(wxColour(255, 255, 255))          self.SetBackgroundColour(wxColour(255, 255, 255))
286    
# Line 279  class MapCanvas(wxWindow, Publisher): Line 303  class MapCanvas(wxWindow, Publisher):
303          # if the mouse is outside the window.          # if the mouse is outside the window.
304          self.current_position = None          self.current_position = None
305    
         # If true, OnIdle will call do_redraw to do the actual  
         # redrawing. Set by OnPaint to avoid some unnecessary redraws.  
         # To force a redraw call full_redraw().  
         self.redraw_on_idle = 0  
   
306          # the bitmap serving as backing store          # the bitmap serving as backing store
307          self.bitmap = None          self.bitmap = None
308    
309          # the interactor          # the selection
310          self.interactor = interactor          self.selection = Selection()
311          self.interactor.Subscribe(SELECTED_SHAPE, self.shape_selected)          self.selection.Subscribe(SHAPES_SELECTED , self.shape_selected)
312    
313          # keep track of which layers/shapes are selected to make sure we          # keep track of which layers/shapes are selected to make sure we
314          # only redraw when necessary          # only redraw when necessary
# Line 303  class MapCanvas(wxWindow, Publisher): Line 322  class MapCanvas(wxWindow, Publisher):
322          EVT_MOTION(self, self.OnMotion)          EVT_MOTION(self, self.OnMotion)
323          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)
324          wx.EVT_SIZE(self, self.OnSize)          wx.EVT_SIZE(self, self.OnSize)
         wx.EVT_IDLE(self, self.OnIdle)  
325    
326      def __del__(self):      def __del__(self):
327          wxWindow.__del__(self)          wxWindow.__del__(self)
328          Publisher.__del__(self)          Publisher.__del__(self)
329    
330        def Subscribe(self, channel, *args):
331            """Extend the inherited method to handle delegated messages.
332    
333            If channel is one of the delegated messages call the appropriate
334            object's Subscribe method. Otherwise just call the inherited
335            method.
336            """
337            if channel in self.delegated_messages:
338                object = getattr(self, self.delegated_messages[channel])
339                object.Subscribe(channel, *args)
340            else:
341                Publisher.Subscribe(self, channel, *args)
342    
343        def Unsubscribe(self, channel, *args):
344            """Extend the inherited method to handle delegated messages.
345    
346            If channel is one of the delegated messages call the appropriate
347            object's Unsubscribe method. Otherwise just call the inherited
348            method.
349            """
350            if channel in self.delegated_messages:
351                object = getattr(self, self.delegated_messages[channel])
352                object.Unsubscribe(channel, *args)
353            else:
354                Publisher.Unsubscribe(self, channel, *args)
355    
356        def __getattr__(self, attr):
357            if attr in self.delegated_methods:
358                return getattr(getattr(self, self.delegated_methods[attr]), attr)
359            raise AttributeError(attr)
360    
361      def OnPaint(self, event):      def OnPaint(self, event):
362          dc = wxPaintDC(self)          dc = wxPaintDC(self)
363          if self.map is not None and self.map.HasLayers():          clear = self.map is None or not self.map.HasLayers()
364              # We have a non-empty map. Redraw it in idle time  
365              self.redraw_on_idle = 1          #wxBeginBusyCursor()
366          else:  
367            if not clear:
368                try:
369                    self.do_redraw()
370                except:
371                    print "Error during drawing:", sys.exc_info()[0]
372                    clear = True
373    
374            if clear:
375              # 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
376              # the screen.              # the screen.
377    
# Line 326  class MapCanvas(wxWindow, Publisher): Line 383  class MapCanvas(wxWindow, Publisher):
383              dc.Clear()              dc.Clear()
384              dc.EndDrawing()              dc.EndDrawing()
385    
386            #wxEndBusyCursor()
387    
388      def do_redraw(self):      def do_redraw(self):
389          # This should only be called if we have a non-empty map.          # This should only be called if we have a non-empty map.
390    
# Line 342  class MapCanvas(wxWindow, Publisher): Line 401  class MapCanvas(wxWindow, Publisher):
401              dc.BeginDrawing()              dc.BeginDrawing()
402    
403              # clear the background              # clear the background
404              dc.SetBrush(wx.wxWHITE_BRUSH)              #dc.SetBrush(wx.wxWHITE_BRUSH)
405              dc.SetPen(wx.wxTRANSPARENT_PEN)              #dc.SetPen(wx.wxTRANSPARENT_PEN)
406              dc.DrawRectangle(0, 0, width, height)              #dc.DrawRectangle(0, 0, width, height)
407                dc.SetBackground(wx.wxWHITE_BRUSH)
408              if 1: #self.interactor.selected_map is self.map:              dc.Clear()
409                  selected_layer = self.interactor.selected_layer  
410                  selected_shape = self.interactor.selected_shape              selected_layer = self.selection.SelectedLayer()
411              else:              selected_shapes = self.selection.SelectedShapes()
                 selected_layer = None  
                 selected_shape = None  
412    
413              # draw the map into the bitmap              # draw the map into the bitmap
414              renderer = ScreenRenderer(dc, self.scale, self.offset)              renderer = ScreenRenderer(dc, self.scale, self.offset)
# Line 359  class MapCanvas(wxWindow, Publisher): Line 416  class MapCanvas(wxWindow, Publisher):
416              # Pass the entire bitmap as update region to the renderer.              # Pass the entire bitmap as update region to the renderer.
417              # We're redrawing the whole bitmap, after all.              # We're redrawing the whole bitmap, after all.
418              renderer.RenderMap(self.map, (0, 0, width, height),              renderer.RenderMap(self.map, (0, 0, width, height),
419                                 selected_layer, selected_shape)                                 selected_layer, selected_shapes)
420    
421              dc.EndDrawing()              dc.EndDrawing()
422              dc.SelectObject(wx.wxNullBitmap)              dc.SelectObject(wx.wxNullBitmap)
# Line 380  class MapCanvas(wxWindow, Publisher): Line 437  class MapCanvas(wxWindow, Publisher):
437          printout.Destroy()          printout.Destroy()
438    
439      def SetMap(self, map):      def SetMap(self, map):
440          redraw_channels = (LAYERS_CHANGED, LAYER_LEGEND_CHANGED,          redraw_channels = (MAP_LAYERS_CHANGED, LAYER_CHANGED,
441                             LAYER_VISIBILITY_CHANGED)                             LAYER_VISIBILITY_CHANGED)
442          if self.map is not None:          if self.map is not None:
443              for channel in redraw_channels:              for channel in redraw_channels:
# Line 388  class MapCanvas(wxWindow, Publisher): Line 445  class MapCanvas(wxWindow, Publisher):
445              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,
446                                   self.projection_changed)                                   self.projection_changed)
447          self.map = map          self.map = map
448            self.selection.ClearSelection()
449          if self.map is not None:          if self.map is not None:
450              for channel in redraw_channels:              for channel in redraw_channels:
451                  self.map.Subscribe(channel, self.full_redraw)                  self.map.Subscribe(channel, self.full_redraw)
# Line 434  class MapCanvas(wxWindow, Publisher): Line 492  class MapCanvas(wxWindow, Publisher):
492    
493      def FitRectToWindow(self, rect):      def FitRectToWindow(self, rect):
494          """Fit the rectangular region given by rect into the window.          """Fit the rectangular region given by rect into the window.
495            
496          Set scale so that rect (in projected coordinates) just fits into          Set scale so that rect (in projected coordinates) just fits into
497          the window and center it.          the window and center it.
498          """          """
499          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
500          llx, lly, urx, ury = rect          llx, lly, urx, ury = rect
501          if llx == urx or lly == ury:          if llx == urx or lly == ury:
502              # zero with or zero height. Do Nothing              # zero width or zero height. Do Nothing
503              return              return
504          scalex = width / (urx - llx)          scalex = width / (urx - llx)
505          scaley = height / (ury - lly)          scaley = height / (ury - lly)
# Line 452  class MapCanvas(wxWindow, Publisher): Line 510  class MapCanvas(wxWindow, Publisher):
510    
511      def FitMapToWindow(self):      def FitMapToWindow(self):
512          """Fit the map to the window          """Fit the map to the window
513            
514          Set the scale so that the map fits exactly into the window and          Set the scale so that the map fits exactly into the window and
515          center it in the window.          center it in the window.
516          """          """
# Line 460  class MapCanvas(wxWindow, Publisher): Line 518  class MapCanvas(wxWindow, Publisher):
518          if bbox is not None:          if bbox is not None:
519              self.FitRectToWindow(bbox)              self.FitRectToWindow(bbox)
520    
521        def FitLayerToWindow(self, layer):
522            """Fit the given layer to the window.
523    
524            Set the scale so that the layer fits exactly into the window and
525            center it in the window.
526            """
527            
528            bbox = layer.LatLongBoundingBox()
529            if bbox is not None:
530                proj = self.map.GetProjection()
531                if proj is not None:
532                    bbox = proj.ForwardBBox(bbox)
533    
534                if bbox is not None:
535                    self.FitRectToWindow(bbox)
536    
537        def FitSelectedToWindow(self):
538            layer = self.selection.SelectedLayer()
539            shapes = self.selection.SelectedShapes()
540    
541            bbox = layer.ShapesBoundingBox(shapes)
542            if bbox is not None:
543                proj = self.map.GetProjection()
544                if proj is not None:
545                    bbox = proj.ForwardBBox(bbox)
546    
547                if bbox is not None:
548                    self.FitRectToWindow(bbox)
549    
550      def ZoomFactor(self, factor, center = None):      def ZoomFactor(self, factor, center = None):
551          """Multiply the zoom by factor and center on center.          """Multiply the zoom by factor and center on center.
552    
# Line 504  class MapCanvas(wxWindow, Publisher): Line 591  class MapCanvas(wxWindow, Publisher):
591          offx, offy = self.offset          offx, offy = self.offset
592          self.set_view_transform(self.scale, (offx + dx, offy + dy))          self.set_view_transform(self.scale, (offx + dx, offy + dy))
593    
594        def SelectTool(self, tool):
595            """Make tool the active tool.
596    
597            The parameter should be an instance of Tool or None to indicate
598            that no tool is active.
599            """
600            self.tool = tool
601    
602      def ZoomInTool(self):      def ZoomInTool(self):
603          """Start the zoom in tool"""          """Start the zoom in tool"""
604          self.tool = ZoomInTool(self)          self.SelectTool(ZoomInTool(self))
605    
606      def ZoomOutTool(self):      def ZoomOutTool(self):
607          """Start the zoom out tool"""          """Start the zoom out tool"""
608          self.tool = ZoomOutTool(self)          self.SelectTool(ZoomOutTool(self))
609    
610      def PanTool(self):      def PanTool(self):
611          """Start the pan tool"""          """Start the pan tool"""
612          self.tool = PanTool(self)          self.SelectTool(PanTool(self))
613            #img = resource.GetImageResource("pan", wxBITMAP_TYPE_XPM)
614            #bmp = resource.GetBitmapResource("pan", wxBITMAP_TYPE_XPM)
615            #print bmp
616            #img = wxImageFromBitmap(bmp)
617            #print img
618            #cur = wxCursor(img)
619            #print cur
620            #self.SetCursor(cur)
621    
622      def IdentifyTool(self):      def IdentifyTool(self):
623          """Start the identify tool"""          """Start the identify tool"""
624          self.tool = IdentifyTool(self)          self.SelectTool(IdentifyTool(self))
625    
626      def LabelTool(self):      def LabelTool(self):
627          """Start the label tool"""          """Start the label tool"""
628          self.tool = LabelTool(self)          self.SelectTool(LabelTool(self))
629    
630      def CurrentTool(self):      def CurrentTool(self):
631          """Return the name of the current tool or None if no tool is active"""          """Return the name of the current tool or None if no tool is active"""
# Line 568  class MapCanvas(wxWindow, Publisher): Line 671  class MapCanvas(wxWindow, Publisher):
671          self.set_current_position(event)          self.set_current_position(event)
672          if self.dragging:          if self.dragging:
673              self.ReleaseMouse()              self.ReleaseMouse()
674              self.tool.Hide(self.drag_dc)              try:
675              self.tool.MouseUp(event)                  self.tool.Hide(self.drag_dc)
676              self.drag_dc = None                  self.tool.MouseUp(event)
677          self.dragging = 0              finally:
678                    self.drag_dc = None
679                    self.dragging = 0
680    
681      def OnMotion(self, event):      def OnMotion(self, event):
682          self.set_current_position(event)          self.set_current_position(event)
# Line 583  class MapCanvas(wxWindow, Publisher): Line 688  class MapCanvas(wxWindow, Publisher):
688      def OnLeaveWindow(self, event):      def OnLeaveWindow(self, event):
689          self.set_current_position(None)          self.set_current_position(None)
690    
     def OnIdle(self, event):  
         if self.redraw_on_idle:  
             self.do_redraw()  
         self.redraw_on_idle = 0  
   
691      def OnSize(self, event):      def OnSize(self, event):
692          # the window's size has changed. We have to get a new bitmap. If          # the window's size has changed. We have to get a new bitmap. If
693          # we want to be clever we could try to get by without throwing          # we want to be clever we could try to get by without throwing
# Line 596  class MapCanvas(wxWindow, Publisher): Line 696  class MapCanvas(wxWindow, Publisher):
696          # Even when the window becomes larger some parts of the bitmap          # Even when the window becomes larger some parts of the bitmap
697          # could be reused.          # could be reused.
698          self.full_redraw()          self.full_redraw()
699            pass
700    
701      def shape_selected(self, layer, shape):      def shape_selected(self, layer, shape):
702          """Redraw the map.          """Receiver for the SHAPES_SELECTED messages. Redraw the map."""
703            # The selection object takes care that it only issues
704          Receiver for the SELECTED_SHAPE messages. Try to redraw only          # SHAPES_SELECTED messages when the set of selected shapes has
705          when necessary.          # actually changed, so we can do a full redraw unconditionally.
706          """          # FIXME: We should perhaps try to limit the redraw to the are
707          # A redraw is necessary when the display has to change, which          # actually covered by the shapes before and after the selection
708          # means that either the status changes from having no selection          # change.
709          # to having a selection shape or vice versa, or when the fact          self.full_redraw()
         # whether there is a selection at all doesn't change, when the  
         # shape which is selected has changed (which means that layer or  
         # shapeid changes).  
         if ((shape is not None or self.last_selected_shape is not None)  
             and (shape != self.last_selected_shape  
                  or layer != self.last_selected_layer)):  
             self.full_redraw()  
   
         # remember the selection so we can compare when it changes again.  
         self.last_selected_layer = layer  
         self.last_selected_shape = shape  
710    
711      def unprojected_rect_around_point(self, x, y):      def unprojected_rect_around_point(self, x, y, dist):
712          """return a rect a few pixels around (x, y) in unprojected corrdinates          """return a rect dist pixels around (x, y) in unprojected corrdinates
713    
714          The return value is a tuple (minx, miny, maxx, maxy) suitable a          The return value is a tuple (minx, miny, maxx, maxy) suitable a
715          parameter to a layer's ShapesInRegion method.          parameter to a layer's ShapesInRegion method.
# Line 633  class MapCanvas(wxWindow, Publisher): Line 723  class MapCanvas(wxWindow, Publisher):
723          xs = []          xs = []
724          ys = []          ys = []
725          for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):          for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
726              px, py = self.win_to_proj(x + dx, y + dy)              px, py = self.win_to_proj(x + dist * dx, y + dist * dy)
727              if inverse:              if inverse:
728                  px, py = inverse(px, py)                  px, py = inverse(px, py)
729              xs.append(px)              xs.append(px)
# Line 662  class MapCanvas(wxWindow, Publisher): Line 752  class MapCanvas(wxWindow, Publisher):
752          scale = self.scale          scale = self.scale
753          offx, offy = self.offset          offx, offy = self.offset
754    
         box = self.unprojected_rect_around_point(px, py)  
   
755          if select_labels:          if select_labels:
756              labels = self.map.LabelLayer().Labels()              labels = self.map.LabelLayer().Labels()
757    
# Line 710  class MapCanvas(wxWindow, Publisher): Line 798  class MapCanvas(wxWindow, Publisher):
798              if not layer.Visible():              if not layer.Visible():
799                  continue                  continue
800    
801              filled = layer.fill is not None              filled = layer.GetClassification().GetDefaultFill() \
802              stroked = layer.stroke is not None                       is not Color.Transparent
803                stroked = layer.GetClassification().GetDefaultLineColor() \
804                          is not Color.Transparent
805    
806              layer_proj = layer.projection              layer_proj = layer.projection
807              if layer_proj is not None:              if layer_proj is not None:
# Line 723  class MapCanvas(wxWindow, Publisher): Line 813  class MapCanvas(wxWindow, Publisher):
813    
814              select_shape = -1              select_shape = -1
815    
816                # Determine the ids of the shapes that overlap a tiny area
817                # around the point. For layers containing points we have to
818                # choose a larger size of the box we're testing agains so
819                # that we take the size of the markers into account
820                # FIXME: Once the markers are more flexible this part has to
821                # become more flexible too, of course
822                if shapetype == SHAPETYPE_POINT:
823                    box = self.unprojected_rect_around_point(px, py, 5)
824                else:
825                    box = self.unprojected_rect_around_point(px, py, 1)
826              shape_ids = layer.ShapesInRegion(box)              shape_ids = layer.ShapesInRegion(box)
827              shape_ids.reverse()              shape_ids.reverse()
828    
# Line 780  class MapCanvas(wxWindow, Publisher): Line 880  class MapCanvas(wxWindow, Publisher):
880          # to deselect the currently selected layer, so we simply select          # to deselect the currently selected layer, so we simply select
881          # the already selected layer again.          # the already selected layer again.
882          if layer is None:          if layer is None:
883              layer = self.interactor.SelectedLayer()              layer = self.selection.SelectedLayer()
884          self.interactor.SelectLayerAndShape(layer, shape)              shapes = []
885            else:
886                shapes = [shape]
887            self.selection.SelectShapes(layer, shapes)
888          return result          return result
889    
890      def LabelShapeAt(self, x, y):      def LabelShapeAt(self, x, y):

Legend:
Removed from v.296  
changed lines
  Added in v.831

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26