Exemple #1
0
class TimerEntry(Screen, ConfigListScreen):
    def __init__(self, session, timer):
        Screen.__init__(self, session)
        self.setup_title = _("Timer entry")
        self.timer = timer

        self.entryDate = None
        self.entryService = None

        self["HelpWindow"] = Pixmap()
        self["HelpWindow"].hide()
        self["VKeyIcon"] = Boolean(False)

        self["locationdescription"] = Label("")
        self["locationfreespace"] = Label("")
        self["description"] = Label("")
        self["oktext"] = Label(_("OK"))
        self["canceltext"] = Label(_("Cancel"))
        self["ok"] = Pixmap()
        self["cancel"] = Pixmap()

        self.createConfig()

        self["actions"] = NumberActionMap(
            [
                "SetupActions", "GlobalActions", "PiPSetupActions",
                "ColorActions"
            ], {
                "ok": self.keySelect,
                "save": self.keyGo,
                "cancel": self.keyCancel,
                "volumeUp": self.incrementStart,
                "volumeDown": self.decrementStart,
                "size+": self.incrementEnd,
                "size-": self.decrementEnd,
            }, -2)

        self["VirtualKB"] = ActionMap(["VirtualKeyboardActions"], {
            "showVirtualKeyboard": self.KeyText,
        }, -2)
        self["VirtualKB"].setEnabled(False)

        self.onChangedEntry = []
        self.list = []
        ConfigListScreen.__init__(self, self.list, session=session)
        self.createSetup("config")
        self.onLayoutFinish.append(self.layoutFinished)

        if not self.selectionChanged in self["config"].onSelectionChanged:
            self["config"].onSelectionChanged.append(self.selectionChanged)
        self.selectionChanged()

    def createConfig(self):
        justplay = self.timer.justplay
        always_zap = self.timer.always_zap
        rename_repeat = self.timer.rename_repeat

        afterevent = {
            AFTEREVENT.NONE: "nothing",
            AFTEREVENT.DEEPSTANDBY: "deepstandby",
            AFTEREVENT.STANDBY: "standby",
            AFTEREVENT.AUTO: "auto"
        }[self.timer.afterEvent]

        if self.timer.record_ecm and self.timer.descramble:
            recordingtype = "descrambled+ecm"
        elif self.timer.record_ecm:
            recordingtype = "scrambled+ecm"
        elif self.timer.descramble:
            recordingtype = "normal"

        weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")

        # calculate default values
        day = []
        weekday = 0
        for x in (0, 1, 2, 3, 4, 5, 6):
            day.append(0)
        if self.timer.repeated:  # repeated
            type = "repeated"
            if self.timer.repeated == 31:  # Mon-Fri
                repeated = "weekdays"
            elif self.timer.repeated == 127:  # daily
                repeated = "daily"
            else:
                flags = self.timer.repeated
                repeated = "user"
                count = 0
                for x in (0, 1, 2, 3, 4, 5, 6):
                    if flags == 1:  # weekly
                        # 						print "Set to weekday " + str(x)
                        weekday = x
                    if flags & 1 == 1:  # set user defined flags
                        day[x] = 1
                        count += 1
                    else:
                        day[x] = 0
                    flags >>= 1
                if count == 1:
                    repeated = "weekly"
        else:  # once
            type = "once"
            repeated = None
            weekday = int(strftime("%u", localtime(self.timer.begin))) - 1
            day[weekday] = 1

        self.timerentry_justplay = ConfigSelection(
            choices=[("zap", _("zap")), ("record", _("record")),
                     ("zap+record", _("zap and record"))],
            default={
                0: "record",
                1: "zap",
                2: "zap+record"
            }[justplay + 2 * always_zap])
        self.timertyp = self.timerentry_justplay.value

        if SystemInfo["DeepstandbySupport"]:
            shutdownString = _("go to deep standby")
        else:
            shutdownString = _("shut down")
        self.timerentry_afterevent = ConfigSelection(choices=[
            ("nothing", _("do nothing")), ("standby", _("go to standby")),
            ("deepstandby", shutdownString), ("auto", _("auto"))
        ],
                                                     default=afterevent)
        self.timerentry_recordingtype = ConfigSelection(choices=[
            ("normal", _("normal")),
            ("descrambled+ecm", _("descramble and record ecm")),
            ("scrambled+ecm", _("don't descramble, record ecm"))
        ],
                                                        default=recordingtype)
        self.timerentry_type = ConfigSelection(choices=[("once", _("once")),
                                                        ("repeated",
                                                         _("repeated"))],
                                               default=type)
        self.timerentry_name = ConfigText(default=self.timer.name.replace(
            '\xc2\x86', '').replace('\xc2\x87', '').encode("utf-8"),
                                          visible_width=50,
                                          fixed_size=False)
        self.timerentry_description_replaced = self.timer.description.replace(
            '\xc2\x8a', ' ').encode("utf-8")
        self.timerentry_description = ConfigText(
            default=self.timerentry_description_replaced,
            visible_width=50,
            fixed_size=False)
        self.timerentry_tags = self.timer.tags[:]
        # if no tags found, make name of event default tag set.
        if not self.timerentry_tags:
            tagname = self.timer.name.strip()
            if tagname:
                tagname = tagname[0].upper() + tagname[1:].replace(" ", "_")
                self.timerentry_tags.append(tagname)

        self.timerentry_tagsset = ConfigSelection(choices=[
            not self.timerentry_tags and "None"
            or " ".join(self.timerentry_tags)
        ])

        self.timerentry_repeated = ConfigSelection(
            default=repeated,
            choices=[("weekly", _("weekly")), ("daily", _("daily")),
                     ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])
        self.timerentry_renamerepeat = ConfigYesNo(default=rename_repeat)

        self.timerentry_date = ConfigDateTime(default=self.timer.begin,
                                              formatstring=_("%d %B %Y"),
                                              increment=86400)
        self.timerentry_starttime = ConfigClock(default=self.timer.begin)
        self.timerentry_endtime = ConfigClock(default=self.timer.end)
        #self.timerentry_showendtime = ConfigSelection(default = False, choices = [(True, _("yes")), (False, _("no"))])
        self.timerentry_showendtime = ConfigSelection(
            default=(self.timer.end > self.timer.begin + 3
                     and self.timer.justplay),
            choices=[(True, _("yes")), (False, _("no"))])

        default = self.timer.dirname or defaultMoviePath()
        tmp = config.movielist.videodirs.value
        if default not in tmp:
            tmp.append(default)
        self.timerentry_dirname = ConfigSelection(default=default, choices=tmp)

        self.timerentry_repeatedbegindate = ConfigDateTime(
            default=self.timer.repeatedbegindate,
            formatstring=_("%d.%B %Y"),
            increment=86400)

        self.timerentry_weekday = ConfigSelection(
            default=weekday_table[weekday],
            choices=[("mon", _("Monday")), ("tue", _("Tuesday")),
                     ("wed", _("Wednesday")), ("thu", _("Thursday")),
                     ("fri", _("Friday")), ("sat", _("Saturday")),
                     ("sun", _("Sunday"))])

        self.timerentry_day = ConfigSubList()
        for x in (0, 1, 2, 3, 4, 5, 6):
            self.timerentry_day.append(ConfigYesNo(default=day[x]))

        # FIXME some service-chooser needed here
        servicename = "N/A"
        try:  # no current service available?
            servicename = str(self.timer.service_ref.getServiceName())
        except:
            pass
        self.timerentry_service_ref = self.timer.service_ref
        self.timerentry_service = ConfigSelection([servicename])

    def createSetup(self, widget):
        if not self.timer in self.session.nav.RecordTimer.timer_list:
            newtime = None
            if self.timerentry_justplay.value == 'zap' and self.timertyp != 'zap':
                newtime = self.getTimestamp(
                    self.timerentry_date.value, self.timerentry_starttime.value
                ) + config.recording.margin_before.value * 60
                newbegin = localtime(newtime)
            elif self.timerentry_justplay.value != 'zap' and self.timertyp == 'zap':
                newtime = self.getTimestamp(
                    self.timerentry_date.value, self.timerentry_starttime.value
                ) - config.recording.margin_before.value * 60
                newbegin = localtime(newtime)
            if newtime:
                self.timerentry_date.value = newtime
                self.timerentry_starttime.value = [
                    newbegin.tm_hour, newbegin.tm_min
                ]
            self.timertyp = self.timerentry_justplay.value

        self.list = []
        self.timerJustplayEntry = getConfigListEntry(
            _("Timer type"), self.timerentry_justplay,
            _("Chose between record and ZAP."))
        self.list.append(self.timerJustplayEntry)
        self.entryName = getConfigListEntry(
            _("Name"), self.timerentry_name,
            _("Set the name the recording will get."))
        self.list.append(self.entryName)
        self.entryDescription = getConfigListEntry(
            _("Description"), self.timerentry_description,
            _("Set the description of the recording."))
        self.list.append(self.entryDescription)
        self.timerTypeEntry = getConfigListEntry(
            _("Repeat type"), self.timerentry_type,
            _("A repeating timer or just once?"))
        self.list.append(self.timerTypeEntry)

        if self.timerentry_type.value == "once":
            self.frequencyEntry = None
        else:  # repeated
            self.frequencyEntry = getConfigListEntry(
                _("Repeats"), self.timerentry_repeated,
                _("Choose between Daily, Weekly, Weekdays or user defined."))
            self.list.append(self.frequencyEntry)
            self.repeatedbegindateEntry = getConfigListEntry(
                _("Starting on"), self.timerentry_repeatedbegindate,
                _("Set the date the timer must start."))
            self.list.append(self.repeatedbegindateEntry)
            if self.timerentry_repeated.value == "daily":
                pass
            if self.timerentry_repeated.value == "weekdays":
                pass
            if self.timerentry_repeated.value == "weekly":
                self.list.append(
                    getConfigListEntry(_("Weekday"), self.timerentry_weekday))

            if self.timerentry_repeated.value == "user":
                self.list.append(
                    getConfigListEntry(_("Monday"), self.timerentry_day[0]))
                self.list.append(
                    getConfigListEntry(_("Tuesday"), self.timerentry_day[1]))
                self.list.append(
                    getConfigListEntry(_("Wednesday"), self.timerentry_day[2]))
                self.list.append(
                    getConfigListEntry(_("Thursday"), self.timerentry_day[3]))
                self.list.append(
                    getConfigListEntry(_("Friday"), self.timerentry_day[4]))
                self.list.append(
                    getConfigListEntry(_("Saturday"), self.timerentry_day[5]))
                self.list.append(
                    getConfigListEntry(_("Sunday"), self.timerentry_day[6]))
            if self.timerentry_justplay.value != "zap":
                self.list.append(
                    getConfigListEntry(
                        _("Rename name and description for new events"),
                        self.timerentry_renamerepeat))

        self.entryDate = getConfigListEntry(
            _("Date"), self.timerentry_date,
            _("Set the date the timer must start."))
        if self.timerentry_type.value == "once":
            self.list.append(self.entryDate)

        self.entryStartTime = getConfigListEntry(
            _("Start time"), self.timerentry_starttime,
            _("Set the time the timer must start."))
        self.list.append(self.entryStartTime)

        self.entryShowEndTime = getConfigListEntry(
            _("Set end time"), self.timerentry_showendtime,
            _("Set the time the timer must stop."))
        if self.timerentry_justplay.value == "zap":
            self.list.append(self.entryShowEndTime)

        self.entryEndTime = getConfigListEntry(
            _("End time"), self.timerentry_endtime,
            _("Set the time the timer must stop."))
        if self.timerentry_justplay.value != "zap" or self.timerentry_showendtime.value:
            self.list.append(self.entryEndTime)

        self.channelEntry = getConfigListEntry(
            _("Channel"), self.timerentry_service,
            _("Set the channel for this timer."))
        self.list.append(self.channelEntry)

        if self.timerentry_showendtime.value and self.timerentry_justplay.value == "zap":
            self.list.append(
                getConfigListEntry(
                    _("After event"), self.timerentry_afterevent,
                    _("What action is required on completion of the timer? 'Auto' lets the box return to the state it had when the timer started. 'Do nothing', 'Go to standby' and 'Go to deep standby' do exactly that."
                      )))

        description = free = ""
        try:
            if self.timerentry_justplay.value != "zap":
                stat = statvfs(self.timerentry_dirname.value)
                a = float(stat.f_blocks) * stat.f_bsize / 1024 / 1024 / 1024
                b = float(stat.f_bavail) * stat.f_bsize / 1024 / 1024 / 1024
                c = 100.0 * b / a
                free = ("%0.f GB (%0.f %s) " + _("free diskspace")) % (b, c,
                                                                       "%")
                description = _("Current location")
        except:
            pass
        self["locationdescription"].setText(description)
        self["locationfreespace"].setText(free)

        self.dirname = getConfigListEntry(
            _("Location"), self.timerentry_dirname,
            _("Where should the recording be saved?"))
        self.tagsSet = getConfigListEntry(
            _("Tags"), self.timerentry_tagsset,
            _("Choose a tag for easy finding a recording."))
        if self.timerentry_justplay.value != "zap":
            if config.usage.setup_level.index >= 2:  # expert+
                self.list.append(self.dirname)
            if getPreferredTagEditor():
                self.list.append(self.tagsSet)
            self.list.append(
                getConfigListEntry(
                    _("After Recording"), self.timerentry_afterevent,
                    _("What action is required on completion of the timer? 'Auto' lets the box return to the state it had when the timer started. 'Do nothing', 'Go to standby' and 'Go to deep standby' do exactly that."
                      )))
            self.list.append(
                getConfigListEntry(
                    _("Recording type"), self.timerentry_recordingtype,
                    _("Descramble & record ECM' gives the option to descramble afterwards if descrambling on recording failed. 'Don't descramble, record ECM' save a scramble recording that can be descrambled on playback. 'Normal' means descramble the recording and don't record ECM."
                      )))

        self[widget].list = self.list
        self[widget].l.setList(self.list)

    def selectionChanged(self):
        if self["config"].getCurrent():
            if len(self["config"].getCurrent()
                   ) > 2 and self["config"].getCurrent()[2]:
                self["description"].setText(self["config"].getCurrent()[2])
            if isinstance(self["config"].getCurrent()[1], ConfigText):
                if self.has_key("VKeyIcon"):
                    self["VirtualKB"].setEnabled(True)
                    self["VKeyIcon"].boolean = True
                if self.has_key("HelpWindow"):
                    if self["config"].getCurrent(
                    )[1].help_window and self["config"].getCurrent(
                    )[1].help_window.instance is not None:
                        helpwindowpos = self["HelpWindow"].getPosition()
                        from enigma import ePoint
                        self["config"].getCurrent(
                        )[1].help_window.instance.move(
                            ePoint(helpwindowpos[0], helpwindowpos[1]))
                    else:
                        if self.has_key("VKeyIcon"):
                            self["VirtualKB"].setEnabled(False)
                            self["VKeyIcon"].boolean = False
        else:
            if self.has_key("VKeyIcon"):
                self["VirtualKB"].setEnabled(False)
                self["VKeyIcon"].boolean = False

    def layoutFinished(self):
        self.setTitle(_(self.setup_title))

    def createSummary(self):
        return SetupSummary

    # for summary:
    def changedEntry(self):
        for x in self.onChangedEntry:
            x()

    def getCurrentEntry(self):
        return self["config"].getCurrent() and self["config"].getCurrent(
        )[0] or ""

    def getCurrentValue(self):
        return self["config"].getCurrent() and str(
            self["config"].getCurrent()[1].getText()) or ""

    def newConfig(self):
        if self["config"].getCurrent() in (self.timerTypeEntry,
                                           self.timerJustplayEntry,
                                           self.frequencyEntry,
                                           self.entryShowEndTime,
                                           self.dirname):
            self.createSetup("config")

    def KeyText(self):
        if self['config'].getCurrent()[0] in (_('Name'), _("Description")):
            self.session.openWithCallback(
                self.renameEntryCallback,
                VirtualKeyBoard,
                title=self["config"].getCurrent()[2],
                text=self["config"].getCurrent()[1].value,
                visible_width=50,
                currPos=0)

    def keyLeft(self):
        cur = self["config"].getCurrent()
        if cur in (self.channelEntry, self.tagsSet):
            self.keySelect()
        #elif cur in (self.entryName, self.entryDescription):
        #	self.renameEntry()
        else:
            ConfigListScreen.keyLeft(self)
            self.newConfig()

    def keyRight(self):
        cur = self["config"].getCurrent()
        if cur in (self.channelEntry, self.tagsSet):
            self.keySelect()
        #elif cur in (self.entryName, self.entryDescription):
        #	self.renameEntry()
        else:
            ConfigListScreen.keyRight(self)
            self.newConfig()

    def renameEntry(self):
        cur = self["config"].getCurrent()
        if cur == self.entryName:
            title_text = _("Please enter new name:")
            old_text = self.timerentry_name.value
        else:
            title_text = _("Please enter new description:")
            old_text = self.timerentry_description.value
        self.session.openWithCallback(self.renameEntryCallback,
                                      VirtualKeyBoard,
                                      title=title_text,
                                      text=old_text)

    def renameEntryCallback(self, answer):
        if answer:
            if self["config"].getCurrent() == self.entryName:
                self.timerentry_name.value = answer
                self["config"].invalidate(self.entryName)
            else:
                self.timerentry_description.value = answer
                self["config"].invalidate(self.entryDescription)

    def handleKeyFileCallback(self, answer):
        if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.handleKeyFileCallback(self, answer)
            self.newConfig()

    def keySelect(self):
        cur = self["config"].getCurrent()
        if cur == self.channelEntry:
            self.session.openWithCallback(
                self.finishedChannelSelection,
                ChannelSelection.SimpleChannelSelection,
                _("Select channel to record from"),
                currentBouquet=True)
        elif config.usage.setup_level.index >= 2 and cur == self.dirname:
            self.session.openWithCallback(
                self.pathSelected,
                MovieLocationBox,
                _("Select target folder"),
                self.timerentry_dirname.value,
                minFree=100  # We require at least 100MB free space
            )
        elif getPreferredTagEditor() and cur == self.tagsSet:
            self.session.openWithCallback(self.tagEditFinished,
                                          getPreferredTagEditor(),
                                          self.timerentry_tags)
        else:
            self.keyGo()

    def finishedChannelSelection(self, *args):
        if args:
            self.timerentry_service_ref = ServiceReference(args[0])
            self.timerentry_service.setCurrentText(
                self.timerentry_service_ref.getServiceName())
            self["config"].invalidate(self.channelEntry)

    def getTimestamp(self, date, mytime):
        d = localtime(date)
        dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
        return int(mktime(dt.timetuple()))

    def getBeginEnd(self):
        date = self.timerentry_date.value
        endtime = self.timerentry_endtime.value
        starttime = self.timerentry_starttime.value

        begin = self.getTimestamp(date, starttime)
        end = self.getTimestamp(date, endtime)

        # if the endtime is less than the starttime, add 1 day.
        if end < begin:
            end += 86400

        # if the timer type is a Zap and no end is set, set duration to 1 second so time is shown in EPG's.
        if self.timerentry_justplay.value == "zap":
            if not self.timerentry_showendtime.value:
                end = begin + 1

        return begin, end

    def selectChannelSelector(self, *args):
        self.session.openWithCallback(self.finishedChannelSelectionCorrection,
                                      ChannelSelection.SimpleChannelSelection,
                                      _("Select channel to record from"))

    def finishedChannelSelectionCorrection(self, *args):
        if args:
            self.finishedChannelSelection(*args)
            self.keyGo()

    def keyGo(self, result=None):
        if not self.timerentry_service_ref.isRecordable():
            self.session.openWithCallback(
                self.selectChannelSelector, MessageBox,
                _("You didn't select a channel to record from."),
                MessageBox.TYPE_ERROR)
            return
        self.timer.name = self.timerentry_name.value
        self.timer.description = self.timerentry_description.value if self.timerentry_description_replaced != self.timerentry_description.value else self.timer.description
        self.timer.justplay = self.timerentry_justplay.value == "zap"
        self.timer.always_zap = self.timerentry_justplay.value == "zap+record"
        self.timer.rename_repeat = self.timerentry_renamerepeat.value
        if self.timerentry_justplay.value == "zap":
            if not self.timerentry_showendtime.value:
                self.timerentry_endtime.value = self.timerentry_starttime.value
                self.timerentry_afterevent.value = "nothing"

        if self.timerentry_endtime.value == self.timerentry_starttime.value and self.timerentry_afterevent.value != "nothing":
            self.timerentry_afterevent.value = "nothing"
            self.session.open(
                MessageBox,
                _("Difference between timer begin and end must be equal or greater than %d minutes.\nEnd Action was disabled !"
                  ) % 1,
                MessageBox.TYPE_INFO,
                timeout=30)

        self.timer.resetRepeated()
        self.timer.afterEvent = {
            "nothing": AFTEREVENT.NONE,
            "deepstandby": AFTEREVENT.DEEPSTANDBY,
            "standby": AFTEREVENT.STANDBY,
            "auto": AFTEREVENT.AUTO
        }[self.timerentry_afterevent.value]
        self.timer.descramble = {
            "normal": True,
            "descrambled+ecm": True,
            "scrambled+ecm": False,
        }[self.timerentry_recordingtype.value]
        self.timer.record_ecm = {
            "normal": False,
            "descrambled+ecm": True,
            "scrambled+ecm": True,
        }[self.timerentry_recordingtype.value]
        self.timer.service_ref = self.timerentry_service_ref
        self.timer.tags = self.timerentry_tags

        if self.timer.dirname or self.timerentry_dirname.value != defaultMoviePath(
        ):
            self.timer.dirname = self.timerentry_dirname.value
            config.movielist.last_timer_videodir.value = self.timer.dirname
            config.movielist.last_timer_videodir.save()

        if self.timerentry_type.value == "once":
            self.timer.begin, self.timer.end = self.getBeginEnd()
        if self.timerentry_type.value == "repeated":
            if self.timerentry_repeated.value == "daily":
                for x in (0, 1, 2, 3, 4, 5, 6):
                    self.timer.setRepeated(x)

            if self.timerentry_repeated.value == "weekly":
                self.timer.setRepeated(self.timerentry_weekday.index)

            if self.timerentry_repeated.value == "weekdays":
                for x in (0, 1, 2, 3, 4):
                    self.timer.setRepeated(x)

            if self.timerentry_repeated.value == "user":
                for x in (0, 1, 2, 3, 4, 5, 6):
                    if self.timerentry_day[x].value:
                        self.timer.setRepeated(x)

            self.timer.repeatedbegindate = self.getTimestamp(
                self.timerentry_repeatedbegindate.value,
                self.timerentry_starttime.value)
            if self.timer.repeated:
                self.timer.begin = self.getTimestamp(
                    self.timerentry_repeatedbegindate.value,
                    self.timerentry_starttime.value)
                self.timer.end = self.getTimestamp(
                    self.timerentry_repeatedbegindate.value,
                    self.timerentry_endtime.value)
            else:
                self.timer.begin = self.getTimestamp(
                    time(), self.timerentry_starttime.value)
                self.timer.end = self.getTimestamp(
                    time(), self.timerentry_endtime.value)

            # when a timer end is set before the start, add 1 day
            if self.timer.end < self.timer.begin:
                self.timer.end += 86400

        if self.timer.eit is not None:
            event = eEPGCache.getInstance().lookupEventId(
                self.timer.service_ref.ref, self.timer.eit)
            if event:
                n = event.getNumOfLinkageServices()
                if n > 1:
                    tlist = []
                    ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
                    parent = self.timer.service_ref.ref
                    selection = 0
                    for x in range(n):
                        i = event.getLinkageService(parent, x)
                        if i.toString() == ref.toString():
                            selection = x
                        tlist.append((i.getName(), i))
                    self.session.openWithCallback(
                        self.subserviceSelected,
                        ChoiceBox,
                        title=_("Please select a subservice to record..."),
                        list=tlist,
                        selection=selection)
                    return
                elif n > 0:
                    parent = self.timer.service_ref.ref
                    self.timer.service_ref = ServiceReference(
                        event.getLinkageService(parent, 0))
        self.saveTimer()
        self.close((True, self.timer))

    def changeTimerType(self):
        self.timerentry_justplay.selectNext()
        self.timerJustplayEntry = getConfigListEntry(_("Timer type"),
                                                     self.timerentry_justplay)
        self["config"].invalidate(self.timerJustplayEntry)

    def incrementStart(self):
        self.timerentry_starttime.increment()
        self["config"].invalidate(self.entryStartTime)
        if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [
                0, 0
        ]:
            self.timerentry_date.value += 86400
            self["config"].invalidate(self.entryDate)

    def decrementStart(self):
        self.timerentry_starttime.decrement()
        self["config"].invalidate(self.entryStartTime)
        if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [
                23, 59
        ]:
            self.timerentry_date.value -= 86400
            self["config"].invalidate(self.entryDate)

    def incrementEnd(self):
        if self.entryEndTime is not None:
            self.timerentry_endtime.increment()
            self["config"].invalidate(self.entryEndTime)

    def decrementEnd(self):
        if self.entryEndTime is not None:
            self.timerentry_endtime.decrement()
            self["config"].invalidate(self.entryEndTime)

    def subserviceSelected(self, service):
        if not service is None:
            self.timer.service_ref = ServiceReference(service[1])
        self.saveTimer()
        self.close((True, self.timer))

    def saveTimer(self):
        self.session.nav.RecordTimer.saveTimer()

    def keyCancel(self):
        self.close((False, ))

    def pathSelected(self, res):
        if res is not None:
            if config.movielist.videodirs.value != self.timerentry_dirname.choices:
                self.timerentry_dirname.setChoices(
                    config.movielist.videodirs.value, default=res)
            self.timerentry_dirname.value = res
            self.newConfig()

    def tagEditFinished(self, ret):
        if ret is not None:
            self.timerentry_tags = ret
            self.timerentry_tagsset.setChoices(
                [not ret and "None" or " ".join(ret)])
            self["config"].invalidate(self.tagsSet)
