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