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