/[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 239 by bh, Wed Jul 24 17:15:54 2002 UTC revision 940 by jonathan, Tue May 20 15:25:33 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    # Frank Koormann <[email protected]>
5  #  #
6  # This program is free software under the GPL (>=v2)  # This program is free software under the GPL (>=v2)
7  # Read the file COPYING coming with Thuban for details.  # Read the file COPYING coming with Thuban for details.
# Line 11  Classes for display of a map and interac Line 12  Classes for display of a map and interac
12    
13  __version__ = "$Revision$"  __version__ = "$Revision$"
14    
15    from Thuban import _
16    
17    import sys
18    import os.path
19    
20  from math import hypot  from math import hypot
21    
22  from wxPython.wx import wxWindow,\  from wxPython.wx import wxWindow,\
23       wxPaintDC, wxColour, wxClientDC, wxINVERT, wxTRANSPARENT_BRUSH, wxFont,\       wxPaintDC, wxColour, wxClientDC, wxINVERT, wxTRANSPARENT_BRUSH, wxFont,\
24       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, \
25         wxBITMAP_TYPE_XPM, wxBeginBusyCursor, wxEndBusyCursor, wxCursor, \
26         wxImageFromBitmap, wxPlatform
27    
28    # Export related stuff
29    if wxPlatform == '__WXMSW__':
30        from wxPython.wx import wxMetaFileDC
31    from wxPython.wx import wxFileDialog, wxSAVE, wxOVERWRITE_PROMPT, wxID_OK
32    
33  from wxPython import wx  from wxPython import wx
34    
35  from wxproj import point_in_polygon_shape, shape_centroid  from wxproj import point_in_polygon_shape, shape_centroid
36    
   
37  from Thuban.Model.messages import MAP_PROJECTION_CHANGED, \  from Thuban.Model.messages import MAP_PROJECTION_CHANGED, \
38       LAYERS_CHANGED, LAYER_LEGEND_CHANGED, LAYER_VISIBILITY_CHANGED       MAP_LAYERS_CHANGED, LAYER_CHANGED, LAYER_VISIBILITY_CHANGED
39  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \
40       SHAPETYPE_POINT       SHAPETYPE_POINT
41  from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \  from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \
42       ALIGN_LEFT, ALIGN_RIGHT       ALIGN_LEFT, ALIGN_RIGHT
43  from Thuban.Lib.connector import Publisher  from Thuban.Lib.connector import Publisher
44    from Thuban.Model.color import Color
45    
46    import resource
47    
48  from renderer import ScreenRenderer, PrinterRender  from selection import Selection
49    from renderer import ScreenRenderer, ExportRenderer, PrinterRenderer
50    
51  import labeldialog  import labeldialog
52    
53  from messages import SELECTED_SHAPE, VIEW_POSITION  from messages import LAYER_SELECTED, SHAPES_SELECTED, VIEW_POSITION, \
54                         SCALE_CHANGED
55    
56    
57  #  #
# Line 129  class ZoomInTool(RectTool): Line 145  class ZoomInTool(RectTool):
145              Tool.MouseUp(self, event)              Tool.MouseUp(self, event)
146              sx, sy = self.start              sx, sy = self.start
147              cx, cy = self.current              cx, cy = self.current
148              if sx == cx and sy == cy:              if sx == cx or sy == cy:
149                  # Just a mouse click. Simply zoom in by a factor of two                  # Just a mouse click or a degenerate rectangle. Simply
150                    # zoom in by a factor of two
151                    # FIXME: For a click this is the desired behavior but should we
152                    # really do this for degenrate rectagles as well or
153                    # should we ignore them?
154                  self.view.ZoomFactor(2, center = (cx, cy))                  self.view.ZoomFactor(2, center = (cx, cy))
155              else:              else:
156                  # A drag. Zoom in to the rectangle                  # A drag. Zoom in to the rectangle
# Line 149  class ZoomOutTool(RectTool): Line 169  class ZoomOutTool(RectTool):
169              Tool.MouseUp(self, event)              Tool.MouseUp(self, event)
170              sx, sy = self.start              sx, sy = self.start
171              cx, cy = self.current              cx, cy = self.current
172              if sx == cx and sy == cy:              if sx == cx or sy == cy:
173                  # Just a mouse click. Simply zoom out by a factor of two                  # Just a mouse click or a degenerate rectangle. Simply
174                    # zoom out by a factor of two.
175                    # FIXME: For a click this is the desired behavior but should we
176                    # really do this for degenrate rectagles as well or
177                    # should we ignore them?
178                  self.view.ZoomFactor(0.5, center = (cx, cy))                  self.view.ZoomFactor(0.5, center = (cx, cy))
179              else:              else:
180                  # A drag. Zoom out to the rectangle                  # A drag. Zoom out to the rectangle
# Line 184  class PanTool(Tool): Line 208  class PanTool(Tool):
208              sx, sy = self.start              sx, sy = self.start
209              cx, cy = self.current              cx, cy = self.current
210              self.view.Translate(cx - sx, cy - sy)              self.view.Translate(cx - sx, cy - sy)
211            
212  class IdentifyTool(Tool):  class IdentifyTool(Tool):
213    
214      """The "Identify" Tool"""      """The "Identify" Tool"""
215        
216      def Name(self):      def Name(self):
217          return "IdentifyTool"          return "IdentifyTool"
218    
# Line 207  class LabelTool(Tool): Line 231  class LabelTool(Tool):
231          self.view.LabelShapeAt(event.m_x, event.m_y)          self.view.LabelShapeAt(event.m_x, event.m_y)
232    
233    
   
   
234  class MapPrintout(wx.wxPrintout):  class MapPrintout(wx.wxPrintout):
235    
236      """      """
237      wxPrintout class for printing Thuban maps      wxPrintout class for printing Thuban maps
238      """      """
239    
240      def __init__(self, map):      def __init__(self, canvas, map, region, selected_layer, selected_shapes):
241          wx.wxPrintout.__init__(self)          wx.wxPrintout.__init__(self)
242            self.canvas = canvas
243          self.map = map          self.map = map
244            self.region = region
245            self.selected_layer = selected_layer
246            self.selected_shapes = selected_shapes
247    
248      def GetPageInfo(self):      def GetPageInfo(self):
249          return (1, 1, 1, 1)          return (1, 1, 1, 1)
# Line 231  class MapPrintout(wx.wxPrintout): Line 257  class MapPrintout(wx.wxPrintout):
257    
258      def draw_on_dc(self, dc):      def draw_on_dc(self, dc):
259          width, height = self.GetPageSizePixels()          width, height = self.GetPageSizePixels()
260          llx, lly, urx, ury = self.map.ProjectedBoundingBox()          scale, offset, mapregion = OutputTransform(self.canvas.scale,
261          scalex = width / (urx - llx)                                                     self.canvas.offset,
262          scaley = height / (ury - lly)                                                     self.canvas.GetSizeTuple(),
263          scale = min(scalex, scaley)                                                     self.GetPageSizePixels())
         offx = 0.5 * (width - (urx + llx) * scale)  
         offy = 0.5 * (height + (ury + lly) * scale)  
   
264          resx, resy = self.GetPPIPrinter()          resx, resy = self.GetPPIPrinter()
265          renderer = PrinterRender(dc, scale, (offx, offy), resolution = resx)          renderer = PrinterRenderer(dc, scale, offset, resolution = resy)
266          renderer.RenderMap(self.map)          x, y, width, height = self.region
267            canvas_scale = self.canvas.scale
268            renderer.RenderMap(self.map,
269                               (0,0,
270                                    (width/canvas_scale)*scale,
271                                    (height/canvas_scale)*scale),
272                                    mapregion,
273                               self.selected_layer, self.selected_shapes)
274          return wx.true          return wx.true
275            
276    
277  class MapCanvas(wxWindow, Publisher):  class MapCanvas(wxWindow, Publisher):
278    
279      """A widget that displays a map and offers some interaction"""      """A widget that displays a map and offers some interaction"""
280    
281      def __init__(self, parent, winid, interactor):      # Some messages that can be subscribed/unsubscribed directly through
282        # the MapCanvas come in fact from other objects. This is a dict
283        # mapping those messages to the names of the instance variables they
284        # actually come from. The delegation is implemented in the Subscribe
285        # and Unsubscribe methods
286        delegated_messages = {LAYER_SELECTED: "selection",
287                              SHAPES_SELECTED: "selection"}
288    
289        # Methods delegated to some instance variables. The delegation is
290        # implemented in the __getattr__ method.
291        delegated_methods = {"SelectLayer": "selection",
292                             "SelectShapes": "selection",
293                             "SelectedLayer": "selection",
294                             "HasSelectedLayer": "selection",
295                             "HasSelectedShapes": "selection",
296                             "SelectedShapes": "selection"}
297    
298        def __init__(self, parent, winid):
299          wxWindow.__init__(self, parent, winid)          wxWindow.__init__(self, parent, winid)
300          self.SetBackgroundColour(wxColour(255, 255, 255))          self.SetBackgroundColour(wxColour(255, 255, 255))
301    
# Line 271  class MapCanvas(wxWindow, Publisher): Line 318  class MapCanvas(wxWindow, Publisher):
318          # if the mouse is outside the window.          # if the mouse is outside the window.
319          self.current_position = None          self.current_position = None
320    
         # 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()  
   
321          # the bitmap serving as backing store          # the bitmap serving as backing store
322          self.bitmap = None          self.bitmap = None
323    
324          # the interactor          # the selection
325          self.interactor = interactor          self.selection = Selection()
326          self.interactor.Subscribe(SELECTED_SHAPE, self.shape_selected)          self.selection.Subscribe(SHAPES_SELECTED , self.shape_selected)
327    
328          # keep track of which layers/shapes are selected to make sure we          # keep track of which layers/shapes are selected to make sure we
329          # only redraw when necessary          # only redraw when necessary
# Line 298  class MapCanvas(wxWindow, Publisher): Line 337  class MapCanvas(wxWindow, Publisher):
337          EVT_MOTION(self, self.OnMotion)          EVT_MOTION(self, self.OnMotion)
338          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)
339          wx.EVT_SIZE(self, self.OnSize)          wx.EVT_SIZE(self, self.OnSize)
         wx.EVT_IDLE(self, self.OnIdle)  
