/[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 125 by bh, Thu May 2 18:55:33 2002 UTC revision 883 by jonathan, Fri May 9 16:34:39 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 129  class ZoomInTool(RectTool): Line 138  class ZoomInTool(RectTool):
138              Tool.MouseUp(self, event)              Tool.MouseUp(self, event)
139              sx, sy = self.start              sx, sy = self.start
140              cx, cy = self.current              cx, cy = self.current
141              if sx == cx and sy == cy:              if sx == cx or sy == cy:
142                  # Just a mouse click. Simply zoom in by a factor of two                  # Just a mouse click or a degenerate rectangle. Simply
143                    # zoom in by a factor of two
144                    # FIXME: For a click this is the desired behavior but should we
145                    # really do this for degenrate rectagles as well or
146                    # should we ignore them?
147                  self.view.ZoomFactor(2, center = (cx, cy))                  self.view.ZoomFactor(2, center = (cx, cy))
148              else:              else:
149                  # A drag. Zoom in to the rectangle                  # A drag. Zoom in to the rectangle
# Line 140  class ZoomInTool(RectTool): Line 153  class ZoomInTool(RectTool):
153  class ZoomOutTool(RectTool):  class ZoomOutTool(RectTool):
154    
155      """The Zoom-Out Tool"""      """The Zoom-Out Tool"""
156        
157      def Name(self):      def Name(self):
158          return "ZoomOutTool"          return "ZoomOutTool"
159    
# Line 149  class ZoomOutTool(RectTool): Line 162  class ZoomOutTool(RectTool):
162              Tool.MouseUp(self, event)              Tool.MouseUp(self, event)
163              sx, sy = self.start              sx, sy = self.start
164              cx, cy = self.current              cx, cy = self.current
165              if sx == cx and sy == cy:              if sx == cx or sy == cy:
166                  # Just a mouse click. Simply zoom out by a factor of two                  # Just a mouse click or a degenerate rectangle. Simply
167                  self.view.ZoomFactor(0.5, center = (cy, cy))                  # zoom out by a factor of two.
168                    # FIXME: For a click this is the desired behavior but should we
169                    # really do this for degenrate rectagles as well or
170                    # should we ignore them?
171                    self.view.ZoomFactor(0.5, center = (cx, cy))
172              else:              else:
173                  # A drag. Zoom out to the rectangle                  # A drag. Zoom out to the rectangle
174                  self.view.ZoomOutToRect((min(sx, cx), min(sy, cy),                  self.view.ZoomOutToRect((min(sx, cx), min(sy, cy),
# Line 167  class PanTool(Tool): Line 184  class PanTool(Tool):
184    
185      def MouseMove(self, event):      def MouseMove(self, event):
186          if self.dragging:          if self.dragging:
             x0, y0 = self.current  
187              Tool.MouseMove(self, event)              Tool.MouseMove(self, event)
188                sx, sy = self.start
189              x, y = self.current              x, y = self.current
190              width, height = self.view.GetSizeTuple()              width, height = self.view.GetSizeTuple()
191    
192                bitmapdc = wx.wxMemoryDC()
193                bitmapdc.SelectObject(self.view.bitmap)
194    
195              dc = self.view.drag_dc              dc = self.view.drag_dc
196              dc.Blit(0, 0, width, height, dc, x0 - x, y0 - y)              dc.Blit(0, 0, width, height, bitmapdc, sx - x, sy - y)
197    
198      def MouseUp(self, event):      def MouseUp(self, event):
199          if self.dragging:          if self.dragging:
# Line 180  class PanTool(Tool): Line 201  class PanTool(Tool):
201              sx, sy = self.start              sx, sy = self.start
202              cx, cy = self.current              cx, cy = self.current
203              self.view.Translate(cx - sx, cy - sy)              self.view.Translate(cx - sx, cy - sy)
204            
205  class IdentifyTool(Tool):  class IdentifyTool(Tool):
206    
207      """The "Identify" Tool"""      """The "Identify" Tool"""
208        
209      def Name(self):      def Name(self):
210          return "IdentifyTool"          return "IdentifyTool"
211    
# Line 238  class MapPrintout(wx.wxPrintout): Line 259  class MapPrintout(wx.wxPrintout):
259          renderer = PrinterRender(dc, scale, (offx, offy), resolution = resx)          renderer = PrinterRender(dc, scale, (offx, offy), resolution = resx)
260          renderer.RenderMap(self.map)          renderer.RenderMap(self.map)
261          return wx.true          return wx.true
262            
263    
264  class MapCanvas(wxWindow, Publisher):  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                             "SelectedShapes": "selection"}
284    
285        def __init__(self, parent, winid):
286          wxWindow.__init__(self, parent, winid)          wxWindow.__init__(self, parent, winid)
287          self.SetBackgroundColour(wxColour(255, 255, 255))          self.SetBackgroundColour(wxColour(255, 255, 255))
288    
# Line 267  class MapCanvas(wxWindow, Publisher): Line 305  class MapCanvas(wxWindow, Publisher):
305          # if the mouse is outside the window.          # if the mouse is outside the window.
306          self.current_position = None          self.current_position = None
307    
   
         # 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  
   
308          # the bitmap serving as backing store          # the bitmap serving as backing store
309          self.bitmap = None          self.bitmap = None
310    
311          # the interactor          # the selection
312          self.interactor = interactor          self.selection = Selection()
313          self.interactor.Subscribe(SELECTED_SHAPE, self.shape_selected)          self.selection.Subscribe(SHAPES_SELECTED , self.shape_selected)
314    
315            # keep track of which layers/shapes are selected to make sure we
316            # only redraw when necessary
317            self.last_selected_layer = None
318            self.last_selected_shape = None
319    
320          # subscribe the WX events we're interested in          # subscribe the WX events we're interested in
321          EVT_PAINT(self, self.OnPaint)          EVT_PAINT(self, self.OnPaint)
# Line 287  class MapCanvas(wxWindow, Publisher): Line 324  class MapCanvas(wxWindow, Publisher):
324          EVT_MOTION(self, self.OnMotion)          EVT_MOTION(self, self.OnMotion)
325          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)
326          wx.EVT_SIZE(self, self.OnSize)          wx.EVT_SIZE(self, self.OnSize)
         wx.EVT_IDLE(self, self.OnIdle)  
327    
328      def __del__(self):      def __del__(self):
329          wxWindow.__del__(self)          wxWindow.__del__(self)
330          Publisher.__del__(self)          Publisher.__del__(self)
331    
332        def Subscribe(self, channel, *args):
333            """Extend the inherited method to handle delegated messages.
334    
335            If channel is one of the delegated messages call the appropriate
336            object's Subscribe method. Otherwise just call the inherited
337            method.
338            """
339            if channel in self.delegated_messages:
340                object = getattr(self, self.delegated_messages[channel])
341                object.Subscribe(channel, *args)
342            else:
343                Publisher.Subscribe(self, channel, *args)
344    
345        def Unsubscribe(self, channel, *args):
346            """Extend the inherited method to handle delegated messages.
347    
348            If channel is one of the delegated messages call the appropriate
349            object's Unsubscribe method. Otherwise just call the inherited
350            method.
351            """
352            if channel in self.delegated_messages:
353                object = getattr(self, self.delegated_messages[channel])
354                object.Unsubscribe(channel, *args)
355            else:
356                Publisher.Unsubscribe(self, channel, *args)
357    
358        def __getattr__(self, attr):
359            if attr in self.delegated_methods:
360                return getattr(getattr(self, self.delegated_methods[attr]), attr)
361            raise AttributeError(attr)
362    
363      def OnPaint(self, event):      def OnPaint(self, event):
364          dc = wxPaintDC(self)          dc = wxPaintDC(self)
365          if self.map is not None and self.map.HasLayers():          clear = self.map is None or not self.map.HasLayers()
366              # We have a non-empty map. Redraw it in idle time  
367              self.redraw_on_idle = 1          #wxBeginBusyCursor()
368          else:  
369            if not clear:
370                try:
371                    self.do_redraw()
372                except:
373                    print "Error during drawing:", sys.exc_info()[0]
374                    clear = True
375    
376            if clear:
377              # 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
378              # the screen.              # the screen.
379                
380              # XXX it's probably possible to get rid of this. The              # XXX it's probably possible to get rid of this. The
381              # background color of the window is already white and the              # background color of the window is already white and the
382              # only thing we may have to do is to call self.Refresh()              # only thing we may have to do is to call self.Refresh()
383              # with a true argument in the right places.              # with a true argument in the right places.
384              dc.BeginDrawing()              dc.BeginDrawing()
385              dc.Clear()                          dc.Clear()
386              dc.EndDrawing()              dc.EndDrawing()
387    
388            #wxEndBusyCursor()
389    
390      def do_redraw(self):      def do_redraw(self):
391          # This should only be called if we have a non-empty map. We draw          # This should only be called if we have a non-empty map.
         # it into a memory DC and then blit it to the screen.  
392    
393            # Get the window size.
394          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
395    
396          # If self.bitmap's still there, reuse it. Otherwise redraw it          # If self.bitmap's still there, reuse it. Otherwise redraw it
# Line 326  class MapCanvas(wxWindow, Publisher): Line 403  class MapCanvas(wxWindow, Publisher):
403              dc.BeginDrawing()              dc.BeginDrawing()
404    
405              # clear the background              # clear the background
406              dc.SetBrush(wx.wxWHITE_BRUSH)              #dc.SetBrush(wx.wxWHITE_BRUSH)
407              dc.SetPen(wx.wxTRANSPARENT_PEN)              #dc.SetPen(wx.wxTRANSPARENT_PEN)
408              dc.DrawRectangle(0, 0, width, height)              #dc.DrawRectangle(0, 0, width, height)
409                dc.SetBackground(wx.wxWHITE_BRUSH)
410              if 1: #self.interactor.selected_map is self.map:              dc.Clear()
411                  selected_layer = self.interactor.selected_layer  
412                  selected_shape = self.interactor.selected_shape              selected_layer = self.selection.SelectedLayer()
413              else:              selected_shapes = self.selection.SelectedShapes()
                 selected_layer = None  
                 selected_shape = None  
414    
415              # draw the map into the bitmap              # draw the map into the bitmap
416              renderer = ScreenRenderer(dc, self.scale, self.offset)              renderer = ScreenRenderer(dc, self.scale, self.offset)
417              renderer.RenderMap(self.map, selected_layer, selected_shape)  
418                # Pass the entire bitmap as update region to the renderer.
419                # We're redrawing the whole bitmap, after all.
420                renderer.RenderMap(self.map, (0, 0, width, height),
421                                   selected_layer, selected_shapes)
422    
423              dc.EndDrawing()              dc.EndDrawing()
424              dc.SelectObject(wx.wxNullBitmap)              dc.SelectObject(wx.wxNullBitmap)
# Line 358  class MapCanvas(wxWindow, Publisher): Line 437  class MapCanvas(wxWindow, Publisher):
437          printout = MapPrintout(self.map)          printout = MapPrintout(self.map)
438          printer.Print(self, printout, wx.true)          printer.Print(self, printout, wx.true)
439          printout.Destroy()          printout.Destroy()
440            
441      def SetMap(self, map):      def SetMap(self, map):
442          redraw_channels = (LAYERS_CHANGED, LAYER_LEGEND_CHANGED,          redraw_channels = (MAP_LAYERS_CHANGED, LAYER_CHANGED,
443                             LAYER_VISIBILITY_CHANGED)                             LAYER_VISIBILITY_CHANGED)
444          if self.map is not None:          if self.map is not None:
445              for channel in redraw_channels:              for channel in redraw_channels:
# Line 368  class MapCanvas(wxWindow, Publisher): Line 447  class MapCanvas(wxWindow, Publisher):
447              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,
448                                   self.projection_changed)                                   self.projection_changed)
449          self.map = map          self.map = map
450            self.selection.ClearSelection()
451          if self.map is not None:          if self.map is not None:
452              for channel in redraw_channels:              for channel in redraw_channels:
453                  self.map.Subscribe(channel, self.full_redraw)                  self.map.Subscribe(channel, self.full_redraw)
# Line 379  class MapCanvas(wxWindow, Publisher): Line 459  class MapCanvas(wxWindow, Publisher):
459          self.full_redraw()          self.full_redraw()
460    
461      def Map(self):      def Map(self):
462            """Return the map displayed by this canvas"""
463          return self.map          return self.map
464    
465      def redraw(self, *args):      def redraw(self, *args):
# Line 396  class MapCanvas(wxWindow, Publisher): Line 477  class MapCanvas(wxWindow, Publisher):
477          self.scale = scale          self.scale = scale
478          self.offset = offset          self.offset = offset
479          self.full_redraw()          self.full_redraw()
480            self.issue(SCALE_CHANGED, scale)
481    
482      def proj_to_win(self, x, y):      def proj_to_win(self, x, y):
483          """\          """\
# Line 412  class MapCanvas(wxWindow, Publisher): Line 494  class MapCanvas(wxWindow, Publisher):
494          return ((x - offx) / self.scale, (offy - y) / self.scale)          return ((x - offx) / self.scale, (offy - y) / self.scale)
495    
496      def FitRectToWindow(self, rect):      def FitRectToWindow(self, rect):
497            """Fit the rectangular region given by rect into the window.
498    
499            Set scale so that rect (in projected coordinates) just fits into
500            the window and center it.
501            """
502          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
503          llx, lly, urx, ury = rect          llx, lly, urx, ury = rect
504          if llx == urx or lly == ury:          if llx == urx or lly == ury:
505              # zero with or zero height. Do Nothing              # zero width or zero height. Do Nothing
506              return              return
507          scalex = width / (urx - llx)          scalex = width / (urx - llx)
508          scaley = height / (ury - lly)          scaley = height / (ury - lly)
# Line 425  class MapCanvas(wxWindow, Publisher): Line 512  class MapCanvas(wxWindow, Publisher):
512          self.set_view_transform(scale, (offx, offy))          self.set_view_transform(scale, (offx, offy))
513    
514      def FitMapToWindow(self):      def FitMapToWindow(self):
515          """\          """Fit the map to the window
516          Set the scale and offset so that the map is centered in the  
517          window          Set the scale so that the map fits exactly into the window and
518            center it in the window.
519          """          """
520          bbox = self.map.ProjectedBoundingBox()          bbox = self.map.ProjectedBoundingBox()
521          if bbox is not None:          if bbox is not None:
522              self.FitRectToWindow(bbox)              self.FitRectToWindow(bbox)
523    
524        def FitLayerToWindow(self, layer):
525            """Fit the given layer to the window.
526    
527            Set the scale so that the layer fits exactly into the window and
528            center it in the window.
529            """
530            
531            bbox = layer.LatLongBoundingBox()
532            if bbox is not None:
533                proj = self.map.GetProjection()
534                if proj is not None:
535                    bbox = proj.ForwardBBox(bbox)
536    
537                if bbox is not None:
538                    self.FitRectToWindow(bbox)
539    
540        def FitSelectedToWindow(self):
541            layer = self.selection.SelectedLayer()
542            shapes = self.selection.SelectedShapes()
543    
544            bbox = layer.ShapesBoundingBox(shapes)
545            if bbox is not None:
546                proj = self.map.GetProjection()
547                if proj is not None:
548                    bbox = proj.ForwardBBox(bbox)
549    
550                if bbox is not None:
551                    self.FitRectToWindow(bbox)
552    
553      def ZoomFactor(self, factor, center = None):      def ZoomFactor(self, factor, center = None):
554          """Multiply the zoom by factor and center on center.          """Multiply the zoom by factor and center on center.
555    
# Line 453  class MapCanvas(wxWindow, Publisher): Line 570  class MapCanvas(wxWindow, Publisher):
570          self.set_view_transform(scale, offset)          self.set_view_transform(scale, offset)
571    
572      def ZoomOutToRect(self, rect):      def ZoomOutToRect(self, rect):
573          # rect is given in window coordinates          """Zoom out to fit the currently visible region into rect.
574    
575            The rect parameter is given in window coordinates
576            """
577          # determine the bbox of the displayed region in projected          # determine the bbox of the displayed region in projected
578          # coordinates          # coordinates
579          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
# Line 471  class MapCanvas(wxWindow, Publisher): Line 590  class MapCanvas(wxWindow, Publisher):
590          self.set_view_transform(scale, (offx, offy))          self.set_view_transform(scale, (offx, offy))
591    
592      def Translate(self, dx, dy):      def Translate(self, dx, dy):
593            """Move the map by dx, dy pixels"""
594          offx, offy = self.offset          offx, offy = self.offset
595          self.set_view_transform(self.scale, (offx + dx, offy + dy))          self.set_view_transform(self.scale, (offx + dx, offy + dy))
596    
597        def SelectTool(self, tool):
598            """Make tool the active tool.
599    
600            The parameter should be an instance of Tool or None to indicate
601            that no tool is active.
602            """
603            self.tool = tool
604    
605      def ZoomInTool(self):      def ZoomInTool(self):
606          self.tool = ZoomInTool(self)          """Start the zoom in tool"""
607            self.SelectTool(ZoomInTool(self))
608    
609      def ZoomOutTool(self):      def ZoomOutTool(self):
610          self.tool = ZoomOutTool(self)          """Start the zoom out tool"""
611            self.SelectTool(ZoomOutTool(self))
612    
613      def PanTool(self):      def PanTool(self):
614          self.tool = PanTool(self)          """Start the pan tool"""
615            self.SelectTool(PanTool(self))
616            #img = resource.GetImageResource("pan", wxBITMAP_TYPE_XPM)
617            #bmp = resource.GetBitmapResource("pan", wxBITMAP_TYPE_XPM)
618            #print bmp
619            #img = wxImageFromBitmap(bmp)
620            #print img
621            #cur = wxCursor(img)
622            #print cur
623            #self.SetCursor(cur)
624    
625      def IdentifyTool(self):      def IdentifyTool(self):
626          self.tool = IdentifyTool(self)          """Start the identify tool"""
627            self.SelectTool(IdentifyTool(self))
628    
629      def LabelTool(self):      def LabelTool(self):
630          self.tool = LabelTool(self)          """Start the label tool"""
631            self.SelectTool(LabelTool(self))
632    
633      def CurrentTool(self):      def CurrentTool(self):
634            """Return the name of the current tool or None if no tool is active"""
635          return self.tool and self.tool.Name() or None          return self.tool and self.tool.Name() or None
636    
637      def CurrentPosition(self):      def CurrentPosition(self):
# Line 527  class MapCanvas(wxWindow, Publisher): Line 669  class MapCanvas(wxWindow, Publisher):
669              self.tool.MouseDown(event)              self.tool.MouseDown(event)
670              self.tool.Show(self.drag_dc)              self.tool.Show(self.drag_dc)
671              self.dragging = 1              self.dragging = 1
672            
673      def OnLeftUp(self, event):      def OnLeftUp(self, event):
         self.ReleaseMouse()  
674          self.set_current_position(event)          self.set_current_position(event)
675          if self.dragging:          if self.dragging:
676              self.tool.Hide(self.drag_dc)              self.ReleaseMouse()
677              self.tool.MouseUp(event)              try:
678              self.drag_dc = None                  self.tool.Hide(self.drag_dc)
679          self.dragging = 0                  self.tool.MouseUp(event)
680                finally:
681                    self.drag_dc = None
682                    self.dragging = 0
683    
684      def OnMotion(self, event):      def OnMotion(self, event):
685          self.set_current_position(event)          self.set_current_position(event)
# Line 547  class MapCanvas(wxWindow, Publisher): Line 691  class MapCanvas(wxWindow, Publisher):
691      def OnLeaveWindow(self, event):      def OnLeaveWindow(self, event):
692          self.set_current_position(None)          self.set_current_position(None)
693    
     def OnIdle(self, event):  
         if self.redraw_on_idle:  
             self.do_redraw()  
         self.redraw_on_idle = 0  
   
694      def OnSize(self, event):      def OnSize(self, event):
695          # 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
696          # 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 560  class MapCanvas(wxWindow, Publisher): Line 699  class MapCanvas(wxWindow, Publisher):
699          # Even when the window becomes larger some parts of the bitmap          # Even when the window becomes larger some parts of the bitmap
700          # could be reused.          # could be reused.
701          self.full_redraw()          self.full_redraw()
702            pass
703    
704      def shape_selected(self, layer, shape):      def shape_selected(self, layer, shape):
705            """Receiver for the SHAPES_SELECTED messages. Redraw the map."""
706            # The selection object takes care that it only issues
707            # SHAPES_SELECTED messages when the set of selected shapes has
708            # actually changed, so we can do a full redraw unconditionally.
709            # FIXME: We should perhaps try to limit the redraw to the are
710            # actually covered by the shapes before and after the selection
711            # change.
712          self.full_redraw()          self.full_redraw()
713    
714      def find_shape_at(self, px, py, select_labels = 0, selected_layer = 1):      def unprojected_rect_around_point(self, x, y, dist):
715            """return a rect dist pixels around (x, y) in unprojected corrdinates
716    
717            The return value is a tuple (minx, miny, maxx, maxy) suitable a
718            parameter to a layer's ShapesInRegion method.
719            """
720            map_proj = self.map.projection
721            if map_proj is not None:
722                inverse = map_proj.Inverse
723            else:
724                inverse = None
725    
726            xs = []
727            ys = []
728            for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
729                px, py = self.win_to_proj(x + dist * dx, y + dist * dy)
730                if inverse:
731                    px, py = inverse(px, py)
732                xs.append(px)
733                ys.append(py)
734            return (min(xs), min(ys), max(xs), max(ys))
735    
736        def find_shape_at(self, px, py, select_labels = 0, searched_layer = None):
737          """Determine the shape at point px, py in window coords          """Determine the shape at point px, py in window coords
738    
739          Return the shape and the corresponding layer as a tuple (layer,          Return the shape and the corresponding layer as a tuple (layer,
# Line 574  class MapCanvas(wxWindow, Publisher): Line 743  class MapCanvas(wxWindow, Publisher):
743          search through the labels. If a label is found return it's index          search through the labels. If a label is found return it's index
744          as the shape and None as the layer.          as the shape and None as the layer.
745    
746          If the optional parameter selected_layer is true (default), only          If the optional parameter searched_layer is given (or not None
747          search in the currently selected layer.          which it defaults to), only search in that layer.
748          """          """
749          map_proj = self.map.projection          map_proj = self.map.projection
750          if map_proj is not None:          if map_proj is not None:
# Line 588  class MapCanvas(wxWindow, Publisher): Line 757  class MapCanvas(wxWindow, Publisher):
757    
758          if select_labels:          if select_labels:
759              labels = self.map.LabelLayer().Labels()              labels = self.map.LabelLayer().Labels()
760                
761              if labels:              if labels:
762                  dc = wxClientDC(self)                  dc = wxClientDC(self)
763                  font = wxFont(10, wx.wxSWISS, wx.wxNORMAL, wx.wxNORMAL)                  font = wxFont(10, wx.wxSWISS, wx.wxNORMAL, wx.wxNORMAL)
# Line 620  class MapCanvas(wxWindow, Publisher): Line 789  class MapCanvas(wxWindow, Publisher):
789                      if x <= px < x + width and y <= py <= y + height:                      if x <= px < x + width and y <= py <= y + height:
790                          return None, i                          return None, i
791    
792          if selected_layer:          if searched_layer:
793              layer = self.interactor.SelectedLayer()              layers = [searched_layer]
             if layer is not None:  
                 layers = [layer]  
             else:  
                 # no layer selected. Use an empty list to effectively  
                 # ignore all layers.  
                 layers = []  
794          else:          else:
795              layers = self.map.Layers()              layers = self.map.Layers()
796    
# Line 638  class MapCanvas(wxWindow, Publisher): Line 801  class MapCanvas(wxWindow, Publisher):
801              if not layer.Visible():              if not layer.Visible():
802                  continue                  continue
803    
804              filled = layer.fill is not None              filled = layer.GetClassification().GetDefaultFill() \
805              stroked = layer.stroke is not None                       is not Color.Transparent
806                                stroked = layer.GetClassification().GetDefaultLineColor() \
807                          is not Color.Transparent
808    
809              layer_proj = layer.projection              layer_proj = layer.projection
810              if layer_proj is not None:              if layer_proj is not None:
811                  inverse = layer_proj.Inverse                  inverse = layer_proj.Inverse
812              else:              else:
813                  inverse = None                  inverse = None
814                    
815              shapetype = layer.ShapeType()              shapetype = layer.ShapeType()
816    
817              select_shape = -1              select_shape = -1
818    
819                # Determine the ids of the shapes that overlap a tiny area
820                # around the point. For layers containing points we have to
821                # choose a larger size of the box we're testing agains so
822                # that we take the size of the markers into account
823                # FIXME: Once the markers are more flexible this part has to
824                # become more flexible too, of course
825                if shapetype == SHAPETYPE_POINT:
826                    box = self.unprojected_rect_around_point(px, py, 5)
827                else:
828                    box = self.unprojected_rect_around_point(px, py, 1)
829                shape_ids = layer.ShapesInRegion(box)
830                shape_ids.reverse()
831    
832              if shapetype == SHAPETYPE_POLYGON:              if shapetype == SHAPETYPE_POLYGON:
833                  for i in range(layer.NumShapes() - 1, -1, -1):                  for i in shape_ids:
834                      result = point_in_polygon_shape(layer.shapefile.cobject(),                      result = point_in_polygon_shape(layer.shapefile.cobject(),
835                                                      i,                                                      i,
836                                                      filled, stroked,                                                      filled, stroked,
# Line 662  class MapCanvas(wxWindow, Publisher): Line 841  class MapCanvas(wxWindow, Publisher):
841                          select_shape = i                          select_shape = i
842                          break                          break
843              elif shapetype == SHAPETYPE_ARC:              elif shapetype == SHAPETYPE_ARC:
844                  for i in range(layer.NumShapes() - 1, -1, -1):                  for i in shape_ids:
845                      result = point_in_polygon_shape(layer.shapefile.cobject(),                      result = point_in_polygon_shape(layer.shapefile.cobject(),
846                                                      i, 0, 1,                                                      i, 0, 1,
847                                                      map_proj, layer_proj,                                                      map_proj, layer_proj,
# Line 672  class MapCanvas(wxWindow, Publisher): Line 851  class MapCanvas(wxWindow, Publisher):
851                          select_shape = i                          select_shape = i
852                          break                          break
853              elif shapetype == SHAPETYPE_POINT:              elif shapetype == SHAPETYPE_POINT:
854                  for i in range(layer.NumShapes() - 1, -1, -1):                  for i in shape_ids:
855                      shape = layer.Shape(i)                      shape = layer.Shape(i)
856                      x, y = shape.Points()[0]                      x, y = shape.Points()[0]
857                      if inverse:                      if inverse:
# Line 689  class MapCanvas(wxWindow, Publisher): Line 868  class MapCanvas(wxWindow, Publisher):
868                  return layer, select_shape                  return layer, select_shape
869          return None, None          return None, None
870    
871      def SelectShapeAt(self, x, y):      def SelectShapeAt(self, x, y, layer = None):
872          layer, shape = self.find_shape_at(x, y, selected_layer = 0)          """\
873            Select and return the shape and its layer at window position (x, y)
874    
875            If layer is given, only search in that layer. If no layer is
876            given, search through all layers.
877    
878            Return a tuple (layer, shapeid). If no shape is found, return
879            (None, None).
880            """
881            layer, shape = result = self.find_shape_at(x, y, searched_layer=layer)
882          # If layer is None, then shape will also be None. We don't want          # If layer is None, then shape will also be None. We don't want
883          # to deselect the currently selected layer, so we simply select          # to deselect the currently selected layer, so we simply select
884          # the already selected layer again.          # the already selected layer again.
885          if layer is None:          if layer is None:
886              layer = self.interactor.SelectedLayer()              layer = self.selection.SelectedLayer()
887          self.interactor.SelectLayerAndShape(layer, shape)              shapes = []
888            else:
889                shapes = [shape]
890            self.selection.SelectShapes(layer, shapes)
891            return result
892    
893      def LabelShapeAt(self, x, y):      def LabelShapeAt(self, x, y):
894            """Add or remove a label at window position x, y.
895    
896            If there's a label at the given position, remove it. Otherwise
897            determine the shape at the position, run the label dialog and
898            unless the user cancels the dialog, add a laber.
899            """
900          ox = x; oy = y          ox = x; oy = y
901          label_layer = self.map.LabelLayer()          label_layer = self.map.LabelLayer()
902          layer, shape_index = self.find_shape_at(x, y, select_labels = 1)          layer, shape_index = self.find_shape_at(x, y, select_labels = 1)

Legend:
Removed from v.125  
changed lines
  Added in v.883

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26