Exemple #2
0
class TimerEntry(Screen, ConfigListScreen):
	def __init__(self, session, timer):
		Screen.__init__(self, session)
		self.timer = timer

		self.entryDate = None
		self.entryService = None

		self["oktext"] = Label(_("OK"))
		self["canceltext"] = Label(_("Cancel"))
		self["ok"] = Pixmap()
		self["cancel"] = Pixmap()
		self["key_yellow"] = Label(_("Timer type"))
		self["key_blue"] = Label()

		self.createConfig()

		self["actions"] = NumberActionMap(["SetupActions", "GlobalActions", "PiPSetupActions", "ColorActions"],
		{
			"ok": self.keySelect,
			"save": self.keyGo,
			"cancel": self.keyCancel,
			"volumeUp": self.incrementStart,
			"volumeDown": self.decrementStart,
			"size+": self.incrementEnd,
			"size-": self.decrementEnd,
			"yellow": self.changeTimerType,
			"blue": self.changeZapWakeupType
		}, -2)

		self.list = []
		ConfigListScreen.__init__(self, self.list, session = session)
		self.setTitle(_("Timer entry"))
		self.createSetup("config")

	def createConfig(self):
			justplay = self.timer.justplay
			always_zap = self.timer.always_zap
			zap_wakeup = self.timer.zap_wakeup
			rename_repeat = self.timer.rename_repeat

			afterevent = {
				AFTEREVENT.NONE: "nothing",
				AFTEREVENT.DEEPSTANDBY: "deepstandby",
				AFTEREVENT.STANDBY: "standby",
				AFTEREVENT.AUTO: "auto"
				}[self.timer.afterEvent]

			if self.timer.record_ecm and self.timer.descramble:
				recordingtype = "descrambled+ecm"
			elif self.timer.record_ecm:
				recordingtype = "scrambled+ecm"
			elif self.timer.descramble:
				recordingtype = "normal"

			weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")

			# calculate default values
			day = []
			weekday = 0
			for x in (0, 1, 2, 3, 4, 5, 6):
				day.append(0)
			if self.timer.repeated: # repeated
				type = "repeated"
				if (self.timer.repeated == 31): # Mon-Fri
					repeated = "weekdays"
				elif (self.timer.repeated == 127): # daily
					repeated = "daily"
				else:
					flags = self.timer.repeated
					repeated = "user"
					count = 0
					for x in (0, 1, 2, 3, 4, 5, 6):
						if flags == 1: # weekly
							print "Set to weekday " + str(x)
							weekday = x
						if flags & 1 == 1: # set user defined flags
							day[x] = 1
							count += 1
						else:
							day[x] = 0
						flags = flags >> 1
					if count == 1:
						repeated = "weekly"
			else: # once
				type = "once"
				repeated = None
				weekday = int(strftime("%u", localtime(self.timer.begin))) - 1
				day[weekday] = 1

			self.timerentry_justplay = ConfigSelection(choices = [
				("zap", _("zap")), ("record", _("record")), ("zap+record", _("zap and record"))],
				default = {0: "record", 1: "zap", 2: "zap+record"}[justplay + 2*always_zap])
			if SystemInfo["DeepstandbySupport"]:
				shutdownString = _("go to deep standby")
				choicelist = [("always", _("always")), ("from_standby", _("only from standby")), ("from_deep_standby", _("only from deep standby")), ("never", _("never"))]
			else:
				shutdownString = _("shut down")
				choicelist = [("always", _("always")), ("never", _("never"))]
			self.timerentry_zapwakeup = ConfigSelection(choices = choicelist, default = zap_wakeup)
			self.timerentry_afterevent = ConfigSelection(choices = [("nothing", _("do nothing")), ("standby", _("go to standby")), ("deepstandby", shutdownString), ("auto", _("auto"))], default = afterevent)
			self.timerentry_recordingtype = ConfigSelection(choices = [("normal", _("normal")), ("descrambled+ecm", _("descramble and record ecm")), ("scrambled+ecm", _("don't descramble, record ecm"))], default = recordingtype)
			self.timerentry_type = ConfigSelection(choices = [("once",_("once")), ("repeated", _("repeated"))], default = type)
			self.timerentry_name = ConfigText(default = self.timer.name, visible_width = 50, fixed_size = False)
			self.timerentry_description = ConfigText(default = self.timer.description, visible_width = 50, fixed_size = False)
			self.timerentry_tags = self.timer.tags[:]
			self.timerentry_tagsset = ConfigSelection(choices = [not self.timerentry_tags and "None" or " ".join(self.timerentry_tags)])

			self.timerentry_repeated = ConfigSelection(default = repeated, choices = [("weekly", _("weekly")), ("daily", _("daily")), ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])
			self.timerentry_renamerepeat = ConfigYesNo(default = rename_repeat)

			self.timerentry_date = ConfigDateTime(default = self.timer.begin, formatstring = _("%d.%B %Y"), increment = 86400)
			self.timerentry_starttime = ConfigClock(default = self.timer.begin)
			self.timerentry_endtime = ConfigClock(default = self.timer.end)
			self.timerentry_showendtime = ConfigSelection(default = ((self.timer.end - self.timer.begin) > 4), choices = [(True, _("yes")), (False, _("no"))])

			default = self.timer.dirname or defaultMoviePath()
			tmp = config.movielist.videodirs.value
			if default not in tmp:
				tmp.append(default)
			self.timerentry_dirname = ConfigSelection(default = default, choices = tmp)

			self.timerentry_repeatedbegindate = ConfigDateTime(default = self.timer.repeatedbegindate, formatstring = _("%d.%B %Y"), increment = 86400)

			self.timerentry_weekday = ConfigSelection(default = weekday_table[weekday], choices = [("mon",_("Monday")), ("tue", _("Tuesday")), ("wed",_("Wednesday")), ("thu", _("Thursday")), ("fri", _("Friday")), ("sat", _("Saturday")), ("sun", _("Sunday"))])

			self.timerentry_day = ConfigSubList()
			for x in (0, 1, 2, 3, 4, 5, 6):
				self.timerentry_day.append(ConfigYesNo(default = day[x]))

			# FIXME some service-chooser needed here
			servicename = "N/A"
			try: # no current service available?
				servicename = str(self.timer.service_ref.getServiceName())
			except:
				pass
			self.timerentry_service_ref = self.timer.service_ref
			self.timerentry_service = ConfigSelection([servicename])

	def createSetup(self, widget):
		self.list = []
		self.entryName = getConfigListEntry(_("Name"), self.timerentry_name)
		self.list.append(self.entryName)
		self.entryDescription = getConfigListEntry(_("Description"), self.timerentry_description)
		self.list.append(self.entryDescription)
		self.timerJustplayEntry = getConfigListEntry(_("Timer type"), self.timerentry_justplay)
		self.list.append(self.timerJustplayEntry)
		self.timerTypeEntry = getConfigListEntry(_("Repeat type"), self.timerentry_type)
		self.list.append(self.timerTypeEntry)

		if self.timerentry_type.value == "once":
			self.frequencyEntry = None
		else: # repeated
			self.frequencyEntry = getConfigListEntry(_("Repeats"), self.timerentry_repeated)
			self.list.append(self.frequencyEntry)
			self.repeatedbegindateEntry = getConfigListEntry(_("Starting on"), self.timerentry_repeatedbegindate)
			self.list.append(self.repeatedbegindateEntry)
			if self.timerentry_repeated.value == "daily":
				pass
			if self.timerentry_repeated.value == "weekdays":
				pass
			if self.timerentry_repeated.value == "weekly":
				self.list.append(getConfigListEntry(_("Weekday"), self.timerentry_weekday))

			if self.timerentry_repeated.value == "user":
				self.list.append(getConfigListEntry(_("Monday"), self.timerentry_day[0]))
				self.list.append(getConfigListEntry(_("Tuesday"), self.timerentry_day[1]))
				self.list.append(getConfigListEntry(_("Wednesday"), self.timerentry_day[2]))
				self.list.append(getConfigListEntry(_("Thursday"), self.timerentry_day[3]))
				self.list.append(getConfigListEntry(_("Friday"), self.timerentry_day[4]))
				self.list.append(getConfigListEntry(_("Saturday"), self.timerentry_day[5]))
				self.list.append(getConfigListEntry(_("Sunday"), self.timerentry_day[6]))
			if self.timerentry_justplay.value != "zap":
				self.list.append(getConfigListEntry(_("Rename name and description for new events"), self.timerentry_renamerepeat))

		self.entryDate = getConfigListEntry(_("Date"), self.timerentry_date)
		if self.timerentry_type.value == "once":
			self.list.append(self.entryDate)

		self.entryStartTime = getConfigListEntry(_("Start time"), self.timerentry_starttime)
		self.list.append(self.entryStartTime)

		self.entryShowEndTime = getConfigListEntry(_("Set end time"), self.timerentry_showendtime)
		self.entryZapWakeup = getConfigListEntry(_("Wakeup receiver for start timer"), self.timerentry_zapwakeup)
		if self.timerentry_justplay.value == "zap":
			self.list.append(self.entryZapWakeup)
			self.list.append(self.entryShowEndTime)
			self["key_blue"].setText(_("Wakeup type"))
		else:
			self["key_blue"].setText("")
		self.entryEndTime = getConfigListEntry(_("End time"), self.timerentry_endtime)
		if self.timerentry_justplay.value != "zap" or self.timerentry_showendtime.value:
			self.list.append(self.entryEndTime)

		self.channelEntry = getConfigListEntry(_("Channel"), self.timerentry_service)
		self.list.append(self.channelEntry)

		self.dirname = getConfigListEntry(_("Location"), self.timerentry_dirname)
		self.tagsSet = getConfigListEntry(_("Tags"), self.timerentry_tagsset)
		if self.timerentry_justplay.value != "zap":
			if config.usage.setup_level.index >= 2: # expert+
				self.list.append(self.dirname)
			if getPreferredTagEditor():
				self.list.append(self.tagsSet)
			self.list.append(getConfigListEntry(_("After event"), self.timerentry_afterevent))
			self.list.append(getConfigListEntry(_("Recording type"), self.timerentry_recordingtype))

		self[widget].list = self.list
		self[widget].l.setList(self.list)

	def newConfig(self):
		print "newConfig", self["config"].getCurrent()
		if self["config"].getCurrent() in (self.timerTypeEntry, self.timerJustplayEntry, self.frequencyEntry, self.entryShowEndTime):
			self.createSetup("config")

	def keyLeft(self):
		cur = self["config"].getCurrent()
		if cur in (self.channelEntry, self.tagsSet):
			self.keySelect()
		elif cur in (self.entryName, self.entryDescription):
			self.renameEntry()
		else:
			ConfigListScreen.keyLeft(self)
			self.newConfig()

	def keyRight(self):
		cur = self["config"].getCurrent()
		if cur in (self.channelEntry, self.tagsSet):
			self.keySelect()
		elif cur in (self.entryName, self.entryDescription):
			self.renameEntry()
		else:
			ConfigListScreen.keyRight(self)
			self.newConfig()

	def renameEntry(self):
		cur = self["config"].getCurrent()
		if cur == self.entryName:
			title_text = _("Please enter new name:")
			old_text = self.timerentry_name.value
		else:
			title_text = _("Please enter new description:")
			old_text = self.timerentry_description.value
		self.session.openWithCallback(self.renameEntryCallback, VirtualKeyBoard, title=title_text, text=old_text)

	def renameEntryCallback(self, answer):
		if answer:
			cur = self["config"].getCurrent()
			if cur == self.entryName:
				self.timerentry_name.value = answer
				self["config"].invalidate(self.entryName)
			else:
				self.timerentry_description.value = answer
				self["config"].invalidate(self.entryDescription)

	def handleKeyFileCallback(self, answer):
		if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
			self.keySelect()
		else:
			ConfigListScreen.handleKeyFileCallback(self, answer)
			self.newConfig()

	def openMovieLocationBox(self, answer=""):
		self.session.openWithCallback(
			self.pathSelected,
			MovieLocationBox,
			_("Select target folder"),
			self.timerentry_dirname.value,
			filename = answer,
			minFree = 100 # We require at least 100MB free space
			)

	def keySelect(self):
		cur = self["config"].getCurrent()
		if cur == self.channelEntry:
			self.session.openWithCallback(
				self.finishedChannelSelection,
				ChannelSelection.SimpleChannelSelection,
				_("Select channel to record from"),
				currentBouquet=True
			)
		elif config.usage.setup_level.index >= 2 and cur == self.dirname:
			menu = [(_("Open select location"), "empty")]
			if self.timerentry_type.value == "repeated" and self.timerentry_name.value:
				menu.append((_("Open select location as timer name"), "timername"))
			if len(menu) == 1:
				self.openMovieLocationBox()
			elif len(menu) == 2:
				text = _("Select action")
				def selectAction(choice):
					if choice:
						if choice[1] == "timername":
							self.openMovieLocationBox(self.timerentry_name.value)
						elif choice[1] == "empty":
							self.openMovieLocationBox()
				self.session.openWithCallback(selectAction, ChoiceBox, title=text, list=menu)

		elif getPreferredTagEditor() and cur == self.tagsSet:
			self.session.openWithCallback(
				self.tagEditFinished,
				getPreferredTagEditor(),
				self.timerentry_tags
			)
		else:
			self.keyGo()

	def finishedChannelSelection(self, *args):
		if args:
			self.timerentry_service_ref = ServiceReference(args[0])
			self.timerentry_service.setCurrentText(self.timerentry_service_ref.getServiceName())
			self["config"].invalidate(self.channelEntry)

	def getTimestamp(self, date, mytime):
		d = localtime(date)
		dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
		return int(mktime(dt.timetuple()))

	def getBeginEnd(self):
		date = self.timerentry_date.value
		endtime = self.timerentry_endtime.value
		starttime = self.timerentry_starttime.value

		begin = self.getTimestamp(date, starttime)
		end = self.getTimestamp(date, endtime)

		# if the endtime is less than the starttime, add 1 day.
		if end < begin:
			end += 86400
		return begin, end

	def selectChannelSelector(self, *args):
		self.session.openWithCallback(
				self.finishedChannelSelectionCorrection,
				ChannelSelection.SimpleChannelSelection,
				_("Select channel to record from")
			)

	def finishedChannelSelectionCorrection(self, *args):
		if args:
			self.finishedChannelSelection(*args)
			self.keyGo()

	def keyGo(self, result = None):
		if not self.timerentry_service_ref.isRecordable():
			self.session.openWithCallback(self.selectChannelSelector, MessageBox, _("You didn't select a channel to record from."), MessageBox.TYPE_ERROR)
			return
		self.timer.name = self.timerentry_name.value
		self.timer.description = self.timerentry_description.value
		self.timer.justplay = self.timerentry_justplay.value == "zap"
		self.timer.always_zap = self.timerentry_justplay.value == "zap+record"
		self.timer.zap_wakeup = self.timerentry_zapwakeup.value
		self.timer.rename_repeat = self.timerentry_renamerepeat.value
		if self.timerentry_justplay.value == "zap":
			if not self.timerentry_showendtime.value:
				self.timerentry_endtime.value = self.timerentry_starttime.value
				self.timerentry_afterevent.value = "nothing"
		self.timer.resetRepeated()
		self.timer.afterEvent = {
			"nothing": AFTEREVENT.NONE,
			"deepstandby": AFTEREVENT.DEEPSTANDBY,
			"standby": AFTEREVENT.STANDBY,
			"auto": AFTEREVENT.AUTO
			}[self.timerentry_afterevent.value]
		self.timer.descramble = {
			"normal": True,
			"descrambled+ecm": True,
			"scrambled+ecm": False,
			}[self.timerentry_recordingtype.value]
		self.timer.record_ecm = {
			"normal": False,
			"descrambled+ecm": True,
			"scrambled+ecm": True,
			}[self.timerentry_recordingtype.value]
		self.timer.service_ref = self.timerentry_service_ref
		self.timer.tags = self.timerentry_tags

		if self.timer.dirname or self.timerentry_dirname.value != defaultMoviePath():
			self.timer.dirname = self.timerentry_dirname.value
			config.movielist.last_timer_videodir.value = self.timer.dirname
			config.movielist.last_timer_videodir.save()

		if self.timerentry_type.value == "once":
			self.timer.begin, self.timer.end = self.getBeginEnd()
		if self.timerentry_type.value == "repeated":
			if self.timerentry_repeated.value == "daily":
				for x in (0, 1, 2, 3, 4, 5, 6):
					self.timer.setRepeated(x)

			if self.timerentry_repeated.value == "weekly":
				self.timer.setRepeated(self.timerentry_weekday.index)

			if self.timerentry_repeated.value == "weekdays":
				for x in (0, 1, 2, 3, 4):
					self.timer.setRepeated(x)

			if self.timerentry_repeated.value == "user":
				for x in (0, 1, 2, 3, 4, 5, 6):
					if self.timerentry_day[x].value:
						self.timer.setRepeated(x)

			self.timer.repeatedbegindate = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
			if self.timer.repeated:
				self.timer.begin = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
				self.timer.end = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_endtime.value)
			else:
				self.timer.begin = self.getTimestamp(time.time(), self.timerentry_starttime.value)
				self.timer.end = self.getTimestamp(time.time(), self.timerentry_endtime.value)

			# when a timer end is set before the start, add 1 day
			if self.timer.end < self.timer.begin:
				self.timer.end += 86400

		if self.timer.eit is not None:
			event = eEPGCache.getInstance().lookupEventId(self.timer.service_ref.ref, self.timer.eit)
			if event:
				n = event.getNumOfLinkageServices()
				if n > 1:
					tlist = []
					ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
					parent = self.timer.service_ref.ref
					selection = 0
					for x in range(n):
						i = event.getLinkageService(parent, x)
						if i.toString() == ref.toString():
							selection = x
						tlist.append((i.getName(), i))
					self.session.openWithCallback(self.subserviceSelected, ChoiceBox, title=_("Please select a subservice to record..."), list = tlist, selection = selection)
					return
				elif n > 0:
					parent = self.timer.service_ref.ref
					self.timer.service_ref = ServiceReference(event.getLinkageService(parent, 0))
		self.saveTimer()
		self.close((True, self.timer))

	def changeTimerType(self):
		self.timerentry_justplay.selectNext()
		self.timerJustplayEntry = getConfigListEntry(_("Timer type"), self.timerentry_justplay)
		self["config"].invalidate(self.timerJustplayEntry)
		self.createSetup("config")

	def changeZapWakeupType(self):
		if self.timerentry_justplay.value == "zap":
			self.timerentry_zapwakeup.selectNext()
			self["config"].invalidate(self.entryZapWakeup)

	def incrementStart(self):
		self.timerentry_starttime.increment()
		self["config"].invalidate(self.entryStartTime)
		if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [0, 0]:
			self.timerentry_date.value = self.timerentry_date.value + 86400
			self["config"].invalidate(self.entryDate)

	def decrementStart(self):
		self.timerentry_starttime.decrement()
		self["config"].invalidate(self.entryStartTime)
		if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [23, 59]:
			self.timerentry_date.value = self.timerentry_date.value - 86400
			self["config"].invalidate(self.entryDate)

	def incrementEnd(self):
		if self.entryEndTime is not None:
			self.timerentry_endtime.increment()
			self["config"].invalidate(self.entryEndTime)

	def decrementEnd(self):
		if self.entryEndTime is not None:
			self.timerentry_endtime.decrement()
			self["config"].invalidate(self.entryEndTime)

	def subserviceSelected(self, service):
		if not service is None:
			self.timer.service_ref = ServiceReference(service[1])
		self.saveTimer()
		self.close((True, self.timer))

	def saveTimer(self):
		self.session.nav.RecordTimer.saveTimer()

	def keyCancel(self):
		self.close((False,))

	def pathSelected(self, res):
		if res is not None:
			if config.movielist.videodirs.value != self.timerentry_dirname.choices:
				self.timerentry_dirname.setChoices(config.movielist.videodirs.value, default=res)
			self.timerentry_dirname.value = res

	def tagEditFinished(self, ret):
		if ret is not None:
			self.timerentry_tags = ret
			self.timerentry_tagsset.setChoices([not ret and "None" or " ".join(ret)])
			self["config"].invalidate(self.tagsSet)
class TimerEntry(Screen, ConfigListScreen):
    EMPTY = 0

    def __init__(self, session, timer):
        Screen.__init__(self, session)
        self.timer = timer

        self.timer.service_ref_prev = self.timer.service_ref
        self.timer.begin_prev = self.timer.begin
        self.timer.end_prev = self.timer.end
        self.timer.external_prev = self.timer.external
        self.timer.dirname_prev = self.timer.dirname

        self.entryDate = None
        self.entryService = None
        self.key_red_choice = self.EMPTY

        if self.key_red_choice != Pixmap:
            self["key_red"] = StaticText(_("Cancel"))
            self["key_green"] = StaticText(_("Save"))
            self["key_yellow"] = StaticText(_("Timer type"))
            self["key_blue"] = StaticText("")
        if self.key_red_choice != StaticText:
            self["oktext"] = Label(_("OK"))
            self["canceltext"] = Label(_("Cancel"))
            self["ok"] = Pixmap()
            self["cancel"] = Pixmap()

        self["actions"] = NumberActionMap(
            [
                "SetupActions", "GlobalActions", "PiPSetupActions",
                "ColorActions"
            ], {
                "ok": self.keySelect,
                "save": self.keyGo,
                "cancel": self.keyCancel,
                "volumeUp": self.incrementStart,
                "volumeDown": self.decrementStart,
                "size+": self.incrementEnd,
                "size-": self.decrementEnd,
                "red": self.keyCancel,
                "green": self.keyGo,
                "yellow": self.changeTimerType,
                "blue": self.changeZapWakeupType
            }, -2)

        self.list = []

        ConfigListScreen.__init__(self, self.list, session=session)
        self.setTitle(_("Timer entry"))
        FallbackTimerDirs(self, self.createConfig)

    def createConfig(self, currlocation=None, locations=[]):
        justplay = self.timer.justplay
        always_zap = self.timer.always_zap
        zap_wakeup = self.timer.zap_wakeup
        pipzap = self.timer.pipzap
        rename_repeat = self.timer.rename_repeat
        conflict_detection = self.timer.conflict_detection

        afterevent = {
            AFTEREVENT.NONE: "nothing",
            AFTEREVENT.DEEPSTANDBY: "deepstandby",
            AFTEREVENT.STANDBY: "standby",
            AFTEREVENT.AUTO: "auto"
        }[self.timer.afterEvent]

        if self.timer.record_ecm and self.timer.descramble:
            recordingtype = "descrambled+ecm"
        elif self.timer.record_ecm:
            recordingtype = "scrambled+ecm"
        elif self.timer.descramble:
            recordingtype = "normal"

        weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")

        day = list(
            [int(x) for x in reversed('{0:07b}'.format(self.timer.repeated))])
        weekday = 0
        if self.timer.repeated:  # repeated
            type = "repeated"
            if (self.timer.repeated == 31):  # Mon-Fri
                repeated = "weekdays"
            elif (self.timer.repeated == 127):  # daily
                repeated = "daily"
            else:
                repeated = "user"
                if day.count(1) == 1:
                    repeated = "weekly"
                    weekday = day.index(1)
        else:  # once
            type = "once"
            repeated = None
            weekday = int(strftime("%u", localtime(self.timer.begin))) - 1
            day[weekday] = 1
        self.timerentry_fallback = ConfigYesNo(
            default=self.timer.external_prev or
            config.usage.remote_fallback_external_timer.value and config.usage.
            remote_fallback.value and not nimmanager.somethingConnected())
        self.timerentry_justplay = ConfigSelection(
            choices=[("zap", _("zap")), ("record", _("record")),
                     ("zap+record", _("zap and record"))],
            default={
                0: "record",
                1: "zap",
                2: "zap+record"
            }[justplay + 2 * always_zap])
        if SystemInfo["DeepstandbySupport"]:
            shutdownString = _("go to deep standby")
            choicelist = [("always", _("always")),
                          ("from_standby", _("only from standby")),
                          ("from_deep_standby", _("only from deep standby")),
                          ("never", _("never"))]
        else:
            shutdownString = _("shut down")
            choicelist = [("always", _("always")), ("never", _("never"))]
        self.timerentry_zapwakeup = ConfigSelection(choices=choicelist,
                                                    default=zap_wakeup)
        self.timerentry_afterevent = ConfigSelection(choices=[
            ("nothing", _("do nothing")), ("standby", _("go to standby")),
            ("deepstandby", shutdownString), ("auto", _("auto"))
        ],
                                                     default=afterevent)
        self.timerentry_recordingtype = ConfigSelection(choices=[
            ("normal", _("normal")),
            ("descrambled+ecm", _("descramble and record ecm")),
            ("scrambled+ecm", _("don't descramble, record ecm"))
        ],
                                                        default=recordingtype)
        self.timerentry_type = ConfigSelection(choices=[("once", _("once")),
                                                        ("repeated",
                                                         _("repeated"))],
                                               default=type)
        self.timerentry_name = ConfigText(default=self.timer.name,
                                          visible_width=50,
                                          fixed_size=False)
        self.timerentry_description = ConfigText(
            default=self.timer.description, visible_width=50, fixed_size=False)
        self.timerentry_tags = self.timer.tags[:]
        self.timerentry_tagsset = ConfigSelection(choices=[
            not self.timerentry_tags and _("None")
            or " ".join(self.timerentry_tags)
        ])

        self.timerentry_repeated = ConfigSelection(
            default=repeated,
            choices=[("weekly", _("weekly")), ("daily", _("daily")),
                     ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])
        self.timerentry_renamerepeat = ConfigYesNo(default=rename_repeat)
        self.timerentry_pipzap = ConfigYesNo(default=pipzap)
        self.timerentry_conflictdetection = ConfigYesNo(
            default=conflict_detection)

        self.timerentry_date = ConfigDateTime(
            default=self.timer.begin,
            formatstring=config.usage.date.full.value,
            increment=86400)
        self.timerentry_starttime = ConfigClock(default=self.timer.begin)
        self.timerentry_endtime = ConfigClock(default=self.timer.end)
        self.timerentry_showendtime = ConfigSelection(
            default=((self.timer.end - self.timer.begin) > 4),
            choices=[(True, _("yes")), (False, _("no"))])

        default = not self.timer.external_prev and self.timer.dirname or defaultMoviePath(
        )
        tmp = config.movielist.videodirs.value
        if default not in tmp:
            tmp.append(default)
        self.timerentry_dirname = ConfigSelection(default=default, choices=tmp)

        default = self.timer.external_prev and self.timer.dirname or currlocation
        if default not in locations:
            locations.append(default)
        self.timerentry_fallbackdirname = ConfigSelection(default=default,
                                                          choices=locations)

        self.timerentry_repeatedbegindate = ConfigDateTime(
            default=self.timer.repeatedbegindate,
            formatstring=config.usage.date.full.value,
            increment=86400)

        self.timerentry_weekday = ConfigSelection(
            default=weekday_table[weekday],
            choices=[("mon", _("Monday")), ("tue", _("Tuesday")),
                     ("wed", _("Wednesday")), ("thu", _("Thursday")),
                     ("fri", _("Friday")), ("sat", _("Saturday")),
                     ("sun", _("Sunday"))])

        self.timerentry_day = ConfigSubList()
        for x in (0, 1, 2, 3, 4, 5, 6):
            self.timerentry_day.append(ConfigYesNo(default=day[x]))

        # FIXME some service-chooser needed here
        servicename = "N/A"
        try:  # no current service available?
            servicename = str(self.timer.service_ref.getServiceName())
        except:
            pass
        self.timerentry_service_ref = self.timer.service_ref
        self.timerentry_service = ConfigSelection([servicename])
        self.createSetup("config")

    def createSetup(self, widget):
        self.list = []
        self.entryFallbackTimer = getConfigListEntry(_("Fallback Timer"),
                                                     self.timerentry_fallback)
        if config.usage.remote_fallback_external_timer.value and config.usage.remote_fallback.value and not hasattr(
                self, "timerentry_remote"):
            self.list.append(self.entryFallbackTimer)
        self.entryName = getConfigListEntry(_("Name"), self.timerentry_name)
        self.list.append(self.entryName)
        self.entryDescription = getConfigListEntry(_("Description"),
                                                   self.timerentry_description)
        self.list.append(self.entryDescription)
        self.timerJustplayEntry = getConfigListEntry(_("Timer type"),
                                                     self.timerentry_justplay)
        if config.usage.setup_level.index >= 1:
            self.list.append(self.timerJustplayEntry)
        self.timerTypeEntry = getConfigListEntry(_("Repeat type"),
                                                 self.timerentry_type)
        self.list.append(self.timerTypeEntry)

        if self.timerentry_type.value == "once":
            self.frequencyEntry = None
        else:  # repeated
            self.frequencyEntry = getConfigListEntry(_("Repeats"),
                                                     self.timerentry_repeated)
            self.list.append(self.frequencyEntry)
            self.repeatedbegindateEntry = getConfigListEntry(
                _("Starting on"), self.timerentry_repeatedbegindate)
            self.list.append(self.repeatedbegindateEntry)
            if self.timerentry_repeated.value == "daily":
                pass
            if self.timerentry_repeated.value == "weekdays":
                pass
            if self.timerentry_repeated.value == "weekly":
                self.list.append(
                    getConfigListEntry(_("Weekday"), self.timerentry_weekday))

            if self.timerentry_repeated.value == "user":
                self.list.append(
                    getConfigListEntry(_("Monday"), self.timerentry_day[0]))
                self.list.append(
                    getConfigListEntry(_("Tuesday"), self.timerentry_day[1]))
                self.list.append(
                    getConfigListEntry(_("Wednesday"), self.timerentry_day[2]))
                self.list.append(
                    getConfigListEntry(_("Thursday"), self.timerentry_day[3]))
                self.list.append(
                    getConfigListEntry(_("Friday"), self.timerentry_day[4]))
                self.list.append(
                    getConfigListEntry(_("Saturday"), self.timerentry_day[5]))
                self.list.append(
                    getConfigListEntry(_("Sunday"), self.timerentry_day[6]))
            if self.timerentry_justplay.value != "zap":
                self.list.append(
                    getConfigListEntry(
                        _("Rename name and description for new events"),
                        self.timerentry_renamerepeat))

        self.entryDate = getConfigListEntry(_("Date"), self.timerentry_date)
        if self.timerentry_type.value == "once":
            self.list.append(self.entryDate)

        self.entryStartTime = getConfigListEntry(_("Start time"),
                                                 self.timerentry_starttime)
        self.list.append(self.entryStartTime)

        self.entryShowEndTime = getConfigListEntry(_("Set end time"),
                                                   self.timerentry_showendtime)
        self.entryZapWakeup = getConfigListEntry(
            _("Wakeup receiver for start timer"), self.timerentry_zapwakeup)
        if self.timerentry_justplay.value == "zap":
            self.list.append(self.entryZapWakeup)
            if SystemInfo["PIPAvailable"]:
                self.list.append(
                    getConfigListEntry(_("Use as PiP if possible"),
                                       self.timerentry_pipzap))
            self.list.append(self.entryShowEndTime)
            self["key_blue"].setText(_("Wakeup type"))
        else:
            self["key_blue"].setText("")
        self.entryEndTime = getConfigListEntry(_("End time"),
                                               self.timerentry_endtime)
        if self.timerentry_justplay.value != "zap" or self.timerentry_showendtime.value:
            self.list.append(self.entryEndTime)

        self.channelEntry = getConfigListEntry(_("Channel"),
                                               self.timerentry_service)
        self.list.append(self.channelEntry)

        self.dirname = getConfigListEntry(
            _("Location"), self.timerentry_fallbackdirname
        ) if self.timerentry_fallback.value and self.timerentry_fallbackdirname.value else getConfigListEntry(
            _("Location"), self.timerentry_dirname)
        if config.usage.setup_level.index >= 2 and (
                self.timerentry_fallback.value
                and self.timerentry_fallbackdirname.value
                or self.timerentry_dirname.value):  # expert+
            self.list.append(self.dirname)

        self.conflictDetectionEntry = getConfigListEntry(
            _("Enable timer conflict detection"),
            self.timerentry_conflictdetection)
        if not self.timerentry_fallback.value:
            self.list.append(self.conflictDetectionEntry)

        self.tagsSet = getConfigListEntry(_("Tags"), self.timerentry_tagsset)
        if self.timerentry_justplay.value != "zap" and not self.timerentry_fallback.value:
            if getPreferredTagEditor():
                self.list.append(self.tagsSet)
            self.list.append(
                getConfigListEntry(_("After event"),
                                   self.timerentry_afterevent))
            self.list.append(
                getConfigListEntry(_("Recording type"),
                                   self.timerentry_recordingtype))

        self[widget].list = self.list
        self[widget].l.setList(self.list)

    def newConfig(self):
        print("[TimerEntry] newConfig", self["config"].getCurrent())
        if self["config"].getCurrent() in (self.timerTypeEntry,
                                           self.timerJustplayEntry,
                                           self.frequencyEntry,
                                           self.entryShowEndTime,
                                           self.entryFallbackTimer):
            self.createSetup("config")

    def keyLeft(self):
        cur = self["config"].getCurrent()
        if cur in (self.channelEntry, self.tagsSet):
            self.keySelect()
        elif cur in (self.entryName, self.entryDescription):
            self.renameEntry()
        else:
            ConfigListScreen.keyLeft(self)
            self.newConfig()

    def keyRight(self):
        cur = self["config"].getCurrent()
        if cur in (self.channelEntry, self.tagsSet):
            self.keySelect()
        elif cur in (self.entryName, self.entryDescription):
            self.renameEntry()
        else:
            ConfigListScreen.keyRight(self)
            self.newConfig()

    def renameEntry(self):
        cur = self["config"].getCurrent()
        if cur == self.entryName:
            title_text = _("Please enter new name:")
            old_text = self.timerentry_name.value
        else:
            title_text = _("Please enter new description:")
            old_text = self.timerentry_description.value
        self.session.openWithCallback(self.renameEntryCallback,
                                      VirtualKeyBoard,
                                      title=title_text,
                                      text=old_text)

    def renameEntryCallback(self, answer):
        if answer:
            cur = self["config"].getCurrent()
            if cur == self.entryName:
                self.timerentry_name.value = answer
                self["config"].invalidate(self.entryName)
            else:
                self.timerentry_description.value = answer
                self["config"].invalidate(self.entryDescription)

    def handleKeyFileCallback(self, answer):
        if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.handleKeyFileCallback(self, answer)
            self.newConfig()

    def openMovieLocationBox(self, answer=""):
        self.session.openWithCallback(
            self.pathSelected,
            MovieLocationBox,
            _("Select target folder"),
            self.timerentry_dirname.value,
            filename=answer,
            minFree=100  # We require at least 100MB free space
        )

    def keySelect(self):
        cur = self["config"].getCurrent()
        if cur == self.channelEntry:
            self.session.openWithCallback(
                self.finishedChannelSelection,
                ChannelSelection.SimpleChannelSelection,
                _("Select channel to record from"),
                currentBouquet=True)
        elif cur == self.dirname:
            menu = [(_("Open select location"), "empty")]
            if self.timerentry_type.value == "repeated" and self.timerentry_name.value:
                menu.append(
                    (_("Open select location as timer name"), "timername"))
            if len(menu) == 1:
                self.openMovieLocationBox()
            elif len(menu) == 2:
                text = _("Select action")

                def selectAction(choice):
                    if choice:
                        if choice[1] == "timername":
                            self.openMovieLocationBox(
                                self.timerentry_name.value)
                        elif choice[1] == "empty":
                            self.openMovieLocationBox()

                self.session.openWithCallback(selectAction,
                                              ChoiceBox,
                                              title=text,
                                              list=menu)

        elif getPreferredTagEditor() and cur == self.tagsSet:
            self.session.openWithCallback(self.tagEditFinished,
                                          getPreferredTagEditor(),
                                          self.timerentry_tags)
        else:
            self.keyGo()

    def finishedChannelSelection(self, *args):
        if args:
            self.timerentry_service_ref = ServiceReference(args[0])
            self.timerentry_service.setCurrentText(
                self.timerentry_service_ref.getServiceName())
            self["config"].invalidate(self.channelEntry)

    def getTimestamp(self, date, mytime):
        d = localtime(date)
        dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
        return int(mktime(dt.timetuple()))

    def getBeginEnd(self):
        date = self.timerentry_date.value
        endtime = self.timerentry_endtime.value
        starttime = self.timerentry_starttime.value

        begin = self.getTimestamp(date, starttime)
        end = self.getTimestamp(date, endtime)

        # if the endtime is less than the starttime, add 1 day.
        if end < begin:
            end += 86400
        return begin, end

    def selectChannelSelector(self, *args):
        self.session.openWithCallback(self.finishedChannelSelectionCorrection,
                                      ChannelSelection.SimpleChannelSelection,
                                      _("Select channel to record from"))

    def finishedChannelSelectionCorrection(self, *args):
        if args:
            self.finishedChannelSelection(*args)
            self.keyGo()

    def RemoteSubserviceSelected(self, service):
        if service:
            # ouch, this hurts a little
            service_ref = timerentry_service_ref
            self.timerentry_service_ref = ServiceReference(service[1])
            eit = self.timer.eit
            self.timer.eit = None
            self.keyGo()
            self.timerentry_service_ref = service_ref
            self.timer.eit = eit

    def keyGo(self, result=None):
        if not self.timerentry_service_ref.isRecordable():
            self.session.openWithCallback(
                self.selectChannelSelector, MessageBox,
                _("You didn't select a channel to record from."),
                MessageBox.TYPE_ERROR)
        else:
            self.timer.external = self.timerentry_fallback.value
            self.timer.name = self.timerentry_name.value
            self.timer.description = self.timerentry_description.value
            self.timer.justplay = self.timerentry_justplay.value == "zap"
            self.timer.always_zap = self.timerentry_justplay.value == "zap+record"
            self.timer.zap_wakeup = self.timerentry_zapwakeup.value
            self.timer.pipzap = self.timerentry_pipzap.value
            self.timer.rename_repeat = self.timerentry_renamerepeat.value
            self.timer.conflict_detection = self.timerentry_conflictdetection.value
            if self.timerentry_justplay.value == "zap":
                if not self.timerentry_showendtime.value:
                    self.timerentry_endtime.value = self.timerentry_starttime.value
                    self.timerentry_afterevent.value = "nothing"
            self.timer.resetRepeated()
            self.timer.afterEvent = {
                "nothing": AFTEREVENT.NONE,
                "deepstandby": AFTEREVENT.DEEPSTANDBY,
                "standby": AFTEREVENT.STANDBY,
                "auto": AFTEREVENT.AUTO
            }[self.timerentry_afterevent.value]
            # There is no point doing anything after a Zap-only timer!
            # For a start, you can't actually configure anything in the menu, but
            # leaving it as AUTO means that the code may try to shutdown at Zap time
            # if the Zap timer woke the box up.
            #
            if self.timer.justplay:
                self.timer.afterEvent = AFTEREVENT.NONE
            self.timer.descramble = {
                "normal": True,
                "descrambled+ecm": True,
                "scrambled+ecm": False,
            }[self.timerentry_recordingtype.value]
            self.timer.record_ecm = {
                "normal": False,
                "descrambled+ecm": True,
                "scrambled+ecm": True,
            }[self.timerentry_recordingtype.value]
            self.timer.service_ref = self.timerentry_service_ref
            self.timer.tags = self.timerentry_tags

            # reset state when edit timer type
            if not self.timer.external and self.timer.justplay != "zap" and self.timer.isRunning(
            ):
                if self.timer in self.session.nav.RecordTimer.timer_list and (
                        not self.timer.record_service or not isinstance(
                            self.timer.record_service, iRecordableServicePtr)):
                    self.timer.resetState()

            if self.timerentry_fallback.value:
                self.timer.dirname = self.timerentry_fallbackdirname.value
            else:
                if self.timer.dirname or self.timerentry_dirname.value != defaultMoviePath(
                ):
                    self.timer.dirname = self.timerentry_dirname.value
                    config.movielist.last_timer_videodir.value = self.timer.dirname
                    config.movielist.last_timer_videodir.save()

            if self.timerentry_type.value == "once":
                self.timer.begin, self.timer.end = self.getBeginEnd()
            if self.timerentry_type.value == "repeated":
                if self.timerentry_repeated.value == "daily":
                    for x in (0, 1, 2, 3, 4, 5, 6):
                        self.timer.setRepeated(x)

                if self.timerentry_repeated.value == "weekly":
                    self.timer.setRepeated(self.timerentry_weekday.index)

                if self.timerentry_repeated.value == "weekdays":
                    for x in (0, 1, 2, 3, 4):
                        self.timer.setRepeated(x)

                if self.timerentry_repeated.value == "user":
                    for x in (0, 1, 2, 3, 4, 5, 6):
                        if self.timerentry_day[x].value:
                            self.timer.setRepeated(x)

                self.timer.repeatedbegindate = self.getTimestamp(
                    self.timerentry_repeatedbegindate.value,
                    self.timerentry_starttime.value)
                if self.timer.repeated:
                    self.timer.begin = self.getTimestamp(
                        self.timerentry_repeatedbegindate.value,
                        self.timerentry_starttime.value)
                    self.timer.end = self.getTimestamp(
                        self.timerentry_repeatedbegindate.value,
                        self.timerentry_endtime.value)
                else:
                    self.timer.begin = self.getTimestamp(
                        time(), self.timerentry_starttime.value)
                    self.timer.end = self.getTimestamp(
                        time(), self.timerentry_endtime.value)

                # when a timer end is set before the start, add 1 day
                if self.timer.end < self.timer.begin:
                    self.timer.end += 86400

            if self.timer.eit is not None:
                event = eEPGCache.getInstance().lookupEventId(
                    self.timer.service_ref.ref, self.timer.eit)
                if event:
                    n = event.getNumOfLinkageServices()
                    if n > 1:
                        tlist = []
                        ref = self.session.nav.getCurrentlyPlayingServiceOrGroup(
                        )
                        parent = self.timer.service_ref.ref
                        selection = 0
                        for x in range(n):
                            i = event.getLinkageService(parent, x)
                            if i.toString() == ref.toString():
                                selection = x
                            tlist.append((i.getName(), i))
                        self.session.openWithCallback(
                            self.subserviceSelected,
                            ChoiceBox,
                            title=_("Please select a subservice to record..."),
                            list=tlist,
                            selection=selection)
                        return
                    elif n > 0:
                        parent = self.timer.service_ref.ref
                        self.timer.service_ref = ServiceReference(
                            event.getLinkageService(parent, 0))
            self.saveTimer()
            self.close((True, self.timer))

    def changeTimerType(self):
        self.timerentry_justplay.selectNext()
        self.timerJustplayEntry = getConfigListEntry(_("Timer type"),
                                                     self.timerentry_justplay)
        self["config"].invalidate(self.timerJustplayEntry)
        self.createSetup("config")

    def changeZapWakeupType(self):
        if self.timerentry_justplay.value == "zap":
            self.timerentry_zapwakeup.selectNext()
            self["config"].invalidate(self.entryZapWakeup)

    def incrementStart(self):
        self.timerentry_starttime.increment()
        self["config"].invalidate(self.entryStartTime)
        if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [
                0, 0
        ]:
            self.timerentry_date.value += 86400
            self["config"].invalidate(self.entryDate)

    def decrementStart(self):
        self.timerentry_starttime.decrement()
        self["config"].invalidate(self.entryStartTime)
        if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [
                23, 59
        ]:
            self.timerentry_date.value -= 86400
            self["config"].invalidate(self.entryDate)

    def incrementEnd(self):
        if self.entryEndTime is not None:
            self.timerentry_endtime.increment()
            self["config"].invalidate(self.entryEndTime)

    def decrementEnd(self):
        if self.entryEndTime is not None:
            self.timerentry_endtime.decrement()
            self["config"].invalidate(self.entryEndTime)

    def subserviceSelected(self, service):
        if not service is None:
            self.timer.service_ref = ServiceReference(service[1])
        self.saveTimer()
        self.close((True, self.timer))

    def saveTimer(self):
        self.session.nav.RecordTimer.saveTimer()

    def keyCancel(self):
        self.close((False, ))

    def pathSelected(self, res):
        if res is not None:
            if config.movielist.videodirs.value != self.timerentry_dirname.choices:
                self.timerentry_dirname.setChoices(
                    config.movielist.videodirs.value, default=res)
            self.timerentry_dirname.value = res

    def tagEditFinished(self, ret):
        if ret is not None:
            self.timerentry_tags = ret
            self.timerentry_tagsset.setChoices(
                [not ret and _("None") or " ".join(ret)])
            self["config"].invalidate(self.tagsSet)
