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