/[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 176 by bh, Wed May 15 13:38:49 2002 UTC revision 822 by jonathan, Mon May 5 18:20:28 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 129  class ZoomInTool(RectTool): Line 137  class ZoomInTool(RectTool):
137              Tool.MouseUp(self, event)              Tool.MouseUp(self, event)
138              sx, sy = self.start              sx, sy = self.start
139              cx, cy = self.current              cx, cy = self.current
140              if sx == cx and sy == cy:              if sx == cx or sy == cy:
141                  # Just a mouse click. Simply zoom in by a factor of two                  # Just a mouse click or a degenerate rectangle. Simply
142                    # zoom in by a factor of two
143                    # FIXME: For a click this is the desired behavior but should we
144                    # really do this for degenrate rectagles as well or
145                    # should we ignore them?
146                  self.view.ZoomFactor(2, center = (cx, cy))                  self.view.ZoomFactor(2, center = (cx, cy))
147              else:              else:
148                  # A drag. Zoom in to the rectangle                  # A drag. Zoom in to the rectangle
# Line 140  class ZoomInTool(RectTool): Line 152  class ZoomInTool(RectTool):
152  class ZoomOutTool(RectTool):  class ZoomOutTool(RectTool):
153    
154      """The Zoom-Out Tool"""      """The Zoom-Out Tool"""
155        
156      def Name(self):      def Name(self):
157          return "ZoomOutTool"          return "ZoomOutTool"
158    
# Line 149  class ZoomOutTool(RectTool): Line 161  class ZoomOutTool(RectTool):
161              Tool.MouseUp(self, event)              Tool.MouseUp(self, event)
162              sx, sy = self.start              sx, sy = self.start
163              cx, cy = self.current              cx, cy = self.current
164              if sx == cx and sy == cy:              if sx == cx or sy == cy:
165                  # Just a mouse click. Simply zoom out by a factor of two                  # Just a mouse click or a degenerate rectangle. Simply
166                  self.view.ZoomFactor(0.5, center = (cy, cy))                  # zoom out by a factor of two.
167                    # FIXME: For a click this is the desired behavior but should we
168                    # really do this for degenrate rectagles as well or
169                    # should we ignore them?
170                    self.view.ZoomFactor(0.5, center = (cx, cy))
171              else:              else:
172                  # A drag. Zoom out to the rectangle                  # A drag. Zoom out to the rectangle
173                  self.view.ZoomOutToRect((min(sx, cx), min(sy, cy),                  self.view.ZoomOutToRect((min(sx, cx), min(sy, cy),
# Line 184  class PanTool(Tool): Line 200  class PanTool(Tool):
200              sx, sy = self.start              sx, sy = self.start
201              cx, cy = self.current              cx, cy = self.current
202              self.view.Translate(cx - sx, cy - sy)              self.view.Translate(cx - sx, cy - sy)
203            
204  class IdentifyTool(Tool):  class IdentifyTool(Tool):
205    
206      """The "Identify" Tool"""      """The "Identify" Tool"""
207        
208      def Name(self):      def Name(self):
209          return "IdentifyTool"          return "IdentifyTool"
210    
# Line 242  class MapPrintout(wx.wxPrintout): Line 258  class MapPrintout(wx.wxPrintout):
258          renderer = PrinterRender(dc, scale, (offx, offy), resolution = resx)          renderer = PrinterRender(dc, scale, (offx, offy), resolution = resx)
259          renderer.RenderMap(self.map)          renderer.RenderMap(self.map)
260          return wx.true          return wx.true
261            
262    
263  class MapCanvas(wxWindow, Publisher):  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    
282        def __init__(self, parent, winid):
283          wxWindow.__init__(self, parent, winid)          wxWindow.__init__(self, parent, winid)
284          self.SetBackgroundColour(wxColour(255, 255, 255))          self.SetBackgroundColour(wxColour(255, 255, 255))
285    
# Line 271  class MapCanvas(wxWindow, Publisher): Line 302  class MapCanvas(wxWindow, Publisher):
302          # if the mouse is outside the window.          # if the mouse is outside the window.
303          self.current_position = None          self.current_position = None
304    
         # 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  
   
         # The region to update when idle  
         self.update_region = wx.wxRegion()  
   
305          # the bitmap serving as backing store          # the bitmap serving as backing store
306          self.bitmap = None          self.bitmap = None
307    
308          # the interactor          # the selection
309          self.interactor = interactor          self.selection = Selection()
310          self.interactor.Subscribe(SELECTED_SHAPE, self.shape_selected)          self.selection.Subscribe(SHAPES_SELECTED , self.shape_selected)
311    
312          # keep track of which layers/shapes are selected to make sure we          # keep track of which layers/shapes are selected to make sure we
313          # only redraw when necessary          # only redraw when necessary
# Line 298  class MapCanvas(wxWindow, Publisher): Line 321  class MapCanvas(wxWindow, Publisher):
321          EVT_MOTION(self, self.OnMotion)          EVT_MOTION(self, self.OnMotion)
322          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)
323          wx.EVT_SIZE(self, self.OnSize)          wx.EVT_SIZE(self, self.OnSize)
         wx.EVT_IDLE(self, self.OnIdle)  
324    
325      def __del__(self):      def __del__(self):
326          wxWindow.__del__(self)          wxWindow.__del__(self)
327          Publisher.__del__(self)          Publisher.__del__(self)
328    
329        def Subscribe(self, channel, *args):
330            """Extend the inherited method to handle delegated messages.
331    
332            If channel is one of the delegated messages call the appropriate
333            object's Subscribe method. Otherwise just call the inherited
334            method.
335            """
336            if channel in self.delegated_messages:
337                object = getattr(self, self.delegated_messages[channel])
338                object.Subscribe(channel, *args)
339            else:
340                Publisher.Subscribe(self, channel, *args)
341    
342        def Unsubscribe(self, channel, *args):
343            """Extend the inherited method to handle delegated messages.
344    
345            If channel is one of the delegated messages call the appropriate
346            object's Unsubscribe method. Otherwise just call the inherited
347            method.
348            """
349            if channel in self.delegated_messages:
350                object = getattr(self, self.delegated_messages[channel])
351                object.Unsubscribe(channel, *args)
352            else:
353                Publisher.Unsubscribe(self, channel, *args)
354    
355        def __getattr__(self, attr):
356            if attr in self.delegated_methods:
357                return getattr(getattr(self, self.delegated_methods[attr]), attr)
358            raise AttributeError(attr)
359    
360      def OnPaint(self, event):      def OnPaint(self, event):
361          dc = wxPaintDC(self)          dc = wxPaintDC(self)
362          if self.map is not None and self.map.HasLayers():          clear = self.map is None or not self.map.HasLayers()
363              # We have a non-empty map. Redraw it in idle time  
364              self.redraw_on_idle = 1          #wxBeginBusyCursor()
365              # update the region that has to be redrawn  
366              self.update_region.UnionRegion(self.GetUpdateRegion())          if not clear:
367          else:              try:
368                    self.do_redraw()
369                except:
370                    print "Error during drawing:", sys.exc_info()[0]
371                    clear = True
372    
373            if clear:
374              # 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
375              # the screen.              # the screen.
376                
377              # XXX it's probably possible to get rid of this. The              # XXX it's probably possible to get rid of this. The
378              # background color of the window is already white and the              # background color of the window is already white and the
379              # only thing we may have to do is to call self.Refresh()              # only thing we may have to do is to call self.Refresh()
380              # with a true argument in the right places.              # with a true argument in the right places.
381              dc.BeginDrawing()              dc.BeginDrawing()
382              dc.Clear()                          dc.Clear()
383              dc.EndDrawing()              dc.EndDrawing()
384    
385              # clear the region          #wxEndBusyCursor()
             self.update_region = wx.wxRegion()  
386    
387      def do_redraw(self):      def do_redraw(self):
388          # This should only be called if we have a non-empty map.          # This should only be called if we have a non-empty map.
389    
         # get the update region and reset it. We're not actually using  
         # it anymore, though.  
         update_box = self.update_region.GetBox()  
         self.update_region = wx.wxRegion()  
   
390          # Get the window size.          # Get the window size.
391          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
392    
# Line 347  class MapCanvas(wxWindow, Publisher): Line 400  class MapCanvas(wxWindow, Publisher):
400              dc.BeginDrawing()              dc.BeginDrawing()
401    
402              # clear the background              # clear the background
403              dc.SetBrush(wx.wxWHITE_BRUSH)              #dc.SetBrush(wx.wxWHITE_BRUSH)
404              dc.SetPen(wx.wxTRANSPARENT_PEN)              #dc.SetPen(wx.wxTRANSPARENT_PEN)
405              dc.DrawRectangle(0, 0, width, height)              #dc.DrawRectangle(0, 0, width, height)
406                dc.SetBackground(wx.wxWHITE_BRUSH)
407              if 1: #self.interactor.selected_map is self.map:              dc.Clear()
408                  selected_layer = self.interactor.selected_layer  
409                  selected_shape = self.interactor.selected_shape              selected_layer = self.selection.SelectedLayer()
410              else:              selected_shapes = self.selection.SelectedShapes()
                 selected_layer = None  
                 selected_shape = None  
411    
412              # draw the map into the bitmap              # draw the map into the bitmap
413              renderer = ScreenRenderer(dc, self.scale, self.offset)              renderer = ScreenRenderer(dc, self.scale, self.offset)
414    
415              # Pass the entire bitmap as update_region to the renderer.              # Pass the entire bitmap as update region to the renderer.
416              # We're redrawing the whole bitmap, after all.              # We're redrawing the whole bitmap, after all.
417              renderer.RenderMap(self.map, (0, 0, width, height),              renderer.RenderMap(self.map, (0, 0, width, height),
418                                 selected_layer, selected_shape)                                 selected_layer, selected_shapes)
419    
420              dc.EndDrawing()              dc.EndDrawing()
421              dc.SelectObject(wx.wxNullBitmap)              dc.SelectObject(wx.wxNullBitmap)
# Line 383  class MapCanvas(wxWindow, Publisher): Line 434  class MapCanvas(wxWindow, Publisher):
434          printout = MapPrintout(self.map)          printout = MapPrintout(self.map)
435          printer.Print(self, printout, wx.true)          printer.Print(self, printout, wx.true)
436          printout.Destroy()          printout.Destroy()
437            
438      def SetMap(self, map):      def SetMap(self, map):
439          redraw_channels = (LAYERS_CHANGED, LAYER_LEGEND_CHANGED,          redraw_channels = (MAP_LAYERS_CHANGED, LAYER_CHANGED,
440                             LAYER_VISIBILITY_CHANGED)                             LAYER_VISIBILITY_CHANGED)
441          if self.map is not None:          if self.map is not None:
442              for channel in redraw_channels:              for channel in redraw_channels:
# Line 393  class MapCanvas(wxWindow, Publisher): Line 444  class MapCanvas(wxWindow, Publisher):
444              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,
445                                   self.projection_changed)                                   self.projection_changed)
446          self.map = map          self.map = map
447            self.selection.ClearSelection()
448          if self.map is not None:          if self.map is not None:
449              for channel in redraw_channels:              for channel in redraw_channels:
450                  self.map.Subscribe(channel, self.full_redraw)                  self.map.Subscribe(channel, self.full_redraw)
# Line 404  class MapCanvas(wxWindow, Publisher): Line 456  class MapCanvas(wxWindow, Publisher):
456          self.full_redraw()          self.full_redraw()
457    
458      def Map(self):      def Map(self):
459            """Return the map displayed by this canvas"""
460          return self.map          return self.map
461    
462      def redraw(self, *args):      def redraw(self, *args):
# Line 437  class MapCanvas(wxWindow, Publisher): Line 490  class MapCanvas(wxWindow, Publisher):
490          return ((x - offx) / self.scale, (offy - y) / self.scale)          return ((x - offx) / self.scale, (offy - y) / self.scale)
491    
492      def FitRectToWindow(self, rect):      def FitRectToWindow(self, rect):
493            """Fit the rectangular region given by rect into the window.
494    
495            Set scale so that rect (in projected coordinates) just fits into
496            the window and center it.
497            """
498          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
499          llx, lly, urx, ury = rect          llx, lly, urx, ury = rect
500          if llx == urx or lly == ury:          if llx == urx or lly == ury:
501              # zero with or zero height. Do Nothing              # zero width or zero height. Do Nothing
502              return              return
503          scalex = width / (urx - llx)          scalex = width / (urx - llx)
504          scaley = height / (ury - lly)          scaley = height / (ury - lly)
# Line 450  class MapCanvas(wxWindow, Publisher): Line 508  class MapCanvas(wxWindow, Publisher):
508          self.set_view_transform(scale, (offx, offy))          self.set_view_transform(scale, (offx, offy))
509    
510      def FitMapToWindow(self):      def FitMapToWindow(self):
511          """\          """Fit the map to the window
512          Set the scale and offset so that the map is centered in the  
513          window          Set the scale so that the map fits exactly into the window and
514            center it in the window.
515          """          """
516          bbox = self.map.ProjectedBoundingBox()          bbox = self.map.ProjectedBoundingBox()
517          if bbox is not None:          if bbox is not None:
518              self.FitRectToWindow(bbox)              self.FitRectToWindow(bbox)
519    
520        def FitLayerToWindow(self, layer):
521            """Fit the given layer to the window.
522    
523            Set the scale so that the layer fits exactly into the window and
524            center it in the window.
525            """
526            
527            bbox = layer.LatLongBoundingBox()
528            if bbox is not None:
529                proj = self.map.GetProjection()
530                if proj is not None:
531                    bbox = proj.ForwardBBox(bbox)
532                    if bbox is not None:
533                        self.FitRectToWindow(bbox)
534    
535      def ZoomFactor(self, factor, center = None):      def ZoomFactor(self, factor, center = None):
536          """Multiply the zoom by factor and center on center.          """Multiply the zoom by factor and center on center.
537    
# Line 478  class MapCanvas(wxWindow, Publisher): Line 552  class MapCanvas(wxWindow, Publisher):
552          self.set_view_transform(scale, offset)          self.set_view_transform(scale, offset)
553    
554      def ZoomOutToRect(self, rect):      def ZoomOutToRect(self, rect):
555          # rect is given in window coordinates          """Zoom out to fit the currently visible region into rect.
556    
557            The rect parameter is given in window coordinates
558            """
559          # determine the bbox of the displayed region in projected          # determine the bbox of the displayed region in projected
560          # coordinates          # coordinates
561          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
# Line 496  class MapCanvas(wxWindow, Publisher): Line 572  class MapCanvas(wxWindow, Publisher):
572          self.set_view_transform(scale, (offx, offy))          self.set_view_transform(scale, (offx, offy))
573    
574      def Translate(self, dx, dy):      def Translate(self, dx, dy):
575            """Move the map by dx, dy pixels"""
576          offx, offy = self.offset          offx, offy = self.offset
577          self.set_view_transform(self.scale, (offx + dx, offy + dy))          self.set_view_transform(self.scale, (offx + dx, offy + dy))
578    
579        def SelectTool(self, tool):
580            """Make tool the active tool.
581    
582            The parameter should be an instance of Tool or None to indicate
583            that no tool is active.
584            """
585            self.tool = tool
586    
587      def ZoomInTool(self):      def ZoomInTool(self):
588          self.tool = ZoomInTool(self)          """Start the zoom in tool"""
589            self.SelectTool(ZoomInTool(self))
590    
591      def ZoomOutTool(self):      def ZoomOutTool(self):
592          self.tool = ZoomOutTool(self)          """Start the zoom out tool"""
593            self.SelectTool(ZoomOutTool(self))
594    
595      def PanTool(self):      def PanTool(self):
596          self.tool = PanTool(self)          """Start the pan tool"""
597            self.SelectTool(PanTool(self))
598            #img = resource.GetImageResource("pan", wxBITMAP_TYPE_XPM)
599            #bmp = resource.GetBitmapResource("pan", wxBITMAP_TYPE_XPM)
600            #print bmp
601            #img = wxImageFromBitmap(bmp)
602            #print img
603            #cur = wxCursor(img)
604            #print cur
605            #self.SetCursor(cur)
606    
607      def IdentifyTool(self):      def IdentifyTool(self):
608          self.tool = IdentifyTool(self)          """Start the identify tool"""
609            self.SelectTool(IdentifyTool(self))
610    
611      def LabelTool(self):      def LabelTool(self):
612          self.tool = LabelTool(self)          """Start the label tool"""
613            self.SelectTool(LabelTool(self))
614    
615      def CurrentTool(self):      def CurrentTool(self):
616            """Return the name of the current tool or None if no tool is active"""
617          return self.tool and self.tool.Name() or None          return self.tool and self.tool.Name() or None
618    
619      def CurrentPosition(self):      def CurrentPosition(self):
# Line 552  class MapCanvas(wxWindow, Publisher): Line 651  class MapCanvas(wxWindow, Publisher):
651              self.tool.MouseDown(event)              self.tool.MouseDown(event)
652              self.tool.Show(self.drag_dc)              self.tool.Show(self.drag_dc)
653              self.dragging = 1              self.dragging = 1
654            
655      def OnLeftUp(self, event):      def OnLeftUp(self, event):
         self.ReleaseMouse()  
656          self.set_current_position(event)          self.set_current_position(event)
657          if self.dragging:          if self.dragging:
658              self.tool.Hide(self.drag_dc)              self.ReleaseMouse()
659              self.tool.MouseUp(event)              try:
660              self.drag_dc = None                  self.tool.Hide(self.drag_dc)
661          self.dragging = 0                  self.tool.MouseUp(event)
662                finally:
663                    self.drag_dc = None
664                    self.dragging = 0
665    
666      def OnMotion(self, event):      def OnMotion(self, event):
667          self.set_current_position(event)          self.set_current_position(event)
# Line 572  class MapCanvas(wxWindow, Publisher): Line 673  class MapCanvas(wxWindow, Publisher):
673      def OnLeaveWindow(self, event):      def OnLeaveWindow(self, event):
674          self.set_current_position(None)          self.set_current_position(None)
675    
     def OnIdle(self, event):  
         if self.redraw_on_idle:  
             self.do_redraw()  
         self.redraw_on_idle = 0  
   
676      def OnSize(self, event):      def OnSize(self, event):
677          # 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
678          # 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 585  class MapCanvas(wxWindow, Publisher): Line 681  class MapCanvas(wxWindow, Publisher):
681          # Even when the window becomes larger some parts of the bitmap          # Even when the window becomes larger some parts of the bitmap
682          # could be reused.          # could be reused.
683          self.full_redraw()          self.full_redraw()
684            pass
685    
686      def shape_selected(self, layer, shape):      def shape_selected(self, layer, shape):
687          """Redraw the map.          """Receiver for the SHAPES_SELECTED messages. Redraw the map."""
688            # The selection object takes care that it only issues
689          Receiver for the SELECTED_SHAPE messages. Try to redraw only          # SHAPES_SELECTED messages when the set of selected shapes has
690          when necessary.          # actually changed, so we can do a full redraw unconditionally.
691          """          # FIXME: We should perhaps try to limit the redraw to the are
692          # A redraw is necessary when the display has to change, which          # actually covered by the shapes before and after the selection
693          # means that either the status changes from having no selection          # change.
694          # 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  
695    
696      def unprojected_rect_around_point(self, x, y):      def unprojected_rect_around_point(self, x, y, dist):
697          """return a rect a few pixels around (x, y) in unprojected corrdinates          """return a rect dist pixels around (x, y) in unprojected corrdinates
698    
699          The return value is a tuple (minx, miny, maxx, maxy) suitable a          The return value is a tuple (minx, miny, maxx, maxy) suitable a
700          parameter to a layer's ShapesInRegion method.          parameter to a layer's ShapesInRegion method.
# Line 622  class MapCanvas(wxWindow, Publisher): Line 708  class MapCanvas(wxWindow, Publisher):
708          xs = []          xs = []
709          ys = []          ys = []
710          for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):          for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
711              px, py = self.win_to_proj(x + dx, y + dy)              px, py = self.win_to_proj(x + dist * dx, y + dist * dy)
712              if inverse:              if inverse:
713                  px, py = inverse(px, py)                  px, py = inverse(px, py)
714              xs.append(px)              xs.append(px)
715              ys.append(py)              ys.append(py)
716          return (min(xs), min(ys), max(xs), max(ys))          return (min(xs), min(ys), max(xs), max(ys))
717    
718      def find_shape_at(self, px, py, select_labels = 0, selected_layer = 1):      def find_shape_at(self, px, py, select_labels = 0, searched_layer = None):
719          """Determine the shape at point px, py in window coords          """Determine the shape at point px, py in window coords
720    
721          Return the shape and the corresponding layer as a tuple (layer,          Return the shape and the corresponding layer as a tuple (layer,
# Line 639  class MapCanvas(wxWindow, Publisher): Line 725  class MapCanvas(wxWindow, Publisher):
725          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
726          as the shape and None as the layer.          as the shape and None as the layer.
727    
728          If the optional parameter selected_layer is true (default), only          If the optional parameter searched_layer is given (or not None
729          search in the currently selected layer.          which it defaults to), only search in that layer.
730          """          """
731          map_proj = self.map.projection          map_proj = self.map.projection
732          if map_proj is not None:          if map_proj is not None:
# Line 651  class MapCanvas(wxWindow, Publisher): Line 737  class MapCanvas(wxWindow, Publisher):
737          scale = self.scale          scale = self.scale
738          offx, offy = self.offset          offx, offy = self.offset
739    
         box = self.unprojected_rect_around_point(px, py)  
   
740          if select_labels:          if select_labels:
741              labels = self.map.LabelLayer().Labels()              labels = self.map.LabelLayer().Labels()
742                
743              if labels:              if labels:
744                  dc = wxClientDC(self)                  dc = wxClientDC(self)
745                  font = wxFont(10, wx.wxSWISS, wx.wxNORMAL, wx.wxNORMAL)                  font = wxFont(10, wx.wxSWISS, wx.wxNORMAL, wx.wxNORMAL)
# Line 687  class MapCanvas(wxWindow, Publisher): Line 771  class MapCanvas(wxWindow, Publisher):
771                      if x <= px < x + width and y <= py <= y + height:                      if x <= px < x + width and y <= py <= y + height:
772                          return None, i                          return None, i
773    
774          if selected_layer:          if searched_layer:
775              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 = []  
776          else:          else:
777              layers = self.map.Layers()              layers = self.map.Layers()
778    
# Line 705  class MapCanvas(wxWindow, Publisher): Line 783  class MapCanvas(wxWindow, Publisher):
783              if not layer.Visible():              if not layer.Visible():
784                  continue                  continue
785    
786              filled = layer.fill is not None              filled = layer.GetClassification().GetDefaultFill() \
787              stroked = layer.stroke is not None                       is not Color.Transparent
788                                stroked = layer.GetClassification().GetDefaultLineColor() \
789                          is not Color.Transparent
790    
791              layer_proj = layer.projection              layer_proj = layer.projection
792              if layer_proj is not None:              if layer_proj is not None:
793                  inverse = layer_proj.Inverse                  inverse = layer_proj.Inverse
794              else:              else:
795                  inverse = None                  inverse = None
796                    
797              shapetype = layer.ShapeType()              shapetype = layer.ShapeType()
798    
799              select_shape = -1              select_shape = -1
800    
801                # Determine the ids of the shapes that overlap a tiny area
802                # around the point. For layers containing points we have to
803                # choose a larger size of the box we're testing agains so
804                # that we take the size of the markers into account
805                # FIXME: Once the markers are more flexible this part has to
806                # become more flexible too, of course
807                if shapetype == SHAPETYPE_POINT:
808                    box = self.unprojected_rect_around_point(px, py, 5)
809                else:
810                    box = self.unprojected_rect_around_point(px, py, 1)
811              shape_ids = layer.ShapesInRegion(box)              shape_ids = layer.ShapesInRegion(box)
812              shape_ids.reverse()              shape_ids.reverse()
813    
# Line 760  class MapCanvas(wxWindow, Publisher): Line 850  class MapCanvas(wxWindow, Publisher):
850                  return layer, select_shape                  return layer, select_shape
851          return None, None          return None, None
852    
853      def SelectShapeAt(self, x, y):      def SelectShapeAt(self, x, y, layer = None):
854          layer, shape = self.find_shape_at(x, y, selected_layer = 0)          """\
855            Select and return the shape and its layer at window position (x, y)
856    
857            If layer is given, only search in that layer. If no layer is
858            given, search through all layers.
859    
860            Return a tuple (layer, shapeid). If no shape is found, return
861            (None, None).
862            """
863            layer, shape = result = self.find_shape_at(x, y, searched_layer=layer)
864          # 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
865          # to deselect the currently selected layer, so we simply select          # to deselect the currently selected layer, so we simply select
866          # the already selected layer again.          # the already selected layer again.
867          if layer is None:          if layer is None:
868              layer = self.interactor.SelectedLayer()              layer = self.selection.SelectedLayer()
869          self.interactor.SelectLayerAndShape(layer, shape)              shapes = []
870            else:
871                shapes = [shape]
872            self.selection.SelectShapes(layer, shapes)
873            return result
874    
875      def LabelShapeAt(self, x, y):      def LabelShapeAt(self, x, y):
876            """Add or remove a label at window position x, y.
877    
878            If there's a label at the given position, remove it. Otherwise
879            determine the shape at the position, run the label dialog and
880            unless the user cancels the dialog, add a laber.
881            """
882          ox = x; oy = y          ox = x; oy = y
883          label_layer = self.map.LabelLayer()          label_layer = self.map.LabelLayer()
884          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.176  
changed lines
  Added in v.822

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26