340    
341      def __del__(self):      def __del__(self):
342          wxWindow.__del__(self)          wxWindow.__del__(self)
343          Publisher.__del__(self)          Publisher.__del__(self)
344    
345        def Subscribe(self, channel, *args):
346            """Extend the inherited method to handle delegated messages.
347    
348            If channel is one of the delegated messages call the appropriate
349            object's Subscribe method. Otherwise just call the inherited
350            method.
351            """
352            if channel in self.delegated_messages:
353                object = getattr(self, self.delegated_messages[channel])
354                object.Subscribe(channel, *args)
355            else:
356                Publisher.Subscribe(self, channel, *args)
357    
358        def Unsubscribe(self, channel, *args):
359            """Extend the inherited method to handle delegated messages.
360    
361            If channel is one of the delegated messages call the appropriate
362            object's Unsubscribe method. Otherwise just call the inherited
363            method.
364            """
365            if channel in self.delegated_messages:
366                object = getattr(self, self.delegated_messages[channel])
367                object.Unsubscribe(channel, *args)
368            else:
369                Publisher.Unsubscribe(self, channel, *args)
370    
371        def __getattr__(self, attr):
372            if attr in self.delegated_methods:
373                return getattr(getattr(self, self.delegated_methods[attr]), attr)
374            raise AttributeError(attr)
375    
376      def OnPaint(self, event):      def OnPaint(self, event):
377          dc = wxPaintDC(self)          dc = wxPaintDC(self)
378          if self.map is not None and self.map.HasLayers():          clear = self.map is None or not self.map.HasLayers()
379              # We have a non-empty map. Redraw it in idle time  
380              self.redraw_on_idle = 1          wxBeginBusyCursor()
381              # update the region that has to be redrawn  
382              self.update_region.UnionRegion(self.GetUpdateRegion())          if not clear:
383          else:              try:
384                    self.do_redraw()
385                except:
386                    print "Error during drawing:", sys.exc_info()[0]
387                    clear = True
388    
389            if clear:
390              # 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
391              # the screen.              # the screen.
392                
393              # XXX it's probably possible to get rid of this. The              # XXX it's probably possible to get rid of this. The
394              # background color of the window is already white and the              # background color of the window is already white and the
395              # only thing we may have to do is to call self.Refresh()              # only thing we may have to do is to call self.Refresh()
396              # with a true argument in the right places.              # with a true argument in the right places.
397              dc.BeginDrawing()              dc.BeginDrawing()
398              dc.Clear()                          dc.Clear()
399              dc.EndDrawing()              dc.EndDrawing()
400    
401              # clear the region          wxEndBusyCursor()
             self.update_region = wx.wxRegion()  
