class AdvancedCutInput(Screen, ConfigListScreen): def __init__(self, session, name, path, descr): Screen.__init__(self, session) self.skinName = [ "AdvancedCutInput", "Setup" ] self["key_green"] = StaticText(_("OK")) self["key_red"] = StaticText(_("Cancel")) if self.baseName(path) == self.baseName(name): title = "" else: title = name dir = self.dirName(path) file = self.baseName(path) + " cut" self.input_replace = ConfigSelection(choices = [("no", _("No")), ("yes", _("Yes"))], default = "no") self.input_file = ConfigText(default = file, fixed_size = False, visible_width = 45) self.input_title = ConfigText(default = title, fixed_size = False, visible_width = 45) self.input_descr = ConfigText(default = descr, fixed_size = False, visible_width = 45) tmp = config.movielist.videodirs.value if not dir in tmp: tmp.append(dir) self.input_dir = ConfigSelection(choices = tmp, default = dir) self.input_manual = ConfigSelection(choices = [("no", _("Cutlist")), ("yes", _("Manual specification"))], default = "no") self.input_space = ConfigNothing() self.input_manualcuts = ConfigText(default = "", fixed_size = False) self.input_manualcuts.setUseableChars(" 0123456789:.") self["actions"] = ActionMap(["SetupActions"], { "ok": self.keySelectOrGo, "save": self.keyGo, "cancel": self.keyCancel, }, -2) self.list = [] ConfigListScreen.__init__(self, self.list) self.entry_replace = getConfigListEntry(_("Replace original:"), self.input_replace) self.entry_file = getConfigListEntry(_("New filename:"), self.input_file) self.entry_title = getConfigListEntry(_("New title:"), self.input_title) self.entry_descr = getConfigListEntry(_("New description:"), self.input_descr) self.entry_dir = getConfigListEntry(_("New location:"), self.input_dir) self.entry_manual = getConfigListEntry(_("Cut source:"), self.input_manual) self.entry_space = getConfigListEntry(_("Cuts (an IN OUT IN OUT ... sequence of hour:min:sec)"), self.input_space) self.entry_manualcuts = getConfigListEntry(":", self.input_manualcuts) self.createSetup(self["config"]) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(_("Cut Parameter Input")) def createSetup(self, configlist): list = [ self.entry_replace ] if self.input_replace.value == "no": list.extend(( self.entry_file, self.entry_dir, )) list.extend(( self.entry_title, self.entry_descr, self.entry_manual, )) if self.input_manual.value == "yes": list.extend(( self.entry_space, self.entry_manualcuts, )) self.list = list configlist.list = list configlist.l.setList(list) def keyLeft(self): ConfigListScreen.keyLeft(self) cc = self["config"].getCurrent() if cc is self.entry_replace or cc is self.entry_manual: self.createSetup(self["config"]) def keyRight(self): ConfigListScreen.keyRight(self) cc = self["config"].getCurrent() if cc is self.entry_replace or cc is self.entry_manual: self.createSetup(self["config"]) def pathSelected(self, res): if res is not None: if config.movielist.videodirs.value != self.input_dir.choices: self.input_dir.setChoices(config.movielist.videodirs.value, default=res) self.input_dir.value = res def keySelectOrGo(self): if self["config"].getCurrent() == self.entry_dir: self.session.openWithCallback( self.pathSelected, MovieLocationBox, _("Choose target folder"), self.input_dir.value, ) else: self.keyGo() def keyGo(self): if self.input_replace.value == "yes": path = False else: path = self.rejoinName(self.input_dir.value, self.input_file.value) if self.input_manual.value == "no": cuts = False else: cuts = self.input_manualcuts.value.split(' ') while "" in cuts: cuts.remove("") self.close((True, self.input_replace.value == "yes", path, self.input_title.value, self.input_descr.value, cuts)) def keyCancel(self): self.close((False,)) def baseName(self, str): name = str.split('/')[-1] if name.endswith(".ts") is True: return name[:-3] else: return name def dirName(self, str): return '/'.join(str.split('/')[:-1]) + '/' def rejoinName(self, dir, name): name = name.strip() if name.endswith(".ts") is True: return dir + name[:-3] else: return dir + name
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)
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)
class RecordPathsSettings(eRecordPathsSettings): def __init__(self, session): eRecordPathsSettings.__init__(self, session) self.onShown.append(self.__setWindowTitle) def __setWindowTitle(self): self.setTitle(_("Record Paths Settings")) def initConfigList(self): eRecordPathsSettings.initConfigList(self) tmp = config.movielist.videodirs.value default = config.AdvancedMovieSelection.movecopydirs.value if default not in tmp: tmp = tmp[:] tmp.append(default) print("MoveCopyPath: ", default, tmp) self.movecopy_dirname = ConfigSelection(default=default, choices=tmp) self.movecopy_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.movecopy_dirname.last_value = config.AdvancedMovieSelection.movecopydirs.value self.movecopy_entry = getConfigListEntry(_("Move/copy location:"), self.movecopy_dirname) self.list.append(self.movecopy_entry) self["config"].setList(self.list) if not self.selectionChanged in self["config"].onSelectionChanged: self["config"].onSelectionChanged.append(self.selectionChanged) def selectionChanged(self): # Topfi: disabled three lines which causes GS #eRecordPathsSettings.selectionChanged(self) currentry = self["config"].getCurrent() #if currentry == self.movecopy_entry: # self["introduction"].setText(_("Please select the default move/copy location which is used for move/copy movies.")) def ok(self): eRecordPathsSettings.ok(self) currentry = self["config"].getCurrent() if currentry == self.movecopy_entry: self.entrydirname = self.movecopy_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Location for move/copy files"), preferredPath(self.movecopy_dirname.value) ) def dirnameSelected(self, res): eRecordPathsSettings.dirnameSelected(self, res) if res is not None: if config.AdvancedMovieSelection.movecopydirs.value != res: tmp = config.movielist.videodirs.value default = config.AdvancedMovieSelection.movecopydirs.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.movecopy_dirname.setChoices(tmp, default=default) def save(self): currentry = self["config"].getCurrent() if self.checkReadWriteDir(currentry[1]): config.AdvancedMovieSelection.movecopydirs.value = self.movecopy_dirname.value config.AdvancedMovieSelection.movecopydirs.save() eRecordPathsSettings.save(self)
class AdvancedCutInput(Screen, ConfigListScreen): def __init__(self, session, name, path, descr): Screen.__init__(self, session) self.skinName = ["AdvancedCutInput", "Setup"] self["key_green"] = StaticText(_("OK")) self["key_red"] = StaticText(_("Cancel")) if self.baseName(path) == self.baseName(name): title = "" else: title = name dir = self.dirName(path) file = self.baseName(path) + " cut" self.input_replace = ConfigSelection(choices=[("no", _("No")), ("yes", _("Yes"))], default="no") self.input_file = ConfigText(default=file, fixed_size=False, visible_width=45) self.input_title = ConfigText(default=title, fixed_size=False, visible_width=45) self.input_descr = ConfigText(default=descr, fixed_size=False, visible_width=45) tmp = config.movielist.videodirs.value if not dir in tmp: tmp.append(dir) self.input_dir = ConfigSelection(choices=tmp, default=dir) self.input_manual = ConfigSelection(choices=[("no", _("Cutlist")), ("yes", _("Manual specification"))], default="no") self.input_space = ConfigNothing() self.input_manualcuts = ConfigText(default="", fixed_size=False) self.input_manualcuts.setUseableChars(" 0123456789:.") self["actions"] = ActionMap(["SetupActions"], { "ok": self.keySelectOrGo, "save": self.keyGo, "cancel": self.keyCancel, }, -2) self.list = [] ConfigListScreen.__init__(self, self.list) self.entry_replace = getConfigListEntry(_("Replace original:"), self.input_replace) self.entry_file = getConfigListEntry(_("New filename:"), self.input_file) self.entry_title = getConfigListEntry(_("New title:"), self.input_title) self.entry_descr = getConfigListEntry(_("New description:"), self.input_descr) self.entry_dir = getConfigListEntry(_("New location:"), self.input_dir) self.entry_manual = getConfigListEntry(_("Cut source:"), self.input_manual) self.entry_space = getConfigListEntry(_("Cuts (an IN OUT IN OUT ... sequence of hour:min:sec)"), self.input_space) self.entry_manualcuts = getConfigListEntry(":", self.input_manualcuts) self.createSetup(self["config"]) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(_("Cut Parameter Input")) def createSetup(self, configlist): list = [ self.entry_replace ] if self.input_replace.value == "no": list.extend(( self.entry_file, self.entry_dir, )) list.extend(( self.entry_title, self.entry_descr, self.entry_manual, )) if self.input_manual.value == "yes": list.extend(( self.entry_space, self.entry_manualcuts, )) self.list = list configlist.list = list configlist.l.setList(list) def keyLeft(self): ConfigListScreen.keyLeft(self) cc = self["config"].getCurrent() if cc is self.entry_replace or cc is self.entry_manual: self.createSetup(self["config"]) def keyRight(self): ConfigListScreen.keyRight(self) cc = self["config"].getCurrent() if cc is self.entry_replace or cc is self.entry_manual: self.createSetup(self["config"]) def pathSelected(self, res): if res is not None: if config.movielist.videodirs.value != self.input_dir.choices: self.input_dir.setChoices(config.movielist.videodirs.value, default=res) self.input_dir.value = res def keySelectOrGo(self): if self["config"].getCurrent() == self.entry_dir: self.session.openWithCallback( self.pathSelected, MovieLocationBox, _("Choose target folder"), self.input_dir.value, ) else: self.keyGo() def keyGo(self): if self.input_replace.value == "yes": path = False else: path = self.rejoinName(self.input_dir.value, self.input_file.value) if self.input_manual.value == "no": cuts = False else: cuts = self.input_manualcuts.value.split(' ') while "" in cuts: cuts.remove("") self.close((True, self.input_replace.value == "yes", path, self.input_title.value, self.input_descr.value, cuts)) def keyCancel(self): self.close((False,)) def baseName(self, str): name = str.split('/')[-1] if name.endswith(".ts") is True: return name[:-3] else: return name def dirName(self, str): return '/'.join(str.split('/')[:-1]) + '/' def rejoinName(self, dir, name): name = name.strip() if name.endswith(".ts") is True: return dir + name[:-3] else: return dir + name
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)
class RecordingSettings(Screen, ConfigListScreen): def removeNotifier(self): if config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.remove(self.levelChanged) def levelChanged(self, configElement): list = [] self.refill(list) self["config"].setList(list) def refill(self, list): xmldata = setupdom().getroot() for x in xmldata.findall("setup"): if x.get("key") != self.setup: continue self.addItems(list, x) self.setup_title = x.get("title", "").encode("UTF-8") self.seperation = int(x.get('separation', '0')) def __init__(self, session): from Components.Sources.StaticText import StaticText Screen.__init__(self, session) self.skinName = "Setup" self['footnote'] = Label() self["HelpWindow"] = Pixmap() self["HelpWindow"].hide() self["VKeyIcon"] = Boolean(False) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) self["description"] = Label(_("")) self.onChangedEntry = [] self.setup = "recording" list = [] ConfigListScreen.__init__(self, list, session=session, on_change=self.changedEntry) self.createSetup() self["setupActions"] = ActionMap( ["SetupActions", "ColorActions", "MenuActions"], { "green": self.keySave, "red": self.keyCancel, "cancel": self.keyCancel, "ok": self.ok, "menu": self.closeRecursive, }, -2) self.onLayoutFinish.append(self.layoutFinished) def checkReadWriteDir(self, configele): # print "checkReadWrite: ", configele.value if configele.value in [x[0] for x in self.styles] or fileExists( configele.value, "w"): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not writable.\nMake sure you select a writable directory instead." ) % dir, type=MessageBox.TYPE_ERROR) return False def createSetup(self): self.styles = [("<default>", _("<Default movie location>")), ("<current>", _("<Current movielist location>")), ("<timer>", _("<Last timer location>"))] styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = config.usage.default_path.value if default not in tmp: tmp = tmp[:] tmp.append(default) # print "DefaultPath: ", default, tmp self.default_dirname = ConfigSelection(default=default, choices=tmp) tmp = config.movielist.videodirs.value default = config.usage.timer_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) # print "TimerPath: ", default, tmp self.timer_dirname = ConfigSelection(default=default, choices=self.styles + tmp) tmp = config.movielist.videodirs.value default = config.usage.instantrec_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) # print "InstantrecPath: ", default, tmp self.instantrec_dirname = ConfigSelection(default=default, choices=self.styles + tmp) self.default_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timer_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.instantrec_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) list = [] if config.usage.setup_level.index >= 2: self.default_entry = getConfigListEntry( _("Default movie location"), self.default_dirname, _("Set the default location for your recordings. Press 'OK' to add new locations, select left/right to select an existing location." )) list.append(self.default_entry) self.timer_entry = getConfigListEntry( _("Timer recording location"), self.timer_dirname, _("Set the default location for your timers. Press 'OK' to add new locations, select left/right to select an existing location." )) list.append(self.timer_entry) self.instantrec_entry = getConfigListEntry( _("Instant recording location"), self.instantrec_dirname, _("Set the default location for your instant recordings. Press 'OK' to add new locations, select left/right to select an existing location." )) list.append(self.instantrec_entry) else: self.default_entry = getConfigListEntry( _("Movie location"), self.default_dirname, _("Set the default location for your recordings. Press 'OK' to add new locations, select left/right to select an existing location." )) list.append(self.default_entry) self.refill(list) self["config"].setList(list) if config.usage.sort_settings.value: self["config"].list.sort() def layoutFinished(self): self.setTitle(_(self.setup_title)) # for summary: def changedEntry(self): self.item = self["config"].getCurrent() if self["config"].getCurrent( )[0] == _("Default movie location") or self["config"].getCurrent( )[0] == _("Timer record location") or self["config"].getCurrent( )[0] == _("Instant record location") or self["config"].getCurrent( )[0] == _("Movie location"): self.checkReadWriteDir(self["config"].getCurrent()[1]) for x in self.onChangedEntry: x() try: if isinstance(self["config"].getCurrent()[1], ConfigYesNo) or isinstance( self["config"].getCurrent()[1], ConfigSelection): self.createSetup() except: pass 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 getCurrentDescription(self): return self["config"].getCurrent() and len(self["config"].getCurrent( )) > 2 and self["config"].getCurrent()[2] or "" def ok(self): currentry = self["config"].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value self.lastautorecorddirs = config.usage.allowed_autorecord_paths.value if config.usage.setup_level.index >= 2: txt = _("Default movie location") else: txt = _("Movie location") if currentry == self.default_entry: self.entrydirname = self.default_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, txt, preferredPath(self.default_dirname.value)) elif currentry == self.timer_entry: self.entrydirname = self.timer_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("New timers location"), preferredPath(self.timer_dirname.value)) elif currentry == self.instantrec_entry: self.entrydirname = self.instantrec_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Instant recordings location"), preferredPath(self.instantrec_dirname.value)) def dirnameSelected(self, res): if res is not None: self.entrydirname.value = res if config.movielist.videodirs.value != self.lastvideodirs: styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = self.default_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.default_dirname.setChoices(tmp, default=default) tmp = config.movielist.videodirs.value default = self.timer_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.timer_dirname.setChoices(self.styles + tmp, default=default) tmp = config.movielist.videodirs.value default = self.instantrec_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.instantrec_dirname.setChoices(self.styles + tmp, default=default) self.entrydirname.value = res if self.entrydirname.last_value != res: self.checkReadWriteDir(self.entrydirname) def saveAll(self): currentry = self["config"].getCurrent() config.usage.default_path.value = self.default_dirname.value config.usage.timer_path.value = self.timer_dirname.value config.usage.instantrec_path.value = self.instantrec_dirname.value config.usage.default_path.save() config.usage.timer_path.save() config.usage.instantrec_path.save() for x in self["config"].list: x[1].save() configfile.save() # keySave and keyCancel are just provided in case you need them. # you have to call them by yourself. def keySave(self): self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self["config"].list: x[1].cancel() self.close() def keyCancel(self): if self["config"].isChanged(): self.session.openWithCallback( self.cancelConfirm, MessageBox, _("Really close without saving settings?"), default=False) else: self.close() def createSummary(self): return SetupSummary def addItems(self, list, parentNode): for x in parentNode: if not x.tag: continue if x.tag == 'item': item_level = int(x.get("level", 0)) if not self.levelChanged in config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.append( self.levelChanged) self.onClose.append(self.removeNotifier) if item_level > config.usage.setup_level.index: continue requires = x.get("requires") if requires and requires.startswith('config.'): item = eval(requires or "") if item.value and not item.value == "0": SystemInfo[requires] = True else: SystemInfo[requires] = False if requires and not SystemInfo.get(requires, False): continue item_text = _(x.get("text", "??").encode("UTF-8")) item_description = _(x.get("description", " ").encode("UTF-8")) b = eval(x.text or "") if b == "": continue #add to configlist item = b # the first b is the item itself, ignored by the configList. # the second one is converted to string. if not isinstance(item, ConfigNothing): list.append((item_text, item, item_description))
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 self.timerentry_justplay = ConfigSelection(choices = [("zap", _("zap")), ("record", _("record"))], default = {0: "record", 1: "zap"}[justplay]) self.timerentry_afterevent = ConfigSelection(choices = [("nothing", _("do nothing")), ("standby", _("go to standby")), ("deepstandby", _("go to deep standby")), ("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) default = self.timer.dirname or resolveFilename(SCOPE_HDD) 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(_("StartTime"), self.timerentry_starttime) self.list.append(self.entryStartTime) if self.timerentry_justplay.value != "zap": self.entryEndTime = getConfigListEntry(_("EndTime"), self.timerentry_endtime) self.list.append(self.entryEndTime) else: self.entryEndTime = None 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[widget].list = self.list self[widget].l.setList(self.list) def newConfig(self): print "newConfig", self["config"].getCurrent() if self["config"].getCurrent() == self.timerTypeEntry: self.createSetup("config") if self["config"].getCurrent() == self.timerJustplayEntry: self.createSetup("config") if self["config"].getCurrent() == self.frequencyEntry: 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 ) 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 keyGo(self): self.timer.name = self.timerentry_name.value self.timer.description = self.timerentry_description.value self.timer.justplay = self.timerentry_justplay.value == "zap" 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 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.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)) 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)
class RecordingSettings(Screen, ConfigListScreen): def removeNotifier(self): if config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.remove(self.levelChanged) def levelChanged(self, configElement): list = [] self.refill(list) self['config'].setList(list) def refill(self, list): xmldata = setupdom().getroot() for x in xmldata.findall('setup'): if x.get('key') != self.setup: continue self.addItems(list, x) self.setup_title = x.get('title', '').encode('UTF-8') self.seperation = int(x.get('separation', '0')) def __init__(self, session): from Components.Sources.StaticText import StaticText Screen.__init__(self, session) self.skinName = 'Setup' self['footnote'] = Label() self['HelpWindow'] = Pixmap() self['HelpWindow'].hide() self['VKeyIcon'] = Boolean(False) self['key_red'] = StaticText(_('Cancel')) self['key_green'] = StaticText(_('Save')) self['description'] = Label(_('')) self.onChangedEntry = [] self.setup = 'recording' list = [] ConfigListScreen.__init__(self, list, session=session, on_change=self.changedEntry) self.createSetup() self['setupActions'] = ActionMap( ['SetupActions', 'ColorActions', 'MenuActions'], { 'green': self.keySave, 'red': self.keyCancel, 'cancel': self.keyCancel, 'ok': self.ok, 'menu': self.closeRecursive }, -2) self.onLayoutFinish.append(self.layoutFinished) def checkReadWriteDir(self, configele): if configele.value in [x[0] for x in self.styles] or fileExists( configele.value, 'w'): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _('The directory %s is not writable.\nMake sure you select a writable directory instead.' ) % dir, type=MessageBox.TYPE_ERROR) return False def createSetup(self): self.styles = [('<default>', _('<Default movie location>')), ('<current>', _('<Current movielist location>')), ('<timer>', _('<Last timer location>'))] styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = config.usage.default_path.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.default_dirname = ConfigSelection(default=default, choices=tmp) tmp = config.movielist.videodirs.value default = config.usage.timer_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.timer_dirname = ConfigSelection(default=default, choices=self.styles + tmp) tmp = config.movielist.videodirs.value default = config.usage.instantrec_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.instantrec_dirname = ConfigSelection(default=default, choices=self.styles + tmp) self.default_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timer_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.instantrec_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) list = [] if config.usage.setup_level.index >= 2: self.default_entry = getConfigListEntry( _('Default movie location'), self.default_dirname, _("Set the default location for your recordings. Press 'OK' to add new locations, select left/right to select an existing location." )) list.append(self.default_entry) self.timer_entry = getConfigListEntry( _('Timer recording location'), self.timer_dirname, _("Set the default location for your timers. Press 'OK' to add new locations, select left/right to select an existing location." )) list.append(self.timer_entry) self.instantrec_entry = getConfigListEntry( _('Instant recording location'), self.instantrec_dirname, _("Set the default location for your instant recordings. Press 'OK' to add new locations, select left/right to select an existing location." )) list.append(self.instantrec_entry) else: self.default_entry = getConfigListEntry( _('Movie location'), self.default_dirname, _("Set the default location for your recordings. Press 'OK' to add new locations, select left/right to select an existing location." )) list.append(self.default_entry) self.refill(list) self['config'].setList(list) if config.usage.sort_settings.value: self['config'].list.sort() def layoutFinished(self): self.setTitle(_(self.setup_title)) def changedEntry(self): self.item = self['config'].getCurrent() if self['config'].getCurrent( )[0] == _('Default movie location') or self['config'].getCurrent( )[0] == _('Timer record location') or self['config'].getCurrent( )[0] == _('Instant record location') or self['config'].getCurrent( )[0] == _('Movie location'): self.checkReadWriteDir(self['config'].getCurrent()[1]) for x in self.onChangedEntry: x() try: if isinstance(self['config'].getCurrent()[1], ConfigYesNo) or isinstance( self['config'].getCurrent()[1], ConfigSelection): self.createSetup() except: pass 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 getCurrentDescription(self): return self['config'].getCurrent() and len(self['config'].getCurrent( )) > 2 and self['config'].getCurrent()[2] or '' def ok(self): currentry = self['config'].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value self.lastautorecorddirs = config.usage.allowed_autorecord_paths.value if config.usage.setup_level.index >= 2: txt = _('Default movie location') else: txt = _('Movie location') if currentry == self.default_entry: self.entrydirname = self.default_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, txt, preferredPath(self.default_dirname.value)) elif currentry == self.timer_entry: self.entrydirname = self.timer_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _('New timers location'), preferredPath(self.timer_dirname.value)) elif currentry == self.instantrec_entry: self.entrydirname = self.instantrec_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _('Instant recordings location'), preferredPath(self.instantrec_dirname.value)) def dirnameSelected(self, res): if res is not None: self.entrydirname.value = res if config.movielist.videodirs.value != self.lastvideodirs: styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = self.default_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.default_dirname.setChoices(tmp, default=default) tmp = config.movielist.videodirs.value default = self.timer_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.timer_dirname.setChoices(self.styles + tmp, default=default) tmp = config.movielist.videodirs.value default = self.instantrec_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.instantrec_dirname.setChoices(self.styles + tmp, default=default) self.entrydirname.value = res if self.entrydirname.last_value != res: self.checkReadWriteDir(self.entrydirname) return def saveAll(self): currentry = self['config'].getCurrent() config.usage.default_path.value = self.default_dirname.value config.usage.timer_path.value = self.timer_dirname.value config.usage.instantrec_path.value = self.instantrec_dirname.value config.usage.default_path.save() config.usage.timer_path.save() config.usage.instantrec_path.save() for x in self['config'].list: x[1].save() configfile.save() def keySave(self): self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self['config'].list: x[1].cancel() self.close() def keyCancel(self): if self['config'].isChanged(): self.session.openWithCallback( self.cancelConfirm, MessageBox, _('Really close without saving settings?'), default=False) else: self.close() def createSummary(self): return SetupSummary def addItems(self, list, parentNode): for x in parentNode: if not x.tag: continue if x.tag == 'item': item_level = int(x.get('level', 0)) if self.levelChanged not in config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.append( self.levelChanged) self.onClose.append(self.removeNotifier) if item_level > config.usage.setup_level.index: continue requires = x.get('requires') if requires and requires.startswith('config.'): item = eval(requires or '') if item.value and not item.value == '0': SystemInfo[requires] = True else: SystemInfo[requires] = False if requires and not SystemInfo.get(requires, False): continue item_text = _(x.get('text', '??').encode('UTF-8')) item_description = _(x.get('description', ' ').encode('UTF-8')) b = eval(x.text or '') if b == '': continue item = b if not isinstance(item, ConfigNothing): list.append((item_text, item, item_description))
class EPGPathsSetup(Screen, ConfigListScreen): def removeNotifier(self): if config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.remove(self.levelChanged) def levelChanged(self, configElement): list = [] self.refill(list) self["config"].setList(list) def refill(self, list): xmldata = setupdom().getroot() for x in xmldata.findall("setup"): if x.get("key") != self.setup: continue self.addItems(list, x) self.setup_title = x.get("title", "").encode("UTF-8") self.seperation = int(x.get('separation', '0')) def __init__(self, session): Screen.__init__(self, session) self.skinName = "Setup" self['footnote'] = Label() self["HelpWindow"] = Pixmap() self["HelpWindow"].hide() self["VKeyIcon"] = Boolean(False) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) self["description"] = Label(_("")) self.onChangedEntry = [] self.setup = "epgsettings" list = [] ConfigListScreen.__init__(self, list, session=session, on_change=self.changedEntry) self.createSetup() self["setupActions"] = ActionMap( ["SetupActions", "ColorActions", "MenuActions"], { "green": self.keySave, "red": self.keyCancel, "cancel": self.keyCancel, "ok": self.ok, "menu": self.closeRecursive, }, -2) self.onLayoutFinish.append(self.layoutFinished) def checkReadWriteDir(self, configele): print "checkReadWrite: ", configele.value if configele.value in [x[0] for x in self.styles] or fileExists( configele.value, "w"): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not writable.\nMake sure you select a writable directory instead." ) % dir, type=MessageBox.TYPE_ERROR) return False def createSetup(self): self.styles = hddchoises styles_keys = [x[0] for x in self.styles] tmp = config.misc.allowed_epgcachepath.value default = config.misc.epgcachepath.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print "EPG Location Path: ", default, tmp self.epg_dirname = ConfigSelection(default=default, choices=self.styles + tmp) #self.epg_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) list = [] if config.usage.setup_level.index >= 2: self.epg_entry = getConfigListEntry( _("EPG location"), self.epg_dirname, _("Choose the location where the EPG data will be stored when the %s %s is shut down. The location must be available at boot time." ) % (getMachineBrand(), getMachineName())) list.append(self.epg_entry) self.refill(list) self["config"].setList(list) if config.usage.sort_settings.value: self["config"].list.sort() def layoutFinished(self): self.setTitle(_(self.setup_title)) # for summary: def changedEntry(self): self.item = self["config"].getCurrent() if self["config"].getCurrent()[0] == _("EPG location"): self.checkReadWriteDir(self["config"].getCurrent()[1]) for x in self.onChangedEntry: x() config.misc.epgcachepath.value = self.epg_dirname.value config.misc.epgcachepath.save() try: if isinstance(self["config"].getCurrent()[1], ConfigYesNo) or isinstance( self["config"].getCurrent()[1], ConfigSelection): self.createSetup() except: pass 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 getCurrentDescription(self): return self["config"].getCurrent() and len(self["config"].getCurrent( )) > 2 and self["config"].getCurrent()[2] or "" def ok(self): currentry = self["config"].getCurrent() if currentry == self.epg_entry: self.entrydirname = self.epg_dirname config.misc.epgcachepath.value = self.epg_dirname.value self.session.openWithCallback(self.dirnameSelected, EPGLocationBox) def dirnameSelected(self, res): if res is not None: self.entrydirname.value = res currentry = self["config"].getCurrent() if currentry == self.epg_entry: styles_keys = [x[0] for x in self.styles] tmp = config.misc.allowed_epgcachepath.value default = self.epg_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.epg_dirname.setChoices(self.styles + tmp, default=default) self.entrydirname.value = res def saveAll(self): currentry = self["config"].getCurrent() config.misc.epgcachepath.value = self.epg_dirname.value config.misc.epgcachepath.save() for x in self["config"].list: x[1].save() configfile.save() # keySave and keyCancel are just provided in case you need them. # you have to call them by yourself. def keySave(self): self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self["config"].list: x[1].cancel() self.close() def keyCancel(self): if self["config"].isChanged(): self.session.openWithCallback( self.cancelConfirm, MessageBox, _("Really close without saving settings?"), default=False) else: self.close() def createSummary(self): return SetupSummary def addItems(self, list, parentNode): for x in parentNode: if not x.tag: continue if x.tag == 'item': item_level = int(x.get("level", 0)) item_rectunerlevel = int(x.get("rectunerlevel", 0)) if not self.levelChanged in config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.append( self.levelChanged) self.onClose.append(self.removeNotifier) if item_level > config.usage.setup_level.index: continue requires = x.get("requires") if requires and requires.startswith('config.'): try: item = eval(requires or "") except: continue if item.value and not item.value == "0": SystemInfo[requires] = True else: SystemInfo[requires] = False if requires and not SystemInfo.get(requires, False): continue item_text = _(x.get("text", "??").encode("UTF-8")) item_description = _(x.get("description", " ").encode("UTF-8")) item_text = item_text.replace( "%s %s", "%s %s" % (getMachineBrand(), getMachineName())) item_description = item_description.replace( "%s %s", "%s %s" % (getMachineBrand(), getMachineName())) try: b = eval(x.text or "") except: b = "" if b == "": continue #add to configlist item = b # the first b is the item itself, ignored by the configList. # the second one is converted to string. if not isinstance(item, ConfigNothing): list.append((item_text, item, item_description))
class RecordPathsSettings(Screen, ConfigListScreen): def __init__(self, session): from Components.Sources.StaticText import StaticText Screen.__init__(self, session) self.skinName = "RecordPathsSettings" self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) self["key_yellow"] = StaticText() self["key_blue"] = StaticText() self["introduction"] = StaticText() ConfigListScreen.__init__(self, []) self.initConfigList() self["setupActions"] = ActionMap( ["SetupActions", "ColorActions"], { "green": self.save, "red": self.cancel, "cancel": self.cancel, "ok": self.ok, }, -2) def checkReadWriteDir(self, configele): print("checkReadWrite: ", configele.value) if configele.value in [x[0] for x in self.styles] or configele.value in [ x[0] for x in self.storage_styles ] or fileExists(configele.value, "w"): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not writable.\nMake sure you select a writable directory instead." ) % dir, type=MessageBox.TYPE_ERROR) return False def initConfigList(self): self.styles = [("<default>", _("<Default movie location>")), ("<current>", _("<Current movielist location>")), ("<timer>", _("<Last timer location>"))] styles_keys = [x[0] for x in self.styles] mountpoints = [(p.mountpoint, p.description) for p in harddiskmanager.getConfiguredStorageDevices() if p.isInitialized] mountpoints.sort(reverse=True) self.storage_styles = [("<undefined>", _("<No default storage device selected.>"))] self.storage_styles += mountpoints storage_styles_keys = [x[0] for x in self.storage_styles] default = defaultStorageDevice() if default not in storage_styles_keys: p = harddiskmanager.getDefaultStorageDevicebyUUID(default) if p is not None: default = p.mountpoint if p.mountpoint not in storage_styles_keys: self.storage_styles.append((p.mountpoint, p.description)) else: cfg_uuid = config.storage.get(default, None) if cfg_uuid is not None: if cfg_uuid["enabled"].value: default = cfg_uuid["mountpoint"].value if default not in storage_styles_keys: description = cfg_uuid[ "device_description"].value.split()[0] or "" description += " ( " + _("Offline") + " )" self.storage_styles.append((default, description)) else: default = "<undefined>" else: default = "<undefined>" print("DefaultDevice: ", default, self.storage_styles) self.default_device = ConfigSelection(default=default, choices=self.storage_styles) tmp = config.movielist.videodirs.value default = config.usage.default_path.value if default not in tmp: tmp = tmp[:] tmp.append(default) print("DefaultPath: ", default, tmp) self.default_dirname = ConfigSelection(default=default, choices=tmp) tmp = config.movielist.videodirs.value default = config.usage.timer_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print("TimerPath: ", default, tmp) self.timer_dirname = ConfigSelection(default=default, choices=self.styles + tmp) tmp = config.movielist.videodirs.value default = config.usage.instantrec_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print("InstantrecPath: ", default, tmp) self.instantrec_dirname = ConfigSelection(default=default, choices=self.styles + tmp) default = config.usage.timeshift_path.value tmp = config.usage.allowed_timeshift_paths.value if default not in tmp: tmp = tmp[:] tmp.append(default) print("TimeshiftPath: ", default, tmp) self.timeshift_dirname = ConfigSelection(default=default, choices=tmp) self.timeshift_dirname.last_value = self.timeshift_dirname.value self.default_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.default_dirname.last_value = self.default_dirname.value self.timer_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timer_dirname.last_value = self.timer_dirname.value self.instantrec_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.instantrec_dirname.last_value = self.instantrec_dirname.value self.timeshift_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timeshift_dirname.last_value = self.timeshift_dirname.value self.list = [] self.device_entry = getConfigListEntry(_("Default storage device"), self.default_device) self.list.append(self.device_entry) if config.usage.setup_level.index >= 2: self.default_entry = getConfigListEntry( _("Default movie location"), self.default_dirname) self.list.append(self.default_entry) self.timer_entry = getConfigListEntry(_("Timer record location"), self.timer_dirname) self.list.append(self.timer_entry) self.instantrec_entry = getConfigListEntry( _("Instant record location"), self.instantrec_dirname) self.list.append(self.instantrec_entry) else: self.default_entry = getConfigListEntry(_("Movie location"), self.default_dirname) self.list.append(self.default_entry) self.timeshift_entry = getConfigListEntry(_("Timeshift location"), self.timeshift_dirname) self.list.append(self.timeshift_entry) self["config"].setList(self.list) if not self.selectionChanged in self["config"].onSelectionChanged: self["config"].onSelectionChanged.append(self.selectionChanged) def selectionChanged(self): currentry = self["config"].getCurrent() if currentry == self.device_entry: self["introduction"].setText( _("Please select the default storage device you want to use for recordings. This device gets mounted to /media/hdd." )) elif currentry == self.default_entry: self["introduction"].setText( _("Please select the default movielist location which is used for recordings." )) elif currentry == self.timeshift_entry: self["introduction"].setText( _("Please select the timeshift location which is used for storing timeshift recordings." )) if config.usage.setup_level.index >= 2: if currentry == self.timer_entry: self["introduction"].setText( _("Please select the default timer record location which is used for timer based recordings." )) elif currentry == self.instantrec_entry: self["introduction"].setText( _("Please select the default instant record location which is used for instant recordings." )) def ok(self): currentry = self["config"].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value if config.usage.setup_level.index >= 2: txt = _("Default movie location") else: txt = _("Movie location") if currentry == self.default_entry: self.entrydirname = self.default_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, txt, preferredPath(self.default_dirname.value)) elif currentry == self.timeshift_entry: self.entrydirname = self.timeshift_dirname config.usage.timeshift_path.value = self.timeshift_dirname.value self.session.openWithCallback(self.dirnameSelected, TimeshiftLocationBox) if config.usage.setup_level.index >= 2: if currentry == self.timer_entry: self.entrydirname = self.timer_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Initial location in new timers"), preferredPath(self.timer_dirname.value)) elif currentry == self.instantrec_entry: self.entrydirname = self.instantrec_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Location for instant recordings"), preferredPath(self.instantrec_dirname.value)) def dirnameSelected(self, res): if res is not None: self.entrydirname.value = res if config.movielist.videodirs.value != self.lastvideodirs: styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = self.default_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.default_dirname.setChoices(tmp, default=default) tmp = config.movielist.videodirs.value default = self.timer_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.timer_dirname.setChoices(self.styles + tmp, default=default) tmp = config.movielist.videodirs.value default = self.instantrec_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.instantrec_dirname.setChoices(self.styles + tmp, default=default) self.entrydirname.value = res if config.usage.allowed_timeshift_paths.value != self.lasttimeshiftdirs: tmp = config.usage.allowed_timeshift_paths.value default = self.instantrec_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.timeshift_dirname.setChoices(tmp, default=default) self.entrydirname.value = res if self.entrydirname.last_value != res: self.checkReadWriteDir(self.entrydirname) def save(self): currentry = self["config"].getCurrent() defaultChanged = None if self.checkReadWriteDir(currentry[1]): config.usage.default_path.value = self.default_dirname.value config.usage.timer_path.value = self.timer_dirname.value config.usage.instantrec_path.value = self.instantrec_dirname.value config.usage.timeshift_path.value = self.timeshift_dirname.value config.usage.default_path.save() config.usage.timer_path.save() config.usage.instantrec_path.save() config.usage.timeshift_path.save() if self.default_device.value != "/media/hdd": if self.default_device.value != "<undefined>": #changing default ? tmp = harddiskmanager.getPartitionbyMountpoint( self.default_device.value) if tmp is not None: defaultChanged = harddiskmanager.changeStorageDevice( tmp.uuid, "mount_default", None) else: #disabling default ? p = harddiskmanager.getDefaultStorageDevicebyUUID( defaultStorageDevice()) if p is not None: defaultChanged = harddiskmanager.changeStorageDevice( defaultStorageDevice(), "unmount", None) if defaultChanged is None: self.close() elif defaultChanged is False: self.session.open( MessageBox, _("There was en error while configuring your storage device." ), MessageBox.TYPE_ERROR) else: self.close() def cancel(self): self.close()
class VcsSetupScreen(Screen, ConfigListScreen): skin = """ <screen name="VcsSetupScreen" position="center,center" size="620,470" title="%s" > <ePixmap pixmap="skin_default/buttons/red.png" position="10,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="150,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="290,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/blue.png" position="430,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/key_info.png" position="580,5" zPosition="1" size="35,25" alphatest="on" /> <widget name="key_red" position="10,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget name="key_green" position="150,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget name="key_yellow" position="290,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" /> <widget name="key_blue" position="430,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" /> <widget name="config" position="10,45" size="600,175" scrollbarMode="showOnDemand" zPosition="1" /> <widget source="profiles" render="Listbox" position="10,220" size="600,230" zPosition="1" > <convert type="TemplatedMultiContent"> {"templates": {"default": (45, [ MultiContentEntryText(pos=(50, 0), size=(200, 45), font=0, flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER|RT_WRAP, text=1), MultiContentEntryText(pos=(260, 0), size=(320, 45), font=1, flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER|RT_WRAP, text=2), MultiContentEntryPixmapAlphaTest(pos=(12, 9), size=(25, 24), png=3), ], True, "showOnDemand"), "notselected": (45, [ MultiContentEntryText(pos=(50, 0), size=(200, 45), font=0, flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER|RT_WRAP, text=1), MultiContentEntryText(pos=(260, 0), size=(320, 45), font=1, flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER|RT_WRAP, text=2), MultiContentEntryPixmapAlphaTest(pos=(12, 9), size=(25, 24), png=3), ], False, "showOnDemand") }, "fonts": [gFont("Regular", 24), gFont("Regular", 18)], "itemHeight": 45, "scrollbarMode": "showOnDemand", } </convert> </widget> </screen>""" % (_('%s: video clipping switcher')%(PLUGIN_NAME)) FOCUS_CONFIG, FOCUS_LIST = range(2) def __init__(self, session): Screen.__init__(self, session) for btn in ("red","green","yellow","blue"): self["key_" + btn] = Button(" ") ConfigListScreen.__init__(self, []) self.defprofile = ConfigSelection([]) self.updateConfigList() self.pfsList = [] self["profiles"] = List(self.pfsList) self.updateProfileList() self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions", "ChannelSelectEPGActions"], { "cancel": self.keyExit, "ok": self.keyOk, "showEPGList": self.showExamples, "red": self.keyRed, "green": self.keyGreen, "yellow": boundFunction(self.moveEntry, -1), "blue": boundFunction(self.moveEntry, +1), "up": self.keyUp, "down": self.keyDown, }, -1) self.onClose.append(self.__closed) self.onLayoutFinish.append(self.__layoutFinished) self.onShown.append(self.updateButtonState) self.prev_ext_menu = config.plugins.VCS.ext_menu.value def __layoutFinished(self): self["config"].instance.setSelectionEnable(True) self["profiles"].style = "notselected" self.focus = self.FOCUS_CONFIG self["profiles"].onSelectionChanged.append(self.updateButtonState) def __closed(self): for x in self["config"].list: if x[1] == self.defprofile: config.plugins.VCS.default.value = self.defprofile.value config.plugins.VCS.default.save() continue x[1].save() def updateButtonState(self): self["key_green"].setText(_("Add")) if self.focus == self.FOCUS_LIST: cur = self["profiles"].getCurrent() if cur: self["key_red"].setText(_("Delete")) self["key_yellow"].setText(self["profiles"].index > 0 and _("Move Up") or " ") self["key_blue"].setText(self["profiles"].index < len(self.pfsList)-1 and _("Move Down") or " ") else: for btn in ("key_red","key_yellow","key_blue"): self[btn].setText(" ") else: self["key_red"].setText(_("Exit")) self["key_yellow"].setText(" ") self["key_blue"].setText(" ") def updateConfigList(self): pfslist = [ (-1,_("None")) ] pfs = config.plugins.VCS.profiles for x in range(len(pfs)): pfslist.append((x, pfs[x].name.value)) default = not config.plugins.VCS.default.value in range(len(pfs)) and -1 or config.plugins.VCS.default.value self.defprofile.setChoices(pfslist, default=default) cfglist = [ getConfigListEntry(_("Plugin quick button(s)"), config.plugins.VCS.hotkey), getConfigListEntry(_("Quick button(s) action"), config.plugins.VCS.hkaction), getConfigListEntry(_("Show \"Choise list\" in extensions menu"), config.plugins.VCS.ext_menu), getConfigListEntry(_("Message timeout on switch profiles"), config.plugins.VCS.msgtime), getConfigListEntry(_("Default profile on enigma startup"), self.defprofile), ] if fileExists("/usr/lib/enigma2/python/Screens/DVD.pyo"): cfglist.append(getConfigListEntry(_('Add \"Choise list\" Blue Button to DVDPlayer'), config.plugins.VCS.dvd_menu)) if fileExists("/usr/lib/enigma2/python/Plugins/Extensions/MediaPlayer/plugin.pyo") or fileExists("/usr/lib/enigma2/python/Plugins/Extensions/MediaPlayer/plugin.pyc"): cfglist.append(getConfigListEntry(_('Add \"Choise list\" Blue Button to MediaPlayer'), config.plugins.VCS.media_player)) self["config"].list = cfglist self["config"].setList(cfglist) def updateProfileList(self): list = [] pfs = config.plugins.VCS.profiles for x in range(len(pfs)): s = "%s %s" % (getAspectString(pfs[x].aspect.value), pfs[x].cliprect.value) path = "skin_default/icons/lock_%s.png"%(pfs[x].enabled.value and "on" or "off") png = LoadPixmap(resolveFilename(SCOPE_SKIN, path)) list.append((pfs[x], pfs[x].name.value, s, png)) self.pfsList = list self["profiles"].setList(self.pfsList) def getUniqProfileName(self, name=_("Profile "), suffix=1): x = 0 uname = "%s%d" % (name, suffix) pfs = config.plugins.VCS.profiles while x < config.plugins.VCS.pfs_count.value: if pfs[x].name.value == uname: x = -1 suffix += 1 uname = "%s%d" % (name, suffix) x += 1 return uname def addEntry(self): self.session.openWithCallback(self.addCallback, VcsProfileSetup, InitVcsProfile(name=self.getUniqProfileName())) def addCallback(self, result, profile): if result: pfs = config.plugins.VCS.profiles idx = config.plugins.VCS.pfs_count.value if profile.name.value == "": profile.name.value = self.getUniqProfileName() profile.name.save() pfs.append(profile) config.plugins.VCS.pfs_count.value = len(pfs) config.plugins.VCS.pfs_count.save() self.updateProfileList() self["profiles"].index = idx self.updateConfigList() self.updateButtonState() else: del profile def editEntry(self): idx = self["profiles"].index if idx < len(self.pfsList): pfs = config.plugins.VCS.profiles self.session.openWithCallback(self.editCallback, VcsProfileSetup, pfs[idx]) def editCallback(self, result, profile): if result: pfs = config.plugins.VCS.profiles idx = self["profiles"].index if profile.name.value == "": profile.name.value = self.getUniqProfileName() profile.name.save() self.updateProfileList() self["profiles"].index = idx self.updateButtonState() def deleteEntry(self): cur = self["profiles"].getCurrent() if cur: self.session.openWithCallback(self.deleteCallback, MessageBox, _("Do you really want to delete profile:\n %s") % (cur[1]), MessageBox.TYPE_YESNO) def deleteCallback(self, yesno): if yesno: idx = self["profiles"].index pfs = config.plugins.VCS.profiles pfs.remove(pfs[idx]) pfs.saved_value = pfs.saved_value config.plugins.VCS.pfs_count.value = len(pfs) config.plugins.VCS.pfs_count.save() self.updateProfileList() if len(pfs): if idx >= len(pfs): self["profiles"].index = len(pfs)-1 else: self["profiles"].index = idx self.updateConfigList() self.updateButtonState() def moveEntry(self, direction): if self.focus == self.FOCUS_LIST: idx = self["profiles"].index if idx + direction in range(len(self.pfsList)): pfs = config.plugins.VCS.profiles tmp_pf = pfs[idx] pfs[idx] = pfs[idx + direction] pfs[idx + direction] = tmp_pf self.updateProfileList() self["profiles"].index = idx + direction self.updateConfigList() self.updateButtonState() def keyRed(self): if self.focus == self.FOCUS_LIST: self.deleteEntry() else: self.keyExit() def keyExit(self): if self.prev_ext_menu != config.plugins.VCS.ext_menu.value: plugins.readPluginList(resolveFilename(SCOPE_PLUGINS)) self.close() def keyGreen(self): self.addEntry() def keyOk(self): if self.focus == self.FOCUS_LIST: self.editEntry() def keyUp(self): if self.focus == self.FOCUS_CONFIG: self["config"].instance.moveSelection(self["config"].instance.moveUp) elif self.focus == self.FOCUS_LIST: if self["profiles"].getIndex() == 0: self["config"].instance.setSelectionEnable(True) self["profiles"].style = "notselected" self["config"].setCurrentIndex(len(self["config"].getList())-1) self.focus = self.FOCUS_CONFIG else: self["profiles"].selectPrevious() self.updateButtonState() def keyDown(self): if self.focus == self.FOCUS_CONFIG: if self["config"].getCurrentIndex() < len(self["config"].getList())-1: self["config"].instance.moveSelection(self["config"].instance.moveDown) else: self["config"].instance.setSelectionEnable(False) self["profiles"].style = "default" self.focus = self.FOCUS_LIST elif self.focus == self.FOCUS_LIST: self["profiles"].selectNext() self.updateButtonState() def showExamples(self): if os.path.exists(examples_sh): try: os.chmod(examples_sh, 0755) self.session.open(Console,_("Examples:"),["%s" % examples_sh]) except: pass
class RecordPathsSettings(eRecordPathsSettings): def __init__(self, session): eRecordPathsSettings.__init__(self, session) self.onShown.append(self.__setWindowTitle) def __setWindowTitle(self): self.setTitle(_("Record Paths Settings")) def initConfigList(self): eRecordPathsSettings.initConfigList(self) tmp = config.movielist.videodirs.value default = config.AdvancedMovieSelection.movecopydirs.value if default not in tmp: tmp = tmp[:] tmp.append(default) print "MoveCopyPath: ", default, tmp self.movecopy_dirname = ConfigSelection(default=default, choices=tmp) self.movecopy_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.movecopy_dirname.last_value = config.AdvancedMovieSelection.movecopydirs.value self.movecopy_entry = getConfigListEntry(_("Move/copy location:"), self.movecopy_dirname) self.list.append(self.movecopy_entry) self["config"].setList(self.list) if not self.selectionChanged in self["config"].onSelectionChanged: self["config"].onSelectionChanged.append(self.selectionChanged) def selectionChanged(self): # Topfi: disabled three lines which causes GS #eRecordPathsSettings.selectionChanged(self) currentry = self["config"].getCurrent() #if currentry == self.movecopy_entry: # self["introduction"].setText(_("Please select the default move/copy location which is used for move/copy movies.")) def ok(self): eRecordPathsSettings.ok(self) currentry = self["config"].getCurrent() if currentry == self.movecopy_entry: self.entrydirname = self.movecopy_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Location for move/copy files"), preferredPath(self.movecopy_dirname.value) ) def dirnameSelected(self, res): eRecordPathsSettings.dirnameSelected(self, res) if res is not None: if config.AdvancedMovieSelection.movecopydirs.value != res: tmp = config.movielist.videodirs.value default = config.AdvancedMovieSelection.movecopydirs.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.movecopy_dirname.setChoices(tmp, default=default) def save(self): currentry = self["config"].getCurrent() if self.checkReadWriteDir(currentry[1]): config.AdvancedMovieSelection.movecopydirs.value = self.movecopy_dirname.value config.AdvancedMovieSelection.movecopydirs.save() eRecordPathsSettings.save(self)
class RecordPathsSettings(Screen,ConfigListScreen): def __init__(self, session): from Components.Sources.StaticText import StaticText Screen.__init__(self, session) self.skinName = "RecordPathsSettings" self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) self["key_yellow"] = StaticText() self["key_blue"] = StaticText() self["introduction"] = StaticText() ConfigListScreen.__init__(self, []) self.initConfigList() self["setupActions"] = ActionMap(["SetupActions", "ColorActions"], { "green": self.save, "red": self.cancel, "cancel": self.cancel, "ok": self.ok, }, -2) def checkReadWriteDir(self, configele): print "checkReadWrite: ", configele.value if configele.value in [x[0] for x in self.styles] or configele.value in [x[0] for x in self.storage_styles] or fileExists(configele.value, "w"): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not writable.\nMake sure you select a writable directory instead.")%dir, type = MessageBox.TYPE_ERROR ) return False def initConfigList(self): self.styles = [ ("<default>", _("<Default movie location>")), ("<current>", _("<Current movielist location>")), ("<timer>", _("<Last timer location>")) ] styles_keys = [x[0] for x in self.styles] mountpoints = [ (p.mountpoint, p.description) for p in harddiskmanager.getConfiguredStorageDevices() if p.isInitialized] mountpoints.sort(reverse = True) self.storage_styles = [ ("<undefined>", _("<No default storage device selected.>"))] self.storage_styles += mountpoints storage_styles_keys = [x[0] for x in self.storage_styles] default = defaultStorageDevice() if default not in storage_styles_keys: p = harddiskmanager.getDefaultStorageDevicebyUUID(default) if p is not None: default = p.mountpoint if p.mountpoint not in storage_styles_keys: self.storage_styles.append((p.mountpoint, p.description)) else: cfg_uuid = config.storage.get(default, None) if cfg_uuid is not None: if cfg_uuid["enabled"].value: default = cfg_uuid["mountpoint"].value if default not in storage_styles_keys: description = cfg_uuid["device_description"].value.split()[0] or "" description += " ( " + _("Offline") + " )" self.storage_styles.append((default, description )) else: default = "<undefined>" else: default = "<undefined>" print "DefaultDevice: ", default, self.storage_styles self.default_device = ConfigSelection(default = default, choices = self.storage_styles) tmp = config.movielist.videodirs.value default = config.usage.default_path.value if default not in tmp: tmp = tmp[:] tmp.append(default) print "DefaultPath: ", default, tmp self.default_dirname = ConfigSelection(default = default, choices = tmp) tmp = config.movielist.videodirs.value default = config.usage.timer_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print "TimerPath: ", default, tmp self.timer_dirname = ConfigSelection(default = default, choices = self.styles+tmp) tmp = config.movielist.videodirs.value default = config.usage.instantrec_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print "InstantrecPath: ", default, tmp self.instantrec_dirname = ConfigSelection(default = default, choices = self.styles+tmp) default = config.usage.timeshift_path.value tmp = config.usage.allowed_timeshift_paths.value if default not in tmp: tmp = tmp[:] tmp.append(default) print "TimeshiftPath: ", default, tmp self.timeshift_dirname = ConfigSelection(default = default, choices = tmp) self.timeshift_dirname.last_value = self.timeshift_dirname.value self.default_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.default_dirname.last_value = self.default_dirname.value self.timer_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timer_dirname.last_value = self.timer_dirname.value self.instantrec_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.instantrec_dirname.last_value = self.instantrec_dirname.value self.timeshift_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timeshift_dirname.last_value = self.timeshift_dirname.value self.list = [] self.device_entry = getConfigListEntry(_("Default storage device"), self.default_device) self.list.append(self.device_entry) if config.usage.setup_level.index >= 2: self.default_entry = getConfigListEntry(_("Default movie location"), self.default_dirname) self.list.append(self.default_entry) self.timer_entry = getConfigListEntry(_("Timer record location"), self.timer_dirname) self.list.append(self.timer_entry) self.instantrec_entry = getConfigListEntry(_("Instant record location"), self.instantrec_dirname) self.list.append(self.instantrec_entry) else: self.default_entry = getConfigListEntry(_("Movie location"), self.default_dirname) self.list.append(self.default_entry) self.timeshift_entry = getConfigListEntry(_("Timeshift location"), self.timeshift_dirname) self.list.append(self.timeshift_entry) self["config"].setList(self.list) if not self.selectionChanged in self["config"].onSelectionChanged: self["config"].onSelectionChanged.append(self.selectionChanged) def selectionChanged(self): currentry = self["config"].getCurrent() if currentry == self.device_entry: self["introduction"].setText(_("Please select the default storage device you want to use for recordings. This device gets mounted to /media/hdd.")) elif currentry == self.default_entry: self["introduction"].setText(_("Please select the default movielist location which is used for recordings.")) elif currentry == self.timeshift_entry: self["introduction"].setText(_("Please select the timeshift location which is used for storing timeshift recordings.")) if config.usage.setup_level.index >= 2: if currentry == self.timer_entry: self["introduction"].setText(_("Please select the default timer record location which is used for timer based recordings.")) elif currentry == self.instantrec_entry: self["introduction"].setText(_("Please select the default instant record location which is used for instant recordings.")) def ok(self): currentry = self["config"].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value if config.usage.setup_level.index >= 2: txt = _("Default movie location") else: txt = _("Movie location") if currentry == self.default_entry: self.entrydirname = self.default_dirname self.session.openWithCallback(self.dirnameSelected, MovieLocationBox, txt, preferredPath(self.default_dirname.value)) elif currentry == self.timeshift_entry: self.entrydirname = self.timeshift_dirname config.usage.timeshift_path.value = self.timeshift_dirname.value self.session.openWithCallback(self.dirnameSelected, TimeshiftLocationBox) if config.usage.setup_level.index >= 2: if currentry == self.timer_entry: self.entrydirname = self.timer_dirname self.session.openWithCallback(self.dirnameSelected, MovieLocationBox,_("Initial location in new timers"), preferredPath(self.timer_dirname.value)) elif currentry == self.instantrec_entry: self.entrydirname = self.instantrec_dirname self.session.openWithCallback(self.dirnameSelected, MovieLocationBox, _("Location for instant recordings"), preferredPath(self.instantrec_dirname.value)) def dirnameSelected(self, res): if res is not None: self.entrydirname.value = res if config.movielist.videodirs.value != self.lastvideodirs: styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = self.default_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.default_dirname.setChoices(tmp, default=default) tmp = config.movielist.videodirs.value default = self.timer_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.timer_dirname.setChoices(self.styles+tmp, default=default) tmp = config.movielist.videodirs.value default = self.instantrec_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.instantrec_dirname.setChoices(self.styles+tmp, default=default) self.entrydirname.value = res if config.usage.allowed_timeshift_paths.value != self.lasttimeshiftdirs: tmp = config.usage.allowed_timeshift_paths.value default = self.instantrec_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.timeshift_dirname.setChoices(tmp, default=default) self.entrydirname.value = res if self.entrydirname.last_value != res: self.checkReadWriteDir(self.entrydirname) def save(self): currentry = self["config"].getCurrent() defaultChanged = None if self.checkReadWriteDir(currentry[1]): config.usage.default_path.value = self.default_dirname.value config.usage.timer_path.value = self.timer_dirname.value config.usage.instantrec_path.value = self.instantrec_dirname.value config.usage.timeshift_path.value = self.timeshift_dirname.value config.usage.default_path.save() config.usage.timer_path.save() config.usage.instantrec_path.save() config.usage.timeshift_path.save() if self.default_device.value != "/media/hdd": if self.default_device.value != "<undefined>": #changing default ? tmp = harddiskmanager.getPartitionbyMountpoint(self.default_device.value) if tmp is not None: defaultChanged = harddiskmanager.changeStorageDevice(tmp.uuid, "mount_default", None) else: #disabling default ? p = harddiskmanager.getDefaultStorageDevicebyUUID(defaultStorageDevice()) if p is not None: defaultChanged = harddiskmanager.changeStorageDevice(defaultStorageDevice(), "unmount", None) if defaultChanged is None: self.close() elif defaultChanged is False: self.session.open(MessageBox, _("There was en error while configuring your storage device."), MessageBox.TYPE_ERROR) else: self.close() def cancel(self): self.close()
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)
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)
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 RecordPathsSettings(Screen,ConfigListScreen): skin = """ <screen name="RecordPathsSettings" position="160,150" size="450,290" title="Settings paths"> <ePixmap pixmap="skin_default/buttons/red.png" position="10,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="300,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="10,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render="Label" position="300,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget name="config" position="10,44" size="430,236" /> </screen>""" def __init__(self, session): from Components.Sources.StaticText import StaticText Screen.__init__(self, session) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) ConfigListScreen.__init__(self, []) self.initConfigList() self["setupActions"] = ActionMap(["SetupActions", "ColorActions", "MenuActions"], { "green": self.save, "red": self.keyCancel, "cancel": self.keyCancel, "ok": self.ok, "menu": self.closeRecursive, }, -2) def checkReadWriteDir(self, configele): print "checkReadWrite: ", configele.value if configele.value in [x[0] for x in self.styles] or fileExists(configele.value, "w"): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not writable.\nMake sure you select a writable directory instead.")%dir, type = MessageBox.TYPE_ERROR ) return False def initConfigList(self): self.styles = [ ("<default>", _("<Default movie location>")), ("<current>", _("<Current movielist location>")), ("<timer>", _("<Last timer location>")) ] styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = config.usage.default_path.value if default not in tmp: tmp = tmp[:] tmp.append(default) print "DefaultPath: ", default, tmp self.default_dirname = ConfigSelection(default = default, choices = tmp) tmp = config.movielist.videodirs.value default = config.usage.timer_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print "TimerPath: ", default, tmp self.timer_dirname = ConfigSelection(default = default, choices = self.styles+tmp) tmp = config.movielist.videodirs.value default = config.usage.instantrec_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print "InstantrecPath: ", default, tmp self.instantrec_dirname = ConfigSelection(default = default, choices = self.styles+tmp) default = config.usage.timeshift_path.value tmp = config.usage.allowed_timeshift_paths.value if default not in tmp: tmp = tmp[:] tmp.append(default) print "TimeshiftPath: ", default, tmp self.timeshift_dirname = ConfigSelection(default = default, choices = tmp) default = "/usr/share/enigma2/picon/" try: default = config.misc.picon_path.value except: pass tmp = [ "/usr/share/enigma2/picon/", "/media/usb/picon/", "/media/hdd/picon/" ] if default not in tmp: tmp = tmp[:] tmp.append(default) print "Picon Path: ", default, tmp self.picon_dirname = ConfigSelection(default = default, choices = tmp) default = "/hdd/" try: default = '/'.join(config.misc.epgcache_filename.value.split('/')[:-1])+'/' except: pass tmp = [ "/media/hdd/", "/media/usb/" ] if default not in tmp: tmp = tmp[:] tmp.append(default) print "EPG Path: ", default, tmp self.epg_dirname = ConfigSelection(default = default, choices = tmp) default = "epg.dat" try: default = config.misc.epgcache_filename.value.split("/")[-1] except: pass print "EPG File name: ", default self.epg_filename = ConfigText(default = default) self.default_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timer_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.instantrec_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timeshift_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.epg_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.list = [] if config.usage.setup_level.index >= 2: self.default_entry = getConfigListEntry(_("Default movie location"), self.default_dirname) self.list.append(self.default_entry) self.timer_entry = getConfigListEntry(_("Timer recording location"), self.timer_dirname) self.list.append(self.timer_entry) self.instantrec_entry = getConfigListEntry(_("Instant recording location"), self.instantrec_dirname) self.list.append(self.instantrec_entry) else: self.default_entry = getConfigListEntry(_("Movie location"), self.default_dirname) self.list.append(self.default_entry) self.timeshift_entry = getConfigListEntry(_("Timeshift location"), self.timeshift_dirname) self.list.append(self.timeshift_entry) self.picon_entry = getConfigListEntry(_("Picon location"), self.picon_dirname) self.list.append(self.picon_entry) self.piconHDD_entry = getConfigListEntry(_("Search picons in /media/hdd"), config.misc.picon_search_hdd) self.list.append(self.piconHDD_entry) self.epgdir_entry = getConfigListEntry(_("EPG location"), self.epg_dirname) self.list.append(self.epgdir_entry) self.epgfile_entry = getConfigListEntry(_("EPG file name"), self.epg_filename) self.list.append(self.epgfile_entry) self["config"].setList(self.list) def ok(self): currentry = self["config"].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value if config.usage.setup_level.index >= 2: txt = _("Default movie location") else: txt = _("Movie location") if currentry == self.default_entry: self.entrydirname = self.default_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, txt, preferredPath(self.default_dirname.value) ) elif currentry == self.timer_entry: self.entrydirname = self.timer_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Initial location in new timers"), preferredPath(self.timer_dirname.value) ) elif currentry == self.instantrec_entry: self.entrydirname = self.instantrec_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Location for instant recordings"), preferredPath(self.instantrec_dirname.value) ) elif currentry == self.timeshift_entry: self.entrydirname = self.timeshift_dirname config.usage.timeshift_path.value = self.timeshift_dirname.value self.session.openWithCallback( self.dirnameSelected, TimeshiftLocationBox ) elif currentry == self.picon_entry: self.entrydirname = self.picon_dirname self.session.openWithCallback( self.dirnameSelected, LocationBox, _("Picon location"), currDir =preferredPath(self.picon_dirname.value), ) elif currentry == self.epgdir_entry: self.entrydirname = self.epg_dirname self.session.openWithCallback( self.dirnameSelected, LocationBox, _("EPG location"), currDir =preferredPath(self.epg_dirname.value), ) def dirnameSelected(self, res): if res is not None: self.entrydirname.value = res currentry = self["config"].getCurrent() if currentry == self.picon_entry: tmp = [ "/usr/share/enigma2/picon/", "/usb/picon/", "/hdd/picon/" ] default = res if default not in tmp: tmp = tmp[:] tmp.append(default) self.picon_dirname.setChoices(tmp, default=default) self.entrydirname.value = res if currentry == self.epgdir_entry: tmp = [ "/hdd/", "/usb/" ] default = res if default not in tmp: tmp = tmp[:] tmp.append(default) self.epg_dirname.setChoices(tmp, default=default) self.entrydirname.value = res if config.movielist.videodirs.value != self.lastvideodirs: styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = self.default_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.default_dirname.setChoices(tmp, default=default) tmp = config.movielist.videodirs.value default = self.timer_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.timer_dirname.setChoices(self.styles+tmp, default=default) tmp = config.movielist.videodirs.value default = self.instantrec_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.instantrec_dirname.setChoices(self.styles+tmp, default=default) self.entrydirname.value = res if config.usage.allowed_timeshift_paths.value != self.lasttimeshiftdirs: tmp = config.usage.allowed_timeshift_paths.value default = self.instantrec_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.timeshift_dirname.setChoices(tmp, default=default) self.entrydirname.value = res if self.entrydirname.last_value != res and currentry != self.picon_entry: self.checkReadWriteDir(self.entrydirname) def save(self): currentry = self["config"].getCurrent() save = True if currentry != self.epgfile_entry and currentry != self.picon_entry and currentry != self.piconHDD_entry: save = self.checkReadWriteDir(currentry[1]) if save: config.usage.default_path.value = self.default_dirname.value config.usage.timer_path.value = self.timer_dirname.value config.usage.instantrec_path.value = self.instantrec_dirname.value config.usage.timeshift_path.value = self.timeshift_dirname.value config.misc.picon_path.value = self.picon_dirname.value config.misc.epgcache_filename.value = self.epg_dirname.value + self.epg_filename.value config.usage.default_path.save() config.misc.picon_path.save() config.usage.timer_path.save() config.usage.instantrec_path.save() config.usage.timeshift_path.save() config.misc.epgcache_filename.save() config.misc.picon_search_hdd.save() from Components.Renderer import Picon Picon.setPiconPath() self.close()
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)
class RecordingSettings(Screen, ConfigListScreen): def removeNotifier(self): if config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.remove(self.levelChanged) def levelChanged(self, configElement): list = [] self.refill(list) self['config'].setList(list) def refill(self, list): xmldata = setupdom().getroot() for x in xmldata.findall('setup'): if x.get('key') != self.setup: continue self.addItems(list, x) self.setup_title = x.get('title', '').encode('UTF-8') self.seperation = int(x.get('separation', '0')) def __init__(self, session): from Components.Sources.StaticText import StaticText Screen.__init__(self, session) self.skinName = 'Setup' self['footnote'] = Label() self['HelpWindow'] = Pixmap() self['HelpWindow'].hide() self['VKeyIcon'] = Boolean(False) self['key_red'] = StaticText(_('Cancel')) self['key_green'] = StaticText(_('Save')) self['description'] = Label(_('')) self.onChangedEntry = [] self.setup = 'recording' list = [] ConfigListScreen.__init__(self, list, session=session, on_change=self.changedEntry) self.createSetup() self['setupActions'] = ActionMap(['SetupActions', 'ColorActions', 'MenuActions'], {'green': self.keySave, 'red': self.keyCancel, 'cancel': self.keyCancel, 'ok': self.ok, 'menu': self.closeRecursive}, -2) self.onLayoutFinish.append(self.layoutFinished) def checkReadWriteDir(self, configele): if configele.value in [ x[0] for x in self.styles ] or fileExists(configele.value, 'w'): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open(MessageBox, _('The directory %s is not writable.\nMake sure you select a writable directory instead.') % dir, type=MessageBox.TYPE_ERROR) return False def createSetup(self): self.styles = [('<default>', _('<Default movie location>')), ('<current>', _('<Current movielist location>')), ('<timer>', _('<Last timer location>'))] styles_keys = [ x[0] for x in self.styles ] tmp = config.movielist.videodirs.value default = config.usage.default_path.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.default_dirname = ConfigSelection(default=default, choices=tmp) tmp = config.movielist.videodirs.value default = config.usage.timer_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.timer_dirname = ConfigSelection(default=default, choices=self.styles + tmp) tmp = config.movielist.videodirs.value default = config.usage.instantrec_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.instantrec_dirname = ConfigSelection(default=default, choices=self.styles + tmp) self.default_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timer_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.instantrec_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) list = [] if config.usage.setup_level.index >= 2: self.default_entry = getConfigListEntry(_('Default movie location'), self.default_dirname, _("Set the default location for your recordings. Press 'OK' to add new locations, select left/right to select an existing location.")) list.append(self.default_entry) self.timer_entry = getConfigListEntry(_('Timer recording location'), self.timer_dirname, _("Set the default location for your timers. Press 'OK' to add new locations, select left/right to select an existing location.")) list.append(self.timer_entry) self.instantrec_entry = getConfigListEntry(_('Instant recording location'), self.instantrec_dirname, _("Set the default location for your instant recordings. Press 'OK' to add new locations, select left/right to select an existing location.")) list.append(self.instantrec_entry) else: self.default_entry = getConfigListEntry(_('Movie location'), self.default_dirname, _("Set the default location for your recordings. Press 'OK' to add new locations, select left/right to select an existing location.")) list.append(self.default_entry) self.refill(list) self['config'].setList(list) if config.usage.sort_settings.value: self['config'].list.sort() def layoutFinished(self): self.setTitle(_(self.setup_title)) def changedEntry(self): self.item = self['config'].getCurrent() if self['config'].getCurrent()[0] == _('Default movie location') or self['config'].getCurrent()[0] == _('Timer record location') or self['config'].getCurrent()[0] == _('Instant record location') or self['config'].getCurrent()[0] == _('Movie location'): self.checkReadWriteDir(self['config'].getCurrent()[1]) for x in self.onChangedEntry: x() try: if isinstance(self['config'].getCurrent()[1], ConfigYesNo) or isinstance(self['config'].getCurrent()[1], ConfigSelection): self.createSetup() except: pass 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 getCurrentDescription(self): return self['config'].getCurrent() and len(self['config'].getCurrent()) > 2 and self['config'].getCurrent()[2] or '' def ok(self): currentry = self['config'].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value self.lastautorecorddirs = config.usage.allowed_autorecord_paths.value if config.usage.setup_level.index >= 2: txt = _('Default movie location') else: txt = _('Movie location') if currentry == self.default_entry: self.entrydirname = self.default_dirname self.session.openWithCallback(self.dirnameSelected, MovieLocationBox, txt, preferredPath(self.default_dirname.value)) elif currentry == self.timer_entry: self.entrydirname = self.timer_dirname self.session.openWithCallback(self.dirnameSelected, MovieLocationBox, _('New timers location'), preferredPath(self.timer_dirname.value)) elif currentry == self.instantrec_entry: self.entrydirname = self.instantrec_dirname self.session.openWithCallback(self.dirnameSelected, MovieLocationBox, _('Instant recordings location'), preferredPath(self.instantrec_dirname.value)) def dirnameSelected(self, res): if res is not None: self.entrydirname.value = res if config.movielist.videodirs.value != self.lastvideodirs: styles_keys = [ x[0] for x in self.styles ] tmp = config.movielist.videodirs.value default = self.default_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.default_dirname.setChoices(tmp, default=default) tmp = config.movielist.videodirs.value default = self.timer_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.timer_dirname.setChoices(self.styles + tmp, default=default) tmp = config.movielist.videodirs.value default = self.instantrec_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.instantrec_dirname.setChoices(self.styles + tmp, default=default) self.entrydirname.value = res if self.entrydirname.last_value != res: self.checkReadWriteDir(self.entrydirname) def saveAll(self): currentry = self['config'].getCurrent() config.usage.default_path.value = self.default_dirname.value config.usage.timer_path.value = self.timer_dirname.value config.usage.instantrec_path.value = self.instantrec_dirname.value config.usage.default_path.save() config.usage.timer_path.save() config.usage.instantrec_path.save() for x in self['config'].list: x[1].save() configfile.save() def keySave(self): self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self['config'].list: x[1].cancel() self.close() def keyCancel(self): if self['config'].isChanged(): self.session.openWithCallback(self.cancelConfirm, MessageBox, _('Really close without saving settings?'), default=False) else: self.close() def createSummary(self): return SetupSummary def addItems(self, list, parentNode): for x in parentNode: if not x.tag: continue if x.tag == 'item': item_level = int(x.get('level', 0)) if self.levelChanged not in config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.append(self.levelChanged) self.onClose.append(self.removeNotifier) if item_level > config.usage.setup_level.index: continue requires = x.get('requires') if requires and requires.startswith('config.'): item = eval(requires or '') if item.value and not item.value == '0': SystemInfo[requires] = True else: SystemInfo[requires] = False if requires and not SystemInfo.get(requires, False): continue item_text = _(x.get('text', '??').encode('UTF-8')) item_description = _(x.get('description', ' ').encode('UTF-8')) b = eval(x.text or '') if b == '': continue item = b if not isinstance(item, ConfigNothing): list.append((item_text, item, item_description))
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
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)
class TimeshiftSettings(Screen, ConfigListScreen): def removeNotifier(self): config.usage.setup_level.notifiers.remove(self.levelChanged) def levelChanged(self, configElement): list = [] self.refill(list) self["config"].setList(list) def refill(self, list): xmldata = setupdom().getroot() for x in xmldata.findall("setup"): if x.get("key") != self.setup: continue self.addItems(list, x) self.setup_title = x.get("title", "").encode("UTF-8") self.seperation = int(x.get('separation', '0')) def __init__(self, session, menu_path=""): Screen.__init__(self, session) self.menu_path = menu_path self.skinName = "Setup" self["menu_path_compressed"] = StaticText() self['footnote'] = Label() self["HelpWindow"] = Pixmap() self["HelpWindow"].hide() self["VKeyIcon"] = Boolean(False) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) self["description"] = Label(_("")) self.onChangedEntry = [] self.setup = "timeshift" list = [] ConfigListScreen.__init__(self, list, session=session, on_change=self.changedEntry) self.createSetup() self["setupActions"] = ActionMap( ["SetupActions", "ColorActions", "MenuActions"], { "green": self.keySave, "red": self.keyCancel, "cancel": self.keyCancel, "ok": self.ok, "menu": self.closeRecursive, }, -2) self.onLayoutFinish.append(self.layoutFinished) # for summary: def changedEntry(self): self.item = self["config"].getCurrent() if self["config"].getCurrent()[0] == _("Timeshift location"): self.checkReadWriteDir(self["config"].getCurrent()[1]) for x in self.onChangedEntry: x() try: if isinstance(self["config"].getCurrent()[1], ConfigYesNo) or isinstance( self["config"].getCurrent()[1], ConfigSelection): self.createSetup() except: pass 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 getCurrentDescription(self): return self["config"].getCurrent() and len(self["config"].getCurrent( )) > 2 and self["config"].getCurrent()[2] or "" def checkReadWriteDir(self, configele): import os.path import Components.Harddisk supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'nfs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions( False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append( (partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint( os.path.realpath(configele.value) ) + '/' in locations or Components.Harddisk.findMountPoint( os.path.realpath(configele.value)) in locations: if fileExists(configele.value, "w"): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not writable.\nMake sure you select a writable directory instead." ) % dir, type=MessageBox.TYPE_ERROR) return False else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type." ) % dir, type=MessageBox.TYPE_ERROR) return False else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type." ) % dir, type=MessageBox.TYPE_ERROR) return False def createSetup(self): default = config.usage.timeshift_path.value tmp = config.usage.allowed_timeshift_paths.value if default not in tmp: tmp = tmp[:] tmp.append(default) # print "TimeshiftPath: ", default, tmp self.timeshift_dirname = ConfigSelection(default=default, choices=tmp) self.timeshift_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) list = [] self.timeshift_entry = getConfigListEntry( _("Timeshift location"), self.timeshift_dirname, _("Set the default location for your timeshift-files. Press 'OK' to add new locations, select left/right to select an existing location." )) list.append(self.timeshift_entry) self.refill(list) self["config"].setList(list) if config.usage.sort_settings.value: self["config"].list.sort() def layoutFinished(self): if config.usage.show_menupath.value == 'large' and self.menu_path: title = self.menu_path + _(self.setup_title) self["menu_path_compressed"].setText("") elif config.usage.show_menupath.value == 'small': title = _(self.setup_title) self["menu_path_compressed"].setText( self.menu_path + " >" if not self.menu_path.endswith(' / ') else self.menu_path[:-3] + " >" or "") else: title = _(self.setup_title) self["menu_path_compressed"].setText("") self.setup_title = title self.setTitle(title) def ok(self): currentry = self["config"].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value if currentry == self.timeshift_entry: self.entrydirname = self.timeshift_dirname config.usage.timeshift_path.value = self.timeshift_dirname.value self.session.openWithCallback(self.dirnameSelected, TimeshiftLocationBox) def dirnameSelected(self, res): if res is not None: import os.path import Components.Harddisk supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'nfs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions( False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append( (partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint( os.path.realpath(res) ) + '/' in locations or Components.Harddisk.findMountPoint( os.path.realpath(res)) in locations: self.entrydirname.value = res if config.usage.allowed_timeshift_paths.value != self.lasttimeshiftdirs: tmp = config.usage.allowed_timeshift_paths.value default = self.timeshift_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.timeshift_dirname.setChoices(tmp, default=default) self.entrydirname.value = res else: self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type." ) % res, type=MessageBox.TYPE_ERROR) else: self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type." ) % res, type=MessageBox.TYPE_ERROR) def saveAll(self): for x in self["config"].list: x[1].save() configfile.save() # keySave and keyCancel are just provided in case you need them. # you have to call them by yourself. def keySave(self): import os.path import Components.Harddisk supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'nfs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions( False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append( (partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint( os.path.realpath(config.usage.timeshift_path.value) ) + '/' in locations or Components.Harddisk.findMountPoint( os.path.realpath( config.usage.timeshift_path.value)) in locations: config.usage.timeshift_path.value = self.timeshift_dirname.value config.usage.timeshift_path.save() self.saveAll() self.close() else: if int(config.timeshift.startdelay.value) > 0: self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type." ) % config.usage.timeshift_path.value, type=MessageBox.TYPE_ERROR) else: config.timeshift.startdelay.setValue(0) self.saveAll() self.close() else: if int(config.timeshift.startdelay.value) > 0: self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type." ) % config.usage.timeshift_path.value, type=MessageBox.TYPE_ERROR) else: config.timeshift.startdelay.setValue(0) self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self["config"].list: x[1].cancel() self.close() def keyCancel(self): if self["config"].isChanged(): self.session.openWithCallback( self.cancelConfirm, MessageBox, _("Really close without saving settings?"), default=False) else: self.close() def createSummary(self): return SetupSummary def addItems(self, list, parentNode): for x in parentNode: if not x.tag: continue if x.tag == 'item': item_level = int(x.get("level", 0)) if not self.levelChanged in config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.append( self.levelChanged) self.onClose.append(self.removeNotifier) if item_level > config.usage.setup_level.index: continue requires = x.get("requires") if requires and requires.startswith('config.'): item = eval(requires or "") if item.value and not item.value == "0": SystemInfo[requires] = True else: SystemInfo[requires] = False if requires and not SystemInfo.get(requires, False): continue item_text = _(x.get("text", "??").encode("UTF-8")) item_description = _(x.get("description", " ").encode("UTF-8")) b = eval(x.text or "") if b == "": continue #add to configlist item = b # the first b is the item itself, ignored by the configList. # the second one is converted to string. if not isinstance(item, ConfigNothing): list.append((item_text, item, item_description))
class TimeshiftSettings(Screen, ConfigListScreen): def removeNotifier(self): if config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.remove(self.levelChanged) def levelChanged(self, configElement): list = [] self.refill(list) self['config'].setList(list) def refill(self, list): xmldata = setupdom().getroot() for x in xmldata.findall('setup'): if x.get('key') != self.setup: continue self.addItems(list, x) self.setup_title = x.get('title', '').encode('UTF-8') self.seperation = int(x.get('separation', '0')) def __init__(self, session): Screen.__init__(self, session) self.skinName = 'Setup' self['footnote'] = Label() self['HelpWindow'] = Pixmap() self['HelpWindow'].hide() self['VKeyIcon'] = Boolean(False) self['key_red'] = StaticText(_('Cancel')) self['key_green'] = StaticText(_('Save')) self['description'] = Label(_('')) self.onChangedEntry = [] self.setup = 'timeshift' list = [] ConfigListScreen.__init__(self, list, session=session, on_change=self.changedEntry) self.createSetup() self['setupActions'] = ActionMap( ['SetupActions', 'ColorActions', 'MenuActions'], { 'green': self.keySave, 'red': self.keyCancel, 'cancel': self.keyCancel, 'ok': self.ok, 'menu': self.closeRecursive }, -2) self.onLayoutFinish.append(self.layoutFinished) def changedEntry(self): self.item = self['config'].getCurrent() if self['config'].getCurrent()[0] == _('Timeshift location'): self.checkReadWriteDir(self['config'].getCurrent()[1]) if self['config'].getCurrent()[0] == _('Autorecord location'): self.checkReadWriteDir(self['config'].getCurrent()[1]) for x in self.onChangedEntry: x() try: if isinstance(self['config'].getCurrent()[1], ConfigYesNo) or isinstance( self['config'].getCurrent()[1], ConfigSelection): self.createSetup() except: pass 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 getCurrentDescription(self): return self['config'].getCurrent() and len(self['config'].getCurrent( )) > 2 and self['config'].getCurrent()[2] or '' def checkReadWriteDir(self, configele): import os.path import Components.Harddisk supported_filesystems = frozenset( ('ext4', 'ext3', 'ext2', 'nfs', 'cifs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions( False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append( (partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint( os.path.realpath(configele.value) ) + '/' in locations or Components.Harddisk.findMountPoint( os.path.realpath(configele.value)) in locations: if fileExists(configele.value, 'w'): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _('The directory %s is not writable.\nMake sure you select a writable directory instead.' ) % dir, type=MessageBox.TYPE_ERROR) return False else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _('The directory %s is not a EXT2, EXT3, EXT4, NFS or CIFS partition.\nMake sure you select a valid partition type.' ) % dir, type=MessageBox.TYPE_ERROR) return False else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _('The directory %s is not a EXT2, EXT3, EXT4, NFS or CIFS partition.\nMake sure you select a valid partition type.' ) % dir, type=MessageBox.TYPE_ERROR) return False def createSetup(self): default = config.usage.timeshift_path.value cooldefault = config.usage.autorecord_path.value tmp = config.usage.allowed_timeshift_paths.value cooltmp = config.usage.allowed_autorecord_paths.value if default not in tmp: tmp = tmp[:] tmp.append(default) if cooldefault not in cooltmp: cooltmp = cooltmp[:] cooltmp.append(cooldefault) self.timeshift_dirname = ConfigSelection(default=default, choices=tmp) self.autorecord_dirname = ConfigSelection(default=cooldefault, choices=cooltmp) self.timeshift_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.autorecord_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) list = [] self.timeshift_entry = getConfigListEntry( _('Timeshift location'), self.timeshift_dirname, _("Set the default location for your timeshift-files. Press 'OK' to add new locations, select left/right to select an existing location." )) list.append(self.timeshift_entry) self.autorecord_entry = getConfigListEntry( _('Autorecord location'), self.autorecord_dirname, _("Set the default location for your autorecord-files. Press 'OK' to add new locations, select left/right to select an existing location." )) list.append(self.autorecord_entry) self.refill(list) self['config'].setList(list) if config.usage.sort_settings.value: self['config'].list.sort() def layoutFinished(self): self.setTitle(_(self.setup_title)) def ok(self): currentry = self['config'].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value self.lastautorecorddirs = config.usage.allowed_autorecord_paths.value if currentry == self.timeshift_entry: self.entrydirname = self.timeshift_dirname config.usage.timeshift_path.value = self.timeshift_dirname.value self.session.openWithCallback(self.dirnameSelected, TimeshiftLocationBox) if currentry == self.autorecord_entry: self.entrydirname = self.autorecord_dirname config.usage.autorecord_path.value = self.autorecord_dirname.value self.session.openWithCallback(self.dirnameSelected, AutorecordLocationBox) def dirnameSelected(self, res): if res is not None: import os.path import Components.Harddisk supported_filesystems = frozenset( ('ext4', 'ext3', 'ext2', 'nfs', 'cifs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions( False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append( (partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint( os.path.realpath(res) ) + '/' in locations or Components.Harddisk.findMountPoint( os.path.realpath(res)) in locations: self.entrydirname.value = res if config.usage.allowed_timeshift_paths.value != self.lasttimeshiftdirs: tmp = config.usage.allowed_timeshift_paths.value default = self.timeshift_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.timeshift_dirname.setChoices(tmp, default=default) self.entrydirname.value = res if config.usage.allowed_autorecord_paths.value != self.lastautorecorddirs: tmp = config.usage.allowed_autorecord_paths.value default = self.autorecord_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.autorecord_dirname.setChoices(tmp, default=default) self.entrydirname.value = res else: self.session.open( MessageBox, _('The directory %s is not a EXT2, EXT3, EXT4, NFS or CIFS partition.\nMake sure you select a valid partition type.' ) % res, type=MessageBox.TYPE_ERROR) else: self.session.open( MessageBox, _('The directory %s is not a EXT2, EXT3, EXT4, NFS or CIFS partition.\nMake sure you select a valid partition type.' ) % res, type=MessageBox.TYPE_ERROR) def saveAll(self): for x in self['config'].list: x[1].save() configfile.save() def keySave(self): import os.path import Components.Harddisk supported_filesystems = frozenset( ('ext4', 'ext3', 'ext2', 'nfs', 'cifs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions( False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append( (partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint( os.path.realpath(config.usage.timeshift_path.value) ) + '/' in locations or Components.Harddisk.findMountPoint( os.path.realpath( config.usage.timeshift_path.value)) in locations: config.usage.timeshift_path.value = self.timeshift_dirname.value config.usage.timeshift_path.save() self.saveAll() self.close() elif int(config.timeshift.startdelay.value) > 0: self.session.open( MessageBox, _('The directory %s is not a EXT2, EXT3, EXT4, NFS or CIFS partition.\nMake sure you select a valid partition type.' ) % config.usage.timeshift_path.value, type=MessageBox.TYPE_ERROR) else: config.timeshift.startdelay.setValue(0) self.saveAll() self.close() elif int(config.timeshift.startdelay.value) > 0: self.session.open( MessageBox, _('The directory %s is not a EXT2, EXT3, EXT4, NFS or CIFS partition.\nMake sure you select a valid partition type.' ) % config.usage.timeshift_path.value, type=MessageBox.TYPE_ERROR) else: config.timeshift.startdelay.setValue(0) self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self['config'].list: x[1].cancel() self.close() def keyCancel(self): if self['config'].isChanged(): self.session.openWithCallback( self.cancelConfirm, MessageBox, _('Really close without saving settings?'), default=False) else: self.close() def createSummary(self): return SetupSummary def addItems(self, list, parentNode): for x in parentNode: if not x.tag: continue if x.tag == 'item': item_level = int(x.get('level', 0)) if self.levelChanged not in config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.append( self.levelChanged) self.onClose.append(self.removeNotifier) if item_level > config.usage.setup_level.index: continue requires = x.get('requires') if requires and requires.startswith('config.'): item = eval(requires or '') if item.value and not item.value == '0': SystemInfo[requires] = True else: SystemInfo[requires] = False if requires and not SystemInfo.get(requires, False): continue item_text = _(x.get('text', '??').encode('UTF-8')) item_description = _(x.get('description', ' ').encode('UTF-8')) b = eval(x.text or '') if b == '': continue item = b if not isinstance(item, ConfigNothing): list.append((item_text, item, item_description))
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)
class MovieRetitle(Screen, ConfigListScreen): def __init__(self, session, service, parent, args = 0): Screen.__init__(self, session, parent = parent) self.skinName = [ "MovieRetitle", "Setup" ] self["HelpWindow"] = Pixmap() self["HelpWindow"].hide() self["VKeyIcon"] = Boolean(False) serviceHandler = eServiceCenter.getInstance() info = serviceHandler.info(service) path = service.getPath() if path.endswith(".ts") is True: path = path[:-3] self.path = path self.dir = '/'.join(path.split('/')[:-1]) + '/' self.file = self.baseName(path) self.name = info.getName(service) if self.file == self.baseName(self.name): self.orig_title = "" else: self.orig_title = self.name self.descr = info.getInfoString(service, iServiceInformation.sDescription) self["key_green"] = StaticText(_("OK")) self["key_red"] = StaticText(_("Cancel")) self.input_file = ConfigText(default = self.file, fixed_size = False, visible_width = 42) self.input_title = ConfigText(default = self.orig_title, fixed_size = False, visible_width = 42) self.input_descr = ConfigText(default = self.descr, fixed_size = False, visible_width = 42) tmp = config.movielist.videodirs.value if not self.dir in tmp: tmp.append(self.dir) self.input_dir = ConfigSelection(choices = tmp, default = self.dir) self["actions"] = ActionMap(["SetupActions"], { "ok": self.keySelectOrGo, "save": self.keyGo, "cancel": self.keyCancel, }, -2) self.locationEl = getConfigListEntry(_("Location"), self.input_dir) l = [ getConfigListEntry(_("Filename"), self.input_file), getConfigListEntry(_("Title"), self.input_title), getConfigListEntry(_("Description"), self.input_descr), self.locationEl ] ConfigListScreen.__init__(self, l) self.onLayoutFinish.append(self.setCustomTitle) def setCustomTitle(self): self.setTitle(_("Name and Description Input")) def pathSelected(self, res): if res is not None: videodirs = config.movielist.videodirs.value if videodirs != self.input_dir.choices: self.input_dir.setChoices(videodirs, default=res) self.input_dir.value = res def keySelectOrGo(self): cur = self["config"].getCurrent() if cur is self.locationEl: self.session.openWithCallback( self.pathSelected, MovieLocationBox, _("Choose target folder"), self.input_dir.value, ) else: self.keyGo() def keyGo(self): if self.input_title.value != self.orig_title or self.input_descr.value != self.descr: self.setTitleDescr(self.path, self.input_title.value, self.input_descr.value) if self.input_file.value != self.file or self.input_dir.value != self.dir: self.maybeMoveMovieFiles(self.path, self.rejoinName(self.input_dir.value, self.input_file.value)) else: self.exitDialog() def keyCancel(self): self.close() def setTitleDescr(self, file, title, descr): if os_path.exists(file + ".ts.meta"): metafile = open(file + ".ts.meta", "r") sid = metafile.readline() oldtitle = metafile.readline().rstrip() olddescr = metafile.readline().rstrip() rest = metafile.read() metafile.close() if not title and title != "": title = oldtitle if not descr and descr != "": descr = olddescr metafile = open(file + ".ts.meta", "w") metafile.write("%s%s\n%s\n%s" %(sid, title, descr, rest)) metafile.close() def maybeMoveMovieFiles(self, fr, to): if os_path.exists(to+".ts"): self.inter_fr = fr self.inter_to = to self.session.openWithCallback(self.confirmedReplace, MessageBox, _("Target file %s.ts already exist.\nDo you want to replace it?") % (to), MessageBox.TYPE_YESNO) elif os_path.isdir(os_path.dirname(to)): self.moveMovieFiles(fr, to) else: self.session.openWithCallback(self.exitDialog, MessageBox, _("The target directory is not found. The file is not renamed."), MessageBox.TYPE_ERROR) def confirmedReplace(self, answer): if answer == True: self.moveMovieFiles(self.inter_fr, self.inter_to) def moveMovieFiles(self, fr, to): try: os_rename(fr + ".ts", to + ".ts") except OSError: print "Moving in background" global_background_mover.enqueue(self.exitDialog, self.session, fr, to) else: print "Moving in foreground" for suff in (".ts.meta", ".ts.cuts", ".ts.ap", ".ts.sc", ".eit"): if os_path.exists(fr + suff): os_rename(fr + suff, to + suff) self.exitDialog() def exitDialog(self, dummy=None): self.close() # This will try to get back to an updated movie list. # A proper way to do this should be provided in enigma2. try: parent = self.parent parent.csel.reloadList() parent.close() except AttributeError: try: # when started from MovieSelection Quickbutton Plugin, MovieSelection is parent, not MovieContextMenu --> try again self.parent.reloadList() except: pass def baseName(self, str): name = str.split('/')[-1] if name.endswith(".ts") is True: return name[:-3] else: return name def rejoinName(self, dir, name): name = name.strip() if name.endswith(".ts") is True: return dir + name[:-3] else: return dir + name
class MovieRetitle(Screen, ConfigListScreen): def __init__(self, session, service, parent, args=0): Screen.__init__(self, session, parent=parent) self.skinName = ["MovieRetitle", "Setup"] self["HelpWindow"] = Pixmap() self["HelpWindow"].hide() self["VKeyIcon"] = Boolean(False) serviceHandler = eServiceCenter.getInstance() info = serviceHandler.info(service) path = service.getPath() if path.endswith(".ts") is True: path = path[:-3] self.path = path self.dir = '/'.join(path.split('/')[:-1]) + '/' self.file = self.baseName(path) self.name = info.getName(service) if self.file == self.baseName(self.name): self.orig_title = "" else: self.orig_title = self.name self.descr = info.getInfoString(service, iServiceInformation.sDescription) self["key_green"] = StaticText(_("OK")) self["key_red"] = StaticText(_("Cancel")) self.input_file = ConfigText(default=self.file, fixed_size=False, visible_width=42) self.input_title = ConfigText(default=self.orig_title, fixed_size=False, visible_width=42) self.input_descr = ConfigText(default=self.descr, fixed_size=False, visible_width=42) tmp = config.movielist.videodirs.value if not self.dir in tmp: tmp.append(self.dir) self.input_dir = ConfigSelection(choices=tmp, default=self.dir) self["actions"] = ActionMap( ["SetupActions"], { "ok": self.keySelectOrGo, "save": self.keyGo, "cancel": self.keyCancel, }, -2) self.locationEl = getConfigListEntry(_("Location"), self.input_dir) l = [ getConfigListEntry(_("Filename"), self.input_file), getConfigListEntry(_("Title"), self.input_title), getConfigListEntry(_("Description"), self.input_descr), self.locationEl ] ConfigListScreen.__init__(self, l, session=session) self.onLayoutFinish.append(self.setCustomTitle) def setCustomTitle(self): self.setTitle(_("Name and Description Input")) def pathSelected(self, res): if res is not None: videodirs = config.movielist.videodirs.value if videodirs != self.input_dir.choices: self.input_dir.setChoices(videodirs, default=res) self.input_dir.value = res def keySelectOrGo(self): cur = self["config"].getCurrent() if cur is self.locationEl: self.session.openWithCallback( self.pathSelected, MovieLocationBox, _("Choose target folder"), self.input_dir.value, ) else: self.keyGo() def keyGo(self): if self.input_title.value != self.orig_title or self.input_descr.value != self.descr: self.setTitleDescr(self.path, self.input_title.value, self.input_descr.value) if self.input_file.value != self.file or self.input_dir.value != self.dir: self.maybeMoveMovieFiles( self.path, self.rejoinName(self.input_dir.value, self.input_file.value)) else: self.exitDialog() def keyCancel(self): self.close() def setTitleDescr(self, file, title, descr): if os_path.exists(file + ".ts.meta"): metafile = open(file + ".ts.meta", "r") sid = metafile.readline() oldtitle = metafile.readline().rstrip() olddescr = metafile.readline().rstrip() rest = metafile.read() metafile.close() if not title and title != "": title = oldtitle if not descr and descr != "": descr = olddescr metafile = open(file + ".ts.meta", "w") metafile.write("%s%s\n%s\n%s" % (sid, title, descr, rest)) metafile.flush() fsync(metafile.fileno()) metafile.close() def maybeMoveMovieFiles(self, fr, to): if os_path.exists(to + ".ts"): self.inter_fr = fr self.inter_to = to self.session.openWithCallback( self.confirmedReplace, MessageBox, _("Target file %s.ts already exist.\nDo you want to replace it?" ) % (to), MessageBox.TYPE_YESNO) elif os_path.isdir(os_path.dirname(to)): self.moveMovieFiles(fr, to) else: self.session.openWithCallback( self.exitDialog, MessageBox, _("The target directory is not found. The file is not renamed." ), MessageBox.TYPE_ERROR) def confirmedReplace(self, answer): if answer == True: self.moveMovieFiles(self.inter_fr, self.inter_to) def moveMovieFiles(self, fr, to): try: os_rename(fr + ".ts", to + ".ts") except OSError: print("Moving in background") global_background_mover.enqueue(self.exitDialog, self.session, fr, to) else: print("Moving in foreground") for suff in (".ts.meta", ".ts.cuts", ".ts.ap", ".ts.sc", ".eit"): if os_path.exists(fr + suff): os_rename(fr + suff, to + suff) self.exitDialog() def exitDialog(self, dummy=None): self.close() # This will try to get back to an updated movie list. # A proper way to do this should be provided in enigma2. try: parent = self.parent parent.csel.reloadList() parent.close() except AttributeError: try: # when started from MovieSelection Quickbutton Plugin, MovieSelection is parent, not MovieContextMenu --> try again self.parent.reloadList() except: pass def baseName(self, str): name = str.split('/')[-1] if name.endswith(".ts") is True: return name[:-3] else: return name def rejoinName(self, dir, name): name = name.strip() if name.endswith(".ts") is True: return dir + name[:-3] else: return dir + name
class RecordingSettings(Screen,ConfigListScreen): skin = """ <screen name="RecordPathsSettings" position="160,150" size="450,200" title="Recording paths"> <ePixmap pixmap="skin_default/buttons/red.png" position="10,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="300,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="10,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render="Label" position="300,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget name="config" position="10,44" size="430,146" /> </screen>""" def __init__(self, session): from Components.Sources.StaticText import StaticText Screen.__init__(self, session) self.skinName = "Setup" self.setup_title = _("Recording Settings") Screen.setTitle(self, _(self.setup_title)) self["status"] = StaticText() self['footnote'] = Label() self["HelpWindow"] = Pixmap() self["HelpWindow"].hide() self["VKeyIcon"] = Boolean(False) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) self.onChangedEntry = [ ] self.list = [] ConfigListScreen.__init__(self, self.list, session = self.session, on_change = self.changedEntry) self.createSetup() self["setupActions"] = ActionMap(["SetupActions", "ColorActions", "MenuActions"], { "green": self.keySave, "red": self.keyCancel, "cancel": self.keyCancel, "ok": self.ok, "menu": self.closeRecursive, }, -2) if not self.SelectionChanged in self["config"].onSelectionChanged: self["config"].onSelectionChanged.append(self.SelectionChanged) def checkReadWriteDir(self, configele): print "checkReadWrite: ", configele.value if configele.value in [x[0] for x in self.styles] or fileExists(configele.value, "w"): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not writable.\nMake sure you select a writable directory instead.")%dir, type = MessageBox.TYPE_ERROR ) return False def createSetup(self): self.styles = [ ("<default>", _("<Default movie location>")), ("<current>", _("<Current movielist location>")), ("<timer>", _("<Last timer location>")) ] styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = config.usage.default_path.value if default not in tmp: tmp = tmp[:] tmp.append(default) print "DefaultPath: ", default, tmp self.default_dirname = ConfigSelection(default = default, choices = tmp) tmp = config.movielist.videodirs.value default = config.usage.timer_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print "TimerPath: ", default, tmp self.timer_dirname = ConfigSelection(default = default, choices = self.styles+tmp) tmp = config.movielist.videodirs.value default = config.usage.instantrec_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print "InstantrecPath: ", default, tmp self.instantrec_dirname = ConfigSelection(default = default, choices = self.styles+tmp) self.default_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timer_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.instantrec_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.list = [] if config.usage.setup_level.index >= 2: self.default_entry = getConfigListEntry(_("Default movie location"), self.default_dirname, _("Set the default location for your recordings. Press 'OK' to add new locations, select left/right to select an existing location.")) self.list.append(self.default_entry) self.timer_entry = getConfigListEntry(_("Timer record location"), self.timer_dirname, _("Set the default location for your timers. Press 'OK' to add new locations, select left/right to select an existing location.")) self.list.append(self.timer_entry) self.instantrec_entry = getConfigListEntry(_("Instant record location"), self.instantrec_dirname, _("Set the default location for your instant recordings. Press 'OK' to add new locations, select left/right to select an existing location.")) self.list.append(self.instantrec_entry) else: self.default_entry = getConfigListEntry(_("Movie location"), self.default_dirname, _("Set the default location for your recordings. Press 'OK' to add new locations, select left/right to select an existing location.")) self.list.append(self.default_entry) if config.usage.setup_level.index >= 1: self.list.append(getConfigListEntry(_("Recordings always have priority"), config.recording.asktozap, _("Select 'Yes' if you want recordings to have priority over live-TV."))) self.list.append(getConfigListEntry(_("Margin before record (minutes)"), config.recording.margin_before, _("Set the time you want recordings to start before the event start-time."))) self.list.append(getConfigListEntry(_("Margin after record"), config.recording.margin_after, _("Set the time you want recordings to stop after the event stop-time."))) if config.usage.setup_level.index >= 2: self.list.append(getConfigListEntry(_("Show Message when Recording starts"), config.usage.show_message_when_recording_starts, _("Do you want a pop-up message saying 'a recording has started'?"))) self.list.append(getConfigListEntry(_("Behavior when a movie is started"), config.usage.on_movie_start, _("On starting playback of a file, you can choose the box's behaviour."))) self.list.append(getConfigListEntry(_("Behavior when a movie is stopped"), config.usage.on_movie_stop, _("On stopping playback of a file, you can choose the box's behaviour."))) self.list.append(getConfigListEntry(_("Behavior when a movie reaches the end"), config.usage.on_movie_eof, _("On reaching the end of a file during playback, you can choose the box's behaviour."))) self.list.append(getConfigListEntry(_("Behavior of 'pause' when paused"), config.seek.on_pause, _("Here you can select the behaviour of the 'puase'-button when playback has been paused."))) self.list.append(getConfigListEntry(_("Custom skip time for '1'/'3'-keys"), config.seek.selfdefined_13, _("Set the skip-forward/backward time of the 1-3 number keys."))) self.list.append(getConfigListEntry(_("Custom skip time for '4'/'6'-keys"), config.seek.selfdefined_46, _("Set the skip-forward/backward time of the 4-6 number keys."))) self.list.append(getConfigListEntry(_("Custom skip time for '7'/'9'-keys"), config.seek.selfdefined_79, _("Set the skip-forward/backward time of the 7-9 number keys."))) self.list.append(getConfigListEntry(_("Display message before next played movie"), config.usage.next_movie_msg, _("Show a popup message after a recording has finished and before start next in queue."))) self.list.append(getConfigListEntry(_("Seekbar activation"), config.seek.baractivation, _("Select seekbar to be activated by arrow L/R (long) or << >> (long)."))) self.list.append(getConfigListEntry(_("Seekbar sensibility"), config.seek.sensibility, _("Set the jump-size of the seekbar."))) self.list.append(getConfigListEntry(_("Fast Forward speeds"), config.seek.speeds_forward, _("Set the values for fast-forward speeds."))) self.list.append(getConfigListEntry(_("Rewind speeds"), config.seek.speeds_backward, _("Set the values for fast-backward speeds."))) self.list.append(getConfigListEntry(_("Slow Motion speeds"), config.seek.speeds_slowmotion, _("Set the values for slow-motion speeds."))) self.list.append(getConfigListEntry(_("Initial Fast Forward speed"), config.seek.enter_forward, _("Set the value for the initial fast-forward speed."))) self.list.append(getConfigListEntry(_("Initial Rewind speed"), config.seek.enter_backward, _("Set the value for the initial fast-backward speed."))) self.list.append(getConfigListEntry(_("Limited character set for recording filenames"), config.recording.ascii_filenames, _("Select 'Yes' if you want only a small number of characters to be used for recording names."))) self.list.append(getConfigListEntry(_("Composition of the recording filenames"), config.recording.filename_composition, _("Select how you want recording names to be populated."))) self.list.append(getConfigListEntry(_("Keep old timers for how many days"), config.recording.keep_timers, _("Set the number of days you want old timers to be kept."))) if config.usage.setup_level.index >= 1: self.list.append(getConfigListEntry(_("Use trashcan in movielist"), config.usage.movielist_trashcan, _("If set to 'Yes' recordings will be deleted to a trashcan. That way thay can still be played."))) self.list.append(getConfigListEntry(_("Remove items from trash after (days)"), config.usage.movielist_trashcan_days, _("Select the number of days after which the box is allowed to permanently delete recordings (from the trashcan)."))) self.list.append(getConfigListEntry(_("Disk space to reserve for recordings (in GB)"), config.usage.movielist_trashcan_reserve, _("Itmes in trashcan will be deleted if less then the set space is available."))) if config.usage.setup_level.index >= 2: self.list.append(getConfigListEntry(_("Recording data sync size"), config.misc.flush_size, _("Only change for debugging; default is 'Off'."))) self.list.append(getConfigListEntry(_("Background delete option"), config.misc.erase_flags, _("Only change for debugging; default is 'Internal hdd only'."))) self.list.append(getConfigListEntry(_("Background delete speed"), config.misc.erase_speed, _("Only change for debugging; default is '20 MB/s'."))) self.list.append(getConfigListEntry(_("Offline decode delay (ms)"), config.recording.offline_decode_delay, _("Change this value if your smartcard can't doesn't handle off-line decoding well; default is '1000'."))) self["config"].setList(self.list) if config.usage.sort_settings.value: self["config"].list.sort() def SelectionChanged(self): self["status"].setText(self["config"].getCurrent()[2]) # for summary: def changedEntry(self): if self["config"].getCurrent()[0] == _("Default movie location") or self["config"].getCurrent()[0] == _("Timer record location") or self["config"].getCurrent()[0] == _("Instant record location") or self["config"].getCurrent()[0] == _("Movie location"): self.checkReadWriteDir(self["config"].getCurrent()[1]) for x in self.onChangedEntry: x() def getCurrentEntry(self): return self["config"].getCurrent()[0] def getCurrentValue(self): return str(self["config"].getCurrent()[1].getText()) def ok(self): currentry = self["config"].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value if config.usage.setup_level.index >= 2: txt = _("Default movie location") else: txt = _("Movie location") if currentry == self.default_entry: self.entrydirname = self.default_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, txt, preferredPath(self.default_dirname.value) ) elif currentry == self.timer_entry: self.entrydirname = self.timer_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("New timers location"), preferredPath(self.timer_dirname.value) ) elif currentry == self.instantrec_entry: self.entrydirname = self.instantrec_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Instant recordings location"), preferredPath(self.instantrec_dirname.value) ) def dirnameSelected(self, res): if res is not None: self.entrydirname.value = res if config.movielist.videodirs.value != self.lastvideodirs: styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = self.default_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.default_dirname.setChoices(tmp, default=default) tmp = config.movielist.videodirs.value default = self.timer_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.timer_dirname.setChoices(self.styles+tmp, default=default) tmp = config.movielist.videodirs.value default = self.instantrec_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.instantrec_dirname.setChoices(self.styles+tmp, default=default) self.entrydirname.value = res if self.entrydirname.last_value != res: self.checkReadWriteDir(self.entrydirname) def saveAll(self): currentry = self["config"].getCurrent() config.usage.default_path.value = self.default_dirname.value config.usage.timer_path.value = self.timer_dirname.value config.usage.instantrec_path.value = self.instantrec_dirname.value config.usage.default_path.save() config.usage.timer_path.save() config.usage.instantrec_path.save() for x in self["config"].list: x[1].save() configfile.save() # keySave and keyCancel are just provided in case you need them. # you have to call them by yourself. def keySave(self): self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self["config"].list: x[1].cancel() self.close() def keyCancel(self): if self["config"].isChanged(): self.session.openWithCallback(self.cancelConfirm, MessageBox, _("Really close without saving settings?")) else: self.close() def createSummary(self): from Screens.Setup import SetupSummary return SetupSummary
class RecordPathsSettings(Screen, ConfigListScreen): skin = """ <screen name="RecordPathsSettings" position="160,150" size="450,200" title="Recording paths"> <ePixmap pixmap="buttons/red.png" position="10,0" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/green.png" position="300,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="10,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render="Label" position="300,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget name="config" position="10,44" size="430,146" /> </screen>""" def __init__(self, session): from Components.Sources.StaticText import StaticText Screen.__init__(self, session) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) ConfigListScreen.__init__(self, []) self.initConfigList() self["setupActions"] = ActionMap( ["SetupActions", "ColorActions"], { "green": self.save, "red": self.cancel, "cancel": self.cancel, "ok": self.ok, }, -2) def checkReadWriteDir(self, configele): value = configele.value print "checkReadWrite: ", configele.value if not value or value in [x[0] for x in self.styles] or fileExists( value, "w"): configele.last_value = value return True else: configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not writable.\nMake sure you select a writable directory instead." ) % value, type=MessageBox.TYPE_ERROR) return False def initConfigList(self): self.styles = [("<default>", _("<Default movie location>")), ("<current>", _("<Current movielist location>")), ("<timer>", _("<Last timer location>"))] styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = config.usage.default_path.value if default and default not in tmp: tmp = tmp[:] tmp.append(default) print "DefaultPath: ", default, tmp self.default_dirname = ConfigSelection( default=default, choices=[("", _("<Default movie location>"))] + tmp) tmp = config.movielist.videodirs.value default = config.usage.timer_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print "TimerPath: ", default, tmp self.timer_dirname = ConfigSelection(default=default, choices=self.styles + tmp) tmp = config.movielist.videodirs.value default = config.usage.instantrec_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print "InstantrecPath: ", default, tmp self.instantrec_dirname = ConfigSelection(default=default, choices=self.styles + tmp) default = config.usage.timeshift_path.value tmp = config.usage.allowed_timeshift_paths.value if default not in tmp: tmp = tmp[:] tmp.append(default) print "TimeshiftPath: ", default, tmp self.timeshift_dirname = ConfigSelection(default=default, choices=tmp) self.default_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timer_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.instantrec_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timeshift_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.list = [] if config.usage.setup_level.index >= 2: self.default_entry = getConfigListEntry( _("Default movie location"), self.default_dirname) self.list.append(self.default_entry) self.timer_entry = getConfigListEntry(_("Timer record location"), self.timer_dirname) self.list.append(self.timer_entry) self.instantrec_entry = getConfigListEntry( _("Instant record location"), self.instantrec_dirname) self.list.append(self.instantrec_entry) else: self.default_entry = getConfigListEntry(_("Movie location"), self.default_dirname) self.list.append(self.default_entry) self.timeshift_entry = getConfigListEntry(_("Timeshift location"), self.timeshift_dirname) self.list.append(self.timeshift_entry) self["config"].setList(self.list) def ok(self): currentry = self["config"].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value if config.usage.setup_level.index >= 2: txt = _("Default movie location") else: txt = _("Movie location") if currentry == self.default_entry: self.entrydirname = self.default_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, txt, preferredPath(self.default_dirname.value)) elif currentry == self.timer_entry: self.entrydirname = self.timer_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Initial location in new timers"), preferredPath(self.timer_dirname.value)) elif currentry == self.instantrec_entry: self.entrydirname = self.instantrec_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Location for instant recordings"), preferredPath(self.instantrec_dirname.value)) elif currentry == self.timeshift_entry: self.entrydirname = self.timeshift_dirname config.usage.timeshift_path.value = self.timeshift_dirname.value self.session.openWithCallback(self.dirnameSelected, TimeshiftLocationBox) def dirnameSelected(self, res): if res is not None: self.entrydirname.value = res if config.movielist.videodirs.value != self.lastvideodirs: styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = self.default_dirname.value if default and default not in tmp: tmp = tmp[:] tmp.append(default) self.default_dirname.setChoices( [("", _("<Default movie location>"))] + tmp, default=default) tmp = config.movielist.videodirs.value default = self.timer_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.timer_dirname.setChoices(self.styles + tmp, default=default) tmp = config.movielist.videodirs.value default = self.instantrec_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.instantrec_dirname.setChoices(self.styles + tmp, default=default) self.entrydirname.value = res if config.usage.allowed_timeshift_paths.value != self.lasttimeshiftdirs: tmp = config.usage.allowed_timeshift_paths.value default = self.instantrec_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.timeshift_dirname.setChoices(tmp, default=default) self.entrydirname.value = res if self.entrydirname.last_value != res: self.checkReadWriteDir(self.entrydirname) def save(self): currentry = self["config"].getCurrent() if self.checkReadWriteDir(currentry[1]): config.usage.default_path.value = self.default_dirname.value config.usage.timer_path.value = self.timer_dirname.value config.usage.instantrec_path.value = self.instantrec_dirname.value config.usage.timeshift_path.value = self.timeshift_dirname.value config.usage.default_path.save() config.usage.timer_path.save() config.usage.instantrec_path.save() config.usage.timeshift_path.save() self.close() def cancel(self): self.close()
class TimeshiftSettings(Screen,ConfigListScreen): skin = """ <screen name="RecordPathsSettings" position="160,150" size="450,200" title="Recording paths"> <ePixmap pixmap="skin_default/buttons/red.png" position="10,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="300,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="10,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render="Label" position="300,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget name="config" position="10,44" size="430,146" /> </screen>""" def __init__(self, session): from Components.Sources.StaticText import StaticText Screen.__init__(self, session) self.skinName = "Setup" self.setup_title = _("Timshift Settings") Screen.setTitle(self, _(self.setup_title)) self["status"] = StaticText() self['footnote'] = Label(_("* = Restart timeshift required")) self["HelpWindow"] = Pixmap() self["HelpWindow"].hide() self["VKeyIcon"] = Boolean(False) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) self.onChangedEntry = [ ] self.list = [] ConfigListScreen.__init__(self, self.list, session = self.session, on_change = self.changedEntry) self.createSetup() self["setupActions"] = ActionMap(["SetupActions", "ColorActions"], { "green": self.keySave, "red": self.keyCancel, "cancel": self.keyCancel, "ok": self.ok, }, -2) if not self.SelectionChanged in self["config"].onSelectionChanged: self["config"].onSelectionChanged.append(self.SelectionChanged) # for summary: def changedEntry(self): if self["config"].getCurrent()[0] == _("Permanent Timeshift Enable"): self.createSetup() if self["config"].getCurrent()[0] == _("Timeshift location"): self.checkReadWriteDir(self["config"].getCurrent()[1]) for x in self.onChangedEntry: x() def getCurrentEntry(self): return self["config"].getCurrent()[0] def getCurrentValue(self): return str(self["config"].getCurrent()[1].getText()) def checkReadWriteDir(self, configele): import os.path import Components.Harddisk supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'nfs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append((partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint(os.path.realpath(configele.value))+'/' in locations or Components.Harddisk.findMountPoint(os.path.realpath(configele.value)) in locations: if fileExists(configele.value, "w"): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not writable.\nMake sure you select a writable directory instead.")%dir, type = MessageBox.TYPE_ERROR ) return False else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type.")%dir, type = MessageBox.TYPE_ERROR ) return False else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type.")%dir, type = MessageBox.TYPE_ERROR ) return False def createSetup(self): default = config.usage.timeshift_path.value tmp = config.usage.allowed_timeshift_paths.value if default not in tmp: tmp = tmp[:] tmp.append(default) print "TimeshiftPath: ", default, tmp self.timeshift_dirname = ConfigSelection(default = default, choices = tmp) self.timeshift_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.list = [] self.timeshift_entry = getConfigListEntry(_("Timeshift location"), self.timeshift_dirname, _("Set the default location for your timeshift-files. Press 'OK' to add new locations, select left/right to select an existing location.")) self.list.append(self.timeshift_entry) self.list.append(getConfigListEntry(_("Permanent Timeshift Enable"), config.timeshift.enabled, _("Enable or disable Permanent Timeshift. When activated, you can wind back until the time you zapped to a channel, and you can make recordings in retrospect."))) if config.usage.setup_level.index >= 2 and config.timeshift.enabled.value: self.list.append(getConfigListEntry(_("Permanent Timeshift Max Events"), config.timeshift.maxevents, _("Set the maximum number of events (programs) that timeshift may handle."))) self.list.append(getConfigListEntry(_("Permanent Timeshift Max Length"), config.timeshift.maxlength, _("Set the maximum length a timeshift file may be."))) self.list.append(getConfigListEntry(_("Permanent Timeshift Start Delay"), config.timeshift.startdelay, _("Timeshift will only start when the start delay time has passed. Thois prevents numurous very short files when zapping."))) self.list.append(getConfigListEntry(_("Stop timeshift while recording?"), config.timeshift.stopwhilerecording, _("Select if timeshift must continue when set to record."))) self.list.append(getConfigListEntry(_("Timeshift-Save Action on zap"), config.timeshift.favoriteSaveAction, _("Set what the required action must be when zapping while a timeshift has been set as recording."))) self.list.append(getConfigListEntry(_("Use PTS seekbar while timeshifting? *"), config.timeshift.showinfobar, _("If set to 'yes' a special seekbar is available during timeshift."))) self["config"].setList(self.list) if config.usage.sort_settings.value: self["config"].list.sort() def SelectionChanged(self): self["status"].setText(self["config"].getCurrent()[2]) def ok(self): currentry = self["config"].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value if currentry == self.timeshift_entry: self.entrydirname = self.timeshift_dirname config.usage.timeshift_path.value = self.timeshift_dirname.value self.session.openWithCallback( self.dirnameSelected, TimeshiftLocationBox ) def dirnameSelected(self, res): if res is not None: import os.path import Components.Harddisk supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'nfs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append((partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint(os.path.realpath(res))+'/' in locations or Components.Harddisk.findMountPoint(os.path.realpath(res)) in locations: self.entrydirname.value = res if config.usage.allowed_timeshift_paths.value != self.lasttimeshiftdirs: tmp = config.usage.allowed_timeshift_paths.value default = self.timeshift_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.timeshift_dirname.setChoices(tmp, default=default) self.entrydirname.value = res else: self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type.")%res, type = MessageBox.TYPE_ERROR ) else: self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type.")%res, type = MessageBox.TYPE_ERROR ) def saveAll(self): for x in self["config"].list: x[1].save() configfile.save() # keySave and keyCancel are just provided in case you need them. # you have to call them by yourself. def keySave(self): import os.path import Components.Harddisk supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'nfs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append((partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint(os.path.realpath(config.usage.timeshift_path.value))+'/' in locations or Components.Harddisk.findMountPoint(os.path.realpath(config.usage.timeshift_path.value)) in locations: config.usage.timeshift_path.value = self.timeshift_dirname.value config.usage.timeshift_path.save() self.saveAll() self.close() else: if config.timeshift.enabled.getValue(): self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type.")%config.usage.timeshift_path.value, type = MessageBox.TYPE_ERROR ) else: config.timeshift.enabled.setValue(False) self.saveAll() self.close() else: if config.timeshift.enabled.getValue(): self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type.")%config.usage.timeshift_path.value, type = MessageBox.TYPE_ERROR ) else: config.timeshift.enabled.setValue(False) self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self["config"].list: x[1].cancel() self.close() def keyCancel(self): if self["config"].isChanged(): self.session.openWithCallback(self.cancelConfirm, MessageBox, _("Really close without saving settings?")) else: self.close() def createSummary(self): from Screens.Setup import SetupSummary return SetupSummary
class EPGPathsSetup(Screen, ConfigListScreen): def removeNotifier(self): if config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.remove(self.levelChanged) def levelChanged(self, configElement): list = [] self.refill(list) self['config'].setList(list) def refill(self, list): xmldata = setupdom().getroot() for x in xmldata.findall('setup'): if x.get('key') != self.setup: continue self.addItems(list, x) self.setup_title = x.get('title', '').encode('UTF-8') self.seperation = int(x.get('separation', '0')) def __init__(self, session): Screen.__init__(self, session) self.skinName = 'Setup' self['footnote'] = Label() self['HelpWindow'] = Pixmap() self['HelpWindow'].hide() self['VKeyIcon'] = Boolean(False) self['key_red'] = StaticText(_('Cancel')) self['key_green'] = StaticText(_('Save')) self['description'] = Label(_('')) self.onChangedEntry = [] self.setup = 'epgsettings' list = [] ConfigListScreen.__init__(self, list, session=session, on_change=self.changedEntry) self.createSetup() self['setupActions'] = ActionMap(['SetupActions', 'ColorActions', 'MenuActions'], {'green': self.keySave, 'red': self.keyCancel, 'cancel': self.keyCancel, 'ok': self.ok, 'menu': self.closeRecursive}, -2) self.onLayoutFinish.append(self.layoutFinished) def checkReadWriteDir(self, configele): print 'checkReadWrite: ', configele.value if configele.value in [ x[0] for x in self.styles ] or fileExists(configele.value, 'w'): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open(MessageBox, _('The directory %s is not writable.\nMake sure you select a writable directory instead.') % dir, type=MessageBox.TYPE_ERROR) return False def createSetup(self): self.styles = hddchoises styles_keys = [ x[0] for x in self.styles ] tmp = config.misc.allowed_epgcachepath.value default = config.misc.epgcachepath.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print 'EPG Location Path: ', default, tmp self.epg_dirname = ConfigSelection(default=default, choices=self.styles + tmp) list = [] if config.usage.setup_level.index >= 2: self.epg_entry = getConfigListEntry(_('EPG location'), self.epg_dirname, _('Choose the location where the EPG data will be stored when the %s %s is shut down. The location must be available at boot time.') % (getMachineBrand(), getMachineName())) list.append(self.epg_entry) self.refill(list) self['config'].setList(list) if config.usage.sort_settings.value: self['config'].list.sort() def layoutFinished(self): self.setTitle(_(self.setup_title)) def changedEntry(self): self.item = self['config'].getCurrent() if self['config'].getCurrent()[0] == _('EPG location'): self.checkReadWriteDir(self['config'].getCurrent()[1]) for x in self.onChangedEntry: x() config.misc.epgcachepath.value = self.epg_dirname.value config.misc.epgcachepath.save() try: if isinstance(self['config'].getCurrent()[1], ConfigYesNo) or isinstance(self['config'].getCurrent()[1], ConfigSelection): self.createSetup() except: pass 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 getCurrentDescription(self): return self['config'].getCurrent() and len(self['config'].getCurrent()) > 2 and self['config'].getCurrent()[2] or '' def ok(self): currentry = self['config'].getCurrent() if currentry == self.epg_entry: self.entrydirname = self.epg_dirname config.misc.epgcachepath.value = self.epg_dirname.value self.session.openWithCallback(self.dirnameSelected, EPGLocationBox) def dirnameSelected(self, res): if res is not None: self.entrydirname.value = res currentry = self['config'].getCurrent() if currentry == self.epg_entry: styles_keys = [ x[0] for x in self.styles ] tmp = config.misc.allowed_epgcachepath.value default = self.epg_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.epg_dirname.setChoices(self.styles + tmp, default=default) self.entrydirname.value = res def saveAll(self): currentry = self['config'].getCurrent() config.misc.epgcachepath.value = self.epg_dirname.value config.misc.epgcachepath.save() for x in self['config'].list: x[1].save() configfile.save() def keySave(self): self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self['config'].list: x[1].cancel() self.close() def keyCancel(self): if self['config'].isChanged(): self.session.openWithCallback(self.cancelConfirm, MessageBox, _('Really close without saving settings?'), default=False) else: self.close() def createSummary(self): return SetupSummary def addItems(self, list, parentNode): for x in parentNode: if not x.tag: continue if x.tag == 'item': item_level = int(x.get('level', 0)) item_rectunerlevel = int(x.get('rectunerlevel', 0)) if self.levelChanged not in config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.append(self.levelChanged) self.onClose.append(self.removeNotifier) if item_level > config.usage.setup_level.index: continue requires = x.get('requires') if requires and requires.startswith('config.'): try: item = eval(requires or '') except: continue if item.value and not item.value == '0': SystemInfo[requires] = True else: SystemInfo[requires] = False if requires and not SystemInfo.get(requires, False): continue item_text = _(x.get('text', '??').encode('UTF-8')) item_description = _(x.get('description', ' ').encode('UTF-8')) item_text = item_text.replace('%s %s', '%s %s' % (getMachineBrand(), getMachineName())) item_description = item_description.replace('%s %s', '%s %s' % (getMachineBrand(), getMachineName())) try: b = eval(x.text or '') except: b = '' if b == '': continue item = b if not isinstance(item, ConfigNothing): list.append((item_text, item, item_description))
class TimeshiftSettings(Screen, ConfigListScreen): def removeNotifier(self): if config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.remove(self.levelChanged) def levelChanged(self, configElement): list = [] self.refill(list) self['config'].setList(list) def refill(self, list): xmldata = setupdom().getroot() for x in xmldata.findall('setup'): if x.get('key') != self.setup: continue self.addItems(list, x) self.setup_title = x.get('title', '').encode('UTF-8') self.seperation = int(x.get('separation', '0')) def __init__(self, session): Screen.__init__(self, session) self.skinName = 'Setup' self['footnote'] = Label() self['HelpWindow'] = Pixmap() self['HelpWindow'].hide() self['VKeyIcon'] = Boolean(False) self['key_red'] = StaticText(_('Cancel')) self['key_green'] = StaticText(_('Save')) self['description'] = Label(_('')) self.onChangedEntry = [] self.setup = 'timeshift' list = [] ConfigListScreen.__init__(self, list, session=session, on_change=self.changedEntry) self.createSetup() self['setupActions'] = ActionMap(['SetupActions', 'ColorActions', 'MenuActions'], {'green': self.keySave, 'red': self.keyCancel, 'cancel': self.keyCancel, 'ok': self.ok, 'menu': self.closeRecursive}, -2) self.onLayoutFinish.append(self.layoutFinished) def changedEntry(self): self.item = self['config'].getCurrent() if self['config'].getCurrent()[0] == _('Timeshift location'): self.checkReadWriteDir(self['config'].getCurrent()[1]) if self['config'].getCurrent()[0] == _('Autorecord location'): self.checkReadWriteDir(self['config'].getCurrent()[1]) for x in self.onChangedEntry: x() try: if isinstance(self['config'].getCurrent()[1], ConfigYesNo) or isinstance(self['config'].getCurrent()[1], ConfigSelection): self.createSetup() except: pass 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 getCurrentDescription(self): return self['config'].getCurrent() and len(self['config'].getCurrent()) > 2 and self['config'].getCurrent()[2] or '' def checkReadWriteDir(self, configele): import os.path import Components.Harddisk supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'nfs', 'cifs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append((partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint(os.path.realpath(configele.value)) + '/' in locations or Components.Harddisk.findMountPoint(os.path.realpath(configele.value)) in locations: if fileExists(configele.value, 'w'): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open(MessageBox, _('The directory %s is not writable.\nMake sure you select a writable directory instead.') % dir, type=MessageBox.TYPE_ERROR) return False else: dir = configele.value configele.value = configele.last_value self.session.open(MessageBox, _('The directory %s is not a EXT2, EXT3, EXT4, NFS or CIFS partition.\nMake sure you select a valid partition type.') % dir, type=MessageBox.TYPE_ERROR) return False else: dir = configele.value configele.value = configele.last_value self.session.open(MessageBox, _('The directory %s is not a EXT2, EXT3, EXT4, NFS or CIFS partition.\nMake sure you select a valid partition type.') % dir, type=MessageBox.TYPE_ERROR) return False def createSetup(self): default = config.usage.timeshift_path.value cooldefault = config.usage.autorecord_path.value tmp = config.usage.allowed_timeshift_paths.value cooltmp = config.usage.allowed_autorecord_paths.value if default not in tmp: tmp = tmp[:] tmp.append(default) if cooldefault not in cooltmp: cooltmp = cooltmp[:] cooltmp.append(cooldefault) self.timeshift_dirname = ConfigSelection(default=default, choices=tmp) self.autorecord_dirname = ConfigSelection(default=cooldefault, choices=cooltmp) self.timeshift_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.autorecord_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) list = [] self.timeshift_entry = getConfigListEntry(_('Timeshift location'), self.timeshift_dirname, _("Set the default location for your timeshift-files. Press 'OK' to add new locations, select left/right to select an existing location.")) list.append(self.timeshift_entry) self.autorecord_entry = getConfigListEntry(_('Autorecord location'), self.autorecord_dirname, _("Set the default location for your autorecord-files. Press 'OK' to add new locations, select left/right to select an existing location.")) list.append(self.autorecord_entry) self.refill(list) self['config'].setList(list) if config.usage.sort_settings.value: self['config'].list.sort() def layoutFinished(self): self.setTitle(_(self.setup_title)) def ok(self): currentry = self['config'].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value self.lastautorecorddirs = config.usage.allowed_autorecord_paths.value if currentry == self.timeshift_entry: self.entrydirname = self.timeshift_dirname config.usage.timeshift_path.value = self.timeshift_dirname.value self.session.openWithCallback(self.dirnameSelected, TimeshiftLocationBox) if currentry == self.autorecord_entry: self.entrydirname = self.autorecord_dirname config.usage.autorecord_path.value = self.autorecord_dirname.value self.session.openWithCallback(self.dirnameSelected, AutorecordLocationBox) def dirnameSelected(self, res): if res is not None: import os.path import Components.Harddisk supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'nfs', 'cifs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append((partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint(os.path.realpath(res)) + '/' in locations or Components.Harddisk.findMountPoint(os.path.realpath(res)) in locations: self.entrydirname.value = res if config.usage.allowed_timeshift_paths.value != self.lasttimeshiftdirs: tmp = config.usage.allowed_timeshift_paths.value default = self.timeshift_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.timeshift_dirname.setChoices(tmp, default=default) self.entrydirname.value = res if config.usage.allowed_autorecord_paths.value != self.lastautorecorddirs: tmp = config.usage.allowed_autorecord_paths.value default = self.autorecord_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.autorecord_dirname.setChoices(tmp, default=default) self.entrydirname.value = res else: self.session.open(MessageBox, _('The directory %s is not a EXT2, EXT3, EXT4, NFS or CIFS partition.\nMake sure you select a valid partition type.') % res, type=MessageBox.TYPE_ERROR) else: self.session.open(MessageBox, _('The directory %s is not a EXT2, EXT3, EXT4, NFS or CIFS partition.\nMake sure you select a valid partition type.') % res, type=MessageBox.TYPE_ERROR) def saveAll(self): for x in self['config'].list: x[1].save() configfile.save() def keySave(self): import os.path import Components.Harddisk supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'nfs', 'cifs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append((partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint(os.path.realpath(config.usage.timeshift_path.value)) + '/' in locations or Components.Harddisk.findMountPoint(os.path.realpath(config.usage.timeshift_path.value)) in locations: config.usage.timeshift_path.value = self.timeshift_dirname.value config.usage.timeshift_path.save() self.saveAll() self.close() elif int(config.timeshift.startdelay.value) > 0: self.session.open(MessageBox, _('The directory %s is not a EXT2, EXT3, EXT4, NFS or CIFS partition.\nMake sure you select a valid partition type.') % config.usage.timeshift_path.value, type=MessageBox.TYPE_ERROR) else: config.timeshift.startdelay.setValue(0) self.saveAll() self.close() elif int(config.timeshift.startdelay.value) > 0: self.session.open(MessageBox, _('The directory %s is not a EXT2, EXT3, EXT4, NFS or CIFS partition.\nMake sure you select a valid partition type.') % config.usage.timeshift_path.value, type=MessageBox.TYPE_ERROR) else: config.timeshift.startdelay.setValue(0) self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self['config'].list: x[1].cancel() self.close() def keyCancel(self): if self['config'].isChanged(): self.session.openWithCallback(self.cancelConfirm, MessageBox, _('Really close without saving settings?'), default=False) else: self.close() def createSummary(self): return SetupSummary def addItems(self, list, parentNode): for x in parentNode: if not x.tag: continue if x.tag == 'item': item_level = int(x.get('level', 0)) if self.levelChanged not in config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.append(self.levelChanged) self.onClose.append(self.removeNotifier) if item_level > config.usage.setup_level.index: continue requires = x.get('requires') if requires and requires.startswith('config.'): item = eval(requires or '') if item.value and not item.value == '0': SystemInfo[requires] = True else: SystemInfo[requires] = False if requires and not SystemInfo.get(requires, False): continue item_text = _(x.get('text', '??').encode('UTF-8')) item_description = _(x.get('description', ' ').encode('UTF-8')) b = eval(x.text or '') if b == '': continue item = b if not isinstance(item, ConfigNothing): list.append((item_text, item, item_description))
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 TimeshiftSettings(Screen,ConfigListScreen): def removeNotifier(self): self.onNotifiers.remove(self.levelChanged) def levelChanged(self, configElement): list = [] self.refill(list) self["config"].setList(list) def refill(self, list): xmldata = setupdom().getroot() for x in xmldata.findall("setup"): if x.get("key") != self.setup: continue self.addItems(list, x) self.setup_title = x.get("title", "").encode("UTF-8") self.seperation = int(x.get('separation', '0')) def __init__(self, session): Screen.__init__(self, session) self.skinName = "Setup" self['footnote'] = Label() self["HelpWindow"] = Pixmap() self["HelpWindow"].hide() self["VKeyIcon"] = Boolean(False) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) self["description"] = Label(_("")) self.onChangedEntry = [ ] self.onNotifiers = [ ] self.setup = "timeshift" list = [] ConfigListScreen.__init__(self, list, session = session, on_change = self.changedEntry) self.createSetup() self["setupActions"] = ActionMap(["SetupActions", "ColorActions", "MenuActions"], { "green": self.keySave, "red": self.keyCancel, "cancel": self.keyCancel, "ok": self.ok, "menu": self.closeRecursive, }, -2) self.onLayoutFinish.append(self.layoutFinished) # for summary: def changedEntry(self): self.item = self["config"].getCurrent() if self["config"].getCurrent()[0] == _("Timeshift location"): self.checkReadWriteDir(self["config"].getCurrent()[1]) for x in self.onChangedEntry: x() try: if isinstance(self["config"].getCurrent()[1], ConfigYesNo) or isinstance(self["config"].getCurrent()[1], ConfigSelection): self.createSetup() except: pass 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 getCurrentDescription(self): return self["config"].getCurrent() and len(self["config"].getCurrent()) > 2 and self["config"].getCurrent()[2] or "" def checkReadWriteDir(self, configele): import os.path import Components.Harddisk supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'nfs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append((partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint(os.path.realpath(configele.value))+'/' in locations or Components.Harddisk.findMountPoint(os.path.realpath(configele.value)) in locations: if fileExists(configele.value, "w"): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not writable.\nMake sure you select a writable directory instead.")%dir, type = MessageBox.TYPE_ERROR ) return False else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type.")%dir, type = MessageBox.TYPE_ERROR ) return False else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type.")%dir, type = MessageBox.TYPE_ERROR ) return False def createSetup(self): default = config.usage.timeshift_path.value tmp = config.usage.allowed_timeshift_paths.value if default not in tmp: tmp = tmp[:] tmp.append(default) # print "TimeshiftPath: ", default, tmp self.timeshift_dirname = ConfigSelection(default = default, choices = tmp) self.timeshift_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) list = [] self.timeshift_entry = getConfigListEntry(_("Timeshift location"), self.timeshift_dirname, _("Set the default location for your timeshift-files. Press 'OK' to add new locations, select left/right to select an existing location.")) list.append(self.timeshift_entry) self.refill(list) self["config"].setList(list) if config.usage.sort_settings.value: self["config"].list.sort() def layoutFinished(self): self.setTitle(_(self.setup_title)) def ok(self): currentry = self["config"].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value if currentry == self.timeshift_entry: self.entrydirname = self.timeshift_dirname config.usage.timeshift_path.value = self.timeshift_dirname.value self.session.openWithCallback( self.dirnameSelected, TimeshiftLocationBox ) def dirnameSelected(self, res): if res is not None: import os.path import Components.Harddisk supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'nfs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append((partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint(os.path.realpath(res))+'/' in locations or Components.Harddisk.findMountPoint(os.path.realpath(res)) in locations: self.entrydirname.value = res if config.usage.allowed_timeshift_paths.value != self.lasttimeshiftdirs: tmp = config.usage.allowed_timeshift_paths.value default = self.timeshift_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.timeshift_dirname.setChoices(tmp, default=default) self.entrydirname.value = res else: self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type.")%res, type = MessageBox.TYPE_ERROR ) else: self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type.")%res, type = MessageBox.TYPE_ERROR ) def saveAll(self): for x in self["config"].list: x[1].save() configfile.save() # keySave and keyCancel are just provided in case you need them. # you have to call them by yourself. def keySave(self): import os.path import Components.Harddisk supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'nfs')) candidates = [] mounts = Components.Harddisk.getProcMounts() for partition in Components.Harddisk.harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append((partition.description, partition.mountpoint)) if candidates: locations = [] for validdevice in candidates: locations.append(validdevice[1]) if Components.Harddisk.findMountPoint(os.path.realpath(config.usage.timeshift_path.value))+'/' in locations or Components.Harddisk.findMountPoint(os.path.realpath(config.usage.timeshift_path.value)) in locations: config.usage.timeshift_path.value = self.timeshift_dirname.value config.usage.timeshift_path.save() self.saveAll() self.close() else: if int(config.timeshift.startdelay.value) > 0: self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type.")%config.usage.timeshift_path.value, type = MessageBox.TYPE_ERROR ) else: config.timeshift.startdelay.setValue(0) self.saveAll() self.close() else: if int(config.timeshift.startdelay.value) > 0: self.session.open( MessageBox, _("The directory %s is not a EXT2, EXT3, EXT4 or NFS partition.\nMake sure you select a valid partition type.")%config.usage.timeshift_path.value, type = MessageBox.TYPE_ERROR ) else: config.timeshift.startdelay.setValue(0) self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self["config"].list: x[1].cancel() self.close() def keyCancel(self): if self["config"].isChanged(): self.session.openWithCallback(self.cancelConfirm, MessageBox, _("Really close without saving settings?"), default = False) else: self.close() def createSummary(self): return SetupSummary def addItems(self, list, parentNode): for x in parentNode: if not x.tag: continue if x.tag == 'item': item_level = int(x.get("level", 0)) if not self.onNotifiers: self.onNotifiers.append(self.levelChanged) self.onClose.append(self.removeNotifier) if item_level > self.onNotifiers.index: continue requires = x.get("requires") if requires and requires.startswith('config.'): item = eval(requires or "") if item.value and not item.value == "0": SystemInfo[requires] = True else: SystemInfo[requires] = False if requires and not SystemInfo.get(requires, False): continue item_text = _(x.get("text", "??").encode("UTF-8")) item_description = _(x.get("description", " ").encode("UTF-8")) b = eval(x.text or "") if b == "": continue #add to configlist item = b # the first b is the item itself, ignored by the configList. # the second one is converted to string. if not isinstance(item, ConfigNothing): list.append((item_text, item, item_description))
class RecordPathsSettings(Screen,ConfigListScreen): skin = """ <screen name="RecordPathsSettings" position="160,150" size="450,200" title="Recording paths"> <ePixmap pixmap="skin_default/buttons/red.png" position="10,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="300,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="10,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render="Label" position="300,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget name="config" position="10,44" size="430,146" /> </screen>""" def __init__(self, session): from Components.Sources.StaticText import StaticText Screen.__init__(self, session) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) self.setTitle(_("Recording paths")) ConfigListScreen.__init__(self, []) config.movielist.videodirs.load() self.initConfigList() self["setupActions"] = ActionMap(["SetupActions", "ColorActions", "MenuActions"], { "green": self.save, "red": self.keyCancel, "cancel": self.keyCancel, "ok": self.ok, "menu": self.closeRecursive, }, -2) def checkReadWriteDir(self, configele): value = configele.value print "checkReadWrite: ", value if not value or value in [x[0] for x in self.styles] or fileExists(value, "w"): configele.last_value = value return True else: configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not writable.\nMake sure you select a writable directory instead.") % value, type = MessageBox.TYPE_ERROR ) return False def initConfigList(self): self.styles = [ ("<default>", _("<Default movie location>")), ("<current>", _("<Current movielist location>")), ("<timer>", _("<Last timer location>")) ] styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = config.usage.default_path.value if default and default not in tmp: tmp = tmp[:] tmp.append(default) print "DefaultPath: ", default, tmp self.default_dirname = ConfigSelection(default = default, choices = [("", _("<Default movie location>"))] + tmp) tmp = config.movielist.videodirs.value default = config.usage.timer_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print "TimerPath: ", default, tmp self.timer_dirname = ConfigSelection(default = default, choices = self.styles+tmp) tmp = config.movielist.videodirs.value default = config.usage.instantrec_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) print "InstantrecPath: ", default, tmp self.instantrec_dirname = ConfigSelection(default = default, choices = self.styles+tmp) default = config.usage.timeshift_path.value tmp = config.usage.allowed_timeshift_paths.value if default not in tmp: tmp = tmp[:] tmp.append(default) print "TimeshiftPath: ", default, tmp self.timeshift_dirname = ConfigSelection(default = default, choices = tmp) self.default_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timer_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.instantrec_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timeshift_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.list = [] if config.usage.setup_level.index >= 2: self.default_entry = getConfigListEntry(_("Default movie location"), self.default_dirname) self.list.append(self.default_entry) self.timer_entry = getConfigListEntry(_("Timer recording location"), self.timer_dirname) self.list.append(self.timer_entry) self.instantrec_entry = getConfigListEntry(_("Instant recording location"), self.instantrec_dirname) self.list.append(self.instantrec_entry) else: self.default_entry = getConfigListEntry(_("Movie location"), self.default_dirname) self.list.append(self.default_entry) self.timeshift_entry = getConfigListEntry(_("Timeshift location"), self.timeshift_dirname) self.list.append(self.timeshift_entry) self["config"].setList(self.list) def ok(self): currentry = self["config"].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value if config.usage.setup_level.index >= 2: txt = _("Default movie location") else: txt = _("Movie location") if currentry == self.default_entry: self.entrydirname = self.default_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, txt, preferredPath(self.default_dirname.value) ) elif currentry == self.timer_entry: self.entrydirname = self.timer_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Initial location in new timers"), preferredPath(self.timer_dirname.value) ) elif currentry == self.instantrec_entry: self.entrydirname = self.instantrec_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Location for instant recordings"), preferredPath(self.instantrec_dirname.value) ) elif currentry == self.timeshift_entry: self.entrydirname = self.timeshift_dirname config.usage.timeshift_path.value = self.timeshift_dirname.value self.session.openWithCallback( self.dirnameSelected, TimeshiftLocationBox ) def dirnameSelected(self, res): if res is not None: self.entrydirname.value = res if config.movielist.videodirs.value != self.lastvideodirs: styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = self.default_dirname.value if default and default not in tmp: tmp = tmp[:] tmp.append(default) self.default_dirname.setChoices([("", _("<Default movie location>"))] + tmp, default=default) tmp = config.movielist.videodirs.value default = self.timer_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.timer_dirname.setChoices(self.styles+tmp, default=default) tmp = config.movielist.videodirs.value default = self.instantrec_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.instantrec_dirname.setChoices(self.styles+tmp, default=default) self.entrydirname.value = res if config.usage.allowed_timeshift_paths.value != self.lasttimeshiftdirs: tmp = config.usage.allowed_timeshift_paths.value default = self.instantrec_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.timeshift_dirname.setChoices(tmp, default=default) self.entrydirname.value = res if self.entrydirname.last_value != res: self.checkReadWriteDir(self.entrydirname) def save(self): currentry = self["config"].getCurrent() if self.checkReadWriteDir(currentry[1]): config.usage.default_path.value = self.default_dirname.value config.usage.timer_path.value = self.timer_dirname.value config.usage.instantrec_path.value = self.instantrec_dirname.value config.usage.timeshift_path.value = self.timeshift_dirname.value config.usage.default_path.save() config.usage.timer_path.save() config.usage.instantrec_path.save() config.usage.timeshift_path.save() self.close()
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)
class RecordingSettings(Screen,ConfigListScreen): def removeNotifier(self): config.usage.setup_level.notifiers.remove(self.levelChanged) def levelChanged(self, configElement): list = [] self.refill(list) self["config"].setList(list) def refill(self, list): xmldata = setupdom().getroot() for x in xmldata.findall("setup"): if x.get("key") != self.setup: continue self.addItems(list, x) self.setup_title = x.get("title", "").encode("UTF-8") self.seperation = int(x.get('separation', '0')) def __init__(self, session, menu_path=""): Screen.__init__(self, session) self.skinName = "Setup" self.menu_path = menu_path self["menu_path_compressed"] = StaticText() self['footnote'] = Label() self["HelpWindow"] = Pixmap() self["HelpWindow"].hide() self["VKeyIcon"] = Boolean(False) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) self["description"] = Label(_("")) self.onChangedEntry = [ ] self.setup = "recording" list = [] ConfigListScreen.__init__(self, list, session = session, on_change = self.changedEntry) self.createSetup() self["setupActions"] = ActionMap(["SetupActions", "ColorActions", "MenuActions"], { "green": self.keySave, "red": self.keyCancel, "cancel": self.keyCancel, "ok": self.ok, "menu": self.closeRecursive, }, -2) self.onLayoutFinish.append(self.layoutFinished) def checkReadWriteDir(self, configele): # print "checkReadWrite: ", configele.value if configele.value in [x[0] for x in self.styles] or fileExists(configele.value, "w"): configele.last_value = configele.value return True else: dir = configele.value configele.value = configele.last_value self.session.open( MessageBox, _("The directory %s is not writable.\nMake sure you select a writable directory instead.")%dir, type = MessageBox.TYPE_ERROR ) return False def createSetup(self): self.styles = [ ("<default>", _("<Default movie location>")), ("<current>", _("<Current movielist location>")), ("<timer>", _("<Last timer location>")) ] styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = config.usage.default_path.value if default not in tmp: tmp = tmp[:] tmp.append(default) # print "DefaultPath: ", default, tmp self.default_dirname = ConfigSelection(default = default, choices = tmp) tmp = config.movielist.videodirs.value default = config.usage.timer_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) # print "TimerPath: ", default, tmp self.timer_dirname = ConfigSelection(default = default, choices = self.styles+tmp) tmp = config.movielist.videodirs.value default = config.usage.instantrec_path.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) # print "InstantrecPath: ", default, tmp self.instantrec_dirname = ConfigSelection(default = default, choices = self.styles+tmp) self.default_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.timer_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) self.instantrec_dirname.addNotifier(self.checkReadWriteDir, initial_call=False, immediate_feedback=False) list = [] if config.usage.setup_level.index >= 2: self.default_entry = getConfigListEntry(_("Default movie location"), self.default_dirname, _("Set the default location for your recordings. Press 'OK' to add new locations, select left/right to select an existing location.")) list.append(self.default_entry) self.timer_entry = getConfigListEntry(_("Timer recording location"), self.timer_dirname, _("Set the default location for your timers. Press 'OK' to add new locations, select left/right to select an existing location.")) list.append(self.timer_entry) self.instantrec_entry = getConfigListEntry(_("Instant recording location"), self.instantrec_dirname, _("Set the default location for your instant recordings. Press 'OK' to add new locations, select left/right to select an existing location.")) list.append(self.instantrec_entry) else: self.default_entry = getConfigListEntry(_("Movie location"), self.default_dirname, _("Set the default location for your recordings. Press 'OK' to add new locations, select left/right to select an existing location.")) list.append(self.default_entry) self.refill(list) self["config"].setList(list) if config.usage.sort_settings.value: self["config"].list.sort() def layoutFinished(self): if config.usage.show_menupath.value == 'large' and self.menu_path: title = self.menu_path + _(self.setup_title) self["menu_path_compressed"].setText("") elif config.usage.show_menupath.value == 'small': title = _(self.setup_title) self["menu_path_compressed"].setText(self.menu_path + " >" if not self.menu_path.endswith(' / ') else self.menu_path[:-3] + " >" or "") else: title = _(self.setup_title) self["menu_path_compressed"].setText("") self.setup_title = title self.setTitle(title) # for summary: def changedEntry(self): self.item = self["config"].getCurrent() if self["config"].getCurrent()[0] == _("Default movie location") or self["config"].getCurrent()[0] == _("Timer record location") or self["config"].getCurrent()[0] == _("Instant record location") or self["config"].getCurrent()[0] == _("Movie location"): self.checkReadWriteDir(self["config"].getCurrent()[1]) for x in self.onChangedEntry: x() try: if isinstance(self["config"].getCurrent()[1], ConfigYesNo) or isinstance(self["config"].getCurrent()[1], ConfigSelection): self.createSetup() except: pass 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 getCurrentDescription(self): return self["config"].getCurrent() and len(self["config"].getCurrent()) > 2 and self["config"].getCurrent()[2] or "" def ok(self): currentry = self["config"].getCurrent() self.lastvideodirs = config.movielist.videodirs.value self.lasttimeshiftdirs = config.usage.allowed_timeshift_paths.value if config.usage.setup_level.index >= 2: txt = _("Default movie location") else: txt = _("Movie location") if currentry == self.default_entry: self.entrydirname = self.default_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, txt, preferredPath(self.default_dirname.value) ) elif currentry == self.timer_entry: self.entrydirname = self.timer_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("New timers location"), preferredPath(self.timer_dirname.value) ) elif currentry == self.instantrec_entry: self.entrydirname = self.instantrec_dirname self.session.openWithCallback( self.dirnameSelected, MovieLocationBox, _("Instant recordings location"), preferredPath(self.instantrec_dirname.value) ) def dirnameSelected(self, res): if res is not None: self.entrydirname.value = res if config.movielist.videodirs.value != self.lastvideodirs: styles_keys = [x[0] for x in self.styles] tmp = config.movielist.videodirs.value default = self.default_dirname.value if default not in tmp: tmp = tmp[:] tmp.append(default) self.default_dirname.setChoices(tmp, default=default) tmp = config.movielist.videodirs.value default = self.timer_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.timer_dirname.setChoices(self.styles+tmp, default=default) tmp = config.movielist.videodirs.value default = self.instantrec_dirname.value if default not in tmp and default not in styles_keys: tmp = tmp[:] tmp.append(default) self.instantrec_dirname.setChoices(self.styles+tmp, default=default) self.entrydirname.value = res if self.entrydirname.last_value != res: self.checkReadWriteDir(self.entrydirname) def saveAll(self): currentry = self["config"].getCurrent() config.usage.default_path.value = self.default_dirname.value config.usage.timer_path.value = self.timer_dirname.value config.usage.instantrec_path.value = self.instantrec_dirname.value config.usage.default_path.save() config.usage.timer_path.save() config.usage.instantrec_path.save() for x in self["config"].list: x[1].save() configfile.save() # keySave and keyCancel are just provided in case you need them. # you have to call them by yourself. def keySave(self): self.saveAll() self.close() def cancelConfirm(self, result): if not result: return for x in self["config"].list: x[1].cancel() self.close() def keyCancel(self): if self["config"].isChanged(): self.session.openWithCallback(self.cancelConfirm, MessageBox, _("Really close without saving settings?"), default = False) else: self.close() def createSummary(self): return SetupSummary def addItems(self, list, parentNode): for x in parentNode: if not x.tag: continue if x.tag == 'item': item_level = int(x.get("level", 0)) if not self.levelChanged in config.usage.setup_level.notifiers: config.usage.setup_level.notifiers.append(self.levelChanged) self.onClose.append(self.removeNotifier) if item_level > config.usage.setup_level.index: continue requires = x.get("requires") if requires and requires.startswith('config.'): item = eval(requires or "") if item.value and not item.value == "0": SystemInfo[requires] = True else: SystemInfo[requires] = False if requires and not SystemInfo.get(requires, False): continue item_text = _(x.get("text", "??").encode("UTF-8")) item_description = _(x.get("description", " ").encode("UTF-8")) b = eval(x.text or "") if b == "": continue #add to configlist item = b # the first b is the item itself, ignored by the configList. # the second one is converted to string. if not isinstance(item, ConfigNothing): list.append((item_text, item, item_description))
class VcsSetupScreen(Screen, ConfigListScreen): skin = """ <screen name="VcsSetupScreen" position="center,center" size="620,470" title="%s" > <ePixmap pixmap="skin_default/buttons/red.png" position="10,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="150,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="290,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/blue.png" position="430,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/key_info.png" position="580,5" zPosition="1" size="35,25" alphatest="on" /> <widget name="key_red" position="10,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget name="key_green" position="150,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget name="key_yellow" position="290,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" /> <widget name="key_blue" position="430,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" /> <widget name="config" position="10,45" size="600,175" scrollbarMode="showOnDemand" zPosition="1" /> <widget source="profiles" render="Listbox" position="10,220" size="600,230" zPosition="1" > <convert type="TemplatedMultiContent"> {"templates": {"default": (45, [ MultiContentEntryText(pos=(50, 0), size=(200, 45), font=0, flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER|RT_WRAP, text=1), MultiContentEntryText(pos=(260, 0), size=(320, 45), font=1, flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER|RT_WRAP, text=2), MultiContentEntryPixmapAlphaTest(pos=(12, 9), size=(25, 24), png=3), ], True, "showOnDemand"), "notselected": (45, [ MultiContentEntryText(pos=(50, 0), size=(200, 45), font=0, flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER|RT_WRAP, text=1), MultiContentEntryText(pos=(260, 0), size=(320, 45), font=1, flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER|RT_WRAP, text=2), MultiContentEntryPixmapAlphaTest(pos=(12, 9), size=(25, 24), png=3), ], False, "showOnDemand") }, "fonts": [gFont("Regular", 24), gFont("Regular", 18)], "itemHeight": 45, "scrollbarMode": "showOnDemand", } </convert> </widget> </screen>""" % (_('%s: video clipping switcher') % (PLUGIN_NAME)) FOCUS_CONFIG, FOCUS_LIST = range(2) def __init__(self, session): Screen.__init__(self, session) for btn in ("red", "green", "yellow", "blue"): self["key_" + btn] = Button(" ") ConfigListScreen.__init__(self, []) self.defprofile = ConfigSelection([]) self.updateConfigList() self.pfsList = [] self["profiles"] = List(self.pfsList) self.updateProfileList() self["actions"] = ActionMap( [ "OkCancelActions", "ColorActions", "DirectionActions", "ChannelSelectEPGActions" ], { "cancel": self.keyExit, "ok": self.keyOk, "showEPGList": self.showExamples, "red": self.keyRed, "green": self.keyGreen, "yellow": boundFunction(self.moveEntry, -1), "blue": boundFunction(self.moveEntry, +1), "up": self.keyUp, "down": self.keyDown, }, -1) self.onClose.append(self.__closed) self.onLayoutFinish.append(self.__layoutFinished) self.onShown.append(self.updateButtonState) self.prev_ext_menu = config.plugins.VCS.ext_menu.value def __layoutFinished(self): self["config"].instance.setSelectionEnable(True) self["profiles"].style = "notselected" self.focus = self.FOCUS_CONFIG self["profiles"].onSelectionChanged.append(self.updateButtonState) def __closed(self): for x in self["config"].list: if x[1] == self.defprofile: config.plugins.VCS.default.value = self.defprofile.value config.plugins.VCS.default.save() continue x[1].save() def updateButtonState(self): self["key_green"].setText(_("Add")) if self.focus == self.FOCUS_LIST: cur = self["profiles"].getCurrent() if cur: self["key_red"].setText(_("Delete")) self["key_yellow"].setText( self["profiles"].index > 0 and _("Move Up") or " ") self["key_blue"].setText( self["profiles"].index < len(self.pfsList) - 1 and _("Move Down") or " ") else: for btn in ("key_red", "key_yellow", "key_blue"): self[btn].setText(" ") else: self["key_red"].setText(_("Exit")) self["key_yellow"].setText(" ") self["key_blue"].setText(" ") def updateConfigList(self): pfslist = [(-1, _("None"))] pfs = config.plugins.VCS.profiles for x in range(len(pfs)): pfslist.append((x, pfs[x].name.value)) default = not config.plugins.VCS.default.value in range( len(pfs)) and -1 or config.plugins.VCS.default.value self.defprofile.setChoices(pfslist, default=default) cfglist = [ getConfigListEntry(_("Plugin quick button(s)"), config.plugins.VCS.hotkey), getConfigListEntry(_("Quick button(s) action"), config.plugins.VCS.hkaction), getConfigListEntry(_("Show \"Choise list\" in extensions menu"), config.plugins.VCS.ext_menu), getConfigListEntry(_("Message timeout on switch profiles"), config.plugins.VCS.msgtime), getConfigListEntry(_("Default profile on enigma startup"), self.defprofile), ] if fileExists("/usr/lib/enigma2/python/Screens/DVD.pyo"): cfglist.append( getConfigListEntry( _('Add \"Choise list\" Blue Button to DVDPlayer'), config.plugins.VCS.dvd_menu)) if fileExists( "/usr/lib/enigma2/python/Plugins/Extensions/MediaPlayer/plugin.pyo" ) or fileExists( "/usr/lib/enigma2/python/Plugins/Extensions/MediaPlayer/plugin.pyc" ): cfglist.append( getConfigListEntry( _('Add \"Choise list\" Blue Button to MediaPlayer'), config.plugins.VCS.media_player)) self["config"].list = cfglist self["config"].setList(cfglist) def updateProfileList(self): list = [] pfs = config.plugins.VCS.profiles for x in range(len(pfs)): s = "%s %s" % (getAspectString( pfs[x].aspect.value), pfs[x].cliprect.value) path = "skin_default/icons/lock_%s.png" % (pfs[x].enabled.value and "on" or "off") png = LoadPixmap(resolveFilename(SCOPE_SKIN, path)) list.append((pfs[x], pfs[x].name.value, s, png)) self.pfsList = list self["profiles"].setList(self.pfsList) def getUniqProfileName(self, name=_("Profile "), suffix=1): x = 0 uname = "%s%d" % (name, suffix) pfs = config.plugins.VCS.profiles while x < config.plugins.VCS.pfs_count.value: if pfs[x].name.value == uname: x = -1 suffix += 1 uname = "%s%d" % (name, suffix) x += 1 return uname def addEntry(self): self.session.openWithCallback( self.addCallback, VcsProfileSetup, InitVcsProfile(name=self.getUniqProfileName())) def addCallback(self, result, profile): if result: pfs = config.plugins.VCS.profiles idx = config.plugins.VCS.pfs_count.value if profile.name.value == "": profile.name.value = self.getUniqProfileName() profile.name.save() pfs.append(profile) config.plugins.VCS.pfs_count.value = len(pfs) config.plugins.VCS.pfs_count.save() self.updateProfileList() self["profiles"].index = idx self.updateConfigList() self.updateButtonState() else: del profile def editEntry(self): idx = self["profiles"].index if idx < len(self.pfsList): pfs = config.plugins.VCS.profiles self.session.openWithCallback(self.editCallback, VcsProfileSetup, pfs[idx]) def editCallback(self, result, profile): if result: pfs = config.plugins.VCS.profiles idx = self["profiles"].index if profile.name.value == "": profile.name.value = self.getUniqProfileName() profile.name.save() self.updateProfileList() self["profiles"].index = idx self.updateButtonState() def deleteEntry(self): cur = self["profiles"].getCurrent() if cur: self.session.openWithCallback( self.deleteCallback, MessageBox, _("Do you really want to delete profile:\n %s") % (cur[1]), MessageBox.TYPE_YESNO) def deleteCallback(self, yesno): if yesno: idx = self["profiles"].index pfs = config.plugins.VCS.profiles pfs.remove(pfs[idx]) pfs.saved_value = pfs.saved_value config.plugins.VCS.pfs_count.value = len(pfs) config.plugins.VCS.pfs_count.save() self.updateProfileList() if len(pfs): if idx >= len(pfs): self["profiles"].index = len(pfs) - 1 else: self["profiles"].index = idx self.updateConfigList() self.updateButtonState() def moveEntry(self, direction): if self.focus == self.FOCUS_LIST: idx = self["profiles"].index if idx + direction in range(len(self.pfsList)): pfs = config.plugins.VCS.profiles tmp_pf = pfs[idx] pfs[idx] = pfs[idx + direction] pfs[idx + direction] = tmp_pf self.updateProfileList() self["profiles"].index = idx + direction self.updateConfigList() self.updateButtonState() def keyRed(self): if self.focus == self.FOCUS_LIST: self.deleteEntry() else: self.keyExit() def keyExit(self): if self.prev_ext_menu != config.plugins.VCS.ext_menu.value: plugins.readPluginList(resolveFilename(SCOPE_PLUGINS)) self.close() def keyGreen(self): self.addEntry() def keyOk(self): if self.focus == self.FOCUS_LIST: self.editEntry() def keyUp(self): if self.focus == self.FOCUS_CONFIG: self["config"].instance.moveSelection( self["config"].instance.moveUp) elif self.focus == self.FOCUS_LIST: if self["profiles"].getIndex() == 0: self["config"].instance.setSelectionEnable(True) self["profiles"].style = "notselected" self["config"].setCurrentIndex( len(self["config"].getList()) - 1) self.focus = self.FOCUS_CONFIG else: self["profiles"].selectPrevious() self.updateButtonState() def keyDown(self): if self.focus == self.FOCUS_CONFIG: if self["config"].getCurrentIndex() < len( self["config"].getList()) - 1: self["config"].instance.moveSelection( self["config"].instance.moveDown) else: self["config"].instance.setSelectionEnable(False) self["profiles"].style = "default" self.focus = self.FOCUS_LIST elif self.focus == self.FOCUS_LIST: self["profiles"].selectNext() self.updateButtonState() def showExamples(self): if os.path.exists(examples_sh): try: os.chmod(examples_sh, 0755) self.session.open(Console, _("Examples:"), ["%s" % examples_sh]) except: pass