BUGFIX : calculate reference pixel properly
[wifihood] / view.py
1
2 import gtk
3 import gobject
4
5 import urllib2
6 import math
7
8 import os
9
10 class background_map ( gtk.gdk.Pixmap ) :
11
12     def __init__ ( self , map_size , tileloader ) :
13         bordersize = 1
14
15         self.tileloader = tileloader
16
17         # Values for minimun fit without border
18         center = map( lambda x :     int( math.ceil( x / float(tileloader.tilesize) ) / 2 )     , map_size )
19         size = map( lambda x : 2 * x + 1 , center )
20
21         self.center = map( lambda x : x + bordersize , center )
22         self.size = map( lambda x : x + 2 * bordersize , size )
23         pixsize = map( lambda x : x * tileloader.tilesize , self.size )
24
25         gtk.gdk.Pixmap.__init__( self , None , pixsize[0] , pixsize[1] , 24 )
26
27         self.fill = map( lambda x : False , range( self.size[0] * self.size[1] ) )
28
29         self.loadtiles()
30
31     def index ( self , x , y ) :
32         return x + y * self.size[0]
33
34     def loadtiles ( self ) :
35
36         for x in range(self.size[0]) :
37             for y in range(self.size[1]) :
38
39                 pixbuf = self.tileloader.get_tile( (x,y) )
40                 if pixbuf :
41                     self.fill[ self.index(x,y) ] = True
42                 else :
43                     pixbuf = self.tileloader.emptytile()
44
45                 dest_x = self.tileloader.tilesize * x
46                 dest_y = self.tileloader.tilesize * y
47                 self.draw_pixbuf( None , pixbuf , 0 , 0 , dest_x , dest_y )
48
49
50 class tile_loader :
51
52     def __init__ ( self , conf ) :
53         self.tilesize = 256
54         self.rootdir = "%s/%s/%s" % ( conf.mapsdir , conf.mapclass , conf.zoom )
55         self.reftile , self.refpix = self.get_reference( conf )
56
57     def get_reference ( self , conf ) :
58         tilex = self.lon2tilex( conf.lon , conf.zoom )
59         tiley = self.lat2tiley( conf.lat , conf.zoom )
60         tile = tilex[1] , tiley[1] 
61         pix = tilex[0] , tiley[0] 
62         return map( int , tile ) , map( lambda x : int( self.tilesize * x ) , pix )
63
64     def lon2tilex ( self , lon , zoom ) :
65         return math.modf( ( lon + 180 ) / 360 * 2 ** zoom )
66
67     def lat2tiley ( self , lat , zoom ) :
68         lat = lat * math.pi / 180
69         return math.modf( ( 1 - math.log( math.tan( lat ) + 1 / math.cos( lat ) ) / math.pi ) / 2 * 2 ** zoom )
70
71     def get_tile ( self , tile ) :
72         file = self.tilepath( self.reftile[0] + tile[0] , self.reftile[1] + tile[1] )
73         try :
74             os.stat(file)
75             return gtk.gdk.pixbuf_new_from_file( file )
76         except :
77             try :
78                 # useful members : response.code, response.headers
79                 response = urllib2.urlopen( "http://tile.openstreetmap.org/%s/%s/%s.png" % ( zoom , x , y ) )
80                 if response.geturl() != "http://tile.openstreetmap.org/11/0/0.png" :
81                     fd = open( file , 'w' )
82                     fd.write( response.read() )
83                     fd.close()
84                     # FIXME : can this actually produce a gobject.GError exception ?
85                     return gtk.gdk.pixbuf_new_from_file( file )
86             except :
87                 pass
88
89         return None
90
91     def tilepath( self , tilex , tiley ) :
92       return "%s/%s/%s.png" % ( self.rootdir , tilex , tiley )
93
94     def emptytile( self ) :
95         pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, self.tilesize, self.tilesize )
96         pixbuf.fill( 0x00000000 )
97         return pixbuf
98
99
100 class AbstractmapWidget :
101
102   def __init__ ( self , config , map_size ) :
103
104     self.conf = config
105
106     # Maximum width should be 800, but actually gets reduced
107     self.win_x , self.win_y = map_size
108     self.tile_size = 256
109
110     self.reftile_x , self.refpix_x = self.lon2tilex( self.conf.lon , self.conf.zoom )
111     self.reftile_y , self.refpix_y = self.lat2tiley( self.conf.lat , self.conf.zoom )
112
113   def recenter ( self , latlon ) :
114
115         center = self.gps2pix( latlon , self.center() )
116         pixel = self.gps2pix( (self.conf.lat,self.conf.lon) , self.center() )
117
118         distance = math.sqrt( (pixel[0]-center[0])**2 + (pixel[1]-center[1])**2 )
119
120         # FIXME : instead of hardcoded, should depend on the actual display size
121         if distance > 150 :
122             self.conf.set_latlon( latlon )
123
124             self.reftile_x , self.refpix_x = self.lon2tilex( self.conf.lon , self.conf.zoom )
125             self.reftile_y , self.refpix_y = self.lat2tiley( self.conf.lat , self.conf.zoom )
126
127             self.composeMap()
128
129   def tilex2lon ( self , ( tilex , pixx ) , zoom ) :
130         tilex = float(tilex)
131         pixx = float(pixx)
132         return ( tilex + pixx/self.tile_size ) / 2.0 ** zoom * 360.0 - 180.0
133
134   def tiley2lat ( self , ( tiley , pixy ) , zoom ) :
135         tiley = float(tiley)
136         pixy = float(pixy)
137         tiley = math.pi * ( 1 - 2 * ( tiley + pixy/self.tile_size ) / 2.0 ** zoom )
138         return math.degrees( math.atan( math.sinh( tiley ) ) )
139
140   def SetZoom( self , zoom ) :
141         self.hide()
142         lat = self.tiley2lat( ( self.reftile_y , self.refpix_y ) , self.conf.zoom )
143         lon = self.tilex2lon( ( self.reftile_x , self.refpix_x ) , self.conf.zoom )
144         self.reftile_x , self.refpix_x = self.lon2tilex( lon , zoom )
145         self.reftile_y , self.refpix_y = self.lat2tiley( lat , zoom )
146         self.conf.set_zoom( zoom )
147         self.composeMap()
148         self.show()
149
150   def lon2tilex ( self , lon , zoom ) :
151     number = math.modf( ( lon + 180 ) / 360 * 2 ** zoom )
152     return int( number[1] ) , int( self.tile_size * number[0] )
153
154   def lat2tiley ( self , lat , zoom ) :
155     lat = lat * math.pi / 180
156     number = math.modf( ( 1 - math.log( math.tan( lat ) + 1 / math.cos( lat ) ) / math.pi ) / 2 * 2 ** zoom )
157     return int( number[1] ) , int( self.tile_size * number[0] )
158
159   def gps2pix ( self , ( lat , lon ) , ( center_x , center_y ) ) :
160
161     x_pos = self.lon2tilex( lon , self.conf.zoom )
162     y_pos = self.lat2tiley( lat , self.conf.zoom )
163
164     dest_x = self.tile_size * ( x_pos[0] - self.reftile_x ) + center_x + x_pos[1]
165     dest_y = self.tile_size * ( y_pos[0] - self.reftile_y ) + center_y + y_pos[1]
166
167     return dest_x , dest_y
168
169   def tilename ( self , x , y , zoom ) :
170     file = self.tile2file( self.reftile_x + x , self.reftile_y + y , zoom )
171     try :
172       os.stat(file)
173     except :
174     #  if mapDownload :
175       if False :
176         try :
177           # useful members : response.code, response.headers
178           response = urllib2.urlopen( "http://tile.openstreetmap.org/%s/%s/%s.png" % ( zoom , x , y ) )
179           if response.geturl() == "http://tile.openstreetmap.org/11/0/0.png" :
180               return None
181           fd = open( file , 'w' )
182           fd.write( response.read() )
183           fd.close()
184         except :
185           return None
186       else :
187         return None
188     return file
189
190   def tile2file( self , tilex , tiley , zoom ) :
191     rootdir = "%s/%s/%s" % ( self.conf.mapsdir , self.conf.mapclass , zoom )
192     if not os.path.isdir( rootdir ) :
193       os.mkdir(rootdir)
194     rootsubdir = "%s/%s" % ( rootdir , tilex )
195     if not os.path.isdir( rootsubdir ) :
196       os.mkdir(rootsubdir)
197     return "%s/%s.png" % ( rootsubdir , tiley )
198
199 class interactiveMapWidget :
200
201   def Shift( self , dx , dy ) :
202     self.hide()
203
204     tile_x , tile_y = ( self.refpix_x - dx ) / self.tile_size , ( self.refpix_y - dy ) / self.tile_size
205     self.reftile_x += tile_x
206     self.reftile_y += tile_y
207
208     self.refpix_x -= dx + self.tile_size * tile_x
209     self.refpix_y -= dy + self.tile_size * tile_y
210
211     self.composeMap()
212     self.show()
213
214   def Up( self ) :
215     self.hide()
216     self.reftile_y -= 1
217     self.composeMap()
218     self.show()
219
220   def Down( self ) :
221     self.hide()
222     self.reftile_y += 1
223     self.composeMap()
224     self.show()
225
226   def Right( self ) :
227     self.hide()
228     self.reftile_x += 1
229     self.composeMap()
230     self.show()
231
232   def Left( self ) :
233     self.hide()
234     self.reftile_x -= 1
235     self.composeMap()
236     self.show()
237
238 class simpleMapWidget ( AbstractmapWidget , gtk.Image ) :
239
240     def __init__ ( self , config , map_size=(800,480) ) :
241         AbstractmapWidget.__init__( self , config , map_size )
242
243         gtk.Image.__init__(self)
244
245         self._bg = background_map( map_size , tile_loader( config ) )
246
247         p = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, map_size[0] , map_size[1] )
248         p.get_from_drawable( self._bg , self._bg.get_colormap() , 0, 0 , 0, 0 , map_size[0] , map_size[1] )
249         self.set_from_pixbuf(p)
250     
251     def composeMap( self ) :
252         center_x , center_y = self.center()
253
254         # Ranges should be long enough as to fill the screen
255         # Maybe they should be decided based on self.win_x, self.win_y
256         for i in range(-3,4) :
257             for j in range(-3,4) :
258                 file = self.tilename( i , j , self.conf.zoom )
259                 if file is None :
260                     pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, self.tile_size, self.tile_size )
261                     pixbuf.fill( 0x00000000 )
262                 else :
263                     try :
264                         pixbuf = gtk.gdk.pixbuf_new_from_file( file )
265                     except gobject.GError , ex :
266                         print "Corrupted file %s" % ( file )
267                         os.unlink( file )
268                         #file = self.tilename( self.reftile_x + i , self.reftile_y + j , self.conf.zoom )
269                         file = self.tilename( i , j , self.conf.zoom )
270                         try :
271                             pixbuf = gtk.gdk.pixbuf_new_from_file( file )
272                         except :
273                             print "Total failure for tile for %s,%s" % ( self.reftile_x + i , self.reftile_y + j )
274                             pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, self.tile_size, self.tile_size )
275
276                 dest_x = self.tile_size * i + center_x
277                 dest_y = self.tile_size * j + center_y
278
279                 init_x = 0
280                 size_x = self.tile_size
281                 if dest_x < 0 :
282                    init_x = abs(dest_x)
283                    size_x = self.tile_size + dest_x
284                    dest_x = 0
285                 if dest_x + self.tile_size > self.win_x :
286                    size_x = self.win_x - dest_x
287     
288                 init_y = 0
289                 size_y = self.tile_size
290                 if dest_y < 0 :
291                    init_y = abs(dest_y)
292                    size_y = self.tile_size + dest_y
293                    dest_y = 0
294                 if dest_y + self.tile_size > self.win_y :
295                    size_y = self.win_y - dest_y
296
297                 if ( size_x > 0 and size_y > 0 ) and ( init_x < self.tile_size and init_y < self.tile_size ) :
298                     pixbuf.copy_area( init_x, init_y, size_x, size_y, self.get_pixbuf(), dest_x , dest_y )
299                 del(pixbuf)
300
301 #        self.draw_paths()
302 #        self.plot_APs()
303
304     def center( self ) :
305
306         center_x , center_y = self.win_x / 2 , self.win_y / 2
307
308         # To get the central pixel in the window center, we must shift to the tile origin
309         center_x -= self.refpix_x
310         center_y -= self.refpix_y
311
312         return center_x , center_y
313
314     def plot( self , pixmap , coords , colorname , radius=3 ) :
315
316         center_x , center_y = self.center()
317
318         gc = pixmap.new_gc()
319         gc.foreground = pixmap.get_colormap().alloc_color( colorname )
320
321         dest_x , dest_y = self.gps2pix( coords , ( center_x , center_y ) )
322         pixmap.draw_rectangle(gc, True , dest_x , dest_y , radius , radius )
323
324     def draw_paths( self ) :
325
326         pixmap,mask = self.get_pixbuf().render_pixmap_and_mask()
327
328         filename = "data/wiscan_gui.info.old"
329         fd = open( filename )
330         for line in fd.readlines() :
331             values = line.split()
332             if values[1] == "FIX" :
333                 self.plot( pixmap , ( float(values[5]) , float(values[6]) ) , "red" )
334         fd.close()
335
336         self.get_pixbuf().get_from_drawable( pixmap , pixmap.get_colormap() , 0, 0 , 0 , 0 , self.win_x, self.win_y )
337
338     def plot_APs( self ) :
339
340         pixmap,mask = self.get_pixbuf().render_pixmap_and_mask()
341
342         db = wifimap.db.database( os.path.join( self.conf.homedir , self.conf.dbname ) )
343         db.open()
344         # NOTE : Intervals for query are just educated guesses to fit in window
345         lat , lon = self.conf.lat , self.conf.lon
346         for ap in db.db.execute( "SELECT * FROM ap where lat/n>%f and lat/n<%f and lon/n>%f and lon/n<%f" % ( lat - 0.003 , lat + 0.003 , lon - 0.007 , lon + 0.007 ) ) :
347             if ap[3] > 1 :
348                 self.plot( pixmap , ( ap[4]/ap[3] , ap[5]/ap[3] ) , "blue" )
349         db.close()
350
351         self.get_pixbuf().get_from_drawable( pixmap , pixmap.get_colormap() , 0, 0 , 0 , 0 , self.win_x, self.win_y )
352
353 class mapWidget ( simpleMapWidget , interactiveMapWidget ) :
354
355     pass
356
357 if __name__ == "__main__" :
358
359     class StaticConfiguration :
360
361         def __init__ ( self , type=None ) :
362             self._type = type
363
364             self.homedir , self.dbname = None , None
365             self.mapsdir , self.mapclass = "/boot/home/localuser/Maps" , "OpenStreetMap I"
366
367             self.store_log , self.use_mapper , self.store_gps = None , None , None
368
369             self.lat , self.lon = 40.416 , -3.683
370             self.zoom = 15
371
372     def on_key_press ( widget, event , map ) :
373         if event.keyval == gtk.keysyms.Up :
374             map.Up()
375         elif event.keyval == gtk.keysyms.Down :
376             map.Down()
377         elif event.keyval == gtk.keysyms.Right :
378             map.Right()
379         elif event.keyval == gtk.keysyms.Left :
380             map.Left()
381         else :
382             print "UNKNOWN",event.keyval
383
384     config = StaticConfiguration()
385     map = mapWidget( config )
386     window = gtk.Window()
387     window.connect("destroy", gtk.main_quit )
388     #window.connect_object("destroy", gtk.Window.destroy , window )
389     window.connect("key-press-event", on_key_press, map )
390     window.add( map )
391     window.show_all()
392     gtk.main()
393