force all results of skin calculations to integers
[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 from enigma import getDesktop,eSize
24 from Plugins.Plugin import PluginDescriptor
25 from Screens.Screen import Screen
26 from Screens.HelpMenu import HelpableScreen
27 from Components.ActionMap import ActionMap
28 from Components.Label import Label
29 from Components.MenuList import MenuList
30 from Components.config import config, ConfigSubList, ConfigSubsection, ConfigInteger, ConfigYesNo, ConfigText, getConfigListEntry
31 from Components.ConfigList import ConfigListScreen
32
33 from Plugins.Extensions.GoogleMaps.KMLlib import RootFolder,KmlFolder,KmlPlace
34 from Plugins.Extensions.GoogleMaps.WebPixmap import WebPixmap
35
36 config.plugins.GoogleMaps = ConfigSubsection()
37 config.plugins.GoogleMaps.add_mainmenu_entry = ConfigYesNo(default = True)
38 config.plugins.GoogleMaps.save_last_position = ConfigYesNo(default = True)
39 config.plugins.GoogleMaps.load_map_overlay = ConfigYesNo(default = True)
40 config.plugins.GoogleMaps.cache_enabled = ConfigYesNo(default = False)
41 config.plugins.GoogleMaps.position = ConfigSubsection()
42 config.plugins.GoogleMaps.position.x = ConfigInteger(33)
43 config.plugins.GoogleMaps.position.y = ConfigInteger(21)
44 config.plugins.GoogleMaps.position.z = ConfigInteger(6)
45
46
47 def applySkinVars(skin,dict):
48     for key in dict.keys():
49         try:
50             skin = skin.replace('{'+key+'}',dict[key])
51         except Exception,e:
52             print e,"@key=",key
53     return skin
54
55 class GoogleMapsConfigScreen(ConfigListScreen,Screen):
56     skin = """
57         <screen position="100,100" size="550,400" title="Google Maps Setup" >
58         <widget name="config" position="0,0" size="550,360" scrollbarMode="showOnDemand" />
59         <widget name="buttonred" position="10,360" size="100,40" backgroundColor="red" valign="center" halign="center" zPosition="1"  foregroundColor="white" font="Regular;18"/> 
60         <widget name="buttongreen" position="120,360" size="100,40" backgroundColor="green" valign="center" halign="center" zPosition="1"  foregroundColor="white" font="Regular;18"/> 
61         <widget name="label" position="240,360" size="200,40"  valign="center" halign="center" zPosition="1"  foregroundColor="white" font="Regular;18"/> 
62         </screen>"""
63     def __init__(self, session, args = 0):
64         self.session = session
65         Screen.__init__(self, session)
66         self.list = []
67         self.list.append(getConfigListEntry(_("add Entry to Main Menu"), config.plugins.GoogleMaps.add_mainmenu_entry))
68         self.list.append(getConfigListEntry(_("save last Map Position"), config.plugins.GoogleMaps.save_last_position))
69         self.list.append(getConfigListEntry(_("load Map Overlay"), config.plugins.GoogleMaps.load_map_overlay))
70         self.list.append(getConfigListEntry(_("enable caching of Images in /tmp/"), config.plugins.GoogleMaps.cache_enabled))
71         
72         ConfigListScreen.__init__(self, self.list)
73         self["buttonred"] = Label(_("cancel"))
74         self["buttongreen"] = Label(_("ok"))
75         self["label"] = Label("Author: 3c5x9")
76         self["setupActions"] = ActionMap(["SetupActions"],
77         {
78             "green": self.save,
79             "red": self.cancel,
80             "save": self.save,
81             "cancel": self.cancel,
82             "ok": self.save,
83         }, -2)
84
85     def save(self):
86         print "saving"
87         for x in self["config"].list:
88             x[1].save()
89         self.close(True)
90
91     def cancel(self):
92         print "cancel"
93         for x in self["config"].list:
94             x[1].cancel()
95         self.close(False)
96
97 class GoogleMapsMainScreen(Screen,HelpableScreen):
98     raw_skin =  """
99             <screen position="{screen.position}" size="{screen.size}" title="GoogleMaps" flags="wfNoBorder">
100     <widget  name="pic1b" position="{pixmap1.pos}" size="{pixmap.size}" zPosition="0" alphatest="blend"/>
101     <widget  name="pic1" position="{pixmap1.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
102     <widget name="pic1o" position="{pixmap1.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
103     <widget name="pic2" position="{pixmap2.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
104     <widget name="pic2o" position="{pixmap2.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
105     <widget name="pic3" position="{pixmap3.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
106     <widget name="pic3o" position="{pixmap3.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
107     <widget name="pic4" position="{pixmap4.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
108     <widget name="pic4o" position="{pixmap4.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
109     <widget name="pic5" position="{pixmap5.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
110     <widget name="pic5o" position="{pixmap5.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
111     <widget name="pic6" position="{pixmap6.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
112     <widget name="pic6o" position="{pixmap6.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
113     <widget name="pic7" position="{pixmap7.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
114     <widget name="pic7o" position="{pixmap7.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
115     <widget name="pic8" position="{pixmap8.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
116     <widget name="pic8o" position="{pixmap8.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
117     <widget name="pic9" position="{pixmap9.pos}" size="{pixmap.size}" zPosition="1" alphatest="blend"/>
118     <widget name="pic9o" position="{pixmap9.pos}" size="{pixmap.size}" zPosition="2" alphatest="blend"/>
119     
120     <widget name="infopanel" position="{infopanel.pos}" size="{infopanel.size}" zPosition="0"  backgroundColor="blue"/>
121     <widget name="posx" position="{posx.pos}" size="{posx.size}" font="{font}" zPosition="1" />
122     <widget name="posy" position="{posy.pos}" size="{posy.size}" font="{font}" zPosition="1" />
123     <widget name="posz" position="{posz.pos}" size="{posz.size}" font="{font}" zPosition="1" />
124     <widget name="placeslist" position="{placeslist.pos}" size="{placeslist.size}" zPosition="1"/>
125     <widget name="buttonmenu" position="{buttonmenu.pos}" size="{buttonmenu.size}" font="{font}" halign="center" valign="center"  zPosition="1"/>        
126     <widget name="buttonhelp" position="{buttonhelp.pos}" size="{buttonhelp.size}" font="{font}" halign="center" valign="center"  zPosition="1"/>
127
128             </screen>
129             """
130     def __init__(self, session):
131         self.session = session
132         size_w = int(getDesktop(0).size().width()*0.9)    
133         size_h = int(getDesktop(0).size().height()*0.9)
134         pos_w = int((getDesktop(0).size().width()-size_w)/2)
135         pos_h = int((getDesktop(0).size().height()-size_h)/2)        
136         p_h = int(size_h/3)
137                 
138         infopanel_width = int(size_w - (p_h*3))
139         infopanel_height = size_h
140         label_height = 30
141         font = "Regular;21"
142         self.dict = {
143                 
144                 'font': font,
145                 
146                 'screen.size': "%i,%i"%(size_w,size_h),
147                 'screen.position': "%i,%i"%(pos_w,pos_h),
148                 'pixmap.size': '%i,%i'%(p_h,p_h),
149                 
150                 'pixmap1.pos': '0,0',
151                 'pixmap2.pos': '%i,0'%(p_h),
152                 'pixmap3.pos': '%i,0'%(int(p_h*2)),
153                 
154                 'pixmap4.pos': '0,%i'%(p_h),
155                 'pixmap5.pos': '%i,%i'%(p_h,p_h),
156                 'pixmap6.pos': '%i,%i'%(int(p_h*2),p_h),
157                 
158                 'pixmap7.pos': '0,%i'%(int(p_h*2)),
159                 'pixmap8.pos': '%i,%i'%(p_h,int(p_h*2)),
160                 'pixmap9.pos': '%i,%i'%(int(p_h*2),int(p_h*2)),
161                 
162                 'infopanel.pos': '%i,0'%(int(p_h*3)),
163                 'infopanel.size': '%i,%i'%(infopanel_width,infopanel_height),
164                 
165                 'posx.pos': '%i,0'%(int(p_h*3)),
166                 'posx.size': '%i,%i'%(infopanel_width,label_height),
167                 
168                 'posy.pos': '%i,%i'%(int(p_h*3),label_height),
169                 'posy.size': '%i,%i'%(infopanel_width,label_height),
170                 
171                 'posz.pos': '%i,%i'%(int(p_h*3),int(label_height*2)),
172                 'posz.size': '%i,%i'%(infopanel_width,label_height),
173                 
174                 'placeslist.pos': '%i,%i'%(int(p_h*3),int(label_height*3)),
175                 'placeslist.size': '%i,%i'%(infopanel_width,int(infopanel_height-(label_height*4))),
176
177                 'buttonmenu.pos': '%i,%i'%(int(p_h*3),int(infopanel_height-(label_height*4)+(label_height*3))),
178                 'buttonmenu.size': '%i,%i'%(int(infopanel_width/2),label_height),
179                 
180                 'buttonhelp.pos': '%i,%i'%(int(p_h*3+(infopanel_width/2)),int(infopanel_height-(label_height*4)+(label_height*3))),
181                 'buttonhelp.size': '%i,%i'%(int(infopanel_width/2),label_height),
182                 
183                 }
184         
185         self.skin = applySkinVars(GoogleMapsMainScreen.raw_skin,self.dict)
186         Screen.__init__(self, session)
187         HelpableScreen.__init__(self)
188     
189         self["infopanel"] = Label()
190         self["posx"] = Label("")
191         self["posy"] = Label("")
192         self["posz"] = Label("")
193         self["placeslist"] = MenuList([])
194         self["buttonmenu"] = Label(_("Menu"))
195         self["buttonhelp"] = Label(_("Help"))
196         
197         self["pic1b"] = WebPixmap()
198         self["pic1"] = WebPixmap()
199         self["pic2"] = WebPixmap()
200         self["pic3"] = WebPixmap()
201         self["pic4"] = WebPixmap()
202         self["pic5"] = WebPixmap()
203         self["pic6"] = WebPixmap()
204         self["pic7"] = WebPixmap()
205         self["pic8"] = WebPixmap()
206         self["pic9"] = WebPixmap()
207         
208         self["pic1o"] = WebPixmap()
209         self["pic2o"] = WebPixmap()
210         self["pic3o"] = WebPixmap()
211         self["pic4o"] = WebPixmap()
212         self["pic5o"] = WebPixmap()
213         self["pic6o"] = WebPixmap()
214         self["pic7o"] = WebPixmap()
215         self["pic8o"] = WebPixmap()
216         self["pic9o"] = WebPixmap()
217         
218         self["actionmap"] = ActionMap(["OkCancelActions", "NumberActions","DirectionActions","MenuActions","InfobarChannelSelection"],
219             {
220              "cancel": self.close,
221              "ok": self.keyOk,
222              "1": self.key1,
223              "2": self.key2,
224              "3": self.key3,
225              "4": self.key4,
226              "5": self.key5,
227              "6": self.key6,
228              "7": self.key7,
229              "8": self.key8,
230              "9": self.key9,
231              "0": self.key0,
232              "menu": self.keymenu,
233              "historyNext": self.toggleMapOverlay,
234              
235              }, -1)
236         
237         self.helpList.append((self["actionmap"], "OkCancelActions", [("cancel", _("quit Google Maps"))]))
238         self.helpList.append((self["actionmap"], "DirectionActions", [("up", _("navigate thru Placemarks"))]))
239         self.helpList.append((self["actionmap"], "DirectionActions", [("down", _("navigate thru Placemarks"))]))
240         self.helpList.append((self["actionmap"], "DirectionActions", [("left", _("navigate thru Placemarks"))]))
241         self.helpList.append((self["actionmap"], "DirectionActions", [("right", _("navigate thru Placemarks"))]))
242         self.helpList.append((self["actionmap"], "OkCancelActions", [("ok", _("show selected Placemark"))]))
243         self.helpList.append((self["actionmap"], "NumberActions", [("1",'move north-west')]))
244         self.helpList.append((self["actionmap"], "NumberActions", [("2",'move north')]))
245         self.helpList.append((self["actionmap"], "NumberActions", [("3",'move north-east')]))
246         self.helpList.append((self["actionmap"], "NumberActions", [("4",'move west')]))
247         self.helpList.append((self["actionmap"], "NumberActions", [("6",'move east')]))
248         self.helpList.append((self["actionmap"], "NumberActions", [("7",'move south-west')]))
249         self.helpList.append((self["actionmap"], "NumberActions", [("8",'move south')]))
250         self.helpList.append((self["actionmap"], "NumberActions", [("9",'move south-east')]))
251         self.helpList.append((self["actionmap"], "NumberActions", [("5",'zoom in')]))
252         self.helpList.append((self["actionmap"], "NumberActions", [("0",'zoom out')]))
253         self.helpList.append((self["actionmap"], "InfobarChannelSelection", [("historyNext",'show/unshow Map Overlay')]))
254         
255         self.onLayoutFinish.append(self.onLayoutFinished)
256
257     def getRandomNumber(self):
258         """ returning a real random number """
259         return 4 # fairly choosen by using a dice
260     
261     def buildMenuRoot(self):
262         list = []
263         root = RootFolder()
264         for i in root.getFiles("/usr/lib/enigma2/python/Plugins/Extensions/GoogleMaps/"):
265             l = lambda name,filepath: self.openFolderRoot(name,filepath)
266             list.append((i[0],i[1],l))
267         self["placeslist"].setList(list)
268
269     def openFolderRoot(self,name,filepath):
270         print "openFolderRoot",name,filepath
271         root = RootFolder()
272         folderx = root.getFolderFromFile(filepath)
273         list = []
274         l = lambda name,filepath: self.buildMenuRoot()
275         list.append(("..",filepath,l))
276         for folderx in folderx.getFolders():
277             l = lambda name,folder: self.openFolder(name,folder)
278             list.append(("+ "+folderx.name,folderx,l))
279         
280         for placex in folderx.getPlacemarks():
281             l = lambda name,place: self.showPlace(name,place)
282             list.append((""+placex.name,placex,l))
283         
284         self["placeslist"].setList(list)
285     
286     def openFolder(self,name,foldery):
287         print  "open Folder",name,foldery
288         list = []
289         if foldery.parent is None:
290             l = lambda name,folder: self.buildMenuRoot()
291             list.append(("..",None,l))
292         else:
293             l = lambda name,folder: self.openFolder(name,folder)
294             list.append(("..",foldery.parent,l))
295             
296         for folderx in foldery.getFolders():
297             l = lambda name,folder: self.openFolder(name,folder)
298             list.append(("+ "+folderx.name,folderx,l))
299         
300         for placex in foldery.getPlacemarks():
301             l = lambda name,place: self.showPlace(name,place)
302             list.append((""+placex.name,placex,l))
303         
304         self["placeslist"].setList(list)
305        
306     def showPlace(self,name,place):
307         #print "show Place",name,place 
308         x,y,z = place.getTile(self.z)
309         self.setNewXYZ(x,y,z)  
310     
311     def onLayoutFinished(self):  
312         self.buildMenuRoot()
313         self.setNewXYZ(config.plugins.GoogleMaps.position.x.value,
314                        config.plugins.GoogleMaps.position.y.value,
315                        config.plugins.GoogleMaps.position.z.value)
316         
317     #################
318     def toggleMapOverlay(self):
319         if config.plugins.GoogleMaps.load_map_overlay.value is True:
320             config.plugins.GoogleMaps.load_map_overlay.value = False
321         else:
322             config.plugins.GoogleMaps.load_map_overlay.value = True
323         self.setNewXYZ(config.plugins.GoogleMaps.position.x.value,
324                        config.plugins.GoogleMaps.position.y.value,
325                        config.plugins.GoogleMaps.position.z.value)
326         
327     def keymenu(self):
328         self.session.openWithCallback(self.menuCB,GoogleMapsConfigScreen)
329     
330     def menuCB(self,dummy):
331         self.setNewXYZ(config.plugins.GoogleMaps.position.x.value,
332                        config.plugins.GoogleMaps.position.y.value,
333                        config.plugins.GoogleMaps.position.z.value)
334         
335     def keyOk(self):
336         listentry = self["placeslist"].getCurrent()
337         if listentry is not None:
338             if listentry[1] is not None:
339                 listentry[2](listentry[0],listentry[1])
340
341     def key1(self):  
342         # northwest
343         self.setNewXYZ(self.x-1,self.y-1,self.z)
344     
345     def key3(self):  
346         # northeast
347         self.setNewXYZ(self.x+1,self.y-1,self.z)
348     
349     def key7(self):  
350         # southwest
351         self.setNewXYZ(self.x-1,self.y+1,self.z)
352     
353     def key9(self):  
354         # southeast
355         self.setNewXYZ(self.x+1,self.y+1,self.z)
356     
357     #################
358     def key2(self):
359         # north
360         self.setNewXYZ(self.x,self.y-1,self.z)
361         
362     def key8(self):
363         # south
364         self.setNewXYZ(self.x,self.y+1,self.z)
365         
366     def key4(self):
367         # west
368         self.setNewXYZ(self.x-1,self.y,self.z)
369         
370     def key6(self):
371         # east
372         self.setNewXYZ(self.x+1,self.y,self.z)
373         
374     #################
375     def key5(self):
376         #zoom in
377         self.setNewXYZ(self.x*2,self.y*2+1,self.z+1)        
378     
379     def key0(self):
380         #zoom out
381         self.setNewXYZ(self.x/2,self.y/2,self.z-1)        
382        
383     #################
384     def setNewXYZ(self,x,y,z):
385         print x,y,z
386         if z<0 or z>=30:
387             return
388         self.x = x
389         self.y = y
390         self.z = z
391         if config.plugins.GoogleMaps.save_last_position.value:
392             config.plugins.GoogleMaps.position.x.value = x    
393             config.plugins.GoogleMaps.position.y.value = y 
394             config.plugins.GoogleMaps.position.z.value = z 
395         
396         self["posx"].setText(_('Pos.')+" X: "+str(x))
397         self["posy"].setText(_('Pos.')+" Y: "+str(y))
398         self["posz"].setText(_('Zoom')+" : "+str(z))
399         
400         self["pic1"].load(self.getURL(x-1,y-1,z))
401         self["pic2"].load(self.getURL(x,y-1,z))
402         self["pic3"].load(self.getURL(x+1,y-1,z))
403         self["pic4"].load(self.getURL(x-1,y,z))
404         self["pic5"].load(self.getURL(x,y,z))
405         self["pic6"].load(self.getURL(x+1,y,z))
406         self["pic7"].load(self.getURL(x-1,y+1,z))
407         self["pic8"].load(self.getURL(x,y+1,z))
408         self["pic9"].load(self.getURL(x+1,y+1,z))
409
410         if config.plugins.GoogleMaps.load_map_overlay.value:
411             self["pic1o"].show()
412             self["pic2o"].show()
413             self["pic3o"].show()
414             self["pic4o"].show()
415             self["pic5o"].show()
416             self["pic6o"].show()
417             self["pic7o"].show()
418             self["pic8o"].show()
419             self["pic9o"].show()
420             self["pic1o"].load(self.getMapURL(x-1,y-1,z))
421             self["pic2o"].load(self.getMapURL(x,y-1,z))
422             self["pic3o"].load(self.getMapURL(x+1,y-1,z))
423             self["pic4o"].load(self.getMapURL(x-1,y,z))
424             self["pic5o"].load(self.getMapURL(x,y,z))
425             self["pic6o"].load(self.getMapURL(x+1,y,z))
426             self["pic7o"].load(self.getMapURL(x-1,y+1,z))
427             self["pic8o"].load(self.getMapURL(x,y+1,z))
428             self["pic9o"].load(self.getMapURL(x+1,y+1,z))
429         else:
430             self["pic1o"].hide()
431             self["pic2o"].hide()
432             self["pic3o"].hide()
433             self["pic4o"].hide()
434             self["pic5o"].hide()
435             self["pic6o"].hide()
436             self["pic7o"].hide()
437             self["pic8o"].hide()
438             self["pic9o"].hide()
439
440     def getURL(self,x,y,z):
441         url = "http://khm1.google.com/kh?v=32&hl=de&x=%i&y=%i&z=%i"%(x,y,z)
442         return url
443    
444     def getMapURL(self,x,y,z):
445         url = "http://mt1.google.com/mt?v=w2t.99&hl=de&x=%i&y=%i&z=%i&s=G"%(x,y,z)
446         return url   
447         
448 ##################################
449
450 def start_from_mainmenu(menuid, **kwargs):
451     #starting from main menu
452     if menuid == "mainmenu":
453         return [(_("Google Maps"), start_from_pluginmenu, "googlemaps", 46)]
454     return []
455
456 originalservice = None
457 mysession = None
458
459 def start_from_pluginmenu(session,**kwargs):
460     global originalservice,mysession
461     mysession = session
462     originalservice = session.nav.getCurrentlyPlayingServiceReference()
463     #session.nav.stopService()
464     session.openWithCallback(mainCB,GoogleMapsMainScreen)    
465
466 def mainCB():
467     global originalservice,mysession
468     #mysession.nav.playService(originalservice)
469     config.plugins.GoogleMaps.position.x.save()    
470     config.plugins.GoogleMaps.position.y.save()    
471     config.plugins.GoogleMaps.position.z.save()    
472     
473 def Plugins(path,**kwargs):
474     pname = "Google Maps"
475     pdesc = "browse google maps"
476     desc_mainmenu  = PluginDescriptor(name=pname, description=pdesc,  where = PluginDescriptor.WHERE_MENU, fnc = start_from_mainmenu)
477     desc_pluginmenu = PluginDescriptor(name=pname, description=pdesc,  where = PluginDescriptor.WHERE_PLUGINMENU, fnc = start_from_pluginmenu, icon="plugin.png")
478     list = []
479     list.append(desc_pluginmenu)
480     if config.plugins.GoogleMaps.add_mainmenu_entry.value:
481         list.append(desc_mainmenu)
482     return list
483
484
485