/[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 246 by bh, Mon Jul 29 13:38:04 2002 UTC revision 565 by jonathan, Wed Mar 26 11:07:40 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 24  from wxproj import point_in_polygon_shap Line 24  from wxproj import point_in_polygon_shap
24    
25    
26  from Thuban.Model.messages import MAP_PROJECTION_CHANGED, \  from Thuban.Model.messages import MAP_PROJECTION_CHANGED, \
27       LAYERS_CHANGED, LAYER_LEGEND_CHANGED, LAYER_VISIBILITY_CHANGED       MAP_LAYERS_CHANGED, LAYER_CHANGED, LAYER_VISIBILITY_CHANGED
28  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \
29       SHAPETYPE_POINT       SHAPETYPE_POINT
30  from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \  from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \
31       ALIGN_LEFT, ALIGN_RIGHT       ALIGN_LEFT, ALIGN_RIGHT
32  from Thuban.Lib.connector import Publisher  from Thuban.Lib.connector import Publisher
33    from Thuban.Model.color import Color
34    
35    from selection import Selection
36  from renderer import ScreenRenderer, PrinterRender  from renderer import ScreenRenderer, PrinterRender
37    
38  import labeldialog  import labeldialog
39    
40  from messages import SELECTED_SHAPE, VIEW_POSITION  from messages import LAYER_SELECTED, SHAPES_SELECTED, VIEW_POSITION
41    
42    
43  #  #
# Line 129  class ZoomInTool(RectTool): Line 131  class ZoomInTool(RectTool):
131              Tool.MouseUp(self, event)              Tool.MouseUp(self, event)
132              sx, sy = self.start              sx, sy = self.start
133              cx, cy = self.current              cx, cy = self.current
134              if sx == cx and sy == cy:              if sx == cx or sy == cy:
135                  # Just a mouse click. Simply zoom in by a factor of two                  # Just a mouse click or a degenerate rectangle. Simply
136                    # zoom in by a factor of two
137                    # FIXME: For a click this is the desired behavior but should we
138                    # really do this for degenrate rectagles as well or
139                    # should we ignore them?
140                  self.view.ZoomFactor(2, center = (cx, cy))                  self.view.ZoomFactor(2, center = (cx, cy))
141              else:              else:
142                  # A drag. Zoom in to the rectangle                  # A drag. Zoom in to the rectangle
# Line 149  class ZoomOutTool(RectTool): Line 155  class ZoomOutTool(RectTool):
155              Tool.MouseUp(self, event)              Tool.MouseUp(self, event)
156              sx, sy = self.start              sx, sy = self.start
157              cx, cy = self.current              cx, cy = self.current
158              if sx == cx and sy == cy:              if sx == cx or sy == cy:
159                  # Just a mouse click. Simply zoom out by a factor of two                  # Just a mouse click or a degenerate rectangle. Simply
160                    # zoom out by a factor of two.
161                    # FIXME: For a click this is the desired behavior but should we
162                    # really do this for degenrate rectagles as well or
163                    # should we ignore them?
164                  self.view.ZoomFactor(0.5, center = (cx, cy))                  self.view.ZoomFactor(0.5, center = (cx, cy))
165              else:              else:
166                  # A drag. Zoom out to the rectangle                  # A drag. Zoom out to the rectangle
# Line 248  class MapCanvas(wxWindow, Publisher): Line 258  class MapCanvas(wxWindow, Publisher):
258    
259      """A widget that displays a map and offers some interaction"""      """A widget that displays a map and offers some interaction"""
260    
261      def __init__(self, parent, winid, interactor):      # Some messages that can be subscribed/unsubscribed directly through
262        # the MapCanvas come in fact from other objects. This is a map to
263        # map those messages to the names of the instance variables they
264        # actually come from. This delegation is implemented in the
265        # Subscribe and unsubscribed methods
266        delegated_messages = {LAYER_SELECTED: "selection",
267                              SHAPES_SELECTED: "selection"}
268    
269        # Methods delegated to some instance variables. The delegation is
270        # implemented in the __getattr__ method.
271        delegated_methods = {"SelectLayer": "selection",
272                             "SelectShapes": "selection",
273                             "SelectedLayer": "selection",
274                             "HasSelectedLayer": "selection"}
275    
276        def __init__(self, parent, winid):
277          wxWindow.__init__(self, parent, winid)          wxWindow.__init__(self, parent, winid)
278          self.SetBackgroundColour(wxColour(255, 255, 255))          self.SetBackgroundColour(wxColour(255, 255, 255))
279    
# Line 271  class MapCanvas(wxWindow, Publisher): Line 296  class MapCanvas(wxWindow, Publisher):
296          # if the mouse is outside the window.          # if the mouse is outside the window.
297          self.current_position = None          self.current_position = None
298    
         # 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()  
   
299          # the bitmap serving as backing store          # the bitmap serving as backing store
300          self.bitmap = None          self.bitmap = None
301    
302          # the interactor          # the selection
303          self.interactor = interactor          self.selection = Selection()
304          self.interactor.Subscribe(SELECTED_SHAPE, self.shape_selected)          self.selection.Subscribe(SHAPES_SELECTED , self.shape_selected)
305    
306          # keep track of which layers/shapes are selected to make sure we          # keep track of which layers/shapes are selected to make sure we
307          # only redraw when necessary          # only redraw when necessary
# Line 298  class MapCanvas(wxWindow, Publisher): Line 315  class MapCanvas(wxWindow, Publisher):
315          EVT_MOTION(self, self.OnMotion)          EVT_MOTION(self, self.OnMotion)
316          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)
317          wx.EVT_SIZE(self, self.OnSize)          wx.EVT_SIZE(self, self.OnSize)
         wx.EVT_IDLE(self, self.OnIdle)  
