/[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 23 by bh, Wed Sep 5 13:35:22 2001 UTC revision 799 by jonathan, Wed Apr 30 17:02:21 2003 UTC
# Line 1  Line 1 
1  # Copyright (c) 2001 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_PAINT, EVT_LEFT_DOWN, EVT_LEFT_UP, EVT_MOTION, EVT_LEAVE_WINDOW
21    
22    
23  from wxPython import wx  from wxPython import wx
# Line 24  from wxproj import point_in_polygon_shap Line 26  from wxproj import point_in_polygon_shap
26    
27    
28  from Thuban.Model.messages import MAP_PROJECTION_CHANGED, \  from Thuban.Model.messages import MAP_PROJECTION_CHANGED, \
29       LAYERS_CHANGED, LAYER_LEGEND_CHANGED, LAYER_VISIBILITY_CHANGED       MAP_LAYERS_CHANGED, LAYER_CHANGED, LAYER_VISIBILITY_CHANGED
30  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \
31       SHAPETYPE_POINT       SHAPETYPE_POINT
32  from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \  from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \
33       ALIGN_LEFT, ALIGN_RIGHT       ALIGN_LEFT, ALIGN_RIGHT
34    from Thuban.Lib.connector import Publisher
35    from Thuban.Model.color import Color
36    
37    from selection import Selection
38  from renderer import ScreenRenderer, PrinterRender  from renderer import ScreenRenderer, PrinterRender
39    
40  import labeldialog  import labeldialog
41    
42  from messages import SELECTED_SHAPE  from messages import LAYER_SELECTED, SHAPES_SELECTED, VIEW_POSITION
43    
44    
45  #  #
# Line 127  class ZoomInTool(RectTool): Line 131  class ZoomInTool(RectTool):
131      def MouseUp(self, event):      def MouseUp(self, event):
132          if self.dragging:          if self.dragging:
133              Tool.MouseUp(self, event)              Tool.MouseUp(self, event)
134              self.view.FitRectToWindow(self.proj_rect())              sx, sy = self.start
135                cx, cy = self.current
136                if sx == cx or sy == cy:
137                    # Just a mouse click or a degenerate rectangle. Simply
138                    # zoom in by a factor of two
139                    # FIXME: For a click this is the desired behavior but should we
140                    # really do this for degenrate rectagles as well or
141                    # should we ignore them?
142                    self.view.ZoomFactor(2, center = (cx, cy))
143                else:
144                    # A drag. Zoom in to the rectangle
145                    self.view.FitRectToWindow(self.proj_rect())
146    
147    
148  class ZoomOutTool(RectTool):  class ZoomOutTool(RectTool):
149    
150      """The Zoom-Out Tool"""      """The Zoom-Out Tool"""
151        
152      def Name(self):      def Name(self):
153          return "ZoomOutTool"          return "ZoomOutTool"
154    
# Line 142  class ZoomOutTool(RectTool): Line 157  class ZoomOutTool(RectTool):
157              Tool.MouseUp(self, event)              Tool.MouseUp(self, event)
158              sx, sy = self.start              sx, sy = self.start
159              cx, cy = self.current              cx, cy = self.current
160              self.view.ZoomOutToRect((min(sx, cx), min(sy, cy),              if sx == cx or sy == cy:
161                                       max(sx, cx), max(sy, cy)))                  # Just a mouse click or a degenerate rectangle. Simply
162                    # zoom out by a factor of two.
163                    # FIXME: For a click this is the desired behavior but should we
164                    # really do this for degenrate rectagles as well or
165                    # should we ignore them?
166                    self.view.ZoomFactor(0.5, center = (cx, cy))
167                else:
168                    # A drag. Zoom out to the rectangle
169                    self.view.ZoomOutToRect((min(sx, cx), min(sy, cy),
170                                             max(sx, cx), max(sy, cy)))
171    
172    
173  class PanTool(Tool):  class PanTool(Tool):
# Line 155  class PanTool(Tool): Line 179  class PanTool(Tool):
179    
180      def MouseMove(self, event):      def MouseMove(self, event):
181          if self.dragging:          if self.dragging:
             x0, y0 = self.current  
182              Tool.MouseMove(self, event)              Tool.MouseMove(self, event)
183                sx, sy = self.start
184              x, y = self.current              x, y = self.current
185              width, height = self.view.GetSizeTuple()              width, height = self.view.GetSizeTuple()
186    
187                bitmapdc = wx.wxMemoryDC()
188                bitmapdc.SelectObject(self.view.bitmap)
189    
190              dc = self.view.drag_dc              dc = self.view.drag_dc
191              dc.Blit(0, 0, width, height, dc, x0 - x, y0 - y)              dc.Blit(0, 0, width, height, bitmapdc, sx - x, sy - y)
192    
193      def MouseUp(self, event):      def MouseUp(self, event):
194          if self.dragging:          if self.dragging:
# Line 168  class PanTool(Tool): Line 196  class PanTool(Tool):
196              sx, sy = self.start              sx, sy = self.start
197              cx, cy = self.current              cx, cy = self.current
198              self.view.Translate(cx - sx, cy - sy)              self.view.Translate(cx - sx, cy - sy)
199            
200  class IdentifyTool(Tool):  class IdentifyTool(Tool):
201    
202      """The "Identify" Tool"""      """The "Identify" Tool"""
203        
204      def Name(self):      def Name(self):
205          return "IdentifyTool"          return "IdentifyTool"
206    
# Line 226  class MapPrintout(wx.wxPrintout): Line 254  class MapPrintout(wx.wxPrintout):
254          renderer = PrinterRender(dc, scale, (offx, offy), resolution = resx)          renderer = PrinterRender(dc, scale, (offx, offy), resolution = resx)
255          renderer.RenderMap(self.map)          renderer.RenderMap(self.map)
256          return wx.true          return wx.true
           
257    
258  class MapCanvas(wxWindow):  
259    class MapCanvas(wxWindow, Publisher):
260    
261      """A widget that displays a map and offers some interaction"""      """A widget that displays a map and offers some interaction"""
262    
263      def __init__(self, parent, winid, interactor):      # Some messages that can be subscribed/unsubscribed directly through
264        # the MapCanvas come in fact from other objects. This is a dict
265        # mapping those messages to the names of the instance variables they
266        # actually come from. The delegation is implemented in the Subscribe
267        # and Unsubscribe methods
268        delegated_messages = {LAYER_SELECTED: "selection",
269                              SHAPES_SELECTED: "selection"}
270    
271        # Methods delegated to some instance variables. The delegation is
272        # implemented in the __getattr__ method.
273        delegated_methods = {"SelectLayer": "selection",
274                             "SelectShapes": "selection",
275                             "SelectedLayer": "selection",
276                             "HasSelectedLayer": "selection"}
277    
278        def __init__(self, parent, winid):
279          wxWindow.__init__(self, parent, winid)          wxWindow.__init__(self, parent, winid)
280          self.SetBackgroundColour(wxColour(255, 255, 255))          self.SetBackgroundColour(wxColour(255, 255, 255))
281    
282            # the map displayed in this canvas. Set with SetMap()
283          self.map = None          self.map = None
284    
285            # scale and offset describe the transformation from projected
286            # coordinates to window coordinates.
287          self.scale = 1.0          self.scale = 1.0
288          self.offset = (0, 0)          self.offset = (0, 0)
289    
290            # whether the user is currently dragging the mouse, i.e. moving
291            # the mouse while pressing a mouse button
292          self.dragging = 0          self.dragging = 0
293    
294            # the currently active tool
295          self.tool = None          self.tool = None
296          self.redraw_on_idle = 0  
297            # The current mouse position of the last OnMotion event or None
298            # if the mouse is outside the window.
299            self.current_position = None
300    
301            # the bitmap serving as backing store
302            self.bitmap = None
303    
304            # the selection
305            self.selection = Selection()
306            self.selection.Subscribe(SHAPES_SELECTED , self.shape_selected)
307    
308            # keep track of which layers/shapes are selected to make sure we
309            # only redraw when necessary
310            self.last_selected_layer = None
311            self.last_selected_shape = None
312    
313            # subscribe the WX events we're interested in
314          EVT_PAINT(self, self.OnPaint)          EVT_PAINT(self, self.OnPaint)
315          EVT_LEFT_DOWN(self, self.OnLeftDown)          EVT_LEFT_DOWN(self, self.OnLeftDown)
316          EVT_LEFT_UP(self, self.OnLeftUp)          EVT_LEFT_UP(self, self.OnLeftUp)
317          EVT_MOTION(self, self.OnMotion)          EVT_MOTION(self, self.OnMotion)
318          wx.EVT_IDLE(self, self.OnIdle)          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)
319          self.interactor = interactor          wx.EVT_SIZE(self, self.OnSize)
320          self.interactor.Subscribe(SELECTED_SHAPE, self.shape_selected)  
321        def __del__(self):
322            wxWindow.__del__(self)
323            Publisher.__del__(self)
324    
325        def Subscribe(self, channel, *args):
326            """Extend the inherited method to handle delegated messages.
327    
328            If channel is one of the delegated messages call the appropriate
329            object's Subscribe method. Otherwise just call the inherited
330            method.
331            """
332            if channel in self.delegated_messages:
333                object = getattr(self, self.delegated_messages[channel])
334                object.Subscribe(channel, *args)
335            else:
336                Publisher.Subscribe(self, channel, *args)
337    
338        def Unsubscribe(self, channel, *args):
339            """Extend the inherited method to handle delegated messages.
340    
341            If channel is one of the delegated messages call the appropriate
342            object's Unsubscribe method. Otherwise just call the inherited
343            method.
344            """
345            if channel in self.delegated_messages:
346                object = getattr(self, self.delegated_messages[channel])
347                object.Unsubscribe(channel, *args)
348            else:
349                Publisher.Unsubscribe(self, channel, *args)
350    
351        def __getattr__(self, attr):
352            if attr in self.delegated_methods:
353                return getattr(getattr(self, self.delegated_methods[attr]), attr)
354            raise AttributeError(attr)
355    
356      def OnPaint(self, event):      def OnPaint(self, event):
357          dc = wxPaintDC(self)          dc = wxPaintDC(self)
358          if self.map is None or not self.map.HasLayers():          clear = self.map is None or not self.map.HasLayers()
             return  
         self.redraw_on_idle = 1  
