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