dedicated to seddi
[enigma2-plugins.git] / googlemaps / src / plugin.py
1 ###############################################################################
2 # Copyright (c) 2008 Rico Schulte, 3c5x9. All rights reserved.
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining a
5 # copy of this software and associated documentation files (the "Software"),
6 # to deal in the Software without restriction, including without limitation
7 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 # and/or sell copies of the Software, and to permit persons to whom the
9 # Software is furnished to do so, subject to the following conditions:
10 #
11 # The above copyright notice and this permission notice shall be included
12 # in all copies or substantial portions of the Software.
13 #
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 # DEALINGS IN THE SOFTWARE.
21 ###############################################################################
22
23 import urllib
24 from twisted.web.client import getPage
25 from xml.dom.minidom import parseString
26
27 from enigma import eTimer, getDesktop, eSize, eRCInput
28 from Plugins.Plugin import PluginDescriptor
29 from Screens.Screen import Screen
30 from Screens.InputBox import InputBox
31 from Screens.HelpMenu import HelpableScreen
32 from Components.ActionMap import ActionMap
33 from Components.Label import Label
34 from Components.MenuList import MenuList
35 from Components.Input import Input
36 from Components.config import config, ConfigSubList, ConfigSubsection, ConfigInteger, ConfigYesNo, ConfigText, getConfigListEntry
37 from Components.ConfigList import ConfigListScreen
38
39 from Plugins.Extensions.GoogleMaps.globalmaptiles import GlobalMercator
40 from Plugins.Extensions.GoogleMaps.KMLlib import RootFolder,KmlFolder,KmlPlace
41 from Plugins.Extensions.GoogleMaps.WebPixmap import WebPixmap
42
43 config.plugins.GoogleMaps = ConfigSubsection()
44 config.plugins.GoogleMaps.stop_service_on_start = ConfigYesNo(default = False)
45 config.plugins.GoogleMaps.add_mainmenu_entry = ConfigYesNo(default = True)
46 config.plugins.GoogleMaps.save_last_position = ConfigYesNo(default = True)
47 config.plugins.GoogleMaps.load_map_overlay = ConfigYesNo(default = True)
48 config.plugins.GoogleMaps.cache_enabled = ConfigYesNo(default = False)
49 config.plugins.GoogleMaps.position = ConfigSubsection()
50 config.plugins.GoogleMaps.position.x = ConfigInteger(33)
51 config.plugins.GoogleMaps.position.y = ConfigInteger(21)
52 config.plugins.GoogleMaps.position.z = ConfigInteger(6)
53 config.plugins.GoogleMaps.last_searchkey = ConfigText(default="New York")
54 config.plugins.GoogleMaps.show_preview_on_searchresults = ConfigYesNo(default = True)
55 config.plugins.GoogleMaps.default_zoomlevel_for_searchresults = ConfigInteger(18, (1,99)) #zoomlevel previewpic
56
57 global plugin_path,not_found_pic,not_found_pic_overlay
58 plugin_path = ""
59 not_found_pic = "404.png"
60 not_found_pic_overlay = "404_transparent.png"
61
62 def applySkinVars(skin,dict):
63     for key in dict.keys():
64         try:
65             skin = skin.replace('{'+key+'}',dict[key])
66         except Exception,e:
67             print e,"@key=",key
68     return skin
69
70 def getURL(x,y,z):
71     url = "http://khm1.google.com/kh?v=32&hl=de&x=%i&y=%i&z=%i"%(x,y,z)
72     return url
73    
74 def getMapURL(x,y,z):
75     url = "http://mt1.google.com/mt?v=w2t.86&hl=de&x=%i&y=%i&z=%i&s=G"%(x,y,z)
76     return url   
77
78 def getMaptilesFromLonLat(lon,lat,zoomlevel):
79     # calc map tiles
80     mercator = GlobalMercator()
81     mx, my = mercator.LatLonToMeters( lat, lon )
82     tminx, tminy = mercator.MetersToTile( mx, my, zoomlevel )
83     gx, gy = mercator.GoogleTile(tminx, tminy, zoomlevel)
84     return gx,gy
85
86 class GoogleMapsConfigScreen(ConfigListScreen,Screen):
87     skin = """
88         <screen position="100,100" size="550,400" title="Google Maps Setup" >
89         <widget name="config" position="0,0" size="550,360" scrollbarMode="showOnDemand" />
90         <widget name="buttonred" position="10,360" size="100,40" backgroundColor="red" valign="center" halign="center" zPosition="1"  foregroundColor="white" font="Regular;18"/> 
91         <widget name="buttongreen" position="120,360" size="100,40" backgroundColor="green" valign="center" halign="center" zPosition="1"  foregroundColor="white" font="Regular;18"/> 
92         <widget name="label" position="240,360" size="200,40"  valign="center" halign="center" zPosition="1"  foregroundColor="white" font="Regular;18"/> 
93         </screen>"""
94     def __init__(self, session, args = 0):
95         self.session = session
96         Screen.__init__(self, session)
97         self.list = []
98         self.list.append(getConfigListEntry(_("add Entry to Main Menu"), config.plugins.GoogleMaps.add_mainmenu_entry))
99         self.list.append(getConfigListEntry(_("stop TV Service on Start"), config.plugins.GoogleMaps.stop_service_on_start))
100         self.list.append(getConfigListEntry(_("save last Map Position"), config.plugins.GoogleMaps.save_last_position))
101         self.list.append(getConfigListEntry(_("load Map Overlay"), config.plugins.GoogleMaps.load_map_overlay))
102         self.list.append(getConfigListEntry(_("enable caching of Images in /tmp/"), config.plugins.GoogleMaps.cache_enabled))
103         self.list.append(getConfigListEntry(_("show Preview Image for Searchresults"), config.plugins.GoogleMaps.show_preview_on_searchresults))
104         self.list.append(getConfigListEntry(_("default Zoomlevel for Preview Images"), config.plugins.GoogleMaps.default_zoomlevel_for_searchresults))
105         
106         ConfigListScreen.__init__(self, self.list)
107         self["buttonred"] = Label(_("cancel"))
108         self["buttongreen"] = Label(_("ok"))
109         self["label"] = Label("Author: 3c5x9")
110         self["setupActions"] = ActionMap(["SetupActions"],
111         {
112             "green": self.save,
113             "red": self.cancel,
114             "save": self.save,
115             "cancel": self.cancel,
116             "ok": self.save,
117         }, -2)
118
119     def save(self):
120         print "saving"
121         for x in self["config"].list:
122             x[1].save()
123         self.close(True)
124
125     def cancel(self):
126         print "cancel"
127         for x in self["config"].list:
128             x[1].cancel()
129         self.close(False)
130
131 class GoogleMapsMainScreen(Screen,HelpableScreen):
132     raw_skin =  """
133             <screen position="{screen.position}" size="{screen.size}" title="GoogleMaps" flags="wfNoBorder">
134     <!-- widget  name="pic1b" position="{pixmap1.pos}" size="{pixmap.size}" zPosition="0" alphatest="blend"//-->
135     <widget  name="pic1" position="{pixmap1.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
136     <widget name="pic1o" position="{pixmap1.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
137     <widget name="pic2" position="{pixmap2.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
138     <widget name="pic2o" position="{pixmap2.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
139     <widget name="pic3" position="{pixmap3.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
140     <widget name="pic3o" position="{pixmap3.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
141     <widget name="pic4" position="{pixmap4.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
142     <widget name="pic4o" position="{pixmap4.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
143     <widget name="pic5" position="{pixmap5.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
144     <widget name="pic5o" position="{pixmap5.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
145     <widget name="pic6" position="{pixmap6.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
146     <widget name="pic6o" position="{pixmap6.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
147     <widget name="pic7" position="{pixmap7.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
148     <widget name="pic7o" position="{pixmap7.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
149     <widget name="pic8" position="{pixmap8.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
150     <widget name="pic8o" position="{pixmap8.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
151     <widget name="pic9" position="{pixmap9.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
152     <widget name="pic9o" position="{pixmap9.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
153     
154     <!-- widget name="infopanel" position="{infopanel.pos}" size="{infopanel.size}" zPosition="0"  backgroundColor="blue" //-->
155     <widget name="posx" position="{posx.pos}" size="{posx.size}" font="{font}" zPosition="1" />
156     <widget name="posy" position="{posy.pos}" size="{posy.size}" font="{font}" zPosition="1" />
157     <widget name="posz" position="{posz.pos}" size="{posz.size}" font="{font}" zPosition="1" />
158     <widget name="placeslist" position="{placeslist.pos}" size="{placeslist.size}" zPosition="1"/>
159     <widget name="buttonmenu" position="{buttonmenu.pos}" size="{buttonmenu.size}" font="{font}" halign="center" valign="center"  zPosition="1"/>        
160     <widget name="buttonsearch" position="{buttonsearch.pos}" size="{buttonsearch.size}" font="{font}" halign="center" valign="center"  zPosition="1"  backgroundColor="red"/>        
161     <widget name="buttonhelp" position="{buttonhelp.pos}" size="{buttonhelp.size}" font="{font}" halign="center" valign="center"  zPosition="1"/>
162
163             </screen>
164             """
165     def __init__(self, session):
166         self.session = session
167         size_w = int(getDesktop(0).size().width()*0.9)    
168         size_h = int(getDesktop(0).size().height()*0.9)
169         pos_w = int((getDesktop(0).size().width()-size_w)/2)
170         pos_h = int((getDesktop(0).size().height()-size_h)/2)        
171         p_h = int(size_h/3)
172                 
173         infopanel_width = int(size_w - (p_h*3))
174         infopanel_height = size_h
175         label_height = 30
176         font = "Regular;21"
177         self.dict = {
178                 
179                 'font': font,
180                 
181                 'screen.size': "%i,%i"%(size_w,size_h),
182                 'screen.position': "%i,%i"%(pos_w,pos_h),
183                 'pixmap.size': '%i,%i'%(p_h,p_h),
184                 
185                 'pixmap1.pos': '0,0',
186                 'pixmap2.pos': '%i,0'%(p_h),
187                 'pixmap3.pos': '%i,0'%(int(p_h*2)),
188                 
189                 'pixmap4.pos': '0,%i'%(p_h),
190                 'pixmap5.pos': '%i,%i'%(p_h,p_h),
191                 'pixmap6.pos': '%i,%i'%(int(p_h*2),p_h),
192                 
193                 'pixmap7.pos': '0,%i'%(int(p_h*2)),
194                 'pixmap8.pos': '%i,%i'%(p_h,int(p_h*2)),
195                 'pixmap9.pos': '%i,%i'%(int(p_h*2),int(p_h*2)),
196                 
197                 'infopanel.pos': '%i,0'%(int(p_h*3)),
198                 'infopanel.size': '%i,%i'%(infopanel_width,infopanel_height),
199                 
200                 'posx.pos': '%i,0'%(int(p_h*3)),
201                 'posx.size': '%i,%i'%(infopanel_width,label_height),
202                 
203                 'posy.pos': '%i,%i'%(int(p_h*3),label_height),
204                 'posy.size': '%i,%i'%(infopanel_width,label_height),
205                 
206                 'posz.pos': '%i,%i'%(int(p_h*3),int(label_height*2)),
207                 'posz.size': '%i,%i'%(infopanel_width,label_height),
208                 
209                 'placeslist.pos': '%i,%i'%(int(p_h*3),int(label_height*3)),
210                 'placeslist.size': '%i,%i'%(infopanel_width,int(infopanel_height-(label_height*4))),
211
212                 'buttonmenu.pos': '%i,%i'%(int(p_h*3),int(infopanel_height-(label_height*4)+(label_height*3))),
213                 'buttonmenu.size': '%i,%i'%(int(infopanel_width/3),label_height),
214                 
215                 'buttonsearch.pos': '%i,%i'%(int(p_h*3+(infopanel_width/3)),int(infopanel_height-(label_height*4)+(label_height*3))),
216                 'buttonsearch.size': '%i,%i'%(int(infopanel_width/3),label_height),
217                 
218                 'buttonhelp.pos': '%i,%i'%(int(p_h*3+((infopanel_width/3)*2)),int(infopanel_height-(label_height*4)+(label_height*3))),
219                 'buttonhelp.size': '%i,%i'%(int(infopanel_width/3),label_height),
220                 
221                 }
222         
223         self.skin = applySkinVars(GoogleMapsMainScreen.raw_skin,self.dict)
224         Screen.__init__(self, session)
225         HelpableScreen.__init__(self)
226     
227         #self["infopanel"] = Label()
228         self["posx"] = Label("")
229         self["posy"] = Label("")
230         self["posz"] = Label("")
231         self["placeslist"] = MenuList([])
232         self["buttonmenu"] = Label(_("Menu"))
233         self["buttonsearch"] = Label(_("Search"))
234         self["buttonhelp"] = Label(_("Help"))
235         
236         #self["pic1b"] = WebPixmap(default=plugin_path+not_found_pic)
237         self["pic1"] = WebPixmap(default=plugin_path+not_found_pic)
238         self["pic2"] = WebPixmap(default=plugin_path+not_found_pic)
239         self["pic3"] = WebPixmap(default=plugin_path+not_found_pic)
240         self["pic4"] = WebPixmap(default=plugin_path+not_found_pic)
241         self["pic5"] = WebPixmap(default=plugin_path+not_found_pic)
242         self["pic6"] = WebPixmap(default=plugin_path+not_found_pic)
243         self["pic7"] = WebPixmap(default=plugin_path+not_found_pic)
244         self["pic8"] = WebPixmap(default=plugin_path+not_found_pic)
245         self["pic9"] = WebPixmap(default=plugin_path+not_found_pic)
246         
247         self["pic1o"] = WebPixmap(default=plugin_path+not_found_pic_overlay)
248         self["pic2o"] = WebPixmap(default=plugin_path+not_found_pic_overlay)
249         self["pic3o"] = WebPixmap(default=plugin_path+not_found_pic_overlay)
250         self["pic4o"] = WebPixmap(default=plugin_path+not_found_pic_overlay)
251         self["pic5o"] = WebPixmap(default=plugin_path+not_found_pic_overlay)
252         self["pic6o"] = WebPixmap(default=plugin_path+not_found_pic_overlay)
253         self["pic7o"] = WebPixmap(default=plugin_path+not_found_pic_overlay)
254         self["pic8o"] = WebPixmap(default=plugin_path+not_found_pic_overlay)
255         self["pic9o"] = WebPixmap(default=plugin_path+not_found_pic_overlay)
256         
257         self["actionmap"] = ActionMap(["OkCancelActions", "NumberActions","DirectionActions","MenuActions","ColorActions","InfobarChannelSelection"],
258             {
259              "cancel": self.close,
260              "ok": self.keyOk,
261              "1": self.key1,
262              "2": self.key2,
263              "3": self.key3,
264              "4": self.key4,
265              "5": self.key5,
266              "6": self.key6,
267              "7": self.key7,
268              "8": self.key8,
269              "9": self.key9,
270              "0": self.key0,
271              "red": self.openSearchScreen,
272              "menu": self.keymenu,
273              "historyNext": self.toggleMapOverlay,
274              
275              }, -1)
276         
277         self.helpList.append((self["actionmap"], "OkCancelActions", [("cancel", _("quit Google Maps"))]))
278         self.helpList.append((self["actionmap"], "DirectionActions", [("up", _("navigate thru Placemarks"))]))
279         self.helpList.append((self["actionmap"], "DirectionActions", [("down", _("navigate thru Placemarks"))]))
280         self.helpList.append((self["actionmap"], "DirectionActions", [("left", _("navigate thru Placemarks"))]))
281         self.helpList.append((self["actionmap"], "DirectionActions", [("right", _("navigate thru Placemarks"))]))
282         self.helpList.append((self["actionmap"], "OkCancelActions", [("ok", _("show selected Placemark"))]))
283         self.helpList.append((self["actionmap"], "NumberActions", [("1",'move north-west')]))
284         self.helpList.append((self["actionmap"], "NumberActions", [("2",'move north')]))
285         self.helpList.append((self["actionmap"], "NumberActions", [("3",'move north-east')]))
286         self.helpList.append((self["actionmap"], "NumberActions", [("4",'move west')]))
287         self.helpList.append((self["actionmap"], "NumberActions", [("6",'move east')]))
288         self.helpList.append((self["actionmap"], "NumberActions", [("7",'move south-west')]))
289         self.helpList.append((self["actionmap"], "NumberActions", [("8",'move south')]))
290         self.helpList.append((self["actionmap"], "NumberActions", [("9",'move south-east')]))
291         self.helpList.append((self["actionmap"], "NumberActions", [("5",'zoom in')]))
292         self.helpList.append((self["actionmap"], "NumberActions", [("0",'zoom out')]))
293         self.helpList.append((self["actionmap"], "ColorActions", [("red",'open Search Screen')]))
294         self.helpList.append((self["actionmap"], "InfobarChannelSelection", [("historyNext",'show/unshow Map Overlay')]))
295         
296         self.onLayoutFinish.append(self.onLayoutFinished)
297
298     def getRandomNumber(self):
299         """ returning a real random number """
300         return 4 # fairly choosen by using a dice
301     
302     def openSearchScreen(self):
303         self.session.openWithCallback(self.searchCB,GoogleMapsGeoSearchScreen)
304     
305     def searchCB(self,result,adress,x,y,zoomlevel):
306         if result:
307             self.setNewXYZ(x,y,zoomlevel)
308             
309     def buildMenuRoot(self):
310         list = []
311         root = RootFolder()
312         for i in root.getFiles("/usr/lib/enigma2/python/Plugins/Extensions/GoogleMaps/"):
313             l = lambda name,filepath: self.openFolderRoot(name,filepath)
314             list.append((i[0],i[1],l))
315         self["placeslist"].setList(list)
316
317     def openFolderRoot(self,name,filepath):
318         print "openFolderRoot",name,filepath
319         root = RootFolder()
320         folderx = root.getFolderFromFile(filepath)
321         list = []
322         l = lambda name,filepath: self.buildMenuRoot()
323         list.append(("..",filepath,l))
324         for folderx in folderx.getFolders():
325             l = lambda name,folder: self.openFolder(name,folder)
326             list.append(("+ "+folderx.name,folderx,l))
327         
328         for placex in folderx.getPlacemarks():
329             l = lambda name,place: self.showPlace(name,place)
330             list.append((""+placex.name,placex,l))
331         
332         self["placeslist"].setList(list)
333     
334     def openFolder(self,name,foldery):
335         print  "open Folder",name,foldery
336         list = []
337         if foldery.parent is None:
338             l = lambda name,folder: self.buildMenuRoot()
339             list.append(("..",None,l))
340         else:
341             l = lambda name,folder: self.openFolder(name,folder)
342             list.append(("..",foldery.parent,l))
343             
344         for folderx in foldery.getFolders():
345             l = lambda name,folder: self.openFolder(name,folder)
346             list.append(("+ "+folderx.name,folderx,l))
347         
348         for placex in foldery.getPlacemarks():
349             l = lambda name,place: self.showPlace(name,place)
350             list.append((""+placex.name,placex,l))
351         
352         self["placeslist"].setList(list)
353        
354     def showPlace(self,name,place):
355         #print "show Place",name,place 
356         x,y,z = place.getTile(self.z)
357         self.setNewXYZ(x,y,z)  
358     
359     def onLayoutFinished(self):  
360         self.buildMenuRoot()
361         self.setNewXYZ(config.plugins.GoogleMaps.position.x.value,
362                        config.plugins.GoogleMaps.position.y.value,
363                        config.plugins.GoogleMaps.position.z.value)
364         
365     #################
366     def toggleMapOverlay(self):
367         if config.plugins.GoogleMaps.load_map_overlay.value is True:
368             config.plugins.GoogleMaps.load_map_overlay.value = False
369         else:
370             config.plugins.GoogleMaps.load_map_overlay.value = True
371         self.setNewXYZ(config.plugins.GoogleMaps.position.x.value,
372                        config.plugins.GoogleMaps.position.y.value,
373                        config.plugins.GoogleMaps.position.z.value)
374         
375     def keymenu(self):
376         self.session.openWithCallback(self.menuCB,GoogleMapsConfigScreen)
377     
378     def menuCB(self,dummy):
379         self.setNewXYZ(config.plugins.GoogleMaps.position.x.value,
380                        config.plugins.GoogleMaps.position.y.value,
381                        config.plugins.GoogleMaps.position.z.value)
382         
383     def keyOk(self):
384         listentry = self["placeslist"].getCurrent()
385         if listentry is not None:
386             if listentry[1] is not None:
387                 listentry[2](listentry[0],listentry[1])
388
389     def key1(self):  
390         # northwest
391         self.setNewXYZ(self.x-1,self.y-1,self.z)
392     
393     def key3(self):  
394         # northeast
395         self.setNewXYZ(self.x+1,self.y-1,self.z)
396     
397     def key7(self):  
398         # southwest
399         self.setNewXYZ(self.x-1,self.y+1,self.z)
400     
401     def key9(self):  
402         # southeast
403         self.setNewXYZ(self.x+1,self.y+1,self.z)
404     
405     #################
406     def key2(self):
407         # north
408         self.setNewXYZ(self.x,self.y-1,self.z)
409         
410     def key8(self):
411         # south
412         self.setNewXYZ(self.x,self.y+1,self.z)
413         
414     def key4(self):
415         # west
416         self.setNewXYZ(self.x-1,self.y,self.z)
417         
418     def key6(self):
419         # east
420         self.setNewXYZ(self.x+1,self.y,self.z)
421         
422     #################
423     def key5(self):
424         #zoom in
425         self.setNewXYZ(self.x*2,self.y*2+1,self.z+1)        
426     
427     def key0(self):
428         #zoom out
429         self.setNewXYZ(self.x/2,self.y/2,self.z-1)        
430        
431     #################
432     def setNewXYZ(self,x,y,z):
433         print x,y,z
434         if z<0 or z>=30:
435             return
436         self.x = x
437         self.y = y
438         self.z = z
439         if config.plugins.GoogleMaps.save_last_position.value:
440             config.plugins.GoogleMaps.position.x.value = x    
441             config.plugins.GoogleMaps.position.y.value = y 
442             config.plugins.GoogleMaps.position.z.value = z 
443         
444         self["posx"].setText(_('Pos.')+" X: "+str(x))
445         self["posy"].setText(_('Pos.')+" Y: "+str(y))
446         self["posz"].setText(_('Zoom')+" : "+str(z))
447         
448         self["pic1"].load(getURL(x-1,y-1,z))
449         self["pic2"].load(getURL(x,y-1,z))
450         self["pic3"].load(getURL(x+1,y-1,z))
451         self["pic4"].load(getURL(x-1,y,z))
452         self["pic5"].load(getURL(x,y,z))
453         self["pic6"].load(getURL(x+1,y,z))
454         self["pic7"].load(getURL(x-1,y+1,z))
455         self["pic8"].load(getURL(x,y+1,z))
456         self["pic9"].load(getURL(x+1,y+1,z))
457
458         if config.plugins.GoogleMaps.load_map_overlay.value:
459             self["pic1o"].show()
460             self["pic2o"].show()
461             self["pic3o"].show()
462             self["pic4o"].show()
463             self["pic5o"].show()
464             self["pic6o"].show()
465             self["pic7o"].show()
466             self["pic8o"].show()
467             self["pic9o"].show()
468             self["pic1o"].load(getMapURL(x-1,y-1,z))
469             self["pic2o"].load(getMapURL(x,y-1,z))
470             self["pic3o"].load(getMapURL(x+1,y-1,z))
471             self["pic4o"].load(getMapURL(x-1,y,z))
472             self["pic5o"].load(getMapURL(x,y,z))
473             self["pic6o"].load(getMapURL(x+1,y,z))
474             self["pic7o"].load(getMapURL(x-1,y+1,z))
475             self["pic8o"].load(getMapURL(x,y+1,z))
476             self["pic9o"].load(getMapURL(x+1,y+1,z))
477         else:
478             self["pic1o"].hide()
479             self["pic2o"].hide()
480             self["pic3o"].hide()
481             self["pic4o"].hide()
482             self["pic5o"].hide()
483             self["pic6o"].hide()
484             self["pic7o"].hide()
485             self["pic8o"].hide()
486             self["pic9o"].hide()
487
488         
489 ##################################
490
491 class GoogleMapsGeoSearchScreen(InputBox):
492     raw_skin =  """
493             <screen position="{screen.position}" size="{screen.size}" title="GoogleMaps Search" flags="wfNoBorder">
494                 <widget name="text" position="{text.position}" size="{text.size}" font="Regular;23"/>
495                 <widget name="input" position="{input.position}" size="{input.size}" font="Regular;23"/>
496                 <widget name="list" position="{list.position}" size="{list.size}" />
497                 <widget name="infotext" position="{infotext.position}" size="{infotext.size}"   font="Regular;20"/>
498                 
499                 <widget name="preview" position="{preview.position}" size="{preview.size}"  zPosition="1" alphatest="blend"/>
500                 <widget name="previewo" position="{preview.position}" size="{preview.size}"  zPosition="2" alphatest="blend"/>
501             </screen>
502             """
503     def __init__(self,session):
504         self.session = session
505         screen_size_w = int(getDesktop(0).size().width()*0.9)    
506         screen_size_h = int(getDesktop(0).size().height()*0.9)
507         screen_pos_w = int((getDesktop(0).size().width()-screen_size_w)/2)
508         screen_pos_h = int((getDesktop(0).size().height()-screen_size_h)/2)
509         
510         label_height = 30
511         offset = 5
512         
513         list_h = int(screen_size_h-(label_height*3)-(offset*5))
514         list_w = int((screen_size_w/2)-offset)
515         list_pos_x = offset
516         list_pos_y = int((offset*3)+(label_height*2))
517                 
518         font = "Regular;21"
519         skindict = {
520                 
521                 'font': font,
522                 
523                 'screen.size': "%i,%i"%(screen_size_w,screen_size_h),
524                 'screen.position': "%i,%i"%(screen_pos_w,screen_pos_h),
525                 
526                 'text.position': "%i,%i"%(offset,offset),
527                 'text.size': "%i,%i"%(list_w-offset,label_height),
528                 
529                 'input.position': "%i,%i"%(offset,(offset*2)+label_height),
530                 'input.size': "%i,%i"%(list_w-offset,label_height),
531                 
532                 'list.position': "%i,%i"%(list_pos_x,list_pos_y),
533                 'list.size': "%i,%i"%(list_w-offset,list_h),
534                 
535                 "infotext.position": "%i,%i"%(offset,list_pos_y+list_h+offset),
536                 "infotext.size": "%i,%i"%(int(screen_size_w-(offset*2)),label_height),
537                 
538                 'preview.position': "%i,%i"%(offset+list_w,offset),
539                 'preview.size': "%i,%i"%(list_w-offset,screen_size_h-(offset*3)-label_height),
540                 
541                 }
542         
543         self.skin = applySkinVars(GoogleMapsGeoSearchScreen.raw_skin,skindict)
544         
545         self["list"] = MenuList([])
546         self["list"].onSelectionChanged.append(self.onListSelectionChanged)
547         self["preview"] = WebPixmap(default=plugin_path+not_found_pic)
548         self["previewo"] = WebPixmap(default=plugin_path+not_found_pic_overlay)
549         self["infotext"] = Label("")
550                 
551         InputBox.__init__(self,session, title = "Please enter a City or Locationname:", windowTitle = _("GoogleMaps Search"),text=config.plugins.GoogleMaps.last_searchkey.value)
552         self.onLayoutFinish.append(self.onLayoutFinished)
553         
554         self.do_preview_timer = eTimer()
555         self.do_search_timer = eTimer()
556
557     def onLayoutFinished(self):
558         self.doSearch(self["input"].getText())    
559     
560     def onListSelectionChanged(self):
561         listitem = self["list"].getCurrent()
562         self.do_preview_timer.stop()
563         if listitem:
564             #print "list changed",listitem
565             adress,lon,lat = listitem[1]
566             for i in self.do_preview_timer.timeout.get():
567                 self.do_preview_timer.timeout.get().remove(i)
568             self.do_preview_timer.timeout.get().append(lambda : self.loadPreview(lon, lat))
569             self.do_preview_timer.start(1500)
570         else:
571             pass #print "nothing selected"
572     
573     def loadPreview(self,lon,lat):
574         self.do_preview_timer.stop()
575         if config.plugins.GoogleMaps.show_preview_on_searchresults.value:
576             zoomlevel = config.plugins.GoogleMaps.default_zoomlevel_for_searchresults.value
577             gx,gy = getMaptilesFromLonLat(lon,lat,zoomlevel)
578             self["preview"].load(getURL(gx, gy, zoomlevel))
579             self["previewo"].load(getMapURL(gx, gy, zoomlevel))    
580
581     def keyNumberGlobal(self, number):
582         self["input"].number(number)
583         self.do_search_timer.stop()
584         for i in self.do_search_timer.timeout.get():
585             self.do_search_timer.timeout.get().remove(i)
586         self.do_search_timer.timeout.get().append(lambda : self.doSearch(self["input"].getText()))
587         self.do_search_timer.start(1000)
588
589         #self.doSearch(self["input"].getText())
590     
591     def go(self):
592         # overwritten from InputBox
593         listitem = self["list"].getCurrent()
594         if listitem:
595             adress,lon,lat = listitem[1]
596             zoomlevel = config.plugins.GoogleMaps.default_zoomlevel_for_searchresults.value
597             gx,gy = getMaptilesFromLonLat(lon,lat,zoomlevel)
598             self.close(True,adress,gx,gy,zoomlevel)
599     
600     def cancel(self):
601         # overwritten from InputBox
602         rcinput = eRCInput.getInstance()
603         rcinput.setKeyboardMode(rcinput.kmNone)
604         self.do_preview_timer.stop()
605         self.do_search_timer.stop()
606         self.close(False,False,False,False,False)
607             
608     def doSearch(self,searchkey):
609         self.do_search_timer.stop()
610         config.plugins.GoogleMaps.last_searchkey.value = searchkey
611         self["infotext"].setText("searching with '%s' ..."%(searchkey))
612         s = urllib.quote(searchkey)
613         url = "http://maps.google.com/maps/geo?q=%s&output=xml&key=abcdefg&oe=utf8"%s
614         cb = lambda result: self.onLoadFinished(searchkey,result) 
615         getPage(url).addCallback(cb).addErrback(self.onLoadFailed)
616     
617     def onLoadFinished(self,searchkey,result):
618         xmldoc = parseString(result)
619         list = []
620         for i in xmldoc.getElementsByTagName('Placemark'):
621             adress = i.getElementsByTagName('address')[0].firstChild.data.encode('utf-8')
622             lon,lat,unknown = i.getElementsByTagName('coordinates')[0].firstChild.data.encode("utf-8").split(",")
623             list.append((adress,[adress,float(lon),float(lat)]))
624         
625         self["list"].setList(list)
626         
627         if len(list):
628             self["infotext"].setText("found %i Locations with '%s'"%(len(list),searchkey))
629         else:
630             self["infotext"].setText("nothing found with '%s'"%(searchkey))
631     
632     def onLoadFailed(self,reason):
633         print reason
634         self["infotext"].setText(str(reason)) 
635     
636 ##################################
637
638 def start_from_mainmenu(menuid, **kwargs):
639     #starting from main menu
640     if menuid == "mainmenu":
641         return [(_("Google Maps"), start_from_pluginmenu, "googlemaps", 46)]
642     return []
643
644 originalservice = None
645 mysession = None
646
647 def start_from_pluginmenu(session,**kwargs):
648     global originalservice,mysession
649     mysession = session
650     originalservice = session.nav.getCurrentlyPlayingServiceReference()
651     if  config.plugins.GoogleMaps.stop_service_on_start.value:
652         session.nav.stopService()
653     session.openWithCallback(mainCB,GoogleMapsMainScreen)    
654
655 def mainCB():
656     global originalservice,mysession
657     mysession.nav.playService(originalservice)
658     config.plugins.GoogleMaps.position.x.save()    
659     config.plugins.GoogleMaps.position.y.save()    
660     config.plugins.GoogleMaps.position.z.save()    
661     
662 def Plugins(path,**kwargs):
663     global plugin_path
664     plugin_path = path+"/"
665     pname = "Google Maps"
666     pdesc = "browse google maps"
667     desc_mainmenu  = PluginDescriptor(name=pname, description=pdesc,  where = PluginDescriptor.WHERE_MENU, fnc = start_from_mainmenu)
668     desc_pluginmenu = PluginDescriptor(name=pname, description=pdesc,  where = PluginDescriptor.WHERE_PLUGINMENU, fnc = start_from_pluginmenu, icon="plugin.png")
669     list = []
670     list.append(desc_pluginmenu)
671     if config.plugins.GoogleMaps.add_mainmenu_entry.value:
672         list.append(desc_mainmenu)
673     return list
674
675
676