remove redundant code
[enigma2.git] / lib / python / Screens / ChannelSelection.py
1 from Screen import Screen
2 from Components.Button import Button
3 from Components.ServiceList import ServiceList
4 from Components.ActionMap import NumberActionMap, ActionMap
5 from Components.MenuList import MenuList
6 from EpgSelection import EPGSelection
7 from enigma import eServiceReference, eEPGCache, eEPGCachePtr, eServiceCenter, eServiceCenterPtr, iMutableServiceListPtr, iStaticServiceInformationPtr, eTimer, eDVBDB
8 from Components.config import config, configElement, ConfigSubsection, configText, currentConfigSelectionElement
9 from Screens.FixedMenu import FixedMenu
10 from Tools.NumericalTextInput import NumericalTextInput
11 from Components.NimManager import nimmanager
12 from Components.ServiceName import ServiceName
13 from Components.Clock import Clock
14 from Components.EventInfo import EventInfo
15 from Components.Input import Input
16 from Screens.InputBox import InputBox
17 from ServiceReference import ServiceReference
18 from re import *
19 from os import remove
20
21 import xml.dom.minidom
22
23 class BouquetSelector(Screen):
24         def __init__(self, session, bouquets, selectedFunc, enableWrapAround=False):
25                 Screen.__init__(self, session)
26
27                 self.selectedFunc=selectedFunc
28
29                 self["actions"] = ActionMap(["OkCancelActions"],
30                         {
31                                 "ok": self.okbuttonClick,
32                                 "cancel": self.cancelClick
33                         })
34                 entrys = [ ]
35                 for x in bouquets:
36                         entrys.append((x[0], x[1]))
37                 self["menu"] = MenuList(entrys, enableWrapAround)
38
39         def getCurrent(self):
40                 cur = self["menu"].getCurrent()
41                 return cur and cur[1]
42
43         def okbuttonClick(self):
44                 self.selectedFunc(self.getCurrent())
45
46         def up(self):
47                 self["menu"].up()
48
49         def down(self):
50                 self["menu"].down()
51
52         def cancelClick(self):
53                 self.close(False)
54
55 class ChannelContextMenu(Screen):
56         def __init__(self, session, csel):
57                 Screen.__init__(self, session)
58                 self.csel = csel
59                 self.bsel = None
60
61                 self["actions"] = ActionMap(["OkCancelActions"],
62                         {
63                                 "ok": self.okbuttonClick,
64                                 "cancel": self.cancelClick
65                         })
66                 menu = [ ]
67
68                 current_root = csel.getRoot()
69                 inBouquetRootList = current_root and current_root.getPath().find('FROM BOUQUET "bouquets.') != -1 #FIXME HACK
70                 inBouquet = csel.getMutableList() is not None
71                 haveBouquets = csel.bouquet_root.getPath().find('FROM BOUQUET "bouquets.') != -1
72
73                 if not csel.bouquet_mark_edit and not csel.movemode:
74                         if not inBouquetRootList:
75                                 if (csel.getCurrentSelection().flags & eServiceReference.flagDirectory) != eServiceReference.flagDirectory:
76                                         if haveBouquets:
77                                                 menu.append((_("add service to bouquet"), self.addServiceToBouquetSelected))
78                                         else:
79                                                 menu.append((_("add service to favourites"), self.addServiceToBouquetSelected))
80                                 elif haveBouquets:
81                                         if not inBouquet and csel.getCurrentSelection().getPath().find("PROVIDERS") == -1:
82                                                 menu.append((_("copy to favourites"), self.copyCurrentToBouquetList))
83                                 if inBouquet:
84                                         menu.append((_("remove service"), self.removeCurrentService))
85                         elif haveBouquets:
86                                 menu.append((_("remove bouquet"), self.removeBouquet))
87
88                 if inBouquet: # current list is editable?
89                         if not csel.bouquet_mark_edit:
90                                 if not csel.movemode:
91                                         menu.append((_("enable move mode"), self.toggleMoveMode))
92                                         menu.append((_("add bouquet..."), self.showBouquetInputBox))
93                                         if not inBouquetRootList:
94                                                 if haveBouquets:
95                                                         menu.append((_("enable bouquet edit"), self.bouquetMarkStart))
96                                                 else:
97                                                         menu.append((_("enable favourite edit"), self.bouquetMarkStart))
98                                 else:
99                                         menu.append((_("disable move mode"), self.toggleMoveMode))
100                         elif not inBouquetRootList:
101                                 if haveBouquets:
102                                         menu.append((_("end bouquet edit"), self.bouquetMarkEnd))
103                                         menu.append((_("abort bouquet edit"), self.bouquetMarkAbort))
104                                 else:
105                                         menu.append((_("end favourites edit"), self.bouquetMarkEnd))
106                                         menu.append((_("abort favourites edit"), self.bouquetMarkAbort))
107
108                 menu.append((_("back"), self.cancelClick))
109                 self["menu"] = MenuList(menu)
110
111         def okbuttonClick(self):
112                 self["menu"].getCurrent()[1]()
113
114         def cancelClick(self):
115                 self.close(False)
116                 
117         def showBouquetInputBox(self):
118                 self.session.openWithCallback(self.bouquetInputCallback, InputBox, title=_("Please enter a name for the new bouquet"), text="bouquetname", maxSize=False, type=Input.TEXT)
119
120         def bouquetInputCallback(self, bouquet):
121                 if bouquet is not None:
122                         self.csel.addBouquet(bouquet, True)
123
124         def addServiceToBouquetSelected(self):
125                 bouquets = self.csel.getBouquetList()
126                 if bouquets is None:
127                         cnt = 0
128                 else:
129                         cnt = len(bouquets)
130                 if cnt > 1: # show bouquet list
131                         self.bsel = self.session.openWithCallback(self.bouquetSelClosed, BouquetSelector, bouquets, self.addCurrentServiceToBouquet)
132                 elif cnt == 1: # add to only one existing bouquet
133                         self.addCurrentServiceToBouquet(bouquets[0][1])
134                 else: #no bouquets in root.. so assume only one favourite list is used
135                         self.addCurrentServiceToBouquet(self.csel.bouquet_root)
136
137         def bouquetSelClosed(self, recursive):
138                 self.bsel = None
139                 if recursive:
140                         self.close(False)
141
142         def copyCurrentToBouquetList(self):
143                 self.csel.copyCurrentToBouquetList()
144                 self.close()
145
146         def removeBouquet(self):
147                 self.csel.removeBouquet()
148                 self.close()
149
150         def addCurrentServiceToBouquet(self, dest):
151                 self.csel.addCurrentServiceToBouquet(dest)
152                 if self.bsel is not None:
153                         self.bsel.close(True)
154                 else:
155                         self.close(True) # close bouquet selection
156
157         def removeCurrentService(self):
158                 self.csel.removeCurrentService()
159                 self.close()
160
161         def toggleMoveMode(self):
162                 self.csel.toggleMoveMode()
163                 self.close()
164
165         def bouquetMarkStart(self):
166                 self.csel.startMarkedEdit()
167                 self.close()
168
169         def bouquetMarkEnd(self):
170                 self.csel.endMarkedEdit(abort=False)
171                 self.close()
172
173         def bouquetMarkAbort(self):
174                 self.csel.endMarkedEdit(abort=True)
175                 self.close()
176
177 class ChannelSelectionEPG:
178         def __init__(self):
179                 self["ChannelSelectEPGActions"] = ActionMap(["ChannelSelectEPGActions"],
180                         {
181                                 "showEPGList": self.showEPGList,
182                         })
183
184         def showEPGList(self):
185                 ref=self.getCurrentSelection()
186                 ptr=eEPGCache.getInstance()
187                 if ptr.startTimeQuery(ref) != -1:
188                         self.session.open(EPGSelection, ref)
189                 else:
190                         print 'no epg for service', ref.toString()
191
192 class ChannelSelectionEdit:
193         def __init__(self):
194                 self.entry_marked = False
195                 self.movemode = False
196                 self.bouquet_mark_edit = False
197                 self.mutableList = None
198                 self.__marked = [ ]
199                 self.saved_title = None
200                 self.saved_root = None
201
202                 class ChannelSelectionEditActionMap(ActionMap):
203                         def __init__(self, csel, contexts = [ ], actions = { }, prio=0):
204                                 ActionMap.__init__(self, contexts, actions, prio)
205                                 self.csel = csel
206
207                         def action(self, contexts, action):
208                                 if action == "cancel":
209                                         self.csel.handleEditCancel()
210                                         return 0 # fall-trough
211                                 elif action == "ok":
212                                         return 0 # fall-trough
213                                 else:
214                                         return ActionMap.action(self, contexts, action)
215
216                 self["ChannelSelectEditActions"] = ChannelSelectionEditActionMap(self, ["ChannelSelectEditActions", "OkCancelActions"],
217                         {
218                                 "contextMenu": self.doContext,
219                         })
220
221         def getMutableList(self, root=eServiceReference()):
222                 if not self.mutableList is None:
223                         return self.mutableList
224                 serviceHandler = eServiceCenter.getInstance()
225                 if not root.valid():
226                         root=self.getRoot()
227                 list = root and serviceHandler.list(root)
228                 if list is not None:
229                         return list.startEdit()
230                 return None
231
232         def buildBouquetID(self, str):
233                 tmp = str.lower()
234                 name = ''
235                 for c in tmp:
236                         if (c >= 'a' and c <= 'z') or (c >= '0' and c <= '9'):
237                                 name += c
238                         else:
239                                 name += '_'
240                 return name
241
242         def addBouquet(self, bName, services, refresh=False):
243                 serviceHandler = eServiceCenter.getInstance()
244                 mutableBouquetList = serviceHandler.list(self.bouquet_root).startEdit()
245                 if mutableBouquetList:
246                         if self.mode == MODE_TV:
247                                 bName += " (TV)"
248                                 str = '1:7:1:0:0:0:0:0:0:0:(type == 1) FROM BOUQUET \"userbouquet.%s.tv\" ORDER BY bouquet'%(self.buildBouquetID(bName))
249                         else:
250                                 bName += " (Radio)"
251                                 str = '1:7:2:0:0:0:0:0:0:0:(type == 2) FROM BOUQUET \"userbouquet.%s.radio\" ORDER BY bouquet'%(self.buildBouquetID(bName))
252                         new_bouquet_ref = eServiceReference(str)
253                         if not mutableBouquetList.addService(new_bouquet_ref):
254                                 self.bouquetNumOffsetCache = { }
255                                 mutableBouquetList.flushChanges()
256                                 eDVBDB.getInstance().reloadBouquets()
257                                 mutableBouquet = serviceHandler.list(new_bouquet_ref).startEdit()
258                                 if mutableBouquet:
259                                         mutableBouquet.setListName(bName)
260                                         if services is not None:
261                                                 for service in services:
262                                                         if mutableBouquet.addService(service):
263                                                                 print "add", service.toString(), "to new bouquet failed"
264                                         mutableBouquet.flushChanges()
265                                         if refresh:
266                                                 self.setRoot(self.getRoot())
267                                 else:
268                                         print "get mutable list for new created bouquet failed"
269                         else:
270                                 print "add", str, "to bouquets failed"
271                 else:
272                         print "bouquetlist is not editable"
273
274         def copyCurrentToBouquetList(self):
275                 provider = ServiceReference(self.getCurrentSelection())
276                 providerName = provider.getServiceName()
277                 serviceHandler = eServiceCenter.getInstance()
278                 services = serviceHandler.list(provider.ref)
279                 self.addBouquet(providerName, services and services.getContent('R', True))
280
281         def removeBouquet(self):
282                 refstr = self.getCurrentSelection().toString()
283                 self.bouquetNumOffsetCache = { }
284                 pos = refstr.find('FROM BOUQUET "')
285                 if pos != -1:
286                         refstr = refstr[pos+14:]
287                         pos = refstr.find('"')
288                         if pos != -1:
289                                 filename = '/etc/enigma2/' + refstr[:pos] # FIXMEEE !!! HARDCODED /etc/enigma2
290                 self.removeCurrentService()
291                 try:
292                         remove(filename)
293                 except OSError:
294                         print "error during remove of", filename
295                 eDVBDB.getInstance().reloadBouquets()
296
297 #  multiple marked entry stuff ( edit mode, later multiepg selection )
298         def startMarkedEdit(self):
299                 self.mutableList = self.getMutableList()
300                 # add all services from the current list to internal marked set in listboxservicecontent
301                 self.clearMarks() # this clears the internal marked set in the listboxservicecontent
302                 self.saved_title = self.instance.getTitle()
303                 pos = self.saved_title.find(')')
304                 new_title = self.saved_title[:pos+1]
305                 if self.bouquet_root.getPath().find('FROM BOUQUET "bouquets.') != -1:
306                         new_title += ' ' + _("[bouquet edit]")
307                 else:
308                         new_title += ' ' + _("[favourite edit]")
309                 self.setTitle(new_title)
310                 self.bouquet_mark_edit = True
311                 self.__marked = self.servicelist.getRootServices()
312                 for x in self.__marked:
313                         self.servicelist.addMarked(eServiceReference(x))
314                 self.savedPath = self.servicePath[:]
315                 self.showAllServices()
316
317         def endMarkedEdit(self, abort):
318                 if not abort and self.mutableList is not None:
319                         self.bouquetNumOffsetCache = { }
320                         new_marked = set(self.servicelist.getMarked())
321                         old_marked = set(self.__marked)
322                         removed = old_marked - new_marked
323                         added = new_marked - old_marked
324                         changed = False
325                         for x in removed:
326                                 changed = True
327                                 self.mutableList.removeService(eServiceReference(x))
328                         for x in added:
329                                 changed = True
330                                 self.mutableList.addService(eServiceReference(x))
331                         if changed:
332                                 self.mutableList.flushChanges()
333                 self.__marked = []
334                 self.clearMarks()
335                 self.bouquet_mark_edit = False
336                 self.mutableList = None
337                 self.setTitle(self.saved_title)
338                 self.saved_title = None
339                 # self.servicePath is just a reference to servicePathTv or Radio...
340                 # so we never ever do use the asignment operator in self.servicePath
341                 del self.servicePath[:] # remove all elements
342                 self.servicePath += self.savedPath # add saved elements
343                 del self.savedPath
344                 self.setRoot(self.servicePath[len(self.servicePath)-1])
345
346         def clearMarks(self):
347                 self.servicelist.clearMarks()
348
349         def doMark(self):
350                 ref = self.servicelist.getCurrent()
351                 if self.servicelist.isMarked(ref):
352                         self.servicelist.removeMarked(ref)
353                 else:
354                         self.servicelist.addMarked(ref)
355
356         def removeCurrentService(self):
357                 ref = self.servicelist.getCurrent()
358                 mutableList = self.getMutableList()
359                 if ref.valid() and mutableList is not None:
360                         if not mutableList.removeService(ref):
361                                 self.bouquetNumOffsetCache = { }
362                                 mutableList.flushChanges() #FIXME dont flush on each single removed service
363                                 self.setRoot(self.getRoot())
364
365         def addCurrentServiceToBouquet(self, dest):
366                 mutableList = self.getMutableList(dest)
367                 if not mutableList is None:
368                         if not mutableList.addService(self.servicelist.getCurrent()):
369                                 self.bouquetNumOffsetCache = { }
370                                 mutableList.flushChanges()
371
372         def toggleMoveMode(self):
373                 if self.movemode:
374                         if self.entry_marked:
375                                 self.toggleMoveMarked() # unmark current entry
376                         self.movemode = False
377                         self.pathChangedDisabled = False # re-enable path change
378                         self.mutableList.flushChanges() # FIXME add check if changes was made
379                         self.mutableList = None
380                         self.setTitle(self.saved_title)
381                         self.saved_title = None
382                         if self.getRoot() == self.bouquet_root:
383                                 self.bouquetNumOffsetCache = { }
384                 else:
385                         self.mutableList = self.getMutableList()
386                         self.movemode = True
387                         self.pathChangedDisabled = True # no path change allowed in movemode
388                         self.saved_title = self.instance.getTitle()
389                         new_title = self.saved_title
390                         pos = self.saved_title.find(')')
391                         new_title = self.saved_title[:pos+1] + ' ' + _("[move mode]") + self.saved_title[pos+1:]
392                         self.setTitle(new_title);
393
394         def handleEditCancel(self):
395                 if self.movemode: #movemode active?
396                         self.channelSelected() # unmark
397                         self.toggleMoveMode() # disable move mode
398                 elif self.bouquet_mark_edit:
399                         self.endMarkedEdit(True) # abort edit mode
400
401         def toggleMoveMarked(self):
402                 if self.entry_marked:
403                         self.servicelist.setCurrentMarked(False)
404                         self.entry_marked = False
405                 else:
406                         self.servicelist.setCurrentMarked(True)
407                         self.entry_marked = True
408
409         def doContext(self):
410                 self.session.open(ChannelContextMenu, self)
411
412 MODE_TV = 0
413 MODE_RADIO = 1
414
415 class ChannelSelectionBase(Screen):
416         def __init__(self, session):
417                 Screen.__init__(self, session)
418
419                 # this makes it much simple to implement a selectable radio or tv mode :)
420                 self.service_types_tv = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 195)'
421                 self.service_types_radio = '1:7:2:0:0:0:0:0:0:0:(type == 2)'
422
423                 self["key_red"] = Button(_("All"))
424                 self["key_green"] = Button(_("Satellites"))
425                 self["key_yellow"] = Button(_("Provider"))
426                 self["key_blue"] = Button(_("Favourites"))
427
428                 self["list"] = ServiceList()
429                 self.servicelist = self["list"]
430
431                 self.numericalTextInput = NumericalTextInput()
432
433                 self.servicePathTV = [ ]
434                 self.servicePathRadio = [ ]
435                 self.servicePath = [ ]
436
437                 self.mode = MODE_TV
438
439                 self.pathChangedDisabled = False
440
441                 self.bouquetNumOffsetCache = { }
442
443                 self["ChannelSelectBaseActions"] = NumberActionMap(["ChannelSelectBaseActions", "NumberActions"],
444                         {
445                                 "showFavourites": self.showFavourites,
446                                 "showAllServices": self.showAllServices,
447                                 "showProviders": self.showProviders,
448                                 "showSatellites": self.showSatellites,
449                                 "nextBouquet": self.nextBouquet,
450                                 "prevBouquet": self.prevBouquet,
451                                 "1": self.keyNumberGlobal,
452                                 "2": self.keyNumberGlobal,
453                                 "3": self.keyNumberGlobal,
454                                 "4": self.keyNumberGlobal,
455                                 "5": self.keyNumberGlobal,
456                                 "6": self.keyNumberGlobal,
457                                 "7": self.keyNumberGlobal,
458                                 "8": self.keyNumberGlobal,
459                                 "9": self.keyNumberGlobal,
460                                 "0": self.keyNumber0
461                         })
462
463         def appendDVBTypes(self, ref):
464                 path = ref.getPath()
465                 pos = path.find(' FROM BOUQUET')
466                 if pos != -1:
467                         return eServiceReference(self.service_types + path[pos:])
468                 return ref
469
470         def getBouquetNumOffset(self, bouquet):
471                 if self.bouquet_root.getPath().find('FROM BOUQUET "bouquets.') == -1: #FIXME HACK
472                         return 0
473                 bouquet = self.appendDVBTypes(bouquet)
474                 try:
475                         return self.bouquetNumOffsetCache[bouquet.toString()]
476                 except:
477                         offsetCount = 0
478                         serviceHandler = eServiceCenter.getInstance()
479                         bouquetlist = serviceHandler.list(self.bouquet_root)
480                         if not bouquetlist is None:
481                                 while True:
482                                         bouquetIterator = self.appendDVBTypes(bouquetlist.getNext())
483                                         if not bouquetIterator.valid(): #end of list
484                                                 break
485                                         self.bouquetNumOffsetCache[bouquetIterator.toString()]=offsetCount
486                                         if ((bouquetIterator.flags & eServiceReference.flagDirectory) != eServiceReference.flagDirectory):
487                                                 continue
488                                         servicelist = serviceHandler.list(bouquetIterator)
489                                         if not servicelist is None:
490                                                 while True:
491                                                         serviceIterator = servicelist.getNext()
492                                                         if not serviceIterator.valid(): #check if end of list
493                                                                 break
494                                                         if serviceIterator.flags: #playable services have no flags
495                                                                 continue
496                                                         offsetCount += 1
497                 return self.bouquetNumOffsetCache.get(bouquet.toString(), offsetCount)
498
499         def recallBouquetMode(self):
500                 if self.mode == MODE_TV:
501                         self.service_types = self.service_types_tv
502                         if currentConfigSelectionElement(config.usage.multibouquet) == "yes":
503                                 self.bouquet_rootstr = '1:7:1:0:0:0:0:0:0:0:(type == 1) FROM BOUQUET "bouquets.tv" ORDER BY bouquet'
504                         else:
505                                 self.bouquet_rootstr = '%s FROM BOUQUET "userbouquet.favourites.tv" ORDER BY bouquet'%(self.service_types)
506                 else:
507                         self.service_types = self.service_types_radio
508                         if currentConfigSelectionElement(config.usage.multibouquet) == "yes":
509                                 self.bouquet_rootstr = '1:7:1:0:0:0:0:0:0:0:(type == 1) FROM BOUQUET "bouquets.radio" ORDER BY bouquet'
510                         else:
511                                 self.bouquet_rootstr = '%s FROM BOUQUET "userbouquet.favourites.radio" ORDER BY bouquet'%(self.service_types)
512                 self.bouquet_root = eServiceReference(self.bouquet_rootstr)
513
514         def setTvMode(self):
515                 self.mode = MODE_TV
516                 self.servicePath = self.servicePathTV
517                 self.recallBouquetMode()
518                 title = self.instance.getTitle()
519                 pos = title.find(" (")
520                 if pos != -1:
521                         title = title[:pos]
522                 title += " (TV)"
523                 self.setTitle(title)
524
525         def setRadioMode(self):
526                 self.mode = MODE_RADIO
527                 self.servicePath = self.servicePathRadio
528                 self.recallBouquetMode()
529                 title = self.instance.getTitle()
530                 pos = title.find(" (")
531                 if pos != -1:
532                         title = title[:pos]
533                 title += " (Radio)"
534                 self.setTitle(title)
535
536         def setRoot(self, root, justSet=False):
537                 path = root.getPath()
538                 inBouquetRootList = path.find('FROM BOUQUET "bouquets.') != -1 #FIXME HACK
539                 pos = path.find(' FROM BOUQUET')
540                 isBouquet = pos != -1
541                 if not inBouquetRootList and isBouquet:
542                         self.servicelist.setMode(ServiceList.MODE_FAVOURITES)
543                         self.servicelist.setNumberOffset(self.getBouquetNumOffset(root))
544                         refstr = self.service_types + path[pos:]
545                         root = eServiceReference(refstr)
546                 else:
547                         self.servicelist.setMode(ServiceList.MODE_NORMAL)
548                 self.servicelist.setRoot(root, justSet)
549                 self.buildTitleString()
550
551         def removeModeStr(self, str):
552                 if self.mode == MODE_TV:
553                         pos = str.find(' (TV)')
554                 else:
555                         pos = str.find(' (Radio)')
556                 if pos != -1:
557                         return str[:pos]
558                 return str
559
560         def getServiceName(self, ref):
561                 str = self.removeModeStr(ServiceReference(ref).getServiceName())
562                 if not len(str):
563                         pathstr = ref.getPath()
564                         if pathstr.find('FROM PROVIDERS') != -1:
565                                 return _("Provider")
566                         if pathstr.find('FROM SATELLITES') != -1:
567                                 return _("Satellites")
568                         if pathstr.find(') ORDER BY name') != -1:
569                                 return _("All")
570                 return str
571
572         def buildTitleString(self):
573                 titleStr = self.instance.getTitle()
574                 pos = titleStr.find(']')
575                 if pos == -1:
576                         pos = titleStr.find(')')
577                 if pos != -1:
578                         titleStr = titleStr[:pos+1]
579                         Len = len(self.servicePath)
580                         if Len > 0:
581                                 base_ref = self.servicePath[0]
582                                 if Len > 1:
583                                         end_ref = self.servicePath[Len-1]
584                                 else:
585                                         end_ref = None
586                                 nameStr = self.getServiceName(base_ref)
587                                 titleStr += ' ' + nameStr
588                                 if end_ref is not None:
589                                         if Len > 2:
590                                                 titleStr += '/../'
591                                         else:
592                                                 titleStr += '/'
593                                         nameStr = self.getServiceName(end_ref)
594                                         titleStr += nameStr
595                                 self.setTitle(titleStr)
596
597         def moveUp(self):
598                 self.servicelist.moveUp()
599
600         def moveDown(self):
601                 self.servicelist.moveDown()
602
603         def clearPath(self):
604                 del self.servicePath[:]
605
606         def enterPath(self, ref, justSet=False):
607                 self.servicePath.append(ref)
608                 self.setRoot(ref, justSet)
609
610         def pathUp(self, justSet=False):
611                 prev = self.servicePath.pop()
612                 length = len(self.servicePath)
613                 if length:
614                         current = self.servicePath[length-1]
615                         self.setRoot(current, justSet)
616                         if not justSet:
617                                 self.setCurrentSelection(prev)
618                 return prev
619
620         def isBasePathEqual(self, ref):
621                 if len(self.servicePath) > 1 and self.servicePath[0] == ref:
622                         return True
623                 return False
624
625         def isPrevPathEqual(self, ref):
626                 length = len(self.servicePath)
627                 if length > 1 and self.servicePath[length-2] == ref:
628                         return True
629                 return False
630
631         def preEnterPath(self, refstr):
632                 return False
633
634         def showAllServices(self):
635                 if not self.pathChangedDisabled:
636                         refstr = '%s ORDER BY name'%(self.service_types)
637                         if not self.preEnterPath(refstr):
638                                 ref = eServiceReference(refstr)
639                                 currentRoot = self.getRoot()
640                                 if currentRoot is None or currentRoot != ref:
641                                         self.clearPath()
642                                         self.enterPath(ref)
643
644         def showSatellites(self):
645                 if not self.pathChangedDisabled:
646                         refstr = '%s FROM SATELLITES ORDER BY satellitePosition'%(self.service_types)
647                         if not self.preEnterPath(refstr):
648                                 ref = eServiceReference(refstr)
649                                 justSet=False
650                                 prev = None
651
652                                 if self.isBasePathEqual(ref):
653                                         if self.isPrevPathEqual(ref):
654                                                 justSet=True
655                                         prev = self.pathUp(justSet)
656                                 else:
657                                         currentRoot = self.getRoot()
658                                         if currentRoot is None or currentRoot != ref:
659                                                 justSet=True
660                                                 self.clearPath()
661                                                 self.enterPath(ref, True)
662                                 if justSet:
663                                         serviceHandler = eServiceCenter.getInstance()
664                                         servicelist = serviceHandler.list(ref)
665                                         if not servicelist is None:
666                                                 while True:
667                                                         service = servicelist.getNext()
668                                                         if not service.valid(): #check if end of list
669                                                                 break
670                                                         orbpos = service.getUnsignedData(4) >> 16
671                                                         if service.getPath().find("FROM PROVIDER") != -1:
672                                                                 service_name = _("Providers")
673                                                         else:
674                                                                 service_name = _("Services")
675                                                         try:
676                                                                 service_name += str(' - %s'%(nimmanager.getSatDescription(orbpos)))
677                                                                 service.setName(service_name) # why we need this cast?
678                                                         except:
679                                                                 if orbpos == 0xFFFF: #Cable
680                                                                         n = ("%s (%s)") % (service_name, _("Cable"))
681                                                                 elif orbpos == 0xEEEE: #Terrestrial
682                                                                         n = ("%s (%s)") % (service_name, _("Terrestrial"))
683                                                                 else:
684                                                                         if orbpos > 1800: # west
685                                                                                 orbpos = 3600 - orbpos
686                                                                                 h = _("W")
687                                                                         else:
688                                                                                 h = _("E")
689                                                                         n = ("%s (%d.%d" + h + ")") % (service_name, orbpos / 10, orbpos % 10)
690                                                                 service.setName(n)
691                                                         self.servicelist.addService(service)
692                                                         self.servicelist.finishFill()
693                                                         if prev is not None:
694                                                                 self.setCurrentSelection(prev)
695
696         def showProviders(self):
697                 if not self.pathChangedDisabled:
698                         refstr = '%s FROM PROVIDERS ORDER BY name'%(self.service_types)
699                         if not self.preEnterPath(refstr):
700                                 ref = eServiceReference(refstr)
701                                 if self.isBasePathEqual(ref):
702                                         self.pathUp()
703                                 else:
704                                         currentRoot = self.getRoot()
705                                         if currentRoot is None or currentRoot != ref:
706                                                 self.clearPath()
707                                                 self.enterPath(ref)
708
709         def changeBouquet(self, direction):
710                 if not self.pathChangedDisabled:
711                         if self.isBasePathEqual(self.bouquet_root):
712                                 self.pathUp()
713                                 if direction < 0:
714                                         self.moveUp()
715                                 else:
716                                         self.moveDown()
717                                 ref = self.getCurrentSelection()
718                                 self.enterPath(ref)
719
720         def inBouquet(self):
721                 return self.isBasePathEqual(self.bouquet_root)
722
723         def atBegin(self):
724                 return self.servicelist.atBegin()
725
726         def atEnd(self):
727                 return self.servicelist.atEnd()
728
729         def nextBouquet(self):
730                 self.changeBouquet(+1)
731
732         def prevBouquet(self):
733                 self.changeBouquet(-1)
734
735         def showFavourites(self):
736                 if not self.pathChangedDisabled:
737                         if not self.preEnterPath(self.bouquet_rootstr):
738                                 if self.isBasePathEqual(self.bouquet_root):
739                                         self.pathUp()
740                                 else:
741                                         currentRoot = self.getRoot()
742                                         if currentRoot is None or currentRoot != self.bouquet_root:
743                                                 self.clearPath()
744                                                 self.enterPath(self.bouquet_root)
745
746         def keyNumberGlobal(self, number):
747                 char = self.numericalTextInput.getKey(number)
748                 self.servicelist.moveToChar(char)
749
750         def getRoot(self):
751                 return self.servicelist.getRoot()
752
753         def getCurrentSelection(self):
754                 return self.servicelist.getCurrent()
755
756         def setCurrentSelection(self, service):
757                 servicepath = service.getPath()
758                 pos = servicepath.find(" FROM BOUQUET")
759                 if pos != -1:
760                         if self.mode == MODE_TV:
761                                 servicepath = '(type == 1)' + servicepath[pos:]
762                         else:
763                                 servicepath = '(type == 2)' + servicepath[pos:]
764                         service.setPath(servicepath)
765                 self.servicelist.setCurrent(service)
766
767         def getBouquetList(self):
768                 serviceCount=0
769                 bouquets = [ ]
770                 serviceHandler = eServiceCenter.getInstance()
771                 list = serviceHandler.list(self.bouquet_root)
772                 if not list is None:
773                         while True:
774                                 s = list.getNext()
775                                 if not s.valid():
776                                         break
777                                 if ((s.flags & eServiceReference.flagDirectory) == eServiceReference.flagDirectory):
778                                         info = serviceHandler.info(s)
779                                         if not info is None:
780                                                 bouquets.append((info.getName(s), s))
781                                 else:
782                                         serviceCount += 1
783                         if len(bouquets) == 0 and serviceCount > 0:
784                                 info = serviceHandler.info(self.bouquet_root)
785                                 if not info is None:
786                                         bouquets.append((info.getName(self.bouquet_root), self.bouquet_root))
787                         return bouquets
788                 return None
789
790         def keyNumber0(self, num):
791                 if len(self.servicePath) > 1:
792                         self.keyGoUp()
793                 else:
794                         self.keyNumberGlobal(num)
795
796         def keyGoUp(self):
797                 if len(self.servicePath) > 1:
798                         if self.isBasePathEqual(self.bouquet_root):
799                                 self.showFavourites()
800                         else:
801                                 ref = eServiceReference('%s FROM SATELLITES ORDER BY satellitePosition'%(self.service_types))
802                                 if self.isBasePathEqual(ref):
803                                         self.showSatellites()
804                                 else:
805                                         ref = eServiceReference('%s FROM PROVIDERS ORDER BY name'%(self.service_types))
806                                         if self.isBasePathEqual(ref):
807                                                 self.showProviders()
808                                         else:
809                                                 self.showAllServices()
810
811 HISTORYSIZE = 20
812
813 class ChannelSelection(ChannelSelectionBase, ChannelSelectionEdit, ChannelSelectionEPG):
814         def __init__(self, session):
815                 ChannelSelectionBase.__init__(self,session)
816                 ChannelSelectionEdit.__init__(self)
817                 ChannelSelectionEPG.__init__(self)
818
819                 #config for lastservice
820                 config.tv = ConfigSubsection();
821                 config.tv.lastservice = configElement("config.tv.lastservice", configText, "", 0);
822                 config.tv.lastroot = configElement("config.tv.lastroot", configText, "", 0);
823
824                 self["actions"] = ActionMap(["OkCancelActions"],
825                         {
826                                 "cancel": self.cancel,
827                                 "ok": self.channelSelected,
828                         })
829                 self.onShown.append(self.__onShown)
830
831                 self.lastChannelRootTimer = eTimer()
832                 self.lastChannelRootTimer.timeout.get().append(self.__onCreate)
833                 self.lastChannelRootTimer.start(100,True)
834
835                 self.history = [ ]
836                 self.history_pos = 0
837
838         def __onCreate(self):
839                 self.setTvMode()
840                 self.restoreRoot()
841                 lastservice=eServiceReference(config.tv.lastservice.value)
842                 if lastservice.valid():
843                         self.setCurrentSelection(lastservice)
844                         self.zap()
845
846         def __onShown(self):
847                 self.recallBouquetMode()
848                 ref = self.session.nav.getCurrentlyPlayingServiceReference()
849                 if ref is not None and ref.valid() and ref.getPath() == "":
850                         self.servicelist.setPlayableIgnoreService(ref)
851                 else:
852                         self.servicelist.setPlayableIgnoreService(eServiceReference())
853
854         def channelSelected(self):
855                 ref = self.getCurrentSelection()
856                 if self.movemode:
857                         self.toggleMoveMarked()
858                 elif (ref.flags & 7) == 7:
859                         self.enterPath(ref)
860                 elif self.bouquet_mark_edit:
861                         self.doMark()
862                 else:
863                         self.zap()
864                         self.close(ref)
865
866         #called from infoBar and channelSelected
867         def zap(self):
868                 ref = self.session.nav.getCurrentlyPlayingServiceReference()
869                 nref = self.getCurrentSelection()
870                 if ref is None or ref != nref:
871                         self.session.nav.playService(nref)
872                 self.saveRoot()
873                 self.saveChannel()
874                 if self.servicePath is not None:
875                         tmp=self.servicePath[:]
876                         tmp.append(nref)
877                         try:
878                                 del self.history[self.history_pos+1:]
879                         except:
880                                 pass
881                         self.history.append(tmp)
882                         hlen = len(self.history)
883                         if hlen > HISTORYSIZE:
884                                 del self.history[0]
885                                 hlen -= 1
886                         self.history_pos = hlen-1
887
888         def historyBack(self):
889                 hlen = len(self.history)
890                 if hlen > 1 and self.history_pos > 0:
891                         self.history_pos -= 1
892                         self.setHistoryPath()
893
894         def historyNext(self):
895                 hlen = len(self.history)
896                 if hlen > 1 and self.history_pos < (hlen-1):
897                         self.history_pos += 1
898                         self.setHistoryPath()
899
900         def setHistoryPath(self):
901                 path = self.history[self.history_pos][:]
902                 ref = path.pop()
903                 del self.servicePath[:]
904                 self.servicePath += path
905                 self.saveRoot()
906                 plen = len(path)
907                 root = path[plen-1]
908                 if self.getRoot() != root:
909                         self.setRoot(root)
910                 self.session.nav.playService(ref)
911                 self.setCurrentSelection(ref)
912                 self.saveChannel()
913
914         def saveRoot(self):
915                 path = ''
916                 for i in self.servicePathTV:
917                         path += i.toString()
918                         path += ';'
919                 if len(path) and path != config.tv.lastroot.value:
920                         config.tv.lastroot.value = path
921                         config.tv.lastroot.save()
922
923         def restoreRoot(self):
924                 self.clearPath()
925                 re = compile('.+?;')
926                 tmp = re.findall(config.tv.lastroot.value)
927                 cnt = 0
928                 for i in tmp:
929                         self.servicePathTV.append(eServiceReference(i[:len(i)-1]))
930                         cnt += 1
931                 if cnt:
932                         path = self.servicePathTV.pop()
933                         self.enterPath(path)
934                 else:
935                         self.showFavourites()
936                         self.saveRoot()
937
938         def preEnterPath(self, refstr):
939                 if len(self.servicePathTV) and self.servicePathTV[0] != eServiceReference(refstr):
940                         pathstr = config.tv.lastroot.value
941                         if pathstr is not None and pathstr.find(refstr) == 0:
942                                 self.restoreRoot()
943                                 lastservice=eServiceReference(config.tv.lastservice.value)
944                                 if lastservice.valid():
945                                         self.setCurrentSelection(lastservice)
946                                 return True
947                 return False
948
949         def saveChannel(self):
950                 ref = self.session.nav.getCurrentlyPlayingServiceReference()
951                 if ref is not None:
952                         refstr = ref.toString()
953                 else:
954                         refstr = ""
955                 if refstr != config.tv.lastservice.value:
956                         config.tv.lastservice.value = refstr
957                         config.tv.lastservice.save()
958
959         def recallPrevService(self):
960                 hlen = len(self.history)
961                 if hlen > 1:
962                         if self.history_pos == hlen-1:
963                                 tmp = self.history[self.history_pos]
964                                 self.history[self.history_pos] = self.history[self.history_pos-1]
965                                 self.history[self.history_pos-1] = tmp
966                         else:
967                                 tmp = self.history[self.history_pos+1]
968                                 self.history[self.history_pos+1] = self.history[self.history_pos]
969                                 self.history[self.history_pos] = tmp
970                         self.setHistoryPath()
971
972         def cancel(self):
973                 self.close(None)
974                 self.restoreRoot()
975                 lastservice=eServiceReference(config.tv.lastservice.value)
976                 if lastservice.valid() and self.getCurrentSelection() != lastservice:
977                         self.setCurrentSelection(lastservice)
978
979 from Screens.InfoBarGenerics import InfoBarEvent, InfoBarServiceName, InfoBarInstantRecord
980
981 class RadioInfoBar(Screen, InfoBarEvent, InfoBarServiceName, InfoBarInstantRecord):
982         def __init__(self, session):
983                 Screen.__init__(self, session)
984                 InfoBarEvent.__init__(self)
985                 InfoBarServiceName.__init__(self)
986                 InfoBarInstantRecord.__init__(self)
987                 self["Clock"] = Clock()
988
989 class ChannelSelectionRadio(ChannelSelectionBase, ChannelSelectionEdit, ChannelSelectionEPG):
990         def __init__(self, session):
991                 ChannelSelectionBase.__init__(self, session)
992                 ChannelSelectionEdit.__init__(self)
993                 ChannelSelectionEPG.__init__(self)
994
995                 config.radio = ConfigSubsection();
996                 config.radio.lastservice = configElement("config.radio.lastservice", configText, "", 0);
997                 config.radio.lastroot = configElement("config.radio.lastroot", configText, "", 0);
998                 self.onLayoutFinish.append(self.onCreate)
999
1000                 self.info = session.instantiateDialog(RadioInfoBar)
1001
1002                 self["actions"] = ActionMap(["OkCancelActions", "TvRadioActions"],
1003                         {
1004                                 "keyTV": self.closeRadio,
1005                                 "keyRadio": self.closeRadio,
1006                                 "cancel": self.closeRadio,
1007                                 "ok": self.channelSelected,
1008                         })
1009
1010         def saveRoot(self):
1011                 path = ''
1012                 for i in self.servicePathRadio:
1013                         path += i.toString()
1014                         path += ';'
1015                 if len(path) and path != config.radio.lastroot.value:
1016                         config.radio.lastroot.value = path
1017                         config.radio.lastroot.save()
1018
1019         def restoreRoot(self):
1020                 self.clearPath()
1021                 re = compile('.+?;')
1022                 tmp = re.findall(config.radio.lastroot.value)
1023                 cnt = 0
1024                 for i in tmp:
1025                         self.servicePathRadio.append(eServiceReference(i[:len(i)-1]))
1026                         cnt += 1
1027                 if cnt:
1028                         path = self.servicePathRadio.pop()
1029                         self.enterPath(path)
1030                 else:
1031                         self.showFavourites()
1032                         self.saveRoot()
1033
1034         def preEnterPath(self, refstr):
1035                 if len(self.servicePathRadio) and self.servicePathRadio[0] != eServiceReference(refstr):
1036                         pathstr = config.radio.lastroot.value
1037                         if pathstr is not None and pathstr.find(refstr) == 0:
1038                                 self.restoreRoot()
1039                                 lastservice=eServiceReference(config.radio.lastservice.value)
1040                                 if lastservice.valid():
1041                                         self.setCurrentSelection(lastservice)
1042                                 return True
1043                 return False
1044
1045         def onCreate(self):
1046                 self.setRadioMode()
1047                 self.restoreRoot()
1048                 lastservice=eServiceReference(config.radio.lastservice.value)
1049                 if lastservice.valid():
1050                         self.servicelist.setCurrent(lastservice)
1051                         self.session.nav.playService(lastservice)
1052                         self.servicelist.setPlayableIgnoreService(lastservice)
1053                 self.info.show()
1054
1055         def channelSelected(self): # just return selected service
1056                 ref = self.getCurrentSelection()
1057                 if self.movemode:
1058                         self.toggleMoveMarked()
1059                 elif (ref.flags & 7) == 7:
1060                         self.enterPath(ref)
1061                 elif self.bouquet_mark_edit:
1062                         self.doMark()
1063                 else:
1064                         playingref = self.session.nav.getCurrentlyPlayingServiceReference()
1065                         if playingref is None or playingref != ref:
1066                                 self.session.nav.playService(ref)
1067                                 self.servicelist.setPlayableIgnoreService(ref)
1068                                 config.radio.lastservice.value = ref.toString()
1069                                 config.radio.lastservice.save()
1070                         self.saveRoot()
1071
1072         def closeRadio(self):
1073                 self.info.hide()
1074                 #set previous tv service
1075                 lastservice=eServiceReference(config.tv.lastservice.value)
1076                 self.session.nav.playService(lastservice)
1077                 self.close(None)
1078
1079 class SimpleChannelSelection(ChannelSelectionBase):
1080         def __init__(self, session, title):
1081                 ChannelSelectionBase.__init__(self, session)
1082                 self.title = title
1083                 self.onShown.append(self.__onExecCallback)
1084
1085                 self["actions"] = ActionMap(["OkCancelActions", "TvRadioActions"],
1086                         {
1087                                 "cancel": self.close,
1088                                 "ok": self.channelSelected,
1089                                 "keyRadio": self.setModeRadio,
1090                                 "keyTV": self.setModeTv,
1091                         })
1092
1093         def __onExecCallback(self):
1094                 self.setTitle(self.title)
1095                 self.setModeTv()
1096
1097         def channelSelected(self): # just return selected service
1098                 ref = self.getCurrentSelection()
1099                 if (ref.flags & 7) == 7:
1100                         self.enterPath(ref)
1101                 else:
1102                         ref = self.getCurrentSelection()
1103                         self.close(ref)
1104
1105         def setModeTv(self):
1106                 self.setTvMode()
1107                 self.showFavourites()
1108
1109         def setModeRadio(self):
1110                 self.setRadioMode()
1111                 self.showFavourites()