small speedups/cleanups by moritz venn
[openblackhole/openblackhole-enigma2.git] / lib / python / Screens / InfoBarGenerics.py
1 from ChannelSelection import ChannelSelection, BouquetSelector
2
3 from Components.ActionMap import ActionMap, HelpableActionMap
4 from Components.ActionMap import NumberActionMap
5 from Components.Harddisk import harddiskmanager
6 from Components.Input import Input
7 from Components.Label import Label
8 from Components.PluginComponent import plugins
9 from Components.ServiceEventTracker import ServiceEventTracker
10 from Components.Sources.Boolean import Boolean
11 from Components.config import config, ConfigBoolean, ConfigClock
12 from Components.SystemInfo import SystemInfo
13 from EpgSelection import EPGSelection
14 from Plugins.Plugin import PluginDescriptor
15
16 from Screen import Screen
17 from Screens.ChoiceBox import ChoiceBox
18 from Screens.Dish import Dish
19 from Screens.EventView import EventViewEPGSelect, EventViewSimple
20 from Screens.InputBox import InputBox
21 from Screens.MessageBox import MessageBox
22 from Screens.MinuteInput import MinuteInput
23 from Screens.TimerSelection import TimerSelection
24 from Screens.PictureInPicture import PictureInPicture
25 from Screens.SubtitleDisplay import SubtitleDisplay
26 from Screens.RdsDisplay import RdsInfoDisplay, RassInteractive
27 from Screens.SleepTimerEdit import SleepTimerEdit
28 from Screens.TimeDateInput import TimeDateInput
29 from ServiceReference import ServiceReference
30
31 from Tools import Notifications
32 from Tools.Directories import SCOPE_HDD, resolveFilename, fileExists
33
34 from enigma import eTimer, eServiceCenter, eDVBServicePMTHandler, iServiceInformation, \
35         iPlayableService, eServiceReference, eEPGCache
36
37 from time import time, localtime, strftime
38 from os import stat as os_stat
39 from bisect import insort
40
41 from RecordTimer import RecordTimerEntry, RecordTimer
42
43 # hack alert!
44 from Menu import MainMenu, mdom
45
46 class InfoBarDish:
47         def __init__(self):
48                 self.dishDialog = self.session.instantiateDialog(Dish)
49
50 class InfoBarShowHide:
51         """ InfoBar show/hide control, accepts toggleShow and hide actions, might start
52         fancy animations. """
53         STATE_HIDDEN = 0
54         STATE_HIDING = 1
55         STATE_SHOWING = 2
56         STATE_SHOWN = 3
57
58         def __init__(self):
59                 self["ShowHideActions"] = ActionMap( ["InfobarShowHideActions"] ,
60                         {
61                                 "toggleShow": self.toggleShow,
62                                 "hide": self.hide,
63                         }, 1) # lower prio to make it possible to override ok and cancel..
64
65                 self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
66                         {
67                                 iPlayableService.evStart: self.serviceStarted,
68                         })
69
70                 self.__state = self.STATE_SHOWN
71                 self.__locked = 0
72
73                 self.hideTimer = eTimer()
74                 self.hideTimer.callback.append(self.doTimerHide)
75                 self.hideTimer.start(5000, True)
76
77                 self.onShow.append(self.__onShow)
78                 self.onHide.append(self.__onHide)
79
80         def serviceStarted(self):
81                 if self.execing:
82                         if config.usage.show_infobar_on_zap.value:
83                                 self.doShow()
84
85         def __onShow(self):
86                 self.__state = self.STATE_SHOWN
87                 self.startHideTimer()
88
89         def startHideTimer(self):
90                 if self.__state == self.STATE_SHOWN and not self.__locked:
91                         idx = config.usage.infobar_timeout.index
92                         if idx:
93                                 self.hideTimer.start(idx*1000, True)
94
95         def __onHide(self):
96                 self.__state = self.STATE_HIDDEN
97
98         def doShow(self):
99                 self.show()
100                 self.startHideTimer()
101
102         def doTimerHide(self):
103                 self.hideTimer.stop()
104                 if self.__state == self.STATE_SHOWN:
105                         self.hide()
106
107         def toggleShow(self):
108                 if self.__state == self.STATE_SHOWN:
109                         self.hide()
110                         self.hideTimer.stop()
111                 elif self.__state == self.STATE_HIDDEN:
112                         self.show()
113
114         def lockShow(self):
115                 self.__locked = self.__locked + 1
116                 if self.execing:
117                         self.show()
118                         self.hideTimer.stop()
119
120         def unlockShow(self):
121                 self.__locked = self.__locked - 1
122                 if self.execing:
123                         self.startHideTimer()
124
125 #       def startShow(self):
126 #               self.instance.m_animation.startMoveAnimation(ePoint(0, 600), ePoint(0, 380), 100)
127 #               self.__state = self.STATE_SHOWN
128 #
129 #       def startHide(self):
130 #               self.instance.m_animation.startMoveAnimation(ePoint(0, 380), ePoint(0, 600), 100)
131 #               self.__state = self.STATE_HIDDEN
132
133 class NumberZap(Screen):
134         def quit(self):
135                 self.Timer.stop()
136                 self.close(0)
137
138         def keyOK(self):
139                 self.Timer.stop()
140                 self.close(int(self["number"].getText()))
141
142         def keyNumberGlobal(self, number):
143                 self.Timer.start(3000, True)            #reset timer
144                 self.field = self.field + str(number)
145                 self["number"].setText(self.field)
146                 if len(self.field) >= 4:
147                         self.keyOK()
148
149         def __init__(self, session, number):
150                 Screen.__init__(self, session)
151                 self.field = str(number)
152
153                 self["channel"] = Label(_("Channel:"))
154
155                 self["number"] = Label(self.field)
156
157                 self["actions"] = NumberActionMap( [ "SetupActions" ],
158                         {
159                                 "cancel": self.quit,
160                                 "ok": self.keyOK,
161                                 "1": self.keyNumberGlobal,
162                                 "2": self.keyNumberGlobal,
163                                 "3": self.keyNumberGlobal,
164                                 "4": self.keyNumberGlobal,
165                                 "5": self.keyNumberGlobal,
166                                 "6": self.keyNumberGlobal,
167                                 "7": self.keyNumberGlobal,
168                                 "8": self.keyNumberGlobal,
169                                 "9": self.keyNumberGlobal,
170                                 "0": self.keyNumberGlobal
171                         })
172
173                 self.Timer = eTimer()
174                 self.Timer.callback.append(self.keyOK)
175                 self.Timer.start(3000, True)
176
177 class InfoBarNumberZap:
178         """ Handles an initial number for NumberZapping """
179         def __init__(self):
180                 self["NumberActions"] = NumberActionMap( [ "NumberActions"],
181                         {
182                                 "1": self.keyNumberGlobal,
183                                 "2": self.keyNumberGlobal,
184                                 "3": self.keyNumberGlobal,
185                                 "4": self.keyNumberGlobal,
186                                 "5": self.keyNumberGlobal,
187                                 "6": self.keyNumberGlobal,
188                                 "7": self.keyNumberGlobal,
189                                 "8": self.keyNumberGlobal,
190                                 "9": self.keyNumberGlobal,
191                                 "0": self.keyNumberGlobal,
192                         })
193
194         def keyNumberGlobal(self, number):
195 #               print "You pressed number " + str(number)
196                 if number == 0:
197                         if isinstance(self, InfoBarPiP) and self.pipHandles0Action():
198                                 self.pipDoHandle0Action()
199                         else:
200                                 self.servicelist.recallPrevService()
201                 else:
202                         if self.has_key("TimeshiftActions") and not self.timeshift_enabled:
203                                 self.session.openWithCallback(self.numberEntered, NumberZap, number)
204
205         def numberEntered(self, retval):
206 #               print self.servicelist
207                 if retval > 0:
208                         self.zapToNumber(retval)
209
210         def searchNumberHelper(self, serviceHandler, num, bouquet):
211                 servicelist = serviceHandler.list(bouquet)
212                 if not servicelist is None:
213                         while num:
214                                 serviceIterator = servicelist.getNext()
215                                 if not serviceIterator.valid(): #check end of list
216                                         break
217                                 playable = not (serviceIterator.flags & (eServiceReference.isMarker|eServiceReference.isDirectory))
218                                 if playable:
219                                         num -= 1;
220                         if not num: #found service with searched number ?
221                                 return serviceIterator, 0
222                 return None, num
223
224         def zapToNumber(self, number):
225                 bouquet = self.servicelist.bouquet_root
226                 service = None
227                 serviceHandler = eServiceCenter.getInstance()
228                 if not config.usage.multibouquet.value:
229                         service, number = self.searchNumberHelper(serviceHandler, number, bouquet)
230                 else:
231                         bouquetlist = serviceHandler.list(bouquet)
232                         if not bouquetlist is None:
233                                 while number:
234                                         bouquet = bouquetlist.getNext()
235                                         if not bouquet.valid(): #check end of list
236                                                 break
237                                         if bouquet.flags & eServiceReference.isDirectory:
238                                                 service, number = self.searchNumberHelper(serviceHandler, number, bouquet)
239                 if not service is None:
240                         if self.servicelist.getRoot() != bouquet: #already in correct bouquet?
241                                 self.servicelist.clearPath()
242                                 if self.servicelist.bouquet_root != bouquet:
243                                         self.servicelist.enterPath(self.servicelist.bouquet_root)
244                                 self.servicelist.enterPath(bouquet)
245                         self.servicelist.setCurrentSelection(service) #select the service in servicelist
246                         self.servicelist.zap()
247
248 config.misc.initialchannelselection = ConfigBoolean(default = True)
249
250 class InfoBarChannelSelection:
251         """ ChannelSelection - handles the channelSelection dialog and the initial
252         channelChange actions which open the channelSelection dialog """
253         def __init__(self):
254                 #instantiate forever
255                 self.servicelist = self.session.instantiateDialog(ChannelSelection)
256
257                 if config.misc.initialchannelselection.value:
258                         self.onShown.append(self.firstRun)
259
260                 self["ChannelSelectActions"] = HelpableActionMap(self, "InfobarChannelSelection",
261                         {
262                                 "switchChannelUp": (self.switchChannelUp, _("open servicelist(up)")),
263                                 "switchChannelDown": (self.switchChannelDown, _("open servicelist(down)")),
264                                 "zapUp": (self.zapUp, _("previous channel")),
265                                 "zapDown": (self.zapDown, _("next channel")),
266                                 "historyBack": (self.historyBack, _("previous channel in history")),
267                                 "historyNext": (self.historyNext, _("next channel in history")),
268                                 "openServiceList": (self.openServiceList, _("open servicelist")),
269                         })
270
271         def showTvChannelList(self, zap=False):
272                 self.servicelist.setModeTv()
273                 if zap:
274                         self.servicelist.zap()
275                 self.session.execDialog(self.servicelist)
276
277         def showRadioChannelList(self, zap=False):
278                 self.servicelist.setModeRadio()
279                 if zap:
280                         self.servicelist.zap()
281                 self.session.execDialog(self.servicelist)
282
283         def firstRun(self):
284                 self.onShown.remove(self.firstRun)
285                 config.misc.initialchannelselection.value = False
286                 config.misc.initialchannelselection.save()
287                 self.switchChannelDown()
288
289         def historyBack(self):
290                 self.servicelist.historyBack()
291
292         def historyNext(self):
293                 self.servicelist.historyNext()
294
295         def switchChannelUp(self):
296                 self.servicelist.moveUp()
297                 self.session.execDialog(self.servicelist)
298
299         def switchChannelDown(self):
300                 self.servicelist.moveDown()
301                 self.session.execDialog(self.servicelist)
302
303         def openServiceList(self):
304                 self.session.execDialog(self.servicelist)
305
306         def zapUp(self):
307                 if self.servicelist.inBouquet():
308                         prev = self.servicelist.getCurrentSelection()
309                         if prev:
310                                 prev = prev.toString()
311                                 while True:
312                                         if config.usage.quickzap_bouquet_change.value:
313                                                 if self.servicelist.atBegin():
314                                                         self.servicelist.prevBouquet()
315                                         self.servicelist.moveUp()
316                                         cur = self.servicelist.getCurrentSelection()
317                                         if not cur or (not (cur.flags & 64)) or cur.toString() == prev:
318                                                 break
319                 else:
320                         self.servicelist.moveUp()
321                 self.servicelist.zap()
322
323         def zapDown(self):
324                 if self.servicelist.inBouquet():
325                         prev = self.servicelist.getCurrentSelection()
326                         if prev:
327                                 prev = prev.toString()
328                                 while True:
329                                         if config.usage.quickzap_bouquet_change.value and self.servicelist.atEnd():
330                                                 self.servicelist.nextBouquet()
331                                         else:
332                                                 self.servicelist.moveDown()
333                                         cur = self.servicelist.getCurrentSelection()
334                                         if not cur or (not (cur.flags & 64)) or cur.toString() == prev:
335                                                 break
336                 else:
337                         self.servicelist.moveDown()
338                 self.servicelist.zap()
339
340 class InfoBarMenu:
341         """ Handles a menu action, to open the (main) menu """
342         def __init__(self):
343                 self["MenuActions"] = HelpableActionMap(self, "InfobarMenuActions",
344                         {
345                                 "mainMenu": (self.mainMenu, _("Enter main menu...")),
346                         })
347                 self.session.infobar = None
348
349         def mainMenu(self):
350                 print "loading mainmenu XML..."
351                 menu = mdom.getroot()
352                 assert menu.tag == "menu", "root element in menu must be 'menu'!"
353
354                 self.session.infobar = self
355                 # so we can access the currently active infobar from screens opened from within the mainmenu
356                 # at the moment used from the SubserviceSelection
357
358                 self.session.openWithCallback(self.mainMenuClosed, MainMenu, menu)
359
360         def mainMenuClosed(self, *val):
361                 self.session.infobar = None
362
363 class InfoBarSimpleEventView:
364         """ Opens the Eventview for now/next """
365         def __init__(self):
366                 self["EPGActions"] = HelpableActionMap(self, "InfobarEPGActions",
367                         {
368                                 "showEventInfo": (self.openEventView, _("show event details")),
369                         })
370
371         def openEventView(self):
372                 self.epglist = [ ]
373                 service = self.session.nav.getCurrentService()
374                 ref = self.session.nav.getCurrentlyPlayingServiceReference()
375                 info = service.info()
376                 ptr=info.getEvent(0)
377                 if ptr:
378                         self.epglist.append(ptr)
379                 ptr=info.getEvent(1)
380                 if ptr:
381                         self.epglist.append(ptr)
382                 if len(self.epglist) > 0:
383                         self.session.open(EventViewSimple, self.epglist[0], ServiceReference(ref), self.eventViewCallback)
384
385         def eventViewCallback(self, setEvent, setService, val): #used for now/next displaying
386                 if len(self.epglist) > 1:
387                         tmp = self.epglist[0]
388                         self.epglist[0]=self.epglist[1]
389                         self.epglist[1]=tmp
390                         setEvent(self.epglist[0])
391
392 class InfoBarEPG:
393         """ EPG - Opens an EPG list when the showEPGList action fires """
394         def __init__(self):
395                 self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
396                         {
397                                 iPlayableService.evUpdatedEventInfo: self.__evEventInfoChanged,
398                         })
399
400                 self.is_now_next = False
401                 self.dlg_stack = [ ]
402                 self.bouquetSel = None
403                 self.eventView = None
404                 self["EPGActions"] = HelpableActionMap(self, "InfobarEPGActions",
405                         {
406                                 "showEventInfo": (self.openEventView, _("show EPG...")),
407                                 "showEventInfoPlugin": (self.showEventInfoPlugins, _("show single service EPG...")),
408                                 "showInfobarOrEpgWhenInfobarAlreadyVisible": self.showEventInfoWhenNotVisible,
409                         })
410
411         def showEventInfoWhenNotVisible(self):
412                 if self.shown:
413                         self.openEventView()
414                 else:
415                         self.toggleShow()
416                         return 1
417
418         def zapToService(self, service):
419                 if not service is None:
420                         if self.servicelist.getRoot() != self.epg_bouquet: #already in correct bouquet?
421                                 self.servicelist.clearPath()
422                                 if self.servicelist.bouquet_root != self.epg_bouquet:
423                                         self.servicelist.enterPath(self.servicelist.bouquet_root)
424                                 self.servicelist.enterPath(self.epg_bouquet)
425                         self.servicelist.setCurrentSelection(service) #select the service in servicelist
426                         self.servicelist.zap()
427
428         def getBouquetServices(self, bouquet):
429                 services = [ ]
430                 servicelist = eServiceCenter.getInstance().list(bouquet)
431                 if not servicelist is None:
432                         while True:
433                                 service = servicelist.getNext()
434                                 if not service.valid(): #check if end of list
435                                         break
436                                 if service.flags & (eServiceReference.isDirectory | eServiceReference.isMarker): #ignore non playable services
437                                         continue
438                                 services.append(ServiceReference(service))
439                 return services
440
441         def openBouquetEPG(self, bouquet, withCallback=True):
442                 services = self.getBouquetServices(bouquet)
443                 if len(services):
444                         self.epg_bouquet = bouquet
445                         if withCallback:
446                                 self.dlg_stack.append(self.session.openWithCallback(self.closed, EPGSelection, services, self.zapToService, None, self.changeBouquetCB))
447                         else:
448                                 self.session.open(EPGSelection, services, self.zapToService, None, self.changeBouquetCB)
449
450         def changeBouquetCB(self, direction, epg):
451                 if self.bouquetSel:
452                         if direction > 0:
453                                 self.bouquetSel.down()
454                         else:
455                                 self.bouquetSel.up()
456                         bouquet = self.bouquetSel.getCurrent()
457                         services = self.getBouquetServices(bouquet)
458                         if len(services):
459                                 self.epg_bouquet = bouquet
460                                 epg.setServices(services)
461
462         def closed(self, ret=False):
463                 closedScreen = self.dlg_stack.pop()
464                 if self.bouquetSel and closedScreen == self.bouquetSel:
465                         self.bouquetSel = None
466                 elif self.eventView and closedScreen == self.eventView:
467                         self.eventView = None
468                 if ret:
469                         dlgs=len(self.dlg_stack)
470                         if dlgs > 0:
471                                 self.dlg_stack[dlgs-1].close(dlgs > 1)
472
473         def openMultiServiceEPG(self, withCallback=True):
474                 bouquets = self.servicelist.getBouquetList()
475                 if bouquets is None:
476                         cnt = 0
477                 else:
478                         cnt = len(bouquets)
479                 if cnt > 1: # show bouquet list
480                         if withCallback:
481                                 self.bouquetSel = self.session.openWithCallback(self.closed, BouquetSelector, bouquets, self.openBouquetEPG, enableWrapAround=True)
482                                 self.dlg_stack.append(self.bouquetSel)
483                         else:
484                                 self.bouquetSel = self.session.open(BouquetSelector, bouquets, self.openBouquetEPG, enableWrapAround=True)
485                 elif cnt == 1:
486                         self.openBouquetEPG(bouquets[0][1], withCallback)
487
488         def openSingleServiceEPG(self):
489                 ref=self.session.nav.getCurrentlyPlayingServiceReference()
490                 self.session.open(EPGSelection, ref)
491
492         def showEventInfoPlugins(self):
493                 list = [(p.name, boundFunction(self.runPlugin, p)) for p in plugins.getPlugins(where = PluginDescriptor.WHERE_EVENTINFO)]
494
495                 if list:
496                         list.append((_("show single service EPG..."), self.openSingleServiceEPG))
497                         self.session.openWithCallback(self.EventInfoPluginChosen, ChoiceBox, title=_("Please choose an extension..."), list = list)
498                 else:
499                         self.openSingleServiceEPG()
500                         
501         def runPlugin(self, plugin):
502                 plugin(session = self.session, servicelist = self.servicelist)
503                 
504         def EventInfoPluginChosen(self, answer):
505                 if answer is not None:
506                         answer[1]()
507
508         def openSimilarList(self, eventid, refstr):
509                 self.session.open(EPGSelection, refstr, None, eventid)
510
511         def getNowNext(self):
512                 epglist = [ ]
513                 service = self.session.nav.getCurrentService()
514                 info = service and service.info()
515                 ptr = info and info.getEvent(0)
516                 if ptr:
517                         epglist.append(ptr)
518                 ptr = info and info.getEvent(1)
519                 if ptr:
520                         epglist.append(ptr)
521                 self.epglist = epglist
522
523         def __evEventInfoChanged(self):
524                 if self.is_now_next and len(self.dlg_stack) == 1:
525                         self.getNowNext()
526                         assert self.eventView
527                         if self.epglist:
528                                 self.eventView.setEvent(self.epglist[0])
529
530         def openEventView(self):
531                 ref = self.session.nav.getCurrentlyPlayingServiceReference()
532                 self.getNowNext()
533                 epglist = self.epglist
534                 if not epglist:
535                         self.is_now_next = False
536                         epg = eEPGCache.getInstance()
537                         ptr = ref and ref.valid() and epg.lookupEventTime(ref, -1)
538                         if ptr:
539                                 epglist.append(ptr)
540                                 ptr = epg.lookupEventTime(ref, ptr.getBeginTime(), +1)
541                                 if ptr:
542                                         epglist.append(ptr)
543                 else:
544                         self.is_now_next = True
545                 if epglist:
546                         self.eventView = self.session.openWithCallback(self.closed, EventViewEPGSelect, self.epglist[0], ServiceReference(ref), self.eventViewCallback, self.openSingleServiceEPG, self.openMultiServiceEPG, self.openSimilarList)
547                         self.dlg_stack.append(self.eventView)
548                 else:
549                         print "no epg for the service avail.. so we show multiepg instead of eventinfo"
550                         self.openMultiServiceEPG(False)
551
552         def eventViewCallback(self, setEvent, setService, val): #used for now/next displaying
553                 epglist = self.epglist
554                 if len(epglist) > 1:
555                         tmp = epglist[0]
556                         epglist[0]=epglist[1]
557                         epglist[1]=tmp
558                         setEvent(epglist[0])
559
560 class InfoBarRdsDecoder:
561         """provides RDS and Rass support/display"""
562         def __init__(self):
563                 self.rds_display = self.session.instantiateDialog(RdsInfoDisplay)
564                 self.rass_interactive = None
565
566                 self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
567                         {
568                                 iPlayableService.evEnd: self.__serviceStopped,
569                                 iPlayableService.evUpdatedRassSlidePic: self.RassSlidePicChanged
570                         })
571
572                 self["RdsActions"] = ActionMap(["InfobarRdsActions"],
573                 {
574                         "startRassInteractive": self.startRassInteractive
575                 },-1)
576
577                 self["RdsActions"].setEnabled(False)
578
579                 self.onLayoutFinish.append(self.rds_display.show)
580                 self.rds_display.onRassInteractivePossibilityChanged.append(self.RassInteractivePossibilityChanged)
581
582         def RassInteractivePossibilityChanged(self, state):
583                 self["RdsActions"].setEnabled(state)
584
585         def RassSlidePicChanged(self):
586                 if not self.rass_interactive:
587                         service = self.session.nav.getCurrentService()
588                         decoder = service and service.rdsDecoder()
589                         if decoder:
590                                 decoder.showRassSlidePicture()
591
592         def __serviceStopped(self):
593                 if self.rass_interactive is not None:
594                         rass_interactive = self.rass_interactive
595                         self.rass_interactive = None
596                         rass_interactive.close()
597
598         def startRassInteractive(self):
599                 self.rds_display.hide()
600                 self.rass_interactive = self.session.openWithCallback(self.RassInteractiveClosed, RassInteractive)
601
602         def RassInteractiveClosed(self, *val):
603                 if self.rass_interactive is not None:
604                         self.rass_interactive = None
605                         self.RassSlidePicChanged()
606                 self.rds_display.show()
607
608 class InfoBarSeek:
609         """handles actions like seeking, pause"""
610
611         SEEK_STATE_PLAY = (0, 0, 0, ">")
612         SEEK_STATE_PAUSE = (1, 0, 0, "||")
613         SEEK_STATE_EOF = (1, 0, 0, "END")
614
615         def __init__(self, actionmap = "InfobarSeekActions", useSeekBackHack=True):
616                 self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
617                         {
618                                 iPlayableService.evSeekableStatusChanged: self.__seekableStatusChanged,
619                                 iPlayableService.evStart: self.__serviceStarted,
620
621                                 iPlayableService.evEOF: self.__evEOF,
622                                 iPlayableService.evSOF: self.__evSOF,
623                         })
624                 self.eofState = 0
625                 self.eofTimer = eTimer()
626                 self.eofTimer.timeout.get().append(self.doEof)
627                 self.eofInhibitTimer = eTimer()
628                 self.eofInhibitTimer.timeout.get().append(self.inhibitEof)
629
630                 self.minSpeedBackward = useSeekBackHack and 16 or 0
631
632                 class InfoBarSeekActionMap(HelpableActionMap):
633                         def __init__(self, screen, *args, **kwargs):
634                                 HelpableActionMap.__init__(self, screen, *args, **kwargs)
635                                 self.screen = screen
636
637                         def action(self, contexts, action):
638                                 print "action:", action
639                                 if action[:5] == "seek:":
640                                         time = int(action[5:])
641                                         self.screen.doSeekRelative(time * 90000)
642                                         return 1
643                                 elif action[:8] == "seekdef:":
644                                         key = int(action[8:])
645                                         time = [-config.seek.selfdefined_13.value, False, config.seek.selfdefined_13.value,
646                                                 -config.seek.selfdefined_46.value, False, config.seek.selfdefined_46.value,
647                                                 -config.seek.selfdefined_79.value, False, config.seek.selfdefined_79.value][key-1]
648                                         self.screen.doSeekRelative(time * 90000)
649                                         return 1                                        
650                                 else:
651                                         return HelpableActionMap.action(self, contexts, action)
652
653                 self["SeekActions"] = InfoBarSeekActionMap(self, actionmap,
654                         {
655                                 "playpauseService": self.playpauseService,
656                                 "pauseService": (self.pauseService, _("pause")),
657                                 "unPauseService": (self.unPauseService, _("continue")),
658
659                                 "seekFwd": (self.seekFwd, _("skip forward")),
660                                 "seekFwdManual": (self.seekFwdManual, _("skip forward (enter time)")),
661                                 "seekBack": (self.seekBack, _("skip backward")),
662                                 "seekBackManual": (self.seekBackManual, _("skip backward (enter time)"))
663                         }, prio=-1)
664                         # give them a little more priority to win over color buttons
665
666                 self["SeekActions"].setEnabled(False)
667
668                 self.seekstate = self.SEEK_STATE_PLAY
669                 self.lastseekstate = self.SEEK_STATE_PLAY
670
671                 self.onPlayStateChanged = [ ]
672
673                 self.lockedBecauseOfSkipping = False
674
675                 self.__seekableStatusChanged()
676
677         def makeStateForward(self, n):
678                 minspeed = config.seek.stepwise_minspeed.value
679                 repeat = int(config.seek.stepwise_repeat.value)
680                 if minspeed != "Never" and n >= int(minspeed) and repeat > 1:
681                         return (0, n * repeat, repeat, ">> %dx" % n)
682                 else:
683                         return (0, n, 0, ">> %dx" % n)
684
685         def makeStateBackward(self, n):
686                 minspeed = config.seek.stepwise_minspeed.value
687                 repeat = int(config.seek.stepwise_repeat.value)
688                 if self.minSpeedBackward and n < self.minSpeedBackward:
689                         r = (self.minSpeedBackward - 1)/ n + 1
690                         if minspeed != "Never" and n >= int(minspeed) and repeat > 1:
691                                 r = max(r, repeat)
692                         return (0, -n * r, r, "<< %dx" % n)
693                 elif minspeed != "Never" and n >= int(minspeed) and repeat > 1:
694                         return (0, -n * repeat, repeat, "<< %dx" % n)
695                 else:
696                         return (0, -n, 0, "<< %dx" % n)
697
698         def makeStateSlowMotion(self, n):
699                 return (0, 0, n, "/%d" % n)
700
701         def isStateForward(self, state):
702                 return state[1] > 1
703
704         def isStateBackward(self, state):
705                 return state[1] < 0
706
707         def isStateSlowMotion(self, state):
708                 return state[1] == 0 and state[2] > 1
709
710         def getHigher(self, n, lst):
711                 for x in lst:
712                         if x > n:
713                                 return x
714                 return False
715
716         def getLower(self, n, lst):
717                 lst = lst[:]
718                 lst.reverse()
719                 for x in lst:
720                         if x < n:
721                                 return x
722                 return False
723
724         def showAfterSeek(self):
725                 if isinstance(self, InfoBarShowHide):
726                         self.doShow()
727
728         def up(self):
729                 pass
730
731         def down(self):
732                 pass
733
734         def getSeek(self):
735                 service = self.session.nav.getCurrentService()
736                 if service is None:
737                         return None
738
739                 seek = service.seek()
740
741                 if seek is None or not seek.isCurrentlySeekable():
742                         return None
743
744                 return seek
745
746         def isSeekable(self):
747                 if self.getSeek() is None:
748                         return False
749                 return True
750
751         def __seekableStatusChanged(self):
752 #               print "seekable status changed!"
753                 if not self.isSeekable():
754                         self["SeekActions"].setEnabled(False)
755 #                       print "not seekable, return to play"
756                         self.setSeekState(self.SEEK_STATE_PLAY)
757                 else:
758                         self["SeekActions"].setEnabled(True)
759 #                       print "seekable"
760
761         def __serviceStarted(self):
762                 self.seekstate = self.SEEK_STATE_PLAY
763                 self.__seekableStatusChanged()
764                 if self.eofState != 0:
765                         self.eofTimer.stop()
766                 self.eofState = 0
767
768         def setSeekState(self, state):
769                 service = self.session.nav.getCurrentService()
770
771                 if service is None:
772                         return False
773
774                 if not self.isSeekable():
775                         if state not in [self.SEEK_STATE_PLAY, self.SEEK_STATE_PAUSE]:
776                                 state = self.SEEK_STATE_PLAY
777
778                 pauseable = service.pause()
779
780                 if pauseable is None:
781                         print "not pauseable."
782                         state = self.SEEK_STATE_PLAY
783
784                 oldstate = self.seekstate
785                 self.seekstate = state
786
787                 for i in (0, 1, 2):
788                         if oldstate[i] != self.seekstate[i]:
789                                 (self.session.nav.pause, pauseable.setFastForward, pauseable.setSlowMotion)[i](self.seekstate[i])
790
791                 for c in self.onPlayStateChanged:
792                         c(self.seekstate)
793
794                 self.checkSkipShowHideLock()
795
796                 return True
797
798         def playpauseService(self):
799                 if self.seekstate != self.SEEK_STATE_PLAY:
800                         self.unPauseService()
801                 else:
802                         self.pauseService()
803
804         def pauseService(self):
805                 if self.seekstate == self.SEEK_STATE_PAUSE:
806                         if config.seek.on_pause.value == "play":
807                                 self.unPauseService()
808                         elif config.seek.on_pause.value == "step":
809                                 self.doSeekRelative(0)
810                         elif config.seek.on_pause.value == "last":
811                                 self.setSeekState(self.lastseekstate)
812                                 self.lastseekstate = self.SEEK_STATE_PLAY
813                 else:
814                         if self.seekstate != self.SEEK_STATE_EOF:
815                                 self.lastseekstate = self.seekstate
816                         self.setSeekState(self.SEEK_STATE_PAUSE);
817
818         def unPauseService(self):
819                 print "unpause"
820                 if self.seekstate == self.SEEK_STATE_PLAY:
821                         return 0
822                 self.setSeekState(self.SEEK_STATE_PLAY)
823
824         def doSeek(self, pts):
825                 seekable = self.getSeek()
826                 if seekable is None:
827                         return
828                 prevstate = self.seekstate
829                 if self.eofState == 1:
830                         self.eofState = 2
831                         self.inhibitEof()
832                 if self.seekstate == self.SEEK_STATE_EOF:
833                         if prevstate == self.SEEK_STATE_PAUSE:
834                                 self.setSeekState(self.SEEK_STATE_PAUSE)
835                         else:
836                                 self.setSeekState(self.SEEK_STATE_PLAY)
837                 self.eofInhibitTimer.start(200, True)
838                 seekable.seekTo(pts)
839
840         def doSeekRelative(self, pts):
841                 seekable = self.getSeek()
842                 if seekable is None:
843                         return
844                 prevstate = self.seekstate
845                 if self.eofState == 1:
846                         self.eofState = 2
847                         self.inhibitEof()
848                 if self.seekstate == self.SEEK_STATE_EOF:
849                         if prevstate == self.SEEK_STATE_PAUSE:
850                                 self.setSeekState(self.SEEK_STATE_PAUSE)
851                         else:
852                                 self.setSeekState(self.SEEK_STATE_PLAY)
853                 self.eofInhibitTimer.start(200, True)
854                 seekable.seekRelative(pts<0 and -1 or 1, abs(pts))
855                 if abs(pts) > 100 and config.usage.show_infobar_on_skip.value:
856                         self.showAfterSeek()
857
858         def seekFwd(self):
859                 if self.seekstate == self.SEEK_STATE_PLAY:
860                         self.setSeekState(self.makeStateForward(int(config.seek.enter_forward.value)))
861                 elif self.seekstate == self.SEEK_STATE_PAUSE:
862                         if len(config.seek.speeds_slowmotion.value):
863                                 self.setSeekState(self.makeStateSlowMotion(config.seek.speeds_slowmotion.value[-1]))
864                         else:
865                                 self.setSeekState(self.makeStateForward(int(config.seek.enter_forward.value)))
866                 elif self.seekstate == self.SEEK_STATE_EOF:
867                         pass
868                 elif self.isStateForward(self.seekstate):
869                         speed = self.seekstate[1]
870                         if self.seekstate[2]:
871                                 speed /= self.seekstate[2]
872                         speed = self.getHigher(speed, config.seek.speeds_forward.value) or config.seek.speeds_forward.value[-1]
873                         self.setSeekState(self.makeStateForward(speed))
874                 elif self.isStateBackward(self.seekstate):
875                         speed = -self.seekstate[1]
876                         if self.seekstate[2]:
877                                 speed /= self.seekstate[2]
878                         speed = self.getLower(speed, config.seek.speeds_backward.value)
879                         if speed:
880                                 self.setSeekState(self.makeStateBackward(speed))
881                         else:
882                                 self.setSeekState(self.SEEK_STATE_PLAY)
883                 elif self.isStateSlowMotion(self.seekstate):
884                         speed = self.getLower(self.seekstate[2], config.seek.speeds_slowmotion.value) or config.seek.speeds_slowmotion.value[0]
885                         self.setSeekState(self.makeStateSlowMotion(speed))
886
887         def seekBack(self):
888                 if self.seekstate == self.SEEK_STATE_PLAY:
889                         self.setSeekState(self.makeStateBackward(int(config.seek.enter_backward.value)))
890                 elif self.seekstate == self.SEEK_STATE_EOF:
891                         self.setSeekState(self.makeStateBackward(int(config.seek.enter_backward.value)))
892                         self.doSeekRelative(-6)
893                 elif self.seekstate == self.SEEK_STATE_PAUSE:
894                         self.doSeekRelative(-3)
895                 elif self.isStateForward(self.seekstate):
896                         speed = self.seekstate[1]
897                         if self.seekstate[2]:
898                                 speed /= self.seekstate[2]
899                         speed = self.getLower(speed, config.seek.speeds_forward.value)
900                         if speed:
901                                 self.setSeekState(self.makeStateForward(speed))
902                         else:
903                                 self.setSeekState(self.SEEK_STATE_PLAY)
904                 elif self.isStateBackward(self.seekstate):
905                         speed = -self.seekstate[1]
906                         if self.seekstate[2]:
907                                 speed /= self.seekstate[2]
908                         speed = self.getHigher(speed, config.seek.speeds_backward.value) or config.seek.speeds_backward.value[-1]
909                         self.setSeekState(self.makeStateBackward(speed))
910                 elif self.isStateSlowMotion(self.seekstate):
911                         speed = self.getHigher(self.seekstate[2], config.seek.speeds_slowmotion.value)
912                         if speed:
913                                 self.setSeekState(self.makeStateSlowMotion(speed))
914                         else:
915                                 self.setSeekState(self.SEEK_STATE_PAUSE)
916
917         def seekFwdManual(self):
918                 self.session.openWithCallback(self.fwdSeekTo, MinuteInput)
919
920         def fwdSeekTo(self, minutes):
921                 print "Seek", minutes, "minutes forward"
922                 self.doSeekRelative(minutes * 60 * 90000)
923
924         def seekBackManual(self):
925                 self.session.openWithCallback(self.rwdSeekTo, MinuteInput)
926
927         def rwdSeekTo(self, minutes):
928                 print "rwdSeekTo"
929                 self.doSeekRelative(-minutes * 60 * 90000)
930
931         def checkSkipShowHideLock(self):
932                 wantlock = self.seekstate != self.SEEK_STATE_PLAY
933
934                 if config.usage.show_infobar_on_skip.value:
935                         if self.lockedBecauseOfSkipping and not wantlock:
936                                 self.unlockShow()
937                                 self.lockedBecauseOfSkipping = False
938
939                         if wantlock and not self.lockedBecauseOfSkipping:
940                                 self.lockShow()
941                                 self.lockedBecauseOfSkipping = True
942
943         def calcRemainingTime(self):
944                 seekable = self.getSeek()
945                 if seekable is not None:
946                         len = seekable.getLength()
947                         try:
948                                 tmp = self.cueGetEndCutPosition()
949                                 if tmp:
950                                         len = [False, tmp]
951                         except:
952                                 pass
953                         pos = seekable.getPlayPosition()
954                         speednom = self.seekstate[1] or 1
955                         speedden = self.seekstate[2] or 1
956                         if not len[0] and not pos[0]:
957                                 if len[1] <= pos[1]:
958                                         return 0
959                                 time = (len[1] - pos[1])*speedden/(90*speednom)
960                                 return time
961                 return False
962                 
963         def __evEOF(self):
964                 if self.eofState == 0 and self.seekstate != self.SEEK_STATE_EOF:
965                         self.eofState = 1
966                         time = self.calcRemainingTime()
967                         if not time:
968                                 time = 3000   # Failed to calc, use default
969                         elif time == 0:
970                                 time = 300    # Passed end, shortest wait
971                         elif time > 15000:
972                                 self.eofState = -2  # Too long, block eof
973                                 time = 15000
974                         else:
975                                 time += 1000  # Add margin
976                         self.eofTimer.start(time, True)
977
978         def inhibitEof(self):
979                 if self.eofState >= 1:
980                         self.eofState = -self.eofState
981                         self.eofTimer.stop()
982                         self.doEof()
983
984         def doEof(self):
985                 if self.seekstate == self.SEEK_STATE_EOF:
986                         return
987                 if self.eofState == -2 or self.isStateBackward(self.seekstate):
988                         self.eofState = 0
989                         return
990
991                 # if we are seeking, we try to end up ~1s before the end, and pause there.
992                 eofstate = self.eofState
993                 seekstate = self.seekstate
994                 self.eofState = 0
995                 if not self.seekstate == self.SEEK_STATE_PAUSE:
996                         self.setSeekState(self.SEEK_STATE_EOF)
997                 if eofstate == -1 or not seekstate in [self.SEEK_STATE_PLAY, self.SEEK_STATE_PAUSE]:
998                         seekable = self.getSeek()
999                         if seekable is not None:
1000                                 seekable.seekTo(-1)
1001                 if eofstate == 1 and seekstate == self.SEEK_STATE_PLAY:
1002                         self.doEofInternal(True)
1003                 else:
1004                         self.doEofInternal(False)
1005
1006         def doEofInternal(self, playing):
1007                 pass            # Defined in subclasses
1008
1009         def __evSOF(self):
1010                 self.setSeekState(self.SEEK_STATE_PLAY)
1011                 self.doSeek(0)
1012
1013 from Screens.PVRState import PVRState, TimeshiftState
1014
1015 class InfoBarPVRState:
1016         def __init__(self, screen=PVRState):
1017                 self.onPlayStateChanged.append(self.__playStateChanged)
1018                 self.pvrStateDialog = self.session.instantiateDialog(screen)
1019                 self.onShow.append(self._mayShow)
1020                 self.onHide.append(self.pvrStateDialog.hide)
1021
1022         def _mayShow(self):
1023                 if self.execing and self.seekstate != self.SEEK_STATE_PLAY:
1024                         self.pvrStateDialog.show()
1025
1026         def __playStateChanged(self, state):
1027                 playstateString = state[3]
1028                 self.pvrStateDialog["state"].setText(playstateString)
1029                 
1030                 # if we return into "PLAY" state, ensure that the dialog gets hidden if there will be no infobar displayed
1031                 if not config.usage.show_infobar_on_skip.value and self.seekstate == self.SEEK_STATE_PLAY:
1032                         self.pvrStateDialog.hide()
1033                 else:
1034                         self._mayShow()
1035                         
1036
1037 class InfoBarTimeshiftState(InfoBarPVRState):
1038         def __init__(self):
1039                 InfoBarPVRState.__init__(self, screen=TimeshiftState)
1040
1041         def _mayShow(self):
1042                 if self.execing and self.timeshift_enabled and self.seekstate != self.SEEK_STATE_PLAY:
1043                         self.pvrStateDialog.show()
1044
1045 class InfoBarShowMovies:
1046
1047         # i don't really like this class.
1048         # it calls a not further specified "movie list" on up/down/movieList,
1049         # so this is not more than an action map
1050         def __init__(self):
1051                 self["MovieListActions"] = HelpableActionMap(self, "InfobarMovieListActions",
1052                         {
1053                                 "movieList": (self.showMovies, _("movie list")),
1054                                 "up": (self.showMovies, _("movie list")),
1055                                 "down": (self.showMovies, _("movie list"))
1056                         })
1057
1058 # InfoBarTimeshift requires InfoBarSeek, instantiated BEFORE!
1059
1060 # Hrmf.
1061 #
1062 # Timeshift works the following way:
1063 #                                         demux0   demux1                    "TimeshiftActions" "TimeshiftActivateActions" "SeekActions"
1064 # - normal playback                       TUNER    unused      PLAY               enable                disable              disable
1065 # - user presses "yellow" button.         FILE     record      PAUSE              enable                disable              enable
1066 # - user presess pause again              FILE     record      PLAY               enable                disable              enable
1067 # - user fast forwards                    FILE     record      FF                 enable                disable              enable
1068 # - end of timeshift buffer reached       TUNER    record      PLAY               enable                enable               disable
1069 # - user backwards                        FILE     record      BACK  # !!         enable                disable              enable
1070 #
1071
1072 # in other words:
1073 # - when a service is playing, pressing the "timeshiftStart" button ("yellow") enables recording ("enables timeshift"),
1074 # freezes the picture (to indicate timeshift), sets timeshiftMode ("activates timeshift")
1075 # now, the service becomes seekable, so "SeekActions" are enabled, "TimeshiftEnableActions" are disabled.
1076 # - the user can now PVR around
1077 # - if it hits the end, the service goes into live mode ("deactivates timeshift", it's of course still "enabled")
1078 # the service looses it's "seekable" state. It can still be paused, but just to activate timeshift right
1079 # after!
1080 # the seek actions will be disabled, but the timeshiftActivateActions will be enabled
1081 # - if the user rewinds, or press pause, timeshift will be activated again
1082
1083 # note that a timeshift can be enabled ("recording") and
1084 # activated (currently time-shifting).
1085
1086 class InfoBarTimeshift:
1087         def __init__(self):
1088                 self["TimeshiftActions"] = HelpableActionMap(self, "InfobarTimeshiftActions",
1089                         {
1090                                 "timeshiftStart": (self.startTimeshift, _("start timeshift")),  # the "yellow key"
1091                                 "timeshiftStop": (self.stopTimeshift, _("stop timeshift"))      # currently undefined :), probably 'TV'
1092                         }, prio=1)
1093                 self["TimeshiftActivateActions"] = ActionMap(["InfobarTimeshiftActivateActions"],
1094                         {
1095                                 "timeshiftActivateEnd": self.activateTimeshiftEnd, # something like "rewind key"
1096                                 "timeshiftActivateEndAndPause": self.activateTimeshiftEndAndPause  # something like "pause key"
1097                         }, prio=-1) # priority over record
1098
1099                 self.timeshift_enabled = 0
1100                 self.timeshift_state = 0
1101                 self.ts_rewind_timer = eTimer()
1102                 self.ts_rewind_timer.callback.append(self.rewindService)
1103
1104                 self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
1105                         {
1106                                 iPlayableService.evStart: self.__serviceStarted,
1107                                 iPlayableService.evSeekableStatusChanged: self.__seekableStatusChanged
1108                         })
1109
1110         def getTimeshift(self):
1111                 service = self.session.nav.getCurrentService()
1112                 return service and service.timeshift()
1113
1114         def startTimeshift(self):
1115                 print "enable timeshift"
1116                 ts = self.getTimeshift()
1117                 if ts is None:
1118                         self.session.open(MessageBox, _("Timeshift not possible!"), MessageBox.TYPE_ERROR)
1119                         print "no ts interface"
1120                         return 0
1121
1122                 if self.timeshift_enabled:
1123                         print "hu, timeshift already enabled?"
1124                 else:
1125                         if not ts.startTimeshift():
1126                                 self.timeshift_enabled = 1
1127
1128                                 # we remove the "relative time" for now.
1129                                 #self.pvrStateDialog["timeshift"].setRelative(time.time())
1130
1131                                 # PAUSE.
1132                                 #self.setSeekState(self.SEEK_STATE_PAUSE)
1133                                 self.activateTimeshiftEnd(False)
1134
1135                                 # enable the "TimeshiftEnableActions", which will override
1136                                 # the startTimeshift actions
1137                                 self.__seekableStatusChanged()
1138                         else:
1139                                 print "timeshift failed"
1140
1141         def stopTimeshift(self):
1142                 if not self.timeshift_enabled:
1143                         return 0
1144                 print "disable timeshift"
1145                 ts = self.getTimeshift()
1146                 if ts is None:
1147                         return 0
1148                 self.session.openWithCallback(self.stopTimeshiftConfirmed, MessageBox, _("Stop Timeshift?"), MessageBox.TYPE_YESNO)
1149
1150         def stopTimeshiftConfirmed(self, confirmed):
1151                 if not confirmed:
1152                         return
1153
1154                 ts = self.getTimeshift()
1155                 if ts is None:
1156                         return
1157
1158                 ts.stopTimeshift()
1159                 self.timeshift_enabled = 0
1160
1161                 # disable actions
1162                 self.__seekableStatusChanged()
1163
1164         # activates timeshift, and seeks to (almost) the end
1165         def activateTimeshiftEnd(self, back = True):
1166                 ts = self.getTimeshift()
1167                 print "activateTimeshiftEnd"
1168
1169                 if ts is None:
1170                         return
1171
1172                 if ts.isTimeshiftActive():
1173                         print "!! activate timeshift called - but shouldn't this be a normal pause?"
1174                         self.pauseService()
1175                 else:
1176                         print "play, ..."
1177                         ts.activateTimeshift() # activate timeshift will automatically pause
1178                         self.setSeekState(self.SEEK_STATE_PAUSE)
1179
1180                 if back:
1181                         self.doSeek(-5) # seek some gops before end
1182                         self.ts_rewind_timer.start(200, 1)
1183                 else:
1184                         self.doSeek(-1) # seek 1 gop before end
1185
1186         def rewindService(self):
1187                 self.setSeekState(self.makeStateBackward(int(config.seek.enter_backward.value)))
1188
1189         # same as activateTimeshiftEnd, but pauses afterwards.
1190         def activateTimeshiftEndAndPause(self):
1191                 print "activateTimeshiftEndAndPause"
1192                 #state = self.seekstate
1193                 self.activateTimeshiftEnd(False)
1194
1195         def __seekableStatusChanged(self):
1196                 enabled = False
1197
1198 #               print "self.isSeekable", self.isSeekable()
1199 #               print "self.timeshift_enabled", self.timeshift_enabled
1200
1201                 # when this service is not seekable, but timeshift
1202                 # is enabled, this means we can activate
1203                 # the timeshift
1204                 if not self.isSeekable() and self.timeshift_enabled:
1205                         enabled = True
1206
1207 #               print "timeshift activate:", enabled
1208                 self["TimeshiftActivateActions"].setEnabled(enabled)
1209
1210         def __serviceStarted(self):
1211                 self.timeshift_enabled = False
1212                 self.__seekableStatusChanged()
1213
1214 from Screens.PiPSetup import PiPSetup
1215
1216 class InfoBarExtensions:
1217         EXTENSION_SINGLE = 0
1218         EXTENSION_LIST = 1
1219
1220         def __init__(self):
1221                 self.list = []
1222
1223                 self["InstantExtensionsActions"] = HelpableActionMap(self, "InfobarExtensions",
1224                         {
1225                                 "extensions": (self.showExtensionSelection, _("view extensions...")),
1226                         }, 1) # lower priority
1227
1228         def addExtension(self, extension, key = None, type = EXTENSION_SINGLE):
1229                 self.list.append((type, extension, key))
1230
1231         def updateExtension(self, extension, key = None):
1232                 self.extensionsList.append(extension)
1233                 if key is not None:
1234                         if self.extensionKeys.has_key(key):
1235                                 key = None
1236
1237                 if key is None:
1238                         for x in self.availableKeys:
1239                                 if not self.extensionKeys.has_key(x):
1240                                         key = x
1241                                         break
1242
1243                 if key is not None:
1244                         self.extensionKeys[key] = len(self.extensionsList) - 1
1245
1246         def updateExtensions(self):
1247                 self.extensionsList = []
1248                 self.availableKeys = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "red", "green", "yellow", "blue" ]
1249                 self.extensionKeys = {}
1250                 for x in self.list:
1251                         if x[0] == self.EXTENSION_SINGLE:
1252                                 self.updateExtension(x[1], x[2])
1253                         else:
1254                                 for y in x[1]():
1255                                         self.updateExtension(y[0], y[1])
1256
1257
1258         def showExtensionSelection(self):
1259                 self.updateExtensions()
1260                 extensionsList = self.extensionsList[:]
1261                 keys = []
1262                 list = []
1263                 for x in self.availableKeys:
1264                         if self.extensionKeys.has_key(x):
1265                                 entry = self.extensionKeys[x]
1266                                 extension = self.extensionsList[entry]
1267                                 if extension[2]():
1268                                         name = str(extension[0]())
1269                                         list.append((extension[0](), extension))
1270                                         keys.append(x)
1271                                         extensionsList.remove(extension)
1272                                 else:
1273                                         extensionsList.remove(extension)
1274                 list.extend([(x[0](), x) for x in extensionsList])
1275
1276                 keys += [""] * len(extensionsList)
1277                 self.session.openWithCallback(self.extensionCallback, ChoiceBox, title=_("Please choose an extension..."), list = list, keys = keys)
1278
1279         def extensionCallback(self, answer):
1280                 if answer is not None:
1281                         answer[1][1]()
1282
1283 from Tools.BoundFunction import boundFunction
1284
1285 # depends on InfoBarExtensions
1286
1287 class InfoBarPlugins:
1288         def __init__(self):
1289                 self.addExtension(extension = self.getPluginList, type = InfoBarExtensions.EXTENSION_LIST)
1290
1291         def getPluginName(self, name):
1292                 return name
1293
1294         def getPluginList(self):
1295                 return [((boundFunction(self.getPluginName, p.name), boundFunction(self.runPlugin, p), lambda: True), None) for p in plugins.getPlugins(where = PluginDescriptor.WHERE_EXTENSIONSMENU)]
1296
1297         def runPlugin(self, plugin):
1298                 if isinstance(self, InfoBarChannelSelection):
1299                         plugin(session = self.session, servicelist = self.servicelist)
1300                 else:
1301                         plugin(session = self.session)
1302
1303 from Components.Task import job_manager
1304 class InfoBarJobman:
1305         def __init__(self):
1306                 self.addExtension(extension = self.getJobList, type = InfoBarExtensions.EXTENSION_LIST)
1307
1308         def getJobList(self):
1309                 return [((boundFunction(self.getJobName, job), boundFunction(self.showJobView, job), lambda: True), None) for job in job_manager.getPendingJobs()]
1310
1311         def getJobName(self, job):
1312                 return "%s: %s (%d%%)" % (job.getStatustext(), job.name, int(100*job.progress/float(job.end)))
1313
1314         def showJobView(self, job):
1315                 from Screens.TaskView import JobView
1316                 job_manager.in_background = False
1317                 self.session.openWithCallback(self.JobViewCB, JobView, job)
1318         
1319         def JobViewCB(self, in_background):
1320                 job_manager.in_background = in_background
1321
1322 # depends on InfoBarExtensions
1323 class InfoBarSleepTimer:
1324         def __init__(self):
1325                 self.addExtension((self.getSleepTimerName, self.showSleepTimerSetup, lambda: True), "1")
1326
1327         def getSleepTimerName(self):
1328                 return _("Sleep Timer")
1329
1330         def showSleepTimerSetup(self):
1331                 self.session.open(SleepTimerEdit)
1332
1333 # depends on InfoBarExtensions
1334 class InfoBarPiP:
1335         def __init__(self):
1336                 self.session.pipshown = False
1337                 if SystemInfo.get("NumVideoDecoders", 1) > 1:
1338                         self.addExtension((self.getShowHideName, self.showPiP, lambda: True), "blue")
1339                         self.addExtension((self.getMoveName, self.movePiP, self.pipShown), "green")
1340                         self.addExtension((self.getSwapName, self.swapPiP, self.pipShown), "yellow")
1341
1342         def pipShown(self):
1343                 return self.session.pipshown
1344
1345         def pipHandles0Action(self):
1346                 return self.pipShown() and config.usage.pip_zero_button.value != "standard"
1347
1348         def getShowHideName(self):
1349                 if self.session.pipshown:
1350                         return _("Disable Picture in Picture")
1351                 else:
1352                         return _("Activate Picture in Picture")
1353
1354         def getSwapName(self):
1355                 return _("Swap Services")
1356
1357         def getMoveName(self):
1358                 return _("Move Picture in Picture")
1359
1360         def showPiP(self):
1361                 if self.session.pipshown:
1362                         del self.session.pip
1363                         self.session.pipshown = False
1364                 else:
1365                         self.session.pip = self.session.instantiateDialog(PictureInPicture)
1366                         self.session.pip.show()
1367                         newservice = self.session.nav.getCurrentlyPlayingServiceReference()
1368                         if self.session.pip.playService(newservice):
1369                                 self.session.pipshown = True
1370                                 self.session.pip.servicePath = self.servicelist.getCurrentServicePath()
1371                         else:
1372                                 self.session.pipshown = False
1373                                 del self.session.pip
1374                         self.session.nav.playService(newservice)
1375
1376         def swapPiP(self):
1377                 swapservice = self.session.nav.getCurrentlyPlayingServiceReference()
1378                 if self.session.pip.servicePath:
1379                         servicepath = self.servicelist.getCurrentServicePath()
1380                         ref=servicepath[len(servicepath)-1]
1381                         pipref=self.session.pip.getCurrentService()
1382                         self.session.pip.playService(swapservice)
1383                         self.servicelist.setCurrentServicePath(self.session.pip.servicePath)
1384                         if pipref.toString() != ref.toString(): # is a subservice ?
1385                                 self.session.nav.stopService() # stop portal
1386                                 self.session.nav.playService(pipref) # start subservice
1387                         self.session.pip.servicePath=servicepath
1388
1389         def movePiP(self):
1390                 self.session.open(PiPSetup, pip = self.session.pip)
1391
1392         def pipDoHandle0Action(self):
1393                 use = config.usage.pip_zero_button.value
1394                 if "swap" == use:
1395                         self.swapPiP()
1396                 elif "swapstop" == use:
1397                         self.swapPiP()
1398                         self.showPiP()
1399                 elif "stop" == use:
1400                         self.showPiP()
1401
1402 from RecordTimer import parseEvent, RecordTimerEntry
1403
1404 class InfoBarInstantRecord:
1405         """Instant Record - handles the instantRecord action in order to
1406         start/stop instant records"""
1407         def __init__(self):
1408                 self["InstantRecordActions"] = HelpableActionMap(self, "InfobarInstantRecord",
1409                         {
1410                                 "instantRecord": (self.instantRecord, _("Instant Record...")),
1411                         })
1412                 self.recording = []
1413
1414         def stopCurrentRecording(self, entry = -1):
1415                 if entry is not None and entry != -1:
1416                         self.session.nav.RecordTimer.removeEntry(self.recording[entry])
1417                         self.recording.remove(self.recording[entry])
1418
1419         def startInstantRecording(self, limitEvent = False):
1420                 serviceref = self.session.nav.getCurrentlyPlayingServiceReference()
1421
1422                 # try to get event info
1423                 event = None
1424                 try:
1425                         service = self.session.nav.getCurrentService()
1426                         epg = eEPGCache.getInstance()
1427                         event = epg.lookupEventTime(serviceref, -1, 0)
1428                         if event is None:
1429                                 info = service.info()
1430                                 ev = info.getEvent(0)
1431                                 event = ev
1432                 except:
1433                         pass
1434
1435                 begin = int(time())
1436                 end = begin + 3600      # dummy
1437                 name = "instant record"
1438                 description = ""
1439                 eventid = None
1440
1441                 if event is not None:
1442                         curEvent = parseEvent(event)
1443                         name = curEvent[2]
1444                         description = curEvent[3]
1445                         eventid = curEvent[4]
1446                         if limitEvent:
1447                                 end = curEvent[1]
1448                 else:
1449                         if limitEvent:
1450                                 self.session.open(MessageBox, _("No event info found, recording indefinitely."), MessageBox.TYPE_INFO)
1451
1452                 if isinstance(serviceref, eServiceReference):
1453                         serviceref = ServiceReference(serviceref)
1454
1455                 recording = RecordTimerEntry(serviceref, begin, end, name, description, eventid, dirname = config.movielist.last_videodir.value)
1456                 recording.dontSave = True
1457                 
1458                 if event is None or limitEvent == False:
1459                         recording.autoincrease = True
1460                         if recording.setAutoincreaseEnd():
1461                                 self.session.nav.RecordTimer.record(recording)
1462                                 self.recording.append(recording)
1463                 else:
1464                                 simulTimerList = self.session.nav.RecordTimer.record(recording)
1465                                 if simulTimerList is not None:  # conflict with other recording
1466                                         name = simulTimerList[1].name
1467                                         name_date = ' '.join((name, strftime('%c', localtime(simulTimerList[1].begin))))
1468                                         print "[TIMER] conflicts with", name_date
1469                                         recording.autoincrease = True   # start with max available length, then increment
1470                                         if recording.setAutoincreaseEnd():
1471                                                 self.session.nav.RecordTimer.record(recording)
1472                                                 self.recording.append(recording)
1473                                                 self.session.open(MessageBox, _("Record time limited due to conflicting timer %s") % name_date, MessageBox.TYPE_INFO)
1474                                         else:
1475                                                 self.session.open(MessageBox, _("Couldn't record due to conflicting timer %s") % name, MessageBox.TYPE_INFO)
1476                                         recording.autoincrease = False
1477                                 else:
1478                                         self.recording.append(recording)
1479
1480         def isInstantRecordRunning(self):
1481                 print "self.recording:", self.recording
1482                 if len(self.recording) > 0:
1483                         for x in self.recording:
1484                                 if x.isRunning():
1485                                         return True
1486                 return False
1487
1488         def recordQuestionCallback(self, answer):
1489                 print "pre:\n", self.recording
1490
1491                 if answer is None or answer[1] == "no":
1492                         return
1493                 list = []
1494                 recording = self.recording[:]
1495                 for x in recording:
1496                         if not x in self.session.nav.RecordTimer.timer_list:
1497                                 self.recording.remove(x)
1498                         elif x.dontSave and x.isRunning():
1499                                 list.append((x, False))
1500
1501                 if answer[1] == "changeduration":
1502                         if len(self.recording) == 1:
1503                                 self.changeDuration(0)
1504                         else:
1505                                 self.session.openWithCallback(self.changeDuration, TimerSelection, list)
1506                 elif answer[1] == "changeendtime":
1507                         if len(self.recording) == 1:
1508                                 self.setEndtime(0)
1509                         else:
1510                                 self.session.openWithCallback(self.setEndtime, TimerSelection, list)
1511                 elif answer[1] == "stop":
1512                         if len(self.recording) == 1:
1513                                 self.stopCurrentRecording(0)
1514                         else:
1515                                 self.session.openWithCallback(self.stopCurrentRecording, TimerSelection, list)
1516                 elif answer[1] in ( "indefinitely" , "manualduration", "manualendtime", "event"):
1517                         self.startInstantRecording(limitEvent = answer[1] in ("event", "manualendtime") or False)
1518                         if answer[1] == "manualduration":
1519                                 self.changeDuration(len(self.recording)-1)
1520                         elif answer[1] == "manualendtime":
1521                                 self.setEndtime(len(self.recording)-1)
1522                 print "after:\n", self.recording
1523
1524         def setEndtime(self, entry):
1525                 if entry is not None:
1526                         self.selectedEntry = entry
1527                         self.endtime=ConfigClock(default = self.recording[self.selectedEntry].end)
1528                         dlg = self.session.openWithCallback(self.TimeDateInputClosed, TimeDateInput, self.endtime)
1529                         dlg.setTitle(_("Please change recording endtime"))
1530
1531         def TimeDateInputClosed(self, ret):
1532                 if len(ret) > 1:
1533                         if ret[0]:
1534                                 localendtime = localtime(ret[1])
1535                                 print "stopping recording at", strftime("%c", localendtime)
1536                                 if self.recording[self.selectedEntry].end != ret[1]:
1537                                         self.recording[self.selectedEntry].autoincrease = False
1538                                 self.recording[self.selectedEntry].end = ret[1]
1539                                 self.session.nav.RecordTimer.timeChanged(self.recording[self.selectedEntry])
1540
1541         def changeDuration(self, entry):
1542                 if entry is not None:
1543                         self.selectedEntry = entry
1544                         self.session.openWithCallback(self.inputCallback, InputBox, title=_("How many minutes do you want to record?"), text="5", maxSize=False, type=Input.NUMBER)
1545
1546         def inputCallback(self, value):
1547                 if value is not None:
1548                         print "stopping recording after", int(value), "minutes."
1549                         entry = self.recording[self.selectedEntry]
1550                         if int(value) != 0:
1551                                 entry.autoincrease = False
1552                         entry.end = int(time()) + 60 * int(value)
1553                         self.session.nav.RecordTimer.timeChanged(entry)
1554
1555         def instantRecord(self):
1556                 dir = config.movielist.last_videodir.value
1557                 if not fileExists(dir, 'w'):
1558                         dir = resolveFilename(SCOPE_HDD)
1559                 try:
1560                         stat = os_stat(dir)
1561                 except:
1562                         # XXX: this message is a little odd as we might be recording to a remote device
1563                         self.session.open(MessageBox, _("No HDD found or HDD not initialized!"), MessageBox.TYPE_ERROR)
1564                         return
1565
1566                 if self.isInstantRecordRunning():
1567                         self.session.openWithCallback(self.recordQuestionCallback, ChoiceBox, \
1568                                 title=_("A recording is currently running.\nWhat do you want to do?"), \
1569                                 list=((_("add recording (stop after current event)"), "event"), \
1570                                 (_("add recording (enter recording duration)"), "manualduration"), \
1571                                 (_("add recording (enter recording endtime)"), "manualendtime"), \
1572                                 (_("add recording (indefinitely)"), "indefinitely"), \
1573                                 (_("change recording (duration)"), "changeduration"), \
1574                                 (_("change recording (endtime)"), "changeendtime"), \
1575                                 (_("stop recording"), "stop"), \
1576                                 (_("do nothing"), "no")))
1577                 else:
1578                         self.session.openWithCallback(self.recordQuestionCallback, ChoiceBox, \
1579                                 title=_("Start recording?"), \
1580                                 list=((_("add recording (stop after current event)"), "event"), \
1581                                 (_("add recording (enter recording duration)"), "manualduration"), \
1582                                 (_("add recording (enter recording endtime)"), "manualendtime"), \
1583                                 (_("add recording (indefinitely)"), "indefinitely"), \
1584                                 (_("don't record"), "no")))
1585
1586 from Tools.ISO639 import LanguageCodes
1587
1588 class InfoBarAudioSelection:
1589         def __init__(self):
1590                 self["AudioSelectionAction"] = HelpableActionMap(self, "InfobarAudioSelectionActions",
1591                         {
1592                                 "audioSelection": (self.audioSelection, _("Audio Options...")),
1593                         })
1594
1595         def audioSelection(self):
1596                 service = self.session.nav.getCurrentService()
1597                 self.audioTracks = audio = service and service.audioTracks()
1598                 n = audio and audio.getNumberOfTracks() or 0
1599                 tlist = []
1600                 if n > 0:
1601                         self.audioChannel = service.audioChannel()
1602
1603                         idx = 0
1604                         while idx < n:
1605                                 i = audio.getTrackInfo(idx)
1606                                 language = i.getLanguage()
1607                                 description = i.getDescription()
1608
1609                                 if LanguageCodes.has_key(language):
1610                                         language = LanguageCodes[language][0]
1611
1612                                 if len(description):
1613                                         description += " (" + language + ")"
1614                                 else:
1615                                         description = language
1616
1617                                 tlist.append((description, idx))
1618                                 idx += 1
1619
1620                         tlist.sort(key=lambda x: x[0])
1621
1622                         selectedAudio = self.audioTracks.getCurrentTrack()
1623
1624                         selection = 0
1625
1626                         for x in tlist:
1627                                 if x[1] != selectedAudio:
1628                                         selection += 1
1629                                 else:
1630                                         break
1631
1632                         if SystemInfo["CanDownmixAC3"]:
1633                                 tlist = [(_("AC3 downmix") + " - " +[_("Off"), _("On")][config.av.downmix_ac3.value and 1 or 0], "CALLFUNC", self.changeAC3Downmix),
1634                                         ([_("Left"), _("Stereo"), _("Right")][self.audioChannel.getCurrentChannel()], "mode"),
1635                                         ("--", "")] + tlist
1636                                 keys = [ "red", "green", "", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] + [""]*n
1637                                 selection += 3
1638                         else:
1639                                 tlist = [([_("Left"), _("Stereo"), _("Right")][self.audioChannel.getCurrentChannel()], "mode"), ("--", "")] + tlist
1640                                 keys = [ "red", "", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] + [""]*n
1641                                 selection += 2
1642                         self.session.openWithCallback(self.audioSelected, ChoiceBox, title=_("Select audio track"), list = tlist, selection = selection, keys = keys)
1643                 else:
1644                         del self.audioTracks
1645
1646         def changeAC3Downmix(self, arg):
1647                 choicelist = self.session.current_dialog["list"]
1648                 list = choicelist.list
1649                 t = list[0][1]
1650                 list[0][1]=(t[0], t[1], t[2], t[3], t[4], t[5], t[6],
1651                         _("AC3 downmix") + " - " +[_("On"), _("Off")][config.av.downmix_ac3.value and 1 or 0])
1652                 choicelist.setList(list)
1653                 if config.av.downmix_ac3.value:
1654                         config.av.downmix_ac3.value = False
1655                 else:
1656                         config.av.downmix_ac3.value = True
1657                 config.av.downmix_ac3.save()
1658
1659         def audioSelected(self, audio):
1660                 if audio is not None:
1661                         if isinstance(audio[1], str):
1662                                 if audio[1] == "mode":
1663                                         keys = ["red", "green", "yellow"]
1664                                         selection = self.audioChannel.getCurrentChannel()
1665                                         tlist = ((_("left"), 0), (_("stereo"), 1), (_("right"), 2))
1666                                         self.session.openWithCallback(self.modeSelected, ChoiceBox, title=_("Select audio mode"), list = tlist, selection = selection, keys = keys)
1667                         else:
1668                                 del self.audioChannel
1669                                 if self.session.nav.getCurrentService().audioTracks().getNumberOfTracks() > audio[1]:
1670                                         self.audioTracks.selectTrack(audio[1])
1671                 else:
1672                         del self.audioChannel
1673                 del self.audioTracks
1674
1675         def modeSelected(self, mode):
1676                 if mode is not None:
1677                         self.audioChannel.selectChannel(mode[1])
1678                 del self.audioChannel
1679
1680 class InfoBarSubserviceSelection:
1681         def __init__(self):
1682                 self["SubserviceSelectionAction"] = HelpableActionMap(self, "InfobarSubserviceSelectionActions",
1683                         {
1684                                 "subserviceSelection": (self.subserviceSelection, _("Subservice list...")),
1685                         })
1686
1687                 self["SubserviceQuickzapAction"] = HelpableActionMap(self, "InfobarSubserviceQuickzapActions",
1688                         {
1689                                 "nextSubservice": (self.nextSubservice, _("Switch to next subservice")),
1690                                 "prevSubservice": (self.prevSubservice, _("Switch to previous subservice"))
1691                         }, -1)
1692                 self["SubserviceQuickzapAction"].setEnabled(False)
1693
1694                 self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
1695                         {
1696                                 iPlayableService.evUpdatedEventInfo: self.checkSubservicesAvail
1697                         })
1698
1699                 self.bsel = None
1700
1701         def checkSubservicesAvail(self):
1702                 service = self.session.nav.getCurrentService()
1703                 subservices = service and service.subServices()
1704                 if not subservices or subservices.getNumberOfSubservices() == 0:
1705                         self["SubserviceQuickzapAction"].setEnabled(False)
1706
1707         def nextSubservice(self):
1708                 self.changeSubservice(+1)
1709
1710         def prevSubservice(self):
1711                 self.changeSubservice(-1)
1712
1713         def changeSubservice(self, direction):
1714                 service = self.session.nav.getCurrentService()
1715                 subservices = service and service.subServices()
1716                 n = subservices and subservices.getNumberOfSubservices()
1717                 if n and n > 0:
1718                         selection = -1
1719                         ref = self.session.nav.getCurrentlyPlayingServiceReference()
1720                         idx = 0
1721                         while idx < n:
1722                                 if subservices.getSubservice(idx).toString() == ref.toString():
1723                                         selection = idx
1724                                         break
1725                                 idx += 1
1726                         if selection != -1:
1727                                 selection += direction
1728                                 if selection >= n:
1729                                         selection=0
1730                                 elif selection < 0:
1731                                         selection=n-1
1732                                 newservice = subservices.getSubservice(selection)
1733                                 if newservice.valid():
1734                                         del subservices
1735                                         del service
1736                                         self.session.nav.playService(newservice, False)
1737
1738         def subserviceSelection(self):
1739                 service = self.session.nav.getCurrentService()
1740                 subservices = service and service.subServices()
1741                 self.bouquets = self.servicelist.getBouquetList()
1742                 n = subservices and subservices.getNumberOfSubservices()
1743                 selection = 0
1744                 if n and n > 0:
1745                         ref = self.session.nav.getCurrentlyPlayingServiceReference()
1746                         tlist = []
1747                         idx = 0
1748                         while idx < n:
1749                                 i = subservices.getSubservice(idx)
1750                                 if i.toString() == ref.toString():
1751                                         selection = idx
1752                                 tlist.append((i.getName(), i))
1753                                 idx += 1
1754
1755                         if self.bouquets and len(self.bouquets):
1756                                 keys = ["red", "blue", "",  "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ] + [""] * n
1757                                 if config.usage.multibouquet.value:
1758                                         tlist = [(_("Quickzap"), "quickzap", service.subServices()), (_("Add to bouquet"), "CALLFUNC", self.addSubserviceToBouquetCallback), ("--", "")] + tlist
1759                                 else:
1760                                         tlist = [(_("Quickzap"), "quickzap", service.subServices()), (_("Add to favourites"), "CALLFUNC", self.addSubserviceToBouquetCallback), ("--", "")] + tlist
1761                                 selection += 3
1762                         else:
1763                                 tlist = [(_("Quickzap"), "quickzap", service.subServices()), ("--", "")] + tlist
1764                                 keys = ["red", "",  "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ] + [""] * n
1765                                 selection += 2
1766
1767                         self.session.openWithCallback(self.subserviceSelected, ChoiceBox, title=_("Please select a subservice..."), list = tlist, selection = selection, keys = keys)
1768
1769         def subserviceSelected(self, service):
1770                 del self.bouquets
1771                 if not service is None:
1772                         if isinstance(service[1], str):
1773                                 if service[1] == "quickzap":
1774                                         from Screens.SubservicesQuickzap import SubservicesQuickzap
1775                                         self.session.open(SubservicesQuickzap, service[2])
1776                         else:
1777                                 self["SubserviceQuickzapAction"].setEnabled(True)
1778                                 self.session.nav.playService(service[1], False)
1779
1780         def addSubserviceToBouquetCallback(self, service):
1781                 if len(service) > 1 and isinstance(service[1], eServiceReference):
1782                         self.selectedSubservice = service
1783                         if self.bouquets is None:
1784                                 cnt = 0
1785                         else:
1786                                 cnt = len(self.bouquets)
1787                         if cnt > 1: # show bouquet list
1788                                 self.bsel = self.session.openWithCallback(self.bouquetSelClosed, BouquetSelector, self.bouquets, self.addSubserviceToBouquet)
1789                         elif cnt == 1: # add to only one existing bouquet
1790                                 self.addSubserviceToBouquet(self.bouquets[0][1])
1791                                 self.session.open(MessageBox, _("Service has been added to the favourites."), MessageBox.TYPE_INFO)
1792
1793         def bouquetSelClosed(self, confirmed):
1794                 self.bsel = None
1795                 del self.selectedSubservice
1796                 if confirmed:
1797                         self.session.open(MessageBox, _("Service has been added to the selected bouquet."), MessageBox.TYPE_INFO)
1798
1799         def addSubserviceToBouquet(self, dest):
1800                 self.servicelist.addServiceToBouquet(dest, self.selectedSubservice[1])
1801                 if self.bsel:
1802                         self.bsel.close(True)
1803                 else:
1804                         del self.selectedSubservice
1805
1806 class InfoBarAdditionalInfo:
1807         def __init__(self):
1808
1809                 self["RecordingPossible"] = Boolean(fixed=harddiskmanager.HDDCount() > 0 and config.misc.rcused.value == 1)
1810                 self["TimeshiftPossible"] = self["RecordingPossible"]
1811                 self["ShowTimeshiftOnYellow"] = Boolean(fixed=(not config.misc.rcused.value == 0))
1812                 self["ShowAudioOnYellow"] = Boolean(fixed=config.misc.rcused.value == 0)
1813                 self["ShowRecordOnRed"] = Boolean(fixed=config.misc.rcused.value == 1)
1814                 self["ExtensionsAvailable"] = Boolean(fixed=1)
1815
1816 class InfoBarNotifications:
1817         def __init__(self):
1818                 self.onExecBegin.append(self.checkNotifications)
1819                 Notifications.notificationAdded.append(self.checkNotificationsIfExecing)
1820                 self.onClose.append(self.__removeNotification)
1821
1822         def __removeNotification(self):
1823                 Notifications.notificationAdded.remove(self.checkNotificationsIfExecing)
1824
1825         def checkNotificationsIfExecing(self):
1826                 if self.execing:
1827                         self.checkNotifications()
1828
1829         def checkNotifications(self):
1830                 notifications = Notifications.notifications
1831                 if notifications:
1832                         n = notifications[0]
1833
1834                         del notifications[0]
1835                         cb = n[0]
1836
1837                         if n[3].has_key("onSessionOpenCallback"):
1838                                 n[3]["onSessionOpenCallback"]()
1839                                 del n[3]["onSessionOpenCallback"]
1840
1841                         if cb is not None:
1842                                 dlg = self.session.openWithCallback(cb, n[1], *n[2], **n[3])
1843                         else:
1844                                 dlg = self.session.open(n[1], *n[2], **n[3])
1845
1846                         # remember that this notification is currently active
1847                         d = (n[4], dlg)
1848                         Notifications.current_notifications.append(d)
1849                         dlg.onClose.append(boundFunction(self.__notificationClosed, d))
1850
1851         def __notificationClosed(self, d):
1852                 Notifications.current_notifications.remove(d)
1853
1854 class InfoBarServiceNotifications:
1855         def __init__(self):
1856                 self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
1857                         {
1858                                 iPlayableService.evEnd: self.serviceHasEnded
1859                         })
1860
1861         def serviceHasEnded(self):
1862                 print "service end!"
1863
1864                 try:
1865                         self.setSeekState(self.SEEK_STATE_PLAY)
1866                 except:
1867                         pass
1868
1869 class InfoBarCueSheetSupport:
1870         CUT_TYPE_IN = 0
1871         CUT_TYPE_OUT = 1
1872         CUT_TYPE_MARK = 2
1873         CUT_TYPE_LAST = 3
1874
1875         ENABLE_RESUME_SUPPORT = False
1876
1877         def __init__(self, actionmap = "InfobarCueSheetActions"):
1878                 self["CueSheetActions"] = HelpableActionMap(self, actionmap,
1879                         {
1880                                 "jumpPreviousMark": (self.jumpPreviousMark, _("jump to previous marked position")),
1881                                 "jumpNextMark": (self.jumpNextMark, _("jump to next marked position")),
1882                                 "toggleMark": (self.toggleMark, _("toggle a cut mark at the current position"))
1883                         }, prio=1)
1884
1885                 self.cut_list = [ ]
1886                 self.is_closing = False
1887                 self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
1888                         {
1889                                 iPlayableService.evStart: self.__serviceStarted,
1890                         })
1891
1892         def __serviceStarted(self):
1893                 if self.is_closing:
1894                         return
1895                 print "new service started! trying to download cuts!"
1896                 self.downloadCuesheet()
1897
1898                 if self.ENABLE_RESUME_SUPPORT:
1899                         last = None
1900
1901                         for (pts, what) in self.cut_list:
1902                                 if what == self.CUT_TYPE_LAST:
1903                                         last = pts
1904
1905                         if last is not None:
1906                                 self.resume_point = last
1907                                 if config.usage.on_movie_start.value == "ask":
1908                                         Notifications.AddNotificationWithCallback(self.playLastCB, MessageBox, _("Do you want to resume this playback?"), timeout=10)
1909                                 elif config.usage.on_movie_start.value == "resume":
1910 # TRANSLATORS: The string "Resuming playback" flashes for a moment
1911 # TRANSLATORS: at the start of a movie, when the user has selected
1912 # TRANSLATORS: "Resume from last position" as start behavior.
1913 # TRANSLATORS: The purpose is to notify the user that the movie starts
1914 # TRANSLATORS: in the middle somewhere and not from the beginning.
1915 # TRANSLATORS: (Some translators seem to have interpreted it as a
1916 # TRANSLATORS: question or a choice, but it is a statement.)
1917                                         Notifications.AddNotificationWithCallback(self.playLastCB, MessageBox, _("Resuming playback"), timeout=2, type=MessageBox.TYPE_INFO)
1918
1919         def playLastCB(self, answer):
1920                 if answer == True:
1921                         self.doSeek(self.resume_point)
1922                 self.hideAfterResume()
1923
1924         def hideAfterResume(self):
1925                 if isinstance(self, InfoBarShowHide):
1926                         self.hide()
1927
1928         def __getSeekable(self):
1929                 service = self.session.nav.getCurrentService()
1930                 if service is None:
1931                         return None
1932                 return service.seek()
1933
1934         def cueGetCurrentPosition(self):
1935                 seek = self.__getSeekable()
1936                 if seek is None:
1937                         return None
1938                 r = seek.getPlayPosition()
1939                 if r[0]:
1940                         return None
1941                 return long(r[1])
1942
1943         def cueGetEndCutPosition(self):
1944                 ret = False
1945                 isin = True
1946                 for cp in self.cut_list:
1947                         if cp[1] == self.CUT_TYPE_OUT:
1948                                 if isin:
1949                                         isin = False
1950                                         ret = cp[0]
1951                         elif cp[1] == self.CUT_TYPE_IN:
1952                                 isin = True
1953                 return ret
1954                 
1955         def jumpPreviousNextMark(self, cmp, start=False):
1956                 current_pos = self.cueGetCurrentPosition()
1957                 if current_pos is None:
1958                         return False
1959                 mark = self.getNearestCutPoint(current_pos, cmp=cmp, start=start)
1960                 if mark is not None:
1961                         pts = mark[0]
1962                 else:
1963                         return False
1964
1965                 self.doSeek(pts)
1966                 return True
1967
1968         def jumpPreviousMark(self):
1969                 # we add 2 seconds, so if the play position is <2s after
1970                 # the mark, the mark before will be used
1971                 self.jumpPreviousNextMark(lambda x: -x-5*90000, start=True)
1972
1973         def jumpNextMark(self):
1974                 if not self.jumpPreviousNextMark(lambda x: x):
1975                         self.doSeek(-1)
1976
1977         def getNearestCutPoint(self, pts, cmp=abs, start=False):
1978                 # can be optimized
1979                 beforecut = False
1980                 nearest = None
1981                 if start:
1982                         beforecut = True
1983                         bestdiff = cmp(0 - pts)
1984                         if bestdiff >= 0:
1985                                 nearest = [0, False]
1986                 for cp in self.cut_list:
1987                         if beforecut and cp[1] in (self.CUT_TYPE_IN, self.CUT_TYPE_OUT):
1988                                 beforecut = False
1989                                 if cp[1] == self.CUT_TYPE_IN:  # Start is here, disregard previous marks
1990                                         diff = cmp(cp[0] - pts)
1991                                         if diff >= 0:
1992                                                 nearest = cp
1993                                                 bestdiff = diff
1994                                         else:
1995                                                 nearest = None
1996                         if cp[1] in (self.CUT_TYPE_MARK, self.CUT_TYPE_LAST):
1997                                 diff = cmp(cp[0] - pts)
1998                                 if diff >= 0 and (nearest is None or bestdiff > diff):
1999                                         nearest = cp
2000                                         bestdiff = diff
2001                 return nearest
2002
2003         def toggleMark(self, onlyremove=False, onlyadd=False, tolerance=5*90000, onlyreturn=False):
2004                 current_pos = self.cueGetCurrentPosition()
2005                 if current_pos is None:
2006                         print "not seekable"
2007                         return
2008
2009                 nearest_cutpoint = self.getNearestCutPoint(current_pos)
2010
2011                 if nearest_cutpoint is not None and abs(nearest_cutpoint[0] - current_pos) < tolerance:
2012                         if onlyreturn:
2013                                 return nearest_cutpoint
2014                         if not onlyadd:
2015                                 self.removeMark(nearest_cutpoint)
2016                 elif not onlyremove and not onlyreturn:
2017                         self.addMark((current_pos, self.CUT_TYPE_MARK))
2018
2019                 if onlyreturn:
2020                         return None
2021
2022         def addMark(self, point):
2023                 insort(self.cut_list, point)
2024                 self.uploadCuesheet()
2025                 self.showAfterCuesheetOperation()
2026
2027         def removeMark(self, point):
2028                 self.cut_list.remove(point)
2029                 self.uploadCuesheet()
2030                 self.showAfterCuesheetOperation()
2031
2032         def showAfterCuesheetOperation(self):
2033                 if isinstance(self, InfoBarShowHide):
2034                         self.doShow()
2035
2036         def __getCuesheet(self):
2037                 service = self.session.nav.getCurrentService()
2038                 if service is None:
2039                         return None
2040                 return service.cueSheet()
2041
2042         def uploadCuesheet(self):
2043                 cue = self.__getCuesheet()
2044
2045                 if cue is None:
2046                         print "upload failed, no cuesheet interface"
2047                         return
2048                 cue.setCutList(self.cut_list)
2049
2050         def downloadCuesheet(self):
2051                 cue = self.__getCuesheet()
2052
2053                 if cue is None:
2054                         print "download failed, no cuesheet interface"
2055                         self.cut_list = [ ]
2056                 else:
2057                         self.cut_list = cue.getCutList()
2058
2059 class InfoBarSummary(Screen):
2060         skin = """
2061         <screen position="0,0" size="132,64">
2062                 <widget source="global.CurrentTime" render="Label" position="62,46" size="82,18" font="Regular;16" >
2063                         <convert type="ClockToText">WithSeconds</convert>
2064                 </widget>
2065                 <widget source="session.RecordState" render="FixedLabel" text=" " position="62,46" size="82,18" zPosition="1" >
2066                         <convert type="ConfigEntryTest">config.usage.blinking_display_clock_during_recording,True,CheckSourceBoolean</convert>
2067                         <convert type="ConditionalShowHide">Blink</convert>
2068                 </widget>
2069                 <widget source="session.CurrentService" render="Label" position="6,4" size="120,42" font="Regular;18" >
2070                         <convert type="ServiceName">Name</convert>
2071                 </widget>
2072                 <widget source="session.Event_Now" render="Progress" position="6,46" size="46,18" borderWidth="1" >
2073                         <convert type="EventTime">Progress</convert>
2074                 </widget>
2075         </screen>"""
2076
2077 # for picon:  (path="piconlcd" will use LCD picons)
2078 #               <widget source="session.CurrentService" render="Picon" position="6,0" size="120,64" path="piconlcd" >
2079 #                       <convert type="ServiceName">Reference</convert>
2080 #               </widget>
2081
2082         def __init__(self, session, parent):
2083                 Screen.__init__(self, session, parent = parent)
2084
2085 class InfoBarSummarySupport:
2086         def __init__(self):
2087                 pass
2088
2089         def createSummary(self):
2090                 return InfoBarSummary
2091
2092 class InfoBarMoviePlayerSummary(Screen):
2093         skin = """
2094         <screen position="0,0" size="132,64">
2095                 <widget source="global.CurrentTime" render="Label" position="62,46" size="64,18" font="Regular;16" halign="right" >
2096                         <convert type="ClockToText">WithSeconds</convert>
2097                 </widget>
2098                 <widget source="session.RecordState" render="FixedLabel" text=" " position="62,46" size="64,18" zPosition="1" >
2099                         <convert type="ConfigEntryTest">config.usage.blinking_display_clock_during_recording,True,CheckSourceBoolean</convert>
2100                         <convert type="ConditionalShowHide">Blink</convert>
2101                 </widget>
2102                 <widget source="session.CurrentService" render="Label" position="6,4" size="120,42" font="Regular;18" >
2103                         <convert type="ServiceName">Name</convert>
2104                 </widget>
2105                 <widget source="session.CurrentService" render="Progress" position="6,46" size="56,18" borderWidth="1" >
2106                         <convert type="ServicePosition">Position</convert>
2107                 </widget>
2108         </screen>"""
2109
2110         def __init__(self, session, parent):
2111                 Screen.__init__(self, session)
2112
2113 class InfoBarMoviePlayerSummarySupport:
2114         def __init__(self):
2115                 pass
2116
2117         def createSummary(self):
2118                 return InfoBarMoviePlayerSummary
2119
2120 class InfoBarTeletextPlugin:
2121         def __init__(self):
2122                 self.teletext_plugin = None
2123
2124                 for p in plugins.getPlugins(PluginDescriptor.WHERE_TELETEXT):
2125                         self.teletext_plugin = p
2126
2127                 if self.teletext_plugin is not None:
2128                         self["TeletextActions"] = HelpableActionMap(self, "InfobarTeletextActions",
2129                                 {
2130                                         "startTeletext": (self.startTeletext, _("View teletext..."))
2131                                 })
2132                 else:
2133                         print "no teletext plugin found!"
2134
2135         def startTeletext(self):
2136                 self.teletext_plugin(session=self.session, service=self.session.nav.getCurrentService())
2137
2138 class InfoBarSubtitleSupport(object):
2139         def __init__(self):
2140                 object.__init__(self)
2141                 self.subtitle_window = self.session.instantiateDialog(SubtitleDisplay)
2142                 self.__subtitles_enabled = False
2143
2144                 self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
2145                         {
2146                                 iPlayableService.evEnd: self.__serviceStopped,
2147                                 iPlayableService.evUpdatedInfo: self.__updatedInfo
2148                         })
2149                 self.cached_subtitle_checked = False
2150                 self.__selected_subtitle = None
2151
2152         def __serviceStopped(self):
2153                 self.subtitle_window.hide()
2154                 self.__subtitles_enabled = False
2155                 self.cached_subtitle_checked = False
2156
2157         def __updatedInfo(self):
2158                 if not self.cached_subtitle_checked:
2159                         subtitle = self.getCurrentServiceSubtitle()
2160                         self.cached_subtitle_checked = True
2161                         self.__selected_subtitle = subtitle and subtitle.getCachedSubtitle()
2162                         if self.__selected_subtitle:
2163                                 subtitle.enableSubtitles(self.subtitle_window.instance, self.selected_subtitle)
2164                                 self.subtitle_window.show()
2165                                 self.__subtitles_enabled = True
2166
2167         def getCurrentServiceSubtitle(self):
2168                 service = self.session.nav.getCurrentService()
2169                 return service and service.subtitle()
2170
2171         def setSubtitlesEnable(self, enable=True):
2172                 subtitle = self.getCurrentServiceSubtitle()
2173                 if enable and self.__selected_subtitle is not None:
2174                         if subtitle and not self.__subtitles_enabled:
2175                                 subtitle.enableSubtitles(self.subtitle_window.instance, self.selected_subtitle)
2176                                 self.subtitle_window.show()
2177                                 self.__subtitles_enabled = True
2178                 else:
2179                         if subtitle:
2180                                 subtitle.disableSubtitles(self.subtitle_window.instance)
2181                         self.__subtitles_enabled = False
2182                         self.subtitle_window.hide()
2183
2184         def setSelectedSubtitle(self, subtitle):
2185                 self.__selected_subtitle = subtitle
2186
2187         subtitles_enabled = property(lambda self: self.__subtitles_enabled, setSubtitlesEnable)
2188         selected_subtitle = property(lambda self: self.__selected_subtitle, setSelectedSubtitle)
2189
2190 class InfoBarServiceErrorPopupSupport:
2191         def __init__(self):
2192                 self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
2193                         {
2194                                 iPlayableService.evTuneFailed: self.__tuneFailed,
2195                                 iPlayableService.evStart: self.__serviceStarted
2196                         })
2197                 self.__serviceStarted()
2198
2199         def __serviceStarted(self):
2200                 self.last_error = None
2201                 Notifications.RemovePopup(id = "ZapError")
2202
2203         def __tuneFailed(self):
2204                 service = self.session.nav.getCurrentService()
2205                 info = service and service.info()
2206                 error = info and info.getInfo(iServiceInformation.sDVBState)
2207
2208                 if error == self.last_error:
2209                         error = None
2210                 else:
2211                         self.last_error = error
2212
2213                 errors = {
2214                         eDVBServicePMTHandler.eventNoResources: _("No free tuner!"),
2215                         eDVBServicePMTHandler.eventTuneFailed: _("Tune failed!"),
2216                         eDVBServicePMTHandler.eventNoPAT: _("No data on transponder!\n(Timeout reading PAT)"),
2217                         eDVBServicePMTHandler.eventNoPATEntry: _("Service not found!\n(SID not found in PAT)"),
2218                         eDVBServicePMTHandler.eventNoPMT: _("Service invalid!\n(Timeout reading PMT)"),
2219                         eDVBServicePMTHandler.eventNewProgramInfo: None,
2220                         eDVBServicePMTHandler.eventTuned: None,
2221                         eDVBServicePMTHandler.eventSOF: None,
2222                         eDVBServicePMTHandler.eventEOF: None,
2223                         eDVBServicePMTHandler.eventMisconfiguration: _("Service unavailable!\nCheck tuner configuration!"),
2224                 }
2225
2226                 error = errors.get(error) #this returns None when the key not exist in the dict
2227
2228                 if error is not None:
2229                         Notifications.AddPopup(text = error, type = MessageBox.TYPE_ERROR, timeout = 5, id = "ZapError")
2230                 else:
2231                         Notifications.RemovePopup(id = "ZapError")