/[thuban]/branches/WIP-pyshapelib-bramz/Thuban/UI/view.py
ViewVC logotype

Contents of /branches/WIP-pyshapelib-bramz/Thuban/UI/view.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 122 - (show annotations)
Mon Apr 29 18:04:54 2002 UTC (22 years, 10 months ago) by bh
Original Path: trunk/thuban/Thuban/UI/view.py
File MIME type: text/x-python
File size: 22873 byte(s)
	* Thuban/UI/view.py (MapCanvas): Derive from Publisher as well
	(MapCanvas.__del__): Implement because Publisher.__del__ has to be
	called.
	(MapCanvas.__init__): Bind EVT_LEAVE_WINDOW too. Initialize
	current_position
	(MapCanvas.set_current_position): New method to set
	current_position. Issue a VIEW_POSITION event
	(MapCanvas.CurrentPosition): New public method to return the value
	of current_position. Should be called when the VIEW_POSITION event
	is processed.
	(MapCanvas.OnLeftDown, MapCanvas.OnLeftUp, MapCanvas.OnMotion):
	Update the position.
	(MapCanvas.OnLeaveWindow): Set the position to None.

1 # Copyright (c) 2001, 2002 by Intevation GmbH
2 # Authors:
3 # Bernhard Herzog <[email protected]>
4 #
5 # This program is free software under the GPL (>=v2)
6 # Read the file COPYING coming with Thuban for details.
7
8 """
9 Classes for display of a map and interaction with it
10 """
11
12 __version__ = "$Revision$"
13
14 from math import hypot
15
16 from wxPython.wx import wxWindow,\
17 wxPaintDC, wxColour, wxClientDC, wxINVERT, wxTRANSPARENT_BRUSH, wxFont,\
18 EVT_PAINT, EVT_LEFT_DOWN, EVT_LEFT_UP, EVT_MOTION, EVT_LEAVE_WINDOW
19
20
21 from wxPython import wx
22
23 from wxproj import point_in_polygon_shape, shape_centroid
24
25
26 from Thuban.Model.messages import MAP_PROJECTION_CHANGED, \
27 LAYERS_CHANGED, LAYER_LEGEND_CHANGED, LAYER_VISIBILITY_CHANGED
28 from Thuban.Model.layer import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \
29 SHAPETYPE_POINT
30 from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \
31 ALIGN_LEFT, ALIGN_RIGHT
32 from Thuban.Lib.connector import Publisher
33
34 from renderer import ScreenRenderer, PrinterRender
35
36 import labeldialog
37
38 from messages import SELECTED_SHAPE, VIEW_POSITION
39
40
41 #
42 # The tools
43 #
44
45 class Tool:
46
47 """
48 Base class for the interactive tools
49 """
50
51 def __init__(self, view):
52 """Intitialize the tool. The view is the canvas displaying the map"""
53 self.view = view
54 self.start = self.current = None
55 self.dragging = 0
56 self.drawn = 0
57
58 def Name(self):
59 """Return the tool's name"""
60 return ''
61
62 def drag_start(self, x, y):
63 self.start = self.current = x, y
64 self.dragging = 1
65
66 def drag_move(self, x, y):
67 self.current = x, y
68
69 def drag_stop(self, x, y):
70 self.current = x, y
71 self.dragging = 0
72
73 def Show(self, dc):
74 if not self.drawn:
75 self.draw(dc)
76 self.drawn = 1
77
78 def Hide(self, dc):
79 if self.drawn:
80 self.draw(dc)
81 self.drawn = 0
82
83 def draw(self, dc):
84 pass
85
86 def MouseDown(self, event):
87 self.drag_start(event.m_x, event.m_y)
88
89 def MouseMove(self, event):
90 if self.dragging:
91 self.drag_move(event.m_x, event.m_y)
92
93 def MouseUp(self, event):
94 if self.dragging:
95 self.drag_move(event.m_x, event.m_y)
96
97 def Cancel(self):
98 self.dragging = 0
99
100
101 class RectTool(Tool):
102
103 """Base class for tools that draw rectangles while dragging"""
104
105 def draw(self, dc):
106 sx, sy = self.start
107 cx, cy = self.current
108 dc.DrawRectangle(sx, sy, cx - sx, cy - sy)
109
110 class ZoomInTool(RectTool):
111
112 """The Zoom-In Tool"""
113
114 def Name(self):
115 return "ZoomInTool"
116
117 def proj_rect(self):
118 """return the rectangle given by start and current in projected
119 coordinates"""
120 sx, sy = self.start
121 cx, cy = self.current
122 left, top = self.view.win_to_proj(sx, sy)
123 right, bottom = self.view.win_to_proj(cx, cy)
124 return (min(left, right), min(top, bottom),
125 max(left, right), max(top, bottom))
126
127 def MouseUp(self, event):
128 if self.dragging:
129 Tool.MouseUp(self, event)
130 sx, sy = self.start
131 cx, cy = self.current
132 if sx == cx and sy == cy:
133 # Just a mouse click. Simply zoom in by a factor of two
134 self.view.ZoomFactor(2, center = (cx, cy))
135 else:
136 # A drag. Zoom in to the rectangle
137 self.view.FitRectToWindow(self.proj_rect())
138
139
140 class ZoomOutTool(RectTool):
141
142 """The Zoom-Out Tool"""
143
144 def Name(self):
145 return "ZoomOutTool"
146
147 def MouseUp(self, event):
148 if self.dragging:
149 Tool.MouseUp(self, event)
150 sx, sy = self.start
151 cx, cy = self.current
152 if sx == cx and sy == cy:
153 # Just a mouse click. Simply zoom out by a factor of two
154 self.view.ZoomFactor(0.5, center = (cy, cy))
155 else:
156 # A drag. Zoom out to the rectangle
157 self.view.ZoomOutToRect((min(sx, cx), min(sy, cy),
158 max(sx, cx), max(sy, cy)))
159
160
161 class PanTool(Tool):
162
163 """The Pan Tool"""
164
165 def Name(self):
166 return "PanTool"
167
168 def MouseMove(self, event):
169 if self.dragging:
170 x0, y0 = self.current
171 Tool.MouseMove(self, event)
172 x, y = self.current
173 width, height = self.view.GetSizeTuple()
174 dc = self.view.drag_dc
175 dc.Blit(0, 0, width, height, dc, x0 - x, y0 - y)
176
177 def MouseUp(self, event):
178 if self.dragging:
179 Tool.MouseUp(self, event)
180 sx, sy = self.start
181 cx, cy = self.current
182 self.view.Translate(cx - sx, cy - sy)
183
184 class IdentifyTool(Tool):
185
186 """The "Identify" Tool"""
187
188 def Name(self):
189 return "IdentifyTool"
190
191 def MouseUp(self, event):
192 self.view.SelectShapeAt(event.m_x, event.m_y)
193
194
195 class LabelTool(Tool):
196
197 """The "Label" Tool"""
198
199 def Name(self):
200 return "LabelTool"
201
202 def MouseUp(self, event):
203 self.view.LabelShapeAt(event.m_x, event.m_y)
204
205
206
207
208 class MapPrintout(wx.wxPrintout):
209
210 """
211 wxPrintout class for printing Thuban maps
212 """
213
214 def __init__(self, map):
215 wx.wxPrintout.__init__(self)
216 self.map = map
217
218 def GetPageInfo(self):
219 return (1, 1, 1, 1)
220
221 def HasPage(self, pagenum):
222 return pagenum == 1
223
224 def OnPrintPage(self, pagenum):
225 if pagenum == 1:
226 self.draw_on_dc(self.GetDC())
227
228 def draw_on_dc(self, dc):
229 width, height = self.GetPageSizePixels()
230 llx, lly, urx, ury = self.map.ProjectedBoundingBox()
231 scalex = width / (urx - llx)
232 scaley = height / (ury - lly)
233 scale = min(scalex, scaley)
234 offx = 0.5 * (width - (urx + llx) * scale)
235 offy = 0.5 * (height + (ury + lly) * scale)
236
237 resx, resy = self.GetPPIPrinter()
238 renderer = PrinterRender(dc, scale, (offx, offy), resolution = resx)
239 renderer.RenderMap(self.map)
240 return wx.true
241
242
243 class MapCanvas(wxWindow, Publisher):
244
245 """A widget that displays a map and offers some interaction"""
246
247 def __init__(self, parent, winid, interactor):
248 wxWindow.__init__(self, parent, winid)
249 self.SetBackgroundColour(wxColour(255, 255, 255))
250 self.map = None
251 self.scale = 1.0
252 self.offset = (0, 0)
253 self.dragging = 0
254 self.tool = None
255 self.redraw_on_idle = 0
256 self.current_position = None
257 EVT_PAINT(self, self.OnPaint)
258 EVT_LEFT_DOWN(self, self.OnLeftDown)
259 EVT_LEFT_UP(self, self.OnLeftUp)
260 EVT_MOTION(self, self.OnMotion)
261 EVT_LEAVE_WINDOW(self, self.OnLeaveWindow)
262 wx.EVT_IDLE(self, self.OnIdle)
263 self.interactor = interactor
264 self.interactor.Subscribe(SELECTED_SHAPE, self.shape_selected)
265
266 def __del__(self):
267 wxWindow.__del__(self)
268 Publisher.__del__(self)
269
270 def OnPaint(self, event):
271 dc = wxPaintDC(self)
272 if self.map is not None and self.map.HasLayers():
273 # We have a non-empty map. Redraw it in idle time
274 self.redraw_on_idle = 1
275 else:
276 # If we've got no map or if the map is empty, simply clear
277 # the screen.
278
279 # XXX it's probably possible to get rid of this. The
280 # background color of the window is already white and the
281 # only thing we may have to do is to call self.Refresh()
282 # with a true argument in the right places.
283 dc.BeginDrawing()
284 dc.Clear()
285 dc.EndDrawing()
286
287 def do_redraw(self):
288 # This should only be called if we have a non-empty map. We draw
289 # it into a memory DC and then blit it to the screen.
290 width, height = self.GetSizeTuple()
291 bitmap = wx.wxEmptyBitmap(width, height)
292 dc = wx.wxMemoryDC()
293 dc.SelectObject(bitmap)
294 dc.BeginDrawing()
295
296 # clear the background
297 dc.SetBrush(wx.wxWHITE_BRUSH)
298 dc.SetPen(wx.wxTRANSPARENT_PEN)
299 dc.DrawRectangle(0, 0, width, height)
300
301 if 1: #self.interactor.selected_map is self.map:
302 selected_layer = self.interactor.selected_layer
303 selected_shape = self.interactor.selected_shape
304 else:
305 selected_layer = None
306 selected_shape = None
307
308 # draw the map into the bitmap
309 renderer = ScreenRenderer(dc, self.scale, self.offset)
310 renderer.RenderMap(self.map, selected_layer, selected_shape)
311
312 dc.EndDrawing()
313
314 # blit the bitmap to the screen
315 clientdc = wxClientDC(self)
316 clientdc.BeginDrawing()
317 clientdc.Blit(0, 0, width, height, dc, 0, 0)
318 clientdc.EndDrawing()
319
320 def Print(self):
321 printer = wx.wxPrinter()
322 printout = MapPrintout(self.map)
323 printer.Print(self, printout, wx.true)
324 printout.Destroy()
325
326 def SetMap(self, map):
327 redraw_channels = (LAYERS_CHANGED, LAYER_LEGEND_CHANGED,
328 LAYER_VISIBILITY_CHANGED)
329 if self.map is not None:
330 for channel in redraw_channels:
331 self.map.Unsubscribe(channel, self.redraw)
332 self.map.Unsubscribe(MAP_PROJECTION_CHANGED,
333 self.projection_changed)
334 self.map = map
335 if self.map is not None:
336 for channel in redraw_channels:
337 self.map.Subscribe(channel, self.redraw)
338 self.map.Subscribe(MAP_PROJECTION_CHANGED, self.projection_changed)
339 self.FitMapToWindow()
340 # force a redraw. If map is not empty, it's already been called
341 # by FitMapToWindow but if map is empty it hasn't been called
342 # yet so we have to explicitly call it.
343 self.redraw()
344
345 def Map(self):
346 return self.map
347
348 def redraw(self, *args):
349 self.Refresh(0)
350
351 def projection_changed(self, *args):
352 self.FitMapToWindow()
353 self.redraw()
354
355 def set_view_transform(self, scale, offset):
356 self.scale = scale
357 self.offset = offset
358 self.redraw()
359
360 def proj_to_win(self, x, y):
361 """\
362 Return the point in window coords given by projected coordinates x y
363 """
364 offx, offy = self.offset
365 return (self.scale * x + offx, -self.scale * y + offy)
366
367 def win_to_proj(self, x, y):
368 """\
369 Return the point in projected coordinates given by window coords x y
370 """
371 offx, offy = self.offset
372 return ((x - offx) / self.scale, (offy - y) / self.scale)
373
374 def FitRectToWindow(self, rect):
375 width, height = self.GetSizeTuple()
376 llx, lly, urx, ury = rect
377 if llx == urx or lly == ury:
378 # zero with or zero height. Do Nothing
379 return
380 scalex = width / (urx - llx)
381 scaley = height / (ury - lly)
382 scale = min(scalex, scaley)
383 offx = 0.5 * (width - (urx + llx) * scale)
384 offy = 0.5 * (height + (ury + lly) * scale)
385 self.set_view_transform(scale, (offx, offy))
386
387 def FitMapToWindow(self):
388 """\
389 Set the scale and offset so that the map is centered in the
390 window
391 """
392 bbox = self.map.ProjectedBoundingBox()
393 if bbox is not None:
394 self.FitRectToWindow(bbox)
395
396 def ZoomFactor(self, factor, center = None):
397 """Multiply the zoom by factor and center on center.
398
399 The optional parameter center is a point in window coordinates
400 that should be centered. If it is omitted, it defaults to the
401 center of the window
402 """
403 width, height = self.GetSizeTuple()
404 scale = self.scale * factor
405 offx, offy = self.offset
406 if center is not None:
407 cx, cy = center
408 else:
409 cx = width / 2
410 cy = height / 2
411 offset = (factor * (offx - cx) + width / 2,
412 factor * (offy - cy) + height / 2)
413 self.set_view_transform(scale, offset)
414
415 def ZoomOutToRect(self, rect):
416 # rect is given in window coordinates
417
418 # determine the bbox of the displayed region in projected
419 # coordinates
420 width, height = self.GetSizeTuple()
421 llx, lly = self.win_to_proj(0, height - 1)
422 urx, ury = self.win_to_proj(width - 1, 0)
423
424 sx, sy, ex, ey = rect
425 scalex = (ex - sx) / (urx - llx)
426 scaley = (ey - sy) / (ury - lly)
427 scale = min(scalex, scaley)
428
429 offx = 0.5 * ((ex + sx) - (urx + llx) * scale)
430 offy = 0.5 * ((ey + sy) + (ury + lly) * scale)
431 self.set_view_transform(scale, (offx, offy))
432
433 def Translate(self, dx, dy):
434 offx, offy = self.offset
435 self.set_view_transform(self.scale, (offx + dx, offy + dy))
436
437 def ZoomInTool(self):
438 self.tool = ZoomInTool(self)
439
440 def ZoomOutTool(self):
441 self.tool = ZoomOutTool(self)
442
443 def PanTool(self):
444 self.tool = PanTool(self)
445
446 def IdentifyTool(self):
447 self.tool = IdentifyTool(self)
448
449 def LabelTool(self):
450 self.tool = LabelTool(self)
451
452 def CurrentTool(self):
453 return self.tool and self.tool.Name() or None
454
455 def CurrentPosition(self):
456 """Return current position of the mouse in projected coordinates.
457
458 The result is a 2-tuple of floats with the coordinates. If the
459 mouse is not in the window, the result is None.
460 """
461 if self.current_position is not None:
462 x, y = self.current_position
463 return self.win_to_proj(x, y)
464 else:
465 return None
466
467 def set_current_position(self, event):
468 """Set the current position from event
469
470 Should be called by all events that contain mouse positions
471 especially EVT_MOTION. The event paramete may be None to
472 indicate the the pointer left the window.
473 """
474 if event is not None:
475 self.current_position = (event.m_x, event.m_y)
476 else:
477 self.current_position = None
478 self.issue(VIEW_POSITION)
479
480 def OnLeftDown(self, event):
481 self.set_current_position(event)
482 if self.tool is not None:
483 self.drag_dc = wxClientDC(self)
484 self.drag_dc.SetLogicalFunction(wxINVERT)
485 self.drag_dc.SetBrush(wxTRANSPARENT_BRUSH)
486 self.CaptureMouse()
487 self.tool.MouseDown(event)
488 self.tool.Show(self.drag_dc)
489 self.dragging = 1
490
491 def OnLeftUp(self, event):
492 self.ReleaseMouse()
493 self.set_current_position(event)
494 if self.dragging:
495 self.tool.Hide(self.drag_dc)
496 self.tool.MouseUp(event)
497 self.drag_dc = None
498 self.dragging = 0
499
500 def OnMotion(self, event):
501 self.set_current_position(event)
502 if self.dragging:
503 self.tool.Hide(self.drag_dc)
504 self.tool.MouseMove(event)
505 self.tool.Show(self.drag_dc)
506
507 def OnLeaveWindow(self, event):
508 self.set_current_position(None)
509
510 def OnIdle(self, event):
511 if self.redraw_on_idle:
512 self.do_redraw()
513 self.redraw_on_idle = 0
514
515 def shape_selected(self, layer, shape):
516 self.redraw()
517
518 def find_shape_at(self, px, py, select_labels = 0, selected_layer = 1):
519 """Determine the shape at point px, py in window coords
520
521 Return the shape and the corresponding layer as a tuple (layer,
522 shape).
523
524 If the optional parameter select_labels is true (default false)
525 search through the labels. If a label is found return it's index
526 as the shape and None as the layer.
527
528 If the optional parameter selected_layer is true (default), only
529 search in the currently selected layer.
530 """
531 map_proj = self.map.projection
532 if map_proj is not None:
533 forward = map_proj.Forward
534 else:
535 forward = None
536
537 scale = self.scale
538 offx, offy = self.offset
539
540 if select_labels:
541 labels = self.map.LabelLayer().Labels()
542
543 if labels:
544 dc = wxClientDC(self)
545 font = wxFont(10, wx.wxSWISS, wx.wxNORMAL, wx.wxNORMAL)
546 dc.SetFont(font)
547 for i in range(len(labels) - 1, -1, -1):
548 label = labels[i]
549 x = label.x
550 y = label.y
551 text = label.text
552 if forward:
553 x, y = forward(x, y)
554 x = x * scale + offx
555 y = -y * scale + offy
556 width, height = dc.GetTextExtent(text)
557 if label.halign == ALIGN_LEFT:
558 # nothing to be done
559 pass
560 elif label.halign == ALIGN_RIGHT:
561 x = x - width
562 elif label.halign == ALIGN_CENTER:
563 x = x - width/2
564 if label.valign == ALIGN_TOP:
565 # nothing to be done
566 pass
567 elif label.valign == ALIGN_BOTTOM:
568 y = y - height
569 elif label.valign == ALIGN_CENTER:
570 y = y - height/2
571 if x <= px < x + width and y <= py <= y + height:
572 return None, i
573
574 if selected_layer:
575 layer = self.interactor.SelectedLayer()
576 if layer is not None:
577 layers = [layer]
578 else:
579 # no layer selected. Use an empty list to effectively
580 # ignore all layers.
581 layers = []
582 else:
583 layers = self.map.Layers()
584
585 for layer_index in range(len(layers) - 1, -1, -1):
586 layer = layers[layer_index]
587
588 # search only in visible layers
589 if not layer.Visible():
590 continue
591
592 filled = layer.fill is not None
593 stroked = layer.stroke is not None
594
595 layer_proj = layer.projection
596 if layer_proj is not None:
597 inverse = layer_proj.Inverse
598 else:
599 inverse = None
600
601 shapetype = layer.ShapeType()
602
603 select_shape = -1
604 if shapetype == SHAPETYPE_POLYGON:
605 for i in range(layer.NumShapes() - 1, -1, -1):
606 result = point_in_polygon_shape(layer.shapefile.cobject(),
607 i,
608 filled, stroked,
609 map_proj, layer_proj,
610 scale, -scale, offx, offy,
611 px, py)
612 if result:
613 select_shape = i
614 break
615 elif shapetype == SHAPETYPE_ARC:
616 for i in range(layer.NumShapes() - 1, -1, -1):
617 result = point_in_polygon_shape(layer.shapefile.cobject(),
618 i, 0, 1,
619 map_proj, layer_proj,
620 scale, -scale, offx, offy,
621 px, py)
622 if result < 0:
623 select_shape = i
624 break
625 elif shapetype == SHAPETYPE_POINT:
626 for i in range(layer.NumShapes() - 1, -1, -1):
627 shape = layer.Shape(i)
628 x, y = shape.Points()[0]
629 if inverse:
630 x, y = inverse(x, y)
631 if forward:
632 x, y = forward(x, y)
633 x = x * scale + offx
634 y = -y * scale + offy
635 if hypot(px - x, py - y) < 5:
636 select_shape = i
637 break
638
639 if select_shape >= 0:
640 return layer, select_shape
641 return None, None
642
643 def SelectShapeAt(self, x, y):
644 layer, shape = self.find_shape_at(x, y, selected_layer = 0)
645 # If layer is None, then shape will also be None. We don't want
646 # to deselect the currently selected layer, so we simply select
647 # the already selected layer again.
648 if layer is None:
649 layer = self.interactor.SelectedLayer()
650 self.interactor.SelectLayerAndShape(layer, shape)
651
652 def LabelShapeAt(self, x, y):
653 ox = x; oy = y
654 label_layer = self.map.LabelLayer()
655 layer, shape_index = self.find_shape_at(x, y, select_labels = 1)
656 if layer is None and shape_index is not None:
657 # a label was selected
658 label_layer.RemoveLabel(shape_index)
659 elif layer is not None:
660 text = labeldialog.run_label_dialog(self, layer.table, shape_index)
661 if text:
662 proj = self.map.projection
663 if proj is not None:
664 map_proj = proj
665 else:
666 map_proj = None
667 proj = layer.projection
668 if proj is not None:
669 layer_proj = proj
670 else:
671 layer_proj = None
672
673 shapetype = layer.ShapeType()
674 if shapetype == SHAPETYPE_POLYGON:
675 x, y = shape_centroid(layer.shapefile.cobject(),
676 shape_index,
677 map_proj, layer_proj, 1, 1, 0, 0)
678 if map_proj is not None:
679 x, y = map_proj.Inverse(x, y)
680 else:
681 shape = layer.Shape(shape_index)
682 if shapetype == SHAPETYPE_POINT:
683 x, y = shape.Points()[0]
684 else:
685 # assume SHAPETYPE_ARC
686 points = shape.Points()
687 x, y = points[len(points) / 2]
688 if layer_proj is not None:
689 x, y = layer_proj.Inverse(x, y)
690 if shapetype == SHAPETYPE_POINT:
691 halign = ALIGN_LEFT
692 valign = ALIGN_CENTER
693 elif shapetype == SHAPETYPE_POLYGON:
694 halign = ALIGN_CENTER
695 valign = ALIGN_CENTER
696 elif shapetype == SHAPETYPE_ARC:
697 halign = ALIGN_LEFT
698 valign = ALIGN_CENTER
699 label_layer.AddLabel(x, y, text,
700 halign = halign, valign = valign)

Properties

Name Value
svn:eol-style native
svn:keywords Author Date Id Revision

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26