402    
403      def do_redraw(self):      def do_redraw(self):
404          # This should only be called if we have a non-empty map.          # This should only be called if we have a non-empty map.
405    
         # 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()  
   
406          # Get the window size.          # Get the window size.
407          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
408    
# Line 347  class MapCanvas(wxWindow, Publisher): Line 416  class MapCanvas(wxWindow, Publisher):
416              dc.BeginDrawing()              dc.BeginDrawing()
417    
418              # clear the background              # clear the background
419              dc.SetBrush(wx.wxWHITE_BRUSH)              #dc.SetBrush(wx.wxWHITE_BRUSH)
420              dc.SetPen(wx.wxTRANSPARENT_PEN)              #dc.SetPen(wx.wxTRANSPARENT_PEN)
421              dc.DrawRectangle(0, 0, width, height)              #dc.DrawRectangle(0, 0, width, height)
422                dc.SetBackground(wx.wxWHITE_BRUSH)
423              if 1: #self.interactor.selected_map is self.map:              dc.Clear()
424                  selected_layer = self.interactor.selected_layer  
425                  selected_shape = self.interactor.selected_shape              selected_layer = self.selection.SelectedLayer()
426              else:              selected_shapes = self.selection.SelectedShapes()
                 selected_layer = None  
                 selected_shape = None  
