/[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 1236 by jonathan, Wed Jun 18 15:29:26 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       LAYER_PROJECTION_CHANGED, \
39         MAP_LAYERS_CHANGED, LAYER_CHANGED, LAYER_VISIBILITY_CHANGED
40  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \  from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \
41       SHAPETYPE_POINT       SHAPETYPE_POINT
42  from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \  from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \
43       ALIGN_LEFT, ALIGN_RIGHT       ALIGN_LEFT, ALIGN_RIGHT
44  from Thuban.Lib.connector import Publisher  from Thuban.Lib.connector import Publisher
45    from Thuban.Model.color import Color
46    
47    import resource
48    
49  from renderer import ScreenRenderer, PrinterRender  from selection import Selection
50    from renderer import ScreenRenderer, ExportRenderer, PrinterRenderer
51    
52  import labeldialog  import labeldialog
53    
54  from messages import SELECTED_SHAPE, VIEW_POSITION  from messages import LAYER_SELECTED, SHAPES_SELECTED, VIEW_POSITION, \
55                         SCALE_CHANGED
56    
57    
58  #  #
# Line 129  class ZoomInTool(RectTool): Line 146  class ZoomInTool(RectTool):
146              Tool.MouseUp(self, event)              Tool.MouseUp(self, event)
147              sx, sy = self.start              sx, sy = self.start
148              cx, cy = self.current              cx, cy = self.current
149              if sx == cx and sy == cy:              if sx == cx or sy == cy:
150                  # Just a mouse click. Simply zoom in by a factor of two                  # Just a mouse click or a degenerate rectangle. Simply
151                    # zoom in by a factor of two
152                    # FIXME: For a click this is the desired behavior but should we
153                    # really do this for degenrate rectagles as well or
154                    # should we ignore them?
155                  self.view.ZoomFactor(2, center = (cx, cy))                  self.view.ZoomFactor(2, center = (cx, cy))
156              else:              else:
157                  # A drag. Zoom in to the rectangle                  # A drag. Zoom in to the rectangle
# Line 149  class ZoomOutTool(RectTool): Line 170  class ZoomOutTool(RectTool):
170              Tool.MouseUp(self, event)              Tool.MouseUp(self, event)
171              sx, sy = self.start              sx, sy = self.start
172              cx, cy = self.current              cx, cy = self.current
173              if sx == cx and sy == cy:              if sx == cx or sy == cy:
174                  # Just a mouse click. Simply zoom out by a factor of two                  # Just a mouse click or a degenerate rectangle. Simply
175                    # zoom out by a factor of two.
176                    # FIXME: For a click this is the desired behavior but should we
177                    # really do this for degenrate rectagles as well or
178                    # should we ignore them?
179                  self.view.ZoomFactor(0.5, center = (cx, cy))                  self.view.ZoomFactor(0.5, center = (cx, cy))
180              else:              else:
181                  # A drag. Zoom out to the rectangle                  # A drag. Zoom out to the rectangle
# Line 207  class LabelTool(Tool): Line 232  class LabelTool(Tool):
232          self.view.LabelShapeAt(event.m_x, event.m_y)          self.view.LabelShapeAt(event.m_x, event.m_y)
233    
234    
   
   
235  class MapPrintout(wx.wxPrintout):  class MapPrintout(wx.wxPrintout):
236    
237      """      """
238      wxPrintout class for printing Thuban maps      wxPrintout class for printing Thuban maps
239      """      """
240    
241      def __init__(self, map):      def __init__(self, canvas, map, region, selected_layer, selected_shapes):
242          wx.wxPrintout.__init__(self)          wx.wxPrintout.__init__(self)
243            self.canvas = canvas
244          self.map = map          self.map = map
245            self.region = region
246            self.selected_layer = selected_layer
247            self.selected_shapes = selected_shapes
248    
249      def GetPageInfo(self):      def GetPageInfo(self):
250          return (1, 1, 1, 1)          return (1, 1, 1, 1)
# Line 231  class MapPrintout(wx.wxPrintout): Line 258  class MapPrintout(wx.wxPrintout):
258    
259      def draw_on_dc(self, dc):      def draw_on_dc(self, dc):
260          width, height = self.GetPageSizePixels()          width, height = self.GetPageSizePixels()
261          llx, lly, urx, ury = self.map.ProjectedBoundingBox()          scale, offset, mapregion = OutputTransform(self.canvas.scale,
262          scalex = width / (urx - llx)                                                     self.canvas.offset,
263          scaley = height / (ury - lly)                                                     self.canvas.GetSizeTuple(),
264          scale = min(scalex, scaley)                                                     self.GetPageSizePixels())
         offx = 0.5 * (width - (urx + llx) * scale)  
         offy = 0.5 * (height + (ury + lly) * scale)  
   
265          resx, resy = self.GetPPIPrinter()          resx, resy = self.GetPPIPrinter()
266          renderer = PrinterRender(dc, scale, (offx, offy), resolution = resx)          renderer = PrinterRenderer(dc, scale, offset, resolution = resy)
267          renderer.RenderMap(self.map)          x, y, width, height = self.region
268          return wx.true          canvas_scale = self.canvas.scale
269            renderer.RenderMap(self.map,
270                               (0,0,
271                                    (width/canvas_scale)*scale,
272                                    (height/canvas_scale)*scale),
273                                    mapregion,
274                               self.selected_layer, self.selected_shapes)
275            return True
276    
277    
278  class MapCanvas(wxWindow, Publisher):  class MapCanvas(wxWindow, Publisher):
279    
280      """A widget that displays a map and offers some interaction"""      """A widget that displays a map and offers some interaction"""
281    
282      def __init__(self, parent, winid, interactor):      # Some messages that can be subscribed/unsubscribed directly through
283        # the MapCanvas come in fact from other objects. This is a dict
284        # mapping those messages to the names of the instance variables they
285        # actually come from. The delegation is implemented in the Subscribe
286        # and Unsubscribe methods
287        delegated_messages = {LAYER_SELECTED: "selection",
288                              SHAPES_SELECTED: "selection"}
289    
290        # Methods delegated to some instance variables. The delegation is
291        # implemented in the __getattr__ method.
292        delegated_methods = {"SelectLayer": "selection",
293                             "SelectShapes": "selection",
294                             "SelectedLayer": "selection",
295                             "HasSelectedLayer": "selection",
296                             "HasSelectedShapes": "selection",
297                             "SelectedShapes": "selection"}
298    
299        def __init__(self, parent, winid):
300          wxWindow.__init__(self, parent, winid)          wxWindow.__init__(self, parent, winid)
301          self.SetBackgroundColour(wxColour(255, 255, 255))          self.SetBackgroundColour(wxColour(255, 255, 255))
302    
303          # the map displayed in this canvas. Set with SetMap()          # the map displayed in this canvas. Set with SetMap()
304          self.map = None          self.map = None
305    
306            # current map projection. should only differ from map.projection
307            # when the map's projection is changing and we need access to the
308            # old projection.
309            self.current_map_proj = None
310    
311          # scale and offset describe the transformation from projected          # scale and offset describe the transformation from projected
312          # coordinates to window coordinates.          # coordinates to window coordinates.
313          self.scale = 1.0          self.scale = 1.0
# Line 271  class MapCanvas(wxWindow, Publisher): Line 324  class MapCanvas(wxWindow, Publisher):
324          # if the mouse is outside the window.          # if the mouse is outside the window.
325          self.current_position = None          self.current_position = None
326    
         # 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()  
   
327          # the bitmap serving as backing store          # the bitmap serving as backing store
328          self.bitmap = None          self.bitmap = None
329    
330          # the interactor          # the selection
331          self.interactor = interactor          self.selection = Selection()
332          self.interactor.Subscribe(SELECTED_SHAPE, self.shape_selected)          self.selection.Subscribe(SHAPES_SELECTED , self.shape_selected)
333    
334          # keep track of which layers/shapes are selected to make sure we          # keep track of which layers/shapes are selected to make sure we
335          # only redraw when necessary          # only redraw when necessary
# Line 298  class MapCanvas(wxWindow, Publisher): Line 343  class MapCanvas(wxWindow, Publisher):
343          EVT_MOTION(self, self.OnMotion)          EVT_MOTION(self, self.OnMotion)
344          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)          EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)
345          wx.EVT_SIZE(self, self.OnSize)          wx.EVT_SIZE(self, self.OnSize)
         wx.EVT_IDLE(self, self.OnIdle)  