class TimerEntry(Screen, ConfigListScreen):
    def __init__(self, session, timer):
        Screen.__init__(self, session)
        self.timer = timer

        self.entryDate = None
        self.entryService = None

        self["oktext"] = Label(_("OK"))
        self["canceltext"] = Label(_("Cancel"))
        self["ok"] = Pixmap()
        self["cancel"] = Pixmap()
        self["key_yellow"] = Label(_("Timer type"))
        self["key_blue"] = Label()

        self.createConfig()

        self["actions"] = NumberActionMap(
            [
                "SetupActions", "GlobalActions", "PiPSetupActions",
                "ColorActions"
            ], {
                "ok": self.keySelect,
                "save": self.keyGo,
                "cancel": self.keyCancel,
                "volumeUp": self.incrementStart,
                "volumeDown": self.decrementStart,
                "size+": self.incrementEnd,
                "size-": self.decrementEnd,
                "yellow": self.changeTimerType,
                "blue": self.changeZapWakeupType
            }, -2)

        self.list = []
        ConfigListScreen.__init__(self, self.list, session=session)
        self.setTitle(_("Timer entry"))
        self.createSetup("config")

    def createConfig(self):
        justplay = self.timer.justplay
        always_zap = self.timer.always_zap
        zap_wakeup = self.timer.zap_wakeup

        afterevent = {
            AFTEREVENT.NONE: "nothing",
            AFTEREVENT.DEEPSTANDBY: "deepstandby",
            AFTEREVENT.STANDBY: "standby",
            AFTEREVENT.AUTO: "auto"
        }[self.timer.afterEvent]

        if self.timer.record_ecm and self.timer.descramble:
            recordingtype = "descrambled+ecm"
        elif self.timer.record_ecm:
            recordingtype = "scrambled+ecm"
        elif self.timer.descramble:
            recordingtype = "normal"

        weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")

        # calculate default values
        day = []
        weekday = 0
        for x in (0, 1, 2, 3, 4, 5, 6):
            day.append(0)
        if self.timer.repeated:  # repeated
            type = "repeated"
            if (self.timer.repeated == 31):  # Mon-Fri
                repeated = "weekdays"
            elif (self.timer.repeated == 127):  # daily
                repeated = "daily"
            else:
                flags = self.timer.repeated
                repeated = "user"
                count = 0
                for x in (0, 1, 2, 3, 4, 5, 6):
                    if flags == 1:  # weekly
                        print "Set to weekday " + str(x)
                        weekday = x
                    if flags & 1 == 1:  # set user defined flags
                        day[x] = 1
                        count += 1
                    else:
                        day[x] = 0
                    flags = flags >> 1
                if count == 1:
                    repeated = "weekly"
        else:  # once
            type = "once"
            repeated = None
            weekday = int(strftime("%u", localtime(self.timer.begin))) - 1
            day[weekday] = 1

        self.timerentry_justplay = ConfigSelection(
            choices=[("zap", _("zap")), ("record", _("record")),
                     ("zap+record", _("zap and record"))],
            default={
                0: "record",
                1: "zap",
                2: "zap+record"
            }[justplay + 2 * always_zap])
        if SystemInfo["DeepstandbySupport"]:
            shutdownString = _("go to deep standby")
            choicelist = [("always", _("always")),
                          ("from_standby", _("only from standby")),
                          ("from_deep_standby", _("only from deep standby")),
                          ("never", _("never"))]
        else:
            shutdownString = _("shut down")
            choicelist = [("always", _("always")), ("never", _("never"))]
        self.timerentry_zapwakeup = ConfigSelection(choices=choicelist,
                                                    default=zap_wakeup)
        self.timerentry_afterevent = ConfigSelection(choices=[
            ("nothing", _("do nothing")), ("standby", _("go to standby")),
            ("deepstandby", shutdownString), ("auto", _("auto"))
        ],
                                                     default=afterevent)
        self.timerentry_recordingtype = ConfigSelection(choices=[
            ("normal", _("normal")),
            ("descrambled+ecm", _("descramble and record ecm")),
            ("scrambled+ecm", _("don't descramble, record ecm"))
        ],
                                                        default=recordingtype)
        self.timerentry_type = ConfigSelection(choices=[("once", _("once")),
                                                        ("repeated",
                                                         _("repeated"))],
                                               default=type)
        self.timerentry_name = ConfigText(default=self.timer.name,
                                          visible_width=50,
                                          fixed_size=False)
        self.timerentry_description = ConfigText(
            default=self.timer.description, visible_width=50, fixed_size=False)
        self.timerentry_tags = self.timer.tags[:]
        self.timerentry_tagsset = ConfigSelection(choices=[
            not self.timerentry_tags and "None"
            or " ".join(self.timerentry_tags)
        ])

        self.timerentry_repeated = ConfigSelection(
            default=repeated,
            choices=[("weekly", _("weekly")), ("daily", _("daily")),
                     ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])

        self.timerentry_date = ConfigDateTime(default=self.timer.begin,
                                              formatstring=_("%d.%B %Y"),
                                              increment=86400)
        self.timerentry_starttime = ConfigClock(default=self.timer.begin)
        self.timerentry_endtime = ConfigClock(default=self.timer.end)
        self.timerentry_showendtime = ConfigSelection(
            default=((self.timer.end - self.timer.begin) > 4),
            choices=[(True, _("yes")), (False, _("no"))])

        default = self.timer.dirname or defaultMoviePath()
        tmp = config.movielist.videodirs.value
        if default not in tmp:
            tmp.append(default)
        self.timerentry_dirname = ConfigSelection(default=default, choices=tmp)

        self.timerentry_repeatedbegindate = ConfigDateTime(
            default=self.timer.repeatedbegindate,
            formatstring=_("%d.%B %Y"),
            increment=86400)

        self.timerentry_weekday = ConfigSelection(
            default=weekday_table[weekday],
            choices=[("mon", _("Monday")), ("tue", _("Tuesday")),
                     ("wed", _("Wednesday")), ("thu", _("Thursday")),
                     ("fri", _("Friday")), ("sat", _("Saturday")),
                     ("sun", _("Sunday"))])

        self.timerentry_day = ConfigSubList()
        for x in (0, 1, 2, 3, 4, 5, 6):
            self.timerentry_day.append(ConfigYesNo(default=day[x]))

        # FIXME some service-chooser needed here
        servicename = "N/A"
        try:  # no current service available?
            servicename = str(self.timer.service_ref.getServiceName())
        except:
            pass
        self.timerentry_service_ref = self.timer.service_ref
        self.timerentry_service = ConfigSelection([servicename])

    def createSetup(self, widget):
        self.list = []
        self.list.append(getConfigListEntry(_("Name"), self.timerentry_name))
        self.list.append(
            getConfigListEntry(_("Description"), self.timerentry_description))
        self.timerJustplayEntry = getConfigListEntry(_("Timer type"),
                                                     self.timerentry_justplay)
        self.list.append(self.timerJustplayEntry)
        self.timerTypeEntry = getConfigListEntry(_("Repeat type"),
                                                 self.timerentry_type)
        self.list.append(self.timerTypeEntry)

        if self.timerentry_type.value == "once":
            self.frequencyEntry = None
        else:  # repeated
            self.frequencyEntry = getConfigListEntry(_("Repeats"),
                                                     self.timerentry_repeated)
            self.list.append(self.frequencyEntry)
            self.repeatedbegindateEntry = getConfigListEntry(
                _("Starting on"), self.timerentry_repeatedbegindate)
            self.list.append(self.repeatedbegindateEntry)
            if self.timerentry_repeated.value == "daily":
                pass
            if self.timerentry_repeated.value == "weekdays":
                pass
            if self.timerentry_repeated.value == "weekly":
                self.list.append(
                    getConfigListEntry(_("Weekday"), self.timerentry_weekday))

            if self.timerentry_repeated.value == "user":
                self.list.append(
                    getConfigListEntry(_("Monday"), self.timerentry_day[0]))
                self.list.append(
                    getConfigListEntry(_("Tuesday"), self.timerentry_day[1]))
                self.list.append(
                    getConfigListEntry(_("Wednesday"), self.timerentry_day[2]))
                self.list.append(
                    getConfigListEntry(_("Thursday"), self.timerentry_day[3]))
                self.list.append(
                    getConfigListEntry(_("Friday"), self.timerentry_day[4]))
                self.list.append(
                    getConfigListEntry(_("Saturday"), self.timerentry_day[5]))
                self.list.append(
                    getConfigListEntry(_("Sunday"), self.timerentry_day[6]))

        self.entryDate = getConfigListEntry(_("Date"), self.timerentry_date)
        if self.timerentry_type.value == "once":
            self.list.append(self.entryDate)

        self.entryStartTime = getConfigListEntry(_("Start time"),
                                                 self.timerentry_starttime)
        self.list.append(self.entryStartTime)

        self.entryShowEndTime = getConfigListEntry(_("Set end time"),
                                                   self.timerentry_showendtime)
        self.entryZapWakeup = getConfigListEntry(
            _("Wakeup receiver for start timer"), self.timerentry_zapwakeup)
        if self.timerentry_justplay.value == "zap":
            self.list.append(self.entryZapWakeup)
            self.list.append(self.entryShowEndTime)
            self["key_blue"].setText(_("Wakeup type"))
        else:
            self["key_blue"].setText("")
        self.entryEndTime = getConfigListEntry(_("End time"),
                                               self.timerentry_endtime)
        if self.timerentry_justplay.value != "zap" or self.timerentry_showendtime.value:
            self.list.append(self.entryEndTime)

        self.channelEntry = getConfigListEntry(_("Channel"),
                                               self.timerentry_service)
        self.list.append(self.channelEntry)

        self.dirname = getConfigListEntry(_("Location"),
                                          self.timerentry_dirname)
        self.tagsSet = getConfigListEntry(_("Tags"), self.timerentry_tagsset)
        if self.timerentry_justplay.value != "zap":
            if config.usage.setup_level.index >= 2:  # expert+
                self.list.append(self.dirname)
            if getPreferredTagEditor():
                self.list.append(self.tagsSet)
            self.list.append(
                getConfigListEntry(_("After event"),
                                   self.timerentry_afterevent))
            self.list.append(
                getConfigListEntry(_("Recording type"),
                                   self.timerentry_recordingtype))

        self[widget].list = self.list
        self[widget].l.setList(self.list)

    def newConfig(self):
        print "newConfig", self["config"].getCurrent()
        if self["config"].getCurrent() in (self.timerTypeEntry,
                                           self.timerJustplayEntry,
                                           self.frequencyEntry,
                                           self.entryShowEndTime):
            self.createSetup("config")

    def keyLeft(self):
        if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.keyLeft(self)
            self.newConfig()

    def keyRight(self):
        if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.keyRight(self)
            self.newConfig()

    def handleKeyFileCallback(self, answer):
        if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.handleKeyFileCallback(self, answer)
            self.newConfig()

    def keySelect(self):
        cur = self["config"].getCurrent()
        if cur == self.channelEntry:
            self.session.openWithCallback(
                self.finishedChannelSelection,
                ChannelSelection.SimpleChannelSelection,
                _("Select channel to record from"),
                currentBouquet=True)
        elif config.usage.setup_level.index >= 2 and cur == self.dirname:
            self.session.openWithCallback(
                self.pathSelected,
                MovieLocationBox,
                _("Select target folder"),
                self.timerentry_dirname.value,
                minFree=100  # We require at least 100MB free space
            )
        elif getPreferredTagEditor() and cur == self.tagsSet:
            self.session.openWithCallback(self.tagEditFinished,
                                          getPreferredTagEditor(),
                                          self.timerentry_tags)
        else:
            self.keyGo()

    def finishedChannelSelection(self, *args):
        if args:
            self.timerentry_service_ref = ServiceReference(args[0])
            self.timerentry_service.setCurrentText(
                self.timerentry_service_ref.getServiceName())
            self["config"].invalidate(self.channelEntry)

    def getTimestamp(self, date, mytime):
        d = localtime(date)
        dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
        return int(mktime(dt.timetuple()))

    def getBeginEnd(self):
        date = self.timerentry_date.value
        endtime = self.timerentry_endtime.value
        starttime = self.timerentry_starttime.value

        begin = self.getTimestamp(date, starttime)
        end = self.getTimestamp(date, endtime)

        # if the endtime is less than the starttime, add 1 day.
        if end < begin:
            end += 86400
        return begin, end

    def selectChannelSelector(self, *args):
        self.session.openWithCallback(self.finishedChannelSelectionCorrection,
                                      ChannelSelection.SimpleChannelSelection,
                                      _("Select channel to record from"))

    def finishedChannelSelectionCorrection(self, *args):
        if args:
            self.finishedChannelSelection(*args)
            self.keyGo()

    def keyGo(self, result=None):
        if not self.timerentry_service_ref.isRecordable():
            self.session.openWithCallback(
                self.selectChannelSelector, MessageBox,
                _("You didn't select a channel to record from."),
                MessageBox.TYPE_ERROR)
            return
        self.timer.name = self.timerentry_name.value
        self.timer.description = self.timerentry_description.value
        self.timer.justplay = self.timerentry_justplay.value == "zap"
        self.timer.always_zap = self.timerentry_justplay.value == "zap+record"
        self.timer.zap_wakeup = self.timerentry_zapwakeup.value
        if self.timerentry_justplay.value == "zap":
            if not self.timerentry_showendtime.value:
                self.timerentry_endtime.value = self.timerentry_starttime.value
                self.timerentry_afterevent.value = "nothing"
        self.timer.resetRepeated()
        self.timer.afterEvent = {
            "nothing": AFTEREVENT.NONE,
            "deepstandby": AFTEREVENT.DEEPSTANDBY,
            "standby": AFTEREVENT.STANDBY,
            "auto": AFTEREVENT.AUTO
        }[self.timerentry_afterevent.value]
        self.timer.descramble = {
            "normal": True,
            "descrambled+ecm": True,
            "scrambled+ecm": False,
        }[self.timerentry_recordingtype.value]
        self.timer.record_ecm = {
            "normal": False,
            "descrambled+ecm": True,
            "scrambled+ecm": True,
        }[self.timerentry_recordingtype.value]
        self.timer.service_ref = self.timerentry_service_ref
        self.timer.tags = self.timerentry_tags

        if self.timer.dirname or self.timerentry_dirname.value != defaultMoviePath(
        ):
            self.timer.dirname = self.timerentry_dirname.value
            config.movielist.last_timer_videodir.value = self.timer.dirname
            config.movielist.last_timer_videodir.save()

        if self.timerentry_type.value == "once":
            self.timer.begin, self.timer.end = self.getBeginEnd()
        if self.timerentry_type.value == "repeated":
            if self.timerentry_repeated.value == "daily":
                for x in (0, 1, 2, 3, 4, 5, 6):
                    self.timer.setRepeated(x)

            if self.timerentry_repeated.value == "weekly":
                self.timer.setRepeated(self.timerentry_weekday.index)

            if self.timerentry_repeated.value == "weekdays":
                for x in (0, 1, 2, 3, 4):
                    self.timer.setRepeated(x)

            if self.timerentry_repeated.value == "user":
                for x in (0, 1, 2, 3, 4, 5, 6):
                    if self.timerentry_day[x].value:
                        self.timer.setRepeated(x)

            self.timer.repeatedbegindate = self.getTimestamp(
                self.timerentry_repeatedbegindate.value,
                self.timerentry_starttime.value)
            if self.timer.repeated:
                self.timer.begin = self.getTimestamp(
                    self.timerentry_repeatedbegindate.value,
                    self.timerentry_starttime.value)
                self.timer.end = self.getTimestamp(
                    self.timerentry_repeatedbegindate.value,
                    self.timerentry_endtime.value)
            else:
                self.timer.begin = self.getTimestamp(
                    time.time(), self.timerentry_starttime.value)
                self.timer.end = self.getTimestamp(
                    time.time(), self.timerentry_endtime.value)

            # when a timer end is set before the start, add 1 day
            if self.timer.end < self.timer.begin:
                self.timer.end += 86400

        if self.timer.eit is not None:
            event = eEPGCache.getInstance().lookupEventId(
                self.timer.service_ref.ref, self.timer.eit)
            if event:
                n = event.getNumOfLinkageServices()
                if n > 1:
                    tlist = []
                    ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
                    parent = self.timer.service_ref.ref
                    selection = 0
                    for x in range(n):
                        i = event.getLinkageService(parent, x)
                        if i.toString() == ref.toString():
                            selection = x
                        tlist.append((i.getName(), i))
                    self.session.openWithCallback(
                        self.subserviceSelected,
                        ChoiceBox,
                        title=_("Please select a subservice to record..."),
                        list=tlist,
                        selection=selection)
                    return
                elif n > 0:
                    parent = self.timer.service_ref.ref
                    self.timer.service_ref = ServiceReference(
                        event.getLinkageService(parent, 0))
        self.saveTimer()
        self.close((True, self.timer))

    def changeTimerType(self):
        self.timerentry_justplay.selectNext()
        self.timerJustplayEntry = getConfigListEntry(_("Timer type"),
                                                     self.timerentry_justplay)
        self["config"].invalidate(self.timerJustplayEntry)
        self.createSetup("config")

    def changeZapWakeupType(self):
        if self.timerentry_justplay.value == "zap":
            self.timerentry_zapwakeup.selectNext()
            self["config"].invalidate(self.entryZapWakeup)

    def incrementStart(self):
        self.timerentry_starttime.increment()
        self["config"].invalidate(self.entryStartTime)
        if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [
                0, 0
        ]:
            self.timerentry_date.value = self.timerentry_date.value + 86400
            self["config"].invalidate(self.entryDate)

    def decrementStart(self):
        self.timerentry_starttime.decrement()
        self["config"].invalidate(self.entryStartTime)
        if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [
                23, 59
        ]:
            self.timerentry_date.value = self.timerentry_date.value - 86400
            self["config"].invalidate(self.entryDate)

    def incrementEnd(self):
        if self.entryEndTime is not None:
            self.timerentry_endtime.increment()
            self["config"].invalidate(self.entryEndTime)

    def decrementEnd(self):
        if self.entryEndTime is not None:
            self.timerentry_endtime.decrement()
            self["config"].invalidate(self.entryEndTime)

    def subserviceSelected(self, service):
        if not service is None:
            self.timer.service_ref = ServiceReference(service[1])
        self.saveTimer()
        self.close((True, self.timer))

    def saveTimer(self):
        self.session.nav.RecordTimer.saveTimer()

    def keyCancel(self):
        self.close((False, ))

    def pathSelected(self, res):
        if res is not None:
            if config.movielist.videodirs.value != self.timerentry_dirname.choices:
                self.timerentry_dirname.setChoices(
                    config.movielist.videodirs.value, default=res)
            self.timerentry_dirname.value = res

    def tagEditFinished(self, ret):
        if ret is not None:
            self.timerentry_tags = ret
            self.timerentry_tagsset.setChoices(
                [not ret and "None" or " ".join(ret)])
            self["config"].invalidate(self.tagsSet)
Exemple #5
0
class TimerEntry(TimerEntryBase):
    def __init__(self, session, timer):
        TimerEntryBase.__init__(self, session, timer, "timerentry")

    def createConfig(self):
        TimerEntryBase.createConfig(self)
        justplay = self.timer.justplay
        always_zap = self.timer.always_zap
        pipzap = self.timer.pipzap
        rename_repeat = self.timer.rename_repeat
        conflict_detection = self.timer.conflict_detection

        afterevent = {
            AFTEREVENT.NONE: "nothing",
            AFTEREVENT.DEEPSTANDBY: "deepstandby",
            AFTEREVENT.STANDBY: "standby",
            AFTEREVENT.AUTO: "auto"
        }[self.timer.afterEvent]

        if self.timer.record_ecm and self.timer.descramble:
            recordingtype = "descrambled+ecm"
        elif self.timer.record_ecm:
            recordingtype = "scrambled+ecm"
        elif self.timer.descramble:
            recordingtype = "normal"

        self.timerentry_justplay = ConfigSelection(
            choices=[("zap", _("zap")), ("record", _("record")),
                     ("zap+record", _("zap and record"))],
            default={
                0: "record",
                1: "zap",
                2: "zap+record"
            }[justplay + 2 * always_zap])
        if SystemInfo["DeepstandbySupport"]:
            shutdownString = _("go to deep standby")
        else:
            shutdownString = _("shut down")
        self.timerentry_afterevent = ConfigSelection(choices=[
            ("nothing", _("do nothing")), ("standby", _("go to standby")),
            ("deepstandby", shutdownString), ("auto", _("auto"))
        ],
                                                     default=afterevent)
        self.timerentry_recordingtype = ConfigSelection(choices=[
            ("normal", _("normal")),
            ("descrambled+ecm", _("descramble and record ecm")),
            ("scrambled+ecm", _("don't descramble, record ecm"))
        ],
                                                        default=recordingtype)
        self.timerentry_name = ConfigText(default=self.timer.name.replace(
            '\x86', '').replace('\x87', ''),
                                          visible_width=50,
                                          fixed_size=False)
        self.timerentry_description = ConfigText(
            default=self.timer.description, visible_width=50, fixed_size=False)
        self.timerentry_tags = self.timer.tags[:]
        # if no tags found, make name of event default tag set.
        if not self.timerentry_tags:
            tagname = self.timer.name.strip()
            if tagname:
                tagname = tagname[0].upper() + tagname[1:].replace(" ", "_")
                self.timerentry_tags.append(tagname)

        self.timerentry_tagsset = ConfigSelection(choices=[
            not self.timerentry_tags and "None"
            or " ".join(self.timerentry_tags)
        ])

        self.timerentry_renamerepeat = ConfigYesNo(default=rename_repeat)

        self.timerentry_pipzap = ConfigYesNo(default=pipzap)
        self.timerentry_conflictdetection = ConfigYesNo(
            default=conflict_detection)

        self.timerentry_showendtime = ConfigSelection(default=False,
                                                      choices=[
                                                          (True, _("yes")),
                                                          (False, _("no"))
                                                      ])

        default = self.timer.dirname or defaultMoviePath()
        tmp = config.movielist.videodirs.value
        if default not in tmp:
            tmp.append(default)
        self.timerentry_dirname = ConfigSelection(default=default, choices=tmp)

        # FIXME some service-chooser needed here
        servicename = "N/A"
        try:  # no current service available?
            servicename = str(self.timer.service_ref.getServiceName())
        except:
            pass
        self.timerentry_service_ref = self.timer.service_ref
        self.timerentry_service = ConfigSelection([servicename])

    # So that setup.xml can call it as self.getPreferredTagEditor()
    def getPreferredTagEditor(self):
        return getPreferredTagEditor()

    def keyText(self):
        self.renameEntry()

    def renameEntry(self):
        cur = self["config"].getCurrent()
        if cur and cur[1] == self.timerentry_name:
            title_text = _("Please enter new name:")
            old_text = self.timerentry_name.value
        else:
            title_text = _("Please enter new description:")
            old_text = self.timerentry_description.value
        self.session.openWithCallback(self.renameEntryCallback,
                                      VirtualKeyBoard,
                                      title=title_text,
                                      text=old_text)

    def renameEntryCallback(self, answer):
        if answer:
            cur = self["config"].getCurrent()
            if cur and cur[1] == self.timerentry_name:
                target = self.timerentry_name
            else:
                target = self.timerentry_description
            target.value = answer
            self.invalidateConfigEntry(target)

    def keySelect(self):
        cur = self["config"].getCurrent()
        if cur and cur[1] == self.timerentry_service:
            self.session.openWithCallback(
                self.finishedChannelSelection,
                Screens.ChannelSelection.SimpleChannelSelection,
                _("Select channel to record from"),
                currentBouquet=True)
        elif cur and cur[1] == self.timerentry_dirname:
            self.session.openWithCallback(
                self.pathSelected,
                MovieLocationBox,
                _("Select target folder"),
                self.timerentry_dirname.value,
                minFree=100  # We require at least 100MB free space
            )
        elif cur and cur[1] == self.timerentry_tagsset:
            self.session.openWithCallback(self.tagEditFinished,
                                          getPreferredTagEditor(),
                                          self.timerentry_tags)
        elif cur and isinstance(cur[1], ConfigText):
            self.renameEntry()
        else:
            TimerEntryBase.keySelect(self)

    def finishedChannelSelection(self, *args):
        if args:
            self.timerentry_service_ref = ServiceReference(args[0])
            self.timerentry_service.setCurrentText(
                self.timerentry_service_ref.getServiceName())
            self.invalidateConfigEntry(self.timerentry_service)

    def getBeginEnd(self):
        begin, end = TimerEntryBase.getBeginEnd(self)

        # if the timer type is a Zap and no end is set, set duration to 1 second so time is shown in EPG's.
        if self.timerentry_justplay.value == "zap":
            if not self.timerentry_showendtime.value:
                end = begin + (config.recording.margin_before.value * 60) + 1

        return begin, end

    def selectChannelSelector(self, *args):
        self.session.openWithCallback(
            self.finishedChannelSelectionCorrection,
            Screens.ChannelSelection.SimpleChannelSelection,
            _("Select channel to record from"))

    def finishedChannelSelectionCorrection(self, *args):
        if args:
            self.finishedChannelSelection(*args)
            self.keySave()

    def keySave(self, result=None):
        if not self.timerentry_service_ref.isRecordable():
            self.session.openWithCallback(
                self.selectChannelSelector, MessageBox,
                _("You didn't select a channel to record from."),
                MessageBox.TYPE_ERROR)
            return
        self.timer.name = self.timerentry_name.value
        self.timer.description = self.timerentry_description.value
        self.timer.justplay = self.timerentry_justplay.value == "zap"
        self.timer.always_zap = self.timerentry_justplay.value == "zap+record"
        self.timer.pipzap = self.timerentry_pipzap.value
        self.timer.rename_repeat = self.timerentry_renamerepeat.value
        self.timer.conflict_detection = self.timerentry_conflictdetection.value
        if self.timerentry_justplay.value == "zap":
            if not self.timerentry_showendtime.value:
                self.timerentry_endtime.value = self.timerentry_starttime.value
        self.timer.afterEvent = {
            "nothing": AFTEREVENT.NONE,
            "deepstandby": AFTEREVENT.DEEPSTANDBY,
            "standby": AFTEREVENT.STANDBY,
            "auto": AFTEREVENT.AUTO
        }[self.timerentry_afterevent.value]
        # There is no point doing anything after a Zap-only timer!
        # For a start, you can't actually configure anything in the menu, but
        # leaving it as AUTO means that the code may try to shutdown at Zap time
        # if the Zap timer woke the box up.
        #
        if self.timer.justplay:
            self.timer.afterEvent = AFTEREVENT.NONE
        self.timer.descramble = {
            "normal": True,
            "descrambled+ecm": True,
            "scrambled+ecm": False,
        }[self.timerentry_recordingtype.value]
        self.timer.record_ecm = {
            "normal": False,
            "descrambled+ecm": True,
            "scrambled+ecm": True,
        }[self.timerentry_recordingtype.value]
        self.timer.service_ref = self.timerentry_service_ref
        self.timer.tags = self.timerentry_tags

        if self.timer.dirname or self.timerentry_dirname.value != defaultMoviePath(
        ):
            self.timer.dirname = self.timerentry_dirname.value
            config.movielist.last_timer_videodir.value = self.timer.dirname
            config.movielist.last_timer_videodir.save()

        if self.timerentry_type.value == "once":
            self.timer.begin, self.timer.end = self.getBeginEnd()

        TimerEntryBase.keySave(self)

        if self.timer.eit is not None:
            event = eEPGCache.getInstance().lookupEventId(
                self.timer.service_ref.ref, self.timer.eit)
            if event:
                n = event.getNumOfLinkageServices()
                if n > 1:
                    tlist = []
                    ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
                    parent = self.timer.service_ref.ref
                    selection = 0
                    for x in range(n):
                        i = event.getLinkageService(parent, x)
                        if i.toString() == ref.toString():
                            selection = x
                        tlist.append((i.getName(), i))
                    self.session.openWithCallback(
                        self.subserviceSelected,
                        ChoiceBox,
                        title=_("Please select a subservice to record..."),
                        list=tlist,
                        selection=selection)
                    return
                elif n > 0:
                    parent = self.timer.service_ref.ref
                    self.timer.service_ref = ServiceReference(
                        event.getLinkageService(parent, 0))

        self.saveTimer()
        self.close((True, self.timer))

    def changeTimerType(self):
        self.timerentry_justplay.selectNext()
        self.invalidateConfigEntry(self.timerentry_justplay)

    def incrementEnd(self):
        if self.timerentry_showendtime.value or self.timerentry_justplay.value != "zap":
            TimerEntryBase.incrementEnd(self)

    def decrementEnd(self):
        if self.timerentry_showendtime.value or self.timerentry_justplay.value != "zap":
            TimerEntryBase.decrementEnd(self)

    def subserviceSelected(self, service):
        if not service is None:
            self.timer.service_ref = ServiceReference(service[1])
        self.saveTimer()
        self.close((True, self.timer))

    def saveTimer(self):
        self.session.nav.RecordTimer.saveTimer()

    def pathSelected(self, res):
        if res is not None:
            if config.movielist.videodirs.value != self.timerentry_dirname.choices:
                self.timerentry_dirname.setChoices(
                    config.movielist.videodirs.value, default=res)
            self.timerentry_dirname.value = res

    def tagEditFinished(self, ret):
        if ret is not None:
            self.timerentry_tags = ret
            self.timerentry_tagsset.setChoices(
                [not ret and "None" or " ".join(ret)])
            self.invalidateConfigEntry(self.timerentry_tagsset)