359    
360      def do_redraw(self):          if not clear:
361          width, height = self.GetSizeTuple()              try:
362          bitmap = wx.wxEmptyBitmap(width, height)                  self.do_redraw()
363                except:
364                    print "Error during drawing:", sys.exc_info()[0]
365                    clear = True
366    
367            if clear:
368                # If we've got no map or if the map is empty, simply clear
369                # the screen.
370    
371                # XXX it's probably possible to get rid of this. The
372                # background color of the window is already white and the
373                # only thing we may have to do is to call self.Refresh()
374                # with a true argument in the right places.
375                dc.BeginDrawing()
376                dc.Clear()
377                dc.EndDrawing()
378    
379          dc = wx.wxMemoryDC()      def do_redraw(self):
380          dc.SelectObject(bitmap)          # This should only be called if we have a non-empty map.
381    
382          dc.BeginDrawing()          # Get the window size.
383            width, height = self.GetSizeTuple()
384    
385          dc.SetBrush(wx.wxWHITE_BRUSH)          # If self.bitmap's still there, reuse it. Otherwise redraw it
386          dc.SetPen(wx.wxTRANSPARENT_PEN)          if self.bitmap is not None:
387          dc.DrawRectangle(0, 0, width, height)              bitmap = self.bitmap
   
         if 1: #self.interactor.selected_map is self.map:  
             selected_layer = self.interactor.selected_layer  
             selected_shape = self.interactor.selected_shape  