346    
347      def __del__(self):      def __del__(self):
348          wxWindow.__del__(self)          wxWindow.__del__(self)
349          Publisher.__del__(self)          Publisher.__del__(self)
350    
351        def Subscribe(self, channel, *args):
352            """Extend the inherited method to handle delegated messages.
353    
354            If channel is one of the delegated messages call the appropriate
355            object's Subscribe method. Otherwise just call the inherited
356            method.
357            """
358            if channel in self.delegated_messages:
359                object = getattr(self, self.delegated_messages[channel])
360                object.Subscribe(channel, *args)
361            else:
362                Publisher.Subscribe(self, channel, *args)
363    
364        def Unsubscribe(self, channel, *args):
365            """Extend the inherited method to handle delegated messages.
366    
367            If channel is one of the delegated messages call the appropriate
368            object's Unsubscribe method. Otherwise just call the inherited
369            method.
370            """
371            if channel in self.delegated_messages:
372                object = getattr(self, self.delegated_messages[channel])
373                object.Unsubscribe(channel, *args)
374            else:
375                Publisher.Unsubscribe(self, channel, *args)
376    
377        def __getattr__(self, attr):
378            if attr in self.delegated_methods:
379                return getattr(getattr(self, self.delegated_methods[attr]), attr)
380            raise AttributeError(attr)
381    
382      def OnPaint(self, event):      def OnPaint(self, event):
383          dc = wxPaintDC(self)          dc = wxPaintDC(self)
384          if self.map is not None and self.map.HasLayers():          clear = self.map is None or not self.map.HasLayers()
             # We have a non-empty map. Redraw it in idle time  
             self.redraw_on_idle = 1  
             # update the region that has to be redrawn  
             self.update_region.UnionRegion(self.GetUpdateRegion())  
         else:  
             # If we've got no map or if the map is empty, simply clear  
             # the screen.  
   
             # XXX it's probably possible to get rid of this. The  
             # background color of the window is already white and the  
             # only thing we may have to do is to call self.Refresh()  
             # with a true argument in the right places.  
             dc.BeginDrawing()  
             dc.Clear()  
             dc.EndDrawing()  