Exemple #6
0
class TimerEntry(Screen, ConfigListScreen):
	def __init__(self, session, timer):
		Screen.__init__(self, session)
		self.timer = timer

		self.entryDate = None
		self.entryService = None

		self["oktext"] = Label(_("OK"))
		self["canceltext"] = Label(_("Cancel"))
		self["ok"] = Pixmap()
		self["cancel"] = Pixmap()

		self.createConfig()

		self["actions"] = NumberActionMap(["SetupActions", "GlobalActions", "PiPSetupActions"],
		{
			"ok": self.keySelect,
			"save": self.keyGo,
			"cancel": self.keyCancel,
			"volumeUp": self.incrementStart,
			"volumeDown": self.decrementStart,
			"size+": self.incrementEnd,
			"size-": self.decrementEnd
		}, -2)

		self.list = []
		ConfigListScreen.__init__(self, self.list, session = session)
		self.createSetup("config")

	def createConfig(self):
			justplay = self.timer.justplay

			afterevent = {
				AFTEREVENT.NONE: "nothing",
				AFTEREVENT.DEEPSTANDBY: "deepstandby",
				AFTEREVENT.STANDBY: "standby",
				AFTEREVENT.AUTO: "auto"
				}[self.timer.afterEvent]

			weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")

			# calculate default values
			day = []
			weekday = 0
			for x in (0, 1, 2, 3, 4, 5, 6):
				day.append(0)
			if self.timer.repeated: # repeated
				type = "repeated"
				if (self.timer.repeated == 31): # Mon-Fri
					repeated = "weekdays"
				elif (self.timer.repeated == 127): # daily
					repeated = "daily"
				else:
					flags = self.timer.repeated
					repeated = "user"
					count = 0
					for x in (0, 1, 2, 3, 4, 5, 6):
						if flags == 1: # weekly
							print "Set to weekday " + str(x)
							weekday = x
						if flags & 1 == 1: # set user defined flags
							day[x] = 1
							count += 1
						else:
							day[x] = 0
						flags = flags >> 1
					if count == 1:
						repeated = "weekly"
			else: # once
				type = "once"
				repeated = None
				weekday = (int(strftime("%w", localtime(self.timer.begin))) - 1) % 7
				day[weekday] = 1

			if not config.misc.recording_allowed.value:
				self.timerentry_justplay = ConfigSelection(choices = [("zap", _("zap"))], default = "zap")
			else:
				tmp_dir = self.timer.dirname or defaultMoviePath()
				if not harddiskmanager.inside_mountpoint(tmp_dir):
					justplay = 1
				justplay_default = {0: "record", 1: "zap"}[justplay]
				self.timerentry_justplay = ConfigSelection(choices = [("zap", _("zap")), ("record", _("record"))], default = justplay_default)

			if SystemInfo["DeepstandbySupport"]:
				shutdownString = _("go to standby")
			else:
				shutdownString = _("shut down")
			self.timerentry_afterevent = ConfigSelection(choices = [("nothing", _("do nothing")), ("standby", _("go to idle mode")), ("deepstandby", shutdownString), ("auto", _("auto"))], default = afterevent)
			self.timerentry_type = ConfigSelection(choices = [("once",_("once")), ("repeated", _("repeated"))], default = type)
			self.timerentry_name = ConfigText(default = self.timer.name, visible_width = 50, fixed_size = False)
			self.timerentry_description = ConfigText(default = self.timer.description, visible_width = 50, fixed_size = False)
			self.timerentry_tags = self.timer.tags[:]
			self.timerentry_tagsset = ConfigSelection(choices = [not self.timerentry_tags and "None" or " ".join(self.timerentry_tags)])

			self.timerentry_repeated = ConfigSelection(default = repeated, choices = [("daily", _("daily")), ("weekly", _("weekly")), ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])
			
			self.timerentry_date = ConfigDateTime(default = self.timer.begin, formatstring = _("%d.%B %Y"), increment = 86400)
			self.timerentry_starttime = ConfigClock(default = self.timer.begin)
			self.timerentry_endtime = ConfigClock(default = self.timer.end)
			self.timerentry_showendtime = ConfigSelection(default = ((self.timer.end - self.timer.begin) > 4), choices = [(True, _("yes")), (False, _("no"))])

			default = self.timer.dirname or defaultMoviePath()
			tmp = config.movielist.videodirs.value
			if default not in tmp:
				tmp.append(default)
			self.timerentry_dirname = ConfigSelection(default = default, choices = tmp)

			self.timerentry_repeatedbegindate = ConfigDateTime(default = self.timer.repeatedbegindate, formatstring = _("%d.%B %Y"), increment = 86400)

			self.timerentry_weekday = ConfigSelection(default = weekday_table[weekday], choices = [("mon",_("Monday")), ("tue", _("Tuesday")), ("wed",_("Wednesday")), ("thu", _("Thursday")), ("fri", _("Friday")), ("sat", _("Saturday")), ("sun", _("Sunday"))])

			self.timerentry_day = ConfigSubList()
			for x in (0, 1, 2, 3, 4, 5, 6):
				self.timerentry_day.append(ConfigYesNo(default = day[x]))

			try: # no current service available?
				servicename = str(self.timer.service_ref.getServiceName())
			except:
				pass
			servicename = servicename or "N/A"
			self.timerentry_service_ref = self.timer.service_ref
			self.timerentry_service = ConfigSelection([servicename])

			self.timerentry_plugins = {}
			if config.usage.setup_level.index >= 2:
				from Plugins.Plugin import PluginDescriptor
				from Components.PluginComponent import plugins
				missing = self.timer.plugins.keys()
				for p in plugins.getPlugins(PluginDescriptor.WHERE_TIMEREDIT):
					if p.__call__.has_key("setupFnc"):
						setupFnc = p.__call__["setupFnc"]
						if setupFnc is not None:
							if p.__call__.has_key("configListEntry"):
								entry = p.__call__["configListEntry"]()
								pdata = None
								if p.name in self.timer.plugins:
									pval = self.timer.plugins[p.name][0]
									pdata = self.timer.plugins[p.name][1]
									try:
										if isinstance(entry[1].value, bool):
											entry[1].value = (pval == "True")
										elif isinstance(entry[1].value, str):
											entry[1].value = str(pval)
										elif isinstance(entry[1].value, int):
											entry[1].value = int(pval)
									except ValueError:
										print "could not get config_val", pval, type(pval), "for WHERE_TIMEREDIT plugin:", p.name
										break

								self.timerentry_plugins[entry] = [p.name, setupFnc, pdata] # [plugin name, function call for plugin setup, plugin private data]
								if p.name in missing:
									missing.remove(p.name)
				if len(missing):
					print "could not setup WHERE_TIMEREDIT plugin(s):", missing

	def createSetup(self, widget):
		self.list = []
		self.list.append(getConfigListEntry(_("Name"), self.timerentry_name))
		self.list.append(getConfigListEntry(_("Description"), self.timerentry_description))
		self.timerJustplayEntry = getConfigListEntry(_("Timer Type"), self.timerentry_justplay)
		self.list.append(self.timerJustplayEntry)
		self.timerTypeEntry = getConfigListEntry(_("Repeat Type"), self.timerentry_type)
		self.list.append(self.timerTypeEntry)

		if self.timerentry_type.value == "once":
			self.frequencyEntry = None
		else: # repeated
			self.frequencyEntry = getConfigListEntry(_("Repeats"), self.timerentry_repeated)
			self.list.append(self.frequencyEntry)
			self.repeatedbegindateEntry = getConfigListEntry(_("Starting on"), self.timerentry_repeatedbegindate)
			self.list.append(self.repeatedbegindateEntry)
			if self.timerentry_repeated.value == "daily":
				pass
			if self.timerentry_repeated.value == "weekdays":
				pass
			if self.timerentry_repeated.value == "weekly":
				self.list.append(getConfigListEntry(_("Weekday"), self.timerentry_weekday))

			if self.timerentry_repeated.value == "user":
				self.list.append(getConfigListEntry(_("Monday"), self.timerentry_day[0]))
				self.list.append(getConfigListEntry(_("Tuesday"), self.timerentry_day[1]))
				self.list.append(getConfigListEntry(_("Wednesday"), self.timerentry_day[2]))
				self.list.append(getConfigListEntry(_("Thursday"), self.timerentry_day[3]))
				self.list.append(getConfigListEntry(_("Friday"), self.timerentry_day[4]))
				self.list.append(getConfigListEntry(_("Saturday"), self.timerentry_day[5]))
				self.list.append(getConfigListEntry(_("Sunday"), self.timerentry_day[6]))

		self.entryDate = getConfigListEntry(_("Date"), self.timerentry_date)
		if self.timerentry_type.value == "once":
			self.list.append(self.entryDate)
		
		self.entryStartTime = getConfigListEntry(_("StartTime"), self.timerentry_starttime)
		self.list.append(self.entryStartTime)
		
		self.entryShowEndTime = getConfigListEntry(_("Set End Time"), self.timerentry_showendtime)
		if self.timerentry_justplay.value == "zap":
			self.list.append(self.entryShowEndTime)
		self.entryEndTime = getConfigListEntry(_("EndTime"), self.timerentry_endtime)
		if self.timerentry_justplay.value != "zap" or self.timerentry_showendtime.value:
			self.list.append(self.entryEndTime)

		self.channelEntry = getConfigListEntry(_("Channel"), self.timerentry_service)
		self.list.append(self.channelEntry)

		self.dirname = getConfigListEntry(_("Location"), self.timerentry_dirname)
		self.tagsSet = getConfigListEntry(_("Tags"), self.timerentry_tagsset)
		if self.timerentry_justplay.value != "zap":
			if config.usage.setup_level.index >= 2: # expert+
				self.list.append(self.dirname)
			if getPreferredTagEditor():
				self.list.append(self.tagsSet)
		self.list.append(getConfigListEntry(_("After event"), self.timerentry_afterevent))

		for entry in self.timerentry_plugins.keys():
			self.list.append(entry)

		self[widget].list = self.list
		self[widget].l.setList(self.list)

	def newConfig(self):
		print "newConfig", self["config"].getCurrent()
		if self["config"].getCurrent() in (self.timerTypeEntry, self.timerJustplayEntry, self.frequencyEntry, self.entryShowEndTime):
			self.createSetup("config")

	def keyLeft(self):
		if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
			self.keySelect()
		else:
			ConfigListScreen.keyLeft(self)
			self.newConfig()

	def keyRight(self):
		if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
			self.keySelect()
		else:
			ConfigListScreen.keyRight(self)
			self.newConfig()

	def keySelect(self):
		cur = self["config"].getCurrent()
		if cur == self.channelEntry:
			self.session.openWithCallback(
				self.finishedChannelSelection,
				ChannelSelection.SimpleChannelSelection,
				_("Select channel to record from")
			)
		elif config.usage.setup_level.index >= 2 and cur == self.dirname:
			self.session.openWithCallback(
				self.pathSelected,
				MovieLocationBox,
				_("Choose target folder"),
				self.timerentry_dirname.value,
				minFree = 100 # We require at least 100MB free space
			)
		elif getPreferredTagEditor() and cur == self.tagsSet:
			self.session.openWithCallback(
				self.tagEditFinished,
				getPreferredTagEditor(),
				self.timerentry_tags
			)
		elif config.usage.setup_level.index >= 2 and cur in self.timerentry_plugins.keys():
			self.getConfigListValues()
			setupFnc = self.timerentry_plugins[cur][1]
			configentry = cur[1]
			private_data = self.timerentry_plugins[cur][2]
			print "calling setupFnc of WHERE_TIMEREDIT plugin:", cur[0], setupFnc, configentry, private_data, self.timer.name
			self.session.openWithCallback(boundFunction(self.pluginFinished, cur), setupFnc , configentry, private_data, self.timer)
		else:
			self.keyGo()

	def pluginFinished(self, entry, ret=""):
		print "[pluginFinished]", entry, ret
		self.timerentry_plugins[entry][2] = ret
		self["config"].invalidate(entry)
		print "plugin private data", self.timerentry_plugins[entry][2]

	def finishedChannelSelection(self, *args):
		if args:
			self.timerentry_service_ref = ServiceReference(args[0])
			self.timerentry_service.setCurrentText(self.timerentry_service_ref.getServiceName())
			self["config"].invalidate(self.channelEntry)
			
	def getTimestamp(self, date, mytime):
		d = localtime(date)
		dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
		return int(mktime(dt.timetuple()))

	def getBeginEnd(self):
		date = self.timerentry_date.value
		endtime = self.timerentry_endtime.value
		starttime = self.timerentry_starttime.value

		begin = self.getTimestamp(date, starttime)
		end = self.getTimestamp(date, endtime)

		# if the endtime is less than the starttime, add 1 day.
		if end < begin:
			end += 86400
		return begin, end

	def selectChannelSelector(self, *args):
		self.session.openWithCallback(
				self.finishedChannelSelectionCorrection,
				ChannelSelection.SimpleChannelSelection,
				_("Select channel to record from")
			)

	def finishedChannelSelectionCorrection(self, *args):
		if args:
			self.finishedChannelSelection(*args)
			self.keyGo()

	def getConfigListValues(self):
		if not self.timerentry_service_ref.isRecordable():
			self.session.openWithCallback(self.selectChannelSelector, MessageBox, _("You didn't select a channel to record from."), MessageBox.TYPE_ERROR)
			return
		if self.timerentry_justplay.value == 'record':
			if not harddiskmanager.inside_mountpoint(self.timerentry_dirname.value):
				if harddiskmanager.HDDCount() and not harddiskmanager.HDDEnabledCount():
					self.session.open(MessageBox, _("Unconfigured storage devices found!") + "\n" \
						+ _("Please make sure to set up your storage devices with the improved storage management in menu -> setup -> system -> storage devices."), MessageBox.TYPE_ERROR)
					return
				elif harddiskmanager.HDDEnabledCount() and defaultStorageDevice() == "<undefined>":
					self.session.open(MessageBox, _("No default storage device found!") + "\n" \
						+ _("Please make sure to set up your default storage device in menu -> setup -> system -> recording paths."), MessageBox.TYPE_ERROR)
					return
				elif harddiskmanager.HDDEnabledCount() and defaultStorageDevice() != "<undefined>":
					part = harddiskmanager.getDefaultStorageDevicebyUUID(defaultStorageDevice())
					if part is None:
						self.session.open(MessageBox, _("Default storage device is not available!") + "\n" \
							+ _("Please verify if your default storage device is attached or set up your default storage device in menu -> setup -> system -> recording paths."), MessageBox.TYPE_ERROR)
						return
				else:
					self.session.open(MessageBox, _("Recording destination for this timer does not exists."), MessageBox.TYPE_ERROR)
					return

		self.timer.name = self.timerentry_name.value
		self.timer.description = self.timerentry_description.value
		self.timer.justplay = self.timerentry_justplay.value == "zap"
		if self.timerentry_justplay.value == "zap":
			if not self.timerentry_showendtime.value:
				self.timerentry_endtime.value = self.timerentry_starttime.value

		self.timer.resetRepeated()
		self.timer.afterEvent = {
			"nothing": AFTEREVENT.NONE,
			"deepstandby": AFTEREVENT.DEEPSTANDBY,
			"standby": AFTEREVENT.STANDBY,
			"auto": AFTEREVENT.AUTO
			}[self.timerentry_afterevent.value]
		self.timer.service_ref = self.timerentry_service_ref
		self.timer.tags = self.timerentry_tags

		if self.timer.dirname or self.timerentry_dirname.value != defaultMoviePath():
			self.timer.dirname = self.timerentry_dirname.value
			config.movielist.last_timer_videodir.value = self.timer.dirname
			config.movielist.last_timer_videodir.save()

		if self.timerentry_type.value == "once":
			self.timer.begin, self.timer.end = self.getBeginEnd()
		if self.timerentry_type.value == "repeated":
			if self.timerentry_repeated.value == "daily":
				for x in (0, 1, 2, 3, 4, 5, 6):
					self.timer.setRepeated(x)

			if self.timerentry_repeated.value == "weekly":
				self.timer.setRepeated(self.timerentry_weekday.index)

			if self.timerentry_repeated.value == "weekdays":
				for x in (0, 1, 2, 3, 4):
					self.timer.setRepeated(x)

			if self.timerentry_repeated.value == "user":
				for x in (0, 1, 2, 3, 4, 5, 6):
					if self.timerentry_day[x].value:
						self.timer.setRepeated(x)

			self.timer.repeatedbegindate = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
			if self.timer.repeated:
				self.timer.begin = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
				self.timer.end = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_endtime.value)
			else:
				self.timer.begin = self.getTimestamp(time.time(), self.timerentry_starttime.value)
				self.timer.end = self.getTimestamp(time.time(), self.timerentry_endtime.value)

			# when a timer end is set before the start, add 1 day
			if self.timer.end < self.timer.begin:
				self.timer.end += 86400

	def keyGo(self, result = None):
		self.getConfigListValues()
		if self.timer.eit is not None:
			event = eEPGCache.getInstance().lookupEventId(self.timer.service_ref.ref, self.timer.eit)
			if event:
				n = event.getNumOfLinkageServices()
				if n > 1:
					tlist = []
					ref = self.session.nav.getCurrentlyPlayingServiceReference()
					parent = self.timer.service_ref.ref
					selection = 0
					for x in range(n):
						i = event.getLinkageService(parent, x)
						if i.toString() == ref.toString():
							selection = x
						tlist.append((i.getName(), i))
					self.session.openWithCallback(self.subserviceSelected, ChoiceBox, title=_("Please select a subservice to record..."), list = tlist, selection = selection)
					return
				elif n > 0:
					parent = self.timer.service_ref.ref
					self.timer.service_ref = ServiceReference(event.getLinkageService(parent, 0))
		
		if self.timerentry_plugins:
			self.timer.plugins = {}
			for key, val in self.timerentry_plugins.iteritems():
				self.timer.plugins[val[0]] = (str(key[1].value),str(val[2]))
				print "timerentry self.timer.plugins", self.timer.plugins
		
		self.saveTimer()
		self.close((True, self.timer))

	def incrementStart(self):
		self.timerentry_starttime.increment()
		self["config"].invalidate(self.entryStartTime)

	def decrementStart(self):
		self.timerentry_starttime.decrement()
		self["config"].invalidate(self.entryStartTime)

	def incrementEnd(self):
		if self.entryEndTime is not None:
			self.timerentry_endtime.increment()
			self["config"].invalidate(self.entryEndTime)

	def decrementEnd(self):
		if self.entryEndTime is not None:
			self.timerentry_endtime.decrement()
			self["config"].invalidate(self.entryEndTime)

	def subserviceSelected(self, service):
		if not service is None:
			self.timer.service_ref = ServiceReference(service[1])
		self.saveTimer()
		self.close((True, self.timer))

	def saveTimer(self):
		self.session.nav.RecordTimer.saveTimer()

	def keyCancel(self):
		self.close((False,))

	def pathSelected(self, res):
		if res is not None:
			if config.movielist.videodirs.value != self.timerentry_dirname.choices:
				self.timerentry_dirname.setChoices(config.movielist.videodirs.value, default=res)
			self.timerentry_dirname.value = res

	def tagEditFinished(self, ret):
		if ret is not None:
			self.timerentry_tags = ret
			self.timerentry_tagsset.setChoices([not ret and "None" or " ".join(ret)])
			self["config"].invalidate(self.tagsSet)
Exemple #7
0
class TimerEntry(Screen, ConfigListScreen):
	def __init__(self, session, timer):
		Screen.__init__(self, session)
		self.setup_title = _("Timer entry")
		self.timer = timer

		self.entryDate = None
		self.entryService = None

		self["HelpWindow"] = Pixmap()
		self["HelpWindow"].hide()

		self["description"] = Label("")
		self["oktext"] = Label(_("OK"))
		self["canceltext"] = Label(_("Cancel"))
		self["ok"] = Pixmap()
		self["cancel"] = Pixmap()
		self["key_yellow"] = Label(_("Timer type"))

		self.createConfig()

		self["actions"] = NumberActionMap(["SetupActions", "GlobalActions", "PiPSetupActions", "ColorActions"],
		{
			"ok": self.keySelect,
			"save": self.keyGo,
			"cancel": self.keyCancel,
			"volumeUp": self.incrementStart,
			"volumeDown": self.decrementStart,
			"size+": self.incrementEnd,
			"size-": self.decrementEnd,
			"yellow": self.changeTimerType
		}, -2)

		self.onChangedEntry = [ ]
		self.list = []
		ConfigListScreen.__init__(self, self.list, session = session)
		self.createSetup("config")
		self.onLayoutFinish.append(self.layoutFinished)
		if not self.selectionChanged in self["config"].onSelectionChanged:
			self["config"].onSelectionChanged.append(self.selectionChanged)
		self.selectionChanged()

	def createConfig(self):
		justplay = self.timer.justplay
		always_zap = self.timer.always_zap

		afterevent = {
			AFTEREVENT.NONE: "nothing",
			AFTEREVENT.DEEPSTANDBY: "deepstandby",
			AFTEREVENT.STANDBY: "standby",
			AFTEREVENT.AUTO: "auto"
			}[self.timer.afterEvent]

		if self.timer.record_ecm and self.timer.descramble:
			recordingtype = "descrambled+ecm"
		elif self.timer.record_ecm:
			recordingtype = "scrambled+ecm"
		elif self.timer.descramble:
			recordingtype = "normal"

		weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")

		# calculate default values
		day = []
		weekday = 0
		for x in (0, 1, 2, 3, 4, 5, 6):
			day.append(0)
		if self.timer.repeated: # repeated
			type = "repeated"
			if self.timer.repeated == 31: # Mon-Fri
				repeated = "weekdays"
			elif self.timer.repeated == 127: # daily
				repeated = "daily"
			else:
				flags = self.timer.repeated
				repeated = "user"
				count = 0
				for x in (0, 1, 2, 3, 4, 5, 6):
					if flags == 1: # weekly
