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