385    
386              # clear the region          wxBeginBusyCursor()
387              self.update_region = wx.wxRegion()          try:
388                if not clear:
389                    self.do_redraw()
390                    try:
391                        pass
392                    except:
393                        print "Error during drawing:", sys.exc_info()[0]
394                        clear = True
395    
396                if clear:
397                    # If we've got no map or if the map is empty, simply clear
398                    # the screen.
399    
400                    # XXX it's probably possible to get rid of this. The
401                    # background color of the window is already white and the
402                    # only thing we may have to do is to call self.Refresh()
403                    # with a true argument in the right places.
404                    dc.BeginDrawing()
405                    dc.Clear()
406                    dc.EndDrawing()
407            finally:
408                wxEndBusyCursor()
409    
410      def do_redraw(self):      def do_redraw(self):
411          # This should only be called if we have a non-empty map.          # This should only be called if we have a non-empty map.
412    
         # 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()  
   
413          # Get the window size.          # Get the window size.
414          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
415    
# Line 347  class MapCanvas(wxWindow, Publisher): Line 423  class MapCanvas(wxWindow, Publisher):
423              dc.BeginDrawing()              dc.BeginDrawing()
424    
425              # clear the background              # clear the background
426              dc.SetBrush(wx.wxWHITE_BRUSH)              #dc.SetBrush(wx.wxWHITE_BRUSH)
427              dc.SetPen(wx.wxTRANSPARENT_PEN)              #dc.SetPen(wx.wxTRANSPARENT_PEN)
428              dc.DrawRectangle(0, 0, width, height)              #dc.DrawRectangle(0, 0, width, height)
429                dc.SetBackground(wx.wxWHITE_BRUSH)
430              if 1: #self.interactor.selected_map is self.map:              dc.Clear()
431                  selected_layer = self.interactor.selected_layer  
432                  selected_shape = self.interactor.selected_shape              selected_layer = self.selection.SelectedLayer()
433              else:              selected_shapes = self.selection.SelectedShapes()
                 selected_layer = None  
                 selected_shape = None  