# 							print "Set to weekday " + str(x)
						weekday = x
					if flags & 1 == 1: # set user defined flags
						day[x] = 1
						count += 1
					else:
						day[x] = 0
					flags >>= 1
				if count == 1:
					repeated = "weekly"
		else: # once
			type = "once"
			repeated = None
			weekday = int(strftime("%u", localtime(self.timer.begin))) - 1
			day[weekday] = 1

		self.timerentry_justplay = ConfigSelection(choices = [
			("zap", _("zap")), ("record", _("record")), ("zap+record", _("zap and record"))],
			default = {0: "record", 1: "zap", 2: "zap+record"}[justplay + 2*always_zap])
		if SystemInfo["DeepstandbySupport"]:
			shutdownString = _("go to deep standby")
		else:
			shutdownString = _("shut down")
		self.timerentry_afterevent = ConfigSelection(choices = [("nothing", _("do nothing")), ("standby", _("go to standby")), ("deepstandby", shutdownString), ("auto", _("auto"))], default = afterevent)
		self.timerentry_recordingtype = ConfigSelection(choices = [("normal", _("normal")), ("descrambled+ecm", _("descramble and record ecm")), ("scrambled+ecm", _("don't descramble, record ecm"))], default = recordingtype)
		self.timerentry_type = ConfigSelection(choices = [("once",_("once")), ("repeated", _("repeated"))], default = type)
		self.timerentry_name = ConfigText(default = self.timer.name.replace('\xc2\x86', '').replace('\xc2\x87', '').encode("utf-8"), visible_width = 50, fixed_size = False)
		self.timerentry_description = ConfigText(default = self.timer.description, visible_width = 50, fixed_size = False)
		self.timerentry_tags = self.timer.tags[:]
		self.timerentry_tagsset = ConfigSelection(choices = [not self.timerentry_tags and "None" or " ".join(self.timerentry_tags)])

		self.timerentry_repeated = ConfigSelection(default = repeated, choices = [("weekly", _("weekly")), ("daily", _("daily")), ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])

		self.timerentry_date = ConfigDateTime(default = self.timer.begin, formatstring = _("%d.%B %Y"), increment = 86400)
		self.timerentry_starttime = ConfigClock(default = self.timer.begin)
		self.timerentry_endtime = ConfigClock(default = self.timer.end)
		self.timerentry_showendtime = ConfigSelection(default = ((self.timer.end - self.timer.begin) > 4), choices = [(True, _("yes")), (False, _("no"))])

		default = self.timer.dirname or defaultMoviePath()
		tmp = config.movielist.videodirs.getValue()
		if default not in tmp:
			tmp.append(default)
		self.timerentry_dirname = ConfigSelection(default = default, choices = tmp)

		self.timerentry_repeatedbegindate = ConfigDateTime(default = self.timer.repeatedbegindate, formatstring = _("%d.%B %Y"), increment = 86400)

		self.timerentry_weekday = ConfigSelection(default = weekday_table[weekday], choices = [("mon",_("Monday")), ("tue", _("Tuesday")), ("wed",_("Wednesday")), ("thu", _("Thursday")), ("fri", _("Friday")), ("sat", _("Saturday")), ("sun", _("Sunday"))])

		self.timerentry_day = ConfigSubList()
		for x in (0, 1, 2, 3, 4, 5, 6):
			self.timerentry_day.append(ConfigYesNo(default = day[x]))

		# FIXME some service-chooser needed here
		servicename = "N/A"
		try: # no current service available?
			servicename = str(self.timer.service_ref.getServiceName())
		except:
			pass
		self.timerentry_service_ref = self.timer.service_ref
		self.timerentry_service = ConfigSelection([servicename])

	def createSetup(self, widget):
		self.list = []
		self.list.append(getConfigListEntry(_("Name"), self.timerentry_name, _("Set the name the recording will get.")))
		self.list.append(getConfigListEntry(_("Description"), self.timerentry_description, _("Set the description of the recording.")))
		self.timerJustplayEntry = getConfigListEntry(_("Timer type"), self.timerentry_justplay, _("Chose between record and ZAP."))
		self.list.append(self.timerJustplayEntry)
		self.timerTypeEntry = getConfigListEntry(_("Repeat type"), self.timerentry_type, _("A repeating timer or just once?"))
		self.list.append(self.timerTypeEntry)

		if self.timerentry_type.getValue() == "once":
			self.frequencyEntry = None
		else: # repeated
			self.frequencyEntry = getConfigListEntry(_("Repeats"), self.timerentry_repeated, _("Choose between Daily, Weekly, Weekdays or user defined."))
			self.list.append(self.frequencyEntry)
			self.repeatedbegindateEntry = getConfigListEntry(_("Starting on"), self.timerentry_repeatedbegindate, _("Set the date the timer must start."))
			self.list.append(self.repeatedbegindateEntry)
			if self.timerentry_repeated.getValue() == "daily":
				pass
			if self.timerentry_repeated.getValue() == "weekdays":
				pass
			if self.timerentry_repeated.getValue() == "weekly":
				self.list.append(getConfigListEntry(_("Weekday"), self.timerentry_weekday))

			if self.timerentry_repeated.getValue() == "user":
				self.list.append(getConfigListEntry(_("Monday"), self.timerentry_day[0]))
				self.list.append(getConfigListEntry(_("Tuesday"), self.timerentry_day[1]))
				self.list.append(getConfigListEntry(_("Wednesday"), self.timerentry_day[2]))
				self.list.append(getConfigListEntry(_("Thursday"), self.timerentry_day[3]))
				self.list.append(getConfigListEntry(_("Friday"), self.timerentry_day[4]))
				self.list.append(getConfigListEntry(_("Saturday"), self.timerentry_day[5]))
				self.list.append(getConfigListEntry(_("Sunday"), self.timerentry_day[6]))

		self.entryDate = getConfigListEntry(_("Date"), self.timerentry_date, _("Set the date the timer must start."))
		if self.timerentry_type.getValue() == "once":
			self.list.append(self.entryDate)

		self.entryStartTime = getConfigListEntry(_("Start time"), self.timerentry_starttime, _("Set the time the timer must start."))
		self.list.append(self.entryStartTime)

		self.entryShowEndTime = getConfigListEntry(_("Set end time"), self.timerentry_showendtime, _("Set the time the timer must stop."))
		if self.timerentry_justplay.getValue() == "zap":
			self.list.append(self.entryShowEndTime)
		self.entryEndTime = getConfigListEntry(_("End time"), self.timerentry_endtime, _("Set the time the timer must stop."))
		if self.timerentry_justplay.getValue() != "zap" or self.timerentry_showendtime.getValue():
			self.list.append(self.entryEndTime)

		self.channelEntry = getConfigListEntry(_("Channel"), self.timerentry_service, _("Set the channel for this timer."))
		self.list.append(self.channelEntry)

		self.dirname = getConfigListEntry(_("Location"), self.timerentry_dirname, _("Where should the recording be saved?"))
		self.tagsSet = getConfigListEntry(_("Tags"), self.timerentry_tagsset, _("Choose a tag for easy finding a recording."))
		if self.timerentry_justplay.getValue() != "zap":
			if config.usage.setup_level.index >= 2: # expert+
				self.list.append(self.dirname)
			if getPreferredTagEditor():
				self.list.append(self.tagsSet)
			self.list.append(getConfigListEntry(_("After event"), self.timerentry_afterevent, _("What action is required on complettion of the timer? 'Auto' lets the box return to the state it had when the timer started. 'Do nothing', 'Go to standby' and 'Go to deep standby' do ecaxtly that.")))
			self.list.append(getConfigListEntry(_("Recording type"), self.timerentry_recordingtype, _("Descramble & record ECM' gives the option to descramble afterwards if descrambling on recording failed. 'Don't descramble, record ECM' save a scramble recording that can be descrambled on playback. 'Normal' means descramble the recording and don't record ECM.")))

		self[widget].list = self.list
		self[widget].l.setList(self.list)

	def selectionChanged(self):
		if self["config"].getCurrent() and len(self["config"].getCurrent()) > 2 and self["config"].getCurrent()[2]:
			self["description"].setText(self["config"].getCurrent()[2])

	def layoutFinished(self):
		self.setTitle(_(self.setup_title))

	def createSummary(self):
		return SetupSummary

	# for summary:
	def changedEntry(self):
		for x in self.onChangedEntry:
			x()

	def getCurrentEntry(self):
		return self["config"].getCurrent() and self["config"].getCurrent()[0] or ""

	def getCurrentValue(self):
		return self["config"].getCurrent() and str(self["config"].getCurrent()[1].getText()) or ""

	def newConfig(self):
		if self["config"].getCurrent() in (self.timerTypeEntry, self.timerJustplayEntry, self.frequencyEntry, self.entryShowEndTime):
			self.createSetup("config")

	def keyLeft(self):
		if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
			self.keySelect()
		else:
			ConfigListScreen.keyLeft(self)
			self.newConfig()

	def keyRight(self):
		if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
			self.keySelect()
		else:
			ConfigListScreen.keyRight(self)
			self.newConfig()

	def keySelect(self):
		cur = self["config"].getCurrent()
		if cur == self.channelEntry:
			self.session.openWithCallback(
				self.finishedChannelSelection,
				ChannelSelection.SimpleChannelSelection,
				_("Select channel to record from")
			)
		elif config.usage.setup_level.index >= 2 and cur == self.dirname:
			self.session.openWithCallback(
				self.pathSelected,
				MovieLocationBox,
				_("Select target folder"),
				self.timerentry_dirname.getValue(),
				minFree = 100 # We require at least 100MB free space
			)
		elif getPreferredTagEditor() and cur == self.tagsSet:
			self.session.openWithCallback(
				self.tagEditFinished,
				getPreferredTagEditor(),
				self.timerentry_tags
			)
		else:
			self.keyGo()

	def finishedChannelSelection(self, *args):
		if args:
			self.timerentry_service_ref = ServiceReference(args[0])
			self.timerentry_service.setCurrentText(self.timerentry_service_ref.getServiceName())
			self["config"].invalidate(self.channelEntry)

	def getTimestamp(self, date, mytime):
		d = localtime(date)
		dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
		return int(mktime(dt.timetuple()))

	def getBeginEnd(self):
		date = self.timerentry_date.getValue()
		endtime = self.timerentry_endtime.getValue()
		starttime = self.timerentry_starttime.getValue()

		begin = self.getTimestamp(date, starttime)
		end = self.getTimestamp(date, endtime)

		# if the endtime is less than the starttime, add 1 day.
		if end < begin:
			end += 86400

		# if the timer type is a Zap and no end is set, set duration to 1 second so time is shown in EPG's.
		if self.timerentry_justplay.getValue() == "zap":
			if not self.timerentry_showendtime.getValue():
				end = begin + (config.recording.margin_before.getValue()*60) + 1

		return begin, end

	def selectChannelSelector(self, *args):
		self.session.openWithCallback(
				self.finishedChannelSelectionCorrection,
				ChannelSelection.SimpleChannelSelection,
				_("Select channel to record from")
			)

	def finishedChannelSelectionCorrection(self, *args):
		if args:
			self.finishedChannelSelection(*args)
			self.keyGo()

	def keyGo(self, result = None):
		if not self.timerentry_service_ref.isRecordable():
			self.session.openWithCallback(self.selectChannelSelector, MessageBox, _("You didn't select a channel to record from."), MessageBox.TYPE_ERROR)
			return
		self.timer.name = self.timerentry_name.getValue()
		self.timer.description = self.timerentry_description.getValue()
		self.timer.justplay = self.timerentry_justplay.getValue() == "zap"
		self.timer.always_zap = self.timerentry_justplay.value == "zap+record"
		if self.timerentry_justplay.getValue() == "zap":
			if not self.timerentry_showendtime.getValue():
				self.timerentry_endtime.value = self.timerentry_starttime.getValue()
		self.timer.resetRepeated()
		self.timer.afterEvent = {
			"nothing": AFTEREVENT.NONE,
			"deepstandby": AFTEREVENT.DEEPSTANDBY,
			"standby": AFTEREVENT.STANDBY,
			"auto": AFTEREVENT.AUTO
			}[self.timerentry_afterevent.value]
		self.timer.descramble = {
			"normal": True,
			"descrambled+ecm": True,
			"scrambled+ecm": False,
			}[self.timerentry_recordingtype.value]
		self.timer.record_ecm = {
			"normal": False,
			"descrambled+ecm": True,
			"scrambled+ecm": True,
			}[self.timerentry_recordingtype.value]
		self.timer.service_ref = self.timerentry_service_ref
		self.timer.tags = self.timerentry_tags

		if self.timer.dirname or self.timerentry_dirname.getValue() != defaultMoviePath():
			self.timer.dirname = self.timerentry_dirname.getValue()
			config.movielist.last_timer_videodir.value = self.timer.dirname
			config.movielist.last_timer_videodir.save()

		if self.timerentry_type.getValue() == "once":
			self.timer.begin, self.timer.end = self.getBeginEnd()
		if self.timerentry_type.getValue() == "repeated":
			if self.timerentry_repeated.getValue() == "daily":
				for x in (0, 1, 2, 3, 4, 5, 6):
					self.timer.setRepeated(x)

			if self.timerentry_repeated.getValue() == "weekly":
				self.timer.setRepeated(self.timerentry_weekday.index)

			if self.timerentry_repeated.getValue() == "weekdays":
				for x in (0, 1, 2, 3, 4):
					self.timer.setRepeated(x)

			if self.timerentry_repeated.getValue() == "user":
				for x in (0, 1, 2, 3, 4, 5, 6):
					if self.timerentry_day[x].getValue():
						self.timer.setRepeated(x)

			self.timer.repeatedbegindate = self.getTimestamp(self.timerentry_repeatedbegindate.getValue(), self.timerentry_starttime.getValue())
			if self.timer.repeated:
				self.timer.begin = self.getTimestamp(self.timerentry_repeatedbegindate.getValue(), self.timerentry_starttime.getValue())
				self.timer.end = self.getTimestamp(self.timerentry_repeatedbegindate.getValue(), self.timerentry_endtime.getValue())
			else:
				self.timer.begin = self.getTimestamp(time.time(), self.timerentry_starttime.getValue())
				self.timer.end = self.getTimestamp(time.time(), self.timerentry_endtime.getValue())

			# when a timer end is set before the start, add 1 day
			if self.timer.end < self.timer.begin:
				self.timer.end += 86400

		if self.timer.eit is not None:
			event = eEPGCache.getInstance().lookupEventId(self.timer.service_ref.ref, self.timer.eit)
			if event:
				n = event.getNumOfLinkageServices()
				if n > 1:
					tlist = []
					ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
					parent = self.timer.service_ref.ref
					selection = 0
					for x in range(n):
						i = event.getLinkageService(parent, x)
						if i.toString() == ref.toString():
							selection = x
						tlist.append((i.getName(), i))
					self.session.openWithCallback(self.subserviceSelected, ChoiceBox, title=_("Please select a subservice to record..."), list = tlist, selection = selection)
					return
				elif n > 0:
					parent = self.timer.service_ref.ref
					self.timer.service_ref = ServiceReference(event.getLinkageService(parent, 0))
		self.saveTimer()
		self.close((True, self.timer))

	def changeTimerType(self):
		self.timerentry_justplay.selectNext()
		self.timerJustplayEntry = getConfigListEntry(_("Timer type"), self.timerentry_justplay)
		self["config"].invalidate(self.timerJustplayEntry)

	def incrementStart(self):
		self.timerentry_starttime.increment()
		self["config"].invalidate(self.entryStartTime)
		if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [0, 0]:
			self.timerentry_date.value += 86400
			self["config"].invalidate(self.entryDate)

	def decrementStart(self):
		self.timerentry_starttime.decrement()
		self["config"].invalidate(self.entryStartTime)
		if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [23, 59]:
			self.timerentry_date.value -= 86400
			self["config"].invalidate(self.entryDate)

	def incrementEnd(self):
		if self.entryEndTime is not None:
			self.timerentry_endtime.increment()
			self["config"].invalidate(self.entryEndTime)

	def decrementEnd(self):
		if self.entryEndTime is not None:
			self.timerentry_endtime.decrement()
			self["config"].invalidate(self.entryEndTime)

	def subserviceSelected(self, service):
		if not service is None:
			self.timer.service_ref = ServiceReference(service[1])
		self.saveTimer()
		self.close((True, self.timer))

	def saveTimer(self):
		self.session.nav.RecordTimer.saveTimer()

	def keyCancel(self):
		self.close((False,))

	def pathSelected(self, res):
		if res is not None:
			if config.movielist.videodirs.getValue() != self.timerentry_dirname.choices:
				self.timerentry_dirname.setChoices(config.movielist.videodirs.getValue(), default=res)
			self.timerentry_dirname.value = res

	def tagEditFinished(self, ret):
		if ret is not None:
			self.timerentry_tags = ret
			self.timerentry_tagsset.setChoices([not ret and "None" or " ".join(ret)])
			self["config"].invalidate(self.tagsSet)
Exemple #8
0
class TimerEntry(Screen, ConfigListScreen):

    def __init__(self, session, timer):
        Screen.__init__(self, session)
        self.setup_title = _('Timer entry')
        self.timer = timer
        self.entryDate = None
        self.entryService = None
        self['HelpWindow'] = Pixmap()
        self['HelpWindow'].hide()
        self['VKeyIcon'] = Boolean(False)
        self['description'] = Label('')
        self['oktext'] = Label(_('OK'))
        self['canceltext'] = Label(_('Cancel'))
        self['ok'] = Pixmap()
        self['cancel'] = Pixmap()
        self.createConfig()
        self['actions'] = NumberActionMap(['SetupActions',
         'GlobalActions',
         'PiPSetupActions',
         'ColorActions'], {'ok': self.keySelect,
         'save': self.keyGo,
         'cancel': self.keyCancel,
         'volumeUp': self.incrementStart,
         'volumeDown': self.decrementStart,
         'size+': self.incrementEnd,
         'size-': self.decrementEnd}, -2)
        self['VirtualKB'] = ActionMap(['VirtualKeyboardActions'], {'showVirtualKeyboard': self.KeyText}, -2)
        self['VirtualKB'].setEnabled(False)
        self.onChangedEntry = []
        self.list = []
        ConfigListScreen.__init__(self, self.list, session=session)
        self.createSetup('config')
        self.onLayoutFinish.append(self.layoutFinished)
        if self.selectionChanged not in self['config'].onSelectionChanged:
            self['config'].onSelectionChanged.append(self.selectionChanged)
        self.selectionChanged()
        return

    def createConfig(self):
        justplay = self.timer.justplay
        always_zap = self.timer.always_zap
        rename_repeat = self.timer.rename_repeat
        afterevent = {AFTEREVENT.NONE: 'nothing',
         AFTEREVENT.DEEPSTANDBY: 'deepstandby',
         AFTEREVENT.STANDBY: 'standby',
         AFTEREVENT.AUTO: 'auto'}[self.timer.afterEvent]
        if self.timer.record_ecm and self.timer.descramble:
            recordingtype = 'descrambled+ecm'
        elif self.timer.record_ecm:
            recordingtype = 'scrambled+ecm'
        elif self.timer.descramble:
            recordingtype = 'normal'
        weekday_table = ('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
        day = []
        weekday = 0
        for x in (0, 1, 2, 3, 4, 5, 6):
            day.append(0)

        if self.timer.repeated:
            type = 'repeated'
            if self.timer.repeated == 31:
                repeated = 'weekdays'
            elif self.timer.repeated == 127:
                repeated = 'daily'
            else:
                flags = self.timer.repeated
                repeated = 'user'
                count = 0
                for x in (0, 1, 2, 3, 4, 5, 6):
                    if flags == 1:
                        weekday = x
                    if flags & 1 == 1:
                        day[x] = 1
                        count += 1
                    else:
                        day[x] = 0
                    flags >>= 1

                if count == 1:
                    repeated = 'weekly'
        else:
            type = 'once'
            repeated = None
            weekday = int(strftime('%u', localtime(self.timer.begin))) - 1
            day[weekday] = 1
        self.timerentry_justplay = ConfigSelection(choices=[('zap', _('zap')), ('record', _('record')), ('zap+record', _('zap and record'))], default={0: 'record',
         1: 'zap',
         2: 'zap+record'}[justplay + 2 * always_zap])
        if SystemInfo['DeepstandbySupport']:
            shutdownString = _('go to deep standby')
        else:
            shutdownString = _('shut down')
        self.timerentry_afterevent = ConfigSelection(choices=[('nothing', _('do nothing')),
         ('standby', _('go to standby')),
         ('deepstandby', shutdownString),
         ('auto', _('auto'))], default=afterevent)
        self.timerentry_recordingtype = ConfigSelection(choices=[('normal', _('normal')), ('descrambled+ecm', _('descramble and record ecm')), ('scrambled+ecm', _("don't descramble, record ecm"))], default=recordingtype)
        self.timerentry_type = ConfigSelection(choices=[('once', _('once')), ('repeated', _('repeated'))], default=type)
        self.timerentry_name = ConfigText(default=self.timer.name.replace('\xc2\x86', '').replace('\xc2\x87', '').encode('utf-8'), visible_width=50, fixed_size=False)
        self.timerentry_description = ConfigText(default=self.timer.description, visible_width=50, fixed_size=False)
        self.timerentry_tags = self.timer.tags[:]
        if not self.timerentry_tags:
            tagname = self.timer.name.strip()
            if tagname:
                tagname = tagname[0].upper() + tagname[1:].replace(' ', '_')
                self.timerentry_tags.append(tagname)
        self.timerentry_tagsset = ConfigSelection(choices=[not self.timerentry_tags and 'None' or ' '.join(self.timerentry_tags)])
        self.timerentry_repeated = ConfigSelection(default=repeated, choices=[('weekly', _('weekly')),
         ('daily', _('daily')),
         ('weekdays', _('Mon-Fri')),
         ('user', _('user defined'))])
        self.timerentry_renamerepeat = ConfigYesNo(default=rename_repeat)
        self.timerentry_date = ConfigDateTime(default=self.timer.begin, formatstring=_('%d %B %Y'), increment=86400)
        self.timerentry_starttime = ConfigClock(default=self.timer.begin)
        self.timerentry_endtime = ConfigClock(default=self.timer.end)
        self.timerentry_showendtime = ConfigSelection(default=self.timer.end > self.timer.begin + 3 and self.timer.justplay, choices=[(True, _('yes')), (False, _('no'))])
        default = self.timer.dirname or defaultMoviePath()
        tmp = config.movielist.videodirs.value
        if default not in tmp:
            tmp.append(default)
        self.timerentry_dirname = ConfigSelection(default=default, choices=tmp)
        self.timerentry_repeatedbegindate = ConfigDateTime(default=self.timer.repeatedbegindate, formatstring=_('%d.%B %Y'), increment=86400)
        self.timerentry_weekday = ConfigSelection(default=weekday_table[weekday], choices=[('mon', _('Monday')),
         ('tue', _('Tuesday')),
         ('wed', _('Wednesday')),
         ('thu', _('Thursday')),
         ('fri', _('Friday')),
         ('sat', _('Saturday')),
         ('sun', _('Sunday'))])
        self.timerentry_day = ConfigSubList()
        for x in (0, 1, 2, 3, 4, 5, 6):
            self.timerentry_day.append(ConfigYesNo(default=day[x]))

        servicename = 'N/A'
        try:
            servicename = str(self.timer.service_ref.getServiceName())
        except:
            pass

        self.timerentry_service_ref = self.timer.service_ref
        self.timerentry_service = ConfigSelection([servicename])
        return

    def createSetup(self, widget):
        self.list = []
        self.entryName = getConfigListEntry(_('Name'), self.timerentry_name, _('Set the name the recording will get.'))
        self.list.append(self.entryName)
        self.entryDescription = getConfigListEntry(_('Description'), self.timerentry_description, _('Set the description of the recording.'))
        self.list.append(self.entryDescription)
        self.timerJustplayEntry = getConfigListEntry(_('Timer type'), self.timerentry_justplay, _('Chose between record and ZAP.'))
        self.list.append(self.timerJustplayEntry)
        self.timerTypeEntry = getConfigListEntry(_('Repeat type'), self.timerentry_type, _('A repeating timer or just once?'))
        self.list.append(self.timerTypeEntry)
        if self.timerentry_type.value == 'once':
            self.frequencyEntry = None
        else:
            self.frequencyEntry = getConfigListEntry(_('Repeats'), self.timerentry_repeated, _('Choose between Daily, Weekly, Weekdays or user defined.'))
            self.list.append(self.frequencyEntry)
            self.repeatedbegindateEntry = getConfigListEntry(_('Starting on'), self.timerentry_repeatedbegindate, _('Set the date the timer must start.'))
            self.list.append(self.repeatedbegindateEntry)
            if self.timerentry_repeated.value == 'daily':
                pass
            if self.timerentry_repeated.value == 'weekdays':
                pass
            if self.timerentry_repeated.value == 'weekly':
                self.list.append(getConfigListEntry(_('Weekday'), self.timerentry_weekday))
            if self.timerentry_repeated.value == 'user':
                self.list.append(getConfigListEntry(_('Monday'), self.timerentry_day[0]))
                self.list.append(getConfigListEntry(_('Tuesday'), self.timerentry_day[1]))
                self.list.append(getConfigListEntry(_('Wednesday'), self.timerentry_day[2]))
                self.list.append(getConfigListEntry(_('Thursday'), self.timerentry_day[3]))
                self.list.append(getConfigListEntry(_('Friday'), self.timerentry_day[4]))
                self.list.append(getConfigListEntry(_('Saturday'), self.timerentry_day[5]))
                self.list.append(getConfigListEntry(_('Sunday'), self.timerentry_day[6]))
            if self.timerentry_justplay.value != 'zap':
                self.list.append(getConfigListEntry(_('Rename name and description for new events'), self.timerentry_renamerepeat))
        self.entryDate = getConfigListEntry(_('Date'), self.timerentry_date, _('Set the date the timer must start.'))
        if self.timerentry_type.value == 'once':
            self.list.append(self.entryDate)
        self.entryStartTime = getConfigListEntry(_('Start time'), self.timerentry_starttime, _('Set the time the timer must start.'))
        self.list.append(self.entryStartTime)
        self.entryShowEndTime = getConfigListEntry(_('Set end time'), self.timerentry_showendtime, _('Set the time the timer must stop.'))
        if self.timerentry_justplay.value == 'zap':
            self.list.append(self.entryShowEndTime)
        self.entryEndTime = getConfigListEntry(_('End time'), self.timerentry_endtime, _('Set the time the timer must stop.'))
        if self.timerentry_justplay.value != 'zap' or self.timerentry_showendtime.value:
            self.list.append(self.entryEndTime)
        self.channelEntry = getConfigListEntry(_('Channel'), self.timerentry_service, _('Set the channel for this timer.'))
        self.list.append(self.channelEntry)
        if self.timerentry_showendtime.value and self.timerentry_justplay.value == 'zap':
            self.list.append(getConfigListEntry(_('After event'), self.timerentry_afterevent, _("What action is required on complettion of the timer? 'Auto' lets the box return to the state it had when the timer started. 'Do nothing', 'Go to standby' and 'Go to deep standby' do ecaxtly that.")))
        self.dirname = getConfigListEntry(_('Location'), self.timerentry_dirname, _('Where should the recording be saved?'))
        self.tagsSet = getConfigListEntry(_('Tags'), self.timerentry_tagsset, _('Choose a tag for easy finding a recording.'))
        if self.timerentry_justplay.value != 'zap':
            if config.usage.setup_level.index >= 2:
                self.list.append(self.dirname)
            if getPreferredTagEditor():
                self.list.append(self.tagsSet)
            self.list.append(getConfigListEntry(_('After event'), self.timerentry_afterevent, _("What action is required on complettion of the timer? 'Auto' lets the box return to the state it had when the timer started. 'Do nothing', 'Go to standby' and 'Go to deep standby' do ecaxtly that.")))
            self.list.append(getConfigListEntry(_('Recording type'), self.timerentry_recordingtype, _("Descramble & record ECM' gives the option to descramble afterwards if descrambling on recording failed. 'Don't descramble, record ECM' save a scramble recording that can be descrambled on playback. 'Normal' means descramble the recording and don't record ECM.")))
        self[widget].list = self.list
        self[widget].l.setList(self.list)
        return

    def selectionChanged(self):
        if self['config'].getCurrent():
            if len(self['config'].getCurrent()) > 2 and self['config'].getCurrent()[2]:
                self['description'].setText(self['config'].getCurrent()[2])
            if isinstance(self['config'].getCurrent()[1], ConfigText):
                if self.has_key('VKeyIcon'):
                    self['VirtualKB'].setEnabled(True)
                    self['VKeyIcon'].boolean = True
                if self.has_key('HelpWindow'):
                    if self['config'].getCurrent()[1].help_window and self['config'].getCurrent()[1].help_window.instance is not None:
                        helpwindowpos = self['HelpWindow'].getPosition()
                        from enigma import ePoint
                        self['config'].getCurrent()[1].help_window.instance.move(ePoint(helpwindowpos[0], helpwindowpos[1]))
                    elif self.has_key('VKeyIcon'):
                        self['VirtualKB'].setEnabled(False)
                        self['VKeyIcon'].boolean = False
        elif self.has_key('VKeyIcon'):
            self['VirtualKB'].setEnabled(False)
            self['VKeyIcon'].boolean = False
        return

    def layoutFinished(self):
        self.setTitle(_(self.setup_title))

    def createSummary(self):
        return SetupSummary

    def changedEntry(self):
        for x in self.onChangedEntry:
            x()

    def getCurrentEntry(self):
        return self['config'].getCurrent() and self['config'].getCurrent()[0] or ''

    def getCurrentValue(self):
        return self['config'].getCurrent() and str(self['config'].getCurrent()[1].getText()) or ''

    def newConfig(self):
        if self['config'].getCurrent() in (self.timerTypeEntry,
         self.timerJustplayEntry,
         self.frequencyEntry,
         self.entryShowEndTime):
            self.createSetup('config')

    def KeyText(self):
        if self['config'].getCurrent()[0] in (_('Name'), _('Description')):
            self.session.openWithCallback(self.renameEntryCallback, VirtualKeyBoard, title=self['config'].getCurrent()[2], text=self['config'].getCurrent()[1].value)

    def keyLeft(self):
        cur = self['config'].getCurrent()
        if cur in (self.channelEntry, self.tagsSet):
            self.keySelect()
        elif cur in (self.entryName, self.entryDescription):
            self.renameEntry()
        else:
            ConfigListScreen.keyLeft(self)
            self.newConfig()

    def keyRight(self):
        cur = self['config'].getCurrent()
        if cur in (self.channelEntry, self.tagsSet):
            self.keySelect()
        elif cur in (self.entryName, self.entryDescription):
            self.renameEntry()
        else:
            ConfigListScreen.keyRight(self)
            self.newConfig()

    def renameEntry(self):
        cur = self['config'].getCurrent()
        if cur == self.entryName:
            title_text = _('Please enter new name:')
            old_text = self.timerentry_name.value
        else:
            title_text = _('Please enter new description:')
            old_text = self.timerentry_description.value
        self.session.openWithCallback(self.renameEntryCallback, VirtualKeyBoard, title=title_text, text=old_text)

    def renameEntryCallback(self, answer):
        if answer:
            if self['config'].getCurrent() == self.entryName:
                self.timerentry_name.value = answer
                self['config'].invalidate(self.entryName)
            else:
                self.timerentry_description.value = answer
                self['config'].invalidate(self.entryDescription)

    def handleKeyFileCallback(self, answer):
        if self['config'].getCurrent() in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.handleKeyFileCallback(self, answer)
            self.newConfig()

    def keySelect(self):
        cur = self['config'].getCurrent()
        if cur == self.channelEntry:
            self.session.openWithCallback(self.finishedChannelSelection, ChannelSelection.SimpleChannelSelection, _('Select channel to record from'), currentBouquet=True)
        elif config.usage.setup_level.index >= 2 and cur == self.dirname:
            self.session.openWithCallback(self.pathSelected, MovieLocationBox, _('Select target folder'), self.timerentry_dirname.value, minFree=100)
        elif getPreferredTagEditor() and cur == self.tagsSet:
            self.session.openWithCallback(self.tagEditFinished, getPreferredTagEditor(), self.timerentry_tags)
        else:
            self.keyGo()

    def finishedChannelSelection(self, *args):
        if args:
            self.timerentry_service_ref = ServiceReference(args[0])
            self.timerentry_service.setCurrentText(self.timerentry_service_ref.getServiceName())
            self['config'].invalidate(self.channelEntry)

    def getTimestamp(self, date, mytime):
        d = localtime(date)
        dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
        return int(mktime(dt.timetuple()))

    def getBeginEnd(self):
        date = self.timerentry_date.value
        endtime = self.timerentry_endtime.value
        starttime = self.timerentry_starttime.value
        begin = self.getTimestamp(date, starttime)
        end = self.getTimestamp(date, endtime)
        if end < begin:
            end += 86400
        if self.timerentry_justplay.value == 'zap':
            if not self.timerentry_showendtime.value:
                end = begin + 1
        return (begin, end)

    def selectChannelSelector(self, *args):
        self.session.openWithCallback(self.finishedChannelSelectionCorrection, ChannelSelection.SimpleChannelSelection, _('Select channel to record from'))

    def finishedChannelSelectionCorrection(self, *args):
        if args:
            self.finishedChannelSelection(*args)
            self.keyGo()

    def keyGo(self, result = None):
        if not self.timerentry_service_ref.isRecordable():
            self.session.openWithCallback(self.selectChannelSelector, MessageBox, _("You didn't select a channel to record from."), MessageBox.TYPE_ERROR)
            return
        else:
            self.timer.name = self.timerentry_name.value
            self.timer.description = self.timerentry_description.value
            self.timer.justplay = self.timerentry_justplay.value == 'zap'
            self.timer.always_zap = self.timerentry_justplay.value == 'zap+record'
            self.timer.rename_repeat = self.timerentry_renamerepeat.value
            if self.timerentry_justplay.value == 'zap':
                if not self.timerentry_showendtime.value:
                    self.timerentry_endtime.value = self.timerentry_starttime.value
                    self.timerentry_afterevent.value = 'nothing'
            if self.timerentry_endtime.value == self.timerentry_starttime.value and self.timerentry_afterevent.value != 'nothing':
                self.timerentry_afterevent.value = 'nothing'
                self.session.open(MessageBox, _('Difference between timer begin and end must be equal or greater than %d minutes.\nEnd Action was disabled !') % 1, MessageBox.TYPE_INFO, timeout=30)
            self.timer.resetRepeated()
            self.timer.afterEvent = {'nothing': AFTEREVENT.NONE,
             'deepstandby': AFTEREVENT.DEEPSTANDBY,
             'standby': AFTEREVENT.STANDBY,
             'auto': AFTEREVENT.AUTO}[self.timerentry_afterevent.value]
            self.timer.descramble = {'normal': True,
             'descrambled+ecm': True,
             'scrambled+ecm': False}[self.timerentry_recordingtype.value]
            self.timer.record_ecm = {'normal': False,
             'descrambled+ecm': True,
             'scrambled+ecm': True}[self.timerentry_recordingtype.value]
            self.timer.service_ref = self.timerentry_service_ref
            self.timer.tags = self.timerentry_tags
            if self.timer.dirname or self.timerentry_dirname.value != defaultMoviePath():
                self.timer.dirname = self.timerentry_dirname.value
                config.movielist.last_timer_videodir.value = self.timer.dirname
                config.movielist.last_timer_videodir.save()
            if self.timerentry_type.value == 'once':
                self.timer.begin, self.timer.end = self.getBeginEnd()
            if self.timerentry_type.value == 'repeated':
                if self.timerentry_repeated.value == 'daily':
                    for x in (0, 1, 2, 3, 4, 5, 6):
                        self.timer.setRepeated(x)

                if self.timerentry_repeated.value == 'weekly':
                    self.timer.setRepeated(self.timerentry_weekday.index)
                if self.timerentry_repeated.value == 'weekdays':
                    for x in (0, 1, 2, 3, 4):
                        self.timer.setRepeated(x)

                if self.timerentry_repeated.value == 'user':
                    for x in (0, 1, 2, 3, 4, 5, 6):
                        if self.timerentry_day[x].value:
                            self.timer.setRepeated(x)

                self.timer.repeatedbegindate = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
                if self.timer.repeated:
                    self.timer.begin = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
                    self.timer.end = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_endtime.value)
                else:
                    self.timer.begin = self.getTimestamp(time.time(), self.timerentry_starttime.value)
                    self.timer.end = self.getTimestamp(time.time(), self.timerentry_endtime.value)
                if self.timer.end < self.timer.begin:
                    self.timer.end += 86400
            if self.timer.eit is not None:
                event = eEPGCache.getInstance().lookupEventId(self.timer.service_ref.ref, self.timer.eit)
                if event:
                    n = event.getNumOfLinkageServices()
                    if n > 1:
                        tlist = []
                        ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
                        parent = self.timer.service_ref.ref
                        selection = 0
                        for x in range(n):
                            i = event.getLinkageService(parent, x)
                            if i.toString() == ref.toString():
                                selection = x
                            tlist.append((i.getName(), i))

                        self.session.openWithCallback(self.subserviceSelected, ChoiceBox, title=_('Please select a subservice to record...'), list=tlist, selection=selection)
                        return
                    if n > 0:
                        parent = self.timer.service_ref.ref
                        self.timer.service_ref = ServiceReference(event.getLinkageService(parent, 0))
            self.saveTimer()
            self.close((True, self.timer))
            return

    def changeTimerType(self):
        self.timerentry_justplay.selectNext()
        self.timerJustplayEntry = getConfigListEntry(_('Timer type'), self.timerentry_justplay)
        self['config'].invalidate(self.timerJustplayEntry)

    def incrementStart(self):
        self.timerentry_starttime.increment()
        self['config'].invalidate(self.entryStartTime)
        if self.timerentry_type.value == 'once' and self.timerentry_starttime.value == [0, 0]:
            self.timerentry_date.value += 86400
            self['config'].invalidate(self.entryDate)

    def decrementStart(self):
        self.timerentry_starttime.decrement()
        self['config'].invalidate(self.entryStartTime)
        if self.timerentry_type.value == 'once' and self.timerentry_starttime.value == [23, 59]:
            self.timerentry_date.value -= 86400
            self['config'].invalidate(self.entryDate)

    def incrementEnd(self):
        if self.entryEndTime is not None:
            self.timerentry_endtime.increment()
            self['config'].invalidate(self.entryEndTime)
        return

    def decrementEnd(self):
        if self.entryEndTime is not None:
            self.timerentry_endtime.decrement()
            self['config'].invalidate(self.entryEndTime)
        return

    def subserviceSelected(self, service):
        if service is not None:
            self.timer.service_ref = ServiceReference(service[1])
        self.saveTimer()
        self.close((True, self.timer))
        return

    def saveTimer(self):
        self.session.nav.RecordTimer.saveTimer()

    def keyCancel(self):
        self.close((False,))

    def pathSelected(self, res):
        if res is not None:
            if config.movielist.videodirs.value != self.timerentry_dirname.choices:
                self.timerentry_dirname.setChoices(config.movielist.videodirs.value, default=res)
            self.timerentry_dirname.value = res
        return

    def tagEditFinished(self, ret):
        if ret is not None:
            self.timerentry_tags = ret
            self.timerentry_tagsset.setChoices([not ret and 'None' or ' '.join(ret)])
            self['config'].invalidate(self.tagsSet)
        return