388          else:          else:
389              selected_layer = None              bitmap = wx.wxEmptyBitmap(width, height)
390              selected_shape = None              dc = wx.wxMemoryDC()
391                            dc.SelectObject(bitmap)
392          renderer = ScreenRenderer(dc, self.scale, self.offset)              dc.BeginDrawing()
393          renderer.RenderMap(self.map, selected_layer, selected_shape)  
394                # clear the background
395                #dc.SetBrush(wx.wxWHITE_BRUSH)
396                #dc.SetPen(wx.wxTRANSPARENT_PEN)
397                #dc.DrawRectangle(0, 0, width, height)
398                dc.SetBackground(wx.wxWHITE_BRUSH)
399                dc.Clear()
400    
401                selected_layer = self.selection.SelectedLayer()
402                selected_shapes = self.selection.SelectedShapes()
403    
404                # draw the map into the bitmap
405                renderer = ScreenRenderer(dc, self.scale, self.offset)
406    
407                # Pass the entire bitmap as update region to the renderer.
408                # We're redrawing the whole bitmap, after all.
409                renderer.RenderMap(self.map, (0, 0, width, height),
410                                   selected_layer, selected_shapes)
411    
412                dc.EndDrawing()
413                dc.SelectObject(wx.wxNullBitmap)
414                self.bitmap = bitmap
415    
416            # blit the bitmap to the screen
417            dc = wx.wxMemoryDC()
418            dc.SelectObject(bitmap)
419          clientdc = wxClientDC(self)          clientdc = wxClientDC(self)
420          clientdc.BeginDrawing()          clientdc.BeginDrawing()
421          clientdc.Blit(0, 0, width, height, dc, 0, 0)          clientdc.Blit(0, 0, width, height, dc, 0, 0)
422          clientdc.EndDrawing()          clientdc.EndDrawing()
423    
   
