Added method to retrieve GPS coordinates from tile
[wifihood] / wifiscanner / wifiview
1 #!/usr/bin/env python
2
3 import gtk
4 import gobject , gconf
5
6 import urllib2
7 import math
8
9 import os
10
11 class WifihoodConfig :
12
13     def __init__ ( self ) :
14         self.lat , self.lon = 40.40491 , -3.6774
15         self.zoom = 11
16         self.mapsdir = "/home/user/MyDocs/.maps"
17
18         self.client = gconf.client_get_default()
19
20     def read ( self , parentdir="/apps/wifihood"  ) :
21         lat = self.client.get_float( "%s/lattitude" % parentdir )
22         if lat : self.lat = lat
23         lon = self.client.get_float( "%s/longitude" % parentdir )
24         if lon : self.lon = lon
25         zoom = self.client.get_int( "%s/zoom" % parentdir )
26         if zoom : self.zoom = zoom
27         mapsdir = self.client.get_string( "%s/mapsdir" % parentdir )
28         if mapsdir : self.mapsdir = mapsdir
29
30     def save ( self , parentdir="/apps/wifihood" ) :
31         self.client.set_float( "%s/lattitude" % parentdir , self.lat )
32         self.client.set_float( "%s/longitude" % parentdir , self.lon )
33         self.client.set_int( "%s/zoom" % parentdir , self.zoom )
34         self.client.set_string( "%s/mapsdir" % parentdir , self.mapsdir )
35
36 class mapWidget ( gtk.Image , WifihoodConfig ) :
37
38   def __init__(self):
39
40     WifihoodConfig.__init__( self )
41     gtk.Image.__init__(self)
42
43     # Maximum width should be 800, but actually gets reduced
44     self.win_x , self.win_y = 800 , 480
45
46     p = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, self.win_x, self.win_y)
47     self.set_from_pixbuf(p)
48
49     self.read()
50     self.reftile_x , self.reftile_y = self.lon2tilex( self.lon , self.zoom ) , self.lat2tiley( self.lat , self.zoom )
51     # Half the size of a tile
52     self.refpix_x , self.refpix_y = 128 , 128
53
54     self.composeMap()
55
56   def lon2tilex ( self , lon , zoom ) :
57     return int( ( lon + 180 ) / 360 * 2 ** zoom )
58
59   def lat2tiley ( self , lat , zoom ) :
60     lat = lat * math.pi / 180
61     return int( ( 1 - math.log( math.tan( lat ) + 1 / math.cos( lat ) ) / math.pi ) / 2 * 2 ** zoom )
62
63   def tilex2lon ( self , tilex , zoom ) :
64     return tilex / 2.0 ** zoom * 360.0 - 180.0
65
66   def tiley2lat ( self , tiley , zoom ) :
67     tiley = math.pi * ( 1 - 2 * tiley / 2.0 ** zoom )
68     return math.degrees( math.atan( math.sinh( tiley ) ) )
69
70   def composeMap( self ) :
71     center_x , center_y = self.win_x / 2 , self.win_y / 2
72
73     # To get the central pixel in the window center, we must shift to the tile origin
74     center_x -= self.refpix_x
75     center_y -= self.refpix_y
76
77     # Ranges should be long enough as to fill the screen
78     # Maybe they should be decided based on self.win_x, self.win_y
79     for i in range(-3,4) :
80       for j in range(-3,4) :
81         file = self.tilename( i , j , self.zoom )
82         if file is None :
83           pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 256, 256 )
84           pixbuf.fill( 0x00000000 )
85         else :
86           try :
87             pixbuf = gtk.gdk.pixbuf_new_from_file( file )
88           except gobject.GError , ex :
89             print "Corrupted file %s" % ( file )
90             os.unlink( file )
91             #file = self.tilename( self.reftile_x + i , self.reftile_y + j , self.zoom )
92             file = self.tilename( i , j , self.zoom )
93             try :
94               pixbuf = gtk.gdk.pixbuf_new_from_file( file )
95             except :
96               print "Total failure for tile for %s,%s" % ( self.reftile_x + i , self.reftile_y + j )
97               pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 256, 256 )
98
99         dest_x = 256 * i + center_x
100         dest_y = 256 * j + center_y
101
102         init_x = 0
103         size_x = 256
104         if dest_x < 0 :
105            init_x = abs(dest_x)
106            size_x = 256 + dest_x
107            dest_x = 0
108         if dest_x + 256 > self.win_x :
109            size_x = self.win_x - dest_x
110
111         init_y = 0
112         size_y = 256
113         if dest_y < 0 :
114            init_y = abs(dest_y)
115            size_y = 256 + dest_y
116            dest_y = 0
117         if dest_y + 256 > self.win_y :
118            size_y = self.win_y - dest_y
119
120         if ( size_x > 0 and size_y > 0 ) and ( init_x < 256 and init_y < 256 ) :
121             pixbuf.copy_area( init_x, init_y, size_x, size_y, self.get_pixbuf(), dest_x , dest_y )
122         del(pixbuf)
123
124   def tilename ( self , x , y , zoom ) :
125     file = self.tile2file( self.reftile_x + x , self.reftile_y + y , zoom )
126     try :
127       os.stat(file)
128     except :
129     #  if mapDownload :
130       if False :
131         try :
132           # useful members : response.code, response.headers
133           response = urllib2.urlopen( "http://tile.openstreetmap.org/%s/%s/%s.png" % ( zoom , x , y ) )
134           if response.geturl() == "http://tile.openstreetmap.org/11/0/0.png" :
135               return None
136           fd = open( file , 'w' )
137           fd.write( response.read() )
138           fd.close()
139         except :
140           return None
141       else :
142         return None
143     return file
144
145   def tile2file( self , tilex , tiley , zoom ) :
146     rootdir = "%s/OpenStreetMap I/%s" % ( self.mapsdir , zoom )
147     if not os.path.isdir( rootdir ) :
148       os.mkdir(rootdir)
149     rootsubdir = "%s/%s" % ( rootdir , tilex )
150     if not os.path.isdir( rootsubdir ) :
151       os.mkdir(rootsubdir)
152     return "%s/%s.png" % ( rootsubdir , tiley )
153
154   def Shift( self , dx , dy ) :
155     self.hide()
156
157     tile_x , tile_y = ( self.refpix_x - dx ) / 256 , ( self.refpix_y - dy ) / 256
158     self.reftile_x += tile_x
159     self.reftile_y += tile_y
160
161     self.refpix_x -= dx + 256 * tile_x
162     self.refpix_y -= dy + 256 * tile_y
163
164     self.composeMap()
165     self.show()
166
167   def SetZoom( self , zoom ) :
168     self.hide()
169     lat = self.tiley2lat( self.reftile_y , self.zoom )
170     lon = self.tilex2lon( self.reftile_x , self.zoom )
171     self.reftile_x , self.reftile_y = self.lon2tilex( lon , zoom ) , self.lat2tiley( lat , zoom )
172     self.zoom = zoom
173     self.refpix_x , self.refpix_y = 128 , 128
174     self.composeMap()
175     self.show()
176
177   def Up( self ) :
178     self.hide()
179     self.reftile_y -= 1
180     self.composeMap()
181     self.show()
182
183   def Down( self ) :
184     self.hide()
185     self.reftile_y += 1
186     self.composeMap()
187     self.show()
188
189   def Right( self ) :
190     self.hide()
191     self.reftile_x += 1
192     self.composeMap()
193     self.show()
194
195   def Left( self ) :
196     self.hide()
197     self.reftile_x -= 1
198     self.composeMap()
199     self.show()
200
201 class ZoomDialog ( gtk.Dialog ) :
202
203     def __init__ ( self , widget ) :
204         gtk.Dialog.__init__( self , "Select zoom level",
205                              None,
206                              gtk.DIALOG_MODAL,
207                              ( gtk.STOCK_OK, gtk.RESPONSE_ACCEPT,
208                                gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT
209                                )
210                              )
211
212         zooms = gtk.ListStore(int)
213         combo = gtk.ComboBox( zooms )
214
215         for zoom in range(8,19) :
216             iter = zooms.append()
217             zooms.set( iter , 0 , zoom )
218             if zoom == widget.zoom :
219                 combo.set_active_iter( iter )
220
221         cell = gtk.CellRendererText()
222         combo.pack_start(cell, True)
223         combo.add_attribute(cell, 'text', 0)  
224
225         self.vbox.pack_start(combo , True, True, 0)
226
227         self.connect_object( "response", self.response , combo , widget )
228
229     def response ( self , combo , response  , widget ) :
230         if response == gtk.RESPONSE_ACCEPT :
231             item = combo.get_active_iter()
232             model = combo.get_model()
233             widget.SetZoom( model.get(item,0)[0] )
234         self.destroy()
235         
236
237 class MapWindow:
238
239     def destroy(self, widget, data=None):
240         gtk.main_quit()
241
242     def press_event ( self, widget, event, *args ) :
243       # FIXME : Set only if far enough from borders
244       border_x = 40
245       border_y = 30
246       print "press  ",event.get_coords(),event.get_root_coords()
247       if event.x > border_x and event.y > border_y and event.x < ( self.size_x - border_x ) and event.y < ( self.size_y - border_y ) :
248         self.click_x = event.x
249         self.click_y = event.y
250
251     def release_event ( self, widget, event, *args ) :
252       min_shift = 50
253       print "unpress",event.get_coords(),event.get_root_coords()
254       if self.click_x is not None and self.click_y is not None :
255         delta_x = int( event.x - self.click_x )
256         delta_y = int( event.y - self.click_y )
257         shift = math.sqrt( delta_x * delta_x + delta_y * delta_y )
258         if shift > min_shift :
259           self.map.Shift(delta_x, delta_y)
260         #  if delta_x > 100 :
261         #    self.map.Left()
262         #  elif delta_x < -100 :
263         #    self.map.Right()
264         #  elif delta_y > 100 :
265         #    self.map.Up()
266         #  elif delta_y < -100 :
267         #    self.map.Down()
268       self.click_x , self.click_y = None , None
269
270     def screen_event ( self, widget, event, *args ) :
271       print "REDIOS",event
272       print "      ",widget
273       print "      ",args
274
275
276     def on_button_press ( self, widget, event, *args ) :
277       print "HOLA",event
278
279     def on_key_press ( self, widget, event, *args ) :
280       if event.keyval == gtk.keysyms.Up :
281           self.map.Up()
282       elif event.keyval == gtk.keysyms.Down :
283           self.map.Down()
284       elif event.keyval == gtk.keysyms.Right :
285           self.map.Right()
286       elif event.keyval == gtk.keysyms.Left :
287           self.map.Left()
288       else :
289           print "UNKNOWN",event.keyval
290
291     def __init__(self):
292
293         self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
294     
295         self.window.connect("destroy", self.destroy)
296
297         self.window.set_border_width(10)
298     
299         self.window.connect("key-press-event", self.on_key_press)
300         
301         vbox = gtk.VBox(False, 0)
302         self.window.add( vbox )
303
304         # To get explicit GDK_BUTTON_PRESS instead of paired GDK_LEAVE_NOTIFY & GDK_ENTER_NOTIFY
305 #        self.window.add_events(gtk.gdk.BUTTON_MOTION_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.POINTER_MOTION_MASK)
306         self.window.set_events( gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK )
307         #
308 #        self.window.connect('motion_notify_event', self.screen_event)
309         self.window.connect('button_press_event', self.press_event)
310         self.window.connect('button_release_event', self.release_event)
311         #
312         self.map = mapWidget()
313         vbox.pack_end( self.map , True , True , 5)
314     
315         self.create_menu( vbox )
316
317         # and the window
318         self.window.show_all()
319
320         self.size_x , self.size_y = 800 , 480
321         self.click_x , self.click_y = None , None
322
323     def zoomdialog ( self , widget ) :
324         dialog = ZoomDialog( widget )
325         dialog.show_all()
326
327     def create_menu ( self , vbox ) :
328         menubar = gtk.MenuBar()
329
330         zoomlevel = gtk.MenuItem( label="Zoom level" )
331         zoomlevel.connect_object( "activate", self.zoomdialog, self.map )
332         menubar.append( zoomlevel )
333
334         vbox.pack_start(menubar,True,True,5)
335
336     def main(self):
337         gtk.main()
338
339 if __name__ == "__main__":
340     map = MapWindow()
341     map.main()
342