Exemple #9
0
class TimerEntry(Screen, ConfigListScreen):

    def __init__(self, session, timer):
        Screen.__init__(self, session)
        self.setup_title = _('Timer entry')
        self.timer = timer
        self.entryDate = None
        self.entryService = None
        self['HelpWindow'] = Pixmap()
        self['HelpWindow'].hide()
        self['VKeyIcon'] = Boolean(False)
        self['locationdescription'] = Label('')
        self['locationfreespace'] = Label('')
        self['description'] = Label('')
        self['oktext'] = Label(_('OK'))
        self['canceltext'] = Label(_('Cancel'))
        self['ok'] = Pixmap()
        self['cancel'] = Pixmap()
        self.createConfig()
        self['actions'] = NumberActionMap(['SetupActions',
         'GlobalActions',
         'PiPSetupActions',
         'ColorActions'], {'ok': self.keySelect,
         'save': self.keyGo,
         'cancel': self.keyCancel,
         'volumeUp': self.incrementStart,
         'volumeDown': self.decrementStart,
         'size+': self.incrementEnd,
         'size-': self.decrementEnd}, -2)
        self['VirtualKB'] = ActionMap(['VirtualKeyboardActions'], {'showVirtualKeyboard': self.KeyText}, -2)
        self['VirtualKB'].setEnabled(False)
        self.onChangedEntry = []
        self.list = []
        ConfigListScreen.__init__(self, self.list, session=session)
        self.createSetup('config')
        self.onLayoutFinish.append(self.layoutFinished)
        if self.selectionChanged not in self['config'].onSelectionChanged:
            self['config'].onSelectionChanged.append(self.selectionChanged)
        self.selectionChanged()

    def createConfig(self):
        justplay = self.timer.justplay
        always_zap = self.timer.always_zap
        rename_repeat = self.timer.rename_repeat
        afterevent = {AFTEREVENT.NONE: 'nothing',
         AFTEREVENT.DEEPSTANDBY: 'deepstandby',
         AFTEREVENT.STANDBY: 'standby',
         AFTEREVENT.AUTO: 'auto'}[self.timer.afterEvent]
        if self.timer.record_ecm and self.timer.descramble:
            recordingtype = 'descrambled+ecm'
        elif self.timer.record_ecm:
            recordingtype = 'scrambled+ecm'
        elif self.timer.descramble:
            recordingtype = 'normal'
        weekday_table = ('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
        day = []
        weekday = 0
        for x in (0, 1, 2, 3, 4, 5, 6):
            day.append(0)

        if self.timer.repeated:
            type = 'repeated'
            if self.timer.repeated == 31:
                repeated = 'weekdays'
            elif self.timer.repeated == 127:
                repeated = 'daily'
            else:
                flags = self.timer.repeated
                repeated = 'user'
                count = 0
                for x in (0, 1, 2, 3, 4, 5, 6):
                    if flags == 1:
                        weekday = x
                    if flags & 1 == 1:
                        day[x] = 1
                        count += 1
                    else:
                        day[x] = 0
                    flags >>= 1

                if count == 1:
                    repeated = 'weekly'
        else:
            type = 'once'
            repeated = None
            weekday = int(strftime('%u', localtime(self.timer.begin))) - 1
            day[weekday] = 1
        self.timerentry_justplay = ConfigSelection(choices=[('zap', _('zap')), ('record', _('record')), ('zap+record', _('zap and record'))], default={0: 'record',
         1: 'zap',
         2: 'zap+record'}[justplay + 2 * always_zap])
        self.timertyp = self.timerentry_justplay.value
        if SystemInfo['DeepstandbySupport']:
            shutdownString = _('go to deep standby')
        else:
            shutdownString = _('shut down')
        self.timerentry_afterevent = ConfigSelection(choices=[('nothing', _('do nothing')),
         ('standby', _('go to standby')),
         ('deepstandby', shutdownString),
         ('auto', _('auto'))], default=afterevent)
        self.timerentry_recordingtype = ConfigSelection(choices=[('normal', _('normal')), ('descrambled+ecm', _('descramble and record ecm')), ('scrambled+ecm', _("don't descramble, record ecm"))], default=recordingtype)
        self.timerentry_type = ConfigSelection(choices=[('once', _('once')), ('repeated', _('repeated'))], default=type)
        self.timerentry_name = ConfigText(default=self.timer.name.replace('\xc2\x86', '').replace('\xc2\x87', '').encode('utf-8'), visible_width=50, fixed_size=False)
        self.timerentry_description_replaced = self.timer.description.replace('\xc2\x8a', ' ').encode('utf-8')
        self.timerentry_description = ConfigText(default=self.timerentry_description_replaced, visible_width=50, fixed_size=False)
        self.timerentry_tags = self.timer.tags[:]
        if not self.timerentry_tags:
            tagname = self.timer.name.strip()
            if tagname:
                tagname = tagname[0].upper() + tagname[1:].replace(' ', '_')
                self.timerentry_tags.append(tagname)
        self.timerentry_tagsset = ConfigSelection(choices=[not self.timerentry_tags and 'None' or ' '.join(self.timerentry_tags)])
        self.timerentry_repeated = ConfigSelection(default=repeated, choices=[('weekly', _('weekly')),
         ('daily', _('daily')),
         ('weekdays', _('Mon-Fri')),
         ('user', _('user defined'))])
        self.timerentry_renamerepeat = ConfigYesNo(default=rename_repeat)
        self.timerentry_date = ConfigDateTime(default=self.timer.begin, formatstring=_('%d %B %Y'), increment=86400)
        self.timerentry_starttime = ConfigClock(default=self.timer.begin)
        self.timerentry_endtime = ConfigClock(default=self.timer.end)
        self.timerentry_showendtime = ConfigSelection(default=self.timer.end > self.timer.begin + 3 and self.timer.justplay, choices=[(True, _('yes')), (False, _('no'))])
        default = self.timer.dirname or defaultMoviePath()
        tmp = config.movielist.videodirs.value
        if default not in tmp:
            tmp.append(default)
        self.timerentry_dirname = ConfigSelection(default=default, choices=tmp)
        self.timerentry_repeatedbegindate = ConfigDateTime(default=self.timer.repeatedbegindate, formatstring=_('%d.%B %Y'), increment=86400)
        self.timerentry_weekday = ConfigSelection(default=weekday_table[weekday], choices=[('mon', _('Monday')),
         ('tue', _('Tuesday')),
         ('wed', _('Wednesday')),
         ('thu', _('Thursday')),
         ('fri', _('Friday')),
         ('sat', _('Saturday')),
         ('sun', _('Sunday'))])
        self.timerentry_day = ConfigSubList()
        for x in (0, 1, 2, 3, 4, 5, 6):
            self.timerentry_day.append(ConfigYesNo(default=day[x]))

        servicename = 'N/A'
        try:
            servicename = str(self.timer.service_ref.getServiceName())
        except:
            pass

        self.timerentry_service_ref = self.timer.service_ref
        self.timerentry_service = ConfigSelection([servicename])

    def createSetup(self, widget):
        if self.timer not in self.session.nav.RecordTimer.timer_list:
            newtime = None
            if self.timerentry_justplay.value == 'zap' and self.timertyp != 'zap':
                newtime = self.getTimestamp(self.timerentry_date.value, self.timerentry_starttime.value) + config.recording.margin_before.value * 60
                newbegin = localtime(newtime)
            elif self.timerentry_justplay.value != 'zap' and self.timertyp == 'zap':
                newtime = self.getTimestamp(self.timerentry_date.value, self.timerentry_starttime.value) - config.recording.margin_before.value * 60
                newbegin = localtime(newtime)
            if newtime:
                self.timerentry_date.value = newtime
                self.timerentry_starttime.value = [newbegin.tm_hour, newbegin.tm_min]
            self.timertyp = self.timerentry_justplay.value
        self.list = []
        self.timerJustplayEntry = getConfigListEntry(_('Timer type'), self.timerentry_justplay, _('Chose between record and ZAP.'))
        self.list.append(self.timerJustplayEntry)
        self.entryName = getConfigListEntry(_('Name'), self.timerentry_name, _('Set the name the recording will get.'))
        self.list.append(self.entryName)
        self.entryDescription = getConfigListEntry(_('Description'), self.timerentry_description, _('Set the description of the recording.'))
        self.list.append(self.entryDescription)
        self.timerTypeEntry = getConfigListEntry(_('Repeat type'), self.timerentry_type, _('A repeating timer or just once?'))
        self.list.append(self.timerTypeEntry)
        if self.timerentry_type.value == 'once':
            self.frequencyEntry = None
        else:
            self.frequencyEntry = getConfigListEntry(_('Repeats'), self.timerentry_repeated, _('Choose between Daily, Weekly, Weekdays or user defined.'))
            self.list.append(self.frequencyEntry)
            self.repeatedbegindateEntry = getConfigListEntry(_('Starting on'), self.timerentry_repeatedbegindate, _('Set the date the timer must start.'))
            self.list.append(self.repeatedbegindateEntry)
            if self.timerentry_repeated.value == 'daily':
                pass
            if self.timerentry_repeated.value == 'weekdays':
                pass
            if self.timerentry_repeated.value == 'weekly':
                self.list.append(getConfigListEntry(_('Weekday'), self.timerentry_weekday))
            if self.timerentry_repeated.value == 'user':
                self.list.append(getConfigListEntry(_('Monday'), self.timerentry_day[0]))
                self.list.append(getConfigListEntry(_('Tuesday'), self.timerentry_day[1]))
                self.list.append(getConfigListEntry(_('Wednesday'), self.timerentry_day[2]))
                self.list.append(getConfigListEntry(_('Thursday'), self.timerentry_day[3]))
                self.list.append(getConfigListEntry(_('Friday'), self.timerentry_day[4]))
                self.list.append(getConfigListEntry(_('Saturday'), self.timerentry_day[5]))
                self.list.append(getConfigListEntry(_('Sunday'), self.timerentry_day[6]))
            if self.timerentry_justplay.value != 'zap':
                self.list.append(getConfigListEntry(_('Rename name and description for new events'), self.timerentry_renamerepeat))
        self.entryDate = getConfigListEntry(_('Date'), self.timerentry_date, _('Set the date the timer must start.'))
        if self.timerentry_type.value == 'once':
            self.list.append(self.entryDate)
        self.entryStartTime = getConfigListEntry(_('Start time'), self.timerentry_starttime, _('Set the time the timer must start.'))
        self.list.append(self.entryStartTime)
        self.entryShowEndTime = getConfigListEntry(_('Set end time'), self.timerentry_showendtime, _('Set the time the timer must stop.'))
        if self.timerentry_justplay.value == 'zap':
            self.list.append(self.entryShowEndTime)
        self.entryEndTime = getConfigListEntry(_('End time'), self.timerentry_endtime, _('Set the time the timer must stop.'))
        if self.timerentry_justplay.value != 'zap' or self.timerentry_showendtime.value:
            self.list.append(self.entryEndTime)
        self.channelEntry = getConfigListEntry(_('Channel'), self.timerentry_service, _('Set the channel for this timer.'))
        self.list.append(self.channelEntry)
        if self.timerentry_showendtime.value and self.timerentry_justplay.value == 'zap':
            self.list.append(getConfigListEntry(_('After event'), self.timerentry_afterevent, _("What action is required on complettion of the timer? 'Auto' lets the box return to the state it had when the timer started. 'Do nothing', 'Go to standby' and 'Go to deep standby' do ecaxtly that.")))
        description = free = ''
        try:
            if self.timerentry_justplay.value != 'zap':
                stat = statvfs(self.timerentry_dirname.value)
                a = float(stat.f_blocks) * stat.f_bsize / 1024 / 1024 / 1024
                b = float(stat.f_bavail) * stat.f_bsize / 1024 / 1024 / 1024
                c = 100.0 * b / a
                free = ('%0.f GB (%0.f %s) ' + _('free diskspace')) % (b, c, '%')
                description = _('Current location')
        except:
            pass

        self['locationdescription'].setText(description)
        self['locationfreespace'].setText(free)
        self.dirname = getConfigListEntry(_('Location'), self.timerentry_dirname, _('Where should the recording be saved?'))
        self.tagsSet = getConfigListEntry(_('Tags'), self.timerentry_tagsset, _('Choose a tag for easy finding a recording.'))
        if self.timerentry_justplay.value != 'zap':
            if config.usage.setup_level.index >= 2:
                self.list.append(self.dirname)
            if getPreferredTagEditor():
                self.list.append(self.tagsSet)
            self.list.append(getConfigListEntry(_('After Recording'), self.timerentry_afterevent, _("What action is required on complettion of the timer? 'Auto' lets the box return to the state it had when the timer started. 'Do nothing', 'Go to standby' and 'Go to deep standby' do ecaxtly that.")))
            self.list.append(getConfigListEntry(_('Recording type'), self.timerentry_recordingtype, _("Descramble & record ECM' gives the option to descramble afterwards if descrambling on recording failed. 'Don't descramble, record ECM' save a scramble recording that can be descrambled on playback. 'Normal' means descramble the recording and don't record ECM.")))
        self[widget].list = self.list
        self[widget].l.setList(self.list)

    def selectionChanged(self):
        if self['config'].getCurrent():
            if len(self['config'].getCurrent()) > 2 and self['config'].getCurrent()[2]:
                self['description'].setText(self['config'].getCurrent()[2])
            if isinstance(self['config'].getCurrent()[1], ConfigText):
                if self.has_key('VKeyIcon'):
                    self['VirtualKB'].setEnabled(True)
                    self['VKeyIcon'].boolean = True
                if self.has_key('HelpWindow'):
                    if self['config'].getCurrent()[1].help_window and self['config'].getCurrent()[1].help_window.instance is not None:
                        helpwindowpos = self['HelpWindow'].getPosition()
                        from enigma import ePoint
                        self['config'].getCurrent()[1].help_window.instance.move(ePoint(helpwindowpos[0], helpwindowpos[1]))
                    elif self.has_key('VKeyIcon'):
                        self['VirtualKB'].setEnabled(False)
                        self['VKeyIcon'].boolean = False
        elif self.has_key('VKeyIcon'):
            self['VirtualKB'].setEnabled(False)
            self['VKeyIcon'].boolean = False

    def layoutFinished(self):
        self.setTitle(_(self.setup_title))

    def createSummary(self):
        return SetupSummary

    def changedEntry(self):
        for x in self.onChangedEntry:
            x()

    def getCurrentEntry(self):
        return self['config'].getCurrent() and self['config'].getCurrent()[0] or ''

    def getCurrentValue(self):
        return self['config'].getCurrent() and str(self['config'].getCurrent()[1].getText()) or ''

    def newConfig(self):
        if self['config'].getCurrent() in (self.timerTypeEntry,
         self.timerJustplayEntry,
         self.frequencyEntry,
         self.entryShowEndTime,
         self.dirname):
            self.createSetup('config')

    def KeyText(self):
        if self['config'].getCurrent()[0] in (_('Name'), _('Description')):
            self.session.openWithCallback(self.renameEntryCallback, VirtualKeyBoard, title=self['config'].getCurrent()[2], text=self['config'].getCurrent()[1].value, visible_width=50, currPos=0)

    def keyLeft(self):
        cur = self['config'].getCurrent()
        if cur in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.keyLeft(self)
            self.newConfig()

    def keyRight(self):
        cur = self['config'].getCurrent()
        if cur in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.keyRight(self)
            self.newConfig()

    def renameEntry(self):
        cur = self['config'].getCurrent()
        if cur == self.entryName:
            title_text = _('Please enter new name:')
            old_text = self.timerentry_name.value
        else:
            title_text = _('Please enter new description:')
            old_text = self.timerentry_description.value
        self.session.openWithCallback(self.renameEntryCallback, VirtualKeyBoard, title=title_text, text=old_text)

    def renameEntryCallback(self, answer):
        if answer:
            if self['config'].getCurrent() == self.entryName:
                self.timerentry_name.value = answer
                self['config'].invalidate(self.entryName)
            else:
                self.timerentry_description.value = answer
                self['config'].invalidate(self.entryDescription)

    def handleKeyFileCallback(self, answer):
        if self['config'].getCurrent() in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.handleKeyFileCallback(self, answer)
            self.newConfig()

    def keySelect(self):
        cur = self['config'].getCurrent()
        if cur == self.channelEntry:
            self.session.openWithCallback(self.finishedChannelSelection, ChannelSelection.SimpleChannelSelection, _('Select channel to record from'), currentBouquet=True)
        elif config.usage.setup_level.index >= 2 and cur == self.dirname:
            self.session.openWithCallback(self.pathSelected, MovieLocationBox, _('Select target folder'), self.timerentry_dirname.value, minFree=100)
        elif getPreferredTagEditor() and cur == self.tagsSet:
            self.session.openWithCallback(self.tagEditFinished, getPreferredTagEditor(), self.timerentry_tags)
        else:
            self.keyGo()

    def finishedChannelSelection(self, *args):
        if args:
            self.timerentry_service_ref = ServiceReference(args[0])
            self.timerentry_service.setCurrentText(self.timerentry_service_ref.getServiceName())
            self['config'].invalidate(self.channelEntry)

    def getTimestamp(self, date, mytime):
        d = localtime(date)
        dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
        return int(mktime(dt.timetuple()))

    def getBeginEnd(self):
        date = self.timerentry_date.value
        endtime = self.timerentry_endtime.value
        starttime = self.timerentry_starttime.value
        begin = self.getTimestamp(date, starttime)
        end = self.getTimestamp(date, endtime)
        if end < begin:
            end += 86400
        if self.timerentry_justplay.value == 'zap':
            if not self.timerentry_showendtime.value:
                end = begin + 1
        return (begin, end)

    def selectChannelSelector(self, *args):
        self.session.openWithCallback(self.finishedChannelSelectionCorrection, ChannelSelection.SimpleChannelSelection, _('Select channel to record from'))

    def finishedChannelSelectionCorrection(self, *args):
        if args:
            self.finishedChannelSelection(*args)
            self.keyGo()

    def keyGo(self, result = None):
        if not self.timerentry_service_ref.isRecordable():
            self.session.openWithCallback(self.selectChannelSelector, MessageBox, _("You didn't select a channel to record from."), MessageBox.TYPE_ERROR)
            return
        self.timer.name = self.timerentry_name.value
        self.timer.description = self.timerentry_description.value if self.timerentry_description_replaced != self.timerentry_description.value else self.timer.description
        self.timer.justplay = self.timerentry_justplay.value == 'zap'
        self.timer.always_zap = self.timerentry_justplay.value == 'zap+record'
        self.timer.rename_repeat = self.timerentry_renamerepeat.value
        if self.timerentry_justplay.value == 'zap':
            if not self.timerentry_showendtime.value:
                self.timerentry_endtime.value = self.timerentry_starttime.value
                self.timerentry_afterevent.value = 'nothing'
        if self.timerentry_endtime.value == self.timerentry_starttime.value and self.timerentry_afterevent.value != 'nothing':
            self.timerentry_afterevent.value = 'nothing'
            self.session.open(MessageBox, _('Difference between timer begin and end must be equal or greater than %d minutes.\nEnd Action was disabled !') % 1, MessageBox.TYPE_INFO, timeout=30)
        self.timer.resetRepeated()
        self.timer.afterEvent = {'nothing': AFTEREVENT.NONE,
         'deepstandby': AFTEREVENT.DEEPSTANDBY,
         'standby': AFTEREVENT.STANDBY,
         'auto': AFTEREVENT.AUTO}[self.timerentry_afterevent.value]
        if self.timer.justplay:
            self.timer.afterEvent = AFTEREVENT.NONE
        self.timer.descramble = {'normal': True,
         'descrambled+ecm': True,
         'scrambled+ecm': False}[self.timerentry_recordingtype.value]
        self.timer.record_ecm = {'normal': False,
         'descrambled+ecm': True,
         'scrambled+ecm': True}[self.timerentry_recordingtype.value]
        self.timer.service_ref = self.timerentry_service_ref
        self.timer.tags = self.timerentry_tags
        if self.timer.dirname or self.timerentry_dirname.value != defaultMoviePath():
            self.timer.dirname = self.timerentry_dirname.value
            config.movielist.last_timer_videodir.value = self.timer.dirname
            config.movielist.last_timer_videodir.save()
        if self.timerentry_type.value == 'once':
            self.timer.begin, self.timer.end = self.getBeginEnd()
        if self.timerentry_type.value == 'repeated':
            if self.timerentry_repeated.value == 'daily':
                for x in (0, 1, 2, 3, 4, 5, 6):
                    self.timer.setRepeated(x)

            if self.timerentry_repeated.value == 'weekly':
                self.timer.setRepeated(self.timerentry_weekday.index)
            if self.timerentry_repeated.value == 'weekdays':
                for x in (0, 1, 2, 3, 4):
                    self.timer.setRepeated(x)

            if self.timerentry_repeated.value == 'user':
                for x in (0, 1, 2, 3, 4, 5, 6):
                    if self.timerentry_day[x].value:
                        self.timer.setRepeated(x)

            self.timer.repeatedbegindate = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
            if self.timer.repeated:
                self.timer.begin = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
                self.timer.end = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_endtime.value)
            else:
                self.timer.begin = self.getTimestamp(time(), self.timerentry_starttime.value)
                self.timer.end = self.getTimestamp(time(), self.timerentry_endtime.value)
            if self.timer.end < self.timer.begin:
                self.timer.end += 86400
        if self.timer.eit is not None:
            event = eEPGCache.getInstance().lookupEventId(self.timer.service_ref.ref, self.timer.eit)
            if event:
                n = event.getNumOfLinkageServices()
                if n > 1:
                    tlist = []
                    ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
                    parent = self.timer.service_ref.ref
                    selection = 0
                    for x in range(n):
                        i = event.getLinkageService(parent, x)
                        if i.toString() == ref.toString():
                            selection = x
                        tlist.append((i.getName(), i))

                    self.session.openWithCallback(self.subserviceSelected, ChoiceBox, title=_('Please select a subservice to record...'), list=tlist, selection=selection)
                    return
                if n > 0:
                    parent = self.timer.service_ref.ref
                    self.timer.service_ref = ServiceReference(event.getLinkageService(parent, 0))
        self.saveTimer()
        self.close((True, self.timer))

    def changeTimerType(self):
        self.timerentry_justplay.selectNext()
        self.timerJustplayEntry = getConfigListEntry(_('Timer type'), self.timerentry_justplay)
        self['config'].invalidate(self.timerJustplayEntry)

    def incrementStart(self):
        self.timerentry_starttime.increment()
        self['config'].invalidate(self.entryStartTime)
        if self.timerentry_type.value == 'once' and self.timerentry_starttime.value == [0, 0]:
            self.timerentry_date.value += 86400
            self['config'].invalidate(self.entryDate)

    def decrementStart(self):
        self.timerentry_starttime.decrement()
        self['config'].invalidate(self.entryStartTime)
        if self.timerentry_type.value == 'once' and self.timerentry_starttime.value == [23, 59]:
            self.timerentry_date.value -= 86400
            self['config'].invalidate(self.entryDate)

    def incrementEnd(self):
        if self.entryEndTime is not None:
            self.timerentry_endtime.increment()
            self['config'].invalidate(self.entryEndTime)

    def decrementEnd(self):
        if self.entryEndTime is not None:
            self.timerentry_endtime.decrement()
            self['config'].invalidate(self.entryEndTime)

    def subserviceSelected(self, service):
        if service is not None:
            self.timer.service_ref = ServiceReference(service[1])
        self.saveTimer()
        self.close((True, self.timer))

    def saveTimer(self):
        self.session.nav.RecordTimer.saveTimer()

    def keyCancel(self):
        self.close((False,))

    def pathSelected(self, res):
        if res is not None:
            if config.movielist.videodirs.value != self.timerentry_dirname.choices:
                self.timerentry_dirname.setChoices(config.movielist.videodirs.value, default=res)
            self.timerentry_dirname.value = res
            self.newConfig()

    def tagEditFinished(self, ret):
        if ret is not None:
            self.timerentry_tags = ret
            self.timerentry_tagsset.setChoices([not ret and 'None' or ' '.join(ret)])
            self['config'].invalidate(self.tagsSet)
