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