424      def Print(self):      def Print(self):
425          printer = wx.wxPrinter()          printer = wx.wxPrinter()
426          printout = MapPrintout(self.map)          printout = MapPrintout(self.map)
427          printer.Print(self, printout, wx.true)          printer.Print(self, printout, wx.true)
428          printout.Destroy()          printout.Destroy()
429            
430      def SetMap(self, map):      def SetMap(self, map):
431          redraw_channels = (LAYERS_CHANGED, LAYER_LEGEND_CHANGED,          redraw_channels = (MAP_LAYERS_CHANGED, LAYER_CHANGED,
432                             LAYER_VISIBILITY_CHANGED)                             LAYER_VISIBILITY_CHANGED)
433          if self.map is not None:          if self.map is not None:
434              for channel in redraw_channels:              for channel in redraw_channels:
435                  self.map.Unsubscribe(channel, self.redraw)                  self.map.Unsubscribe(channel, self.full_redraw)
436              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,
437                                   self.projection_changed)                                   self.projection_changed)
438          self.map = map          self.map = map
439            self.selection.ClearSelection()
440          if self.map is not None:          if self.map is not None:
441              for channel in redraw_channels:              for channel in redraw_channels:
442                  self.map.Subscribe(channel, self.redraw)                  self.map.Subscribe(channel, self.full_redraw)
443              self.map.Subscribe(MAP_PROJECTION_CHANGED, self.projection_changed)              self.map.Subscribe(MAP_PROJECTION_CHANGED, self.projection_changed)
444          self.FitMapToWindow()          self.FitMapToWindow()
445            # force a redraw. If map is not empty, it's already been called
446            # by FitMapToWindow but if map is empty it hasn't been called
447            # yet so we have to explicitly call it.
448            self.full_redraw()
449    
450      def Map(self):      def Map(self):
451            """Return the map displayed by this canvas"""
452          return self.map          return self.map
453    
454      def redraw(self, *args):      def redraw(self, *args):
455          self.Refresh(0)          self.Refresh(0)
456    
457        def full_redraw(self, *args):
458            self.bitmap = None
459            self.redraw()
460    
461      def projection_changed(self, *args):      def projection_changed(self, *args):
462          self.FitMapToWindow()          self.FitMapToWindow()
463          self.redraw()          self.full_redraw()
464    
465      def set_view_transform(self, scale, offset):      def set_view_transform(self, scale, offset):
466          self.scale = scale          self.scale = scale
467          self.offset = offset          self.offset = offset
468          self.redraw()          self.full_redraw()
469    
470      def proj_to_win(self, x, y):      def proj_to_win(self, x, y):
471          """\          """\
# Line 335  class MapCanvas(wxWindow): Line 482  class MapCanvas(wxWindow):
482          return ((x - offx) / self.scale, (offy - y) / self.scale)          return ((x - offx) / self.scale, (offy - y) / self.scale)
483    
484      def FitRectToWindow(self, rect):      def FitRectToWindow(self, rect):
485            """Fit the rectangular region given by rect into the window.
486    
487            Set scale so that rect (in projected coordinates) just fits into
488            the window and center it.
489            """
490          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
491          llx, lly, urx, ury = rect          llx, lly, urx, ury = rect
492            if llx == urx or lly == ury:
493                # zero width or zero height. Do Nothing
494                return
495          scalex = width / (urx - llx)          scalex = width / (urx - llx)
496          scaley = height / (ury - lly)          scaley = height / (ury - lly)
497          scale = min(scalex, scaley)          scale = min(scalex, scaley)
# Line 345  class MapCanvas(wxWindow): Line 500  class MapCanvas(wxWindow):
500          self.set_view_transform(scale, (offx, offy))          self.set_view_transform(scale, (offx, offy))
501    
502      def FitMapToWindow(self):      def FitMapToWindow(self):
503          """\          """Fit the map to the window
504          Set the scale and offset so that the map is centered in the  
505          window          Set the scale so that the map fits exactly into the window and
506            center it in the window.
507          """          """
508          bbox = self.map.ProjectedBoundingBox()          bbox = self.map.ProjectedBoundingBox()
509          if bbox is not None:          if bbox is not None:
510              self.FitRectToWindow(bbox)              self.FitRectToWindow(bbox)
511    
512      def ZoomFactor(self, factor):      def ZoomFactor(self, factor, center = None):
513            """Multiply the zoom by factor and center on center.
514    
515            The optional parameter center is a point in window coordinates
516            that should be centered. If it is omitted, it defaults to the
517            center of the window
518            """
519          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
520          scale = self.scale * factor          scale = self.scale * factor
521          offx, offy = self.offset          offx, offy = self.offset
522          offset = (factor * (offx - width / 2) + width / 2,          if center is not None:
523                    factor * (offy - height / 2) + height / 2)              cx, cy = center
524            else:
525                cx = width / 2
526                cy = height / 2
527            offset = (factor * (offx - cx) + width / 2,
528                      factor * (offy - cy) + height / 2)
529          self.set_view_transform(scale, offset)          self.set_view_transform(scale, offset)
530    
531      def ZoomOutToRect(self, rect):      def ZoomOutToRect(self, rect):
532          # rect is given in window coordinates          """Zoom out to fit the currently visible region into rect.
533    
534            The rect parameter is given in window coordinates
535            """
536          # determine the bbox of the displayed region in projected          # determine the bbox of the displayed region in projected
537          # coordinates          # coordinates
538          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
# Line 380  class MapCanvas(wxWindow): Line 549  class MapCanvas(wxWindow):
549          self.set_view_transform(scale, (offx, offy))          self.set_view_transform(scale, (offx, offy))
550    
551      def Translate(self, dx, dy):      def Translate(self, dx, dy):
552            """Move the map by dx, dy pixels"""
553          offx, offy = self.offset          offx, offy = self.offset
554          self.set_view_transform(self.scale, (offx + dx, offy + dy))          self.set_view_transform(self.scale, (offx + dx, offy + dy))
555    
556        def SelectTool(self, tool):
557            """Make tool the active tool.
558    
559            The parameter should be an instance of Tool or None to indicate
560            that no tool is active.
561            """
562            self.tool = tool
563    
564      def ZoomInTool(self):      def ZoomInTool(self):
565          self.tool = ZoomInTool(self)          """Start the zoom in tool"""
566            self.SelectTool(ZoomInTool(self))
567    
568      def ZoomOutTool(self):      def ZoomOutTool(self):
569          self.tool = ZoomOutTool(self)          """Start the zoom out tool"""
570            self.SelectTool(ZoomOutTool(self))
571    
572      def PanTool(self):      def PanTool(self):
573          self.tool = PanTool(self)          """Start the pan tool"""
574            self.SelectTool(PanTool(self))
575    
576      def IdentifyTool(self):      def IdentifyTool(self):
577          self.tool = IdentifyTool(self)          """Start the identify tool"""
578            self.SelectTool(IdentifyTool(self))
579    
580      def LabelTool(self):      def LabelTool(self):
581          self.tool = LabelTool(self)          """Start the label tool"""
582            self.SelectTool(LabelTool(self))
583    
584      def CurrentTool(self):      def CurrentTool(self):
585            """Return the name of the current tool or None if no tool is active"""
586          return self.tool and self.tool.Name() or None          return self.tool and self.tool.Name() or None
587    
588        def CurrentPosition(self):
589            """Return current position of the mouse in projected coordinates.
590    
591            The result is a 2-tuple of floats with the coordinates. If the
592            mouse is not in the window, the result is None.
593            """
594            if self.current_position is not None:
595                x, y = self.current_position
596                return self.win_to_proj(x, y)
597            else:
598                return None
599    
600        def set_current_position(self, event):
601            """Set the current position from event
602    
603            Should be called by all events that contain mouse positions
604            especially EVT_MOTION. The event paramete may be None to
605            indicate the the pointer left the window.
606            """
607            if event is not None:
608                self.current_position = (event.m_x, event.m_y)
609            else:
610                self.current_position = None
611            self.issue(VIEW_POSITION)
612    
613      def OnLeftDown(self, event):      def OnLeftDown(self, event):
614            self.set_current_position(event)
615          if self.tool is not None:          if self.tool is not None:
616              self.drag_dc = wxClientDC(self)              self.drag_dc = wxClientDC(self)
617              self.drag_dc.SetLogicalFunction(wxINVERT)              self.drag_dc.SetLogicalFunction(wxINVERT)
# Line 410  class MapCanvas(wxWindow): Line 620  class MapCanvas(wxWindow):
620              self.tool.MouseDown(event)              self.tool.MouseDown(event)
621              self.tool.Show(self.drag_dc)              self.tool.Show(self.drag_dc)
622              self.dragging = 1              self.dragging = 1
623            
624      def OnLeftUp(self, event):      def OnLeftUp(self, event):
625          self.ReleaseMouse()          self.set_current_position(event)
626          if self.dragging:          if self.dragging:
627              self.tool.Hide(self.drag_dc)              self.ReleaseMouse()
628              self.tool.MouseUp(event)              try:
629              self.drag_dc = None                  self.tool.Hide(self.drag_dc)
630          self.dragging = 0                  self.tool.MouseUp(event)
631                finally:
632                    self.drag_dc = None
633                    self.dragging = 0
634    
635      def OnMotion(self, event):      def OnMotion(self, event):
636            self.set_current_position(event)
637          if self.dragging:          if self.dragging:
638              self.tool.Hide(self.drag_dc)              self.tool.Hide(self.drag_dc)
639              self.tool.MouseMove(event)              self.tool.MouseMove(event)
640              self.tool.Show(self.drag_dc)              self.tool.Show(self.drag_dc)
641    
642      def OnIdle(self, event):      def OnLeaveWindow(self, event):
643          if self.redraw_on_idle:          self.set_current_position(None)
644              self.do_redraw()  
645          self.redraw_on_idle = 0      def OnSize(self, event):
646            # the window's size has changed. We have to get a new bitmap. If
647            # we want to be clever we could try to get by without throwing
648            # everything away. E.g. when the window gets smaller, we could
649            # either keep the bitmap or create the new one from the old one.
650            # Even when the window becomes larger some parts of the bitmap
651            # could be reused.
652            self.full_redraw()
653            pass
654    
655      def shape_selected(self, layer, shape):      def shape_selected(self, layer, shape):
656          self.redraw()          """Receiver for the SHAPES_SELECTED messages. Redraw the map."""
657            # The selection object takes care that it only issues
658            # SHAPES_SELECTED messages when the set of selected shapes has
659            # actually changed, so we can do a full redraw unconditionally.
660            # FIXME: We should perhaps try to limit the redraw to the are
661            # actually covered by the shapes before and after the selection
662            # change.
663            self.full_redraw()
664    
665        def unprojected_rect_around_point(self, x, y, dist):
666            """return a rect dist pixels around (x, y) in unprojected corrdinates
667    
668      def find_shape_at(self, px, py, select_labels = 0):          The return value is a tuple (minx, miny, maxx, maxy) suitable a
669          """Return a tuple shape at point px, py in window coords."""          parameter to a layer's ShapesInRegion method.
670            """
671            map_proj = self.map.projection
672            if map_proj is not None:
673                inverse = map_proj.Inverse
674            else:
675                inverse = None
676    
677            xs = []
678            ys = []
679            for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
680                px, py = self.win_to_proj(x + dist * dx, y + dist * dy)
681                if inverse:
682                    px, py = inverse(px, py)
683                xs.append(px)
684                ys.append(py)
685            return (min(xs), min(ys), max(xs), max(ys))
686    
687        def find_shape_at(self, px, py, select_labels = 0, searched_layer = None):
688            """Determine the shape at point px, py in window coords
689    
690            Return the shape and the corresponding layer as a tuple (layer,
691            shape).
692    
693            If the optional parameter select_labels is true (default false)
694            search through the labels. If a label is found return it's index
695            as the shape and None as the layer.
696    
697            If the optional parameter searched_layer is given (or not None
698            which it defaults to), only search in that layer.
699            """
700          map_proj = self.map.projection          map_proj = self.map.projection
701          if map_proj is not None:          if map_proj is not None:
702              forward = map_proj.Forward              forward = map_proj.Forward
# Line 446  class MapCanvas(wxWindow): Line 708  class MapCanvas(wxWindow):
708    
709          if select_labels:          if select_labels:
710              labels = self.map.LabelLayer().Labels()              labels = self.map.LabelLayer().Labels()
711                
712              if labels:              if labels:
713                  dc = wxClientDC(self)                  dc = wxClientDC(self)
714                  font = wxFont(10, wx.wxSWISS, wx.wxNORMAL, wx.wxNORMAL)                  font = wxFont(10, wx.wxSWISS, wx.wxNORMAL, wx.wxNORMAL)
715                  dc.SetFont(font)                  dc.SetFont(font)
716                  for i in range(len(labels)):                  for i in range(len(labels) - 1, -1, -1):
717                      label = labels[i]                      label = labels[i]
718                      x = label.x                      x = label.x
719                      y = label.y                      y = label.y
# Line 477  class MapCanvas(wxWindow): Line 739  class MapCanvas(wxWindow):
739                          y = y - height/2                          y = y - height/2
740                      if x <= px < x + width and y <= py <= y + height:                      if x <= px < x + width and y <= py <= y + height:
741                          return None, i                          return None, i
742                    
743          layers = self.map.Layers()          if searched_layer:
744                layers = [searched_layer]
745            else:
746                layers = self.map.Layers()
747    
748          for layer_index in range(len(layers) - 1, -1, -1):          for layer_index in range(len(layers) - 1, -1, -1):
749              layer = layers[layer_index]              layer = layers[layer_index]
750    
# Line 486  class MapCanvas(wxWindow): Line 752  class MapCanvas(wxWindow):
752              if not layer.Visible():              if not layer.Visible():
753                  continue                  continue
754    
755              filled = layer.fill is not None              filled = layer.GetClassification().GetDefaultFill() \
756              stroked = layer.stroke is not None                       is not Color.Transparent
757                                stroked = layer.GetClassification().GetDefaultLineColor() \
758                          is not Color.Transparent
759    
760              layer_proj = layer.projection              layer_proj = layer.projection
761              if layer_proj is not None:              if layer_proj is not None:
762                  inverse = layer_proj.Inverse                  inverse = layer_proj.Inverse
763              else:              else:
764                  inverse = None                  inverse = None
765                    
766              shapetype = layer.ShapeType()              shapetype = layer.ShapeType()
767    
768              select_shape = -1              select_shape = -1
769    
770                # Determine the ids of the shapes that overlap a tiny area
771                # around the point. For layers containing points we have to
772                # choose a larger size of the box we're testing agains so
773                # that we take the size of the markers into account
774                # FIXME: Once the markers are more flexible this part has to
775                # become more flexible too, of course
776                if shapetype == SHAPETYPE_POINT:
777                    box = self.unprojected_rect_around_point(px, py, 5)
778                else:
779                    box = self.unprojected_rect_around_point(px, py, 1)
780                shape_ids = layer.ShapesInRegion(box)
781                shape_ids.reverse()
782    
783              if shapetype == SHAPETYPE_POLYGON:              if shapetype == SHAPETYPE_POLYGON:
784                  for i in range(layer.NumShapes()):                  for i in shape_ids:
785                      result = point_in_polygon_shape(layer.shapefile.cobject(),                      result = point_in_polygon_shape(layer.shapefile.cobject(),
786                                                      i,                                                      i,
787                                                      filled, stroked,                                                      filled, stroked,
# Line 510  class MapCanvas(wxWindow): Line 792  class MapCanvas(wxWindow):
792                          select_shape = i                          select_shape = i
793                          break                          break
794              elif shapetype == SHAPETYPE_ARC:              elif shapetype == SHAPETYPE_ARC:
795                  for i in range(layer.NumShapes()):                  for i in shape_ids:
796                      result = point_in_polygon_shape(layer.shapefile.cobject(),                      result = point_in_polygon_shape(layer.shapefile.cobject(),
797                                                      i, 0, 1,                                                      i, 0, 1,
798                                                      map_proj, layer_proj,                                                      map_proj, layer_proj,
# Line 520  class MapCanvas(wxWindow): Line 802  class MapCanvas(wxWindow):
802                          select_shape = i                          select_shape = i
803                          break                          break
804              elif shapetype == SHAPETYPE_POINT:              elif shapetype == SHAPETYPE_POINT:
805                  for i in range(layer.NumShapes()):                  for i in shape_ids:
806                      shape = layer.Shape(i)                      shape = layer.Shape(i)
807                      x, y = shape.Points()[0]                      x, y = shape.Points()[0]
808                      if inverse:                      if inverse:
# Line 537  class MapCanvas(wxWindow): Line 819  class MapCanvas(wxWindow):
819                  return layer, select_shape                  return layer, select_shape
820          return None, None          return None, None
821    
822      def SelectShapeAt(self, x, y):      def SelectShapeAt(self, x, y, layer = None):
823          layer, shape = self.find_shape_at(x, y)          """\
824          self.interactor.SelectLayerAndShape(layer, shape)          Select and return the shape and its layer at window position (x, y)
825    
826            If layer is given, only search in that layer. If no layer is
827            given, search through all layers.
828    
829            Return a tuple (layer, shapeid). If no shape is found, return
830            (None, None).
831            """
832            layer, shape = result = self.find_shape_at(x, y, searched_layer=layer)
833            # If layer is None, then shape will also be None. We don't want
834            # to deselect the currently selected layer, so we simply select
835            # the already selected layer again.
836            if layer is None:
837                layer = self.selection.SelectedLayer()
838                shapes = []
839            else:
840                shapes = [shape]
841            self.selection.SelectShapes(layer, shapes)
842            return result
843    
844      def LabelShapeAt(self, x, y):      def LabelShapeAt(self, x, y):
845            """Add or remove a label at window position x, y.
846    
847            If there's a label at the given position, remove it. Otherwise
848            determine the shape at the position, run the label dialog and
849            unless the user cancels the dialog, add a laber.
850            """
851          ox = x; oy = y          ox = x; oy = y
852          label_layer = self.map.LabelLayer()          label_layer = self.map.LabelLayer()
853          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.23  
changed lines
  Added in v.799

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26