Exemple #10
0
class TimerEntry(Screen, ConfigListScreen, HelpableScreen):
	def __init__(self, session, timer):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
		self.setup_title = _("Timer entry")
		self.timer = timer

		self.entryDate = None
		self.entryService = None

		self["HelpWindow"] = Pixmap()
		self["HelpWindow"].hide()
		self["VKeyIcon"] = Pixmap()

		self["description"] = Label("")
		self["key_red"] = Label(_("Cancel"))
		self["key_green"] = Label(_("OK"))
		self["key_yellow"] = Label()
		self["key_blue"] = Label()

		self.createConfig()

		self["actions"] = HelpableNumberActionMap(self, ["SetupActions", "GlobalActions", "PiPSetupActions", "ColorActions"], {
			"ok": (self.keySelect, _("Save the timer and exit")),
			"save": (self.keyGo, "Save the timer and exit"),
			"cancel": (self.keyCancel, "Cancel creation of the timer and exit"),
			"volumeUp": (self.incrementStart, _("Increment start time")),
			"volumeDown": (self.decrementStart, _("Decrement start time")),
			"size+": (self.incrementEnd, _("Increment end time")),
			"size-": (self.decrementEnd, _("Decrement end time"))
		}, -2)

		self["VirtualKB"] = ActionMap(["VirtualKeyboardActions"], {
			"showVirtualKeyboard": self.KeyText,
		}, -2)
		self["VirtualKB"].setEnabled(False)

		self.onChangedEntry = []
		self.list = []
		ConfigListScreen.__init__(self, self.list, session=session)
		self.createSetup("config")
		self.onLayoutFinish.append(self.layoutFinished)
		if self.selectionChanged not in self["config"].onSelectionChanged:
			self["config"].onSelectionChanged.append(self.selectionChanged)
		self.selectionChanged()

	def createConfig(self):
		justplay = self.timer.justplay
		always_zap = self.timer.always_zap
		rename_repeat = self.timer.rename_repeat

		afterevent = {
			AFTEREVENT.NONE: "nothing",
			AFTEREVENT.DEEPSTANDBY: "deepstandby",
			AFTEREVENT.STANDBY: "standby",
			AFTEREVENT.AUTO: "auto"
		}[self.timer.afterEvent]

		if self.timer.record_ecm and self.timer.descramble:
			recordingtype = "descrambled+ecm"
		elif self.timer.record_ecm:
			recordingtype = "scrambled+ecm"
		elif self.timer.descramble:
			recordingtype = "normal"

		weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")

		# calculate default values
		day = []
		weekday = 0
		for x in (0, 1, 2, 3, 4, 5, 6):
			day.append(0)
		if self.timer.repeated:  # repeated
			repeat_type = "repeated"
			if self.timer.repeated == 31:  # Mon-Fri
				repeated = "weekdays"
			elif self.timer.repeated == 127:  # daily
				repeated = "daily"
			else:
				flags = self.timer.repeated
				repeated = "user"
				count = 0
				for x in (0, 1, 2, 3, 4, 5, 6):
					if flags == 1:  # weekly
						#  print "Set to weekday " + str(x)
						weekday = x
					if flags & 1 == 1:  # set user defined flags
						day[x] = 1
						count += 1
					else:
						day[x] = 0
					flags >>= 1
				if count == 1:
					repeated = "weekly"
		else:  # once
			repeat_type = "once"
			repeated = None
			weekday = int(strftime("%u", localtime(self.timer.begin))) - 1
			day[weekday] = 1

		self.timerentry_justplay = ConfigSelection(
			choices=[
				("zap", _("zap")),
				("record", _("record")),
				("zap+record", _("zap and record"))
			],
			default={
				0: "record",
				1: "zap",
				2: "zap+record"
			}[justplay + 2 * always_zap]
		)
		if SystemInfo["DeepstandbySupport"]:
			shutdownString = _("go to deep standby")
		else:
			shutdownString = _("shut down")
		self.timerentry_afterevent = ConfigSelection(choices=[
			("nothing", _("do nothing")),
			("standby", _("go to standby")),
			("deepstandby", shutdownString),
			("auto", _("auto"))
		], default=afterevent)
		self.timerentry_recordingtype = ConfigSelection(choices=[
			("normal", _("normal")),
			("descrambled+ecm", _("descramble and record ecm")),
			("scrambled+ecm", _("don't descramble, record ecm"))
		], default=recordingtype)
		self.timerentry_type = ConfigSelection(choices=[
			("once", _("once")),
			("repeated", _("repeated"))
		], default=repeat_type)
		self.timerentry_name = ConfigText(default=self.timer.name.replace('\xc2\x86', '').replace('\xc2\x87', '').encode("utf-8"), visible_width=50, fixed_size=False)
		self.timerentry_description = ConfigText(default=self.timer.description, visible_width=50, fixed_size=False)
		self.timerentry_tags = self.timer.tags[:]
		# if no tags found, make name of event default tag set.
		if not self.timerentry_tags:
				tagname = self.timer.name.strip()
				if tagname:
					tagname = tagname[0].upper() + tagname[1:].replace(" ", "_")
					self.timerentry_tags.append(tagname)

		self.timerentry_tagsset = ConfigSelection(choices=[not self.timerentry_tags and "None" or " ".join(self.timerentry_tags)])
		self.timerentry_repeated = ConfigSelection(choices=[
			("weekly", _("weekly")),
			("daily", _("daily")),
			("weekdays", _("Mon-Fri")),
			("user", _("user defined"))
		], default=repeated)
		self.timerentry_renamerepeat = ConfigYesNo(default=rename_repeat)

		self.timerentry_date = ConfigDateTime(default=self.timer.begin, formatstring=_("%d %B %Y"), increment=86400)
		self.timerentry_starttime = ConfigClock(default=self.timer.begin)
		self.timerentry_endtime = ConfigClock(default=self.timer.end)
		self.timerentry_showendtime = ConfigSelection(default=((self.timer.end - self.timer.begin) > 4), choices=[(True, _("yes")), (False, _("no"))])

		default = self.timer.dirname or defaultMoviePath()
		tmp = config.movielist.videodirs.value
		if default not in tmp:
			tmp.append(default)
		self.timerentry_dirname = ConfigSelection(default=default, choices=tmp)

		self.timerentry_repeatedbegindate = ConfigDateTime(default=self.timer.repeatedbegindate, formatstring=_("%d.%B %Y"), increment=86400)

		self.timerentry_weekday = ConfigSelection(default=weekday_table[weekday], choices=[
			("mon", _("Monday")),
			("tue", _("Tuesday")),
			("wed", _("Wednesday")),
			("thu", _("Thursday")),
			("fri", _("Friday")),
			("sat", _("Saturday")),
			("sun", _("Sunday"))
		])

		self.timerentry_day = ConfigSubList()
		for x in (0, 1, 2, 3, 4, 5, 6):
			self.timerentry_day.append(ConfigYesNo(default=day[x]))

		# FIXME some service-chooser needed here
		servicename = "N/A"
		try:  # no current service available?
			servicename = str(self.timer.service_ref.getServiceName())
		except:
			pass
		self.timerentry_service_ref = self.timer.service_ref
		self.timerentry_service = ConfigSelection([servicename])

	def createSetup(self, widget):
		self.list = []
		self.entryName = getConfigListEntry(_("Name"), self.timerentry_name, _("The name the recording will get."))
		self.list.append(self.entryName)
		self.entryDescription = getConfigListEntry(_("Description"), self.timerentry_description, _("The description of the recording."))
		self.list.append(self.entryDescription)
		self.timerJustplayEntry = getConfigListEntry(_("Timer type"), self.timerentry_justplay, _("Choose between record and ZAP."))
		self.list.append(self.timerJustplayEntry)
		self.timerTypeEntry = getConfigListEntry(_("Repeat type"), self.timerentry_type, _("A repeating timer or just once?"))
		self.list.append(self.timerTypeEntry)

		if self.timerentry_type.value == "once":
			self.frequencyEntry = None
		else:  # repeated
			self.frequencyEntry = getConfigListEntry(_("Repeats"), self.timerentry_repeated, _("The type of repetition required: daily, weekly on a specified day, on weekdays (Mon-Fri), or regularly on specified days."))
			self.list.append(self.frequencyEntry)
			self.repeatedbegindateEntry = getConfigListEntry(_("Starting on"), self.timerentry_repeatedbegindate, _("The timer becomes active (but doesn't necessarily run) on this date."))
			self.list.append(self.repeatedbegindateEntry)
			if self.timerentry_repeated.value == "daily":
				pass
			if self.timerentry_repeated.value == "weekdays":
				pass
			if self.timerentry_repeated.value == "weekly":
				self.list.append(getConfigListEntry(_("Weekday"), self.timerentry_weekday, _("The day of the week the timer runs.")))

			if self.timerentry_repeated.value == "user":
				self.list.append(getConfigListEntry(_("Monday"), self.timerentry_day[0], _("Enable/disable the timer on Mondays.")))
				self.list.append(getConfigListEntry(_("Tuesday"), self.timerentry_day[1], _("Enable/disable the timer on Tuesdays.")))
				self.list.append(getConfigListEntry(_("Wednesday"), self.timerentry_day[2], _("Enable/disable the timer on Wednesdays.")))
				self.list.append(getConfigListEntry(_("Thursday"), self.timerentry_day[3], _("Enable/disable the timer on Thursdays.")))
				self.list.append(getConfigListEntry(_("Friday"), self.timerentry_day[4], _("Enable/disable the timer on Fridays.")))
				self.list.append(getConfigListEntry(_("Saturday"), self.timerentry_day[5], _("Enable/disable the timer on Saturdays.")))
				self.list.append(getConfigListEntry(_("Sunday"), self.timerentry_day[6], _("Enable/disable the timer on Sundays.")))
			if self.timerentry_justplay.value != "zap":
				self.list.append(getConfigListEntry(_("Generate name and description for new events"), self.timerentry_renamerepeat, _("Generate a new name and description from the EPG for each run of the timer.")))

		self.entryDate = getConfigListEntry(_("Date"), self.timerentry_date, _("The date the timer starts."))
		if self.timerentry_type.value == "once":
			self.list.append(self.entryDate)

		self.entryStartTime = getConfigListEntry(_("Start time"), self.timerentry_starttime, _("The time the timer starts."))
		self.list.append(self.entryStartTime)

		self.entryShowEndTime = getConfigListEntry(_("Set end time"), self.timerentry_showendtime, _("Set the time the ZAP timer completes and performs any \"After event\" action."))
		if self.timerentry_justplay.value == "zap":
			self.list.append(self.entryShowEndTime)
		self.entryEndTime = getConfigListEntry(_("End time"), self.timerentry_endtime, _("The time the timer completes and the \"After event\" action is taken. If the end time is earlier than the start time of the timer, the completion action takes place at that time on the following day."))
		if self.timerentry_justplay.value != "zap" or self.timerentry_showendtime.value:
			self.list.append(self.entryEndTime)

		self.channelEntry = getConfigListEntry(_("Channel"), self.timerentry_service, _("The channel for this timer."))
		self.list.append(self.channelEntry)

		self.dirname = getConfigListEntry(_("Location"), self.timerentry_dirname, _("Where the recording will be saved."))
		self.tagsSet = getConfigListEntry(_("Tags"), self.timerentry_tagsset, _("Choose a tag to make searching for the recording easier."))
		if self.timerentry_justplay.value != "zap":
			if config.usage.setup_level.index >= 2:  # expert+
				self.list.append(self.dirname)
			if getPreferredTagEditor():
				self.list.append(self.tagsSet)
			self.list.append(getConfigListEntry(_("After event"), self.timerentry_afterevent, _("Action taken on the completion of the timer. \"Auto\" lets your %s %s return to the state it was in when the timer started. \"Do nothing\", \"Go to standby\" and \"Go to deep standby\" do exactly that.") % (getMachineBrand(), getMachineName())))
			self.list.append(getConfigListEntry(_("Recording type"), self.timerentry_recordingtype, _("\"Descramble & record ECM\" allows the recording to be descrambled later if descrambling while recording failed. \"Don't descramble, record ECM\" saves a scrambled recording that can be descrambled on playback. \"Normal\" means descramble while recording and don't record ECM.")))

		self[widget].list = self.list
		self[widget].l.setList(self.list)

	def selectionChanged(self):
		if self["config"].getCurrent():
			if len(self["config"].getCurrent()) > 2 and self["config"].getCurrent()[2]:
				self["description"].setText(self["config"].getCurrent()[2])

	def layoutFinished(self):
		self.setTitle(_(self.setup_title))

	def createSummary(self):
		return SetupSummary

	# for summary:
	def changedEntry(self):
		for x in self.onChangedEntry:
			x()

	def getCurrentEntry(self):
		return self["config"].getCurrent() and self["config"].getCurrent()[0] or ""

	def getCurrentValue(self):
		return self["config"].getCurrent() and str(self["config"].getCurrent()[1].getText()) or ""

	def newConfig(self):
		if self["config"].getCurrent() in (self.timerTypeEntry, self.timerJustplayEntry, self.frequencyEntry, self.entryShowEndTime):
			self.createSetup("config")

	def showHelp(self):
		self.hideTextHelp()
		HelpableScreen.showHelp(self)

	def hideTextHelp(self):
		currConfig = self["config"].getCurrent()
		if isinstance(currConfig[1], ConfigText) and currConfig[1].help_window.instance is not None:
			currConfig[1].help_window.hide()

	def showTextHelp(self):
		currConfig = self["config"].getCurrent()
		if isinstance(currConfig[1], ConfigText) and currConfig[1].help_window.instance is not None:
			currConfig[1].help_window.show()

	def KeyText(self):
		self.hideTextHelp()
		currConfig = self["config"].getCurrent()
		if currConfig[0] in (_('Name'), _("Description")):
			self.session.openWithCallback(self.renameEntryCallback, VirtualKeyBoard, title=currConfig[2], text=currConfig[1].value)

	def keyLeft(self):
		cur = self["config"].getCurrent()
		if cur in (self.channelEntry, self.tagsSet):
			self.keySelect()
		elif cur in (self.entryName, self.entryDescription):
			self.renameEntry()
		else:
			ConfigListScreen.keyLeft(self)
			self.newConfig()

	def keyRight(self):
		cur = self["config"].getCurrent()
		if cur in (self.channelEntry, self.tagsSet):
			self.keySelect()
		elif cur in (self.entryName, self.entryDescription):
			self.renameEntry()
		else:
			ConfigListScreen.keyRight(self)
			self.newConfig()

	def renameEntry(self):
		cur = self["config"].getCurrent()
		if cur == self.entryName:
			title_text = _("Please enter new name:")
			old_text = self.timerentry_name.value
		else:
			title_text = _("Please enter new description:")
			old_text = self.timerentry_description.value
		self.hideTextHelp()
		self.session.openWithCallback(self.renameEntryCallback, VirtualKeyBoard, title=title_text, text=old_text)

	def renameEntryCallback(self, answer):
		self.showTextHelp()
		if answer:
			if self["config"].getCurrent() == self.entryName:
				self.timerentry_name.value = answer
				self["config"].invalidate(self.entryName)
			else:
				self.timerentry_description.value = answer
				self["config"].invalidate(self.entryDescription)

	def handleKeyFileCallback(self, answer):
		if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
			self.keySelect()
		else:
			ConfigListScreen.handleKeyFileCallback(self, answer)
			self.newConfig()

	def keySelect(self):
		cur = self["config"].getCurrent()
		if cur == self.channelEntry:
			self.session.openWithCallback(
				self.finishedChannelSelection,
				ChannelSelection.SimpleChannelSelection,
				_("Select channel to record from"),
				currentBouquet=True
			)
		elif config.usage.setup_level.index >= 2 and cur == self.dirname:
			self.session.openWithCallback(
				self.pathSelected,
				MovieLocationBox,
				_("Select target folder"),
				self.timerentry_dirname.value,
				minFree=100  # We require at least 100MB free space
			)
		elif getPreferredTagEditor() and cur == self.tagsSet:
			self.session.openWithCallback(
				self.tagEditFinished,
				getPreferredTagEditor(),
				self.timerentry_tags
			)
		else:
			self.keyGo()

	def finishedChannelSelection(self, *args):
		if args:
			self.timerentry_service_ref = ServiceReference(args[0])
			self.timerentry_service.setCurrentText(self.timerentry_service_ref.getServiceName())
			self["config"].invalidate(self.channelEntry)

	def getTimestamp(self, date, mytime):
		d = localtime(date)
		dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
		return int(mktime(dt.timetuple()))

	def getBeginEnd(self):
		date = self.timerentry_date.value
		endtime = self.timerentry_endtime.value
		starttime = self.timerentry_starttime.value

		begin = self.getTimestamp(date, starttime)
		end = self.getTimestamp(date, endtime)

		# if the endtime is less than the starttime, add 1 day.
		if end < begin:
			end += 86400

		# if the timer type is a Zap and no end is set, set duration to 1 second so time is shown in EPG's.
		if self.timerentry_justplay.value == "zap":
			if not self.timerentry_showendtime.value:
				end = begin + (config.recording.margin_before.value * 60) + 1

		return begin, end

	def selectChannelSelector(self, *args):
		self.session.openWithCallback(
			self.finishedChannelSelectionCorrection,
			ChannelSelection.SimpleChannelSelection,
			_("Select channel to record from")
		)

	def finishedChannelSelectionCorrection(self, *args):
		if args:
			self.finishedChannelSelection(*args)
			self.keyGo()

	def keyGo(self, result=None):
		if not self.timerentry_service_ref.isRecordable():
			self.session.openWithCallback(self.selectChannelSelector, MessageBox, _("You didn't select a channel to record from."), MessageBox.TYPE_ERROR)
			return
		self.timer.name = self.timerentry_name.value
		self.timer.description = self.timerentry_description.value
		self.timer.justplay = self.timerentry_justplay.value == "zap"
		self.timer.always_zap = self.timerentry_justplay.value == "zap+record"
		self.timer.rename_repeat = self.timerentry_renamerepeat.value
		if self.timerentry_justplay.value == "zap":
			if not self.timerentry_showendtime.value:
				self.timerentry_endtime.value = self.timerentry_starttime.value
		self.timer.resetRepeated()
		self.timer.afterEvent = {
			"nothing": AFTEREVENT.NONE,
			"deepstandby": AFTEREVENT.DEEPSTANDBY,
			"standby": AFTEREVENT.STANDBY,
			"auto": AFTEREVENT.AUTO
		}[self.timerentry_afterevent.value]
		self.timer.descramble = {
			"normal": True,
			"descrambled+ecm": True,
			"scrambled+ecm": False,
		}[self.timerentry_recordingtype.value]
		self.timer.record_ecm = {
			"normal": False,
			"descrambled+ecm": True,
			"scrambled+ecm": True,
		}[self.timerentry_recordingtype.value]
		self.timer.service_ref = self.timerentry_service_ref
		self.timer.tags = self.timerentry_tags

		if self.timer.dirname or self.timerentry_dirname.value != defaultMoviePath():
			self.timer.dirname = self.timerentry_dirname.value
			config.movielist.last_timer_videodir.value = self.timer.dirname
			config.movielist.last_timer_videodir.save()

		if self.timerentry_type.value == "once":
			self.timer.begin, self.timer.end = self.getBeginEnd()
		if self.timerentry_type.value == "repeated":
			if self.timerentry_repeated.value == "daily":
				for x in (0, 1, 2, 3, 4, 5, 6):
					self.timer.setRepeated(x)

			if self.timerentry_repeated.value == "weekly":
				self.timer.setRepeated(self.timerentry_weekday.index)

			if self.timerentry_repeated.value == "weekdays":
				for x in (0, 1, 2, 3, 4):
					self.timer.setRepeated(x)

			if self.timerentry_repeated.value == "user":
				for x in (0, 1, 2, 3, 4, 5, 6):
					if self.timerentry_day[x].value:
						self.timer.setRepeated(x)

			self.timer.repeatedbegindate = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
			if self.timer.repeated:
				self.timer.begin = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
				self.timer.end = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_endtime.value)
			else:
				self.timer.begin = self.getTimestamp(time.time(), self.timerentry_starttime.value)
				self.timer.end = self.getTimestamp(time.time(), self.timerentry_endtime.value)

			# when a timer end is set before the start, add 1 day
			if self.timer.end < self.timer.begin:
				self.timer.end += 86400

		if self.timer.eit is not None:
			event = eEPGCache.getInstance().lookupEventId(self.timer.service_ref.ref, self.timer.eit)
			if event:
				n = event.getNumOfLinkageServices()
				if n > 1:
					tlist = []
					ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
					parent = self.timer.service_ref.ref
					selection = 0
					for x in range(n):
						i = event.getLinkageService(parent, x)
						if i.toString() == ref.toString():
							selection = x
						tlist.append((i.getName(), i))
					self.session.openWithCallback(self.subserviceSelected, ChoiceBox, title=_("Please select a subservice to record..."), list=tlist, selection=selection)
					return
				elif n > 0:
					parent = self.timer.service_ref.ref
					self.timer.service_ref = ServiceReference(event.getLinkageService(parent, 0))
		self.saveTimer()
		self.close((True, self.timer))

	def changeTimerType(self):
		self.timerentry_justplay.selectNext()
		self["config"].invalidate(self.timerJustplayEntry)

	def incrementStart(self):
		self.timerentry_starttime.increment()
		self["config"].invalidate(self.entryStartTime)
		if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [0, 0]:
			self.timerentry_date.value += 86400
			self["config"].invalidate(self.entryDate)

	def decrementStart(self):
		self.timerentry_starttime.decrement()
		self["config"].invalidate(self.entryStartTime)
		if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [23, 59]:
			self.timerentry_date.value -= 86400
			self["config"].invalidate(self.entryDate)

	def incrementEnd(self):
		if self.entryEndTime is not None:
			self.timerentry_endtime.increment()
			self["config"].invalidate(self.entryEndTime)

	def decrementEnd(self):
		if self.entryEndTime is not None:
			self.timerentry_endtime.decrement()
			self["config"].invalidate(self.entryEndTime)

	def subserviceSelected(self, service):
		if service is not None:
			self.timer.service_ref = ServiceReference(service[1])
		self.saveTimer()
		self.close((True, self.timer))

	def saveTimer(self):
		self.session.nav.RecordTimer.saveTimer()

	def keyCancel(self):
		self.close((False,))

	def pathSelected(self, res):
		if res is not None:
			if config.movielist.videodirs.value != self.timerentry_dirname.choices:
				self.timerentry_dirname.setChoices(config.movielist.videodirs.value, default=res)
			self.timerentry_dirname.value = res

	def tagEditFinished(self, ret):
		if ret is not None:
			self.timerentry_tags = ret
			self.timerentry_tagsset.setChoices([not ret and "None" or " ".join(ret)])
			self["config"].invalidate(self.tagsSet)
Exemple #11
0
class TimerEntry(Screen, ConfigListScreen):
    def __init__(self, session, timer):
        Screen.__init__(self, session)
        self.timer = timer

        self.entryDate = None
        self.entryService = None

        self["oktext"] = Label(_("OK"))
        self["canceltext"] = Label(_("Cancel"))
        self["ok"] = Pixmap()
        self["cancel"] = Pixmap()

        self.createConfig()

        self["actions"] = NumberActionMap(
            ["SetupActions", "GlobalActions", "PiPSetupActions"], {
                "ok": self.keySelect,
                "save": self.keyGo,
                "cancel": self.keyCancel,
                "volumeUp": self.incrementStart,
                "volumeDown": self.decrementStart,
                "size+": self.incrementEnd,
                "size-": self.decrementEnd
            }, -2)

        self.list = []
        ConfigListScreen.__init__(self, self.list, session=session)
        self.createSetup("config")

    def createConfig(self):
        justplay = self.timer.justplay

        afterevent = {
            AFTEREVENT.NONE: "nothing",
            AFTEREVENT.DEEPSTANDBY: "deepstandby",
            AFTEREVENT.STANDBY: "standby",
            AFTEREVENT.AUTO: "auto"
        }[self.timer.afterEvent]

        weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")

        # calculate default values
        day = []
        weekday = 0
        for x in (0, 1, 2, 3, 4, 5, 6):
            day.append(0)
        if self.timer.repeated:  # repeated
            type = "repeated"
            if (self.timer.repeated == 31):  # Mon-Fri
                repeated = "weekdays"
            elif (self.timer.repeated == 127):  # daily
                repeated = "daily"
            else:
                flags = self.timer.repeated
                repeated = "user"
                count = 0
                for x in (0, 1, 2, 3, 4, 5, 6):
                    if flags == 1:  # weekly
                        print("Set to weekday " + str(x))
                        weekday = x
                    if flags & 1 == 1:  # set user defined flags
                        day[x] = 1
                        count += 1
                    else:
                        day[x] = 0
                    flags = flags >> 1
                if count == 1:
                    repeated = "weekly"
        else:  # once
            type = "once"
            repeated = None
            weekday = (int(strftime("%w", localtime(self.timer.begin))) -
                       1) % 7
            day[weekday] = 1

        if not config.misc.recording_allowed.value:
            self.timerentry_justplay = ConfigSelection(choices=[("zap",
                                                                 _("zap"))],
                                                       default="zap")
        else:
            tmp_dir = self.timer.dirname or defaultMoviePath()
            if not harddiskmanager.inside_mountpoint(tmp_dir):
                justplay = 1
            justplay_default = {0: "record", 1: "zap"}[justplay]
            self.timerentry_justplay = ConfigSelection(
                choices=[("zap", _("zap")), ("record", _("record"))],
                default=justplay_default)

        if SystemInfo["DeepstandbySupport"]:
            shutdownString = _("go to standby")
        else:
            shutdownString = _("shut down")
        self.timerentry_afterevent = ConfigSelection(choices=[
            ("nothing", _("do nothing")), ("standby", _("go to idle mode")),
            ("deepstandby", shutdownString), ("auto", _("auto"))
        ],
                                                     default=afterevent)
        self.timerentry_type = ConfigSelection(choices=[("once", _("once")),
                                                        ("repeated",
                                                         _("repeated"))],
                                               default=type)
        self.timerentry_name = ConfigText(default=self.timer.name,
                                          visible_width=50,
                                          fixed_size=False)
        self.timerentry_description = ConfigText(
            default=self.timer.description, visible_width=50, fixed_size=False)
        self.timerentry_tags = self.timer.tags[:]
        self.timerentry_tagsset = ConfigSelection(choices=[
            not self.timerentry_tags and "None"
            or " ".join(self.timerentry_tags)
        ])

        self.timerentry_repeated = ConfigSelection(
            default=repeated,
            choices=[("daily", _("daily")), ("weekly", _("weekly")),
                     ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])

        self.timerentry_date = ConfigDateTime(default=self.timer.begin,
                                              formatstring=_("%d.%B %Y"),
                                              increment=86400)
        self.timerentry_starttime = ConfigClock(default=self.timer.begin)
        self.timerentry_endtime = ConfigClock(default=self.timer.end)
        self.timerentry_showendtime = ConfigSelection(
            default=((self.timer.end - self.timer.begin) > 4),
            choices=[(True, _("yes")), (False, _("no"))])

        default = self.timer.dirname or defaultMoviePath()
        tmp = config.movielist.videodirs.value
        if default not in tmp:
            tmp.append(default)
        self.timerentry_dirname = ConfigSelection(default=default, choices=tmp)

        self.timerentry_repeatedbegindate = ConfigDateTime(
            default=self.timer.repeatedbegindate,
            formatstring=_("%d.%B %Y"),
            increment=86400)

        self.timerentry_weekday = ConfigSelection(
            default=weekday_table[weekday],
            choices=[("mon", _("Monday")), ("tue", _("Tuesday")),
                     ("wed", _("Wednesday")), ("thu", _("Thursday")),
                     ("fri", _("Friday")), ("sat", _("Saturday")),
                     ("sun", _("Sunday"))])

        self.timerentry_day = ConfigSubList()
        for x in (0, 1, 2, 3, 4, 5, 6):
            self.timerentry_day.append(ConfigYesNo(default=day[x]))

        try:  # no current service available?
            servicename = str(self.timer.service_ref.getServiceName())
        except:
            pass
        servicename = servicename or "N/A"
        self.timerentry_service_ref = self.timer.service_ref
        self.timerentry_service = ConfigSelection([servicename])

        self.timerentry_plugins = {}
        if config.usage.setup_level.index >= 2:
            from Plugins.Plugin import PluginDescriptor
            from Components.PluginComponent import plugins
            missing = list(self.timer.plugins.keys())
            for p in plugins.getPlugins(PluginDescriptor.WHERE_TIMEREDIT):
                if "setupFnc" in p.__call__:
                    setupFnc = p.__call__["setupFnc"]
                    if setupFnc is not None:
                        if "configListEntry" in p.__call__:
                            entry = p.__call__["configListEntry"]()
                            pdata = None
                            if p.name in self.timer.plugins:
                                pval = self.timer.plugins[p.name][0]
                                pdata = self.timer.plugins[p.name][1]
                                try:
                                    if isinstance(entry[1].value, bool):
                                        entry[1].value = (pval == "True")
                                    elif isinstance(entry[1].value, str):
                                        entry[1].value = str(pval)
                                    elif isinstance(entry[1].value, int):
                                        entry[1].value = int(pval)
                                except ValueError:
                                    print("could not get config_val", pval,
                                          type(pval),
                                          "for WHERE_TIMEREDIT plugin:",
                                          p.name)
                                    break

                            self.timerentry_plugins[entry] = [
                                p.name, setupFnc, pdata
                            ]  # [plugin name, function call for plugin setup, plugin private data]
                            if p.name in missing:
                                missing.remove(p.name)
            if len(missing):
                print("could not setup WHERE_TIMEREDIT plugin(s):", missing)

    def createSetup(self, widget):
        self.list = []
        self.list.append(getConfigListEntry(_("Name"), self.timerentry_name))
        self.list.append(
            getConfigListEntry(_("Description"), self.timerentry_description))
        self.timerJustplayEntry = getConfigListEntry(_("Timer Type"),
                                                     self.timerentry_justplay)
        self.list.append(self.timerJustplayEntry)
        self.timerTypeEntry = getConfigListEntry(_("Repeat Type"),
                                                 self.timerentry_type)
        self.list.append(self.timerTypeEntry)

        if self.timerentry_type.value == "once":
            self.frequencyEntry = None
        else:  # repeated
            self.frequencyEntry = getConfigListEntry(_("Repeats"),
                                                     self.timerentry_repeated)
            self.list.append(self.frequencyEntry)
            self.repeatedbegindateEntry = getConfigListEntry(
                _("Starting on"), self.timerentry_repeatedbegindate)
            self.list.append(self.repeatedbegindateEntry)
            if self.timerentry_repeated.value == "daily":
                pass
            if self.timerentry_repeated.value == "weekdays":
                pass
            if self.timerentry_repeated.value == "weekly":
                self.list.append(
                    getConfigListEntry(_("Weekday"), self.timerentry_weekday))

            if self.timerentry_repeated.value == "user":
                self.list.append(
                    getConfigListEntry(_("Monday"), self.timerentry_day[0]))
                self.list.append(
                    getConfigListEntry(_("Tuesday"), self.timerentry_day[1]))
                self.list.append(
                    getConfigListEntry(_("Wednesday"), self.timerentry_day[2]))
                self.list.append(
                    getConfigListEntry(_("Thursday"), self.timerentry_day[3]))
                self.list.append(
                    getConfigListEntry(_("Friday"), self.timerentry_day[4]))
                self.list.append(
                    getConfigListEntry(_("Saturday"), self.timerentry_day[5]))
                self.list.append(
                    getConfigListEntry(_("Sunday"), self.timerentry_day[6]))

        self.entryDate = getConfigListEntry(_("Date"), self.timerentry_date)
        if self.timerentry_type.value == "once":
            self.list.append(self.entryDate)

        self.entryStartTime = getConfigListEntry(_("StartTime"),
                                                 self.timerentry_starttime)
        self.list.append(self.entryStartTime)

        self.entryShowEndTime = getConfigListEntry(_("Set End Time"),
                                                   self.timerentry_showendtime)
        if self.timerentry_justplay.value == "zap":
            self.list.append(self.entryShowEndTime)
        self.entryEndTime = getConfigListEntry(_("EndTime"),
                                               self.timerentry_endtime)
        if self.timerentry_justplay.value != "zap" or self.timerentry_showendtime.value:
            self.list.append(self.entryEndTime)

        self.channelEntry = getConfigListEntry(_("Channel"),
                                               self.timerentry_service)
        self.list.append(self.channelEntry)

        self.dirname = getConfigListEntry(_("Location"),
                                          self.timerentry_dirname)
        self.tagsSet = getConfigListEntry(_("Tags"), self.timerentry_tagsset)
        if self.timerentry_justplay.value != "zap":
            if config.usage.setup_level.index >= 2:  # expert+
                self.list.append(self.dirname)
            if getPreferredTagEditor():
                self.list.append(self.tagsSet)
        self.list.append(
            getConfigListEntry(_("After event"), self.timerentry_afterevent))

        for entry in self.timerentry_plugins.keys():
            self.list.append(entry)

        self[widget].list = self.list
        self[widget].l.setList(self.list)

    def newConfig(self):
        print("newConfig", self["config"].getCurrent())
        if self["config"].getCurrent() in (self.timerTypeEntry,
                                           self.timerJustplayEntry,
                                           self.frequencyEntry,
                                           self.entryShowEndTime):
            self.createSetup("config")

    def keyLeft(self):
        if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.keyLeft(self)
            self.newConfig()

    def keyRight(self):
        if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.keyRight(self)
            self.newConfig()

    def keySelect(self):
        cur = self["config"].getCurrent()
        if cur == self.channelEntry:
            self.session.openWithCallback(
                self.finishedChannelSelection,
                Screens.ChannelSelection.SimpleChannelSelection,
                _("Select channel to record from"))
        elif config.usage.setup_level.index >= 2 and cur == self.dirname:
            self.session.openWithCallback(
                self.pathSelected,
                MovieLocationBox,
                _("Choose target folder"),
                self.timerentry_dirname.value,
                minFree=100  # We require at least 100MB free space
            )
        elif getPreferredTagEditor() and cur == self.tagsSet:
            self.session.openWithCallback(self.tagEditFinished,
                                          getPreferredTagEditor(),
                                          self.timerentry_tags)
        elif config.usage.setup_level.index >= 2 and cur in self.timerentry_plugins:
            self.getConfigListValues()
            setupFnc = self.timerentry_plugins[cur][1]
            configentry = cur[1]
            private_data = self.timerentry_plugins[cur][2]
            print("calling setupFnc of WHERE_TIMEREDIT plugin:", cur[0],
                  setupFnc, configentry, private_data, self.timer.name)
            self.session.openWithCallback(
                boundFunction(self.pluginFinished, cur), setupFnc, configentry,
                private_data, self.timer)
        else:
            self.keyGo()

    def pluginFinished(self, entry, ret=""):
        print("[pluginFinished]", entry, ret)
        self.timerentry_plugins[entry][2] = ret
        self["config"].invalidate(entry)
        print("plugin private data", self.timerentry_plugins[entry][2])

    def finishedChannelSelection(self, *args):
        if args:
            self.timerentry_service_ref = ServiceReference(args[0])
            self.timerentry_service.setCurrentText(
                self.timerentry_service_ref.getServiceName())
            self["config"].invalidate(self.channelEntry)

    def getTimestamp(self, date, mytime):
        d = localtime(date)
        dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
        return int(mktime(dt.timetuple()))

    def getBeginEnd(self):
        date = self.timerentry_date.value
        endtime = self.timerentry_endtime.value
        starttime = self.timerentry_starttime.value

        begin = self.getTimestamp(date, starttime)
        end = self.getTimestamp(date, endtime)

        # if the endtime is less than the starttime, add 1 day.
        if end < begin:
            end += 86400
        return begin, end

    def selectChannelSelector(self, *args):
        self.session.openWithCallback(
            self.finishedChannelSelectionCorrection,
            Screens.ChannelSelection.SimpleChannelSelection,
            _("Select channel to record from"))

    def finishedChannelSelectionCorrection(self, *args):
        if args:
            self.finishedChannelSelection(*args)
            self.keyGo()

    def getConfigListValues(self):
        if not self.timerentry_service_ref.isRecordable():
            self.session.openWithCallback(
                self.selectChannelSelector, MessageBox,
                _("You didn't select a channel to record from."),
                MessageBox.TYPE_ERROR)
            return
        if self.timerentry_justplay.value == 'record':
            if not harddiskmanager.inside_mountpoint(
                    self.timerentry_dirname.value):
                if harddiskmanager.HDDCount(
                ) and not harddiskmanager.HDDEnabledCount():
                    self.session.open(MessageBox, _("Unconfigured storage devices found!") + "\n" \
                     + _("Please make sure to set up your storage devices with the improved storage management in menu -> setup -> system -> storage devices."), MessageBox.TYPE_ERROR)
                    return
                elif harddiskmanager.HDDEnabledCount(
                ) and defaultStorageDevice() == "<undefined>":
                    self.session.open(MessageBox, _("No default storage device found!") + "\n" \
                     + _("Please make sure to set up your default storage device in menu -> setup -> system -> recording paths."), MessageBox.TYPE_ERROR)
                    return
                elif harddiskmanager.HDDEnabledCount(
                ) and defaultStorageDevice() != "<undefined>":
                    part = harddiskmanager.getDefaultStorageDevicebyUUID(
                        defaultStorageDevice())
                    if part is None:
                        self.session.open(MessageBox, _("Default storage device is not available!") + "\n" \
                         + _("Please verify if your default storage device is attached or set up your default storage device in menu -> setup -> system -> recording paths."), MessageBox.TYPE_ERROR)
                        return
                else:
                    self.session.open(
                        MessageBox,
                        _("Recording destination for this timer does not exists."
                          ), MessageBox.TYPE_ERROR)
                    return

        self.timer.name = self.timerentry_name.value
        self.timer.description = self.timerentry_description.value
        self.timer.justplay = self.timerentry_justplay.value == "zap"
        if self.timerentry_justplay.value == "zap":
            if not self.timerentry_showendtime.value:
                self.timerentry_endtime.value = self.timerentry_starttime.value

        self.timer.resetRepeated()
        self.timer.afterEvent = {
            "nothing": AFTEREVENT.NONE,
            "deepstandby": AFTEREVENT.DEEPSTANDBY,
            "standby": AFTEREVENT.STANDBY,
            "auto": AFTEREVENT.AUTO
        }[self.timerentry_afterevent.value]
        self.timer.service_ref = self.timerentry_service_ref
        self.timer.tags = self.timerentry_tags

        if self.timer.dirname or self.timerentry_dirname.value != defaultMoviePath(
        ):
            self.timer.dirname = self.timerentry_dirname.value
            config.movielist.last_timer_videodir.value = self.timer.dirname
            config.movielist.last_timer_videodir.save()

        if self.timerentry_type.value == "once":
            self.timer.begin, self.timer.end = self.getBeginEnd()
        if self.timerentry_type.value == "repeated":
            if self.timerentry_repeated.value == "daily":
                for x in (0, 1, 2, 3, 4, 5, 6):
                    self.timer.setRepeated(x)

            if self.timerentry_repeated.value == "weekly":
                self.timer.setRepeated(self.timerentry_weekday.index)

            if self.timerentry_repeated.value == "weekdays":
                for x in (0, 1, 2, 3, 4):
                    self.timer.setRepeated(x)

            if self.timerentry_repeated.value == "user":
                for x in (0, 1, 2, 3, 4, 5, 6):
                    if self.timerentry_day[x].value:
                        self.timer.setRepeated(x)

            self.timer.repeatedbegindate = self.getTimestamp(
                self.timerentry_repeatedbegindate.value,
                self.timerentry_starttime.value)
            if self.timer.repeated:
                self.timer.begin = self.getTimestamp(
                    self.timerentry_repeatedbegindate.value,
                    self.timerentry_starttime.value)
                self.timer.end = self.getTimestamp(
                    self.timerentry_repeatedbegindate.value,
                    self.timerentry_endtime.value)
            else:
                self.timer.begin = self.getTimestamp(
                    time.time(), self.timerentry_starttime.value)
                self.timer.end = self.getTimestamp(
                    time.time(), self.timerentry_endtime.value)

            # when a timer end is set before the start, add 1 day
            if self.timer.end < self.timer.begin:
                self.timer.end += 86400

    def keyGo(self, result=None):
        self.getConfigListValues()
        if self.timer.eit is not None:
            event = eEPGCache.getInstance().lookupEventId(
                self.timer.service_ref.ref, self.timer.eit)
            if event:
                n = event.getNumOfLinkageServices()
                if n > 1:
                    tlist = []
                    ref = self.session.nav.getCurrentlyPlayingServiceReference(
                    )
                    parent = self.timer.service_ref.ref
                    selection = 0
                    for x in range(n):
                        i = event.getLinkageService(parent, x)
                        if i.toString() == ref.toString():
                            selection = x
                        tlist.append((i.getName(), i))
                    self.session.openWithCallback(
                        self.subserviceSelected,
                        ChoiceBox,
                        title=_("Please select a subservice to record..."),
                        list=tlist,
                        selection=selection)
                    return
                elif n > 0:
                    parent = self.timer.service_ref.ref
                    self.timer.service_ref = ServiceReference(
                        event.getLinkageService(parent, 0))

        if self.timerentry_plugins:
            self.timer.plugins = {}
            for key, val in six.iteritems(self.timerentry_plugins):
                self.timer.plugins[val[0]] = (str(key[1].value), str(val[2]))
                print("timerentry self.timer.plugins", self.timer.plugins)

        self.saveTimer()
        self.close((True, self.timer))

    def incrementStart(self):
        self.timerentry_starttime.increment()
        self["config"].invalidate(self.entryStartTime)

    def decrementStart(self):
        self.timerentry_starttime.decrement()
        self["config"].invalidate(self.entryStartTime)

    def incrementEnd(self):
        if self.entryEndTime is not None:
            self.timerentry_endtime.increment()
            self["config"].invalidate(self.entryEndTime)

    def decrementEnd(self):
        if self.entryEndTime is not None:
            self.timerentry_endtime.decrement()
            self["config"].invalidate(self.entryEndTime)

    def subserviceSelected(self, service):
        if not service is None:
            self.timer.service_ref = ServiceReference(service[1])
        self.saveTimer()
        self.close((True, self.timer))

    def saveTimer(self):
        self.session.nav.RecordTimer.saveTimer()

    def keyCancel(self):
        self.close((False, ))

    def pathSelected(self, res):
        if res is not None:
            if config.movielist.videodirs.value != self.timerentry_dirname.choices:
                self.timerentry_dirname.setChoices(
                    config.movielist.videodirs.value, default=res)
            self.timerentry_dirname.value = res

    def tagEditFinished(self, ret):
        if ret is not None:
            self.timerentry_tags = ret
            self.timerentry_tagsset.setChoices(
                [not ret and "None" or " ".join(ret)])
            self["config"].invalidate(self.tagsSet)
