/[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 855 by frank, Wed May 7 18:24:27 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                         SCALE_CHANGED
48    
49    
50  #  #
# Line 256  class MapCanvas(wxWindow, Publisher): Line 265  class MapCanvas(wxWindow, Publisher):
265    
266      """A widget that displays a map and offers some interaction"""      """A widget that displays a map and offers some interaction"""
267    
268      def __init__(self, parent, winid, interactor):      # Some messages that can be subscribed/unsubscribed directly through
269        # the MapCanvas come in fact from other objects. This is a dict
270        # mapping those messages to the names of the instance variables they
271        # actually come from. The delegation is implemented in the Subscribe
272        # and Unsubscribe methods
273        delegated_messages = {LAYER_SELECTED: "selection",
274                              SHAPES_SELECTED: "selection"}
275    
276        # Methods delegated to some instance variables. The delegation is
277        # implemented in the __getattr__ method.
278        delegated_methods = {"SelectLayer": "selection",
279                             "SelectShapes": "selection",
280                             "SelectedLayer": "selection",
281                             "HasSelectedLayer": "selection",
282                             "HasSelectedShapes": "selection"}
283    
284        def __init__(self, parent, winid):
285          wxWindow.__init__(self, parent, winid)          wxWindow.__init__(self, parent, winid)
286          self.SetBackgroundColour(wxColour(255, 255, 255))          self.SetBackgroundColour(wxColour(255, 255, 255))
287    
# Line 279  class MapCanvas(wxWindow, Publisher): Line 304  class MapCanvas(wxWindow, Publisher):
304          # if the mouse is outside the window.          # if the mouse is outside the window.
305          self.current_position = None          self.current_position = None
306    
         # 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  
   
307          # the bitmap serving as backing store          # the bitmap serving as backing store
308          self.bitmap = None          self.bitmap = None
309    
310          # the interactor          # the selection
311          self.interactor = interactor          self.selection = Selection()
312          self.interactor.Subscribe(SELECTED_SHAPE, self.shape_selected)          self.selection.Subscribe(SHAPES_SELECTED , self.shape_selected)
313    
314          # keep track of which layers/shapes are selected to make sure we          # keep track of which layers/shapes are selected to make sure we
315          # only redraw when necessary          # only redraw when necessary
# Line 303  class MapCanvas(wxWindow, Publisher): Line 323  class MapCanvas(wxWindow, Publisher):
323          EVT_MOTION(self, self.OnMotion)          EVT_MOTION(self, self.OnMotion)
324          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)
325          wx.EVT_SIZE(self, self.OnSize)          wx.EVT_SIZE(self, self.OnSize)
         wx.EVT_IDLE(self, self.OnIdle)  
326    
327      def __del__(self):      def __del__(self):
328          wxWindow.__del__(self)          wxWindow.__del__(self)
329          Publisher.__del__(self)          Publisher.__del__(self)
330    
331        def Subscribe(self, channel, *args):
332            """Extend the inherited method to handle delegated messages.
333    
334            If channel is one of the delegated messages call the appropriate
335            object's Subscribe method. Otherwise just call the inherited
336            method.
337            """
338            if channel in self.delegated_messages:
339                object = getattr(self, self.delegated_messages[channel])
340                object.Subscribe(channel, *args)
341            else:
342                Publisher.Subscribe(self, channel, *args)
343    
344        def Unsubscribe(self, channel, *args):
345            """Extend the inherited method to handle delegated messages.
346    
347            If channel is one of the delegated messages call the appropriate
348            object's Unsubscribe method. Otherwise just call the inherited
349            method.
350            """
351            if channel in self.delegated_messages:
352                object = getattr(self, self.delegated_messages[channel])
353                object.Unsubscribe(channel, *args)
354            else:
355                Publisher.Unsubscribe(self, channel, *args)
356    
357        def __getattr__(self, attr):
358            if attr in self.delegated_methods:
359                return getattr(getattr(self, self.delegated_methods[attr]), attr)
360            raise AttributeError(attr)
361    
362      def OnPaint(self, event):      def OnPaint(self, event):
363          dc = wxPaintDC(self)          dc = wxPaintDC(self)
364          if self.map is not None and self.map.HasLayers():          clear = self.map is None or not self.map.HasLayers()
365              # We have a non-empty map. Redraw it in idle time  
366              self.redraw_on_idle = 1          #wxBeginBusyCursor()
367          else:  
368            if not clear:
369                try:
370                    self.do_redraw()
371                except:
372                    print "Error during drawing:", sys.exc_info()[0]
373                    clear = True
374    
375            if clear:
376              # 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
377              # the screen.              # the screen.
378    
# Line 326  class MapCanvas(wxWindow, Publisher): Line 384  class MapCanvas(wxWindow, Publisher):
384              dc.Clear()              dc.Clear()
385              dc.EndDrawing()              dc.EndDrawing()
386    
387            #wxEndBusyCursor()
388    
389      def do_redraw(self):      def do_redraw(self):
390          # This should only be called if we have a non-empty map.          # This should only be called if we have a non-empty map.
391    
# Line 342  class MapCanvas(wxWindow, Publisher): Line 402  class MapCanvas(wxWindow, Publisher):
402              dc.BeginDrawing()              dc.BeginDrawing()
403    
404              # clear the background              # clear the background
405              dc.SetBrush(wx.wxWHITE_BRUSH)              #dc.SetBrush(wx.wxWHITE_BRUSH)
406              dc.SetPen(wx.wxTRANSPARENT_PEN)              #dc.SetPen(wx.wxTRANSPARENT_PEN)
407              dc.DrawRectangle(0, 0, width, height)              #dc.DrawRectangle(0, 0, width, height)
408                dc.SetBackground(wx.wxWHITE_BRUSH)
409              if 1: #self.interactor.selected_map is self.map:              dc.Clear()
410                  selected_layer = self.interactor.selected_layer  
411                  selected_shape = self.interactor.selected_shape              selected_layer = self.selection.SelectedLayer()
412              else:              selected_shapes = self.selection.SelectedShapes()
                 selected_layer = None  
                 selected_shape = None  