434    
435              # draw the map into the bitmap              # draw the map into the bitmap
436              renderer = ScreenRenderer(dc, self.scale, self.offset)              renderer = ScreenRenderer(dc, self.scale, self.offset)
437    
438              # Pass the entire bitmap as update_region to the renderer.              # Pass the entire bitmap as update region to the renderer.
439              # We're redrawing the whole bitmap, after all.              # We're redrawing the whole bitmap, after all.
440              renderer.RenderMap(self.map, (0, 0, width, height),              renderer.RenderMap(self.map, (0, 0, width, height),
441                                 selected_layer, selected_shape)                                 selected_layer, selected_shapes)
442    
443              dc.EndDrawing()              dc.EndDrawing()
444              dc.SelectObject(wx.wxNullBitmap)              dc.SelectObject(wx.wxNullBitmap)
# Line 378  class MapCanvas(wxWindow, Publisher): Line 452  class MapCanvas(wxWindow, Publisher):
452          clientdc.Blit(0, 0, width, height, dc, 0, 0)          clientdc.Blit(0, 0, width, height, dc, 0, 0)
453          clientdc.EndDrawing()          clientdc.EndDrawing()
454    
455        def Export(self):
456            if self.scale == 0:
457                return
458    
459            if hasattr(self, "export_path"):
460                export_path = self.export_path
461            else:
462                export_path="."
463            dlg = wxFileDialog(self, _("Export Map"), export_path, "",
464                               "Enhanced Metafile (*.wmf)|*.wmf",
465                               wxSAVE|wxOVERWRITE_PROMPT)
466            if dlg.ShowModal() == wxID_OK:
467                self.export_path = os.path.dirname(dlg.GetPath())
468                dc = wxMetaFileDC(dlg.GetPath())
469        
470                scale, offset, mapregion = OutputTransform(self.scale,
471                                                           self.offset,
472                                                           self.GetSizeTuple(),
473                                                           dc.GetSizeTuple())
474    
475                selected_layer = self.selection.SelectedLayer()
476                selected_shapes = self.selection.SelectedShapes()
477    
478                renderer = ExportRenderer(dc, scale, offset)
479    
480                # Pass the entire bitmap as update region to the renderer.
481                # We're redrawing the whole bitmap, after all.
482                width, height = self.GetSizeTuple()
483                renderer.RenderMap(self.map,
484                                    (0,0,
485                                        (width/self.scale)*scale,
486                                        (height/self.scale)*scale),
487                                    mapregion,
488                                    selected_layer, selected_shapes)
489                dc.EndDrawing()
490                dc.Close()
491            dlg.Destroy()
492            
493      def Print(self):      def Print(self):
494          printer = wx.wxPrinter()          printer = wx.wxPrinter()
495          printout = MapPrintout(self.map)          width, height = self.GetSizeTuple()
496          printer.Print(self, printout, wx.true)          selected_layer = self.selection.SelectedLayer()
497            selected_shapes = self.selection.SelectedShapes()
498            
499            printout = MapPrintout(self, self.map, (0, 0, width, height),
500                                   selected_layer, selected_shapes)
501            printer.Print(self, printout, True)
502          printout.Destroy()          printout.Destroy()
503    
504      def SetMap(self, map):      def SetMap(self, map):
505          redraw_channels = (LAYERS_CHANGED, LAYER_LEGEND_CHANGED,          redraw_channels = (MAP_LAYERS_CHANGED, LAYER_CHANGED,
506                             LAYER_VISIBILITY_CHANGED)                             LAYER_VISIBILITY_CHANGED)
507          if self.map is not None:          if self.map is not None:
508              for channel in redraw_channels:              for channel in redraw_channels:
509                  self.map.Unsubscribe(channel, self.full_redraw)                  self.map.Unsubscribe(channel, self.full_redraw)
510              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,              self.map.Unsubscribe(MAP_PROJECTION_CHANGED,
511                                   self.projection_changed)                                   self.map_projection_changed)
512                self.map.Unsubscribe(LAYER_PROJECTION_CHANGED,
513                                     self.layer_projection_changed)
514          self.map = map          self.map = map
515            self.current_map_proj = self.map.GetProjection()
516            self.selection.ClearSelection()
517          if self.map is not None:          if self.map is not None:
518              for channel in redraw_channels:              for channel in redraw_channels:
519                  self.map.Subscribe(channel, self.full_redraw)                  self.map.Subscribe(channel, self.full_redraw)
520              self.map.Subscribe(MAP_PROJECTION_CHANGED, self.projection_changed)              self.map.Subscribe(MAP_PROJECTION_CHANGED, self.map_projection_changed)
521                self.map.Subscribe(LAYER_PROJECTION_CHANGED, self.layer_projection_changed)
522          self.FitMapToWindow()          self.FitMapToWindow()
523          # force a redraw. If map is not empty, it's already been called          # force a redraw. If map is not empty, it's already been called
524          # by FitMapToWindow but if map is empty it hasn't been called          # by FitMapToWindow but if map is empty it hasn't been called
# Line 404  class MapCanvas(wxWindow, Publisher): Line 526  class MapCanvas(wxWindow, Publisher):
526          self.full_redraw()          self.full_redraw()
527    
528      def Map(self):      def Map(self):
529            """Return the map displayed by this canvas"""
530          return self.map          return self.map
531    
532      def redraw(self, *args):      def redraw(self, *args):
# Line 413  class MapCanvas(wxWindow, Publisher): Line 536  class MapCanvas(wxWindow, Publisher):
536          self.bitmap = None          self.bitmap = None
537          self.redraw()          self.redraw()
538    
539      def projection_changed(self, *args):      def map_projection_changed(self, *args):
540          self.FitMapToWindow()  
541            proj = self.current_map_proj
542            self.current_map_proj = self.map.GetProjection()
543    
544            bbox = None
545    
546            if proj is not None and self.current_map_proj is not None:
547                width, height = self.GetSizeTuple()
548                llx, lly = self.win_to_proj(0, height)
549                urx, ury = self.win_to_proj(width, 0)
550                bbox = proj.Inverse(llx, lly) + proj.Inverse(urx, ury)
551                bbox = self.current_map_proj.ForwardBBox(bbox)
552    
553            if bbox is not None:
554                self.FitRectToWindow(bbox)
555            else:
556                self.FitMapToWindow()
557    
558            self.full_redraw()
559    
560        def layer_projection_changed(self, *args):
561          self.full_redraw()          self.full_redraw()
562    
563      def set_view_transform(self, scale, offset):      def set_view_transform(self, scale, offset):
564            # width/height of the projected bbox
565            llx, lly, urx, ury = bbox = self.map.ProjectedBoundingBox()
566            pwidth = float(urx - llx)
567            pheight = float(ury - lly)
568    
569            # width/height of the window
570            wwidth, wheight = self.GetSizeTuple()
571    
572            # The window's center in projected coordinates assuming the new
573            # scale/offset
574            pcenterx = (wwidth/2 - offset[0]) / scale
575            pcentery = (offset[1] - wheight/2) / scale
576    
577            # The window coordinates used when drawing the shapes must fit
578            # into 16bit signed integers.
579            max_len = max(pwidth, pheight)
580            if max_len:
581                max_scale = 32000.0 / max_len
582            else:
583                # FIXME: What to do in this case? The bbox is effectively
584                # empty so any scale should work.
585                max_scale = scale
586    
587            # The minimal scale is somewhat arbitrarily set to half that of
588            # the bbox fit into the window
589            scales = []
590            if pwidth:
591                scales.append(wwidth / pwidth)
592            if pheight:
593                scales.append(wheight / pheight)
594            if scales:
595                min_scale = 0.5 * min(scales)
596            else:
597                min_scale = scale
598    
599            if scale > max_scale:
600                scale = max_scale
601            elif scale < min_scale:
602                scale = min_scale
603    
604          self.scale = scale          self.scale = scale
605          self.offset = offset  
606            # determine new offset to preserve the center
607            self.offset = (wwidth/2 - scale * pcenterx,
608                           wheight/2 + scale * pcentery)
609          self.full_redraw()          self.full_redraw()
610            self.issue(SCALE_CHANGED, scale)
611    
612      def proj_to_win(self, x, y):      def proj_to_win(self, x, y):
613          """\          """\
614          Return the point in  window coords given by projected coordinates x y          Return the point in  window coords given by projected coordinates x y
615          """          """
616            if self.scale == 0:
617                return (0, 0)
618    
619          offx, offy = self.offset          offx, offy = self.offset
620          return (self.scale * x + offx, -self.scale * y + offy)          return (self.scale * x + offx, -self.scale * y + offy)
621    
# Line 433  class MapCanvas(wxWindow, Publisher): Line 623  class MapCanvas(wxWindow, Publisher):
623          """\          """\
624          Return the point in projected coordinates given by window coords x y          Return the point in projected coordinates given by window coords x y
625          """          """
626            if self.scale == 0:
627                return (0, 0)
628    
629          offx, offy = self.offset          offx, offy = self.offset
630          return ((x - offx) / self.scale, (offy - y) / self.scale)          return ((x - offx) / self.scale, (offy - y) / self.scale)
631    
632      def FitRectToWindow(self, rect):      def FitRectToWindow(self, rect):
633            """Fit the rectangular region given by rect into the window.
634    
635            Set scale so that rect (in projected coordinates) just fits into
636            the window and center it.
637            """
638          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
639          llx, lly, urx, ury = rect          llx, lly, urx, ury = rect
640          if llx == urx or lly == ury:          if llx == urx or lly == ury:
641              # zero with or zero height. Do Nothing              # zero width or zero height. Do Nothing
642              return              return
643          scalex = width / (urx - llx)          scalex = width / (urx - llx)
644          scaley = height / (ury - lly)          scaley = height / (ury - lly)
# Line 450  class MapCanvas(wxWindow, Publisher): Line 648  class MapCanvas(wxWindow, Publisher):
648          self.set_view_transform(scale, (offx, offy))          self.set_view_transform(scale, (offx, offy))
649    
650      def FitMapToWindow(self):      def FitMapToWindow(self):
651          """\          """Fit the map to the window
652          Set the scale and offset so that the map is centered in the  
653          window          Set the scale so that the map fits exactly into the window and
654            center it in the window.
655            """
656            if self.map is not None:
657                bbox = self.map.ProjectedBoundingBox()
658                if bbox is not None:
659                    self.FitRectToWindow(bbox)
660    
661        def FitLayerToWindow(self, layer):
662            """Fit the given layer to the window.
663    
664            Set the scale so that the layer fits exactly into the window and
665            center it in the window.
666          """          """
667          bbox = self.map.ProjectedBoundingBox()          
668            bbox = layer.LatLongBoundingBox()
669          if bbox is not None:          if bbox is not None:
670              self.FitRectToWindow(bbox)              proj = self.map.GetProjection()
671                if proj is not None:
672                    bbox = proj.ForwardBBox(bbox)
673    
674                if bbox is not None:
675                    self.FitRectToWindow(bbox)
676    
677        def FitSelectedToWindow(self):
678            layer = self.selection.SelectedLayer()
679            shapes = self.selection.SelectedShapes()
680    
681            bbox = layer.ShapesBoundingBox(shapes)
682            if bbox is not None:
683                proj = self.map.GetProjection()
684                if proj is not None:
685                    bbox = proj.ForwardBBox(bbox)
686    
687                if bbox is not None:
688                    if len(shapes) == 1 and layer.ShapeType() == SHAPETYPE_POINT:
689                        self.ZoomFactor(1, self.proj_to_win(bbox[0], bbox[1]))
690                    else:
691                        self.FitRectToWindow(bbox)
692    
693      def ZoomFactor(self, factor, center = None):      def ZoomFactor(self, factor, center = None):
694          """Multiply the zoom by factor and center on center.          """Multiply the zoom by factor and center on center.
# Line 465  class MapCanvas(wxWindow, Publisher): Line 697  class MapCanvas(wxWindow, Publisher):
697          that should be centered. If it is omitted, it defaults to the          that should be centered. If it is omitted, it defaults to the
698          center of the window          center of the window
699          """          """
700          width, height = self.GetSizeTuple()          if self.scale > 0:
701          scale = self.scale * factor              width, height = self.GetSizeTuple()
702          offx, offy = self.offset              scale = self.scale * factor
703          if center is not None:              offx, offy = self.offset
704              cx, cy = center              if center is not None:
705          else:                  cx, cy = center
706              cx = width / 2              else:
707              cy = height / 2                  cx = width / 2
708          offset = (factor * (offx - cx) + width / 2,                  cy = height / 2
709                    factor * (offy - cy) + height / 2)              offset = (factor * (offx - cx) + width / 2,
710          self.set_view_transform(scale, offset)                      factor * (offy - cy) + height / 2)
711                self.set_view_transform(scale, offset)
712    
713      def ZoomOutToRect(self, rect):      def ZoomOutToRect(self, rect):
714          # rect is given in window coordinates          """Zoom out to fit the currently visible region into rect.
715    
716            The rect parameter is given in window coordinates
717            """
718          # determine the bbox of the displayed region in projected          # determine the bbox of the displayed region in projected
719          # coordinates          # coordinates
720          width, height = self.GetSizeTuple()          width, height = self.GetSizeTuple()
# Line 496  class MapCanvas(wxWindow, Publisher): Line 731  class MapCanvas(wxWindow, Publisher):
731          self.set_view_transform(scale, (offx, offy))          self.set_view_transform(scale, (offx, offy))
732    
733      def Translate(self, dx, dy):      def Translate(self, dx, dy):
734            """Move the map by dx, dy pixels"""
735          offx, offy = self.offset          offx, offy = self.offset
736          self.set_view_transform(self.scale, (offx + dx, offy + dy))          self.set_view_transform(self.scale, (offx + dx, offy + dy))
737    
738        def SelectTool(self, tool):
739            """Make tool the active tool.
740    
741            The parameter should be an instance of Tool or None to indicate
742            that no tool is active.
743            """
744            self.tool = tool
745    
746      def ZoomInTool(self):      def ZoomInTool(self):
747          self.tool = ZoomInTool(self)          """Start the zoom in tool"""
748            self.SelectTool(ZoomInTool(self))
749    
750      def ZoomOutTool(self):      def ZoomOutTool(self):
751          self.tool = ZoomOutTool(self)          """Start the zoom out tool"""
752            self.SelectTool(ZoomOutTool(self))
753    
754      def PanTool(self):      def PanTool(self):
755          self.tool = PanTool(self)          """Start the pan tool"""
756            self.SelectTool(PanTool(self))
757            #img = resource.GetImageResource("pan", wxBITMAP_TYPE_XPM)
758            #bmp = resource.GetBitmapResource("pan", wxBITMAP_TYPE_XPM)
759            #print bmp
760            #img = wxImageFromBitmap(bmp)
761            #print img
762            #cur = wxCursor(img)
763            #print cur
764            #self.SetCursor(cur)
765    
766      def IdentifyTool(self):      def IdentifyTool(self):
767          self.tool = IdentifyTool(self)          """Start the identify tool"""
768            self.SelectTool(IdentifyTool(self))
769    
770      def LabelTool(self):      def LabelTool(self):
771          self.tool = LabelTool(self)          """Start the label tool"""
772            self.SelectTool(LabelTool(self))
773    
774      def CurrentTool(self):      def CurrentTool(self):
775            """Return the name of the current tool or None if no tool is active"""
776          return self.tool and self.tool.Name() or None          return self.tool and self.tool.Name() or None
777    
778      def CurrentPosition(self):      def CurrentPosition(self):
# Line 554  class MapCanvas(wxWindow, Publisher): Line 812  class MapCanvas(wxWindow, Publisher):
812              self.dragging = 1              self.dragging = 1
813    
814      def OnLeftUp(self, event):      def OnLeftUp(self, event):
         self.ReleaseMouse()  
815          self.set_current_position(event)          self.set_current_position(event)
816          if self.dragging:          if self.dragging:
817              self.tool.Hide(self.drag_dc)              self.ReleaseMouse()
818              self.tool.MouseUp(event)              try:
819              self.drag_dc = None                  self.tool.Hide(self.drag_dc)
820          self.dragging = 0                  self.tool.MouseUp(event)
821                finally:
822                    self.drag_dc = None
823                    self.dragging = 0
824    
825      def OnMotion(self, event):      def OnMotion(self, event):
826          self.set_current_position(event)          self.set_current_position(event)
# Line 572  class MapCanvas(wxWindow, Publisher): Line 832  class MapCanvas(wxWindow, Publisher):
832      def OnLeaveWindow(self, event):      def OnLeaveWindow(self, event):
833          self.set_current_position(None)          self.set_current_position(None)
834    
     def OnIdle(self, event):  
         if self.redraw_on_idle:  
             self.do_redraw()  
         self.redraw_on_idle = 0  
   
835      def OnSize(self, event):      def OnSize(self, event):
836          # 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
837          # 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 840  class MapCanvas(wxWindow, Publisher):
840          # Even when the window becomes larger some parts of the bitmap          # Even when the window becomes larger some parts of the bitmap
841          # could be reused.          # could be reused.
842          self.full_redraw()          self.full_redraw()
843            pass
844    
845      def shape_selected(self, layer, shape):      def shape_selected(self, layer, shape):
846          """Redraw the map.          """Receiver for the SHAPES_SELECTED messages. Redraw the map."""
847            # The selection object takes care that it only issues
848          Receiver for the SELECTED_SHAPE messages. Try to redraw only          # SHAPES_SELECTED messages when the set of selected shapes has
849          when necessary.          # actually changed, so we can do a full redraw unconditionally.
850          """          # FIXME: We should perhaps try to limit the redraw to the are
851          # A redraw is necessary when the display has to change, which          # actually covered by the shapes before and after the selection
852          # means that either the status changes from having no selection          # change.
853          # 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  
854    
855      def unprojected_rect_around_point(self, x, y):      def unprojected_rect_around_point(self, x, y, dist):
856          """return a rect a few pixels around (x, y) in unprojected corrdinates          """return a rect dist pixels around (x, y) in unprojected corrdinates
857    
858          The return value is a tuple (minx, miny, maxx, maxy) suitable a          The return value is a tuple (minx, miny, maxx, maxy) suitable a
859          parameter to a layer's ShapesInRegion method.          parameter to a layer's ShapesInRegion method.
# Line 622  class MapCanvas(wxWindow, Publisher): Line 867  class MapCanvas(wxWindow, Publisher):
867          xs = []          xs = []
868          ys = []          ys = []
869          for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):          for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
870              px, py = self.win_to_proj(x + dx, y + dy)              px, py = self.win_to_proj(x + dist * dx, y + dist * dy)
871              if inverse:              if inverse:
872                  px, py = inverse(px, py)                  px, py = inverse(px, py)
873              xs.append(px)              xs.append(px)
# Line 649  class MapCanvas(wxWindow, Publisher): Line 894  class MapCanvas(wxWindow, Publisher):
894              forward = None              forward = None
895    
896          scale = self.scale          scale = self.scale
         offx, offy = self.offset  
897    
898          box = self.unprojected_rect_around_point(px, py)          if scale == 0:
899                return None, None
900    
901            offx, offy = self.offset
902    
903          if select_labels:          if select_labels:
904              labels = self.map.LabelLayer().Labels()              labels = self.map.LabelLayer().Labels()
# Line 699  class MapCanvas(wxWindow, Publisher): Line 946  class MapCanvas(wxWindow, Publisher):
946              if not layer.Visible():              if not layer.Visible():
947                  continue                  continue
948    
949              filled = layer.fill is not None              filled = layer.GetClassification().GetDefaultFill() \
950              stroked = layer.stroke is not None                       is not Color.Transparent
951                stroked = layer.GetClassification().GetDefaultLineColor() \
952                          is not Color.Transparent
953    
954              layer_proj = layer.projection              layer_proj = layer.projection
955              if layer_proj is not None:              if layer_proj is not None:
# Line 712  class MapCanvas(wxWindow, Publisher): Line 961  class MapCanvas(wxWindow, Publisher):
961    
962              select_shape = -1              select_shape = -1
963    
964                # Determine the ids of the shapes that overlap a tiny area
965                # around the point. For layers containing points we have to
966                # choose a larger size of the box we're testing agains so
967                # that we take the size of the markers into account
968                # FIXME: Once the markers are more flexible this part has to
969                # become more flexible too, of course
970                if shapetype == SHAPETYPE_POINT:
971                    box = self.unprojected_rect_around_point(px, py, 5)
972                else:
973                    box = self.unprojected_rect_around_point(px, py, 1)
974              shape_ids = layer.ShapesInRegion(box)              shape_ids = layer.ShapesInRegion(box)
975              shape_ids.reverse()              shape_ids.reverse()
976    
977              if shapetype == SHAPETYPE_POLYGON:              if shapetype == SHAPETYPE_POLYGON:
978                  for i in shape_ids:                  for i in shape_ids:
979                      result = point_in_polygon_shape(layer.shapefile.cobject(),                      shapefile = layer.ShapeStore().Shapefile().cobject()
980                                                      i,                      result = point_in_polygon_shape(shapefile, i,
981                                                      filled, stroked,                                                      filled, stroked,
982                                                      map_proj, layer_proj,                                                      map_proj, layer_proj,
983                                                      scale, -scale, offx, offy,                                                      scale, -scale, offx, offy,
# Line 728  class MapCanvas(wxWindow, Publisher): Line 987  class MapCanvas(wxWindow, Publisher):
987                          break                          break
988              elif shapetype == SHAPETYPE_ARC:              elif shapetype == SHAPETYPE_ARC:
989                  for i in shape_ids:                  for i in shape_ids:
990                      result = point_in_polygon_shape(layer.shapefile.cobject(),                      shapefile = layer.ShapeStore().Shapefile().cobject()
991                        result = point_in_polygon_shape(shapefile,
992                                                      i, 0, 1,                                                      i, 0, 1,
993                                                      map_proj, layer_proj,                                                      map_proj, layer_proj,
994                                                      scale, -scale, offx, offy,                                                      scale, -scale, offx, offy,
# Line 769  class MapCanvas(wxWindow, Publisher): Line 1029  class MapCanvas(wxWindow, Publisher):
1029          # to deselect the currently selected layer, so we simply select          # to deselect the currently selected layer, so we simply select
1030          # the already selected layer again.          # the already selected layer again.
1031          if layer is None:          if layer is None:
1032              layer = self.interactor.SelectedLayer()              layer = self.selection.SelectedLayer()
1033          self.interactor.SelectLayerAndShape(layer, shape)              shapes = []
1034            else:
1035                shapes = [shape]
1036            self.selection.SelectShapes(layer, shapes)
1037          return result          return result
1038    
1039      def LabelShapeAt(self, x, y):      def LabelShapeAt(self, x, y):
1040            """Add or remove a label at window position x, y.
1041    
1042            If there's a label at the given position, remove it. Otherwise
1043            determine the shape at the position, run the label dialog and
1044            unless the user cancels the dialog, add a laber.
1045            """
1046          ox = x; oy = y          ox = x; oy = y
1047          label_layer = self.map.LabelLayer()          label_layer = self.map.LabelLayer()
1048          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 781  class MapCanvas(wxWindow, Publisher): Line 1050  class MapCanvas(wxWindow, Publisher):
1050              # a label was selected              # a label was selected
1051              label_layer.RemoveLabel(shape_index)              label_layer.RemoveLabel(shape_index)
1052          elif layer is not None:          elif layer is not None:
1053              text = labeldialog.run_label_dialog(self, layer.table, shape_index)              text = labeldialog.run_label_dialog(self,
1054                                                    layer.ShapeStore().Table(),
1055                                                    shape_index)
1056              if text:              if text:
1057                  proj = self.map.projection                  proj = self.map.projection
1058                  if proj is not None:                  if proj is not None:
# Line 796  class MapCanvas(wxWindow, Publisher): Line 1067  class MapCanvas(wxWindow, Publisher):
1067    
1068                  shapetype = layer.ShapeType()                  shapetype = layer.ShapeType()
1069                  if shapetype == SHAPETYPE_POLYGON:                  if shapetype == SHAPETYPE_POLYGON:
1070                      x, y = shape_centroid(layer.shapefile.cobject(),                      shapefile = layer.ShapeStore().Shapefile().cobject()
1071                                            shape_index,                      x, y = shape_centroid(shapefile, shape_index,
1072                                            map_proj, layer_proj, 1, 1, 0, 0)                                            map_proj, layer_proj, 1, 1, 0, 0)
1073                      if map_proj is not None:                      if map_proj is not None:
1074                          x, y = map_proj.Inverse(x, y)                          x, y = map_proj.Inverse(x, y)
# Line 822  class MapCanvas(wxWindow, Publisher): Line 1093  class MapCanvas(wxWindow, Publisher):
1093                      valign = ALIGN_CENTER                      valign = ALIGN_CENTER
1094                  label_layer.AddLabel(x, y, text,                  label_layer.AddLabel(x, y, text,
1095                                       halign = halign, valign = valign)                                       halign = halign, valign = valign)
1096    
1097    def OutputTransform(canvas_scale, canvas_offset, canvas_size, device_extend):
1098        """Calculate dimensions to transform canvas content to output device."""
1099        width, height = device_extend
1100    
1101        # Only 80 % of the with are available for the map
1102        width = width * 0.8
1103    
1104        # Define the distance of the map from DC border
1105        distance = 20
1106    
1107        if height < width:
1108            # landscape
1109            map_height = height - 2*distance
1110            map_width = map_height
1111        else:
1112            # portrait, recalibrate width (usually the legend width is too
1113            # small
1114            width = width * 0.9
1115            map_height = width - 2*distance
1116            map_width = map_height
1117        
1118        mapregion = (distance, distance,
1119                     distance+map_width, distance+map_height)
1120    
1121        canvas_width, canvas_height = canvas_size
1122        
1123        scalex = map_width / (canvas_width/canvas_scale)
1124        scaley = map_height / (canvas_height/canvas_scale)
1125        scale = min(scalex, scaley)
1126        canvas_offx, canvas_offy = canvas_offset
1127        offx = scale*canvas_offx/canvas_scale
1128        offy = scale*canvas_offy/canvas_scale
1129    
1130        return scale, (offx, offy), mapregion

Legend:
Removed from v.246  
changed lines
  Added in v.1236

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26