Exemple #12
0
class TimerEntry(Screen, ConfigListScreen, HelpableScreen):
    def __init__(self, session, timer, menu_path=""):
        Screen.__init__(self, session)
        HelpableScreen.__init__(self)
        screentitle = _("Timer entry")
        menu_path += screentitle
        if config.usage.show_menupath.value == 'large':
            title = menu_path
            self["menu_path_compressed"] = StaticText("")
        elif config.usage.show_menupath.value == 'small':
            title = screentitle
            print 'menu_path:', menu_path
            self["menu_path_compressed"] = StaticText(
                menu_path +
                " >" if not menu_path.endswith(' / ') else menu_path[:-3] +
                " >" or "")
        else:
            title = screentitle
            self["menu_path_compressed"] = StaticText("")
        self.setup_title = title
        Screen.setTitle(self, title)

        self.timer = timer
        self.eit = self.timer.eit

        self.entryDate = None
        self.entryService = None

        self["HelpWindow"] = Pixmap()
        self["HelpWindow"].hide()
        self["VKeyIcon"] = Boolean(False)

        self["description"] = Label("")
        self["key_red"] = Label(_("Cancel"))
        self["key_green"] = Label(_("OK"))
        self["key_yellow"] = Label()
        self["key_blue"] = Label()

        self.createConfig()

        self["actions"] = HelpableNumberActionMap(
            self, ["SetupActions", "TimerEntryActions", "ColorActions"], {
                "ok": (self.keySelect, _("Save the timer and exit")),
                "save": (self.keyGo, "Save the timer and exit"),
                "cancel":
                (self.keyCancel, "Cancel creation of the timer and exit"),
                "incStart": (self.incrementStart, _("Increment start time")),
                "decStart": (self.decrementStart, _("Decrement start time")),
                "incEnd": (self.incrementEnd, _("Increment end time")),
                "decEnd": (self.decrementEnd, _("Decrement end time")),
                "nextStepStart":
                (self.nextStepStart, _("Increment start time")),
                "prevStepStart":
                (self.prevStepStart, _("Decrement start time")),
                "nextStepEnd": (self.nextStepEnd, _("Increment end time")),
                "prevStepEnd": (self.prevStepEnd, _("Decrement end time"))
            }, -2)

        self.onChangedEntry = []
        self.list = []
        ConfigListScreen.__init__(self, self.list, session=session)
        self.createSetup("config")
        if self.selectionChanged not in self["config"].onSelectionChanged:
            self["config"].onSelectionChanged.append(self.selectionChanged)
        self.selectionChanged()
        if self.ShowHelp not in self.onExecBegin:
            self.onExecBegin.append(self.ShowHelp)
        if self.HideHelp not in self.onExecEnd:
            self.onExecEnd.append(self.HideHelp)

    def createConfig(self):
        justplay = self.timer.justplay
        always_zap = self.timer.always_zap
        rename_repeat = self.timer.rename_repeat

        afterevent = {
            AFTEREVENT.NONE: "nothing",
            AFTEREVENT.DEEPSTANDBY: "deepstandby",
            AFTEREVENT.STANDBY: "standby",
            AFTEREVENT.AUTO: "auto"
        }[self.timer.afterEvent]

        if self.timer.record_ecm and self.timer.descramble:
            recordingtype = "descrambled+ecm"
        elif self.timer.record_ecm:
            recordingtype = "scrambled+ecm"
        elif self.timer.descramble:
            recordingtype = "normal"

        weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")

        # calculate default values
        weekday = 0
        day = [False] * 7
        if self.timer.repeated:  # repeated
            repeat_type = "repeated"
            if self.timer.repeated == 31:  # Mon-Fri
                repeated = "weekdays"
            elif self.timer.repeated == 127:  # daily
                repeated = "daily"
            else:
                flags = self.timer.repeated
                day = [bool(flags & (1 << n)) for n in range(7)]
                if sum(day) == 1:
                    repeated = "weekly"
                    weekday = day.index(True)
                else:
                    repeated = "user"
        else:  # once
            repeat_type = "once"
            repeated = None
            weekday = localtime(self.timer.begin).tm_wday
            day[weekday] = 1

        self.timerentry_justplay = ConfigSelection(
            choices=[("zap", _("zap")), ("record", _("record")),
                     ("zap+record", _("zap and record"))],
            default={
                0: "record",
                1: "zap",
                2: "zap+record"
            }[justplay + 2 * always_zap])
        if SystemInfo["DeepstandbySupport"]:
            shutdownString = _("go to deep standby")
        else:
            shutdownString = _("shut down")
        self.timerentry_afterevent = ConfigSelection(choices=[
            ("nothing", _("do nothing")), ("standby", _("go to standby")),
            ("deepstandby", shutdownString), ("auto", _("auto"))
        ],
                                                     default=afterevent)
        self.timerentry_recordingtype = ConfigSelection(choices=[
            ("normal", _("normal")),
            ("descrambled+ecm", _("descramble and record ecm")),
            ("scrambled+ecm", _("don't descramble, record ecm"))
        ],
                                                        default=recordingtype)
        self.timerentry_type = ConfigSelection(choices=[("once", _("once")),
                                                        ("repeated",
                                                         _("repeated"))],
                                               default=repeat_type)
        self.timerentry_name = ConfigText(default=self.timer.name.replace(
            '\xc2\x86', '').replace('\xc2\x87', '').encode("utf-8"),
                                          visible_width=50,
                                          fixed_size=False)
        self.timerentry_description = ConfigText(
            default=self.timer.description, visible_width=50, fixed_size=False)
        self.timerentry_tags = self.timer.tags[:]
        # if no tags found, make name of event default tag set.
        if not self.timerentry_tags:
            tagname = self.timer.name.strip()
            if tagname:
                tagname = tagname[0].upper() + tagname[1:].replace(" ", "_")
                self.timerentry_tags.append(tagname)

        self.timerentry_tagsset = ConfigSelection(choices=[
            not self.timerentry_tags and "None"
            or " ".join(self.timerentry_tags)
        ])
        self.timerentry_repeated = ConfigSelection(choices=[
            ("weekly", _("weekly")), ("daily", _("daily")),
            ("weekdays", _("Mon-Fri")), ("user", _("user defined"))
        ],
                                                   default=repeated)
        self.timerentry_renamerepeat = ConfigYesNo(default=rename_repeat)

        self.timerentry_date = ConfigDateTime(
            default=self.timer.begin,
            formatstring=config.usage.date.daylong.value,
            increment=24 * 60 * 60)
        self.timerentry_starttime = ConfigClock(default=self.timer.begin)
        self.timerentry_endtime = ConfigClock(default=self.timer.end)
        duration = self.timer.end - self.timer.begin
        self.timerentry_showendtime = ConfigSelection(
            default=duration > 4
            and duration != config.recording.margin_before.value * 60 + 1,
            choices=[(True, _("yes")), (False, _("no"))])

        default = self.timer.dirname or defaultMoviePath()
        tmp = config.movielist.videodirs.value
        if default not in tmp:
            tmp.append(default)
        tmp = [(p, friendlyMoviePath(p, trailing=False)) for p in tmp]
        self.timerentry_dirname = ConfigSelection(default=default, choices=tmp)

        self.timerentry_repeatedbegindate = ConfigDateTime(
            default=self.timer.repeatedbegindate,
            formatstring=config.usage.date.daylong.value,
            increment=24 * 60 * 60)

        self.timerentry_weekday = ConfigSelection(
            default=weekday_table[weekday],
            choices=[("mon", _("Monday")), ("tue", _("Tuesday")),
                     ("wed", _("Wednesday")), ("thu", _("Thursday")),
                     ("fri", _("Friday")), ("sat", _("Saturday")),
                     ("sun", _("Sunday"))])

        self.timerentry_day = ConfigSubList()
        for x in range(7):
            self.timerentry_day.append(ConfigYesNo(default=day[x]))

        # FIXME some service-chooser needed here
        servicename = "N/A"
        try:  # no current service available?
            servicename = str(self.timer.service_ref.getServiceName())
        except:
            pass
        self.timerentry_service_ref = self.timer.service_ref
        self.timerentry_service = ConfigSelection([servicename])

        self.eventName, self.eventDescription, __ = self.getEventInfo()

        for i in [
                self.timerentry_type,
                self.timerentry_repeated,
                self.timerentry_date,
                self.timerentry_starttime,
                self.timerentry_endtime,
                self.timerentry_repeatedbegindate,
                self.timerentry_weekday,
        ] + self.timerentry_day[0:7]:
            i.addNotifier(self.updateEventInfo)

        self.timerentry_name.addNotifier(self.nameInfoUpdated,
                                         immediate_feedback=False)
        self.timerentry_description.addNotifier(self.descriptionInfoUpdated,
                                                immediate_feedback=False)

    def createSetup(self, widget):
        self.list = []
        self.entryName = getConfigListEntry(
            _("Name"), self.timerentry_name,
            _("The name the recording will get.\nA manually entered name will override naming extracted from the EPG. Clear the name and move the selection away to return to updating the name from the EPG"
              ))
        self.list.append(self.entryName)
        self.entryDescription = getConfigListEntry(
            _("Description"), self.timerentry_description,
            _("The description of the recording.\nA manually entered description will override naming extracted from the EPG. Clear the description and move the selection away to return to updating the description from the EPG"
              ))
        self.list.append(self.entryDescription)
        self.timerJustplayEntry = getConfigListEntry(
            _("Timer type"), self.timerentry_justplay,
            _("Choose between record and ZAP."))
        self.list.append(self.timerJustplayEntry)
        self.timerTypeEntry = getConfigListEntry(
            _("Repeat type"), self.timerentry_type,
            _("A repeating timer or just once?"))
        self.list.append(self.timerTypeEntry)

        if self.timerentry_type.value == "once":
            self.frequencyEntry = None
        else:  # repeated
            self.frequencyEntry = getConfigListEntry(
                _("Repeats"), self.timerentry_repeated,
                _("The type of repetition required: daily, weekly on a specified day, on weekdays (Mon-Fri), or regularly on specified days."
                  ))
            self.list.append(self.frequencyEntry)
            self.repeatedbegindateEntry = getConfigListEntry(
                _("Starting on"), self.timerentry_repeatedbegindate,
                _("The timer becomes active (but doesn't necessarily run) on this date."
                  ))
            self.list.append(self.repeatedbegindateEntry)
            if self.timerentry_repeated.value == "daily":
                pass
            if self.timerentry_repeated.value == "weekdays":
                pass
            if self.timerentry_repeated.value == "weekly":
                self.list.append(
                    getConfigListEntry(
                        _("Weekday"), self.timerentry_weekday,
                        _("The day of the week the timer runs.")))

            if self.timerentry_repeated.value == "user":
                self.list.append(
                    getConfigListEntry(
                        _("Monday"), self.timerentry_day[0],
                        _("Enable/disable the timer on Mondays.")))
                self.list.append(
                    getConfigListEntry(
                        _("Tuesday"), self.timerentry_day[1],
                        _("Enable/disable the timer on Tuesdays.")))
                self.list.append(
                    getConfigListEntry(
                        _("Wednesday"), self.timerentry_day[2],
                        _("Enable/disable the timer on Wednesdays.")))
                self.list.append(
                    getConfigListEntry(
                        _("Thursday"), self.timerentry_day[3],
                        _("Enable/disable the timer on Thursdays.")))
                self.list.append(
                    getConfigListEntry(
                        _("Friday"), self.timerentry_day[4],
                        _("Enable/disable the timer on Fridays.")))
                self.list.append(
                    getConfigListEntry(
                        _("Saturday"), self.timerentry_day[5],
                        _("Enable/disable the timer on Saturdays.")))
                self.list.append(
                    getConfigListEntry(
                        _("Sunday"), self.timerentry_day[6],
                        _("Enable/disable the timer on Sundays.")))
            if self.timerentry_justplay.value != "zap":
                self.list.append(
                    getConfigListEntry(
                        _("Generate name and description for new events"),
                        self.timerentry_renamerepeat,
                        _("Generate a new name and description from the EPG for each run of the timer."
                          )))

        self.entryDate = getConfigListEntry(_("Date"), self.timerentry_date,
                                            _("The date the timer starts."))
        if self.timerentry_type.value == "once":
            self.list.append(self.entryDate)

        self.entryStartTime = getConfigListEntry(
            _("Start time"), self.timerentry_starttime,
            _("The time the timer starts."))
        self.list.append(self.entryStartTime)

        self.entryShowEndTime = getConfigListEntry(
            _("Set end time"), self.timerentry_showendtime,
            _("Set the time the ZAP timer completes and performs any \"After event\" action."
              ))
        if self.timerentry_justplay.value == "zap":
            self.list.append(self.entryShowEndTime)
        self.entryEndTime = getConfigListEntry(
            _("End time"), self.timerentry_endtime,
            _("The time the timer completes and the \"After event\" action is taken. If the end time is earlier than the start time of the timer, the completion action takes place at that time on the following day."
              ))
        if self.timerentry_justplay.value != "zap" or self.timerentry_showendtime.value:
            self.list.append(self.entryEndTime)

        self.channelEntry = getConfigListEntry(
            _("Channel"), self.timerentry_service,
            _("The channel for this timer."))
        self.list.append(self.channelEntry)

        self.dirname = getConfigListEntry(
            _("Location"), self.timerentry_dirname,
            _("Where the recording will be saved."))
        self.tagsSet = getConfigListEntry(
            _("Tags"), self.timerentry_tagsset,
            _("Choose a tag to make searching for the recording easier."))
        if self.timerentry_justplay.value != "zap":
            if config.usage.setup_level.index >= 2:  # expert+
                self.list.append(self.dirname)
            if getPreferredTagEditor():
                self.list.append(self.tagsSet)
            self.list.append(
                getConfigListEntry(
                    _("After event"), self.timerentry_afterevent,
                    _("Action taken on the completion of the timer. \"Auto\" lets your %s %s return to the state it was in when the timer started. \"Do nothing\", \"Go to standby\" and \"Go to deep standby\" do exactly that."
                      ) % (getMachineBrand(), getMachineName())))
            self.list.append(
                getConfigListEntry(
                    _("Recording type"), self.timerentry_recordingtype,
                    _("\"Descramble & record ECM\" allows the recording to be descrambled later if descrambling while recording failed. \"Don't descramble, record ECM\" saves a scrambled recording that can be descrambled on playback. \"Normal\" means descramble while recording and don't record ECM."
                      )))

        self[widget].list = self.list
        self[widget].l.setList(self.list)

    def selectionChanged(self):
        if self["config"].getCurrent():
            if len(self["config"].getCurrent()
                   ) > 2 and self["config"].getCurrent()[2]:
                self["description"].setText(self["config"].getCurrent()[2])

    def createSummary(self):
        return SetupSummary

    # for summary:
    def changedEntry(self):
        for x in self.onChangedEntry:
            x()

    def getCurrentEntry(self):
        return self["config"].getCurrent() and self["config"].getCurrent(
        )[0] or ""

    def getCurrentValue(self):
        return self["config"].getCurrent() and str(
            self["config"].getCurrent()[1].getText()) or ""

    def newConfig(self):
        if self["config"].getCurrent() in (self.timerTypeEntry,
                                           self.timerJustplayEntry,
                                           self.frequencyEntry,
                                           self.entryShowEndTime):
            self.createSetup("config")

    def showHelp(self):
        HelpableScreen.showHelp(self)

    def hideTextHelp(self):
        self.ShowHelp()

    def showTextHelp(self):
        self.HideHelp()

    def KeyText(self):
        currConfig = self["config"].getCurrent()
        if currConfig[0] in (_('Name'), _("Description")):
            self.session.openWithCallback(self.renameEntryCallback,
                                          VirtualKeyBoard,
                                          title=currConfig[2],
                                          text=currConfig[1].value)

    def keyLeft(self):
        cur = self["config"].getCurrent()
        if cur in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.keyLeft(self)
            self.newConfig()

    def keyRight(self):
        cur = self["config"].getCurrent()
        if cur in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.keyRight(self)
            self.newConfig()

    def renameEntry(self):
        cur = self["config"].getCurrent()
        if cur == self.entryName:
            title_text = _("Please enter new name:")
            old_text = self.timerentry_name.value
        else:
            title_text = _("Please enter new description:")
            old_text = self.timerentry_description.value
        self.session.openWithCallback(self.renameEntryCallback,
                                      VirtualKeyBoard,
                                      title=title_text,
                                      text=old_text)

    def renameEntryCallback(self, answer):
        if answer:
            if self["config"].getCurrent() == self.entryName:
                self.timerentry_name.value = answer
                self["config"].invalidate(self.entryName)
            else:
                self.timerentry_description.value = answer
                self["config"].invalidate(self.entryDescription)

    def handleKeyFileCallback(self, answer):
        if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
            self.keySelect()
        else:
            ConfigListScreen.handleKeyFileCallback(self, answer)
            self.newConfig()

    def keySelect(self):
        cur = self["config"].getCurrent()
        if cur == self.channelEntry:
            self.session.openWithCallback(
                self.finishedChannelSelection,
                ChannelSelection.SimpleChannelSelection,
                _("Select channel to record from"),
                currentBouquet=True)
        elif config.usage.setup_level.index >= 2 and cur == self.dirname:
            self.session.openWithCallback(
                self.pathSelected,
                MovieLocationBox,
                _("Select target folder"),
                self.timerentry_dirname.value,
                minFree=100  # We require at least 100MB free space
            )
        elif getPreferredTagEditor() and cur == self.tagsSet:
            self.session.openWithCallback(self.tagEditFinished,
                                          getPreferredTagEditor(),
                                          self.timerentry_tags)
        else:
            self.keyGo()

    def finishedChannelSelection(self, *args):
        if args:
            self.timerentry_service_ref = ServiceReference(args[0])
            self.timerentry_service.setCurrentText(
                self.timerentry_service_ref.getServiceName())
            # Update the event info, because
            # ConfigSelection.setCurrentText() doesn't call
            # ConfigElement.changed()
            self.updateEventInfo(self.timerentry_service)
            self["config"].invalidate(self.channelEntry)

    def getTimestamp(self, date, mytime):
        d = localtime(date)
        dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
        return int(mktime(dt.timetuple()))

    def getBeginEnd(self):
        date = self.timerentry_date.value
        endtime = self.timerentry_endtime.value
        starttime = self.timerentry_starttime.value

        begin = self.getTimestamp(date, starttime)
        end = self.getTimestamp(date, endtime)

        # if the endtime is less than the starttime, add 1 day.
        if end < begin:
            end += 24 * 60 * 60

        # if the timer type is a Zap and no end is set, set duration to short, fairly arbitrary, time so timer is shown in EPG's.
        if self.timerentry_justplay.value == "zap":
            if not self.timerentry_showendtime.value:
                end = begin + (config.recording.margin_before.value * 60) + 1

        return begin, end

    def getRepeatedBeginEnd(self):
        if self.timerentry_repeated.value == "daily":
            repeated = [True] * 7
        elif self.timerentry_repeated.value == "weekly":
            repeated = [False] * 7
            repeated[self.timerentry_weekday.index] = True
        elif self.timerentry_repeated.value == "weekdays":
            repeated = [True] * 5 + [False] * 2
        if self.timerentry_repeated.value == "user":
            repeated = [self.timerentry_day[x].value for x in range(7)]

        endtime = self.timerentry_endtime.value
        starttime = self.timerentry_starttime.value

        repeatedbegindate = self.timerentry_repeatedbegindate.value
        if any(repeated):
            begin = self.getTimestamp(repeatedbegindate, starttime)
            end = self.getTimestamp(repeatedbegindate, endtime)
        else:
            now = time()
            begin = self.getTimestamp(now, starttime)
            end = self.getTimestamp(now, endtime)
        repeatedbegindate = self.getTimestamp(repeatedbegindate, starttime)

        # when a timer end is set before the start, add 1 day
        if end < begin:
            end += 24 * 60 * 60

        return begin, end, repeatedbegindate, repeated

    def selectChannelSelector(self, *args):
        self.session.openWithCallback(self.finishedChannelSelectionCorrection,
                                      ChannelSelection.SimpleChannelSelection,
                                      _("Select channel to record from"))

    def finishedChannelSelectionCorrection(self, *args):
        if args:
            self.finishedChannelSelection(*args)
            self.keyGo()

    def keyGo(self, result=None):
        if not self.timerentry_service_ref.isRecordable():
            self.session.openWithCallback(
                self.selectChannelSelector, MessageBox,
                _("You didn't select a channel to record from."),
                MessageBox.TYPE_ERROR)
            return
        self.timer.eit = self.eit
        self.timer.name = self.timerentry_name.value
        self.timer.description = self.timerentry_description.value
        self.timer.justplay = self.timerentry_justplay.value == "zap"
        self.timer.always_zap = self.timerentry_justplay.value == "zap+record"
        self.timer.rename_repeat = self.timerentry_renamerepeat.value
        if self.timerentry_justplay.value == "zap":
            if not self.timerentry_showendtime.value:
                self.timerentry_endtime.value = self.timerentry_starttime.value
        self.timer.resetRepeated()
        self.timer.afterEvent = {
            "nothing": AFTEREVENT.NONE,
            "deepstandby": AFTEREVENT.DEEPSTANDBY,
            "standby": AFTEREVENT.STANDBY,
            "auto": AFTEREVENT.AUTO
        }[self.timerentry_afterevent.value]
        self.timer.descramble = {
            "normal": True,
            "descrambled+ecm": True,
            "scrambled+ecm": False,
        }[self.timerentry_recordingtype.value]
        self.timer.record_ecm = {
            "normal": False,
            "descrambled+ecm": True,
            "scrambled+ecm": True,
        }[self.timerentry_recordingtype.value]
        self.timer.service_ref = self.timerentry_service_ref
        self.timer.tags = self.timerentry_tags

        if self.timer.dirname or self.timerentry_dirname.value != defaultMoviePath(
        ):
            self.timer.dirname = self.timerentry_dirname.value
            config.movielist.last_timer_videodir.value = self.timer.dirname
            config.movielist.last_timer_videodir.save()

        if self.timerentry_type.value == "once":
            self.timer.begin, self.timer.end = self.getBeginEnd()
        elif self.timerentry_type.value == "repeated":
            self.timer.begin, self.timer.end, self.timer.repeatedbegindate, repeated = self.getRepeatedBeginEnd(
            )
            for i, r in enumerate(repeated):
                if r:
                    self.timer.setRepeated(i)

        if self.timer.eit is not None:
            event = eEPGCache.getInstance().lookupEventId(
                self.timer.service_ref.ref, self.timer.eit)
            if event:
                n = event.getNumOfLinkageServices()
                if n > 1:
                    tlist = []
                    ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
                    parent = self.timer.service_ref.ref
                    selection = 0
                    for x in range(n):
                        i = event.getLinkageService(parent, x)
                        if i.toString() == ref.toString():
                            selection = x
                        tlist.append((i.getName(), i))
                    self.session.openWithCallback(
                        self.subserviceSelected,
                        ChoiceBox,
                        title=_("Please select a subservice to record..."),
                        list=tlist,
                        selection=selection)
                    return
                elif n > 0:
                    parent = self.timer.service_ref.ref
                    self.timer.service_ref = ServiceReference(
                        event.getLinkageService(parent, 0))
        self.saveTimer()
        self.close((True, self.timer))

    def getEventInfo(self):
        if self.timerentry_type.value == "once":
            begin, end = self.getBeginEnd()
        elif self.timerentry_type.value == "repeated":
            begin, end, repeatedbegindate, repeated = self.getRepeatedBeginEnd(
            )
            if sum(repeated):
                begin, end = self.timer.nextRepeatTime(begin, end,
                                                       repeatedbegindate,
                                                       repeated)
        queryTime = (begin + end) / 2
        ref = self.timerentry_service_ref and self.timerentry_service_ref.ref
        epgcache = eEPGCache.getInstance()
        evt = epgcache.lookupEventTime(ref, queryTime)
        if evt:
            ev_begin, ev_end, name, description, eit = parseEvent(evt)
            name = name.replace('\xc2\x86', '').replace('\xc2\x87',
                                                        '').encode("utf-8")
            return name, description, eit
        else:
            return "", "", None

    def updateEventInfo(self, confEntry):
        name, description, eit = self.getEventInfo()
        self.eit = eit
        if name and self.eventName != name:
            if self.timerentry_name.value == self.eventName and (
                    self.timerentry_name.value != name
                    or not self.timerentry_name.value):
                self.timerentry_name.value = name
                if "config" in self:
                    self["config"].invalidate(self.entryName)
            self.eventName = name
        if self.eventDescription != description:
            if self.timerentry_description.value == self.eventDescription and (
                    self.timerentry_description.value != description
                    or not self.timerentry_description.value):
                self.timerentry_description.value = description
                if "config" in self:
                    self["config"].invalidate(self.entryDescription)
            self.eventDescription = description

    def nameInfoUpdated(self, confEntry):
        if not self.timerentry_name.value:
            name, __, __ = self.getEventInfo()
            if name:
                self.timerentry_name.value = name
                if "config" in self:
                    self["config"].invalidate(self.entryName)

    def descriptionInfoUpdated(self, confEntry):
        if not self.timerentry_description.value:
            __, description, __ = self.getEventInfo()
            if description:
                self.timerentry_description.value = description
                if "config" in self:
                    self["config"].invalidate(self.entryDescription)

    def changeTimerType(self):
        self.timerentry_justplay.selectNext()
        self["config"].invalidate(self.timerJustplayEntry)

    def incrementStart(self):
        self.keyRepeat = 0
        self.timerentry_starttime.increment()
        self["config"].invalidate(self.entryStartTime)
        if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [
                0, 0
        ]:
            self.timerentry_date.value += 24 * 60 * 60
            self["config"].invalidate(self.entryDate)

    def decrementStart(self):
        self.keyRepeat = 0
        self.timerentry_starttime.decrement()
        self["config"].invalidate(self.entryStartTime)
        if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [
                23, 59
        ]:
            self.timerentry_date.value -= 24 * 60 * 60
            self["config"].invalidate(self.entryDate)

    def incrementEnd(self):
        self.keyRepeat = 0
        if self.entryEndTime is not None:
            self.timerentry_endtime.increment()
            self["config"].invalidate(self.entryEndTime)

    def decrementEnd(self):
        self.keyRepeat = 0
        if self.entryEndTime is not None:
            self.timerentry_endtime.decrement()
            self["config"].invalidate(self.entryEndTime)

    def nextStepStart(self):
        self.keyRepeat += 1
        if self.keyRepeat >= 5:
            if self.keyRepeat & 1:  # step every second repeat
                return
            self.timerentry_starttime.nextStep()
        else:
            self.timerentry_starttime.increment()
        self["config"].invalidate(self.entryStartTime)
        if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [
                0, 0
        ]:
            self.timerentry_date.value += 24 * 60 * 60
            self["config"].invalidate(self.entryDate)

    def prevStepStart(self):
        self.keyRepeat += 1
        if self.keyRepeat >= 5:
            if self.keyRepeat & 1:  # step every second repeat
                return
        if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [
                0, 0
        ]:
            self.timerentry_date.value -= 24 * 60 * 60
            self["config"].invalidate(self.entryDate)
        if self.keyRepeat >= 5:
            self.timerentry_starttime.prevStep()
        else:
            self.timerentry_starttime.decrement()
        self["config"].invalidate(self.entryStartTime)

    def nextStepEnd(self):
        if self.entryEndTime is not None:
            self.keyRepeat += 1
            if self.keyRepeat >= 5:
                if self.keyRepeat & 1:  # step every second repeat
                    return
                self.timerentry_endtime.nextStep()
            else:
                self.timerentry_endtime.increment()
            self["config"].invalidate(self.entryEndTime)

    def prevStepEnd(self):
        if self.entryEndTime is not None:
            self.keyRepeat += 1
            if self.keyRepeat >= 5:
                if self.keyRepeat & 1:  # step every second repeat
                    return
                self.timerentry_endtime.prevStep()
            else:
                self.timerentry_endtime.decrement()
            self["config"].invalidate(self.entryEndTime)

    def subserviceSelected(self, service):
        if service is not None:
            self.timer.service_ref = ServiceReference(service[1])
        self.saveTimer()
        self.close((True, self.timer))

    def saveTimer(self):
        self.session.nav.RecordTimer.saveTimer()

    def keyCancel(self):
        self.close((False, ))

    def pathSelected(self, res):
        # even if it was cancelled the aliases may have changed
        if res is None:
            res = self.timerentry_dirname.value
        tmp = [(p, friendlyMoviePath(p, trailing=False))
               for p in config.movielist.videodirs.value]
        if tmp != self.timerentry_dirname.choices:
            self.timerentry_dirname.setChoices(tmp, default=res)
        self.timerentry_dirname.value = res

    def tagEditFinished(self, ret):
        if ret is not None:
            self.timerentry_tags = ret
            self.timerentry_tagsset.setChoices(
                [not ret and "None" or " ".join(ret)])
            self["config"].invalidate(self.tagsSet)