413    
414              # draw the map into the bitmap              # draw the map into the bitmap
415              renderer = ScreenRenderer(dc, self.scale, self.offset)              renderer = ScreenRenderer(dc, self.scale, self.offset)
# Line 359  class MapCanvas(wxWindow, Publisher): Line 417  class MapCanvas(wxWindow, Publisher):
417              # Pass the entire bitmap as update region to the renderer.              # Pass the entire bitmap as update region to the renderer.
418              # We're redrawing the whole bitmap, after all.              # We're redrawing the whole bitmap, after all.
419              renderer.RenderMap(self.map, (0, 0, width, height),              renderer.RenderMap(self.map, (0, 0, width, height),
420                                 selected_layer, selected_shape)                                 selected_layer, selected_shapes)
421    
422              dc.EndDrawing()              dc.EndDrawing()
423              dc.SelectObject(wx.wxNullBitmap)              dc.SelectObject(wx.wxNullBitmap)
# Line 380  class MapCanvas(wxWindow, Publisher): Line 438  class MapCanvas(wxWindow, Publisher):
438          printout.Destroy()          printout.Destroy()
439    
440      def SetMap(self, map):      def SetMap(self, map):
441          redraw_channels = (LAYERS_CHANGED, LAYER_LEGEND_CHANGED,          redraw_channels = (MAP_LAYERS_CHANGED, LAYER_CHANGED,
442                             LAYER_VISIBILITY_CHANGED)                             LAYER_VISIBILITY_CHANGED)
443          if self.map is not None:          if self.map is not None:
444              for channel in redraw_channels:              for channel in redraw_channels:
# Line 388  class MapCanvas(wxWindow, Publisher): Line 446  class MapCanvas(wxWindow, Publisher):
446              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,
447                                   self.projection_changed)                                   self.projection_changed)
448          self.map = map          self.map = map
449            self.selection.ClearSelection()
450          if self.map is not None:          if self.map is not None:
451              for channel in redraw_channels:              for channel in redraw_channels:
452                  self.map.Subscribe(channel, self.full_redraw)                  self.map.Subscribe(channel, self.full_redraw)
# Line 417  class MapCanvas(wxWindow, Publisher): Line 476  class MapCanvas(wxWindow, Publisher):
476          self.scale = scale          self.scale = scale
477          self.offset = offset          self.offset = offset
478          self.full_redraw()          self.full_redraw()
479            self.issue(SCALE_CHANGED, scale)
480    
481      def proj_to_win(self, x, y):      def proj_to_win(self, x, y):
482          """\          """\
# Line 434  class MapCanvas(wxWindow, Publisher): Line 494  class MapCanvas(wxWindow, Publisher):
494    
495      def FitRectToWindow(self, rect):      def FitRectToWindow(self, rect):
496          """Fit the rectangular region given by rect into the window.          """Fit the rectangular region given by rect into the window.
497            
498          Set scale so that rect (in projected coordinates) just fits into          Set scale so that rect (in projected coordinates) just fits into
499          the window and center it.          the window and center it.
500          """          """
501          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
502          llx, lly, urx, ury = rect          llx, lly, urx, ury = rect
503          if llx == urx or lly == ury:          if llx == urx or lly == ury:
504              # zero with or zero height. Do Nothing              # zero width or zero height. Do Nothing
505              return              return
506          scalex = width / (urx - llx)          scalex = width / (urx - llx)
507          scaley = height / (ury - lly)          scaley = height / (ury - lly)
# Line 452  class MapCanvas(wxWindow, Publisher): Line 512  class MapCanvas(wxWindow, Publisher):
512    
513      def FitMapToWindow(self):      def FitMapToWindow(self):
514          """Fit the map to the window          """Fit the map to the window
515            
516          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
517          center it in the window.          center it in the window.
518          """          """
# Line 460  class MapCanvas(wxWindow, Publisher): Line 520  class MapCanvas(wxWindow, Publisher):
520          if bbox is not None:          if bbox is not None:
521              self.FitRectToWindow(bbox)              self.FitRectToWindow(bbox)
522    
523        def FitLayerToWindow(self, layer):
524            """Fit the given layer to the window.
525    
526            Set the scale so that the layer fits exactly into the window and
527            center it in the window.
528            """
529            
530            bbox = layer.LatLongBoundingBox()
531            if bbox is not None:
532                proj = self.map.GetProjection()
533                if proj is not None:
534                    bbox = proj.ForwardBBox(bbox)
535    
536                if bbox is not None:
537                    self.FitRectToWindow(bbox)
538    
539        def FitSelectedToWindow(self):
540            layer = self.selection.SelectedLayer()
541            shapes = self.selection.SelectedShapes()
542    
543            bbox = layer.ShapesBoundingBox(shapes)
544            if bbox is not None:
545                proj = self.map.GetProjection()
546                if proj is not None:
547                    bbox = proj.ForwardBBox(bbox)
548    
549                if bbox is not None:
550                    self.FitRectToWindow(bbox)
551    
552      def ZoomFactor(self, factor, center = None):      def ZoomFactor(self, factor, center = None):
553          """Multiply the zoom by factor and center on center.          """Multiply the zoom by factor and center on center.
554    
# Line 504  class MapCanvas(wxWindow, Publisher): Line 593  class MapCanvas(wxWindow, Publisher):
593          offx, offy = self.offset          offx, offy = self.offset
594          self.set_view_transform(self.scale, (offx + dx, offy + dy))          self.set_view_transform(self.scale, (offx + dx, offy + dy))
595    
596        def SelectTool(self, tool):
597            """Make tool the active tool.
598    
599            The parameter should be an instance of Tool or None to indicate
600            that no tool is active.
601            """
602            self.tool = tool
603    
604      def ZoomInTool(self):      def ZoomInTool(self):
605          """Start the zoom in tool"""          """Start the zoom in tool"""
606          self.tool = ZoomInTool(self)          self.SelectTool(ZoomInTool(self))
607    
608      def ZoomOutTool(self):      def ZoomOutTool(self):
609          """Start the zoom out tool"""          """Start the zoom out tool"""
610          self.tool = ZoomOutTool(self)          self.SelectTool(ZoomOutTool(self))
611    
612      def PanTool(self):      def PanTool(self):
613          """Start the pan tool"""          """Start the pan tool"""
614          self.tool = PanTool(self)          self.SelectTool(PanTool(self))
615            #img = resource.GetImageResource("pan", wxBITMAP_TYPE_XPM)
616            #bmp = resource.GetBitmapResource("pan", wxBITMAP_TYPE_XPM)
617            #print bmp
618            #img = wxImageFromBitmap(bmp)
619            #print img
620            #cur = wxCursor(img)
621            #print cur
622            #self.SetCursor(cur)
623    
624      def IdentifyTool(self):      def IdentifyTool(self):
625          """Start the identify tool"""          """Start the identify tool"""
626          self.tool = IdentifyTool(self)          self.SelectTool(IdentifyTool(self))
627    
628      def LabelTool(self):      def LabelTool(self):
629          """Start the label tool"""          """Start the label tool"""
630          self.tool = LabelTool(self)          self.SelectTool(LabelTool(self))
631    
632      def CurrentTool(self):      def CurrentTool(self):
633          """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 673  class MapCanvas(wxWindow, Publisher):
673          self.set_current_position(event)          self.set_current_position(event)
674          if self.dragging:          if self.dragging:
675              self.ReleaseMouse()              self.ReleaseMouse()
676              self.tool.Hide(self.drag_dc)              try:
677              self.tool.MouseUp(event)                  self.tool.Hide(self.drag_dc)
678              self.drag_dc = None                  self.tool.MouseUp(event)
679          self.dragging = 0              finally:
680                    self.drag_dc = None
681                    self.dragging = 0
682    
683      def OnMotion(self, event):      def OnMotion(self, event):
684          self.set_current_position(event)          self.set_current_position(event)
# Line 583  class MapCanvas(wxWindow, Publisher): Line 690  class MapCanvas(wxWindow, Publisher):
690      def OnLeaveWindow(self, event):      def OnLeaveWindow(self, event):
691          self.set_current_position(None)          self.set_current_position(None)
692    
     def OnIdle(self, event):  
         if self.redraw_on_idle:  
             self.do_redraw()  
         self.redraw_on_idle = 0  
   
693      def OnSize(self, event):      def OnSize(self, event):
694          # 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
695          # 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 698  class MapCanvas(wxWindow, Publisher):
698          # Even when the window becomes larger some parts of the bitmap          # Even when the window becomes larger some parts of the bitmap
699          # could be reused.          # could be reused.
700          self.full_redraw()          self.full_redraw()
701            pass
702    
703      def shape_selected(self, layer, shape):      def shape_selected(self, layer, shape):
704          """Redraw the map.          """Receiver for the SHAPES_SELECTED messages. Redraw the map."""
705            # The selection object takes care that it only issues
706          Receiver for the SELECTED_SHAPE messages. Try to redraw only          # SHAPES_SELECTED messages when the set of selected shapes has
707          when necessary.          # actually changed, so we can do a full redraw unconditionally.
708          """          # FIXME: We should perhaps try to limit the redraw to the are
709          # A redraw is necessary when the display has to change, which          # actually covered by the shapes before and after the selection
710          # means that either the status changes from having no selection          # change.
711          # 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  
712    
713      def unprojected_rect_around_point(self, x, y):      def unprojected_rect_around_point(self, x, y, dist):
714          """return a rect a few pixels around (x, y) in unprojected corrdinates          """return a rect dist pixels around (x, y) in unprojected corrdinates
715    
716          The return value is a tuple (minx, miny, maxx, maxy) suitable a          The return value is a tuple (minx, miny, maxx, maxy) suitable a
717          parameter to a layer's ShapesInRegion method.          parameter to a layer's ShapesInRegion method.
# Line 633  class MapCanvas(wxWindow, Publisher): Line 725  class MapCanvas(wxWindow, Publisher):
725          xs = []          xs = []
726          ys = []          ys = []
727          for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):          for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
728              px, py = self.win_to_proj(x + dx, y + dy)              px, py = self.win_to_proj(x + dist * dx, y + dist * dy)
729              if inverse:              if inverse:
730                  px, py = inverse(px, py)                  px, py = inverse(px, py)
731              xs.append(px)              xs.append(px)
# Line 662  class MapCanvas(wxWindow, Publisher): Line 754  class MapCanvas(wxWindow, Publisher):
754          scale = self.scale          scale = self.scale
755          offx, offy = self.offset          offx, offy = self.offset
756    
         box = self.unprojected_rect_around_point(px, py)  
   
757          if select_labels:          if select_labels:
758              labels = self.map.LabelLayer().Labels()              labels = self.map.LabelLayer().Labels()
759    
# Line 710  class MapCanvas(wxWindow, Publisher): Line 800  class MapCanvas(wxWindow, Publisher):
800              if not layer.Visible():              if not layer.Visible():
801                  continue                  continue
802    
803              filled = layer.fill is not None              filled = layer.GetClassification().GetDefaultFill() \
804              stroked = layer.stroke is not None                       is not Color.Transparent
805                stroked = layer.GetClassification().GetDefaultLineColor() \
806                          is not Color.Transparent
807    
808              layer_proj = layer.projection              layer_proj = layer.projection
809              if layer_proj is not None:              if layer_proj is not None:
# Line 723  class MapCanvas(wxWindow, Publisher): Line 815  class MapCanvas(wxWindow, Publisher):
815    
816              select_shape = -1              select_shape = -1
817    
818                # Determine the ids of the shapes that overlap a tiny area
819                # around the point. For layers containing points we have to
820                # choose a larger size of the box we're testing agains so
821                # that we take the size of the markers into account
822                # FIXME: Once the markers are more flexible this part has to
823                # become more flexible too, of course
824                if shapetype == SHAPETYPE_POINT:
825                    box = self.unprojected_rect_around_point(px, py, 5)
826                else:
827                    box = self.unprojected_rect_around_point(px, py, 1)
828              shape_ids = layer.ShapesInRegion(box)              shape_ids = layer.ShapesInRegion(box)
829              shape_ids.reverse()              shape_ids.reverse()
830    
# Line 780  class MapCanvas(wxWindow, Publisher): Line 882  class MapCanvas(wxWindow, Publisher):
882          # to deselect the currently selected layer, so we simply select          # to deselect the currently selected layer, so we simply select
883          # the already selected layer again.          # the already selected layer again.
884          if layer is None:          if layer is None:
885              layer = self.interactor.SelectedLayer()              layer = self.selection.SelectedLayer()
886          self.interactor.SelectLayerAndShape(layer, shape)              shapes = []
887            else:
888                shapes = [shape]
889            self.selection.SelectShapes(layer, shapes)
890          return result          return result
891    
892      def LabelShapeAt(self, x, y):      def LabelShapeAt(self, x, y):

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26