318    
319      def __del__(self):      def __del__(self):
320          wxWindow.__del__(self)          wxWindow.__del__(self)
321          Publisher.__del__(self)          Publisher.__del__(self)
322    
323        def Subscribe(self, channel, *args):
324            """Extend the inherited method to handle delegated messages.
325    
326            If channel is one of the delegated messages call the appropriate
327            object's Subscribe method. Otherwise just call the inherited
328            method.
329            """
330            if channel in self.delegated_messages:
331                object = getattr(self, self.delegated_messages[channel])
332                object.Subscribe(channel, *args)
333            else:
334                Publisher.Subscribe(self, channel, *args)
335    
336        def Unsubscribe(self, channel, *args):
337            """Extend the inherited method to handle delegated messages.
338    
339            If channel is one of the delegated messages call the appropriate
340            object's Unsubscribe method. Otherwise just call the inherited
341            method.
342            """
343            if channel in self.delegated_messages:
344                object = getattr(self, self.delegated_messages[channel])
345                object.Unsubscribe(channel, *args)
346            else:
347                Publisher.Unsubscribe(self, channel, *args)
348    
349        def __getattr__(self, attr):
350            if attr in self.delegated_methods:
351                return getattr(getattr(self, self.delegated_methods[attr]), attr)
352            raise AttributeError(attr)
353    
354      def OnPaint(self, event):      def OnPaint(self, event):
355          dc = wxPaintDC(self)          dc = wxPaintDC(self)
356          if self.map is not None and self.map.HasLayers():          if self.map is not None and self.map.HasLayers():
357              # We have a non-empty map. Redraw it in idle time              self.do_redraw()
             self.redraw_on_idle = 1  
             # update the region that has to be redrawn  
             self.update_region.UnionRegion(self.GetUpdateRegion())  
358          else:          else:
359              # 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
360              # the screen.              # the screen.
# Line 323  class MapCanvas(wxWindow, Publisher): Line 367  class MapCanvas(wxWindow, Publisher):
367              dc.Clear()              dc.Clear()
368              dc.EndDrawing()              dc.EndDrawing()
369    
             # clear the region  
             self.update_region = wx.wxRegion()  
   
370      def do_redraw(self):      def do_redraw(self):
371          # This should only be called if we have a non-empty map.          # This should only be called if we have a non-empty map.
372    
         # 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()  
   
373          # Get the window size.          # Get the window size.
374          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
375    
# Line 351  class MapCanvas(wxWindow, Publisher): Line 387  class MapCanvas(wxWindow, Publisher):
387              dc.SetPen(wx.wxTRANSPARENT_PEN)              dc.SetPen(wx.wxTRANSPARENT_PEN)
388              dc.DrawRectangle(0, 0, width, height)              dc.DrawRectangle(0, 0, width, height)
389    
390              if 1: #self.interactor.selected_map is self.map:              selected_layer = self.selection.SelectedLayer()
391                  selected_layer = self.interactor.selected_layer              selected_shapes = self.selection.SelectedShapes()
                 selected_shape = self.interactor.selected_shape  
             else:  
                 selected_layer = None  
                 selected_shape = None  