427    
428              # draw the map into the bitmap              # draw the map into the bitmap
429              renderer = ScreenRenderer(dc, self.scale, self.offset)              renderer = ScreenRenderer(dc, self.scale, self.offset)
430    
431              # Pass the entire bitmap as update_region to the renderer.              # Pass the entire bitmap as update region to the renderer.
432              # We're redrawing the whole bitmap, after all.              # We're redrawing the whole bitmap, after all.
433              renderer.RenderMap(self.map, (0, 0, width, height),              renderer.RenderMap(self.map, (0, 0, width, height),
434                                 selected_layer, selected_shape)                                 selected_layer, selected_shapes)
435    
436              dc.EndDrawing()              dc.EndDrawing()
437              dc.SelectObject(wx.wxNullBitmap)              dc.SelectObject(wx.wxNullBitmap)
# Line 378  class MapCanvas(wxWindow, Publisher): Line 445  class MapCanvas(wxWindow, Publisher):
445          clientdc.Blit(0, 0, width, height, dc, 0, 0)          clientdc.Blit(0, 0, width, height, dc, 0, 0)
446          clientdc.EndDrawing()          clientdc.EndDrawing()
447    
448        def Export(self):
449            if hasattr(self, "export_path"):
450                export_path = self.export_path
451            else:
452                export_path="."
453            dlg = wxFileDialog(self, _("Export Map"), export_path, "",
454                               "Enhanced Metafile (*.wmf)|*.wmf",
455                               wxSAVE|wxOVERWRITE_PROMPT)
456            if dlg.ShowModal() == wxID_OK:
457                self.export_path = os.path.dirname(dlg.GetPath())
458                dc = wxMetaFileDC(dlg.GetPath())
459        
460                scale, offset, mapregion = OutputTransform(self.scale,
461                                                           self.offset,
462                                                           self.GetSizeTuple(),
463                                                           dc.GetSizeTuple())
464    
465                selected_layer = self.selection.SelectedLayer()
466                selected_shapes = self.selection.SelectedShapes()
467    
468                renderer = ExportRenderer(dc, scale, offset)
469    
470                # Pass the entire bitmap as update region to the renderer.
471                # We're redrawing the whole bitmap, after all.
472                width, height = self.GetSizeTuple()
473                renderer.RenderMap(self.map,
474                                    (0,0,
475                                        (width/self.scale)*scale,
476                                        (height/self.scale)*scale),
477                                    mapregion,
478                                    selected_layer, selected_shapes)
479                dc.EndDrawing()
480                dc.Close()
481            dlg.Destroy()
482            
483      def Print(self):      def Print(self):
484          printer = wx.wxPrinter()          printer = wx.wxPrinter()
485          printout = MapPrintout(self.map)          width, height = self.GetSizeTuple()
486            selected_layer = self.selection.SelectedLayer()
487            selected_shapes = self.selection.SelectedShapes()
488            
489            printout = MapPrintout(self, self.map, (0, 0, width, height),
490                                   selected_layer, selected_shapes)
491          printer.Print(self, printout, wx.true)          printer.Print(self, printout, wx.true)
492          printout.Destroy()          printout.Destroy()
493            
494      def SetMap(self, map):      def SetMap(self, map):
495          redraw_channels = (LAYERS_CHANGED, LAYER_LEGEND_CHANGED,          redraw_channels = (MAP_LAYERS_CHANGED, LAYER_CHANGED,
496                             LAYER_VISIBILITY_CHANGED)                             LAYER_VISIBILITY_CHANGED)
497          if self.map is not None:          if self.map is not None:
498              for channel in redraw_channels:              for channel in redraw_channels:
# Line 393  class MapCanvas(wxWindow, Publisher): Line 500  class MapCanvas(wxWindow, Publisher):
500              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,
501                                   self.projection_changed)                                   self.projection_changed)
502          self.map = map          self.map = map
503            self.selection.ClearSelection()
504          if self.map is not None:          if self.map is not None:
505              for channel in redraw_channels:              for channel in redraw_channels:
506                  self.map.Subscribe(channel, self.full_redraw)                  self.map.Subscribe(channel, self.full_redraw)
# Line 404  class MapCanvas(wxWindow, Publisher): Line 512  class MapCanvas(wxWindow, Publisher):
512          self.full_redraw()          self.full_redraw()
513    
514      def Map(self):      def Map(self):
515            """Return the map displayed by this canvas"""
516          return self.map          return self.map
517    
518      def redraw(self, *args):      def redraw(self, *args):
# Line 419  class MapCanvas(wxWindow, Publisher): Line 528  class MapCanvas(wxWindow, Publisher):
528    
529      def set_view_transform(self, scale, offset):      def set_view_transform(self, scale, offset):
530          self.scale = scale          self.scale = scale
531            if self.scale < 0.0001:
532                self.scale = 0.0001
533    
534          self.offset = offset          self.offset = offset
535          self.full_redraw()          self.full_redraw()
536            self.issue(SCALE_CHANGED, scale)
537    
538      def proj_to_win(self, x, y):      def proj_to_win(self, x, y):
539          """\          """\
# Line 437  class MapCanvas(wxWindow, Publisher): Line 550  class MapCanvas(wxWindow, Publisher):
550          return ((x - offx) / self.scale, (offy - y) / self.scale)          return ((x - offx) / self.scale, (offy - y) / self.scale)
551    
552      def FitRectToWindow(self, rect):      def FitRectToWindow(self, rect):
553            """Fit the rectangular region given by rect into the window.
554    
555            Set scale so that rect (in projected coordinates) just fits into
556            the window and center it.
557            """
558          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
559          llx, lly, urx, ury = rect          llx, lly, urx, ury = rect
560          if llx == urx or lly == ury:          if llx == urx or lly == ury:
561              # zero with or zero height. Do Nothing              # zero width or zero height. Do Nothing
562              return              return
563          scalex = width / (urx - llx)          scalex = width / (urx - llx)
564          scaley = height / (ury - lly)          scaley = height / (ury - lly)
565          scale = min(scalex, scaley)          scale = min(scalex, scaley)
566          offx = 0.5 * (width - (urx + llx) * scale)          offx = 0.5 * (width - (urx + llx) * scale)
567          offy = 0.5 * (height + (ury + lly) * scale)          offy = 0.5 * (height + (ury + lly) * scale)
568            print "scalex:", scalex, "scaley:", scaley
569          self.set_view_transform(scale, (offx, offy))          self.set_view_transform(scale, (offx, offy))
570    
571      def FitMapToWindow(self):      def FitMapToWindow(self):
572          """\          """Fit the map to the window
573          Set the scale and offset so that the map is centered in the  
574          window          Set the scale so that the map fits exactly into the window and
575            center it in the window.
576          """          """
577          bbox = self.map.ProjectedBoundingBox()          bbox = self.map.ProjectedBoundingBox()
578          if bbox is not None:          if bbox is not None:
579              self.FitRectToWindow(bbox)              self.FitRectToWindow(bbox)
580    
581        def FitLayerToWindow(self, layer):
582            """Fit the given layer to the window.
583    
584            Set the scale so that the layer fits exactly into the window and
585            center it in the window.
586            """
587            
588            bbox = layer.LatLongBoundingBox()
589            if bbox is not None:
590                proj = self.map.GetProjection()
591                if proj is not None:
592                    bbox = proj.ForwardBBox(bbox)
593    
594                if bbox is not None:
595                    self.FitRectToWindow(bbox)
596    
597        def FitSelectedToWindow(self):
598            layer = self.selection.SelectedLayer()
599            shapes = self.selection.SelectedShapes()
600    
601            bbox = layer.ShapesBoundingBox(shapes)
602            if bbox is not None:
603                proj = self.map.GetProjection()
604                if proj is not None:
605                    bbox = proj.ForwardBBox(bbox)
606    
607                if bbox is not None:
608                    self.FitRectToWindow(bbox)
609    
610      def ZoomFactor(self, factor, center = None):      def ZoomFactor(self, factor, center = None):
611          """Multiply the zoom by factor and center on center.          """Multiply the zoom by factor and center on center.
612    
# Line 478  class MapCanvas(wxWindow, Publisher): Line 627  class MapCanvas(wxWindow, Publisher):
627          self.set_view_transform(scale, offset)          self.set_view_transform(scale, offset)
628    
629      def ZoomOutToRect(self, rect):      def ZoomOutToRect(self, rect):
630          # rect is given in window coordinates          """Zoom out to fit the currently visible region into rect.
631    
632            The rect parameter is given in window coordinates
633            """
634          # determine the bbox of the displayed region in projected          # determine the bbox of the displayed region in projected
635          # coordinates          # coordinates
636          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
# Line 496  class MapCanvas(wxWindow, Publisher): Line 647  class MapCanvas(wxWindow, Publisher):
647          self.set_view_transform(scale, (offx, offy))          self.set_view_transform(scale, (offx, offy))
648    
649      def Translate(self, dx, dy):      def Translate(self, dx, dy):
650            """Move the map by dx, dy pixels"""
651          offx, offy = self.offset          offx, offy = self.offset
652          self.set_view_transform(self.scale, (offx + dx, offy + dy))          self.set_view_transform(self.scale, (offx + dx, offy + dy))
653    
654        def SelectTool(self, tool):
655            """Make tool the active tool.
656    
657            The parameter should be an instance of Tool or None to indicate
658            that no tool is active.
659            """
660            self.tool = tool
661    
662      def ZoomInTool(self):      def ZoomInTool(self):
663          self.tool = ZoomInTool(self)          """Start the zoom in tool"""
664            self.SelectTool(ZoomInTool(self))
665    
666      def ZoomOutTool(self):      def ZoomOutTool(self):
667          self.tool = ZoomOutTool(self)          """Start the zoom out tool"""
668            self.SelectTool(ZoomOutTool(self))
669    
670      def PanTool(self):      def PanTool(self):
671          self.tool = PanTool(self)          """Start the pan tool"""
672            self.SelectTool(PanTool(self))
673            #img = resource.GetImageResource("pan", wxBITMAP_TYPE_XPM)
674            #bmp = resource.GetBitmapResource("pan", wxBITMAP_TYPE_XPM)
675            #print bmp
676            #img = wxImageFromBitmap(bmp)
677            #print img
678            #cur = wxCursor(img)
679            #print cur
680            #self.SetCursor(cur)
681    
682      def IdentifyTool(self):      def IdentifyTool(self):
683          self.tool = IdentifyTool(self)          """Start the identify tool"""
684            self.SelectTool(IdentifyTool(self))
685    
686      def LabelTool(self):      def LabelTool(self):
687          self.tool = LabelTool(self)          """Start the label tool"""
688            self.SelectTool(LabelTool(self))
689    
690      def CurrentTool(self):      def CurrentTool(self):
691            """Return the name of the current tool or None if no tool is active"""
692          return self.tool and self.tool.Name() or None          return self.tool and self.tool.Name() or None
693    
694      def CurrentPosition(self):      def CurrentPosition(self):
# Line 552  class MapCanvas(wxWindow, Publisher): Line 726  class MapCanvas(wxWindow, Publisher):
726              self.tool.MouseDown(event)              self.tool.MouseDown(event)
727              self.tool.Show(self.drag_dc)              self.tool.Show(self.drag_dc)
728              self.dragging = 1              self.dragging = 1
729            
730      def OnLeftUp(self, event):      def OnLeftUp(self, event):
         self.ReleaseMouse()  
731          self.set_current_position(event)          self.set_current_position(event)
732          if self.dragging:          if self.dragging:
733              self.tool.Hide(self.drag_dc)              self.ReleaseMouse()
734              self.tool.MouseUp(event)              try:
735              self.drag_dc = None                  self.tool.Hide(self.drag_dc)
736          self.dragging = 0                  self.tool.MouseUp(event)
737                finally:
738                    self.drag_dc = None
739                    self.dragging = 0
740    
741      def OnMotion(self, event):      def OnMotion(self, event):
742          self.set_current_position(event)          self.set_current_position(event)
# Line 572  class MapCanvas(wxWindow, Publisher): Line 748  class MapCanvas(wxWindow, Publisher):
748      def OnLeaveWindow(self, event):      def OnLeaveWindow(self, event):
749          self.set_current_position(None)          self.set_current_position(None)
750    
     def OnIdle(self, event):  
         if self.redraw_on_idle:  
             self.do_redraw()  
         self.redraw_on_idle = 0  
   
751      def OnSize(self, event):      def OnSize(self, event):
752          # 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
753          # 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 756  class MapCanvas(wxWindow, Publisher):
756          # Even when the window becomes larger some parts of the bitmap          # Even when the window becomes larger some parts of the bitmap
757          # could be reused.          # could be reused.
758          self.full_redraw()          self.full_redraw()
759            pass
760    
761      def shape_selected(self, layer, shape):      def shape_selected(self, layer, shape):
762          """Redraw the map.          """Receiver for the SHAPES_SELECTED messages. Redraw the map."""
763            # The selection object takes care that it only issues
764          Receiver for the SELECTED_SHAPE messages. Try to redraw only          # SHAPES_SELECTED messages when the set of selected shapes has
765          when necessary.          # actually changed, so we can do a full redraw unconditionally.
766          """          # FIXME: We should perhaps try to limit the redraw to the are
767          # A redraw is necessary when the display has to change, which          # actually covered by the shapes before and after the selection
768          # means that either the status changes from having no selection          # change.
769          # 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  
770    
771      def unprojected_rect_around_point(self, x, y):      def unprojected_rect_around_point(self, x, y, dist):
772          """return a rect a few pixels around (x, y) in unprojected corrdinates          """return a rect dist pixels around (x, y) in unprojected corrdinates
773    
774          The return value is a tuple (minx, miny, maxx, maxy) suitable a          The return value is a tuple (minx, miny, maxx, maxy) suitable a
775          parameter to a layer's ShapesInRegion method.          parameter to a layer's ShapesInRegion method.
# Line 622  class MapCanvas(wxWindow, Publisher): Line 783  class MapCanvas(wxWindow, Publisher):
783          xs = []          xs = []
784          ys = []          ys = []
785          for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):          for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
786              px, py = self.win_to_proj(x + dx, y + dy)              px, py = self.win_to_proj(x + dist * dx, y + dist * dy)
787              if inverse:              if inverse:
788                  px, py = inverse(px, py)                  px, py = inverse(px, py)
789              xs.append(px)              xs.append(px)
790              ys.append(py)              ys.append(py)
791          return (min(xs), min(ys), max(xs), max(ys))          return (min(xs), min(ys), max(xs), max(ys))
792    
793      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):
794          """Determine the shape at point px, py in window coords          """Determine the shape at point px, py in window coords
795    
796          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 800  class MapCanvas(wxWindow, Publisher):
800          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
801          as the shape and None as the layer.          as the shape and None as the layer.
802    
803          If the optional parameter selected_layer is true (default), only          If the optional parameter searched_layer is given (or not None
804          search in the currently selected layer.          which it defaults to), only search in that layer.
805          """          """
806          map_proj = self.map.projection          map_proj = self.map.projection
807          if map_proj is not None:          if map_proj is not None:
# Line 651  class MapCanvas(wxWindow, Publisher): Line 812  class MapCanvas(wxWindow, Publisher):
812          scale = self.scale          scale = self.scale
813          offx, offy = self.offset          offx, offy = self.offset
814    
         box = self.unprojected_rect_around_point(px, py)  
   
815          if select_labels:          if select_labels:
816              labels = self.map.LabelLayer().Labels()              labels = self.map.LabelLayer().Labels()
817                
818              if labels:              if labels:
819                  dc = wxClientDC(self)                  dc = wxClientDC(self)
820                  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 846  class MapCanvas(wxWindow, Publisher):
846                      if x <= px < x + width and y <= py <= y + height:                      if x <= px < x + width and y <= py <= y + height:
847                          return None, i                          return None, i
848    
849          if selected_layer:          if searched_layer:
850              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 = []  
851          else:          else:
852              layers = self.map.Layers()              layers = self.map.Layers()
853    
# Line 705  class MapCanvas(wxWindow, Publisher): Line 858  class MapCanvas(wxWindow, Publisher):
858              if not layer.Visible():              if not layer.Visible():
859                  continue                  continue
860    
861              filled = layer.fill is not None              filled = layer.GetClassification().GetDefaultFill() \
862              stroked = layer.stroke is not None                       is not Color.Transparent
863                                stroked = layer.GetClassification().GetDefaultLineColor() \
864                          is not Color.Transparent
865    
866              layer_proj = layer.projection              layer_proj = layer.projection
867              if layer_proj is not None:              if layer_proj is not None:
868                  inverse = layer_proj.Inverse                  inverse = layer_proj.Inverse
869              else:              else:
870                  inverse = None                  inverse = None
871                    
872              shapetype = layer.ShapeType()              shapetype = layer.ShapeType()
873    
874              select_shape = -1              select_shape = -1
875    
876                # Determine the ids of the shapes that overlap a tiny area
877                # around the point. For layers containing points we have to
878                # choose a larger size of the box we're testing agains so
879                # that we take the size of the markers into account
880                # FIXME: Once the markers are more flexible this part has to
881                # become more flexible too, of course
882                if shapetype == SHAPETYPE_POINT:
883                    box = self.unprojected_rect_around_point(px, py, 5)
884                else:
885                    box = self.unprojected_rect_around_point(px, py, 1)
886              shape_ids = layer.ShapesInRegion(box)              shape_ids = layer.ShapesInRegion(box)
887              shape_ids.reverse()              shape_ids.reverse()
888    
# Line 760  class MapCanvas(wxWindow, Publisher): Line 925  class MapCanvas(wxWindow, Publisher):
925                  return layer, select_shape                  return layer, select_shape
926          return None, None          return None, None
927    
928      def SelectShapeAt(self, x, y):      def SelectShapeAt(self, x, y, layer = None):
929          layer, shape = self.find_shape_at(x, y, selected_layer = 0)          """\
930            Select and return the shape and its layer at window position (x, y)
931    
932            If layer is given, only search in that layer. If no layer is
933            given, search through all layers.
934    
935            Return a tuple (layer, shapeid). If no shape is found, return
936            (None, None).
937            """
938            layer, shape = result = self.find_shape_at(x, y, searched_layer=layer)
939          # 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
940          # to deselect the currently selected layer, so we simply select          # to deselect the currently selected layer, so we simply select
941          # the already selected layer again.          # the already selected layer again.
942          if layer is None:          if layer is None:
943              layer = self.interactor.SelectedLayer()              layer = self.selection.SelectedLayer()
944          self.interactor.SelectLayerAndShape(layer, shape)              shapes = []
945            else:
946                shapes = [shape]
947            self.selection.SelectShapes(layer, shapes)
948            return result
949    
950      def LabelShapeAt(self, x, y):      def LabelShapeAt(self, x, y):
951            """Add or remove a label at window position x, y.
952    
953            If there's a label at the given position, remove it. Otherwise
954            determine the shape at the position, run the label dialog and
955            unless the user cancels the dialog, add a laber.
956            """
957          ox = x; oy = y          ox = x; oy = y
958          label_layer = self.map.LabelLayer()          label_layer = self.map.LabelLayer()
959          layer, shape_index = self.find_shape_at(x, y, select_labels = 1)          layer, shape_index = self.find_shape_at(x, y, select_labels = 1)
# Line 818  class MapCanvas(wxWindow, Publisher): Line 1002  class MapCanvas(wxWindow, Publisher):
1002                      valign = ALIGN_CENTER                      valign = ALIGN_CENTER
1003                  label_layer.AddLabel(x, y, text,                  label_layer.AddLabel(x, y, text,
1004                                       halign = halign, valign = valign)                                       halign = halign, valign = valign)
1005    
1006    def OutputTransform(canvas_scale, canvas_offset, canvas_size, device_extend):
1007        """Calculate dimensions to transform canvas content to output device."""
1008        width, height = device_extend
1009    
1010        # Only 80 % of the with are available for the map
1011        width = width * 0.8
1012    
1013        # Define the distance of the map from DC border
1014        distance = 20
1015    
1016        if height < width:
1017            # landscape
1018            map_height = height - 2*distance
1019            map_width = map_height
1020        else:
1021            # portrait, recalibrate width (usually the legend width is too
1022            # small
1023            width = width * 0.9
1024            map_height = width - 2*distance
1025            map_width = map_height
1026        
1027        mapregion = (distance, distance,
1028                     distance+map_width, distance+map_height)
1029    
1030        canvas_width, canvas_height = canvas_size
1031        
1032        scalex = map_width / (canvas_width/canvas_scale)
1033        scaley = map_height / (canvas_height/canvas_scale)
1034        scale = min(scalex, scaley)
1035        canvas_offx, canvas_offy = canvas_offset
1036        offx = scale*canvas_offx/canvas_scale
1037        offy = scale*canvas_offy/canvas_scale
1038    
1039        return scale, (offx, offy), mapregion

Legend:
Removed from v.239  
changed lines
  Added in v.940

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26