392    
393              # draw the map into the bitmap              # draw the map into the bitmap
394              renderer = ScreenRenderer(dc, self.scale, self.offset)              renderer = ScreenRenderer(dc, self.scale, self.offset)
395    
396              # Pass the entire bitmap as update_region to the renderer.              # Pass the entire bitmap as update region to the renderer.
397              # We're redrawing the whole bitmap, after all.              # We're redrawing the whole bitmap, after all.
398              renderer.RenderMap(self.map, (0, 0, width, height),              renderer.RenderMap(self.map, (0, 0, width, height),
399                                 selected_layer, selected_shape)                                 selected_layer, selected_shapes)
400    
401              dc.EndDrawing()              dc.EndDrawing()
402              dc.SelectObject(wx.wxNullBitmap)              dc.SelectObject(wx.wxNullBitmap)
# Line 385  class MapCanvas(wxWindow, Publisher): Line 417  class MapCanvas(wxWindow, Publisher):
417          printout.Destroy()          printout.Destroy()
418    
419      def SetMap(self, map):      def SetMap(self, map):
420          redraw_channels = (LAYERS_CHANGED, LAYER_LEGEND_CHANGED,          redraw_channels = (MAP_LAYERS_CHANGED, LAYER_CHANGED,
421                             LAYER_VISIBILITY_CHANGED)                             LAYER_VISIBILITY_CHANGED)
422          if self.map is not None:          if self.map is not None:
423              for channel in redraw_channels:              for channel in redraw_channels:
# Line 393  class MapCanvas(wxWindow, Publisher): Line 425  class MapCanvas(wxWindow, Publisher):
425              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,
426                                   self.projection_changed)                                   self.projection_changed)
427          self.map = map          self.map = map
428            self.selection.ClearSelection()
429          if self.map is not None:          if self.map is not None:
430              for channel in redraw_channels:              for channel in redraw_channels:
431                  self.map.Subscribe(channel, self.full_redraw)                  self.map.Subscribe(channel, self.full_redraw)
# Line 404  class MapCanvas(wxWindow, Publisher): Line 437  class MapCanvas(wxWindow, Publisher):
437          self.full_redraw()          self.full_redraw()
438    
439      def Map(self):      def Map(self):
440            """Return the map displayed by this canvas"""
441          return self.map          return self.map
442    
443      def redraw(self, *args):      def redraw(self, *args):
# Line 437  class MapCanvas(wxWindow, Publisher): Line 471  class MapCanvas(wxWindow, Publisher):
471          return ((x - offx) / self.scale, (offy - y) / self.scale)          return ((x - offx) / self.scale, (offy - y) / self.scale)
472    
473      def FitRectToWindow(self, rect):      def FitRectToWindow(self, rect):
474            """Fit the rectangular region given by rect into the window.
475    
476            Set scale so that rect (in projected coordinates) just fits into
477            the window and center it.
478            """
479          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
480          llx, lly, urx, ury = rect          llx, lly, urx, ury = rect
481          if llx == urx or lly == ury:          if llx == urx or lly == ury:
# Line 450  class MapCanvas(wxWindow, Publisher): Line 489  class MapCanvas(wxWindow, Publisher):
489          self.set_view_transform(scale, (offx, offy))          self.set_view_transform(scale, (offx, offy))
490    
491      def FitMapToWindow(self):      def FitMapToWindow(self):
492          """\          """Fit the map to the window
493          Set the scale and offset so that the map is centered in the  
494          window          Set the scale so that the map fits exactly into the window and
495            center it in the window.
496          """          """
497          bbox = self.map.ProjectedBoundingBox()          bbox = self.map.ProjectedBoundingBox()
498          if bbox is not None:          if bbox is not None:
# Line 478  class MapCanvas(wxWindow, Publisher): Line 518  class MapCanvas(wxWindow, Publisher):
518          self.set_view_transform(scale, offset)          self.set_view_transform(scale, offset)
519    
520      def ZoomOutToRect(self, rect):      def ZoomOutToRect(self, rect):
521          # rect is given in window coordinates          """Zoom out to fit the currently visible region into rect.
522    
523            The rect parameter is given in window coordinates
524            """
525          # determine the bbox of the displayed region in projected          # determine the bbox of the displayed region in projected
526          # coordinates          # coordinates
527          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
# Line 496  class MapCanvas(wxWindow, Publisher): Line 538  class MapCanvas(wxWindow, Publisher):
538          self.set_view_transform(scale, (offx, offy))          self.set_view_transform(scale, (offx, offy))
539    
540      def Translate(self, dx, dy):      def Translate(self, dx, dy):
541            """Move the map by dx, dy pixels"""
542          offx, offy = self.offset          offx, offy = self.offset
543          self.set_view_transform(self.scale, (offx + dx, offy + dy))          self.set_view_transform(self.scale, (offx + dx, offy + dy))
544    
545        def SelectTool(self, tool):
546            """Make tool the active tool.
547    
548            The parameter should be an instance of Tool or None to indicate
549            that no tool is active.
550            """
551            self.tool = tool
552    
553      def ZoomInTool(self):      def ZoomInTool(self):
554          self.tool = ZoomInTool(self)          """Start the zoom in tool"""
555            self.SelectTool(ZoomInTool(self))
556    
557      def ZoomOutTool(self):      def ZoomOutTool(self):
558          self.tool = ZoomOutTool(self)          """Start the zoom out tool"""
559            self.SelectTool(ZoomOutTool(self))
560    
561      def PanTool(self):      def PanTool(self):
562          self.tool = PanTool(self)          """Start the pan tool"""
563            self.SelectTool(PanTool(self))
564    
565      def IdentifyTool(self):      def IdentifyTool(self):
566          self.tool = IdentifyTool(self)          """Start the identify tool"""
567            self.SelectTool(IdentifyTool(self))
568    
569      def LabelTool(self):      def LabelTool(self):
570          self.tool = LabelTool(self)          """Start the label tool"""
571            self.SelectTool(LabelTool(self))
572    
573      def CurrentTool(self):      def CurrentTool(self):
574            """Return the name of the current tool or None if no tool is active"""
575          return self.tool and self.tool.Name() or None          return self.tool and self.tool.Name() or None
576    
577      def CurrentPosition(self):      def CurrentPosition(self):
# Line 554  class MapCanvas(wxWindow, Publisher): Line 611  class MapCanvas(wxWindow, Publisher):
611              self.dragging = 1              self.dragging = 1
612    
613      def OnLeftUp(self, event):      def OnLeftUp(self, event):
         self.ReleaseMouse()  
614          self.set_current_position(event)          self.set_current_position(event)
615          if self.dragging:          if self.dragging:
616              self.tool.Hide(self.drag_dc)              self.ReleaseMouse()
617              self.tool.MouseUp(event)              try:
618              self.drag_dc = None                  self.tool.Hide(self.drag_dc)
619          self.dragging = 0                  self.tool.MouseUp(event)
620                finally:
621                    self.drag_dc = None
622                    self.dragging = 0
623    
624      def OnMotion(self, event):      def OnMotion(self, event):
625          self.set_current_position(event)          self.set_current_position(event)
# Line 572  class MapCanvas(wxWindow, Publisher): Line 631  class MapCanvas(wxWindow, Publisher):
631      def OnLeaveWindow(self, event):      def OnLeaveWindow(self, event):
632          self.set_current_position(None)          self.set_current_position(None)
633    
     def OnIdle(self, event):  
         if self.redraw_on_idle:  
             self.do_redraw()  
         self.redraw_on_idle = 0  
   
634      def OnSize(self, event):      def OnSize(self, event):
635          # 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
636          # 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 587  class MapCanvas(wxWindow, Publisher): Line 641  class MapCanvas(wxWindow, Publisher):
641          self.full_redraw()          self.full_redraw()
642    
643      def shape_selected(self, layer, shape):      def shape_selected(self, layer, shape):
644          """Redraw the map.          """Receiver for the SHAPES_SELECTED messages. Redraw the map."""
645            # The selection object takes care that it only issues
646          Receiver for the SELECTED_SHAPE messages. Try to redraw only          # SHAPES_SELECTED messages when the set of selected shapes has
647          when necessary.          # actually changed, so we can do a full redraw unconditionally.
648          """          # FIXME: We should perhaps try to limit the redraw to the are
649          # A redraw is necessary when the display has to change, which          # actually covered by the shapes before and after the selection
650          # means that either the status changes from having no selection          # change.
651          # 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  
652    
653      def unprojected_rect_around_point(self, x, y):      def unprojected_rect_around_point(self, x, y, dist):
654          """return a rect a few pixels around (x, y) in unprojected corrdinates          """return a rect dist pixels around (x, y) in unprojected corrdinates
655    
656          The return value is a tuple (minx, miny, maxx, maxy) suitable a          The return value is a tuple (minx, miny, maxx, maxy) suitable a
657          parameter to a layer's ShapesInRegion method.          parameter to a layer's ShapesInRegion method.
# Line 622  class MapCanvas(wxWindow, Publisher): Line 665  class MapCanvas(wxWindow, Publisher):
665          xs = []          xs = []
666          ys = []          ys = []
667          for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):          for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
668              px, py = self.win_to_proj(x + dx, y + dy)              px, py = self.win_to_proj(x + dist * dx, y + dist * dy)
669              if inverse:              if inverse:
670                  px, py = inverse(px, py)                  px, py = inverse(px, py)
671              xs.append(px)              xs.append(px)
# Line 651  class MapCanvas(wxWindow, Publisher): Line 694  class MapCanvas(wxWindow, Publisher):
694          scale = self.scale          scale = self.scale
695          offx, offy = self.offset          offx, offy = self.offset
696    
         box = self.unprojected_rect_around_point(px, py)  
   
697          if select_labels:          if select_labels:
698              labels = self.map.LabelLayer().Labels()              labels = self.map.LabelLayer().Labels()
699    
# Line 699  class MapCanvas(wxWindow, Publisher): Line 740  class MapCanvas(wxWindow, Publisher):
740              if not layer.Visible():              if not layer.Visible():
741                  continue                  continue
742    
743              filled = layer.fill is not None              filled = layer.GetClassification().GetDefaultFill() \
744              stroked = layer.stroke is not None                       is not Color.None
745                stroked = layer.GetClassification().GetDefaultLineColor() \
746                          is not Color.None
747    
748              layer_proj = layer.projection              layer_proj = layer.projection
749              if layer_proj is not None:              if layer_proj is not None:
# Line 712  class MapCanvas(wxWindow, Publisher): Line 755  class MapCanvas(wxWindow, Publisher):
755    
756              select_shape = -1              select_shape = -1
757    
758                # Determine the ids of the shapes that overlap a tiny area
759                # around the point. For layers containing points we have to
760                # choose a larger size of the box we're testing agains so
761                # that we take the size of the markers into account
762                # FIXME: Once the markers are more flexible this part has to
763                # become more flexible too, of course
764                if shapetype == SHAPETYPE_POINT:
765                    box = self.unprojected_rect_around_point(px, py, 5)
766                else:
767                    box = self.unprojected_rect_around_point(px, py, 1)
768              shape_ids = layer.ShapesInRegion(box)              shape_ids = layer.ShapesInRegion(box)
769              shape_ids.reverse()              shape_ids.reverse()
770    
# Line 769  class MapCanvas(wxWindow, Publisher): Line 822  class MapCanvas(wxWindow, Publisher):
822          # to deselect the currently selected layer, so we simply select          # to deselect the currently selected layer, so we simply select
823          # the already selected layer again.          # the already selected layer again.
824          if layer is None:          if layer is None:
825              layer = self.interactor.SelectedLayer()              layer = self.selection.SelectedLayer()
826          self.interactor.SelectLayerAndShape(layer, shape)              shapes = []
827            else:
828                shapes = [shape]
829            self.selection.SelectShapes(layer, shapes)
830          return result          return result
831    
832      def LabelShapeAt(self, x, y):      def LabelShapeAt(self, x, y):
833            """Add or remove a label at window position x, y.
834    
835            If there's a label at the given position, remove it. Otherwise
836            determine the shape at the position, run the label dialog and
837            unless the user cancels the dialog, add a laber.
838            """
839          ox = x; oy = y          ox = x; oy = y
840          label_layer = self.map.LabelLayer()          label_layer = self.map.LabelLayer()
841          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.246  
changed lines
  Added in v.565

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26